harbor-tui 0.1.0__py3-none-any.whl
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.
- harbor/__init__.py +3 -0
- harbor/agent_form.py +71 -0
- harbor/agent_view.py +207 -0
- harbor/app.py +365 -0
- harbor/artifacts_pane.py +138 -0
- harbor/boat.py +324 -0
- harbor/cli.py +113 -0
- harbor/config.py +61 -0
- harbor/console.py +159 -0
- harbor/core.py +142 -0
- harbor/dashboard.py +140 -0
- harbor/find.py +19 -0
- harbor/local.py +97 -0
- harbor/message_bar.py +96 -0
- harbor/orders.py +71 -0
- harbor/view.py +53 -0
- harbor_tui-0.1.0.dist-info/METADATA +192 -0
- harbor_tui-0.1.0.dist-info/RECORD +21 -0
- harbor_tui-0.1.0.dist-info/WHEEL +4 -0
- harbor_tui-0.1.0.dist-info/entry_points.txt +3 -0
- harbor_tui-0.1.0.dist-info/licenses/LICENSE +21 -0
harbor/__init__.py
ADDED
harbor/agent_form.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""The agent form: repo, provider, model, and prompt for a new agent on a sandbox."""
|
|
2
|
+
|
|
3
|
+
from textual.app import ComposeResult
|
|
4
|
+
from textual.binding import Binding
|
|
5
|
+
from textual.containers import Vertical
|
|
6
|
+
from textual.screen import ModalScreen
|
|
7
|
+
from textual.widgets import Input, Label, Select
|
|
8
|
+
|
|
9
|
+
from harbor.core import Order, parse_repo
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AgentForm(ModalScreen[Order | None]):
|
|
13
|
+
"""Enter in any field starts the agent. Tab moves on. Escape cancels."""
|
|
14
|
+
|
|
15
|
+
BINDINGS = [Binding("escape", "dismiss", "Cancel")]
|
|
16
|
+
|
|
17
|
+
def __init__(self, title: str, last: Order, providers: list[str], repos: list[str]):
|
|
18
|
+
super().__init__()
|
|
19
|
+
self.title_text = title
|
|
20
|
+
self.last = last # remembers the provider and model you chose before
|
|
21
|
+
self.providers = providers
|
|
22
|
+
self.repos = repos
|
|
23
|
+
|
|
24
|
+
def compose(self) -> ComposeResult:
|
|
25
|
+
with Vertical(id="agent-form"):
|
|
26
|
+
yield Label(self.title_text, id="title")
|
|
27
|
+
yield self._repo_field()
|
|
28
|
+
known = self.last.provider in self.providers
|
|
29
|
+
yield Select([(p, p) for p in self.providers], prompt="provider (required)",
|
|
30
|
+
value=self.last.provider if known else Select.NULL, id="provider")
|
|
31
|
+
yield Input(self.last.model, placeholder="model (blank: harness default)", id="model")
|
|
32
|
+
yield Input(placeholder="prompt: what should the agent do?", id="prompt")
|
|
33
|
+
yield Label("Enter starts the agent · Tab next field · Esc cancels", classes="hint")
|
|
34
|
+
|
|
35
|
+
def _repo_field(self):
|
|
36
|
+
"""A gh repo list when there is one (type to jump), else free text."""
|
|
37
|
+
if not self.repos:
|
|
38
|
+
return Input(placeholder="repo: owner/name (optional)", id="repo")
|
|
39
|
+
options = [(f"{repo.split('/')[1]} · {repo.split('/')[0]}", repo) for repo in self.repos]
|
|
40
|
+
return Select(options, prompt="repo (none)", id="repo")
|
|
41
|
+
|
|
42
|
+
def _repo(self) -> str:
|
|
43
|
+
field = self.query_one("#repo")
|
|
44
|
+
if isinstance(field, Select):
|
|
45
|
+
return "" if field.value is Select.NULL else field.value
|
|
46
|
+
return parse_repo(field.value) if field.value.strip() else ""
|
|
47
|
+
|
|
48
|
+
def on_mount(self) -> None:
|
|
49
|
+
self.query_one("#repo").focus()
|
|
50
|
+
|
|
51
|
+
def _text(self, field: str) -> str:
|
|
52
|
+
return self.query_one(f"#{field}", Input).value.strip()
|
|
53
|
+
|
|
54
|
+
def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
55
|
+
event.stop()
|
|
56
|
+
prompt = self._text("prompt")
|
|
57
|
+
if not prompt:
|
|
58
|
+
self.notify("Write a prompt first.", severity="warning")
|
|
59
|
+
self.query_one("#prompt").focus()
|
|
60
|
+
return
|
|
61
|
+
provider = self.query_one("#provider", Select).value
|
|
62
|
+
if provider is Select.NULL:
|
|
63
|
+
self.notify("Choose a provider.", severity="warning")
|
|
64
|
+
self.query_one("#provider", Select).focus()
|
|
65
|
+
return
|
|
66
|
+
try:
|
|
67
|
+
repo = self._repo()
|
|
68
|
+
except ValueError as error:
|
|
69
|
+
self.notify(str(error), severity="error")
|
|
70
|
+
return
|
|
71
|
+
self.dismiss(Order(prompt=prompt, provider=provider, model=self._text("model"), repo=repo))
|
harbor/agent_view.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""An agent's view: its results, artifacts, logs, and a shell on its sandbox.
|
|
2
|
+
|
|
3
|
+
The agent has exactly one sandbox, so this view is both. Keys act on the agent,
|
|
4
|
+
and the footer shows only the ones that fit what it's doing. Anything that needs
|
|
5
|
+
the sandbox up (messaging, the shell, artifacts) wakes it first.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from functools import partial
|
|
10
|
+
|
|
11
|
+
from rich.text import Text
|
|
12
|
+
from textual import work
|
|
13
|
+
from textual.app import ComposeResult
|
|
14
|
+
from textual.binding import Binding
|
|
15
|
+
from textual.screen import Screen
|
|
16
|
+
from textual.widgets import Footer, Header, OptionList, RichLog, Static, TabbedContent, TabPane
|
|
17
|
+
|
|
18
|
+
from harbor.artifacts_pane import ArtifactsPane
|
|
19
|
+
from harbor.boat import Boat
|
|
20
|
+
from harbor.console import Console
|
|
21
|
+
from harbor.core import error_text
|
|
22
|
+
from harbor.dashboard import fill, result_rows, status
|
|
23
|
+
from harbor.message_bar import MessageBar, ResultScreen
|
|
24
|
+
from harbor.view import Pick, render_line
|
|
25
|
+
|
|
26
|
+
SHELL_HINT = "Press c for a shell on this agent's sandbox. ctrl+] leaves it; it keeps running."
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def info(pick: Pick) -> Text:
|
|
30
|
+
box, agent = pick.box, pick.agent
|
|
31
|
+
model = f" model {agent.model}" if agent and agent.model else ""
|
|
32
|
+
repo = box.labels.get("harbor/repo", "")
|
|
33
|
+
return Text.assemble(status(pick, datetime.now(UTC)), " ",
|
|
34
|
+
((agent.harness if agent else "") or "", "bold"),
|
|
35
|
+
(f"{model} {repo} sandbox {box.name} ({box.state})", "dim"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AgentScreen(Screen):
|
|
39
|
+
BINDINGS = [Binding("escape", "back", "Home"),
|
|
40
|
+
Binding("y", "run('approve')", "Approve"),
|
|
41
|
+
Binding("d", "run('deny')", "Deny"),
|
|
42
|
+
Binding("r", "run('continue_agent')", "Continue"),
|
|
43
|
+
Binding("t", "run('steer')", "Steer"),
|
|
44
|
+
Binding("s", "run('stop_agent')", "Stop"),
|
|
45
|
+
Binding("p", "run('prompt')", "Feedback"),
|
|
46
|
+
Binding("c", "run('shell')", "Shell"),
|
|
47
|
+
Binding("v", "tab('artifacts')", "Artifacts"),
|
|
48
|
+
Binding("l", "tab('logs')", "Logs"),
|
|
49
|
+
Binding("o", "run('desktop')", "Desktop"),
|
|
50
|
+
Binding("x", "run('close_agent')", "Close"),
|
|
51
|
+
Binding("1", "tab('results')", "Results", show=False),
|
|
52
|
+
Binding("2", "tab('artifacts')", "Artifacts", show=False),
|
|
53
|
+
Binding("3", "tab('logs')", "Logs", show=False),
|
|
54
|
+
Binding("4", "tab('shell')", "Shell", show=False)]
|
|
55
|
+
# Keys that only make sense in one state are hidden in the other.
|
|
56
|
+
WHEN_WORKING = {"steer", "stop_agent"}
|
|
57
|
+
WHEN_WAITING = {"approve", "deny", "continue_agent"}
|
|
58
|
+
NEED_AGENT = {"prompt"} | WHEN_WORKING | WHEN_WAITING
|
|
59
|
+
|
|
60
|
+
def __init__(self, pick: Pick, boat: Boat):
|
|
61
|
+
super().__init__()
|
|
62
|
+
self.target, self.boat = pick, boat
|
|
63
|
+
self.replies: list[str] = []
|
|
64
|
+
self.log_text = "" # the Logs tab as plain text, for copying
|
|
65
|
+
|
|
66
|
+
def compose(self) -> ComposeResult:
|
|
67
|
+
yield Header()
|
|
68
|
+
yield Static(id="agent-info")
|
|
69
|
+
with TabbedContent(id="tabs"):
|
|
70
|
+
with TabPane("Results", id="results"):
|
|
71
|
+
yield OptionList(id="result-list")
|
|
72
|
+
with TabPane("Artifacts", id="artifacts"):
|
|
73
|
+
yield ArtifactsPane(self.target.box, self.boat, self.agents())
|
|
74
|
+
with TabPane("Logs", id="logs"):
|
|
75
|
+
yield RichLog(id="log-view", wrap=True)
|
|
76
|
+
with TabPane("Shell", id="shell"):
|
|
77
|
+
yield Static(SHELL_HINT, id="shell-hint")
|
|
78
|
+
yield MessageBar(self.boat)
|
|
79
|
+
yield Footer()
|
|
80
|
+
|
|
81
|
+
def agents(self) -> list:
|
|
82
|
+
return [self.target.agent] if self.target.agent else []
|
|
83
|
+
|
|
84
|
+
def on_mount(self) -> None:
|
|
85
|
+
self.update(self.target)
|
|
86
|
+
self.query_one("#result-list").focus()
|
|
87
|
+
|
|
88
|
+
def update(self, pick: Pick) -> None:
|
|
89
|
+
"""Fresh data from the app's refresh."""
|
|
90
|
+
self.target = pick
|
|
91
|
+
box, agent = pick.box, pick.agent
|
|
92
|
+
self.sub_title = box.labels.get("harbor/task") or (agent.preview if agent else "") or box.name
|
|
93
|
+
self.query_one("#agent-info", Static).update(info(pick))
|
|
94
|
+
self.query_one(MessageBar).set_target(pick if agent else None)
|
|
95
|
+
self.query_one(ArtifactsPane).agents = self.agents()
|
|
96
|
+
rows = result_rows(pick)
|
|
97
|
+
self.replies = [text for _, text in rows]
|
|
98
|
+
panel = self.query_one("#result-list", OptionList)
|
|
99
|
+
fill(panel, [row for row, _ in rows], "No results yet.", panel.highlighted)
|
|
100
|
+
self.refresh_bindings() # its keys follow what it's doing
|
|
101
|
+
|
|
102
|
+
def action_run(self, action: str) -> None:
|
|
103
|
+
getattr(self.app, f"action_{action}")()
|
|
104
|
+
|
|
105
|
+
def check_action(self, action: str, parameters: tuple) -> bool:
|
|
106
|
+
if action != "run":
|
|
107
|
+
return True
|
|
108
|
+
name, agent = parameters[0], self.target.agent
|
|
109
|
+
if name in self.NEED_AGENT and not agent:
|
|
110
|
+
return False
|
|
111
|
+
if name in self.WHEN_WORKING:
|
|
112
|
+
return agent.running
|
|
113
|
+
return not agent.running if name in self.WHEN_WAITING else True
|
|
114
|
+
|
|
115
|
+
def commands(self) -> list[tuple[str, str, object]]:
|
|
116
|
+
"""This agent's keys, as palette commands: only the ones that fit what it's doing."""
|
|
117
|
+
found = []
|
|
118
|
+
for binding in self.BINDINGS:
|
|
119
|
+
name, _, arg = binding.action.partition("(")
|
|
120
|
+
arg = arg.strip("')")
|
|
121
|
+
usable = name == "tab" or (name == "run" and self.check_action(name, (arg,)))
|
|
122
|
+
if binding.show and usable:
|
|
123
|
+
go = partial(getattr(self, f"action_{name}"), arg)
|
|
124
|
+
found.append((binding.description.lower(), f"this agent ({binding.key})", go))
|
|
125
|
+
return found
|
|
126
|
+
|
|
127
|
+
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
|
|
128
|
+
if event.option_list.id != "result-list" or event.option_index >= len(self.replies):
|
|
129
|
+
return
|
|
130
|
+
event.stop()
|
|
131
|
+
self.app.push_screen(ResultScreen(self.sub_title, self.replies[event.option_index]))
|
|
132
|
+
|
|
133
|
+
def on_tabbed_content_tab_activated(self, event: TabbedContent.TabActivated) -> None:
|
|
134
|
+
"""Artifacts load when you look at them, so opening an agent never wakes its sandbox."""
|
|
135
|
+
if event.pane.id == "artifacts":
|
|
136
|
+
self.query_one(ArtifactsPane).load()
|
|
137
|
+
elif event.pane.id == "logs":
|
|
138
|
+
self.load_logs()
|
|
139
|
+
|
|
140
|
+
@work(thread=True, exclusive=True, group="logs")
|
|
141
|
+
def load_logs(self) -> None:
|
|
142
|
+
"""The agent's conversation (prompts, replies, tool calls), then the commands Boat
|
|
143
|
+
ran. Boat keeps both while the sandbox sleeps, so this never wakes it."""
|
|
144
|
+
box, agent = self.target.box.id, self.target.agent
|
|
145
|
+
try:
|
|
146
|
+
lines = [render_line(line) for line in self.boat.events(box, agent.id)] if agent else []
|
|
147
|
+
commands = self.boat.commands(box) or "No commands yet."
|
|
148
|
+
except Exception as error: # noqa: BLE001 - shown, not raised
|
|
149
|
+
lines, commands = [Text(error_text(error), "red")], ""
|
|
150
|
+
lines += [Text(""), Text("Commands Boat ran", "bold"), Text(commands)]
|
|
151
|
+
self.app.call_from_thread(self.show_logs, lines)
|
|
152
|
+
|
|
153
|
+
def show_logs(self, lines: list[Text]) -> None:
|
|
154
|
+
self.log_text = "\n".join(line.plain for line in lines)
|
|
155
|
+
log = self.query_one("#log-view", RichLog)
|
|
156
|
+
log.clear()
|
|
157
|
+
for line in lines:
|
|
158
|
+
log.write(line)
|
|
159
|
+
|
|
160
|
+
def copy_text(self) -> str:
|
|
161
|
+
"""The highlighted reply, or the artifact in the viewer."""
|
|
162
|
+
active = self.query_one("#tabs", TabbedContent).active
|
|
163
|
+
if active == "artifacts":
|
|
164
|
+
return self.query_one(ArtifactsPane).shown
|
|
165
|
+
if active == "logs":
|
|
166
|
+
return self.log_text
|
|
167
|
+
index = self.query_one("#result-list", OptionList).highlighted
|
|
168
|
+
return self.replies[index] if index is not None and index < len(self.replies) else ""
|
|
169
|
+
|
|
170
|
+
def action_tab(self, tab: str) -> None:
|
|
171
|
+
self.query_one("#tabs", TabbedContent).active = tab
|
|
172
|
+
|
|
173
|
+
# The shell
|
|
174
|
+
|
|
175
|
+
def console(self) -> Console | None:
|
|
176
|
+
found = self.query(Console)
|
|
177
|
+
return found.first() if found else None
|
|
178
|
+
|
|
179
|
+
def attach(self, console: Console) -> None:
|
|
180
|
+
self.query_one("#shell-hint").display = False
|
|
181
|
+
self.query_one("#shell", TabPane).mount(console)
|
|
182
|
+
self.show_shell()
|
|
183
|
+
|
|
184
|
+
def show_shell(self) -> None:
|
|
185
|
+
self.action_tab("shell")
|
|
186
|
+
if console := self.console():
|
|
187
|
+
self.call_after_refresh(console.focus)
|
|
188
|
+
|
|
189
|
+
def on_console_left(self) -> None:
|
|
190
|
+
self.action_tab("results")
|
|
191
|
+
self.query_one("#result-list").focus()
|
|
192
|
+
|
|
193
|
+
def on_console_closed(self, message: Console.Closed) -> None:
|
|
194
|
+
message.console.remove()
|
|
195
|
+
self.query_one("#shell-hint").display = True
|
|
196
|
+
self.notify("Shell closed.")
|
|
197
|
+
|
|
198
|
+
def action_back(self) -> None:
|
|
199
|
+
"""From the message bar to the results; from the results to Home."""
|
|
200
|
+
if self.query_one(MessageBar).has_focus_within:
|
|
201
|
+
self.query_one("#result-list").focus()
|
|
202
|
+
else:
|
|
203
|
+
self.app.pop_screen()
|
|
204
|
+
|
|
205
|
+
def close(self) -> None:
|
|
206
|
+
if console := self.console():
|
|
207
|
+
console.close()
|
harbor/app.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""Harbor: your agents, each with exactly one sandbox.
|
|
2
|
+
|
|
3
|
+
Home lists every agent. `n` starts one, which creates its sandbox; `Enter` opens
|
|
4
|
+
an agent's view (results, artifacts, logs, and a shell, with a message bar).
|
|
5
|
+
Closing an agent deletes its sandbox. Each sandbox stops itself after it sits
|
|
6
|
+
idle (`auto_stop_minutes`), and Harbor wakes it whenever you need it up.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import webbrowser
|
|
12
|
+
from dataclasses import replace
|
|
13
|
+
from functools import partial
|
|
14
|
+
|
|
15
|
+
from textual import work
|
|
16
|
+
from textual.app import App, ComposeResult
|
|
17
|
+
from textual.binding import Binding
|
|
18
|
+
from textual.command import CommandPalette
|
|
19
|
+
from textual.containers import Horizontal, Vertical
|
|
20
|
+
from textual.screen import ModalScreen
|
|
21
|
+
from textual.widgets import Button, Footer, Header, Input, Label
|
|
22
|
+
|
|
23
|
+
from harbor.agent_form import AgentForm
|
|
24
|
+
from harbor.agent_view import AgentScreen
|
|
25
|
+
from harbor.boat import Boat
|
|
26
|
+
from harbor.config import Settings
|
|
27
|
+
from harbor.console import Console
|
|
28
|
+
from harbor.core import Box, Order, error_text
|
|
29
|
+
from harbor.dashboard import Dashboard
|
|
30
|
+
from harbor.find import Navigate
|
|
31
|
+
from harbor.local import pin, public_key, ssh_command
|
|
32
|
+
from harbor.view import Pick, search_text
|
|
33
|
+
|
|
34
|
+
APPROVE = "Approved. Go ahead."
|
|
35
|
+
DENY = "Denied. Don't do that."
|
|
36
|
+
RESUME_PROMPT = "Continue where you left off."
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Ask(ModalScreen[str | None]):
|
|
40
|
+
"""One-line question. Enter answers, Escape cancels."""
|
|
41
|
+
|
|
42
|
+
BINDINGS = [Binding("escape", "dismiss", "Cancel")]
|
|
43
|
+
|
|
44
|
+
def __init__(self, question: str, value: str = ""):
|
|
45
|
+
super().__init__()
|
|
46
|
+
self.question = question
|
|
47
|
+
self.value = value
|
|
48
|
+
|
|
49
|
+
def compose(self) -> ComposeResult:
|
|
50
|
+
with Vertical(id="ask"):
|
|
51
|
+
yield Label(self.question)
|
|
52
|
+
yield Input(value=self.value)
|
|
53
|
+
|
|
54
|
+
def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
55
|
+
event.stop()
|
|
56
|
+
self.dismiss(event.value.strip() or None)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Confirm(ModalScreen[bool]):
|
|
60
|
+
"""Yes or no. Cancel has focus, so a stray Enter changes nothing. y confirms."""
|
|
61
|
+
|
|
62
|
+
BINDINGS = [Binding("y", "answer(True)", "Yes"), Binding("n", "answer(False)", "No"),
|
|
63
|
+
Binding("escape", "answer(False)", "Cancel"),
|
|
64
|
+
Binding("left,right", "app.focus_next", "Switch", show=False)]
|
|
65
|
+
|
|
66
|
+
def __init__(self, question: str, yes: str):
|
|
67
|
+
super().__init__()
|
|
68
|
+
self.question, self.yes = question, yes
|
|
69
|
+
|
|
70
|
+
def compose(self) -> ComposeResult:
|
|
71
|
+
with Vertical(id="confirm"):
|
|
72
|
+
yield Label(self.question)
|
|
73
|
+
with Horizontal(classes="buttons"):
|
|
74
|
+
yield Button(self.yes, variant="error", id="yes")
|
|
75
|
+
yield Button("Cancel", id="no")
|
|
76
|
+
|
|
77
|
+
def on_mount(self) -> None:
|
|
78
|
+
self.query_one("#no").focus()
|
|
79
|
+
|
|
80
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
81
|
+
self.dismiss(event.button.id == "yes")
|
|
82
|
+
|
|
83
|
+
def action_answer(self, yes: bool) -> None:
|
|
84
|
+
self.dismiss(yes)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Harbor(App):
|
|
88
|
+
TITLE = "Harbor"
|
|
89
|
+
COMMANDS = App.COMMANDS | {Navigate}
|
|
90
|
+
CSS = """
|
|
91
|
+
#dashboard { height: 1fr; }
|
|
92
|
+
#metrics { height: 5; }
|
|
93
|
+
.metric { width: 1fr; height: 5; border: round $panel-lighten-2; text-align: center;
|
|
94
|
+
content-align: center middle; }
|
|
95
|
+
#agents { height: 1fr; border: round $panel-lighten-2; }
|
|
96
|
+
#agent-info { height: 1; padding: 0 1; }
|
|
97
|
+
#tabs { height: 1fr; }
|
|
98
|
+
#tabs OptionList { height: 1fr; border: none; }
|
|
99
|
+
#result { width: 90%; height: 85%; padding: 1 2; background: $panel; border: tall $accent; }
|
|
100
|
+
ResultScreen { align: center middle; }
|
|
101
|
+
Ask, Confirm { align: center middle; }
|
|
102
|
+
#confirm { width: 70; height: auto; padding: 1 2; background: $panel; border: tall $error; }
|
|
103
|
+
#confirm .buttons { height: auto; margin-top: 1; align: right middle; }
|
|
104
|
+
#confirm Button { margin-left: 2; }
|
|
105
|
+
#ask { width: 70; height: auto; padding: 1 2; background: $panel; border: tall $accent; }
|
|
106
|
+
AgentForm { align: center middle; }
|
|
107
|
+
#agent-form { width: 80; height: auto; padding: 1 2; background: $panel; border: tall $accent; }
|
|
108
|
+
#agent-form #title { text-style: bold; margin-bottom: 1; }
|
|
109
|
+
#agent-form .hint { color: $text-muted; margin-top: 1; }
|
|
110
|
+
"""
|
|
111
|
+
BINDINGS = [
|
|
112
|
+
Binding("n", "new_agent", "New agent"),
|
|
113
|
+
Binding("C", "copy", "Copy"),
|
|
114
|
+
Binding("slash", "command_palette", "Find"),
|
|
115
|
+
Binding("g", "refresh", "Refresh"),
|
|
116
|
+
Binding("q", "quit", "Quit"),
|
|
117
|
+
]
|
|
118
|
+
|
|
119
|
+
def __init__(self, boat: Boat, settings: Settings, poll_seconds: float = 5.0):
|
|
120
|
+
super().__init__()
|
|
121
|
+
self.boat = boat
|
|
122
|
+
self.settings = settings
|
|
123
|
+
self.poll_seconds = poll_seconds
|
|
124
|
+
self.last = Order(prompt="", provider="") # the form remembers your provider and model
|
|
125
|
+
self.repos: list[str] = [] # owner/name, from gh
|
|
126
|
+
self.fleet: list[Pick] = [] # one per sandbox, from the last refresh
|
|
127
|
+
self.results: dict[tuple, tuple] = {} # (agent id, prompts, running) -> its results
|
|
128
|
+
self.views: dict[str, AgentScreen] = {} # sandbox id -> its agent's view, kept
|
|
129
|
+
|
|
130
|
+
def compose(self) -> ComposeResult:
|
|
131
|
+
yield Header()
|
|
132
|
+
yield Dashboard(id="dashboard")
|
|
133
|
+
yield Footer()
|
|
134
|
+
|
|
135
|
+
def on_mount(self) -> None:
|
|
136
|
+
self.reload()
|
|
137
|
+
self.load_repos()
|
|
138
|
+
self.set_interval(self.poll_seconds, self.reload)
|
|
139
|
+
|
|
140
|
+
def on_unmount(self) -> None:
|
|
141
|
+
for view in self.views.values():
|
|
142
|
+
view.close()
|
|
143
|
+
|
|
144
|
+
# Loading
|
|
145
|
+
|
|
146
|
+
def _call(self, fn, *args):
|
|
147
|
+
"""Run a Boat call in a worker thread. Show failures instead of crashing."""
|
|
148
|
+
try:
|
|
149
|
+
return True, fn(*args)
|
|
150
|
+
except Exception as error: # noqa: BLE001 - every API failure goes to the user
|
|
151
|
+
self.call_from_thread(self.notify, error_text(error), title="Harbor", severity="error")
|
|
152
|
+
return False, None
|
|
153
|
+
|
|
154
|
+
@work(thread=True, group="repos")
|
|
155
|
+
def load_repos(self) -> None:
|
|
156
|
+
ok, repos = self._call(self.settings.repos)
|
|
157
|
+
self.repos = repos if ok else []
|
|
158
|
+
|
|
159
|
+
def _pick_for(self, box: Box) -> Pick:
|
|
160
|
+
"""The sandbox with its agent, and every reply that agent wrote."""
|
|
161
|
+
ok, agent = self._call(self.boat.agent_of, box)
|
|
162
|
+
if not (ok and agent):
|
|
163
|
+
return Pick(box)
|
|
164
|
+
turn = (agent.id, agent.prompts, agent.running)
|
|
165
|
+
if turn not in self.results:
|
|
166
|
+
ok, results = self._call(self.boat.results, box.id, agent.id)
|
|
167
|
+
if not ok:
|
|
168
|
+
return Pick(box, agent)
|
|
169
|
+
self.results[turn] = tuple(results)
|
|
170
|
+
return Pick(box, replace(agent, results=self.results[turn]))
|
|
171
|
+
|
|
172
|
+
@work(thread=True, exclusive=True, group="load")
|
|
173
|
+
def reload(self) -> None:
|
|
174
|
+
ok, boxes = self._call(self.boat.boxes)
|
|
175
|
+
if ok:
|
|
176
|
+
self.call_from_thread(self._show_fleet, [self._pick_for(box) for box in boxes])
|
|
177
|
+
|
|
178
|
+
def _show_fleet(self, fleet: list[Pick]) -> None:
|
|
179
|
+
"""New data everywhere: Home, and every agent view."""
|
|
180
|
+
self.fleet = fleet
|
|
181
|
+
self.query_one(Dashboard).show(fleet)
|
|
182
|
+
for pick in fleet:
|
|
183
|
+
if view := self.views.get(pick.box.id):
|
|
184
|
+
view.update(pick)
|
|
185
|
+
|
|
186
|
+
# Screens
|
|
187
|
+
|
|
188
|
+
def on_dashboard_opened(self, message: Dashboard.Opened) -> None:
|
|
189
|
+
self.open_agent(message.pick.box.id)
|
|
190
|
+
|
|
191
|
+
def open_agent(self, box_id: str) -> AgentScreen | None:
|
|
192
|
+
"""Open an agent's view, made once and kept, so its shell lives while you're away."""
|
|
193
|
+
pick = next((p for p in self.fleet if p.box.id == box_id), None)
|
|
194
|
+
if pick is None:
|
|
195
|
+
return None
|
|
196
|
+
if box_id not in self.views:
|
|
197
|
+
self.views[box_id] = AgentScreen(pick, self.boat)
|
|
198
|
+
self.install_screen(self.views[box_id], name=f"agent-{box_id}")
|
|
199
|
+
while len(self.screen_stack) > 1:
|
|
200
|
+
self.pop_screen()
|
|
201
|
+
self.push_screen(f"agent-{box_id}")
|
|
202
|
+
return self.views[box_id]
|
|
203
|
+
|
|
204
|
+
def entries(self) -> list[tuple[str, str, object]]:
|
|
205
|
+
"""What search offers: the commands for the agent on screen, the global commands,
|
|
206
|
+
every agent, and a shell for every agent whose sandbox is up."""
|
|
207
|
+
under = self.screen_stack[-2] if isinstance(self.screen, CommandPalette) else self.screen
|
|
208
|
+
found = under.commands() if isinstance(under, AgentScreen) else []
|
|
209
|
+
found += [("new agent", "start an agent with its own sandbox (n)", self.action_new_agent),
|
|
210
|
+
("refresh", "fetch everything again (g)", self.action_refresh)]
|
|
211
|
+
for pick in self.fleet:
|
|
212
|
+
text = search_text(pick) if pick.agent else f"sandbox {pick.box.name}"
|
|
213
|
+
found.append((text, "open", partial(self.open_agent, pick.box.id)))
|
|
214
|
+
if pick.shell:
|
|
215
|
+
found.append((f"shell {pick.box.name}", "a shell inside Harbor",
|
|
216
|
+
partial(self.open_shell, pick.box.id)))
|
|
217
|
+
return found
|
|
218
|
+
|
|
219
|
+
def open_shell(self, box_id: str) -> None:
|
|
220
|
+
if self.open_agent(box_id):
|
|
221
|
+
self.call_after_refresh(self.action_shell)
|
|
222
|
+
|
|
223
|
+
def action_copy(self) -> None:
|
|
224
|
+
"""Copy what the screen is showing: a reply, an artifact, a log, or an id."""
|
|
225
|
+
source = self.screen if hasattr(self.screen, "copy_text") else self.query_one(Dashboard)
|
|
226
|
+
text = source.copy_text()
|
|
227
|
+
if not text:
|
|
228
|
+
self.notify("Nothing to copy here.", severity="warning")
|
|
229
|
+
return
|
|
230
|
+
self.copy_to_clipboard(text) # the terminal's clipboard (OSC 52), where it works
|
|
231
|
+
if shutil.which("pbcopy"): # macOS, in any terminal
|
|
232
|
+
subprocess.run(["pbcopy"], input=text, text=True, check=False)
|
|
233
|
+
self.notify(f"Copied {len(text)} characters.")
|
|
234
|
+
|
|
235
|
+
# The target
|
|
236
|
+
|
|
237
|
+
def _pick(self) -> Pick | None:
|
|
238
|
+
"""The agent on screen, with its sandbox. Home has none."""
|
|
239
|
+
return self.screen.target if isinstance(self.screen, AgentScreen) else None
|
|
240
|
+
|
|
241
|
+
def _agent(self) -> Pick | None:
|
|
242
|
+
pick = self._pick()
|
|
243
|
+
return pick if pick and pick.agent else None
|
|
244
|
+
|
|
245
|
+
def _waiting(self) -> Pick | None:
|
|
246
|
+
"""The agent on screen, if its turn is over. A working agent gets steered instead."""
|
|
247
|
+
p = self._agent()
|
|
248
|
+
if p and p.agent.running:
|
|
249
|
+
self.notify("It's still working. Steer it with t.", severity="warning")
|
|
250
|
+
return None
|
|
251
|
+
return p
|
|
252
|
+
|
|
253
|
+
# Doing things
|
|
254
|
+
|
|
255
|
+
def _ask(self, question: str, then, value: str = "") -> None:
|
|
256
|
+
self.push_screen(Ask(question, value), lambda answer: answer and then(answer))
|
|
257
|
+
|
|
258
|
+
@work(thread=True)
|
|
259
|
+
def _act(self, done: str, fn, *args) -> None:
|
|
260
|
+
ok, _ = self._call(fn, *args)
|
|
261
|
+
if ok:
|
|
262
|
+
self.call_from_thread(self.notify, done)
|
|
263
|
+
self.call_from_thread(self.reload)
|
|
264
|
+
|
|
265
|
+
def _tell(self, done: str, pick: Pick, text: str) -> None:
|
|
266
|
+
"""Send the agent a message, waking its sandbox first if it's asleep."""
|
|
267
|
+
self._act(done, self._wake_and_prompt, pick, text)
|
|
268
|
+
|
|
269
|
+
def _wake_and_prompt(self, pick: Pick, text: str) -> None:
|
|
270
|
+
self.boat.wake(pick.box.id)
|
|
271
|
+
self.boat.prompt(pick.box.id, pick.agent, text)
|
|
272
|
+
|
|
273
|
+
def action_refresh(self) -> None:
|
|
274
|
+
self.reload()
|
|
275
|
+
|
|
276
|
+
def action_new_agent(self) -> None:
|
|
277
|
+
"""A new agent, with its own new sandbox: repo, provider, model, prompt."""
|
|
278
|
+
def start(order: Order | None) -> None:
|
|
279
|
+
if order:
|
|
280
|
+
self.last = replace(self.last, provider=order.provider, model=order.model)
|
|
281
|
+
self.notify("Starting an agent. Its sandbox is being made, which takes a moment.")
|
|
282
|
+
self._act("Agent started", self.boat.start_agent, order,
|
|
283
|
+
self.settings.auto_stop_seconds)
|
|
284
|
+
form = AgentForm("New agent", self.last, self.boat.providers, self.repos)
|
|
285
|
+
self.push_screen(form, start)
|
|
286
|
+
|
|
287
|
+
def action_stop_agent(self) -> None:
|
|
288
|
+
if p := self._agent():
|
|
289
|
+
self._act("Agent stopped", self.boat.interrupt, p.box.id, p.agent.id)
|
|
290
|
+
|
|
291
|
+
def action_continue_agent(self) -> None:
|
|
292
|
+
if p := self._waiting():
|
|
293
|
+
self._tell("Agent continued", p, RESUME_PROMPT)
|
|
294
|
+
|
|
295
|
+
def action_prompt(self) -> None:
|
|
296
|
+
if p := self._agent():
|
|
297
|
+
self._ask("Feedback for the agent", lambda text: self._tell("Feedback sent", p, text))
|
|
298
|
+
|
|
299
|
+
def action_approve(self) -> None:
|
|
300
|
+
if p := self._waiting():
|
|
301
|
+
self._tell("Approved", p, APPROVE)
|
|
302
|
+
|
|
303
|
+
def action_deny(self) -> None:
|
|
304
|
+
if p := self._waiting():
|
|
305
|
+
self.push_screen(Ask("Why not? (optional, Enter to skip)"),
|
|
306
|
+
lambda reason: self._tell("Denied", p, f"{DENY} {reason or ''}".strip()))
|
|
307
|
+
|
|
308
|
+
def action_steer(self) -> None:
|
|
309
|
+
if p := self._agent():
|
|
310
|
+
self._ask("Steer the running turn", lambda text: self._act(
|
|
311
|
+
"Steer sent", self.boat.steer, p.box.id, p.agent.id, text))
|
|
312
|
+
|
|
313
|
+
@work(thread=True)
|
|
314
|
+
def action_close_agent(self) -> None:
|
|
315
|
+
"""Close the agent: its sandbox is deleted, and with it anything not pushed."""
|
|
316
|
+
pick = self.call_from_thread(self._pick)
|
|
317
|
+
if not pick:
|
|
318
|
+
return
|
|
319
|
+
changed = []
|
|
320
|
+
if pick.box.live:
|
|
321
|
+
ok, items = self._call(self.boat.artifacts, pick.box.id)
|
|
322
|
+
changed = [a.title for a in items if a.kind == "diff"] if ok else []
|
|
323
|
+
warning = f"\n\nUnpushed changes in: {', '.join(changed)}." if changed else ""
|
|
324
|
+
question = f"Close this agent? Its sandbox {pick.box.name} is deleted for good.{warning}"
|
|
325
|
+
dialog = Confirm(question, "Close agent")
|
|
326
|
+
self.call_from_thread(self.push_screen, dialog, lambda yes: yes and self._close(pick))
|
|
327
|
+
|
|
328
|
+
def _close(self, pick: Pick) -> None:
|
|
329
|
+
self._act(f"Closed. Deleting {pick.box.name}", self.boat.delete, pick.box.id)
|
|
330
|
+
self.pop_screen()
|
|
331
|
+
self.uninstall_screen(f"agent-{pick.box.id}")
|
|
332
|
+
self.views.pop(pick.box.id).close()
|
|
333
|
+
|
|
334
|
+
@work(thread=True)
|
|
335
|
+
def action_shell(self) -> None:
|
|
336
|
+
"""The Shell tab: ssh into the agent's sandbox, inside Harbor. Wakes it first."""
|
|
337
|
+
pick, view = self.call_from_thread(lambda: (self._pick(), self.screen))
|
|
338
|
+
if not pick:
|
|
339
|
+
return
|
|
340
|
+
if view.console():
|
|
341
|
+
self.call_from_thread(view.show_shell)
|
|
342
|
+
return
|
|
343
|
+
if not pick.box.live:
|
|
344
|
+
self.call_from_thread(self.notify, "Waking its sandbox…")
|
|
345
|
+
ok, argv = self._call(self._ssh_argv, pick)
|
|
346
|
+
if ok:
|
|
347
|
+
self.call_from_thread(view.attach, Console(argv, f"shell {pick.box.name}"))
|
|
348
|
+
|
|
349
|
+
def _ssh_argv(self, pick: Pick) -> list[str]:
|
|
350
|
+
self.boat.wake(pick.box.id)
|
|
351
|
+
key = self.settings.key
|
|
352
|
+
target = self.boat.ssh(pick.box.id, public_key(key))
|
|
353
|
+
return ssh_command(target, key, pinned=pin(target))
|
|
354
|
+
|
|
355
|
+
@work(thread=True)
|
|
356
|
+
def action_desktop(self) -> None:
|
|
357
|
+
pick = self.call_from_thread(self._pick)
|
|
358
|
+
if not pick:
|
|
359
|
+
return
|
|
360
|
+
self._call(self.boat.wake, pick.box.id)
|
|
361
|
+
ok, url = self._call(self.boat.desktop_url, pick.box.id)
|
|
362
|
+
if ok and url:
|
|
363
|
+
webbrowser.open(url)
|
|
364
|
+
elif ok:
|
|
365
|
+
self.call_from_thread(self.notify, "Nothing to open yet. Try again.")
|