zettcode-engine 0.5.2__tar.gz → 0.5.4__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 (93) hide show
  1. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/PKG-INFO +3 -3
  2. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/pyproject.toml +2 -2
  3. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/turns.py +4 -3
  4. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/loader.py +12 -0
  5. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/plugin.py +10 -0
  6. zettcode_engine-0.5.4/src/zettcode/engine/storage/pages.py +102 -0
  7. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/storage/records.py +17 -9
  8. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/storage/store.py +80 -8
  9. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/version.py +1 -1
  10. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/wire.py +10 -0
  11. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/.gitignore +0 -0
  12. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/_compat.py +0 -0
  13. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/budget.py +0 -0
  14. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/config.py +0 -0
  15. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/config_edit.py +0 -0
  16. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/__init__.py +0 -0
  17. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/__init__.py +0 -0
  18. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/base.py +0 -0
  19. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/context.py +0 -0
  20. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/exports.py +0 -0
  21. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/interaction.py +0 -0
  22. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/sessions.py +0 -0
  23. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/agent/settings.py +0 -0
  24. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/core.py +0 -0
  25. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/delivery.py +0 -0
  26. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/delivery_runtime.py +0 -0
  27. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/dialogue/__init__.py +0 -0
  28. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/dialogue/ask.py +0 -0
  29. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/dialogue/side.py +0 -0
  30. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/dialogue/title.py +0 -0
  31. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/export/__init__.py +0 -0
  32. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/export/trace/script.js +0 -0
  33. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/export/trace/style.css +0 -0
  34. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/export/trace/template.html +0 -0
  35. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/__init__.py +0 -0
  36. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/capabilities.py +0 -0
  37. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/compaction.py +0 -0
  38. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/context.py +0 -0
  39. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/files.py +0 -0
  40. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/guidance.py +0 -0
  41. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/harness_switch.py +0 -0
  42. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/mcp_notice.py +0 -0
  43. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/relay.py +0 -0
  44. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/subagents.py +0 -0
  45. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/extensions/usage.py +0 -0
  46. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/harness_library.py +0 -0
  47. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/harness_paths.py +0 -0
  48. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/inbox.py +0 -0
  49. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/permission/__init__.py +0 -0
  50. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/permission/approval.py +0 -0
  51. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/permission/readonly.py +0 -0
  52. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/permission/sandbox.py +0 -0
  53. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/pipeline.py +0 -0
  54. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/__init__.py +0 -0
  55. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/children.py +0 -0
  56. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/cli.py +0 -0
  57. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/commands.py +0 -0
  58. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/context.py +0 -0
  59. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/environment.py +0 -0
  60. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/extension.py +0 -0
  61. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/graph.py +0 -0
  62. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/groups.py +0 -0
  63. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/llm.py +0 -0
  64. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/mixins.py +0 -0
  65. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/services.py +0 -0
  66. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/settings.py +0 -0
  67. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/state.py +0 -0
  68. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/switches.py +0 -0
  69. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/plugins/triggers.py +0 -0
  70. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/provided.py +0 -0
  71. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/py.typed +0 -0
  72. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/server_tools.py +0 -0
  73. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/service_contracts.py +0 -0
  74. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/storage/__init__.py +0 -0
  75. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/storage/layout.py +0 -0
  76. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/storage/ledger.py +0 -0
  77. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/storage/locks.py +0 -0
  78. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/engine/storage/metadata.py +0 -0
  79. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/error_text.py +0 -0
  80. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/filelock.py +0 -0
  81. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/logging_setup.py +0 -0
  82. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/mention.py +0 -0
  83. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/modes.py +0 -0
  84. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/paths.py +0 -0
  85. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/plugin_tui.py +0 -0
  86. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/processes.py +0 -0
  87. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/prompt.py +0 -0
  88. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/providers.py +0 -0
  89. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/py.typed +0 -0
  90. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/registry.py +0 -0
  91. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/relay.py +0 -0
  92. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/statusline_parts.py +0 -0
  93. {zettcode_engine-0.5.2 → zettcode_engine-0.5.4}/src/zettcode/wording.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: zettcode-engine
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: The agent core of ZettCode: the runtime over zett-agent, and the leaf types it is written on
5
5
  Project-URL: Repository, https://github.com/Chang-LeHung/zettcode
6
6
  Author: Chang-LeHung
@@ -18,7 +18,7 @@ Requires-Python: >=3.10
18
18
  Requires-Dist: exceptiongroup<2,>=1.2; python_version < '3.11'
19
19
  Requires-Dist: pydantic<3,>=2
20
20
  Requires-Dist: tomli<3,>=2; python_version < '3.11'
21
- Requires-Dist: zett-agent<0.4,>=0.3.1
22
- Requires-Dist: zettcode-tools<0.6,>=0.5.2
21
+ Requires-Dist: zett-agent<0.4,>=0.3.3
22
+ Requires-Dist: zettcode-tools<0.6,>=0.5.4
23
23
  Provides-Extra: tiktoken
24
24
  Requires-Dist: tiktoken<1,>=0.12; extra == 'tiktoken'
@@ -18,9 +18,9 @@ classifiers = [
18
18
  ]
19
19
  dependencies = [
20
20
  # The coding tools the runtime hands the model, a leaf of its own beneath the engine.
21
- "zettcode-tools>=0.5.2,<0.6",
21
+ "zettcode-tools>=0.5.4,<0.6",
22
22
  # The runtime this is a core over. Imported directly: the agent, the message types, the approval mode.
23
- "zett-agent>=0.3.1,<0.4",
23
+ "zett-agent>=0.3.3,<0.4",
24
24
  # The session store's records are pydantic models.
25
25
  "pydantic>=2,<3",
26
26
  # The stdlib gained both of these in 3.11; older runtimes take the backports.
@@ -145,6 +145,7 @@ class TurnsMixin(AgentBase):
145
145
  config=AgentRunConfig(
146
146
  session_id=session_id,
147
147
  cache_mode=cache_mode_of(cache, side=side),
148
+ steering_mode="all",
148
149
  ),
149
150
  model=self.runtime.provider,
150
151
  reasoning_effort=self.runtime.effort,
@@ -168,7 +169,7 @@ class TurnsMixin(AgentBase):
168
169
  self.require_session()
169
170
  await self.runtime.start()
170
171
  return await self.runtime.started.resume_point(
171
- config=AgentRunConfig(session_id=self.session_id), model=self.runtime.provider
172
+ config=AgentRunConfig(session_id=self.session_id, steering_mode="all"), model=self.runtime.provider
172
173
  )
173
174
 
174
175
  async def resume_blocker(self) -> str | None:
@@ -181,7 +182,7 @@ class TurnsMixin(AgentBase):
181
182
  self.require_session()
182
183
  await self.runtime.start()
183
184
  stream = self.runtime.started.stream_resume(
184
- config=AgentRunConfig(session_id=self.session_id), model=self.runtime.provider
185
+ config=AgentRunConfig(session_id=self.session_id, steering_mode="all"), model=self.runtime.provider
185
186
  )
186
187
  try:
187
188
  async for _event in stream:
@@ -211,7 +212,7 @@ class TurnsMixin(AgentBase):
211
212
  cast(
212
213
  "AsyncGenerator[AgentEvent]",
213
214
  client.stream_resume(
214
- config=AgentRunConfig(session_id=session_id),
215
+ config=AgentRunConfig(session_id=session_id, steering_mode="all"),
215
216
  model=self.runtime.provider,
216
217
  reasoning_effort=self.runtime.effort,
217
218
  ),
@@ -487,6 +487,8 @@ class Loader:
487
487
  def __init__(self, config: ZettCodeConfig, shared: Mapping[str, object] | None = None) -> None:
488
488
  self.config = config
489
489
  self.plugins: list[Plugin[Any]] = []
490
+ #: Validated startup snapshots; never re-read a plugin's mutable hints while building the bundle.
491
+ self.tips: list[str] = []
490
492
  self.mentions: list[MentionProvider] = []
491
493
  self.providers: list[Provider] = []
492
494
  self.contributed: list[Contribution] = []
@@ -606,6 +608,7 @@ class Loader:
606
608
  providers=tuple(self.providers),
607
609
  contributed=tuple(self.contributed),
608
610
  services=dict(self.services),
611
+ tips=tuple(dict.fromkeys(self.tips)),
609
612
  plain_commands=tuple(self.plain_commands),
610
613
  failed=tuple(self.failed),
611
614
  required=tuple(self.required),
@@ -663,6 +666,14 @@ class Loader:
663
666
  plugin.restore_child(validate_child_state({name: self.child_state[name]})[name])
664
667
  plugin.activate(container)
665
668
  self.activated(plugin, container)
669
+ tips = plugin.tips
670
+ if not isinstance(tips, tuple) or any(
671
+ not isinstance(tip, str) or not tip.strip() or tip != tip.strip() or "\n" in tip or "\r" in tip
672
+ for tip in tips
673
+ ):
674
+ raise ValueError(
675
+ "tips must be a tuple of non-empty, single-line strings without surrounding whitespace"
676
+ )
666
677
  except KeyboardInterrupt:
667
678
  raise
668
679
  except BaseException as error:
@@ -675,6 +686,7 @@ class Loader:
675
686
  self._identities.add(name)
676
687
  self.merge(container)
677
688
  self.plugins.append(plugin)
689
+ self.tips.extend(tips)
678
690
  return True
679
691
 
680
692
 
@@ -90,6 +90,9 @@ class Plugin(PluginAgentMixin, Generic[_C], ABC):
90
90
  description: One-line summary of what the plugin adds, shown beside its switch on ``/plugins`` and used in
91
91
  diagnostics. A plugin a reader can switch should say something here: a listed row with nothing to say
92
92
  costs the reader the one line that tells the two plugins called alike apart.
93
+ tips: Short waiting-row hints, snapshotted after activation. Set the instance tuple to empty when the
94
+ functionality is disabled; nested groups contribute through their loaded parent. Tips are display text,
95
+ not model input, and changes after startup require a restart to refresh the deck.
93
96
  priority: Hook order against every other extension: lower runs first,
94
97
  and equal priorities keep registration order.
95
98
  setting: The configuration key that turns its work off; ``None`` when the plugin is switched by
@@ -104,6 +107,9 @@ class Plugin(PluginAgentMixin, Generic[_C], ABC):
104
107
  #: switch file are matched against it.
105
108
  origin: str = ""
106
109
  description: ClassVar[str] = ""
110
+ #: Short hints offered to the reader while a request runs. Only loaded plugins contribute; the terminal
111
+ #: shuffles the combined deck once and rotates it across requests. Leave empty to offer none.
112
+ tips: tuple[str, ...] = ()
107
113
  #: The names of the plugins this one needs. The loader activates a plugin after every plugin it lists, and
108
114
  #: leaves it out, reported, when one of them is absent, turned off, failed, or the lists go round in a circle.
109
115
  deps: ClassVar[tuple[str, ...]] = ()
@@ -192,6 +198,8 @@ class Plugins:
192
198
  into the extensions the agent is given, beside the host, so each keeps the priority it declares.
193
199
  services: Objects the runtime handed over and the plugins provided, by name; read them with
194
200
  :meth:`service` and :meth:`find`.
201
+ tips: Validated startup hints from loaded plugins, deduplicated in activation and declaration order;
202
+ the terminal draws them under the waiting row.
195
203
  plain_commands: Commands a plugin registered on ``ctx.commands``, in load and registration order, each
196
204
  typed ``"plugin"``. The terminal turns them into shell commands; another front end reads them here.
197
205
  failures: One message per plugin that could not be loaded or activated, ``origin: why``, read from
@@ -215,6 +223,8 @@ class Plugins:
215
223
  providers: tuple[Provider, ...] = ()
216
224
  contributed: tuple[Contribution, ...] = ()
217
225
  services: Mapping[str, object] = field(default_factory=dict)
226
+ #: Unique hints from successfully loaded plugins, in activation and declaration order.
227
+ tips: tuple[str, ...] = ()
218
228
  plain_commands: tuple[object, ...] = ()
219
229
  failed: tuple[tuple[str, str], ...] = ()
220
230
  required: tuple[str, ...] = ()
@@ -0,0 +1,102 @@
1
+ """Backward, demand-driven reads of raw message records; no branch walk or replay."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections.abc import Iterator
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, BinaryIO
11
+
12
+ if TYPE_CHECKING:
13
+ from .records import MessageLine
14
+
15
+ CHUNK_BYTES = 16 * 1024
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class NodeCursor:
20
+ """Exclusive byte boundary in one append-only session file."""
21
+
22
+ session_id: str
23
+ offset: int
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class RawNodePage:
28
+ """Raw messages in chronological file order and the boundary for earlier ones."""
29
+
30
+ nodes: tuple[MessageLine, ...]
31
+ cursor: NodeCursor | None
32
+
33
+
34
+ def _backwards(handle: BinaryIO, end: int) -> Iterator[tuple[int, bytes]]:
35
+ """Yield lines with their start offsets, reading at most one chunk ahead."""
36
+ position = end
37
+ fragments: list[bytes] = []
38
+ while position:
39
+ start = max(0, position - CHUNK_BYTES)
40
+ handle.seek(start)
41
+ data = handle.read(position - start)
42
+ stop = len(data)
43
+ while (newline := data.rfind(b"\n", 0, stop)) >= 0:
44
+ fragments.append(data[newline + 1 : stop])
45
+ yield start + newline + 1, b"".join(reversed(fragments))
46
+ fragments.clear()
47
+ stop = newline
48
+ if stop:
49
+ fragments.append(data[:stop])
50
+ position = start
51
+ if fragments:
52
+ yield 0, b"".join(reversed(fragments))
53
+
54
+
55
+ def read_node_page(path: Path, session_id: str, *, cursor: NodeCursor | None = None, limit: int = 50) -> RawNodePage:
56
+ """Read only as far backwards as the requested messages require.
57
+
58
+ Blank/header/head/compaction records are skipped without runtime decoding.
59
+ An invalid final nonblank record is tolerated like the store's full reader.
60
+ A single JSON record must fit in memory; large payloads are not runtime-decoded.
61
+ Cursors exclude newer appends and are never mutated by a read.
62
+ """
63
+ from .records import MessageLine
64
+
65
+ if isinstance(limit, bool) or not 1 <= limit <= 200:
66
+ raise ValueError("limit must be between 1 and 200")
67
+ if cursor is not None and (cursor.session_id != session_id or cursor.offset < 0):
68
+ raise ValueError("Cursor belongs to another session or has an invalid offset")
69
+ try:
70
+ handle = path.open("rb")
71
+ except FileNotFoundError:
72
+ if cursor is not None:
73
+ raise ValueError("Session file disappeared; reopen the picker") from None
74
+ return RawNodePage((), None)
75
+ with handle:
76
+ size = os.fstat(handle.fileno()).st_size
77
+ end = size if cursor is None else cursor.offset
78
+ if end > size:
79
+ raise ValueError("Session file was shortened; reopen the picker")
80
+ nodes = []
81
+ final = cursor is None
82
+ for offset, raw in _backwards(handle, end):
83
+ if not raw.strip():
84
+ continue
85
+ try:
86
+ record = json.loads(raw)
87
+ if not isinstance(record, dict):
88
+ raise ValueError("Expected a JSON object")
89
+ kind = record.get("kind")
90
+ if kind not in {"message", "session", "head", "compaction"}:
91
+ raise ValueError("Unknown session record kind")
92
+ if kind == "message":
93
+ nodes.append(MessageLine.model_validate_json(raw))
94
+ except ValueError as error:
95
+ if final:
96
+ final = False
97
+ continue
98
+ raise ValueError(f"Invalid session record at byte {offset}: {error}") from error
99
+ final = False
100
+ if len(nodes) == limit:
101
+ return RawNodePage(tuple(reversed(nodes)), NodeCursor(session_id, offset) if offset else None)
102
+ return RawNodePage(tuple(reversed(nodes)), None)
@@ -5,9 +5,10 @@ Records are a tree, not a list. Every record names the node it continues from::
5
5
  m1 ── m2 ── m3 ── m4 ── m5 <- the head is the last message written
6
6
  └── C (a checkpoint through m3)
7
7
 
8
- * The **head** is the last message line in the file. Appending continues from
9
- it, and a *fork* is therefore a plain append: write a message whose ``parent``
10
- is an older node and the abandoned branch stays in the file, out of context.
8
+ * The **head** is the last message written or the target of the last head
9
+ selection. Appending continues from it: an older ``parent`` or a head selection
10
+ starts another branch while the previous branch stays in the file, out of context.
11
+ Selecting ``None`` returns to the empty root without deleting any nodes.
11
12
  * A **checkpoint** is an annotation rather than a conversation node: its
12
13
  ``parent`` is the last message it summarizes. The summary applies to any
13
14
  branch that still contains that boundary, and a checkpoint never becomes the
@@ -69,6 +70,7 @@ class LineKind(StrEnum):
69
70
  SESSION = "session"
70
71
  MESSAGE = "message"
71
72
  COMPACTION = "compaction"
73
+ HEAD = "head"
72
74
 
73
75
 
74
76
  def _load_messages(value: object) -> object:
@@ -259,10 +261,18 @@ class CompactionLine(BaseModel):
259
261
  return _dump_messages(value)
260
262
 
261
263
 
262
- Line: TypeAlias = Annotated[SessionLine | MessageLine | CompactionLine, Field(discriminator="kind")]
264
+ class HeadLine(BaseModel):
265
+ """Select an existing conversation node (or the empty root), without deleting history."""
266
+
267
+ kind: Literal[LineKind.HEAD] = LineKind.HEAD
268
+ head_id: str | None
269
+ created_at: datetime
270
+
271
+
272
+ Line: TypeAlias = Annotated[SessionLine | MessageLine | CompactionLine | HeadLine, Field(discriminator="kind")]
263
273
  # `TypeAdapter` takes a `TypeForm`, which mypy does not recognise in an `Annotated` union alias; the declared type
264
274
  # on the left is what callers get.
265
- LINES: TypeAdapter[SessionLine | MessageLine | CompactionLine] = TypeAdapter(cast(Any, Line))
275
+ LINES: TypeAdapter[SessionLine | MessageLine | CompactionLine | HeadLine] = TypeAdapter(cast(Any, Line))
266
276
 
267
277
 
268
278
  @dataclass(frozen=True, slots=True)
@@ -273,10 +283,8 @@ class Session:
273
283
  header: The session line, or ``None`` for a file that has none yet.
274
284
  messages: Every message line in file order, across all branches.
275
285
  compactions: Every checkpoint in file order.
276
- head_id: Id of the last message written, which the next append continues
277
- from. A tree can have several leaves, so "the head" is a choice and
278
- this is the store's: the most recent append wins, which is what
279
- makes a fork a plain append.
286
+ head_id: Selected message id, which the next append continues from;
287
+ None means the empty root. The most recent message or head selection wins.
280
288
  """
281
289
 
282
290
  header: SessionLine | None
@@ -72,6 +72,7 @@ from .metadata import (
72
72
  read_session_metadata,
73
73
  write_session_metadata,
74
74
  )
75
+ from .pages import NodeCursor, RawNodePage, read_node_page
75
76
  from .records import (
76
77
  FORK_SUFFIX,
77
78
  LINES,
@@ -80,6 +81,7 @@ from .records import (
80
81
  STORE_FILE,
81
82
  STORE_VERSION,
82
83
  CompactionLine,
84
+ HeadLine,
83
85
  JsonValue,
84
86
  Line,
85
87
  MessageLine,
@@ -259,6 +261,10 @@ class SessionPersistenceMixin:
259
261
  return None
260
262
  return None
261
263
 
264
+ def nodes_page(self, session_id: str, *, cursor: NodeCursor | None = None, limit: int = 50) -> RawNodePage:
265
+ """Read raw message records backwards, without populating the full-session cache."""
266
+ return read_node_page(self.session_path(session_id), session_id, cursor=cursor, limit=limit)
267
+
262
268
  def read(self, session_id: str) -> Session:
263
269
  """Parse one session file, tolerating a half-written final line.
264
270
 
@@ -369,6 +375,9 @@ class SessionPersistenceMixin:
369
375
  head_id = parsed.id
370
376
  case CompactionLine():
371
377
  compactions.append(parsed)
378
+ case HeadLine():
379
+ self._check_head(parsed, messages)
380
+ head_id = parsed.head_id
372
381
  case other:
373
382
  raise ValueError(f"Unknown session record: {type(other).__name__}")
374
383
  if trailing.strip():
@@ -386,6 +395,9 @@ class SessionPersistenceMixin:
386
395
  head_id = parsed.id
387
396
  case CompactionLine():
388
397
  compactions.append(parsed)
398
+ case HeadLine():
399
+ self._check_head(parsed, messages)
400
+ head_id = parsed.head_id
389
401
  case other:
390
402
  raise ValueError(f"Unknown session record: {type(other).__name__}")
391
403
  elif trailing:
@@ -399,6 +411,12 @@ class SessionPersistenceMixin:
399
411
  taken = data[:consumed].count(b"\n") + (1 if consumed and not data[:consumed].endswith(b"\n") else 0)
400
412
  return session, _Reading(session, end, before[-_ANCHOR:], (known.lines if known is not None else 0) + taken)
401
413
 
414
+ @staticmethod
415
+ def _check_head(line: HeadLine, messages: Sequence[MessageLine]) -> None:
416
+ """A head selection can only name a message already written, never a checkpoint."""
417
+ if line.head_id is not None and not any(item.id == line.head_id for item in messages):
418
+ raise ValueError(f"Unknown head message: {line.head_id!r}")
419
+
402
420
  @staticmethod
403
421
  def _stamp(path: Path) -> tuple[int, int]:
404
422
  """Return the file's identity as mtime and size, the cache's validity key.
@@ -427,8 +445,13 @@ class SessionPersistenceMixin:
427
445
  if boundary.parent not in known:
428
446
  raise ValueError(f"Unknown boundary {boundary.parent!r} in {path.name}")
429
447
 
430
- def _append_line(self, session_id: str, line: Line) -> None:
431
- """Append one validated line, flushing so a reader sees whole records."""
448
+ def _append_line(self, session_id: str, line: Line, *, durable: bool = False) -> None:
449
+ """Append a validated line.
450
+
451
+ A caller writing a session that may be open elsewhere holds its writer lock;
452
+ a fresh fork does not require one. Flush whole records for readers, and optionally sync the writable handle
453
+ before publishing the completed operation to the cache.
454
+ """
432
455
  text = json.dumps(line.model_dump(mode="json"), ensure_ascii=False, allow_nan=False, sort_keys=True)
433
456
  if not self._claimed:
434
457
  claim_workspace(self.workspace_dir, self.workspace)
@@ -438,6 +461,8 @@ class SessionPersistenceMixin:
438
461
  with path.open("a", encoding="utf-8") as handle:
439
462
  handle.write(text + "\n")
440
463
  handle.flush()
464
+ if durable:
465
+ os.fsync(handle.fileno())
441
466
  self._remember(session_id, line)
442
467
 
443
468
  def _remember(self, session_id: str, line: Line) -> None:
@@ -483,6 +508,11 @@ class SessionPersistenceMixin:
483
508
  # below, or the next append would re-parse the whole file.
484
509
  if not (session.messages and session.messages[-1].id == line.id):
485
510
  session = replace(session, messages=(*session.messages, line), head_id=line.id)
511
+ case HeadLine():
512
+ if line.head_id is not None and session.message(line.head_id) is None:
513
+ self._forget(session_id)
514
+ return
515
+ session = replace(session, head_id=line.head_id)
486
516
  case CompactionLine():
487
517
  if session.message(line.parent) is None:
488
518
  self._forget(session_id)
@@ -546,6 +576,45 @@ class SessionPersistenceMixin:
546
576
  # modification time moved with the line above, and that is the activity a list shows.
547
577
  return node_id
548
578
 
579
+ def rewind(self, session_id: str, head_id: str | None) -> bool:
580
+ """Durably select the context after a node, retaining every branch and checkpoint.
581
+
582
+ None selects the empty root. Tool batches must be complete at the selected
583
+ boundary; unlike interrupted-request recovery, rewind never invents results.
584
+ """
585
+ session = self.read(session_id)
586
+ if session.header is None:
587
+ raise ValueError(f"Unknown session: {session_id}")
588
+ if session.head_id == head_id:
589
+ return False
590
+ line = HeadLine(head_id=head_id, created_at=now())
591
+ self._check_head(line, session.messages)
592
+ selected = replace(session, head_id=head_id)
593
+ # Validate raw ancestry too: a checkpoint must not hide a cut inside a
594
+ # tool batch. Rewind is stricter than interrupted-request recovery.
595
+ messages = [item.message[0] for item in selected.branch() if item.message[0].include_in_messages]
596
+ pending: Counter[str] = Counter()
597
+ for message in messages:
598
+ if isinstance(message, ToolMessage):
599
+ if not pending[message.tool_call_id]:
600
+ raise ValueError("Cannot rewind into malformed tool results")
601
+ pending[message.tool_call_id] -= 1
602
+ pending = +pending # discard completed calls
603
+ else:
604
+ if pending:
605
+ raise ValueError("Cannot rewind across an incomplete tool batch")
606
+ if isinstance(message, AssistantMessage) and message.tool_calls:
607
+ pending = Counter(call.id for call in message.tool_calls)
608
+ if any(count != 1 for count in pending.values()):
609
+ raise ValueError("Cannot rewind across duplicate tool calls")
610
+ if pending:
611
+ raise ValueError(
612
+ "Cannot rewind into an incomplete tool batch; choose before the user prompt or after results"
613
+ )
614
+ # Selection is a completed user operation, even without a following prompt.
615
+ self._append_line(session_id, line, durable=True)
616
+ return True
617
+
549
618
  async def checkpoint(
550
619
  self,
551
620
  session_id: str,
@@ -561,8 +630,9 @@ class SessionPersistenceMixin:
561
630
  raise ValueError("Checkpoint conflict; reload the session")
562
631
  if session.message(boundary_id) is None:
563
632
  raise ValueError("Checkpoint boundary must identify an existing message")
564
- if latest is not None:
565
- previous = session.index(latest.parent)
633
+ applicable = session.checkpoint_for()
634
+ if applicable is not None:
635
+ previous = session.index(applicable.parent)
566
636
  position = session.index(boundary_id)
567
637
  if previous is not None and position is not None and position <= previous:
568
638
  raise ValueError("Checkpoint boundary must advance beyond the previous one")
@@ -1058,7 +1128,7 @@ class SessionStore(SessionPersistenceMixin, AgentExtension, SessionStoreService,
1058
1128
 
1059
1129
  async def on_state(self, context: AgentRunContext) -> None:
1060
1130
  """Restore the conversation and map every context position to a message id."""
1061
- checkpoint, tail = await self._restore(context)
1131
+ session, checkpoint, tail = await self._restore(context)
1062
1132
  ids: list[str | None] = []
1063
1133
  if checkpoint is not None:
1064
1134
  ids.append(checkpoint.parent)
@@ -1069,7 +1139,7 @@ class SessionStore(SessionPersistenceMixin, AgentExtension, SessionStoreService,
1069
1139
  )
1070
1140
  self._requests[context] = _Request(
1071
1141
  request_id=context.config.request_id or new_uuid7(),
1072
- checkpoint_version=checkpoint.version if checkpoint is not None else 0,
1142
+ checkpoint_version=latest.version if (latest := session.latest_compaction) else 0,
1073
1143
  context_ids=ids,
1074
1144
  )
1075
1145
 
@@ -1131,7 +1201,9 @@ class SessionStore(SessionPersistenceMixin, AgentExtension, SessionStoreService,
1131
1201
  """Release the bookkeeping; the append-only history remains available."""
1132
1202
  self._requests.pop(context, None)
1133
1203
 
1134
- async def _restore(self, context: AgentRunContext) -> tuple[CompactionLine | None, tuple[MessageLine, ...]]:
1204
+ async def _restore(
1205
+ self, context: AgentRunContext
1206
+ ) -> tuple[Session, CompactionLine | None, tuple[MessageLine, ...]]:
1135
1207
  """Load the conversation and merge it with the current configuration.
1136
1208
 
1137
1209
  Parsing a long JSONL file is file work with no await in it. Running it
@@ -1160,7 +1232,7 @@ class SessionStore(SessionPersistenceMixin, AgentExtension, SessionStoreService,
1160
1232
  [*instructions, *self._provider_safe_messages(stored)],
1161
1233
  emit_new=False,
1162
1234
  )
1163
- return checkpoint, tail
1235
+ return session, checkpoint, tail
1164
1236
 
1165
1237
  @staticmethod
1166
1238
  def _provider_safe_messages(messages: Sequence[AnyMessage]) -> list[AnyMessage]:
@@ -8,4 +8,4 @@ of the dependency graph: everything else may import `zettcode.version`, nothing
8
8
  from __future__ import annotations
9
9
 
10
10
  #: The version of the program and of every distribution built beside it.
11
- __version__ = "0.5.2"
11
+ __version__ = "0.5.4"
@@ -55,6 +55,16 @@ class RosterPeer(ABC):
55
55
  def status(self) -> str:
56
56
  """``idle`` or ``working``."""
57
57
 
58
+ @property
59
+ def work_started_at(self) -> float | None:
60
+ """Epoch seconds when the current turn began, or ``None`` when unknown or idle."""
61
+ return None
62
+
63
+ @property
64
+ def started_at(self) -> float | None:
65
+ """Epoch seconds when the reporting client started, or ``None`` for legacy peers."""
66
+ return None
67
+
58
68
 
59
69
  @dataclass(frozen=True, slots=True)
60
70
  class ImageData: