coder-agent 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.
Files changed (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
coderagent/ui/tui.py ADDED
@@ -0,0 +1,610 @@
1
+ """The terminal interface.
2
+
3
+ The core of the agent knows nothing about the screen: it publishes events and the
4
+ interface listens to them. The turn itself runs in a thread, so the screen stays
5
+ alive while the model is thinking.
6
+ """
7
+
8
+ import logging
9
+ import threading
10
+ import time
11
+ from pathlib import Path
12
+
13
+ from textual.app import App, ComposeResult
14
+ from textual.containers import VerticalScroll
15
+ from textual.widgets import Input, Tree
16
+
17
+ from coderagent.config.schema import Config
18
+ from coderagent.core.content import describe_message
19
+ from coderagent.core.events import Event, EventBus, EventType
20
+ from coderagent.core.loop import stop_note
21
+ from coderagent.core.sandbox import describe
22
+ from coderagent.core.session import SessionStore
23
+ from coderagent.models import warm_up_litellm
24
+ from coderagent.run import build_loop, build_store, remember_capability
25
+ from coderagent.tools.permissions import ApprovalDecision
26
+ from coderagent.ui.commands import CommandContext
27
+ from coderagent.ui.commands import run as run_command
28
+ from coderagent.ui.commands.resume import resume as resume_session
29
+ from coderagent.ui.notify import TITLE, escape_sequence, run_notifier
30
+ from coderagent.ui.widgets import (
31
+ ApprovalPrompt,
32
+ FileTree,
33
+ MarkdownMessage,
34
+ MessageBlock,
35
+ StatusBar,
36
+ TodoPanel,
37
+ ToolCard,
38
+ WorkingDots,
39
+ )
40
+ from coderagent.ui.widgets.diff_view import prospective_diff
41
+ from coderagent.ui.widgets.path_suggester import PathSuggester
42
+ from coderagent.ui.widgets.session_picker import SessionPicker
43
+
44
+ WRITE_TOOLS = {"write", "edit", "multi_edit", "apply_patch"}
45
+ logger = logging.getLogger("coderagent.ui")
46
+
47
+
48
+ class TUIAprover:
49
+ """Asks the user, through the interface, whether a tool may run."""
50
+
51
+ def __init__(self, bus: EventBus, timeout: int = 0) -> None:
52
+ self.bus = bus
53
+ self.timeout = timeout
54
+ self._events: dict[str, threading.Event] = {}
55
+ self._decisions: dict[str, ApprovalDecision] = {}
56
+ self._counter = 0
57
+
58
+ def request(self, tool: str, params: dict, reason: str) -> ApprovalDecision:
59
+ """Wait until the user answers."""
60
+ self._counter += 1
61
+ key = str(self._counter)
62
+ event = threading.Event()
63
+ self._events[key] = event
64
+ self.bus.publish(
65
+ Event(
66
+ type=EventType.APPROVAL_REQUEST,
67
+ session_id="",
68
+ timestamp=time.time(),
69
+ payload={"id": key, "tool": tool, "params": params, "reason": reason},
70
+ )
71
+ )
72
+ event.wait(self.timeout or None)
73
+ self._events.pop(key, None)
74
+ return self._decisions.pop(key, ApprovalDecision.DENY)
75
+
76
+ def answer(self, key: str, decision: ApprovalDecision) -> None:
77
+ """Give the answer of the user to the waiting tool."""
78
+ self._decisions[key] = decision
79
+ event = self._events.get(key)
80
+ if event is not None:
81
+ event.set()
82
+
83
+
84
+ class CoderApp(App):
85
+ """The application: the conversation, the status bar and the input."""
86
+
87
+ TITLE = "coder"
88
+ CSS = """
89
+ #conversation {
90
+ height: 1fr;
91
+ padding: 0 1;
92
+ }
93
+ #todos {
94
+ dock: bottom;
95
+ }
96
+ #files {
97
+ dock: left;
98
+ width: 34;
99
+ height: 1fr;
100
+ border: round $panel;
101
+ background: $panel;
102
+ }
103
+ """
104
+ BINDINGS = [
105
+ ("ctrl+c", "interrupt", "Interrupt"),
106
+ ("ctrl+q", "quit", "Quit"),
107
+ ("ctrl+o", "sessions", "Sessions"),
108
+ ("ctrl+t", "files", "Files"),
109
+ ]
110
+
111
+ def __init__(
112
+ self,
113
+ config: Config,
114
+ cwd: Path,
115
+ *,
116
+ bus: EventBus | None = None,
117
+ approver=None,
118
+ session=None,
119
+ store: SessionStore | None = None,
120
+ loop=None,
121
+ ) -> None:
122
+ super().__init__()
123
+ self.config = config
124
+ self.cwd = Path(cwd)
125
+ self.bus = bus or EventBus()
126
+ self.approver = approver or TUIAprover(self.bus, config.ui.approval_timeout)
127
+ self.store = store or build_store(config)
128
+ self.loop = loop or build_loop(
129
+ config,
130
+ self.cwd,
131
+ bus=self.bus,
132
+ approver=self.approver,
133
+ store=self.store,
134
+ session=session,
135
+ remember=remember_capability,
136
+ )
137
+ self.cards: dict[str, ToolCard] = {}
138
+ self.current: MessageBlock | None = None
139
+ """The message the agent is writing right now."""
140
+ self.pending_approval: ApprovalPrompt | None = None
141
+ self.approval_id = ""
142
+ self.working: WorkingDots | None = None
143
+ """The dots that say the agent is still working."""
144
+ self.turn_running = threading.Event()
145
+ self.interrupted = threading.Event()
146
+ self.alive = True
147
+ """False when the interface is gone; the events are dropped then."""
148
+ self.history: list[str] = []
149
+ """The messages the user sent, the oldest first."""
150
+ self.history_index: int | None = None
151
+ """Where in the history the user is; None is the message being written."""
152
+ self.draft = ""
153
+ """The message that was being written when the user went back in the history."""
154
+ self.last_answer = ""
155
+ """The last thing the agent said; the notification tells that much."""
156
+
157
+ def compose(self) -> ComposeResult:
158
+ yield FileTree(self.cwd, self.loop.policy.roots(), id="files")
159
+ yield StatusBar(id="status")
160
+ yield VerticalScroll(id="conversation")
161
+ yield TodoPanel(id="todos")
162
+ yield Input(
163
+ placeholder="输入消息… (/help 查看命令)",
164
+ id="input",
165
+ suggester=PathSuggester(self.cwd),
166
+ )
167
+
168
+ def on_mount(self) -> None:
169
+ self._subscribe()
170
+ self._update_status()
171
+ self._say_pending()
172
+ self.query_one("#input", Input).focus()
173
+ self.call_after_refresh(warm_up_litellm)
174
+ """The screen is up: litellm loads while the user reads it and writes."""
175
+
176
+ def _say_pending(self) -> None:
177
+ """Say that the project has code that is not used, so that it is no surprise."""
178
+ from coderagent.config.loader import pending_code
179
+
180
+ pending = pending_code(self.cwd, self.loop.context.user_home)
181
+ if pending:
182
+ self._add_message(
183
+ "notice",
184
+ f"The project has code that waits for a decision of the user: {', '.join(pending.values())}. "
185
+ "It is not used. Run /trust to see it.",
186
+ )
187
+
188
+ # -- the events of the core -------------------------------------------
189
+
190
+ def _subscribe(self) -> None:
191
+ bus = self.loop.bus
192
+ bus.subscribe(EventType.USER_MESSAGE, self._on_user_message)
193
+ bus.subscribe(EventType.ASSISTANT_MESSAGE, self._on_assistant_message)
194
+ bus.subscribe(EventType.TEXT_DELTA, self._on_text_delta)
195
+ bus.subscribe(EventType.REASONING, self._on_reasoning)
196
+ bus.subscribe(EventType.TOOL_CALL, self._on_tool_call)
197
+ bus.subscribe(EventType.TOOL_RESULT, self._on_tool_result)
198
+ bus.subscribe(EventType.APPROVAL_REQUEST, self._on_approval_request)
199
+ bus.subscribe(EventType.STATE_CHANGE, self._on_state_change)
200
+ bus.subscribe(EventType.ERROR, self._on_error)
201
+
202
+ def _on_user_message(self, event: Event) -> None:
203
+ self._ui(self._add_message, "user", describe_message(event.payload.get("content", "")))
204
+
205
+ def _on_assistant_message(self, event: Event) -> None:
206
+ message = event.payload.get("message") or {}
207
+ reasoning = (message.get("extra") or {}).get("reasoning", "")
208
+ self._ui(self._add_markdown, message.get("content", ""), reasoning)
209
+
210
+ def _on_text_delta(self, event: Event) -> None:
211
+ self._ui(self._append_text, event.payload.get("content", ""))
212
+
213
+ def _on_reasoning(self, event: Event) -> None:
214
+ self._ui(self._add_reasoning, event.payload.get("content", ""))
215
+
216
+ def _on_tool_call(self, event: Event) -> None:
217
+ for action in event.payload.get("actions", []):
218
+ self._ui(self._add_card, action)
219
+
220
+ def _on_tool_result(self, event: Event) -> None:
221
+ payload = event.payload
222
+ if "todos" in payload:
223
+ self._ui(self.query_one("#todos", TodoPanel).show_todos, payload.get("todos") or [])
224
+ return
225
+ self._ui(self._finish_card, payload)
226
+
227
+ def _on_approval_request(self, event: Event) -> None:
228
+ self._ui(self._show_approval, event.payload)
229
+
230
+ def _on_state_change(self, event: Event) -> None:
231
+ payload = event.payload
232
+ if payload.get("model"):
233
+ self._ui(
234
+ self._add_message,
235
+ "notice",
236
+ f"Switched from {payload.get('previous', '?')} to {payload['model']}: {payload.get('reason', '')}",
237
+ )
238
+ state = payload.get("state", "")
239
+ self._ui(self._show_working if state == "thinking" else self._hide_working)
240
+ self._ui(self._update_status, state)
241
+
242
+ def _on_error(self, event: Event) -> None:
243
+ self._ui(self._add_message, "error", event.payload.get("error", ""))
244
+
245
+ # -- what the interface does with them -------------------------------
246
+
247
+ def _add_message(self, role: str, content: str, reasoning: str = "") -> None:
248
+ if role == "assistant":
249
+ self.last_answer = content
250
+ """The notification tells the user what the agent said."""
251
+ if role == "assistant" and self.current is not None:
252
+ self.current.set_content(content)
253
+ if reasoning:
254
+ self.current.add_reasoning(reasoning)
255
+ return
256
+ block = MessageBlock(role, content, reasoning)
257
+ self.query_one("#conversation", VerticalScroll).mount(block)
258
+ if role == "assistant":
259
+ self.current = block
260
+ elif role == "user":
261
+ self.current = None
262
+ """The next answer of the agent is a message of its own."""
263
+ block.scroll_visible()
264
+
265
+ def _add_command(self, text: str) -> None:
266
+ """The answer of a command: a block of its own, so the answer of the agent stays."""
267
+ block = MessageBlock("command", text)
268
+ self.query_one("#conversation", VerticalScroll).mount(block)
269
+ block.scroll_visible()
270
+
271
+ def _add_markdown(self, content: str, reasoning: str = "") -> None:
272
+ """The answer of the agent, rendered as Markdown.
273
+
274
+ The text is shown as it arrives and rendered when it is complete: half a
275
+ code block is not worth rendering.
276
+ """
277
+ self.last_answer = content
278
+ """The notification tells the user what the agent said."""
279
+ if not self.config.ui.markdown:
280
+ """The user asked for plain text, so the text that arrived stays."""
281
+ self._add_message("assistant", content, reasoning)
282
+ return
283
+ block = MarkdownMessage(content, reasoning)
284
+ conversation = self.query_one("#conversation", VerticalScroll)
285
+ if self.current is not None:
286
+ """The plain text that was shown while it arrived gives way to the Markdown."""
287
+ conversation.mount(block, before=self.current)
288
+ self.current.remove()
289
+ else:
290
+ conversation.mount(block)
291
+ self.current = None
292
+ block.scroll_visible()
293
+
294
+ def _append_text(self, text: str) -> None:
295
+ self._hide_working()
296
+ """The answer is coming: the dots have nothing left to say."""
297
+ if self.current is None:
298
+ self._add_message("assistant", "")
299
+ self.current.append(text)
300
+
301
+ def _add_reasoning(self, text: str) -> None:
302
+ self._hide_working()
303
+ if self.current is None:
304
+ self._add_message("assistant", "")
305
+ self.current.add_reasoning(text)
306
+
307
+ def _add_card(self, action: dict) -> None:
308
+ self._hide_working()
309
+ """The card of the tool says that the tool is running."""
310
+ card = ToolCard(action.get("tool", ""), action.get("args", {}), action.get("tool_call_id", ""))
311
+ self.cards[card.call_id] = card
312
+ self.query_one("#conversation", VerticalScroll).mount(card)
313
+ card.start()
314
+
315
+ def _show_working(self) -> None:
316
+ """Say that the agent is still working."""
317
+ if self.working is not None:
318
+ return
319
+ self.working = WorkingDots()
320
+ self.query_one("#conversation", VerticalScroll).mount(self.working)
321
+
322
+ def _hide_working(self) -> None:
323
+ """The agent said something; the dots go away."""
324
+ if self.working is None:
325
+ return
326
+ self.working.remove()
327
+ self.working = None
328
+
329
+ def _finish_card(self, payload: dict) -> None:
330
+ card = self.cards.get(payload.get("tool_call_id", ""))
331
+ if card is None:
332
+ return
333
+ card.finish(payload.get("content", ""), payload.get("is_error", False), payload.get("diff", ""))
334
+
335
+ def _show_approval(self, payload: dict) -> None:
336
+ tool = payload.get("tool", "")
337
+ params = payload.get("params", {})
338
+ diff = prospective_diff(tool, params, self.cwd) if tool in WRITE_TOOLS else ""
339
+ prompt = ApprovalPrompt(tool, params, payload.get("reason", ""), diff)
340
+ self.pending_approval = prompt
341
+ self.approval_id = payload.get("id", "")
342
+ self.query_one("#conversation", VerticalScroll).mount(prompt)
343
+ self.query_one("#input", Input).disabled = True
344
+
345
+ def _update_status(self, state: str = "") -> None:
346
+ bar = self.query_one("#status", StatusBar)
347
+ context = self.loop.context
348
+ bar.update_status(
349
+ model=getattr(self.loop.model.backend, "model_name", self.config.model.model_name),
350
+ tokens=context.estimated_tokens(self.loop.tools),
351
+ window=context.config.context_window,
352
+ cost=self.loop.session.total_cost,
353
+ priced=self.loop.model.priced,
354
+ cwd=str(self.cwd),
355
+ mode=self.loop.executor.policy.mode.value,
356
+ state=state,
357
+ sandbox=describe(self.loop.sandbox, self.config.sandbox.type, self.config.sandbox.mode),
358
+ )
359
+
360
+ def _ui(self, callback, *args) -> None:
361
+ """Run something in the thread of the interface."""
362
+ if not self.alive:
363
+ return
364
+ if self._thread_id == threading.get_ident():
365
+ callback(*args)
366
+ return
367
+ try:
368
+ self.call_from_thread(callback, *args)
369
+ except Exception:
370
+ logger.debug("The interface is gone, the event is dropped", exc_info=True)
371
+
372
+ def on_unmount(self) -> None:
373
+ """The interface is gone; the events that still come are dropped."""
374
+ self.alive = False
375
+
376
+ # -- the input --------------------------------------------------------
377
+
378
+ def on_input_submitted(self, event: Input.Submitted) -> None:
379
+ text = event.value.strip()
380
+ event.input.value = ""
381
+ if not text:
382
+ return
383
+ self.history.append(text)
384
+ self.history_index = None
385
+ if text.startswith("/"):
386
+ self._run_command(text)
387
+ return
388
+ self.run_worker(lambda: self._run_turn(text), thread=True, exclusive=True)
389
+
390
+ def _show_history(self, key: str) -> None:
391
+ """Walk through the messages the user sent before, the way a shell does."""
392
+ if not self.history:
393
+ return
394
+ widget = self.query_one("#input", Input)
395
+ if self.history_index is None:
396
+ if key == "down":
397
+ return
398
+ self.draft = widget.value
399
+ self.history_index = len(self.history)
400
+ self.history_index += -1 if key == "up" else 1
401
+ if self.history_index < 0:
402
+ self.history_index = 0
403
+ if self.history_index >= len(self.history):
404
+ self.history_index = None
405
+ widget.value = self.draft
406
+ return
407
+ widget.value = self.history[self.history_index]
408
+ widget.cursor_position = len(widget.value)
409
+
410
+ def _run_turn(self, text: str | list[dict], purpose: str = "", session=None) -> None:
411
+ """The turn itself, in a thread."""
412
+ self.interrupted.clear()
413
+ self.turn_running.set()
414
+ self.last_answer = ""
415
+ self.loop.cancel = self.interrupted.is_set
416
+ try:
417
+ result = self.loop.run_turn(text, purpose, session)
418
+ except Exception as e:
419
+ self._ui(self._add_message, "error", f"{type(e).__name__}: {e}")
420
+ self._notify_terminal(f"{type(e).__name__}: {e}")
421
+ return
422
+ finally:
423
+ self.turn_running.clear()
424
+ self._ui(self._hide_working)
425
+ """The turn is over: the dots have nothing left to say."""
426
+ if result.stop_reason == "interrupted":
427
+ self._ui(self._add_message, "error", "interrupted")
428
+ elif result.error:
429
+ self._ui(self._add_message, "error", result.error)
430
+ else:
431
+ """A turn that was cut off is not a failure, but the user has to know why."""
432
+ note = stop_note(result.stop_reason, self.loop.max_turns)
433
+ if note:
434
+ self._ui(self._add_message, "notice", note)
435
+ self._ui(self._refresh_files)
436
+ self._notify_terminal()
437
+
438
+ def _notify_terminal(self, body: str = "") -> None:
439
+ """Tell the terminal that the turn is over, in the way a terminal understands."""
440
+ if not self.config.ui.notifications:
441
+ return
442
+ body = body or self.last_answer or "The turn is over."
443
+ if not self.is_headless:
444
+ driver = getattr(self, "_driver", None)
445
+ if driver is not None:
446
+ driver.write(self._notification(body))
447
+ if self.config.ui.notify_command:
448
+ """The program of the user tells him too, in the way he wants it."""
449
+ run_notifier(self.config.ui.notify_command, TITLE, body)
450
+
451
+ def _notification(self, body: str = "") -> str:
452
+ """The sequence that tells the terminal that the turn is over."""
453
+ return escape_sequence(TITLE, body or self.last_answer or "The turn is over.")
454
+
455
+ def _run_command(self, line: str) -> None:
456
+ """A slash command: quick enough to run in the interface itself."""
457
+ if self.turn_running.is_set():
458
+ self._add_message("error", "The agent is working. Wait for it, or press ctrl+c to stop it.")
459
+ return
460
+ self._add_message("user", line)
461
+ """What the user typed is part of the conversation."""
462
+ context = CommandContext(
463
+ loop=self.loop,
464
+ session=self.loop.session,
465
+ store=self.store,
466
+ bus=self.loop.bus,
467
+ cwd=self.cwd,
468
+ config=self.config,
469
+ policy=self.loop.executor.policy,
470
+ checkpoints=self.loop.checkpoints,
471
+ mcp=self.loop.mcp,
472
+ output=self._add_command,
473
+ submit=self._submit_turn,
474
+ submit_side=self._submit_side,
475
+ quit=self.action_quit,
476
+ )
477
+ run_command(context, line)
478
+
479
+ def _submit_turn(self, text: str | list[dict], purpose: str = "") -> None:
480
+ """Run a turn for a command that needs the model."""
481
+ self.run_worker(lambda: self._run_turn(text, purpose), thread=True, exclusive=True)
482
+
483
+ def _submit_side(self, text: str, session) -> None:
484
+ """Run a turn in a conversation that goes aside."""
485
+ self.run_worker(lambda: self._run_turn(text, "", session), thread=True, exclusive=True)
486
+
487
+ # -- the keys ---------------------------------------------------------
488
+
489
+ def on_key(self, event) -> None:
490
+ prompt = self.pending_approval
491
+ if prompt is None:
492
+ if event.key in ("up", "down"):
493
+ self._show_history(event.key)
494
+ event.stop()
495
+ return
496
+ if event.key in ("left", "up"):
497
+ prompt.move(-1)
498
+ event.stop()
499
+ return
500
+ if event.key in ("right", "down"):
501
+ prompt.move(1)
502
+ event.stop()
503
+ return
504
+ if event.key == " ":
505
+ prompt.options.toggle(prompt.options.cursor)
506
+ event.stop()
507
+ return
508
+ if event.key.isdigit():
509
+ index = int(event.key) - 1
510
+ if 0 <= index < len(prompt.options.items):
511
+ prompt.options.toggle(index)
512
+ event.stop()
513
+ return
514
+ if event.key == "enter":
515
+ self._decide(prompt.selected_key)
516
+ event.stop()
517
+ return
518
+ if event.key in ("y", "n", "a"):
519
+ self._decide(event.key)
520
+ event.stop()
521
+
522
+ def _decide(self, key: str) -> None:
523
+ """Give the answer of the user to the waiting tool."""
524
+ decision = {"y": ApprovalDecision.ALLOW, "n": ApprovalDecision.DENY, "a": ApprovalDecision.ALWAYS}[key]
525
+ self.pending_approval.remove()
526
+ self.pending_approval = None
527
+ self.approver.answer(self.approval_id, decision)
528
+ input_widget = self.query_one("#input", Input)
529
+ input_widget.disabled = False
530
+ input_widget.focus()
531
+
532
+ def action_interrupt(self) -> None:
533
+ """Stop the turn that is running."""
534
+ if self.turn_running.is_set():
535
+ self.interrupted.set()
536
+ self._add_message("error", "interrupting…")
537
+ else:
538
+ self.exit()
539
+
540
+ def action_files(self) -> None:
541
+ """Show or hide the tree of the files that are open to the agent."""
542
+ tree = self.query_one("#files", FileTree)
543
+ tree.display = not tree.display
544
+ if tree.display:
545
+ tree.reload()
546
+
547
+ def _refresh_files(self) -> None:
548
+ """Read the directory again, so that the tree tells the truth."""
549
+ tree = self.query_one("#files", FileTree)
550
+ if tree.display:
551
+ tree.reload()
552
+
553
+ def on_tree_node_selected(self, event: Tree.NodeSelected) -> None:
554
+ """Put the file that was picked into the input, so it can be asked about."""
555
+ path = event.node.data
556
+ if not path:
557
+ return
558
+ widget = self.query_one("#input", Input)
559
+ widget.value = path
560
+ widget.focus()
561
+
562
+ def action_sessions(self) -> None:
563
+ """Show the sessions of this directory, so that another one can be continued."""
564
+ if self.turn_running.is_set():
565
+ self._add_message("error", "The agent is working. Wait for it, or press ctrl+c to stop it.")
566
+ return
567
+ sessions = self.store.list(self.cwd)
568
+ if not sessions:
569
+ self._add_message("error", "No sessions yet.")
570
+ return
571
+ self.push_screen(SessionPicker(sessions), self._continue_session)
572
+
573
+ def _continue_session(self, session_id: str | None) -> None:
574
+ """Continue the session that was picked."""
575
+ if not session_id:
576
+ return
577
+ self.loop.switch_to(resume_session(self.store, session_id))
578
+ self._show_session(session_id)
579
+ self._update_status()
580
+ self._add_command(f"Resumed {session_id}")
581
+
582
+ def _show_session(self, session_id: str) -> None:
583
+ """Show the conversation of the session, so that the screen is not a lie."""
584
+ self.query_one("#conversation", VerticalScroll).remove_children()
585
+ self.cards.clear()
586
+ self.current = None
587
+ self.working = None
588
+ """The dots of the session that was left belong to it."""
589
+ for event in self.store.events(session_id):
590
+ if event.type == EventType.USER_MESSAGE:
591
+ self._add_message("user", describe_message(event.payload.get("content", "")))
592
+ elif event.type == EventType.ASSISTANT_MESSAGE:
593
+ self.current = None
594
+ """Every message of the log is a message of its own."""
595
+ self._add_markdown((event.payload.get("message") or {}).get("content", ""))
596
+
597
+ def action_quit(self) -> None:
598
+ """Leave, after settling the session in the memory."""
599
+ from coderagent.run import settle
600
+
601
+ settle(self.loop, self.config, self.cwd)
602
+ self.exit()
603
+
604
+
605
+ def main(config: Config, cwd: Path, **kwargs) -> None:
606
+ """Run the interface."""
607
+ CoderApp(config, cwd, **kwargs).run()
608
+
609
+
610
+ __all__ = ["CoderApp", "TUIAprover", "main"]
@@ -0,0 +1,29 @@
1
+ """The widgets of the terminal interface."""
2
+
3
+ from coderagent.ui.widgets.approval_prompt import ApprovalPrompt, Options
4
+ from coderagent.ui.widgets.diff_view import DiffView, make_diff
5
+ from coderagent.ui.widgets.file_tree import FileTree
6
+ from coderagent.ui.widgets.markdown_message import MarkdownMessage
7
+ from coderagent.ui.widgets.message_block import MessageBlock
8
+ from coderagent.ui.widgets.path_suggester import PathSuggester
9
+ from coderagent.ui.widgets.session_picker import SessionPicker
10
+ from coderagent.ui.widgets.status_bar import StatusBar
11
+ from coderagent.ui.widgets.todo_panel import TodoPanel
12
+ from coderagent.ui.widgets.tool_card import ToolCard
13
+ from coderagent.ui.widgets.working_dots import WorkingDots
14
+
15
+ __all__ = [
16
+ "ApprovalPrompt",
17
+ "DiffView",
18
+ "FileTree",
19
+ "MarkdownMessage",
20
+ "MessageBlock",
21
+ "Options",
22
+ "PathSuggester",
23
+ "SessionPicker",
24
+ "StatusBar",
25
+ "TodoPanel",
26
+ "ToolCard",
27
+ "WorkingDots",
28
+ "make_diff",
29
+ ]