zettcode-engine 0.4.5__tar.gz → 0.4.7__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.
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/.gitignore +1 -3
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/PKG-INFO +2 -2
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/pyproject.toml +1 -1
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/config.py +21 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/config_edit.py +4 -1
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/sessions.py +9 -1
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/settings.py +3 -3
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/core.py +114 -3
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/storage/metadata.py +10 -4
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/storage/store.py +180 -22
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/version.py +1 -1
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/_compat.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/budget.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/base.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/context.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/exports.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/interaction.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/agent/turns.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/delivery.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/delivery_runtime.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/dialogue/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/dialogue/ask.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/dialogue/side.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/dialogue/title.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/export/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/export/trace/script.js +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/export/trace/style.css +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/export/trace/template.html +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/capabilities.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/compaction.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/context.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/files.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/guidance.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/harness_switch.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/mcp_notice.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/relay.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/subagents.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/usage.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/harness_paths.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/inbox.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/permission/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/permission/approval.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/permission/readonly.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/permission/sandbox.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/pipeline.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/cli.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/commands.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/context.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/extension.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/graph.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/groups.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/llm.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/loader.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/mixins.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/plugin.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/services.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/settings.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/state.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/switches.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/plugins/triggers.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/provided.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/py.typed +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/server_tools.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/service_contracts.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/storage/__init__.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/storage/layout.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/storage/ledger.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/storage/locks.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/storage/records.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/error_text.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/filelock.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/logging_setup.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/mention.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/modes.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/paths.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/plugin_tui.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/processes.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/prompt.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/providers.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/py.typed +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/registry.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/relay.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/statusline_parts.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/wire.py +0 -0
- {zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/wording.py +0 -0
|
@@ -36,7 +36,5 @@ docs/internal/palettes.html
|
|
|
36
36
|
# The release order is generated from the pyproject.toml files (`make order`); it is not kept in git.
|
|
37
37
|
packages/order.txt
|
|
38
38
|
|
|
39
|
-
#
|
|
40
|
-
# installers under release/.
|
|
41
|
-
clients/desktop/renderer/
|
|
39
|
+
# electron-builder writes the desktop installers under release/.
|
|
42
40
|
clients/desktop/release/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: zettcode-engine
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.7
|
|
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
|
|
@@ -19,6 +19,6 @@ 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
21
|
Requires-Dist: zett-agent<0.3,>=0.2.10
|
|
22
|
-
Requires-Dist: zettcode-tools
|
|
22
|
+
Requires-Dist: zettcode-tools<0.5,>=0.4.7
|
|
23
23
|
Provides-Extra: tiktoken
|
|
24
24
|
Requires-Dist: tiktoken<1,>=0.12; extra == 'tiktoken'
|
|
@@ -18,7 +18,7 @@ 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",
|
|
21
|
+
"zettcode-tools>=0.4.7,<0.5",
|
|
22
22
|
# The runtime this is a core over. Imported directly: the agent, the message types, the approval mode.
|
|
23
23
|
"zett-agent>=0.2.10,<0.3",
|
|
24
24
|
# The session store's records are pydantic models.
|
|
@@ -77,6 +77,7 @@ MODEL_KEYS = frozenset(
|
|
|
77
77
|
"web_search_name",
|
|
78
78
|
"context_window",
|
|
79
79
|
"compact_percent",
|
|
80
|
+
"max_tokens",
|
|
80
81
|
"reasoning_efforts",
|
|
81
82
|
}
|
|
82
83
|
)
|
|
@@ -170,6 +171,10 @@ DEFAULT_AGENTS_MCP_CONFIG = "~/.agents/mcp.json"
|
|
|
170
171
|
#: Messages API lives at the root itself, not under ``/v1``.
|
|
171
172
|
DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com"
|
|
172
173
|
|
|
174
|
+
#: The host of OpenAI's own API. An entry may leave ``base_url`` out or write this address out — both are the same
|
|
175
|
+
#: endpoint — and it is the one whose reasoning models refuse ``max_tokens`` for ``max_completion_tokens``.
|
|
176
|
+
OPENAI_HOST = "api.openai.com"
|
|
177
|
+
|
|
173
178
|
#: Routes a client appends to ``base_url`` itself. Writing one out is a common
|
|
174
179
|
#: reading of "the API address", and keeping it would double the path —
|
|
175
180
|
#: ``…/v1/messages/v1/messages``, which a gateway answers with 404 for a route it
|
|
@@ -183,6 +188,13 @@ DEFAULT_CONTEXT_WINDOW = 128_000
|
|
|
183
188
|
DEFAULT_COMPACT_PERCENT = 80.0
|
|
184
189
|
KEEP_SHARE = 4
|
|
185
190
|
|
|
191
|
+
#: Tokens one reply may spend before the endpoint cuts it off, when the config does not say otherwise. The providers'
|
|
192
|
+
#: own defaults are much smaller — 4,096 on most chat endpoints, 16,384 on Anthropic — and a long answer hit that
|
|
193
|
+
#: limit, ended early, and cost the reader a `/continue` for what was one reply. Twenty thousand is under what every
|
|
194
|
+
#: current frontier model emits and over what a long answer needs, and an entry whose endpoint refuses a budget says
|
|
195
|
+
#: so on its first request, where the fix is one number in the file.
|
|
196
|
+
DEFAULT_MAX_TOKENS = 20_000
|
|
197
|
+
|
|
186
198
|
#: The sampling temperature a model may be given: 0 is the most deterministic. OpenAI-compatible endpoints take up to
|
|
187
199
|
#: 2; Anthropic's Messages API stops at 1, which is checked for an ``anthropic`` entry.
|
|
188
200
|
MAX_TEMPERATURE = 2.0
|
|
@@ -261,6 +273,11 @@ class ModelConfig:
|
|
|
261
273
|
measures against.
|
|
262
274
|
compact_percent: Share of :attr:`context_window` at which a request is
|
|
263
275
|
compacted, in percent.
|
|
276
|
+
max_tokens: Tokens one reply may spend, sent as the request's output budget: ``max_tokens`` on a chat
|
|
277
|
+
endpoint and on Anthropic's Messages API, ``max_output_tokens`` on the Responses API. ``0`` sends none,
|
|
278
|
+
which leaves the endpoint's own default in force — the escape for a provider that refuses a budget,
|
|
279
|
+
or counts the prompt against it. It is what stops an answer being cut off in the middle at the
|
|
280
|
+
provider's default.
|
|
264
281
|
reasoning_efforts: The reasoning levels this model accepts, cheapest first. The empty
|
|
265
282
|
tuple, the default, means every level: a provider that cannot express one maps it
|
|
266
283
|
onto its closest, which is what makes the default right for an endpoint whose
|
|
@@ -281,6 +298,7 @@ class ModelConfig:
|
|
|
281
298
|
multimodal: bool = False
|
|
282
299
|
context_window: int = DEFAULT_CONTEXT_WINDOW
|
|
283
300
|
compact_percent: float = DEFAULT_COMPACT_PERCENT
|
|
301
|
+
max_tokens: int = DEFAULT_MAX_TOKENS
|
|
284
302
|
reasoning_efforts: tuple[ReasoningEffort, ...] = ()
|
|
285
303
|
chat: bool = False
|
|
286
304
|
temperature: float | None = None
|
|
@@ -328,6 +346,8 @@ class ModelConfig:
|
|
|
328
346
|
raise ValueError(f"context_window must be positive for model {self.model!r}")
|
|
329
347
|
if not 0 < self.compact_percent <= 100:
|
|
330
348
|
raise ValueError(f"compact_percent must be between 0 and 100 for model {self.model!r}")
|
|
349
|
+
if isinstance(self.max_tokens, bool) or not isinstance(self.max_tokens, int) or self.max_tokens < 0:
|
|
350
|
+
raise ValueError(f"max_tokens must be 0 (the endpoint's own) or a positive number for model {self.model!r}")
|
|
331
351
|
# Cheapest first, one of each: the order is the picker's rail, and a repeat would put two
|
|
332
352
|
# nodes on one level.
|
|
333
353
|
levels = tuple(sorted(set(self.reasoning_efforts), key=tuple(ReasoningEffort).index))
|
|
@@ -730,6 +750,7 @@ def _entry_model(entry: dict[str, object], index: int, *, label: str | None = No
|
|
|
730
750
|
compact_percent=_number(
|
|
731
751
|
entry.get("compact_percent", DEFAULT_COMPACT_PERCENT), f"{label} key 'compact_percent'"
|
|
732
752
|
),
|
|
753
|
+
max_tokens=_typed(entry.get("max_tokens", DEFAULT_MAX_TOKENS), f"{label} key 'max_tokens'", int),
|
|
733
754
|
reasoning_efforts=_read_reasoning_efforts(
|
|
734
755
|
entry.get("reasoning_efforts"), f"{label} key 'reasoning_efforts'"
|
|
735
756
|
),
|
|
@@ -46,6 +46,7 @@ _KEY_ORDER = (
|
|
|
46
46
|
"web_search_name",
|
|
47
47
|
"context_window",
|
|
48
48
|
"compact_percent",
|
|
49
|
+
"max_tokens",
|
|
49
50
|
"reasoning_efforts",
|
|
50
51
|
)
|
|
51
52
|
|
|
@@ -111,7 +112,7 @@ def entry_from_model(model: ModelConfig, *, token: str | None = None) -> dict[st
|
|
|
111
112
|
model: A validated model.
|
|
112
113
|
token: What to write for the token; ``None`` writes the one the model holds.
|
|
113
114
|
"""
|
|
114
|
-
from zettcode.config import DEFAULT_COMPACT_PERCENT, DEFAULT_CONTEXT_WINDOW
|
|
115
|
+
from zettcode.config import DEFAULT_COMPACT_PERCENT, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS
|
|
115
116
|
|
|
116
117
|
written = model.token if token is None else token
|
|
117
118
|
entry: dict[str, object] = {"model": model.model}
|
|
@@ -139,6 +140,8 @@ def entry_from_model(model: ModelConfig, *, token: str | None = None) -> dict[st
|
|
|
139
140
|
entry["context_window"] = model.context_window
|
|
140
141
|
if model.compact_percent != DEFAULT_COMPACT_PERCENT:
|
|
141
142
|
entry["compact_percent"] = model.compact_percent
|
|
143
|
+
if model.max_tokens != DEFAULT_MAX_TOKENS:
|
|
144
|
+
entry["max_tokens"] = model.max_tokens
|
|
142
145
|
if model.reasoning_efforts:
|
|
143
146
|
entry["reasoning_efforts"] = [level.value for level in model.reasoning_efforts]
|
|
144
147
|
return entry
|
|
@@ -35,6 +35,8 @@ class StoredSession:
|
|
|
35
35
|
the metadata log is the other thing resuming used to do on the loop.
|
|
36
36
|
model: The model the session last used, by the name the model picker shows, if one
|
|
37
37
|
was recorded; read here for the same reason as the title.
|
|
38
|
+
effort: The reasoning level it last ran at, if one was recorded: it comes back with the
|
|
39
|
+
model, so a resume does not reason less than the conversation did.
|
|
38
40
|
"""
|
|
39
41
|
|
|
40
42
|
session_id: str
|
|
@@ -42,6 +44,7 @@ class StoredSession:
|
|
|
42
44
|
usage: UsageSnapshot
|
|
43
45
|
title: str | None
|
|
44
46
|
model: str | None = None
|
|
47
|
+
effort: str | None = None
|
|
45
48
|
|
|
46
49
|
|
|
47
50
|
class SessionsMixin(ContextMixin):
|
|
@@ -117,10 +120,11 @@ class SessionsMixin(ContextMixin):
|
|
|
117
120
|
usage=session_usage(session.branch()),
|
|
118
121
|
title=persistence.session_title(session_id),
|
|
119
122
|
model=persistence.session_model(session_id),
|
|
123
|
+
effort=persistence.session_effort(session_id),
|
|
120
124
|
)
|
|
121
125
|
|
|
122
126
|
def install_session(self, stored: StoredSession) -> None:
|
|
123
|
-
"""Make a loaded session the active one: its totals, its id, its model.
|
|
127
|
+
"""Make a loaded session the active one: its totals, its id, its model and reasoning level.
|
|
124
128
|
|
|
125
129
|
The cheap half, and the one that changes state; everything it does is assignment.
|
|
126
130
|
"""
|
|
@@ -133,6 +137,10 @@ class SessionsMixin(ContextMixin):
|
|
|
133
137
|
model = self.runtime.find_model(stored.model) if stored.model else None
|
|
134
138
|
if model is not None and model is not self.runtime.active_model:
|
|
135
139
|
self.runtime.use_model(model)
|
|
140
|
+
# The level was put back against the model the shell happened to be on, and `use_model` only moves what is
|
|
141
|
+
# in force to the nearest level the new model takes — a level the old model could not take was already
|
|
142
|
+
# gone by then. The session's own level is read again, now against the model it actually ran on.
|
|
143
|
+
self.runtime.adopt_effort()
|
|
136
144
|
# Prime the report with what the next turn would send, not with what the
|
|
137
145
|
# transcript shows: the display keeps every message a compaction folded
|
|
138
146
|
# away, and measuring those claims a request several times the size of the
|
|
@@ -257,9 +257,9 @@ class SettingsMixin(AgentBase):
|
|
|
257
257
|
model = self.runtime.active_model
|
|
258
258
|
return () if model is None else tuple(level.value for level in model.efforts)
|
|
259
259
|
|
|
260
|
-
def use_effort(self, name: str) -> str:
|
|
261
|
-
"""Select a reasoning level for later requests and return its value."""
|
|
262
|
-
return self.runtime.use_effort(name).value
|
|
260
|
+
def use_effort(self, name: str, *, remember: bool = True) -> str:
|
|
261
|
+
"""Select a reasoning level for later requests and return its value; the session keeps it unless told not to."""
|
|
262
|
+
return self.runtime.use_effort(name, remember=remember).value
|
|
263
263
|
|
|
264
264
|
def approve_all_shell_commands(self) -> None:
|
|
265
265
|
"""Approve every shell command for the rest of this run, without asking."""
|
|
@@ -20,6 +20,7 @@ from collections.abc import Callable, Mapping
|
|
|
20
20
|
from dataclasses import dataclass, field, replace
|
|
21
21
|
from datetime import datetime
|
|
22
22
|
from typing import TYPE_CHECKING, TypeAlias
|
|
23
|
+
from urllib.parse import urlparse
|
|
23
24
|
|
|
24
25
|
from zett_agent.agent import AgentRunConfig
|
|
25
26
|
from zett_agent.client import AgentClient
|
|
@@ -34,6 +35,7 @@ from zettcode.config import (
|
|
|
34
35
|
KEYLESS_TOKEN,
|
|
35
36
|
NO_MODEL_CHOSEN,
|
|
36
37
|
NO_MODEL_REFUSAL,
|
|
38
|
+
OPENAI_HOST,
|
|
37
39
|
ModelConfig,
|
|
38
40
|
ZettCodeConfig,
|
|
39
41
|
model_index,
|
|
@@ -191,14 +193,33 @@ def _build_provider(selected: ModelConfig) -> Adapter:
|
|
|
191
193
|
A model with no key is called with :data:`KEYLESS_TOKEN`, because the adapters refuse to be built without one and a
|
|
192
194
|
local server ignores what it is sent. The temperature is the adapter's own argument on an OpenAI-compatible
|
|
193
195
|
endpoint; Anthropic's adapter has none, so it goes in the body of the request, where the API reads it.
|
|
196
|
+
|
|
197
|
+
The output budget is :attr:`ModelConfig.max_tokens`: the adapter's own ``max_tokens`` where it has one, and a
|
|
198
|
+
field of the request body where it does not. Which field is not one name: the Responses API calls it
|
|
199
|
+
``max_output_tokens``, OpenAI's own chat API calls it ``max_completion_tokens`` — its reasoning models refuse
|
|
200
|
+
``max_tokens`` — and every other chat endpoint (DeepSeek, GLM, a local server) calls it ``max_tokens``, so the
|
|
201
|
+
name follows the endpoint: OpenAI's own address when the entry names none, the compatible spelling when it does.
|
|
202
|
+
Zero sends none, so an endpoint whose own default is what the reader wants keeps it; every other entry spends the
|
|
203
|
+
budget instead of the provider's smaller default, which is what used to end a long answer in the middle with
|
|
204
|
+
``max_tokens``.
|
|
205
|
+
|
|
206
|
+
A budget larger than the window is sent as the window: a reply longer than the context that has to hold it is not
|
|
207
|
+
a request any endpoint can serve, and the default of 20,000 would otherwise make every small-context entry
|
|
208
|
+
impossible the moment it was read. The entry keeps the number it was given; only the request is bounded.
|
|
194
209
|
"""
|
|
195
210
|
token = selected.token or KEYLESS_TOKEN
|
|
211
|
+
budget = min(selected.max_tokens, selected.context_window) if selected.max_tokens > 0 else 0
|
|
196
212
|
if selected.anthropic:
|
|
197
213
|
from zett_agent.providers.anthropic import AnthropicProvider
|
|
198
214
|
|
|
199
215
|
extra: dict[str, object] = {}
|
|
216
|
+
body: dict[str, object] = {}
|
|
200
217
|
if selected.temperature is not None:
|
|
201
|
-
|
|
218
|
+
body["temperature"] = selected.temperature
|
|
219
|
+
if body:
|
|
220
|
+
extra["extra_body"] = body
|
|
221
|
+
if budget > 0:
|
|
222
|
+
extra["max_tokens"] = budget
|
|
202
223
|
return AnthropicProvider(
|
|
203
224
|
selected.model,
|
|
204
225
|
token,
|
|
@@ -210,6 +231,9 @@ def _build_provider(selected: ModelConfig) -> Adapter:
|
|
|
210
231
|
options: dict[str, object] = {}
|
|
211
232
|
if selected.temperature is not None:
|
|
212
233
|
options["temperature"] = selected.temperature
|
|
234
|
+
if budget > 0:
|
|
235
|
+
# The OpenAI SDK sends `extra_body` as fields of the request, which is where an output budget belongs.
|
|
236
|
+
options["extra_body"] = {_budget_field(selected): budget}
|
|
213
237
|
return OpenAIProvider(
|
|
214
238
|
selected.model,
|
|
215
239
|
token,
|
|
@@ -219,6 +243,25 @@ def _build_provider(selected: ModelConfig) -> Adapter:
|
|
|
219
243
|
)
|
|
220
244
|
|
|
221
245
|
|
|
246
|
+
def _budget_field(selected: ModelConfig) -> str:
|
|
247
|
+
"""Return the field one endpoint reads the output budget from, by the API it speaks and whose it is.
|
|
248
|
+
|
|
249
|
+
The Responses API names it ``max_output_tokens``. Chat completions has two spellings: OpenAI's own API takes
|
|
250
|
+
``max_completion_tokens``, which its reasoning models demand and its older ones accept, while the compatible
|
|
251
|
+
endpoints (DeepSeek, GLM, a local server) take ``max_tokens``. A compatible endpoint that also refuses
|
|
252
|
+
``max_tokens`` sets ``max_tokens = 0`` and keeps its own default.
|
|
253
|
+
|
|
254
|
+
Which of the two is decided by the *host*, not by whether the entry wrote an address: an entry that spells out
|
|
255
|
+
``https://api.openai.com/v1`` — the way the guide shows one — is the same endpoint as one that leaves ``base_url``
|
|
256
|
+
out, and a test on "no address at all" would hand it the spelling its reasoning models refuse.
|
|
257
|
+
"""
|
|
258
|
+
if selected.responses_api:
|
|
259
|
+
return "max_output_tokens"
|
|
260
|
+
host = "" if selected.base_url is None else (urlparse(selected.base_url).hostname or "")
|
|
261
|
+
openai = host == OPENAI_HOST or host.endswith(f".{OPENAI_HOST}")
|
|
262
|
+
return "max_completion_tokens" if selected.base_url is None or openai else "max_tokens"
|
|
263
|
+
|
|
264
|
+
|
|
222
265
|
class _ContextReportAdapter(ContextReportService):
|
|
223
266
|
"""A context report service bound to the runtime after its plugins have loaded."""
|
|
224
267
|
|
|
@@ -295,6 +338,10 @@ class ZettCodeEngine:
|
|
|
295
338
|
#: What the compaction counts the context with; loaded on a thread of its own so that the
|
|
296
339
|
#: first turn does not load it on the event loop. See :class:`CompactionCounter`.
|
|
297
340
|
compaction_counter: CompactionCounter
|
|
341
|
+
#: The reasoning level a run starts at — the configuration's ``reasoning_effort`` as the first model takes it —
|
|
342
|
+
#: and what a session that never chose one goes back to when it is opened again. Here rather than beside
|
|
343
|
+
#: :attr:`effort` because every field after it already has a default.
|
|
344
|
+
default_effort: ReasoningEffort = ReasoningEffort.MEDIUM
|
|
298
345
|
plugins: Plugins = field(default_factory=Plugins)
|
|
299
346
|
#: The lock on the session this process has open: only the process that holds it writes to the session.
|
|
300
347
|
#: A runtime that was not given one (a test's) shares nothing, so every claim is granted.
|
|
@@ -323,9 +370,14 @@ class ZettCodeEngine:
|
|
|
323
370
|
_self_choices: dict[str, bool | None] = field(default_factory=dict, repr=False)
|
|
324
371
|
#: Each session's own permission level as last read or written; see :meth:`permission_choice`.
|
|
325
372
|
_permissions: dict[str, str | None] = field(default_factory=dict, repr=False)
|
|
373
|
+
#: Each session's own reasoning level as last read or written; see :meth:`effort_choice`.
|
|
374
|
+
_efforts: dict[str, str | None] = field(default_factory=dict, repr=False)
|
|
326
375
|
#: Whether a level was chosen for this process rather than for a session (``--full``, a client's
|
|
327
376
|
#: ``permission=``): while it is set, opening a session does not put that session's level back.
|
|
328
377
|
_permission_override: bool = field(default=False, repr=False)
|
|
378
|
+
#: The same for the reasoning level: a client built with ``effort=`` runs at that level whatever the session
|
|
379
|
+
#: recorded, and does not write it down.
|
|
380
|
+
_effort_override: bool = field(default=False, repr=False)
|
|
329
381
|
#: The warm-up imports, running on a daemon thread, and the loop-side event
|
|
330
382
|
#: that releases whoever is waiting for them.
|
|
331
383
|
_imports: ImportPipeline | None = field(default=None, repr=False)
|
|
@@ -427,6 +479,7 @@ class ZettCodeEngine:
|
|
|
427
479
|
default_permission=policy.level,
|
|
428
480
|
tokenizer=Tokenizer(),
|
|
429
481
|
effort=effort,
|
|
482
|
+
default_effort=effort,
|
|
430
483
|
session_id=new_uuid7(),
|
|
431
484
|
active_model=selected,
|
|
432
485
|
compaction_counter=counter,
|
|
@@ -841,23 +894,34 @@ class ZettCodeEngine:
|
|
|
841
894
|
choice = self.self_compaction_choice(session_id)
|
|
842
895
|
return self.config.self_compaction if choice is None else choice
|
|
843
896
|
|
|
844
|
-
def use_effort(self, name: str | ReasoningEffort) -> ReasoningEffort:
|
|
845
|
-
"""Select how much reasoning the model may spend on later requests.
|
|
897
|
+
def use_effort(self, name: str | ReasoningEffort, *, remember: bool = True) -> ReasoningEffort:
|
|
898
|
+
"""Select how much reasoning the model may spend on later requests, and remember it for this session.
|
|
846
899
|
|
|
847
900
|
A level the active model does not take is refused, naming the ones it does: a reader who typed
|
|
848
901
|
``/effort ultra`` should hear that this model stops at ``high``, not get ``high`` unannounced.
|
|
849
902
|
(A level that is *inherited* — the one in force when the model changes — is moved, by
|
|
850
903
|
:meth:`use_model`, because nobody asked for it.)
|
|
851
904
|
|
|
905
|
+
The level is written to the session's own metadata, so opening the session again reasons as much as it
|
|
906
|
+
last did instead of going back to what a new session starts at; a session set back to the level a run
|
|
907
|
+
starts at forgets the choice and follows the default. A new session begins at the default, so one job's
|
|
908
|
+
choice does not leak into the next.
|
|
909
|
+
|
|
852
910
|
Args:
|
|
853
911
|
name: One of zett-agent's levels, by value (``"high"``) or as the
|
|
854
912
|
enum itself; case and surrounding space are ignored.
|
|
913
|
+
remember: Whether the level belongs to the session. ``False`` is for a level this *process* runs
|
|
914
|
+
at — a client built with ``effort=``, a daemon told ``--effort`` — which then survives opening
|
|
915
|
+
another session and leaves every session's own level as it was.
|
|
855
916
|
|
|
856
917
|
Returns:
|
|
857
918
|
The level now in force.
|
|
858
919
|
|
|
859
920
|
Raises:
|
|
860
921
|
ValueError: The name is not a level, or the active model does not take it, or no model is configured.
|
|
922
|
+
SessionLocked: Another process has the session open, and the level is part of the session.
|
|
923
|
+
OSError: The level could not be written to the session; nothing changed, so a caller that reported
|
|
924
|
+
success would be reporting a setting that is not on disk.
|
|
861
925
|
"""
|
|
862
926
|
if isinstance(name, ReasoningEffort):
|
|
863
927
|
level = name
|
|
@@ -874,9 +938,54 @@ class ZettCodeEngine:
|
|
|
874
938
|
if level not in accepted:
|
|
875
939
|
levels = ", ".join(known.value for known in accepted)
|
|
876
940
|
raise ValueError(f"{active.shown_name} does not take {level.value}. Try one of: {levels}")
|
|
941
|
+
if remember:
|
|
942
|
+
# The level is stored in the session, so it is a write, and only the process holding the session may
|
|
943
|
+
# write to it. The other settings that are the session's own ask the same question first.
|
|
944
|
+
if self.session_locked:
|
|
945
|
+
raise SessionLocked()
|
|
946
|
+
self.persistence.set_effort(self.session_id, level.value, default=self.default_effort.value)
|
|
947
|
+
self._efforts[self.session_id] = level.value
|
|
948
|
+
# The level belongs to the session again, so opening another one puts that one's level back.
|
|
949
|
+
self._effort_override = False
|
|
950
|
+
else:
|
|
951
|
+
# A level chosen for this process wins over what a session remembers, for as long as it runs.
|
|
952
|
+
self._effort_override = True
|
|
877
953
|
self.effort = level
|
|
878
954
|
return level
|
|
879
955
|
|
|
956
|
+
def effort_choice(self, session_id: str) -> str | None:
|
|
957
|
+
"""Return the level one session last ran at, ``None`` when it never chose one.
|
|
958
|
+
|
|
959
|
+
Read from the session's file once and remembered: opening a session asks on every start, and the only
|
|
960
|
+
writer is the process holding the session's lock.
|
|
961
|
+
"""
|
|
962
|
+
if session_id not in self._efforts:
|
|
963
|
+
self._efforts[session_id] = self.persistence.session_effort(session_id)
|
|
964
|
+
return self._efforts[session_id]
|
|
965
|
+
|
|
966
|
+
def adopt_effort(self) -> None:
|
|
967
|
+
"""Put the active session's own level in force, or the one a run starts at when it has none.
|
|
968
|
+
|
|
969
|
+
The stored level is moved to the nearest one the model in use takes, as :meth:`use_model` does: a session
|
|
970
|
+
recorded against a model that went away, or a configuration that narrowed ``reasoning_efforts`` since,
|
|
971
|
+
must not send a request with a level its endpoint rejects.
|
|
972
|
+
|
|
973
|
+
Called when a session is selected — and again by whoever switches to the session's own model afterwards, which
|
|
974
|
+
is the order :meth:`install_session` uses: the level must be read against the model the session ran on, not
|
|
975
|
+
against whichever one the shell happened to be on, or a level the narrow model cannot take is lost on the way
|
|
976
|
+
back to the model that can.
|
|
977
|
+
"""
|
|
978
|
+
if self._effort_override:
|
|
979
|
+
return
|
|
980
|
+
stored = self.effort_choice(self.session_id)
|
|
981
|
+
try:
|
|
982
|
+
chosen = self.default_effort if stored is None else ReasoningEffort(stored)
|
|
983
|
+
except ValueError:
|
|
984
|
+
# A level a newer version wrote, or a damaged file: the default is the honest answer.
|
|
985
|
+
chosen = self.default_effort
|
|
986
|
+
active = self.active_model
|
|
987
|
+
self.effort = chosen if active is None else active.accepted_effort(chosen)
|
|
988
|
+
|
|
880
989
|
def find_model(self, name: str) -> ModelConfig | None:
|
|
881
990
|
"""Return the configured model a recorded name stands for, if exactly one does.
|
|
882
991
|
|
|
@@ -984,6 +1093,7 @@ class ZettCodeEngine:
|
|
|
984
1093
|
self.session_id = new_uuid7()
|
|
985
1094
|
self.session_locks.claim(self.session_id)
|
|
986
1095
|
self._adopt_permission()
|
|
1096
|
+
self.adopt_effort()
|
|
987
1097
|
return self.session_id
|
|
988
1098
|
|
|
989
1099
|
def use_session(self, session_id: str) -> None:
|
|
@@ -997,6 +1107,7 @@ class ZettCodeEngine:
|
|
|
997
1107
|
self.session_id = session_id.strip()
|
|
998
1108
|
self.session_locks.claim(self.session_id)
|
|
999
1109
|
self._adopt_permission()
|
|
1110
|
+
self.adopt_effort()
|
|
1000
1111
|
|
|
1001
1112
|
@property
|
|
1002
1113
|
def session_locked(self) -> bool:
|
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
{"version": 1, "session_id": "01a1...", "created_at": "...", "updated_at": "...",
|
|
6
6
|
"title": "Fix the parser", "model": "gpt-5-mini"}
|
|
7
7
|
|
|
8
|
-
It is written when a session begins, when it is renamed,
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
It is written when a session begins, when it is renamed, when the model it uses changes, and when a
|
|
9
|
+
setting the session keeps for itself changes — its permission level, its reasoning level, its choice
|
|
10
|
+
about self-compaction — and at no other time — about two hundred bytes, whatever the conversation does.
|
|
11
|
+
A file written before one of those was recorded simply has none, and a reader that does not know the
|
|
12
|
+
field ignores it, so the layout version is unchanged. What a list needs besides that is when the
|
|
12
13
|
conversation last changed, and the conversation file already says so: its modification time moves
|
|
13
14
|
with every message it is given, so the age a list shows is read from there instead of being
|
|
14
15
|
written down again on every append. The folder is also the unit a person copies, moves or
|
|
@@ -94,6 +95,11 @@ class SessionMetadata(BaseModel):
|
|
|
94
95
|
#: it never chose one and a run starts at the level it was built with. Resuming the session puts it back in
|
|
95
96
|
#: force, so a reader who chose ``full`` for a job does not answer the question again on the next start.
|
|
96
97
|
permission: str | None = None
|
|
98
|
+
#: The reasoning level this session last ran at — ``low``, ``high``, ... — or ``None`` when it never chose one
|
|
99
|
+
#: and a run starts at the configuration's ``reasoning_effort``. It travels with the model, which is why it is
|
|
100
|
+
#: recorded at all: a conversation that reasoned at ``high`` and is resumed at the level a *new* session starts
|
|
101
|
+
#: at would answer the same question with less care, and nothing on screen would say why.
|
|
102
|
+
effort: str | None = None
|
|
97
103
|
|
|
98
104
|
|
|
99
105
|
@dataclass(frozen=True, slots=True)
|
|
@@ -29,13 +29,14 @@ from __future__ import annotations
|
|
|
29
29
|
|
|
30
30
|
import asyncio
|
|
31
31
|
import json
|
|
32
|
+
import os
|
|
32
33
|
import threading
|
|
33
34
|
from collections import Counter
|
|
34
35
|
from collections.abc import Iterator, Mapping, Sequence
|
|
35
36
|
from dataclasses import dataclass, field, replace
|
|
36
37
|
from datetime import datetime
|
|
37
38
|
from pathlib import Path
|
|
38
|
-
from typing import cast
|
|
39
|
+
from typing import BinaryIO, cast
|
|
39
40
|
from weakref import WeakKeyDictionary
|
|
40
41
|
|
|
41
42
|
from pydantic import ValidationError
|
|
@@ -92,6 +93,26 @@ from .records import (
|
|
|
92
93
|
#: reach it through :meth:`SessionPersistenceMixin.session_dir`, so the name is stated here, once.
|
|
93
94
|
KEPT_OUTPUT = "tool-output"
|
|
94
95
|
|
|
96
|
+
#: How many bytes before the end of a read are remembered, to tell an appended file from a replaced one.
|
|
97
|
+
_ANCHOR = 64
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True, slots=True)
|
|
101
|
+
class _Reading:
|
|
102
|
+
"""Where the last read of a session file stopped, so the next one can start there.
|
|
103
|
+
|
|
104
|
+
Attributes:
|
|
105
|
+
session: What that read produced.
|
|
106
|
+
offset: The byte after the last line it took in.
|
|
107
|
+
anchor: The bytes just before ``offset``. A file that no longer has them there was replaced, not appended to.
|
|
108
|
+
lines: How many lines the read took in, so an error further on can name its line number.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
session: Session
|
|
112
|
+
offset: int
|
|
113
|
+
anchor: bytes
|
|
114
|
+
lines: int = 0
|
|
115
|
+
|
|
95
116
|
|
|
96
117
|
def message_context(
|
|
97
118
|
value: Mapping[str, object] | None, *, field: str, nonempty_keys: bool = False
|
|
@@ -174,6 +195,8 @@ class SessionPersistenceMixin:
|
|
|
174
195
|
# is the hot path — one call per message — so it must not re-parse the
|
|
175
196
|
# whole log; the cache makes a read O(1) and a write a tuple copy.
|
|
176
197
|
self._sessions: dict[str, tuple[tuple[int, int] | None, Session]] = {}
|
|
198
|
+
#: Where the last full or partial read of each session stopped, so a log that only grew is read from there.
|
|
199
|
+
self._readings: dict[str, _Reading] = {}
|
|
177
200
|
#: A read now runs on a worker thread for the framework's restore hook,
|
|
178
201
|
#: while appends still fold into the same cache on the loop. The lock
|
|
179
202
|
#: orders only the cache lookups and the publish; the parse itself runs
|
|
@@ -253,36 +276,91 @@ class SessionPersistenceMixin:
|
|
|
253
276
|
return cached[1]
|
|
254
277
|
if stamp is None:
|
|
255
278
|
session = Session(header=None, messages=(), compactions=(), head_id=None)
|
|
279
|
+
reading: _Reading | None = None
|
|
256
280
|
else:
|
|
257
|
-
|
|
281
|
+
with self._cache_lock:
|
|
282
|
+
known = self._readings.get(session_id)
|
|
283
|
+
session, reading = self._read_from(path, known)
|
|
258
284
|
with self._cache_lock:
|
|
259
285
|
cached = self._sessions.get(session_id)
|
|
260
286
|
if stamp is not None and cached is not None and cached[0] is not None and cached[0] >= stamp:
|
|
261
287
|
return cached[1]
|
|
262
288
|
self._sessions[session_id] = (stamp, session)
|
|
289
|
+
if reading is None:
|
|
290
|
+
self._forget(session_id, keep_session=True)
|
|
291
|
+
else:
|
|
292
|
+
self._readings[session_id] = reading
|
|
263
293
|
return session
|
|
264
294
|
|
|
265
|
-
def
|
|
266
|
-
"""
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
295
|
+
def _forget(self, session_id: str, *, keep_session: bool = False) -> None:
|
|
296
|
+
"""Drop what is remembered of a session's file: the parse, and where the last read of it stopped.
|
|
297
|
+
|
|
298
|
+
They go together, because a reading kept without its entry would be continued from by the next read, and
|
|
299
|
+
"dropped" has always meant "read again from the first byte".
|
|
300
|
+
"""
|
|
301
|
+
with self._cache_lock:
|
|
302
|
+
if not keep_session:
|
|
303
|
+
self._sessions.pop(session_id, None)
|
|
304
|
+
self._readings.pop(session_id, None)
|
|
305
|
+
|
|
306
|
+
def _read_from(self, path: Path, known: _Reading | None) -> tuple[Session, _Reading]:
|
|
307
|
+
"""Parse a session file, taking only what was appended since ``known`` when that is safe.
|
|
308
|
+
|
|
309
|
+
The log is append-only, so a file that is longer than it was, with the same bytes where the earlier read
|
|
310
|
+
stopped, is the earlier file plus new lines: only those are parsed. Anything else (shorter, a different
|
|
311
|
+
file, other bytes before the offset) is parsed whole, so a replaced file can never be read as an extension.
|
|
312
|
+
"""
|
|
313
|
+
with path.open("rb") as handle:
|
|
314
|
+
size = os.fstat(handle.fileno()).st_size
|
|
315
|
+
if known is not None and self._extends(handle, known, size):
|
|
316
|
+
handle.seek(known.offset)
|
|
317
|
+
tail = handle.read(size - known.offset)
|
|
318
|
+
return self._parse_tail(path, known, tail)
|
|
319
|
+
handle.seek(0)
|
|
320
|
+
return self._parse_tail(path, None, handle.read(size))
|
|
321
|
+
|
|
322
|
+
@staticmethod
|
|
323
|
+
def _extends(handle: BinaryIO, known: _Reading, size: int) -> bool:
|
|
324
|
+
"""Return whether the file still has the bytes the earlier read ended on, in the same place.
|
|
325
|
+
|
|
326
|
+
An equal-size file with those bytes is an extension of nothing: the parse of its empty tail is the cached one.
|
|
327
|
+
"""
|
|
328
|
+
if size < known.offset or known.offset == 0:
|
|
329
|
+
return False
|
|
330
|
+
anchor = min(known.offset, _ANCHOR)
|
|
331
|
+
handle.seek(known.offset - anchor)
|
|
332
|
+
return handle.read(anchor) == known.anchor
|
|
333
|
+
|
|
334
|
+
def _parse_tail(self, path: Path, known: _Reading | None, data: bytes) -> tuple[Session, _Reading]:
|
|
335
|
+
"""Parse ``data`` (the whole file, or what follows ``known``) and return the session and where it ended.
|
|
336
|
+
|
|
337
|
+
Only whole lines are consumed: a final line with no newline is parsed when it is complete JSON (the writer
|
|
338
|
+
is between its two writes) and left for the next read when it is not, so a torn line is never skipped.
|
|
339
|
+
"""
|
|
340
|
+
base = known.offset if known is not None else 0
|
|
341
|
+
first_line = known.lines + 1 if known is not None else 1
|
|
342
|
+
# Bytes, split on b"\n" only: ``str.splitlines`` also breaks at U+2028, U+2029 and U+0085, which JSON writes
|
|
343
|
+
# into a string as they are, and a message that held one was once cut in half and the file called corrupt.
|
|
344
|
+
lines = data.split(b"\n")
|
|
345
|
+
trailing = lines.pop() # what follows the last newline: usually empty
|
|
346
|
+
header = known.session.header if known is not None else None
|
|
347
|
+
messages = list(known.session.messages) if known is not None else []
|
|
348
|
+
compactions = list(known.session.compactions) if known is not None else []
|
|
349
|
+
head_id = known.session.head_id if known is not None else None
|
|
350
|
+
consumed = 0
|
|
277
351
|
for index, line in enumerate(lines):
|
|
352
|
+
consumed += len(line) + 1
|
|
278
353
|
if not line.strip():
|
|
279
354
|
continue
|
|
280
355
|
try:
|
|
281
356
|
parsed = LINES.validate_json(line)
|
|
282
357
|
except ValidationError as error:
|
|
283
|
-
if index == len(lines) - 1:
|
|
284
|
-
|
|
285
|
-
|
|
358
|
+
if index == len(lines) - 1 and not trailing.strip():
|
|
359
|
+
consumed -= len(line) + 1 # a torn last line: leave it for the next read
|
|
360
|
+
break
|
|
361
|
+
raise ValueError(
|
|
362
|
+
f"Corrupt session file {path.name} at line {first_line + index} (byte {base + consumed - len(line) - 1})"
|
|
363
|
+
) from error
|
|
286
364
|
match parsed:
|
|
287
365
|
case SessionLine():
|
|
288
366
|
header = parsed
|
|
@@ -293,8 +371,33 @@ class SessionPersistenceMixin:
|
|
|
293
371
|
compactions.append(parsed)
|
|
294
372
|
case other:
|
|
295
373
|
raise ValueError(f"Unknown session record: {type(other).__name__}")
|
|
374
|
+
if trailing.strip():
|
|
375
|
+
try:
|
|
376
|
+
parsed = LINES.validate_json(trailing)
|
|
377
|
+
except ValidationError:
|
|
378
|
+
pass # half a record: the next read starts at its first byte
|
|
379
|
+
else:
|
|
380
|
+
consumed += len(trailing)
|
|
381
|
+
match parsed:
|
|
382
|
+
case SessionLine():
|
|
383
|
+
header = parsed
|
|
384
|
+
case MessageLine():
|
|
385
|
+
messages.append(parsed)
|
|
386
|
+
head_id = parsed.id
|
|
387
|
+
case CompactionLine():
|
|
388
|
+
compactions.append(parsed)
|
|
389
|
+
case other:
|
|
390
|
+
raise ValueError(f"Unknown session record: {type(other).__name__}")
|
|
391
|
+
elif trailing:
|
|
392
|
+
consumed += len(trailing) # blanks only
|
|
296
393
|
self._check_links(path, messages, compactions)
|
|
297
|
-
|
|
394
|
+
session = Session(header=header, messages=tuple(messages), compactions=tuple(compactions), head_id=head_id)
|
|
395
|
+
end = base + consumed
|
|
396
|
+
# The anchor comes from the bytes just parsed, never from a second look at the file: a writer could have
|
|
397
|
+
# appended in between, and the anchor would then describe bytes this read never took in.
|
|
398
|
+
before = (known.anchor if known is not None else b"") + data[:consumed]
|
|
399
|
+
taken = data[:consumed].count(b"\n") + (1 if consumed and not data[:consumed].endswith(b"\n") else 0)
|
|
400
|
+
return session, _Reading(session, end, before[-_ANCHOR:], (known.lines if known is not None else 0) + taken)
|
|
298
401
|
|
|
299
402
|
@staticmethod
|
|
300
403
|
def _stamp(path: Path) -> tuple[int, int]:
|
|
@@ -348,7 +451,14 @@ class SessionPersistenceMixin:
|
|
|
348
451
|
A cache entry that does not know the line's parent is dropped rather
|
|
349
452
|
than extended: a worker may have published an empty session between the
|
|
350
453
|
append's leading read and this call, and a one-line cache would then
|
|
351
|
-
claim to be the whole history.
|
|
454
|
+
claim to be the whole history. Its reading is dropped with it, so a
|
|
455
|
+
dropped entry means the next read parses the file whole, as it always did.
|
|
456
|
+
|
|
457
|
+
The reading of a kept entry is deliberately *not* advanced to the spliced
|
|
458
|
+
session. It stays where the last read of the file stopped, so the first
|
|
459
|
+
read after another writer appends parses this process's recent lines once
|
|
460
|
+
more, and that is what keeps them from being counted twice: moving the
|
|
461
|
+
reading forward here would add each of them to the session a second time.
|
|
352
462
|
"""
|
|
353
463
|
with self._cache_lock:
|
|
354
464
|
cached = self._sessions.get(session_id)
|
|
@@ -364,7 +474,7 @@ class SessionPersistenceMixin:
|
|
|
364
474
|
and line.parent != session.head_id
|
|
365
475
|
and session.message(line.parent) is None
|
|
366
476
|
):
|
|
367
|
-
self.
|
|
477
|
+
self._forget(session_id)
|
|
368
478
|
return
|
|
369
479
|
# A read on a worker may have parsed the file after this
|
|
370
480
|
# append wrote it but before it reached this cache update.
|
|
@@ -375,7 +485,7 @@ class SessionPersistenceMixin:
|
|
|
375
485
|
session = replace(session, messages=(*session.messages, line), head_id=line.id)
|
|
376
486
|
case CompactionLine():
|
|
377
487
|
if session.message(line.parent) is None:
|
|
378
|
-
self.
|
|
488
|
+
self._forget(session_id)
|
|
379
489
|
return
|
|
380
490
|
if not any(item.id == line.id for item in session.compactions):
|
|
381
491
|
session = replace(session, compactions=(*session.compactions, line))
|
|
@@ -524,7 +634,8 @@ class SessionPersistenceMixin:
|
|
|
524
634
|
f"{title}{FORK_SUFFIX}" if title is not None and len(f"{title}{FORK_SUFFIX}") <= MAX_TITLE else None
|
|
525
635
|
)
|
|
526
636
|
# A fork carries on from where the session left off, so it uses the model that did,
|
|
527
|
-
# and keeps the choice about compaction that was made
|
|
637
|
+
# reasons at the level that did, and keeps the choice about compaction that was made
|
|
638
|
+
# for that conversation.
|
|
528
639
|
self._begin_metadata(
|
|
529
640
|
new_id,
|
|
530
641
|
created_at,
|
|
@@ -532,6 +643,7 @@ class SessionPersistenceMixin:
|
|
|
532
643
|
model=self.session_model(session_id),
|
|
533
644
|
self_compact=self.session_self_compact(session_id),
|
|
534
645
|
permission=self.session_permission(session_id),
|
|
646
|
+
effort=self.session_effort(session_id),
|
|
535
647
|
)
|
|
536
648
|
parent: str | None = None
|
|
537
649
|
if checkpoint is not None:
|
|
@@ -676,6 +788,50 @@ class SessionPersistenceMixin:
|
|
|
676
788
|
metadata = self._metadata(session_id)
|
|
677
789
|
return metadata.permission if metadata is not None else None
|
|
678
790
|
|
|
791
|
+
def session_effort(self, session_id: str) -> str | None:
|
|
792
|
+
"""Return the reasoning level one session last ran at, or ``None`` when it never chose.
|
|
793
|
+
|
|
794
|
+
``None`` is the answer of every session whose file predates the setting, and of every session nobody
|
|
795
|
+
changed the level in; a run of one of those starts at the configuration's ``reasoning_effort``.
|
|
796
|
+
"""
|
|
797
|
+
metadata = self._metadata(session_id)
|
|
798
|
+
return metadata.effort if metadata is not None else None
|
|
799
|
+
|
|
800
|
+
def set_effort(self, session_id: str, level: str | None, *, default: str) -> None:
|
|
801
|
+
"""Record the reasoning level one session last ran at.
|
|
802
|
+
|
|
803
|
+
The same rule as :meth:`set_permission`: the level is metadata, so only this small file is rewritten and
|
|
804
|
+
the title, the model and the times stay as they were; a level equal to the one a run starts at records
|
|
805
|
+
nothing — and takes back a level recorded before, so a session put back to the default really does follow
|
|
806
|
+
it; and a level differing from it records the session before the first message does, the header going in
|
|
807
|
+
first.
|
|
808
|
+
|
|
809
|
+
Args:
|
|
810
|
+
session_id: The session the level belongs to.
|
|
811
|
+
level: The level's name, or ``None`` to forget the choice.
|
|
812
|
+
default: What a session with no level runs at, to tell a choice that changes something from one
|
|
813
|
+
that does not.
|
|
814
|
+
|
|
815
|
+
Raises:
|
|
816
|
+
OSError: The metadata file could not be replaced, so nothing was saved.
|
|
817
|
+
"""
|
|
818
|
+
stored = level if level != default else None
|
|
819
|
+
metadata = self._metadata(session_id)
|
|
820
|
+
if metadata is None:
|
|
821
|
+
if stored is None:
|
|
822
|
+
return
|
|
823
|
+
created_at = self._write_header(self.read(session_id), session_id, None, None)
|
|
824
|
+
metadata = (
|
|
825
|
+
SessionMetadata(session_id=session_id, created_at=created_at, updated_at=created_at)
|
|
826
|
+
if created_at is not None
|
|
827
|
+
else self._metadata(session_id)
|
|
828
|
+
)
|
|
829
|
+
if metadata is None or metadata.effort == stored:
|
|
830
|
+
return
|
|
831
|
+
updated = metadata.model_copy(update={"effort": stored})
|
|
832
|
+
if not write_session_metadata(self._metadata_file(session_id), updated):
|
|
833
|
+
raise OSError(f"Could not save the reasoning level for session {session_id!r}")
|
|
834
|
+
|
|
679
835
|
def set_permission(self, session_id: str, level: str | None, *, default: str) -> None:
|
|
680
836
|
"""Record the permission level one session last ran at.
|
|
681
837
|
|
|
@@ -765,6 +921,7 @@ class SessionPersistenceMixin:
|
|
|
765
921
|
model: str | None = None,
|
|
766
922
|
self_compact: bool | None = None,
|
|
767
923
|
permission: str | None = None,
|
|
924
|
+
effort: str | None = None,
|
|
768
925
|
) -> SessionMetadata:
|
|
769
926
|
"""Write the metadata of a session that has just been created, and return it."""
|
|
770
927
|
metadata = SessionMetadata(
|
|
@@ -775,6 +932,7 @@ class SessionPersistenceMixin:
|
|
|
775
932
|
model=model,
|
|
776
933
|
self_compact=self_compact,
|
|
777
934
|
permission=permission,
|
|
935
|
+
effort=effort,
|
|
778
936
|
)
|
|
779
937
|
write_session_metadata(self._metadata_file(session_id), metadata)
|
|
780
938
|
return metadata
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/export/trace/template.html
RENAMED
|
File without changes
|
|
File without changes
|
{zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/capabilities.py
RENAMED
|
File without changes
|
{zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/compaction.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/harness_switch.py
RENAMED
|
File without changes
|
{zettcode_engine-0.4.5 → zettcode_engine-0.4.7}/src/zettcode/engine/extensions/mcp_notice.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|