@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.
- 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 +68 -38
- package/python/harness/builtin/prompts/shared/learning-goal.md +1 -1
- package/python/harness/cli.py +140 -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 +71 -27
- package/python/harness/instructions.py +329 -0
- 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/model.py +9 -4
- package/python/harness/runtime/events.py +1 -0
- package/python/harness/runtime/execution/entries.py +53 -7
- package/python/harness/runtime/execution/session.py +57 -10
- package/python/harness/runtime/learning/active.py +4 -4
- package/python/harness/runtime/reactive/tree.py +96 -53
- package/python/harness/runtime/task/environments.py +3 -1
- package/python/harness/runtime/task/run.py +93 -4
- package/python/harness/runtime/tick.py +34 -3
- package/python/harness/settings.py +23 -1
- package/python/harness/terminal.py +3 -0
- package/python/harness/transcript.py +12 -0
- package/python/harness/tui/__init__.py +28 -6
- package/python/harness/tui/chat.py +323 -80
- package/python/harness/tui/pty.py +16 -0
- package/python/harness/tui/renderer.py +1 -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,8 +105,11 @@ 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 = []
|
|
111
|
+
self.printed = [] # every renderable printed into the scrollback, in order (_resized prints them again)
|
|
112
|
+
self.printed_size = None # the terminal size the scrollback was last printed for
|
|
109
113
|
self.help = False
|
|
110
114
|
self.ask = None # what waits for the user's approval: {text, options, at, reason}
|
|
111
115
|
self.echoed = None # the first message of a conversation started here, printed at once
|
|
@@ -113,18 +117,14 @@ class Chat:
|
|
|
113
117
|
self.starting = None # what starting the first message's conversation says now
|
|
114
118
|
self.armed = {} # key: when it was last pressed (twice to leave, Esc Esc)
|
|
115
119
|
self.model, self.workspace = None, None
|
|
116
|
-
self.model_entry =
|
|
120
|
+
self.model_entry = getattr(start, "model_entry", None)
|
|
121
|
+
self.model_effort = getattr(start, "model_effort", None)
|
|
117
122
|
self.environment = None # (kind, folder) picked with /environment for the next conversation
|
|
118
123
|
self.agents_on = False # /agents before a conversation starts: on in the next one
|
|
119
124
|
self.learning = None # where a conversation that learns its environment stands (runtime/learning/active.py progress())
|
|
120
125
|
self.lanes = Lanes()
|
|
121
126
|
self._reset()
|
|
122
|
-
|
|
123
|
-
from ..providers import load
|
|
124
|
-
|
|
125
|
-
self.model = load(data())["model"]
|
|
126
|
-
except Exception:
|
|
127
|
-
pass
|
|
127
|
+
self._refresh_next_model(initial_name=getattr(start, "model_name", None))
|
|
128
128
|
# sys.stdout when it prints: patch_stdout's, above the live region.
|
|
129
129
|
self.console = Console(force_terminal=True, legacy_windows=False, highlight=False, soft_wrap=False,
|
|
130
130
|
color_system="truecolor" if os.environ.get("WT_SESSION") or os.environ.get("COLORTERM")
|
|
@@ -140,7 +140,7 @@ class Chat:
|
|
|
140
140
|
prompt = lambda line, wrap: [("class:rule", "› " if line == 0 and not wrap else " ")] # noqa: E731
|
|
141
141
|
field = Window(BufferControl(self.buffer, search_buffer_control=search.control, preview_search=True,
|
|
142
142
|
input_processors=[Placeholder(self)]),
|
|
143
|
-
height=
|
|
143
|
+
height=self._input_height, wrap_lines=True,
|
|
144
144
|
get_line_prefix=prompt, dont_extend_height=True)
|
|
145
145
|
rule = Window(height=1, char="─", style="class:rule")
|
|
146
146
|
# The completions under the input, as many lines as there are (at most 8).
|
|
@@ -148,7 +148,7 @@ class Chat:
|
|
|
148
148
|
self.buffer.complete_state.completions), 8) if self.buffer.complete_state else 1, scroll_offsets=ScrollOffsets(1, 1),
|
|
149
149
|
dont_extend_width=True, style="class:completion-menu"), has_completions)
|
|
150
150
|
status = VSplit([Window(FormattedTextControl(self._status), height=1),
|
|
151
|
-
Window(FormattedTextControl(self._hint), height=1, align=WindowAlign.RIGHT)])
|
|
151
|
+
Window(FormattedTextControl(self._hint), height=1, width=lambda: min(38, self.app.output.get_size().columns // 2), align=WindowAlign.RIGHT)])
|
|
152
152
|
body = HSplit([ConditionalContainer(Window(FormattedTextControl(self._asking), dont_extend_height=True),
|
|
153
153
|
Condition(lambda: self.ask is not None)),
|
|
154
154
|
rule, field, search, rule, menu, status,
|
|
@@ -161,9 +161,19 @@ class Chat:
|
|
|
161
161
|
|
|
162
162
|
app.renderer = WindowsInlineRenderer(app.renderer.style, app.output,
|
|
163
163
|
cpr_not_supported_callback=app.cpr_not_supported_callback)
|
|
164
|
+
else:
|
|
165
|
+
# A resize prints the chat again (_resized). tmux does not always deliver SIGWINCH for
|
|
166
|
+
# each change, so the size is also polled; _resized acts once per size.
|
|
167
|
+
app._on_resize = self._resized
|
|
168
|
+
app.terminal_size_polling_interval = 0.2
|
|
164
169
|
app.timeoutlen, app.ttimeoutlen = 0.3, 0.05
|
|
165
170
|
return app
|
|
166
171
|
|
|
172
|
+
def _input_height(self):
|
|
173
|
+
width = max(1, self.app.output.get_size().columns - 2)
|
|
174
|
+
return min(12, sum(max(1, (get_cwidth(line.expandtabs()) + width - 1) // width)
|
|
175
|
+
for line in self.buffer.text.split("\n")))
|
|
176
|
+
|
|
167
177
|
def _status(self):
|
|
168
178
|
status = self.status
|
|
169
179
|
if status == "starting":
|
|
@@ -178,6 +188,8 @@ class Chat:
|
|
|
178
188
|
state = ("class:status.state", "○ new conversation")
|
|
179
189
|
else:
|
|
180
190
|
state = ("class:status.state", "● " + word(status))
|
|
191
|
+
if self.app.output.get_size().columns < 80:
|
|
192
|
+
return [state]
|
|
181
193
|
# Learning the environment first: the line is cut at the terminal's width.
|
|
182
194
|
parts = [progress_line(self.learning, short=True) if self.learning else None, self.model,
|
|
183
195
|
self.workspace or (self.environment[0] if self.environment and self.conversation is None else None),
|
|
@@ -185,8 +197,12 @@ class Chat:
|
|
|
185
197
|
return [state] + [("class:status", " · " + part) for part in parts if part]
|
|
186
198
|
|
|
187
199
|
def _hint(self):
|
|
200
|
+
if getattr(self, "waiting", None) is not None:
|
|
201
|
+
return [("class:status.wait", "waiting · Esc cancel ")]
|
|
188
202
|
if self.armed.get("leave") and time.time() - self.armed["leave"][1] < TWICE:
|
|
189
203
|
return [("class:status.wait", f"{self.armed['leave'][0]} again to leave ")]
|
|
204
|
+
if self.app.output.get_size().columns < 70:
|
|
205
|
+
return [("class:status.hint", "esc pause" if self.status == "RUNNING" else "? keys · / commands")]
|
|
190
206
|
if self.status == "RUNNING":
|
|
191
207
|
return [("class:status.hint", "esc interrupt · type to steer ")]
|
|
192
208
|
return [("class:status.hint", "? keys · / commands ")]
|
|
@@ -268,7 +284,9 @@ class Chat:
|
|
|
268
284
|
|
|
269
285
|
@keys.add("escape")
|
|
270
286
|
def _(event):
|
|
271
|
-
if
|
|
287
|
+
if getattr(self, "waiting", None) is not None:
|
|
288
|
+
self.waiting.cancel()
|
|
289
|
+
elif buffer.complete_state:
|
|
272
290
|
buffer.cancel_completion()
|
|
273
291
|
elif self.ask is not None and self.ask.get("reason"):
|
|
274
292
|
self.ask["reason"] = False
|
|
@@ -323,12 +341,18 @@ class Chat:
|
|
|
323
341
|
|
|
324
342
|
async def _view(self, coroutine):
|
|
325
343
|
"""A full-screen view over the chat; what it returns."""
|
|
326
|
-
|
|
327
|
-
|
|
344
|
+
size = self.app.output.get_size()
|
|
345
|
+
try:
|
|
346
|
+
async with in_terminal(render_cli_done=False):
|
|
347
|
+
return await coroutine
|
|
348
|
+
finally:
|
|
349
|
+
if sys.platform != "win32" and self.app.output.get_size() != size:
|
|
350
|
+
self._resized()
|
|
328
351
|
|
|
329
352
|
def run(self):
|
|
330
353
|
"""Until the user leaves; returns the conversation shown then (None: none)."""
|
|
331
354
|
self._banner()
|
|
355
|
+
self.printed_size = self.app.output.get_size()
|
|
332
356
|
with patch_stdout(raw=True):
|
|
333
357
|
self.app.run(pre_run=lambda: self._follow(self.conversation, self.records)
|
|
334
358
|
if self.conversation is not None else self._open_environment())
|
|
@@ -339,9 +363,11 @@ class Chat:
|
|
|
339
363
|
from .. import __version__
|
|
340
364
|
|
|
341
365
|
here = os.getcwd().replace(os.path.expanduser("~"), "~", 1)
|
|
342
|
-
self.
|
|
343
|
-
|
|
344
|
-
|
|
366
|
+
self._print(Text.assemble(("The Harness", "bold"), f" {__version__} ", (here, "dim")),
|
|
367
|
+
Text("Tell it what to do. / for commands, @ to attach a file, ! to run a command, ? for keys.",
|
|
368
|
+
style="dim"))
|
|
369
|
+
if warning := getattr(self.start, "warning", None):
|
|
370
|
+
self.note(warning, "yellow")
|
|
345
371
|
|
|
346
372
|
# Printing into the scrollback (patch_stdout carries it above the live region).
|
|
347
373
|
|
|
@@ -349,6 +375,7 @@ class Chat:
|
|
|
349
375
|
if self.details_open:
|
|
350
376
|
self.details_output.extend(renderables)
|
|
351
377
|
return
|
|
378
|
+
self.printed.extend(renderables)
|
|
352
379
|
try:
|
|
353
380
|
self.console.width = self.app.output.get_size().columns
|
|
354
381
|
except Exception:
|
|
@@ -356,6 +383,29 @@ class Chat:
|
|
|
356
383
|
for renderable in renderables:
|
|
357
384
|
self.console.print(renderable)
|
|
358
385
|
|
|
386
|
+
def _resized(self):
|
|
387
|
+
"""The terminal changed size: clear it and print the chat again at the new width, then
|
|
388
|
+
draw the live region, as Claude Code does. A terminal reflows the rows it already shows
|
|
389
|
+
in its own way (tmux 3.2 and 3.8 split the same row differently), so erasing the old
|
|
390
|
+
live region in place left some of its rows behind. Clearing also takes the terminal's
|
|
391
|
+
scrollback from before the chat started."""
|
|
392
|
+
app = self.app
|
|
393
|
+
size = app.output.get_size()
|
|
394
|
+
if size == self.printed_size:
|
|
395
|
+
return
|
|
396
|
+
self.printed_size = size
|
|
397
|
+
stream = io.StringIO()
|
|
398
|
+
console = Console(file=stream, force_terminal=True, legacy_windows=False, highlight=False, soft_wrap=False,
|
|
399
|
+
color_system=self.console.color_system, width=size.columns)
|
|
400
|
+
for renderable in self.printed:
|
|
401
|
+
console.print(renderable)
|
|
402
|
+
# Home, clear the screen, then the scrollback (clearing the screen copies it there in tmux).
|
|
403
|
+
app.output.write_raw("\x1b[H\x1b[2J\x1b[3J" + stream.getvalue().replace("\n", "\r\n"))
|
|
404
|
+
app.output.flush()
|
|
405
|
+
app.renderer.reset(leave_alternate_screen=False)
|
|
406
|
+
app.renderer.request_absolute_cursor_position()
|
|
407
|
+
app.invalidate()
|
|
408
|
+
|
|
359
409
|
def note(self, text, style="dim"):
|
|
360
410
|
self._later(self._print, Text(str(text), style=style))
|
|
361
411
|
|
|
@@ -387,8 +437,11 @@ class Chat:
|
|
|
387
437
|
any other (that goes on)."""
|
|
388
438
|
self.stop.set()
|
|
389
439
|
self.stop, self.generation = threading.Event(), self.generation + 1
|
|
440
|
+
self.pending = []
|
|
441
|
+
self.starting = None
|
|
390
442
|
self.conversation, self.ask, self.lanes = conversation, None, Lanes()
|
|
391
443
|
self.learning, self.workspace, self.parked = None, None, False
|
|
444
|
+
self.instruction_files = [] # (label, path) of each instruction file the conversation read
|
|
392
445
|
self.status = getattr(conversation, "status", None)
|
|
393
446
|
self._reset()
|
|
394
447
|
generation, stop = self.generation, self.stop
|
|
@@ -398,7 +451,7 @@ class Chat:
|
|
|
398
451
|
if hasattr(conversation, "describe"):
|
|
399
452
|
conversation.describe()
|
|
400
453
|
agent = conversation.agent or {}
|
|
401
|
-
self.
|
|
454
|
+
self._later(self._described, generation, agent)
|
|
402
455
|
except Exception:
|
|
403
456
|
pass
|
|
404
457
|
try:
|
|
@@ -408,16 +461,21 @@ class Chat:
|
|
|
408
461
|
self._later(self.show, record, generation)
|
|
409
462
|
except HostGone as error:
|
|
410
463
|
self._later(self._lost, generation, f"({error}: /resume or harness --continue goes on with "
|
|
411
|
-
"this conversation
|
|
464
|
+
"this conversation)")
|
|
412
465
|
except Exception as error:
|
|
413
466
|
self._later(self._lost, generation, f"(the conversation cannot be read any more: {error})")
|
|
414
467
|
|
|
415
468
|
threading.Thread(target=read, daemon=True).start()
|
|
416
469
|
|
|
470
|
+
def _described(self, generation, agent):
|
|
471
|
+
if generation == self.generation:
|
|
472
|
+
self.model, self.workspace = agent.get("model") or self.model, agent.get("workspace")
|
|
473
|
+
|
|
417
474
|
def _lost(self, generation, text):
|
|
418
475
|
"""The conversation shown can no longer be followed: say why, and stop showing it as working."""
|
|
419
476
|
if generation != self.generation:
|
|
420
477
|
return
|
|
478
|
+
self.host = None
|
|
421
479
|
self.note(text, "red")
|
|
422
480
|
if self.status not in ENDED:
|
|
423
481
|
self.status, self.interrupted, self.ask = LOST, False, None
|
|
@@ -435,6 +493,12 @@ class Chat:
|
|
|
435
493
|
self.ask = None
|
|
436
494
|
if kind in ("physical_answer", "confirmation"):
|
|
437
495
|
self.ask = None
|
|
496
|
+
if kind == "instructions":
|
|
497
|
+
known = getattr(self, "instruction_files", None)
|
|
498
|
+
if known is None:
|
|
499
|
+
known = self.instruction_files = []
|
|
500
|
+
known += [(item["label"], item["path"]) for item in record.get("files") or ()
|
|
501
|
+
if (item["label"], item["path"]) not in known]
|
|
438
502
|
# The timeline's items too, for the reasoning and the answer of finish() in a program.
|
|
439
503
|
items = [item for item in transcript.items(record, self.names, timeline=True) if item["kind"] not in TIMELINE]
|
|
440
504
|
if kind == "cell" and self.program is not None:
|
|
@@ -493,7 +557,7 @@ class Chat:
|
|
|
493
557
|
"lexer": "python" if item["keys"].get("reply") == "python" else "json"}
|
|
494
558
|
return []
|
|
495
559
|
if kind in DETAILS and self.program is not None:
|
|
496
|
-
lines =
|
|
560
|
+
lines = self._detail_lines(item)
|
|
497
561
|
self.program["details"] += lines
|
|
498
562
|
return []
|
|
499
563
|
if kind == "state":
|
|
@@ -516,28 +580,41 @@ class Chat:
|
|
|
516
580
|
self.last_program = done
|
|
517
581
|
result = record.get("result") or {}
|
|
518
582
|
done.update(status=result.get("status"), seconds=result.get("seconds"))
|
|
519
|
-
lines = [
|
|
583
|
+
lines = [line for item in items for line in self._detail_lines(item)]
|
|
520
584
|
done["details"] += lines
|
|
521
585
|
return [self._program_line(done)]
|
|
522
586
|
|
|
587
|
+
@staticmethod
|
|
588
|
+
def _detail_lines(item):
|
|
589
|
+
if item["kind"] in ("output", "cell_error", "unhandled"):
|
|
590
|
+
return [Text(item["text"], style=ROLES.get(item["role"], ""))]
|
|
591
|
+
return [Text(line, style=ROLES.get(role, "")) for role, line in item_lines(item)]
|
|
592
|
+
|
|
523
593
|
async def _show_details(self, program):
|
|
524
594
|
if self.details_open:
|
|
525
595
|
return
|
|
526
596
|
self.details_open = True
|
|
527
597
|
try:
|
|
528
598
|
await self._view(views.read("Program details · Ctrl+O to return",
|
|
529
|
-
lambda: self._details_text(program), close_key="c-o"))
|
|
599
|
+
lambda: self._details_text(program), close_key="c-o", live=program.get("status") is None))
|
|
530
600
|
finally:
|
|
531
601
|
self.details_open = False
|
|
532
602
|
output, self.details_output = self.details_output, []
|
|
533
603
|
self._print(*output)
|
|
534
604
|
|
|
535
605
|
def _details_text(self, program):
|
|
606
|
+
width = self.app.output.get_size().columns
|
|
607
|
+
version = (len(program["details"]), program.get("status"), program.get("seconds"))
|
|
608
|
+
cached = program.get("_rendered")
|
|
609
|
+
if cached and cached[:2] == (version, width):
|
|
610
|
+
return cached[2]
|
|
536
611
|
stream = io.StringIO()
|
|
537
612
|
console = Console(file=stream, force_terminal=False, color_system=None,
|
|
538
|
-
width=
|
|
613
|
+
width=width, highlight=False)
|
|
539
614
|
console.print(*self._program_lines(program), sep="\n") # each output line on its own
|
|
540
|
-
|
|
615
|
+
value = stream.getvalue()
|
|
616
|
+
program["_rendered"] = (version, width, value)
|
|
617
|
+
return value
|
|
541
618
|
|
|
542
619
|
def _program_line(self, program) -> Text:
|
|
543
620
|
status = program.get("status") or "?"
|
|
@@ -591,8 +668,12 @@ class Chat:
|
|
|
591
668
|
if run is None or conversation is not self.conversation:
|
|
592
669
|
return
|
|
593
670
|
now = self._host().learning(run)
|
|
594
|
-
self.
|
|
595
|
-
|
|
671
|
+
self._later(self._learned, conversation, now)
|
|
672
|
+
|
|
673
|
+
def _learned(self, conversation, now):
|
|
674
|
+
if conversation is self.conversation:
|
|
675
|
+
self.learning = now if now.get("active") else None
|
|
676
|
+
self.app.invalidate()
|
|
596
677
|
|
|
597
678
|
def send(self, text, files=(), learn=None):
|
|
598
679
|
"""A message: to the conversation, or the first of a new one (`learn`: one that learns
|
|
@@ -607,63 +688,88 @@ class Chat:
|
|
|
607
688
|
elif self.start is None:
|
|
608
689
|
self.note("The conversation has ended", "red")
|
|
609
690
|
else:
|
|
691
|
+
if self.model_entry is not None and not self._refresh_next_model():
|
|
692
|
+
self.note(self.next_model_problem, "red")
|
|
693
|
+
return
|
|
694
|
+
generation = self.generation
|
|
695
|
+
self.pending = []
|
|
610
696
|
self.before_start = self.status
|
|
611
697
|
self.status, self.echoed = "starting", text
|
|
612
698
|
self._print(Text("› " + text, style="bold"))
|
|
613
699
|
|
|
700
|
+
place, self.environment = self.environment, None
|
|
701
|
+
agents, self.agents_on = self.agents_on, False
|
|
702
|
+
model_entry, model_effort = self.model_entry, self.model_effort
|
|
703
|
+
|
|
614
704
|
def begin():
|
|
615
705
|
# Where it works: what /environment picked, else the opening choice below.
|
|
616
|
-
place
|
|
617
|
-
agents, self.agents_on = self.agents_on, False
|
|
706
|
+
nonlocal place
|
|
618
707
|
try:
|
|
619
708
|
while True:
|
|
709
|
+
if generation != self.generation:
|
|
710
|
+
return
|
|
620
711
|
try:
|
|
621
|
-
|
|
712
|
+
host, conversation = self.start(text, files, log=lambda message: self._later(self._starting, message, generation),
|
|
622
713
|
**({"learn": learn} if learn is not None else {}),
|
|
623
|
-
**({"model_entry":
|
|
624
|
-
if
|
|
714
|
+
**({"model_entry": model_entry, "reasoning_effort": model_effort}
|
|
715
|
+
if model_entry else {}),
|
|
625
716
|
**({"workspace": place[0], "folder": place[1]} if place else {}),
|
|
626
717
|
**({"agents": True} if agents else {}))
|
|
627
718
|
break
|
|
628
719
|
except ChoiceRequired as error:
|
|
720
|
+
if generation != self.generation:
|
|
721
|
+
return
|
|
629
722
|
if error.choice.get("per_conversation"):
|
|
630
723
|
# (Opened by the Enter that sent the message: that key press
|
|
631
724
|
# must not answer it.)
|
|
632
725
|
place = asyncio.run_coroutine_threadsafe(
|
|
633
|
-
self._choose_environment(error.choice, settle=SETTLE), self.app.loop).result()
|
|
726
|
+
self._choose_environment(error.choice, settle=SETTLE, generation=generation), self.app.loop).result()
|
|
634
727
|
if place is None:
|
|
635
|
-
self._later(self._cancel_start, text)
|
|
728
|
+
self._later(self._cancel_start, text, generation)
|
|
636
729
|
return
|
|
637
730
|
continue
|
|
638
731
|
accepted = asyncio.run_coroutine_threadsafe(
|
|
639
|
-
self._choose_first_use(error.choice), self.app.loop).result()
|
|
732
|
+
self._choose_first_use(error.choice, generation=generation), self.app.loop).result()
|
|
640
733
|
if not accepted:
|
|
641
|
-
self._later(self._cancel_start, text)
|
|
734
|
+
self._later(self._cancel_start, text, generation)
|
|
642
735
|
return
|
|
643
736
|
except Exception as error:
|
|
644
737
|
# As before the message: an ended conversation stays ended, and the next
|
|
645
738
|
# message starts a new one again.
|
|
646
|
-
self.
|
|
647
|
-
self.note(f"(could not start: {error})", "red")
|
|
739
|
+
self._later(self._failed_start, generation, str(error))
|
|
648
740
|
return
|
|
649
|
-
self._later(self._started, conversation)
|
|
741
|
+
self._later(self._started, conversation, generation, host)
|
|
650
742
|
|
|
651
743
|
threading.Thread(target=begin, daemon=True).start()
|
|
652
744
|
|
|
653
|
-
async def _choose_first_use(self, choice):
|
|
745
|
+
async def _choose_first_use(self, choice, generation=None):
|
|
654
746
|
"""No initial answer: Enter on the placeholder does not save a preference."""
|
|
747
|
+
if generation is not None and generation != self.generation:
|
|
748
|
+
return False
|
|
655
749
|
options = choice["options"]
|
|
656
750
|
while True:
|
|
751
|
+
if generation is not None and generation != self.generation:
|
|
752
|
+
return False
|
|
657
753
|
picked = await self._view(views.choose(choice["title"],
|
|
658
754
|
["Choose an option below (nothing selected)", *[row["label"] for row in options]],
|
|
659
755
|
hint="↑↓ choose · Enter confirm · Esc cancel task · Saved for future tasks; change in /settings"))
|
|
756
|
+
if generation is not None and generation != self.generation:
|
|
757
|
+
return False
|
|
660
758
|
if picked is None:
|
|
661
759
|
return False
|
|
662
760
|
if picked == 0:
|
|
663
761
|
continue
|
|
664
762
|
changes = {choice["section"]: {choice["key"]: options[picked - 1]["value"]}}
|
|
665
|
-
|
|
666
|
-
|
|
763
|
+
def save():
|
|
764
|
+
if generation is not None and generation != self.generation:
|
|
765
|
+
return False
|
|
766
|
+
host = self._host()
|
|
767
|
+
if generation is not None and generation != self.generation:
|
|
768
|
+
return False
|
|
769
|
+
host.post("/api/app/settings", changes)
|
|
770
|
+
return True
|
|
771
|
+
|
|
772
|
+
return await asyncio.to_thread(save)
|
|
667
773
|
|
|
668
774
|
def _open_environment(self):
|
|
669
775
|
"""A conversation opens: ask where it works before the first message is typed, when
|
|
@@ -688,21 +794,27 @@ class Chat:
|
|
|
688
794
|
|
|
689
795
|
self.app.create_background_task(self._guarded(ask))
|
|
690
796
|
|
|
691
|
-
async def _choose_environment(self, choice, settle=0.0):
|
|
797
|
+
async def _choose_environment(self, choice, settle=0.0, generation=None):
|
|
692
798
|
"""The opening choice of a new conversation: where it works. The last choice is
|
|
693
799
|
highlighted and Enter takes it; with none yet, nothing is preselected. A kind bound
|
|
694
800
|
to a folder then asks for the folder (this directory inside a repository, else the
|
|
695
801
|
last one). (kind, folder), or None when cancelled. Nothing is saved as a setting."""
|
|
802
|
+
if generation is not None and generation != self.generation:
|
|
803
|
+
return None
|
|
696
804
|
options = choice["options"]
|
|
697
805
|
values = [row["value"] for row in options]
|
|
698
806
|
chosen = choice.get("selected") in values
|
|
699
807
|
rows = [environment_row(row) for row in options]
|
|
700
808
|
while True:
|
|
809
|
+
if generation is not None and generation != self.generation:
|
|
810
|
+
return None
|
|
701
811
|
picked = await self._view(views.choose(
|
|
702
812
|
choice["title"], rows if chosen else ["Choose an option below (nothing selected)", *rows],
|
|
703
813
|
current=values.index(choice["selected"]) if chosen else 0, settle=settle,
|
|
704
814
|
hint="↑↓ choose · Enter confirm · Esc cancel task · Asked for each new conversation "
|
|
705
815
|
"(session.environment in /settings)"))
|
|
816
|
+
if generation is not None and generation != self.generation:
|
|
817
|
+
return None
|
|
706
818
|
if picked is None:
|
|
707
819
|
return None
|
|
708
820
|
if not chosen:
|
|
@@ -715,6 +827,8 @@ class Chat:
|
|
|
715
827
|
folder = await self._view(views.ask(f"{row.get('name') or row['value']}: the folder to work in",
|
|
716
828
|
default_folder(choice.get("folder")),
|
|
717
829
|
hint="Enter confirm · Esc back"))
|
|
830
|
+
if generation is not None and generation != self.generation:
|
|
831
|
+
return None
|
|
718
832
|
if folder and folder.strip():
|
|
719
833
|
return row["value"], str(Path(folder.strip()).expanduser())
|
|
720
834
|
|
|
@@ -746,23 +860,38 @@ class Chat:
|
|
|
746
860
|
self.agents_on = True
|
|
747
861
|
self.note("Sub-agents are on for the next conversation (session.agents in /settings keeps them on)")
|
|
748
862
|
|
|
749
|
-
def
|
|
863
|
+
def _failed_start(self, generation, error):
|
|
864
|
+
if generation != self.generation:
|
|
865
|
+
return
|
|
866
|
+
self.status, self.starting, self.pending = self.before_start, None, []
|
|
867
|
+
self.note(f"(could not start: {error}; queued follow-ups discarded)", "red")
|
|
868
|
+
|
|
869
|
+
def _cancel_start(self, text, generation=None):
|
|
870
|
+
if generation is not None and generation != self.generation:
|
|
871
|
+
return
|
|
750
872
|
self.status, self.starting = self.before_start, None
|
|
751
873
|
self.pending = []
|
|
752
874
|
self.buffer.text = text
|
|
753
875
|
self.buffer.cursor_position = len(text) # typing goes on from its end, as before it was sent
|
|
754
876
|
self.note("Task not started. Your message is kept in the input box.")
|
|
755
877
|
|
|
756
|
-
def _starting(self, message):
|
|
878
|
+
def _starting(self, message, generation=None):
|
|
757
879
|
"""What starting the conversation says (the session host starting): the status line's."""
|
|
880
|
+
if generation is not None and generation != self.generation:
|
|
881
|
+
return
|
|
758
882
|
self.starting = str(message).removeprefix("harness: ").split(" (log:")[0]
|
|
759
883
|
self._later(self.app.invalidate)
|
|
760
884
|
|
|
761
|
-
def _started(self, conversation):
|
|
885
|
+
def _started(self, conversation, generation=None, host=None):
|
|
886
|
+
if generation is not None and generation != self.generation:
|
|
887
|
+
return
|
|
888
|
+
pending, self.pending = self.pending, []
|
|
889
|
+
if host is not None:
|
|
890
|
+
self.host = host
|
|
762
891
|
self.starting = None
|
|
763
892
|
self._follow(conversation)
|
|
764
893
|
self.status = "RUNNING"
|
|
765
|
-
for text, files in
|
|
894
|
+
for text, files in pending:
|
|
766
895
|
self._background(_message, conversation, text, files)
|
|
767
896
|
self.pending = []
|
|
768
897
|
|
|
@@ -779,6 +908,19 @@ class Chat:
|
|
|
779
908
|
if not line:
|
|
780
909
|
return
|
|
781
910
|
|
|
911
|
+
origin, generation = self.conversation, self.generation
|
|
912
|
+
|
|
913
|
+
def deliver(output):
|
|
914
|
+
message = f"I ran `{line}` here:\n```\n{formats.clip(output, 20000)}\n```"
|
|
915
|
+
if origin is not None and origin is self.conversation:
|
|
916
|
+
self.send(message)
|
|
917
|
+
elif origin is not None:
|
|
918
|
+
self._background(_message, origin, message, ())
|
|
919
|
+
elif generation == self.generation:
|
|
920
|
+
self.send(message)
|
|
921
|
+
else:
|
|
922
|
+
self.note("Shell output was not sent: its original conversation was left.")
|
|
923
|
+
|
|
782
924
|
def run():
|
|
783
925
|
try:
|
|
784
926
|
done = subprocess.run(line, shell=True, capture_output=True, text=True, encoding=locale.getpreferredencoding(False),
|
|
@@ -789,7 +931,7 @@ class Chat:
|
|
|
789
931
|
self._later(self._print, Text(f"! {line}", style="bold"), Text("\n".join(formats.clip_lines(output, 40)),
|
|
790
932
|
style="dim"))
|
|
791
933
|
if send:
|
|
792
|
-
self._later(
|
|
934
|
+
self._later(deliver, output)
|
|
793
935
|
|
|
794
936
|
threading.Thread(target=run, daemon=True).start()
|
|
795
937
|
|
|
@@ -844,17 +986,20 @@ class Chat:
|
|
|
844
986
|
return
|
|
845
987
|
agent, _, context = words.partition(" ")
|
|
846
988
|
|
|
989
|
+
origin, generation = self.conversation, self.generation
|
|
990
|
+
|
|
847
991
|
def handoff():
|
|
848
|
-
self._later(self._started,
|
|
992
|
+
self._later(self._started, origin.handoff(agent, context), generation)
|
|
849
993
|
|
|
850
994
|
self._background(handoff)
|
|
851
995
|
|
|
852
996
|
def do_import(self, words):
|
|
853
997
|
provider, _, file = words.partition(" ")
|
|
998
|
+
generation = self.generation
|
|
854
999
|
|
|
855
1000
|
def load():
|
|
856
1001
|
conversation = self._host().import_session(Path(file.strip('"')).expanduser().resolve(), provider)
|
|
857
|
-
self._later(self._started, conversation)
|
|
1002
|
+
self._later(self._started, conversation, generation)
|
|
858
1003
|
|
|
859
1004
|
self._background(load)
|
|
860
1005
|
|
|
@@ -868,24 +1013,56 @@ class Chat:
|
|
|
868
1013
|
def _continue(self, session, text=None, files=()):
|
|
869
1014
|
"""Go on with the ended session `session` in its own id (the host starts it again
|
|
870
1015
|
from what it kept), then send it `text`."""
|
|
1016
|
+
generation = self.generation
|
|
871
1017
|
conversation = self._host().resume_session(session)
|
|
872
1018
|
if text is not None:
|
|
873
1019
|
_message(conversation, text, files)
|
|
874
|
-
self._later(self.
|
|
1020
|
+
self._later(self._resumed, conversation, generation)
|
|
1021
|
+
|
|
1022
|
+
def _resumed(self, conversation, generation):
|
|
1023
|
+
if generation == self.generation:
|
|
1024
|
+
self._follow(conversation)
|
|
875
1025
|
|
|
876
1026
|
def _leave(self):
|
|
877
1027
|
"""No conversation shown (the one that was goes on)."""
|
|
878
1028
|
self.stop.set()
|
|
879
1029
|
self.generation += 1
|
|
1030
|
+
self.pending, self.starting = [], None
|
|
880
1031
|
self.conversation, self.status, self.ask, self.lanes = None, None, None, Lanes()
|
|
881
1032
|
self.learning = None
|
|
882
1033
|
self._reset()
|
|
883
|
-
|
|
884
|
-
from ..providers import load
|
|
1034
|
+
self._refresh_next_model()
|
|
885
1035
|
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
1036
|
+
def _refresh_next_model(self, *, rows=None, initial_name=None):
|
|
1037
|
+
"""Keep the explicit next route, including an invalid one, until /model replaces it."""
|
|
1038
|
+
problem, label = None, initial_name
|
|
1039
|
+
if self.model_entry is not None:
|
|
1040
|
+
if initial_name is None:
|
|
1041
|
+
try:
|
|
1042
|
+
if rows is None:
|
|
1043
|
+
from ..model_list import select
|
|
1044
|
+
|
|
1045
|
+
row = select(data(), self.model_entry)
|
|
1046
|
+
else:
|
|
1047
|
+
row = next((row for row in rows if row["enabled"] and row["id"] == self.model_entry), None)
|
|
1048
|
+
if row is None:
|
|
1049
|
+
raise ValueError("selected model is unavailable")
|
|
1050
|
+
label = row["name"]
|
|
1051
|
+
except (OSError, ValueError):
|
|
1052
|
+
self.model_effort = None
|
|
1053
|
+
label = "model unavailable · choose with /model"
|
|
1054
|
+
problem = "The selected model is unavailable. Choose with /model before starting a new conversation."
|
|
1055
|
+
else:
|
|
1056
|
+
try:
|
|
1057
|
+
from ..providers import load
|
|
1058
|
+
|
|
1059
|
+
label = load(data())["model"]
|
|
1060
|
+
except Exception:
|
|
1061
|
+
label = self.model
|
|
1062
|
+
self.next_model_label, self.next_model_problem = label, problem
|
|
1063
|
+
if self.conversation is None:
|
|
1064
|
+
self.model = label
|
|
1065
|
+
return problem is None
|
|
889
1066
|
|
|
890
1067
|
def do_exit(self, _):
|
|
891
1068
|
self.app.exit()
|
|
@@ -926,12 +1103,21 @@ class Chat:
|
|
|
926
1103
|
|
|
927
1104
|
def do_host(self, words):
|
|
928
1105
|
"""/host: how the session host runs; /host stop: end it, with what runs in it."""
|
|
1106
|
+
async def show():
|
|
1107
|
+
if str(words or "").strip() == "stop":
|
|
1108
|
+
await asyncio.to_thread(self._host_info, words)
|
|
1109
|
+
else:
|
|
1110
|
+
await self._request(self._host_info, words)
|
|
1111
|
+
|
|
1112
|
+
self.app.create_background_task(self._guarded(show))
|
|
1113
|
+
|
|
1114
|
+
def _host_info(self, words):
|
|
929
1115
|
host = self._host(start=False)
|
|
930
1116
|
if host is None:
|
|
931
1117
|
self.note("No session host runs (the next conversation starts it)")
|
|
932
1118
|
return
|
|
933
1119
|
if str(words or "").strip() == "stop":
|
|
934
|
-
self._leave
|
|
1120
|
+
self._later(self._leave)
|
|
935
1121
|
host.stop(force=True)
|
|
936
1122
|
self.host = None
|
|
937
1123
|
self.note(f"Stopped the session host at {host.url}")
|
|
@@ -946,12 +1132,14 @@ class Chat:
|
|
|
946
1132
|
from harness.runtime.decision.model import valid_effort
|
|
947
1133
|
|
|
948
1134
|
async def pick():
|
|
949
|
-
|
|
1135
|
+
conversation = self.conversation
|
|
1136
|
+
active = conversation is not None and self.status not in ENDED
|
|
950
1137
|
level = str(words or "").strip()
|
|
1138
|
+
if active and not level:
|
|
1139
|
+
self.note("Use /effort LEVEL or /effort default for the open conversation.")
|
|
1140
|
+
return
|
|
1141
|
+
row = None if active else select(data(), self.model_entry)
|
|
951
1142
|
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
1143
|
levels = [value for value in (row or {}).get("efforts", []) if value != "default"]
|
|
956
1144
|
option = await self._view(views.choose("Reasoning effort", ["Provider default", *levels]))
|
|
957
1145
|
if option is None:
|
|
@@ -960,8 +1148,8 @@ class Chat:
|
|
|
960
1148
|
effort = "" if level == "default" else level
|
|
961
1149
|
if not valid_effort(effort):
|
|
962
1150
|
raise ValueError("invalid reasoning effort ID")
|
|
963
|
-
if
|
|
964
|
-
self._background(lambda:
|
|
1151
|
+
if active:
|
|
1152
|
+
self._background(lambda: conversation.set_model(reasoning_effort=effort))
|
|
965
1153
|
elif row:
|
|
966
1154
|
if effort and effort not in row["efforts"]:
|
|
967
1155
|
raise ValueError("this model does not offer that reasoning effort")
|
|
@@ -990,23 +1178,26 @@ class Chat:
|
|
|
990
1178
|
self.note("/experiment NAME [TASK [SEED]] [-- instruction]", "red")
|
|
991
1179
|
return
|
|
992
1180
|
|
|
1181
|
+
generation = self.generation
|
|
1182
|
+
|
|
993
1183
|
def start():
|
|
994
1184
|
request = {"experiment": parts[0], "task": parts[1] if len(parts) > 1 else None,
|
|
995
1185
|
"seed": seed, "frontend": "terminal",
|
|
996
1186
|
**({"instruction": instruction.strip()} if instruction.strip() else {})}
|
|
997
1187
|
conversation = self._host().start(**request)
|
|
998
1188
|
self._later(self._print, Text(f"── experiment {parts[0]} " + "─" * 40, style="dim"))
|
|
999
|
-
self._later(self._started, conversation)
|
|
1189
|
+
self._later(self._started, conversation, generation)
|
|
1000
1190
|
|
|
1001
1191
|
self._background(start)
|
|
1002
1192
|
|
|
1003
1193
|
def do_sessions(self, _):
|
|
1004
1194
|
async def pick():
|
|
1005
|
-
host = self._host
|
|
1195
|
+
host = await self._request(self._host, False)
|
|
1006
1196
|
if host is None:
|
|
1007
1197
|
self.note("No session host runs: nothing is open")
|
|
1008
1198
|
return
|
|
1009
|
-
|
|
1199
|
+
sessions = await self._request(host.sessions)
|
|
1200
|
+
lines = table_rows([session.row for session in sessions])
|
|
1010
1201
|
if not lines:
|
|
1011
1202
|
self.note("No sessions run")
|
|
1012
1203
|
return
|
|
@@ -1016,14 +1207,14 @@ class Chat:
|
|
|
1016
1207
|
picked = await self._view(views.choose("Sessions that run", rows, current=current))
|
|
1017
1208
|
if picked is not None and lines[picked]["run"] != getattr(self.conversation, "run", None):
|
|
1018
1209
|
self._print(Text(f"── session {lines[picked]['run']} " + "─" * 40, style="dim"))
|
|
1019
|
-
self._follow(host.conversation
|
|
1210
|
+
self._follow(await self._request(host.conversation, lines[picked]["run"]))
|
|
1020
1211
|
|
|
1021
1212
|
self.app.create_background_task(self._guarded(pick))
|
|
1022
1213
|
|
|
1023
1214
|
def do_resume(self, _):
|
|
1024
1215
|
async def pick():
|
|
1025
|
-
host = self._host
|
|
1026
|
-
sessions = [session.row for session in host.sessions
|
|
1216
|
+
host = await self._request(self._host)
|
|
1217
|
+
sessions = [session.row for session in await self._request(host.sessions, all=True, limit=100)]
|
|
1027
1218
|
if not sessions:
|
|
1028
1219
|
self.note("No conversations yet")
|
|
1029
1220
|
return
|
|
@@ -1035,7 +1226,7 @@ class Chat:
|
|
|
1035
1226
|
row = sessions[picked]
|
|
1036
1227
|
self._print(Text(f"── {row.get('title') or row['id']} " + "─" * 40, style="dim"))
|
|
1037
1228
|
if row.get("status") in LIVE:
|
|
1038
|
-
self._follow(host.conversation
|
|
1229
|
+
self._follow(await self._request(host.conversation, row["run"]))
|
|
1039
1230
|
return
|
|
1040
1231
|
if row.get("kind", "harness") == "harness":
|
|
1041
1232
|
# It goes on in its own session: its messages and facts, a new kernel.
|
|
@@ -1057,8 +1248,11 @@ class Chat:
|
|
|
1057
1248
|
from ..providers import PROVIDERS
|
|
1058
1249
|
|
|
1059
1250
|
options = [row for row in models(data()) if row["enabled"]]
|
|
1060
|
-
|
|
1061
|
-
|
|
1251
|
+
try:
|
|
1252
|
+
current = select(data(), self.model_entry) if any(
|
|
1253
|
+
row["id"] == self.model_entry for row in options) else select(data())
|
|
1254
|
+
except ValueError:
|
|
1255
|
+
current = None # an invalid default must not prevent choosing a valid route
|
|
1062
1256
|
rows = [f"{row['name']} · {PROVIDERS[row['provider']].name if row['provider'] in PROVIDERS else row['provider']}"
|
|
1063
1257
|
+ (f" · {row['base_url']}" if row["base_url"] else "") for row in options]
|
|
1064
1258
|
picked = await self._view(views.choose("Model for new conversations", rows,
|
|
@@ -1067,16 +1261,49 @@ class Chat:
|
|
|
1067
1261
|
if picked is not None:
|
|
1068
1262
|
row = options[picked]
|
|
1069
1263
|
self.model_entry, self.model_effort = row["id"], None
|
|
1070
|
-
|
|
1071
|
-
self.model = row["name"]
|
|
1264
|
+
self._refresh_next_model(rows=options)
|
|
1072
1265
|
self.note(f"Model for new conversations: {rows[picked]}")
|
|
1073
1266
|
|
|
1074
1267
|
self.app.create_background_task(self._guarded(pick))
|
|
1075
1268
|
|
|
1269
|
+
async def _edit(self, path):
|
|
1270
|
+
"""`path` in the user's editor ($EDITOR; notepad on Windows, vi elsewhere), until it closes."""
|
|
1271
|
+
from shlex import split
|
|
1272
|
+
|
|
1273
|
+
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.")
|
|
1274
|
+
editor = os.environ.get("EDITOR") or ("notepad.exe" if os.name == "nt" else "vi")
|
|
1275
|
+
command = [editor] if os.path.isfile(editor) else split(editor, posix=os.name != "nt")
|
|
1276
|
+
async with in_terminal():
|
|
1277
|
+
result = await asyncio.to_thread(subprocess.run, [*command, str(path)], check=False)
|
|
1278
|
+
if result.returncode:
|
|
1279
|
+
raise ValueError(f"the editor exited with code {result.returncode}")
|
|
1280
|
+
|
|
1281
|
+
def do_instructions(self, words):
|
|
1282
|
+
"""The instruction files this conversation read (instructions.py); N opens that one."""
|
|
1283
|
+
files = getattr(self, "instruction_files", None) or []
|
|
1284
|
+
if not files:
|
|
1285
|
+
self.note("This conversation read no instruction files. It reads ~/.harness/AGENTS.md and the "
|
|
1286
|
+
"project's AGENTS.md (or CLAUDE.md) from its root down to its folder; instructions.load in "
|
|
1287
|
+
"/settings says which.")
|
|
1288
|
+
return
|
|
1289
|
+
if words.strip().isdigit() and 1 <= int(words) <= len(files):
|
|
1290
|
+
path = files[int(words) - 1][1]
|
|
1291
|
+
self.app.create_background_task(self._guarded(lambda: self._edit(path)))
|
|
1292
|
+
return
|
|
1293
|
+
self._print(*[Text.assemble((f" {number} {label}".ljust(36), "bold"), (path, "dim"))
|
|
1294
|
+
for number, (label, path) in enumerate(files, 1)],
|
|
1295
|
+
Text("/instructions N opens one in your editor; a new conversation reads them again.", style="dim"))
|
|
1296
|
+
|
|
1297
|
+
def do_init(self, _):
|
|
1298
|
+
"""Have the agent write the project's AGENTS.md (Claude Code's and Codex's /init)."""
|
|
1299
|
+
self.send("Write an AGENTS.md at the root of this project for the agents that work in it: how to set it "
|
|
1300
|
+
"up, build, test and lint it, how the code is laid out, its conventions, and what to check "
|
|
1301
|
+
"before a change is done. Read the project first, and keep it short and specific to it. If an "
|
|
1302
|
+
"AGENTS.md or a CLAUDE.md is there already, do not replace it: tell me what you would change "
|
|
1303
|
+
"and why, and change it only when I agree.")
|
|
1304
|
+
|
|
1076
1305
|
def do_models(self, _):
|
|
1077
1306
|
async def edit():
|
|
1078
|
-
from shlex import split
|
|
1079
|
-
|
|
1080
1307
|
from ..model_list import models
|
|
1081
1308
|
|
|
1082
1309
|
path = data() / "models.json"
|
|
@@ -1084,16 +1311,13 @@ class Chat:
|
|
|
1084
1311
|
models(data()) # writes the list when there is none yet
|
|
1085
1312
|
except ValueError:
|
|
1086
1313
|
pass # one saved with a mistake opens as it is, to be put right
|
|
1087
|
-
|
|
1088
|
-
command = [editor] if os.path.isfile(editor) else split(editor, posix=os.name != "nt")
|
|
1089
|
-
async with in_terminal():
|
|
1090
|
-
result = await asyncio.to_thread(subprocess.run, [*command, str(path)], check=False)
|
|
1091
|
-
if result.returncode:
|
|
1092
|
-
raise ValueError(f"the editor exited with code {result.returncode}")
|
|
1314
|
+
await self._edit(path)
|
|
1093
1315
|
try:
|
|
1094
1316
|
rows = models(data())
|
|
1095
1317
|
except ValueError as error:
|
|
1096
1318
|
raise ValueError(f"{error}; /models opens it again to correct it") from None
|
|
1319
|
+
if not self._refresh_next_model(rows=rows):
|
|
1320
|
+
self.note(self.next_model_problem, "yellow")
|
|
1097
1321
|
count = sum(row["enabled"] for row in rows)
|
|
1098
1322
|
self.note(f"{count} enabled models · /model to select · {path}")
|
|
1099
1323
|
|
|
@@ -1108,7 +1332,7 @@ class Chat:
|
|
|
1108
1332
|
|
|
1109
1333
|
def do_packages(self, _):
|
|
1110
1334
|
async def edit():
|
|
1111
|
-
for line in await self._view(views.packages_view()):
|
|
1335
|
+
for line in await self._view(views.packages_view(await self._request(self._host))):
|
|
1112
1336
|
self.note(line)
|
|
1113
1337
|
|
|
1114
1338
|
self.app.create_background_task(self._guarded(edit))
|
|
@@ -1122,10 +1346,29 @@ class Chat:
|
|
|
1122
1346
|
(lambda: rows(run=conversation.directory)) if conversation is not None else None)
|
|
1123
1347
|
self.app.create_background_task(self._guarded(lambda: self._view(views.library_view(memory))))
|
|
1124
1348
|
|
|
1349
|
+
async def _request(self, function, *args, **kwargs):
|
|
1350
|
+
"""A host read may finish after cancellation, but never applies its abandoned result."""
|
|
1351
|
+
task, generation = asyncio.current_task(), self.generation
|
|
1352
|
+
self.waiting = task
|
|
1353
|
+
self.app.invalidate()
|
|
1354
|
+
try:
|
|
1355
|
+
result = await asyncio.to_thread(function, *args, **kwargs)
|
|
1356
|
+
if generation != self.generation:
|
|
1357
|
+
raise asyncio.CancelledError
|
|
1358
|
+
return result
|
|
1359
|
+
finally:
|
|
1360
|
+
if self.waiting is task:
|
|
1361
|
+
self.waiting = None
|
|
1362
|
+
self.app.invalidate()
|
|
1363
|
+
|
|
1125
1364
|
async def _guarded(self, function):
|
|
1126
1365
|
try:
|
|
1127
1366
|
await function()
|
|
1367
|
+
except asyncio.CancelledError:
|
|
1368
|
+
self.note("Stopped waiting for the host.")
|
|
1128
1369
|
except Exception as error:
|
|
1370
|
+
if isinstance(error, (HostGone, OSError)):
|
|
1371
|
+
self.host = None
|
|
1129
1372
|
self.note(f"({error})", "red")
|
|
1130
1373
|
|
|
1131
1374
|
|