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.
- viola/__init__.py +33 -0
- viola/__main__.py +8 -0
- viola/agent/__init__.py +20 -0
- viola/agent/autocompact.py +121 -0
- viola/agent/context.py +339 -0
- viola/agent/hook.py +141 -0
- viola/agent/loop.py +2058 -0
- viola/agent/memory.py +1092 -0
- viola/agent/model_presets.py +65 -0
- viola/agent/profiles.py +160 -0
- viola/agent/progress_hook.py +178 -0
- viola/agent/runner.py +1210 -0
- viola/agent/skills.py +242 -0
- viola/agent/subagent.py +337 -0
- viola/agent/tools/__init__.py +31 -0
- viola/agent/tools/base.py +296 -0
- viola/agent/tools/context.py +33 -0
- viola/agent/tools/cron.py +337 -0
- viola/agent/tools/dream_workspace_tools.py +292 -0
- viola/agent/tools/exec_session.py +596 -0
- viola/agent/tools/file_state.py +205 -0
- viola/agent/tools/loader.py +117 -0
- viola/agent/tools/long_task.py +227 -0
- viola/agent/tools/mcp.py +725 -0
- viola/agent/tools/message.py +196 -0
- viola/agent/tools/notebook.py +169 -0
- viola/agent/tools/registry.py +157 -0
- viola/agent/tools/runtime_state.py +59 -0
- viola/agent/tools/sandbox.py +57 -0
- viola/agent/tools/schema.py +232 -0
- viola/agent/tools/search.py +557 -0
- viola/agent/tools/self.py +475 -0
- viola/agent/tools/shell.py +559 -0
- viola/agent/tools/spawn.py +78 -0
- viola/agent/tools/web.py +595 -0
- viola/agent/tools/workspace_paths.py +103 -0
- viola/api/__init__.py +1 -0
- viola/api/server.py +822 -0
- viola/api/twilio_media.py +257 -0
- viola/api/twilio_webhook.py +359 -0
- viola/api/whatsapp_response_template.py +509 -0
- viola/billing.py +242 -0
- viola/bus/__init__.py +6 -0
- viola/bus/events.py +38 -0
- viola/bus/queue.py +44 -0
- viola/channels/__init__.py +6 -0
- viola/channels/base.py +244 -0
- viola/channels/manager.py +421 -0
- viola/channels/registry.py +41 -0
- viola/cli/__init__.py +1 -0
- viola/cli/commands.py +2088 -0
- viola/cli/doctor.py +443 -0
- viola/cli/models.py +31 -0
- viola/cli/onboard.py +1169 -0
- viola/cli/stream.py +230 -0
- viola/command/__init__.py +6 -0
- viola/command/builtin.py +624 -0
- viola/command/router.py +98 -0
- viola/config/__init__.py +30 -0
- viola/config/loader.py +482 -0
- viola/config/paths.py +81 -0
- viola/config/schema.py +568 -0
- viola/cron/__init__.py +7 -0
- viola/cron/registry.py +202 -0
- viola/cron/service.py +686 -0
- viola/cron/types.py +83 -0
- viola/heartbeat/__init__.py +5 -0
- viola/heartbeat/service.py +243 -0
- viola/infra/__init__.py +1 -0
- viola/infra/redis/__init__.py +29 -0
- viola/infra/redis/client.py +21 -0
- viola/infra/redis/guards.py +259 -0
- viola/infra/redis/runtime/__init__.py +17 -0
- viola/infra/redis/runtime/cache.py +24 -0
- viola/infra/redis/runtime/client.py +63 -0
- viola/infra/redis/runtime/keys.py +8 -0
- viola/infra/redis/runtime/lock.py +41 -0
- viola/infra/redis/runtime/rate_limit.py +23 -0
- viola/infra/redis/runtime/session.py +80 -0
- viola/notify/__init__.py +36 -0
- viola/notify/catalog.py +138 -0
- viola/notify/service.py +281 -0
- viola/notify/store.py +144 -0
- viola/notify/templates.yaml +79 -0
- viola/notify/twilio_content.py +254 -0
- viola/notify/window.py +58 -0
- viola/pairing/__init__.py +33 -0
- viola/pairing/store.py +254 -0
- viola/providers/__init__.py +33 -0
- viola/providers/anthropic_provider.py +629 -0
- viola/providers/base.py +814 -0
- viola/providers/factory.py +214 -0
- viola/providers/fallback_provider.py +273 -0
- viola/providers/image_generation.py +395 -0
- viola/providers/openai_compat_provider.py +1079 -0
- viola/providers/openai_responses/__init__.py +29 -0
- viola/providers/openai_responses/converters.py +110 -0
- viola/providers/openai_responses/parsing.py +297 -0
- viola/providers/registry.py +542 -0
- viola/providers/transcription.py +881 -0
- viola/runtime/__init__.py +17 -0
- viola/runtime/background_tasks.py +274 -0
- viola/runtime/whatsapp_outbound.py +105 -0
- viola/security/__init__.py +1 -0
- viola/security/network.py +119 -0
- viola/session/__init__.py +5 -0
- viola/session/goal_state.py +117 -0
- viola/session/manager.py +660 -0
- viola/settings.py +243 -0
- viola/skills/README.md +30 -0
- viola/skills/cron/SKILL.md +57 -0
- viola/skills/github/SKILL.md +48 -0
- viola/skills/long-goal/SKILL.md +79 -0
- viola/skills/memory/SKILL.md +36 -0
- viola/skills/my/SKILL.md +72 -0
- viola/skills/my/references/examples.md +75 -0
- viola/skills/skill-creator/SKILL.md +374 -0
- viola/skills/skill-creator/scripts/init_skill.py +378 -0
- viola/skills/skill-creator/scripts/package_skill.py +152 -0
- viola/skills/skill-creator/scripts/quick_validate.py +213 -0
- viola/skills/summarize/SKILL.md +67 -0
- viola/skills/tmux/SKILL.md +121 -0
- viola/skills/tmux/scripts/find-sessions.sh +112 -0
- viola/skills/tmux/scripts/wait-for-text.sh +83 -0
- viola/skills/update-setup/SKILL.md +123 -0
- viola/skills/weather/SKILL.md +49 -0
- viola/templates/AGENTS.md +15 -0
- viola/templates/HEARTBEAT.md +16 -0
- viola/templates/SKILL.md +0 -0
- viola/templates/SOUL.md +23 -0
- viola/templates/TOOLS.md +36 -0
- viola/templates/USER.md +49 -0
- viola/templates/__init__.py +0 -0
- viola/templates/agent/_snippets/untrusted_content.md +2 -0
- viola/templates/agent/consolidator_archive.md +13 -0
- viola/templates/agent/dream_phase1.md +40 -0
- viola/templates/agent/dream_phase2.md +35 -0
- viola/templates/agent/evaluator.md +17 -0
- viola/templates/agent/identity.md +37 -0
- viola/templates/agent/max_iterations_message.md +1 -0
- viola/templates/agent/platform_policy.md +10 -0
- viola/templates/agent/skills_section.md +6 -0
- viola/templates/agent/subagent_announce.md +8 -0
- viola/templates/agent/subagent_system.md +19 -0
- viola/templates/agent/tool_contract.md +67 -0
- viola/templates/memory/MEMORY.md +27 -0
- viola/templates/memory/__init__.py +0 -0
- viola/utils/__init__.py +6 -0
- viola/utils/artifacts.py +323 -0
- viola/utils/document.py +374 -0
- viola/utils/evaluator.py +89 -0
- viola/utils/gitstore.py +390 -0
- viola/utils/helpers.py +654 -0
- viola/utils/llm_runtime.py +22 -0
- viola/utils/logging_bridge.py +47 -0
- viola/utils/media_decode.py +54 -0
- viola/utils/path.py +107 -0
- viola/utils/progress_events.py +84 -0
- viola/utils/prompt_templates.py +35 -0
- viola/utils/restart.py +84 -0
- viola/utils/runtime.py +170 -0
- viola/utils/searchusage.py +168 -0
- viola/utils/subagent_channel_display.py +59 -0
- viola/utils/tool_hints.py +142 -0
- viola/viola.py +100 -0
- viola_agent-0.2.1.dist-info/METADATA +198 -0
- viola_agent-0.2.1.dist-info/RECORD +171 -0
- viola_agent-0.2.1.dist-info/WHEEL +4 -0
- viola_agent-0.2.1.dist-info/entry_points.txt +2 -0
- viola_agent-0.2.1.dist-info/licenses/LICENSE +21 -0
- viola_agent-0.2.1.dist-info/licenses/THIRD_PARTY_NOTICES.md +5 -0
viola/agent/loop.py
ADDED
|
@@ -0,0 +1,2058 @@
|
|
|
1
|
+
"""Agent loop: the core processing engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import dataclasses
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
from contextlib import AsyncExitStack, nullcontext, suppress
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from enum import Enum, auto
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Any, Awaitable, Callable
|
|
15
|
+
|
|
16
|
+
from loguru import logger
|
|
17
|
+
|
|
18
|
+
from viola.agent import context as agent_context
|
|
19
|
+
from viola.agent import model_presets as preset_helpers
|
|
20
|
+
from viola.agent.autocompact import AutoCompact
|
|
21
|
+
from viola.agent.context import ContextBuilder, api_channel_hidden_tools
|
|
22
|
+
from viola.agent.hook import AgentHook, CompositeHook
|
|
23
|
+
from viola.agent.memory import Consolidator, Dream
|
|
24
|
+
from viola.agent.progress_hook import AgentProgressHook
|
|
25
|
+
from viola.agent.runner import _MAX_INJECTIONS_PER_TURN, AgentRunner, AgentRunSpec
|
|
26
|
+
from viola.agent.subagent import SubagentManager
|
|
27
|
+
from viola.agent.tools.file_state import FileStateStore, bind_file_states, reset_file_states
|
|
28
|
+
from viola.agent.tools.message import MessageTool
|
|
29
|
+
from viola.agent.tools.registry import ToolRegistry
|
|
30
|
+
from viola.agent.tools.self import MyTool
|
|
31
|
+
from viola.bus.events import InboundMessage, OutboundMessage
|
|
32
|
+
from viola.bus.queue import MessageBus
|
|
33
|
+
from viola.command import (
|
|
34
|
+
CommandContext,
|
|
35
|
+
CommandRouter,
|
|
36
|
+
is_new_session_command,
|
|
37
|
+
register_builtin_commands,
|
|
38
|
+
)
|
|
39
|
+
from viola.config.schema import AgentDefaults, ModelPresetConfig
|
|
40
|
+
from viola.providers.base import LLMProvider
|
|
41
|
+
from viola.providers.factory import ProviderSnapshot
|
|
42
|
+
from viola.session.manager import Session, SessionManager
|
|
43
|
+
from viola.utils.artifacts import generated_attachment_paths_from_messages
|
|
44
|
+
from viola.utils.document import extract_documents, is_audio_media
|
|
45
|
+
from viola.utils.helpers import (
|
|
46
|
+
ensure_dir,
|
|
47
|
+
image_placeholder_text,
|
|
48
|
+
safe_filename,
|
|
49
|
+
sync_workspace_templates,
|
|
50
|
+
)
|
|
51
|
+
from viola.utils.helpers import truncate_text as truncate_text_fn
|
|
52
|
+
from viola.utils.llm_runtime import LLMRuntime
|
|
53
|
+
from viola.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
|
|
54
|
+
|
|
55
|
+
if TYPE_CHECKING:
|
|
56
|
+
from viola.config.schema import (
|
|
57
|
+
ChannelsConfig,
|
|
58
|
+
ProfilesConfig,
|
|
59
|
+
ToolsConfig,
|
|
60
|
+
)
|
|
61
|
+
from viola.cron.service import CronService
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
UNIFIED_SESSION_KEY = "unified:default"
|
|
65
|
+
|
|
66
|
+
# Matches bracket-wrapped metadata injected by the Twilio webhook, e.g.
|
|
67
|
+
# "[User profile name: ...]", "[Sender mobile_digits: ...]".
|
|
68
|
+
_METADATA_HEADER_LINE_RE = re.compile(r"^\[[^\]]+\]\s*$")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _extract_body_line(content: str) -> str:
|
|
72
|
+
"""Return the last non-metadata line from a multi-line inbound message.
|
|
73
|
+
|
|
74
|
+
The Twilio webhook prepends bracket-wrapped metadata lines before the
|
|
75
|
+
actual user body. When the full content string does not match any
|
|
76
|
+
registered command, try just the body so commands like ``/new`` still
|
|
77
|
+
fire even when the message arrived with a metadata preamble.
|
|
78
|
+
"""
|
|
79
|
+
for line in reversed(content.splitlines()):
|
|
80
|
+
line = line.strip()
|
|
81
|
+
if line and not _METADATA_HEADER_LINE_RE.match(line):
|
|
82
|
+
return line
|
|
83
|
+
return content.strip()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class TurnState(Enum):
|
|
87
|
+
RESTORE = auto()
|
|
88
|
+
COMPACT = auto()
|
|
89
|
+
COMMAND = auto()
|
|
90
|
+
BUILD = auto()
|
|
91
|
+
RUN = auto()
|
|
92
|
+
SAVE = auto()
|
|
93
|
+
RESPOND = auto()
|
|
94
|
+
DONE = auto()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _transcription_settings_from_config(config: Any) -> tuple[str, str, str, str | None, str | None]:
|
|
98
|
+
"""Match ChannelManager: resolve the STT provider and its credentials."""
|
|
99
|
+
from viola.providers.transcription import resolve_transcription_credentials
|
|
100
|
+
|
|
101
|
+
ch = config.channels
|
|
102
|
+
provider = ch.transcription_provider
|
|
103
|
+
key, base = resolve_transcription_credentials(getattr(config, "providers", None), provider)
|
|
104
|
+
return provider, key, base, ch.transcription_language, ch.transcription_model
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class StateTraceEntry:
|
|
109
|
+
state: TurnState
|
|
110
|
+
started_at: float
|
|
111
|
+
duration_ms: float
|
|
112
|
+
event: str
|
|
113
|
+
error: str | None = None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass
|
|
117
|
+
class TurnContext:
|
|
118
|
+
msg: InboundMessage
|
|
119
|
+
session_key: str
|
|
120
|
+
state: TurnState
|
|
121
|
+
turn_id: str
|
|
122
|
+
runtime: WorkspaceRuntime
|
|
123
|
+
session: Session | None = None
|
|
124
|
+
|
|
125
|
+
history: list[dict[str, Any]] = field(default_factory=list)
|
|
126
|
+
initial_messages: list[dict[str, Any]] = field(default_factory=list)
|
|
127
|
+
|
|
128
|
+
final_content: str | None = None
|
|
129
|
+
tools_used: list[str] = field(default_factory=list)
|
|
130
|
+
all_messages: list[dict[str, Any]] = field(default_factory=list)
|
|
131
|
+
stop_reason: str = ""
|
|
132
|
+
had_injections: bool = False
|
|
133
|
+
usage: dict[str, int] = field(default_factory=dict)
|
|
134
|
+
# Speech-to-text token usage this turn, keyed by transcription model.
|
|
135
|
+
stt_usage: dict[str, dict[str, int]] = field(default_factory=dict)
|
|
136
|
+
|
|
137
|
+
user_persisted_early: bool = False
|
|
138
|
+
save_skip: int = 0
|
|
139
|
+
|
|
140
|
+
outbound: OutboundMessage | None = None
|
|
141
|
+
generated_media: list[str] = field(default_factory=list)
|
|
142
|
+
|
|
143
|
+
on_progress: Callable[..., Awaitable[None]] | None = None
|
|
144
|
+
on_stream: Callable[[str], Awaitable[None]] | None = None
|
|
145
|
+
on_stream_end: Callable[..., Awaitable[None]] | None = None
|
|
146
|
+
on_retry_wait: Callable[[str], Awaitable[None]] | None = None
|
|
147
|
+
|
|
148
|
+
pending_queue: asyncio.Queue | None = None
|
|
149
|
+
pending_summary: str | None = None
|
|
150
|
+
|
|
151
|
+
trace: list[StateTraceEntry] = field(default_factory=list)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass
|
|
155
|
+
class WorkspaceRuntime:
|
|
156
|
+
"""Workspace-scoped runtime objects for memory/session isolation."""
|
|
157
|
+
|
|
158
|
+
workspace: Path
|
|
159
|
+
context: ContextBuilder
|
|
160
|
+
sessions: SessionManager
|
|
161
|
+
consolidator: Consolidator
|
|
162
|
+
auto_compact: AutoCompact
|
|
163
|
+
dream: Dream
|
|
164
|
+
file_state_store: FileStateStore
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class AgentLoop:
|
|
168
|
+
"""
|
|
169
|
+
The agent loop is the core processing engine.
|
|
170
|
+
|
|
171
|
+
It:
|
|
172
|
+
1. Receives messages from the bus
|
|
173
|
+
2. Builds context with history, memory, skills
|
|
174
|
+
3. Calls the LLM
|
|
175
|
+
4. Executes tool calls
|
|
176
|
+
5. Sends responses back
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def current_iteration(self) -> int:
|
|
181
|
+
return self._current_iteration
|
|
182
|
+
|
|
183
|
+
@property
|
|
184
|
+
def tool_names(self) -> list[str]:
|
|
185
|
+
return self.tools.tool_names
|
|
186
|
+
|
|
187
|
+
def llm_runtime(self) -> LLMRuntime:
|
|
188
|
+
"""Return the current provider/model pair owned by this loop."""
|
|
189
|
+
self._refresh_provider_snapshot()
|
|
190
|
+
return LLMRuntime(self.provider, self.model)
|
|
191
|
+
|
|
192
|
+
_RUNTIME_CHECKPOINT_KEY = "runtime_checkpoint"
|
|
193
|
+
_PENDING_USER_TURN_KEY = "pending_user_turn"
|
|
194
|
+
|
|
195
|
+
# Event-driven state transition table.
|
|
196
|
+
# Handlers return an event string; the driver looks up the next state here.
|
|
197
|
+
_TRANSITIONS: dict[tuple[TurnState, str], TurnState] = {
|
|
198
|
+
(TurnState.RESTORE, "ok"): TurnState.COMPACT,
|
|
199
|
+
(TurnState.COMPACT, "ok"): TurnState.COMMAND,
|
|
200
|
+
(TurnState.COMMAND, "dispatch"): TurnState.BUILD,
|
|
201
|
+
(TurnState.COMMAND, "shortcut"): TurnState.DONE,
|
|
202
|
+
(TurnState.BUILD, "ok"): TurnState.RUN,
|
|
203
|
+
(TurnState.RUN, "ok"): TurnState.SAVE,
|
|
204
|
+
(TurnState.SAVE, "ok"): TurnState.RESPOND,
|
|
205
|
+
(TurnState.RESPOND, "ok"): TurnState.DONE,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
def __init__(
|
|
209
|
+
self,
|
|
210
|
+
bus: MessageBus,
|
|
211
|
+
provider: LLMProvider,
|
|
212
|
+
workspace: Path,
|
|
213
|
+
model: str | None = None,
|
|
214
|
+
max_iterations: int | None = None,
|
|
215
|
+
context_window_tokens: int | None = None,
|
|
216
|
+
context_block_limit: int | None = None,
|
|
217
|
+
max_tool_result_chars: int | None = None,
|
|
218
|
+
provider_retry_mode: str = "standard",
|
|
219
|
+
tool_hint_max_length: int | None = None,
|
|
220
|
+
cron_service: CronService | None = None,
|
|
221
|
+
restrict_to_workspace: bool = False,
|
|
222
|
+
session_manager: SessionManager | None = None,
|
|
223
|
+
mcp_servers: dict | None = None,
|
|
224
|
+
channels_config: ChannelsConfig | None = None,
|
|
225
|
+
transcription_provider: str = "",
|
|
226
|
+
transcription_api_key: str = "",
|
|
227
|
+
transcription_api_base: str = "",
|
|
228
|
+
transcription_language: str | None = None,
|
|
229
|
+
transcription_model: str | None = None,
|
|
230
|
+
timezone: str | None = None,
|
|
231
|
+
session_ttl_minutes: int = 0,
|
|
232
|
+
consolidation_ratio: float = 0.5,
|
|
233
|
+
max_messages: int = 120,
|
|
234
|
+
per_user_workspaces: bool = False,
|
|
235
|
+
per_user_workspace_root: Path | None = None,
|
|
236
|
+
hooks: list[AgentHook] | None = None,
|
|
237
|
+
unified_session: bool = False,
|
|
238
|
+
disabled_skills: list[str] | None = None,
|
|
239
|
+
tools_config: ToolsConfig | None = None,
|
|
240
|
+
provider_snapshot_loader: Callable[..., ProviderSnapshot] | None = None,
|
|
241
|
+
provider_signature: tuple[object, ...] | None = None,
|
|
242
|
+
model_presets: dict[str, ModelPresetConfig] | None = None,
|
|
243
|
+
model_preset: str | None = None,
|
|
244
|
+
preset_snapshot_loader: preset_helpers.PresetSnapshotLoader | None = None,
|
|
245
|
+
runtime_model_publisher: Callable[[str, str | None], None] | None = None,
|
|
246
|
+
profiles_config: ProfilesConfig | None = None,
|
|
247
|
+
):
|
|
248
|
+
from viola.agent.profiles import build_policies
|
|
249
|
+
from viola.config.schema import ToolsConfig
|
|
250
|
+
|
|
251
|
+
_tc = tools_config or ToolsConfig()
|
|
252
|
+
# Only schema defaults are read here; ``model`` is required and comes from callers.
|
|
253
|
+
defaults = AgentDefaults.model_construct()
|
|
254
|
+
self.bus = bus
|
|
255
|
+
self.channels_config = channels_config
|
|
256
|
+
self.transcription_provider = transcription_provider
|
|
257
|
+
self.transcription_api_key = transcription_api_key or ""
|
|
258
|
+
self.transcription_api_base = transcription_api_base or ""
|
|
259
|
+
self.transcription_language = transcription_language
|
|
260
|
+
self.transcription_model = transcription_model
|
|
261
|
+
self.provider = provider
|
|
262
|
+
self._provider_snapshot_loader = provider_snapshot_loader
|
|
263
|
+
self._preset_snapshot_loader = preset_snapshot_loader
|
|
264
|
+
self._runtime_model_publisher = runtime_model_publisher
|
|
265
|
+
self._provider_signature = provider_signature
|
|
266
|
+
self._default_selection_signature = preset_helpers.default_selection_signature(provider_signature)
|
|
267
|
+
self.workspace = workspace
|
|
268
|
+
self._runtime_timezone = timezone
|
|
269
|
+
self._runtime_disabled_skills = list(disabled_skills or [])
|
|
270
|
+
self._runtime_session_ttl_minutes = session_ttl_minutes
|
|
271
|
+
self._runtime_consolidation_ratio = consolidation_ratio
|
|
272
|
+
self._per_user_workspaces = per_user_workspaces
|
|
273
|
+
self._per_user_workspace_root = (
|
|
274
|
+
ensure_dir(Path(per_user_workspace_root).expanduser())
|
|
275
|
+
if per_user_workspace_root is not None
|
|
276
|
+
else ensure_dir(workspace / "users")
|
|
277
|
+
)
|
|
278
|
+
self.model = model or provider.get_default_model()
|
|
279
|
+
self.max_iterations = (
|
|
280
|
+
max_iterations if max_iterations is not None else defaults.max_tool_iterations
|
|
281
|
+
)
|
|
282
|
+
self.context_window_tokens = (
|
|
283
|
+
context_window_tokens
|
|
284
|
+
if context_window_tokens is not None
|
|
285
|
+
else defaults.context_window_tokens
|
|
286
|
+
)
|
|
287
|
+
self.context_block_limit = context_block_limit
|
|
288
|
+
self.max_tool_result_chars = (
|
|
289
|
+
max_tool_result_chars
|
|
290
|
+
if max_tool_result_chars is not None
|
|
291
|
+
else defaults.max_tool_result_chars
|
|
292
|
+
)
|
|
293
|
+
self.provider_retry_mode = provider_retry_mode
|
|
294
|
+
self.tool_hint_max_length = (
|
|
295
|
+
tool_hint_max_length if tool_hint_max_length is not None
|
|
296
|
+
else defaults.tool_hint_max_length
|
|
297
|
+
)
|
|
298
|
+
self.tools_config = _tc
|
|
299
|
+
self.web_config = _tc.web
|
|
300
|
+
self.exec_config = _tc.exec
|
|
301
|
+
self.cron_service = cron_service
|
|
302
|
+
self.restrict_to_workspace = restrict_to_workspace
|
|
303
|
+
self._start_time = time.time()
|
|
304
|
+
self._last_usage: dict[str, int] = {}
|
|
305
|
+
self._extra_hooks: list[AgentHook] = hooks or []
|
|
306
|
+
|
|
307
|
+
self.context = ContextBuilder(
|
|
308
|
+
workspace,
|
|
309
|
+
timezone=timezone,
|
|
310
|
+
disabled_skills=disabled_skills,
|
|
311
|
+
allow_api_scheduling=_tc.allow_scheduled_tasks_on_api,
|
|
312
|
+
)
|
|
313
|
+
self.sessions = session_manager or SessionManager(workspace)
|
|
314
|
+
self.tools = ToolRegistry()
|
|
315
|
+
# One file-read/write tracker per logical session. The tool registry is
|
|
316
|
+
# shared by this loop, so tools resolve the active state via contextvars.
|
|
317
|
+
self._file_state_store = FileStateStore()
|
|
318
|
+
self.runner = AgentRunner(provider)
|
|
319
|
+
self.subagents = SubagentManager(
|
|
320
|
+
provider=provider,
|
|
321
|
+
workspace=workspace,
|
|
322
|
+
bus=bus,
|
|
323
|
+
model=self.model,
|
|
324
|
+
tools_config=_tc,
|
|
325
|
+
max_tool_result_chars=self.max_tool_result_chars,
|
|
326
|
+
restrict_to_workspace=restrict_to_workspace,
|
|
327
|
+
disabled_skills=disabled_skills,
|
|
328
|
+
max_iterations=self.max_iterations,
|
|
329
|
+
)
|
|
330
|
+
self._unified_session = unified_session
|
|
331
|
+
self._max_messages = max_messages if max_messages > 0 else 120
|
|
332
|
+
self._running = False
|
|
333
|
+
self._mcp_servers = mcp_servers or {}
|
|
334
|
+
# Per-profile tool policies (phase 5); applied per turn from the session key.
|
|
335
|
+
self.tool_policies = build_policies(profiles_config, self._mcp_servers)
|
|
336
|
+
self._mcp_stacks: dict[str, AsyncExitStack] = {}
|
|
337
|
+
self._mcp_connected = False
|
|
338
|
+
self._mcp_connecting = False
|
|
339
|
+
self._active_tasks: dict[str, list[asyncio.Task]] = {} # session_key -> tasks
|
|
340
|
+
self._background_tasks: list[asyncio.Task] = []
|
|
341
|
+
self._session_locks: dict[str, asyncio.Lock] = {}
|
|
342
|
+
# Per-session pending queues for mid-turn message injection.
|
|
343
|
+
# When a session has an active task, new messages for that session
|
|
344
|
+
# are routed here instead of creating a new task.
|
|
345
|
+
self._pending_queues: dict[str, asyncio.Queue] = {}
|
|
346
|
+
# VIOLA_MAX_CONCURRENT_REQUESTS: <=0 means unlimited; default 3.
|
|
347
|
+
_max = int(os.environ.get("VIOLA_MAX_CONCURRENT_REQUESTS", "3"))
|
|
348
|
+
self._concurrency_gate: asyncio.Semaphore | None = (
|
|
349
|
+
asyncio.Semaphore(_max) if _max > 0 else None
|
|
350
|
+
)
|
|
351
|
+
self.consolidator = Consolidator(
|
|
352
|
+
store=self.context.memory,
|
|
353
|
+
provider=provider,
|
|
354
|
+
model=self.model,
|
|
355
|
+
sessions=self.sessions,
|
|
356
|
+
context_window_tokens=self.context_window_tokens,
|
|
357
|
+
build_messages=self.context.build_messages,
|
|
358
|
+
get_tool_definitions=self.tools.get_definitions,
|
|
359
|
+
max_completion_tokens=provider.generation.max_tokens,
|
|
360
|
+
consolidation_ratio=consolidation_ratio,
|
|
361
|
+
)
|
|
362
|
+
self.auto_compact = AutoCompact(
|
|
363
|
+
sessions=self.sessions,
|
|
364
|
+
consolidator=self.consolidator,
|
|
365
|
+
session_ttl_minutes=session_ttl_minutes,
|
|
366
|
+
)
|
|
367
|
+
self.dream = Dream(
|
|
368
|
+
store=self.context.memory,
|
|
369
|
+
provider=provider,
|
|
370
|
+
model=self.model,
|
|
371
|
+
persistence_via_mcp_only=_tc.persistence_via_mcp_only,
|
|
372
|
+
)
|
|
373
|
+
self.model_presets: dict[str, ModelPresetConfig] = model_presets or {}
|
|
374
|
+
self._active_preset: str | None = None
|
|
375
|
+
if model_preset:
|
|
376
|
+
self.set_model_preset(model_preset, publish_update=False)
|
|
377
|
+
self._register_default_tools()
|
|
378
|
+
self._runtime_vars: dict[str, Any] = {}
|
|
379
|
+
self._current_iteration: int = 0
|
|
380
|
+
self._default_runtime = WorkspaceRuntime(
|
|
381
|
+
workspace=self.workspace,
|
|
382
|
+
context=self.context,
|
|
383
|
+
sessions=self.sessions,
|
|
384
|
+
consolidator=self.consolidator,
|
|
385
|
+
auto_compact=self.auto_compact,
|
|
386
|
+
dream=self.dream,
|
|
387
|
+
file_state_store=self._file_state_store,
|
|
388
|
+
)
|
|
389
|
+
self._workspace_runtimes: dict[str, WorkspaceRuntime] = {
|
|
390
|
+
self._runtime_id_for_workspace(self.workspace): self._default_runtime
|
|
391
|
+
}
|
|
392
|
+
self._session_runtime_ids: dict[str, str] = {}
|
|
393
|
+
self.commands = CommandRouter()
|
|
394
|
+
register_builtin_commands(self.commands)
|
|
395
|
+
|
|
396
|
+
@classmethod
|
|
397
|
+
def from_config(
|
|
398
|
+
cls,
|
|
399
|
+
config: Any,
|
|
400
|
+
bus: MessageBus | None = None,
|
|
401
|
+
**extra: Any,
|
|
402
|
+
) -> AgentLoop:
|
|
403
|
+
"""Create an AgentLoop from config with the common parameter set.
|
|
404
|
+
|
|
405
|
+
Extra keyword arguments are forwarded to ``AgentLoop.__init__``,
|
|
406
|
+
allowing callers to override or extend the standard config-derived
|
|
407
|
+
parameters (e.g. ``cron_service``, ``session_manager``).
|
|
408
|
+
"""
|
|
409
|
+
from viola.providers.factory import make_provider
|
|
410
|
+
|
|
411
|
+
if bus is None:
|
|
412
|
+
bus = MessageBus()
|
|
413
|
+
defaults = config.agents.defaults
|
|
414
|
+
provider = extra.pop("provider", None) or make_provider(config)
|
|
415
|
+
resolved = config.resolve_preset()
|
|
416
|
+
model = extra.pop("model", None) or resolved.model
|
|
417
|
+
context_window_tokens = extra.pop("context_window_tokens", None) or resolved.context_window_tokens
|
|
418
|
+
provider_snapshot_loader = extra.pop("provider_snapshot_loader", None)
|
|
419
|
+
preset_snapshot_loader = extra.pop("preset_snapshot_loader", None) or preset_helpers.make_preset_snapshot_loader(
|
|
420
|
+
config,
|
|
421
|
+
provider_snapshot_loader,
|
|
422
|
+
)
|
|
423
|
+
tp, tk, tb, tl, tm = _transcription_settings_from_config(config)
|
|
424
|
+
return cls(
|
|
425
|
+
bus=bus,
|
|
426
|
+
provider=provider,
|
|
427
|
+
workspace=config.workspace_path,
|
|
428
|
+
model=model,
|
|
429
|
+
max_iterations=defaults.max_tool_iterations,
|
|
430
|
+
context_window_tokens=context_window_tokens,
|
|
431
|
+
context_block_limit=defaults.context_block_limit,
|
|
432
|
+
max_tool_result_chars=defaults.max_tool_result_chars,
|
|
433
|
+
provider_retry_mode=defaults.provider_retry_mode,
|
|
434
|
+
tool_hint_max_length=defaults.tool_hint_max_length,
|
|
435
|
+
restrict_to_workspace=config.tools.restrict_to_workspace,
|
|
436
|
+
mcp_servers=config.tools.mcp_servers,
|
|
437
|
+
channels_config=config.channels,
|
|
438
|
+
transcription_provider=tp,
|
|
439
|
+
transcription_api_key=tk,
|
|
440
|
+
transcription_api_base=tb,
|
|
441
|
+
transcription_language=tl,
|
|
442
|
+
transcription_model=tm,
|
|
443
|
+
timezone=defaults.timezone,
|
|
444
|
+
unified_session=defaults.unified_session,
|
|
445
|
+
disabled_skills=defaults.disabled_skills,
|
|
446
|
+
session_ttl_minutes=defaults.session_ttl_minutes,
|
|
447
|
+
consolidation_ratio=defaults.consolidation_ratio,
|
|
448
|
+
max_messages=defaults.max_messages,
|
|
449
|
+
per_user_workspaces=defaults.per_user_workspaces,
|
|
450
|
+
per_user_workspace_root=(
|
|
451
|
+
Path(defaults.per_user_workspace_root).expanduser()
|
|
452
|
+
if defaults.per_user_workspace_root
|
|
453
|
+
else None
|
|
454
|
+
),
|
|
455
|
+
tools_config=config.tools,
|
|
456
|
+
model_presets=preset_helpers.configured_model_presets(config),
|
|
457
|
+
model_preset=defaults.model_preset,
|
|
458
|
+
provider_snapshot_loader=provider_snapshot_loader,
|
|
459
|
+
preset_snapshot_loader=preset_snapshot_loader,
|
|
460
|
+
profiles_config=getattr(config, "profiles", None),
|
|
461
|
+
**extra,
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
def _sync_subagent_runtime_limits(self) -> None:
|
|
465
|
+
"""Keep subagent runtime limits aligned with mutable loop settings."""
|
|
466
|
+
self.subagents.max_iterations = self.max_iterations
|
|
467
|
+
|
|
468
|
+
def _apply_provider_snapshot(
|
|
469
|
+
self,
|
|
470
|
+
snapshot: ProviderSnapshot,
|
|
471
|
+
*,
|
|
472
|
+
publish_update: bool = True,
|
|
473
|
+
model_preset: str | None = None,
|
|
474
|
+
) -> None:
|
|
475
|
+
"""Swap model/provider for future turns without disturbing an active one."""
|
|
476
|
+
provider = snapshot.provider
|
|
477
|
+
model = snapshot.model
|
|
478
|
+
context_window_tokens = snapshot.context_window_tokens
|
|
479
|
+
old_model = self.model
|
|
480
|
+
self.provider = provider
|
|
481
|
+
self.model = model
|
|
482
|
+
self.context_window_tokens = context_window_tokens
|
|
483
|
+
self.runner.provider = provider
|
|
484
|
+
self.subagents.set_provider(provider, model)
|
|
485
|
+
runtimes = getattr(self, "_workspace_runtimes", None)
|
|
486
|
+
if runtimes:
|
|
487
|
+
for runtime in runtimes.values():
|
|
488
|
+
runtime.consolidator.set_provider(provider, model, context_window_tokens)
|
|
489
|
+
runtime.dream.set_provider(provider, model)
|
|
490
|
+
else:
|
|
491
|
+
self.consolidator.set_provider(provider, model, context_window_tokens)
|
|
492
|
+
self.dream.set_provider(provider, model)
|
|
493
|
+
self._provider_signature = snapshot.signature
|
|
494
|
+
if publish_update and self._runtime_model_publisher is not None:
|
|
495
|
+
self._runtime_model_publisher(
|
|
496
|
+
self.model,
|
|
497
|
+
model_preset if model_preset is not None else self.model_preset,
|
|
498
|
+
)
|
|
499
|
+
logger.info("Runtime model switched for next turn: {} -> {}", old_model, model)
|
|
500
|
+
|
|
501
|
+
def _refresh_provider_snapshot(self) -> None:
|
|
502
|
+
if self._provider_snapshot_loader is None:
|
|
503
|
+
return
|
|
504
|
+
try:
|
|
505
|
+
snapshot = self._provider_snapshot_loader()
|
|
506
|
+
except Exception:
|
|
507
|
+
logger.exception("Failed to refresh provider config")
|
|
508
|
+
return
|
|
509
|
+
default_selection = preset_helpers.default_selection_signature(snapshot.signature)
|
|
510
|
+
if self._active_preset and self._default_selection_signature in (None, default_selection):
|
|
511
|
+
self._default_selection_signature = default_selection
|
|
512
|
+
try:
|
|
513
|
+
snapshot = self._build_model_preset_snapshot(self._active_preset)
|
|
514
|
+
except Exception:
|
|
515
|
+
logger.exception("Failed to refresh active model preset")
|
|
516
|
+
return
|
|
517
|
+
else:
|
|
518
|
+
self._active_preset = None
|
|
519
|
+
self._default_selection_signature = default_selection
|
|
520
|
+
if snapshot.signature == self._provider_signature:
|
|
521
|
+
return
|
|
522
|
+
self._default_selection_signature = preset_helpers.default_selection_signature(snapshot.signature)
|
|
523
|
+
self._apply_provider_snapshot(snapshot)
|
|
524
|
+
|
|
525
|
+
@property
|
|
526
|
+
def model_preset(self) -> str | None:
|
|
527
|
+
return self._active_preset
|
|
528
|
+
|
|
529
|
+
@model_preset.setter
|
|
530
|
+
def model_preset(self, name: str | None) -> None:
|
|
531
|
+
self.set_model_preset(name)
|
|
532
|
+
|
|
533
|
+
def _build_model_preset_snapshot(self, name: str) -> ProviderSnapshot:
|
|
534
|
+
return preset_helpers.build_runtime_preset_snapshot(
|
|
535
|
+
name=name,
|
|
536
|
+
presets=self.model_presets,
|
|
537
|
+
provider=self.provider,
|
|
538
|
+
loader=self._preset_snapshot_loader,
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
def set_model_preset(self, name: str | None, *, publish_update: bool = True) -> None:
|
|
542
|
+
"""Resolve a preset by name and apply all runtime model dependents."""
|
|
543
|
+
name = preset_helpers.normalize_preset_name(name, self.model_presets)
|
|
544
|
+
snapshot = self._build_model_preset_snapshot(name)
|
|
545
|
+
self._apply_provider_snapshot(snapshot, publish_update=publish_update, model_preset=name)
|
|
546
|
+
self._active_preset = name
|
|
547
|
+
|
|
548
|
+
@staticmethod
|
|
549
|
+
def _runtime_id_for_workspace(path: Path) -> str:
|
|
550
|
+
return str(path.expanduser().resolve(strict=False))
|
|
551
|
+
|
|
552
|
+
def _is_global_session(self, session_key: str) -> bool:
|
|
553
|
+
return (
|
|
554
|
+
session_key == UNIFIED_SESSION_KEY
|
|
555
|
+
or session_key in {"heartbeat"}
|
|
556
|
+
or session_key.startswith("cron:")
|
|
557
|
+
or session_key.startswith("system:")
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
def _workspace_user_key(self, msg: InboundMessage, effective_key: str) -> str | None:
|
|
561
|
+
if not self._per_user_workspaces:
|
|
562
|
+
return None
|
|
563
|
+
if msg.channel in {"cli", "system"}:
|
|
564
|
+
return None
|
|
565
|
+
if self._is_global_session(effective_key):
|
|
566
|
+
return None
|
|
567
|
+
if msg.channel != "api" and msg.sender_id:
|
|
568
|
+
return f"{msg.channel}:{msg.sender_id}"
|
|
569
|
+
return effective_key
|
|
570
|
+
|
|
571
|
+
def _workspace_for_user_key(self, user_key: str) -> Path:
|
|
572
|
+
safe_key = safe_filename(user_key.replace(":", "_"))
|
|
573
|
+
return ensure_dir(self._per_user_workspace_root / safe_key)
|
|
574
|
+
|
|
575
|
+
def _build_workspace_runtime(self, workspace: Path) -> WorkspaceRuntime:
|
|
576
|
+
sync_workspace_templates(workspace, silent=True)
|
|
577
|
+
context = ContextBuilder(
|
|
578
|
+
workspace,
|
|
579
|
+
timezone=self._runtime_timezone,
|
|
580
|
+
disabled_skills=self._runtime_disabled_skills,
|
|
581
|
+
allow_api_scheduling=self.tools_config.allow_scheduled_tasks_on_api,
|
|
582
|
+
)
|
|
583
|
+
sessions = SessionManager(workspace)
|
|
584
|
+
file_state_store = FileStateStore()
|
|
585
|
+
consolidator = Consolidator(
|
|
586
|
+
store=context.memory,
|
|
587
|
+
provider=self.provider,
|
|
588
|
+
model=self.model,
|
|
589
|
+
sessions=sessions,
|
|
590
|
+
context_window_tokens=self.context_window_tokens,
|
|
591
|
+
build_messages=context.build_messages,
|
|
592
|
+
get_tool_definitions=self.tools.get_definitions,
|
|
593
|
+
max_completion_tokens=self.provider.generation.max_tokens,
|
|
594
|
+
consolidation_ratio=self._runtime_consolidation_ratio,
|
|
595
|
+
)
|
|
596
|
+
auto_compact = AutoCompact(
|
|
597
|
+
sessions=sessions,
|
|
598
|
+
consolidator=consolidator,
|
|
599
|
+
session_ttl_minutes=self._runtime_session_ttl_minutes,
|
|
600
|
+
)
|
|
601
|
+
dream = Dream(
|
|
602
|
+
store=context.memory,
|
|
603
|
+
provider=self.provider,
|
|
604
|
+
model=self.model,
|
|
605
|
+
persistence_via_mcp_only=self.tools_config.persistence_via_mcp_only,
|
|
606
|
+
)
|
|
607
|
+
return WorkspaceRuntime(
|
|
608
|
+
workspace=workspace,
|
|
609
|
+
context=context,
|
|
610
|
+
sessions=sessions,
|
|
611
|
+
consolidator=consolidator,
|
|
612
|
+
auto_compact=auto_compact,
|
|
613
|
+
dream=dream,
|
|
614
|
+
file_state_store=file_state_store,
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
def runtime_for_session_key(self, session_key: str) -> WorkspaceRuntime:
|
|
618
|
+
runtime_id = self._session_runtime_ids.get(session_key)
|
|
619
|
+
if runtime_id:
|
|
620
|
+
runtime = self._workspace_runtimes.get(runtime_id)
|
|
621
|
+
if runtime is not None:
|
|
622
|
+
return runtime
|
|
623
|
+
if not self._per_user_workspaces or self._is_global_session(session_key):
|
|
624
|
+
return self._default_runtime
|
|
625
|
+
workspace = self._workspace_for_user_key(session_key)
|
|
626
|
+
runtime_id = self._runtime_id_for_workspace(workspace)
|
|
627
|
+
runtime = self._workspace_runtimes.get(runtime_id)
|
|
628
|
+
if runtime is None:
|
|
629
|
+
runtime = self._build_workspace_runtime(workspace)
|
|
630
|
+
self._workspace_runtimes[runtime_id] = runtime
|
|
631
|
+
self._session_runtime_ids[session_key] = runtime_id
|
|
632
|
+
return runtime
|
|
633
|
+
|
|
634
|
+
def _runtime_for_message(self, msg: InboundMessage, effective_key: str) -> WorkspaceRuntime:
|
|
635
|
+
user_key = self._workspace_user_key(msg, effective_key)
|
|
636
|
+
if user_key is None:
|
|
637
|
+
self._session_runtime_ids[effective_key] = self._runtime_id_for_workspace(self.workspace)
|
|
638
|
+
return self._default_runtime
|
|
639
|
+
workspace = self._workspace_for_user_key(user_key)
|
|
640
|
+
runtime_id = self._runtime_id_for_workspace(workspace)
|
|
641
|
+
runtime = self._workspace_runtimes.get(runtime_id)
|
|
642
|
+
if runtime is None:
|
|
643
|
+
runtime = self._build_workspace_runtime(workspace)
|
|
644
|
+
self._workspace_runtimes[runtime_id] = runtime
|
|
645
|
+
self._session_runtime_ids[effective_key] = runtime_id
|
|
646
|
+
return runtime
|
|
647
|
+
|
|
648
|
+
def flush_all_sessions(self) -> int:
|
|
649
|
+
total = 0
|
|
650
|
+
seen: set[int] = set()
|
|
651
|
+
for runtime in self._workspace_runtimes.values():
|
|
652
|
+
sid = id(runtime.sessions)
|
|
653
|
+
if sid in seen:
|
|
654
|
+
continue
|
|
655
|
+
seen.add(sid)
|
|
656
|
+
total += runtime.sessions.flush_all()
|
|
657
|
+
return total
|
|
658
|
+
|
|
659
|
+
def workspace_for_session_key(self, session_key: str) -> Path:
|
|
660
|
+
return self.runtime_for_session_key(session_key).workspace
|
|
661
|
+
|
|
662
|
+
def workspace_roots(self) -> list[Path]:
|
|
663
|
+
roots: list[Path] = []
|
|
664
|
+
seen: set[str] = set()
|
|
665
|
+
for runtime in self._workspace_runtimes.values():
|
|
666
|
+
rid = self._runtime_id_for_workspace(runtime.workspace)
|
|
667
|
+
if rid in seen:
|
|
668
|
+
continue
|
|
669
|
+
seen.add(rid)
|
|
670
|
+
roots.append(runtime.workspace)
|
|
671
|
+
return roots
|
|
672
|
+
|
|
673
|
+
def _register_default_tools(self) -> None:
|
|
674
|
+
"""Register the default set of tools via plugin loader."""
|
|
675
|
+
from viola.agent.tools.context import ToolContext
|
|
676
|
+
from viola.agent.tools.loader import ToolLoader
|
|
677
|
+
|
|
678
|
+
ctx = ToolContext(
|
|
679
|
+
config=self.tools_config,
|
|
680
|
+
workspace=str(self.workspace),
|
|
681
|
+
bus=self.bus,
|
|
682
|
+
subagent_manager=self.subagents,
|
|
683
|
+
cron_service=self.cron_service,
|
|
684
|
+
provider_snapshot_loader=self._provider_snapshot_loader,
|
|
685
|
+
timezone=self.context.timezone or "UTC",
|
|
686
|
+
)
|
|
687
|
+
loader = ToolLoader()
|
|
688
|
+
registered = loader.load(ctx, self.tools)
|
|
689
|
+
|
|
690
|
+
# MyTool needs runtime state reference — manual registration
|
|
691
|
+
if self.tools_config.my.enable:
|
|
692
|
+
self.tools.register(
|
|
693
|
+
MyTool(
|
|
694
|
+
runtime_state=self,
|
|
695
|
+
modify_allowed=(
|
|
696
|
+
self.tools_config.my.allow_set and not self.tools_config.persistence_via_mcp_only
|
|
697
|
+
),
|
|
698
|
+
)
|
|
699
|
+
)
|
|
700
|
+
registered.append("my")
|
|
701
|
+
|
|
702
|
+
logger.info("Registered {} tools: {}", len(registered), registered)
|
|
703
|
+
|
|
704
|
+
async def _connect_mcp(self) -> None:
|
|
705
|
+
"""Connect to configured MCP servers (one-time, lazy)."""
|
|
706
|
+
if self._mcp_connected or self._mcp_connecting or not self._mcp_servers:
|
|
707
|
+
return
|
|
708
|
+
self._mcp_connecting = True
|
|
709
|
+
from viola.agent.tools.mcp import connect_mcp_servers
|
|
710
|
+
|
|
711
|
+
try:
|
|
712
|
+
self._mcp_stacks = await connect_mcp_servers(self._mcp_servers, self.tools)
|
|
713
|
+
if self._mcp_stacks:
|
|
714
|
+
self._mcp_connected = True
|
|
715
|
+
else:
|
|
716
|
+
logger.warning("No MCP servers connected successfully (will retry next message)")
|
|
717
|
+
except asyncio.CancelledError:
|
|
718
|
+
logger.warning("MCP connection cancelled (will retry next message)")
|
|
719
|
+
self._mcp_stacks.clear()
|
|
720
|
+
except BaseException as e:
|
|
721
|
+
logger.warning("Failed to connect MCP servers (will retry next message): {}", e)
|
|
722
|
+
self._mcp_stacks.clear()
|
|
723
|
+
finally:
|
|
724
|
+
self._mcp_connecting = False
|
|
725
|
+
|
|
726
|
+
def _set_tool_context(
|
|
727
|
+
self, channel: str, chat_id: str,
|
|
728
|
+
message_id: str | None = None, metadata: dict | None = None,
|
|
729
|
+
session_key: str | None = None,
|
|
730
|
+
) -> None:
|
|
731
|
+
"""Update context for all tools that need routing info."""
|
|
732
|
+
from viola.agent.tools.context import ContextAware, RequestContext
|
|
733
|
+
|
|
734
|
+
if session_key is not None:
|
|
735
|
+
effective_key = session_key
|
|
736
|
+
elif self._unified_session:
|
|
737
|
+
effective_key = UNIFIED_SESSION_KEY
|
|
738
|
+
else:
|
|
739
|
+
effective_key = f"{channel}:{chat_id}"
|
|
740
|
+
|
|
741
|
+
request_ctx = RequestContext(
|
|
742
|
+
channel=channel,
|
|
743
|
+
chat_id=chat_id,
|
|
744
|
+
message_id=message_id,
|
|
745
|
+
session_key=effective_key,
|
|
746
|
+
metadata=dict(metadata or {}),
|
|
747
|
+
)
|
|
748
|
+
|
|
749
|
+
for name in self.tools.tool_names:
|
|
750
|
+
tool = self.tools.get(name)
|
|
751
|
+
if tool and isinstance(tool, ContextAware):
|
|
752
|
+
tool.set_context(request_ctx)
|
|
753
|
+
|
|
754
|
+
@staticmethod
|
|
755
|
+
def _runtime_chat_id(msg: InboundMessage) -> str:
|
|
756
|
+
"""Return the chat id shown in runtime metadata for the model."""
|
|
757
|
+
return str(msg.metadata.get("context_chat_id") or msg.chat_id)
|
|
758
|
+
|
|
759
|
+
async def _build_bus_progress_callback(
|
|
760
|
+
self, msg: InboundMessage
|
|
761
|
+
) -> Callable[..., Awaitable[None]]:
|
|
762
|
+
"""Build a progress callback that publishes to the message bus."""
|
|
763
|
+
|
|
764
|
+
async def _bus_progress(
|
|
765
|
+
content: str,
|
|
766
|
+
*,
|
|
767
|
+
tool_hint: bool = False,
|
|
768
|
+
tool_events: list[dict[str, Any]] | None = None,
|
|
769
|
+
reasoning: bool = False,
|
|
770
|
+
reasoning_end: bool = False,
|
|
771
|
+
) -> None:
|
|
772
|
+
meta = dict(msg.metadata or {})
|
|
773
|
+
meta["_progress"] = True
|
|
774
|
+
meta["_tool_hint"] = tool_hint
|
|
775
|
+
if reasoning:
|
|
776
|
+
meta["_reasoning_delta"] = True
|
|
777
|
+
if reasoning_end:
|
|
778
|
+
meta["_reasoning_end"] = True
|
|
779
|
+
if tool_events:
|
|
780
|
+
meta["_tool_events"] = tool_events
|
|
781
|
+
await self.bus.publish_outbound(
|
|
782
|
+
OutboundMessage(
|
|
783
|
+
channel=msg.channel,
|
|
784
|
+
chat_id=msg.chat_id,
|
|
785
|
+
content=content,
|
|
786
|
+
metadata=meta,
|
|
787
|
+
)
|
|
788
|
+
)
|
|
789
|
+
|
|
790
|
+
return _bus_progress
|
|
791
|
+
|
|
792
|
+
async def _build_retry_wait_callback(
|
|
793
|
+
self, msg: InboundMessage
|
|
794
|
+
) -> Callable[[str], Awaitable[None]]:
|
|
795
|
+
"""Build a retry-wait callback that publishes to the message bus."""
|
|
796
|
+
|
|
797
|
+
async def _on_retry_wait(content: str) -> None:
|
|
798
|
+
meta = dict(msg.metadata or {})
|
|
799
|
+
meta["_retry_wait"] = True
|
|
800
|
+
await self.bus.publish_outbound(
|
|
801
|
+
OutboundMessage(
|
|
802
|
+
channel=msg.channel,
|
|
803
|
+
chat_id=msg.chat_id,
|
|
804
|
+
content=content,
|
|
805
|
+
metadata=meta,
|
|
806
|
+
)
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
return _on_retry_wait
|
|
810
|
+
|
|
811
|
+
def _persist_user_message_early(
|
|
812
|
+
self,
|
|
813
|
+
msg: InboundMessage,
|
|
814
|
+
session: Session,
|
|
815
|
+
**kwargs: Any,
|
|
816
|
+
) -> bool:
|
|
817
|
+
"""Persist the triggering user message before the turn starts.
|
|
818
|
+
|
|
819
|
+
Returns True if the message was persisted.
|
|
820
|
+
"""
|
|
821
|
+
media_paths = [p for p in (msg.media or []) if isinstance(p, str) and p]
|
|
822
|
+
has_text = isinstance(msg.content, str) and msg.content.strip()
|
|
823
|
+
if has_text or media_paths:
|
|
824
|
+
extra: dict[str, Any] = ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
|
|
825
|
+
extra.update(kwargs)
|
|
826
|
+
text = msg.content if isinstance(msg.content, str) else ""
|
|
827
|
+
session.add_message("user", text, **extra)
|
|
828
|
+
self._mark_pending_user_turn(session)
|
|
829
|
+
self.runtime_for_session_key(session.key).sessions.save(session)
|
|
830
|
+
return True
|
|
831
|
+
return False
|
|
832
|
+
|
|
833
|
+
def _build_initial_messages(
|
|
834
|
+
self,
|
|
835
|
+
msg: InboundMessage,
|
|
836
|
+
session: Session,
|
|
837
|
+
history: list[dict[str, Any]],
|
|
838
|
+
pending_summary: str | None,
|
|
839
|
+
context: ContextBuilder,
|
|
840
|
+
) -> list[dict[str, Any]]:
|
|
841
|
+
"""Build the initial message list for the LLM turn."""
|
|
842
|
+
return context.build_messages(
|
|
843
|
+
history=history,
|
|
844
|
+
current_message=msg.content,
|
|
845
|
+
media=msg.media if msg.media else None,
|
|
846
|
+
channel=msg.channel,
|
|
847
|
+
chat_id=self._runtime_chat_id(msg),
|
|
848
|
+
sender_id=msg.sender_id,
|
|
849
|
+
session_summary=pending_summary,
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
async def _dispatch_command_inline(
|
|
853
|
+
self,
|
|
854
|
+
msg: InboundMessage,
|
|
855
|
+
key: str,
|
|
856
|
+
raw: str,
|
|
857
|
+
dispatch_fn: Callable[[CommandContext], Awaitable[OutboundMessage | None]],
|
|
858
|
+
runtime: WorkspaceRuntime | None = None,
|
|
859
|
+
) -> None:
|
|
860
|
+
"""Dispatch a command directly from the run() loop and publish the result."""
|
|
861
|
+
resolved_runtime = runtime or self.runtime_for_session_key(key)
|
|
862
|
+
session = resolved_runtime.sessions.get_or_create(key)
|
|
863
|
+
ctx = CommandContext(msg=msg, session=session, key=key, raw=raw, loop=self)
|
|
864
|
+
result = await dispatch_fn(ctx)
|
|
865
|
+
if result:
|
|
866
|
+
await self.bus.publish_outbound(result)
|
|
867
|
+
else:
|
|
868
|
+
logger.warning("Command '{}' matched but dispatch returned None", raw)
|
|
869
|
+
|
|
870
|
+
async def _cancel_active_tasks(self, key: str) -> int:
|
|
871
|
+
"""Cancel and await all active tasks and subagents for *key*.
|
|
872
|
+
|
|
873
|
+
Returns the total number of cancelled tasks + subagents.
|
|
874
|
+
"""
|
|
875
|
+
tasks = self._active_tasks.pop(key, [])
|
|
876
|
+
cancelled = sum(1 for t in tasks if not t.done() and t.cancel())
|
|
877
|
+
for t in tasks:
|
|
878
|
+
with suppress(asyncio.CancelledError, Exception):
|
|
879
|
+
await t
|
|
880
|
+
sub_cancelled = await self.subagents.cancel_by_session(key)
|
|
881
|
+
return cancelled + sub_cancelled
|
|
882
|
+
|
|
883
|
+
def _effective_session_key(self, msg: InboundMessage) -> str:
|
|
884
|
+
"""Return the session key used for task routing and mid-turn injections."""
|
|
885
|
+
if self._unified_session and not msg.session_key_override:
|
|
886
|
+
return UNIFIED_SESSION_KEY
|
|
887
|
+
return msg.session_key
|
|
888
|
+
|
|
889
|
+
def _replay_token_budget(self) -> int:
|
|
890
|
+
"""Derive a token budget for session history replay from the context window."""
|
|
891
|
+
if self.context_window_tokens <= 0:
|
|
892
|
+
return 0
|
|
893
|
+
max_output = getattr(getattr(self.provider, "generation", None), "max_tokens", 4096)
|
|
894
|
+
try:
|
|
895
|
+
reserved_output = int(max_output)
|
|
896
|
+
except (TypeError, ValueError):
|
|
897
|
+
reserved_output = 4096
|
|
898
|
+
budget = self.context_window_tokens - max(1, reserved_output) - 1024
|
|
899
|
+
return budget if budget > 0 else max(128, self.context_window_tokens // 2)
|
|
900
|
+
|
|
901
|
+
async def _run_agent_loop(
|
|
902
|
+
self,
|
|
903
|
+
initial_messages: list[dict],
|
|
904
|
+
runtime: WorkspaceRuntime,
|
|
905
|
+
on_progress: Callable[..., Awaitable[None]] | None = None,
|
|
906
|
+
on_stream: Callable[[str], Awaitable[None]] | None = None,
|
|
907
|
+
on_stream_end: Callable[..., Awaitable[None]] | None = None,
|
|
908
|
+
on_retry_wait: Callable[[str], Awaitable[None]] | None = None,
|
|
909
|
+
*,
|
|
910
|
+
tools: Any | None = None,
|
|
911
|
+
session: Session | None = None,
|
|
912
|
+
channel: str = "cli",
|
|
913
|
+
chat_id: str = "direct",
|
|
914
|
+
message_id: str | None = None,
|
|
915
|
+
metadata: dict[str, Any] | None = None,
|
|
916
|
+
session_key: str | None = None,
|
|
917
|
+
pending_queue: asyncio.Queue | None = None,
|
|
918
|
+
) -> tuple[str | None, list[str], list[dict], str, bool]:
|
|
919
|
+
"""Run the agent iteration loop.
|
|
920
|
+
|
|
921
|
+
*on_stream*: called with each content delta during streaming.
|
|
922
|
+
*on_stream_end(resuming)*: called when a streaming session finishes.
|
|
923
|
+
``resuming=True`` means tool calls follow (spinner should restart);
|
|
924
|
+
``resuming=False`` means this is the final response.
|
|
925
|
+
|
|
926
|
+
Returns (final_content, tools_used, messages, stop_reason, had_injections).
|
|
927
|
+
"""
|
|
928
|
+
self._sync_subagent_runtime_limits()
|
|
929
|
+
|
|
930
|
+
loop_hook = AgentProgressHook(
|
|
931
|
+
on_progress=on_progress,
|
|
932
|
+
on_stream=on_stream,
|
|
933
|
+
on_stream_end=on_stream_end,
|
|
934
|
+
channel=channel,
|
|
935
|
+
chat_id=chat_id,
|
|
936
|
+
message_id=message_id,
|
|
937
|
+
metadata=metadata,
|
|
938
|
+
session_key=session_key,
|
|
939
|
+
tool_hint_max_length=self.tool_hint_max_length,
|
|
940
|
+
set_tool_context=self._set_tool_context,
|
|
941
|
+
on_iteration=lambda iteration: setattr(self, "_current_iteration", iteration),
|
|
942
|
+
)
|
|
943
|
+
hook: AgentHook = (
|
|
944
|
+
CompositeHook([loop_hook] + self._extra_hooks) if self._extra_hooks else loop_hook
|
|
945
|
+
)
|
|
946
|
+
|
|
947
|
+
async def _checkpoint(payload: dict[str, Any]) -> None:
|
|
948
|
+
if session is None:
|
|
949
|
+
return
|
|
950
|
+
self._set_runtime_checkpoint(session, payload)
|
|
951
|
+
|
|
952
|
+
async def _drain_pending(*, limit: int = _MAX_INJECTIONS_PER_TURN) -> list[dict[str, Any]]:
|
|
953
|
+
"""Drain follow-up messages from the pending queue.
|
|
954
|
+
|
|
955
|
+
When no messages are immediately available but sub-agents
|
|
956
|
+
spawned in this dispatch are still running, blocks until at
|
|
957
|
+
least one result arrives (or timeout). This keeps the runner
|
|
958
|
+
loop alive so subsequent sub-agent completions are consumed
|
|
959
|
+
in-order rather than dispatched separately.
|
|
960
|
+
"""
|
|
961
|
+
if pending_queue is None:
|
|
962
|
+
return []
|
|
963
|
+
|
|
964
|
+
async def _to_user_message(pending_msg: InboundMessage) -> dict[str, Any]:
|
|
965
|
+
content = pending_msg.content
|
|
966
|
+
media = pending_msg.media if pending_msg.media else None
|
|
967
|
+
if media:
|
|
968
|
+
content, media = await self._prepare_inbound_media(content, list(media))
|
|
969
|
+
media = media or None
|
|
970
|
+
user_content = runtime.context._build_user_content(content, media)
|
|
971
|
+
runtime_ctx = runtime.context._build_runtime_context(
|
|
972
|
+
pending_msg.channel,
|
|
973
|
+
self._runtime_chat_id(pending_msg),
|
|
974
|
+
runtime.context.timezone,
|
|
975
|
+
)
|
|
976
|
+
if isinstance(user_content, str):
|
|
977
|
+
merged: str | list[dict[str, Any]] = f"{runtime_ctx}\n\n{user_content}"
|
|
978
|
+
else:
|
|
979
|
+
merged = [{"type": "text", "text": runtime_ctx}] + user_content
|
|
980
|
+
return {"role": "user", "content": merged}
|
|
981
|
+
|
|
982
|
+
items: list[dict[str, Any]] = []
|
|
983
|
+
while len(items) < limit:
|
|
984
|
+
try:
|
|
985
|
+
items.append(await _to_user_message(pending_queue.get_nowait()))
|
|
986
|
+
except asyncio.QueueEmpty:
|
|
987
|
+
break
|
|
988
|
+
|
|
989
|
+
# Block if nothing drained but sub-agents spawned in this dispatch
|
|
990
|
+
# are still running. Keeps the runner loop alive so subsequent
|
|
991
|
+
# completions are injected in-order rather than dispatched separately.
|
|
992
|
+
if (not items
|
|
993
|
+
and session is not None
|
|
994
|
+
and self.subagents.get_running_count_by_session(session.key) > 0):
|
|
995
|
+
try:
|
|
996
|
+
msg = await asyncio.wait_for(pending_queue.get(), timeout=300)
|
|
997
|
+
except asyncio.TimeoutError:
|
|
998
|
+
logger.warning(
|
|
999
|
+
"Timeout waiting for sub-agent completion in session {}",
|
|
1000
|
+
session.key,
|
|
1001
|
+
)
|
|
1002
|
+
return items
|
|
1003
|
+
items.append(await _to_user_message(msg))
|
|
1004
|
+
while len(items) < limit:
|
|
1005
|
+
try:
|
|
1006
|
+
items.append(await _to_user_message(pending_queue.get_nowait()))
|
|
1007
|
+
except asyncio.QueueEmpty:
|
|
1008
|
+
break
|
|
1009
|
+
|
|
1010
|
+
return items
|
|
1011
|
+
|
|
1012
|
+
active_session_key = session.key if session else session_key
|
|
1013
|
+
file_state_token = bind_file_states(runtime.file_state_store.for_session(active_session_key))
|
|
1014
|
+
try:
|
|
1015
|
+
result = await self.runner.run(AgentRunSpec(
|
|
1016
|
+
initial_messages=initial_messages,
|
|
1017
|
+
tools=tools if tools is not None else self.tools,
|
|
1018
|
+
model=self.model,
|
|
1019
|
+
max_iterations=self.max_iterations,
|
|
1020
|
+
max_tool_result_chars=self.max_tool_result_chars,
|
|
1021
|
+
hook=hook,
|
|
1022
|
+
error_message="Sorry, I encountered an error calling the AI model.",
|
|
1023
|
+
concurrent_tools=True,
|
|
1024
|
+
workspace=runtime.workspace,
|
|
1025
|
+
session_key=session.key if session else None,
|
|
1026
|
+
context_window_tokens=self.context_window_tokens,
|
|
1027
|
+
context_block_limit=self.context_block_limit,
|
|
1028
|
+
provider_retry_mode=self.provider_retry_mode,
|
|
1029
|
+
progress_callback=on_progress,
|
|
1030
|
+
stream_progress_deltas=on_stream is not None,
|
|
1031
|
+
retry_wait_callback=on_retry_wait,
|
|
1032
|
+
checkpoint_callback=_checkpoint,
|
|
1033
|
+
injection_callback=_drain_pending,
|
|
1034
|
+
excluded_prompt_tools=(
|
|
1035
|
+
api_channel_hidden_tools(allow_scheduling=self.tools_config.allow_scheduled_tasks_on_api)
|
|
1036
|
+
if channel == "api"
|
|
1037
|
+
else frozenset()
|
|
1038
|
+
),
|
|
1039
|
+
))
|
|
1040
|
+
finally:
|
|
1041
|
+
reset_file_states(file_state_token)
|
|
1042
|
+
self._last_usage = result.usage
|
|
1043
|
+
if result.stop_reason == "max_iterations":
|
|
1044
|
+
logger.warning("Max iterations ({}) reached", self.max_iterations)
|
|
1045
|
+
# Push final content through stream so streaming channels (e.g. Feishu)
|
|
1046
|
+
# update the card instead of leaving it empty.
|
|
1047
|
+
if on_stream and on_stream_end:
|
|
1048
|
+
await on_stream(result.final_content or "")
|
|
1049
|
+
await on_stream_end(resuming=False)
|
|
1050
|
+
elif result.stop_reason == "error":
|
|
1051
|
+
logger.error("LLM returned error: {}", (result.final_content or "")[:200])
|
|
1052
|
+
return result.final_content, result.tools_used, result.messages, result.stop_reason, result.had_injections
|
|
1053
|
+
|
|
1054
|
+
async def run(self) -> None:
|
|
1055
|
+
"""Run the agent loop, dispatching messages as tasks to stay responsive to /stop."""
|
|
1056
|
+
self._running = True
|
|
1057
|
+
await self._connect_mcp()
|
|
1058
|
+
logger.info("Agent loop started")
|
|
1059
|
+
|
|
1060
|
+
while self._running:
|
|
1061
|
+
try:
|
|
1062
|
+
msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
|
|
1063
|
+
except asyncio.TimeoutError:
|
|
1064
|
+
for runtime_id, runtime in self._workspace_runtimes.items():
|
|
1065
|
+
active_keys = [
|
|
1066
|
+
key for key, rid in self._session_runtime_ids.items()
|
|
1067
|
+
if rid == runtime_id and key in self._pending_queues
|
|
1068
|
+
]
|
|
1069
|
+
runtime.auto_compact.check_expired(
|
|
1070
|
+
self._schedule_background,
|
|
1071
|
+
active_session_keys=active_keys,
|
|
1072
|
+
)
|
|
1073
|
+
continue
|
|
1074
|
+
except asyncio.CancelledError:
|
|
1075
|
+
# Preserve real task cancellation so shutdown can complete cleanly.
|
|
1076
|
+
# Only ignore non-task CancelledError signals that may leak from integrations.
|
|
1077
|
+
if not self._running or asyncio.current_task().cancelling():
|
|
1078
|
+
raise
|
|
1079
|
+
continue
|
|
1080
|
+
except Exception as e:
|
|
1081
|
+
logger.warning("Error consuming inbound message: {}, continuing...", e)
|
|
1082
|
+
continue
|
|
1083
|
+
|
|
1084
|
+
if await agent_context.handle_runtime_control(self, msg, self.tools):
|
|
1085
|
+
continue
|
|
1086
|
+
raw = msg.content.strip()
|
|
1087
|
+
effective_key = self._effective_session_key(msg)
|
|
1088
|
+
runtime = self._runtime_for_message(msg, effective_key)
|
|
1089
|
+
if self.commands.is_priority(raw):
|
|
1090
|
+
await self._dispatch_command_inline(
|
|
1091
|
+
msg, effective_key, raw,
|
|
1092
|
+
self.commands.dispatch_priority,
|
|
1093
|
+
runtime=runtime,
|
|
1094
|
+
)
|
|
1095
|
+
continue
|
|
1096
|
+
# If this session already has an active pending queue (i.e. a task
|
|
1097
|
+
# is processing this session), route the message there for mid-turn
|
|
1098
|
+
# injection instead of creating a competing task.
|
|
1099
|
+
if effective_key in self._pending_queues:
|
|
1100
|
+
# Non-priority commands must not be queued for injection;
|
|
1101
|
+
# dispatch them directly (same pattern as priority commands).
|
|
1102
|
+
if self.commands.is_dispatchable_command(raw):
|
|
1103
|
+
await self._dispatch_command_inline(
|
|
1104
|
+
msg, effective_key, raw,
|
|
1105
|
+
self.commands.dispatch,
|
|
1106
|
+
runtime=runtime,
|
|
1107
|
+
)
|
|
1108
|
+
continue
|
|
1109
|
+
pending_msg = msg
|
|
1110
|
+
if effective_key != msg.session_key:
|
|
1111
|
+
pending_msg = dataclasses.replace(
|
|
1112
|
+
msg,
|
|
1113
|
+
session_key_override=effective_key,
|
|
1114
|
+
)
|
|
1115
|
+
try:
|
|
1116
|
+
self._pending_queues[effective_key].put_nowait(pending_msg)
|
|
1117
|
+
except asyncio.QueueFull:
|
|
1118
|
+
logger.warning(
|
|
1119
|
+
"Pending queue full for session {}, falling back to queued task",
|
|
1120
|
+
effective_key,
|
|
1121
|
+
)
|
|
1122
|
+
else:
|
|
1123
|
+
logger.info(
|
|
1124
|
+
"Routed follow-up message to pending queue for session {}",
|
|
1125
|
+
effective_key,
|
|
1126
|
+
)
|
|
1127
|
+
continue
|
|
1128
|
+
# Compute the effective session key before dispatching
|
|
1129
|
+
# This ensures /stop command can find tasks correctly when unified session is enabled
|
|
1130
|
+
task = asyncio.create_task(self._dispatch(msg))
|
|
1131
|
+
self._active_tasks.setdefault(effective_key, []).append(task)
|
|
1132
|
+
task.add_done_callback(
|
|
1133
|
+
lambda t, k=effective_key: self._active_tasks.get(k, [])
|
|
1134
|
+
and self._active_tasks[k].remove(t)
|
|
1135
|
+
if t in self._active_tasks.get(k, [])
|
|
1136
|
+
else None
|
|
1137
|
+
)
|
|
1138
|
+
|
|
1139
|
+
async def _dispatch(self, msg: InboundMessage) -> None:
|
|
1140
|
+
"""Process a message: per-session serial, cross-session concurrent."""
|
|
1141
|
+
session_key = self._effective_session_key(msg)
|
|
1142
|
+
runtime = self._runtime_for_message(msg, session_key)
|
|
1143
|
+
if session_key != msg.session_key:
|
|
1144
|
+
msg = dataclasses.replace(msg, session_key_override=session_key)
|
|
1145
|
+
lock = self._session_locks.setdefault(session_key, asyncio.Lock())
|
|
1146
|
+
gate = self._concurrency_gate or nullcontext()
|
|
1147
|
+
|
|
1148
|
+
# Register a pending queue so follow-up messages for this session are
|
|
1149
|
+
# routed here (mid-turn injection) instead of spawning a new task.
|
|
1150
|
+
pending = asyncio.Queue(maxsize=20)
|
|
1151
|
+
self._pending_queues[session_key] = pending
|
|
1152
|
+
|
|
1153
|
+
try:
|
|
1154
|
+
async with lock, gate:
|
|
1155
|
+
try:
|
|
1156
|
+
on_stream = on_stream_end = None
|
|
1157
|
+
if msg.metadata.get("_wants_stream"):
|
|
1158
|
+
# Split one answer into distinct stream segments.
|
|
1159
|
+
stream_base_id = f"{msg.session_key}:{time.time_ns()}"
|
|
1160
|
+
stream_segment = 0
|
|
1161
|
+
|
|
1162
|
+
def _current_stream_id() -> str:
|
|
1163
|
+
return f"{stream_base_id}:{stream_segment}"
|
|
1164
|
+
|
|
1165
|
+
async def on_stream(delta: str) -> None:
|
|
1166
|
+
meta = dict(msg.metadata or {})
|
|
1167
|
+
meta["_stream_delta"] = True
|
|
1168
|
+
meta["_stream_id"] = _current_stream_id()
|
|
1169
|
+
await self.bus.publish_outbound(OutboundMessage(
|
|
1170
|
+
channel=msg.channel, chat_id=msg.chat_id,
|
|
1171
|
+
content=delta,
|
|
1172
|
+
metadata=meta,
|
|
1173
|
+
))
|
|
1174
|
+
|
|
1175
|
+
async def on_stream_end(*, resuming: bool = False) -> None:
|
|
1176
|
+
nonlocal stream_segment
|
|
1177
|
+
meta = dict(msg.metadata or {})
|
|
1178
|
+
meta["_stream_end"] = True
|
|
1179
|
+
meta["_resuming"] = resuming
|
|
1180
|
+
meta["_stream_id"] = _current_stream_id()
|
|
1181
|
+
await self.bus.publish_outbound(OutboundMessage(
|
|
1182
|
+
channel=msg.channel, chat_id=msg.chat_id,
|
|
1183
|
+
content="",
|
|
1184
|
+
metadata=meta,
|
|
1185
|
+
))
|
|
1186
|
+
stream_segment += 1
|
|
1187
|
+
|
|
1188
|
+
response = await self._process_message(
|
|
1189
|
+
msg, on_stream=on_stream, on_stream_end=on_stream_end,
|
|
1190
|
+
pending_queue=pending,
|
|
1191
|
+
runtime=runtime,
|
|
1192
|
+
)
|
|
1193
|
+
if response is not None:
|
|
1194
|
+
await self.bus.publish_outbound(response)
|
|
1195
|
+
elif msg.channel == "cli":
|
|
1196
|
+
await self.bus.publish_outbound(OutboundMessage(
|
|
1197
|
+
channel=msg.channel, chat_id=msg.chat_id,
|
|
1198
|
+
content="", metadata=msg.metadata or {},
|
|
1199
|
+
))
|
|
1200
|
+
except asyncio.CancelledError:
|
|
1201
|
+
logger.info("Task cancelled for session {}", session_key)
|
|
1202
|
+
# Preserve partial context from the interrupted turn so
|
|
1203
|
+
# the user does not lose tool results and assistant
|
|
1204
|
+
# messages accumulated before /stop. The checkpoint was
|
|
1205
|
+
# already persisted to session metadata by
|
|
1206
|
+
# _emit_checkpoint during tool execution; materializing
|
|
1207
|
+
# it into session history now makes it visible in the
|
|
1208
|
+
# next conversation turn.
|
|
1209
|
+
try:
|
|
1210
|
+
key = self._effective_session_key(msg)
|
|
1211
|
+
restored_runtime = self.runtime_for_session_key(key)
|
|
1212
|
+
session = restored_runtime.sessions.get_or_create(key)
|
|
1213
|
+
if self._restore_runtime_checkpoint(session):
|
|
1214
|
+
self._clear_pending_user_turn(session)
|
|
1215
|
+
restored_runtime.sessions.save(session)
|
|
1216
|
+
logger.info(
|
|
1217
|
+
"Restored partial context for cancelled session {}",
|
|
1218
|
+
key,
|
|
1219
|
+
)
|
|
1220
|
+
except Exception:
|
|
1221
|
+
logger.debug(
|
|
1222
|
+
"Could not restore checkpoint for cancelled session {}",
|
|
1223
|
+
session_key,
|
|
1224
|
+
exc_info=True,
|
|
1225
|
+
)
|
|
1226
|
+
raise
|
|
1227
|
+
except Exception:
|
|
1228
|
+
logger.exception("Error processing message for session {}", session_key)
|
|
1229
|
+
await self.bus.publish_outbound(OutboundMessage(
|
|
1230
|
+
channel=msg.channel, chat_id=msg.chat_id,
|
|
1231
|
+
content="Sorry, I encountered an error.",
|
|
1232
|
+
))
|
|
1233
|
+
finally:
|
|
1234
|
+
# Drain any messages still in the pending queue and re-publish
|
|
1235
|
+
# them to the bus so they are processed as fresh inbound messages
|
|
1236
|
+
# rather than silently lost.
|
|
1237
|
+
queue = self._pending_queues.pop(session_key, None)
|
|
1238
|
+
if queue is not None:
|
|
1239
|
+
leftover = 0
|
|
1240
|
+
while True:
|
|
1241
|
+
try:
|
|
1242
|
+
item = queue.get_nowait()
|
|
1243
|
+
except asyncio.QueueEmpty:
|
|
1244
|
+
break
|
|
1245
|
+
await self.bus.publish_inbound(item)
|
|
1246
|
+
leftover += 1
|
|
1247
|
+
if leftover:
|
|
1248
|
+
logger.info(
|
|
1249
|
+
"Re-published {} leftover message(s) to bus for session {}",
|
|
1250
|
+
leftover, session_key,
|
|
1251
|
+
)
|
|
1252
|
+
|
|
1253
|
+
async def close_mcp(self) -> None:
|
|
1254
|
+
"""Drain pending background archives, then close MCP connections."""
|
|
1255
|
+
if self._background_tasks:
|
|
1256
|
+
await asyncio.gather(*self._background_tasks, return_exceptions=True)
|
|
1257
|
+
self._background_tasks.clear()
|
|
1258
|
+
for name, stack in self._mcp_stacks.items():
|
|
1259
|
+
try:
|
|
1260
|
+
await stack.aclose()
|
|
1261
|
+
except (RuntimeError, BaseExceptionGroup):
|
|
1262
|
+
logger.debug("MCP server '{}' cleanup error (can be ignored)", name)
|
|
1263
|
+
self._mcp_stacks.clear()
|
|
1264
|
+
|
|
1265
|
+
def _schedule_background(self, coro) -> None:
|
|
1266
|
+
"""Schedule a coroutine as a tracked background task (drained on shutdown)."""
|
|
1267
|
+
task = asyncio.create_task(coro)
|
|
1268
|
+
self._background_tasks.append(task)
|
|
1269
|
+
task.add_done_callback(self._background_tasks.remove)
|
|
1270
|
+
|
|
1271
|
+
def stop(self) -> None:
|
|
1272
|
+
"""Stop the agent loop."""
|
|
1273
|
+
self._running = False
|
|
1274
|
+
logger.info("Agent loop stopping")
|
|
1275
|
+
|
|
1276
|
+
async def _process_system_message(
|
|
1277
|
+
self,
|
|
1278
|
+
msg: InboundMessage,
|
|
1279
|
+
runtime: WorkspaceRuntime,
|
|
1280
|
+
session_key: str | None = None,
|
|
1281
|
+
on_progress: Callable[..., Awaitable[None]] | None = None,
|
|
1282
|
+
on_stream: Callable[[str], Awaitable[None]] | None = None,
|
|
1283
|
+
on_stream_end: Callable[..., Awaitable[None]] | None = None,
|
|
1284
|
+
pending_queue: asyncio.Queue | None = None,
|
|
1285
|
+
) -> OutboundMessage | None:
|
|
1286
|
+
"""Process a system inbound message (e.g. subagent announce)."""
|
|
1287
|
+
channel, chat_id = (
|
|
1288
|
+
msg.chat_id.split(":", 1) if ":" in msg.chat_id else ("cli", msg.chat_id)
|
|
1289
|
+
)
|
|
1290
|
+
logger.info("Processing system message from {}", msg.sender_id)
|
|
1291
|
+
key = msg.session_key_override or f"{channel}:{chat_id}"
|
|
1292
|
+
session = runtime.sessions.get_or_create(key)
|
|
1293
|
+
if self._restore_runtime_checkpoint(session):
|
|
1294
|
+
runtime.sessions.save(session)
|
|
1295
|
+
if self._restore_pending_user_turn(session):
|
|
1296
|
+
runtime.sessions.save(session)
|
|
1297
|
+
|
|
1298
|
+
session, pending = runtime.auto_compact.prepare_session(session, key)
|
|
1299
|
+
if pending:
|
|
1300
|
+
logger.info("Memory compact triggered for session {}", key)
|
|
1301
|
+
|
|
1302
|
+
await runtime.consolidator.maybe_consolidate_by_tokens(
|
|
1303
|
+
session,
|
|
1304
|
+
replay_max_messages=self._max_messages,
|
|
1305
|
+
)
|
|
1306
|
+
is_subagent = msg.sender_id == "subagent"
|
|
1307
|
+
if is_subagent and self._persist_subagent_followup(session, msg):
|
|
1308
|
+
logger.debug("Subagent result persisted for session {}", key)
|
|
1309
|
+
runtime.sessions.save(session)
|
|
1310
|
+
self._set_tool_context(
|
|
1311
|
+
channel, chat_id, msg.metadata.get("message_id"),
|
|
1312
|
+
msg.metadata, session_key=key,
|
|
1313
|
+
)
|
|
1314
|
+
_hist_kwargs: dict[str, Any] = {
|
|
1315
|
+
"max_messages": self._max_messages,
|
|
1316
|
+
"max_tokens": self._replay_token_budget(),
|
|
1317
|
+
"include_timestamps": True,
|
|
1318
|
+
}
|
|
1319
|
+
history = session.get_history(**_hist_kwargs)
|
|
1320
|
+
current_role = "assistant" if is_subagent else "user"
|
|
1321
|
+
|
|
1322
|
+
messages = runtime.context.build_messages(
|
|
1323
|
+
history=history,
|
|
1324
|
+
current_message="" if is_subagent else msg.content,
|
|
1325
|
+
channel=channel,
|
|
1326
|
+
chat_id=chat_id,
|
|
1327
|
+
current_role=current_role,
|
|
1328
|
+
sender_id=msg.sender_id,
|
|
1329
|
+
session_summary=pending,
|
|
1330
|
+
)
|
|
1331
|
+
final_content, _, all_msgs, stop_reason, _ = await self._run_agent_loop(
|
|
1332
|
+
messages, runtime=runtime, session=session, channel=channel, chat_id=chat_id,
|
|
1333
|
+
message_id=msg.metadata.get("message_id"),
|
|
1334
|
+
metadata=msg.metadata,
|
|
1335
|
+
session_key=key,
|
|
1336
|
+
pending_queue=pending_queue,
|
|
1337
|
+
)
|
|
1338
|
+
self._save_turn(session, all_msgs, 1 + len(history))
|
|
1339
|
+
session.enforce_file_cap(on_archive=runtime.context.memory.raw_archive)
|
|
1340
|
+
self._clear_runtime_checkpoint(session)
|
|
1341
|
+
runtime.sessions.save(session)
|
|
1342
|
+
self._schedule_background(
|
|
1343
|
+
runtime.consolidator.maybe_consolidate_by_tokens(
|
|
1344
|
+
session,
|
|
1345
|
+
replay_max_messages=self._max_messages,
|
|
1346
|
+
)
|
|
1347
|
+
)
|
|
1348
|
+
content = final_content or "Background task completed."
|
|
1349
|
+
outbound_metadata: dict[str, Any] = {}
|
|
1350
|
+
if origin_message_id := msg.metadata.get("origin_message_id"):
|
|
1351
|
+
outbound_metadata["origin_message_id"] = origin_message_id
|
|
1352
|
+
return OutboundMessage(
|
|
1353
|
+
channel=channel,
|
|
1354
|
+
chat_id=chat_id,
|
|
1355
|
+
content=content,
|
|
1356
|
+
metadata=outbound_metadata,
|
|
1357
|
+
)
|
|
1358
|
+
|
|
1359
|
+
async def _process_message(
|
|
1360
|
+
self,
|
|
1361
|
+
msg: InboundMessage,
|
|
1362
|
+
runtime: WorkspaceRuntime | None = None,
|
|
1363
|
+
session_key: str | None = None,
|
|
1364
|
+
on_progress: Callable[..., Awaitable[None]] | None = None,
|
|
1365
|
+
on_stream: Callable[[str], Awaitable[None]] | None = None,
|
|
1366
|
+
on_stream_end: Callable[..., Awaitable[None]] | None = None,
|
|
1367
|
+
pending_queue: asyncio.Queue | None = None,
|
|
1368
|
+
) -> OutboundMessage | None:
|
|
1369
|
+
"""Process a single inbound message under its channel profile's tool policy."""
|
|
1370
|
+
from viola.agent.profiles import active_tool_policy, profile_for_session_key
|
|
1371
|
+
|
|
1372
|
+
profile = profile_for_session_key(session_key or msg.session_key)
|
|
1373
|
+
policy = self.tool_policies.get(profile) if profile else None
|
|
1374
|
+
token = active_tool_policy.set(policy)
|
|
1375
|
+
try:
|
|
1376
|
+
return await self._process_message_in_profile(
|
|
1377
|
+
msg,
|
|
1378
|
+
runtime=runtime,
|
|
1379
|
+
session_key=session_key,
|
|
1380
|
+
on_progress=on_progress,
|
|
1381
|
+
on_stream=on_stream,
|
|
1382
|
+
on_stream_end=on_stream_end,
|
|
1383
|
+
pending_queue=pending_queue,
|
|
1384
|
+
)
|
|
1385
|
+
finally:
|
|
1386
|
+
active_tool_policy.reset(token)
|
|
1387
|
+
|
|
1388
|
+
async def _process_message_in_profile(
|
|
1389
|
+
self,
|
|
1390
|
+
msg: InboundMessage,
|
|
1391
|
+
runtime: WorkspaceRuntime | None = None,
|
|
1392
|
+
session_key: str | None = None,
|
|
1393
|
+
on_progress: Callable[..., Awaitable[None]] | None = None,
|
|
1394
|
+
on_stream: Callable[[str], Awaitable[None]] | None = None,
|
|
1395
|
+
on_stream_end: Callable[..., Awaitable[None]] | None = None,
|
|
1396
|
+
pending_queue: asyncio.Queue | None = None,
|
|
1397
|
+
) -> OutboundMessage | None:
|
|
1398
|
+
"""Process a single inbound message and return the response."""
|
|
1399
|
+
self._refresh_provider_snapshot()
|
|
1400
|
+
runtime = runtime or self.runtime_for_session_key(session_key or msg.session_key)
|
|
1401
|
+
|
|
1402
|
+
if msg.channel == "system":
|
|
1403
|
+
return await self._process_system_message(
|
|
1404
|
+
msg,
|
|
1405
|
+
runtime=runtime,
|
|
1406
|
+
session_key=session_key,
|
|
1407
|
+
on_progress=on_progress,
|
|
1408
|
+
on_stream=on_stream,
|
|
1409
|
+
on_stream_end=on_stream_end,
|
|
1410
|
+
pending_queue=pending_queue,
|
|
1411
|
+
)
|
|
1412
|
+
|
|
1413
|
+
key = session_key or msg.session_key
|
|
1414
|
+
ctx = TurnContext(
|
|
1415
|
+
msg=msg,
|
|
1416
|
+
session=None,
|
|
1417
|
+
session_key=key,
|
|
1418
|
+
state=TurnState.RESTORE,
|
|
1419
|
+
turn_id=f"{key}:{time.time_ns()}",
|
|
1420
|
+
runtime=runtime,
|
|
1421
|
+
on_progress=on_progress,
|
|
1422
|
+
on_stream=on_stream,
|
|
1423
|
+
on_stream_end=on_stream_end,
|
|
1424
|
+
pending_queue=pending_queue,
|
|
1425
|
+
)
|
|
1426
|
+
|
|
1427
|
+
while ctx.state is not TurnState.DONE:
|
|
1428
|
+
handler_name = f"_state_{ctx.state.name.lower()}"
|
|
1429
|
+
handler = getattr(self, handler_name, None)
|
|
1430
|
+
if handler is None:
|
|
1431
|
+
raise RuntimeError(f"Missing state handler for {ctx.state}")
|
|
1432
|
+
|
|
1433
|
+
t0 = time.perf_counter()
|
|
1434
|
+
try:
|
|
1435
|
+
event = await handler(ctx)
|
|
1436
|
+
except Exception:
|
|
1437
|
+
duration = (time.perf_counter() - t0) * 1000
|
|
1438
|
+
ctx.trace.append(
|
|
1439
|
+
StateTraceEntry(
|
|
1440
|
+
state=ctx.state,
|
|
1441
|
+
started_at=t0,
|
|
1442
|
+
duration_ms=duration,
|
|
1443
|
+
event="",
|
|
1444
|
+
error="exception",
|
|
1445
|
+
)
|
|
1446
|
+
)
|
|
1447
|
+
raise
|
|
1448
|
+
|
|
1449
|
+
duration = (time.perf_counter() - t0) * 1000
|
|
1450
|
+
ctx.trace.append(
|
|
1451
|
+
StateTraceEntry(
|
|
1452
|
+
state=ctx.state,
|
|
1453
|
+
started_at=t0,
|
|
1454
|
+
duration_ms=duration,
|
|
1455
|
+
event=event,
|
|
1456
|
+
)
|
|
1457
|
+
)
|
|
1458
|
+
logger.debug(
|
|
1459
|
+
"[turn {}] State {} took {:.1f}ms -> event {}",
|
|
1460
|
+
ctx.turn_id,
|
|
1461
|
+
ctx.state.name,
|
|
1462
|
+
duration,
|
|
1463
|
+
event,
|
|
1464
|
+
)
|
|
1465
|
+
|
|
1466
|
+
next_state = self._TRANSITIONS.get((ctx.state, event))
|
|
1467
|
+
if next_state is None:
|
|
1468
|
+
raise RuntimeError(
|
|
1469
|
+
f"[turn {ctx.turn_id}] No transition from {ctx.state} "
|
|
1470
|
+
f"on event {event!r}"
|
|
1471
|
+
)
|
|
1472
|
+
ctx.state = next_state
|
|
1473
|
+
|
|
1474
|
+
logger.debug(
|
|
1475
|
+
"[turn {}] Turn completed after {} states",
|
|
1476
|
+
ctx.turn_id,
|
|
1477
|
+
len(ctx.trace),
|
|
1478
|
+
)
|
|
1479
|
+
return ctx.outbound
|
|
1480
|
+
|
|
1481
|
+
def _assemble_outbound(
|
|
1482
|
+
self,
|
|
1483
|
+
msg: InboundMessage,
|
|
1484
|
+
final_content: str,
|
|
1485
|
+
all_msgs: list[dict[str, Any]],
|
|
1486
|
+
stop_reason: str,
|
|
1487
|
+
had_injections: bool,
|
|
1488
|
+
generated_media: list[str],
|
|
1489
|
+
on_stream: Callable[[str], Awaitable[None]] | None,
|
|
1490
|
+
*,
|
|
1491
|
+
save_skip: int,
|
|
1492
|
+
usage: dict[str, int] | None = None,
|
|
1493
|
+
stt_usage: dict[str, dict[str, int]] | None = None,
|
|
1494
|
+
) -> OutboundMessage | None:
|
|
1495
|
+
"""Assemble the final outbound message from turn results."""
|
|
1496
|
+
# MessageTool suppression
|
|
1497
|
+
if (mt := self.tools.get("message")) and isinstance(mt, MessageTool) and mt._sent_in_turn:
|
|
1498
|
+
if not had_injections or stop_reason == "empty_final_response":
|
|
1499
|
+
return None
|
|
1500
|
+
|
|
1501
|
+
preview = final_content[:120] + "..." if len(final_content) > 120 else final_content
|
|
1502
|
+
logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview)
|
|
1503
|
+
|
|
1504
|
+
meta = dict(msg.metadata or {})
|
|
1505
|
+
if on_stream is not None and stop_reason not in {"error", "tool_error"}:
|
|
1506
|
+
meta["_streamed"] = True
|
|
1507
|
+
# Match _save_turn: only count tool calls introduced in this turn, not replayed history.
|
|
1508
|
+
turn_msgs = all_msgs[save_skip:] if save_skip > 0 else all_msgs
|
|
1509
|
+
tool_events = self._summarize_turn_tool_events(turn_msgs)
|
|
1510
|
+
if tool_events:
|
|
1511
|
+
meta["_tool_events"] = tool_events
|
|
1512
|
+
if usage:
|
|
1513
|
+
meta["_usage"] = dict(usage)
|
|
1514
|
+
if stt_usage:
|
|
1515
|
+
meta["_stt_usage"] = {model: dict(u) for model, u in stt_usage.items()}
|
|
1516
|
+
|
|
1517
|
+
return OutboundMessage(
|
|
1518
|
+
channel=msg.channel,
|
|
1519
|
+
chat_id=msg.chat_id,
|
|
1520
|
+
content=final_content,
|
|
1521
|
+
media=generated_media,
|
|
1522
|
+
metadata=meta,
|
|
1523
|
+
)
|
|
1524
|
+
|
|
1525
|
+
@staticmethod
|
|
1526
|
+
def _summarize_turn_tool_events(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
1527
|
+
"""Summarize tool calls in ``messages`` (caller should pass this-turn slice only)."""
|
|
1528
|
+
declared: dict[str, str] = {}
|
|
1529
|
+
status_by_call_id: dict[str, str] = {}
|
|
1530
|
+
content_by_call_id: dict[str, str] = {}
|
|
1531
|
+
|
|
1532
|
+
for message in messages:
|
|
1533
|
+
if not isinstance(message, dict):
|
|
1534
|
+
continue
|
|
1535
|
+
if message.get("role") == "assistant":
|
|
1536
|
+
for tool_call in message.get("tool_calls") or []:
|
|
1537
|
+
if not isinstance(tool_call, dict):
|
|
1538
|
+
continue
|
|
1539
|
+
call_id = str(tool_call.get("id") or "").strip()
|
|
1540
|
+
if not call_id:
|
|
1541
|
+
continue
|
|
1542
|
+
fn = tool_call.get("function")
|
|
1543
|
+
name = ""
|
|
1544
|
+
if isinstance(fn, dict):
|
|
1545
|
+
name = str(fn.get("name") or "").strip()
|
|
1546
|
+
if not name:
|
|
1547
|
+
name = "tool"
|
|
1548
|
+
declared[call_id] = name
|
|
1549
|
+
continue
|
|
1550
|
+
|
|
1551
|
+
if message.get("role") == "tool":
|
|
1552
|
+
call_id = str(message.get("tool_call_id") or "").strip()
|
|
1553
|
+
if not call_id:
|
|
1554
|
+
continue
|
|
1555
|
+
raw_content = str(message.get("content") or "").strip()
|
|
1556
|
+
content = raw_content.lower()
|
|
1557
|
+
status = "ok"
|
|
1558
|
+
if content.startswith("error") or content.startswith("{\"status\":\"error\""):
|
|
1559
|
+
status = "error"
|
|
1560
|
+
status_by_call_id[call_id] = status
|
|
1561
|
+
content_by_call_id[call_id] = raw_content
|
|
1562
|
+
|
|
1563
|
+
events: list[dict[str, Any]] = []
|
|
1564
|
+
for call_id, name in declared.items():
|
|
1565
|
+
event: dict[str, Any] = {
|
|
1566
|
+
"call_id": call_id,
|
|
1567
|
+
"name": name,
|
|
1568
|
+
"status": status_by_call_id.get(call_id, "ok"),
|
|
1569
|
+
}
|
|
1570
|
+
events.append(event)
|
|
1571
|
+
return events
|
|
1572
|
+
|
|
1573
|
+
async def _transcribe_audio_file(
|
|
1574
|
+
self,
|
|
1575
|
+
file_path: str | Path,
|
|
1576
|
+
stt_usage: dict[str, dict[str, int]] | None = None,
|
|
1577
|
+
) -> str:
|
|
1578
|
+
"""Transcribe one audio file using the configured STT backend.
|
|
1579
|
+
|
|
1580
|
+
When *stt_usage* is given, the call's token usage is added to it under
|
|
1581
|
+
the transcription model so the turn can be billed for it.
|
|
1582
|
+
"""
|
|
1583
|
+
from viola.providers.transcription import create_transcription_provider
|
|
1584
|
+
|
|
1585
|
+
try:
|
|
1586
|
+
provider = create_transcription_provider(
|
|
1587
|
+
self.transcription_provider,
|
|
1588
|
+
api_key=self.transcription_api_key or None,
|
|
1589
|
+
api_base=self.transcription_api_base or None,
|
|
1590
|
+
language=self.transcription_language or None,
|
|
1591
|
+
model=self.transcription_model,
|
|
1592
|
+
)
|
|
1593
|
+
if provider is None:
|
|
1594
|
+
return ""
|
|
1595
|
+
text = await provider.transcribe(file_path)
|
|
1596
|
+
usage = getattr(provider, "last_usage", None) or {}
|
|
1597
|
+
model = str(getattr(provider, "model", "") or "")
|
|
1598
|
+
if stt_usage is not None and usage and model:
|
|
1599
|
+
bucket = stt_usage.setdefault(model, {})
|
|
1600
|
+
for key, value in usage.items():
|
|
1601
|
+
bucket[key] = bucket.get(key, 0) + int(value)
|
|
1602
|
+
if usage and model:
|
|
1603
|
+
from viola import billing
|
|
1604
|
+
|
|
1605
|
+
await billing.record_llm_usage(usage=dict(usage), model=model)
|
|
1606
|
+
return text
|
|
1607
|
+
except Exception:
|
|
1608
|
+
logger.exception("Audio transcription failed for {}", file_path)
|
|
1609
|
+
return ""
|
|
1610
|
+
|
|
1611
|
+
async def _inline_audio_transcriptions(
|
|
1612
|
+
self,
|
|
1613
|
+
content: str,
|
|
1614
|
+
media: list[str],
|
|
1615
|
+
stt_usage: dict[str, dict[str, int]] | None = None,
|
|
1616
|
+
) -> tuple[str, list[str]]:
|
|
1617
|
+
"""Run Whisper on audio attachments and remove them from *media* when consumed."""
|
|
1618
|
+
if not media:
|
|
1619
|
+
return content, media
|
|
1620
|
+
extras: list[str] = []
|
|
1621
|
+
kept: list[str] = []
|
|
1622
|
+
for path_str in media:
|
|
1623
|
+
if not is_audio_media(path_str):
|
|
1624
|
+
kept.append(path_str)
|
|
1625
|
+
continue
|
|
1626
|
+
if not self.transcription_api_key:
|
|
1627
|
+
kept.append(path_str)
|
|
1628
|
+
continue
|
|
1629
|
+
text = await self._transcribe_audio_file(path_str, stt_usage)
|
|
1630
|
+
label = Path(path_str).name
|
|
1631
|
+
if text:
|
|
1632
|
+
extras.append(f"[transcription: {text}]")
|
|
1633
|
+
logger.info("Transcribed audio {}: {}...", label, text[:50])
|
|
1634
|
+
else:
|
|
1635
|
+
extras.append(f"[Audio: {label} — transcription failed or returned empty.]")
|
|
1636
|
+
|
|
1637
|
+
if extras:
|
|
1638
|
+
joined = "\n".join(extras)
|
|
1639
|
+
content = f"{content}\n\n{joined}" if content.strip() else joined
|
|
1640
|
+
return content, kept
|
|
1641
|
+
|
|
1642
|
+
async def _prepare_inbound_media(
|
|
1643
|
+
self,
|
|
1644
|
+
content: str,
|
|
1645
|
+
media: list[str],
|
|
1646
|
+
stt_usage: dict[str, dict[str, int]] | None = None,
|
|
1647
|
+
) -> tuple[str, list[str]]:
|
|
1648
|
+
"""Transcribe audio, then extract document text and retain only image paths."""
|
|
1649
|
+
content, media = await self._inline_audio_transcriptions(content, media, stt_usage)
|
|
1650
|
+
return extract_documents(content, media)
|
|
1651
|
+
|
|
1652
|
+
async def _state_restore(self, ctx: TurnContext) -> TurnState:
|
|
1653
|
+
"""Restore checkpoint / pending user turn; extract documents."""
|
|
1654
|
+
msg = ctx.msg
|
|
1655
|
+
|
|
1656
|
+
if msg.media:
|
|
1657
|
+
new_content, image_only = await self._prepare_inbound_media(
|
|
1658
|
+
msg.content, list(msg.media), ctx.stt_usage,
|
|
1659
|
+
)
|
|
1660
|
+
ctx.msg = dataclasses.replace(msg, content=new_content, media=image_only)
|
|
1661
|
+
msg = ctx.msg
|
|
1662
|
+
|
|
1663
|
+
preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content
|
|
1664
|
+
logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview)
|
|
1665
|
+
|
|
1666
|
+
# Session is already fetched by the caller (_process_message) but
|
|
1667
|
+
# ensure it exists in case this handler is invoked independently.
|
|
1668
|
+
if ctx.session is None:
|
|
1669
|
+
ctx.session = ctx.runtime.sessions.get_or_create(ctx.session_key)
|
|
1670
|
+
|
|
1671
|
+
if self._restore_runtime_checkpoint(ctx.session):
|
|
1672
|
+
ctx.runtime.sessions.save(ctx.session)
|
|
1673
|
+
if self._restore_pending_user_turn(ctx.session):
|
|
1674
|
+
ctx.runtime.sessions.save(ctx.session)
|
|
1675
|
+
|
|
1676
|
+
return "ok"
|
|
1677
|
+
|
|
1678
|
+
async def _state_compact(self, ctx: TurnContext) -> str:
|
|
1679
|
+
ctx.session, pending = ctx.runtime.auto_compact.prepare_session(ctx.session, ctx.session_key)
|
|
1680
|
+
ctx.pending_summary = pending
|
|
1681
|
+
return "ok"
|
|
1682
|
+
|
|
1683
|
+
async def _state_command(self, ctx: TurnContext) -> str:
|
|
1684
|
+
raw = ctx.msg.content.strip()
|
|
1685
|
+
# For API/webhook channels, messages arrive with metadata headers such as
|
|
1686
|
+
# "[User profile name: ...]\n[Sender mobile_digits: ...]\n/new".
|
|
1687
|
+
# The exact-match router can't see the command buried in the body, so fall
|
|
1688
|
+
# back to the last non-bracket line when the full content isn't matched.
|
|
1689
|
+
effective_raw = raw
|
|
1690
|
+
if not self.commands.is_dispatchable_command(raw) and not self.commands.is_priority(raw):
|
|
1691
|
+
body_line = _extract_body_line(raw)
|
|
1692
|
+
if body_line and body_line != raw:
|
|
1693
|
+
effective_raw = body_line
|
|
1694
|
+
cmd_ctx = CommandContext(
|
|
1695
|
+
msg=ctx.msg, session=ctx.session, key=ctx.session_key, raw=effective_raw, loop=self
|
|
1696
|
+
)
|
|
1697
|
+
result = await self.commands.dispatch(cmd_ctx)
|
|
1698
|
+
if result is not None:
|
|
1699
|
+
ctx.outbound = result
|
|
1700
|
+
# Shortcut commands skip BUILD and SAVE, so we must persist the
|
|
1701
|
+
# turn here so WebUI history hydration after _turn_end sees the
|
|
1702
|
+
# message. Mark messages with _command so get_history can filter
|
|
1703
|
+
# them out of LLM context. New-session commands are excluded
|
|
1704
|
+
# because they intentionally clear the session.
|
|
1705
|
+
if not is_new_session_command(effective_raw):
|
|
1706
|
+
ctx.user_persisted_early = self._persist_user_message_early(
|
|
1707
|
+
ctx.msg, ctx.session, _command=True
|
|
1708
|
+
)
|
|
1709
|
+
ctx.session.add_message(
|
|
1710
|
+
"assistant", result.content, _command=True
|
|
1711
|
+
)
|
|
1712
|
+
ctx.runtime.sessions.save(ctx.session)
|
|
1713
|
+
self._clear_pending_user_turn(ctx.session)
|
|
1714
|
+
return "shortcut"
|
|
1715
|
+
return "dispatch"
|
|
1716
|
+
|
|
1717
|
+
async def _state_build(self, ctx: TurnContext) -> str:
|
|
1718
|
+
await ctx.runtime.consolidator.maybe_consolidate_by_tokens(
|
|
1719
|
+
ctx.session,
|
|
1720
|
+
replay_max_messages=self._max_messages,
|
|
1721
|
+
)
|
|
1722
|
+
self._set_tool_context(
|
|
1723
|
+
ctx.msg.channel,
|
|
1724
|
+
ctx.msg.chat_id,
|
|
1725
|
+
ctx.msg.metadata.get("message_id"),
|
|
1726
|
+
ctx.msg.metadata,
|
|
1727
|
+
session_key=ctx.session_key,
|
|
1728
|
+
)
|
|
1729
|
+
if message_tool := self.tools.get("message"):
|
|
1730
|
+
if isinstance(message_tool, MessageTool):
|
|
1731
|
+
message_tool.start_turn()
|
|
1732
|
+
|
|
1733
|
+
_hist_kwargs: dict[str, Any] = {
|
|
1734
|
+
"max_messages": self._max_messages,
|
|
1735
|
+
"max_tokens": self._replay_token_budget(),
|
|
1736
|
+
"include_timestamps": True,
|
|
1737
|
+
}
|
|
1738
|
+
ctx.history = ctx.session.get_history(**_hist_kwargs)
|
|
1739
|
+
|
|
1740
|
+
ctx.initial_messages = self._build_initial_messages(
|
|
1741
|
+
ctx.msg, ctx.session, ctx.history, ctx.pending_summary, ctx.runtime.context
|
|
1742
|
+
)
|
|
1743
|
+
ctx.user_persisted_early = self._persist_user_message_early(
|
|
1744
|
+
ctx.msg, ctx.session
|
|
1745
|
+
)
|
|
1746
|
+
|
|
1747
|
+
if ctx.on_progress is None:
|
|
1748
|
+
ctx.on_progress = await self._build_bus_progress_callback(ctx.msg)
|
|
1749
|
+
if ctx.on_retry_wait is None:
|
|
1750
|
+
ctx.on_retry_wait = await self._build_retry_wait_callback(ctx.msg)
|
|
1751
|
+
|
|
1752
|
+
return "ok"
|
|
1753
|
+
|
|
1754
|
+
async def _state_run(self, ctx: TurnContext) -> str:
|
|
1755
|
+
result = await self._run_agent_loop(
|
|
1756
|
+
ctx.initial_messages,
|
|
1757
|
+
runtime=ctx.runtime,
|
|
1758
|
+
on_progress=ctx.on_progress,
|
|
1759
|
+
on_stream=ctx.on_stream,
|
|
1760
|
+
on_stream_end=ctx.on_stream_end,
|
|
1761
|
+
on_retry_wait=ctx.on_retry_wait,
|
|
1762
|
+
session=ctx.session,
|
|
1763
|
+
channel=ctx.msg.channel,
|
|
1764
|
+
chat_id=ctx.msg.chat_id,
|
|
1765
|
+
message_id=ctx.msg.metadata.get("message_id"),
|
|
1766
|
+
metadata=ctx.msg.metadata,
|
|
1767
|
+
session_key=ctx.session_key,
|
|
1768
|
+
pending_queue=ctx.pending_queue,
|
|
1769
|
+
)
|
|
1770
|
+
final_content, tools_used, all_msgs, stop_reason, had_injections = result
|
|
1771
|
+
# Read before the next await so a concurrent turn cannot overwrite it.
|
|
1772
|
+
ctx.usage = dict(self._last_usage)
|
|
1773
|
+
ctx.final_content = final_content
|
|
1774
|
+
ctx.tools_used = tools_used
|
|
1775
|
+
ctx.all_messages = all_msgs
|
|
1776
|
+
ctx.stop_reason = stop_reason
|
|
1777
|
+
ctx.had_injections = had_injections
|
|
1778
|
+
return "ok"
|
|
1779
|
+
|
|
1780
|
+
async def _state_save(self, ctx: TurnContext) -> str:
|
|
1781
|
+
if ctx.final_content is None or not ctx.final_content.strip():
|
|
1782
|
+
ctx.final_content = EMPTY_FINAL_RESPONSE_MESSAGE
|
|
1783
|
+
|
|
1784
|
+
ctx.save_skip = 1 + len(ctx.history) + (1 if ctx.user_persisted_early else 0)
|
|
1785
|
+
skip_msgs = ctx.all_messages[ctx.save_skip:]
|
|
1786
|
+
ctx.generated_media = generated_attachment_paths_from_messages(
|
|
1787
|
+
skip_msgs,
|
|
1788
|
+
workspace=ctx.runtime.workspace,
|
|
1789
|
+
final_content=ctx.final_content,
|
|
1790
|
+
)
|
|
1791
|
+
last_msg = ctx.all_messages[-1] if ctx.all_messages else None
|
|
1792
|
+
if ctx.generated_media and last_msg and last_msg.get("role") == "assistant":
|
|
1793
|
+
existing_media = last_msg.get("media")
|
|
1794
|
+
media = existing_media if isinstance(existing_media, list) else []
|
|
1795
|
+
last_msg["media"] = list(dict.fromkeys([*media, *ctx.generated_media]))
|
|
1796
|
+
|
|
1797
|
+
self._save_turn(ctx.session, ctx.all_messages, ctx.save_skip)
|
|
1798
|
+
ctx.session.enforce_file_cap(on_archive=ctx.runtime.context.memory.raw_archive)
|
|
1799
|
+
self._clear_pending_user_turn(ctx.session)
|
|
1800
|
+
self._clear_runtime_checkpoint(ctx.session)
|
|
1801
|
+
ctx.runtime.sessions.save(ctx.session)
|
|
1802
|
+
self._schedule_background(
|
|
1803
|
+
ctx.runtime.consolidator.maybe_consolidate_by_tokens(
|
|
1804
|
+
ctx.session,
|
|
1805
|
+
replay_max_messages=self._max_messages,
|
|
1806
|
+
)
|
|
1807
|
+
)
|
|
1808
|
+
return "ok"
|
|
1809
|
+
|
|
1810
|
+
async def _state_respond(self, ctx: TurnContext) -> str:
|
|
1811
|
+
ctx.outbound = self._assemble_outbound(
|
|
1812
|
+
ctx.msg,
|
|
1813
|
+
ctx.final_content,
|
|
1814
|
+
ctx.all_messages,
|
|
1815
|
+
ctx.stop_reason,
|
|
1816
|
+
ctx.had_injections,
|
|
1817
|
+
ctx.generated_media,
|
|
1818
|
+
ctx.on_stream,
|
|
1819
|
+
save_skip=ctx.save_skip,
|
|
1820
|
+
usage=ctx.usage,
|
|
1821
|
+
stt_usage=ctx.stt_usage,
|
|
1822
|
+
)
|
|
1823
|
+
return "ok"
|
|
1824
|
+
|
|
1825
|
+
def _sanitize_persisted_blocks(
|
|
1826
|
+
self,
|
|
1827
|
+
content: list[dict[str, Any]],
|
|
1828
|
+
*,
|
|
1829
|
+
should_truncate_text: bool = False,
|
|
1830
|
+
drop_runtime: bool = False,
|
|
1831
|
+
) -> list[dict[str, Any]]:
|
|
1832
|
+
"""Strip volatile multimodal payloads before writing session history."""
|
|
1833
|
+
filtered: list[dict[str, Any]] = []
|
|
1834
|
+
for block in content:
|
|
1835
|
+
if not isinstance(block, dict):
|
|
1836
|
+
filtered.append(block)
|
|
1837
|
+
continue
|
|
1838
|
+
|
|
1839
|
+
if (
|
|
1840
|
+
drop_runtime
|
|
1841
|
+
and block.get("type") == "text"
|
|
1842
|
+
and isinstance(block.get("text"), str)
|
|
1843
|
+
and block["text"].startswith(ContextBuilder._RUNTIME_CONTEXT_TAG)
|
|
1844
|
+
):
|
|
1845
|
+
continue
|
|
1846
|
+
|
|
1847
|
+
if block.get("type") == "image_url" and block.get("image_url", {}).get(
|
|
1848
|
+
"url", ""
|
|
1849
|
+
).startswith("data:image/"):
|
|
1850
|
+
path = (block.get("_meta") or {}).get("path", "")
|
|
1851
|
+
filtered.append({"type": "text", "text": image_placeholder_text(path)})
|
|
1852
|
+
continue
|
|
1853
|
+
|
|
1854
|
+
if block.get("type") == "text" and isinstance(block.get("text"), str):
|
|
1855
|
+
text = block["text"]
|
|
1856
|
+
if should_truncate_text and len(text) > self.max_tool_result_chars:
|
|
1857
|
+
text = truncate_text_fn(text, self.max_tool_result_chars)
|
|
1858
|
+
filtered.append({**block, "text": text})
|
|
1859
|
+
continue
|
|
1860
|
+
|
|
1861
|
+
filtered.append(block)
|
|
1862
|
+
|
|
1863
|
+
return filtered
|
|
1864
|
+
|
|
1865
|
+
def _save_turn(self, session: Session, messages: list[dict], skip: int) -> None:
|
|
1866
|
+
"""Save new-turn messages into session, truncating large tool results."""
|
|
1867
|
+
from datetime import datetime
|
|
1868
|
+
|
|
1869
|
+
for m in messages[skip:]:
|
|
1870
|
+
entry = dict(m)
|
|
1871
|
+
role, content = entry.get("role"), entry.get("content")
|
|
1872
|
+
if role == "assistant" and not content and not entry.get("tool_calls"):
|
|
1873
|
+
continue # skip empty assistant messages — they poison session context
|
|
1874
|
+
if role == "tool":
|
|
1875
|
+
if isinstance(content, str) and len(content) > self.max_tool_result_chars:
|
|
1876
|
+
entry["content"] = truncate_text_fn(content, self.max_tool_result_chars)
|
|
1877
|
+
elif isinstance(content, list):
|
|
1878
|
+
filtered = self._sanitize_persisted_blocks(content, should_truncate_text=True)
|
|
1879
|
+
if not filtered:
|
|
1880
|
+
continue
|
|
1881
|
+
entry["content"] = filtered
|
|
1882
|
+
elif role == "user":
|
|
1883
|
+
if isinstance(content, str) and content.startswith(ContextBuilder._RUNTIME_CONTEXT_TAG):
|
|
1884
|
+
# Strip the entire runtime-context block (including any session summary).
|
|
1885
|
+
# The block is bounded by _RUNTIME_CONTEXT_TAG and _RUNTIME_CONTEXT_END.
|
|
1886
|
+
end_marker = ContextBuilder._RUNTIME_CONTEXT_END
|
|
1887
|
+
end_pos = content.find(end_marker)
|
|
1888
|
+
if end_pos >= 0:
|
|
1889
|
+
after = content[end_pos + len(end_marker):].strip()
|
|
1890
|
+
if after:
|
|
1891
|
+
entry["content"] = after
|
|
1892
|
+
else:
|
|
1893
|
+
continue
|
|
1894
|
+
else:
|
|
1895
|
+
# Fallback: no end marker found, strip the tag prefix
|
|
1896
|
+
after_tag = content[len(ContextBuilder._RUNTIME_CONTEXT_TAG):].strip()
|
|
1897
|
+
if after_tag.strip():
|
|
1898
|
+
entry["content"] = after_tag
|
|
1899
|
+
else:
|
|
1900
|
+
continue
|
|
1901
|
+
if isinstance(content, list):
|
|
1902
|
+
filtered = self._sanitize_persisted_blocks(content, drop_runtime=True)
|
|
1903
|
+
if not filtered:
|
|
1904
|
+
continue
|
|
1905
|
+
entry["content"] = filtered
|
|
1906
|
+
entry.setdefault("timestamp", datetime.now().isoformat())
|
|
1907
|
+
session.messages.append(entry)
|
|
1908
|
+
session.updated_at = datetime.now()
|
|
1909
|
+
|
|
1910
|
+
def _persist_subagent_followup(self, session: Session, msg: InboundMessage) -> bool:
|
|
1911
|
+
"""Persist subagent follow-ups before prompt assembly so history stays durable.
|
|
1912
|
+
|
|
1913
|
+
Returns True if a new entry was appended; False if the follow-up was
|
|
1914
|
+
deduped (same ``subagent_task_id`` already in session) or carries no
|
|
1915
|
+
content worth persisting.
|
|
1916
|
+
"""
|
|
1917
|
+
if not msg.content:
|
|
1918
|
+
return False
|
|
1919
|
+
task_id = msg.metadata.get("subagent_task_id") if isinstance(msg.metadata, dict) else None
|
|
1920
|
+
if task_id and any(
|
|
1921
|
+
m.get("injected_event") == "subagent_result" and m.get("subagent_task_id") == task_id
|
|
1922
|
+
for m in session.messages
|
|
1923
|
+
):
|
|
1924
|
+
return False
|
|
1925
|
+
session.add_message(
|
|
1926
|
+
"assistant",
|
|
1927
|
+
msg.content,
|
|
1928
|
+
sender_id=msg.sender_id,
|
|
1929
|
+
injected_event="subagent_result",
|
|
1930
|
+
subagent_task_id=task_id,
|
|
1931
|
+
)
|
|
1932
|
+
return True
|
|
1933
|
+
|
|
1934
|
+
def _set_runtime_checkpoint(self, session: Session, payload: dict[str, Any]) -> None:
|
|
1935
|
+
"""Persist the latest in-flight turn state into session metadata."""
|
|
1936
|
+
session.metadata[self._RUNTIME_CHECKPOINT_KEY] = payload
|
|
1937
|
+
self.runtime_for_session_key(session.key).sessions.save(session)
|
|
1938
|
+
|
|
1939
|
+
def _mark_pending_user_turn(self, session: Session) -> None:
|
|
1940
|
+
session.metadata[self._PENDING_USER_TURN_KEY] = True
|
|
1941
|
+
|
|
1942
|
+
def _clear_pending_user_turn(self, session: Session) -> None:
|
|
1943
|
+
session.metadata.pop(self._PENDING_USER_TURN_KEY, None)
|
|
1944
|
+
|
|
1945
|
+
def _clear_runtime_checkpoint(self, session: Session) -> None:
|
|
1946
|
+
if self._RUNTIME_CHECKPOINT_KEY in session.metadata:
|
|
1947
|
+
session.metadata.pop(self._RUNTIME_CHECKPOINT_KEY, None)
|
|
1948
|
+
|
|
1949
|
+
@staticmethod
|
|
1950
|
+
def _checkpoint_message_key(message: dict[str, Any]) -> tuple[Any, ...]:
|
|
1951
|
+
return (
|
|
1952
|
+
message.get("role"),
|
|
1953
|
+
message.get("content"),
|
|
1954
|
+
message.get("tool_call_id"),
|
|
1955
|
+
message.get("name"),
|
|
1956
|
+
message.get("tool_calls"),
|
|
1957
|
+
message.get("reasoning_content"),
|
|
1958
|
+
message.get("thinking_blocks"),
|
|
1959
|
+
)
|
|
1960
|
+
|
|
1961
|
+
def _restore_runtime_checkpoint(self, session: Session) -> bool:
|
|
1962
|
+
"""Materialize an unfinished turn into session history before a new request."""
|
|
1963
|
+
from datetime import datetime
|
|
1964
|
+
|
|
1965
|
+
checkpoint = session.metadata.get(self._RUNTIME_CHECKPOINT_KEY)
|
|
1966
|
+
if not isinstance(checkpoint, dict):
|
|
1967
|
+
return False
|
|
1968
|
+
|
|
1969
|
+
assistant_message = checkpoint.get("assistant_message")
|
|
1970
|
+
completed_tool_results = checkpoint.get("completed_tool_results") or []
|
|
1971
|
+
pending_tool_calls = checkpoint.get("pending_tool_calls") or []
|
|
1972
|
+
|
|
1973
|
+
restored_messages: list[dict[str, Any]] = []
|
|
1974
|
+
if isinstance(assistant_message, dict):
|
|
1975
|
+
restored = dict(assistant_message)
|
|
1976
|
+
restored.setdefault("timestamp", datetime.now().isoformat())
|
|
1977
|
+
restored_messages.append(restored)
|
|
1978
|
+
for message in completed_tool_results:
|
|
1979
|
+
if isinstance(message, dict):
|
|
1980
|
+
restored = dict(message)
|
|
1981
|
+
restored.setdefault("timestamp", datetime.now().isoformat())
|
|
1982
|
+
restored_messages.append(restored)
|
|
1983
|
+
for tool_call in pending_tool_calls:
|
|
1984
|
+
if not isinstance(tool_call, dict):
|
|
1985
|
+
continue
|
|
1986
|
+
tool_id = tool_call.get("id")
|
|
1987
|
+
name = ((tool_call.get("function") or {}).get("name")) or "tool"
|
|
1988
|
+
restored_messages.append(
|
|
1989
|
+
{
|
|
1990
|
+
"role": "tool",
|
|
1991
|
+
"tool_call_id": tool_id,
|
|
1992
|
+
"name": name,
|
|
1993
|
+
"content": "Error: Task interrupted before this tool finished.",
|
|
1994
|
+
"timestamp": datetime.now().isoformat(),
|
|
1995
|
+
}
|
|
1996
|
+
)
|
|
1997
|
+
|
|
1998
|
+
overlap = 0
|
|
1999
|
+
max_overlap = min(len(session.messages), len(restored_messages))
|
|
2000
|
+
for size in range(max_overlap, 0, -1):
|
|
2001
|
+
existing = session.messages[-size:]
|
|
2002
|
+
restored = restored_messages[:size]
|
|
2003
|
+
if all(
|
|
2004
|
+
self._checkpoint_message_key(left) == self._checkpoint_message_key(right)
|
|
2005
|
+
for left, right in zip(existing, restored)
|
|
2006
|
+
):
|
|
2007
|
+
overlap = size
|
|
2008
|
+
break
|
|
2009
|
+
session.messages.extend(restored_messages[overlap:])
|
|
2010
|
+
|
|
2011
|
+
self._clear_pending_user_turn(session)
|
|
2012
|
+
self._clear_runtime_checkpoint(session)
|
|
2013
|
+
return True
|
|
2014
|
+
|
|
2015
|
+
def _restore_pending_user_turn(self, session: Session) -> bool:
|
|
2016
|
+
"""Close a turn that only persisted the user message before crashing."""
|
|
2017
|
+
from datetime import datetime
|
|
2018
|
+
|
|
2019
|
+
if not session.metadata.get(self._PENDING_USER_TURN_KEY):
|
|
2020
|
+
return False
|
|
2021
|
+
|
|
2022
|
+
if session.messages and session.messages[-1].get("role") == "user":
|
|
2023
|
+
session.messages.append(
|
|
2024
|
+
{
|
|
2025
|
+
"role": "assistant",
|
|
2026
|
+
"content": "Error: Task interrupted before a response was generated.",
|
|
2027
|
+
"timestamp": datetime.now().isoformat(),
|
|
2028
|
+
}
|
|
2029
|
+
)
|
|
2030
|
+
session.updated_at = datetime.now()
|
|
2031
|
+
|
|
2032
|
+
self._clear_pending_user_turn(session)
|
|
2033
|
+
return True
|
|
2034
|
+
|
|
2035
|
+
async def process_direct(
|
|
2036
|
+
self,
|
|
2037
|
+
content: str,
|
|
2038
|
+
session_key: str = "cli:direct",
|
|
2039
|
+
channel: str = "cli",
|
|
2040
|
+
chat_id: str = "direct",
|
|
2041
|
+
media: list[str] | None = None,
|
|
2042
|
+
on_progress: Callable[..., Awaitable[None]] | None = None,
|
|
2043
|
+
on_stream: Callable[[str], Awaitable[None]] | None = None,
|
|
2044
|
+
on_stream_end: Callable[..., Awaitable[None]] | None = None,
|
|
2045
|
+
) -> OutboundMessage | None:
|
|
2046
|
+
"""Process a message directly and return the outbound payload."""
|
|
2047
|
+
await self._connect_mcp()
|
|
2048
|
+
msg = InboundMessage(
|
|
2049
|
+
channel=channel, sender_id="user", chat_id=chat_id,
|
|
2050
|
+
content=content, media=media or [],
|
|
2051
|
+
)
|
|
2052
|
+
return await self._process_message(
|
|
2053
|
+
msg,
|
|
2054
|
+
session_key=session_key,
|
|
2055
|
+
on_progress=on_progress,
|
|
2056
|
+
on_stream=on_stream,
|
|
2057
|
+
on_stream_end=on_stream_end,
|
|
2058
|
+
)
|