Skip to content

Agent Zero AI framework

Scope settings snapshots to prompt builds

Alessandrod1a9bfa13e22
diff --git a/extensions/python/_functions/AGENTS.md b/extensions/python/_functions/AGENTS.md
index db75fd4af..1fe2f6a0d 100644
--- a/extensions/python/_functions/AGENTS.md
+++ b/extensions/python/_functions/AGENTS.md
@@ -17,6 +17,7 @@
- Preserve ordering prefixes where exception handling, watchdog registration, or cleanup depends on them.
- Hooks that mirror persisted AI responses into UI logs must reuse existing stream log items and avoid duplicating live response-tool logs.
- Recovery-loop circuit breakers must stop at the General Settings limit and render their user-visible cost warning from a core framework prompt.
+- Prompt settings snapshots must be task-local, accessed through `get_settings_for_prompt()`, and end with the matching `Agent.prepare_prompt` call, including exceptional exits.
## Work Guidance
diff --git a/extensions/python/_functions/agent/Agent/prepare_prompt/end/_00_restore_settings.py b/extensions/python/_functions/agent/Agent/prepare_prompt/end/_00_restore_settings.py
new file mode 100644
index 000000000..616534089
--- /dev/null
+++ b/extensions/python/_functions/agent/Agent/prepare_prompt/end/_00_restore_settings.py
@@ -0,0 +1,12 @@
+from helpers import settings
+from helpers.extension import Extension
+
+
+_TOKEN_KEY = "_prompt_settings_snapshot_token"
+
+
+class RestorePromptSettings(Extension):
+ def execute(self, data: dict | None = None, **kwargs):
+ token = data.pop(_TOKEN_KEY, None) if isinstance(data, dict) else None
+ if token is not None:
+ settings.end_prompt_settings_snapshot(token)
diff --git a/extensions/python/_functions/agent/Agent/prepare_prompt/start/_99_snapshot_settings.py b/extensions/python/_functions/agent/Agent/prepare_prompt/start/_99_snapshot_settings.py
new file mode 100644
index 000000000..acc2e8b5f
--- /dev/null
+++ b/extensions/python/_functions/agent/Agent/prepare_prompt/start/_99_snapshot_settings.py
@@ -0,0 +1,11 @@
+from helpers import settings
+from helpers.extension import Extension
+
+
+_TOKEN_KEY = "_prompt_settings_snapshot_token"
+
+
+class SnapshotPromptSettings(Extension):
+ def execute(self, data: dict | None = None, **kwargs):
+ if isinstance(data, dict):
+ data[_TOKEN_KEY] = settings.begin_prompt_settings_snapshot()
diff --git a/extensions/python/message_loop_prompts_after/_75_include_workdir_extras.py b/extensions/python/message_loop_prompts_after/_75_include_workdir_extras.py
index d823b8199..a6b5cf10b 100644
--- a/extensions/python/message_loop_prompts_after/_75_include_workdir_extras.py
+++ b/extensions/python/message_loop_prompts_after/_75_include_workdir_extras.py
@@ -38,7 +38,7 @@ class IncludeWorkdirExtras(Extension):
file_structure = projects.get_file_structure(project_name)
else:
- set = settings.get_settings()
+ set = settings.get_settings_for_prompt()
enabled = bool(set["workdir_show"])
if not enabled:
diff --git a/extensions/python/system_prompt/_13_secrets_prompt.py b/extensions/python/system_prompt/_13_secrets_prompt.py
index 7264c431d..fdd4cfdd8 100644
--- a/extensions/python/system_prompt/_13_secrets_prompt.py
+++ b/extensions/python/system_prompt/_13_secrets_prompt.py
@@ -23,11 +23,11 @@ class SecretsPrompt(Extension):
async def build_prompt(agent: Agent) -> str:
try:
from helpers.secrets import get_secrets_manager
- from helpers.settings import get_settings
+ from helpers.settings import get_settings_for_prompt
secrets_manager = get_secrets_manager(agent.context)
secrets = secrets_manager.get_secrets_for_prompt()
- variables = get_settings()["variables"]
+ variables = get_settings_for_prompt()["variables"]
return agent.read_prompt(
"agent.system.secrets.md", secrets=secrets, vars=variables
)
diff --git a/helpers/settings.py b/helpers/settings.py
index ddeb02d35..4edd852c5 100644
--- a/helpers/settings.py
+++ b/helpers/settings.py
@@ -1,4 +1,6 @@
import base64
+from contextvars import ContextVar, Token
+from copy import deepcopy
import hashlib
import json
import os
@@ -175,6 +177,9 @@ UI_CONTROL_VISIBILITY_DEFAULTS = {
SETTINGS_FILE = files.get_abs_path("usr/settings.json")
_settings: Settings | None = None
_runtime_settings_snapshot: Settings | None = None
+_prompt_settings_snapshot: ContextVar[Settings | None] = ContextVar(
+ "prompt_settings_snapshot", default=None
+)
OptionT = TypeVar("OptionT", bound=FieldOption)
@@ -375,10 +380,27 @@ def get_settings() -> Settings:
return norm
+def get_settings_for_prompt() -> Settings:
+ if (snapshot := _prompt_settings_snapshot.get()) is not None:
+ return deepcopy(snapshot)
+ return get_settings()
+
+
+def begin_prompt_settings_snapshot() -> Token:
+ return _prompt_settings_snapshot.set(get_settings())
+
+
+def end_prompt_settings_snapshot(token: Token) -> None:
+ _prompt_settings_snapshot.reset(token)
+
+
def reload_settings() -> Settings:
global _settings
_settings = None
- return get_settings()
+ current = get_settings()
+ if _prompt_settings_snapshot.get() is not None:
+ _prompt_settings_snapshot.set(deepcopy(current))
+ return current
def set_runtime_settings_snapshot(settings: Settings) -> None:
diff --git a/helpers/settings.py.dox.md b/helpers/settings.py.dox.md
index bb6d8656b..f943e25ff 100644
--- a/helpers/settings.py.dox.md
+++ b/helpers/settings.py.dox.md
@@ -62,9 +62,13 @@
## Key Concepts
-- Important called helpers/classes observed in the source: `TypeVar`, `files.get_abs_path`, `dotenv.get_dotenv_value`, `opts.insert`, `str.strip`, `_is_valid_timezone`, `str.strip.lower`, `_normalize_timezone_setting`, `SettingsOutput`, `get_default_settings`, `_ensure_option_present`, `_resolve_runtime_timezone`, `get_default_secrets_manager`, `get_settings`, `normalize_settings`, `_load_sensitive_settings`, `settings.copy`, `_write_settings_file`, `reload_settings`, `set_settings`, `initialize_agent`.
+- Important called helpers/classes observed in the source: `TypeVar`, `files.get_abs_path`, `dotenv.get_dotenv_value`, `opts.insert`, `str.strip`, `_is_valid_timezone`, `str.strip.lower`, `_normalize_timezone_setting`, `SettingsOutput`, `get_default_settings`, `_ensure_option_present`, `_resolve_runtime_timezone`, `get_default_secrets_manager`, `get_settings`, `get_settings_for_prompt`, `normalize_settings`, `_load_sensitive_settings`, `deepcopy`, `settings.copy`, `_write_settings_file`, `reload_settings`, `set_settings`, `initialize_agent`.
- Applying settings refreshes active context configs while preserving each subordinate agent's own profile.
- Applying settings starts a deferred `MCPConfig.update(...)` with the current `mcp_servers` string when global MCP server settings change.
+- `get_settings()` retains normalize-on-read behavior. Prompt-building callers
+ explicitly use `get_settings_for_prompt()` to reuse one task-local snapshot
+ within each `Agent.prepare_prompt()` call.
+- Explicit reloads also refresh an active prompt snapshot.
- `max_consecutive_unusable_responses` defaults to `5` and controls the cost circuit breaker for malformed or repeated main-model outputs.
- `ui_control_visibility` stores validated mobile and desktop visibility flags for the project selector, clock, connection status, and right canvas rail; missing or malformed values fall back per device.
- The Global default-profile selector lists only globally available profiles.
diff --git a/plugins/_promptinclude/extensions/python/system_prompt/_16_promptinclude.py b/plugins/_promptinclude/extensions/python/system_prompt/_16_promptinclude.py
index afc5923e9..fad4cdda9 100644
--- a/plugins/_promptinclude/extensions/python/system_prompt/_16_promptinclude.py
+++ b/plugins/_promptinclude/extensions/python/system_prompt/_16_promptinclude.py
@@ -1,7 +1,7 @@
from helpers.extension import Extension
from helpers import plugins, files, runtime
from helpers import projects
-from helpers.settings import get_settings
+from helpers.settings import get_settings_for_prompt
from agent import Agent, LoopData
from plugins._promptinclude.helpers.scanner import scan_promptinclude_files, ScanResult
@@ -61,7 +61,7 @@ def _resolve_workdir(agent: Agent) -> str:
if runtime.is_development():
folder = files.normalize_a0_path(folder)
return folder
- return get_settings()["workdir_path"]
+ return get_settings_for_prompt()["workdir_path"]
def _format_includes(agent: Agent, result: ScanResult) -> str:
diff --git a/prompts/agent.system.main.tips.py b/prompts/agent.system.main.tips.py
index f4745c912..6766f9a94 100644
--- a/prompts/agent.system.main.tips.py
+++ b/prompts/agent.system.main.tips.py
@@ -19,6 +19,6 @@ class WorkdirPath(VariablesPlugin):
# folder = files.normalize_a0_path(folder)
# return {"workdir_path": folder}
- set = settings.get_settings()
+ set = settings.get_settings_for_prompt()
return {"workdir_path": set["workdir_path"]}
diff --git a/tests/test_settings_cache.py b/tests/test_settings_cache.py
new file mode 100644
index 000000000..87705c45e
--- /dev/null
+++ b/tests/test_settings_cache.py
@@ -0,0 +1,81 @@
+import copy
+
+from helpers import extension, settings
+
+
+def test_settings_snapshot_is_limited_to_one_prompt(monkeypatch):
+ configured = settings.get_default_settings()
+ configured["api_keys"] = {"provider": "secret"}
+ versions = iter(["first", "second", "third", "fourth"])
+ calls = 0
+
+ def defaults():
+ nonlocal calls
+ calls += 1
+ result = copy.deepcopy(configured)
+ result["version"] = next(versions)
+ return result
+
+ monkeypatch.setattr(settings, "_settings", configured)
+ monkeypatch.setattr(settings, "_read_settings_file", lambda: configured)
+ monkeypatch.setattr(settings, "get_default_settings", defaults)
+ monkeypatch.setattr(settings, "_load_sensitive_settings", lambda _value: None)
+
+ token = settings.begin_prompt_settings_snapshot()
+ try:
+ configured["workdir_show"] = False
+ first = settings.get_settings_for_prompt()
+ second = settings.get_settings_for_prompt()
+
+ assert calls == 1
+ assert first == second
+ assert first["workdir_show"] is True
+ assert first is not second
+ assert first["api_keys"] is not second["api_keys"]
+
+ first["api_keys"]["provider"] = "masked"
+ assert settings.get_settings_for_prompt()["api_keys"]["provider"] == "secret"
+
+ current = settings.get_settings()
+ assert current["version"] == "second"
+ assert current["workdir_show"] is False
+ assert settings.get_settings_for_prompt()["workdir_show"] is True
+
+ reloaded = settings.reload_settings()
+ assert reloaded["version"] == "third"
+ assert reloaded["workdir_show"] is False
+ assert settings.get_settings_for_prompt() == reloaded
+ finally:
+ settings.end_prompt_settings_snapshot(token)
+
+ refreshed = settings.get_settings()
+ assert refreshed["workdir_show"] is False
+ assert refreshed["version"] == "fourth"
+ assert calls == 4
+
+
+def test_prompt_snapshot_hooks_are_registered_and_paired():
+ start = next(
+ cls
+ for cls in extension._get_extension_classes( # type: ignore[attr-defined]
+ "_functions/agent/Agent/prepare_prompt/start"
+ )
+ if cls.__name__ == "SnapshotPromptSettings"
+ )
+ end = next(
+ cls
+ for cls in extension._get_extension_classes( # type: ignore[attr-defined]
+ "_functions/agent/Agent/prepare_prompt/end"
+ )
+ if cls.__name__ == "RestorePromptSettings"
+ )
+ previous = settings._prompt_settings_snapshot.get()
+ data = {}
+
+ start(agent=None).execute(data=data)
+ try:
+ assert settings._prompt_settings_snapshot.get() is not None
+ finally:
+ end(agent=None).execute(data=data)
+
+ assert settings._prompt_settings_snapshot.get() is previous