2025-11-08 16:02:31 +00:00
|
|
|
|
package session
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
2026-07-14 03:06:13 +00:00
|
|
|
|
"crypto/sha256"
|
2025-11-11 14:26:59 +00:00
|
|
|
|
"encoding/json"
|
2025-11-11 06:25:20 +00:00
|
|
|
|
"fmt"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
"net/http"
|
2026-07-16 06:48:20 +00:00
|
|
|
|
"os"
|
2026-08-09 08:23:36 +00:00
|
|
|
|
"path/filepath"
|
2025-11-11 06:25:20 +00:00
|
|
|
|
"runtime"
|
2026-07-16 06:48:20 +00:00
|
|
|
|
"strconv"
|
|
|
|
|
|
"strings"
|
2026-04-10 04:49:20 +00:00
|
|
|
|
"sync"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/errors"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/event"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
2026-08-04 09:14:52 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/storageurl"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
2025-11-25 14:19:41 +00:00
|
|
|
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
"github.com/gin-gonic/gin"
|
2026-03-11 09:17:32 +00:00
|
|
|
|
"github.com/google/uuid"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
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
|
|
|
|
const (
|
|
|
|
|
|
maxAttachmentUploadsPerRequest = 5
|
|
|
|
|
|
maxAttachmentUploadTotalBytes = int64(100 * 1024 * 1024)
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// qaRequestContext holds all the common data needed for QA requests
|
|
|
|
|
|
type qaRequestContext struct {
|
2026-07-14 03:06:13 +00:00
|
|
|
|
ctx context.Context
|
|
|
|
|
|
c *gin.Context
|
|
|
|
|
|
sessionID string
|
|
|
|
|
|
requestID string
|
|
|
|
|
|
receivedAt time.Time // Wall-clock time the handler started processing the request
|
|
|
|
|
|
query string
|
|
|
|
|
|
session *types.Session
|
|
|
|
|
|
customAgent *types.CustomAgent
|
|
|
|
|
|
assistantMessage *types.Message
|
|
|
|
|
|
knowledgeBaseIDs []string
|
|
|
|
|
|
knowledgeIDs []string
|
|
|
|
|
|
tagScopes []types.TagScope
|
|
|
|
|
|
tagIDs []string
|
|
|
|
|
|
mcpServiceIDs []string
|
|
|
|
|
|
skillNames []string
|
|
|
|
|
|
summaryModelID string
|
|
|
|
|
|
webSearchEnabled bool
|
|
|
|
|
|
mentionedItems types.MentionedItems
|
|
|
|
|
|
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
|
2026-07-30 04:10:31 +00:00
|
|
|
|
sharedAgentReadOnly bool // access was granted by a read-only agent share
|
2026-07-14 03:06:13 +00:00
|
|
|
|
images []ImageAttachment // Uploaded images with analysis text
|
|
|
|
|
|
userMessageID string // Created user message ID (populated after createUserMessage)
|
|
|
|
|
|
channel string // Source channel: "web", "api", "im", etc.
|
2026-07-16 06:48:20 +00:00
|
|
|
|
attachments types.MessageAttachments // Processed base64 file attachments (legacy inline uploads)
|
|
|
|
|
|
attachmentIDs []string // Pre-uploaded session-scoped document IDs, resolved after SSE starts
|
|
|
|
|
|
attachmentMetas types.MessageAttachments // Metadata-only view of attachmentIDs for the persisted user message
|
2026-07-14 03:06:13 +00:00
|
|
|
|
suggestionAttribution *types.SuggestionAttribution
|
2026-08-04 09:14:52 +00:00
|
|
|
|
// resourceRewriter turns internal storage references in the outbound stream
|
|
|
|
|
|
// into directly loadable URLs when the caller asks for `resource_urls=public`.
|
|
|
|
|
|
// Disabled (a pass-through) in the default handle mode.
|
|
|
|
|
|
resourceRewriter *storageurl.StreamRewriter
|
2026-05-18 14:24:39 +00:00
|
|
|
|
|
|
|
|
|
|
// Snapshot of the request fields needed to persist the input-bar state
|
|
|
|
|
|
// for session restoration. Kept verbatim from the request so we record
|
|
|
|
|
|
// what the user had selected on the UI (not server-side resolutions).
|
|
|
|
|
|
reqAgentEnabled bool
|
|
|
|
|
|
reqAgentID string
|
2025-12-24 02:34:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-15 14:12:45 +00:00
|
|
|
|
// buildQARequest converts the qaRequestContext into a types.QARequest for service invocation.
|
|
|
|
|
|
func (rc *qaRequestContext) buildQARequest() *types.QARequest {
|
|
|
|
|
|
imageURLs, imageDescription := extractImageURLsAndOCRText(rc.images)
|
|
|
|
|
|
return &types.QARequest{
|
2026-07-30 04:10:31 +00:00
|
|
|
|
Session: rc.session,
|
|
|
|
|
|
Query: rc.query,
|
|
|
|
|
|
AssistantMessageID: rc.assistantMessage.ID,
|
|
|
|
|
|
SummaryModelID: rc.summaryModelID,
|
|
|
|
|
|
CustomAgent: rc.customAgent,
|
|
|
|
|
|
SharedAgentReadOnly: rc.sharedAgentReadOnly,
|
|
|
|
|
|
KnowledgeBaseIDs: rc.knowledgeBaseIDs,
|
|
|
|
|
|
KnowledgeIDs: rc.knowledgeIDs,
|
|
|
|
|
|
TagScopes: rc.tagScopes,
|
|
|
|
|
|
MCPServiceIDs: rc.mcpServiceIDs,
|
|
|
|
|
|
SkillNames: rc.skillNames,
|
|
|
|
|
|
ImageURLs: imageURLs,
|
|
|
|
|
|
ImageDescription: imageDescription,
|
|
|
|
|
|
UserMessageID: rc.userMessageID,
|
|
|
|
|
|
WebSearchEnabled: rc.webSearchEnabled,
|
|
|
|
|
|
Attachments: rc.attachments,
|
2026-03-15 14:12:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// parseQARequest parses and validates a QA request, returns the request context
|
|
|
|
|
|
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
|
2026-05-12 13:12:03 +00:00
|
|
|
|
receivedAt := time.Now()
|
2025-12-24 02:34:41 +00:00
|
|
|
|
ctx := logger.CloneContext(c.Request.Context())
|
2026-05-12 13:12:03 +00:00
|
|
|
|
requestID := secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String()))
|
|
|
|
|
|
logger.Infof(ctx, "[%s] TTFB:start request_id=%s received_at=%d",
|
|
|
|
|
|
logPrefix, requestID, receivedAt.UnixMilli())
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
|
|
|
|
|
// Get session ID from URL parameter
|
|
|
|
|
|
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
|
|
|
|
|
if sessionID == "" {
|
|
|
|
|
|
logger.Error(ctx, "Session ID is empty")
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(errors.ErrInvalidSessionID.Error())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Parse request body
|
|
|
|
|
|
var request CreateKnowledgeQARequest
|
|
|
|
|
|
if err := c.ShouldBindJSON(&request); err != nil {
|
|
|
|
|
|
logger.Error(ctx, "Failed to parse request data", err)
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(err.Error())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Validate query content
|
|
|
|
|
|
if request.Query == "" {
|
|
|
|
|
|
logger.Error(ctx, "Query content is empty")
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError("Query content cannot be empty")
|
|
|
|
|
|
}
|
2026-08-04 09:14:52 +00:00
|
|
|
|
|
|
|
|
|
|
// Resolve the storage-reference representation up front: once the SSE stream
|
|
|
|
|
|
// has started an invalid value can no longer be reported as a 400.
|
|
|
|
|
|
resourceRewriter, err := h.resolveStreamRewriter(c)
|
|
|
|
|
|
if err != nil {
|
fix(api): close the resource_urls=public gaps found in review
Follow-up on resource_urls=public. Review turned up one authorization gap plus a
set of correctness problems in the streaming path.
Authorization:
- Embed channels were documented as excluded, but nothing enforced it. The
delegating handlers hand the visitor's own gin context to the shared
handlers, so ?resource_urls=public — and a deployment-wide
RESOURCE_URL_MODE=public — reached anonymous traffic and produced
shareable, credential-free URLs that bypass the channel-scoped
/embed/:channel_id/files proxy. ensureEmbedSession now pins the request
context to handle mode, which covers every delegated endpoint including
future ones. The downgrade is silent so a client that forwards the
parameter keeps working.
- A knowledge-base-restricted API key is refused with 403. Such a key is
already denied /files because a raw storage path cannot be bound to its
allow-list, so handing it anonymous file URLs would reopen that hole from
the other side. The default handle mode stays available to it.
Streaming:
- Rewriter.ref holds its lock across resolution. Resolver implementations keep
an unsynchronised per-provider cache, so the previous unlocked window was a
real data race for any caller sharing a StreamRewriter between goroutines —
which its own doc comment invited. Serialising also collapses a concurrent
duplicate into one signature.
- Release the holdback buffer on every path that ends a stream while the
client is still connected: a user-requested stop, an error event, and
giving up on the event store. Only completion flushed before, so the tail
generated just before a stop was silently dropped.
- A released tail carries the metadata of the event it was cut from instead of
a bare event_id.
- The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting
a character in half, and an unclosed "
|
|
|
|
|
|
return nil, nil, err
|
2026-08-04 09:14:52 +00:00
|
|
|
|
}
|
2026-07-14 03:06:13 +00:00
|
|
|
|
if h.suggestionService != nil && request.SuggestionAttribution != nil {
|
|
|
|
|
|
if err := h.suggestionService.ValidateAttribution(ctx, sessionID, request.Query, request.SuggestionAttribution); err != nil {
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError("invalid suggestion attribution")
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
2026-03-23 05:11:11 +00:00
|
|
|
|
// SSRF protection: strip client-supplied URL/Caption fields from image attachments.
|
|
|
|
|
|
// The URL field must only be populated server-side by saveImageAttachments; an
|
|
|
|
|
|
// attacker could inject internal network URLs to trigger SSRF via the LLM provider.
|
|
|
|
|
|
for i := range request.Images {
|
|
|
|
|
|
request.Images[i].URL = ""
|
|
|
|
|
|
request.Images[i].Caption = ""
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Log request details
|
|
|
|
|
|
if requestJSON, err := json.Marshal(request); err == nil {
|
|
|
|
|
|
logger.Infof(ctx, "[%s] Request: session_id=%s, request=%s",
|
2026-03-11 09:17:32 +00:00
|
|
|
|
logPrefix, sessionID, secutils.SanitizeForLog(secutils.CompactImageDataURLForLog(string(requestJSON))))
|
2025-12-24 02:34:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-20 11:27:25 +00:00
|
|
|
|
// Get session. QA writes new messages into the session, so use the strict
|
|
|
|
|
|
// owner scope: a tenant admin may read an API-key session but must not be
|
|
|
|
|
|
// able to post messages to it (which would otherwise fail later at message
|
|
|
|
|
|
// creation with a 500 instead of a clean not-found).
|
|
|
|
|
|
session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
|
2025-12-24 02:34:41 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
|
|
|
|
|
|
return nil, nil, errors.NewNotFoundError("Session not found")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-04 12:12:29 +00:00
|
|
|
|
// Get custom agent if agent_id is provided. Backend resolves shared agent from share relation (no client-provided tenant).
|
2026-07-30 04:10:31 +00:00
|
|
|
|
customAgent, effectiveTenantID, sharedAgentReadOnly := h.resolveAgent(ctx, c, request.AgentID, request.AgentSourceTenantID)
|
|
|
|
|
|
if request.AgentSourceTenantID != 0 && customAgent == nil {
|
|
|
|
|
|
return nil, nil, errors.NewNotFoundError("Shared agent not found")
|
|
|
|
|
|
}
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
2026-03-15 14:12:45 +00:00
|
|
|
|
// Merge @mentioned items into knowledge_base_ids and knowledge_ids
|
|
|
|
|
|
kbIDs, knowledgeIDs := mergeKnowledgeTargets(request.KnowledgeBaseIDs, request.KnowledgeIds, request.MentionedItems)
|
2026-07-06 05:23:55 +00:00
|
|
|
|
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil {
|
2026-07-05 02:25:37 +00:00
|
|
|
|
return nil, nil, err
|
|
|
|
|
|
}
|
2026-01-30 08:28:01 +00:00
|
|
|
|
|
2026-05-20 16:08:33 +00:00
|
|
|
|
// The built-in wiki fixer is invoked from a KB page, not from a tenant's
|
|
|
|
|
|
// regular agent picker. When the KB is shared, run it in the source tenant
|
|
|
|
|
|
// only if the caller has edit permission, so KB-scoped models/tools resolve
|
|
|
|
|
|
// without granting viewers write capability.
|
|
|
|
|
|
if customAgent != nil && customAgent.ID == types.BuiltinWikiFixerID {
|
|
|
|
|
|
if scopedAgent, scopedTenantID := h.resolveWikiFixerTenantScope(
|
|
|
|
|
|
ctx,
|
|
|
|
|
|
customAgent,
|
|
|
|
|
|
c.GetUint64(types.TenantIDContextKey.String()),
|
|
|
|
|
|
types.TenantRoleFromContext(ctx),
|
|
|
|
|
|
kbIDs,
|
|
|
|
|
|
); scopedTenantID != 0 {
|
|
|
|
|
|
customAgent = scopedAgent
|
|
|
|
|
|
effectiveTenantID = scopedTenantID
|
2026-07-30 04:10:31 +00:00
|
|
|
|
sharedAgentReadOnly = false
|
2026-05-20 16:08:33 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-30 08:28:01 +00:00
|
|
|
|
// Log merge results for debugging
|
|
|
|
|
|
logger.Infof(ctx, "[%s] @mention merge: request.KnowledgeBaseIDs=%v, request.MentionedItems=%d, merged kbIDs=%v, merged knowledgeIDs=%v",
|
|
|
|
|
|
logPrefix, request.KnowledgeBaseIDs, len(request.MentionedItems), kbIDs, knowledgeIDs)
|
|
|
|
|
|
|
2026-03-11 09:17:32 +00:00
|
|
|
|
// Process inline base64 images: decode and save to storage.
|
|
|
|
|
|
// VLM analysis for RAG paths is deferred to the pipeline rewrite step.
|
|
|
|
|
|
// For pure chat paths with non-vision models, VLM analysis runs here as fallback.
|
|
|
|
|
|
if len(request.Images) > 0 {
|
|
|
|
|
|
if customAgent == nil || !customAgent.Config.ImageUploadEnabled {
|
|
|
|
|
|
logger.Warnf(ctx, "[%s] Image upload is not enabled for this agent, rejecting %d images", logPrefix, len(request.Images))
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError("Image upload is not enabled for this agent")
|
|
|
|
|
|
}
|
|
|
|
|
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
|
|
|
|
|
agentStorageProvider := customAgent.Config.ImageStorageProvider
|
|
|
|
|
|
if err := h.saveImageAttachments(ctx, request.Images, tenantID, agentStorageProvider); err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "[%s] Failed to save images: %v", logPrefix, err)
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(fmt.Sprintf("Image save failed: %v", err))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-11 13:16:23 +00:00
|
|
|
|
// VLM analysis is always deferred to after SSE stream is up:
|
|
|
|
|
|
// - Agent mode: runs in async execution flow with tool_call/tool_result events
|
|
|
|
|
|
// - Normal RAG mode: runs in the pipeline rewrite step with progress events
|
|
|
|
|
|
// - Normal pure-chat mode: runs in the async goroutine with progress events
|
2026-03-11 09:17:32 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-10 04:49:20 +00:00
|
|
|
|
// Process file attachments: decode and save to storage, extract content
|
|
|
|
|
|
var processedAttachments types.MessageAttachments
|
|
|
|
|
|
if len(request.AttachmentUploads) > 0 {
|
|
|
|
|
|
logger.Infof(ctx, "[%s] processing %d attachment(s)", logPrefix, len(request.AttachmentUploads))
|
|
|
|
|
|
|
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
|
|
|
|
// Decode first and validate actual bytes. Client-declared file_size is
|
|
|
|
|
|
// metadata only and must not be trusted for memory or sandbox limits.
|
|
|
|
|
|
maxSize := secutils.GetMaxFileSize()
|
|
|
|
|
|
decodedAttachments, decodeErr := decodeAndValidateAttachmentUploads(
|
|
|
|
|
|
request.AttachmentUploads,
|
|
|
|
|
|
maxAttachmentUploadsPerRequest,
|
|
|
|
|
|
maxSize,
|
|
|
|
|
|
maxAttachmentUploadTotalBytes,
|
|
|
|
|
|
)
|
|
|
|
|
|
if decodeErr != nil {
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(decodeErr.Error())
|
2026-04-10 04:49:20 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
2026-07-30 04:10:31 +00:00
|
|
|
|
attachmentRuntimeCtx := ctx
|
|
|
|
|
|
if effectiveTenantID != 0 {
|
|
|
|
|
|
attachmentRuntimeCtx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
|
|
|
|
|
}
|
2026-04-10 04:49:20 +00:00
|
|
|
|
|
|
|
|
|
|
// Use ASR only when the agent has audio upload enabled.
|
|
|
|
|
|
asrModelID := ""
|
|
|
|
|
|
if customAgent != nil && customAgent.Config.AudioUploadEnabled && customAgent.Config.ASRModelID != "" {
|
|
|
|
|
|
asrModelID = customAgent.Config.ASRModelID
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-09 08:23:36 +00:00
|
|
|
|
// Resolve the agent's chat parser engine from attachment file types
|
|
|
|
|
|
if customAgent != nil {
|
|
|
|
|
|
for _, att := range request.AttachmentUploads {
|
|
|
|
|
|
ext := strings.ToLower(filepath.Ext(att.FileName))
|
|
|
|
|
|
if engine := customAgent.Config.ResolveChatParserEngine(ext); engine != "" {
|
|
|
|
|
|
attachmentRuntimeCtx = context.WithValue(attachmentRuntimeCtx, types.ChatParserEngineContextKey, engine)
|
|
|
|
|
|
break
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-10 04:49:20 +00:00
|
|
|
|
// Process all attachments concurrently.
|
|
|
|
|
|
processedAttachments = make(types.MessageAttachments, len(request.AttachmentUploads))
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
|
errChan := make(chan error, len(request.AttachmentUploads))
|
|
|
|
|
|
|
|
|
|
|
|
for i, upload := range request.AttachmentUploads {
|
|
|
|
|
|
wg.Add(1)
|
|
|
|
|
|
go func(idx int, att AttachmentUpload) {
|
|
|
|
|
|
defer wg.Done()
|
|
|
|
|
|
|
|
|
|
|
|
processed, err := h.attachmentProcessor.ProcessAttachment(
|
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
|
|
|
|
attachmentRuntimeCtx, decodedAttachments[idx], att.FileName, int64(len(decodedAttachments[idx])), tenantID, asrModelID,
|
2026-04-10 04:49:20 +00:00
|
|
|
|
)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
errChan <- fmt.Errorf("attachment %d processing failed: %w", idx+1, err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
processedAttachments[idx] = *processed
|
|
|
|
|
|
}(i, upload)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
|
|
close(errChan)
|
|
|
|
|
|
|
|
|
|
|
|
if len(errChan) > 0 {
|
|
|
|
|
|
err := <-errChan
|
|
|
|
|
|
logger.Errorf(ctx, "[%s] attachment processing failed: %v", logPrefix, err)
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(fmt.Sprintf("attachment processing failed: %v", err))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "[%s] all attachments processed", logPrefix)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-16 06:48:20 +00:00
|
|
|
|
// Pre-uploaded documents may still be parsing. Only fetch their metadata
|
|
|
|
|
|
// here (fast, available even while processing) to validate agent file-type
|
|
|
|
|
|
// limits and to record the attachments on the persisted user message. The
|
|
|
|
|
|
// heavy content selection happens after the SSE stream is up, so the send
|
|
|
|
|
|
// is not blocked while parsing finishes (see resolveTemporaryAttachments).
|
|
|
|
|
|
var attachmentIDs []string
|
|
|
|
|
|
var attachmentMetas types.MessageAttachments
|
|
|
|
|
|
if len(request.AttachmentIDs) > 0 {
|
2026-07-16 09:18:08 +00:00
|
|
|
|
normalizedIDs, normErr := normalizeTemporaryAttachmentIDs(request.AttachmentIDs)
|
|
|
|
|
|
if normErr != nil {
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(normErr.Error())
|
|
|
|
|
|
}
|
|
|
|
|
|
tenantID := session.TenantID
|
|
|
|
|
|
attachmentMetas = make(types.MessageAttachments, 0, len(normalizedIDs))
|
|
|
|
|
|
for _, id := range normalizedIDs {
|
2026-07-16 06:48:20 +00:00
|
|
|
|
doc, getErr := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
|
|
|
|
|
|
if getErr != nil || doc == nil {
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(
|
|
|
|
|
|
fmt.Sprintf("attachment %s was not found in this session", secutils.SanitizeForLog(id)))
|
|
|
|
|
|
}
|
|
|
|
|
|
if customAgent != nil && len(customAgent.Config.SupportedFileTypes) > 0 {
|
|
|
|
|
|
ext := strings.TrimPrefix(strings.ToLower(doc.FileType), ".")
|
|
|
|
|
|
if !containsFileType(customAgent.Config.SupportedFileTypes, ext) {
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(
|
|
|
|
|
|
fmt.Sprintf("file type %s is not supported by this agent", ext))
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
attachmentMetas = append(attachmentMetas, types.MessageAttachment{
|
|
|
|
|
|
ID: doc.ID, URL: doc.ResourceRef, FileName: doc.FileName,
|
|
|
|
|
|
FileType: doc.FileType, FileSize: doc.FileSize,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
2026-07-16 09:18:08 +00:00
|
|
|
|
attachmentIDs = normalizedIDs
|
2026-07-16 06:48:20 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-06 15:38:43 +00:00
|
|
|
|
mentionScopes := tagScopesFromMentionedItems(request.MentionedItems)
|
|
|
|
|
|
requestTagIDs := dedupRequestStrings(request.TagIDs)
|
|
|
|
|
|
if err := validateUnscopedTagIDs(orphanTagIDsForScope(requestTagIDs, mentionScopes), secutils.SanitizeForLogArray(kbIDs)); err != nil {
|
|
|
|
|
|
return nil, nil, errors.NewBadRequestError(err.Error())
|
|
|
|
|
|
}
|
|
|
|
|
|
tagScopes := mergeTagScopesFromRequestIDs(mentionScopes, requestTagIDs, secutils.SanitizeForLogArray(kbIDs))
|
2026-06-29 08:01:58 +00:00
|
|
|
|
tagIDs := dedupRequestStrings(append(request.TagIDs, mentionedIDsByType(request.MentionedItems, "tag")...))
|
|
|
|
|
|
mcpServiceIDs := dedupRequestStrings(append(request.MCPServiceIDs, mentionedIDsByType(request.MentionedItems, "mcp")...))
|
|
|
|
|
|
skillNames := dedupRequestStrings(append(request.SkillNames, mentionedIDsByType(request.MentionedItems, "skill")...))
|
2026-07-14 03:06:13 +00:00
|
|
|
|
executionContext, agentID, agentTenantID, modelID := buildMessageExecutionContext(
|
|
|
|
|
|
ctx,
|
|
|
|
|
|
customAgent,
|
|
|
|
|
|
effectiveTenantID,
|
|
|
|
|
|
request.SummaryModelID,
|
|
|
|
|
|
secutils.SanitizeForLogArray(kbIDs),
|
|
|
|
|
|
secutils.SanitizeForLogArray(knowledgeIDs),
|
|
|
|
|
|
secutils.SanitizeForLogArray(tagIDs),
|
2026-07-17 02:16:58 +00:00
|
|
|
|
tagScopes,
|
2026-07-14 03:06:13 +00:00
|
|
|
|
secutils.SanitizeForLogArray(mcpServiceIDs),
|
|
|
|
|
|
secutils.SanitizeForLogArray(skillNames),
|
|
|
|
|
|
request.WebSearchEnabled,
|
|
|
|
|
|
)
|
2026-06-29 08:01:58 +00:00
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Build request context
|
|
|
|
|
|
reqCtx := &qaRequestContext{
|
|
|
|
|
|
ctx: ctx,
|
|
|
|
|
|
c: c,
|
|
|
|
|
|
sessionID: sessionID,
|
2026-05-12 13:12:03 +00:00
|
|
|
|
requestID: requestID,
|
|
|
|
|
|
receivedAt: receivedAt,
|
2026-05-22 06:56:51 +00:00
|
|
|
|
query: request.Query,
|
2025-12-24 02:34:41 +00:00
|
|
|
|
session: session,
|
|
|
|
|
|
customAgent: customAgent,
|
|
|
|
|
|
assistantMessage: &types.Message{
|
2026-07-14 03:06:13 +00:00
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Role: "assistant",
|
|
|
|
|
|
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
|
|
|
|
|
IsCompleted: false,
|
|
|
|
|
|
Channel: request.Channel,
|
|
|
|
|
|
AgentID: agentID,
|
|
|
|
|
|
AgentTenantID: agentTenantID,
|
|
|
|
|
|
ModelID: modelID,
|
|
|
|
|
|
ExecutionContext: executionContext,
|
2025-12-24 02:34:41 +00:00
|
|
|
|
},
|
2026-07-14 03:06:13 +00:00
|
|
|
|
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
|
|
|
|
|
|
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
|
|
|
|
|
|
tagScopes: tagScopes,
|
|
|
|
|
|
tagIDs: secutils.SanitizeForLogArray(tagIDs),
|
|
|
|
|
|
mcpServiceIDs: secutils.SanitizeForLogArray(mcpServiceIDs),
|
|
|
|
|
|
skillNames: secutils.SanitizeForLogArray(skillNames),
|
|
|
|
|
|
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
|
|
|
|
|
webSearchEnabled: request.WebSearchEnabled,
|
|
|
|
|
|
mentionedItems: convertMentionedItems(request.MentionedItems),
|
|
|
|
|
|
effectiveTenantID: effectiveTenantID,
|
2026-07-30 04:10:31 +00:00
|
|
|
|
sharedAgentReadOnly: sharedAgentReadOnly,
|
2026-07-14 03:06:13 +00:00
|
|
|
|
images: request.Images,
|
|
|
|
|
|
channel: request.Channel,
|
|
|
|
|
|
attachments: processedAttachments,
|
2026-07-16 06:48:20 +00:00
|
|
|
|
attachmentIDs: attachmentIDs,
|
|
|
|
|
|
attachmentMetas: attachmentMetas,
|
2026-07-14 03:06:13 +00:00
|
|
|
|
suggestionAttribution: request.SuggestionAttribution,
|
|
|
|
|
|
reqAgentEnabled: request.AgentEnabled,
|
|
|
|
|
|
reqAgentID: request.AgentID,
|
2026-08-04 09:14:52 +00:00
|
|
|
|
resourceRewriter: resourceRewriter,
|
2025-12-24 02:34:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return reqCtx, &request, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
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
|
|
|
|
func decodeAndValidateAttachmentUploads(
|
|
|
|
|
|
uploads []AttachmentUpload,
|
|
|
|
|
|
maxCount int,
|
|
|
|
|
|
maxFileBytes, maxTotalBytes int64,
|
|
|
|
|
|
) ([][]byte, error) {
|
|
|
|
|
|
if len(uploads) > maxCount {
|
|
|
|
|
|
return nil, fmt.Errorf("at most %d attachments are allowed per request", maxCount)
|
|
|
|
|
|
}
|
|
|
|
|
|
decoded := make([][]byte, len(uploads))
|
|
|
|
|
|
var total int64
|
|
|
|
|
|
for i, upload := range uploads {
|
|
|
|
|
|
data, err := DecodeBase64Attachment(upload.Data)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("attachment %d decode failed: %w", i+1, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
actualSize := int64(len(data))
|
|
|
|
|
|
if actualSize > maxFileBytes {
|
|
|
|
|
|
return nil, fmt.Errorf("attachment %d exceeds size limit of %d bytes", i+1, maxFileBytes)
|
|
|
|
|
|
}
|
|
|
|
|
|
total += actualSize
|
|
|
|
|
|
if total > maxTotalBytes {
|
|
|
|
|
|
return nil, fmt.Errorf("attachments exceed total request limit of %d bytes", maxTotalBytes)
|
|
|
|
|
|
}
|
|
|
|
|
|
decoded[i] = data
|
|
|
|
|
|
}
|
|
|
|
|
|
return decoded, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-14 03:06:13 +00:00
|
|
|
|
func buildMessageExecutionContext(
|
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
|
agent *types.CustomAgent,
|
|
|
|
|
|
effectiveTenantID uint64,
|
|
|
|
|
|
modelOverride string,
|
|
|
|
|
|
knowledgeBaseIDs []string,
|
|
|
|
|
|
knowledgeIDs []string,
|
|
|
|
|
|
tagIDs []string,
|
2026-07-17 02:16:58 +00:00
|
|
|
|
tagScopes []types.TagScope,
|
2026-07-14 03:06:13 +00:00
|
|
|
|
mcpServiceIDs []string,
|
|
|
|
|
|
skillNames []string,
|
|
|
|
|
|
webSearchEnabled bool,
|
|
|
|
|
|
) (types.MessageExecutionContext, string, uint64, string) {
|
2026-08-05 07:24:10 +00:00
|
|
|
|
locale := types.LanguageFromContextOrDefault(ctx)
|
2026-07-14 03:06:13 +00:00
|
|
|
|
|
|
|
|
|
|
snapshot := types.MessageExecutionContext{
|
|
|
|
|
|
KnowledgeBaseIDs: knowledgeBaseIDs,
|
|
|
|
|
|
KnowledgeIDs: knowledgeIDs,
|
|
|
|
|
|
TagIDs: tagIDs,
|
2026-07-17 02:16:58 +00:00
|
|
|
|
TagScopes: cloneTagScopes(tagScopes),
|
2026-07-14 03:06:13 +00:00
|
|
|
|
MCPServiceIDs: mcpServiceIDs,
|
|
|
|
|
|
SkillNames: skillNames,
|
|
|
|
|
|
WebSearchEnabled: webSearchEnabled,
|
|
|
|
|
|
Locale: locale,
|
|
|
|
|
|
}
|
|
|
|
|
|
if agent == nil {
|
|
|
|
|
|
return snapshot, "", effectiveTenantID, modelOverride
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
modelID := modelOverride
|
|
|
|
|
|
if modelID == "" {
|
|
|
|
|
|
modelID = agent.Config.ModelID
|
|
|
|
|
|
}
|
|
|
|
|
|
agentTenantID := effectiveTenantID
|
|
|
|
|
|
if agentTenantID == 0 {
|
|
|
|
|
|
agentTenantID = agent.TenantID
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Marshal/unmarshal gives the snapshot independent backing slices, so a
|
|
|
|
|
|
// later agent edit cannot mutate an in-flight message context.
|
|
|
|
|
|
if agent.Config.QuestionSuggestions != nil {
|
|
|
|
|
|
if encoded, err := json.Marshal(agent.Config.QuestionSuggestions); err == nil {
|
|
|
|
|
|
var suggestions types.QuestionSuggestionConfig
|
|
|
|
|
|
if json.Unmarshal(encoded, &suggestions) == nil {
|
|
|
|
|
|
snapshot.QuestionSuggestions = &suggestions
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
hashInput := struct {
|
|
|
|
|
|
QuestionSuggestions *types.QuestionSuggestionConfig `json:"question_suggestions,omitempty"`
|
|
|
|
|
|
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
|
|
|
|
|
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
|
|
|
|
|
TagIDs []string `json:"tag_ids,omitempty"`
|
2026-07-17 02:16:58 +00:00
|
|
|
|
TagScopes []types.TagScope `json:"tag_scopes,omitempty"`
|
2026-07-14 03:06:13 +00:00
|
|
|
|
ModelID string `json:"model_id,omitempty"`
|
|
|
|
|
|
}{
|
|
|
|
|
|
QuestionSuggestions: snapshot.QuestionSuggestions,
|
|
|
|
|
|
KnowledgeBaseIDs: knowledgeBaseIDs,
|
|
|
|
|
|
KnowledgeIDs: knowledgeIDs,
|
|
|
|
|
|
TagIDs: tagIDs,
|
2026-07-17 02:16:58 +00:00
|
|
|
|
TagScopes: snapshot.TagScopes,
|
2026-07-14 03:06:13 +00:00
|
|
|
|
ModelID: modelID,
|
|
|
|
|
|
}
|
|
|
|
|
|
if encoded, err := json.Marshal(hashInput); err == nil {
|
|
|
|
|
|
hash := sha256.Sum256(encoded)
|
|
|
|
|
|
snapshot.AgentConfigHash = fmt.Sprintf("%x", hash[:])
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return snapshot, agent.ID, agentTenantID, modelID
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-17 02:16:58 +00:00
|
|
|
|
func cloneTagScopes(scopes []types.TagScope) []types.TagScope {
|
|
|
|
|
|
if len(scopes) == 0 {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
cloned := make([]types.TagScope, 0, len(scopes))
|
|
|
|
|
|
for _, scope := range scopes {
|
|
|
|
|
|
if scope.KnowledgeBaseID == "" || len(scope.TagIDs) == 0 {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
cloned = append(cloned, types.TagScope{
|
|
|
|
|
|
KnowledgeBaseID: scope.KnowledgeBaseID,
|
|
|
|
|
|
TagIDs: append([]string(nil), scope.TagIDs...),
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
return cloned
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-15 14:12:45 +00:00
|
|
|
|
// resolveAgent resolves the custom agent by ID, trying shared agent first, then own agent.
|
|
|
|
|
|
// Returns (nil, 0) if agentID is empty or not found.
|
2026-07-30 04:10:31 +00:00
|
|
|
|
func (h *Handler) resolveAgent(
|
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
|
c *gin.Context,
|
|
|
|
|
|
agentID string,
|
|
|
|
|
|
sourceTenantID uint64,
|
|
|
|
|
|
) (*types.CustomAgent, uint64, bool) {
|
2026-03-15 14:12:45 +00:00
|
|
|
|
if agentID == "" {
|
2026-07-30 04:10:31 +00:00
|
|
|
|
return nil, 0, false
|
2026-03-15 14:12:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Resolving agent, agent ID: %s", secutils.SanitizeForLog(agentID))
|
|
|
|
|
|
|
|
|
|
|
|
// Try shared agent first
|
|
|
|
|
|
var customAgent *types.CustomAgent
|
|
|
|
|
|
var effectiveTenantID uint64
|
2026-07-30 04:10:31 +00:00
|
|
|
|
var sharedAgentReadOnly bool
|
2026-03-15 14:12:45 +00:00
|
|
|
|
userIDVal, _ := c.Get(types.UserIDContextKey.String())
|
|
|
|
|
|
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
|
|
|
|
|
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
|
feat(rbac): lift org membership from per-user to per-tenant (Plan 3, #1303)
Before this change, the `organization_members` table keyed on user_id —
joining an org as a Viewer in tenant T meant only that one user got
visibility on shared KBs/agents, while the rest of T (including its
Owner) saw nothing. The mismatch surfaced as confusing UX bugs:
"my colleague shared this with us, why can't I see it?"
This change replaces `organization_members` with
`organization_tenant_members`. Membership and Org-RBAC role now key on
(org_id, tenant_id); `representative_user_id` stays as a display-only
label of the user who first brought the tenant in.
Permission resolution gains a 3-D cap so tenant-RBAC stays honest under
cross-tenant sharing:
effective = min(share.Permission, tenant_org_role, tenant_role_cap)
where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless
of the org-level grant. A Viewer in their own tenant cannot edit a
shared KB even if the org granted Editor — preserves the
"Viewer = read-only everywhere" promise.
Migration 000045 backfills `organization_tenant_members` from the old
table by collapsing each (org, tenant) group to its max role, then
renames the old table to `organization_members_pre_plan3` for safe
rollback. Sqlite mirror (Lite mode) is fresh-bootstrap: the init
schema replaces the old table directly.
Routes: member-management URLs change from `:user_id` to `:tenant_id`.
Org create / join / leave now require Admin+ in the caller's tenant —
joining an Org affects everyone in T, so the decision can't sit with
a Viewer.
Frontend: OrganizationSettingsModal + store update to address members
by tenant_id.
2026-05-15 13:49:54 +00:00
|
|
|
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
2026-07-30 04:10:31 +00:00
|
|
|
|
var agent *types.CustomAgent
|
|
|
|
|
|
var err error
|
|
|
|
|
|
agent, err = h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID, sourceTenantID)
|
2026-03-15 14:12:45 +00:00
|
|
|
|
if err == nil && agent != nil {
|
|
|
|
|
|
effectiveTenantID = agent.TenantID
|
|
|
|
|
|
customAgent = agent
|
2026-07-30 04:10:31 +00:00
|
|
|
|
sharedAgentReadOnly = true
|
2026-03-15 14:12:45 +00:00
|
|
|
|
logger.Infof(ctx, "Using shared agent: ID=%s, Name=%s, effectiveTenantID=%d (retrieval scope)",
|
|
|
|
|
|
customAgent.ID, customAgent.Name, effectiveTenantID)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-30 04:10:31 +00:00
|
|
|
|
// Fall back to an own agent only when no source workspace was requested.
|
|
|
|
|
|
// A rejected shared selector must not silently run a same-ID local builtin.
|
|
|
|
|
|
if customAgent == nil && sourceTenantID == 0 {
|
2026-03-15 14:12:45 +00:00
|
|
|
|
agent, err := h.customAgentService.GetAgentByID(ctx, agentID)
|
|
|
|
|
|
if err == nil {
|
|
|
|
|
|
customAgent = agent
|
|
|
|
|
|
logger.Infof(ctx, "Using own agent: ID=%s, Name=%s, AgentMode=%s",
|
|
|
|
|
|
customAgent.ID, customAgent.Name, customAgent.Config.AgentMode)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
|
|
|
|
|
|
secutils.SanitizeForLog(agentID), err)
|
|
|
|
|
|
}
|
2026-07-30 04:26:25 +00:00
|
|
|
|
} else if customAgent != nil {
|
2026-03-15 14:12:45 +00:00
|
|
|
|
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
|
|
|
|
|
|
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode, effectiveTenantID)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-30 04:10:31 +00:00
|
|
|
|
return customAgent, effectiveTenantID, sharedAgentReadOnly
|
2026-03-15 14:12:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// mergeKnowledgeTargets merges request KB/knowledge IDs with @mentioned items into deduplicated slices.
|
|
|
|
|
|
func mergeKnowledgeTargets(requestKBIDs []string, requestKnowledgeIDs []string, mentionedItems []MentionedItemRequest) (kbIDs []string, knowledgeIDs []string) {
|
|
|
|
|
|
kbIDSet := make(map[string]bool)
|
|
|
|
|
|
kbIDs = make([]string, 0, len(requestKBIDs)+len(mentionedItems))
|
|
|
|
|
|
for _, id := range requestKBIDs {
|
|
|
|
|
|
if id != "" && !kbIDSet[id] {
|
|
|
|
|
|
kbIDs = append(kbIDs, id)
|
|
|
|
|
|
kbIDSet[id] = true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
knowledgeIDSet := make(map[string]bool)
|
|
|
|
|
|
knowledgeIDs = make([]string, 0, len(requestKnowledgeIDs)+len(mentionedItems))
|
|
|
|
|
|
for _, id := range requestKnowledgeIDs {
|
|
|
|
|
|
if id != "" && !knowledgeIDSet[id] {
|
|
|
|
|
|
knowledgeIDs = append(knowledgeIDs, id)
|
|
|
|
|
|
knowledgeIDSet[id] = true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for _, item := range mentionedItems {
|
|
|
|
|
|
if item.ID == "" {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
switch item.Type {
|
|
|
|
|
|
case "kb":
|
|
|
|
|
|
if !kbIDSet[item.ID] {
|
|
|
|
|
|
kbIDs = append(kbIDs, item.ID)
|
|
|
|
|
|
kbIDSet[item.ID] = true
|
|
|
|
|
|
}
|
|
|
|
|
|
case "file":
|
|
|
|
|
|
if !knowledgeIDSet[item.ID] {
|
|
|
|
|
|
knowledgeIDs = append(knowledgeIDs, item.ID)
|
|
|
|
|
|
knowledgeIDSet[item.ID] = true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return kbIDs, knowledgeIDs
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// sseStreamContext holds the context for SSE streaming
|
|
|
|
|
|
type sseStreamContext struct {
|
|
|
|
|
|
eventBus *event.EventBus
|
|
|
|
|
|
asyncCtx context.Context
|
|
|
|
|
|
cancel context.CancelFunc
|
|
|
|
|
|
assistantMessage *types.Message
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// setupSSEStream sets up the SSE streaming context
|
2025-12-31 05:59:38 +00:00
|
|
|
|
func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool) *sseStreamContext {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Set SSE headers
|
|
|
|
|
|
setSSEHeaders(reqCtx.c)
|
|
|
|
|
|
|
|
|
|
|
|
// Write initial agent_query event
|
|
|
|
|
|
h.writeAgentQueryEvent(reqCtx.ctx, reqCtx.sessionID, reqCtx.assistantMessage.ID)
|
|
|
|
|
|
|
2026-02-04 12:12:29 +00:00
|
|
|
|
// Base context for async work: when using shared agent, use source tenant for model/KB/MCP resolution
|
|
|
|
|
|
baseCtx := reqCtx.ctx
|
|
|
|
|
|
if reqCtx.effectiveTenantID != 0 && h.tenantService != nil {
|
|
|
|
|
|
if tenant, err := h.tenantService.GetTenantByID(reqCtx.ctx, reqCtx.effectiveTenantID); err == nil && tenant != nil {
|
|
|
|
|
|
baseCtx = context.WithValue(context.WithValue(reqCtx.ctx, types.TenantIDContextKey, reqCtx.effectiveTenantID), types.TenantInfoContextKey, tenant)
|
|
|
|
|
|
logger.Infof(reqCtx.ctx, "Using effective tenant %d for shared agent (model/KB/MCP)", reqCtx.effectiveTenantID)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
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
|
|
|
|
// The session's sandbox stays bound to the session owner even when the
|
|
|
|
|
|
// borrowed tenant above drives everything else, because DeleteSession tears
|
|
|
|
|
|
// that sandbox down from a request that only knows the session's tenant.
|
|
|
|
|
|
baseCtx = types.WithSandboxTenantID(baseCtx, reqCtx.session.TenantID)
|
2026-02-04 12:12:29 +00:00
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Create EventBus and cancellable context
|
|
|
|
|
|
eventBus := event.NewEventBus()
|
2026-02-04 12:12:29 +00:00
|
|
|
|
asyncCtx, cancel := context.WithCancel(logger.CloneContext(baseCtx))
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
|
|
|
|
|
streamCtx := &sseStreamContext{
|
|
|
|
|
|
eventBus: eventBus,
|
|
|
|
|
|
asyncCtx: asyncCtx,
|
|
|
|
|
|
cancel: cancel,
|
|
|
|
|
|
assistantMessage: reqCtx.assistantMessage,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Setup stop event handler
|
2026-02-05 09:10:20 +00:00
|
|
|
|
h.setupStopEventHandler(eventBus, reqCtx.sessionID, reqCtx.session.TenantID, reqCtx.assistantMessage, cancel)
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
2026-06-02 11:40:02 +00:00
|
|
|
|
// Watch for stop events independently of the client SSE connection so a
|
|
|
|
|
|
// user-requested stop reliably cancels generation even when the client
|
|
|
|
|
|
// has already disconnected (e.g. API-Key callers that close the stream
|
|
|
|
|
|
// before POSTing /stop). The watcher self-terminates on a terminal stream
|
|
|
|
|
|
// event, so its lifetime is decoupled from when the QA service call
|
|
|
|
|
|
// returns (KnowledgeQA returns immediately while streaming continues in a
|
|
|
|
|
|
// background goroutine, whereas AgentQA blocks until done). Use a
|
|
|
|
|
|
// connection-independent context derived from baseCtx so it survives the
|
|
|
|
|
|
// client disconnect.
|
|
|
|
|
|
h.startStopWatcher(logger.CloneContext(baseCtx), reqCtx.sessionID, reqCtx.assistantMessage.ID, eventBus)
|
|
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Setup stream handler
|
|
|
|
|
|
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
|
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
|
|
|
|
reqCtx.requestID, reqCtx.session.TenantID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus)
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
|
|
|
|
|
// Generate title if needed
|
2025-12-31 05:59:38 +00:00
|
|
|
|
if generateTitle && reqCtx.session.Title == "" {
|
2025-12-29 06:35:13 +00:00
|
|
|
|
// Use the same model as the conversation for title generation
|
|
|
|
|
|
modelID := ""
|
|
|
|
|
|
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ModelID != "" {
|
|
|
|
|
|
modelID = reqCtx.customAgent.Config.ModelID
|
|
|
|
|
|
}
|
|
|
|
|
|
logger.Infof(reqCtx.ctx, "Session has no title, starting async title generation, session ID: %s, model: %s", reqCtx.sessionID, modelID)
|
|
|
|
|
|
h.sessionService.GenerateTitleAsync(asyncCtx, reqCtx.session, reqCtx.query, modelID, eventBus)
|
2025-12-24 02:34:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return streamCtx
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// SearchKnowledge godoc
|
|
|
|
|
|
// @Summary 知识搜索
|
|
|
|
|
|
// @Description 在知识库中搜索(不使用LLM总结)
|
|
|
|
|
|
// @Tags 问答
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param request body SearchKnowledgeRequest true "搜索请求"
|
2026-08-04 09:29:27 +00:00
|
|
|
|
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Success 200 {object} map[string]interface{} "搜索结果"
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
|
|
|
|
|
// @Security Bearer
|
2025-12-22 06:36:29 +00:00
|
|
|
|
// @Security ApiKeyAuth
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Router /sessions/search [post]
|
2025-11-08 16:02:31 +00:00
|
|
|
|
func (h *Handler) SearchKnowledge(c *gin.Context) {
|
|
|
|
|
|
ctx := logger.CloneContext(c.Request.Context())
|
|
|
|
|
|
logger.Info(ctx, "Start processing knowledge search request")
|
|
|
|
|
|
|
|
|
|
|
|
// Parse request body
|
|
|
|
|
|
var request SearchKnowledgeRequest
|
|
|
|
|
|
if err := c.ShouldBindJSON(&request); err != nil {
|
|
|
|
|
|
logger.Error(ctx, "Failed to parse request data", err)
|
|
|
|
|
|
c.Error(errors.NewBadRequestError(err.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Validate request parameters
|
|
|
|
|
|
if request.Query == "" {
|
|
|
|
|
|
logger.Error(ctx, "Query content is empty")
|
|
|
|
|
|
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
fix(api): close the resource_urls=public gaps found in review
Follow-up on resource_urls=public. Review turned up one authorization gap plus a
set of correctness problems in the streaming path.
Authorization:
- Embed channels were documented as excluded, but nothing enforced it. The
delegating handlers hand the visitor's own gin context to the shared
handlers, so ?resource_urls=public — and a deployment-wide
RESOURCE_URL_MODE=public — reached anonymous traffic and produced
shareable, credential-free URLs that bypass the channel-scoped
/embed/:channel_id/files proxy. ensureEmbedSession now pins the request
context to handle mode, which covers every delegated endpoint including
future ones. The downgrade is silent so a client that forwards the
parameter keeps working.
- A knowledge-base-restricted API key is refused with 403. Such a key is
already denied /files because a raw storage path cannot be bound to its
allow-list, so handing it anonymous file URLs would reopen that hole from
the other side. The default handle mode stays available to it.
Streaming:
- Rewriter.ref holds its lock across resolution. Resolver implementations keep
an unsynchronised per-provider cache, so the previous unlocked window was a
real data race for any caller sharing a StreamRewriter between goroutines —
which its own doc comment invited. Serialising also collapses a concurrent
duplicate into one signature.
- Release the holdback buffer on every path that ends a stream while the
client is still connected: a user-requested stop, an error event, and
giving up on the event store. Only completion flushed before, so the tail
generated just before a stop was silently dropped.
- A released tail carries the metadata of the event it was cut from instead of
a bare event_id.
- The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting
a character in half, and an unclosed "
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Warnf(ctx, "Rejected resource URL mode: %v", err)
|
|
|
|
|
|
_ = c.Error(err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-24 03:23:20 +00:00
|
|
|
|
// Merge single knowledge_base_id into knowledge_base_ids for backward compatibility
|
|
|
|
|
|
knowledgeBaseIDs := request.KnowledgeBaseIDs
|
|
|
|
|
|
if request.KnowledgeBaseID != "" {
|
|
|
|
|
|
// Check if it's already in the list to avoid duplicates
|
|
|
|
|
|
found := false
|
|
|
|
|
|
for _, id := range knowledgeBaseIDs {
|
|
|
|
|
|
if id == request.KnowledgeBaseID {
|
|
|
|
|
|
found = true
|
|
|
|
|
|
break
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if !found {
|
|
|
|
|
|
knowledgeBaseIDs = append(knowledgeBaseIDs, request.KnowledgeBaseID)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-06 15:38:43 +00:00
|
|
|
|
mentionScopes := tagScopesFromMentionedItems(request.MentionedItems)
|
|
|
|
|
|
requestTagIDs := dedupRequestStrings(request.TagIDs)
|
|
|
|
|
|
if err := validateUnscopedTagIDs(orphanTagIDsForScope(requestTagIDs, mentionScopes), secutils.SanitizeForLogArray(knowledgeBaseIDs)); err != nil {
|
|
|
|
|
|
logger.Error(ctx, err.Error())
|
|
|
|
|
|
c.Error(errors.NewBadRequestError(err.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
tagScopes := mergeTagScopesFromRequestIDs(mentionScopes, requestTagIDs, secutils.SanitizeForLogArray(knowledgeBaseIDs))
|
2026-07-03 02:42:54 +00:00
|
|
|
|
|
|
|
|
|
|
if len(knowledgeBaseIDs) == 0 && len(request.KnowledgeIDs) == 0 && len(tagScopes) == 0 {
|
|
|
|
|
|
logger.Error(ctx, "No knowledge base IDs, knowledge IDs, or tag scopes provided")
|
|
|
|
|
|
c.Error(errors.NewBadRequestError("At least one knowledge_base_id, knowledge_base_ids, knowledge_ids, or scoped tag must be provided"))
|
2025-11-08 16:02:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-07-06 05:23:55 +00:00
|
|
|
|
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, knowledgeBaseIDs, request.KnowledgeIDs); err != nil {
|
2026-07-05 02:25:37 +00:00
|
|
|
|
c.Error(err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
|
|
|
|
|
logger.Infof(
|
|
|
|
|
|
ctx,
|
2026-07-03 02:42:54 +00:00
|
|
|
|
"Knowledge search request, knowledge base IDs: %v, knowledge IDs: %v, tag scopes: %d, query: %s",
|
2025-12-24 03:23:20 +00:00
|
|
|
|
secutils.SanitizeForLogArray(knowledgeBaseIDs),
|
|
|
|
|
|
secutils.SanitizeForLogArray(request.KnowledgeIDs),
|
2026-07-03 02:42:54 +00:00
|
|
|
|
len(tagScopes),
|
2025-11-25 15:33:34 +00:00
|
|
|
|
secutils.SanitizeForLog(request.Query),
|
2025-11-08 16:02:31 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// Directly call knowledge retrieval service without LLM summarization
|
2026-07-03 02:42:54 +00:00
|
|
|
|
searchResults, err := h.sessionService.SearchKnowledge(ctx, knowledgeBaseIDs, request.KnowledgeIDs, tagScopes, request.Query)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.ErrorWithFields(ctx, err, nil)
|
|
|
|
|
|
c.Error(errors.NewInternalServerError(err.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Knowledge search completed, found %d results", len(searchResults))
|
|
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
2026-08-04 09:14:52 +00:00
|
|
|
|
"data": rewriter.CopyReferences(ctx, searchResults),
|
2025-11-08 16:02:31 +00:00
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// KnowledgeQA godoc
|
|
|
|
|
|
// @Summary 知识问答
|
|
|
|
|
|
// @Description 基于知识库的问答(使用LLM总结),支持SSE流式响应
|
|
|
|
|
|
// @Tags 问答
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce text/event-stream
|
|
|
|
|
|
// @Param session_id path string true "会话ID"
|
|
|
|
|
|
// @Param request body CreateKnowledgeQARequest true "问答请求"
|
2026-08-04 09:29:27 +00:00
|
|
|
|
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Success 200 {object} map[string]interface{} "问答结果(SSE流)"
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
|
|
|
|
|
// @Security Bearer
|
2025-12-22 06:36:29 +00:00
|
|
|
|
// @Security ApiKeyAuth
|
2026-08-06 05:38:30 +00:00
|
|
|
|
// @Router /knowledge-chat/{session_id} [post]
|
2025-11-08 16:02:31 +00:00
|
|
|
|
func (h *Handler) KnowledgeQA(c *gin.Context) {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Parse and validate request
|
2025-12-31 05:44:23 +00:00
|
|
|
|
reqCtx, request, err := h.parseQARequest(c, "KnowledgeQA")
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if err != nil {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
c.Error(err)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-31 05:44:23 +00:00
|
|
|
|
// Execute normal mode QA, generate title unless disabled
|
2026-03-15 12:55:25 +00:00
|
|
|
|
h.executeQA(reqCtx, qaModeNormal, !request.DisableTitle)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// AgentQA godoc
|
|
|
|
|
|
// @Summary Agent问答
|
|
|
|
|
|
// @Description 基于Agent的智能问答,支持多轮对话和SSE流式响应
|
|
|
|
|
|
// @Tags 问答
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce text/event-stream
|
|
|
|
|
|
// @Param session_id path string true "会话ID"
|
|
|
|
|
|
// @Param request body CreateKnowledgeQARequest true "问答请求"
|
2026-08-04 09:29:27 +00:00
|
|
|
|
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Success 200 {object} map[string]interface{} "问答结果(SSE流)"
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
|
|
|
|
|
// @Security Bearer
|
2025-12-22 06:36:29 +00:00
|
|
|
|
// @Security ApiKeyAuth
|
2026-08-06 05:38:30 +00:00
|
|
|
|
// @Router /agent-chat/{session_id} [post]
|
2025-11-08 16:02:31 +00:00
|
|
|
|
func (h *Handler) AgentQA(c *gin.Context) {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Parse and validate request
|
|
|
|
|
|
reqCtx, request, err := h.parseQARequest(c, "AgentQA")
|
2025-11-11 14:26:59 +00:00
|
|
|
|
if err != nil {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
c.Error(err)
|
2025-11-11 14:26:59 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Determine if agent mode should be enabled
|
|
|
|
|
|
// Priority: customAgent.IsAgentMode() > request.AgentEnabled
|
|
|
|
|
|
agentModeEnabled := request.AgentEnabled
|
|
|
|
|
|
if reqCtx.customAgent != nil {
|
|
|
|
|
|
agentModeEnabled = reqCtx.customAgent.IsAgentMode()
|
|
|
|
|
|
logger.Infof(reqCtx.ctx, "Agent mode determined by custom agent: %v (config.agent_mode=%s)",
|
|
|
|
|
|
agentModeEnabled, reqCtx.customAgent.Config.AgentMode)
|
2025-11-10 18:47:38 +00:00
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-05-15 04:16:18 +00:00
|
|
|
|
// Sanity gate: agent mode requires a resolved CustomAgent. If we got
|
|
|
|
|
|
// here with agent_enabled=true but agent_id missing/unresolvable, the
|
|
|
|
|
|
// AgentQA service will fail deep inside the async goroutine with a
|
|
|
|
|
|
// generic "custom agent configuration is required" error and the user
|
|
|
|
|
|
// just sees a broken stream. Reject early with a clear 400 so the
|
|
|
|
|
|
// frontend can recover (e.g. fall back to quick-answer). Most likely
|
|
|
|
|
|
// cause is a stale localStorage settings blob where selectedAgentId
|
|
|
|
|
|
// got blanked but isAgentEnabled stayed true — usually after a
|
|
|
|
|
|
// cross-tenant switch where the previously selected agent is no
|
|
|
|
|
|
// longer visible.
|
|
|
|
|
|
if agentModeEnabled && reqCtx.customAgent == nil {
|
|
|
|
|
|
logger.Warnf(reqCtx.ctx,
|
|
|
|
|
|
"Agent mode requested without a resolvable agent_id, rejecting; session=%s, request.AgentID=%q",
|
|
|
|
|
|
reqCtx.sessionID, secutils.SanitizeForLog(request.AgentID))
|
|
|
|
|
|
c.Error(errors.NewBadRequestError(
|
|
|
|
|
|
"agent_id is required when agent mode is enabled"))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Route to appropriate handler based on agent mode
|
|
|
|
|
|
if agentModeEnabled {
|
2026-03-15 12:55:25 +00:00
|
|
|
|
h.executeQA(reqCtx, qaModeAgent, true)
|
2025-12-24 02:34:41 +00:00
|
|
|
|
} else {
|
|
|
|
|
|
logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID)
|
2026-05-18 09:55:33 +00:00
|
|
|
|
h.executeQA(reqCtx, qaModeNormal, !request.DisableTitle)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
2025-12-24 02:34:41 +00:00
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// qaMode determines which QA execution path to use.
|
|
|
|
|
|
type qaMode int
|
|
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
|
qaModeNormal qaMode = iota // KnowledgeQA pipeline (RAG / pure chat)
|
|
|
|
|
|
qaModeAgent // Agent engine with tool calling
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// executeQA is the unified execution flow for both KnowledgeQA and AgentQA modes.
|
|
|
|
|
|
// It handles message creation, SSE setup, VLM analysis, service invocation, and error handling.
|
|
|
|
|
|
func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle bool) {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
ctx := reqCtx.ctx
|
|
|
|
|
|
sessionID := reqCtx.sessionID
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-05-18 14:24:39 +00:00
|
|
|
|
// Persist the input-bar state used for this request so reopening the
|
|
|
|
|
|
// session can rehydrate agent / model / KB / web-search / MCP selections.
|
|
|
|
|
|
// This is a pure UI memo (no behavioural effect) and runs in a goroutine
|
|
|
|
|
|
// to avoid adding a DB round-trip to TTFB. Use WithoutCancel so a fast
|
|
|
|
|
|
// client disconnect doesn't drop the write.
|
|
|
|
|
|
go h.persistLastRequestState(ctx, reqCtx, mode)
|
|
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// Agent mode: emit agent query event before message creation
|
|
|
|
|
|
if mode == qaModeAgent {
|
|
|
|
|
|
if err := event.Emit(ctx, event.Event{
|
|
|
|
|
|
Type: event.EventAgentQuery,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
RequestID: reqCtx.requestID,
|
|
|
|
|
|
Data: event.AgentQueryData{
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Query: reqCtx.query,
|
|
|
|
|
|
RequestID: reqCtx.requestID,
|
|
|
|
|
|
},
|
|
|
|
|
|
}); err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-16 06:48:20 +00:00
|
|
|
|
// Create user message. Include pre-uploaded document metadata so history
|
|
|
|
|
|
// reload shows the attachments even though their content is selected later.
|
|
|
|
|
|
userMessageAttachments := reqCtx.attachments
|
|
|
|
|
|
if len(reqCtx.attachmentMetas) > 0 {
|
|
|
|
|
|
userMessageAttachments = append(append(types.MessageAttachments{}, reqCtx.attachments...), reqCtx.attachmentMetas...)
|
|
|
|
|
|
}
|
|
|
|
|
|
userMsg, err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems, convertImageAttachments(reqCtx.images), userMessageAttachments, reqCtx.channel, reqCtx.suggestionAttribution)
|
2026-03-12 05:17:47 +00:00
|
|
|
|
if err != nil {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
2025-11-08 16:02:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-03-12 05:17:47 +00:00
|
|
|
|
reqCtx.userMessageID = userMsg.ID
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Create assistant message
|
2026-03-15 12:55:25 +00:00
|
|
|
|
assistantMessagePtr, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage)
|
|
|
|
|
|
if err != nil {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
2025-11-08 16:02:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-03-15 12:55:25 +00:00
|
|
|
|
reqCtx.assistantMessage = assistantMessagePtr
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
if mode == qaModeNormal {
|
|
|
|
|
|
logger.Infof(ctx, "Using knowledge bases: %v", reqCtx.knowledgeBaseIDs)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Setup SSE stream
|
2025-12-31 05:59:38 +00:00
|
|
|
|
streamCtx := h.setupSSEStream(reqCtx, generateTitle)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// Normal mode: register completion handler on EventAgentFinalAnswer
|
|
|
|
|
|
// (Agent mode handles completion in the defer block instead)
|
|
|
|
|
|
if mode == qaModeNormal {
|
|
|
|
|
|
var completionHandled bool
|
2026-06-04 14:03:54 +00:00
|
|
|
|
|
|
|
|
|
|
// Persist reasoning_content into agent_steps so historical reload can
|
|
|
|
|
|
// reconstruct the thinking card (same shape as Agent-mode steps).
|
|
|
|
|
|
// Accumulate on assistantMessage directly so user-initiated stop also
|
|
|
|
|
|
// keeps whatever reasoning had streamed before the cancel.
|
|
|
|
|
|
streamCtx.eventBus.On(event.EventAgentThought, func(ctx context.Context, evt event.Event) error {
|
|
|
|
|
|
data, ok := evt.Data.(event.AgentThoughtData)
|
|
|
|
|
|
if !ok || data.Content == "" {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
appendQuickAnswerReasoning(streamCtx.assistantMessage, data.Content)
|
|
|
|
|
|
return nil
|
|
|
|
|
|
})
|
|
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
streamCtx.eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
|
|
|
|
|
|
data, ok := evt.Data.(event.AgentFinalAnswerData)
|
|
|
|
|
|
if !ok {
|
2026-01-20 08:20:43 +00:00
|
|
|
|
return nil
|
|
|
|
|
|
}
|
2026-03-15 12:55:25 +00:00
|
|
|
|
streamCtx.assistantMessage.Content += data.Content
|
|
|
|
|
|
if data.IsFallback {
|
|
|
|
|
|
streamCtx.assistantMessage.IsFallback = true
|
|
|
|
|
|
}
|
|
|
|
|
|
if data.Done {
|
|
|
|
|
|
if completionHandled {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
completionHandled = true
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(streamCtx.asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
|
|
|
|
|
|
updateCtx := context.WithValue(streamCtx.asyncCtx, types.TenantIDContextKey, reqCtx.session.TenantID)
|
|
|
|
|
|
h.completeAssistantMessage(updateCtx, streamCtx.assistantMessage, reqCtx.query)
|
|
|
|
|
|
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
|
|
|
|
|
Type: event.EventAgentComplete,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Data: event.AgentCompleteData{FinalAnswer: streamCtx.assistantMessage.Content},
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
return nil
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// Execute QA asynchronously
|
2025-11-08 16:02:31 +00:00
|
|
|
|
go func() {
|
|
|
|
|
|
defer func() {
|
|
|
|
|
|
if r := recover(); r != nil {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
buf := make([]byte, 10240)
|
2025-11-11 06:25:20 +00:00
|
|
|
|
runtime.Stack(buf, true)
|
2026-03-15 12:55:25 +00:00
|
|
|
|
stageName := "Knowledge QA"
|
|
|
|
|
|
if mode == qaModeAgent {
|
|
|
|
|
|
stageName = "Agent QA"
|
|
|
|
|
|
}
|
2025-12-24 02:34:41 +00:00
|
|
|
|
logger.ErrorWithFields(streamCtx.asyncCtx,
|
2026-03-15 12:55:25 +00:00
|
|
|
|
errors.NewInternalServerError(fmt.Sprintf("%s service panicked: %v\n%s", stageName, r, string(buf))),
|
|
|
|
|
|
map[string]interface{}{"session_id": sessionID})
|
|
|
|
|
|
}
|
|
|
|
|
|
// Agent mode: complete the assistant message in defer (normal mode does it via event handler)
|
|
|
|
|
|
if mode == qaModeAgent {
|
2026-04-29 09:04:51 +00:00
|
|
|
|
// Use WithoutCancel so a user-triggered stop (which cancels
|
|
|
|
|
|
// asyncCtx) doesn't also cancel the GORM UPDATE that persists
|
|
|
|
|
|
// AgentSteps/Content. Without this, cancelled-ctx makes
|
|
|
|
|
|
// GORM skip the write and the agent's intermediate steps
|
|
|
|
|
|
// (thinking / tool_call history) are lost on page refresh.
|
|
|
|
|
|
updateCtx := context.WithValue(
|
|
|
|
|
|
context.WithoutCancel(streamCtx.asyncCtx),
|
|
|
|
|
|
types.TenantIDContextKey, reqCtx.session.TenantID,
|
|
|
|
|
|
)
|
2026-03-15 12:55:25 +00:00
|
|
|
|
h.completeAssistantMessage(updateCtx, streamCtx.assistantMessage, reqCtx.query)
|
|
|
|
|
|
logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
2026-07-16 06:48:20 +00:00
|
|
|
|
// Resolve pre-uploaded attachments (may still be parsing): waits with a
|
|
|
|
|
|
// timeline step so the send is not blocked, then injects content/images.
|
|
|
|
|
|
h.resolveTemporaryAttachments(streamCtx, reqCtx)
|
|
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// Run VLM image analysis if applicable
|
|
|
|
|
|
h.runVLMAnalysisIfNeeded(streamCtx, reqCtx, mode)
|
|
|
|
|
|
|
|
|
|
|
|
// Build QA request and invoke the appropriate service
|
2026-03-15 14:12:45 +00:00
|
|
|
|
qaReq := reqCtx.buildQARequest()
|
2026-03-15 12:55:25 +00:00
|
|
|
|
|
|
|
|
|
|
var serviceErr error
|
|
|
|
|
|
var stageName string
|
|
|
|
|
|
if mode == qaModeNormal {
|
|
|
|
|
|
stageName = "knowledge_qa_execution"
|
|
|
|
|
|
serviceErr = h.sessionService.KnowledgeQA(streamCtx.asyncCtx, qaReq, streamCtx.eventBus)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
stageName = "agent_execution"
|
|
|
|
|
|
serviceErr = h.sessionService.AgentQA(streamCtx.asyncCtx, qaReq, streamCtx.eventBus)
|
2026-03-11 13:16:23 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
if serviceErr != nil {
|
2026-06-03 03:30:16 +00:00
|
|
|
|
// A user-requested stop cancels asyncCtx, which surfaces here as a
|
|
|
|
|
|
// context cancellation. That is an expected outcome, not a failure:
|
|
|
|
|
|
// the stop event already notifies the client, so don't emit a
|
|
|
|
|
|
// spurious error event (which would otherwise show an error toast).
|
|
|
|
|
|
if streamCtx.asyncCtx.Err() != nil {
|
|
|
|
|
|
logger.Infof(streamCtx.asyncCtx, "QA cancelled by user stop for session: %s", sessionID)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
logger.ErrorWithFields(streamCtx.asyncCtx, serviceErr, nil)
|
|
|
|
|
|
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
|
|
|
|
|
Type: event.EventError,
|
2025-11-08 16:02:31 +00:00
|
|
|
|
SessionID: sessionID,
|
2026-06-03 03:30:16 +00:00
|
|
|
|
Data: event.ErrorData{
|
|
|
|
|
|
Error: serviceErr.Error(),
|
|
|
|
|
|
Stage: stageName,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
}()
|
|
|
|
|
|
|
2025-12-24 02:34:41 +00:00
|
|
|
|
// Handle SSE events (blocking)
|
|
|
|
|
|
shouldWaitForTitle := generateTitle && reqCtx.session.Title == ""
|
|
|
|
|
|
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
|
2026-08-04 09:14:52 +00:00
|
|
|
|
reqCtx.requestID, streamCtx.eventBus, shouldWaitForTitle, reqCtx.resourceRewriter)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// runVLMAnalysisIfNeeded runs VLM image analysis within the async goroutine,
|
|
|
|
|
|
// emitting tool_call/tool_result events so the user can see progress.
|
|
|
|
|
|
// For normal mode, VLM only runs on the pure-chat path (no KB, no web search);
|
|
|
|
|
|
// RAG paths defer VLM to the pipeline rewrite step.
|
|
|
|
|
|
// For agent mode, VLM always runs when images and a VLM model are present.
|
|
|
|
|
|
func (h *Handler) runVLMAnalysisIfNeeded(streamCtx *sseStreamContext, reqCtx *qaRequestContext, mode qaMode) {
|
|
|
|
|
|
if len(reqCtx.images) == 0 || reqCtx.customAgent == nil || reqCtx.customAgent.Config.VLMModelID == "" {
|
2025-11-08 16:02:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
sessionID := reqCtx.sessionID
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// In normal mode, only run VLM for pure-chat path
|
|
|
|
|
|
if mode == qaModeNormal {
|
|
|
|
|
|
hasRequestKBs := len(reqCtx.knowledgeBaseIDs) > 0 || len(reqCtx.knowledgeIDs) > 0
|
|
|
|
|
|
agentWillResolveKBs := false
|
|
|
|
|
|
if !hasRequestKBs && reqCtx.customAgent != nil && !reqCtx.customAgent.Config.RetrieveKBOnlyWhenMentioned {
|
|
|
|
|
|
switch reqCtx.customAgent.Config.KBSelectionMode {
|
|
|
|
|
|
case "all":
|
|
|
|
|
|
agentWillResolveKBs = true
|
|
|
|
|
|
case "selected", "":
|
|
|
|
|
|
agentWillResolveKBs = len(reqCtx.customAgent.Config.KnowledgeBases) > 0
|
|
|
|
|
|
case "none":
|
|
|
|
|
|
agentWillResolveKBs = false
|
|
|
|
|
|
default:
|
|
|
|
|
|
agentWillResolveKBs = len(reqCtx.customAgent.Config.KnowledgeBases) > 0
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if hasRequestKBs || agentWillResolveKBs || reqCtx.webSearchEnabled {
|
|
|
|
|
|
return // VLM will be handled by the pipeline rewrite step
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
2025-12-24 02:34:41 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
// Emit VLM tool call/result events
|
|
|
|
|
|
toolCallID := uuid.New().String()
|
|
|
|
|
|
iteration := 0 // agent mode uses iteration field
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
|
|
|
|
|
Type: event.EventAgentToolCall,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Data: event.AgentToolCallData{
|
|
|
|
|
|
ToolCallID: toolCallID,
|
|
|
|
|
|
ToolName: "image_analysis",
|
|
|
|
|
|
Iteration: iteration,
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
2026-03-11 09:17:32 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
vlmStart := time.Now()
|
|
|
|
|
|
h.analyzeImageAttachments(streamCtx.asyncCtx, reqCtx.images,
|
|
|
|
|
|
reqCtx.customAgent.Config.VLMModelID, reqCtx.query)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
2026-03-15 12:55:25 +00:00
|
|
|
|
outputMsg := "已分析图片内容"
|
|
|
|
|
|
if mode == qaModeAgent {
|
|
|
|
|
|
outputMsg = "已查看图片内容"
|
|
|
|
|
|
}
|
|
|
|
|
|
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
|
|
|
|
|
Type: event.EventAgentToolResult,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Data: event.AgentToolResultData{
|
|
|
|
|
|
ToolCallID: toolCallID,
|
|
|
|
|
|
ToolName: "image_analysis",
|
|
|
|
|
|
Output: outputMsg,
|
|
|
|
|
|
Success: true,
|
|
|
|
|
|
Duration: time.Since(vlmStart).Milliseconds(),
|
|
|
|
|
|
Iteration: iteration,
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-16 06:48:20 +00:00
|
|
|
|
// defaultAttachmentParseWaitTimeout bounds how long a QA turn waits for
|
|
|
|
|
|
// still-parsing attachments before proceeding with only the finished ones.
|
|
|
|
|
|
// Large or scanned documents can exceed this; raise it via
|
|
|
|
|
|
// WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC when needed.
|
|
|
|
|
|
const defaultAttachmentParseWaitTimeout = 60 * time.Second
|
|
|
|
|
|
|
|
|
|
|
|
// attachmentParseWaitTimeout returns the configured wait timeout, honoring the
|
|
|
|
|
|
// WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC override (in seconds) and falling
|
|
|
|
|
|
// back to the default when unset or invalid.
|
|
|
|
|
|
func attachmentParseWaitTimeout() time.Duration {
|
|
|
|
|
|
if raw := strings.TrimSpace(os.Getenv("WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC")); raw != "" {
|
|
|
|
|
|
if secs, err := strconv.Atoi(raw); err == nil && secs > 0 {
|
|
|
|
|
|
return time.Duration(secs) * time.Second
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return defaultAttachmentParseWaitTimeout
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// resolveTemporaryAttachments selects prompt content for pre-uploaded documents
|
|
|
|
|
|
// after the SSE stream is live. When any attachment is still parsing it emits a
|
|
|
|
|
|
// "attachment_parsing" timeline step and waits (bounded); unfinished attachments
|
|
|
|
|
|
// are skipped rather than blocking or failing the whole turn.
|
|
|
|
|
|
func (h *Handler) resolveTemporaryAttachments(streamCtx *sseStreamContext, reqCtx *qaRequestContext) {
|
|
|
|
|
|
if len(reqCtx.attachmentIDs) == 0 {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
ctx := streamCtx.asyncCtx
|
|
|
|
|
|
sessionID := reqCtx.sessionID
|
2026-07-16 09:18:08 +00:00
|
|
|
|
// Prefer the session's tenant over gin.Context: this runs in an async
|
|
|
|
|
|
// goroutine after the HTTP handler may have returned.
|
|
|
|
|
|
tenantID := reqCtx.session.TenantID
|
2026-07-16 06:48:20 +00:00
|
|
|
|
|
|
|
|
|
|
start := time.Now()
|
|
|
|
|
|
var toolCallID string
|
|
|
|
|
|
if h.hasPendingAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs) {
|
|
|
|
|
|
toolCallID = uuid.New().String()
|
|
|
|
|
|
streamCtx.eventBus.Emit(ctx, event.Event{
|
|
|
|
|
|
Type: event.EventAgentToolCall,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Data: event.AgentToolCallData{
|
|
|
|
|
|
ToolCallID: toolCallID,
|
|
|
|
|
|
ToolName: "attachment_parsing",
|
|
|
|
|
|
Iteration: 0,
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
waitTimeout := attachmentParseWaitTimeout()
|
|
|
|
|
|
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.AttachmentParseWaitTimeoutSec > 0 {
|
|
|
|
|
|
waitTimeout = time.Duration(reqCtx.customAgent.Config.AttachmentParseWaitTimeoutSec) * time.Second
|
|
|
|
|
|
}
|
|
|
|
|
|
h.waitForAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs, waitTimeout)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
readyIDs, skipped := h.partitionReadyAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs)
|
|
|
|
|
|
|
|
|
|
|
|
var temporaryResult *types.TemporaryDocumentPromptResult
|
|
|
|
|
|
var resolveErr error
|
|
|
|
|
|
if len(readyIDs) > 0 {
|
|
|
|
|
|
temporaryResult, resolveErr = h.temporaryDocuments.ResolveForPrompt(ctx, tenantID, sessionID, readyIDs, reqCtx.query)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if toolCallID != "" {
|
|
|
|
|
|
output := fmt.Sprintf("已解析 %d 个附件", len(readyIDs))
|
|
|
|
|
|
if skipped > 0 {
|
|
|
|
|
|
output += fmt.Sprintf(",%d 个未完成已跳过", skipped)
|
|
|
|
|
|
}
|
|
|
|
|
|
success := resolveErr == nil
|
|
|
|
|
|
if resolveErr != nil {
|
|
|
|
|
|
output = fmt.Sprintf("附件解析失败: %v", resolveErr)
|
|
|
|
|
|
}
|
|
|
|
|
|
streamCtx.eventBus.Emit(ctx, event.Event{
|
|
|
|
|
|
Type: event.EventAgentToolResult,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Data: event.AgentToolResultData{
|
|
|
|
|
|
ToolCallID: toolCallID,
|
|
|
|
|
|
ToolName: "attachment_parsing",
|
|
|
|
|
|
Output: output,
|
|
|
|
|
|
Success: success,
|
|
|
|
|
|
Duration: time.Since(start).Milliseconds(),
|
|
|
|
|
|
Iteration: 0,
|
|
|
|
|
|
Data: map[string]interface{}{
|
|
|
|
|
|
"display_type": "attachment_parsing",
|
|
|
|
|
|
"parsed_count": len(readyIDs),
|
|
|
|
|
|
"skipped_count": skipped,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
if resolveErr != nil || temporaryResult == nil {
|
|
|
|
|
|
if resolveErr != nil {
|
|
|
|
|
|
logger.Warnf(ctx, "temporary attachment resolution failed for session %s: %v", sessionID, resolveErr)
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
attachments := temporaryResult.Attachments
|
|
|
|
|
|
if reqCtx.customAgent != nil && len(reqCtx.customAgent.Config.SupportedFileTypes) > 0 {
|
|
|
|
|
|
filtered := attachments[:0]
|
|
|
|
|
|
for _, att := range attachments {
|
|
|
|
|
|
ext := strings.TrimPrefix(strings.ToLower(att.FileType), ".")
|
|
|
|
|
|
if containsFileType(reqCtx.customAgent.Config.SupportedFileTypes, ext) {
|
|
|
|
|
|
filtered = append(filtered, att)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
attachments = filtered
|
|
|
|
|
|
}
|
|
|
|
|
|
reqCtx.attachments = append(reqCtx.attachments, attachments...)
|
2026-07-16 08:38:22 +00:00
|
|
|
|
// Persist the freshly selected content back onto the stored user message.
|
|
|
|
|
|
// The message was created with metadata-only attachment entries (content is
|
|
|
|
|
|
// selected here, after the SSE stream is live), so without this write a
|
|
|
|
|
|
// later Agent-mode turn rebuilds history from the Attachments column and
|
|
|
|
|
|
// sees empty attachments (see buildUserHistoryMessage in agent_history.go).
|
|
|
|
|
|
h.persistResolvedAttachmentContent(ctx, reqCtx, attachments)
|
2026-07-16 06:48:20 +00:00
|
|
|
|
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ImageUploadEnabled {
|
|
|
|
|
|
for _, imageURL := range temporaryResult.ImageURLs {
|
|
|
|
|
|
reqCtx.images = append(reqCtx.images, ImageAttachment{URL: imageURL})
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-16 08:38:22 +00:00
|
|
|
|
// persistResolvedAttachmentContent writes the parsed content of pre-uploaded
|
|
|
|
|
|
// attachments back onto the stored user message so multi-turn history can
|
|
|
|
|
|
// replay it. Entries are matched by their temporary-document ID; only those
|
|
|
|
|
|
// present on the message are enriched. Failures are logged but never bubble up
|
|
|
|
|
|
// — losing the write only degrades follow-up context, it must not fail the turn.
|
|
|
|
|
|
func (h *Handler) persistResolvedAttachmentContent(
|
|
|
|
|
|
ctx context.Context, reqCtx *qaRequestContext, resolved types.MessageAttachments,
|
|
|
|
|
|
) {
|
|
|
|
|
|
if reqCtx.userMessageID == "" || len(resolved) == 0 {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
// Detach from the request/stream lifetime and pin the session tenant so a
|
|
|
|
|
|
// user-triggered stop (which cancels asyncCtx) does not drop the write.
|
|
|
|
|
|
updateCtx := context.WithValue(
|
|
|
|
|
|
context.WithoutCancel(ctx), types.TenantIDContextKey, reqCtx.session.TenantID,
|
|
|
|
|
|
)
|
|
|
|
|
|
msg, err := h.messageService.GetMessage(updateCtx, reqCtx.sessionID, reqCtx.userMessageID)
|
|
|
|
|
|
if err != nil || msg == nil {
|
|
|
|
|
|
logger.Warnf(updateCtx, "persist attachment content: load user message %s failed: %v",
|
|
|
|
|
|
reqCtx.userMessageID, err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
byID := make(map[string]types.MessageAttachment, len(resolved))
|
|
|
|
|
|
for _, att := range resolved {
|
|
|
|
|
|
if att.ID != "" {
|
|
|
|
|
|
byID[att.ID] = att
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
changed := false
|
|
|
|
|
|
for i := range msg.Attachments {
|
|
|
|
|
|
if msg.Attachments[i].ID == "" {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
if enriched, ok := byID[msg.Attachments[i].ID]; ok {
|
|
|
|
|
|
msg.Attachments[i] = enriched
|
|
|
|
|
|
changed = true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if !changed {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if err := h.messageService.UpdateMessage(updateCtx, msg); err != nil {
|
|
|
|
|
|
logger.Warnf(updateCtx, "persist attachment content: update user message %s failed: %v",
|
|
|
|
|
|
reqCtx.userMessageID, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-16 09:18:08 +00:00
|
|
|
|
// normalizeTemporaryAttachmentIDs rejects oversized ID lists before any DB
|
|
|
|
|
|
// lookup, then returns a deduplicated, order-preserving list of non-empty IDs.
|
|
|
|
|
|
func normalizeTemporaryAttachmentIDs(ids []string) ([]string, error) {
|
|
|
|
|
|
if len(ids) > types.MaxTemporaryAttachmentsPerMessage {
|
|
|
|
|
|
return nil, fmt.Errorf("a message can use at most %d attachments", types.MaxTemporaryAttachmentsPerMessage)
|
|
|
|
|
|
}
|
|
|
|
|
|
out := make([]string, 0, len(ids))
|
|
|
|
|
|
seen := make(map[string]struct{}, len(ids))
|
|
|
|
|
|
for _, id := range ids {
|
|
|
|
|
|
id = strings.TrimSpace(id)
|
|
|
|
|
|
if id == "" {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
if _, ok := seen[id]; ok {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
seen[id] = struct{}{}
|
|
|
|
|
|
out = append(out, id)
|
|
|
|
|
|
}
|
|
|
|
|
|
return out, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-16 06:48:20 +00:00
|
|
|
|
// hasPendingAttachments reports whether any of the given documents is still
|
|
|
|
|
|
// uploading or being parsed.
|
|
|
|
|
|
func (h *Handler) hasPendingAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string) bool {
|
|
|
|
|
|
for _, id := range ids {
|
|
|
|
|
|
doc, err := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
|
|
|
|
|
|
if err != nil || doc == nil {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
if doc.Status == types.TemporaryDocumentStatusUploaded ||
|
|
|
|
|
|
doc.Status == types.TemporaryDocumentStatusProcessing {
|
|
|
|
|
|
return true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return false
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// waitForAttachments polls until no attachment is pending or the timeout / ctx
|
|
|
|
|
|
// cancellation fires.
|
|
|
|
|
|
func (h *Handler) waitForAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string, timeout time.Duration) {
|
|
|
|
|
|
deadline := time.Now().Add(timeout)
|
|
|
|
|
|
ticker := time.NewTicker(500 * time.Millisecond)
|
|
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
for {
|
|
|
|
|
|
if !h.hasPendingAttachments(ctx, tenantID, sessionID, ids) || time.Now().After(deadline) {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
select {
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
|
return
|
|
|
|
|
|
case <-ticker.C:
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// partitionReadyAttachments splits the ids into ready ones and a count of those
|
|
|
|
|
|
// skipped (missing, failed, or still parsing after the wait).
|
|
|
|
|
|
func (h *Handler) partitionReadyAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string) (ready []string, skipped int) {
|
|
|
|
|
|
for _, id := range ids {
|
|
|
|
|
|
doc, err := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
|
|
|
|
|
|
if err != nil || doc == nil || doc.Status != types.TemporaryDocumentStatusReady {
|
|
|
|
|
|
skipped++
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
ready = append(ready, id)
|
|
|
|
|
|
}
|
|
|
|
|
|
return ready, skipped
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-18 14:24:39 +00:00
|
|
|
|
// persistLastRequestState records the input-bar state the user just sent so
|
|
|
|
|
|
// that reopening this session restores agent/model/KB/web-search/MCP picks.
|
|
|
|
|
|
// Pure UI memo — failures are logged but never bubble up; the caller runs
|
|
|
|
|
|
// this in a goroutine and is safe to discard the returned context.
|
|
|
|
|
|
func (h *Handler) persistLastRequestState(parentCtx context.Context, reqCtx *qaRequestContext, mode qaMode) {
|
|
|
|
|
|
// Detach from the HTTP request lifetime: this write must survive both
|
|
|
|
|
|
// SSE disconnects and the parent gin context being released after the
|
|
|
|
|
|
// handler returns.
|
|
|
|
|
|
ctx := logger.CloneContext(context.WithoutCancel(parentCtx))
|
|
|
|
|
|
|
|
|
|
|
|
agentEnabled := reqCtx.reqAgentEnabled
|
|
|
|
|
|
// Mirror the resolution rule used in AgentQA: a resolved custom agent's
|
|
|
|
|
|
// agent_mode wins over the request flag. For KnowledgeQA the request
|
|
|
|
|
|
// itself carries agent_enabled=false, so this collapses correctly.
|
|
|
|
|
|
if mode == qaModeAgent && reqCtx.customAgent != nil {
|
|
|
|
|
|
agentEnabled = reqCtx.customAgent.IsAgentMode()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
state := &types.SessionLastRequestState{
|
|
|
|
|
|
AgentID: reqCtx.reqAgentID,
|
|
|
|
|
|
AgentEnabled: agentEnabled,
|
|
|
|
|
|
ModelID: reqCtx.summaryModelID,
|
|
|
|
|
|
KnowledgeBaseIDs: reqCtx.knowledgeBaseIDs,
|
|
|
|
|
|
KnowledgeIDs: reqCtx.knowledgeIDs,
|
2026-06-29 08:01:58 +00:00
|
|
|
|
TagIDs: reqCtx.tagIDs,
|
|
|
|
|
|
MCPServiceIDs: reqCtx.mcpServiceIDs,
|
|
|
|
|
|
SkillNames: reqCtx.skillNames,
|
|
|
|
|
|
MentionedItems: reqCtx.mentionedItems,
|
2026-05-18 14:24:39 +00:00
|
|
|
|
WebSearchEnabled: reqCtx.webSearchEnabled,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if err := h.sessionService.UpdateSessionLastRequestState(ctx, reqCtx.sessionID, state); err != nil {
|
|
|
|
|
|
logger.Warnf(ctx, "persist last_request_state failed for session %s: %v", reqCtx.sessionID, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-04 14:03:54 +00:00
|
|
|
|
// appendQuickAnswerReasoning accumulates streamed reasoning_content from
|
|
|
|
|
|
// KnowledgeQA (fast answer) into a single AgentStep for history replay.
|
|
|
|
|
|
func appendQuickAnswerReasoning(msg *types.Message, content string) {
|
|
|
|
|
|
if content == "" {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(msg.AgentSteps) == 0 {
|
|
|
|
|
|
msg.AgentSteps = types.AgentSteps{{
|
|
|
|
|
|
Iteration: 0,
|
|
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
|
|
ToolCalls: make([]types.ToolCall, 0),
|
|
|
|
|
|
}}
|
|
|
|
|
|
}
|
|
|
|
|
|
msg.AgentSteps[0].ReasoningContent += content
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-06 13:06:10 +00:00
|
|
|
|
// completeAssistantMessage marks an assistant message as complete, updates it,
|
|
|
|
|
|
// and asynchronously indexes the Q&A pair into the chat history knowledge base.
|
|
|
|
|
|
func (h *Handler) completeAssistantMessage(ctx context.Context, assistantMessage *types.Message, userQuery string) {
|
2025-11-08 16:02:31 +00:00
|
|
|
|
assistantMessage.UpdatedAt = time.Now()
|
|
|
|
|
|
assistantMessage.IsCompleted = true
|
|
|
|
|
|
_ = h.messageService.UpdateMessage(ctx, assistantMessage)
|
2026-03-06 13:06:10 +00:00
|
|
|
|
|
|
|
|
|
|
// Asynchronously index the Q&A pair into the chat history knowledge base for vector search.
|
|
|
|
|
|
// Use WithoutCancel so the goroutine survives after the HTTP request context is done.
|
|
|
|
|
|
bgCtx := context.WithoutCancel(ctx)
|
|
|
|
|
|
go h.messageService.IndexMessageToKB(bgCtx, userQuery, assistantMessage.Content, assistantMessage.ID, assistantMessage.SessionID)
|
2026-07-14 03:06:13 +00:00
|
|
|
|
if userQuery != "" && h.suggestionService != nil {
|
|
|
|
|
|
go func() {
|
|
|
|
|
|
if _, err := h.suggestionService.EnsureFollowUps(
|
|
|
|
|
|
bgCtx, assistantMessage.SessionID, assistantMessage.ID, false,
|
|
|
|
|
|
); err != nil {
|
|
|
|
|
|
logger.Warnf(bgCtx, "follow-up suggestion generation failed for message %s: %v", assistantMessage.ID, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
}()
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|