zettcode-engine 0.5.3__tar.gz → 0.5.5__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.3 → zettcode_engine-0.5.5}/PKG-INFO +3 -3
  2. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/pyproject.toml +2 -2
  3. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/config.py +4 -0
  4. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/config_edit.py +16 -7
  5. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/context.py +9 -10
  6. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/sessions.py +2 -1
  7. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/turns.py +4 -3
  8. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/core.py +59 -27
  9. zettcode_engine-0.5.5/src/zettcode/engine/storage/pages.py +102 -0
  10. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/storage/records.py +17 -9
  11. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/storage/store.py +80 -8
  12. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/plugin_tui.py +5 -1
  13. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/version.py +1 -1
  14. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/.gitignore +0 -0
  15. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/_compat.py +0 -0
  16. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/budget.py +0 -0
  17. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/__init__.py +0 -0
  18. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/__init__.py +0 -0
  19. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/base.py +0 -0
  20. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/exports.py +0 -0
  21. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/interaction.py +0 -0
  22. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/agent/settings.py +0 -0
  23. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/delivery.py +0 -0
  24. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/delivery_runtime.py +0 -0
  25. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/dialogue/__init__.py +0 -0
  26. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/dialogue/ask.py +0 -0
  27. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/dialogue/side.py +0 -0
  28. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/dialogue/title.py +0 -0
  29. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/export/__init__.py +0 -0
  30. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/export/trace/script.js +0 -0
  31. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/export/trace/style.css +0 -0
  32. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/export/trace/template.html +0 -0
  33. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/__init__.py +0 -0
  34. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/capabilities.py +0 -0
  35. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/compaction.py +0 -0
  36. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/context.py +0 -0
  37. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/files.py +0 -0
  38. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/guidance.py +0 -0
  39. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/harness_switch.py +0 -0
  40. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/mcp_notice.py +0 -0
  41. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/relay.py +0 -0
  42. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/subagents.py +0 -0
  43. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/extensions/usage.py +0 -0
  44. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/harness_library.py +0 -0
  45. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/harness_paths.py +0 -0
  46. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/inbox.py +0 -0
  47. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/permission/__init__.py +0 -0
  48. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/permission/approval.py +0 -0
  49. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/permission/readonly.py +0 -0
  50. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/permission/sandbox.py +0 -0
  51. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/pipeline.py +0 -0
  52. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/__init__.py +0 -0
  53. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/children.py +0 -0
  54. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/cli.py +0 -0
  55. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/commands.py +0 -0
  56. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/context.py +0 -0
  57. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/environment.py +0 -0
  58. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/extension.py +0 -0
  59. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/graph.py +0 -0
  60. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/groups.py +0 -0
  61. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/llm.py +0 -0
  62. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/loader.py +0 -0
  63. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/mixins.py +0 -0
  64. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/plugin.py +0 -0
  65. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/services.py +0 -0
  66. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/settings.py +0 -0
  67. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/state.py +0 -0
  68. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/switches.py +0 -0
  69. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/plugins/triggers.py +0 -0
  70. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/provided.py +0 -0
  71. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/py.typed +0 -0
  72. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/server_tools.py +0 -0
  73. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/service_contracts.py +0 -0
  74. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/storage/__init__.py +0 -0
  75. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/storage/layout.py +0 -0
  76. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/storage/ledger.py +0 -0
  77. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/storage/locks.py +0 -0
  78. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/engine/storage/metadata.py +0 -0
  79. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/error_text.py +0 -0
  80. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/filelock.py +0 -0
  81. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/logging_setup.py +0 -0
  82. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/mention.py +0 -0
  83. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/modes.py +0 -0
  84. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/paths.py +0 -0
  85. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/processes.py +0 -0
  86. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/prompt.py +0 -0
  87. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/providers.py +0 -0
  88. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/py.typed +0 -0
  89. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/registry.py +0 -0
  90. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/relay.py +0 -0
  91. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/statusline_parts.py +0 -0
  92. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/src/zettcode/wire.py +0 -0
  93. {zettcode_engine-0.5.3 → zettcode_engine-0.5.5}/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.3
3
+ Version: 0.5.5
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.2
22
- Requires-Dist: zettcode-tools<0.6,>=0.5.3
21
+ Requires-Dist: zett-agent<0.4,>=0.3.3
22
+ Requires-Dist: zettcode-tools<0.6,>=0.5.5
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.3,<0.6",
21
+ "zettcode-tools>=0.5.5,<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.2,<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.
@@ -79,6 +79,7 @@ MODEL_KEYS = frozenset(
79
79
  "compact_percent",
80
80
  "max_tokens",
81
81
  "reasoning_efforts",
82
+ "system_prompt",
82
83
  }
83
84
  )
84
85
 
@@ -288,6 +289,7 @@ class ModelConfig:
288
289
  token_env: The environment variable a plugin named for this model's token, when it was not set when the
289
290
  runtime was built; ``None`` when the entry carries its token, has no host to name one, or the variable
290
291
  was present. It is shown so a model that cannot work says which key is missing.
292
+ system_prompt: Optional template replacing the built-in system prompt for this model. Blank uses the default.
291
293
  """
292
294
 
293
295
  model: str
@@ -307,6 +309,7 @@ class ModelConfig:
307
309
  web_search_name: str | None = None
308
310
  provider: str | None = None
309
311
  token_env: str | None = None
312
+ system_prompt: str | None = None
310
313
 
311
314
  def __post_init__(self) -> None:
312
315
  """Reject a model that cannot be called."""
@@ -752,6 +755,7 @@ def _entry_model(entry: dict[str, object], index: int, *, label: str | None = No
752
755
  else _number(entry["temperature"], f"{label} key 'temperature'"),
753
756
  web_search=_setting(entry, "web_search", bool, False),
754
757
  web_search_name=_setting(entry, "web_search_name", str, None),
758
+ system_prompt=_setting(entry, "system_prompt", str, None),
755
759
  context_window=_typed(
756
760
  entry.get("context_window", DEFAULT_CONTEXT_WINDOW), f"{label} key 'context_window'", int
757
761
  ),
@@ -48,6 +48,7 @@ _KEY_ORDER = (
48
48
  "compact_percent",
49
49
  "max_tokens",
50
50
  "reasoning_efforts",
51
+ "system_prompt",
51
52
  )
52
53
 
53
54
 
@@ -144,24 +145,32 @@ def entry_from_model(model: ModelConfig, *, token: str | None = None) -> dict[st
144
145
  entry["max_tokens"] = model.max_tokens
145
146
  if model.reasoning_efforts:
146
147
  entry["reasoning_efforts"] = [level.value for level in model.reasoning_efforts]
148
+ if model.system_prompt and model.system_prompt.strip():
149
+ entry["system_prompt"] = model.system_prompt
147
150
  return entry
148
151
 
149
152
 
153
+ def _complete_prefix(lines: list[str], index: int) -> bool:
154
+ """A header is real only if the preceding TOML is complete (not inside a string or array)."""
155
+ try:
156
+ tomllib.loads("\n".join(lines[:index]) + "\n")
157
+ except tomllib.TOMLDecodeError:
158
+ return False
159
+ return True
160
+
161
+
150
162
  def _blocks(lines: list[str]) -> list[tuple[int, int]]:
151
163
  """Return the ``(start, end)`` line range of every ``[[models]]`` block, in order.
152
164
 
153
165
  A block runs to the next table header, less the blank and comment lines at its end: those are
154
166
  the introduction to whatever follows, and belong to it.
155
167
  """
168
+ headers = [index for index, line in enumerate(lines) if _HEADER.match(line) and _complete_prefix(lines, index)]
156
169
  blocks: list[tuple[int, int]] = []
157
- for index, line in enumerate(lines):
158
- if not _MODEL_HEADER.match(line):
170
+ for position, index in enumerate(headers):
171
+ if not _MODEL_HEADER.match(lines[index]):
159
172
  continue
160
- end = len(lines)
161
- for later in range(index + 1, len(lines)):
162
- if _HEADER.match(lines[later]):
163
- end = later
164
- break
173
+ end = headers[position + 1] if position + 1 < len(headers) else len(lines)
165
174
  while end > index + 1 and (not lines[end - 1].strip() or lines[end - 1].lstrip().startswith("#")):
166
175
  end -= 1
167
176
  blocks.append((index, end))
@@ -14,6 +14,7 @@ from zett_agent.extensions.events import CompactionEvent
14
14
  from zett_agent.messages import AnyMessage, SystemMessage
15
15
  from zett_agent.model import ToolDefinition
16
16
 
17
+ from zettcode.config import ModelConfig
17
18
  from zettcode.engine.core import ZettCodeEngine, build_system_prompt
18
19
  from zettcode.engine.extensions.context import ContextReport
19
20
  from zettcode.engine.extensions.usage import UsageSnapshot
@@ -131,19 +132,17 @@ class ContextMixin(AgentBase):
131
132
  if assembled is not None:
132
133
  messages, tools = assembled
133
134
  return tuple(messages), tuple(tools)
134
- return self._stored_request(session), self.runtime.context.tools
135
+ return self._stored_request(session, self.runtime.active_model), self.runtime.context.tools
135
136
 
136
- def _stored_request(self, session: Session) -> tuple[AnyMessage, ...]:
137
- """Return the messages a request for ``session`` would carry, from what is stored.
137
+ def _stored_request(self, session: Session, model: ModelConfig | None) -> tuple[AnyMessage, ...]:
138
+ """Reconstruct the base prompt and dialogue without borrowing another session's request.
138
139
 
139
- This depends on the session it is given and on nothing that changes with the
140
- active one, so it can be run later — a restore hands it over unrun, and the
141
- reader may have moved to another session by the time it is wanted.
140
+ A lazy restore captures its selected model because the active one can change before a report is read.
141
+ This estimate omits project and tool instructions: those can depend on the session or model, so reusing
142
+ system messages captured from another request would put the wrong instructions in a report or export.
142
143
  """
143
- instructions = self.runtime.context.instructions or (
144
- SystemMessage(content=build_system_prompt(self.runtime.config, role=self.runtime.system_prompt)),
145
- )
144
+ prompt = build_system_prompt(self.runtime.config, model=model, role=self.runtime.system_prompt)
146
145
  checkpoint, tail = session.active()
147
146
  stored: list[AnyMessage] = [checkpoint.message[0]] if checkpoint is not None else []
148
147
  stored.extend(line.message[0] for line in tail if line.message[0].include_in_messages)
149
- return (*instructions, *stored)
148
+ return (SystemMessage(content=prompt), *stored)
@@ -152,7 +152,8 @@ class SessionsMixin(ContextMixin):
152
152
  # It is handed over as a function, not built here: the request holds every
153
153
  # message since the last checkpoint, decoding them is most of what a long
154
154
  # resume would cost, and nothing reads the list until `/context` does.
155
- self.runtime.context.remember(session_id, lambda: self._stored_request(session))
155
+ selected = self.runtime.active_model
156
+ self.runtime.context.remember(session_id, lambda: self._stored_request(session, selected))
156
157
 
157
158
  def restore_session(self, session_id: str) -> None:
158
159
  """Load the stored branch and make it the active one."""
@@ -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
  ),
@@ -15,6 +15,7 @@ import asyncio
15
15
  import logging
16
16
  import os
17
17
  import platform
18
+ import re
18
19
  import sys
19
20
  from collections.abc import Callable, Mapping
20
21
  from dataclasses import dataclass, field, replace
@@ -69,6 +70,7 @@ from zettcode.engine.service_contracts import (
69
70
  ContextPageWriter,
70
71
  ContextReportService,
71
72
  )
73
+ from zettcode.version import __version__
72
74
 
73
75
  from .delivery import DELIVERY
74
76
  from .delivery_runtime import RuntimeDelivery
@@ -129,25 +131,7 @@ def _load_engine_plugins(config: ZettCodeConfig, shared: Mapping[str, object]) -
129
131
  return load_plugins(config, shared=shared)
130
132
 
131
133
 
132
- def build_system_prompt(config: ZettCodeConfig, *, now: datetime | None = None, role: str | None = None) -> str:
133
- """Build request instructions with an explicit workspace boundary.
134
-
135
- The prompt is the head of every request, so whatever it contains is part of
136
- the provider's cache key: the date is deliberately the only time-derived
137
- value, and only the day of it. A clock reading with seconds would make the
138
- head unique to each launch and drop the cache for the whole conversation.
139
-
140
- Args:
141
- config: Settings the runtime was built from.
142
- now: Moment to describe, injectable for tests; defaults to the local
143
- current time.
144
- role: The part this run plays, appended after the rules above — a client's
145
- ``system_prompt``, which is what ``daemon spawn --system`` sets. It is
146
- the process's, not the session's, and blank or ``None`` adds nothing,
147
- so a program that sets no role sends the head every other one sends.
148
- """
149
- moment = now or datetime.now().astimezone()
150
- prompt = f"""You are ZettCode, a focused coding agent working with the user in one local workspace.
134
+ DEFAULT_SYSTEM_PROMPT = """You are ZettCode, a focused coding agent working with the user in one local workspace.
151
135
 
152
136
  Inspect relevant files before editing. Make focused changes, preserve unrelated work,
153
137
  and run checks proportional to risk. Explain blockers concretely. Do not perform
@@ -177,16 +161,56 @@ what to read — the matching lines — not for printing a file. A bash call sta
177
161
  the workspace and every call is a new shell, so give it work_dir instead of cd'ing.
178
162
 
179
163
  Runtime environment:
180
- - Workspace: {config.workspace}
181
- - Today: {moment.date().isoformat()}
182
- - Operating system: {platform.platform()}
183
- - Architecture: {platform.machine() or "unknown"}
184
- - Python: {platform.python_implementation()} {platform.python_version()}
185
- - Executable: {sys.executable}
186
- - Shell: {os.getenv("SHELL", "unknown")}
164
+ - Workspace: {workspace}
165
+ - Today: {day}
166
+ - Operating system: {os}
167
+ - Architecture: {arch}
168
+ - Python: {python}
169
+ - Executable: {python_executable}
170
+ - Shell: {shell}
187
171
 
188
172
  Treat the workspace as the current working directory. Prefer relative paths in tool
189
173
  calls. Verify mutable facts with tools instead of assuming this startup snapshot is current."""
174
+
175
+ # Only bare placeholders and doubled braces have meaning. Code and unknown names stay as written.
176
+ _PROMPT_TOKEN = re.compile(r"\{\{|\}\}|\{([a-zA-Z_][a-zA-Z_0-9]*)\}")
177
+
178
+
179
+ def build_system_prompt(
180
+ config: ZettCodeConfig,
181
+ *,
182
+ model: ModelConfig | None = None,
183
+ now: datetime | None = None,
184
+ role: str | None = None,
185
+ ) -> str:
186
+ """Render the selected model's template or the built-in prompt, then append the literal run role.
187
+
188
+ The local date is the only time-derived value so the provider's cache prefix does not change within a day.
189
+ ``now`` lets tests supply that date. ``role`` is the optional SDK or daemon role, not a template.
190
+ """
191
+ moment = now or datetime.now().astimezone()
192
+ template = model.system_prompt if model is not None else None
193
+ python_version = platform.python_version()
194
+ values = {
195
+ "workspace": str(config.workspace),
196
+ "day": moment.date().isoformat(),
197
+ "os": platform.platform(),
198
+ "arch": platform.machine() or "unknown",
199
+ "python": f"{platform.python_implementation()} {python_version}",
200
+ "python_version": python_version,
201
+ "python_executable": sys.executable,
202
+ "shell": os.getenv("SHELL", "unknown"),
203
+ "version": __version__,
204
+ "model": model.model if model is not None else "unknown",
205
+ }
206
+
207
+ def expand(match: re.Match[str]) -> str:
208
+ token = match[0]
209
+ if len(token) == 2:
210
+ return token[0]
211
+ return values.get(match[1], token)
212
+
213
+ prompt = _PROMPT_TOKEN.sub(expand, template if template and template.strip() else DEFAULT_SYSTEM_PROMPT)
190
214
  role = (role or "").strip()
191
215
  if not role:
192
216
  return prompt
@@ -687,7 +711,7 @@ class ZettCodeEngine:
687
711
  client = await create_agent(
688
712
  model,
689
713
  config=AgentRunConfig(session_id=self.session_id),
690
- system_prompt=build_system_prompt(self.config, role=self.system_prompt),
714
+ system_prompt=self.prompt_for(selected),
691
715
  extensions=extensions,
692
716
  reasoning_effort=self.config.reasoning_effort,
693
717
  parallel_tool_call=self.config.parallel_tool_call,
@@ -698,6 +722,10 @@ class ZettCodeEngine:
698
722
  self.client = client
699
723
  return self
700
724
 
725
+ def prompt_for(self, model: ModelConfig | None) -> str:
726
+ """Build the base instructions for a model in this runtime, including the run's role."""
727
+ return build_system_prompt(self.config, model=model, role=self.system_prompt)
728
+
701
729
  def _provider(self, selected: ModelConfig) -> Adapter:
702
730
  """Return the provider for one configured model, building it if needed.
703
731
 
@@ -1062,11 +1090,15 @@ class ZettCodeEngine:
1062
1090
  if index is None:
1063
1091
  raise ValueError(f"Unknown model: {name}")
1064
1092
  chosen = models[index]
1093
+ previous = self.active_model
1065
1094
  self.active_model = chosen
1066
1095
  # A preview runtime has no provider yet; the model it names is what
1067
1096
  # :meth:`_build` starts from.
1068
1097
  if self.client is not None:
1069
1098
  self.model = self._provider(chosen)
1099
+ if chosen != previous and (chosen.system_prompt or (previous and previous.system_prompt)):
1100
+ # The agent copies these instructions into each fresh request. An in-flight request keeps its own.
1101
+ self.client.agent.system_prompt = self.prompt_for(chosen)
1070
1102
  # Context size is a property of the model, so switching models moves
1071
1103
  # the point at which a request is compacted with it.
1072
1104
  self.compaction.max_tokens = chosen.compaction_max_tokens
@@ -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]:
@@ -57,7 +57,7 @@ class TuiGroup(ABC):
57
57
  description: str,
58
58
  handler: Any,
59
59
  *,
60
- when_busy: str = "refuse",
60
+ when_busy: Any = "refuse",
61
61
  subcommands: Any = (),
62
62
  ) -> Any:
63
63
  """Add a command that may open a page, ask the shell to act, or wait for a request to end.
@@ -67,6 +67,10 @@ class TuiGroup(ABC):
67
67
  ``ctx.commands`` instead, where a process without a screen can run it too.
68
68
  """
69
69
 
70
+ def register_help(self, command: str, text: str) -> None:
71
+ """Stage a usage note for the help service to receive when this activation is accepted."""
72
+ raise NotImplementedError("This terminal group does not support help notes")
73
+
70
74
  @abstractmethod
71
75
  def register_command_provider(self, provider: Any) -> Any:
72
76
  """Add commands that are worked out when the menu is built, from the current state."""
@@ -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.3"
11
+ __version__ = "0.5.5"