@lmmslab/harness 0.82.0 → 0.84.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/README.md +2 -2
- package/bin/harness.js +6 -1
- package/package.json +1 -1
- package/python/harness/__init__.py +1 -1
- package/python/harness/builtin/prompts/core/core.md +61 -30
- package/python/harness/builtin/prompts/reflect/core.md +3 -12
- package/python/harness/builtin/prompts/reflect/pack.toml +3 -2
- package/python/harness/builtin/prompts/shared/learning-goal.md +1 -1
- package/python/harness/cli.py +104 -18
- package/python/harness/config/agent.py +3 -0
- package/python/harness/core/trace.py +23 -3
- package/python/harness/core/worker.py +6 -0
- package/python/harness/host/client.py +26 -21
- package/python/harness/host/http.py +11 -1
- package/python/harness/host/sessions.py +38 -3
- package/python/harness/host/tasks.py +62 -26
- package/python/harness/model_list.py +25 -5
- package/python/harness/packages/environments.py +51 -12
- package/python/harness/packages/manager.py +379 -102
- package/python/harness/packages/resolve.py +52 -15
- package/python/harness/packages/sources.py +17 -5
- package/python/harness/packages/state.py +10 -0
- package/python/harness/providers.py +66 -24
- package/python/harness/runtime/decision/loop.py +18 -9
- package/python/harness/runtime/decision/messages.py +5 -10
- package/python/harness/runtime/decision/model.py +21 -11
- package/python/harness/runtime/decision/notices.py +66 -0
- package/python/harness/runtime/execution/entries.py +53 -7
- package/python/harness/runtime/execution/session.py +60 -7
- package/python/harness/runtime/learning/active.py +12 -9
- package/python/harness/runtime/reactive/tree.py +35 -22
- package/python/harness/runtime/task/run.py +259 -162
- package/python/harness/runtime/tick.py +34 -3
- package/python/harness/settings.py +8 -3
- package/python/harness/tui/__init__.py +28 -6
- package/python/harness/tui/chat.py +243 -67
- package/python/harness/tui/pty.py +16 -0
- package/python/harness/tui/renderer.py +34 -0
- package/python/harness/tui/views.py +160 -38
|
@@ -38,6 +38,7 @@ from prompt_toolkit.layout.menus import CompletionsMenuControl
|
|
|
38
38
|
from prompt_toolkit.layout.processors import Processor, Transformation
|
|
39
39
|
from prompt_toolkit.patch_stdout import patch_stdout
|
|
40
40
|
from prompt_toolkit.styles import Style
|
|
41
|
+
from prompt_toolkit.utils import get_cwidth
|
|
41
42
|
from prompt_toolkit.widgets import SearchToolbar
|
|
42
43
|
from rich.console import Console
|
|
43
44
|
from rich.syntax import Syntax
|
|
@@ -104,6 +105,7 @@ class Chat:
|
|
|
104
105
|
self.generation = 0
|
|
105
106
|
self.stop = threading.Event()
|
|
106
107
|
self.pending = [] # messages typed while the conversation was created
|
|
108
|
+
self.waiting = None
|
|
107
109
|
self.details_open = False
|
|
108
110
|
self.details_output = []
|
|
109
111
|
self.help = False
|
|
@@ -113,18 +115,14 @@ class Chat:
|
|
|
113
115
|
self.starting = None # what starting the first message's conversation says now
|
|
114
116
|
self.armed = {} # key: when it was last pressed (twice to leave, Esc Esc)
|
|
115
117
|
self.model, self.workspace = None, None
|
|
116
|
-
self.model_entry =
|
|
118
|
+
self.model_entry = getattr(start, "model_entry", None)
|
|
119
|
+
self.model_effort = getattr(start, "model_effort", None)
|
|
117
120
|
self.environment = None # (kind, folder) picked with /environment for the next conversation
|
|
118
121
|
self.agents_on = False # /agents before a conversation starts: on in the next one
|
|
119
122
|
self.learning = None # where a conversation that learns its environment stands (runtime/learning/active.py progress())
|
|
120
123
|
self.lanes = Lanes()
|
|
121
124
|
self._reset()
|
|
122
|
-
|
|
123
|
-
from ..providers import load
|
|
124
|
-
|
|
125
|
-
self.model = load(data())["model"]
|
|
126
|
-
except Exception:
|
|
127
|
-
pass
|
|
125
|
+
self._refresh_next_model(initial_name=getattr(start, "model_name", None))
|
|
128
126
|
# sys.stdout when it prints: patch_stdout's, above the live region.
|
|
129
127
|
self.console = Console(force_terminal=True, legacy_windows=False, highlight=False, soft_wrap=False,
|
|
130
128
|
color_system="truecolor" if os.environ.get("WT_SESSION") or os.environ.get("COLORTERM")
|
|
@@ -140,7 +138,7 @@ class Chat:
|
|
|
140
138
|
prompt = lambda line, wrap: [("class:rule", "› " if line == 0 and not wrap else " ")] # noqa: E731
|
|
141
139
|
field = Window(BufferControl(self.buffer, search_buffer_control=search.control, preview_search=True,
|
|
142
140
|
input_processors=[Placeholder(self)]),
|
|
143
|
-
height=
|
|
141
|
+
height=self._input_height, wrap_lines=True,
|
|
144
142
|
get_line_prefix=prompt, dont_extend_height=True)
|
|
145
143
|
rule = Window(height=1, char="─", style="class:rule")
|
|
146
144
|
# The completions under the input, as many lines as there are (at most 8).
|
|
@@ -148,7 +146,7 @@ class Chat:
|
|
|
148
146
|
self.buffer.complete_state.completions), 8) if self.buffer.complete_state else 1, scroll_offsets=ScrollOffsets(1, 1),
|
|
149
147
|
dont_extend_width=True, style="class:completion-menu"), has_completions)
|
|
150
148
|
status = VSplit([Window(FormattedTextControl(self._status), height=1),
|
|
151
|
-
Window(FormattedTextControl(self._hint), height=1, align=WindowAlign.RIGHT)])
|
|
149
|
+
Window(FormattedTextControl(self._hint), height=1, width=lambda: min(38, self.app.output.get_size().columns // 2), align=WindowAlign.RIGHT)])
|
|
152
150
|
body = HSplit([ConditionalContainer(Window(FormattedTextControl(self._asking), dont_extend_height=True),
|
|
153
151
|
Condition(lambda: self.ask is not None)),
|
|
154
152
|
rule, field, search, rule, menu, status,
|
|
@@ -161,9 +159,19 @@ class Chat:
|
|
|
161
159
|
|
|
162
160
|
app.renderer = WindowsInlineRenderer(app.renderer.style, app.output,
|
|
163
161
|
cpr_not_supported_callback=app.cpr_not_supported_callback)
|
|
162
|
+
elif sys.platform == "darwin":
|
|
163
|
+
from .renderer import ReflowInlineRenderer
|
|
164
|
+
|
|
165
|
+
app.renderer = ReflowInlineRenderer(app.renderer.style, app.output,
|
|
166
|
+
cpr_not_supported_callback=app.cpr_not_supported_callback)
|
|
164
167
|
app.timeoutlen, app.ttimeoutlen = 0.3, 0.05
|
|
165
168
|
return app
|
|
166
169
|
|
|
170
|
+
def _input_height(self):
|
|
171
|
+
width = max(1, self.app.output.get_size().columns - 2)
|
|
172
|
+
return min(12, sum(max(1, (get_cwidth(line.expandtabs()) + width - 1) // width)
|
|
173
|
+
for line in self.buffer.text.split("\n")))
|
|
174
|
+
|
|
167
175
|
def _status(self):
|
|
168
176
|
status = self.status
|
|
169
177
|
if status == "starting":
|
|
@@ -178,6 +186,8 @@ class Chat:
|
|
|
178
186
|
state = ("class:status.state", "○ new conversation")
|
|
179
187
|
else:
|
|
180
188
|
state = ("class:status.state", "● " + word(status))
|
|
189
|
+
if self.app.output.get_size().columns < 80:
|
|
190
|
+
return [state]
|
|
181
191
|
# Learning the environment first: the line is cut at the terminal's width.
|
|
182
192
|
parts = [progress_line(self.learning, short=True) if self.learning else None, self.model,
|
|
183
193
|
self.workspace or (self.environment[0] if self.environment and self.conversation is None else None),
|
|
@@ -185,8 +195,12 @@ class Chat:
|
|
|
185
195
|
return [state] + [("class:status", " · " + part) for part in parts if part]
|
|
186
196
|
|
|
187
197
|
def _hint(self):
|
|
198
|
+
if getattr(self, "waiting", None) is not None:
|
|
199
|
+
return [("class:status.wait", "waiting · Esc cancel ")]
|
|
188
200
|
if self.armed.get("leave") and time.time() - self.armed["leave"][1] < TWICE:
|
|
189
201
|
return [("class:status.wait", f"{self.armed['leave'][0]} again to leave ")]
|
|
202
|
+
if self.app.output.get_size().columns < 70:
|
|
203
|
+
return [("class:status.hint", "esc pause" if self.status == "RUNNING" else "? keys · / commands")]
|
|
190
204
|
if self.status == "RUNNING":
|
|
191
205
|
return [("class:status.hint", "esc interrupt · type to steer ")]
|
|
192
206
|
return [("class:status.hint", "? keys · / commands ")]
|
|
@@ -268,7 +282,9 @@ class Chat:
|
|
|
268
282
|
|
|
269
283
|
@keys.add("escape")
|
|
270
284
|
def _(event):
|
|
271
|
-
if
|
|
285
|
+
if getattr(self, "waiting", None) is not None:
|
|
286
|
+
self.waiting.cancel()
|
|
287
|
+
elif buffer.complete_state:
|
|
272
288
|
buffer.cancel_completion()
|
|
273
289
|
elif self.ask is not None and self.ask.get("reason"):
|
|
274
290
|
self.ask["reason"] = False
|
|
@@ -342,6 +358,8 @@ class Chat:
|
|
|
342
358
|
self.console.print(Text.assemble(("The Harness", "bold"), f" {__version__} ", (here, "dim")))
|
|
343
359
|
self.console.print(Text("Tell it what to do. / for commands, @ to attach a file, ! to run a command, ? for keys.",
|
|
344
360
|
style="dim"))
|
|
361
|
+
if warning := getattr(self.start, "warning", None):
|
|
362
|
+
self.note(warning, "yellow")
|
|
345
363
|
|
|
346
364
|
# Printing into the scrollback (patch_stdout carries it above the live region).
|
|
347
365
|
|
|
@@ -387,6 +405,8 @@ class Chat:
|
|
|
387
405
|
any other (that goes on)."""
|
|
388
406
|
self.stop.set()
|
|
389
407
|
self.stop, self.generation = threading.Event(), self.generation + 1
|
|
408
|
+
self.pending = []
|
|
409
|
+
self.starting = None
|
|
390
410
|
self.conversation, self.ask, self.lanes = conversation, None, Lanes()
|
|
391
411
|
self.learning, self.workspace, self.parked = None, None, False
|
|
392
412
|
self.status = getattr(conversation, "status", None)
|
|
@@ -398,7 +418,7 @@ class Chat:
|
|
|
398
418
|
if hasattr(conversation, "describe"):
|
|
399
419
|
conversation.describe()
|
|
400
420
|
agent = conversation.agent or {}
|
|
401
|
-
self.
|
|
421
|
+
self._later(self._described, generation, agent)
|
|
402
422
|
except Exception:
|
|
403
423
|
pass
|
|
404
424
|
try:
|
|
@@ -408,16 +428,21 @@ class Chat:
|
|
|
408
428
|
self._later(self.show, record, generation)
|
|
409
429
|
except HostGone as error:
|
|
410
430
|
self._later(self._lost, generation, f"({error}: /resume or harness --continue goes on with "
|
|
411
|
-
"this conversation
|
|
431
|
+
"this conversation)")
|
|
412
432
|
except Exception as error:
|
|
413
433
|
self._later(self._lost, generation, f"(the conversation cannot be read any more: {error})")
|
|
414
434
|
|
|
415
435
|
threading.Thread(target=read, daemon=True).start()
|
|
416
436
|
|
|
437
|
+
def _described(self, generation, agent):
|
|
438
|
+
if generation == self.generation:
|
|
439
|
+
self.model, self.workspace = agent.get("model") or self.model, agent.get("workspace")
|
|
440
|
+
|
|
417
441
|
def _lost(self, generation, text):
|
|
418
442
|
"""The conversation shown can no longer be followed: say why, and stop showing it as working."""
|
|
419
443
|
if generation != self.generation:
|
|
420
444
|
return
|
|
445
|
+
self.host = None
|
|
421
446
|
self.note(text, "red")
|
|
422
447
|
if self.status not in ENDED:
|
|
423
448
|
self.status, self.interrupted, self.ask = LOST, False, None
|
|
@@ -493,7 +518,7 @@ class Chat:
|
|
|
493
518
|
"lexer": "python" if item["keys"].get("reply") == "python" else "json"}
|
|
494
519
|
return []
|
|
495
520
|
if kind in DETAILS and self.program is not None:
|
|
496
|
-
lines =
|
|
521
|
+
lines = self._detail_lines(item)
|
|
497
522
|
self.program["details"] += lines
|
|
498
523
|
return []
|
|
499
524
|
if kind == "state":
|
|
@@ -516,28 +541,41 @@ class Chat:
|
|
|
516
541
|
self.last_program = done
|
|
517
542
|
result = record.get("result") or {}
|
|
518
543
|
done.update(status=result.get("status"), seconds=result.get("seconds"))
|
|
519
|
-
lines = [
|
|
544
|
+
lines = [line for item in items for line in self._detail_lines(item)]
|
|
520
545
|
done["details"] += lines
|
|
521
546
|
return [self._program_line(done)]
|
|
522
547
|
|
|
548
|
+
@staticmethod
|
|
549
|
+
def _detail_lines(item):
|
|
550
|
+
if item["kind"] in ("output", "cell_error", "unhandled"):
|
|
551
|
+
return [Text(item["text"], style=ROLES.get(item["role"], ""))]
|
|
552
|
+
return [Text(line, style=ROLES.get(role, "")) for role, line in item_lines(item)]
|
|
553
|
+
|
|
523
554
|
async def _show_details(self, program):
|
|
524
555
|
if self.details_open:
|
|
525
556
|
return
|
|
526
557
|
self.details_open = True
|
|
527
558
|
try:
|
|
528
559
|
await self._view(views.read("Program details · Ctrl+O to return",
|
|
529
|
-
lambda: self._details_text(program), close_key="c-o"))
|
|
560
|
+
lambda: self._details_text(program), close_key="c-o", live=program.get("status") is None))
|
|
530
561
|
finally:
|
|
531
562
|
self.details_open = False
|
|
532
563
|
output, self.details_output = self.details_output, []
|
|
533
564
|
self._print(*output)
|
|
534
565
|
|
|
535
566
|
def _details_text(self, program):
|
|
567
|
+
width = self.app.output.get_size().columns
|
|
568
|
+
version = (len(program["details"]), program.get("status"), program.get("seconds"))
|
|
569
|
+
cached = program.get("_rendered")
|
|
570
|
+
if cached and cached[:2] == (version, width):
|
|
571
|
+
return cached[2]
|
|
536
572
|
stream = io.StringIO()
|
|
537
573
|
console = Console(file=stream, force_terminal=False, color_system=None,
|
|
538
|
-
width=
|
|
574
|
+
width=width, highlight=False)
|
|
539
575
|
console.print(*self._program_lines(program), sep="\n") # each output line on its own
|
|
540
|
-
|
|
576
|
+
value = stream.getvalue()
|
|
577
|
+
program["_rendered"] = (version, width, value)
|
|
578
|
+
return value
|
|
541
579
|
|
|
542
580
|
def _program_line(self, program) -> Text:
|
|
543
581
|
status = program.get("status") or "?"
|
|
@@ -591,8 +629,12 @@ class Chat:
|
|
|
591
629
|
if run is None or conversation is not self.conversation:
|
|
592
630
|
return
|
|
593
631
|
now = self._host().learning(run)
|
|
594
|
-
self.
|
|
595
|
-
|
|
632
|
+
self._later(self._learned, conversation, now)
|
|
633
|
+
|
|
634
|
+
def _learned(self, conversation, now):
|
|
635
|
+
if conversation is self.conversation:
|
|
636
|
+
self.learning = now if now.get("active") else None
|
|
637
|
+
self.app.invalidate()
|
|
596
638
|
|
|
597
639
|
def send(self, text, files=(), learn=None):
|
|
598
640
|
"""A message: to the conversation, or the first of a new one (`learn`: one that learns
|
|
@@ -607,63 +649,88 @@ class Chat:
|
|
|
607
649
|
elif self.start is None:
|
|
608
650
|
self.note("The conversation has ended", "red")
|
|
609
651
|
else:
|
|
652
|
+
if self.model_entry is not None and not self._refresh_next_model():
|
|
653
|
+
self.note(self.next_model_problem, "red")
|
|
654
|
+
return
|
|
655
|
+
generation = self.generation
|
|
656
|
+
self.pending = []
|
|
610
657
|
self.before_start = self.status
|
|
611
658
|
self.status, self.echoed = "starting", text
|
|
612
659
|
self._print(Text("› " + text, style="bold"))
|
|
613
660
|
|
|
661
|
+
place, self.environment = self.environment, None
|
|
662
|
+
agents, self.agents_on = self.agents_on, False
|
|
663
|
+
model_entry, model_effort = self.model_entry, self.model_effort
|
|
664
|
+
|
|
614
665
|
def begin():
|
|
615
666
|
# Where it works: what /environment picked, else the opening choice below.
|
|
616
|
-
place
|
|
617
|
-
agents, self.agents_on = self.agents_on, False
|
|
667
|
+
nonlocal place
|
|
618
668
|
try:
|
|
619
669
|
while True:
|
|
670
|
+
if generation != self.generation:
|
|
671
|
+
return
|
|
620
672
|
try:
|
|
621
|
-
|
|
673
|
+
host, conversation = self.start(text, files, log=lambda message: self._later(self._starting, message, generation),
|
|
622
674
|
**({"learn": learn} if learn is not None else {}),
|
|
623
|
-
**({"model_entry":
|
|
624
|
-
if
|
|
675
|
+
**({"model_entry": model_entry, "reasoning_effort": model_effort}
|
|
676
|
+
if model_entry else {}),
|
|
625
677
|
**({"workspace": place[0], "folder": place[1]} if place else {}),
|
|
626
678
|
**({"agents": True} if agents else {}))
|
|
627
679
|
break
|
|
628
680
|
except ChoiceRequired as error:
|
|
681
|
+
if generation != self.generation:
|
|
682
|
+
return
|
|
629
683
|
if error.choice.get("per_conversation"):
|
|
630
684
|
# (Opened by the Enter that sent the message: that key press
|
|
631
685
|
# must not answer it.)
|
|
632
686
|
place = asyncio.run_coroutine_threadsafe(
|
|
633
|
-
self._choose_environment(error.choice, settle=SETTLE), self.app.loop).result()
|
|
687
|
+
self._choose_environment(error.choice, settle=SETTLE, generation=generation), self.app.loop).result()
|
|
634
688
|
if place is None:
|
|
635
|
-
self._later(self._cancel_start, text)
|
|
689
|
+
self._later(self._cancel_start, text, generation)
|
|
636
690
|
return
|
|
637
691
|
continue
|
|
638
692
|
accepted = asyncio.run_coroutine_threadsafe(
|
|
639
|
-
self._choose_first_use(error.choice), self.app.loop).result()
|
|
693
|
+
self._choose_first_use(error.choice, generation=generation), self.app.loop).result()
|
|
640
694
|
if not accepted:
|
|
641
|
-
self._later(self._cancel_start, text)
|
|
695
|
+
self._later(self._cancel_start, text, generation)
|
|
642
696
|
return
|
|
643
697
|
except Exception as error:
|
|
644
698
|
# As before the message: an ended conversation stays ended, and the next
|
|
645
699
|
# message starts a new one again.
|
|
646
|
-
self.
|
|
647
|
-
self.note(f"(could not start: {error})", "red")
|
|
700
|
+
self._later(self._failed_start, generation, str(error))
|
|
648
701
|
return
|
|
649
|
-
self._later(self._started, conversation)
|
|
702
|
+
self._later(self._started, conversation, generation, host)
|
|
650
703
|
|
|
651
704
|
threading.Thread(target=begin, daemon=True).start()
|
|
652
705
|
|
|
653
|
-
async def _choose_first_use(self, choice):
|
|
706
|
+
async def _choose_first_use(self, choice, generation=None):
|
|
654
707
|
"""No initial answer: Enter on the placeholder does not save a preference."""
|
|
708
|
+
if generation is not None and generation != self.generation:
|
|
709
|
+
return False
|
|
655
710
|
options = choice["options"]
|
|
656
711
|
while True:
|
|
712
|
+
if generation is not None and generation != self.generation:
|
|
713
|
+
return False
|
|
657
714
|
picked = await self._view(views.choose(choice["title"],
|
|
658
715
|
["Choose an option below (nothing selected)", *[row["label"] for row in options]],
|
|
659
716
|
hint="↑↓ choose · Enter confirm · Esc cancel task · Saved for future tasks; change in /settings"))
|
|
717
|
+
if generation is not None and generation != self.generation:
|
|
718
|
+
return False
|
|
660
719
|
if picked is None:
|
|
661
720
|
return False
|
|
662
721
|
if picked == 0:
|
|
663
722
|
continue
|
|
664
723
|
changes = {choice["section"]: {choice["key"]: options[picked - 1]["value"]}}
|
|
665
|
-
|
|
666
|
-
|
|
724
|
+
def save():
|
|
725
|
+
if generation is not None and generation != self.generation:
|
|
726
|
+
return False
|
|
727
|
+
host = self._host()
|
|
728
|
+
if generation is not None and generation != self.generation:
|
|
729
|
+
return False
|
|
730
|
+
host.post("/api/app/settings", changes)
|
|
731
|
+
return True
|
|
732
|
+
|
|
733
|
+
return await asyncio.to_thread(save)
|
|
667
734
|
|
|
668
735
|
def _open_environment(self):
|
|
669
736
|
"""A conversation opens: ask where it works before the first message is typed, when
|
|
@@ -688,21 +755,27 @@ class Chat:
|
|
|
688
755
|
|
|
689
756
|
self.app.create_background_task(self._guarded(ask))
|
|
690
757
|
|
|
691
|
-
async def _choose_environment(self, choice, settle=0.0):
|
|
758
|
+
async def _choose_environment(self, choice, settle=0.0, generation=None):
|
|
692
759
|
"""The opening choice of a new conversation: where it works. The last choice is
|
|
693
760
|
highlighted and Enter takes it; with none yet, nothing is preselected. A kind bound
|
|
694
761
|
to a folder then asks for the folder (this directory inside a repository, else the
|
|
695
762
|
last one). (kind, folder), or None when cancelled. Nothing is saved as a setting."""
|
|
763
|
+
if generation is not None and generation != self.generation:
|
|
764
|
+
return None
|
|
696
765
|
options = choice["options"]
|
|
697
766
|
values = [row["value"] for row in options]
|
|
698
767
|
chosen = choice.get("selected") in values
|
|
699
768
|
rows = [environment_row(row) for row in options]
|
|
700
769
|
while True:
|
|
770
|
+
if generation is not None and generation != self.generation:
|
|
771
|
+
return None
|
|
701
772
|
picked = await self._view(views.choose(
|
|
702
773
|
choice["title"], rows if chosen else ["Choose an option below (nothing selected)", *rows],
|
|
703
774
|
current=values.index(choice["selected"]) if chosen else 0, settle=settle,
|
|
704
775
|
hint="↑↓ choose · Enter confirm · Esc cancel task · Asked for each new conversation "
|
|
705
776
|
"(session.environment in /settings)"))
|
|
777
|
+
if generation is not None and generation != self.generation:
|
|
778
|
+
return None
|
|
706
779
|
if picked is None:
|
|
707
780
|
return None
|
|
708
781
|
if not chosen:
|
|
@@ -715,6 +788,8 @@ class Chat:
|
|
|
715
788
|
folder = await self._view(views.ask(f"{row.get('name') or row['value']}: the folder to work in",
|
|
716
789
|
default_folder(choice.get("folder")),
|
|
717
790
|
hint="Enter confirm · Esc back"))
|
|
791
|
+
if generation is not None and generation != self.generation:
|
|
792
|
+
return None
|
|
718
793
|
if folder and folder.strip():
|
|
719
794
|
return row["value"], str(Path(folder.strip()).expanduser())
|
|
720
795
|
|
|
@@ -746,23 +821,38 @@ class Chat:
|
|
|
746
821
|
self.agents_on = True
|
|
747
822
|
self.note("Sub-agents are on for the next conversation (session.agents in /settings keeps them on)")
|
|
748
823
|
|
|
749
|
-
def
|
|
824
|
+
def _failed_start(self, generation, error):
|
|
825
|
+
if generation != self.generation:
|
|
826
|
+
return
|
|
827
|
+
self.status, self.starting, self.pending = self.before_start, None, []
|
|
828
|
+
self.note(f"(could not start: {error}; queued follow-ups discarded)", "red")
|
|
829
|
+
|
|
830
|
+
def _cancel_start(self, text, generation=None):
|
|
831
|
+
if generation is not None and generation != self.generation:
|
|
832
|
+
return
|
|
750
833
|
self.status, self.starting = self.before_start, None
|
|
751
834
|
self.pending = []
|
|
752
835
|
self.buffer.text = text
|
|
753
836
|
self.buffer.cursor_position = len(text) # typing goes on from its end, as before it was sent
|
|
754
837
|
self.note("Task not started. Your message is kept in the input box.")
|
|
755
838
|
|
|
756
|
-
def _starting(self, message):
|
|
839
|
+
def _starting(self, message, generation=None):
|
|
757
840
|
"""What starting the conversation says (the session host starting): the status line's."""
|
|
841
|
+
if generation is not None and generation != self.generation:
|
|
842
|
+
return
|
|
758
843
|
self.starting = str(message).removeprefix("harness: ").split(" (log:")[0]
|
|
759
844
|
self._later(self.app.invalidate)
|
|
760
845
|
|
|
761
|
-
def _started(self, conversation):
|
|
846
|
+
def _started(self, conversation, generation=None, host=None):
|
|
847
|
+
if generation is not None and generation != self.generation:
|
|
848
|
+
return
|
|
849
|
+
pending, self.pending = self.pending, []
|
|
850
|
+
if host is not None:
|
|
851
|
+
self.host = host
|
|
762
852
|
self.starting = None
|
|
763
853
|
self._follow(conversation)
|
|
764
854
|
self.status = "RUNNING"
|
|
765
|
-
for text, files in
|
|
855
|
+
for text, files in pending:
|
|
766
856
|
self._background(_message, conversation, text, files)
|
|
767
857
|
self.pending = []
|
|
768
858
|
|
|
@@ -779,6 +869,19 @@ class Chat:
|
|
|
779
869
|
if not line:
|
|
780
870
|
return
|
|
781
871
|
|
|
872
|
+
origin, generation = self.conversation, self.generation
|
|
873
|
+
|
|
874
|
+
def deliver(output):
|
|
875
|
+
message = f"I ran `{line}` here:\n```\n{formats.clip(output, 20000)}\n```"
|
|
876
|
+
if origin is not None and origin is self.conversation:
|
|
877
|
+
self.send(message)
|
|
878
|
+
elif origin is not None:
|
|
879
|
+
self._background(_message, origin, message, ())
|
|
880
|
+
elif generation == self.generation:
|
|
881
|
+
self.send(message)
|
|
882
|
+
else:
|
|
883
|
+
self.note("Shell output was not sent: its original conversation was left.")
|
|
884
|
+
|
|
782
885
|
def run():
|
|
783
886
|
try:
|
|
784
887
|
done = subprocess.run(line, shell=True, capture_output=True, text=True, encoding=locale.getpreferredencoding(False),
|
|
@@ -789,7 +892,7 @@ class Chat:
|
|
|
789
892
|
self._later(self._print, Text(f"! {line}", style="bold"), Text("\n".join(formats.clip_lines(output, 40)),
|
|
790
893
|
style="dim"))
|
|
791
894
|
if send:
|
|
792
|
-
self._later(
|
|
895
|
+
self._later(deliver, output)
|
|
793
896
|
|
|
794
897
|
threading.Thread(target=run, daemon=True).start()
|
|
795
898
|
|
|
@@ -844,17 +947,20 @@ class Chat:
|
|
|
844
947
|
return
|
|
845
948
|
agent, _, context = words.partition(" ")
|
|
846
949
|
|
|
950
|
+
origin, generation = self.conversation, self.generation
|
|
951
|
+
|
|
847
952
|
def handoff():
|
|
848
|
-
self._later(self._started,
|
|
953
|
+
self._later(self._started, origin.handoff(agent, context), generation)
|
|
849
954
|
|
|
850
955
|
self._background(handoff)
|
|
851
956
|
|
|
852
957
|
def do_import(self, words):
|
|
853
958
|
provider, _, file = words.partition(" ")
|
|
959
|
+
generation = self.generation
|
|
854
960
|
|
|
855
961
|
def load():
|
|
856
962
|
conversation = self._host().import_session(Path(file.strip('"')).expanduser().resolve(), provider)
|
|
857
|
-
self._later(self._started, conversation)
|
|
963
|
+
self._later(self._started, conversation, generation)
|
|
858
964
|
|
|
859
965
|
self._background(load)
|
|
860
966
|
|
|
@@ -868,24 +974,56 @@ class Chat:
|
|
|
868
974
|
def _continue(self, session, text=None, files=()):
|
|
869
975
|
"""Go on with the ended session `session` in its own id (the host starts it again
|
|
870
976
|
from what it kept), then send it `text`."""
|
|
977
|
+
generation = self.generation
|
|
871
978
|
conversation = self._host().resume_session(session)
|
|
872
979
|
if text is not None:
|
|
873
980
|
_message(conversation, text, files)
|
|
874
|
-
self._later(self.
|
|
981
|
+
self._later(self._resumed, conversation, generation)
|
|
982
|
+
|
|
983
|
+
def _resumed(self, conversation, generation):
|
|
984
|
+
if generation == self.generation:
|
|
985
|
+
self._follow(conversation)
|
|
875
986
|
|
|
876
987
|
def _leave(self):
|
|
877
988
|
"""No conversation shown (the one that was goes on)."""
|
|
878
989
|
self.stop.set()
|
|
879
990
|
self.generation += 1
|
|
991
|
+
self.pending, self.starting = [], None
|
|
880
992
|
self.conversation, self.status, self.ask, self.lanes = None, None, None, Lanes()
|
|
881
993
|
self.learning = None
|
|
882
994
|
self._reset()
|
|
883
|
-
|
|
884
|
-
from ..providers import load
|
|
995
|
+
self._refresh_next_model()
|
|
885
996
|
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
997
|
+
def _refresh_next_model(self, *, rows=None, initial_name=None):
|
|
998
|
+
"""Keep the explicit next route, including an invalid one, until /model replaces it."""
|
|
999
|
+
problem, label = None, initial_name
|
|
1000
|
+
if self.model_entry is not None:
|
|
1001
|
+
if initial_name is None:
|
|
1002
|
+
try:
|
|
1003
|
+
if rows is None:
|
|
1004
|
+
from ..model_list import select
|
|
1005
|
+
|
|
1006
|
+
row = select(data(), self.model_entry)
|
|
1007
|
+
else:
|
|
1008
|
+
row = next((row for row in rows if row["enabled"] and row["id"] == self.model_entry), None)
|
|
1009
|
+
if row is None:
|
|
1010
|
+
raise ValueError("selected model is unavailable")
|
|
1011
|
+
label = row["name"]
|
|
1012
|
+
except (OSError, ValueError):
|
|
1013
|
+
self.model_effort = None
|
|
1014
|
+
label = "model unavailable · choose with /model"
|
|
1015
|
+
problem = "The selected model is unavailable. Choose with /model before starting a new conversation."
|
|
1016
|
+
else:
|
|
1017
|
+
try:
|
|
1018
|
+
from ..providers import load
|
|
1019
|
+
|
|
1020
|
+
label = load(data())["model"]
|
|
1021
|
+
except Exception:
|
|
1022
|
+
label = self.model
|
|
1023
|
+
self.next_model_label, self.next_model_problem = label, problem
|
|
1024
|
+
if self.conversation is None:
|
|
1025
|
+
self.model = label
|
|
1026
|
+
return problem is None
|
|
889
1027
|
|
|
890
1028
|
def do_exit(self, _):
|
|
891
1029
|
self.app.exit()
|
|
@@ -926,12 +1064,21 @@ class Chat:
|
|
|
926
1064
|
|
|
927
1065
|
def do_host(self, words):
|
|
928
1066
|
"""/host: how the session host runs; /host stop: end it, with what runs in it."""
|
|
1067
|
+
async def show():
|
|
1068
|
+
if str(words or "").strip() == "stop":
|
|
1069
|
+
await asyncio.to_thread(self._host_info, words)
|
|
1070
|
+
else:
|
|
1071
|
+
await self._request(self._host_info, words)
|
|
1072
|
+
|
|
1073
|
+
self.app.create_background_task(self._guarded(show))
|
|
1074
|
+
|
|
1075
|
+
def _host_info(self, words):
|
|
929
1076
|
host = self._host(start=False)
|
|
930
1077
|
if host is None:
|
|
931
1078
|
self.note("No session host runs (the next conversation starts it)")
|
|
932
1079
|
return
|
|
933
1080
|
if str(words or "").strip() == "stop":
|
|
934
|
-
self._leave
|
|
1081
|
+
self._later(self._leave)
|
|
935
1082
|
host.stop(force=True)
|
|
936
1083
|
self.host = None
|
|
937
1084
|
self.note(f"Stopped the session host at {host.url}")
|
|
@@ -946,12 +1093,14 @@ class Chat:
|
|
|
946
1093
|
from harness.runtime.decision.model import valid_effort
|
|
947
1094
|
|
|
948
1095
|
async def pick():
|
|
949
|
-
|
|
1096
|
+
conversation = self.conversation
|
|
1097
|
+
active = conversation is not None and self.status not in ENDED
|
|
950
1098
|
level = str(words or "").strip()
|
|
1099
|
+
if active and not level:
|
|
1100
|
+
self.note("Use /effort LEVEL or /effort default for the open conversation.")
|
|
1101
|
+
return
|
|
1102
|
+
row = None if active else select(data(), self.model_entry)
|
|
951
1103
|
if not level:
|
|
952
|
-
if self.conversation is not None and self.status not in ENDED:
|
|
953
|
-
self.note("Use /effort LEVEL or /effort default for the open conversation.")
|
|
954
|
-
return
|
|
955
1104
|
levels = [value for value in (row or {}).get("efforts", []) if value != "default"]
|
|
956
1105
|
option = await self._view(views.choose("Reasoning effort", ["Provider default", *levels]))
|
|
957
1106
|
if option is None:
|
|
@@ -960,8 +1109,8 @@ class Chat:
|
|
|
960
1109
|
effort = "" if level == "default" else level
|
|
961
1110
|
if not valid_effort(effort):
|
|
962
1111
|
raise ValueError("invalid reasoning effort ID")
|
|
963
|
-
if
|
|
964
|
-
self._background(lambda:
|
|
1112
|
+
if active:
|
|
1113
|
+
self._background(lambda: conversation.set_model(reasoning_effort=effort))
|
|
965
1114
|
elif row:
|
|
966
1115
|
if effort and effort not in row["efforts"]:
|
|
967
1116
|
raise ValueError("this model does not offer that reasoning effort")
|
|
@@ -990,23 +1139,26 @@ class Chat:
|
|
|
990
1139
|
self.note("/experiment NAME [TASK [SEED]] [-- instruction]", "red")
|
|
991
1140
|
return
|
|
992
1141
|
|
|
1142
|
+
generation = self.generation
|
|
1143
|
+
|
|
993
1144
|
def start():
|
|
994
1145
|
request = {"experiment": parts[0], "task": parts[1] if len(parts) > 1 else None,
|
|
995
1146
|
"seed": seed, "frontend": "terminal",
|
|
996
1147
|
**({"instruction": instruction.strip()} if instruction.strip() else {})}
|
|
997
1148
|
conversation = self._host().start(**request)
|
|
998
1149
|
self._later(self._print, Text(f"── experiment {parts[0]} " + "─" * 40, style="dim"))
|
|
999
|
-
self._later(self._started, conversation)
|
|
1150
|
+
self._later(self._started, conversation, generation)
|
|
1000
1151
|
|
|
1001
1152
|
self._background(start)
|
|
1002
1153
|
|
|
1003
1154
|
def do_sessions(self, _):
|
|
1004
1155
|
async def pick():
|
|
1005
|
-
host = self._host
|
|
1156
|
+
host = await self._request(self._host, False)
|
|
1006
1157
|
if host is None:
|
|
1007
1158
|
self.note("No session host runs: nothing is open")
|
|
1008
1159
|
return
|
|
1009
|
-
|
|
1160
|
+
sessions = await self._request(host.sessions)
|
|
1161
|
+
lines = table_rows([session.row for session in sessions])
|
|
1010
1162
|
if not lines:
|
|
1011
1163
|
self.note("No sessions run")
|
|
1012
1164
|
return
|
|
@@ -1016,14 +1168,14 @@ class Chat:
|
|
|
1016
1168
|
picked = await self._view(views.choose("Sessions that run", rows, current=current))
|
|
1017
1169
|
if picked is not None and lines[picked]["run"] != getattr(self.conversation, "run", None):
|
|
1018
1170
|
self._print(Text(f"── session {lines[picked]['run']} " + "─" * 40, style="dim"))
|
|
1019
|
-
self._follow(host.conversation
|
|
1171
|
+
self._follow(await self._request(host.conversation, lines[picked]["run"]))
|
|
1020
1172
|
|
|
1021
1173
|
self.app.create_background_task(self._guarded(pick))
|
|
1022
1174
|
|
|
1023
1175
|
def do_resume(self, _):
|
|
1024
1176
|
async def pick():
|
|
1025
|
-
host = self._host
|
|
1026
|
-
sessions = [session.row for session in host.sessions
|
|
1177
|
+
host = await self._request(self._host)
|
|
1178
|
+
sessions = [session.row for session in await self._request(host.sessions, all=True, limit=100)]
|
|
1027
1179
|
if not sessions:
|
|
1028
1180
|
self.note("No conversations yet")
|
|
1029
1181
|
return
|
|
@@ -1035,7 +1187,7 @@ class Chat:
|
|
|
1035
1187
|
row = sessions[picked]
|
|
1036
1188
|
self._print(Text(f"── {row.get('title') or row['id']} " + "─" * 40, style="dim"))
|
|
1037
1189
|
if row.get("status") in LIVE:
|
|
1038
|
-
self._follow(host.conversation
|
|
1190
|
+
self._follow(await self._request(host.conversation, row["run"]))
|
|
1039
1191
|
return
|
|
1040
1192
|
if row.get("kind", "harness") == "harness":
|
|
1041
1193
|
# It goes on in its own session: its messages and facts, a new kernel.
|
|
@@ -1057,8 +1209,11 @@ class Chat:
|
|
|
1057
1209
|
from ..providers import PROVIDERS
|
|
1058
1210
|
|
|
1059
1211
|
options = [row for row in models(data()) if row["enabled"]]
|
|
1060
|
-
|
|
1061
|
-
|
|
1212
|
+
try:
|
|
1213
|
+
current = select(data(), self.model_entry) if any(
|
|
1214
|
+
row["id"] == self.model_entry for row in options) else select(data())
|
|
1215
|
+
except ValueError:
|
|
1216
|
+
current = None # an invalid default must not prevent choosing a valid route
|
|
1062
1217
|
rows = [f"{row['name']} · {PROVIDERS[row['provider']].name if row['provider'] in PROVIDERS else row['provider']}"
|
|
1063
1218
|
+ (f" · {row['base_url']}" if row["base_url"] else "") for row in options]
|
|
1064
1219
|
picked = await self._view(views.choose("Model for new conversations", rows,
|
|
@@ -1067,8 +1222,7 @@ class Chat:
|
|
|
1067
1222
|
if picked is not None:
|
|
1068
1223
|
row = options[picked]
|
|
1069
1224
|
self.model_entry, self.model_effort = row["id"], None
|
|
1070
|
-
|
|
1071
|
-
self.model = row["name"]
|
|
1225
|
+
self._refresh_next_model(rows=options)
|
|
1072
1226
|
self.note(f"Model for new conversations: {rows[picked]}")
|
|
1073
1227
|
|
|
1074
1228
|
self.app.create_background_task(self._guarded(pick))
|
|
@@ -1084,6 +1238,7 @@ class Chat:
|
|
|
1084
1238
|
models(data()) # writes the list when there is none yet
|
|
1085
1239
|
except ValueError:
|
|
1086
1240
|
pass # one saved with a mistake opens as it is, to be put right
|
|
1241
|
+
self.note(f"Editing {path}. Save and close your editor to return. vi: Esc, :wq, Enter saves; :q! discards. Set EDITOR to choose another editor.")
|
|
1087
1242
|
editor = os.environ.get("EDITOR") or ("notepad.exe" if os.name == "nt" else "vi")
|
|
1088
1243
|
command = [editor] if os.path.isfile(editor) else split(editor, posix=os.name != "nt")
|
|
1089
1244
|
async with in_terminal():
|
|
@@ -1094,6 +1249,8 @@ class Chat:
|
|
|
1094
1249
|
rows = models(data())
|
|
1095
1250
|
except ValueError as error:
|
|
1096
1251
|
raise ValueError(f"{error}; /models opens it again to correct it") from None
|
|
1252
|
+
if not self._refresh_next_model(rows=rows):
|
|
1253
|
+
self.note(self.next_model_problem, "yellow")
|
|
1097
1254
|
count = sum(row["enabled"] for row in rows)
|
|
1098
1255
|
self.note(f"{count} enabled models · /model to select · {path}")
|
|
1099
1256
|
|
|
@@ -1108,7 +1265,7 @@ class Chat:
|
|
|
1108
1265
|
|
|
1109
1266
|
def do_packages(self, _):
|
|
1110
1267
|
async def edit():
|
|
1111
|
-
for line in await self._view(views.packages_view()):
|
|
1268
|
+
for line in await self._view(views.packages_view(await self._request(self._host))):
|
|
1112
1269
|
self.note(line)
|
|
1113
1270
|
|
|
1114
1271
|
self.app.create_background_task(self._guarded(edit))
|
|
@@ -1122,10 +1279,29 @@ class Chat:
|
|
|
1122
1279
|
(lambda: rows(run=conversation.directory)) if conversation is not None else None)
|
|
1123
1280
|
self.app.create_background_task(self._guarded(lambda: self._view(views.library_view(memory))))
|
|
1124
1281
|
|
|
1282
|
+
async def _request(self, function, *args, **kwargs):
|
|
1283
|
+
"""A host read may finish after cancellation, but never applies its abandoned result."""
|
|
1284
|
+
task, generation = asyncio.current_task(), self.generation
|
|
1285
|
+
self.waiting = task
|
|
1286
|
+
self.app.invalidate()
|
|
1287
|
+
try:
|
|
1288
|
+
result = await asyncio.to_thread(function, *args, **kwargs)
|
|
1289
|
+
if generation != self.generation:
|
|
1290
|
+
raise asyncio.CancelledError
|
|
1291
|
+
return result
|
|
1292
|
+
finally:
|
|
1293
|
+
if self.waiting is task:
|
|
1294
|
+
self.waiting = None
|
|
1295
|
+
self.app.invalidate()
|
|
1296
|
+
|
|
1125
1297
|
async def _guarded(self, function):
|
|
1126
1298
|
try:
|
|
1127
1299
|
await function()
|
|
1300
|
+
except asyncio.CancelledError:
|
|
1301
|
+
self.note("Stopped waiting for the host.")
|
|
1128
1302
|
except Exception as error:
|
|
1303
|
+
if isinstance(error, (HostGone, OSError)):
|
|
1304
|
+
self.host = None
|
|
1129
1305
|
self.note(f"({error})", "red")
|
|
1130
1306
|
|
|
1131
1307
|
|