mirror of
https://github.com/memohai/Memoh.git
synced 2026-04-27 07:16:19 +09:00
1680316c7f
* refactor(agent): replace TypeScript agent gateway with in-process Go agent using twilight-ai SDK
- Remove apps/agent (Bun/Elysia gateway), packages/agent (@memoh/agent),
internal/bun runtime manager, and all embedded agent/bun assets
- Add internal/agent package powered by twilight-ai SDK for LLM calls,
tool execution, streaming, sential logic, tag extraction, and prompts
- Integrate ToolGatewayService in-process for both built-in and user MCP
tools, eliminating HTTP round-trips to the old gateway
- Update resolver to convert between sdk.Message and ModelMessage at the
boundary (resolver_messages.go), keeping agent package free of
persistence concerns
- Prepend user message before storeRound since SDK only returns output
messages (assistant + tool)
- Clean up all Docker configs, TOML configs, nginx proxy, Dockerfile.agent,
and Go config structs related to the removed agent gateway
- Update cmd/agent and cmd/memoh entry points with setter-based
ToolGateway injection to avoid FX dependency cycles
* fix(web): move form declaration before computed properties that reference it
The `form` reactive object was declared after computed properties like
`selectedMemoryProvider` and `isSelectedMemoryProviderPersisted` that
reference it, causing a TDZ ReferenceError during setup.
* fix: prevent UTF-8 character corruption in streaming text output
StreamTagExtractor.Push() used byte-level string slicing to hold back
buffer tails for tag detection, which could split multi-byte UTF-8
characters. After json.Marshal replaced invalid bytes with U+FFFD,
the corruption became permanent — causing garbled CJK characters (�)
in agent responses.
Add safeUTF8SplitIndex() to back up split points to valid character
boundaries. Also fix byte-level truncation in command/formatter.go
and command/fs.go to use rune-aware slicing.
* fix: add agent error logging and fix Gemini tool schema validation
- Log agent stream errors in both SSE and WebSocket paths with bot/model context
- Fix send tool `attachments` parameter: empty `items` schema rejected by
Google Gemini API (INVALID_ARGUMENT), now specifies `{"type": "string"}`
- Upgrade twilight-ai to d898f0b (includes raw body in API error messages)
* chore(ci): remove agent gateway from Docker build and release pipelines
Agent gateway has been replaced by in-process Go agent; remove the
obsolete Docker image matrix entry, Bun/UPX CI steps, and agent-binary
build logic from the release script.
* fix: preserve attachment filename, metadata, and container path through persistence
- Add `name` column to `bot_history_message_assets` (migration 0034) to
persist original filenames across page refreshes.
- Add `metadata` JSONB column (migration 0035) to store source_path,
source_url, and other context alongside each asset.
- Update SQL queries, sqlc-generated code, and all Go types (MessageAsset,
AssetRef, OutboundAssetRef, FileAttachment) to carry name and metadata
through the full lifecycle.
- Extract filenames from path/URL in AttachmentsResolver before clearing
raw paths; enrich streaming event metadata with name, source_path, and
source_url in both the WebSocket and channel inbound ingestion paths.
- Implement `LinkAssets` on message service and `LinkOutboundAssets` on
flow resolver so WebSocket-streamed bot attachments are persisted to the
correct assistant message after streaming completes.
- Frontend: update MessageAsset type with metadata field, pass metadata
through to attachment items, and reorder attachment-block.vue template
so container files (identified by metadata.source_path) open in the
sidebar file manager instead of triggering a download.
* refactor(agent): decouple built-in tools from MCP, load via ToolProvider interface
Migrate all 13 built-in tool providers from internal/mcp/providers/ to
internal/agent/tools/ using the twilight-ai sdk.Tool structure. The agent
now loads tools through a ToolProvider interface instead of the MCP
ToolGatewayService, which is simplified to only manage external federation
sources. This enables selective tool loading and removes the coupling
between business tools and the MCP protocol layer.
* refactor(flow): split monolithic resolver.go into focused modules
Break the 1959-line resolver.go into 12 files organized by concern:
- resolver.go: core orchestration (Resolver struct, resolve, Chat, prepareRunConfig)
- resolver_stream.go: streaming (StreamChat, StreamChatWS, tryStoreStream)
- resolver_trigger.go: schedule/heartbeat triggers
- resolver_attachments.go: attachment routing, inlining, encoding
- resolver_history.go: message loading, deduplication, token trimming
- resolver_store.go: persistence (storeRound, storeMessages, asset linking)
- resolver_memory.go: memory provider integration
- resolver_model_selection.go: model selection and candidate matching
- resolver_identity.go: display name and channel identity resolution
- resolver_settings.go: bot settings, loop detection, inbox
- user_header.go: YAML front-matter formatting
- resolver_util.go: shared utilities (sanitize, normalize, dedup, UUID)
* fix(agent): enable Anthropic extended thinking by passing ReasoningConfig to provider
Anthropic's thinking requires WithThinking() at provider creation time,
unlike OpenAI which uses per-request ReasoningEffort. The config was
never wired through, so Claude models could not trigger thinking.
* refactor(agent): extract prompts into embedded markdown templates
Move inline prompt strings from prompt.go into separate .md files under
internal/agent/prompts/, using {{key}} placeholders and a simple render
engine. Remove obsolete SystemPromptParams fields (Language,
MaxContextLoadTime, Channels, CurrentChannel) and their call-site usage.
* fix: lint
159 lines
4.1 KiB
Go
159 lines
4.1 KiB
Go
package agent
|
|
|
|
import (
|
|
"encoding/json"
|
|
"time"
|
|
|
|
sdk "github.com/memohai/twilight-ai/sdk"
|
|
)
|
|
|
|
// SessionContext carries request-scoped identity and routing information.
|
|
type SessionContext struct {
|
|
BotID string
|
|
ChatID string
|
|
ChannelIdentityID string
|
|
DisplayName string
|
|
CurrentPlatform string
|
|
ReplyTarget string
|
|
ConversationType string
|
|
SessionToken string //nolint:gosec // carries session credential material at runtime
|
|
IsSubagent bool
|
|
}
|
|
|
|
// SkillEntry represents a skill loaded from the bot container.
|
|
type SkillEntry struct {
|
|
Name string
|
|
Description string
|
|
Content string
|
|
Metadata map[string]any
|
|
}
|
|
|
|
// InboxItem represents an unread inbox notification.
|
|
type InboxItem struct {
|
|
ID string `json:"id"`
|
|
Source string `json:"source"`
|
|
Header map[string]any `json:"header"`
|
|
Content string `json:"content"`
|
|
CreatedAt string `json:"createdAt"`
|
|
}
|
|
|
|
// Schedule represents a scheduled task definition.
|
|
type Schedule struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Pattern string `json:"pattern"`
|
|
MaxCalls *int `json:"maxCalls,omitempty"`
|
|
Command string `json:"command"`
|
|
}
|
|
|
|
// LoopDetectionConfig controls loop detection behavior.
|
|
type LoopDetectionConfig struct {
|
|
Enabled bool
|
|
}
|
|
|
|
// RunConfig holds everything needed for a single agent invocation.
|
|
type RunConfig struct {
|
|
Model *sdk.Model
|
|
ReasoningEffort string
|
|
Messages []sdk.Message
|
|
Query string
|
|
System string
|
|
Tools []sdk.Tool
|
|
Channels []string
|
|
CurrentChannel string
|
|
Identity SessionContext
|
|
Skills []SkillEntry
|
|
EnabledSkillNames []string
|
|
Inbox []InboxItem
|
|
LoopDetection LoopDetectionConfig
|
|
ActiveContextTime int
|
|
}
|
|
|
|
// GenerateResult holds the result of a non-streaming agent invocation.
|
|
type GenerateResult struct {
|
|
Messages []sdk.Message
|
|
Text string
|
|
Attachments []FileAttachment
|
|
Reactions []ReactionItem
|
|
Speeches []SpeechItem
|
|
Skills []string
|
|
Usage *sdk.Usage
|
|
}
|
|
|
|
// FileAttachment represents a file reference extracted from agent output.
|
|
type FileAttachment struct {
|
|
Type string `json:"type"`
|
|
Path string `json:"path,omitempty"`
|
|
URL string `json:"url,omitempty"`
|
|
Mime string `json:"mime,omitempty"`
|
|
Name string `json:"name,omitempty"`
|
|
}
|
|
|
|
// ReactionItem represents an emoji reaction extracted from agent output.
|
|
type ReactionItem struct {
|
|
Emoji string `json:"emoji"`
|
|
}
|
|
|
|
// SpeechItem represents a TTS request extracted from agent output.
|
|
type SpeechItem struct {
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
// SystemFile is a file loaded from the bot container for prompt generation.
|
|
type SystemFile struct {
|
|
Filename string
|
|
Content string
|
|
}
|
|
|
|
// ModelConfig holds provider and model information resolved from DB.
|
|
type ModelConfig struct {
|
|
ModelID string
|
|
ClientType string
|
|
InputModalities []string
|
|
APIKey string //nolint:gosec // carries provider credential material at runtime
|
|
BaseURL string
|
|
ReasoningConfig *ReasoningConfig
|
|
}
|
|
|
|
// ReasoningConfig controls extended thinking/reasoning behavior.
|
|
type ReasoningConfig struct {
|
|
Enabled bool
|
|
Effort string
|
|
}
|
|
|
|
func mustMarshal(v any) json.RawMessage {
|
|
data, err := json.Marshal(v)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return data
|
|
}
|
|
|
|
// StripTagsFromMessages strips attachment/reaction/speech tags from assistant messages.
|
|
func StripTagsFromMessages(msgs []sdk.Message) []sdk.Message {
|
|
resolvers := DefaultTagResolvers()
|
|
result := make([]sdk.Message, 0, len(msgs))
|
|
for _, msg := range msgs {
|
|
if msg.Role != sdk.MessageRoleAssistant {
|
|
result = append(result, msg)
|
|
continue
|
|
}
|
|
cleaned := make([]sdk.MessagePart, 0, len(msg.Content))
|
|
for _, part := range msg.Content {
|
|
if tp, ok := part.(sdk.TextPart); ok {
|
|
text, _ := ExtractTagsFromText(tp.Text, resolvers)
|
|
cleaned = append(cleaned, sdk.TextPart{Text: text})
|
|
} else {
|
|
cleaned = append(cleaned, part)
|
|
}
|
|
}
|
|
msg.Content = cleaned
|
|
result = append(result, msg)
|
|
}
|
|
return result
|
|
}
|
|
|
|
// TimeNow is a hook for testing. Defaults to time.Now.
|
|
var TimeNow = time.Now
|