@lmmslab/harness 0.0.0-stage → 0.81.1

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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -2
  3. package/bin/harness.js +71 -0
  4. package/package.json +34 -4
  5. package/python/harness/README.md +72 -0
  6. package/python/harness/__init__.py +8 -0
  7. package/python/harness/__main__.py +3 -0
  8. package/python/harness/bench.py +124 -0
  9. package/python/harness/builtin/benches/README.md +5 -0
  10. package/python/harness/builtin/benches/none/bench.toml +6 -0
  11. package/python/harness/builtin/configs/README.md +26 -0
  12. package/python/harness/builtin/configs/assistant.toml +11 -0
  13. package/python/harness/builtin/configs/default.toml +33 -0
  14. package/python/harness/builtin/configs/deploy/example-api.toml +10 -0
  15. package/python/harness/builtin/configs/models/deepseek-api.toml +21 -0
  16. package/python/harness/builtin/configs/models/deepseek-flash.toml +12 -0
  17. package/python/harness/builtin/configs/models/grok-low.toml +8 -0
  18. package/python/harness/builtin/configs/models/grok-medium.toml +43 -0
  19. package/python/harness/builtin/configs/models/opus-5.5.toml +11 -0
  20. package/python/harness/builtin/environment/README.md +53 -0
  21. package/python/harness/builtin/environment/constraints.txt +31 -0
  22. package/python/harness/builtin/model-settings.js +143 -0
  23. package/python/harness/builtin/prompts/conversation/core.md +5 -0
  24. package/python/harness/builtin/prompts/conversation/pack.toml +12 -0
  25. package/python/harness/builtin/prompts/core/core.md +88 -0
  26. package/python/harness/builtin/prompts/core/pack.toml +9 -0
  27. package/python/harness/builtin/prompts/reflect/core.md +45 -0
  28. package/python/harness/builtin/prompts/reflect/pack.toml +7 -0
  29. package/python/harness/builtin/prompts/shared/agent-skills.md +5 -0
  30. package/python/harness/builtin/prompts/shared/agents.md +14 -0
  31. package/python/harness/builtin/prompts/shared/checklist.md +21 -0
  32. package/python/harness/builtin/prompts/shared/entries.md +86 -0
  33. package/python/harness/builtin/prompts/shared/environments.md +21 -0
  34. package/python/harness/builtin/prompts/shared/learning-goal.md +31 -0
  35. package/python/harness/builtin/prompts/shared/learning.md +27 -0
  36. package/python/harness/builtin/prompts/shared/mcp.md +9 -0
  37. package/python/harness/builtin/prompts/shared/world.md +1 -0
  38. package/python/harness/builtin/skills/README.md +10 -0
  39. package/python/harness/builtin/skills/agents/__init__.py +88 -0
  40. package/python/harness/builtin/skills/agents/skill.toml +11 -0
  41. package/python/harness/builtin/skills/checklist/__init__.py +32 -0
  42. package/python/harness/builtin/skills/checklist/skill.toml +9 -0
  43. package/python/harness/builtin/skills/conversation/__init__.py +23 -0
  44. package/python/harness/builtin/skills/conversation/skill.toml +8 -0
  45. package/python/harness/builtin/skills/entries/__init__.py +62 -0
  46. package/python/harness/builtin/skills/entries/skill.toml +8 -0
  47. package/python/harness/builtin/skills/environments/__init__.py +69 -0
  48. package/python/harness/builtin/skills/environments/skill.toml +9 -0
  49. package/python/harness/builtin/skills/experience/__init__.py +27 -0
  50. package/python/harness/builtin/skills/experience/skill.toml +9 -0
  51. package/python/harness/builtin/skills/instructions/__init__.py +29 -0
  52. package/python/harness/builtin/skills/instructions/skill.toml +9 -0
  53. package/python/harness/builtin/skills/learning/__init__.py +189 -0
  54. package/python/harness/builtin/skills/learning/skill.toml +7 -0
  55. package/python/harness/builtin/skills/mcp/__init__.py +54 -0
  56. package/python/harness/builtin/skills/mcp/skill.toml +10 -0
  57. package/python/harness/builtin/skills/memory/__init__.py +130 -0
  58. package/python/harness/builtin/skills/memory/skill.toml +13 -0
  59. package/python/harness/builtin/skills/verify/__init__.py +31 -0
  60. package/python/harness/builtin/skills/verify/skill.toml +7 -0
  61. package/python/harness/builtin/third_party/sources.toml +40 -0
  62. package/python/harness/cli.py +1182 -0
  63. package/python/harness/config/__init__.py +224 -0
  64. package/python/harness/config/agent.py +777 -0
  65. package/python/harness/core/__init__.py +52 -0
  66. package/python/harness/core/artifacts.py +46 -0
  67. package/python/harness/core/codec.py +160 -0
  68. package/python/harness/core/contracts.py +75 -0
  69. package/python/harness/core/episodes.py +150 -0
  70. package/python/harness/core/format.py +51 -0
  71. package/python/harness/core/http.py +124 -0
  72. package/python/harness/core/lanes.py +324 -0
  73. package/python/harness/core/linux_sandbox.py +55 -0
  74. package/python/harness/core/media.py +96 -0
  75. package/python/harness/core/memory.py +147 -0
  76. package/python/harness/core/ports.py +63 -0
  77. package/python/harness/core/procs.py +227 -0
  78. package/python/harness/core/remote.py +102 -0
  79. package/python/harness/core/spans.py +166 -0
  80. package/python/harness/core/trace.py +139 -0
  81. package/python/harness/core/wait.py +12 -0
  82. package/python/harness/core/worker.py +388 -0
  83. package/python/harness/core/worker_pipe.py +119 -0
  84. package/python/harness/embodiments.py +217 -0
  85. package/python/harness/extensions.py +112 -0
  86. package/python/harness/host/__init__.py +397 -0
  87. package/python/harness/host/client.py +201 -0
  88. package/python/harness/host/http.py +720 -0
  89. package/python/harness/host/listing.py +68 -0
  90. package/python/harness/host/server.py +189 -0
  91. package/python/harness/host/sessions.py +406 -0
  92. package/python/harness/host/tasks.py +1356 -0
  93. package/python/harness/host/workers.py +257 -0
  94. package/python/harness/host/workspaces.py +256 -0
  95. package/python/harness/model_list.py +117 -0
  96. package/python/harness/packages/__init__.py +73 -0
  97. package/python/harness/packages/addons.py +121 -0
  98. package/python/harness/packages/archive.py +122 -0
  99. package/python/harness/packages/describe.py +46 -0
  100. package/python/harness/packages/environments.py +448 -0
  101. package/python/harness/packages/fetch.py +57 -0
  102. package/python/harness/packages/manager.py +587 -0
  103. package/python/harness/packages/manifest.py +232 -0
  104. package/python/harness/packages/migrate.py +68 -0
  105. package/python/harness/packages/provision.py +38 -0
  106. package/python/harness/packages/registry.py +275 -0
  107. package/python/harness/packages/resolve.py +89 -0
  108. package/python/harness/packages/sources.py +141 -0
  109. package/python/harness/packages/state.py +213 -0
  110. package/python/harness/packages/versions.py +112 -0
  111. package/python/harness/paths.py +218 -0
  112. package/python/harness/providers.py +303 -0
  113. package/python/harness/runtime/__init__.py +8 -0
  114. package/python/harness/runtime/decision/__init__.py +1 -0
  115. package/python/harness/runtime/decision/loop.py +198 -0
  116. package/python/harness/runtime/decision/messages.py +271 -0
  117. package/python/harness/runtime/decision/model.py +424 -0
  118. package/python/harness/runtime/decision/prompts.py +248 -0
  119. package/python/harness/runtime/decision/protocol.py +169 -0
  120. package/python/harness/runtime/decision/thoughts.py +199 -0
  121. package/python/harness/runtime/events.py +213 -0
  122. package/python/harness/runtime/execution/__init__.py +1 -0
  123. package/python/harness/runtime/execution/attached.py +96 -0
  124. package/python/harness/runtime/execution/control.py +211 -0
  125. package/python/harness/runtime/execution/entries.py +665 -0
  126. package/python/harness/runtime/execution/kernel.py +811 -0
  127. package/python/harness/runtime/execution/noenv.py +84 -0
  128. package/python/harness/runtime/execution/results.py +40 -0
  129. package/python/harness/runtime/execution/session.py +871 -0
  130. package/python/harness/runtime/execution/skills.py +436 -0
  131. package/python/harness/runtime/learning/__init__.py +1 -0
  132. package/python/harness/runtime/learning/active.py +314 -0
  133. package/python/harness/runtime/learning/experience.py +48 -0
  134. package/python/harness/runtime/learning/fixtures.py +167 -0
  135. package/python/harness/runtime/learning/learner.py +651 -0
  136. package/python/harness/runtime/learning/library.py +504 -0
  137. package/python/harness/runtime/learning/reflect.py +151 -0
  138. package/python/harness/runtime/learning/usage.py +30 -0
  139. package/python/harness/runtime/learning/views.py +89 -0
  140. package/python/harness/runtime/reactive/__init__.py +1 -0
  141. package/python/harness/runtime/reactive/rules.py +549 -0
  142. package/python/harness/runtime/safety/__init__.py +1 -0
  143. package/python/harness/runtime/safety/approval.py +131 -0
  144. package/python/harness/runtime/safety/input.py +62 -0
  145. package/python/harness/runtime/safety/isolation.py +419 -0
  146. package/python/harness/runtime/safety/shield.py +129 -0
  147. package/python/harness/runtime/status.py +23 -0
  148. package/python/harness/runtime/task/__init__.py +7 -0
  149. package/python/harness/runtime/task/context.py +431 -0
  150. package/python/harness/runtime/task/delegation.py +468 -0
  151. package/python/harness/runtime/task/environments.py +268 -0
  152. package/python/harness/runtime/task/run.py +2878 -0
  153. package/python/harness/runtime/tick.py +909 -0
  154. package/python/harness/sdk/__init__.py +281 -0
  155. package/python/harness/services/__init__.py +6 -0
  156. package/python/harness/services/broker.py +35 -0
  157. package/python/harness/services/connectors.py +88 -0
  158. package/python/harness/services/mcp.py +298 -0
  159. package/python/harness/services/mcp_stdio.py +131 -0
  160. package/python/harness/services/placement.py +82 -0
  161. package/python/harness/services/registry.py +156 -0
  162. package/python/harness/settings.py +536 -0
  163. package/python/harness/terminal.py +79 -0
  164. package/python/harness/transcript.py +297 -0
  165. package/python/harness/tui/__init__.py +68 -0
  166. package/python/harness/tui/chat.py +1181 -0
  167. package/python/harness/tui/pty.py +81 -0
  168. package/python/harness/tui/renderer.py +45 -0
  169. package/python/harness/tui/timeline_rows.py +58 -0
  170. package/python/harness/tui/views.py +434 -0
@@ -0,0 +1,1181 @@
1
+ """The terminal chat: the conversation printed into the terminal's scrollback (rich), a live
2
+ region under it (prompt_toolkit): an approval's choices when one waits, the input box, one
3
+ status line. Keys as in the coding agents' terminals: Enter sends, Shift+Enter or Ctrl+J
4
+ is a new line, Up and Down the history, Ctrl+R searches it, Tab completes (/ commands,
5
+ @ files), Esc interrupts the agent (Esc Esc clears the input), Ctrl+C interrupts or
6
+ clears and twice leaves, Ctrl+D twice leaves, Ctrl+O shows a program's code and output,
7
+ Ctrl+T the timeline, ? the keys. !command runs a command here and gives the agent its
8
+ output; !!command only runs it.
9
+
10
+ Nothing starts until the first message: then `start(text, files, log)` gives the host and a
11
+ conversation of the app's agent. A message while the agent works reaches it at once."""
12
+
13
+ import asyncio
14
+ import io
15
+ import json
16
+ import locale
17
+ import os
18
+ from pathlib import Path
19
+ from ..settings import ChoiceRequired
20
+ import re
21
+ import subprocess
22
+ import sys
23
+ import threading
24
+ import time
25
+
26
+ from prompt_toolkit.application import Application, in_terminal
27
+ from prompt_toolkit.buffer import Buffer
28
+ from prompt_toolkit.completion import Completer, Completion, PathCompleter
29
+ from prompt_toolkit.document import Document
30
+ from prompt_toolkit.filters import Condition, has_completions
31
+ from prompt_toolkit.history import FileHistory
32
+ from prompt_toolkit.input import ansi_escape_sequences, create_input
33
+ from prompt_toolkit.key_binding import KeyBindings
34
+ from prompt_toolkit.keys import Keys
35
+ from prompt_toolkit.layout import ConditionalContainer, HSplit, Layout, ScrollOffsets, VSplit, Window, WindowAlign
36
+ from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
37
+ from prompt_toolkit.layout.menus import CompletionsMenuControl
38
+ from prompt_toolkit.layout.processors import Processor, Transformation
39
+ from prompt_toolkit.patch_stdout import patch_stdout
40
+ from prompt_toolkit.styles import Style
41
+ from prompt_toolkit.widgets import SearchToolbar
42
+ from rich.console import Console
43
+ from rich.markdown import Markdown
44
+ from rich.syntax import Syntax
45
+ from rich.text import Text
46
+
47
+ from .. import transcript
48
+ from ..core import format as formats
49
+ from harness.runtime.safety.approval import say
50
+ from ..core.lanes import Lanes
51
+ from ..host.sessions import ENDED, LIVE, table_rows, word
52
+ from ..paths import data
53
+ from harness.runtime.learning.active import progress_line
54
+ from ..terminal import COMMANDS, command, item_lines
55
+ from . import views
56
+
57
+ # Shift+Enter where the terminal tells it from Enter: as Ctrl+J, a new line.
58
+ for _sequence in ("\x1b[13;2u", "\x1b[27;2;13~"):
59
+ ansi_escape_sequences.ANSI_SEQUENCES[_sequence] = Keys.ControlJ
60
+
61
+ KEYS = [("Enter", "send"), ("Shift+Enter, Ctrl+J", "new line"), ("↑ ↓", "history"), ("Ctrl+R", "search the history"),
62
+ ("Tab", "complete"), ("/", "commands"), ("@", "attach a file"), ("!cmd", "run it, give the agent its output"),
63
+ ("!!cmd", "run it only"), ("Esc", "interrupt the agent"), ("Esc Esc", "clear the input"),
64
+ ("Ctrl+C", "interrupt; clear; twice: leave"), ("Ctrl+D twice", "leave"), ("Ctrl+O", "program details"),
65
+ ("Ctrl+T", "timeline"), ("?", "these keys")]
66
+ STYLE = Style.from_dict({"rule": "#585858", "status": "#8a8a8a", "status.state": "bold", "status.busy": "bold #5fafff",
67
+ "status.wait": "bold #ffaf00", "status.hint": "#6c6c6c", "placeholder": "#6c6c6c",
68
+ "ask": "bold #ffaf00", "ask.selected": "bold reverse", "help": "#8a8a8a", "help.key": "bold",
69
+ "completion-menu": "bg:#262626 #bcbcbc", "completion-menu.completion.current": "bg:#444444 #ffffff bold",
70
+ "completion-menu.meta.completion": "bg:#262626 #808080",
71
+ "completion-menu.meta.completion.current": "bg:#444444 #bcbcbc"})
72
+ # Rich styles of the roles of transcript items (transcript.items).
73
+ ROLES = {"task": "bold", "you": "bold", "call": "dim", "thinking": "dim italic", "code": "#5f87ff", "skill": "magenta",
74
+ "result": "green", "verifier": "cyan", "note": "yellow", "turn": "dim", "outcome": "bold green", "end": "bold",
75
+ "error": "red", "entry": "green", "output": "dim"}
76
+ # A sub-agent's colour, by its name.
77
+ AGENT_COLOURS = ("magenta", "cyan", "green", "yellow", "bright_blue", "bright_magenta")
78
+ # Items of a program (its steps, entries, output): shown with Ctrl+O.
79
+ DETAILS = {"skill", "skill_step", "entry_start", "entry_claims", "entry_end", "skill_failed", "result", "output",
80
+ "cell_error", "unhandled"}
81
+ # Items of the timeline (transcript.items with timeline) the chat leaves out: its calls and
82
+ # their usage, how the run ended inside.
83
+ TIMELINE = {"call", "usage", "call_set_aside", "context_shortened", "malformed_dropped", "library_loaded",
84
+ "policy_to_end", "wrap_up", "cleanup_error"}
85
+ SPINNER = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
86
+ # Seconds within which a second Ctrl+C, Ctrl+D or Esc counts.
87
+ TWICE = 1.0
88
+ FILE = re.compile(r'@"([^"]+)"|@(\S+)')
89
+
90
+
91
+ class Chat:
92
+ """One terminal chat; run() returns once the user leaves."""
93
+
94
+ def __init__(self, conversation=None, records=None, *, host=None, start=None):
95
+ self.conversation, self.records, self.host, self.start = conversation, records, host, start
96
+ self.status = None # the conversation's last status; "starting" while it is created
97
+ self.generation = 0
98
+ self.stop = threading.Event()
99
+ self.pending = [] # messages typed while the conversation was created
100
+ self.details_open = False
101
+ self.details_output = []
102
+ self.help = False
103
+ self.ask = None # what waits for the user's approval: {text, options, at, reason}
104
+ self.echoed = None # the first message of a conversation started here, printed at once
105
+ self.interrupted = False # asked to pause, not paused yet
106
+ self.starting = None # what starting the first message's conversation says now
107
+ self.armed = {} # key: when it was last pressed (twice to leave, Esc Esc)
108
+ self.spent, self.model, self.workspace = 0.0, None, None
109
+ self.model_entry = self.model_effort = None
110
+ self.environment = None # (kind, folder) picked with /environment for the next conversation
111
+ self.agents_on = False # /agents before a conversation starts: on in the next one
112
+ self.learning = None # where a conversation that learns its environment stands (runtime/learning/active.py progress())
113
+ self.lanes = Lanes()
114
+ self._reset()
115
+ try:
116
+ from ..providers import load
117
+
118
+ self.model = load(data())["model"]
119
+ except Exception:
120
+ pass
121
+ # sys.stdout when it prints: patch_stdout's, above the live region.
122
+ self.console = Console(force_terminal=True, legacy_windows=False, highlight=False, soft_wrap=False,
123
+ color_system="truecolor" if os.environ.get("WT_SESSION") or os.environ.get("COLORTERM")
124
+ in ("truecolor", "24bit") else "256")
125
+ self.buffer = Buffer(multiline=True, history=FileHistory(str(_history_file())), completer=Completions(),
126
+ complete_while_typing=True)
127
+ self.app = self._application()
128
+
129
+ # The live region.
130
+
131
+ def _application(self) -> Application:
132
+ search = SearchToolbar(text_if_not_searching="", ignore_case=True)
133
+ prompt = lambda line, wrap: [("class:rule", "› " if line == 0 and not wrap else " ")] # noqa: E731
134
+ field = Window(BufferControl(self.buffer, search_buffer_control=search.control, preview_search=True,
135
+ input_processors=[Placeholder(self)]),
136
+ height=lambda: min(max(self.buffer.document.line_count, 1), 12), wrap_lines=True,
137
+ get_line_prefix=prompt, dont_extend_height=True)
138
+ rule = Window(height=1, char="─", style="class:rule")
139
+ # The completions under the input, as many lines as there are (at most 8).
140
+ menu = ConditionalContainer(Window(CompletionsMenuControl(), height=lambda: min(len(
141
+ self.buffer.complete_state.completions), 8) if self.buffer.complete_state else 1, scroll_offsets=ScrollOffsets(1, 1),
142
+ dont_extend_width=True, style="class:completion-menu"), has_completions)
143
+ status = VSplit([Window(FormattedTextControl(self._status), height=1),
144
+ Window(FormattedTextControl(self._hint), height=1, align=WindowAlign.RIGHT)])
145
+ body = HSplit([ConditionalContainer(Window(FormattedTextControl(self._asking), dont_extend_height=True),
146
+ Condition(lambda: self.ask is not None)),
147
+ rule, field, search, rule, menu, status,
148
+ ConditionalContainer(Window(FormattedTextControl(self._keys), dont_extend_height=True),
149
+ Condition(lambda: self.help))])
150
+ app = Application(Layout(body, focused_element=field), key_bindings=self._keys_bound(), style=STYLE,
151
+ full_screen=False, refresh_interval=0.25, input=_input(), erase_when_done=True)
152
+ if sys.platform == "win32" and hasattr(app.output, "get_win32_screen_buffer_info"):
153
+ from .renderer import WindowsInlineRenderer
154
+
155
+ app.renderer = WindowsInlineRenderer(app.renderer.style, app.output,
156
+ cpr_not_supported_callback=app.cpr_not_supported_callback)
157
+ app.timeoutlen, app.ttimeoutlen = 0.3, 0.05
158
+ return app
159
+
160
+ def _status(self):
161
+ status = self.status
162
+ if status == "starting":
163
+ state = ("class:status.busy", f"{SPINNER[int(time.time() * 8) % len(SPINNER)]} {self.starting or 'starting'}")
164
+ elif status == "RUNNING":
165
+ state = ("class:status.busy", f"{SPINNER[int(time.time() * 8) % len(SPINNER)]} working")
166
+ elif status == "WAITING_FOR_CONFIRMATION" or self.ask is not None:
167
+ state = ("class:status.wait", "● waits for you")
168
+ elif status is None:
169
+ state = ("class:status.state", "○ new conversation")
170
+ else:
171
+ state = ("class:status.state", "● " + word(status))
172
+ # Learning the environment first: the line is cut at the terminal's width.
173
+ parts = [progress_line(self.learning, short=True) if self.learning else None, self.model,
174
+ formats.cost(self.spent) if self.spent else None,
175
+ self.workspace or (self.environment[0] if self.environment and self.conversation is None else None),
176
+ f"session {self.session}" if self.session else None]
177
+ return [state] + [("class:status", " · " + part) for part in parts if part]
178
+
179
+ def _hint(self):
180
+ if self.armed.get("leave") and time.time() - self.armed["leave"][1] < TWICE:
181
+ return [("class:status.wait", f"{self.armed['leave'][0]} again to leave ")]
182
+ if self.status == "RUNNING":
183
+ return [("class:status.hint", "esc interrupt · type to steer ")]
184
+ return [("class:status.hint", "? keys · / commands ")]
185
+
186
+ def _asking(self):
187
+ ask = self.ask
188
+ out = [("class:ask", f"{ask['text']}\n")]
189
+ if ask.get("reason"):
190
+ return out + [("class:status.hint", f" {say('answer.why')}: type it below, Enter sends, Esc goes back\n")]
191
+ for number, (_, words) in enumerate(ask["options"], 1):
192
+ selected = number - 1 == ask["at"]
193
+ out.append(("class:ask.selected" if selected else "", f"{'❯' if selected else ' '} {number}. {words}"))
194
+ out.append(("", "\n"))
195
+ return out
196
+
197
+ def _keys(self):
198
+ out = []
199
+ for index, (key, what) in enumerate(KEYS):
200
+ out += [("class:help.key", f" {key:<22}"), ("class:help", f"{what:<34}"), ("", "\n" if index % 2 else "")]
201
+ return out
202
+
203
+ @property
204
+ def session(self):
205
+ return getattr(self.conversation, "session", None)
206
+
207
+ def _keys_bound(self) -> KeyBindings:
208
+ keys = KeyBindings()
209
+ idle = Condition(lambda: self.status != "RUNNING" or self.conversation is None)
210
+ empty = Condition(lambda: not self.buffer.text)
211
+ choosing = Condition(lambda: self.ask is not None and not self.ask.get("reason") and not self.buffer.text)
212
+ buffer = self.buffer
213
+
214
+ @keys.add("enter", filter=choosing)
215
+ def _(event):
216
+ self._answer(self.ask["at"])
217
+
218
+ for digit in "123456789":
219
+ @keys.add(digit, filter=choosing)
220
+ def _(event, digit=digit):
221
+ if int(digit) <= len(self.ask["options"]):
222
+ self._answer(int(digit) - 1)
223
+
224
+ @keys.add("up", filter=choosing)
225
+ def _(event):
226
+ self.ask["at"] = max(self.ask["at"] - 1, 0)
227
+
228
+ @keys.add("down", filter=choosing)
229
+ def _(event):
230
+ self.ask["at"] = min(self.ask["at"] + 1, len(self.ask["options"]) - 1)
231
+
232
+ @keys.add("enter", filter=~choosing)
233
+ def _(event):
234
+ state = buffer.complete_state
235
+ slash = buffer.text.startswith("/") and " " not in buffer.text
236
+ if state and state.completions and (state.current_completion or slash):
237
+ # A completion picked (or the first command): taken; Enter sends once nothing changes.
238
+ before = buffer.text
239
+ buffer.apply_completion(state.current_completion or state.completions[0])
240
+ found = COMMANDS.get(buffer.text[1:]) if slash else None
241
+ if found is not None and found.words:
242
+ buffer.insert_text(" ")
243
+ return
244
+ if not slash and buffer.text != before:
245
+ return
246
+ if buffer.document.text_before_cursor.endswith("\\"):
247
+ buffer.delete_before_cursor()
248
+ buffer.newline(copy_margin=False)
249
+ return
250
+ text = buffer.text
251
+ if text.strip():
252
+ buffer.append_to_history()
253
+ buffer.reset()
254
+ self.submit(text)
255
+
256
+ @keys.add("c-j")
257
+ @keys.add("escape", "enter")
258
+ def _(event):
259
+ buffer.newline(copy_margin=False)
260
+
261
+ @keys.add("escape")
262
+ def _(event):
263
+ if buffer.complete_state:
264
+ buffer.cancel_completion()
265
+ elif self.ask is not None and self.ask.get("reason"):
266
+ self.ask["reason"] = False
267
+ elif self.help:
268
+ self.help = False
269
+ elif not idle():
270
+ self.interrupt()
271
+ elif self._twice("escape") and buffer.text:
272
+ buffer.append_to_history()
273
+ buffer.reset()
274
+
275
+ @keys.add("c-c")
276
+ def _(event):
277
+ if not idle():
278
+ self.interrupt()
279
+ elif self._twice("c-c"):
280
+ event.app.exit()
281
+ else:
282
+ buffer.reset()
283
+ self.armed["leave"] = ("Ctrl+C", time.time())
284
+
285
+ @keys.add("c-d", filter=empty)
286
+ def _(event):
287
+ if self._twice("c-d"):
288
+ event.app.exit()
289
+ else:
290
+ self.armed["leave"] = ("Ctrl+D", time.time())
291
+
292
+ @keys.add("c-o")
293
+ def _(event):
294
+ program = self.program or self.last_program
295
+ if program is not None:
296
+ event.app.create_background_task(self._show_details(program))
297
+
298
+ @keys.add("c-t")
299
+ def _(event):
300
+ event.app.create_background_task(self._view(views.timeline_view(self.lanes)))
301
+
302
+ @keys.add("?", filter=empty)
303
+ def _(event):
304
+ self.help = not self.help
305
+
306
+ return keys
307
+
308
+ def _twice(self, key) -> bool:
309
+ """Whether `key` was pressed within TWICE seconds before (then it no longer counts)."""
310
+ now, before = time.time(), self.armed.get(key)
311
+ self.armed[key] = None if before and now - before < TWICE else now
312
+ return bool(before and now - before < TWICE)
313
+
314
+ async def _view(self, coroutine):
315
+ """A full-screen view over the chat; what it returns."""
316
+ async with in_terminal(render_cli_done=False):
317
+ return await coroutine
318
+
319
+ def run(self):
320
+ """Until the user leaves; returns the conversation shown then (None: none)."""
321
+ self._banner()
322
+ with patch_stdout(raw=True):
323
+ self.app.run(pre_run=lambda: self._follow(self.conversation, self.records)
324
+ if self.conversation is not None else self._open_environment())
325
+ self.stop.set()
326
+ return self.conversation
327
+
328
+ def _banner(self):
329
+ from .. import __version__
330
+
331
+ here = os.getcwd().replace(os.path.expanduser("~"), "~", 1)
332
+ self.console.print(Text.assemble(("The Harness", "bold"), f" {__version__} ", (here, "dim")))
333
+ self.console.print(Text("Tell it what to do. / for commands, @ to attach a file, ! to run a command, ? for keys.",
334
+ style="dim"))
335
+
336
+ # Printing into the scrollback (patch_stdout carries it above the live region).
337
+
338
+ def _print(self, *renderables):
339
+ if self.details_open:
340
+ self.details_output.extend(renderables)
341
+ return
342
+ try:
343
+ self.console.width = self.app.output.get_size().columns
344
+ except Exception:
345
+ pass
346
+ for renderable in renderables:
347
+ self.console.print(renderable)
348
+
349
+ def note(self, text, style="dim"):
350
+ self._later(self._print, Text(str(text), style=style))
351
+
352
+ def _later(self, function, *args):
353
+ """`function` on the chat's own thread (the event loop), from any thread."""
354
+ loop = getattr(self.app, "loop", None)
355
+ if loop is not None and self.app.is_running:
356
+ loop.call_soon_threadsafe(function, *args)
357
+ else:
358
+ function(*args)
359
+
360
+ def _background(self, function, *args):
361
+ """`function` on a thread of its own (the host's calls block); an error is noted."""
362
+ def run():
363
+ try:
364
+ function(*args)
365
+ except Exception as error:
366
+ self.note(f"({error})", "red")
367
+
368
+ threading.Thread(target=run, daemon=True).start()
369
+
370
+ # The conversation's records.
371
+
372
+ def _reset(self):
373
+ self.names, self.program, self.last_program, self.programs, self.said = {}, None, None, 0, None
374
+
375
+ def _follow(self, conversation, records=None):
376
+ """Show `conversation` from its first record (or `records`, a local one's), in place of
377
+ any other (that goes on)."""
378
+ self.stop.set()
379
+ self.stop, self.generation = threading.Event(), self.generation + 1
380
+ self.conversation, self.ask, self.spent, self.lanes = conversation, None, 0.0, Lanes()
381
+ self.learning, self.workspace = None, None
382
+ self.status = getattr(conversation, "status", None)
383
+ self._reset()
384
+ generation, stop = self.generation, self.stop
385
+
386
+ def read():
387
+ try:
388
+ if hasattr(conversation, "describe"):
389
+ conversation.describe()
390
+ agent = conversation.agent or {}
391
+ self.model, self.workspace = agent.get("model") or self.model, agent.get("workspace")
392
+ except Exception:
393
+ pass
394
+ try:
395
+ for record in records if records is not None else conversation.records(stop=stop):
396
+ if generation != self.generation:
397
+ return
398
+ self._later(self.show, record, generation)
399
+ except Exception as error:
400
+ self.note(f"(the conversation cannot be read any more: {error})", "red")
401
+
402
+ threading.Thread(target=read, daemon=True).start()
403
+
404
+ def show(self, record: dict, generation=None):
405
+ if generation is not None and generation != self.generation:
406
+ return
407
+ self.lanes.add(record)
408
+ kind = record.get("event")
409
+ if kind == "state":
410
+ self.status, self.interrupted = record["status"], False
411
+ if self.status in ("IDLE", "PAUSED", *ENDED):
412
+ self.ask = None
413
+ usage = record.get("usage") or {}
414
+ self.spent += (usage.get("cost_usd") or 0) if kind == "model_reply" else (record.get("cost_usd") or 0) \
415
+ if kind == "agent_report" else 0
416
+ if kind in ("physical_answer", "confirmation"):
417
+ self.ask = None
418
+ # The timeline's items too, for the reasoning and the answer of finish() in a program.
419
+ items = [item for item in transcript.items(record, self.names, timeline=True) if item["kind"] not in TIMELINE]
420
+ if kind == "cell" and self.program is not None:
421
+ out = self._ended(record, items)
422
+ else:
423
+ out = [line for item in items for line in self._item(item, record)]
424
+ if kind == "confirmation_request" and self.program is not None:
425
+ # What it asks to run.
426
+ out += self._program_lines(self.program)[:2]
427
+ if kind in ("physical_request", "confirmation_request"):
428
+ self._ask(record, items)
429
+ if kind in ("library", "cell", "state") and self.host is not None:
430
+ self._background(self._learning_now, self.conversation)
431
+ self._print(*out)
432
+ self.app.invalidate()
433
+
434
+ def _ask(self, record, items):
435
+ asked = next(item for item in items if item["kind"] in ("physical_request", "approval_request"))
436
+ keys = asked.get("keys") or {}
437
+ text = asked["text"] if asked["kind"] == "physical_request" else asked["text"].capitalize()
438
+ if keys.get("why") and not keys.get("sensitive"):
439
+ text += f"\n why: {keys['why']}"
440
+ self.ask = {"text": text, "options": transcript.approval_options(asked),
441
+ "at": 0, "reason": False, "request_id": record.get("id")}
442
+
443
+ def _answer(self, index: int):
444
+ remember = self.ask["options"][index][0]
445
+ if remember is None:
446
+ self.ask["reason"] = True
447
+ return
448
+ request_id = self.ask["request_id"]
449
+ conversation, self.ask = self.conversation, None
450
+ self._background(command, conversation, "approve", {"remember": remember, "request_id": request_id})
451
+
452
+ def _item(self, item, record) -> list:
453
+ """Chat scrollback stays compact; program details belong to the reversible view."""
454
+ kind, text = item["kind"], item["text"]
455
+ if not text.strip():
456
+ return []
457
+ if kind == "task" and text == self.echoed:
458
+ self.echoed = None
459
+ return []
460
+ if kind in ("task", "user"):
461
+ return [Text("› " + text, style="bold")]
462
+ if kind == "finished": # finish(answer) in a program, or the reply that said it
463
+ answer = str(record.get("text") or "").strip()
464
+ return [] if not answer or answer == self.said else [Markdown(answer), Text("")]
465
+ if kind in ("message", "thought", "finish", "verify_ask", "invalid"):
466
+ self.said = text.strip()
467
+ return [Markdown(text), Text("")]
468
+ if kind == "reasoning":
469
+ return [Text("\n".join(formats.clip_lines(text, 12)), style="dim italic")]
470
+ if kind == "program":
471
+ self.programs += 1
472
+ self.program = {"number": self.programs, "code": text, "details": [],
473
+ "lexer": "python" if item["keys"].get("reply") == "python" else "json"}
474
+ return []
475
+ if kind in DETAILS and self.program is not None:
476
+ lines = [Text(line, style=ROLES.get(role, "")) for role, line in item_lines(item)]
477
+ self.program["details"] += lines
478
+ return []
479
+ if kind == "state":
480
+ return [] if text == "your turn" else [Text(f"— {text}" + (": /continue, or send a message"
481
+ if text == "paused" else ""), style="dim")]
482
+ if kind == "approval_request" or kind == "outcome" and (record.get("outcome") or {}).get("success") is None:
483
+ return [] # the approval box asks; an outcome nothing scored says nothing
484
+ if kind == "physical_request": # asked in the approval box; its answer is a line of its own
485
+ return []
486
+ agent = record.get("agent") if kind.startswith("agent") else None
487
+ if agent:
488
+ colour = AGENT_COLOURS[sum(map(ord, str(agent))) % len(AGENT_COLOURS)]
489
+ return [Text.assemble((f"◆ {agent} ", f"bold {colour}"), (line, ROLES.get(role, "")))
490
+ for role, line in item_lines(item)]
491
+ return [Text(line, style=ROLES.get(role, "")) for role, line in item_lines(item)]
492
+
493
+ def _ended(self, record, items) -> list:
494
+ """The program's `cell` record: its result and output join its details; one line for it."""
495
+ done, self.program = self.program, None
496
+ self.last_program = done
497
+ result = record.get("result") or {}
498
+ done.update(status=result.get("status"), seconds=result.get("seconds"))
499
+ lines = [Text(line, style=ROLES.get(role, "")) for item in items for role, line in item_lines(item)]
500
+ done["details"] += lines
501
+ return [self._program_line(done)]
502
+
503
+ async def _show_details(self, program):
504
+ if self.details_open:
505
+ return
506
+ self.details_open = True
507
+ try:
508
+ await self._view(views.read("Program details · Ctrl+O to return",
509
+ lambda: self._details_text(program), close_key="c-o"))
510
+ finally:
511
+ self.details_open = False
512
+ output, self.details_output = self.details_output, []
513
+ self._print(*output)
514
+
515
+ def _details_text(self, program):
516
+ stream = io.StringIO()
517
+ console = Console(file=stream, force_terminal=False, color_system=None,
518
+ width=self.console.width, highlight=False)
519
+ console.print(*self._program_lines(program))
520
+ return stream.getvalue()
521
+
522
+ def _program_line(self, program) -> Text:
523
+ status = program.get("status") or "?"
524
+ style = "green" if status in ("ok", "finished") else "red" if status in ("error", "failed", "timeout") else "yellow"
525
+ return Text.assemble((f"▸ Program {program['number']}", "#5f87ff"), " · ", (status, style),
526
+ f" · {formats.duration(program.get('seconds'))}" if program.get("seconds") is not None else "",
527
+ (" ctrl+o details", "dim"))
528
+
529
+ def _program_lines(self, program) -> list:
530
+ return [Text(f"▾ Program {program['number']}", style="#5f87ff"),
531
+ Syntax(program["code"], program["lexer"], word_wrap=True), *program["details"]]
532
+
533
+ # What the user does.
534
+
535
+ def submit(self, text: str):
536
+ line = text.strip()
537
+ if not line:
538
+ return
539
+ if self.ask is not None and self.ask.get("reason"):
540
+ request_id = self.ask["request_id"]
541
+ conversation, self.ask = self.conversation, None
542
+ self._background(command, conversation, "reject", {"reason": line, "request_id": request_id})
543
+ return
544
+ if line.startswith("!"):
545
+ self._shell(line.lstrip("!").strip(), send=not line.startswith("!!"))
546
+ return
547
+ if line.startswith("/"):
548
+ name, _, rest = line[1:].partition(" ")
549
+ found = COMMANDS.get(name)
550
+ if found is None:
551
+ self.note(f"No command /{name}: /help lists them", "red")
552
+ elif found.method:
553
+ if self.conversation is None:
554
+ self.note("No conversation yet: send a message first", "red")
555
+ else:
556
+ values = {found.takes[0]: rest.strip()} if found.takes else {}
557
+ if self.ask is not None and "request_id" in found.takes:
558
+ values["request_id"] = self.ask["request_id"]
559
+ self._background(command, self.conversation, name, values)
560
+ else:
561
+ getattr(self, "do_" + name)(rest.strip())
562
+ return
563
+ files = [str(Path(quoted or bare).expanduser().resolve()) for quoted, bare in FILE.findall(line)
564
+ if Path(quoted or bare).expanduser().exists()]
565
+ self.send(line, files)
566
+
567
+ def _learning_now(self, conversation):
568
+ """Where the conversation stands, if it learns its environment (the status line's)."""
569
+ run = getattr(conversation, "run", None)
570
+ if run is None or conversation is not self.conversation:
571
+ return
572
+ now = self._host().learning(run)
573
+ self.learning = now if now.get("active") else None
574
+ self._later(self.app.invalidate)
575
+
576
+ def send(self, text, files=(), learn=None):
577
+ """A message: to the conversation, or the first of a new one (`learn`: one that learns
578
+ its environment for that many minutes, True: the settings')."""
579
+ if self.status == "starting":
580
+ self.pending.append((text, files))
581
+ elif self.conversation is not None and self.status not in ENDED:
582
+ self._background(_message, self.conversation, text, files)
583
+ elif self.start is None:
584
+ self.note("The conversation has ended", "red")
585
+ else:
586
+ self.status, self.echoed = "starting", text
587
+ self._print(Text("› " + text, style="bold"))
588
+
589
+ def begin():
590
+ # Where it works: what /environment picked, else the opening choice below.
591
+ place, self.environment = self.environment, None
592
+ agents, self.agents_on = self.agents_on, False
593
+ try:
594
+ while True:
595
+ try:
596
+ self.host, conversation = self.start(text, files, log=self._starting,
597
+ **({"learn": learn} if learn is not None else {}),
598
+ **({"model_entry": self.model_entry, "reasoning_effort": self.model_effort}
599
+ if self.model_entry else {}),
600
+ **({"workspace": place[0], "folder": place[1]} if place else {}),
601
+ **({"agents": True} if agents else {}))
602
+ break
603
+ except ChoiceRequired as error:
604
+ if error.choice.get("per_conversation"):
605
+ # (Opened by the Enter that sent the message: that key press
606
+ # must not answer it.)
607
+ place = asyncio.run_coroutine_threadsafe(
608
+ self._choose_environment(error.choice, settle=SETTLE), self.app.loop).result()
609
+ if place is None:
610
+ self._later(self._cancel_start, text)
611
+ return
612
+ continue
613
+ accepted = asyncio.run_coroutine_threadsafe(
614
+ self._choose_first_use(error.choice), self.app.loop).result()
615
+ if not accepted:
616
+ self._later(self._cancel_start, text)
617
+ return
618
+ except Exception as error:
619
+ self.status = None
620
+ self.note(f"(could not start: {error})", "red")
621
+ return
622
+ self._later(self._started, conversation)
623
+
624
+ threading.Thread(target=begin, daemon=True).start()
625
+
626
+ async def _choose_first_use(self, choice):
627
+ """No initial answer: Enter on the placeholder does not save a preference."""
628
+ options = choice["options"]
629
+ while True:
630
+ picked = await self._view(views.choose(choice["title"],
631
+ ["Choose an option below (nothing selected)", *[row["label"] for row in options]],
632
+ hint="↑↓ choose · Enter confirm · Esc cancel task · Saved for future tasks; change in /settings"))
633
+ if picked is None:
634
+ return False
635
+ if picked == 0:
636
+ continue
637
+ changes = {choice["section"]: {choice["key"]: options[picked - 1]["value"]}}
638
+ await asyncio.to_thread(lambda: self._host().post("/api/app/settings", changes))
639
+ return True
640
+
641
+ def _open_environment(self):
642
+ """A conversation opens: ask where it works before the first message is typed, when
643
+ the setting asks (session.environment) and the command line named none. The last
644
+ choice is highlighted and Enter takes it; Esc leaves it for the first message."""
645
+ if self.start is None or getattr(self.start, "named", False) or self.environment is not None:
646
+ return
647
+
648
+ async def ask():
649
+ offered = await asyncio.to_thread(lambda: self._host().get("/api/app/environments"))
650
+ if offered.get("setting") != "ask" or self.conversation is not None or self.status is not None:
651
+ return
652
+ place = await self._choose_environment({
653
+ "title": "Where should Harness work?", "selected": offered.get("selected"),
654
+ "folder": offered.get("folder"),
655
+ "options": [{**row, "name": row["label"]} for row in offered["options"]]})
656
+ if place is not None and self.conversation is None:
657
+ self.environment = place
658
+ self.note(f"This conversation works in {place[0]}" + (f" ({place[1]})" if place[1] else "")
659
+ + " · /environment changes it")
660
+ self.app.invalidate()
661
+
662
+ self.app.create_background_task(self._guarded(ask))
663
+
664
+ async def _choose_environment(self, choice, settle=0.0):
665
+ """The opening choice of a new conversation: where it works. The last choice is
666
+ highlighted and Enter takes it; with none yet, nothing is preselected. A kind bound
667
+ to a folder then asks for the folder (this directory inside a repository, else the
668
+ last one). (kind, folder), or None when cancelled. Nothing is saved as a setting."""
669
+ options = choice["options"]
670
+ values = [row["value"] for row in options]
671
+ chosen = choice.get("selected") in values
672
+ rows = [environment_row(row) for row in options]
673
+ while True:
674
+ picked = await self._view(views.choose(
675
+ choice["title"], rows if chosen else ["Choose an option below (nothing selected)", *rows],
676
+ current=values.index(choice["selected"]) if chosen else 0, settle=settle,
677
+ hint="↑↓ choose · Enter confirm · Esc cancel task · Asked for each new conversation "
678
+ "(session.environment in /settings)"))
679
+ if picked is None:
680
+ return None
681
+ if not chosen:
682
+ if picked == 0:
683
+ continue
684
+ picked -= 1
685
+ row = options[picked]
686
+ if not row.get("folder"):
687
+ return row["value"], None
688
+ folder = await self._view(views.ask(f"{row.get('name') or row['value']}: the folder to work in",
689
+ default_folder(choice.get("folder")),
690
+ hint="Enter confirm · Esc back"))
691
+ if folder and folder.strip():
692
+ return row["value"], str(Path(folder.strip()).expanduser())
693
+
694
+ def do_environment(self, _):
695
+ """/environment: where this conversation works, and the choice for the next one."""
696
+ async def pick():
697
+ offered = await asyncio.to_thread(lambda: self._host().get("/api/app/environments"))
698
+ now = f"This conversation works in: {self.workspace}. " if self.conversation is not None and self.workspace else ""
699
+ place = await self._choose_environment({
700
+ "title": now + "Where should the next conversation work?", "selected": offered.get("selected"),
701
+ "folder": offered.get("folder"),
702
+ "options": [{**row, "name": row["label"]} for row in offered["options"]]})
703
+ if place is not None:
704
+ self.environment = place
705
+ self.note(f"The next conversation works in {place[0]}" + (f" ({place[1]})" if place[1] else "")
706
+ + ("; /new starts it" if self.conversation is not None else ""))
707
+
708
+ self.app.create_background_task(self._guarded(pick))
709
+
710
+ def do_agents(self, _):
711
+ """/agents: sub-agents on, for this conversation or (before one starts) the next."""
712
+ if self.conversation is not None and self.status not in ENDED:
713
+ def switch():
714
+ self.conversation.enable_agents()
715
+ self._later(self.note, "Sub-agents are on for this conversation")
716
+
717
+ self._background(switch)
718
+ else:
719
+ self.agents_on = True
720
+ self.note("Sub-agents are on for the next conversation (session.agents in /settings keeps them on)")
721
+
722
+ def _cancel_start(self, text):
723
+ self.status = self.starting = None
724
+ self.pending = []
725
+ self.buffer.text = text
726
+ self.note("Task not started. Your message is kept in the input box.")
727
+
728
+ def _starting(self, message):
729
+ """What starting the conversation says (the session host starting): the status line's."""
730
+ self.starting = str(message).removeprefix("harness: ").split(" (log:")[0]
731
+ self._later(self.app.invalidate)
732
+
733
+ def _started(self, conversation):
734
+ self.starting = None
735
+ self._follow(conversation)
736
+ self.status = "RUNNING"
737
+ for text, files in self.pending:
738
+ self._background(_message, conversation, text, files)
739
+ self.pending = []
740
+
741
+ def interrupt(self):
742
+ """Esc or Ctrl+C while the agent works: it pauses at its next step, keeping what it did."""
743
+ if self.conversation is not None and self.status == "RUNNING" and not self.interrupted:
744
+ self.interrupted = True
745
+ self._background(self.conversation.pause)
746
+ self.note("interrupting: it stops at its next step (/continue goes on, a message tells it what to do)")
747
+
748
+ def _shell(self, line: str, send: bool):
749
+ """!command: run it here (in this directory), show its output, and give it to the agent
750
+ with the command (send)."""
751
+ if not line:
752
+ return
753
+
754
+ def run():
755
+ try:
756
+ done = subprocess.run(line, shell=True, capture_output=True, text=True, encoding=locale.getpreferredencoding(False),
757
+ errors="replace", timeout=600)
758
+ output = (done.stdout + done.stderr).rstrip() + ("" if done.returncode == 0 else f"\n(exit {done.returncode})")
759
+ except subprocess.TimeoutExpired:
760
+ output = "(stopped after 600 s)"
761
+ self._later(self._print, Text(f"! {line}", style="bold"), Text("\n".join(formats.clip_lines(output, 40)),
762
+ style="dim"))
763
+ if send:
764
+ self._later(self.send, f"I ran `{line}` here:\n```\n{formats.clip(output, 20000)}\n```")
765
+
766
+ threading.Thread(target=run, daemon=True).start()
767
+
768
+ # The terminal's own commands (terminal.COMMANDS without a method).
769
+
770
+ def do_help(self, _):
771
+ width = max(len(name) + len(found.words) for name, found in COMMANDS.items()) + 4
772
+ self._print(*[Text.assemble((f" /{name} {found.words}".ljust(width), "bold"), (found.note, "dim"))
773
+ for name, found in COMMANDS.items()],
774
+ *[Text.assemble((f" {key}".ljust(width), "bold"), (what, "dim")) for key, what in KEYS])
775
+
776
+ def do_answer(self, words):
777
+ if self.conversation is None:
778
+ self.note("Open a conversation first", "red")
779
+ return
780
+ identifier, _, value = words.partition(" ")
781
+ try:
782
+ content = json.loads(value)
783
+ except ValueError:
784
+ self.note("Use /answer REQUEST_ID JSON (or null to decline)", "red")
785
+ return
786
+ self._background(self.conversation.answer, identifier, content)
787
+
788
+ def do_config(self, words):
789
+ if self.conversation is None:
790
+ self.note("Open a conversation first", "red")
791
+ return
792
+ identifier, _, value = words.partition(" ")
793
+ self._background(self.conversation.set_config, identifier, value)
794
+
795
+ def do_diff(self, _):
796
+ if self.conversation is None:
797
+ self.note("Open a conversation first", "red")
798
+ return
799
+
800
+ def show():
801
+ result = self.conversation.diff()
802
+ text = "\n".join([result["patch"], *(f"Untracked: {path}" for path in result["untracked"])])
803
+ self._print(Text(text or "No changes"))
804
+
805
+ self._background(show)
806
+
807
+ def do_merge(self, _):
808
+ if self.conversation is None:
809
+ self.note("Open a conversation first", "red")
810
+ return
811
+ self._background(self.conversation.merge)
812
+
813
+ def do_handoff(self, words):
814
+ if self.conversation is None:
815
+ self.note("Open a conversation first", "red")
816
+ return
817
+ agent, _, context = words.partition(" ")
818
+
819
+ def handoff():
820
+ self._later(self._started, self.conversation.handoff(agent, context))
821
+
822
+ self._background(handoff)
823
+
824
+ def do_import(self, words):
825
+ provider, _, file = words.partition(" ")
826
+
827
+ def load():
828
+ conversation = self._host().import_session(Path(file.strip('"')).expanduser().resolve(), provider)
829
+ self._later(self._started, conversation)
830
+
831
+ self._background(load)
832
+
833
+ def do_new(self, _):
834
+ self._leave()
835
+ self._print(Text("── new conversation " + "─" * 40, style="dim"))
836
+ self._open_environment()
837
+
838
+ def _leave(self):
839
+ """No conversation shown (the one that was goes on)."""
840
+ self.stop.set()
841
+ self.generation += 1
842
+ self.conversation, self.status, self.ask, self.spent, self.lanes = None, None, None, 0.0, Lanes()
843
+ self.learning = None
844
+ self._reset()
845
+ try:
846
+ from ..providers import load
847
+
848
+ self.model = load(data())["model"]
849
+ except Exception:
850
+ pass
851
+
852
+ def do_exit(self, _):
853
+ self.app.exit()
854
+
855
+ do_detach = do_exit
856
+
857
+ def do_learn(self, rest):
858
+ """/learn [minutes] [for what]: a new conversation that learns this environment; while
859
+ one runs, where it stands."""
860
+ if self.learning and self.status not in ENDED:
861
+ self.note(progress_line(self.learning) + ("\n open: " + " | ".join(self.learning["open"][:8])
862
+ if self.learning["open"] else ""))
863
+ return
864
+ first, _, words = rest.partition(" ")
865
+ try:
866
+ minutes = float(first)
867
+ except ValueError:
868
+ minutes, words = True, rest
869
+ if self.start is None:
870
+ self.note("This chat follows one conversation: /learn starts one in harness (the terminal chat)", "red")
871
+ return
872
+ if self.status == "starting":
873
+ self.note("A conversation is starting: /learn once it has", "red")
874
+ return
875
+ if self.conversation is not None:
876
+ self.do_new("")
877
+ self.send(words.strip() or "Get to know this environment for the tasks I give you.", learn=minutes)
878
+
879
+ def do_timeline(self, _):
880
+ self.app.create_background_task(self._view(views.timeline_view(self.lanes)))
881
+
882
+ def _host(self, start=True):
883
+ if self.host is None:
884
+ from ..host import Host
885
+
886
+ self.host = Host.connect(start=start)
887
+ return self.host
888
+
889
+ def do_host(self, words):
890
+ """/host: how the session host runs; /host stop: end it, with what runs in it."""
891
+ host = self._host(start=False)
892
+ if host is None:
893
+ self.note("No session host runs (the next conversation starts it)")
894
+ return
895
+ if str(words or "").strip() == "stop":
896
+ self._leave()
897
+ host.stop(force=True)
898
+ self.host = None
899
+ self.note(f"Stopped the session host at {host.url}")
900
+ return
901
+ info = host.info()
902
+ self.note(f"Session host {host.url}, process {info.get('pid')}, version {info.get('version')}, "
903
+ f"{info.get('open', 0)} open, idle {formats.duration(info.get('idle_seconds') or 0)}")
904
+
905
+ def do_effort(self, words):
906
+ """Choose an effort for the saved model or apply an explicit effort to an open conversation."""
907
+ from ..model_list import select
908
+ from harness.runtime.decision.model import valid_effort
909
+
910
+ async def pick():
911
+ row = select(data(), self.model_entry)
912
+ level = str(words or "").strip()
913
+ if not level:
914
+ if self.conversation is not None and self.status not in ENDED:
915
+ self.note("Use /effort LEVEL or /effort default for the open conversation.")
916
+ return
917
+ levels = [value for value in (row or {}).get("efforts", []) if value != "default"]
918
+ option = await self._view(views.choose("Reasoning effort", ["Provider default", *levels]))
919
+ if option is None:
920
+ return
921
+ level = (["default", *levels])[option]
922
+ effort = "" if level == "default" else level
923
+ if not valid_effort(effort):
924
+ raise ValueError("invalid reasoning effort ID")
925
+ if self.conversation is not None and self.status not in ENDED:
926
+ self._background(lambda: self.conversation.set_model(reasoning_effort=effort))
927
+ elif row:
928
+ if effort and effort not in row["efforts"]:
929
+ raise ValueError("this model does not offer that reasoning effort")
930
+ self.model_entry, self.model_effort = row["id"], effort
931
+ else:
932
+ raise ValueError("add an enabled model first")
933
+ self.note(f"Effort: {level}")
934
+
935
+ self.app.create_background_task(self._guarded(pick))
936
+
937
+ def do_experiment(self, words):
938
+ """/experiment NAME [TASK [SEED]] [-- instruction]: a session of an experiment's task on
939
+ its worker, in the session host (as the app's /dev page starts one)."""
940
+ from shlex import split
941
+
942
+ try:
943
+ parts = split(str(words or ""))
944
+ instruction = ""
945
+ if "--" in parts:
946
+ marker = parts.index("--")
947
+ instruction, parts = " ".join(parts[marker + 1:]), parts[:marker]
948
+ if not 1 <= len(parts) <= 3:
949
+ raise ValueError("experiment arguments")
950
+ seed = int(parts[2]) if len(parts) > 2 else 0
951
+ except ValueError:
952
+ self.note("/experiment NAME [TASK [SEED]] [-- instruction]", "red")
953
+ return
954
+
955
+ def start():
956
+ request = {"experiment": parts[0], "task": parts[1] if len(parts) > 1 else None,
957
+ "seed": seed, "frontend": "terminal",
958
+ **({"instruction": instruction.strip()} if instruction.strip() else {})}
959
+ conversation = self._host().start(**request)
960
+ self._later(self._print, Text(f"── experiment {parts[0]} " + "─" * 40, style="dim"))
961
+ self._later(self._started, conversation)
962
+
963
+ self._background(start)
964
+
965
+ def do_sessions(self, _):
966
+ async def pick():
967
+ host = self._host(start=False)
968
+ if host is None:
969
+ self.note("No session host runs: nothing is open")
970
+ return
971
+ lines = table_rows([session.row for session in host.sessions()])
972
+ if not lines:
973
+ self.note("No sessions run")
974
+ return
975
+ rows = [f"{line['session'] or ' '} {line['agent']:<12} {line['status']:<26} {line['spent']:<16} {line['title']}"
976
+ for line in lines]
977
+ current = next((index for index, line in enumerate(lines) if line["run"] == getattr(self.conversation, "run", None)), 0)
978
+ picked = await self._view(views.choose("Sessions that run", rows, current=current))
979
+ if picked is not None and lines[picked]["run"] != getattr(self.conversation, "run", None):
980
+ self._print(Text(f"── session {lines[picked]['run']} " + "─" * 40, style="dim"))
981
+ self._follow(host.conversation(lines[picked]["run"]))
982
+
983
+ self.app.create_background_task(self._guarded(pick))
984
+
985
+ def do_resume(self, _):
986
+ async def pick():
987
+ host = self._host()
988
+ sessions = [session.row for session in host.sessions(all=True, limit=100)]
989
+ if not sessions:
990
+ self.note("No conversations yet")
991
+ return
992
+ rows = [f"{formats.timestamp(row.get('created'))} {word(row.get('status')):<26} {row.get('title') or ''}"
993
+ for row in sessions]
994
+ picked = await self._view(views.choose("Resume a conversation", rows))
995
+ if picked is None:
996
+ return
997
+ row = sessions[picked]
998
+ self._print(Text(f"── {row.get('title') or row['id']} " + "─" * 40, style="dim"))
999
+ if row.get("status") in LIVE:
1000
+ self._follow(host.conversation(row["run"]))
1001
+ return
1002
+ from ..core.episodes import Follow
1003
+
1004
+ self._leave()
1005
+ for record in Follow(Path(row["directory"])).next() if row.get("directory") else []:
1006
+ self.show(record)
1007
+ self.status, self.spent = None, 0.0
1008
+ self.note("This conversation has ended; a message starts a new one")
1009
+
1010
+ self.app.create_background_task(self._guarded(pick))
1011
+
1012
+ def do_model(self, _):
1013
+ async def pick():
1014
+ from ..model_list import models, select
1015
+ from ..providers import PROVIDERS
1016
+
1017
+ options = [row for row in models(data()) if row["enabled"]]
1018
+ current = select(data(), self.model_entry) if any(
1019
+ row["id"] == self.model_entry for row in options) else select(data())
1020
+ rows = [f"{row['name']} · {PROVIDERS[row['provider']].name if row['provider'] in PROVIDERS else row['provider']}"
1021
+ + (f" · {row['base_url']}" if row["base_url"] else "") for row in options]
1022
+ picked = await self._view(views.choose("Model for new conversations", rows,
1023
+ current=options.index(current) if current else 0,
1024
+ hint="Enter select · Esc close · /models edits the local list"))
1025
+ if picked is not None:
1026
+ row = options[picked]
1027
+ self.model_entry, self.model_effort = row["id"], None
1028
+ if self.conversation is None:
1029
+ self.model = row["name"]
1030
+ self.note(f"Model for new conversations: {rows[picked]}")
1031
+
1032
+ self.app.create_background_task(self._guarded(pick))
1033
+
1034
+ def do_models(self, _):
1035
+ async def edit():
1036
+ from shlex import split
1037
+
1038
+ from ..model_list import models
1039
+
1040
+ path = data() / "models.json"
1041
+ models(data())
1042
+ editor = os.environ.get("EDITOR") or ("notepad.exe" if os.name == "nt" else "vi")
1043
+ command = [editor] if os.path.isfile(editor) else split(editor, posix=os.name != "nt")
1044
+ async with in_terminal():
1045
+ result = await asyncio.to_thread(subprocess.run, [*command, str(path)], check=False)
1046
+ if result.returncode:
1047
+ raise ValueError(f"the editor exited with code {result.returncode}")
1048
+ count = sum(row["enabled"] for row in models(data()))
1049
+ self.note(f"{count} enabled models · /model to select · {path}")
1050
+
1051
+ self.app.create_background_task(self._guarded(edit))
1052
+
1053
+ def do_settings(self, _):
1054
+ async def edit():
1055
+ for line in await self._view(views.settings_view(data())):
1056
+ self.note(f"set {line}")
1057
+
1058
+ self.app.create_background_task(self._guarded(edit))
1059
+
1060
+ def do_packages(self, _):
1061
+ async def edit():
1062
+ for line in await self._view(views.packages_view()):
1063
+ self.note(line)
1064
+
1065
+ self.app.create_background_task(self._guarded(edit))
1066
+
1067
+ def do_library(self, _):
1068
+ from harness.core.memory import rows
1069
+
1070
+ conversation = self.conversation
1071
+ # A session's conversation says (RemoteConversation.memory); one in this process, its trace.
1072
+ memory = getattr(conversation, "memory", None) or (
1073
+ (lambda: rows(run=conversation.directory)) if conversation is not None else None)
1074
+ self.app.create_background_task(self._guarded(lambda: self._view(views.library_view(memory))))
1075
+
1076
+ async def _guarded(self, function):
1077
+ try:
1078
+ await function()
1079
+ except Exception as error:
1080
+ self.note(f"({error})", "red")
1081
+
1082
+
1083
+ class Completions(Completer):
1084
+ """/ the commands (and /approve's words), @ the paths under this directory."""
1085
+
1086
+ def __init__(self):
1087
+ self.paths = PathCompleter(expanduser=True)
1088
+
1089
+ def get_completions(self, document, event):
1090
+ text = document.text_before_cursor
1091
+ if text.startswith("/") and " " not in text:
1092
+ for name, found in COMMANDS.items():
1093
+ if name.startswith(text[1:]):
1094
+ yield Completion(f"/{name}", -len(text), display=f"/{name} {found.words}".strip(),
1095
+ display_meta=found.note)
1096
+ return
1097
+ if text.startswith("/approve ") and text.count(" ") == 1:
1098
+ for remember in REMEMBER[1:]:
1099
+ if remember.startswith(text.split(" ")[1]):
1100
+ yield Completion(remember, -len(text.split(" ")[1]))
1101
+ return
1102
+ found = re.search(r'@("?)([^\s"]*)$', text)
1103
+ if found:
1104
+ for completion in self.paths.get_completions(Document(found.group(2)), event):
1105
+ path = found.group(2)[:len(found.group(2)) + completion.start_position] + completion.text
1106
+ quoted = f'"{path}"' if " " in path else path
1107
+ yield Completion(quoted, -len(found.group(1) + found.group(2)), display=completion.display,
1108
+ display_meta="folder" if Path(path).is_dir() else "")
1109
+
1110
+
1111
+ class Placeholder(Processor):
1112
+ """What the empty input box is for, dim."""
1113
+
1114
+ def __init__(self, chat):
1115
+ self.chat = chat
1116
+
1117
+ def apply_transformation(self, given):
1118
+ if given.document.text or given.lineno:
1119
+ return Transformation(given.fragments)
1120
+ ask = self.chat.ask
1121
+ words = (f"{say('answer.why')}, Enter" if ask and ask.get("reason") else
1122
+ f"1-{len(ask['options'])} or ↑↓ Enter to answer, or type a message" if ask else
1123
+ "a message: it reaches the agent at once" if self.chat.status in ("RUNNING", "starting") else
1124
+ "what should it do?")
1125
+ return Transformation(given.fragments + [("class:placeholder", words)])
1126
+
1127
+
1128
+ # Seconds a choice opened by sending a message does not take Enter (views.choose settle).
1129
+ SETTLE = 0.6
1130
+
1131
+
1132
+ def environment_row(row) -> str:
1133
+ """One environment of the opening choice as its line: the label, what it is, a note."""
1134
+ text = row.get("name") or row.get("label") or row["value"]
1135
+ about = row.get("about")
1136
+ return text + (f" — {about}" if about else "") + (f" ({row['note']})" if row.get("note") else "")
1137
+
1138
+
1139
+ def default_folder(last=None) -> str:
1140
+ """The folder a project choice starts from: this directory when it is inside a
1141
+ repository, else the last folder chosen, else this directory."""
1142
+ here = Path.cwd()
1143
+ if any((parent / ".git").exists() for parent in (here, *here.parents)):
1144
+ return str(here)
1145
+ return str(last or here)
1146
+
1147
+
1148
+ def _message(conversation, text, files):
1149
+ if files:
1150
+ conversation.send_message(text, files=files)
1151
+ else:
1152
+ conversation.send_message(text)
1153
+
1154
+
1155
+ def _history_file() -> Path:
1156
+ path = data() / "tui-history"
1157
+ path.parent.mkdir(parents=True, exist_ok=True)
1158
+ return path
1159
+
1160
+
1161
+ def _input():
1162
+ """The terminal's keys; on Windows read as the console's key records, so that Shift+Enter
1163
+ comes apart from Enter (as Ctrl+J, a new line)."""
1164
+ if sys.platform != "win32":
1165
+ return create_input()
1166
+ from prompt_toolkit.input.win32 import ConsoleInputReader, Win32Input
1167
+ from prompt_toolkit.key_binding.key_processor import KeyPress
1168
+
1169
+ class Reader(ConsoleInputReader):
1170
+ def _event_to_key_presses(self, ev):
1171
+ # Shift+Enter, Ctrl+Enter and Ctrl+J: a new line (the console gives the last two as Esc, Ctrl+J).
1172
+ control = ev.ControlKeyState & (self.LEFT_CTRL_PRESSED | self.RIGHT_CTRL_PRESSED)
1173
+ if ev.VirtualKeyCode == 13 and ev.ControlKeyState & (self.SHIFT_PRESSED | control) or \
1174
+ ev.VirtualKeyCode == 0x4A and control:
1175
+ return [KeyPress(Keys.ControlJ, "\n")]
1176
+ return super()._event_to_key_presses(ev)
1177
+
1178
+ found = Win32Input()
1179
+ found._use_virtual_terminal_input = False
1180
+ found.console_input_reader = Reader()
1181
+ return found