viola-agent 0.2.1__py3-none-any.whl

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 (171) hide show
  1. viola/__init__.py +33 -0
  2. viola/__main__.py +8 -0
  3. viola/agent/__init__.py +20 -0
  4. viola/agent/autocompact.py +121 -0
  5. viola/agent/context.py +339 -0
  6. viola/agent/hook.py +141 -0
  7. viola/agent/loop.py +2058 -0
  8. viola/agent/memory.py +1092 -0
  9. viola/agent/model_presets.py +65 -0
  10. viola/agent/profiles.py +160 -0
  11. viola/agent/progress_hook.py +178 -0
  12. viola/agent/runner.py +1210 -0
  13. viola/agent/skills.py +242 -0
  14. viola/agent/subagent.py +337 -0
  15. viola/agent/tools/__init__.py +31 -0
  16. viola/agent/tools/base.py +296 -0
  17. viola/agent/tools/context.py +33 -0
  18. viola/agent/tools/cron.py +337 -0
  19. viola/agent/tools/dream_workspace_tools.py +292 -0
  20. viola/agent/tools/exec_session.py +596 -0
  21. viola/agent/tools/file_state.py +205 -0
  22. viola/agent/tools/loader.py +117 -0
  23. viola/agent/tools/long_task.py +227 -0
  24. viola/agent/tools/mcp.py +725 -0
  25. viola/agent/tools/message.py +196 -0
  26. viola/agent/tools/notebook.py +169 -0
  27. viola/agent/tools/registry.py +157 -0
  28. viola/agent/tools/runtime_state.py +59 -0
  29. viola/agent/tools/sandbox.py +57 -0
  30. viola/agent/tools/schema.py +232 -0
  31. viola/agent/tools/search.py +557 -0
  32. viola/agent/tools/self.py +475 -0
  33. viola/agent/tools/shell.py +559 -0
  34. viola/agent/tools/spawn.py +78 -0
  35. viola/agent/tools/web.py +595 -0
  36. viola/agent/tools/workspace_paths.py +103 -0
  37. viola/api/__init__.py +1 -0
  38. viola/api/server.py +822 -0
  39. viola/api/twilio_media.py +257 -0
  40. viola/api/twilio_webhook.py +359 -0
  41. viola/api/whatsapp_response_template.py +509 -0
  42. viola/billing.py +242 -0
  43. viola/bus/__init__.py +6 -0
  44. viola/bus/events.py +38 -0
  45. viola/bus/queue.py +44 -0
  46. viola/channels/__init__.py +6 -0
  47. viola/channels/base.py +244 -0
  48. viola/channels/manager.py +421 -0
  49. viola/channels/registry.py +41 -0
  50. viola/cli/__init__.py +1 -0
  51. viola/cli/commands.py +2088 -0
  52. viola/cli/doctor.py +443 -0
  53. viola/cli/models.py +31 -0
  54. viola/cli/onboard.py +1169 -0
  55. viola/cli/stream.py +230 -0
  56. viola/command/__init__.py +6 -0
  57. viola/command/builtin.py +624 -0
  58. viola/command/router.py +98 -0
  59. viola/config/__init__.py +30 -0
  60. viola/config/loader.py +482 -0
  61. viola/config/paths.py +81 -0
  62. viola/config/schema.py +568 -0
  63. viola/cron/__init__.py +7 -0
  64. viola/cron/registry.py +202 -0
  65. viola/cron/service.py +686 -0
  66. viola/cron/types.py +83 -0
  67. viola/heartbeat/__init__.py +5 -0
  68. viola/heartbeat/service.py +243 -0
  69. viola/infra/__init__.py +1 -0
  70. viola/infra/redis/__init__.py +29 -0
  71. viola/infra/redis/client.py +21 -0
  72. viola/infra/redis/guards.py +259 -0
  73. viola/infra/redis/runtime/__init__.py +17 -0
  74. viola/infra/redis/runtime/cache.py +24 -0
  75. viola/infra/redis/runtime/client.py +63 -0
  76. viola/infra/redis/runtime/keys.py +8 -0
  77. viola/infra/redis/runtime/lock.py +41 -0
  78. viola/infra/redis/runtime/rate_limit.py +23 -0
  79. viola/infra/redis/runtime/session.py +80 -0
  80. viola/notify/__init__.py +36 -0
  81. viola/notify/catalog.py +138 -0
  82. viola/notify/service.py +281 -0
  83. viola/notify/store.py +144 -0
  84. viola/notify/templates.yaml +79 -0
  85. viola/notify/twilio_content.py +254 -0
  86. viola/notify/window.py +58 -0
  87. viola/pairing/__init__.py +33 -0
  88. viola/pairing/store.py +254 -0
  89. viola/providers/__init__.py +33 -0
  90. viola/providers/anthropic_provider.py +629 -0
  91. viola/providers/base.py +814 -0
  92. viola/providers/factory.py +214 -0
  93. viola/providers/fallback_provider.py +273 -0
  94. viola/providers/image_generation.py +395 -0
  95. viola/providers/openai_compat_provider.py +1079 -0
  96. viola/providers/openai_responses/__init__.py +29 -0
  97. viola/providers/openai_responses/converters.py +110 -0
  98. viola/providers/openai_responses/parsing.py +297 -0
  99. viola/providers/registry.py +542 -0
  100. viola/providers/transcription.py +881 -0
  101. viola/runtime/__init__.py +17 -0
  102. viola/runtime/background_tasks.py +274 -0
  103. viola/runtime/whatsapp_outbound.py +105 -0
  104. viola/security/__init__.py +1 -0
  105. viola/security/network.py +119 -0
  106. viola/session/__init__.py +5 -0
  107. viola/session/goal_state.py +117 -0
  108. viola/session/manager.py +660 -0
  109. viola/settings.py +243 -0
  110. viola/skills/README.md +30 -0
  111. viola/skills/cron/SKILL.md +57 -0
  112. viola/skills/github/SKILL.md +48 -0
  113. viola/skills/long-goal/SKILL.md +79 -0
  114. viola/skills/memory/SKILL.md +36 -0
  115. viola/skills/my/SKILL.md +72 -0
  116. viola/skills/my/references/examples.md +75 -0
  117. viola/skills/skill-creator/SKILL.md +374 -0
  118. viola/skills/skill-creator/scripts/init_skill.py +378 -0
  119. viola/skills/skill-creator/scripts/package_skill.py +152 -0
  120. viola/skills/skill-creator/scripts/quick_validate.py +213 -0
  121. viola/skills/summarize/SKILL.md +67 -0
  122. viola/skills/tmux/SKILL.md +121 -0
  123. viola/skills/tmux/scripts/find-sessions.sh +112 -0
  124. viola/skills/tmux/scripts/wait-for-text.sh +83 -0
  125. viola/skills/update-setup/SKILL.md +123 -0
  126. viola/skills/weather/SKILL.md +49 -0
  127. viola/templates/AGENTS.md +15 -0
  128. viola/templates/HEARTBEAT.md +16 -0
  129. viola/templates/SKILL.md +0 -0
  130. viola/templates/SOUL.md +23 -0
  131. viola/templates/TOOLS.md +36 -0
  132. viola/templates/USER.md +49 -0
  133. viola/templates/__init__.py +0 -0
  134. viola/templates/agent/_snippets/untrusted_content.md +2 -0
  135. viola/templates/agent/consolidator_archive.md +13 -0
  136. viola/templates/agent/dream_phase1.md +40 -0
  137. viola/templates/agent/dream_phase2.md +35 -0
  138. viola/templates/agent/evaluator.md +17 -0
  139. viola/templates/agent/identity.md +37 -0
  140. viola/templates/agent/max_iterations_message.md +1 -0
  141. viola/templates/agent/platform_policy.md +10 -0
  142. viola/templates/agent/skills_section.md +6 -0
  143. viola/templates/agent/subagent_announce.md +8 -0
  144. viola/templates/agent/subagent_system.md +19 -0
  145. viola/templates/agent/tool_contract.md +67 -0
  146. viola/templates/memory/MEMORY.md +27 -0
  147. viola/templates/memory/__init__.py +0 -0
  148. viola/utils/__init__.py +6 -0
  149. viola/utils/artifacts.py +323 -0
  150. viola/utils/document.py +374 -0
  151. viola/utils/evaluator.py +89 -0
  152. viola/utils/gitstore.py +390 -0
  153. viola/utils/helpers.py +654 -0
  154. viola/utils/llm_runtime.py +22 -0
  155. viola/utils/logging_bridge.py +47 -0
  156. viola/utils/media_decode.py +54 -0
  157. viola/utils/path.py +107 -0
  158. viola/utils/progress_events.py +84 -0
  159. viola/utils/prompt_templates.py +35 -0
  160. viola/utils/restart.py +84 -0
  161. viola/utils/runtime.py +170 -0
  162. viola/utils/searchusage.py +168 -0
  163. viola/utils/subagent_channel_display.py +59 -0
  164. viola/utils/tool_hints.py +142 -0
  165. viola/viola.py +100 -0
  166. viola_agent-0.2.1.dist-info/METADATA +198 -0
  167. viola_agent-0.2.1.dist-info/RECORD +171 -0
  168. viola_agent-0.2.1.dist-info/WHEEL +4 -0
  169. viola_agent-0.2.1.dist-info/entry_points.txt +2 -0
  170. viola_agent-0.2.1.dist-info/licenses/LICENSE +21 -0
  171. viola_agent-0.2.1.dist-info/licenses/THIRD_PARTY_NOTICES.md +5 -0
viola/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """
2
+ viola - A lightweight AI agent framework
3
+ """
4
+
5
+ import tomllib
6
+ from importlib.metadata import PackageNotFoundError
7
+ from importlib.metadata import version as _pkg_version
8
+ from pathlib import Path
9
+
10
+
11
+ def _read_pyproject_version() -> str | None:
12
+ """Read the source-tree version when package metadata is unavailable."""
13
+ pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"
14
+ if not pyproject.exists():
15
+ return None
16
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
17
+ return data.get("project", {}).get("version")
18
+
19
+
20
+ def _resolve_version() -> str:
21
+ try:
22
+ return _pkg_version("viola-agent")
23
+ except PackageNotFoundError:
24
+ # Source checkouts often import viola without installed dist-info.
25
+ return _read_pyproject_version() or "0.0.0"
26
+
27
+
28
+ __version__ = _resolve_version()
29
+ __logo__ = "🐈"
30
+
31
+ from viola.viola import RunResult, Viola # noqa: E402 (submodules import __version__ during this import)
32
+
33
+ __all__ = ["Viola", "RunResult"]
viola/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """
2
+ Entry point for running viola as a module: python -m viola
3
+ """
4
+
5
+ from viola.cli.commands import app
6
+
7
+ if __name__ == "__main__":
8
+ app()
@@ -0,0 +1,20 @@
1
+ """Agent core module."""
2
+
3
+ from viola.agent.context import ContextBuilder
4
+ from viola.agent.hook import AgentHook, AgentHookContext, CompositeHook
5
+ from viola.agent.loop import AgentLoop
6
+ from viola.agent.memory import Dream, MemoryStore
7
+ from viola.agent.skills import SkillsLoader
8
+ from viola.agent.subagent import SubagentManager
9
+
10
+ __all__ = [
11
+ "AgentHook",
12
+ "AgentHookContext",
13
+ "AgentLoop",
14
+ "CompositeHook",
15
+ "ContextBuilder",
16
+ "Dream",
17
+ "MemoryStore",
18
+ "SkillsLoader",
19
+ "SubagentManager",
20
+ ]
@@ -0,0 +1,121 @@
1
+ """Auto compact: proactive compression of idle sessions to reduce token cost and latency."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Collection
6
+ from datetime import datetime
7
+ from typing import TYPE_CHECKING, Any, Callable, Coroutine
8
+
9
+ from loguru import logger
10
+
11
+ from viola.session.manager import Session, SessionManager
12
+
13
+ if TYPE_CHECKING:
14
+ from viola.agent.memory import Consolidator
15
+
16
+
17
+ class AutoCompact:
18
+ _RECENT_SUFFIX_MESSAGES = 8
19
+
20
+ def __init__(self, sessions: SessionManager, consolidator: Consolidator,
21
+ session_ttl_minutes: int = 0):
22
+ self.sessions = sessions
23
+ self.consolidator = consolidator
24
+ self._ttl = session_ttl_minutes
25
+ self._archiving: set[str] = set()
26
+ self._summaries: dict[str, tuple[str, datetime]] = {}
27
+
28
+ def _is_expired(self, ts: datetime | str | None,
29
+ now: datetime | None = None) -> bool:
30
+ if self._ttl <= 0 or not ts:
31
+ return False
32
+ if isinstance(ts, str):
33
+ ts = datetime.fromisoformat(ts)
34
+ return ((now or datetime.now()) - ts).total_seconds() >= self._ttl * 60
35
+
36
+ @staticmethod
37
+ def _format_summary(text: str, last_active: datetime) -> str:
38
+ return f"Previous conversation summary (last active {last_active.isoformat()}):\n{text}"
39
+
40
+ def _split_unconsolidated(
41
+ self, session: Session,
42
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
43
+ """Split live session tail into archiveable prefix and retained recent suffix."""
44
+ tail = list(session.messages[session.last_consolidated:])
45
+ if not tail:
46
+ return [], []
47
+
48
+ probe = Session(
49
+ key=session.key,
50
+ messages=tail.copy(),
51
+ created_at=session.created_at,
52
+ updated_at=session.updated_at,
53
+ metadata={},
54
+ last_consolidated=0,
55
+ )
56
+ probe.retain_recent_legal_suffix(self._RECENT_SUFFIX_MESSAGES)
57
+ kept = probe.messages
58
+ cut = len(tail) - len(kept)
59
+ return tail[:cut], kept
60
+
61
+ def check_expired(self, schedule_background: Callable[[Coroutine], None],
62
+ active_session_keys: Collection[str] = ()) -> None:
63
+ """Schedule archival for idle sessions, skipping those with in-flight agent tasks."""
64
+ now = datetime.now()
65
+ for info in self.sessions.list_sessions():
66
+ key = info.get("key", "")
67
+ if not key or key in self._archiving:
68
+ continue
69
+ if key in active_session_keys:
70
+ continue
71
+ if self._is_expired(info.get("updated_at"), now):
72
+ self._archiving.add(key)
73
+ schedule_background(self._archive(key))
74
+
75
+ async def _archive(self, key: str) -> None:
76
+ try:
77
+ self.sessions.invalidate(key)
78
+ session = self.sessions.get_or_create(key)
79
+ archive_msgs, kept_msgs = self._split_unconsolidated(session)
80
+ if not archive_msgs and not kept_msgs:
81
+ session.updated_at = datetime.now()
82
+ self.sessions.save(session)
83
+ return
84
+
85
+ last_active = session.updated_at
86
+ summary = ""
87
+ if archive_msgs:
88
+ summary = await self.consolidator.archive(archive_msgs) or ""
89
+ if summary and summary != "(nothing)":
90
+ self._summaries[key] = (summary, last_active)
91
+ session.metadata["_last_summary"] = {"text": summary, "last_active": last_active.isoformat()}
92
+ session.messages = kept_msgs
93
+ session.last_consolidated = 0
94
+ session.updated_at = datetime.now()
95
+ self.sessions.save(session)
96
+ if archive_msgs:
97
+ logger.info(
98
+ "Auto-compact: archived {} (archived={}, kept={}, summary={})",
99
+ key,
100
+ len(archive_msgs),
101
+ len(kept_msgs),
102
+ bool(summary),
103
+ )
104
+ except Exception:
105
+ logger.exception("Auto-compact: failed for {}", key)
106
+ finally:
107
+ self._archiving.discard(key)
108
+
109
+ def prepare_session(self, session: Session, key: str) -> tuple[Session, str | None]:
110
+ if key in self._archiving or self._is_expired(session.updated_at):
111
+ logger.info("Auto-compact: reloading session {} (archiving={})", key, key in self._archiving)
112
+ session = self.sessions.get_or_create(key)
113
+ # Hot path: summary from in-memory dict (process hasn't restarted).
114
+ entry = self._summaries.pop(key, None)
115
+ if entry:
116
+ return session, self._format_summary(entry[0], entry[1])
117
+ # Cold path: summary persisted in session metadata (process restarted).
118
+ meta = session.metadata.get("_last_summary")
119
+ if isinstance(meta, dict):
120
+ return session, self._format_summary(meta["text"], datetime.fromisoformat(meta["last_active"]))
121
+ return session, None
viola/agent/context.py ADDED
@@ -0,0 +1,339 @@
1
+ """Context builder for assembling agent prompts."""
2
+
3
+ import base64
4
+ import logging
5
+ import mimetypes
6
+ import os
7
+ import platform
8
+ from contextlib import suppress
9
+ from importlib.resources import files as pkg_files
10
+ from pathlib import Path
11
+ from typing import Any, Mapping, Sequence
12
+
13
+ from viola.agent.memory import MemoryStore
14
+ from viola.agent.skills import SkillsLoader
15
+ from viola.agent.tools import mcp as mcp_tools
16
+ from viola.agent.tools.registry import ToolRegistry
17
+ from viola.bus.events import InboundMessage
18
+ from viola.session.goal_state import goal_state_runtime_lines
19
+ from viola.utils.helpers import (
20
+ current_time_str,
21
+ detect_image_mime,
22
+ truncate_text,
23
+ )
24
+ from viola.utils.prompt_templates import render_template
25
+
26
+ _log = logging.getLogger(__name__)
27
+
28
+ # Tools withheld from LLM-facing definitions on ``channel=api`` (WhatsApp / OpenAI-compat API).
29
+ API_CHANNEL_HIDDEN_TOOLS: frozenset[str] = frozenset({"cron"})
30
+
31
+
32
+ def api_channel_hidden_tools(*, allow_scheduling: bool) -> frozenset[str]:
33
+ """Return tool names hidden on channel=api."""
34
+ if allow_scheduling:
35
+ return frozenset()
36
+ return API_CHANNEL_HIDDEN_TOOLS
37
+
38
+
39
+ def _build_api_channel_note(*, allow_scheduling: bool = False) -> str:
40
+ """Short channel note injected into every ``channel=api`` system prompt.
41
+
42
+ Traffic on this channel comes from WhatsApp (via the Twilio webhook) or from a
43
+ company backend calling the OpenAI-compatible API.
44
+ """
45
+ lines = [
46
+ "## Messaging channel",
47
+ "",
48
+ "Messages on this channel usually come from WhatsApp. Keep replies short and easy "
49
+ "to read on a phone. Reply in the language the user writes in.",
50
+ "Only say an action succeeded when a tool result in this turn confirms it. "
51
+ "If no tool fits or a tool fails, say so plainly.",
52
+ ]
53
+ if allow_scheduling:
54
+ lines.append(
55
+ "Scheduled tasks are enabled: use the `cron` tool for one-shot reminders and "
56
+ "`HEARTBEAT.md` for recurring checks. Do not claim a reminder is set unless "
57
+ "`cron` succeeded or HEARTBEAT.md was updated."
58
+ )
59
+ else:
60
+ lines.append(
61
+ "Reminders and scheduled tasks are not available on this channel. If asked, "
62
+ "say so once instead of promising them."
63
+ )
64
+ return "\n".join(lines)
65
+
66
+
67
+ def _cli_app_session_extra(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
68
+ cli_apps = metadata.get("cli_apps") if isinstance(metadata, Mapping) else None
69
+ return {"cli_apps": cli_apps} if isinstance(cli_apps, list) and cli_apps else {}
70
+
71
+
72
+ def _cli_app_runtime_lines(msg: Any, workspace: Path, *, skip: bool = False) -> list[str]:
73
+ if skip:
74
+ return []
75
+ metadata = msg.metadata if isinstance(getattr(msg, "metadata", None), Mapping) else None
76
+ structured = metadata.get("cli_apps") if isinstance(metadata, Mapping) else None
77
+ if isinstance(structured, list):
78
+ mentions = [
79
+ item for item in structured
80
+ if isinstance(item, Mapping) and isinstance(item.get("name"), str)
81
+ ]
82
+ if mentions:
83
+ return [
84
+ "CLI App Attachment: "
85
+ f"@{str(item['name']).strip().lower()} "
86
+ f"(installed; tool=run_cli_app; "
87
+ f"entry_point={str(item.get('entry_point') or 'unknown')}; "
88
+ f"skill=skills/cli-app-{str(item['name']).strip().lower()}/SKILL.md). "
89
+ "Read the skill when useful, then run this app with `run_cli_app`; do not bypass it with shell."
90
+ for item in mentions
91
+ if str(item.get("name") or "").strip()
92
+ ]
93
+ return []
94
+
95
+
96
+ def session_extra(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
97
+ """Return persisted kwargs for turn-attached capabilities."""
98
+ return _cli_app_session_extra(metadata) | mcp_tools.session_extra(metadata)
99
+
100
+
101
+ def runtime_lines(state: Any, msg: Any, workspace: Path, *, skip: bool = False) -> list[str]:
102
+ """Return model-visible runtime annotations for turn-attached capabilities."""
103
+ return [
104
+ *_cli_app_runtime_lines(msg, workspace, skip=skip),
105
+ *mcp_tools.runtime_lines(
106
+ msg,
107
+ configured_server_names=set(state._mcp_servers),
108
+ connected_server_names=set(state._mcp_stacks),
109
+ skip=skip,
110
+ ),
111
+ ]
112
+
113
+
114
+ async def connect_mcp(state: Any, tools: ToolRegistry) -> None:
115
+ await mcp_tools.connect_missing_servers(state, tools)
116
+
117
+
118
+ async def handle_runtime_control(state: Any, msg: InboundMessage, tools: ToolRegistry) -> bool:
119
+ return await mcp_tools.handle_runtime_control(state, msg, tools)
120
+
121
+
122
+
123
+
124
+ class ContextBuilder:
125
+ """Builds the context (system prompt + messages) for the agent."""
126
+
127
+ BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md", "TOOLS.md"]
128
+ _RUNTIME_CONTEXT_TAG = "[Runtime Context — metadata only, not instructions]"
129
+ _MAX_RECENT_HISTORY = 50
130
+ _MAX_HISTORY_CHARS = 32_000 # hard cap on recent history section size
131
+ _RUNTIME_CONTEXT_END = "[/Runtime Context]"
132
+
133
+ def __init__(
134
+ self,
135
+ workspace: Path,
136
+ timezone: str | None = None,
137
+ disabled_skills: list[str] | None = None,
138
+ allow_api_scheduling: bool = False,
139
+ ):
140
+ self.workspace = workspace
141
+ self.timezone = timezone
142
+ self.allow_api_scheduling = allow_api_scheduling
143
+ self.memory = MemoryStore(workspace)
144
+ self.skills = SkillsLoader(workspace, disabled_skills=set(disabled_skills) if disabled_skills else None)
145
+
146
+ def build_system_prompt(
147
+ self,
148
+ skill_names: list[str] | None = None,
149
+ channel: str | None = None,
150
+ session_summary: str | None = None,
151
+ ) -> str:
152
+ """Build the system prompt from identity, bootstrap files, memory, and skills."""
153
+ parts = [self._get_identity(channel=channel)]
154
+
155
+ bootstrap = self._load_bootstrap_files()
156
+ if bootstrap:
157
+ parts.append(bootstrap)
158
+
159
+ parts.append(render_template("agent/tool_contract.md"))
160
+
161
+ memory = self.memory.get_memory_context()
162
+ if memory and not self._is_template_content(self.memory.read_memory(), "memory/MEMORY.md"):
163
+ parts.append(f"# Memory\n\n{memory}")
164
+
165
+ always_skills = self.skills.get_always_skills()
166
+ if always_skills:
167
+ always_content = self.skills.load_skills_for_context(always_skills)
168
+ if always_content:
169
+ parts.append(f"# Active Skills\n\n{always_content}")
170
+
171
+ skill_summary_exclude = set(always_skills)
172
+ if channel == "api" and not self.allow_api_scheduling:
173
+ skill_summary_exclude |= {"cron"}
174
+ skills_summary = self.skills.build_skills_summary(exclude=skill_summary_exclude)
175
+ if skills_summary:
176
+ parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary))
177
+
178
+ entries = self.memory.read_unprocessed_history(since_cursor=self.memory.get_last_dream_cursor())
179
+ if entries:
180
+ capped = entries[-self._MAX_RECENT_HISTORY:]
181
+ history_text = "\n".join(
182
+ f"- [{e['timestamp']}] {e['content']}" for e in capped
183
+ )
184
+ history_text = truncate_text(history_text, self._MAX_HISTORY_CHARS)
185
+ parts.append("# Recent History\n\n" + history_text)
186
+
187
+ if session_summary:
188
+ parts.append(f"[Archived Context Summary]\n\n{session_summary}")
189
+
190
+ if channel == "api":
191
+ parts.append(_build_api_channel_note(allow_scheduling=self.allow_api_scheduling))
192
+ extra = (os.environ.get("AGENT_EXTRA_SYSTEM_PROMPT") or "").strip()
193
+ if extra:
194
+ parts.append(extra)
195
+
196
+ return "\n\n---\n\n".join(parts)
197
+
198
+ def _get_identity(self, channel: str | None = None) -> str:
199
+ """Get the core identity section."""
200
+ workspace_path = str(self.workspace.expanduser().resolve())
201
+ system = platform.system()
202
+ runtime = f"{'macOS' if system == 'Darwin' else system} {platform.machine()}, Python {platform.python_version()}"
203
+
204
+ return render_template(
205
+ "agent/identity.md",
206
+ workspace_path=workspace_path,
207
+ runtime=runtime,
208
+ platform_policy=render_template("agent/platform_policy.md", system=system),
209
+ channel=channel or "",
210
+ )
211
+
212
+ @staticmethod
213
+ def _build_runtime_context(
214
+ channel: str | None,
215
+ chat_id: str | None,
216
+ timezone: str | None = None,
217
+ sender_id: str | None = None,
218
+ supplemental_lines: Sequence[str] | None = None,
219
+ ) -> str:
220
+ """Build untrusted runtime metadata block for injection before the user message."""
221
+ lines = [f"Current Time: {current_time_str(timezone)}"]
222
+ if channel and chat_id:
223
+ lines += [f"Channel: {channel}", f"Chat ID: {chat_id}"]
224
+ if sender_id:
225
+ lines += [f"Sender ID: {sender_id}"]
226
+ if supplemental_lines:
227
+ lines.extend(supplemental_lines)
228
+ return ContextBuilder._RUNTIME_CONTEXT_TAG + "\n" + "\n".join(lines) + "\n" + ContextBuilder._RUNTIME_CONTEXT_END
229
+
230
+ @staticmethod
231
+ def _merge_message_content(left: Any, right: Any) -> str | list[dict[str, Any]]:
232
+ if isinstance(left, str) and isinstance(right, str):
233
+ return f"{left}\n\n{right}" if left else right
234
+
235
+ def _to_blocks(value: Any) -> list[dict[str, Any]]:
236
+ if isinstance(value, list):
237
+ return [item if isinstance(item, dict) else {"type": "text", "text": str(item)} for item in value]
238
+ if value is None:
239
+ return []
240
+ return [{"type": "text", "text": str(value)}]
241
+
242
+ return _to_blocks(left) + _to_blocks(right)
243
+
244
+ def _load_bootstrap_files(self) -> str:
245
+ """Load all bootstrap files from workspace."""
246
+ parts = []
247
+
248
+ for filename in self.BOOTSTRAP_FILES:
249
+ file_path = self.workspace / filename
250
+ if file_path.exists():
251
+ content = file_path.read_text(encoding="utf-8")
252
+ parts.append(f"## {filename}\n\n{content}")
253
+
254
+ return "\n\n".join(parts) if parts else ""
255
+
256
+ @staticmethod
257
+ def _is_template_content(content: str, template_path: str) -> bool:
258
+ """Check if *content* is identical to the bundled template (user hasn't customized it)."""
259
+ with suppress(Exception):
260
+ tpl = pkg_files("viola") / "templates" / template_path
261
+ if tpl.is_file():
262
+ return content.strip() == tpl.read_text(encoding="utf-8").strip()
263
+ return False
264
+
265
+ def build_messages(
266
+ self,
267
+ history: list[dict[str, Any]],
268
+ current_message: str,
269
+ skill_names: list[str] | None = None,
270
+ media: list[str] | None = None,
271
+ channel: str | None = None,
272
+ chat_id: str | None = None,
273
+ current_role: str = "user",
274
+ sender_id: str | None = None,
275
+ session_metadata: Mapping[str, Any] | None = None,
276
+ session_summary: str | None = None,
277
+ current_runtime_lines: Sequence[str] | None = None,
278
+ ) -> list[dict[str, Any]]:
279
+ """Build the complete message list for an LLM call."""
280
+ extra = [
281
+ *goal_state_runtime_lines(session_metadata),
282
+ ]
283
+ if current_runtime_lines:
284
+ extra.extend(line for line in current_runtime_lines if line)
285
+
286
+ runtime_ctx = self._build_runtime_context(channel, chat_id, self.timezone, sender_id=sender_id)
287
+ user_content = self._build_user_content(current_message, media)
288
+
289
+ # Merge runtime context and user content into a single user message
290
+ # to avoid consecutive same-role messages that some providers reject.
291
+ if isinstance(user_content, str):
292
+ merged = f"{runtime_ctx}\n\n{user_content}"
293
+ else:
294
+ merged = [{"type": "text", "text": runtime_ctx}] + user_content
295
+ messages = [
296
+ {"role": "system", "content": self.build_system_prompt(skill_names, channel=channel, session_summary=session_summary)},
297
+ *history,
298
+ ]
299
+ if messages[-1].get("role") == current_role:
300
+ last = dict(messages[-1])
301
+ last["content"] = self._merge_message_content(last.get("content"), merged)
302
+ messages[-1] = last
303
+ return messages
304
+ messages.append({"role": current_role, "content": merged})
305
+ return messages
306
+
307
+ def _build_user_content(self, text: str, media: list[str] | None) -> str | list[dict[str, Any]]:
308
+ """Build user message content with optional base64-encoded images."""
309
+ if not media:
310
+ return text
311
+
312
+ images = []
313
+ for path in media:
314
+ p = Path(path)
315
+ if not p.is_file():
316
+ continue
317
+ raw = p.read_bytes()
318
+ mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]
319
+ if not mime or not mime.startswith("image/"):
320
+ continue
321
+ b64 = base64.b64encode(raw).decode()
322
+ images.append({
323
+ "type": "image_url",
324
+ "image_url": {"url": f"data:{mime};base64,{b64}"},
325
+ "_meta": {"path": str(p)},
326
+ })
327
+
328
+ if not images:
329
+ return text
330
+ return images + [{"type": "text", "text": text}]
331
+
332
+ def add_tool_result(
333
+ self, messages: list[dict[str, Any]],
334
+ tool_call_id: str, tool_name: str, result: Any,
335
+ ) -> list[dict[str, Any]]:
336
+ """Add a tool result to the message list."""
337
+ messages.append({"role": "tool", "tool_call_id": tool_call_id, "name": tool_name, "content": result})
338
+ return messages
339
+
viola/agent/hook.py ADDED
@@ -0,0 +1,141 @@
1
+ """Shared lifecycle hook primitives for agent runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from loguru import logger
9
+
10
+ from viola.providers.base import LLMResponse, ToolCallRequest
11
+
12
+
13
+ @dataclass(slots=True)
14
+ class AgentHookContext:
15
+ """Mutable per-iteration state exposed to runner hooks."""
16
+
17
+ iteration: int
18
+ messages: list[dict[str, Any]]
19
+ response: LLMResponse | None = None
20
+ usage: dict[str, int] = field(default_factory=dict)
21
+ tool_calls: list[ToolCallRequest] = field(default_factory=list)
22
+ tool_results: list[Any] = field(default_factory=list)
23
+ tool_events: list[dict[str, str]] = field(default_factory=list)
24
+ streamed_content: bool = False
25
+ streamed_reasoning: bool = False
26
+ final_content: str | None = None
27
+ stop_reason: str | None = None
28
+ error: str | None = None
29
+
30
+
31
+ class AgentHook:
32
+ """Minimal lifecycle surface for shared runner customization."""
33
+
34
+ def __init__(self, reraise: bool = False) -> None:
35
+ self._reraise = reraise
36
+
37
+ def wants_streaming(self) -> bool:
38
+ return False
39
+
40
+ async def before_iteration(self, context: AgentHookContext) -> None:
41
+ pass
42
+
43
+ async def on_stream(self, context: AgentHookContext, delta: str) -> None:
44
+ pass
45
+
46
+ async def on_stream_end(self, context: AgentHookContext, *, resuming: bool) -> None:
47
+ pass
48
+
49
+ async def before_execute_tools(self, context: AgentHookContext) -> None:
50
+ pass
51
+
52
+ async def emit_reasoning(self, reasoning_content: str | None) -> None:
53
+ pass
54
+
55
+ async def emit_reasoning_end(self) -> None:
56
+ """Mark the end of an in-flight reasoning stream.
57
+
58
+ Hooks that buffer ``emit_reasoning`` chunks (for in-place UI updates)
59
+ flush and freeze the rendered group here. One-shot hooks ignore.
60
+ """
61
+ pass
62
+
63
+ async def after_iteration(self, context: AgentHookContext) -> None:
64
+ pass
65
+
66
+ def finalize_content(self, context: AgentHookContext, content: str | None) -> str | None:
67
+ return content
68
+
69
+
70
+ class CompositeHook(AgentHook):
71
+ """Fan-out hook that delegates to an ordered list of hooks.
72
+
73
+ Error isolation: async methods catch and log per-hook exceptions
74
+ so a faulty custom hook cannot crash the agent loop.
75
+ ``finalize_content`` is a pipeline (no isolation — bugs should surface).
76
+ """
77
+
78
+ __slots__ = ("_hooks",)
79
+
80
+ def __init__(self, hooks: list[AgentHook]) -> None:
81
+ super().__init__()
82
+ self._hooks = list(hooks)
83
+
84
+ def wants_streaming(self) -> bool:
85
+ return any(h.wants_streaming() for h in self._hooks)
86
+
87
+ async def _for_each_hook_safe(self, method_name: str, *args: Any, **kwargs: Any) -> None:
88
+ for h in self._hooks:
89
+ if getattr(h, "_reraise", False):
90
+ await getattr(h, method_name)(*args, **kwargs)
91
+ continue
92
+
93
+ try:
94
+ await getattr(h, method_name)(*args, **kwargs)
95
+ except Exception:
96
+ logger.exception("AgentHook.{} error in {}", method_name, type(h).__name__)
97
+
98
+ async def before_iteration(self, context: AgentHookContext) -> None:
99
+ await self._for_each_hook_safe("before_iteration", context)
100
+
101
+ async def on_stream(self, context: AgentHookContext, delta: str) -> None:
102
+ await self._for_each_hook_safe("on_stream", context, delta)
103
+
104
+ async def on_stream_end(self, context: AgentHookContext, *, resuming: bool) -> None:
105
+ await self._for_each_hook_safe("on_stream_end", context, resuming=resuming)
106
+
107
+ async def before_execute_tools(self, context: AgentHookContext) -> None:
108
+ await self._for_each_hook_safe("before_execute_tools", context)
109
+
110
+ async def emit_reasoning(self, reasoning_content: str | None) -> None:
111
+ await self._for_each_hook_safe("emit_reasoning", reasoning_content)
112
+
113
+ async def emit_reasoning_end(self) -> None:
114
+ await self._for_each_hook_safe("emit_reasoning_end")
115
+
116
+ async def after_iteration(self, context: AgentHookContext) -> None:
117
+ await self._for_each_hook_safe("after_iteration", context)
118
+
119
+ def finalize_content(self, context: AgentHookContext, content: str | None) -> str | None:
120
+ for h in self._hooks:
121
+ content = h.finalize_content(context, content)
122
+ return content
123
+
124
+
125
+ class SDKCaptureHook(AgentHook):
126
+ """Record tool names and the final message list for ``RunResult``.
127
+
128
+ The runner mutates ``context.messages`` in place across iterations, so the
129
+ snapshot is refreshed on every ``after_iteration`` call; the last call
130
+ reflects the end-of-turn state the SDK caller cares about.
131
+ """
132
+
133
+ def __init__(self) -> None:
134
+ super().__init__()
135
+ self.tools_used: list[str] = []
136
+ self.messages: list[dict[str, Any]] = []
137
+
138
+ async def after_iteration(self, context: AgentHookContext) -> None:
139
+ for call in context.tool_calls:
140
+ self.tools_used.append(call.name)
141
+ self.messages = list(context.messages)