zenagent-py 0.2.2__tar.gz → 0.3.0__tar.gz

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 (121) hide show
  1. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/PKG-INFO +1 -1
  2. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/pyproject.toml +1 -1
  3. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/pyproject.toml.orig +1 -1
  4. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/__init__.py +1 -1
  5. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/agent/session.py +64 -0
  6. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/chat.py +176 -33
  7. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/commands.py +77 -3
  8. zenagent_py-0.3.0/zenagent/app/retry.py +58 -0
  9. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/sessions.py +23 -0
  10. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/support.py +45 -1
  11. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/views.py +23 -0
  12. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/completion.py +2 -0
  13. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/main.py +2 -2
  14. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/repl.py +21 -2
  15. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/app.py +95 -11
  16. zenagent_py-0.3.0/zenagent/cli/tui/history.py +82 -0
  17. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/screens/modals.py +24 -1
  18. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/status/presets.py +10 -1
  19. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/status/segments.py +29 -0
  20. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/theme.tcss +22 -0
  21. zenagent_py-0.3.0/zenagent/cli/tui/widgets/attachments.py +58 -0
  22. zenagent_py-0.3.0/zenagent/cli/tui/widgets/error_banner.py +48 -0
  23. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/prompt_input.py +2 -0
  24. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/rows.py +14 -1
  25. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/tool_card.py +73 -6
  26. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/transcript.py +16 -1
  27. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/README.md +0 -0
  28. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/agent/__init__.py +0 -0
  29. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/agent/agent.py +0 -0
  30. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/agent/loop.py +0 -0
  31. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/agent/validate.py +0 -0
  32. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/__init__.py +0 -0
  33. {zenagent_py-0.2.2/zenagent/cli → zenagent_py-0.3.0/zenagent/app}/compact.py +0 -0
  34. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/models.py +0 -0
  35. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/modes.py +0 -0
  36. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/permissions.py +0 -0
  37. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/runtime.py +0 -0
  38. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/app/slash_args.py +0 -0
  39. /zenagent_py-0.2.2/zenagent/cli/images.py → /zenagent_py-0.3.0/zenagent/attachments.py +0 -0
  40. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/catalog.yaml +0 -0
  41. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/__init__.py +0 -0
  42. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/doctor.py +0 -0
  43. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/exportcmd.py +0 -0
  44. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/keybindings.py +0 -0
  45. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/permissions.py +0 -0
  46. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/render.py +0 -0
  47. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/rpc.py +0 -0
  48. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/sessionscmd.py +0 -0
  49. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/theme.py +0 -0
  50. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/__init__.py +0 -0
  51. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/run.py +0 -0
  52. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/screens/palette.py +0 -0
  53. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/screens/secrets.py +0 -0
  54. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/status/__init__.py +0 -0
  55. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/command_hints.py +0 -0
  56. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/new_content.py +0 -0
  57. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/prompt_gutter.py +0 -0
  58. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/sidebar.py +0 -0
  59. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/status_band.py +0 -0
  60. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/welcome.py +0 -0
  61. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/tui/widgets/work_indicator.py +0 -0
  62. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/cli/usagecmd.py +0 -0
  63. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/config.py +0 -0
  64. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/context_files.py +0 -0
  65. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/crash.py +0 -0
  66. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/evals_runner.py +0 -0
  67. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/events.py +0 -0
  68. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/export.py +0 -0
  69. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/extensions.py +0 -0
  70. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/frontmatter.py +0 -0
  71. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/mcp/__init__.py +0 -0
  72. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/mcp/client.py +0 -0
  73. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/mcp/config.py +0 -0
  74. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/mcp/manager.py +0 -0
  75. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/project.py +0 -0
  76. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/__init__.py +0 -0
  77. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/anthropic_messages.py +0 -0
  78. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/catalog.py +0 -0
  79. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/compat.py +0 -0
  80. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/anthropic-badjson.txt +0 -0
  81. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/anthropic-text.txt +0 -0
  82. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/anthropic-thinking-toolcall.txt +0 -0
  83. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/badjson-toolcall.txt +0 -0
  84. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/deepseek-chat-live-text.request.json +0 -0
  85. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/deepseek-chat-live-text.txt +0 -0
  86. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/deepseek-chat-live-toolcall.request.json +0 -0
  87. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/deepseek-chat-live-toolcall.txt +0 -0
  88. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/deepseek-reasoner-live-thinking.request.json +0 -0
  89. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/deepseek-reasoner-live-thinking.txt +0 -0
  90. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/deepseek-reasoner.txt +0 -0
  91. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/google-text.txt +0 -0
  92. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/google-toolcall.txt +0 -0
  93. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/multi-tool-parallel.txt +0 -0
  94. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/openai-responses-text.txt +0 -0
  95. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/openai-responses-toolcall.txt +0 -0
  96. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/zai-glm-5.3-text+thinking.txt +0 -0
  97. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/fixtures/zai-glm-5.3-toolcall.txt +0 -0
  98. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/google_generative_ai.py +0 -0
  99. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/openai_completions.py +0 -0
  100. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/openai_responses.py +0 -0
  101. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/registry.py +0 -0
  102. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/providers/transport.py +0 -0
  103. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/retry.py +0 -0
  104. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/settings.py +0 -0
  105. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/skills.py +0 -0
  106. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/telemetry.py +0 -0
  107. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/templates.py +0 -0
  108. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/__init__.py +0 -0
  109. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/bash.py +0 -0
  110. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/fs.py +0 -0
  111. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/search.py +0 -0
  112. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/web/__init__.py +0 -0
  113. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/web/net.py +0 -0
  114. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/web/providers.py +0 -0
  115. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/web/query.py +0 -0
  116. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/web/registry.py +0 -0
  117. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/web/tools.py +0 -0
  118. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/tools/web/types.py +0 -0
  119. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/trace.py +0 -0
  120. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/types.py +0 -0
  121. {zenagent_py-0.2.2 → zenagent_py-0.3.0}/zenagent/usage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: zenagent-py
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: A minimal, Pythonic coding agent: streaming LLM client, async-generator agent loop, and terminal harness.
5
5
  Keywords: agent,llm,ai,cli,async,coding-agent
6
6
  Author: Justin Gao
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "zenagent-py"
3
- version = "0.2.2"
3
+ version = "0.3.0"
4
4
  description = "A minimal, Pythonic coding agent: streaming LLM client, async-generator agent loop, and terminal harness."
5
5
  readme = "README.md"
6
6
  keywords = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "zenagent-py"
3
- version = "0.2.2"
3
+ version = "0.3.0"
4
4
  description = "A minimal, Pythonic coding agent: streaming LLM client, async-generator agent loop, and terminal harness."
5
5
  readme = "README.md"
6
6
  keywords = ["agent", "llm", "ai", "cli", "async", "coding-agent"]
@@ -1,4 +1,4 @@
1
1
 
2
2
  from __future__ import annotations
3
3
 
4
- __version__ = "0.2.2"
4
+ __version__ = "0.3.0"
@@ -28,10 +28,12 @@ __all__ = [
28
28
  "brief",
29
29
  "latest_session",
30
30
  "list_sessions",
31
+ "read_session_pins",
31
32
  "read_session_titles",
32
33
  "session_path",
33
34
  "session_title",
34
35
  "sessions_dir",
36
+ "set_session_pin",
35
37
  "set_session_title",
36
38
  "truncate_last_turn",
37
39
  "unique_session_path",
@@ -41,6 +43,10 @@ __all__ = [
41
43
  #: append-only ``Message.to_json()`` and can still be replayed by other tools.
42
44
  TITLES_FILENAME = ".titles.json"
43
45
 
46
+ #: Pinned sessions live in a sibling sidecar (a JSON array of filenames), for
47
+ #: the same reason: the transcript format never changes for UI metadata.
48
+ PINS_FILENAME = ".pins.json"
49
+
44
50
  #: Stored display names are capped after whitespace normalization.
45
51
  TITLE_LIMIT = 80
46
52
 
@@ -209,6 +215,64 @@ def set_session_title(path: Path, title: str) -> str:
209
215
  return normalized
210
216
 
211
217
 
218
+ def _pins_path(directory: Path) -> Path:
219
+ return Path(directory) / PINS_FILENAME
220
+
221
+
222
+ def read_session_pins(directory: Path | None = None) -> set[str]:
223
+ """Pinned session filenames for one sessions directory.
224
+
225
+ Like the titles sidecar, a missing/corrupt/non-list file is an empty set:
226
+ pinning is a convenience and must never break session listing.
227
+ """
228
+ base = sessions_dir() if directory is None else Path(directory)
229
+ try:
230
+ data = json.loads(_pins_path(base).read_text(encoding="utf-8"))
231
+ except (OSError, ValueError):
232
+ return set()
233
+ if not isinstance(data, list):
234
+ return set()
235
+ return {name for name in data if isinstance(name, str) and name}
236
+
237
+
238
+ def _write_session_pins(directory: Path, pins: set[str]) -> None:
239
+ """Replace one directory's pins sidecar atomically."""
240
+ sidecar = _pins_path(directory)
241
+ sidecar.parent.mkdir(parents=True, exist_ok=True)
242
+ descriptor, temp_name = tempfile.mkstemp(
243
+ dir=sidecar.parent, prefix=f"{sidecar.name}.", suffix=".tmp"
244
+ )
245
+ try:
246
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
247
+ json.dump(sorted(pins), handle, ensure_ascii=False, indent=2)
248
+ handle.write("\n")
249
+ handle.flush()
250
+ os.fsync(handle.fileno())
251
+ os.replace(temp_name, sidecar)
252
+ except BaseException:
253
+ Path(temp_name).unlink(missing_ok=True)
254
+ raise
255
+
256
+
257
+ def set_session_pin(session_file: Path, pinned: bool) -> bool:
258
+ """Pin or unpin one saved session; returns the resulting state.
259
+
260
+ Raises ``ValueError`` for anything that is not a saved ``*.jsonl`` session
261
+ (pinning a nonexistent file would silently pollute the sidecar). The
262
+ transcript is never read or modified.
263
+ """
264
+ target = Path(session_file)
265
+ if target.suffix != ".jsonl" or not target.is_file():
266
+ raise ValueError(f"not a saved session file: {target}")
267
+ pins = read_session_pins(target.parent)
268
+ if pinned:
269
+ pins.add(target.name)
270
+ else:
271
+ pins.discard(target.name)
272
+ _write_session_pins(target.parent, pins)
273
+ return pinned
274
+
275
+
212
276
  def _title_from_messages(messages: list[Message]) -> str:
213
277
  """Brief of the first text user message; ``"(empty)"`` when there is none."""
214
278
  for message in messages:
@@ -3,15 +3,19 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import time
6
7
  from collections.abc import Callable
7
8
  from pathlib import Path
8
9
 
9
- from zenagent.agent.session import Session
10
+ from zenagent.app.compact import compact, should_auto_compact
11
+ from zenagent.app.retry import prepare_retry
10
12
  from zenagent.app.runtime import Runtime
13
+ from zenagent.app.support import cache_hit_ratio
11
14
  from zenagent.app.views import (
12
15
  MessageView,
13
16
  RunStatus,
14
17
  ToolCallView,
18
+ TranscriptNotice,
15
19
  args_preview,
16
20
  messages_to_views,
17
21
  usage_total,
@@ -38,9 +42,23 @@ class ChatController:
38
42
  self._transcript: list[MessageView | ToolCallView] = []
39
43
  self._current: MessageView | None = None
40
44
  self._cards: dict[str, ToolCallView] = {}
41
- self._follow_ups: list[str] = []
45
+ #: (text, images) pairs; images are captured when the turn is queued.
46
+ self._follow_ups: list[tuple[str, list[ImageContent]]] = []
42
47
  self._task: asyncio.Task | None = None
43
48
  self._running = False
49
+ #: True while an automatic compaction runs: the controller stays busy
50
+ #: so a submit queues instead of racing the summarizer (C2).
51
+ self._compacting = False
52
+ #: Last finished turn: wall time and output tokens (status segments).
53
+ self._turn_ms = 0
54
+ self._turn_output = 0
55
+ #: Provider failure from the last run, shown by the TUI's error banner.
56
+ self._last_error = ""
57
+ #: Out-of-band lines (compaction dividers, auto-compaction failures) the
58
+ #: frontend drains on refresh.
59
+ self._notices: list[TranscriptNotice] = []
60
+ #: Images attached with /image that will ride along with the next prompt.
61
+ self._attachments: list[ImageContent] = []
44
62
  runtime.agent.subscribe(self._on_event)
45
63
 
46
64
  # -- snapshots ----------------------------------------------------------
@@ -60,10 +78,15 @@ class ChatController:
60
78
  return RunStatus(
61
79
  model_id=agent.model.id,
62
80
  thinking=agent.thinking,
63
- running=self._running,
81
+ running=self._running or self._compacting,
64
82
  input_tokens=usage.input,
65
83
  output_tokens=usage.output,
66
84
  cache_read=usage.cache_read,
85
+ cache_write=usage.cache_write,
86
+ cache_hit_ratio=cache_hit_ratio(usage, agent.model.api),
87
+ turn_ms=self._turn_ms,
88
+ turn_output_tokens=self._turn_output,
89
+ last_error=self._last_error,
67
90
  cost=usage.cost.total,
68
91
  context_used=context_used,
69
92
  context_window=agent.model.context_window,
@@ -76,23 +99,74 @@ class ChatController:
76
99
 
77
100
  # -- commands -----------------------------------------------------------
78
101
 
79
- async def submit(self, text: str) -> None:
80
- """Start a run, or queue the text when one is already running."""
81
- if self._running:
82
- self.queue_follow_up(text)
102
+ async def submit(
103
+ self, text: str, *, images: list[ImageContent] | None = None
104
+ ) -> None:
105
+ """Start a run, or queue the text when one is already running.
106
+
107
+ ``images`` overrides the pending attachment list; otherwise whatever was
108
+ attached with ``/image`` rides along and is cleared once the run starts.
109
+ """
110
+ if self._running or self._compacting:
111
+ pending = list(images if images is not None else self._attachments)
112
+ if images is None:
113
+ self._attachments.clear()
114
+ self.queue_follow_up(text, pending)
83
115
  return
84
- self._task = asyncio.create_task(self._run(text))
116
+ pending = list(images if images is not None else self._attachments)
117
+ if images is None:
118
+ self._attachments.clear()
119
+ self._task = asyncio.create_task(self._run(text, pending))
120
+
121
+ @property
122
+ def attachments(self) -> list[ImageContent]:
123
+ """Pending images attached but not yet sent."""
124
+ return list(self._attachments)
125
+
126
+ def attach_image(self, block: ImageContent) -> None:
127
+ self._attachments.append(block)
128
+ self._notify()
129
+
130
+ def remove_attachment(self, index: int) -> None:
131
+ if 0 <= index < len(self._attachments):
132
+ del self._attachments[index]
133
+ self._notify()
134
+
135
+ def clear_attachments(self) -> None:
136
+ if self._attachments:
137
+ self._attachments.clear()
138
+ self._notify()
85
139
 
86
- def queue_follow_up(self, text: str) -> None:
140
+ def queue_follow_up(
141
+ self, text: str, images: list[ImageContent] | None = None
142
+ ) -> None:
143
+ """Queue a follow-up; ``images=None`` takes the pending attachments."""
87
144
  if not text.strip():
88
145
  return
89
- self._follow_ups.append(text)
146
+ pending = list(images if images is not None else self._attachments)
147
+ if images is None:
148
+ self._attachments.clear()
149
+ self._follow_ups.append((text, pending))
90
150
  self._notify()
91
151
 
92
152
  def clear_follow_ups(self) -> None:
93
153
  self._follow_ups.clear()
94
154
  self._notify()
95
155
 
156
+ def dequeue_follow_up(self) -> str | None:
157
+ """Take the most recently queued follow-up back out of the queue.
158
+
159
+ omp's dequeue semantics: the last thing you queued is the one you most
160
+ likely want to edit, so pop from the end. Returns ``None`` when empty.
161
+ """
162
+ if not self._follow_ups:
163
+ return None
164
+ text, images = self._follow_ups.pop()
165
+ if images:
166
+ self._attachments[:0] = images # put the images back in the composer
167
+ self._notify()
168
+ return text
169
+
96
170
  def steer(self, text: str) -> None:
97
171
  if text.strip():
98
172
  self.runtime.agent.steer(text)
@@ -102,6 +176,47 @@ class ChatController:
102
176
  self.runtime.agent.abort()
103
177
  self._notify()
104
178
 
179
+ def clear_last_error(self) -> None:
180
+ """Dismiss the provider-error banner (click on the dock row)."""
181
+ if self._last_error:
182
+ self._last_error = ""
183
+ self._notify()
184
+
185
+ def take_notices(self) -> list[TranscriptNotice]:
186
+ """Drain out-of-band lines the frontend should render (dividers, info)."""
187
+ notices = self._notices
188
+ self._notices = []
189
+ return notices
190
+
191
+ def _before_tokens(self) -> int:
192
+ last = self.runtime.guard.last_usage
193
+ if last is not None:
194
+ return last.input + last.cache_read
195
+ usage = usage_total(self.runtime.agent.messages)
196
+ return usage.input + usage.output
197
+
198
+ async def compact_now(self, *, force: bool = False) -> str | None:
199
+ """Summarize the transcript into a new session file; returns the notice.
200
+
201
+ Refuses mid-run (nested model calls would corrupt the transcript) and on
202
+ an empty transcript. ``force`` is the auto path: the controller already
203
+ owns the busy flag, so only the agent streaming check applies.
204
+ """
205
+ if not force and (self._running or self._compacting):
206
+ return None
207
+ if self.runtime.agent.is_streaming:
208
+ return None
209
+ if not self.runtime.agent.messages:
210
+ return None
211
+ before = self._before_tokens()
212
+ path = await compact(self.runtime.agent)
213
+ await self.runtime.switch_session(path)
214
+ self.reload_transcript()
215
+ text = f"compacted · {before:,} prompt tokens → summary session"
216
+ self._notices.append(TranscriptNotice("divider", text))
217
+ self._notify()
218
+ return text
219
+
105
220
  def reload_transcript(self) -> None:
106
221
  """Rebuild views from the current agent messages (after a session switch)."""
107
222
  from zenagent.app.views import messages_to_views
@@ -116,35 +231,24 @@ class ChatController:
116
231
  self._transcript.clear()
117
232
  self._cards.clear()
118
233
  self._current = None
234
+ self._attachments.clear()
119
235
  self._notify()
120
236
 
121
237
  def retry(self) -> str | None:
122
238
  """Drop everything after the last user message and run that turn again.
123
239
 
124
240
  The user message is dropped too and re-sent, so the transcript never
125
- ends up with two copies of the same prompt.
241
+ ends up with two copies of the same prompt. Shares the truncation logic
242
+ with the REPL through :func:`zenagent.app.retry.prepare_retry`.
126
243
  """
127
244
  if self._running:
128
245
  return None
129
- messages = list(self.runtime.agent.messages)
130
- index = next(
131
- (
132
- position
133
- for position in range(len(messages) - 1, -1, -1)
134
- if isinstance(messages[position], UserMessage)
135
- ),
136
- None,
137
- )
138
- if index is None or index == len(messages) - 1:
139
- return None # nothing answered yet
140
- text = _user_text(messages[index])
141
- if not text.strip():
246
+ prepared = prepare_retry(self.runtime.agent, self.runtime.session)
247
+ if prepared is None:
142
248
  return None
143
- truncated = messages[:index]
144
- self.runtime.agent.replace_messages(truncated)
145
- new_path = Session(Path(self.runtime.session.path)).rewrite(truncated)
146
- self.runtime.session = Session(new_path)
147
- self._transcript = messages_to_views(truncated)
249
+ text, new_session = prepared
250
+ self.runtime.session = new_session
251
+ self._transcript = messages_to_views(self.runtime.agent.messages)
148
252
  self._cards.clear()
149
253
  self._current = None
150
254
  self._task = asyncio.create_task(self._run(text))
@@ -158,21 +262,59 @@ class ChatController:
158
262
 
159
263
  # -- run loop -----------------------------------------------------------
160
264
 
161
- async def _run(self, text: str) -> None:
265
+ async def _run(self, text: str, images: list[ImageContent] | None = None) -> None:
162
266
  self._running = True
267
+ self._last_error = ""
163
268
  self._notify()
269
+ started = time.monotonic()
270
+ before_output = usage_total(self.runtime.agent.messages).output
164
271
  try:
165
- await self.runtime.agent.prompt(text)
272
+ await self.runtime.agent.prompt(text, images=images or None)
166
273
  finally:
167
- self._running = False
168
274
  self._current = None
275
+ self._turn_ms = int((time.monotonic() - started) * 1000)
276
+ self._turn_output = (
277
+ usage_total(self.runtime.agent.messages).output - before_output
278
+ )
279
+ if self.runtime.agent.termination == "error":
280
+ detail = self.runtime.agent.error_message
281
+ self._last_error = (
282
+ detail if detail and detail != "error" else "the run failed"
283
+ )
284
+ self._notify()
285
+ # Stay busy (running=True, task set) through the summarizer call so
286
+ # a submit during compaction queues instead of racing it. Queued
287
+ # turns go first: compress only between bursts (Review Focus #1).
288
+ if self.runtime.agent.termination != "aborted" and not self._follow_ups:
289
+ await self._maybe_auto_compact()
290
+ self._running = False
169
291
  self._task = None
170
292
  self._notify()
171
293
  if self._follow_ups and self.runtime.agent.termination != "aborted":
172
- self._task = asyncio.create_task(self._run(self._follow_ups.pop(0)))
294
+ text, images = self._follow_ups.pop(0)
295
+ self._task = asyncio.create_task(self._run(text, images))
173
296
  elif self._follow_ups:
174
297
  self._notify()
175
298
 
299
+ async def _maybe_auto_compact(self) -> None:
300
+ """One automatic compaction; failures become a transcript notice."""
301
+ if not should_auto_compact(
302
+ self.runtime.guard.last_usage,
303
+ self.runtime.agent.model.context_window,
304
+ ):
305
+ return
306
+ self._compacting = True
307
+ self._notify()
308
+ try:
309
+ await self.compact_now(force=True)
310
+ except Exception as exc: # noqa: BLE001 - never break the session
311
+ self._notices.append(
312
+ TranscriptNotice("info", f"auto-compaction failed: {exc}")
313
+ )
314
+ finally:
315
+ self._compacting = False
316
+ self._notify()
317
+
176
318
  # -- event → view models ------------------------------------------------
177
319
 
178
320
  def _on_event(self, event: AgentEvent) -> None:
@@ -205,6 +347,7 @@ class ChatController:
205
347
  card.is_error = bool(event.is_error)
206
348
  card.status = "error" if event.is_error else "ok"
207
349
  card.result_text = _result_text(event.result)
350
+ card.details = dict(getattr(event.result, "details", None) or {})
208
351
  card.duration_ms = event.duration_ms
209
352
  else:
210
353
  return
@@ -126,6 +126,28 @@ async def _rename(services: AppServices, argument: str) -> CommandResult:
126
126
  return CommandResult(message=f"renamed: {stored}")
127
127
 
128
128
 
129
+ @_command("pin", "pin or unpin the current session")
130
+ async def _pin(services: AppServices, argument: str) -> CommandResult:
131
+ from zenagent.agent.session import session_title
132
+
133
+ requested = argument.strip().lower()
134
+ current = services.sessions.current()
135
+ try:
136
+ if requested in ("on", "off"):
137
+ state = services.sessions.set_pin(current, requested == "on")
138
+ elif requested:
139
+ return CommandResult(
140
+ message=f"unknown pin argument: {requested} (use on|off)"
141
+ )
142
+ else:
143
+ state = services.sessions.toggle_pin(current)
144
+ except ValueError as exc:
145
+ return CommandResult(message=str(exc))
146
+ return CommandResult(
147
+ message=f"{'pinned' if state else 'unpinned'} {session_title(current)}"
148
+ )
149
+
150
+
129
151
  @_command("clear", "clear the visible conversation")
130
152
  async def _clear(services: AppServices, argument: str) -> CommandResult:
131
153
  services.chat.clear()
@@ -134,7 +156,48 @@ async def _clear(services: AppServices, argument: str) -> CommandResult:
134
156
 
135
157
  @_command("compact", "summarize the conversation now")
136
158
  async def _compact(services: AppServices, argument: str) -> CommandResult:
137
- return CommandResult(message="compaction runs after the current turn")
159
+ try:
160
+ message = await services.chat.compact_now()
161
+ except (ValueError, RuntimeError) as exc:
162
+ return CommandResult(message=f"compaction failed: {exc}")
163
+ return CommandResult(message=message or "nothing to compact", reset_transcript=True)
164
+
165
+
166
+ @_command("image", "attach an image for the next prompt (/image <path>)")
167
+ async def _image(services: AppServices, argument: str) -> CommandResult:
168
+ from pathlib import Path
169
+
170
+ from zenagent.attachments import read_image_argument
171
+
172
+ path = argument.strip()
173
+ if not path:
174
+ return CommandResult(message="usage: /image <path>")
175
+ model = services.runtime.agent.model
176
+ if not model.supports_vision:
177
+ return CommandResult(message=f"{model.id} does not accept images")
178
+ try:
179
+ block = read_image_argument(Path(path).expanduser())
180
+ except ValueError as exc:
181
+ return CommandResult(message=str(exc))
182
+ services.chat.attach_image(block)
183
+ return CommandResult(
184
+ message=f"attached {block.mime_type} ({len(services.chat.attachments)} pending)"
185
+ )
186
+
187
+
188
+ @_command("images", "list attached images, or /images clear")
189
+ async def _images(services: AppServices, argument: str) -> CommandResult:
190
+ if argument.strip() == "clear":
191
+ services.chat.clear_attachments()
192
+ return CommandResult(message="cleared attached images")
193
+ blocks = services.chat.attachments
194
+ if not blocks:
195
+ return CommandResult(message="no attached images")
196
+ rows = [
197
+ f"{position}. {block.mime_type} ({len(block.data)} base64 chars)"
198
+ for position, block in enumerate(blocks, start=1)
199
+ ]
200
+ return CommandResult(message="\n".join(rows))
138
201
 
139
202
 
140
203
  @_command("mcp", "reconnect MCP servers and refresh tools")
@@ -186,8 +249,8 @@ THINKING_LEVELS = ("off", "low", "medium", "high", "max")
186
249
 
187
250
  HOTKEYS_TEXT = """\
188
251
  enter send · shift+enter newline
189
- esc interrupt · ctrl+c clear draft · ctrl+d quit
190
- ctrl+q queue follow-up · ctrl+s steer · ctrl+x clear queue
252
+ esc interrupt · empty-draft double esc rewind · ctrl+c clear draft · ctrl+d quit
253
+ ctrl+q queue follow-up · alt+up dequeue · ctrl+s steer · ctrl+x clear queue
191
254
  ctrl+p next model · alt+p pick model · shift+tab thinking
192
255
  ctrl+o expand tools · ctrl+t hide thinking
193
256
  ctrl+k commands · ctrl+b info · pageup/pagedown scroll"""
@@ -208,6 +271,13 @@ async def _thinking(services: AppServices, argument: str) -> CommandResult:
208
271
  return CommandResult(message=f"thinking: {level}")
209
272
 
210
273
 
274
+ @_command("tools", "list the tools the model can call")
275
+ async def _tools(services: AppServices, argument: str) -> CommandResult:
276
+ from zenagent.app.support import describe_tools
277
+
278
+ return CommandResult(message=describe_tools(services.runtime.agent.tools))
279
+
280
+
211
281
  @_command("session", "show this session's model, context and spend")
212
282
  async def _session(services: AppServices, argument: str) -> CommandResult:
213
283
  status = services.chat.status
@@ -321,8 +391,11 @@ def build_default_commands(services: AppServices) -> CommandRegistry:
321
391
  _mode,
322
392
  _sessions,
323
393
  _rename,
394
+ _pin,
324
395
  _clear,
325
396
  _compact,
397
+ _image,
398
+ _images,
326
399
  _mcp,
327
400
  _skills,
328
401
  _reload,
@@ -331,6 +404,7 @@ def build_default_commands(services: AppServices) -> CommandRegistry:
331
404
  _quit,
332
405
  _exit,
333
406
  _thinking,
407
+ _tools,
334
408
  _session,
335
409
  _usage,
336
410
  _context,
@@ -0,0 +1,58 @@
1
+ """Shared retry/rewind: drop the last turn and re-send its prompt.
2
+
3
+ Both frontends need the same move: find the last user message, truncate the
4
+ transcript *before* it, write the truncated transcript to a new (recoverable)
5
+ session file, and hand the prompt text back so the caller can run it again.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from zenagent.agent import Agent
11
+ from zenagent.agent.session import Session, truncate_last_turn
12
+ from zenagent.types import ImageContent, TextContent, UserMessage
13
+
14
+ __all__ = ["prepare_retry", "user_text"]
15
+
16
+
17
+ def user_text(message: UserMessage) -> str:
18
+ """Flatten a user message (text and image markers) back into prompt text."""
19
+ content = message.content
20
+ if isinstance(content, str):
21
+ return content
22
+ parts: list[str] = []
23
+ for block in content:
24
+ if isinstance(block, TextContent):
25
+ parts.append(block.text)
26
+ elif isinstance(block, ImageContent):
27
+ parts.append(f"[image {block.mime_type}]")
28
+ return "\n".join(parts)
29
+
30
+
31
+ def prepare_retry(agent: Agent, session: Session) -> tuple[str, Session] | None:
32
+ """Prepare one retry; ``None`` when there is no answered turn to replay.
33
+
34
+ Mutates ``agent`` (the transcript is truncated) and returns the new session
35
+ file; the caller owns re-sending the prompt. Returns ``None`` while a run is
36
+ streaming so retry never races the loop.
37
+ """
38
+ if agent.is_streaming:
39
+ return None
40
+ messages = list(agent.messages)
41
+ last_user = next(
42
+ (
43
+ position
44
+ for position in range(len(messages) - 1, -1, -1)
45
+ if isinstance(messages[position], UserMessage)
46
+ ),
47
+ None,
48
+ )
49
+ if last_user is None or last_user == len(messages) - 1:
50
+ return None # nothing answered yet
51
+ text = user_text(messages[last_user])
52
+ if not text.strip():
53
+ return None
54
+
55
+ truncated = truncate_last_turn(messages)
56
+ agent.replace_messages(truncated)
57
+ new_path = Session(session.path).rewrite(truncated)
58
+ return text, Session(new_path)
@@ -18,7 +18,9 @@ from zenagent import project
18
18
  from zenagent.agent.session import (
19
19
  Session,
20
20
  list_sessions,
21
+ read_session_pins,
21
22
  read_session_titles,
23
+ set_session_pin,
22
24
  set_session_title,
23
25
  truncate_last_turn,
24
26
  unique_session_path,
@@ -98,6 +100,7 @@ class SessionEntry:
98
100
  current: bool = False
99
101
  title: str = ""
100
102
  project: str = ""
103
+ pinned: bool = False
101
104
 
102
105
 
103
106
  class SessionManager:
@@ -125,11 +128,15 @@ class SessionManager:
125
128
  def entries(self, *, scope: str = "project") -> list[SessionEntry]:
126
129
  current = self.current()
127
130
  entries: list[SessionEntry] = []
131
+ pins_by_dir: dict[Path, set[str]] = {}
128
132
  for info in list_sessions(limit=100, scope=scope):
129
133
  try:
130
134
  size = info.path.stat().st_size
131
135
  except OSError:
132
136
  size = 0
137
+ directory = info.path.parent
138
+ if directory not in pins_by_dir:
139
+ pins_by_dir[directory] = read_session_pins(directory)
133
140
  entries.append(
134
141
  SessionEntry(
135
142
  path=info.path,
@@ -139,10 +146,26 @@ class SessionManager:
139
146
  current=info.path == current,
140
147
  title=info.title,
141
148
  project=info.project,
149
+ pinned=info.path.name in pins_by_dir[directory],
142
150
  )
143
151
  )
152
+ # Pinned first, otherwise newest-first exactly as list_sessions returned
153
+ # (sorted() is stable, so no time order is lost inside each group).
154
+ entries.sort(key=lambda entry: not entry.pinned)
144
155
  return entries
145
156
 
157
+ def set_pin(self, path: Path, pinned: bool) -> bool:
158
+ """Pin/unpin one saved session; ``ValueError`` for a non-session path."""
159
+ return set_session_pin(Path(path), pinned)
160
+
161
+ def toggle_pin(self, path: Path) -> bool:
162
+ """Flip the pinned flag of one saved session; returns the new state."""
163
+ target = Path(path)
164
+ if not target.is_file():
165
+ raise ValueError(f"session not found: {target}")
166
+ currently = target.name in read_session_pins(target.parent)
167
+ return set_session_pin(target, not currently)
168
+
146
169
  async def resume(self, path: Path) -> None:
147
170
  await self.runtime.switch_session(path)
148
171