WeKnora/internal/agent/engine.go

1122 lines
43 KiB
Go
Raw Normal View History

package agent
import (
"context"
"encoding/base64"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/agent/compaction"
"github.com/Tencent/WeKnora/internal/agent/skills"
agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/common"
appconfig "github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/modelcontext"
"github.com/Tencent/WeKnora/internal/models/chat"
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549) * feat(sandbox): resolve workspace paths through WorkspaceLayout Keep remote sessions on the /workspace contract, while file, shell, and artifact code follow the session layout instead of hardcoded paths. * fix(sandbox): fail closed on host layout lookup and restore the shell blacklist Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots, and skip collection when the output tree is missing or equals the project root. * fix(sandbox): close leftover fail-open holes in the layout path Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots. * fix(sandbox): satisfy golangci-lint on the layout helpers Wrap new copy and test lines to 120 columns, and add the exported comments revive requires. * fix(sandbox): gofmt the read_file layout copy wrap * feat(sandbox): add host as an OS-enforced backend type Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B. * feat(session): persist Lite host workspace directory Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects. * feat(localsandbox): adapt the host OS sandbox to session interfaces File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace. * feat(sandbox): run unpinned Lite sessions on the host backend Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed. * feat(desktop): pick and persist host project directories The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it. * fix(sandbox): fail closed on Lite host layout lookup misses Unpinned host sessions were described as /workspace when pin read or sandbox resolve failed. Prompts and attachment staging now share the same fallback so Lite never pretends the remote tree exists. * fix(frontend): keep settings.sandbox.host in sync with the backend keys TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI. * fix(lint): satisfy golangci-lint on the host sandbox wiring Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 11:35:03 +00:00
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
)
// langfuseQueryPreview caps the query length we ship as the agent.execute
// span input — long quoted-context queries can be many KB of prose.
const langfuseQueryPreview = 2000
refactor(agent): rebuild multi-turn history from DB, drop llmcontext layer The Agent ran a parallel context cache (Redis/in-memory) on top of the messages table to feed multi-turn history into the LLM. That dual-write caused subtle drift (e.g. compression diverging from DB, system-prompt swaps lost on restart) and required a separate ClearContext path on session/IM clear. Make the messages table the single source of truth: - Add service.LoadAgentHistory: rebuilds chat.Message history per turn from the persisted messages, expanding AgentSteps into proper OpenAI assistant_with_tool_calls + tool messages and replaying the canonical final answer (with <think> blocks stripped). final_answer tool calls are filtered to avoid duplicating the trailing answer. - Make AgentEngine stateless across turns: drop ContextManager / sessionID cache plumbing from the engine, agent service, and CreateAgentEngine signature. The engine only uses sessionID for logging/event emission. - Wire AgentQA to load history from DB on demand using HistoryTurns (default 5) when MultiTurnEnabled, otherwise run with empty history. - Delete the llmcontext package (ContextManager interface, Redis/memory storage, factory) and the SessionService.ClearContext API path; IM /clear and session message clear no longer need to invalidate cache. Behavior preserved: KnowledgeQA-mode replay is unchanged (turns with empty AgentSteps just produce the single canonical assistant message), and Agent-mode turns now consistently see prior tool calls and results.
2026-05-12 03:43:35 +00:00
// AgentEngine is the core engine for running ReAct agents.
//
// History persistence note: the engine is stateless across turns. Conversation
// history is rebuilt from the DB once per turn by the caller
// (see service.LoadAgentHistory) and passed into Execute as llmContext. The
// engine therefore does not maintain its own cache, system-prompt store, or
// cross-turn buffer.
type AgentEngine struct {
config *types.AgentConfig
toolRegistry *agenttools.ToolRegistry
chatModel chat.Chat
eventBus *event.EventBus
knowledgeBasesInfo []*KnowledgeBaseInfo // Detailed knowledge base information for prompt
selectedDocs []*SelectedDocumentInfo // User-selected documents (via @ mention)
pinnedMCPServices []*PinnedMCPServiceInfo // User @mentioned MCP services for this turn
pinnedSkills []*PinnedSkillInfo // User @mentioned skills for this turn
fix(agent): search bound knowledge bases before answering, and pass suggested-question origins (#3400) * fix(agent): search bound knowledge bases before answering, and pass suggested-question origins A user picked the suggested question "为什么在比较图形时需要谨慎处理?" and the agent answered in round 1 with no tool call, claiming it had searched the knowledge base and found nothing, then explained misleading statistical charts. The question had been generated from "Corners Don't Look Like That: Regarding Screenspace Ambient Occlusion" in a bound base, where "comparing graphs" means SSAO falloff curves. Two things let that happen: the grounding prompt said "Stable general explanations need no lookup", and nothing told the agent where the question came from - the base in question had no profile, only two recent titles in the directory, and the click sent the text alone. Prompt - With knowledge tools available, search bound bases before answering a question about a topic, even one that reads like general knowledge; directory profiles and recent titles cannot prove a base lacks it. - The general-explanation exemption applies only without bound bases. - Say you searched or found nothing only when a search tool ran. Question origin - Suggested questions from FAQ/document chunks also return knowledge_id. - Picking one on the home or chat page sends question_origin {knowledge_base_id, knowledge_id} with that question only. - The service keeps the origin only when its base is inside the turn's resolved scope and the document belongs to that base; it never changes the scope (unlike knowledge_base_ids, which narrows it). - The engine renders it in runtime_context as <question_origin> with the base and document handles and a note to search it before answering. * fix(agent): keep question origins across file/tag scopes and bind them to the send Review follow-up for the suggested-question origin. - Scope check: the origin was kept only when its base was in the resolved KB list, which is empty for file-only and tag-only scopes even though their bases are searched. It is now checked against SearchTargets after they are built; the document is kept only when a target for that base covers it (unfiltered base, or a document scope listing it). resolveQuestionOriginInfo re-checks SearchTargets, looks up the name of a base that is not in kbInfos, and the renderer omits an unknown name. - Frontend: the origin travelled through module-level "pending" state, so a send that returned early (agent not ready, upload in progress, steering) left it behind and a second pick overwrote it. It now rides with the one send: triggerSend(text, options) -> createSession -> send-msg -> sendMsg / changeFirstQuery. - RetrieveKBOnlyWhenMentioned: suggestions are still generated from the agent's bases, but picking one retrieved nothing. The origin now selects its base, as an @mention would, when the agent may read it. - API sync: question_origin in docs/api/chat.md and swagger; QuestionOrigin on the Go SDK's KnowledgeQARequest/AgentQARequest and knowledge_id on SuggestedQuestion.
2026-09-18 09:00:47 +00:00
questionOrigin *QuestionOriginInfo // Source of a picked suggested question, if any
sessionID string // Session ID for logging and event emission
systemPromptTemplate string // System prompt template (optional, uses default if empty)
memoryPrompt string // Long-term memory envelope appended to the system prompt
skillsManager *skills.Manager // Skills manager for Progressive Disclosure (optional)
appConfig *appconfig.Config // Application config for prompt template resolution (optional)
imageDescriber ImageDescriberFunc // VLM function for describing images in tool results (optional)
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
tokenEstimator *agenttoken.Estimator // Token estimator for context window management, calibrated
rawEstimator *agenttoken.Estimator // Same tokenizer at scale 1, for measuring the calibration
compactor *compaction.Compactor // Summarizes older history to fit the context window (nil = disabled)
lastUsage types.TokenUsage // Token usage from the most recent LLM call
lastSentMsgCount int // Number of messages sent in the most recent LLM call
// overflowRecovered records that this turn already spent its one
// compact-and-retry on a context overflow. A second attempt would mean
// history size was never the problem, and looping on it burns the round
// budget without changing anything.
overflowRecovered bool
// compactionExhaustedAt is the message count at which compaction last
// reported it could free nothing. Below that count the answer has not
// changed, so there is no reason to spend another summarization call.
compactionExhaustedAt int
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
// checkpointSink, when set, persists compactions that end on a stored
// turn so later turns start from them. Nil keeps compaction turn-local.
checkpointSink types.ContextCheckpointSink
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
// calibration learns the provider's tokens per estimated token from
// consecutive requests (see calibrateEstimator).
calibration tokenCalibration
// contextRewrites counts compactions and tool-result trims. Either one
// changes messages an earlier request already sent, so the next request
// cannot be compared with that one for calibration.
contextRewrites int
modelContext *modelcontext.Registry // single request-local boundary for every model handle
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// steerSink, when set, lets users append messages into the running turn.
// Drained at every round boundary; nil disables mid-run injection.
steerSink types.SteerSink
allowSteerOverrun bool // one extra ReAct round after a loop-end inject past MaxIterations
steerOverruns int // how many times this turn has already used the extra round
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549) * feat(sandbox): resolve workspace paths through WorkspaceLayout Keep remote sessions on the /workspace contract, while file, shell, and artifact code follow the session layout instead of hardcoded paths. * fix(sandbox): fail closed on host layout lookup and restore the shell blacklist Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots, and skip collection when the output tree is missing or equals the project root. * fix(sandbox): close leftover fail-open holes in the layout path Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots. * fix(sandbox): satisfy golangci-lint on the layout helpers Wrap new copy and test lines to 120 columns, and add the exported comments revive requires. * fix(sandbox): gofmt the read_file layout copy wrap * feat(sandbox): add host as an OS-enforced backend type Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B. * feat(session): persist Lite host workspace directory Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects. * feat(localsandbox): adapt the host OS sandbox to session interfaces File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace. * feat(sandbox): run unpinned Lite sessions on the host backend Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed. * feat(desktop): pick and persist host project directories The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it. * fix(sandbox): fail closed on Lite host layout lookup misses Unpinned host sessions were described as /workspace when pin read or sandbox resolve failed. Prompts and attachment staging now share the same fallback so Lite never pretends the remote tree exists. * fix(frontend): keep settings.sandbox.host in sync with the backend keys TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI. * fix(lint): satisfy golangci-lint on the host sandbox wiring Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 11:35:03 +00:00
workspaceLayout sandbox.WorkspaceLayout
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// maxSteerOverruns caps loop-end injects past MaxIterations. One extra round
// lets a last-moment nudge revise the answer; further injects stay queued for
// a follow-up turn instead of stretching the same run indefinitely.
const maxSteerOverruns = 1
// ImageDescriberFunc generates a text description of an image.
// Signature matches vlm.VLM.Predict so it can be injected without importing the vlm package.
type ImageDescriberFunc func(ctx context.Context, imgBytes []byte, prompt string) (string, error)
// NewAgentEngine creates a new agent engine
func NewAgentEngine(
config *types.AgentConfig,
chatModel chat.Chat,
toolRegistry *agenttools.ToolRegistry,
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
selectedDocs []*SelectedDocumentInfo,
sessionID string,
systemPromptTemplate string,
) *AgentEngine {
if eventBus == nil {
eventBus = event.NewEventBus()
}
tokenEst, err := agenttoken.NewEstimator()
if err != nil {
return nil
}
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
// The previous turn's measured scale, so this turn's first compaction
// check is calibrated before it has a provider count of its own.
tokenEst.SetScale(config.ContextTokenScale)
engine := &AgentEngine{
config: config,
toolRegistry: toolRegistry,
chatModel: chatModel,
eventBus: eventBus,
knowledgeBasesInfo: knowledgeBasesInfo,
selectedDocs: selectedDocs,
sessionID: sessionID,
systemPromptTemplate: systemPromptTemplate,
tokenEstimator: tokenEst,
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
rawEstimator: tokenEst.Unscaled(),
modelContext: modelcontext.NewRegistry(config.CitationsEnabled()),
}
engine.compactor = compaction.New(chatModel, tokenEst, compaction.Settings{
Enabled: true,
MaxContextTokens: config.MaxContextTokens,
ReserveTokens: engine.contextReserveTokens(),
KeepRecentTokens: config.CompactionKeepRecentTokens,
MaxSummaryTokens: engine.getCompletionTokenBudget(),
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
StallTimeout: engine.getLLMStallTimeout(),
})
return engine
}
fix(agent): search bound knowledge bases before answering, and pass suggested-question origins (#3400) * fix(agent): search bound knowledge bases before answering, and pass suggested-question origins A user picked the suggested question "为什么在比较图形时需要谨慎处理?" and the agent answered in round 1 with no tool call, claiming it had searched the knowledge base and found nothing, then explained misleading statistical charts. The question had been generated from "Corners Don't Look Like That: Regarding Screenspace Ambient Occlusion" in a bound base, where "comparing graphs" means SSAO falloff curves. Two things let that happen: the grounding prompt said "Stable general explanations need no lookup", and nothing told the agent where the question came from - the base in question had no profile, only two recent titles in the directory, and the click sent the text alone. Prompt - With knowledge tools available, search bound bases before answering a question about a topic, even one that reads like general knowledge; directory profiles and recent titles cannot prove a base lacks it. - The general-explanation exemption applies only without bound bases. - Say you searched or found nothing only when a search tool ran. Question origin - Suggested questions from FAQ/document chunks also return knowledge_id. - Picking one on the home or chat page sends question_origin {knowledge_base_id, knowledge_id} with that question only. - The service keeps the origin only when its base is inside the turn's resolved scope and the document belongs to that base; it never changes the scope (unlike knowledge_base_ids, which narrows it). - The engine renders it in runtime_context as <question_origin> with the base and document handles and a note to search it before answering. * fix(agent): keep question origins across file/tag scopes and bind them to the send Review follow-up for the suggested-question origin. - Scope check: the origin was kept only when its base was in the resolved KB list, which is empty for file-only and tag-only scopes even though their bases are searched. It is now checked against SearchTargets after they are built; the document is kept only when a target for that base covers it (unfiltered base, or a document scope listing it). resolveQuestionOriginInfo re-checks SearchTargets, looks up the name of a base that is not in kbInfos, and the renderer omits an unknown name. - Frontend: the origin travelled through module-level "pending" state, so a send that returned early (agent not ready, upload in progress, steering) left it behind and a second pick overwrote it. It now rides with the one send: triggerSend(text, options) -> createSession -> send-msg -> sendMsg / changeFirstQuery. - RetrieveKBOnlyWhenMentioned: suggestions are still generated from the agent's bases, but picking one retrieved nothing. The origin now selects its base, as an @mention would, when the agent may read it. - API sync: question_origin in docs/api/chat.md and swagger; QuestionOrigin on the Go SDK's KnowledgeQARequest/AgentQARequest and knowledge_id on SuggestedQuestion.
2026-09-18 09:00:47 +00:00
// SetQuestionOrigin records the knowledge source of a suggested question the
// user picked for this turn; nil clears it.
func (e *AgentEngine) SetQuestionOrigin(origin *QuestionOriginInfo) {
e.questionOrigin = origin
}
// SetPinnedMentions sets per-turn @mention scope for MCP services and skills.
func (e *AgentEngine) SetPinnedMentions(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo) {
e.pinnedMCPServices = mcpServices
e.pinnedSkills = skills
}
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549) * feat(sandbox): resolve workspace paths through WorkspaceLayout Keep remote sessions on the /workspace contract, while file, shell, and artifact code follow the session layout instead of hardcoded paths. * fix(sandbox): fail closed on host layout lookup and restore the shell blacklist Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots, and skip collection when the output tree is missing or equals the project root. * fix(sandbox): close leftover fail-open holes in the layout path Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots. * fix(sandbox): satisfy golangci-lint on the layout helpers Wrap new copy and test lines to 120 columns, and add the exported comments revive requires. * fix(sandbox): gofmt the read_file layout copy wrap * feat(sandbox): add host as an OS-enforced backend type Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B. * feat(session): persist Lite host workspace directory Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects. * feat(localsandbox): adapt the host OS sandbox to session interfaces File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace. * feat(sandbox): run unpinned Lite sessions on the host backend Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed. * feat(desktop): pick and persist host project directories The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it. * fix(sandbox): fail closed on Lite host layout lookup misses Unpinned host sessions were described as /workspace when pin read or sandbox resolve failed. Prompts and attachment staging now share the same fallback so Lite never pretends the remote tree exists. * fix(frontend): keep settings.sandbox.host in sync with the backend keys TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI. * fix(lint): satisfy golangci-lint on the host sandbox wiring Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 11:35:03 +00:00
// SetWorkspaceLayout injects the session's real workspace into the system
// prompt. Host sessions must pass the user directory so the model does not
// keep listing /workspace.
func (e *AgentEngine) SetWorkspaceLayout(layout sandbox.WorkspaceLayout) {
if e == nil {
return
}
e.workspaceLayout = layout
}
func (e *AgentEngine) systemPromptOptions(ctx context.Context) *BuildSystemPromptOptions {
opts := &BuildSystemPromptOptions{
feat(browser): polish connection settings, open tasks in a new window, and streamline prompts (#3193) * feat(browser): enhance BrowserIcon component and update localization strings - Updated BrowserIcon component to accept dynamic width and height props. - Revised localization strings in English, Japanese, Korean, Russian, and Chinese for improved clarity and user guidance regarding browser connection and usage instructions. - Enhanced BrowserConnectionSettings view with better structure and user feedback elements. * Default BrowserSkill tasks to a separate window * refactor(prompts): streamline agent system prompts and context templates - Updated agent system prompts to enhance clarity and specificity in user interactions. - Revised context templates to better separate metadata and user requests, improving overall structure. - Adjusted fallback and intent prompts to ensure consistent language handling and response requirements. - Introduced new localization strings for browser search instructions across multiple languages. - Added tests for agent prompt serialization and hydration to ensure template integrity and functionality. * chore: wrap prompt strings to satisfy golangci-lint Keep the settings, separate-window, and prompt commits pushable together without rewriting their history. * fix(frontend): match agent editor save test to serialized payload The prompt-inheritance save path still closes after update; the test should assert that payload, not the unsanitized form object. * feat(browser): implement browser connection management and related tests - Introduced a new `browserConnection` store to manage the state of browser connections, including online status and device information. - Updated the `Input-field` component to handle browser connection states, enabling/disabling features based on the connection status. - Added tests for the `browserConnection` store to ensure correct behavior under various scenarios. - Enhanced the `Input-field` and `BrowserConnectionSettings` components to provide user feedback based on the browser connection state. - Adjusted related components and views to integrate the new browser connection logic, improving overall user experience. * fix(frontend): update model-save assertion for serialized agent payload The agent editor still persists the selected model ID via a spread of formData; the source test should match that payload, not the raw form.
2026-09-11 13:28:58 +00:00
Language: types.LanguageNameFromContext(ctx),
Config: e.appConfig,
SkillInstallMode: e.config.SkillInstallMode(),
MemoryPrompt: e.memoryPrompt,
ProtocolPrompt: e.modelContext.ProtocolPrompt(),
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549) * feat(sandbox): resolve workspace paths through WorkspaceLayout Keep remote sessions on the /workspace contract, while file, shell, and artifact code follow the session layout instead of hardcoded paths. * fix(sandbox): fail closed on host layout lookup and restore the shell blacklist Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots, and skip collection when the output tree is missing or equals the project root. * fix(sandbox): close leftover fail-open holes in the layout path Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots. * fix(sandbox): satisfy golangci-lint on the layout helpers Wrap new copy and test lines to 120 columns, and add the exported comments revive requires. * fix(sandbox): gofmt the read_file layout copy wrap * feat(sandbox): add host as an OS-enforced backend type Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B. * feat(session): persist Lite host workspace directory Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects. * feat(localsandbox): adapt the host OS sandbox to session interfaces File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace. * feat(sandbox): run unpinned Lite sessions on the host backend Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed. * feat(desktop): pick and persist host project directories The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it. * fix(sandbox): fail closed on Lite host layout lookup misses Unpinned host sessions were described as /workspace when pin read or sandbox resolve failed. Prompts and attachment staging now share the same fallback so Lite never pretends the remote tree exists. * fix(frontend): keep settings.sandbox.host in sync with the backend keys TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI. * fix(lint): satisfy golangci-lint on the host sandbox wiring Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 11:35:03 +00:00
WorkspaceLayout: e.workspaceLayout,
}
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
opts.SkillsMetadata = e.skillsManager.GetAllMetadata()
}
feat(sandbox) (#2301) * cubesandbox support * feat(agent): add sandbox shell execution, file management tools, and Artifacts collection/download system - Add three sandbox agent tools: shell_exec / sandbox_ls / sandbox_read - shell_exec: safely execute shell commands in session sandbox with timeout & output truncation - sandbox_ls: enumerate files under sandbox artifact output directory with recursive listing & pagination - sandbox_read: read sandbox file content with offset-based chunked reading - Add Artifacts system: - ArtifactCollector: real-time collection of sandbox tool output files, attached to messages - /api/artifacts/{session_id}/{message_id}/{filename}: download endpoint for frontend - ChatArtifactsDrawer.vue: frontend artifacts sidebar UI - DB migration 000066_message_artifacts: add artifacts column to messages table - Attachment sandbox staging: upload user attachments to session sandbox on QA request for skill tool access - Update Agent Prompts: add shell/sandbox tool usage constraints and safety rules - Extend Agent Observe: include agent steps in Langfuse observability tracing - Refactor Sandbox SessionManager: support session-scoped file listing, reading, and status queries - Frontend: render artifact events in AgentStreamDisplay, i18n updates for 4 locales - Add comprehensive tests: shell_exec_test, sandbox_read_test, artifact_collector_test, etc. * feat(agent):add remote sandbox client abstract & client errors * feat(sandbox): implement Redis binding store with distributed lifecycle lock; * feat(sandbox): add remote session lifecycle with ownership context Implement remoteSessionLifecycle to coordinate persistent remote sandboxes across multi-instance deployments. Supports Resolve (lazy provision, recovery, race-safe create) and Destroy with compare-delete semantics. Add ownership context isolation to decouple remote resource cleanup from request cancellation. * feat(sandbox): add CubeRemoteClient adapter for RemoteSandboxClient Implement CubeRemoteClient as a provider-neutral RemoteSandboxClient implementation. Error normalization, timeout mapping, and metadata support are fully integrated. SDK details remain private to the adapter. * refactor(sandbox): decouple SessionBoundManager from Cube Remove internal/sandbox/cube.go (CubeSandbox, sync.Map reaper). Add RemoteSandbox as provider-neutral Sandbox interface implementation. Rewrite SessionBoundManager to depend on RemoteSandboxClient + SessionSandboxBindingStore + SessionExistenceChecker, with all lifecycle ops delegated to remoteSessionLifecycle (Redis + distributed lock). Application-layer interfaces migrated to RemoteDirEntry/StatEntry with time.Time ModTime. Cleanup delegated to provider idle-timeout. * refactor(agent): enhance session capability handling in sandbox manager - Introduced sessionFileStore and sessionShellExecutor functions to centralize capability checks for session-scoped file and shell execution. - Updated agent service to register tools based on the presence of session filesystem capabilities, improving compatibility with various sandbox backends. - Refactored tests to validate behavior when session capabilities are absent, ensuring robust handling of different sandbox types. - Removed Cube-specific checks, promoting a more provider-neutral approach to session management. * refactor(sandbox): add E2B backend, modernize Cube adapter, and enable multi-instance Redis binding - Add e2b_remote_client.go (~850 lines) — full RemoteSandboxClient implementation covering lifecycle, execution, and filesystem ops (ListDir/Stat/MakeDir/Remove) - Wire E2B into NewManagerFromType and container/bootstrap path (buildE2BManager) - Dependency: matiasinsaurralde/go-e2b v0.1.0 - Cut ~1500 lines of legacy SDK wrapper (cube_client.go, cube_envd.go, cube_defaults.go) and replace with direct *cubesandbox.Client usage - Parse CubeProxy URL directly in adapter (parseProxyURL), removing the old hand-rolled envd transport layer - Pass lifecycle extra fields (onTimeout, autoResume) via SDK CreateOptions.Extra - Target Cube deployment v0.5.1 - Add RemoteNetworkPolicy to RemoteCreateRequest with AllowInternetAccess, AllowPublicTraffic, AllowOut/DenyOut — shared by Cube and E2B adapters - Both adapters default to permissive (internet+public on) for backwards compat - Add selectSessionBindingStore() — Redis-backed or in-memory, controlled by WEKNORA_SANDBOX_REDIS_NAMESPACE / WEKNORA_REDIS_NAMESPACE - Add repositorySessionExistenceChecker — checks session existence via DB (gorm.ErrRecordNotFound → not exists, transient errors → preserve binding) - newSandboxManager() now accepts redisClient + sessionRepo; deprecated hardcoded NewMemorySessionSandboxBindingStore() in production path - buildSessionCreateRequest default timeout action: Kill → Pause+AutoResume (Cube and E2B). Sessions survive brief idle periods; providers still handle TTL-based reaping. - buildSessionCreateRequest() and effectiveHTTPTimeout() parameterized by RemoteProvider (was hardcoded to Cube Config fields) - NewSessionBoundManager validates provider and delegates defaults to per-provider apply*Defaults helpers - Legacy SDK wrapper: cube_client.go, cube_envd.go, cube_defaults.go, cube_envd_test.go, cube_net_diag_test.go, cube_test.go (~2500 lines) - Unused helpers: DefaultManager.validateExecution, IsRemoteTerminal, IsRemoteUnsupported, IsRemoteTransient, ShouldPreserveRemoteBinding - Dead Config fields: CubeEnvdPort, CubeIdleTTL, AllowedCmds - Dead ExecuteResult method: GetOutput - Unused test: session_artifacts_integration_test.go - Preloaded skill: sandbox-test-python - Extract shared httpErrorKind() from per-adapter normalize functions - Add SupportsFilesystemEnumeration capability flag — gates SessionFileStore advertisement (E2B returns true post-reconnect, Cube always true) - Fix stale comments: Cube-only → remote backends, remove "tomorrow"/"future" - Bump session sandbox TTL defaults: 604800s → 300s (.env.example) - Update docs/agent-skills.md: full multi-instance deployment guide Total: 29 files, +1188 / -3721 * feat(agent): bind collected skill artifacts to owning message in resource registry When ArtifactCollector persists a skill-generated file it now registers a resource:// binding (owner_type=message, owner_id=assistantMessageID, relation=artifact) in addition to the messages.artifacts JSONB record. This mirrors how knowledge uploads and chat attachments bind their resources, so artifacts can be enumerated and garbage-collected through the resource registry instead of only via the message JSONB column. - ArtifactCollector: inject ResourceCatalog, add messageID to Collect/ maybePersist, and add best-effort bindArtifactResource (binding failures are logged, never drop the artifact; only resource:// refs are bound). - agent_stream_handler: pass assistantMessageID into Collect. - Renumber message_artifacts migration 000066 -> 000077 to resolve the version collision with existing migrations (upstream now uses 000075/000076). - Tests: update collector signatures and add coverage for the binding path and for graceful degradation when Bind fails. Note: binding applies to newly generated artifacts only; existing rows are not backfilled. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(sandbox): harden remote sandbox security and artifact collection Disable Cube local fallback so skill scripts never run on the host when the remote provider is unavailable. Require Redis for cube/e2b binding unless WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true for single-node dev. Collect artifacts with WithoutCancel so user stop does not drop files, reject shell_exec work_dir outside /workspace, and refuse session-scoped Execute when a local fallback would be engaged. * fix(ci): gofmt sandbox files and resolve artifact drawer type error Apply gofmt to PR-touched Go files and narrow ChatArtifactsDrawer props in AgentStreamDisplay so session-id is always a string. * fix(sandbox): adapt to upstream main after rebase Renumber the message_artifacts migration 000077 -> 000079: upstream now uses 000077_remove_wiki_log and 000078_chunk_editing_and_custom_metadata. Declare empty model-handle policies for shell_exec / list_sandbox_files / read_sandbox_file. Upstream added a coverage test requiring every UI-exposed tool to declare one; sandbox output is arbitrary skill-authored content, so it gets the same treatment as execute_skill_script. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(sandbox): replace single tenant sandbox config column with a configs table to support multi-sandbox config per tenant. * feat(sandbox): add sandbox config entity, cordon lease and session pin field * feat(sandbox): add sandbox config repository with tenant scoping and cordon lease * feat(sandbox): stamp sandbox config ID onto sandbox metadata * feat(sandbox): scope sandbox listing, release and reaping to a single config * feat(sandbox): resolve managers per config and refuse cordoned or missing configs * feat(sandbox): implement session pinning and config identity change detection - Add SessionSandboxPinner with read/pin/clear to bind session to config - Refactor four entry points (execute/attachment/artifact/destroy) to use pinned config - Add config_identity.go to detect identity changes by effective values (APIURL/APIKey/Domain/ProxyURL) - Add SandboxIdentityChanged with key-masked comparison to prevent false 409 conflicts - Fix artifact collection for default backend and destroy for legacy empty-pin sessions * feat(sandbox): add multi-tenant sandbox config management and HTTP APIs Service layer: - Add sandbox config business service supporting CRUD and inventory listing - For non-identity changes (e.g., template, TTL), save directly without locking or remote interactions - For identity changes (e.g., API key, endpoint), reject save if there are still live sandboxes under this config on the remote side, and return structured inventory details (sandbox count, affected sessions, related agents) for frontend prompting - Before deleting a config, check remote live sandboxes; if occupied, reject and prompt user to end sessions or create a new config - Identity comparison based on effective values to avoid normal saves being misidentified as credential rotation HTTP interfaces and routing: - Add REST endpoints for sandbox config (List/Create/Get/Update/Delete/Inventory) - Mask sensitive credentials (API key, etc.) in all read responses - Return 409 with structured inventory details on rejection scenarios - sandbox-check probing supports specifying an existing config_id directly - Remove old handler file, consolidate validation logic into service layer - DI wiring and route registration for all six endpoints * feat(sandbox): add sandbox_config_id field to allow agent referencing named sandbox config - Add SandboxConfigID field to CustomAgentConfig with omitempty; empty value falls back to global defaults - Validate config existence on create/update; return 400 if not found - Inject sandboxConfigService into CustomAgentHandler - Add unit tests covering field serialization and validation logic * feat(sandbox, agent): Migrate sandbox config to multi-config CRUD, support named backend selection and workspace scripts policy Migrate frontend API from legacy KV single-config to /sandbox-configs REST interface, supplement type definitions, detection methods and policy fields; refactor sandbox settings page to multi-config card grid, manage configs with cube/e2b tabs, add editor drawer for create/edit/delete, connection testing and occupancy hints, and add workspace scripts policy toggle; add sandbox config dropdown in Agent editor skill section, integrate config caching, and support selecting named config or falling back to deployment default. * feat(sandbox): Unify sandbox disable semantics and add tenant-level policy master switch - Backend: Unify interception in resolveTenantSandboxForConfig with priority: global disable > tenant disable > default fallback > named config; add deploymentSandboxDisabled() using env var to avoid mis‑impacting named E2B; update WorkspaceSandboxPolicy comment as master switch for entire workspace; add unit tests for various scenarios. - Frontend: Sync i18n copy: button text changed to "Disable/Enable sandbox execution"; confirmation dialog clarifies impact scope; success/failure messages aligned. - Semantic layering: WEKNORA_SANDBOX_MODE=disabled disables globally; tenant‑level "Disable sandbox execution" only disables for the current workspace. * feat(sandbox): Add SSRF protection, Agent binding to named configs, and reference query capabilities - Add outbound URL security guard to validate Cube/E2B API/Proxy addresses against SSRF (including cloud metadata), support allowing private endpoints via env var, link-local always blocked - Add named backend type validation, only cube/e2b can be stored as workspace named config - Add sandbox config ID field to Agent at runtime, resolve sandbox for attachments and execution based on Agent's selected named config instead of always global default - Add query to list Agents referencing a sandbox config ID, useful for deletion/changes to show dependents - Adapt artifact collector and other callers to fill missing resolve signature parameter * fix(sandbox): fix session teardown and config-update, add HTTP pool sharing for Cube Session teardown & deletion ordering - Move sandbox destroy (and pin `Clear`) before soft‑delete operations (`DeleteSession`/`BatchDeleteSessions`/`DeleteAllSessions`) to prevent remote sandbox leaks and stale pins. - Pass deployment‑wide `SessionBoundManager` as fallback into `resolveTenantSandboxForConfig` for sentinel pins (`"-"`) to support deployment‑default sessions. ## Config update edge cases - When identity fields change but old credentials cannot build a client or list config sandboxes, log a warning and proceed with the update instead of returning `sandbox_inventory_unverifiable`; live sandboxes still return 409. - UI: move `sandboxes_still_live` / `unverifiable` alerts to the top of the sandbox config drawer and auto‑scroll on save refusal and connectivity check results. Artifact collection for Cube skills - Pre‑create `/workspace/output` via envd with correct ownership/permissions for `DefaultSandboxExecUser` to ensure Cube skill artifacts are collected properly by `ArtifactCollector`. HTTP pool sharing for named Cube configs - Named sandbox configs rebuilt a client on every `Resolve`, causing fresh TCP connections to CubeAPI and the envd proxy on each request. - Add `CubeTransportPool` and `cubeSplitTransport`: - Control plane traffic reuses the same `SharedTransport` as E2B. - Data plane traffic uses a guarded transport cached per proxy host:port, preserving the sandbox `Host` header. - Wire the pool through the tenant resolver `buildClient`; keep SDK defaults for the deployment‑default manager and connectivity probes. * feat(sandbox): sandbox execution DefaultUser change from root to user * fix(multi-sandbox-config-per-tenant): align deployment config with tenant resolver and centralize defaults - Merge form overrides onto DeploymentConfig() via WEKNORA_SANDBOX_* env vars instead of DefaultConfig() hardcoded values, allowing empty fields to inherit from .env rather than Go constants - Centralize deployment baseline parsing in sandbox/defaults.go with DeploymentConfig, CubeConfigFromEnv, E2BConfigFromEnv - Delegate container startup to shared helpers to avoid drift - Propagate tenant env_vars through ResolveEffectiveConfig into buildSessionCreateRequest for both Cube and E2B session sandboxes * fix(multi-sandbox-config-per-tenant): fix some bugs frontend. * fix(sandbox): guard check-path dials, fix staging gate and shared-agent binding tenant Three defects found while reviewing the remote sandbox work: - The Cube connectivity probe and the deployment-default Cube/E2B managers built clients without a guarded transport, so an admin-supplied api_url or proxy_url could reach link-local addresses via DNS rebinding even though save-time validation passed. All three now dial through the same outbound guard the per-tenant resolver enforces. - Attachment staging was gated on the process-wide manager, so a workspace pointing an agent at a named Cube/E2B config while the deployment default stayed docker/local would run its tools remotely against an empty /workspace/input. The gate now resolves the manager the session actually runs on. - Session to sandbox bindings were keyed by the tenant in context, which a shared agent deliberately swaps for the agent owner's so models, KBs and named configs resolve in the sharing workspace. Session deletion only ever knows the session's own tenant, so teardown looked up a key nobody wrote and abandoned a paused MicroVM that keeps billing. The binding tenant is now carried separately and survives CloneContext. * chore(sandbox): renumber migrations above upstream and de-collide test stub Upstream main took 000079 (knowledge_folder_path) and 000080 (knowledge_base_auto_tag_config) while this branch was open, so the three sandbox migrations move to 000081-000083. golang-migrate requires unique, ordered versions, and the RAISE NOTICE labels move with the file names. Main also added a handler test declaring stubSessionService in the same package; the artifact download test's configurable variant is renamed rather than merged, since the two stubs answer GetSession differently. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-08-10 13:28:20 +00:00
if e.toolRegistry != nil {
opts.SelectedTools = e.toolRegistry.ListTools()
if _, err := e.toolRegistry.GetTool("local_browser"); err == nil {
metadata := make([]*skills.SkillMetadata, 0, len(opts.SkillsMetadata))
for _, item := range opts.SkillsMetadata {
if item != nil && item.Name != "browser" && item.Name != "browser-skill" {
metadata = append(metadata, item)
}
}
opts.SkillsMetadata = metadata
}
feat(sandbox) (#2301) * cubesandbox support * feat(agent): add sandbox shell execution, file management tools, and Artifacts collection/download system - Add three sandbox agent tools: shell_exec / sandbox_ls / sandbox_read - shell_exec: safely execute shell commands in session sandbox with timeout & output truncation - sandbox_ls: enumerate files under sandbox artifact output directory with recursive listing & pagination - sandbox_read: read sandbox file content with offset-based chunked reading - Add Artifacts system: - ArtifactCollector: real-time collection of sandbox tool output files, attached to messages - /api/artifacts/{session_id}/{message_id}/{filename}: download endpoint for frontend - ChatArtifactsDrawer.vue: frontend artifacts sidebar UI - DB migration 000066_message_artifacts: add artifacts column to messages table - Attachment sandbox staging: upload user attachments to session sandbox on QA request for skill tool access - Update Agent Prompts: add shell/sandbox tool usage constraints and safety rules - Extend Agent Observe: include agent steps in Langfuse observability tracing - Refactor Sandbox SessionManager: support session-scoped file listing, reading, and status queries - Frontend: render artifact events in AgentStreamDisplay, i18n updates for 4 locales - Add comprehensive tests: shell_exec_test, sandbox_read_test, artifact_collector_test, etc. * feat(agent):add remote sandbox client abstract & client errors * feat(sandbox): implement Redis binding store with distributed lifecycle lock; * feat(sandbox): add remote session lifecycle with ownership context Implement remoteSessionLifecycle to coordinate persistent remote sandboxes across multi-instance deployments. Supports Resolve (lazy provision, recovery, race-safe create) and Destroy with compare-delete semantics. Add ownership context isolation to decouple remote resource cleanup from request cancellation. * feat(sandbox): add CubeRemoteClient adapter for RemoteSandboxClient Implement CubeRemoteClient as a provider-neutral RemoteSandboxClient implementation. Error normalization, timeout mapping, and metadata support are fully integrated. SDK details remain private to the adapter. * refactor(sandbox): decouple SessionBoundManager from Cube Remove internal/sandbox/cube.go (CubeSandbox, sync.Map reaper). Add RemoteSandbox as provider-neutral Sandbox interface implementation. Rewrite SessionBoundManager to depend on RemoteSandboxClient + SessionSandboxBindingStore + SessionExistenceChecker, with all lifecycle ops delegated to remoteSessionLifecycle (Redis + distributed lock). Application-layer interfaces migrated to RemoteDirEntry/StatEntry with time.Time ModTime. Cleanup delegated to provider idle-timeout. * refactor(agent): enhance session capability handling in sandbox manager - Introduced sessionFileStore and sessionShellExecutor functions to centralize capability checks for session-scoped file and shell execution. - Updated agent service to register tools based on the presence of session filesystem capabilities, improving compatibility with various sandbox backends. - Refactored tests to validate behavior when session capabilities are absent, ensuring robust handling of different sandbox types. - Removed Cube-specific checks, promoting a more provider-neutral approach to session management. * refactor(sandbox): add E2B backend, modernize Cube adapter, and enable multi-instance Redis binding - Add e2b_remote_client.go (~850 lines) — full RemoteSandboxClient implementation covering lifecycle, execution, and filesystem ops (ListDir/Stat/MakeDir/Remove) - Wire E2B into NewManagerFromType and container/bootstrap path (buildE2BManager) - Dependency: matiasinsaurralde/go-e2b v0.1.0 - Cut ~1500 lines of legacy SDK wrapper (cube_client.go, cube_envd.go, cube_defaults.go) and replace with direct *cubesandbox.Client usage - Parse CubeProxy URL directly in adapter (parseProxyURL), removing the old hand-rolled envd transport layer - Pass lifecycle extra fields (onTimeout, autoResume) via SDK CreateOptions.Extra - Target Cube deployment v0.5.1 - Add RemoteNetworkPolicy to RemoteCreateRequest with AllowInternetAccess, AllowPublicTraffic, AllowOut/DenyOut — shared by Cube and E2B adapters - Both adapters default to permissive (internet+public on) for backwards compat - Add selectSessionBindingStore() — Redis-backed or in-memory, controlled by WEKNORA_SANDBOX_REDIS_NAMESPACE / WEKNORA_REDIS_NAMESPACE - Add repositorySessionExistenceChecker — checks session existence via DB (gorm.ErrRecordNotFound → not exists, transient errors → preserve binding) - newSandboxManager() now accepts redisClient + sessionRepo; deprecated hardcoded NewMemorySessionSandboxBindingStore() in production path - buildSessionCreateRequest default timeout action: Kill → Pause+AutoResume (Cube and E2B). Sessions survive brief idle periods; providers still handle TTL-based reaping. - buildSessionCreateRequest() and effectiveHTTPTimeout() parameterized by RemoteProvider (was hardcoded to Cube Config fields) - NewSessionBoundManager validates provider and delegates defaults to per-provider apply*Defaults helpers - Legacy SDK wrapper: cube_client.go, cube_envd.go, cube_defaults.go, cube_envd_test.go, cube_net_diag_test.go, cube_test.go (~2500 lines) - Unused helpers: DefaultManager.validateExecution, IsRemoteTerminal, IsRemoteUnsupported, IsRemoteTransient, ShouldPreserveRemoteBinding - Dead Config fields: CubeEnvdPort, CubeIdleTTL, AllowedCmds - Dead ExecuteResult method: GetOutput - Unused test: session_artifacts_integration_test.go - Preloaded skill: sandbox-test-python - Extract shared httpErrorKind() from per-adapter normalize functions - Add SupportsFilesystemEnumeration capability flag — gates SessionFileStore advertisement (E2B returns true post-reconnect, Cube always true) - Fix stale comments: Cube-only → remote backends, remove "tomorrow"/"future" - Bump session sandbox TTL defaults: 604800s → 300s (.env.example) - Update docs/agent-skills.md: full multi-instance deployment guide Total: 29 files, +1188 / -3721 * feat(agent): bind collected skill artifacts to owning message in resource registry When ArtifactCollector persists a skill-generated file it now registers a resource:// binding (owner_type=message, owner_id=assistantMessageID, relation=artifact) in addition to the messages.artifacts JSONB record. This mirrors how knowledge uploads and chat attachments bind their resources, so artifacts can be enumerated and garbage-collected through the resource registry instead of only via the message JSONB column. - ArtifactCollector: inject ResourceCatalog, add messageID to Collect/ maybePersist, and add best-effort bindArtifactResource (binding failures are logged, never drop the artifact; only resource:// refs are bound). - agent_stream_handler: pass assistantMessageID into Collect. - Renumber message_artifacts migration 000066 -> 000077 to resolve the version collision with existing migrations (upstream now uses 000075/000076). - Tests: update collector signatures and add coverage for the binding path and for graceful degradation when Bind fails. Note: binding applies to newly generated artifacts only; existing rows are not backfilled. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(sandbox): harden remote sandbox security and artifact collection Disable Cube local fallback so skill scripts never run on the host when the remote provider is unavailable. Require Redis for cube/e2b binding unless WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true for single-node dev. Collect artifacts with WithoutCancel so user stop does not drop files, reject shell_exec work_dir outside /workspace, and refuse session-scoped Execute when a local fallback would be engaged. * fix(ci): gofmt sandbox files and resolve artifact drawer type error Apply gofmt to PR-touched Go files and narrow ChatArtifactsDrawer props in AgentStreamDisplay so session-id is always a string. * fix(sandbox): adapt to upstream main after rebase Renumber the message_artifacts migration 000077 -> 000079: upstream now uses 000077_remove_wiki_log and 000078_chunk_editing_and_custom_metadata. Declare empty model-handle policies for shell_exec / list_sandbox_files / read_sandbox_file. Upstream added a coverage test requiring every UI-exposed tool to declare one; sandbox output is arbitrary skill-authored content, so it gets the same treatment as execute_skill_script. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(sandbox): replace single tenant sandbox config column with a configs table to support multi-sandbox config per tenant. * feat(sandbox): add sandbox config entity, cordon lease and session pin field * feat(sandbox): add sandbox config repository with tenant scoping and cordon lease * feat(sandbox): stamp sandbox config ID onto sandbox metadata * feat(sandbox): scope sandbox listing, release and reaping to a single config * feat(sandbox): resolve managers per config and refuse cordoned or missing configs * feat(sandbox): implement session pinning and config identity change detection - Add SessionSandboxPinner with read/pin/clear to bind session to config - Refactor four entry points (execute/attachment/artifact/destroy) to use pinned config - Add config_identity.go to detect identity changes by effective values (APIURL/APIKey/Domain/ProxyURL) - Add SandboxIdentityChanged with key-masked comparison to prevent false 409 conflicts - Fix artifact collection for default backend and destroy for legacy empty-pin sessions * feat(sandbox): add multi-tenant sandbox config management and HTTP APIs Service layer: - Add sandbox config business service supporting CRUD and inventory listing - For non-identity changes (e.g., template, TTL), save directly without locking or remote interactions - For identity changes (e.g., API key, endpoint), reject save if there are still live sandboxes under this config on the remote side, and return structured inventory details (sandbox count, affected sessions, related agents) for frontend prompting - Before deleting a config, check remote live sandboxes; if occupied, reject and prompt user to end sessions or create a new config - Identity comparison based on effective values to avoid normal saves being misidentified as credential rotation HTTP interfaces and routing: - Add REST endpoints for sandbox config (List/Create/Get/Update/Delete/Inventory) - Mask sensitive credentials (API key, etc.) in all read responses - Return 409 with structured inventory details on rejection scenarios - sandbox-check probing supports specifying an existing config_id directly - Remove old handler file, consolidate validation logic into service layer - DI wiring and route registration for all six endpoints * feat(sandbox): add sandbox_config_id field to allow agent referencing named sandbox config - Add SandboxConfigID field to CustomAgentConfig with omitempty; empty value falls back to global defaults - Validate config existence on create/update; return 400 if not found - Inject sandboxConfigService into CustomAgentHandler - Add unit tests covering field serialization and validation logic * feat(sandbox, agent): Migrate sandbox config to multi-config CRUD, support named backend selection and workspace scripts policy Migrate frontend API from legacy KV single-config to /sandbox-configs REST interface, supplement type definitions, detection methods and policy fields; refactor sandbox settings page to multi-config card grid, manage configs with cube/e2b tabs, add editor drawer for create/edit/delete, connection testing and occupancy hints, and add workspace scripts policy toggle; add sandbox config dropdown in Agent editor skill section, integrate config caching, and support selecting named config or falling back to deployment default. * feat(sandbox): Unify sandbox disable semantics and add tenant-level policy master switch - Backend: Unify interception in resolveTenantSandboxForConfig with priority: global disable > tenant disable > default fallback > named config; add deploymentSandboxDisabled() using env var to avoid mis‑impacting named E2B; update WorkspaceSandboxPolicy comment as master switch for entire workspace; add unit tests for various scenarios. - Frontend: Sync i18n copy: button text changed to "Disable/Enable sandbox execution"; confirmation dialog clarifies impact scope; success/failure messages aligned. - Semantic layering: WEKNORA_SANDBOX_MODE=disabled disables globally; tenant‑level "Disable sandbox execution" only disables for the current workspace. * feat(sandbox): Add SSRF protection, Agent binding to named configs, and reference query capabilities - Add outbound URL security guard to validate Cube/E2B API/Proxy addresses against SSRF (including cloud metadata), support allowing private endpoints via env var, link-local always blocked - Add named backend type validation, only cube/e2b can be stored as workspace named config - Add sandbox config ID field to Agent at runtime, resolve sandbox for attachments and execution based on Agent's selected named config instead of always global default - Add query to list Agents referencing a sandbox config ID, useful for deletion/changes to show dependents - Adapt artifact collector and other callers to fill missing resolve signature parameter * fix(sandbox): fix session teardown and config-update, add HTTP pool sharing for Cube Session teardown & deletion ordering - Move sandbox destroy (and pin `Clear`) before soft‑delete operations (`DeleteSession`/`BatchDeleteSessions`/`DeleteAllSessions`) to prevent remote sandbox leaks and stale pins. - Pass deployment‑wide `SessionBoundManager` as fallback into `resolveTenantSandboxForConfig` for sentinel pins (`"-"`) to support deployment‑default sessions. ## Config update edge cases - When identity fields change but old credentials cannot build a client or list config sandboxes, log a warning and proceed with the update instead of returning `sandbox_inventory_unverifiable`; live sandboxes still return 409. - UI: move `sandboxes_still_live` / `unverifiable` alerts to the top of the sandbox config drawer and auto‑scroll on save refusal and connectivity check results. Artifact collection for Cube skills - Pre‑create `/workspace/output` via envd with correct ownership/permissions for `DefaultSandboxExecUser` to ensure Cube skill artifacts are collected properly by `ArtifactCollector`. HTTP pool sharing for named Cube configs - Named sandbox configs rebuilt a client on every `Resolve`, causing fresh TCP connections to CubeAPI and the envd proxy on each request. - Add `CubeTransportPool` and `cubeSplitTransport`: - Control plane traffic reuses the same `SharedTransport` as E2B. - Data plane traffic uses a guarded transport cached per proxy host:port, preserving the sandbox `Host` header. - Wire the pool through the tenant resolver `buildClient`; keep SDK defaults for the deployment‑default manager and connectivity probes. * feat(sandbox): sandbox execution DefaultUser change from root to user * fix(multi-sandbox-config-per-tenant): align deployment config with tenant resolver and centralize defaults - Merge form overrides onto DeploymentConfig() via WEKNORA_SANDBOX_* env vars instead of DefaultConfig() hardcoded values, allowing empty fields to inherit from .env rather than Go constants - Centralize deployment baseline parsing in sandbox/defaults.go with DeploymentConfig, CubeConfigFromEnv, E2BConfigFromEnv - Delegate container startup to shared helpers to avoid drift - Propagate tenant env_vars through ResolveEffectiveConfig into buildSessionCreateRequest for both Cube and E2B session sandboxes * fix(multi-sandbox-config-per-tenant): fix some bugs frontend. * fix(sandbox): guard check-path dials, fix staging gate and shared-agent binding tenant Three defects found while reviewing the remote sandbox work: - The Cube connectivity probe and the deployment-default Cube/E2B managers built clients without a guarded transport, so an admin-supplied api_url or proxy_url could reach link-local addresses via DNS rebinding even though save-time validation passed. All three now dial through the same outbound guard the per-tenant resolver enforces. - Attachment staging was gated on the process-wide manager, so a workspace pointing an agent at a named Cube/E2B config while the deployment default stayed docker/local would run its tools remotely against an empty /workspace/input. The gate now resolves the manager the session actually runs on. - Session to sandbox bindings were keyed by the tenant in context, which a shared agent deliberately swaps for the agent owner's so models, KBs and named configs resolve in the sharing workspace. Session deletion only ever knows the session's own tenant, so teardown looked up a key nobody wrote and abandoned a paused MicroVM that keeps billing. The binding tenant is now carried separately and survives CloneContext. * chore(sandbox): renumber migrations above upstream and de-collide test stub Upstream main took 000079 (knowledge_folder_path) and 000080 (knowledge_base_auto_tag_config) while this branch was open, so the three sandbox migrations move to 000081-000083. golang-migrate requires unique, ordered versions, and the RAISE NOTICE labels move with the file names. Main also added a handler test declaring stubSessionService in the same package; the artifact download test's configurable variant is renamed rather than merged, since the two stubs answer GetSession differently. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-08-10 13:28:20 +00:00
_, err := e.toolRegistry.GetTool(agenttools.ToolShellExec)
opts.ShellExecEnabled = err == nil
}
return opts
}
func (e *AgentEngine) buildSystemPrompt(ctx context.Context) string {
feat(browser): polish connection settings, open tasks in a new window, and streamline prompts (#3193) * feat(browser): enhance BrowserIcon component and update localization strings - Updated BrowserIcon component to accept dynamic width and height props. - Revised localization strings in English, Japanese, Korean, Russian, and Chinese for improved clarity and user guidance regarding browser connection and usage instructions. - Enhanced BrowserConnectionSettings view with better structure and user feedback elements. * Default BrowserSkill tasks to a separate window * refactor(prompts): streamline agent system prompts and context templates - Updated agent system prompts to enhance clarity and specificity in user interactions. - Revised context templates to better separate metadata and user requests, improving overall structure. - Adjusted fallback and intent prompts to ensure consistent language handling and response requirements. - Introduced new localization strings for browser search instructions across multiple languages. - Added tests for agent prompt serialization and hydration to ensure template integrity and functionality. * chore: wrap prompt strings to satisfy golangci-lint Keep the settings, separate-window, and prompt commits pushable together without rewriting their history. * fix(frontend): match agent editor save test to serialized payload The prompt-inheritance save path still closes after update; the test should assert that payload, not the unsanitized form object. * feat(browser): implement browser connection management and related tests - Introduced a new `browserConnection` store to manage the state of browser connections, including online status and device information. - Updated the `Input-field` component to handle browser connection states, enabling/disabling features based on the connection status. - Added tests for the `browserConnection` store to ensure correct behavior under various scenarios. - Enhanced the `Input-field` and `BrowserConnectionSettings` components to provide user feedback based on the browser connection state. - Adjusted related components and views to integrate the new browser connection logic, improving overall user experience. * fix(frontend): update model-save assertion for serialized agent payload The agent editor still persists the selected model ID via a spread of formData; the source test should match that payload, not the raw form.
2026-09-11 13:28:58 +00:00
sections := BuildSystemPromptSections(
e.knowledgeBasesInfo,
e.config.WebSearchEnabled,
e.systemPromptOptions(ctx),
e.systemPromptTemplate,
)
feat(browser): polish connection settings, open tasks in a new window, and streamline prompts (#3193) * feat(browser): enhance BrowserIcon component and update localization strings - Updated BrowserIcon component to accept dynamic width and height props. - Revised localization strings in English, Japanese, Korean, Russian, and Chinese for improved clarity and user guidance regarding browser connection and usage instructions. - Enhanced BrowserConnectionSettings view with better structure and user feedback elements. * Default BrowserSkill tasks to a separate window * refactor(prompts): streamline agent system prompts and context templates - Updated agent system prompts to enhance clarity and specificity in user interactions. - Revised context templates to better separate metadata and user requests, improving overall structure. - Adjusted fallback and intent prompts to ensure consistent language handling and response requirements. - Introduced new localization strings for browser search instructions across multiple languages. - Added tests for agent prompt serialization and hydration to ensure template integrity and functionality. * chore: wrap prompt strings to satisfy golangci-lint Keep the settings, separate-window, and prompt commits pushable together without rewriting their history. * fix(frontend): match agent editor save test to serialized payload The prompt-inheritance save path still closes after update; the test should assert that payload, not the unsanitized form object. * feat(browser): implement browser connection management and related tests - Introduced a new `browserConnection` store to manage the state of browser connections, including online status and device information. - Updated the `Input-field` component to handle browser connection states, enabling/disabling features based on the connection status. - Added tests for the `browserConnection` store to ensure correct behavior under various scenarios. - Enhanced the `Input-field` and `BrowserConnectionSettings` components to provide user feedback based on the browser connection state. - Adjusted related components and views to integrate the new browser connection logic, improving overall user experience. * fix(frontend): update model-save assertion for serialized agent payload The agent editor still persists the selected model ID via a spread of formData; the source test should match that payload, not the raw form.
2026-09-11 13:28:58 +00:00
for _, section := range sections {
logger.Debugf(ctx, "[Agent][Prompt] section=%s bytes=%d", section.Name, len(section.Content))
}
feat(browser): polish connection settings, open tasks in a new window, and streamline prompts (#3193) * feat(browser): enhance BrowserIcon component and update localization strings - Updated BrowserIcon component to accept dynamic width and height props. - Revised localization strings in English, Japanese, Korean, Russian, and Chinese for improved clarity and user guidance regarding browser connection and usage instructions. - Enhanced BrowserConnectionSettings view with better structure and user feedback elements. * Default BrowserSkill tasks to a separate window * refactor(prompts): streamline agent system prompts and context templates - Updated agent system prompts to enhance clarity and specificity in user interactions. - Revised context templates to better separate metadata and user requests, improving overall structure. - Adjusted fallback and intent prompts to ensure consistent language handling and response requirements. - Introduced new localization strings for browser search instructions across multiple languages. - Added tests for agent prompt serialization and hydration to ensure template integrity and functionality. * chore: wrap prompt strings to satisfy golangci-lint Keep the settings, separate-window, and prompt commits pushable together without rewriting their history. * fix(frontend): match agent editor save test to serialized payload The prompt-inheritance save path still closes after update; the test should assert that payload, not the unsanitized form object. * feat(browser): implement browser connection management and related tests - Introduced a new `browserConnection` store to manage the state of browser connections, including online status and device information. - Updated the `Input-field` component to handle browser connection states, enabling/disabling features based on the connection status. - Added tests for the `browserConnection` store to ensure correct behavior under various scenarios. - Enhanced the `Input-field` and `BrowserConnectionSettings` components to provide user feedback based on the browser connection state. - Adjusted related components and views to integrate the new browser connection logic, improving overall user experience. * fix(frontend): update model-save assertion for serialized agent payload The agent editor still persists the selected model ID via a spread of formData; the source test should match that payload, not the raw form.
2026-09-11 13:28:58 +00:00
return renderSystemPromptSections(sections)
}
// SetMemoryPrompt supplies the long-term memory envelope for this run. Empty
// input leaves the system prompt untouched.
func (e *AgentEngine) SetMemoryPrompt(prompt string) {
e.memoryPrompt = prompt
}
// NewAgentEngineWithSkills creates a new agent engine with skills support
func NewAgentEngineWithSkills(
config *types.AgentConfig,
chatModel chat.Chat,
toolRegistry *agenttools.ToolRegistry,
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
selectedDocs []*SelectedDocumentInfo,
sessionID string,
systemPromptTemplate string,
skillsManager *skills.Manager,
) *AgentEngine {
engine := NewAgentEngine(
config,
chatModel,
toolRegistry,
eventBus,
knowledgeBasesInfo,
selectedDocs,
sessionID,
systemPromptTemplate,
)
engine.skillsManager = skillsManager
return engine
}
// SetAppConfig sets the application config for prompt template resolution.
// This allows the engine to read default prompts from config/prompt_templates/ YAML files.
func (e *AgentEngine) SetAppConfig(cfg *appconfig.Config) {
e.appConfig = cfg
}
// SetImageDescriber sets the VLM function for generating text descriptions of images
// in tool results. When set, MCP tool result images are automatically analyzed and
// their descriptions are appended to the tool message content.
// This follows the same pattern as Handler.analyzeImageAttachments() in the handler layer.
func (e *AgentEngine) SetImageDescriber(fn ImageDescriberFunc) {
e.imageDescriber = fn
}
// SetSkillsManager sets the skills manager for the engine
func (e *AgentEngine) SetSkillsManager(manager *skills.Manager) {
e.skillsManager = manager
}
// GetSkillsManager returns the skills manager
func (e *AgentEngine) GetSkillsManager() *skills.Manager {
return e.skillsManager
}
// estimateCurrentTokens returns the best estimate of the current context token
// count:
//
// - When API usage from a previous round is available, that number is the
// baseline (the provider already billed tools + system + history) and only
// the messages appended since then are BPE-estimated.
// - Otherwise it is a pure message-size estimate. Tool schemas are NOT
// added here. Adding 232 tool schemas (~105k) to a 12k conversation made
// every round look over the 111k threshold even after a successful
// compaction.
//
// The baseline already contains the assistant reply, as the `output` half of
// the round that produced it. So the delta must start *after* that reply.
func (e *AgentEngine) estimateCurrentTokens(messages []chat.Message) int {
if baseline := contextTokensFromUsage(e.lastUsage); baseline > 0 &&
e.lastSentMsgCount > 0 && e.lastSentMsgCount <= len(messages) {
return baseline + e.tokenEstimator.EstimateMessages(messages[e.deltaStart(messages):])
}
return e.tokenEstimator.EstimateMessages(messages)
}
// deltaStart is the first message not already accounted for by e.lastUsage.
func (e *AgentEngine) deltaStart(messages []chat.Message) int {
start := e.lastSentMsgCount
// The reply to the previous request lands here. Its tokens are the usage's
// completion half, so skip it — but only if it is really there, since a
// failed round appends nothing.
if start < len(messages) && messages[start].Role == "assistant" {
start++
}
return start
}
// contextTokensFromUsage reduces a usage report to the size of the context it
// describes. Cache counters are not added in: WeKnora normalizes PromptTokens
// to the provider's full input count, with read/write/miss as descriptive
// subsets of it (see types.TokenUsage.SetPromptCacheUsage).
func contextTokensFromUsage(usage types.TokenUsage) int {
if usage.TotalTokens > 0 {
return usage.TotalTokens
}
return usage.PromptTokens + usage.CompletionTokens
}
// Execute executes the agent with conversation history and streaming output
// All events are emitted to EventBus and handled by subscribers (like Handler layer)
func (e *AgentEngine) Execute(
ctx context.Context,
sessionID, messageID, query string,
llmContext []chat.Message,
imageURLs ...[]string,
) (*types.AgentState, error) {
logger.Infof(ctx, "[Agent] Starting execution: session=%s, message=%s, query_len=%d, context_msgs=%d",
sessionID, messageID, len(query), len(llmContext))
// Ensure tools are cleaned up after execution
defer e.toolRegistry.Cleanup(ctx)
common.PipelineInfo(ctx, "Agent", "execute_start", map[string]interface{}{
"session_id": sessionID,
"message_id": messageID,
"query": query,
"context_msgs": len(llmContext),
})
// Open a top-level Langfuse span so the agent run — including every
// round's LLM call and every tool execution — groups under a single
// node in the Langfuse UI instead of being flat children of the HTTP
// trace. No-op when Langfuse is disabled.
imgCount := 0
if len(imageURLs) > 0 {
imgCount = len(imageURLs[0])
}
kbIDs := make([]string, 0, len(e.knowledgeBasesInfo))
for _, kb := range e.knowledgeBasesInfo {
if kb != nil {
kbIDs = append(kbIDs, kb.ID)
}
}
spanCtx, agentSpan := langfuse.GetManager().StartSpan(ctx, langfuse.SpanOptions{
Name: "agent.execute",
Input: map[string]interface{}{
"query": truncateRunes(query, langfuseQueryPreview),
"query_len": len(query),
"context_msgs": len(llmContext),
"image_count": imgCount,
},
Metadata: map[string]interface{}{
"session_id": sessionID,
"message_id": messageID,
"max_iterations": e.config.MaxIterations,
"parallel_tool_calls": e.config.ParallelToolCalls,
"web_search": e.config.WebSearchEnabled,
"multi_turn": e.config.MultiTurnEnabled,
"knowledge_base_ids": kbIDs,
"allowed_tools": e.config.AllowedTools,
},
})
ctx = spanCtx
// Initialize state
state := &types.AgentState{
RoundSteps: []types.AgentStep{},
KnowledgeRefs: []*types.SearchResult{},
IsComplete: false,
CurrentRound: 0,
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
// A turn that measures no scale of its own (no tool call, so no two
// requests to compare) passes on the one it started from, so the
// newest turn always carries the latest known scale and the loader
// never has to look past its first page for one.
TurnUsage: types.TokenUsage{ContextTokenScale: e.config.ContextTokenScale},
}
// Build system prompt using progressive RAG prompt
// If skills are enabled, include skills metadata (Level 1 - Progressive Disclosure)
systemPrompt := e.buildSystemPrompt(ctx)
logger.Debugf(ctx, "[Agent] SystemPrompt: %d chars", len(systemPrompt))
// Initialize messages with history
var imgs []string
if len(imageURLs) > 0 {
imgs = imageURLs[0]
}
messages := e.buildMessagesWithLLMContext(systemPrompt, query, sessionID, llmContext, imgs)
if e.toolRegistry != nil {
e.toolRegistry.RememberMCPHistory(messages)
e.toolRegistry.RefreshMCPTools(ctx)
}
// Get tool definitions for function calling
tools := e.buildToolsForLLM()
toolListStr := strings.Join(listToolNames(tools), ", ")
logger.Infof(ctx, "[Agent] Ready: %d messages, %d tools [%s], mcp_catalog=%d chars, %d images",
len(messages), len(tools), toolListStr, mcpCatalogDescriptionLen(tools), len(imgs))
common.PipelineInfo(ctx, "Agent", "tools_ready", map[string]interface{}{
"session_id": sessionID,
"tool_count": len(tools),
"tools": toolListStr,
})
_, err := e.executeLoop(ctx, state, query, messages, tools, sessionID, messageID)
if err != nil {
logger.Errorf(ctx, "[Agent] Execution failed: %v", err)
e.eventBus.Emit(ctx, event.Event{
ID: generateEventID("error"),
Type: event.EventError,
SessionID: sessionID,
Data: event.ErrorData{
Error: err.Error(),
Stage: "agent_execution",
SessionID: sessionID,
},
})
finishAgentSpan(agentSpan, state, err)
return nil, err
}
logger.Infof(ctx, "[Agent] Completed: %d rounds, %d steps, complete=%v",
state.CurrentRound, len(state.RoundSteps), state.IsComplete)
common.PipelineInfo(ctx, "Agent", "execute_complete", map[string]interface{}{
"session_id": sessionID,
"rounds": state.CurrentRound,
"steps": len(state.RoundSteps),
"complete": state.IsComplete,
})
finishAgentSpan(agentSpan, state, nil)
return state, nil
}
// finishAgentSpan records the final outcome of an agent execution onto the
// top-level Langfuse span. Extracted so the same payload is used for both
// success and error return paths in Execute().
func finishAgentSpan(span *langfuse.Span, state *types.AgentState, err error) {
if span == nil {
return
}
totalToolCalls := 0
for _, step := range state.RoundSteps {
totalToolCalls += len(step.ToolCalls)
}
output := map[string]interface{}{
"rounds": state.CurrentRound,
"steps": len(state.RoundSteps),
"tool_calls": totalToolCalls,
"complete": state.IsComplete,
"final_answer_len": len(state.FinalAnswer),
"final_answer": truncateRunes(state.FinalAnswer, langfuseQueryPreview),
}
span.Finish(output, map[string]interface{}{
"rounds": state.CurrentRound,
"steps": len(state.RoundSteps),
"tool_calls": totalToolCalls,
"complete": state.IsComplete,
}, err)
}
// truncateRunes caps s to n runes and appends "…" when truncated. Identical
// in spirit to the helper in act.go, but kept locally so both files stay
// independent and the truncation budget can diverge if needed.
func truncateRunes(s string, n int) string {
if n <= 0 || s == "" {
return s
}
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
// withinIterationBudget reports whether another ReAct round is allowed.
// A negative MaxIterations is unlimited: the loop still stops on a natural
// finish, user cancel, empty-response retries, or a repeated-content stall.
func (e *AgentEngine) withinIterationBudget(round int) bool {
if e.config == nil {
return false
}
if e.config.UnlimitedIterations() {
return true
}
return round < e.config.MaxIterations
}
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
// loopGuards is the per-turn state the ReAct loop uses to notice it is not
// making progress. All three counters exist because a model can keep the loop
// spinning without ever finishing: empty answers, the same answer repeated,
// and rounds cut off at the completion-token cap.
type loopGuards struct {
// emptyRetries counts nudges sent after a stop with no content.
emptyRetries int
// consecutiveSameContent counts plain rounds that repeated the previous
// plain round verbatim, an identical lack of content included.
consecutiveSameContent int
// sawPlainRound records whether lastResponseContent holds a real
// observation yet, so the first plain round of a turn is never counted as
// a repeat of the zero value.
sawPlainRound bool
lastResponseContent string
// consecutiveLength counts rounds in a row that the provider cut off at
// the completion-token cap.
consecutiveLength int
}
// closeAnswerStream emits the Done:true marker for an answer that is actually
// finishing. Loop-end inject skips this so the client does not drop isReplying
// while the engine continues. truncated rides along on the marker because an
// answer streamed live only finds out about the completion cap at the close.
func (e *AgentEngine) closeAnswerStream(ctx context.Context, sessionID, answerID string, truncated bool) {
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
if e.eventBus == nil || answerID == "" {
return
}
_ = e.eventBus.Emit(ctx, event.Event{
ID: answerID,
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
Content: "",
Done: true,
Truncated: truncated,
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
},
})
}
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
// finishStalledTurn ends a turn that a guard stopped rather than the model.
// Whatever text the last round produced stands as the answer; when the round
// produced none, a fallback says why instead of completing with an empty
// message. The answer stream is closed here because no natural-stop path will
// reach it once the loop breaks.
func (e *AgentEngine) finishStalledTurn(
ctx context.Context,
state *types.AgentState,
sessionID string,
response *types.ChatResponse,
truncated bool,
) {
// Text that arrived alongside tool calls is a preamble — "let me look that
// up" — from a round that meant to keep working. Presenting it as the final
// answer would show an opening line and call the turn finished, so the
// fallback speaks for it instead.
answer := response.Content
if len(response.ToolCalls) > 0 {
answer = ""
}
answerID := ""
if response.AnswerStreamed && answer != "" {
answerID = response.AnswerEventID
}
if strings.TrimSpace(answer) == "" {
answer = stalledAnswerFallback
if truncated {
answer = truncatedAnswerFallback
}
answerID = ""
}
// No answer stream reached the client for this text: the round never
// streamed it, or it is the fallback just chosen. Emit it once so the turn
// does not end on a Done marker for content the client never saw.
if answerID == "" && e.eventBus != nil {
answerID = generateEventID("answer")
_ = e.eventBus.Emit(ctx, event.Event{
ID: answerID,
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
Content: answer,
Done: false,
Truncated: truncated,
},
})
}
e.closeAnswerStream(ctx, sessionID, answerID, truncated)
state.FinalAnswer = answer
state.IsComplete = true
}
func (e *AgentEngine) maxIterationsDisplay() string {
if e.config != nil && e.config.UnlimitedIterations() {
return "unlimited"
}
n := 0
if e.config != nil {
n = e.config.MaxIterations
}
return fmt.Sprintf("%d", n)
}
// executeLoop executes the main ReAct loop
// All events are emitted through EventBus with the given sessionID
func (e *AgentEngine) executeLoop(
ctx context.Context,
state *types.AgentState,
query string,
messages []chat.Message,
tools []chat.Tool,
sessionID string,
messageID string,
) (*types.AgentState, error) {
startTime := time.Now()
common.PipelineInfo(ctx, "Agent", "loop_start", map[string]interface{}{
"max_iterations": e.config.MaxIterations,
})
// Guarantee exactly-one EventAgentComplete emission on every exit path
// (normal finish, ctx cancel observed at the loop head, or iteration error
// bubbling up while ctx was cancelled). The emission triggers
// agent_stream_handler.handleComplete, which is where state.RoundSteps
// (thinking + tool_call history) gets written onto assistantMessage.AgentSteps
// so it can be persisted by the caller's defer. Use WithoutCancel so a
// cancelled ctx does not short-circuit the emit on the stop path.
completionEmitted := false
emitCompletion := func() {
if completionEmitted {
return
}
completionEmitted = true
e.emitCompletionEvent(context.WithoutCancel(ctx), state, sessionID, messageID, startTime)
}
defer emitCompletion()
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
guards := &loopGuards{}
loop:
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
for e.withinIterationBudget(state.CurrentRound) || e.allowSteerOverrun {
e.allowSteerOverrun = false
// Check for context cancellation (request timeout, user cancel, etc.)
select {
case <-ctx.Done():
logger.Warnf(ctx, "[Agent] Context cancelled at round %d: %v",
state.CurrentRound+1, ctx.Err())
// Try to salvage existing results
if totalTC := countTotalToolCalls(state.RoundSteps); totalTC > 0 {
logger.Infof(ctx, "[Agent] Synthesizing final answer from %d existing tool results",
totalTC)
feat(browser): polish connection settings, open tasks in a new window, and streamline prompts (#3193) * feat(browser): enhance BrowserIcon component and update localization strings - Updated BrowserIcon component to accept dynamic width and height props. - Revised localization strings in English, Japanese, Korean, Russian, and Chinese for improved clarity and user guidance regarding browser connection and usage instructions. - Enhanced BrowserConnectionSettings view with better structure and user feedback elements. * Default BrowserSkill tasks to a separate window * refactor(prompts): streamline agent system prompts and context templates - Updated agent system prompts to enhance clarity and specificity in user interactions. - Revised context templates to better separate metadata and user requests, improving overall structure. - Adjusted fallback and intent prompts to ensure consistent language handling and response requirements. - Introduced new localization strings for browser search instructions across multiple languages. - Added tests for agent prompt serialization and hydration to ensure template integrity and functionality. * chore: wrap prompt strings to satisfy golangci-lint Keep the settings, separate-window, and prompt commits pushable together without rewriting their history. * fix(frontend): match agent editor save test to serialized payload The prompt-inheritance save path still closes after update; the test should assert that payload, not the unsanitized form object. * feat(browser): implement browser connection management and related tests - Introduced a new `browserConnection` store to manage the state of browser connections, including online status and device information. - Updated the `Input-field` component to handle browser connection states, enabling/disabling features based on the connection status. - Added tests for the `browserConnection` store to ensure correct behavior under various scenarios. - Enhanced the `Input-field` and `BrowserConnectionSettings` components to provide user feedback based on the browser connection state. - Adjusted related components and views to integrate the new browser connection logic, improving overall user experience. * fix(frontend): update model-save assertion for serialized agent payload The agent editor still persists the selected model ID via a spread of formData; the source test should match that payload, not the raw form.
2026-09-11 13:28:58 +00:00
_ = e.streamFinalAnswerToEventBus(ctx, query, state, sessionID, messages)
state.IsComplete = true
}
return state, ctx.Err()
default:
}
// A slow startup, OAuth discovery or explicit refresh may have produced
// new definitions since the previous response. Publish them only here,
// after all previous tool calls have finished, and rebuild the wire list.
if e.toolRegistry != nil {
e.toolRegistry.RefreshMCPTools(ctx)
tools = e.buildToolsForLLM()
}
// Each iteration runs inside an "agent.round.<N>" Langfuse span.
// We execute the body in a closure so `defer span.Finish()` fires at
// every exit path (break/continue/next) without having to sprinkle
// manual finish calls throughout the many branches below.
outcome, iterErr := e.runReActIteration(ctx, state, &messages, tools,
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
sessionID, messageID, query, guards)
if iterErr != nil {
return state, iterErr
}
switch outcome {
case iterOutcomeContinue:
continue loop
case iterOutcomeBreak:
break loop
case iterOutcomeNext:
state.CurrentRound++
}
}
// If loop finished without final answer, generate one — but skip this
// when the context was cancelled (user pressed stop). In that case the
// fallback LLM call would fail on the already-cancelled ctx and set
// state.FinalAnswer to the generic "Sorry, I was unable to generate a
// complete answer." message, which then leaks to the UI as the final
// answer for a conversation the user deliberately stopped.
if !state.IsComplete && ctx.Err() == nil {
feat(browser): polish connection settings, open tasks in a new window, and streamline prompts (#3193) * feat(browser): enhance BrowserIcon component and update localization strings - Updated BrowserIcon component to accept dynamic width and height props. - Revised localization strings in English, Japanese, Korean, Russian, and Chinese for improved clarity and user guidance regarding browser connection and usage instructions. - Enhanced BrowserConnectionSettings view with better structure and user feedback elements. * Default BrowserSkill tasks to a separate window * refactor(prompts): streamline agent system prompts and context templates - Updated agent system prompts to enhance clarity and specificity in user interactions. - Revised context templates to better separate metadata and user requests, improving overall structure. - Adjusted fallback and intent prompts to ensure consistent language handling and response requirements. - Introduced new localization strings for browser search instructions across multiple languages. - Added tests for agent prompt serialization and hydration to ensure template integrity and functionality. * chore: wrap prompt strings to satisfy golangci-lint Keep the settings, separate-window, and prompt commits pushable together without rewriting their history. * fix(frontend): match agent editor save test to serialized payload The prompt-inheritance save path still closes after update; the test should assert that payload, not the unsanitized form object. * feat(browser): implement browser connection management and related tests - Introduced a new `browserConnection` store to manage the state of browser connections, including online status and device information. - Updated the `Input-field` component to handle browser connection states, enabling/disabling features based on the connection status. - Added tests for the `browserConnection` store to ensure correct behavior under various scenarios. - Enhanced the `Input-field` and `BrowserConnectionSettings` components to provide user feedback based on the browser connection state. - Adjusted related components and views to integrate the new browser connection logic, improving overall user experience. * fix(frontend): update model-save assertion for serialized agent payload The agent editor still persists the selected model ID via a spread of formData; the source test should match that payload, not the raw form.
2026-09-11 13:28:58 +00:00
e.handleMaxIterations(ctx, query, state, sessionID, messages)
}
return state, nil
}
// iterOutcome directs executeLoop's control flow after one ReAct iteration.
// Using a sentinel (rather than bare return values from runReActIteration)
// keeps the loop's break/continue/next branches explicit in one place.
type iterOutcome int
const (
// iterOutcomeNext advances state.CurrentRound and loops again.
iterOutcomeNext iterOutcome = iota
// iterOutcomeContinue re-runs the loop without advancing the round
// counter. Used by the empty-content retry path.
iterOutcomeContinue
// iterOutcomeBreak exits the loop (final answer, stuck loop, or end).
iterOutcomeBreak
)
// runReActIteration executes one ReAct step: think → analyze → act → observe.
// Extracted from executeLoop so the whole iteration body can live inside a
// single `defer span.Finish()` scope — otherwise we'd need to sprinkle
// manual finish calls across every break/continue/return branch.
//
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
// The mutable loop state (messages and the no-progress guards) is shared
// across iterations so each round can see what the previous ones did.
func (e *AgentEngine) runReActIteration(
parentCtx context.Context,
state *types.AgentState,
messagesPtr *[]chat.Message,
tools []chat.Tool,
feat(agent): human-in-the-loop approval for MCP tool calls (#1173) Add an opt-in human approval gate so Agent runs pause before executing MCP tools that operators flag as dangerous, surface an approval card in the chat UI, and only resume after the user approves (optionally with edited args) or rejects. Backend - New mcp_tool_approvals table + repo/service to mark per-tool approval required (PG migration 000042 + sqlite init). - approval.Gate coordinates RequestAndWait / Resolve with sync.Once delivery, configurable timeout, and Redis Pub/Sub fan-out so multi- replica deployments work without sticky sessions. - MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx (without the per-tool 60s timeout) for the wait, and re-derives a fresh 60s exec ctx after approval so CallTool keeps a full window. - New SSE response types (tool_approval_required / _resolved) and EventBus events plumb approval state to AgentStreamDisplay. - REST: list/set per-tool approval flag, resolve pending approval. - Configurable via agent.tool_approval_timeout_seconds (yaml) or WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go duration). Frontend - MCP settings: per-tool "require approval" switch on the test panel. - Chat: ToolApprovalCard renders the pause point with editable JSON args, validation feedback, mm:ss countdown that turns warning/danger near deadline, and a resolved state that retains context. - i18n strings added for zh-CN / en-US / ko-KR / ru-RU. Docs - docs/zh/mcp-approval.md covering behavior, config, API, deployment considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
sessionID, assistantMessageID, query string,
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
guards *loopGuards,
) (outcome iterOutcome, retErr error) {
roundStart := time.Now()
round := state.CurrentRound + 1
// Open the round-level Langfuse span. Any chat/tool calls made inside
// this iteration will attach under it via ctx, giving the UI a clean
// trace → agent.execute → agent.round.N → (chat + tools) structure.
ctx, roundSpan := langfuse.GetManager().StartSpan(parentCtx, langfuse.SpanOptions{
Name: fmt.Sprintf("agent.round.%d", round),
Input: map[string]interface{}{
"round": round,
"message_count": len(*messagesPtr),
"max_iterations": e.config.MaxIterations,
},
Metadata: map[string]interface{}{
"iteration": state.CurrentRound,
"round": round,
"session_id": sessionID,
},
})
var (
response *types.ChatResponse
toolCallCount int
)
defer func() {
if roundSpan == nil {
return
}
out := map[string]interface{}{
"round": round,
"outcome": outcome.String(),
"tool_calls": toolCallCount,
}
if response != nil {
out["has_tool_calls"] = len(response.ToolCalls) > 0
out["finish_reason"] = response.FinishReason
out["content_len"] = len(response.Content)
if response.Usage.TotalTokens > 0 {
out["prompt_tokens"] = response.Usage.PromptTokens
out["completion_tokens"] = response.Usage.CompletionTokens
out["total_tokens"] = response.Usage.TotalTokens
}
}
out["duration_ms"] = time.Since(roundStart).Milliseconds()
roundSpan.Finish(out, map[string]interface{}{
"round": round,
"tool_calls": toolCallCount,
"outcome": outcome.String(),
"duration_ms": time.Since(roundStart).Milliseconds(),
}, retErr)
}()
// Compact older history before the next assistant response when the
// estimate is over the threshold. The trigger is estimateCurrentTokens —
// usage+delta when a previous round reported one, otherwise the message
// list alone. Tool schemas are not added here.
currentTokens := e.estimateCurrentTokens(*messagesPtr)
managed, changed := e.manageContextWindow(ctx, *messagesPtr, round, currentTokens)
if changed {
*messagesPtr = managed
currentTokens = e.tokenEstimator.EstimateMessages(managed)
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// Mid-run steering: drain any user messages queued while the previous
// round was thinking/executing tools. Runs after compression (injected
// text stays inside the protected tail) and before lastSentMsgCount is
// updated (the injected text counts as new delta tokens for the next
// call), so the very next LLM call sees the user's addition.
e.drainSteerMessages(ctx, state, messagesPtr, sessionID, assistantMessageID)
logger.Infof(ctx, "[Agent][Round-%d/%s] Starting: %d messages, %d tools, est_tokens=%d",
round, e.maxIterationsDisplay(), len(*messagesPtr), len(tools), currentTokens)
e.logContextPrediction(ctx, round, *messagesPtr, tools, currentTokens)
common.PipelineInfo(ctx, "Agent", "round_start", map[string]interface{}{
"iteration": state.CurrentRound,
"round": round,
"message_count": len(*messagesPtr),
"pending_tools": len(tools),
"max_iterations": e.config.MaxIterations,
})
// 1. Think: Call LLM with function calling (includes retry + graceful degradation)
e.lastSentMsgCount = len(*messagesPtr)
resp, err := e.callLLMWithRetry(ctx, messagesPtr, tools, state, query, state.CurrentRound, sessionID)
if err != nil {
retErr = err
return iterOutcomeNext, err
}
if resp == nil {
return iterOutcomeBreak, nil
}
// The round's own token estimate can be wrong — history is estimated, not
// counted — so a request that looked safe can still come back having hit
// the window. Compacting and retrying once turns that into a recovered
// round instead of a wasted one. Once per turn: if the retry overflows
// too, the problem is not the history size.
if !e.overflowRecovered && e.responseHitContextLimit(resp) {
e.overflowRecovered = true
logger.Warnf(ctx, "[Agent][Round-%d] Response hit the context window (finish=%s, "+
"completion=%d of %d requested); compacting and retrying once",
round, resp.FinishReason, resp.Usage.CompletionTokens, e.getCompletionTokenBudget())
*messagesPtr = e.forceCompaction(ctx, *messagesPtr, round)
e.lastSentMsgCount = len(*messagesPtr)
resp, err = e.callLLMWithRetry(ctx, messagesPtr, tools, state, query, state.CurrentRound, sessionID)
if err != nil {
retErr = err
return iterOutcomeNext, err
}
if resp == nil {
return iterOutcomeBreak, nil
}
}
response = resp
e.logContextDrift(ctx, round, currentTokens, response.Usage)
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
// Calibration needs only a prompt count; some providers report no total.
e.calibrateEstimator(ctx, round, *messagesPtr, tools, response.Usage, state)
if response.Usage.TotalTokens > 0 {
e.lastUsage = response.Usage
state.TurnUsage.Accumulate(response.Usage)
logger.Infof(ctx, "[Agent][Round-%d] Usage: prompt=%d, completion=%d, total=%d, "+
"cache_read=%d, cache_write=%d, cache_hit_rate=%.1f%%, cache_status=%s",
round, response.Usage.PromptTokens,
response.Usage.CompletionTokens, response.Usage.TotalTokens,
response.Usage.CacheReadTokens, response.Usage.CacheWriteTokens,
response.Usage.PromptCacheHitRate(), response.Usage.CacheStatus)
}
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
// Every round in a row that the provider cut off at the completion cap.
// A truncated *answer* already ends the turn in analyzeResponse, so a run
// of these means the truncation keeps landing inside tool-call arguments:
// act.go refuses the calls, the model is told to re-issue them, writes an
// even longer call, and hits the cap again. Give up rather than spend the
// whole round budget on it (#3446).
if isLengthFinishReason(response.FinishReason) {
guards.consecutiveLength++
if guards.consecutiveLength >= maxConsecutiveLengthRounds {
logger.Warnf(ctx, "[Agent][Round-%d] %d consecutive rounds cut off at the completion cap "+
"(finish=%s, completion=%d of %d); stopping",
round, guards.consecutiveLength, response.FinishReason,
response.Usage.CompletionTokens, e.getCompletionTokenBudget())
common.PipelineWarn(ctx, "Agent", "consecutive_length_stop", map[string]interface{}{
"iteration": state.CurrentRound,
"round": round,
"consecutive_length": guards.consecutiveLength,
})
// Record the round the way every other round is recorded. The
// refused tool calls are also what tells the UI that this round's
// plain text was a preamble: without them the "let me look that
// up" line stays sitting in the answer area, exactly as if it were
// the answer.
step := types.AgentStep{
Iteration: state.CurrentRound,
Thought: response.Content,
ReasoningContent: response.ReasoningContent,
ToolCalls: make([]types.ToolCall, 0),
Timestamp: time.Now(),
Truncated: true,
}
if len(response.ToolCalls) > 0 {
e.failTruncatedToolCalls(ctx, response, &step, state.CurrentRound, sessionID)
}
state.RoundSteps = append(state.RoundSteps, step)
e.finishStalledTurn(ctx, state, sessionID, response, true)
return iterOutcomeBreak, nil
}
} else {
guards.consecutiveLength = 0
}
// Detect stuck loops: a round with no tool calls that repeats the previous
// such round is not making progress. An identical *lack* of content counts
// — a model burning its whole budget on reasoning returns empty every
// round, which used to land in the else branch and reset the counter, so
// the guard could never fire on the one shape that needs it most (#3446).
if len(response.ToolCalls) == 0 {
if guards.sawPlainRound && response.Content == guards.lastResponseContent {
guards.consecutiveSameContent++
} else {
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
guards.consecutiveSameContent = 0
}
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
guards.sawPlainRound = true
guards.lastResponseContent = response.Content
if guards.consecutiveSameContent >= maxRepeatedResponseRounds {
logger.Warnf(ctx, "[Agent][Round-%d] Detected stuck loop: same content repeated %d times (finish=%s), stopping",
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
round, guards.consecutiveSameContent+1, response.FinishReason)
e.finishStalledTurn(ctx, state, sessionID, response, false)
return iterOutcomeBreak, nil
}
} else {
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
guards.consecutiveSameContent = 0
guards.sawPlainRound = false
guards.lastResponseContent = ""
}
// Create agent step
step := types.AgentStep{
UserMessagesBefore: state.PendingSteerMessages,
Iteration: state.CurrentRound,
Thought: response.Content,
ReasoningContent: response.ReasoningContent,
ReasoningSignature: response.ReasoningSignature,
ReasoningMetadata: response.ReasoningMetadata,
ToolCalls: make([]types.ToolCall, 0),
Timestamp: time.Now(),
}
state.PendingSteerMessages = nil
// If the request was cancelled while the LLM was streaming (e.g. the
// user pressed "stop"), the stream driver still returns a usable
// response (partial content / finish_reason="stop" / no tool calls).
// Do NOT let analyzeResponse treat that partial thinking text as the
// final answer — it would pollute Message.Content with mid-stream
// thinking and show up as a duplicate card next to the intermediate-
// steps tree. Preserve the partial thinking as an AgentStep and break
// out of the loop without marking state.IsComplete. executeLoop's
// deferred emitCompletionEvent will persist the step onto
// Message.AgentSteps so it still appears in the tree on refresh.
if ctx.Err() != nil {
logger.Warnf(ctx, "[Agent][Round-%d] Context cancelled during LLM call; preserving partial step",
round)
if step.Thought != "" || len(step.ToolCalls) > 0 || len(step.UserMessagesBefore) > 0 {
state.RoundSteps = append(state.RoundSteps, step)
}
return iterOutcomeBreak, nil
}
// 2. Analyze: Check for stop conditions (natural stop with no tool calls)
verdict := e.analyzeResponse(ctx, response, step, state.CurrentRound, sessionID, roundStart)
if verdict.isDone {
// Guard against empty content: when the LLM stops naturally with no
// content and no tool calls (e.g., thinking-only loop without KB),
// retry with a nudge message instead of accepting an empty answer.
if verdict.emptyContent {
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
guards.emptyRetries++
if guards.emptyRetries <= maxEmptyResponseRetries {
state.PendingSteerMessages = step.UserMessagesBefore
logger.Warnf(ctx, "[Agent][Round-%d] Empty content with stop - retrying (%d/%d)",
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
round, guards.emptyRetries, maxEmptyResponseRetries)
*messagesPtr = append(*messagesPtr, chat.Message{
Role: "user",
Content: "Please provide your complete answer now as plain text.",
})
return iterOutcomeContinue, nil
}
// Retries exhausted — use fallback message rather than empty answer.
// analyzeResponse emitted nothing for the empty rounds (they were
// retryable), so the fallback must be emitted here as the turn's
// sole terminal answer event (#2906).
logger.Warnf(ctx, "[Agent][Round-%d] Empty content after %d retries - using fallback",
round, maxEmptyResponseRetries)
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
fallback := stalledAnswerFallback
answerID := generateEventID("answer")
_ = e.eventBus.Emit(ctx, event.Event{
ID: answerID,
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
Content: fallback,
Done: false,
},
})
_ = e.eventBus.Emit(ctx, event.Event{
ID: answerID,
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
Content: "",
Done: true,
},
})
state.FinalAnswer = fallback
state.IsComplete = true
state.RoundSteps = append(state.RoundSteps, verdict.step)
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
e.closeAnswerStream(ctx, sessionID, verdict.answerID, verdict.truncated)
return iterOutcomeBreak, nil
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// Loop-end inject: a user message queued while this finishing round
// ran should keep the agent going instead of emitting a final answer.
// Content-filter stops are terminal and do not take this path.
// Past MaxIterations only the first inject gets an extra round;
// anything after that stays in the queue for a follow-up turn.
if response.FinishReason != "content_filter" {
nextRound := state.CurrentRound + 1
canContinue := e.withinIterationBudget(nextRound) || e.steerOverruns < maxSteerOverruns
if canContinue {
*messagesPtr = append(*messagesPtr, chat.Message{
Role: "assistant",
Content: verdict.finalAnswer,
ReasoningContent: response.ReasoningContent,
ReasoningSignature: response.ReasoningSignature,
ReasoningMetadata: response.ReasoningMetadata,
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
})
injected := e.drainSteerMessages(ctx, state, messagesPtr, sessionID, assistantMessageID)
if injected > 0 {
verdict.step.IntermediateAnswer = true
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
state.RoundSteps = append(state.RoundSteps, verdict.step)
if !e.withinIterationBudget(nextRound) {
e.steerOverruns++
e.allowSteerOverrun = true
}
return iterOutcomeNext, nil
}
}
}
state.FinalAnswer = verdict.finalAnswer
state.IsComplete = true
state.RoundSteps = append(state.RoundSteps, verdict.step)
fix(agent): end the turn when the completion cap truncates an answer (#3449) * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline <think> block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling <think> through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer.
2026-09-20 05:17:50 +00:00
e.closeAnswerStream(ctx, sessionID, verdict.answerID, verdict.truncated)
return iterOutcomeBreak, nil
}
// This round is non-terminal (it will execute tools and loop again). Any
// plain assistant text streamed live to the answer area this round was a
// preamble (e.g. "let me search the knowledge base…"), not the final
// answer. No explicit retraction signal is emitted: the agent only ends by
// stopping naturally with plain text and no tool calls, so the upcoming
// tool-call events are themselves the authoritative "that wasn't the final
// answer" marker. Both the stream handler and the UI treat any answer text
// preceding a tool call in the same stream as a preamble and relocate it
// into the steps tree. The preamble is still preserved as this round's
// Thought.
// 3. Act: Execute tool calls
feat(agent): human-in-the-loop approval for MCP tool calls (#1173) Add an opt-in human approval gate so Agent runs pause before executing MCP tools that operators flag as dangerous, surface an approval card in the chat UI, and only resume after the user approves (optionally with edited args) or rejects. Backend - New mcp_tool_approvals table + repo/service to mark per-tool approval required (PG migration 000042 + sqlite init). - approval.Gate coordinates RequestAndWait / Resolve with sync.Once delivery, configurable timeout, and Redis Pub/Sub fan-out so multi- replica deployments work without sticky sessions. - MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx (without the per-tool 60s timeout) for the wait, and re-derives a fresh 60s exec ctx after approval so CallTool keeps a full window. - New SSE response types (tool_approval_required / _resolved) and EventBus events plumb approval state to AgentStreamDisplay. - REST: list/set per-tool approval flag, resolve pending approval. - Configurable via agent.tool_approval_timeout_seconds (yaml) or WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go duration). Frontend - MCP settings: per-tool "require approval" switch on the test panel. - Chat: ToolApprovalCard renders the pause point with editable JSON args, validation feedback, mm:ss countdown that turns warning/danger near deadline, and a resolved state that retains context. - i18n strings added for zh-CN / en-US / ko-KR / ru-RU. Docs - docs/zh/mcp-approval.md covering behavior, config, API, deployment considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
e.executeToolCalls(ctx, response, &step, state.CurrentRound, sessionID, assistantMessageID)
toolCallCount = len(step.ToolCalls)
// 4. Observe: Add tool results to messages and write to context
state.RoundSteps = append(state.RoundSteps, step)
refactor(agent): rebuild multi-turn history from DB, drop llmcontext layer The Agent ran a parallel context cache (Redis/in-memory) on top of the messages table to feed multi-turn history into the LLM. That dual-write caused subtle drift (e.g. compression diverging from DB, system-prompt swaps lost on restart) and required a separate ClearContext path on session/IM clear. Make the messages table the single source of truth: - Add service.LoadAgentHistory: rebuilds chat.Message history per turn from the persisted messages, expanding AgentSteps into proper OpenAI assistant_with_tool_calls + tool messages and replaying the canonical final answer (with <think> blocks stripped). final_answer tool calls are filtered to avoid duplicating the trailing answer. - Make AgentEngine stateless across turns: drop ContextManager / sessionID cache plumbing from the engine, agent service, and CreateAgentEngine signature. The engine only uses sessionID for logging/event emission. - Wire AgentQA to load history from DB on demand using HistoryTurns (default 5) when MultiTurnEnabled, otherwise run with empty history. - Delete the llmcontext package (ContextManager interface, Redis/memory storage, factory) and the SessionService.ClearContext API path; IM /clear and session message clear no longer need to invalidate cache. Behavior preserved: KnowledgeQA-mode replay is unchanged (turns with empty AgentSteps just produce the single canonical assistant message), and Agent-mode turns now consistently see prior tool calls and results.
2026-05-12 03:43:35 +00:00
*messagesPtr = e.appendToolResults(*messagesPtr, step)
*messagesPtr = e.appendToolImages(ctx, *messagesPtr, step)
common.PipelineInfo(ctx, "Agent", "round_end", map[string]interface{}{
"iteration": state.CurrentRound,
"round": round,
"tool_calls": toolCallCount,
"thought_len": len(step.Thought),
})
return iterOutcomeNext, nil
}
// String returns a stable label for Langfuse output payloads.
func (o iterOutcome) String() string {
switch o {
case iterOutcomeNext:
return "next"
case iterOutcomeContinue:
return "continue"
case iterOutcomeBreak:
return "break"
default:
return "unknown"
}
}
// ---------------------------------------------------------------------------
// Tool result image VLM description helpers
// ---------------------------------------------------------------------------
const toolImageAnalysisPrompt = "Describe the content of this image in detail. " +
"If it contains text, extract all readable text. " +
"If it contains charts or diagrams, describe the data and structure."
// describeImages generates text descriptions for tool result images using the
// configured imageDescriber (VLM). Each image is decoded from a data URI and
// analyzed independently. Failures are logged and skipped gracefully.
// This follows the same pattern as Handler.analyzeImageAttachments().
func (e *AgentEngine) describeImages(ctx context.Context, imageDataURIs []string) []string {
if e.imageDescriber == nil {
return nil
}
var descriptions []string
for i, dataURI := range imageDataURIs {
if ctx.Err() != nil {
logger.Warnf(ctx, "[Agent] Context cancelled, skipping remaining %d tool result images", len(imageDataURIs)-i)
break
}
imgBytes, err := decodeDataURIBytes(dataURI)
if err != nil {
logger.Warnf(ctx, "[Agent] Failed to decode tool result image %d: %v", i, err)
continue
}
desc, err := e.imageDescriber(ctx, imgBytes, toolImageAnalysisPrompt)
if err != nil {
logger.Warnf(ctx, "[Agent] VLM analysis failed for tool result image %d: %v", i, err)
continue
}
if desc = strings.TrimSpace(desc); desc != "" {
descriptions = append(descriptions, desc)
}
}
return descriptions
}
// decodeDataURIBytes extracts raw bytes from a "data:mime;base64,..." URI.
// Retries with RawStdEncoding when standard base64 decoding fails (some MCP
// servers omit trailing '=' padding).
func decodeDataURIBytes(dataURI string) ([]byte, error) {
if !strings.HasPrefix(dataURI, "data:") {
return nil, fmt.Errorf("not a data URI")
}
idx := strings.Index(dataURI, ";base64,")
if idx < 0 {
return nil, fmt.Errorf("unsupported data URI encoding (expected base64)")
}
raw := dataURI[idx+8:]
decoded, err := base64.StdEncoding.DecodeString(raw)
if err != nil {
// Retry without padding — some MCP servers omit trailing '='
decoded, err = base64.RawStdEncoding.DecodeString(raw)
}
return decoded, err
}