2026-02-04 11:06:13 +00:00
|
|
|
// PicoClaw - Ultra-lightweight personal AI agent
|
|
|
|
|
// Inspired by and based on nanobot: https://github.com/HKUDS/nanobot
|
|
|
|
|
// License: MIT
|
|
|
|
|
//
|
|
|
|
|
// Copyright (c) 2026 PicoClaw contributors
|
|
|
|
|
|
|
|
|
|
package agent
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"encoding/json"
|
2026-02-23 13:13:37 +00:00
|
|
|
"errors"
|
2026-02-04 11:06:13 +00:00
|
|
|
"fmt"
|
2026-02-22 22:03:23 +00:00
|
|
|
"path/filepath"
|
2026-03-04 10:21:59 +00:00
|
|
|
"regexp"
|
2026-02-10 08:05:23 +00:00
|
|
|
"strings"
|
2026-02-11 11:27:36 +00:00
|
|
|
"sync"
|
2026-02-11 17:26:22 +00:00
|
|
|
"sync/atomic"
|
2026-02-11 11:27:36 +00:00
|
|
|
"time"
|
2026-02-04 11:06:13 +00:00
|
|
|
|
|
|
|
|
"github.com/sipeed/picoclaw/pkg/bus"
|
2026-02-16 08:30:54 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/channels"
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/commands"
|
2026-02-04 11:06:13 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/config"
|
2026-02-13 07:05:16 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/constants"
|
2026-02-10 05:18:23 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/logger"
|
2026-02-22 15:27:55 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/media"
|
2026-02-04 11:06:13 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/providers"
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/routing"
|
2026-02-20 10:55:04 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/skills"
|
2026-02-12 11:49:36 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/state"
|
2026-02-04 11:06:13 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/tools"
|
2026-02-11 12:22:41 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/utils"
|
2026-03-01 08:31:04 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/voice"
|
2026-02-04 11:06:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type AgentLoop struct {
|
|
|
|
|
bus *bus.MessageBus
|
2026-02-16 13:34:55 +00:00
|
|
|
cfg *config.Config
|
|
|
|
|
registry *AgentRegistry
|
2026-02-12 11:49:36 +00:00
|
|
|
state *state.Manager
|
2026-03-20 06:53:22 +00:00
|
|
|
eventBus *EventBus
|
2026-02-11 17:26:22 +00:00
|
|
|
running atomic.Bool
|
2026-02-16 13:34:55 +00:00
|
|
|
summarizing sync.Map
|
|
|
|
|
fallback *providers.FallbackChain
|
2026-02-16 08:30:54 +00:00
|
|
|
channelManager *channels.Manager
|
2026-02-22 15:27:55 +00:00
|
|
|
mediaStore media.MediaStore
|
2026-03-01 08:31:04 +00:00
|
|
|
transcriber voice.Transcriber
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
cmdRegistry *commands.Registry
|
2026-03-11 17:06:48 +00:00
|
|
|
mcp mcpRuntime
|
2026-03-15 16:08:16 +00:00
|
|
|
steering *steeringQueue
|
2026-03-13 06:27:46 +00:00
|
|
|
mu sync.RWMutex
|
2026-03-20 09:28:12 +00:00
|
|
|
activeTurnMu sync.RWMutex
|
|
|
|
|
activeTurn *turnState
|
2026-03-20 06:53:22 +00:00
|
|
|
turnSeq atomic.Uint64
|
2026-03-13 06:27:46 +00:00
|
|
|
// Track active requests for safe provider cleanup
|
|
|
|
|
activeRequests sync.WaitGroup
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-11 12:22:41 +00:00
|
|
|
// processOptions configures how a message is processed
|
|
|
|
|
type processOptions struct {
|
2026-03-15 16:08:16 +00:00
|
|
|
SessionKey string // Session identifier for history/context
|
|
|
|
|
Channel string // Target channel for tool execution
|
|
|
|
|
ChatID string // Target chat ID for tool execution
|
|
|
|
|
UserMessage string // User message content (may include prefix)
|
|
|
|
|
Media []string // media:// refs from inbound message
|
|
|
|
|
DefaultResponse string // Response when LLM returns empty
|
|
|
|
|
EnableSummary bool // Whether to trigger summarization
|
|
|
|
|
SendResponse bool // Whether to send response via bus
|
|
|
|
|
NoHistory bool // If true, don't load session history (for heartbeat)
|
|
|
|
|
SkipInitialSteeringPoll bool // If true, skip the steering poll at loop start (used by Continue)
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
type continuationTarget struct {
|
|
|
|
|
SessionKey string
|
|
|
|
|
Channel string
|
|
|
|
|
ChatID string
|
|
|
|
|
}
|
|
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
const (
|
|
|
|
|
defaultResponse = "I've completed processing but have no response to give. Increase `max_tool_iterations` in config.json."
|
|
|
|
|
sessionKeyAgentPrefix = "agent:"
|
|
|
|
|
metadataKeyAccountID = "account_id"
|
|
|
|
|
metadataKeyGuildID = "guild_id"
|
|
|
|
|
metadataKeyTeamID = "team_id"
|
|
|
|
|
metadataKeyParentPeerKind = "parent_peer_kind"
|
|
|
|
|
metadataKeyParentPeerID = "parent_peer_id"
|
|
|
|
|
)
|
2026-02-27 07:42:47 +00:00
|
|
|
|
2026-03-01 00:53:13 +00:00
|
|
|
func NewAgentLoop(
|
|
|
|
|
cfg *config.Config,
|
|
|
|
|
msgBus *bus.MessageBus,
|
|
|
|
|
provider providers.LLMProvider,
|
|
|
|
|
) *AgentLoop {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
registry := NewAgentRegistry(cfg, provider)
|
2026-02-10 08:05:23 +00:00
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
// Register shared tools to all agents
|
|
|
|
|
registerSharedTools(cfg, msgBus, registry, provider)
|
2026-02-13 06:39:39 +00:00
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
// Set up shared fallback chain
|
|
|
|
|
cooldown := providers.NewCooldownTracker()
|
|
|
|
|
fallbackChain := providers.NewFallbackChain(cooldown)
|
2026-02-13 06:39:39 +00:00
|
|
|
|
2026-02-13 15:24:26 +00:00
|
|
|
// Create state manager using default agent's workspace for channel recording
|
|
|
|
|
defaultAgent := registry.GetDefaultAgent()
|
|
|
|
|
var stateManager *state.Manager
|
|
|
|
|
if defaultAgent != nil {
|
|
|
|
|
stateManager = state.NewManager(defaultAgent.Workspace)
|
|
|
|
|
}
|
2026-02-10 08:05:23 +00:00
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
al := &AgentLoop{
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
bus: msgBus,
|
|
|
|
|
cfg: cfg,
|
|
|
|
|
registry: registry,
|
2026-02-13 15:24:26 +00:00
|
|
|
state: stateManager,
|
2026-03-20 06:53:22 +00:00
|
|
|
eventBus: NewEventBus(),
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
summarizing: sync.Map{},
|
|
|
|
|
fallback: fallbackChain,
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
cmdRegistry: commands.NewRegistry(commands.BuiltinDefinitions()),
|
2026-03-15 16:08:16 +00:00
|
|
|
steering: newSteeringQueue(parseSteeringMode(cfg.Agents.Defaults.SteeringMode)),
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
}
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
|
|
|
|
|
return al
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
// registerSharedTools registers tools that are shared across all agents (web, message, spawn).
|
2026-02-20 18:03:11 +00:00
|
|
|
func registerSharedTools(
|
|
|
|
|
cfg *config.Config,
|
|
|
|
|
msgBus *bus.MessageBus,
|
|
|
|
|
registry *AgentRegistry,
|
|
|
|
|
provider providers.LLMProvider,
|
|
|
|
|
) {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
for _, agentID := range registry.ListAgentIDs() {
|
|
|
|
|
agent, ok := registry.GetAgent(agentID)
|
|
|
|
|
if !ok {
|
|
|
|
|
continue
|
|
|
|
|
}
|
2026-02-12 11:49:36 +00:00
|
|
|
|
2026-03-05 06:53:26 +00:00
|
|
|
if cfg.Tools.IsToolEnabled("web") {
|
|
|
|
|
searchTool, err := tools.NewWebSearchTool(tools.WebSearchToolOptions{
|
2026-03-10 08:34:11 +00:00
|
|
|
BraveAPIKeys: config.MergeAPIKeys(cfg.Tools.Web.Brave.APIKey, cfg.Tools.Web.Brave.APIKeys),
|
2026-03-05 06:53:26 +00:00
|
|
|
BraveMaxResults: cfg.Tools.Web.Brave.MaxResults,
|
|
|
|
|
BraveEnabled: cfg.Tools.Web.Brave.Enabled,
|
2026-03-10 08:34:11 +00:00
|
|
|
TavilyAPIKeys: config.MergeAPIKeys(cfg.Tools.Web.Tavily.APIKey, cfg.Tools.Web.Tavily.APIKeys),
|
2026-03-05 06:53:26 +00:00
|
|
|
TavilyBaseURL: cfg.Tools.Web.Tavily.BaseURL,
|
|
|
|
|
TavilyMaxResults: cfg.Tools.Web.Tavily.MaxResults,
|
|
|
|
|
TavilyEnabled: cfg.Tools.Web.Tavily.Enabled,
|
|
|
|
|
DuckDuckGoMaxResults: cfg.Tools.Web.DuckDuckGo.MaxResults,
|
|
|
|
|
DuckDuckGoEnabled: cfg.Tools.Web.DuckDuckGo.Enabled,
|
2026-03-10 08:34:11 +00:00
|
|
|
PerplexityAPIKeys: config.MergeAPIKeys(
|
|
|
|
|
cfg.Tools.Web.Perplexity.APIKey,
|
|
|
|
|
cfg.Tools.Web.Perplexity.APIKeys,
|
|
|
|
|
),
|
2026-03-05 06:53:26 +00:00
|
|
|
PerplexityMaxResults: cfg.Tools.Web.Perplexity.MaxResults,
|
|
|
|
|
PerplexityEnabled: cfg.Tools.Web.Perplexity.Enabled,
|
2026-03-05 20:36:05 +00:00
|
|
|
SearXNGBaseURL: cfg.Tools.Web.SearXNG.BaseURL,
|
|
|
|
|
SearXNGMaxResults: cfg.Tools.Web.SearXNG.MaxResults,
|
|
|
|
|
SearXNGEnabled: cfg.Tools.Web.SearXNG.Enabled,
|
2026-03-05 06:53:26 +00:00
|
|
|
GLMSearchAPIKey: cfg.Tools.Web.GLMSearch.APIKey,
|
|
|
|
|
GLMSearchBaseURL: cfg.Tools.Web.GLMSearch.BaseURL,
|
|
|
|
|
GLMSearchEngine: cfg.Tools.Web.GLMSearch.SearchEngine,
|
|
|
|
|
GLMSearchMaxResults: cfg.Tools.Web.GLMSearch.MaxResults,
|
|
|
|
|
GLMSearchEnabled: cfg.Tools.Web.GLMSearch.Enabled,
|
|
|
|
|
Proxy: cfg.Tools.Web.Proxy,
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorCF("agent", "Failed to create web search tool", map[string]any{"error": err.Error()})
|
|
|
|
|
} else if searchTool != nil {
|
|
|
|
|
agent.Tools.Register(searchTool)
|
|
|
|
|
}
|
2026-02-14 13:38:04 +00:00
|
|
|
}
|
2026-03-05 06:53:26 +00:00
|
|
|
if cfg.Tools.IsToolEnabled("web_fetch") {
|
|
|
|
|
fetchTool, err := tools.NewWebFetchToolWithProxy(50000, cfg.Tools.Web.Proxy, cfg.Tools.Web.FetchLimitBytes)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorCF("agent", "Failed to create web fetch tool", map[string]any{"error": err.Error()})
|
|
|
|
|
} else {
|
|
|
|
|
agent.Tools.Register(fetchTool)
|
|
|
|
|
}
|
2026-03-01 05:55:46 +00:00
|
|
|
}
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
|
2026-02-14 13:38:04 +00:00
|
|
|
// Hardware tools (I2C, SPI) - Linux only, returns error on other platforms
|
2026-03-05 06:53:26 +00:00
|
|
|
if cfg.Tools.IsToolEnabled("i2c") {
|
|
|
|
|
agent.Tools.Register(tools.NewI2CTool())
|
|
|
|
|
}
|
|
|
|
|
if cfg.Tools.IsToolEnabled("spi") {
|
|
|
|
|
agent.Tools.Register(tools.NewSPITool())
|
|
|
|
|
}
|
2026-02-14 13:38:04 +00:00
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
// Message tool
|
2026-03-05 06:53:26 +00:00
|
|
|
if cfg.Tools.IsToolEnabled("message") {
|
|
|
|
|
messageTool := tools.NewMessageTool()
|
|
|
|
|
messageTool.SetSendCallback(func(channel, chatID, content string) error {
|
|
|
|
|
pubCtx, pubCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
defer pubCancel()
|
|
|
|
|
return msgBus.PublishOutbound(pubCtx, bus.OutboundMessage{
|
|
|
|
|
Channel: channel,
|
|
|
|
|
ChatID: chatID,
|
|
|
|
|
Content: content,
|
|
|
|
|
})
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
})
|
2026-03-05 06:53:26 +00:00
|
|
|
agent.Tools.Register(messageTool)
|
|
|
|
|
}
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
|
feat(feishu,tools): add outbound media delivery via send_file tool (#1156)
* feat(feishu): implement SendMedia and add send_file tool
Add outbound media support for the Feishu channel so the agent can send
images and files to users via the MediaStore pipeline.
Feishu channel:
- SendMedia dispatches media parts as image or file uploads
- sendImage uploads via Image.Create then sends image message
- sendFile uploads via File.Create then sends file message
- feishuFileType maps extensions to Feishu file_type values
send_file tool:
- New tool lets the LLM send a local file to the current chat
- Validates path, registers file in MediaStore, returns media ref
- Agent loop wires tool registration, MediaStore propagation, and
context updates
Tested on Radxa Cubie A7A (arm64) with Feishu websocket channel.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): publish outbound media regardless of SendResponse flag
The SendResponse flag controls whether the agent loop publishes the
final text response (callers that publish it themselves set this to
false). However, the media publish path was also gated behind this
flag, which meant tool-produced media was silently dropped for normal
channel messages.
Media should be published immediately when a tool returns media refs,
independent of how the text response is delivered.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(tools): use magic-bytes MIME detection and add file size limit to send_file
- Replace hardcoded extension-to-MIME map with h2non/filetype (magic
bytes) + mime.TypeByExtension fallback, consistent with the vision
pipeline in resolveMediaRefs
- Add configurable max file size check (defaults to config.DefaultMaxMediaSize,
20 MB) to prevent oversized uploads
- Add tests for magic-bytes detection, extension fallback, size limit,
and default max size
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): add ForEachTool to AgentRegistry for cross-agent tool lookup
Extract the pattern of iterating agents to find a named tool into
AgentRegistry.ForEachTool, simplifying SetMediaStore propagation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent,tools): adapt send_file to ctx-based channel injection after upstream refactor
Replace ContextualTool interface (removed upstream) with direct ctx
reading in SendFileTool.Execute, using ToolChannel/ToolChatID helpers.
Remove updateToolContexts which is no longer needed since ExecuteWithContext
already injects channel/chatID into ctx for all tools.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(tools): support toggling send_file tool via config
Add SendFileConfig with Enabled field to ToolsConfig, defaulting to
true. Wrap send_file tool registration in loop.go with the config
check, consistent with the pattern used by other tools.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 11:42:52 +00:00
|
|
|
// Send file tool (outbound media via MediaStore — store injected later by SetMediaStore)
|
|
|
|
|
if cfg.Tools.IsToolEnabled("send_file") {
|
|
|
|
|
sendFileTool := tools.NewSendFileTool(
|
|
|
|
|
agent.Workspace,
|
|
|
|
|
cfg.Agents.Defaults.RestrictToWorkspace,
|
|
|
|
|
cfg.Agents.Defaults.GetMaxMediaSize(),
|
|
|
|
|
nil,
|
|
|
|
|
)
|
|
|
|
|
agent.Tools.Register(sendFileTool)
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-20 10:55:04 +00:00
|
|
|
// Skill discovery and installation tools
|
2026-03-05 12:40:06 +00:00
|
|
|
skills_enabled := cfg.Tools.IsToolEnabled("skills")
|
2026-03-05 06:53:26 +00:00
|
|
|
find_skills_enable := cfg.Tools.IsToolEnabled("find_skills")
|
|
|
|
|
install_skills_enable := cfg.Tools.IsToolEnabled("install_skill")
|
2026-03-05 12:40:06 +00:00
|
|
|
if skills_enabled && (find_skills_enable || install_skills_enable) {
|
2026-03-05 06:53:26 +00:00
|
|
|
registryMgr := skills.NewRegistryManagerFromConfig(skills.RegistryConfig{
|
|
|
|
|
MaxConcurrentSearches: cfg.Tools.Skills.MaxConcurrentSearches,
|
|
|
|
|
ClawHub: skills.ClawHubConfig(cfg.Tools.Skills.Registries.ClawHub),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if find_skills_enable {
|
|
|
|
|
searchCache := skills.NewSearchCache(
|
|
|
|
|
cfg.Tools.Skills.SearchCache.MaxSize,
|
|
|
|
|
time.Duration(cfg.Tools.Skills.SearchCache.TTLSeconds)*time.Second,
|
|
|
|
|
)
|
|
|
|
|
agent.Tools.Register(tools.NewFindSkillsTool(registryMgr, searchCache))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if install_skills_enable {
|
|
|
|
|
agent.Tools.Register(tools.NewInstallSkillTool(registryMgr, agent.Workspace))
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-20 10:55:04 +00:00
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
// Spawn tool with allowlist checker
|
2026-03-05 06:53:26 +00:00
|
|
|
if cfg.Tools.IsToolEnabled("spawn") {
|
|
|
|
|
if cfg.Tools.IsToolEnabled("subagent") {
|
2026-03-05 12:07:17 +00:00
|
|
|
subagentManager := tools.NewSubagentManager(provider, agent.Model, agent.Workspace)
|
2026-03-05 06:53:26 +00:00
|
|
|
subagentManager.SetLLMOptions(agent.MaxTokens, agent.Temperature)
|
|
|
|
|
spawnTool := tools.NewSpawnTool(subagentManager)
|
|
|
|
|
currentAgentID := agentID
|
|
|
|
|
spawnTool.SetAllowlistChecker(func(targetAgentID string) bool {
|
|
|
|
|
return registry.CanSpawnSubagent(currentAgentID, targetAgentID)
|
|
|
|
|
})
|
|
|
|
|
agent.Tools.Register(spawnTool)
|
|
|
|
|
} else {
|
|
|
|
|
logger.WarnCF("agent", "spawn tool requires subagent to be enabled", nil)
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (al *AgentLoop) Run(ctx context.Context) error {
|
2026-02-11 17:26:22 +00:00
|
|
|
al.running.Store(true)
|
2026-03-13 06:27:46 +00:00
|
|
|
|
2026-03-11 17:06:48 +00:00
|
|
|
if err := al.ensureMCPInitialized(ctx); err != nil {
|
|
|
|
|
return err
|
2026-02-19 11:06:37 +00:00
|
|
|
}
|
2026-02-16 11:56:00 +00:00
|
|
|
|
2026-02-11 17:26:22 +00:00
|
|
|
for al.running.Load() {
|
2026-02-04 11:06:13 +00:00
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
return nil
|
|
|
|
|
default:
|
|
|
|
|
msg, ok := al.bus.ConsumeInbound(ctx)
|
|
|
|
|
if !ok {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
// Start a goroutine that drains the bus while processMessage is
|
|
|
|
|
// running. Any inbound messages that arrive during processing are
|
|
|
|
|
// redirected into the steering queue so the agent loop can pick
|
|
|
|
|
// them up between tool calls.
|
|
|
|
|
drainCtx, drainCancel := context.WithCancel(ctx)
|
|
|
|
|
go al.drainBusToSteering(drainCtx)
|
|
|
|
|
|
2026-02-23 00:20:15 +00:00
|
|
|
// Process message
|
2026-02-22 15:27:55 +00:00
|
|
|
func() {
|
2026-02-23 00:20:15 +00:00
|
|
|
// TODO: Re-enable media cleanup after inbound media is properly consumed by the agent.
|
|
|
|
|
// Currently disabled because files are deleted before the LLM can access their content.
|
|
|
|
|
// defer func() {
|
|
|
|
|
// if al.mediaStore != nil && msg.MediaScope != "" {
|
|
|
|
|
// if releaseErr := al.mediaStore.ReleaseAll(msg.MediaScope); releaseErr != nil {
|
|
|
|
|
// logger.WarnCF("agent", "Failed to release media", map[string]any{
|
|
|
|
|
// "scope": msg.MediaScope,
|
|
|
|
|
// "error": releaseErr.Error(),
|
|
|
|
|
// })
|
|
|
|
|
// }
|
|
|
|
|
// }
|
|
|
|
|
// }()
|
2026-02-22 15:27:55 +00:00
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
defer drainCancel()
|
|
|
|
|
|
2026-02-22 15:27:55 +00:00
|
|
|
response, err := al.processMessage(ctx, msg)
|
|
|
|
|
if err != nil {
|
|
|
|
|
response = fmt.Sprintf("Error processing message: %v", err)
|
2026-02-13 06:41:21 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-22 15:27:55 +00:00
|
|
|
if response != "" {
|
2026-03-20 09:28:12 +00:00
|
|
|
al.publishResponseIfNeeded(ctx, msg.Channel, msg.ChatID, response)
|
|
|
|
|
}
|
2026-02-22 15:27:55 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
target, targetErr := al.buildContinuationTarget(msg)
|
|
|
|
|
if targetErr != nil {
|
|
|
|
|
logger.WarnCF("agent", "Failed to build steering continuation target",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"channel": msg.Channel,
|
|
|
|
|
"error": targetErr.Error(),
|
2026-02-22 15:27:55 +00:00
|
|
|
})
|
2026-03-20 09:28:12 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if target == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for al.pendingSteeringCount() > 0 {
|
|
|
|
|
logger.InfoCF("agent", "Continuing queued steering after turn end",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"channel": target.Channel,
|
|
|
|
|
"chat_id": target.ChatID,
|
|
|
|
|
"session_key": target.SessionKey,
|
|
|
|
|
"queue_depth": al.pendingSteeringCount(),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
continued, continueErr := al.Continue(ctx, target.SessionKey, target.Channel, target.ChatID)
|
|
|
|
|
if continueErr != nil {
|
|
|
|
|
logger.WarnCF("agent", "Failed to continue queued steering",
|
2026-02-22 20:29:27 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"channel": target.Channel,
|
|
|
|
|
"chat_id": target.ChatID,
|
|
|
|
|
"error": continueErr.Error(),
|
2026-02-22 20:29:27 +00:00
|
|
|
})
|
2026-03-20 09:28:12 +00:00
|
|
|
return
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
2026-03-20 09:28:12 +00:00
|
|
|
if continued == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
al.publishResponseIfNeeded(ctx, target.Channel, target.ChatID, continued)
|
2026-02-23 23:50:55 +00:00
|
|
|
}
|
2026-02-22 15:27:55 +00:00
|
|
|
}()
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
// drainBusToSteering continuously consumes inbound messages and redirects
|
|
|
|
|
// them into the steering queue. It runs in a goroutine while processMessage
|
|
|
|
|
// is active and stops when drainCtx is canceled (i.e., processMessage returns).
|
|
|
|
|
func (al *AgentLoop) drainBusToSteering(ctx context.Context) {
|
|
|
|
|
for {
|
|
|
|
|
msg, ok := al.bus.ConsumeInbound(ctx)
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Transcribe audio if needed before steering, so the agent sees text.
|
|
|
|
|
msg, _ = al.transcribeAudioInMessage(ctx, msg)
|
|
|
|
|
|
|
|
|
|
logger.InfoCF("agent", "Redirecting inbound message to steering queue",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"channel": msg.Channel,
|
|
|
|
|
"sender_id": msg.SenderID,
|
|
|
|
|
"content_len": len(msg.Content),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if err := al.Steer(providers.Message{
|
|
|
|
|
Role: "user",
|
|
|
|
|
Content: msg.Content,
|
|
|
|
|
}); err != nil {
|
|
|
|
|
logger.WarnCF("agent", "Failed to steer message, will be lost",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"error": err.Error(),
|
|
|
|
|
"channel": msg.Channel,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-04 11:06:13 +00:00
|
|
|
func (al *AgentLoop) Stop() {
|
2026-02-11 17:26:22 +00:00
|
|
|
al.running.Store(false)
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
func (al *AgentLoop) publishResponseIfNeeded(ctx context.Context, channel, chatID, response string) {
|
|
|
|
|
if response == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
alreadySent := false
|
|
|
|
|
defaultAgent := al.GetRegistry().GetDefaultAgent()
|
|
|
|
|
if defaultAgent != nil {
|
|
|
|
|
if tool, ok := defaultAgent.Tools.Get("message"); ok {
|
|
|
|
|
if mt, ok := tool.(*tools.MessageTool); ok {
|
|
|
|
|
alreadySent = mt.HasSentInRound()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if alreadySent {
|
|
|
|
|
logger.DebugCF(
|
|
|
|
|
"agent",
|
|
|
|
|
"Skipped outbound (message tool already sent)",
|
|
|
|
|
map[string]any{"channel": channel},
|
|
|
|
|
)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
al.bus.PublishOutbound(ctx, bus.OutboundMessage{
|
|
|
|
|
Channel: channel,
|
|
|
|
|
ChatID: chatID,
|
|
|
|
|
Content: response,
|
|
|
|
|
})
|
|
|
|
|
logger.InfoCF("agent", "Published outbound response",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"channel": channel,
|
|
|
|
|
"chat_id": chatID,
|
|
|
|
|
"content_len": len(response),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (al *AgentLoop) pendingSteeringCount() int {
|
|
|
|
|
if al.steering == nil {
|
|
|
|
|
return 0
|
|
|
|
|
}
|
|
|
|
|
return al.steering.len()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (al *AgentLoop) buildContinuationTarget(msg bus.InboundMessage) (*continuationTarget, error) {
|
|
|
|
|
if msg.Channel == "system" {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
route, _, err := al.resolveMessageRoute(msg)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &continuationTarget{
|
|
|
|
|
SessionKey: resolveScopeKey(route, msg.SessionKey),
|
|
|
|
|
Channel: msg.Channel,
|
|
|
|
|
ChatID: msg.ChatID,
|
|
|
|
|
}, nil
|
|
|
|
|
}
|
|
|
|
|
|
feat(session): integrate JSONL persistence into agent loop (#1170)
* feat(session): add SessionStore interface and JSONL backend adapter
Extract a SessionStore interface from the methods the agent loop uses
(AddMessage, GetHistory, SetSummary, TruncateHistory, Save, etc.).
Both SessionManager and the new JSONLBackend satisfy this interface,
allowing the persistence layer to be swapped transparently.
JSONLBackend wraps memory.Store and maps its error-returning API to
the fire-and-forget contract that the agent loop expects — write
errors are logged, reads return empty defaults on failure. Save()
triggers compaction to reclaim space after logical truncation.
Part of #1169
* test(session): add JSONLBackend integration tests
8 tests covering the full SessionStore contract through the JSONL
backend: message roundtrip, tool calls, summary, truncation with
compaction, history replacement, empty sessions, session isolation,
and the complete summarization flow (SetSummary → TruncateHistory →
Save).
Includes compile-time interface satisfaction checks for both
SessionManager and JSONLBackend.
Part of #1169
* feat(agent): wire JSONL session store into agent loop
Replace the concrete *SessionManager field with the SessionStore
interface and initialize the JSONL backend by default. Legacy .json
session files are auto-migrated on first startup. Falls back to
SessionManager if the JSONL store cannot be initialized.
The agent loop code (loop.go) requires zero changes — all method
calls work identically through the interface.
Closes #1169
* fix(session): propagate compact error from Save
Save() was swallowing the error returned by Compact and always
returning nil. Callers checking Save's return value would never
see a compaction failure. Return the error directly so the agent
loop can log or handle it as needed.
* feat(session): add Close to SessionStore interface
Add Close() error to SessionStore so callers can release resources
through the interface. JSONLBackend already had Close; this adds
a no-op implementation to SessionManager for compatibility.
* fix(session): close session stores on shutdown and harden migration
- Add Close() to AgentInstance, AgentRegistry, and AgentLoop so JSONL
file handles are released during gateway shutdown and CLI exit.
- Fall back to SessionManager when migration fails, preventing a split
state where some sessions live in JSONL and others remain in JSON.
- Add defer agentLoop.Close() in the CLI agent command path.
- Document SessionStore interface methods (fire-and-forget contract).
2026-03-10 07:14:09 +00:00
|
|
|
// Close releases resources held by agent session stores. Call after Stop.
|
|
|
|
|
func (al *AgentLoop) Close() {
|
2026-03-11 17:06:48 +00:00
|
|
|
mcpManager := al.mcp.takeManager()
|
|
|
|
|
|
|
|
|
|
if mcpManager != nil {
|
|
|
|
|
if err := mcpManager.Close(); err != nil {
|
|
|
|
|
logger.ErrorCF("agent", "Failed to close MCP manager",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"error": err.Error(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 06:27:46 +00:00
|
|
|
al.GetRegistry().Close()
|
2026-03-20 06:53:22 +00:00
|
|
|
if al.eventBus != nil {
|
|
|
|
|
al.eventBus.Close()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SubscribeEvents registers a subscriber for agent-loop events.
|
|
|
|
|
func (al *AgentLoop) SubscribeEvents(buffer int) EventSubscription {
|
|
|
|
|
if al == nil || al.eventBus == nil {
|
|
|
|
|
ch := make(chan Event)
|
|
|
|
|
close(ch)
|
|
|
|
|
return EventSubscription{C: ch}
|
|
|
|
|
}
|
|
|
|
|
return al.eventBus.Subscribe(buffer)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// UnsubscribeEvents removes a previously registered event subscriber.
|
|
|
|
|
func (al *AgentLoop) UnsubscribeEvents(id uint64) {
|
|
|
|
|
if al == nil || al.eventBus == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
al.eventBus.Unsubscribe(id)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// EventDrops returns the number of dropped events for the given kind.
|
|
|
|
|
func (al *AgentLoop) EventDrops(kind EventKind) int64 {
|
|
|
|
|
if al == nil || al.eventBus == nil {
|
|
|
|
|
return 0
|
|
|
|
|
}
|
|
|
|
|
return al.eventBus.Dropped(kind)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type turnEventScope struct {
|
|
|
|
|
agentID string
|
|
|
|
|
sessionKey string
|
|
|
|
|
turnID string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (al *AgentLoop) newTurnEventScope(agentID, sessionKey string) turnEventScope {
|
|
|
|
|
seq := al.turnSeq.Add(1)
|
|
|
|
|
return turnEventScope{
|
|
|
|
|
agentID: agentID,
|
|
|
|
|
sessionKey: sessionKey,
|
|
|
|
|
turnID: fmt.Sprintf("%s-turn-%d", agentID, seq),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (ts turnEventScope) meta(iteration int, source, tracePath string) EventMeta {
|
|
|
|
|
return EventMeta{
|
|
|
|
|
AgentID: ts.agentID,
|
|
|
|
|
TurnID: ts.turnID,
|
|
|
|
|
SessionKey: ts.sessionKey,
|
|
|
|
|
Iteration: iteration,
|
|
|
|
|
Source: source,
|
|
|
|
|
TracePath: tracePath,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (al *AgentLoop) emitEvent(kind EventKind, meta EventMeta, payload any) {
|
2026-03-20 07:06:43 +00:00
|
|
|
evt := Event{
|
2026-03-20 06:53:22 +00:00
|
|
|
Kind: kind,
|
|
|
|
|
Meta: meta,
|
|
|
|
|
Payload: payload,
|
2026-03-20 07:06:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
al.logEvent(evt)
|
|
|
|
|
|
|
|
|
|
if al == nil || al.eventBus == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
al.eventBus.Emit(evt)
|
2026-03-20 06:53:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func cloneEventArguments(args map[string]any) map[string]any {
|
|
|
|
|
if len(args) == 0 {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
cloned := make(map[string]any, len(args))
|
|
|
|
|
for k, v := range args {
|
|
|
|
|
cloned[k] = v
|
|
|
|
|
}
|
|
|
|
|
return cloned
|
feat(session): integrate JSONL persistence into agent loop (#1170)
* feat(session): add SessionStore interface and JSONL backend adapter
Extract a SessionStore interface from the methods the agent loop uses
(AddMessage, GetHistory, SetSummary, TruncateHistory, Save, etc.).
Both SessionManager and the new JSONLBackend satisfy this interface,
allowing the persistence layer to be swapped transparently.
JSONLBackend wraps memory.Store and maps its error-returning API to
the fire-and-forget contract that the agent loop expects — write
errors are logged, reads return empty defaults on failure. Save()
triggers compaction to reclaim space after logical truncation.
Part of #1169
* test(session): add JSONLBackend integration tests
8 tests covering the full SessionStore contract through the JSONL
backend: message roundtrip, tool calls, summary, truncation with
compaction, history replacement, empty sessions, session isolation,
and the complete summarization flow (SetSummary → TruncateHistory →
Save).
Includes compile-time interface satisfaction checks for both
SessionManager and JSONLBackend.
Part of #1169
* feat(agent): wire JSONL session store into agent loop
Replace the concrete *SessionManager field with the SessionStore
interface and initialize the JSONL backend by default. Legacy .json
session files are auto-migrated on first startup. Falls back to
SessionManager if the JSONL store cannot be initialized.
The agent loop code (loop.go) requires zero changes — all method
calls work identically through the interface.
Closes #1169
* fix(session): propagate compact error from Save
Save() was swallowing the error returned by Compact and always
returning nil. Callers checking Save's return value would never
see a compaction failure. Return the error directly so the agent
loop can log or handle it as needed.
* feat(session): add Close to SessionStore interface
Add Close() error to SessionStore so callers can release resources
through the interface. JSONLBackend already had Close; this adds
a no-op implementation to SessionManager for compatibility.
* fix(session): close session stores on shutdown and harden migration
- Add Close() to AgentInstance, AgentRegistry, and AgentLoop so JSONL
file handles are released during gateway shutdown and CLI exit.
- Fall back to SessionManager when migration fails, preventing a split
state where some sessions live in JSONL and others remain in JSON.
- Add defer agentLoop.Close() in the CLI agent command path.
- Document SessionStore interface methods (fire-and-forget contract).
2026-03-10 07:14:09 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 07:06:43 +00:00
|
|
|
func (al *AgentLoop) logEvent(evt Event) {
|
|
|
|
|
fields := map[string]any{
|
|
|
|
|
"event_kind": evt.Kind.String(),
|
|
|
|
|
"agent_id": evt.Meta.AgentID,
|
|
|
|
|
"turn_id": evt.Meta.TurnID,
|
|
|
|
|
"session_key": evt.Meta.SessionKey,
|
|
|
|
|
"iteration": evt.Meta.Iteration,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if evt.Meta.TracePath != "" {
|
|
|
|
|
fields["trace"] = evt.Meta.TracePath
|
|
|
|
|
}
|
|
|
|
|
if evt.Meta.Source != "" {
|
|
|
|
|
fields["source"] = evt.Meta.Source
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
switch payload := evt.Payload.(type) {
|
|
|
|
|
case TurnStartPayload:
|
|
|
|
|
fields["channel"] = payload.Channel
|
|
|
|
|
fields["chat_id"] = payload.ChatID
|
|
|
|
|
fields["user_len"] = len(payload.UserMessage)
|
|
|
|
|
fields["media_count"] = payload.MediaCount
|
|
|
|
|
case TurnEndPayload:
|
|
|
|
|
fields["status"] = payload.Status
|
|
|
|
|
fields["iterations_total"] = payload.Iterations
|
|
|
|
|
fields["duration_ms"] = payload.Duration.Milliseconds()
|
|
|
|
|
fields["final_len"] = payload.FinalContentLen
|
|
|
|
|
case LLMRequestPayload:
|
|
|
|
|
fields["model"] = payload.Model
|
|
|
|
|
fields["messages"] = payload.MessagesCount
|
|
|
|
|
fields["tools"] = payload.ToolsCount
|
|
|
|
|
fields["max_tokens"] = payload.MaxTokens
|
2026-03-20 07:29:52 +00:00
|
|
|
case LLMDeltaPayload:
|
|
|
|
|
fields["content_delta_len"] = payload.ContentDeltaLen
|
|
|
|
|
fields["reasoning_delta_len"] = payload.ReasoningDeltaLen
|
2026-03-20 07:06:43 +00:00
|
|
|
case LLMResponsePayload:
|
|
|
|
|
fields["content_len"] = payload.ContentLen
|
|
|
|
|
fields["tool_calls"] = payload.ToolCalls
|
|
|
|
|
fields["has_reasoning"] = payload.HasReasoning
|
2026-03-20 07:29:52 +00:00
|
|
|
case LLMRetryPayload:
|
|
|
|
|
fields["attempt"] = payload.Attempt
|
|
|
|
|
fields["max_retries"] = payload.MaxRetries
|
|
|
|
|
fields["reason"] = payload.Reason
|
|
|
|
|
fields["error"] = payload.Error
|
|
|
|
|
fields["backoff_ms"] = payload.Backoff.Milliseconds()
|
|
|
|
|
case ContextCompressPayload:
|
|
|
|
|
fields["reason"] = payload.Reason
|
|
|
|
|
fields["dropped_messages"] = payload.DroppedMessages
|
|
|
|
|
fields["remaining_messages"] = payload.RemainingMessages
|
|
|
|
|
case SessionSummarizePayload:
|
|
|
|
|
fields["summarized_messages"] = payload.SummarizedMessages
|
|
|
|
|
fields["kept_messages"] = payload.KeptMessages
|
|
|
|
|
fields["summary_len"] = payload.SummaryLen
|
|
|
|
|
fields["omitted_oversized"] = payload.OmittedOversized
|
2026-03-20 07:06:43 +00:00
|
|
|
case ToolExecStartPayload:
|
|
|
|
|
fields["tool"] = payload.Tool
|
|
|
|
|
fields["args_count"] = len(payload.Arguments)
|
|
|
|
|
case ToolExecEndPayload:
|
|
|
|
|
fields["tool"] = payload.Tool
|
|
|
|
|
fields["duration_ms"] = payload.Duration.Milliseconds()
|
|
|
|
|
fields["for_llm_len"] = payload.ForLLMLen
|
|
|
|
|
fields["for_user_len"] = payload.ForUserLen
|
|
|
|
|
fields["is_error"] = payload.IsError
|
|
|
|
|
fields["async"] = payload.Async
|
2026-03-20 07:29:52 +00:00
|
|
|
case ToolExecSkippedPayload:
|
|
|
|
|
fields["tool"] = payload.Tool
|
|
|
|
|
fields["reason"] = payload.Reason
|
|
|
|
|
case SteeringInjectedPayload:
|
|
|
|
|
fields["count"] = payload.Count
|
|
|
|
|
fields["total_content_len"] = payload.TotalContentLen
|
|
|
|
|
case FollowUpQueuedPayload:
|
|
|
|
|
fields["source_tool"] = payload.SourceTool
|
|
|
|
|
fields["channel"] = payload.Channel
|
|
|
|
|
fields["chat_id"] = payload.ChatID
|
|
|
|
|
fields["content_len"] = payload.ContentLen
|
|
|
|
|
case InterruptReceivedPayload:
|
2026-03-20 09:28:12 +00:00
|
|
|
fields["interrupt_kind"] = payload.Kind
|
2026-03-20 07:29:52 +00:00
|
|
|
fields["role"] = payload.Role
|
|
|
|
|
fields["content_len"] = payload.ContentLen
|
|
|
|
|
fields["queue_depth"] = payload.QueueDepth
|
2026-03-20 09:28:12 +00:00
|
|
|
fields["hint_len"] = payload.HintLen
|
2026-03-20 07:29:52 +00:00
|
|
|
case SubTurnSpawnPayload:
|
|
|
|
|
fields["child_agent_id"] = payload.AgentID
|
|
|
|
|
fields["label"] = payload.Label
|
|
|
|
|
case SubTurnEndPayload:
|
|
|
|
|
fields["child_agent_id"] = payload.AgentID
|
|
|
|
|
fields["status"] = payload.Status
|
|
|
|
|
case SubTurnResultDeliveredPayload:
|
|
|
|
|
fields["target_channel"] = payload.TargetChannel
|
|
|
|
|
fields["target_chat_id"] = payload.TargetChatID
|
|
|
|
|
fields["content_len"] = payload.ContentLen
|
2026-03-20 07:06:43 +00:00
|
|
|
case ErrorPayload:
|
|
|
|
|
fields["stage"] = payload.Stage
|
|
|
|
|
fields["error"] = payload.Message
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.InfoCF("eventbus", fmt.Sprintf("Agent event: %s", evt.Kind.String()), fields)
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-11 04:28:37 +00:00
|
|
|
func (al *AgentLoop) RegisterTool(tool tools.Tool) {
|
2026-03-13 06:27:46 +00:00
|
|
|
registry := al.GetRegistry()
|
|
|
|
|
for _, agentID := range registry.ListAgentIDs() {
|
|
|
|
|
if agent, ok := registry.GetAgent(agentID); ok {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
agent.Tools.Register(tool)
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-16 08:30:54 +00:00
|
|
|
func (al *AgentLoop) SetChannelManager(cm *channels.Manager) {
|
|
|
|
|
al.channelManager = cm
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 06:27:46 +00:00
|
|
|
// ReloadProviderAndConfig atomically swaps the provider and config with proper synchronization.
|
|
|
|
|
// It uses a context to allow timeout control from the caller.
|
|
|
|
|
// Returns an error if the reload fails or context is canceled.
|
|
|
|
|
func (al *AgentLoop) ReloadProviderAndConfig(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
provider providers.LLMProvider,
|
|
|
|
|
cfg *config.Config,
|
|
|
|
|
) error {
|
|
|
|
|
// Validate inputs
|
|
|
|
|
if provider == nil {
|
|
|
|
|
return fmt.Errorf("provider cannot be nil")
|
|
|
|
|
}
|
|
|
|
|
if cfg == nil {
|
|
|
|
|
return fmt.Errorf("config cannot be nil")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create new registry with updated config and provider
|
|
|
|
|
// Wrap in defer/recover to handle any panics gracefully
|
|
|
|
|
var registry *AgentRegistry
|
|
|
|
|
var panicErr error
|
|
|
|
|
done := make(chan struct{}, 1)
|
|
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
defer func() {
|
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
|
panicErr = fmt.Errorf("panic during registry creation: %v", r)
|
|
|
|
|
logger.ErrorCF("agent", "Panic during registry creation",
|
|
|
|
|
map[string]any{"panic": r})
|
|
|
|
|
}
|
|
|
|
|
close(done)
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
registry = NewAgentRegistry(cfg, provider)
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
// Wait for completion or context cancellation
|
|
|
|
|
select {
|
|
|
|
|
case <-done:
|
|
|
|
|
if registry == nil {
|
|
|
|
|
if panicErr != nil {
|
|
|
|
|
return fmt.Errorf("registry creation failed: %w", panicErr)
|
|
|
|
|
}
|
|
|
|
|
return fmt.Errorf("registry creation failed (nil result)")
|
|
|
|
|
}
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
return fmt.Errorf("context canceled during registry creation: %w", ctx.Err())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check context again before proceeding
|
|
|
|
|
if err := ctx.Err(); err != nil {
|
|
|
|
|
return fmt.Errorf("context canceled after registry creation: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Ensure shared tools are re-registered on the new registry
|
|
|
|
|
registerSharedTools(cfg, al.bus, registry, provider)
|
|
|
|
|
|
|
|
|
|
// Atomically swap the config and registry under write lock
|
|
|
|
|
// This ensures readers see a consistent pair
|
|
|
|
|
al.mu.Lock()
|
|
|
|
|
oldRegistry := al.registry
|
|
|
|
|
|
|
|
|
|
// Store new values
|
|
|
|
|
al.cfg = cfg
|
|
|
|
|
al.registry = registry
|
|
|
|
|
|
|
|
|
|
// Also update fallback chain with new config
|
|
|
|
|
al.fallback = providers.NewFallbackChain(providers.NewCooldownTracker())
|
|
|
|
|
|
|
|
|
|
al.mu.Unlock()
|
|
|
|
|
|
|
|
|
|
// Close old provider after releasing the lock
|
|
|
|
|
// This prevents blocking readers while closing
|
|
|
|
|
if oldProvider, ok := extractProvider(oldRegistry); ok {
|
|
|
|
|
if stateful, ok := oldProvider.(providers.StatefulProvider); ok {
|
|
|
|
|
// Give in-flight requests a moment to complete
|
|
|
|
|
// Use a reasonable timeout that balances cleanup vs resource usage
|
|
|
|
|
select {
|
|
|
|
|
case <-time.After(100 * time.Millisecond):
|
|
|
|
|
stateful.Close()
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
// Context canceled, close immediately but log warning
|
|
|
|
|
logger.WarnCF("agent", "Context canceled during provider cleanup, forcing close",
|
|
|
|
|
map[string]any{"error": ctx.Err()})
|
|
|
|
|
stateful.Close()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.InfoCF("agent", "Provider and config reloaded successfully",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"model": cfg.Agents.Defaults.GetModelName(),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetRegistry returns the current registry (thread-safe)
|
|
|
|
|
func (al *AgentLoop) GetRegistry() *AgentRegistry {
|
|
|
|
|
al.mu.RLock()
|
|
|
|
|
defer al.mu.RUnlock()
|
|
|
|
|
return al.registry
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetConfig returns the current config (thread-safe)
|
|
|
|
|
func (al *AgentLoop) GetConfig() *config.Config {
|
|
|
|
|
al.mu.RLock()
|
|
|
|
|
defer al.mu.RUnlock()
|
|
|
|
|
return al.cfg
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-22 15:27:55 +00:00
|
|
|
// SetMediaStore injects a MediaStore for media lifecycle management.
|
|
|
|
|
func (al *AgentLoop) SetMediaStore(s media.MediaStore) {
|
|
|
|
|
al.mediaStore = s
|
feat(feishu,tools): add outbound media delivery via send_file tool (#1156)
* feat(feishu): implement SendMedia and add send_file tool
Add outbound media support for the Feishu channel so the agent can send
images and files to users via the MediaStore pipeline.
Feishu channel:
- SendMedia dispatches media parts as image or file uploads
- sendImage uploads via Image.Create then sends image message
- sendFile uploads via File.Create then sends file message
- feishuFileType maps extensions to Feishu file_type values
send_file tool:
- New tool lets the LLM send a local file to the current chat
- Validates path, registers file in MediaStore, returns media ref
- Agent loop wires tool registration, MediaStore propagation, and
context updates
Tested on Radxa Cubie A7A (arm64) with Feishu websocket channel.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): publish outbound media regardless of SendResponse flag
The SendResponse flag controls whether the agent loop publishes the
final text response (callers that publish it themselves set this to
false). However, the media publish path was also gated behind this
flag, which meant tool-produced media was silently dropped for normal
channel messages.
Media should be published immediately when a tool returns media refs,
independent of how the text response is delivered.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(tools): use magic-bytes MIME detection and add file size limit to send_file
- Replace hardcoded extension-to-MIME map with h2non/filetype (magic
bytes) + mime.TypeByExtension fallback, consistent with the vision
pipeline in resolveMediaRefs
- Add configurable max file size check (defaults to config.DefaultMaxMediaSize,
20 MB) to prevent oversized uploads
- Add tests for magic-bytes detection, extension fallback, size limit,
and default max size
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): add ForEachTool to AgentRegistry for cross-agent tool lookup
Extract the pattern of iterating agents to find a named tool into
AgentRegistry.ForEachTool, simplifying SetMediaStore propagation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent,tools): adapt send_file to ctx-based channel injection after upstream refactor
Replace ContextualTool interface (removed upstream) with direct ctx
reading in SendFileTool.Execute, using ToolChannel/ToolChatID helpers.
Remove updateToolContexts which is no longer needed since ExecuteWithContext
already injects channel/chatID into ctx for all tools.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(tools): support toggling send_file tool via config
Add SendFileConfig with Enabled field to ToolsConfig, defaulting to
true. Wrap send_file tool registration in loop.go with the config
check, consistent with the pattern used by other tools.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 11:42:52 +00:00
|
|
|
|
|
|
|
|
// Propagate store to send_file tools in all agents.
|
2026-03-13 06:27:46 +00:00
|
|
|
registry := al.GetRegistry()
|
|
|
|
|
registry.ForEachTool("send_file", func(t tools.Tool) {
|
feat(feishu,tools): add outbound media delivery via send_file tool (#1156)
* feat(feishu): implement SendMedia and add send_file tool
Add outbound media support for the Feishu channel so the agent can send
images and files to users via the MediaStore pipeline.
Feishu channel:
- SendMedia dispatches media parts as image or file uploads
- sendImage uploads via Image.Create then sends image message
- sendFile uploads via File.Create then sends file message
- feishuFileType maps extensions to Feishu file_type values
send_file tool:
- New tool lets the LLM send a local file to the current chat
- Validates path, registers file in MediaStore, returns media ref
- Agent loop wires tool registration, MediaStore propagation, and
context updates
Tested on Radxa Cubie A7A (arm64) with Feishu websocket channel.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): publish outbound media regardless of SendResponse flag
The SendResponse flag controls whether the agent loop publishes the
final text response (callers that publish it themselves set this to
false). However, the media publish path was also gated behind this
flag, which meant tool-produced media was silently dropped for normal
channel messages.
Media should be published immediately when a tool returns media refs,
independent of how the text response is delivered.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(tools): use magic-bytes MIME detection and add file size limit to send_file
- Replace hardcoded extension-to-MIME map with h2non/filetype (magic
bytes) + mime.TypeByExtension fallback, consistent with the vision
pipeline in resolveMediaRefs
- Add configurable max file size check (defaults to config.DefaultMaxMediaSize,
20 MB) to prevent oversized uploads
- Add tests for magic-bytes detection, extension fallback, size limit,
and default max size
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): add ForEachTool to AgentRegistry for cross-agent tool lookup
Extract the pattern of iterating agents to find a named tool into
AgentRegistry.ForEachTool, simplifying SetMediaStore propagation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent,tools): adapt send_file to ctx-based channel injection after upstream refactor
Replace ContextualTool interface (removed upstream) with direct ctx
reading in SendFileTool.Execute, using ToolChannel/ToolChatID helpers.
Remove updateToolContexts which is no longer needed since ExecuteWithContext
already injects channel/chatID into ctx for all tools.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(tools): support toggling send_file tool via config
Add SendFileConfig with Enabled field to ToolsConfig, defaulting to
true. Wrap send_file tool registration in loop.go with the config
check, consistent with the pattern used by other tools.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 11:42:52 +00:00
|
|
|
if sf, ok := t.(*tools.SendFileTool); ok {
|
|
|
|
|
sf.SetMediaStore(s)
|
|
|
|
|
}
|
|
|
|
|
})
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-01 08:31:04 +00:00
|
|
|
// SetTranscriber injects a voice transcriber for agent-level audio transcription.
|
|
|
|
|
func (al *AgentLoop) SetTranscriber(t voice.Transcriber) {
|
|
|
|
|
al.transcriber = t
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var audioAnnotationRe = regexp.MustCompile(`\[(voice|audio)(?::[^\]]*)?\]`)
|
|
|
|
|
|
|
|
|
|
// transcribeAudioInMessage resolves audio media refs, transcribes them, and
|
|
|
|
|
// replaces audio annotations in msg.Content with the transcribed text.
|
2026-03-08 17:22:15 +00:00
|
|
|
// Returns the (possibly modified) message and true if audio was transcribed.
|
|
|
|
|
func (al *AgentLoop) transcribeAudioInMessage(ctx context.Context, msg bus.InboundMessage) (bus.InboundMessage, bool) {
|
2026-03-01 21:02:16 +00:00
|
|
|
if al.transcriber == nil || al.mediaStore == nil || len(msg.Media) == 0 {
|
2026-03-08 17:22:15 +00:00
|
|
|
return msg, false
|
2026-03-01 08:31:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Transcribe each audio media ref in order.
|
|
|
|
|
var transcriptions []string
|
|
|
|
|
for _, ref := range msg.Media {
|
|
|
|
|
path, meta, err := al.mediaStore.ResolveWithMeta(ref)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.WarnCF("voice", "Failed to resolve media ref", map[string]any{"ref": ref, "error": err})
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if !utils.IsAudioFile(meta.Filename, meta.ContentType) {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
result, err := al.transcriber.Transcribe(ctx, path)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.WarnCF("voice", "Transcription failed", map[string]any{"ref": ref, "error": err})
|
|
|
|
|
transcriptions = append(transcriptions, "")
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
transcriptions = append(transcriptions, result.Text)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(transcriptions) == 0 {
|
2026-03-08 17:22:15 +00:00
|
|
|
return msg, false
|
2026-03-01 08:31:04 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-08 17:22:15 +00:00
|
|
|
al.sendTranscriptionFeedback(ctx, msg.Channel, msg.ChatID, msg.MessageID, transcriptions)
|
2026-03-08 17:00:02 +00:00
|
|
|
|
2026-03-01 08:31:04 +00:00
|
|
|
// Replace audio annotations sequentially with transcriptions.
|
|
|
|
|
idx := 0
|
|
|
|
|
newContent := audioAnnotationRe.ReplaceAllStringFunc(msg.Content, func(match string) string {
|
|
|
|
|
if idx >= len(transcriptions) {
|
|
|
|
|
return match
|
|
|
|
|
}
|
|
|
|
|
text := transcriptions[idx]
|
|
|
|
|
idx++
|
|
|
|
|
return "[voice: " + text + "]"
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// Append any remaining transcriptions not matched by an annotation.
|
|
|
|
|
for ; idx < len(transcriptions); idx++ {
|
|
|
|
|
newContent += "\n[voice: " + transcriptions[idx] + "]"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
msg.Content = newContent
|
2026-03-08 17:22:15 +00:00
|
|
|
return msg, true
|
2026-03-01 08:31:04 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-08 17:22:15 +00:00
|
|
|
// sendTranscriptionFeedback sends feedback to the user with the result of
|
2026-03-09 10:38:23 +00:00
|
|
|
// audio transcription if the option is enabled. It uses Manager.SendMessage
|
|
|
|
|
// which executes synchronously (rate limiting, splitting, retry) so that
|
|
|
|
|
// ordering with the subsequent placeholder is guaranteed.
|
2026-03-08 17:22:15 +00:00
|
|
|
func (al *AgentLoop) sendTranscriptionFeedback(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
channel, chatID, messageID string,
|
|
|
|
|
validTexts []string,
|
|
|
|
|
) {
|
2026-03-07 14:49:33 +00:00
|
|
|
if !al.cfg.Voice.EchoTranscription {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-03-08 17:22:15 +00:00
|
|
|
if al.channelManager == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-03-07 14:49:33 +00:00
|
|
|
|
2026-03-08 17:22:15 +00:00
|
|
|
var nonEmpty []string
|
|
|
|
|
for _, t := range validTexts {
|
|
|
|
|
if t != "" {
|
|
|
|
|
nonEmpty = append(nonEmpty, t)
|
2026-03-08 17:00:02 +00:00
|
|
|
}
|
2026-03-08 17:22:15 +00:00
|
|
|
}
|
2026-03-08 17:00:02 +00:00
|
|
|
|
2026-03-08 17:22:15 +00:00
|
|
|
var feedbackMsg string
|
|
|
|
|
if len(nonEmpty) > 0 {
|
|
|
|
|
feedbackMsg = "Transcript: " + strings.Join(nonEmpty, "\n")
|
|
|
|
|
} else {
|
|
|
|
|
feedbackMsg = "No voice detected in the audio"
|
|
|
|
|
}
|
2026-03-07 14:49:33 +00:00
|
|
|
|
2026-03-09 10:38:23 +00:00
|
|
|
err := al.channelManager.SendMessage(ctx, bus.OutboundMessage{
|
2026-03-08 17:22:15 +00:00
|
|
|
Channel: channel,
|
|
|
|
|
ChatID: chatID,
|
|
|
|
|
Content: feedbackMsg,
|
|
|
|
|
ReplyToMessageID: messageID,
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.WarnCF("voice", "Failed to send transcription feedback", map[string]any{"error": err.Error()})
|
|
|
|
|
}
|
2026-03-07 14:49:33 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-22 22:03:23 +00:00
|
|
|
// inferMediaType determines the media type ("image", "audio", "video", "file")
|
|
|
|
|
// from a filename and MIME content type.
|
|
|
|
|
func inferMediaType(filename, contentType string) string {
|
|
|
|
|
ct := strings.ToLower(contentType)
|
|
|
|
|
fn := strings.ToLower(filename)
|
|
|
|
|
|
|
|
|
|
if strings.HasPrefix(ct, "image/") {
|
|
|
|
|
return "image"
|
|
|
|
|
}
|
|
|
|
|
if strings.HasPrefix(ct, "audio/") || ct == "application/ogg" {
|
|
|
|
|
return "audio"
|
|
|
|
|
}
|
|
|
|
|
if strings.HasPrefix(ct, "video/") {
|
|
|
|
|
return "video"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Fallback: infer from extension
|
|
|
|
|
ext := filepath.Ext(fn)
|
|
|
|
|
switch ext {
|
|
|
|
|
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg":
|
|
|
|
|
return "image"
|
|
|
|
|
case ".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac", ".wma", ".opus":
|
|
|
|
|
return "audio"
|
|
|
|
|
case ".mp4", ".avi", ".mov", ".webm", ".mkv":
|
|
|
|
|
return "video"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return "file"
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 11:49:36 +00:00
|
|
|
// RecordLastChannel records the last active channel for this workspace.
|
|
|
|
|
// This uses the atomic state save mechanism to prevent data loss on crash.
|
|
|
|
|
func (al *AgentLoop) RecordLastChannel(channel string) error {
|
2026-02-13 15:24:26 +00:00
|
|
|
if al.state == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2026-02-12 15:51:52 +00:00
|
|
|
return al.state.SetLastChannel(channel)
|
2026-02-12 11:49:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RecordLastChatID records the last active chat ID for this workspace.
|
|
|
|
|
// This uses the atomic state save mechanism to prevent data loss on crash.
|
|
|
|
|
func (al *AgentLoop) RecordLastChatID(chatID string) error {
|
2026-02-13 15:24:26 +00:00
|
|
|
if al.state == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2026-02-12 15:51:52 +00:00
|
|
|
return al.state.SetLastChatID(chatID)
|
2026-02-12 11:49:36 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-01 00:53:13 +00:00
|
|
|
func (al *AgentLoop) ProcessDirect(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
content, sessionKey string,
|
|
|
|
|
) (string, error) {
|
2026-02-11 04:28:37 +00:00
|
|
|
return al.ProcessDirectWithChannel(ctx, content, sessionKey, "cli", "direct")
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-20 18:03:11 +00:00
|
|
|
func (al *AgentLoop) ProcessDirectWithChannel(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
content, sessionKey, channel, chatID string,
|
|
|
|
|
) (string, error) {
|
2026-03-11 17:06:48 +00:00
|
|
|
if err := al.ensureMCPInitialized(ctx); err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-04 11:06:13 +00:00
|
|
|
msg := bus.InboundMessage{
|
2026-02-11 04:28:37 +00:00
|
|
|
Channel: channel,
|
|
|
|
|
SenderID: "cron",
|
|
|
|
|
ChatID: chatID,
|
2026-02-04 11:06:13 +00:00
|
|
|
Content: content,
|
|
|
|
|
SessionKey: sessionKey,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return al.processMessage(ctx, msg)
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-13 06:39:39 +00:00
|
|
|
// ProcessHeartbeat processes a heartbeat request without session history.
|
|
|
|
|
// Each heartbeat is independent and doesn't accumulate context.
|
2026-03-01 00:53:13 +00:00
|
|
|
func (al *AgentLoop) ProcessHeartbeat(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
content, channel, chatID string,
|
|
|
|
|
) (string, error) {
|
2026-03-13 06:27:46 +00:00
|
|
|
agent := al.GetRegistry().GetDefaultAgent()
|
2026-02-22 20:29:27 +00:00
|
|
|
if agent == nil {
|
|
|
|
|
return "", fmt.Errorf("no default agent for heartbeat")
|
|
|
|
|
}
|
2026-02-13 15:24:26 +00:00
|
|
|
return al.runAgentLoop(ctx, agent, processOptions{
|
2026-02-13 06:39:39 +00:00
|
|
|
SessionKey: "heartbeat",
|
|
|
|
|
Channel: channel,
|
|
|
|
|
ChatID: chatID,
|
|
|
|
|
UserMessage: content,
|
2026-02-27 07:42:47 +00:00
|
|
|
DefaultResponse: defaultResponse,
|
2026-02-13 06:39:39 +00:00
|
|
|
EnableSummary: false,
|
|
|
|
|
SendResponse: false,
|
|
|
|
|
NoHistory: true, // Don't load session history for heartbeat
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-04 11:06:13 +00:00
|
|
|
func (al *AgentLoop) processMessage(ctx context.Context, msg bus.InboundMessage) (string, error) {
|
2026-02-13 03:13:32 +00:00
|
|
|
// Add message preview to log (show full content for error messages)
|
|
|
|
|
var logContent string
|
|
|
|
|
if strings.Contains(msg.Content, "Error:") || strings.Contains(msg.Content, "error") {
|
|
|
|
|
logContent = msg.Content // Full content for errors
|
|
|
|
|
} else {
|
|
|
|
|
logContent = utils.Truncate(msg.Content, 80)
|
|
|
|
|
}
|
2026-03-01 00:53:13 +00:00
|
|
|
logger.InfoCF(
|
|
|
|
|
"agent",
|
|
|
|
|
fmt.Sprintf("Processing message from %s:%s: %s", msg.Channel, msg.SenderID, logContent),
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-02-10 05:18:23 +00:00
|
|
|
"channel": msg.Channel,
|
|
|
|
|
"chat_id": msg.ChatID,
|
|
|
|
|
"sender_id": msg.SenderID,
|
|
|
|
|
"session_key": msg.SessionKey,
|
2026-03-01 00:53:13 +00:00
|
|
|
},
|
|
|
|
|
)
|
2026-02-10 05:18:23 +00:00
|
|
|
|
2026-03-08 17:22:15 +00:00
|
|
|
var hadAudio bool
|
|
|
|
|
msg, hadAudio = al.transcribeAudioInMessage(ctx, msg)
|
|
|
|
|
|
|
|
|
|
// For audio messages the placeholder was deferred by the channel.
|
|
|
|
|
// Now that transcription (and optional feedback) is done, send it.
|
|
|
|
|
if hadAudio && al.channelManager != nil {
|
|
|
|
|
al.channelManager.SendPlaceholder(ctx, msg.Channel, msg.ChatID)
|
|
|
|
|
}
|
2026-02-10 05:18:23 +00:00
|
|
|
|
2026-02-10 08:05:23 +00:00
|
|
|
// Route system messages to processSystemMessage
|
|
|
|
|
if msg.Channel == "system" {
|
|
|
|
|
return al.processSystemMessage(ctx, msg)
|
|
|
|
|
}
|
|
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
route, agent, routeErr := al.resolveMessageRoute(msg)
|
|
|
|
|
if routeErr != nil {
|
|
|
|
|
return "", routeErr
|
2026-02-22 20:29:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Reset message-tool state for this round so we don't skip publishing due to a previous round.
|
|
|
|
|
if tool, ok := agent.Tools.Get("message"); ok {
|
2026-03-05 01:57:33 +00:00
|
|
|
if resetter, ok := tool.(interface{ ResetSentInRound() }); ok {
|
|
|
|
|
resetter.ResetSentInRound()
|
2026-02-22 20:29:27 +00:00
|
|
|
}
|
|
|
|
|
}
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
// Resolve session key from route, while preserving explicit agent-scoped keys.
|
|
|
|
|
scopeKey := resolveScopeKey(route, msg.SessionKey)
|
|
|
|
|
sessionKey := scopeKey
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
|
|
|
|
|
logger.InfoCF("agent", "Routed message",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
"agent_id": agent.ID,
|
|
|
|
|
"scope_key": scopeKey,
|
|
|
|
|
"session_key": sessionKey,
|
|
|
|
|
"matched_by": route.MatchedBy,
|
|
|
|
|
"route_agent": route.AgentID,
|
|
|
|
|
"route_channel": route.Channel,
|
2026-02-27 09:35:50 +00:00
|
|
|
})
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
|
2026-03-09 08:39:33 +00:00
|
|
|
opts := processOptions{
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
SessionKey: sessionKey,
|
2026-02-11 12:22:41 +00:00
|
|
|
Channel: msg.Channel,
|
|
|
|
|
ChatID: msg.ChatID,
|
|
|
|
|
UserMessage: msg.Content,
|
2026-03-03 06:52:57 +00:00
|
|
|
Media: msg.Media,
|
2026-02-27 07:42:47 +00:00
|
|
|
DefaultResponse: defaultResponse,
|
2026-02-11 12:22:41 +00:00
|
|
|
EnableSummary: true,
|
|
|
|
|
SendResponse: false,
|
2026-03-09 08:39:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// context-dependent commands check their own Runtime fields and report
|
|
|
|
|
// "unavailable" when the required capability is nil.
|
|
|
|
|
if response, handled := al.handleCommand(ctx, msg, agent, &opts); handled {
|
|
|
|
|
return response, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return al.runAgentLoop(ctx, agent, opts)
|
2026-02-11 12:22:41 +00:00
|
|
|
}
|
|
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
func (al *AgentLoop) resolveMessageRoute(msg bus.InboundMessage) (routing.ResolvedRoute, *AgentInstance, error) {
|
2026-03-13 06:27:46 +00:00
|
|
|
registry := al.GetRegistry()
|
|
|
|
|
route := registry.ResolveRoute(routing.RouteInput{
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
Channel: msg.Channel,
|
|
|
|
|
AccountID: inboundMetadata(msg, metadataKeyAccountID),
|
|
|
|
|
Peer: extractPeer(msg),
|
|
|
|
|
ParentPeer: extractParentPeer(msg),
|
|
|
|
|
GuildID: inboundMetadata(msg, metadataKeyGuildID),
|
|
|
|
|
TeamID: inboundMetadata(msg, metadataKeyTeamID),
|
|
|
|
|
})
|
|
|
|
|
|
2026-03-13 06:27:46 +00:00
|
|
|
agent, ok := registry.GetAgent(route.AgentID)
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
if !ok {
|
2026-03-13 06:27:46 +00:00
|
|
|
agent = registry.GetDefaultAgent()
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
}
|
|
|
|
|
if agent == nil {
|
|
|
|
|
return routing.ResolvedRoute{}, nil, fmt.Errorf("no agent available for route (agent_id=%s)", route.AgentID)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return route, agent, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func resolveScopeKey(route routing.ResolvedRoute, msgSessionKey string) string {
|
|
|
|
|
if msgSessionKey != "" && strings.HasPrefix(msgSessionKey, sessionKeyAgentPrefix) {
|
|
|
|
|
return msgSessionKey
|
|
|
|
|
}
|
|
|
|
|
return route.SessionKey
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-01 00:53:13 +00:00
|
|
|
func (al *AgentLoop) processSystemMessage(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
msg bus.InboundMessage,
|
|
|
|
|
) (string, error) {
|
2026-02-11 12:22:41 +00:00
|
|
|
if msg.Channel != "system" {
|
2026-03-01 00:53:13 +00:00
|
|
|
return "", fmt.Errorf(
|
|
|
|
|
"processSystemMessage called with non-system message channel: %s",
|
|
|
|
|
msg.Channel,
|
|
|
|
|
)
|
2026-02-10 08:05:23 +00:00
|
|
|
}
|
2026-02-11 12:22:41 +00:00
|
|
|
|
|
|
|
|
logger.InfoCF("agent", "Processing system message",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-02-11 12:22:41 +00:00
|
|
|
"sender_id": msg.SenderID,
|
|
|
|
|
"chat_id": msg.ChatID,
|
|
|
|
|
})
|
|
|
|
|
|
2026-02-13 06:39:39 +00:00
|
|
|
// Parse origin channel from chat_id (format: "channel:chat_id")
|
2026-02-11 12:22:41 +00:00
|
|
|
var originChannel, originChatID string
|
|
|
|
|
if idx := strings.Index(msg.ChatID, ":"); idx > 0 {
|
|
|
|
|
originChannel = msg.ChatID[:idx]
|
|
|
|
|
originChatID = msg.ChatID[idx+1:]
|
|
|
|
|
} else {
|
|
|
|
|
originChannel = "cli"
|
|
|
|
|
originChatID = msg.ChatID
|
2026-02-10 08:05:23 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-13 06:39:39 +00:00
|
|
|
// Extract subagent result from message content
|
|
|
|
|
// Format: "Task 'label' completed.\n\nResult:\n<actual content>"
|
|
|
|
|
content := msg.Content
|
|
|
|
|
if idx := strings.Index(content, "Result:\n"); idx >= 0 {
|
|
|
|
|
content = content[idx+8:] // Extract just the result part
|
|
|
|
|
}
|
2026-02-11 12:22:41 +00:00
|
|
|
|
2026-02-13 06:39:39 +00:00
|
|
|
// Skip internal channels - only log, don't send to user
|
2026-02-13 07:05:16 +00:00
|
|
|
if constants.IsInternalChannel(originChannel) {
|
2026-02-13 06:39:39 +00:00
|
|
|
logger.InfoCF("agent", "Subagent completed (internal channel)",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-02-13 09:51:47 +00:00
|
|
|
"sender_id": msg.SenderID,
|
|
|
|
|
"content_len": len(content),
|
|
|
|
|
"channel": originChannel,
|
2026-02-13 06:39:39 +00:00
|
|
|
})
|
|
|
|
|
return "", nil
|
|
|
|
|
}
|
2026-02-10 16:30:38 +00:00
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
// Use default agent for system messages
|
2026-03-13 06:27:46 +00:00
|
|
|
agent := al.GetRegistry().GetDefaultAgent()
|
2026-02-22 20:29:27 +00:00
|
|
|
if agent == nil {
|
|
|
|
|
return "", fmt.Errorf("no default agent for system message")
|
|
|
|
|
}
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
|
2026-02-11 12:22:41 +00:00
|
|
|
// Use the origin session for context
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
sessionKey := routing.BuildAgentMainSessionKey(agent.ID)
|
2026-02-13 06:39:39 +00:00
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
return al.runAgentLoop(ctx, agent, processOptions{
|
2026-02-11 12:22:41 +00:00
|
|
|
SessionKey: sessionKey,
|
|
|
|
|
Channel: originChannel,
|
|
|
|
|
ChatID: originChatID,
|
|
|
|
|
UserMessage: fmt.Sprintf("[System: %s] %s", msg.SenderID, msg.Content),
|
|
|
|
|
DefaultResponse: "Background task completed.",
|
|
|
|
|
EnableSummary: false,
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
SendResponse: true,
|
2026-02-11 12:22:41 +00:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
// runAgentLoop remains the top-level shell that starts a turn and publishes
|
|
|
|
|
// any post-turn work. runTurn owns the full turn lifecycle.
|
2026-03-01 00:53:13 +00:00
|
|
|
func (al *AgentLoop) runAgentLoop(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
agent *AgentInstance,
|
|
|
|
|
opts processOptions,
|
|
|
|
|
) (string, error) {
|
2026-03-20 09:28:12 +00:00
|
|
|
if opts.Channel != "" && opts.ChatID != "" && !constants.IsInternalChannel(opts.Channel) {
|
|
|
|
|
channelKey := fmt.Sprintf("%s:%s", opts.Channel, opts.ChatID)
|
|
|
|
|
if err := al.RecordLastChannel(channelKey); err != nil {
|
|
|
|
|
logger.WarnCF(
|
|
|
|
|
"agent",
|
|
|
|
|
"Failed to record last channel",
|
|
|
|
|
map[string]any{"error": err.Error()},
|
2026-03-13 06:20:24 +00:00
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
ts := newTurnState(agent, opts, al.newTurnEventScope(agent.ID, opts.SessionKey))
|
|
|
|
|
result, err := al.runTurn(ctx, ts)
|
2026-02-11 12:22:41 +00:00
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
2026-03-20 09:28:12 +00:00
|
|
|
if result.status == TurnEndStatusAborted {
|
|
|
|
|
return "", nil
|
2026-02-11 12:22:41 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
for _, followUp := range result.followUps {
|
|
|
|
|
if pubErr := al.bus.PublishInbound(ctx, followUp); pubErr != nil {
|
|
|
|
|
logger.WarnCF("agent", "Failed to publish follow-up after turn",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"turn_id": ts.turnID,
|
|
|
|
|
"error": pubErr.Error(),
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-02-11 12:22:41 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if opts.SendResponse && result.finalContent != "" {
|
refactor(bus): fix deadlock and concurrency issues in MessageBus
PublishInbound/PublishOutbound held RLock during blocking channel sends,
deadlocking against Close() which needs a write lock when the buffer is
full. ConsumeInbound/SubscribeOutbound used bare receives instead of
comma-ok, causing zero-value processing or busy loops after close.
Replace sync.RWMutex+bool with atomic.Bool+done channel so Publish
methods use a lock-free 3-way select (send / done / ctx.Done). Add
context.Context parameter to both Publish methods so callers can cancel
or timeout blocked sends. Close() now only sets the atomic flag and
closes the done channel—never closes the data channels—eliminating
send-on-closed-channel panics.
- Remove dead code: RegisterHandler, GetHandler, handlers map,
MessageHandler type (zero callers across the whole repo)
- Add ErrBusClosed sentinel error
- Update all 10 caller sites to pass context
- Add msgBus.Close() to gateway and agent shutdown flows
- Add pkg/bus/bus_test.go with 11 test cases covering basic round-trip,
context cancellation, closed-bus behavior, concurrent publish+close,
full-buffer timeout, and idempotent Close
2026-02-22 16:44:45 +00:00
|
|
|
al.bus.PublishOutbound(ctx, bus.OutboundMessage{
|
2026-02-11 12:22:41 +00:00
|
|
|
Channel: opts.Channel,
|
|
|
|
|
ChatID: opts.ChatID,
|
2026-03-20 09:28:12 +00:00
|
|
|
Content: result.finalContent,
|
2026-02-11 12:22:41 +00:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if result.finalContent != "" {
|
|
|
|
|
responsePreview := utils.Truncate(result.finalContent, 120)
|
|
|
|
|
logger.InfoCF("agent", fmt.Sprintf("Response: %s", responsePreview),
|
|
|
|
|
map[string]any{
|
|
|
|
|
"agent_id": agent.ID,
|
|
|
|
|
"session_key": opts.SessionKey,
|
|
|
|
|
"iterations": ts.currentIteration(),
|
|
|
|
|
"final_length": len(result.finalContent),
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-02-11 12:22:41 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
return result.finalContent, nil
|
2026-02-11 12:22:41 +00:00
|
|
|
}
|
2026-02-11 10:43:21 +00:00
|
|
|
|
2026-02-26 05:24:51 +00:00
|
|
|
func (al *AgentLoop) targetReasoningChannelID(channelName string) (chatID string) {
|
|
|
|
|
if al.channelManager == nil {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
if ch, ok := al.channelManager.GetChannel(channelName); ok {
|
|
|
|
|
return ch.ReasoningChannelID()
|
|
|
|
|
}
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-01 00:53:13 +00:00
|
|
|
func (al *AgentLoop) handleReasoning(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
reasoningContent, channelName, channelID string,
|
|
|
|
|
) {
|
2026-02-26 05:24:51 +00:00
|
|
|
if reasoningContent == "" || channelName == "" || channelID == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check context cancellation before attempting to publish,
|
|
|
|
|
// since PublishOutbound's select may race between send and ctx.Done().
|
|
|
|
|
if ctx.Err() != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-27 17:39:17 +00:00
|
|
|
// Use a short timeout so the goroutine does not block indefinitely when
|
|
|
|
|
// the outbound bus is full. Reasoning output is best-effort; dropping it
|
|
|
|
|
// is acceptable to avoid goroutine accumulation.
|
|
|
|
|
pubCtx, pubCancel := context.WithTimeout(ctx, 5*time.Second)
|
|
|
|
|
defer pubCancel()
|
|
|
|
|
|
|
|
|
|
if err := al.bus.PublishOutbound(pubCtx, bus.OutboundMessage{
|
2026-02-26 05:24:51 +00:00
|
|
|
Channel: channelName,
|
|
|
|
|
ChatID: channelID,
|
|
|
|
|
Content: reasoningContent,
|
2026-02-27 17:39:17 +00:00
|
|
|
}); err != nil {
|
2026-02-28 04:54:05 +00:00
|
|
|
// Treat context.DeadlineExceeded / context.Canceled as expected
|
2026-02-28 05:00:21 +00:00
|
|
|
// (bus full under load, or parent canceled). Check the error
|
2026-02-28 04:54:05 +00:00
|
|
|
// itself rather than ctx.Err(), because pubCtx may time out
|
|
|
|
|
// (5 s) while the parent ctx is still active.
|
2026-02-28 06:13:24 +00:00
|
|
|
// Also treat ErrBusClosed as expected — it occurs during normal
|
|
|
|
|
// shutdown when the bus is closed before all goroutines finish.
|
|
|
|
|
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) ||
|
|
|
|
|
errors.Is(err, bus.ErrBusClosed) {
|
2026-02-28 04:54:05 +00:00
|
|
|
logger.DebugCF("agent", "Reasoning publish skipped (timeout/cancel)", map[string]any{
|
2026-02-27 19:05:19 +00:00
|
|
|
"channel": channelName,
|
|
|
|
|
"error": err.Error(),
|
|
|
|
|
})
|
|
|
|
|
} else {
|
2026-02-28 04:54:05 +00:00
|
|
|
logger.WarnCF("agent", "Failed to publish reasoning (best-effort)", map[string]any{
|
2026-02-27 19:05:19 +00:00
|
|
|
"channel": channelName,
|
|
|
|
|
"error": err.Error(),
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-02-27 17:39:17 +00:00
|
|
|
}
|
2026-02-26 05:24:51 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
func (al *AgentLoop) runTurn(ctx context.Context, ts *turnState) (turnResult, error) {
|
|
|
|
|
turnCtx, turnCancel := context.WithCancel(ctx)
|
|
|
|
|
defer turnCancel()
|
|
|
|
|
ts.setTurnCancel(turnCancel)
|
|
|
|
|
|
|
|
|
|
al.registerActiveTurn(ts)
|
|
|
|
|
defer al.clearActiveTurn(ts)
|
|
|
|
|
|
|
|
|
|
turnStatus := TurnEndStatusCompleted
|
|
|
|
|
defer func() {
|
|
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindTurnEnd,
|
|
|
|
|
ts.eventMeta("runTurn", "turn.end"),
|
|
|
|
|
TurnEndPayload{
|
|
|
|
|
Status: turnStatus,
|
|
|
|
|
Iterations: ts.currentIteration(),
|
|
|
|
|
Duration: time.Since(ts.startedAt),
|
|
|
|
|
FinalContentLen: ts.finalContentLen(),
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
}()
|
2026-03-15 16:08:16 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindTurnStart,
|
|
|
|
|
ts.eventMeta("runTurn", "turn.start"),
|
|
|
|
|
TurnStartPayload{
|
|
|
|
|
Channel: ts.channel,
|
|
|
|
|
ChatID: ts.chatID,
|
|
|
|
|
UserMessage: ts.userMessage,
|
|
|
|
|
MediaCount: len(ts.media),
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var history []providers.Message
|
|
|
|
|
var summary string
|
|
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
history = ts.agent.Sessions.GetHistory(ts.sessionKey)
|
|
|
|
|
summary = ts.agent.Sessions.GetSummary(ts.sessionKey)
|
|
|
|
|
}
|
|
|
|
|
ts.captureRestorePoint(history, summary)
|
|
|
|
|
|
|
|
|
|
messages := ts.agent.ContextBuilder.BuildMessages(
|
|
|
|
|
history,
|
|
|
|
|
summary,
|
|
|
|
|
ts.userMessage,
|
|
|
|
|
ts.media,
|
|
|
|
|
ts.channel,
|
|
|
|
|
ts.chatID,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
cfg := al.GetConfig()
|
|
|
|
|
maxMediaSize := cfg.Agents.Defaults.GetMaxMediaSize()
|
|
|
|
|
messages = resolveMediaRefs(messages, al.mediaStore, maxMediaSize)
|
|
|
|
|
|
|
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
toolDefs := ts.agent.Tools.ToProviderDefs()
|
|
|
|
|
if isOverContextBudget(ts.agent.ContextWindow, messages, toolDefs, ts.agent.MaxTokens) {
|
|
|
|
|
logger.WarnCF("agent", "Proactive compression: context budget exceeded before LLM call",
|
|
|
|
|
map[string]any{"session_key": ts.sessionKey})
|
|
|
|
|
if compression, ok := al.forceCompression(ts.agent, ts.sessionKey); ok {
|
|
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindContextCompress,
|
|
|
|
|
ts.eventMeta("runTurn", "turn.context.compress"),
|
|
|
|
|
ContextCompressPayload{
|
|
|
|
|
Reason: ContextCompressReasonProactive,
|
|
|
|
|
DroppedMessages: compression.DroppedMessages,
|
|
|
|
|
RemainingMessages: compression.RemainingMessages,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
ts.refreshRestorePointFromSession(ts.agent)
|
|
|
|
|
}
|
|
|
|
|
newHistory := ts.agent.Sessions.GetHistory(ts.sessionKey)
|
|
|
|
|
newSummary := ts.agent.Sessions.GetSummary(ts.sessionKey)
|
|
|
|
|
messages = ts.agent.ContextBuilder.BuildMessages(
|
|
|
|
|
newHistory, newSummary, ts.userMessage,
|
|
|
|
|
ts.media, ts.channel, ts.chatID,
|
|
|
|
|
)
|
|
|
|
|
messages = resolveMediaRefs(messages, al.mediaStore, maxMediaSize)
|
2026-03-15 16:08:16 +00:00
|
|
|
}
|
|
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
rootMsg := providers.Message{Role: "user", Content: ts.userMessage}
|
|
|
|
|
ts.agent.Sessions.AddMessage(ts.sessionKey, rootMsg.Role, rootMsg.Content)
|
|
|
|
|
ts.recordPersistedMessage(rootMsg)
|
|
|
|
|
}
|
2026-03-02 14:42:52 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
activeCandidates, activeModel := al.selectCandidates(ts.agent, ts.userMessage, messages)
|
|
|
|
|
var pendingMessages []providers.Message
|
|
|
|
|
var finalContent string
|
|
|
|
|
|
|
|
|
|
for ts.currentIteration() < ts.agent.MaxIterations || len(pendingMessages) > 0 || func() bool {
|
|
|
|
|
graceful, _ := ts.gracefulInterruptRequested()
|
|
|
|
|
return graceful
|
|
|
|
|
}() {
|
|
|
|
|
if ts.hardAbortRequested() {
|
|
|
|
|
turnStatus = TurnEndStatusAborted
|
|
|
|
|
return al.abortTurn(ts)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
iteration := ts.currentIteration() + 1
|
|
|
|
|
ts.setIteration(iteration)
|
|
|
|
|
ts.setPhase(TurnPhaseRunning)
|
|
|
|
|
|
|
|
|
|
if iteration > 1 || !ts.opts.SkipInitialSteeringPoll {
|
|
|
|
|
if steerMsgs := al.dequeueSteeringMessages(); len(steerMsgs) > 0 {
|
|
|
|
|
pendingMessages = append(pendingMessages, steerMsgs...)
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
if len(pendingMessages) > 0 {
|
2026-03-20 07:29:52 +00:00
|
|
|
totalContentLen := 0
|
2026-03-15 16:08:16 +00:00
|
|
|
for _, pm := range pendingMessages {
|
|
|
|
|
messages = append(messages, pm)
|
2026-03-20 07:29:52 +00:00
|
|
|
totalContentLen += len(pm.Content)
|
2026-03-20 09:28:12 +00:00
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
ts.agent.Sessions.AddMessage(ts.sessionKey, pm.Role, pm.Content)
|
|
|
|
|
ts.recordPersistedMessage(pm)
|
|
|
|
|
}
|
2026-03-15 16:08:16 +00:00
|
|
|
logger.InfoCF("agent", "Injected steering message into context",
|
|
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-03-15 16:08:16 +00:00
|
|
|
"iteration": iteration,
|
|
|
|
|
"content_len": len(pm.Content),
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-03-20 07:29:52 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindSteeringInjected,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.steering.injected"),
|
2026-03-20 07:29:52 +00:00
|
|
|
SteeringInjectedPayload{
|
|
|
|
|
Count: len(pendingMessages),
|
|
|
|
|
TotalContentLen: totalContentLen,
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-03-15 16:08:16 +00:00
|
|
|
pendingMessages = nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-10 05:18:23 +00:00
|
|
|
logger.DebugCF("agent", "LLM iteration",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-02-10 05:18:23 +00:00
|
|
|
"iteration": iteration,
|
2026-03-20 09:28:12 +00:00
|
|
|
"max": ts.agent.MaxIterations,
|
2026-02-10 05:18:23 +00:00
|
|
|
})
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
gracefulTerminal, _ := ts.gracefulInterruptRequested()
|
|
|
|
|
providerToolDefs := ts.agent.Tools.ToProviderDefs()
|
|
|
|
|
callMessages := messages
|
|
|
|
|
if gracefulTerminal {
|
|
|
|
|
callMessages = append(append([]providers.Message(nil), messages...), ts.interruptHintMessage())
|
|
|
|
|
providerToolDefs = nil
|
|
|
|
|
ts.markGracefulTerminalUsed()
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 06:53:22 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindLLMRequest,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.llm.request"),
|
2026-03-20 06:53:22 +00:00
|
|
|
LLMRequestPayload{
|
|
|
|
|
Model: activeModel,
|
2026-03-20 09:28:12 +00:00
|
|
|
MessagesCount: len(callMessages),
|
2026-03-20 06:53:22 +00:00
|
|
|
ToolsCount: len(providerToolDefs),
|
2026-03-20 09:28:12 +00:00
|
|
|
MaxTokens: ts.agent.MaxTokens,
|
|
|
|
|
Temperature: ts.agent.Temperature,
|
2026-03-20 06:53:22 +00:00
|
|
|
},
|
|
|
|
|
)
|
2026-02-04 11:06:13 +00:00
|
|
|
|
2026-02-10 15:33:28 +00:00
|
|
|
logger.DebugCF("agent", "LLM request",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-02-11 12:22:41 +00:00
|
|
|
"iteration": iteration,
|
2026-03-02 14:42:52 +00:00
|
|
|
"model": activeModel,
|
2026-03-20 09:28:12 +00:00
|
|
|
"messages_count": len(callMessages),
|
2026-02-11 12:22:41 +00:00
|
|
|
"tools_count": len(providerToolDefs),
|
2026-03-20 09:28:12 +00:00
|
|
|
"max_tokens": ts.agent.MaxTokens,
|
|
|
|
|
"temperature": ts.agent.Temperature,
|
|
|
|
|
"system_prompt_len": len(callMessages[0].Content),
|
2026-02-10 15:33:28 +00:00
|
|
|
})
|
|
|
|
|
logger.DebugCF("agent", "Full LLM request",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-02-10 15:33:28 +00:00
|
|
|
"iteration": iteration,
|
2026-03-20 09:28:12 +00:00
|
|
|
"messages_json": formatMessagesForLog(callMessages),
|
2026-02-10 15:33:28 +00:00
|
|
|
"tools_json": formatToolsForLog(providerToolDefs),
|
|
|
|
|
})
|
|
|
|
|
|
2026-03-05 01:51:18 +00:00
|
|
|
llmOpts := map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"max_tokens": ts.agent.MaxTokens,
|
|
|
|
|
"temperature": ts.agent.Temperature,
|
|
|
|
|
"prompt_cache_key": ts.agent.ID,
|
2026-03-05 01:51:18 +00:00
|
|
|
}
|
2026-03-20 09:28:12 +00:00
|
|
|
if ts.agent.ThinkingLevel != ThinkingOff {
|
|
|
|
|
if tc, ok := ts.agent.Provider.(providers.ThinkingCapable); ok && tc.SupportsThinking() {
|
|
|
|
|
llmOpts["thinking_level"] = string(ts.agent.ThinkingLevel)
|
2026-03-05 01:51:18 +00:00
|
|
|
} else {
|
|
|
|
|
logger.WarnCF("agent", "thinking_level is set but current provider does not support it, ignoring",
|
2026-03-20 09:28:12 +00:00
|
|
|
map[string]any{"agent_id": ts.agent.ID, "thinking_level": string(ts.agent.ThinkingLevel)})
|
2026-03-05 01:51:18 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
callLLM := func(messagesForCall []providers.Message, toolDefsForCall []providers.ToolDefinition) (*providers.LLMResponse, error) {
|
|
|
|
|
providerCtx, providerCancel := context.WithCancel(turnCtx)
|
|
|
|
|
ts.setProviderCancel(providerCancel)
|
|
|
|
|
defer func() {
|
|
|
|
|
providerCancel()
|
|
|
|
|
ts.clearProviderCancel(providerCancel)
|
|
|
|
|
}()
|
|
|
|
|
|
2026-03-13 06:27:46 +00:00
|
|
|
al.activeRequests.Add(1)
|
|
|
|
|
defer al.activeRequests.Done()
|
|
|
|
|
|
2026-03-02 14:42:52 +00:00
|
|
|
if len(activeCandidates) > 1 && al.fallback != nil {
|
2026-03-01 00:53:13 +00:00
|
|
|
fbResult, fbErr := al.fallback.Execute(
|
2026-03-20 09:28:12 +00:00
|
|
|
providerCtx,
|
2026-03-03 04:22:45 +00:00
|
|
|
activeCandidates,
|
2026-02-16 13:34:55 +00:00
|
|
|
func(ctx context.Context, provider, model string) (*providers.LLMResponse, error) {
|
2026-03-20 09:28:12 +00:00
|
|
|
return ts.agent.Provider.Chat(ctx, messagesForCall, toolDefsForCall, model, llmOpts)
|
2026-02-16 13:34:55 +00:00
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
if fbErr != nil {
|
|
|
|
|
return nil, fbErr
|
|
|
|
|
}
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
if fbResult.Provider != "" && len(fbResult.Attempts) > 0 {
|
2026-03-01 00:53:13 +00:00
|
|
|
logger.InfoCF(
|
|
|
|
|
"agent",
|
|
|
|
|
fmt.Sprintf("Fallback: succeeded with %s/%s after %d attempts",
|
|
|
|
|
fbResult.Provider, fbResult.Model, len(fbResult.Attempts)+1),
|
2026-03-20 09:28:12 +00:00
|
|
|
map[string]any{"agent_id": ts.agent.ID, "iteration": iteration},
|
2026-03-01 00:53:13 +00:00
|
|
|
)
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
}
|
2026-02-16 13:34:55 +00:00
|
|
|
return fbResult.Response, nil
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
}
|
2026-03-20 09:28:12 +00:00
|
|
|
return ts.agent.Provider.Chat(providerCtx, messagesForCall, toolDefsForCall, activeModel, llmOpts)
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
}
|
2026-02-16 08:30:54 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
var response *providers.LLMResponse
|
|
|
|
|
var err error
|
2026-02-16 13:34:55 +00:00
|
|
|
maxRetries := 2
|
|
|
|
|
for retry := 0; retry <= maxRetries; retry++ {
|
2026-03-20 09:28:12 +00:00
|
|
|
response, err = callLLM(callMessages, providerToolDefs)
|
2026-02-16 08:30:54 +00:00
|
|
|
if err == nil {
|
2026-02-16 13:34:55 +00:00
|
|
|
break
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
2026-03-20 09:28:12 +00:00
|
|
|
if ts.hardAbortRequested() && errors.Is(err, context.Canceled) {
|
|
|
|
|
turnStatus = TurnEndStatusAborted
|
|
|
|
|
return al.abortTurn(ts)
|
|
|
|
|
}
|
2026-02-16 08:30:54 +00:00
|
|
|
|
|
|
|
|
errMsg := strings.ToLower(err.Error())
|
2026-02-23 13:13:37 +00:00
|
|
|
isTimeoutError := errors.Is(err, context.DeadlineExceeded) ||
|
|
|
|
|
strings.Contains(errMsg, "deadline exceeded") ||
|
|
|
|
|
strings.Contains(errMsg, "client.timeout") ||
|
|
|
|
|
strings.Contains(errMsg, "timed out") ||
|
|
|
|
|
strings.Contains(errMsg, "timeout exceeded")
|
|
|
|
|
|
|
|
|
|
isContextError := !isTimeoutError && (strings.Contains(errMsg, "context_length_exceeded") ||
|
|
|
|
|
strings.Contains(errMsg, "context window") ||
|
|
|
|
|
strings.Contains(errMsg, "maximum context length") ||
|
|
|
|
|
strings.Contains(errMsg, "token limit") ||
|
|
|
|
|
strings.Contains(errMsg, "too many tokens") ||
|
|
|
|
|
strings.Contains(errMsg, "max_tokens") ||
|
2026-02-16 08:30:54 +00:00
|
|
|
strings.Contains(errMsg, "invalidparameter") ||
|
2026-02-23 13:13:37 +00:00
|
|
|
strings.Contains(errMsg, "prompt is too long") ||
|
|
|
|
|
strings.Contains(errMsg, "request too large"))
|
|
|
|
|
|
|
|
|
|
if isTimeoutError && retry < maxRetries {
|
|
|
|
|
backoff := time.Duration(retry+1) * 5 * time.Second
|
2026-03-20 07:29:52 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindLLMRetry,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.llm.retry"),
|
2026-03-20 07:29:52 +00:00
|
|
|
LLMRetryPayload{
|
|
|
|
|
Attempt: retry + 1,
|
|
|
|
|
MaxRetries: maxRetries,
|
|
|
|
|
Reason: "timeout",
|
|
|
|
|
Error: err.Error(),
|
|
|
|
|
Backoff: backoff,
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-23 13:13:37 +00:00
|
|
|
logger.WarnCF("agent", "Timeout error, retrying after backoff", map[string]any{
|
|
|
|
|
"error": err.Error(),
|
|
|
|
|
"retry": retry,
|
|
|
|
|
"backoff": backoff.String(),
|
|
|
|
|
})
|
2026-03-20 09:28:12 +00:00
|
|
|
if sleepErr := sleepWithContext(turnCtx, backoff); sleepErr != nil {
|
|
|
|
|
if ts.hardAbortRequested() {
|
|
|
|
|
turnStatus = TurnEndStatusAborted
|
|
|
|
|
return al.abortTurn(ts)
|
|
|
|
|
}
|
|
|
|
|
err = sleepErr
|
|
|
|
|
break
|
|
|
|
|
}
|
2026-02-23 13:13:37 +00:00
|
|
|
continue
|
|
|
|
|
}
|
2026-02-16 08:30:54 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if isContextError && retry < maxRetries && !ts.opts.NoHistory {
|
2026-03-20 07:29:52 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindLLMRetry,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.llm.retry"),
|
2026-03-20 07:29:52 +00:00
|
|
|
LLMRetryPayload{
|
|
|
|
|
Attempt: retry + 1,
|
|
|
|
|
MaxRetries: maxRetries,
|
|
|
|
|
Reason: "context_limit",
|
|
|
|
|
Error: err.Error(),
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-03-01 00:53:13 +00:00
|
|
|
logger.WarnCF(
|
|
|
|
|
"agent",
|
|
|
|
|
"Context window error detected, attempting compression",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"error": err.Error(),
|
|
|
|
|
"retry": retry,
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-16 08:30:54 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if retry == 0 && !constants.IsInternalChannel(ts.channel) {
|
refactor(bus): fix deadlock and concurrency issues in MessageBus
PublishInbound/PublishOutbound held RLock during blocking channel sends,
deadlocking against Close() which needs a write lock when the buffer is
full. ConsumeInbound/SubscribeOutbound used bare receives instead of
comma-ok, causing zero-value processing or busy loops after close.
Replace sync.RWMutex+bool with atomic.Bool+done channel so Publish
methods use a lock-free 3-way select (send / done / ctx.Done). Add
context.Context parameter to both Publish methods so callers can cancel
or timeout blocked sends. Close() now only sets the atomic flag and
closes the done channel—never closes the data channels—eliminating
send-on-closed-channel panics.
- Remove dead code: RegisterHandler, GetHandler, handlers map,
MessageHandler type (zero callers across the whole repo)
- Add ErrBusClosed sentinel error
- Update all 10 caller sites to pass context
- Add msgBus.Close() to gateway and agent shutdown flows
- Add pkg/bus/bus_test.go with 11 test cases covering basic round-trip,
context cancellation, closed-bus behavior, concurrent publish+close,
full-buffer timeout, and idempotent Close
2026-02-22 16:44:45 +00:00
|
|
|
al.bus.PublishOutbound(ctx, bus.OutboundMessage{
|
2026-03-20 09:28:12 +00:00
|
|
|
Channel: ts.channel,
|
|
|
|
|
ChatID: ts.chatID,
|
2026-02-16 13:34:55 +00:00
|
|
|
Content: "Context window exceeded. Compressing history and retrying...",
|
2026-02-16 08:30:54 +00:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if compression, ok := al.forceCompression(ts.agent, ts.sessionKey); ok {
|
2026-03-20 07:29:52 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindContextCompress,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.context.compress"),
|
2026-03-20 07:29:52 +00:00
|
|
|
ContextCompressPayload{
|
|
|
|
|
Reason: ContextCompressReasonRetry,
|
|
|
|
|
DroppedMessages: compression.DroppedMessages,
|
|
|
|
|
RemainingMessages: compression.RemainingMessages,
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.refreshRestorePointFromSession(ts.agent)
|
2026-03-20 07:29:52 +00:00
|
|
|
}
|
2026-03-20 09:28:12 +00:00
|
|
|
|
|
|
|
|
newHistory := ts.agent.Sessions.GetHistory(ts.sessionKey)
|
|
|
|
|
newSummary := ts.agent.Sessions.GetSummary(ts.sessionKey)
|
|
|
|
|
messages = ts.agent.ContextBuilder.BuildMessages(
|
2026-02-16 13:34:55 +00:00
|
|
|
newHistory, newSummary, "",
|
2026-03-20 09:28:12 +00:00
|
|
|
nil, ts.channel, ts.chatID,
|
2026-02-16 08:30:54 +00:00
|
|
|
)
|
2026-03-20 09:28:12 +00:00
|
|
|
callMessages = messages
|
|
|
|
|
if gracefulTerminal {
|
|
|
|
|
callMessages = append(append([]providers.Message(nil), messages...), ts.interruptHintMessage())
|
|
|
|
|
}
|
2026-02-16 08:30:54 +00:00
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
break
|
|
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
|
|
|
|
|
if err != nil {
|
2026-03-20 09:28:12 +00:00
|
|
|
turnStatus = TurnEndStatusError
|
2026-03-20 06:53:22 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindError,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.error"),
|
2026-03-20 06:53:22 +00:00
|
|
|
ErrorPayload{
|
|
|
|
|
Stage: "llm",
|
|
|
|
|
Message: err.Error(),
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-10 05:18:23 +00:00
|
|
|
logger.ErrorCF("agent", "LLM call failed",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-02-10 05:18:23 +00:00
|
|
|
"iteration": iteration,
|
2026-03-13 06:27:46 +00:00
|
|
|
"model": activeModel,
|
2026-02-10 05:18:23 +00:00
|
|
|
"error": err.Error(),
|
|
|
|
|
})
|
2026-03-20 09:28:12 +00:00
|
|
|
return turnResult{}, fmt.Errorf("LLM call failed after retries: %w", err)
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-01 00:53:13 +00:00
|
|
|
go al.handleReasoning(
|
2026-03-20 09:28:12 +00:00
|
|
|
turnCtx,
|
2026-03-01 00:53:13 +00:00
|
|
|
response.Reasoning,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.channel,
|
|
|
|
|
al.targetReasoningChannelID(ts.channel),
|
2026-03-01 00:53:13 +00:00
|
|
|
)
|
2026-03-20 06:53:22 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindLLMResponse,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.llm.response"),
|
2026-03-20 06:53:22 +00:00
|
|
|
LLMResponsePayload{
|
|
|
|
|
ContentLen: len(response.Content),
|
|
|
|
|
ToolCalls: len(response.ToolCalls),
|
|
|
|
|
HasReasoning: response.Reasoning != "" || response.ReasoningContent != "",
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-26 05:24:51 +00:00
|
|
|
|
|
|
|
|
logger.DebugCF("agent", "LLM response",
|
|
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-02-26 05:24:51 +00:00
|
|
|
"iteration": iteration,
|
|
|
|
|
"content_chars": len(response.Content),
|
|
|
|
|
"tool_calls": len(response.ToolCalls),
|
|
|
|
|
"reasoning": response.Reasoning,
|
2026-03-20 09:28:12 +00:00
|
|
|
"target_channel": al.targetReasoningChannelID(ts.channel),
|
|
|
|
|
"channel": ts.channel,
|
2026-02-26 05:24:51 +00:00
|
|
|
})
|
2026-03-20 09:28:12 +00:00
|
|
|
|
|
|
|
|
if len(response.ToolCalls) == 0 || gracefulTerminal {
|
2026-02-04 11:06:13 +00:00
|
|
|
finalContent = response.Content
|
2026-03-07 13:17:33 +00:00
|
|
|
if finalContent == "" && response.ReasoningContent != "" {
|
|
|
|
|
finalContent = response.ReasoningContent
|
|
|
|
|
}
|
2026-02-10 05:18:23 +00:00
|
|
|
logger.InfoCF("agent", "LLM response without tool calls (direct answer)",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-02-10 05:18:23 +00:00
|
|
|
"iteration": iteration,
|
|
|
|
|
"content_chars": len(finalContent),
|
|
|
|
|
})
|
2026-02-04 11:06:13 +00:00
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-17 05:55:44 +00:00
|
|
|
normalizedToolCalls := make([]providers.ToolCall, 0, len(response.ToolCalls))
|
2026-02-10 05:18:23 +00:00
|
|
|
for _, tc := range response.ToolCalls {
|
2026-02-19 01:22:39 +00:00
|
|
|
normalizedToolCalls = append(normalizedToolCalls, providers.NormalizeToolCall(tc))
|
2026-02-17 05:55:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
toolNames := make([]string, 0, len(normalizedToolCalls))
|
|
|
|
|
for _, tc := range normalizedToolCalls {
|
2026-02-10 05:18:23 +00:00
|
|
|
toolNames = append(toolNames, tc.Name)
|
|
|
|
|
}
|
|
|
|
|
logger.InfoCF("agent", "LLM requested tool calls",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-02-10 05:18:23 +00:00
|
|
|
"tools": toolNames,
|
2026-02-17 05:55:44 +00:00
|
|
|
"count": len(normalizedToolCalls),
|
2026-02-10 05:18:23 +00:00
|
|
|
"iteration": iteration,
|
|
|
|
|
})
|
|
|
|
|
|
2026-02-04 11:06:13 +00:00
|
|
|
assistantMsg := providers.Message{
|
2026-02-21 15:29:40 +00:00
|
|
|
Role: "assistant",
|
|
|
|
|
Content: response.Content,
|
|
|
|
|
ReasoningContent: response.ReasoningContent,
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
2026-02-17 05:55:44 +00:00
|
|
|
for _, tc := range normalizedToolCalls {
|
2026-02-04 11:06:13 +00:00
|
|
|
argumentsJSON, _ := json.Marshal(tc.Arguments)
|
2026-02-19 16:36:31 +00:00
|
|
|
extraContent := tc.ExtraContent
|
2026-02-16 12:10:23 +00:00
|
|
|
thoughtSignature := ""
|
|
|
|
|
if tc.Function != nil {
|
|
|
|
|
thoughtSignature = tc.Function.ThoughtSignature
|
|
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
assistantMsg.ToolCalls = append(assistantMsg.ToolCalls, providers.ToolCall{
|
2026-02-19 16:36:31 +00:00
|
|
|
ID: tc.ID,
|
|
|
|
|
Type: "function",
|
|
|
|
|
Name: tc.Name,
|
2026-02-04 11:06:13 +00:00
|
|
|
Function: &providers.FunctionCall{
|
2026-02-16 12:10:23 +00:00
|
|
|
Name: tc.Name,
|
|
|
|
|
Arguments: string(argumentsJSON),
|
|
|
|
|
ThoughtSignature: thoughtSignature,
|
2026-02-04 11:06:13 +00:00
|
|
|
},
|
2026-02-19 16:36:31 +00:00
|
|
|
ExtraContent: extraContent,
|
|
|
|
|
ThoughtSignature: thoughtSignature,
|
2026-02-04 11:06:13 +00:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
messages = append(messages, assistantMsg)
|
2026-03-20 09:28:12 +00:00
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
ts.agent.Sessions.AddFullMessage(ts.sessionKey, assistantMsg)
|
|
|
|
|
ts.recordPersistedMessage(assistantMsg)
|
|
|
|
|
}
|
2026-02-04 11:06:13 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.setPhase(TurnPhaseTools)
|
2026-03-04 09:17:28 +00:00
|
|
|
for i, tc := range normalizedToolCalls {
|
2026-03-20 09:28:12 +00:00
|
|
|
if ts.hardAbortRequested() {
|
|
|
|
|
turnStatus = TurnEndStatusAborted
|
|
|
|
|
return al.abortTurn(ts)
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
argsJSON, _ := json.Marshal(tc.Arguments)
|
|
|
|
|
argsPreview := utils.Truncate(string(argsJSON), 200)
|
|
|
|
|
logger.InfoCF("agent", fmt.Sprintf("Tool call: %s(%s)", tc.Name, argsPreview),
|
|
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
2026-03-15 16:08:16 +00:00
|
|
|
"tool": tc.Name,
|
|
|
|
|
"iteration": iteration,
|
|
|
|
|
})
|
2026-03-20 06:53:22 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindToolExecStart,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.tool.start"),
|
2026-03-20 06:53:22 +00:00
|
|
|
ToolExecStartPayload{
|
|
|
|
|
Tool: tc.Name,
|
|
|
|
|
Arguments: cloneEventArguments(tc.Arguments),
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-03-04 09:17:28 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
toolCall := tc
|
|
|
|
|
toolIteration := iteration
|
2026-03-15 16:08:16 +00:00
|
|
|
asyncCallback := func(_ context.Context, result *tools.ToolResult) {
|
|
|
|
|
if !result.Silent && result.ForUser != "" {
|
|
|
|
|
outCtx, outCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
defer outCancel()
|
|
|
|
|
_ = al.bus.PublishOutbound(outCtx, bus.OutboundMessage{
|
2026-03-20 09:28:12 +00:00
|
|
|
Channel: ts.channel,
|
|
|
|
|
ChatID: ts.chatID,
|
2026-03-15 16:08:16 +00:00
|
|
|
Content: result.ForUser,
|
2026-03-04 09:17:28 +00:00
|
|
|
})
|
2026-03-15 16:08:16 +00:00
|
|
|
}
|
2026-03-04 09:17:28 +00:00
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
content := result.ForLLM
|
|
|
|
|
if content == "" && result.Err != nil {
|
|
|
|
|
content = result.Err.Error()
|
|
|
|
|
}
|
|
|
|
|
if content == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-03-05 12:07:17 +00:00
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
logger.InfoCF("agent", "Async tool completed, publishing result",
|
|
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"tool": toolCall.Name,
|
2026-03-15 16:08:16 +00:00
|
|
|
"content_len": len(content),
|
2026-03-20 09:28:12 +00:00
|
|
|
"channel": ts.channel,
|
2026-03-05 12:07:17 +00:00
|
|
|
})
|
2026-03-20 07:29:52 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindFollowUpQueued,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.scope.meta(toolIteration, "runTurn", "turn.follow_up.queued"),
|
2026-03-20 07:29:52 +00:00
|
|
|
FollowUpQueuedPayload{
|
2026-03-20 09:28:12 +00:00
|
|
|
SourceTool: toolCall.Name,
|
|
|
|
|
Channel: ts.channel,
|
|
|
|
|
ChatID: ts.chatID,
|
2026-03-20 07:29:52 +00:00
|
|
|
ContentLen: len(content),
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-12 11:42:24 +00:00
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
pubCtx, pubCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
defer pubCancel()
|
|
|
|
|
_ = al.bus.PublishInbound(pubCtx, bus.InboundMessage{
|
|
|
|
|
Channel: "system",
|
2026-03-20 09:28:12 +00:00
|
|
|
SenderID: fmt.Sprintf("async:%s", toolCall.Name),
|
|
|
|
|
ChatID: fmt.Sprintf("%s:%s", ts.channel, ts.chatID),
|
2026-03-15 16:08:16 +00:00
|
|
|
Content: content,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 06:53:22 +00:00
|
|
|
toolStart := time.Now()
|
2026-03-20 09:28:12 +00:00
|
|
|
toolResult := ts.agent.Tools.ExecuteWithContext(
|
|
|
|
|
turnCtx,
|
|
|
|
|
toolCall.Name,
|
|
|
|
|
toolCall.Arguments,
|
|
|
|
|
ts.channel,
|
|
|
|
|
ts.chatID,
|
2026-03-15 16:08:16 +00:00
|
|
|
asyncCallback,
|
|
|
|
|
)
|
2026-03-20 06:53:22 +00:00
|
|
|
toolDuration := time.Since(toolStart)
|
2026-02-12 11:34:32 +00:00
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if ts.hardAbortRequested() {
|
|
|
|
|
turnStatus = TurnEndStatusAborted
|
|
|
|
|
return al.abortTurn(ts)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if !toolResult.Silent && toolResult.ForUser != "" && ts.opts.SendResponse {
|
refactor(bus): fix deadlock and concurrency issues in MessageBus
PublishInbound/PublishOutbound held RLock during blocking channel sends,
deadlocking against Close() which needs a write lock when the buffer is
full. ConsumeInbound/SubscribeOutbound used bare receives instead of
comma-ok, causing zero-value processing or busy loops after close.
Replace sync.RWMutex+bool with atomic.Bool+done channel so Publish
methods use a lock-free 3-way select (send / done / ctx.Done). Add
context.Context parameter to both Publish methods so callers can cancel
or timeout blocked sends. Close() now only sets the atomic flag and
closes the done channel—never closes the data channels—eliminating
send-on-closed-channel panics.
- Remove dead code: RegisterHandler, GetHandler, handlers map,
MessageHandler type (zero callers across the whole repo)
- Add ErrBusClosed sentinel error
- Update all 10 caller sites to pass context
- Add msgBus.Close() to gateway and agent shutdown flows
- Add pkg/bus/bus_test.go with 11 test cases covering basic round-trip,
context cancellation, closed-bus behavior, concurrent publish+close,
full-buffer timeout, and idempotent Close
2026-02-22 16:44:45 +00:00
|
|
|
al.bus.PublishOutbound(ctx, bus.OutboundMessage{
|
2026-03-20 09:28:12 +00:00
|
|
|
Channel: ts.channel,
|
|
|
|
|
ChatID: ts.chatID,
|
2026-03-15 16:08:16 +00:00
|
|
|
Content: toolResult.ForUser,
|
2026-02-12 11:34:32 +00:00
|
|
|
})
|
|
|
|
|
logger.DebugCF("agent", "Sent tool result to user",
|
2026-02-20 18:03:11 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"tool": toolCall.Name,
|
2026-03-15 16:08:16 +00:00
|
|
|
"content_len": len(toolResult.ForUser),
|
2026-02-12 11:34:32 +00:00
|
|
|
})
|
|
|
|
|
}
|
2026-02-12 11:28:56 +00:00
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
if len(toolResult.Media) > 0 {
|
|
|
|
|
parts := make([]bus.MediaPart, 0, len(toolResult.Media))
|
|
|
|
|
for _, ref := range toolResult.Media {
|
2026-02-22 22:03:23 +00:00
|
|
|
part := bus.MediaPart{Ref: ref}
|
|
|
|
|
if al.mediaStore != nil {
|
|
|
|
|
if _, meta, err := al.mediaStore.ResolveWithMeta(ref); err == nil {
|
|
|
|
|
part.Filename = meta.Filename
|
|
|
|
|
part.ContentType = meta.ContentType
|
|
|
|
|
part.Type = inferMediaType(meta.Filename, meta.ContentType)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
parts = append(parts, part)
|
2026-02-22 19:10:57 +00:00
|
|
|
}
|
|
|
|
|
al.bus.PublishOutboundMedia(ctx, bus.OutboundMediaMessage{
|
2026-03-20 09:28:12 +00:00
|
|
|
Channel: ts.channel,
|
|
|
|
|
ChatID: ts.chatID,
|
2026-02-22 19:10:57 +00:00
|
|
|
Parts: parts,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-15 16:08:16 +00:00
|
|
|
contentForLLM := toolResult.ForLLM
|
|
|
|
|
if contentForLLM == "" && toolResult.Err != nil {
|
|
|
|
|
contentForLLM = toolResult.Err.Error()
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
toolResultMsg := providers.Message{
|
|
|
|
|
Role: "tool",
|
2026-02-12 11:28:56 +00:00
|
|
|
Content: contentForLLM,
|
2026-03-20 09:28:12 +00:00
|
|
|
ToolCallID: toolCall.ID,
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
2026-03-20 06:53:22 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindToolExecEnd,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.tool.end"),
|
2026-03-20 06:53:22 +00:00
|
|
|
ToolExecEndPayload{
|
2026-03-20 09:28:12 +00:00
|
|
|
Tool: toolCall.Name,
|
2026-03-20 06:53:22 +00:00
|
|
|
Duration: toolDuration,
|
|
|
|
|
ForLLMLen: len(contentForLLM),
|
|
|
|
|
ForUserLen: len(toolResult.ForUser),
|
|
|
|
|
IsError: toolResult.IsError,
|
|
|
|
|
Async: toolResult.Async,
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-04 11:06:13 +00:00
|
|
|
messages = append(messages, toolResultMsg)
|
2026-03-20 09:28:12 +00:00
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
ts.agent.Sessions.AddFullMessage(ts.sessionKey, toolResultMsg)
|
|
|
|
|
ts.recordPersistedMessage(toolResultMsg)
|
|
|
|
|
}
|
2026-03-15 16:08:16 +00:00
|
|
|
|
|
|
|
|
if steerMsgs := al.dequeueSteeringMessages(); len(steerMsgs) > 0 {
|
2026-03-20 09:28:12 +00:00
|
|
|
pendingMessages = append(pendingMessages, steerMsgs...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
skipReason := ""
|
|
|
|
|
skipMessage := ""
|
|
|
|
|
if len(pendingMessages) > 0 {
|
|
|
|
|
skipReason = "queued user steering message"
|
|
|
|
|
skipMessage = "Skipped due to queued user message."
|
|
|
|
|
} else if gracefulPending, _ := ts.gracefulInterruptRequested(); gracefulPending {
|
|
|
|
|
skipReason = "graceful interrupt requested"
|
|
|
|
|
skipMessage = "Skipped due to graceful interrupt."
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if skipReason != "" {
|
2026-03-15 16:08:16 +00:00
|
|
|
remaining := len(normalizedToolCalls) - i - 1
|
|
|
|
|
if remaining > 0 {
|
2026-03-20 09:28:12 +00:00
|
|
|
logger.InfoCF("agent", "Turn checkpoint: skipping remaining tools",
|
2026-03-15 16:08:16 +00:00
|
|
|
map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID,
|
|
|
|
|
"completed": i + 1,
|
|
|
|
|
"skipped": remaining,
|
|
|
|
|
"reason": skipReason,
|
2026-03-15 16:08:16 +00:00
|
|
|
})
|
|
|
|
|
for j := i + 1; j < len(normalizedToolCalls); j++ {
|
|
|
|
|
skippedTC := normalizedToolCalls[j]
|
2026-03-20 07:29:52 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindToolExecSkipped,
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.eventMeta("runTurn", "turn.tool.skipped"),
|
2026-03-20 07:29:52 +00:00
|
|
|
ToolExecSkippedPayload{
|
|
|
|
|
Tool: skippedTC.Name,
|
2026-03-20 09:28:12 +00:00
|
|
|
Reason: skipReason,
|
2026-03-20 07:29:52 +00:00
|
|
|
},
|
|
|
|
|
)
|
2026-03-20 09:28:12 +00:00
|
|
|
skippedMsg := providers.Message{
|
2026-03-15 16:08:16 +00:00
|
|
|
Role: "tool",
|
2026-03-20 09:28:12 +00:00
|
|
|
Content: skipMessage,
|
2026-03-15 16:08:16 +00:00
|
|
|
ToolCallID: skippedTC.ID,
|
|
|
|
|
}
|
2026-03-20 09:28:12 +00:00
|
|
|
messages = append(messages, skippedMsg)
|
|
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
ts.agent.Sessions.AddFullMessage(ts.sessionKey, skippedMsg)
|
|
|
|
|
ts.recordPersistedMessage(skippedMsg)
|
|
|
|
|
}
|
2026-03-15 16:08:16 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
ts.agent.Tools.TickTTL()
|
2026-03-09 17:21:49 +00:00
|
|
|
logger.DebugCF("agent", "TTL tick after tool execution", map[string]any{
|
2026-03-20 09:28:12 +00:00
|
|
|
"agent_id": ts.agent.ID, "iteration": iteration,
|
2026-03-09 17:21:49 +00:00
|
|
|
})
|
2026-02-04 11:06:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 09:28:12 +00:00
|
|
|
if ts.hardAbortRequested() {
|
|
|
|
|
turnStatus = TurnEndStatusAborted
|
|
|
|
|
return al.abortTurn(ts)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if finalContent == "" {
|
|
|
|
|
finalContent = ts.opts.DefaultResponse
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ts.setPhase(TurnPhaseFinalizing)
|
|
|
|
|
ts.setFinalContent(finalContent)
|
|
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
finalMsg := providers.Message{Role: "assistant", Content: finalContent}
|
|
|
|
|
ts.agent.Sessions.AddMessage(ts.sessionKey, finalMsg.Role, finalMsg.Content)
|
|
|
|
|
ts.recordPersistedMessage(finalMsg)
|
|
|
|
|
if err := ts.agent.Sessions.Save(ts.sessionKey); err != nil {
|
|
|
|
|
turnStatus = TurnEndStatusError
|
|
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindError,
|
|
|
|
|
ts.eventMeta("runTurn", "turn.error"),
|
|
|
|
|
ErrorPayload{
|
|
|
|
|
Stage: "session_save",
|
|
|
|
|
Message: err.Error(),
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
return turnResult{}, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ts.opts.EnableSummary {
|
|
|
|
|
al.maybeSummarize(ts.agent, ts.sessionKey, ts.scope)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ts.setPhase(TurnPhaseCompleted)
|
|
|
|
|
return turnResult{
|
|
|
|
|
finalContent: finalContent,
|
|
|
|
|
status: turnStatus,
|
|
|
|
|
followUps: append([]bus.InboundMessage(nil), ts.followUps...),
|
|
|
|
|
}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (al *AgentLoop) abortTurn(ts *turnState) (turnResult, error) {
|
|
|
|
|
ts.setPhase(TurnPhaseAborted)
|
|
|
|
|
if !ts.opts.NoHistory {
|
|
|
|
|
if err := ts.restoreSession(ts.agent); err != nil {
|
|
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindError,
|
|
|
|
|
ts.eventMeta("abortTurn", "turn.error"),
|
|
|
|
|
ErrorPayload{
|
|
|
|
|
Stage: "session_restore",
|
|
|
|
|
Message: err.Error(),
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
return turnResult{}, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return turnResult{status: TurnEndStatusAborted}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func sleepWithContext(ctx context.Context, d time.Duration) error {
|
|
|
|
|
timer := time.NewTimer(d)
|
|
|
|
|
defer timer.Stop()
|
|
|
|
|
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
return ctx.Err()
|
|
|
|
|
case <-timer.C:
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2026-02-10 08:05:23 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-02 14:42:52 +00:00
|
|
|
// selectCandidates returns the model candidates and resolved model name to use
|
|
|
|
|
// for a conversation turn. When model routing is configured and the incoming
|
|
|
|
|
// message scores below the complexity threshold, it returns the light model
|
|
|
|
|
// candidates instead of the primary ones.
|
|
|
|
|
//
|
|
|
|
|
// The returned (candidates, model) pair is used for all LLM calls within one
|
|
|
|
|
// turn — tool follow-up iterations use the same tier as the initial call so
|
|
|
|
|
// that a multi-step tool chain doesn't switch models mid-way.
|
|
|
|
|
func (al *AgentLoop) selectCandidates(
|
|
|
|
|
agent *AgentInstance,
|
|
|
|
|
userMsg string,
|
|
|
|
|
history []providers.Message,
|
|
|
|
|
) (candidates []providers.FallbackCandidate, model string) {
|
|
|
|
|
if agent.Router == nil || len(agent.LightCandidates) == 0 {
|
|
|
|
|
return agent.Candidates, agent.Model
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 05:10:20 +00:00
|
|
|
_, usedLight, score := agent.Router.SelectModel(userMsg, history, agent.Model)
|
2026-03-02 14:42:52 +00:00
|
|
|
if !usedLight {
|
2026-03-06 05:10:20 +00:00
|
|
|
logger.DebugCF("agent", "Model routing: primary model selected",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"agent_id": agent.ID,
|
|
|
|
|
"score": score,
|
|
|
|
|
"threshold": agent.Router.Threshold(),
|
|
|
|
|
})
|
2026-03-02 14:42:52 +00:00
|
|
|
return agent.Candidates, agent.Model
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.InfoCF("agent", "Model routing: light model selected",
|
|
|
|
|
map[string]any{
|
|
|
|
|
"agent_id": agent.ID,
|
|
|
|
|
"light_model": agent.Router.LightModel(),
|
2026-03-06 05:10:20 +00:00
|
|
|
"score": score,
|
2026-03-02 14:42:52 +00:00
|
|
|
"threshold": agent.Router.Threshold(),
|
|
|
|
|
})
|
|
|
|
|
return agent.LightCandidates, agent.Router.LightModel()
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-11 12:22:41 +00:00
|
|
|
// maybeSummarize triggers summarization if the session history exceeds thresholds.
|
2026-03-20 07:29:52 +00:00
|
|
|
func (al *AgentLoop) maybeSummarize(agent *AgentInstance, sessionKey string, turnScope turnEventScope) {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
newHistory := agent.Sessions.GetHistory(sessionKey)
|
2026-02-11 12:22:41 +00:00
|
|
|
tokenEstimate := al.estimateTokens(newHistory)
|
2026-03-04 03:23:01 +00:00
|
|
|
threshold := agent.ContextWindow * agent.SummarizeTokenPercent / 100
|
2026-02-11 10:43:21 +00:00
|
|
|
|
2026-03-04 03:23:01 +00:00
|
|
|
if len(newHistory) > agent.SummarizeMessageThreshold || tokenEstimate > threshold {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
summarizeKey := agent.ID + ":" + sessionKey
|
|
|
|
|
if _, loading := al.summarizing.LoadOrStore(summarizeKey, true); !loading {
|
2026-02-11 12:22:41 +00:00
|
|
|
go func() {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
defer al.summarizing.Delete(summarizeKey)
|
2026-02-26 04:36:19 +00:00
|
|
|
logger.Debug("Memory threshold reached. Optimizing conversation history...")
|
2026-03-20 07:29:52 +00:00
|
|
|
al.summarizeSession(agent, sessionKey, turnScope)
|
2026-02-11 12:22:41 +00:00
|
|
|
}()
|
2026-02-10 08:05:23 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 07:29:52 +00:00
|
|
|
type compressionResult struct {
|
|
|
|
|
DroppedMessages int
|
|
|
|
|
RemainingMessages int
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-16 08:30:54 +00:00
|
|
|
// forceCompression aggressively reduces context when the limit is hit.
|
2026-03-13 07:54:50 +00:00
|
|
|
// It drops the oldest ~50% of Turns (a Turn is a complete user→LLM→response
|
|
|
|
|
// cycle, as defined in #1316), so tool-call sequences are never split.
|
2026-03-13 07:13:04 +00:00
|
|
|
//
|
2026-03-17 02:23:16 +00:00
|
|
|
// If the history is a single Turn with no safe split point, the function
|
|
|
|
|
// falls back to keeping only the most recent user message. This breaks
|
|
|
|
|
// Turn atomicity as a last resort to avoid a context-exceeded loop.
|
|
|
|
|
//
|
2026-03-13 07:13:04 +00:00
|
|
|
// Session history contains only user/assistant/tool messages — the system
|
|
|
|
|
// prompt is built dynamically by BuildMessages and is NOT stored here.
|
|
|
|
|
// The compression note is recorded in the session summary so that
|
|
|
|
|
// BuildMessages can include it in the next system prompt.
|
2026-03-20 07:29:52 +00:00
|
|
|
func (al *AgentLoop) forceCompression(agent *AgentInstance, sessionKey string) (compressionResult, bool) {
|
2026-02-16 13:34:55 +00:00
|
|
|
history := agent.Sessions.GetHistory(sessionKey)
|
2026-03-13 07:13:04 +00:00
|
|
|
if len(history) <= 2 {
|
2026-03-20 07:29:52 +00:00
|
|
|
return compressionResult{}, false
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-13 07:54:50 +00:00
|
|
|
// Split at a Turn boundary so no tool-call sequence is torn apart.
|
|
|
|
|
// parseTurnBoundaries gives us the start of each Turn; we drop the
|
|
|
|
|
// oldest half of Turns and keep the most recent ones.
|
|
|
|
|
turns := parseTurnBoundaries(history)
|
|
|
|
|
var mid int
|
|
|
|
|
if len(turns) >= 2 {
|
|
|
|
|
mid = turns[len(turns)/2]
|
|
|
|
|
} else {
|
|
|
|
|
// Fewer than 2 Turns — fall back to message-level midpoint
|
|
|
|
|
// aligned to the nearest Turn boundary.
|
|
|
|
|
mid = findSafeBoundary(history, len(history)/2)
|
|
|
|
|
}
|
2026-03-17 02:23:16 +00:00
|
|
|
var keptHistory []providers.Message
|
2026-03-13 07:13:04 +00:00
|
|
|
if mid <= 0 {
|
2026-03-17 02:23:16 +00:00
|
|
|
// No safe Turn boundary — the entire history is a single Turn
|
|
|
|
|
// (e.g. one user message followed by a massive tool response).
|
|
|
|
|
// Keeping everything would leave the agent stuck in a context-
|
|
|
|
|
// exceeded loop, so fall back to keeping only the most recent
|
|
|
|
|
// user message. This breaks Turn atomicity as a last resort.
|
|
|
|
|
for i := len(history) - 1; i >= 0; i-- {
|
|
|
|
|
if history[i].Role == "user" {
|
|
|
|
|
keptHistory = []providers.Message{history[i]}
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
keptHistory = history[mid:]
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-17 02:23:16 +00:00
|
|
|
droppedCount := len(history) - len(keptHistory)
|
2026-02-19 14:47:03 +00:00
|
|
|
|
2026-03-13 07:13:04 +00:00
|
|
|
// Record compression in the session summary so BuildMessages includes it
|
|
|
|
|
// in the system prompt. We do not modify history messages themselves.
|
|
|
|
|
existingSummary := agent.Sessions.GetSummary(sessionKey)
|
2026-02-20 18:03:11 +00:00
|
|
|
compressionNote := fmt.Sprintf(
|
2026-03-13 07:13:04 +00:00
|
|
|
"[Emergency compression dropped %d oldest messages due to context limit]",
|
2026-02-20 18:03:11 +00:00
|
|
|
droppedCount,
|
|
|
|
|
)
|
2026-03-13 07:13:04 +00:00
|
|
|
if existingSummary != "" {
|
|
|
|
|
compressionNote = existingSummary + "\n\n" + compressionNote
|
|
|
|
|
}
|
|
|
|
|
agent.Sessions.SetSummary(sessionKey, compressionNote)
|
2026-02-16 08:30:54 +00:00
|
|
|
|
2026-03-13 07:13:04 +00:00
|
|
|
agent.Sessions.SetHistory(sessionKey, keptHistory)
|
2026-02-16 13:34:55 +00:00
|
|
|
agent.Sessions.Save(sessionKey)
|
2026-02-16 08:30:54 +00:00
|
|
|
|
2026-02-20 18:03:11 +00:00
|
|
|
logger.WarnCF("agent", "Forced compression executed", map[string]any{
|
2026-02-16 08:30:54 +00:00
|
|
|
"session_key": sessionKey,
|
|
|
|
|
"dropped_msgs": droppedCount,
|
2026-03-13 07:13:04 +00:00
|
|
|
"new_count": len(keptHistory),
|
2026-02-16 08:30:54 +00:00
|
|
|
})
|
2026-03-20 07:29:52 +00:00
|
|
|
|
|
|
|
|
return compressionResult{
|
|
|
|
|
DroppedMessages: droppedCount,
|
|
|
|
|
RemainingMessages: len(keptHistory),
|
|
|
|
|
}, true
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-10 08:05:23 +00:00
|
|
|
// GetStartupInfo returns information about loaded tools and skills for logging.
|
2026-02-20 18:03:11 +00:00
|
|
|
func (al *AgentLoop) GetStartupInfo() map[string]any {
|
|
|
|
|
info := make(map[string]any)
|
2026-02-10 08:05:23 +00:00
|
|
|
|
2026-03-13 06:27:46 +00:00
|
|
|
registry := al.GetRegistry()
|
|
|
|
|
agent := registry.GetDefaultAgent()
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
if agent == nil {
|
|
|
|
|
return info
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-10 08:05:23 +00:00
|
|
|
// Tools info
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
toolsList := agent.Tools.List()
|
2026-02-20 18:03:11 +00:00
|
|
|
info["tools"] = map[string]any{
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
"count": len(toolsList),
|
|
|
|
|
"names": toolsList,
|
2026-02-10 08:05:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Skills info
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
info["skills"] = agent.ContextBuilder.GetSkillsInfo()
|
|
|
|
|
|
|
|
|
|
// Agents info
|
2026-02-20 18:03:11 +00:00
|
|
|
info["agents"] = map[string]any{
|
2026-03-13 06:27:46 +00:00
|
|
|
"count": len(registry.ListAgentIDs()),
|
|
|
|
|
"ids": registry.ListAgentIDs(),
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
}
|
2026-02-10 08:05:23 +00:00
|
|
|
|
|
|
|
|
return info
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-10 15:33:28 +00:00
|
|
|
// formatMessagesForLog formats messages for logging
|
|
|
|
|
func formatMessagesForLog(messages []providers.Message) string {
|
|
|
|
|
if len(messages) == 0 {
|
|
|
|
|
return "[]"
|
2026-02-09 18:25:46 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-20 07:06:33 +00:00
|
|
|
var sb strings.Builder
|
|
|
|
|
sb.WriteString("[\n")
|
2026-02-10 15:33:28 +00:00
|
|
|
for i, msg := range messages {
|
2026-02-20 07:06:33 +00:00
|
|
|
fmt.Fprintf(&sb, " [%d] Role: %s\n", i, msg.Role)
|
2026-02-16 08:30:54 +00:00
|
|
|
if len(msg.ToolCalls) > 0 {
|
2026-02-20 07:06:33 +00:00
|
|
|
sb.WriteString(" ToolCalls:\n")
|
2026-02-10 15:33:28 +00:00
|
|
|
for _, tc := range msg.ToolCalls {
|
2026-02-20 07:06:33 +00:00
|
|
|
fmt.Fprintf(&sb, " - ID: %s, Type: %s, Name: %s\n", tc.ID, tc.Type, tc.Name)
|
2026-02-10 15:33:28 +00:00
|
|
|
if tc.Function != nil {
|
2026-03-01 00:53:13 +00:00
|
|
|
fmt.Fprintf(
|
|
|
|
|
&sb,
|
|
|
|
|
" Arguments: %s\n",
|
|
|
|
|
utils.Truncate(tc.Function.Arguments, 200),
|
|
|
|
|
)
|
2026-02-10 15:33:28 +00:00
|
|
|
}
|
|
|
|
|
}
|
2026-02-09 19:00:57 +00:00
|
|
|
}
|
2026-02-10 15:33:28 +00:00
|
|
|
if msg.Content != "" {
|
2026-02-11 12:22:41 +00:00
|
|
|
content := utils.Truncate(msg.Content, 200)
|
2026-02-20 07:06:33 +00:00
|
|
|
fmt.Fprintf(&sb, " Content: %s\n", content)
|
2026-02-09 19:00:57 +00:00
|
|
|
}
|
2026-02-10 15:33:28 +00:00
|
|
|
if msg.ToolCallID != "" {
|
2026-02-20 07:06:33 +00:00
|
|
|
fmt.Fprintf(&sb, " ToolCallID: %s\n", msg.ToolCallID)
|
2026-02-09 18:25:46 +00:00
|
|
|
}
|
2026-02-20 07:06:33 +00:00
|
|
|
sb.WriteString("\n")
|
2026-02-09 18:25:46 +00:00
|
|
|
}
|
2026-02-20 07:06:33 +00:00
|
|
|
sb.WriteString("]")
|
|
|
|
|
return sb.String()
|
2026-02-09 19:00:57 +00:00
|
|
|
}
|
2026-02-09 18:25:46 +00:00
|
|
|
|
2026-02-10 15:33:28 +00:00
|
|
|
// formatToolsForLog formats tool definitions for logging
|
2026-02-20 07:06:33 +00:00
|
|
|
func formatToolsForLog(toolDefs []providers.ToolDefinition) string {
|
|
|
|
|
if len(toolDefs) == 0 {
|
2026-02-10 15:33:28 +00:00
|
|
|
return "[]"
|
2026-02-09 18:25:46 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-20 07:06:33 +00:00
|
|
|
var sb strings.Builder
|
|
|
|
|
sb.WriteString("[\n")
|
|
|
|
|
for i, tool := range toolDefs {
|
|
|
|
|
fmt.Fprintf(&sb, " [%d] Type: %s, Name: %s\n", i, tool.Type, tool.Function.Name)
|
|
|
|
|
fmt.Fprintf(&sb, " Description: %s\n", tool.Function.Description)
|
2026-02-10 15:33:28 +00:00
|
|
|
if len(tool.Function.Parameters) > 0 {
|
2026-03-01 00:53:13 +00:00
|
|
|
fmt.Fprintf(
|
|
|
|
|
&sb,
|
|
|
|
|
" Parameters: %s\n",
|
|
|
|
|
utils.Truncate(fmt.Sprintf("%v", tool.Function.Parameters), 200),
|
|
|
|
|
)
|
2026-02-10 15:33:28 +00:00
|
|
|
}
|
2026-02-09 18:25:46 +00:00
|
|
|
}
|
2026-02-20 07:06:33 +00:00
|
|
|
sb.WriteString("]")
|
|
|
|
|
return sb.String()
|
2026-02-09 19:00:57 +00:00
|
|
|
}
|
2026-02-09 18:25:46 +00:00
|
|
|
|
2026-02-11 11:27:36 +00:00
|
|
|
// summarizeSession summarizes the conversation history for a session.
|
2026-03-20 07:29:52 +00:00
|
|
|
func (al *AgentLoop) summarizeSession(agent *AgentInstance, sessionKey string, turnScope turnEventScope) {
|
2026-02-11 11:27:36 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
history := agent.Sessions.GetHistory(sessionKey)
|
|
|
|
|
summary := agent.Sessions.GetSummary(sessionKey)
|
2026-02-11 11:27:36 +00:00
|
|
|
|
2026-03-13 07:54:50 +00:00
|
|
|
// Keep the most recent Turns for continuity, aligned to a Turn boundary
|
2026-03-13 06:20:24 +00:00
|
|
|
// so that no tool-call sequence is split.
|
2026-02-11 11:27:36 +00:00
|
|
|
if len(history) <= 4 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 06:20:24 +00:00
|
|
|
safeCut := findSafeBoundary(history, len(history)-4)
|
|
|
|
|
if safeCut <= 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
keepCount := len(history) - safeCut
|
|
|
|
|
toSummarize := history[:safeCut]
|
2026-02-11 11:27:36 +00:00
|
|
|
|
|
|
|
|
// Oversized Message Guard
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
maxMessageTokens := agent.ContextWindow / 2
|
2026-02-11 11:27:36 +00:00
|
|
|
validMessages := make([]providers.Message, 0)
|
|
|
|
|
omitted := false
|
|
|
|
|
|
|
|
|
|
for _, m := range toSummarize {
|
|
|
|
|
if m.Role != "user" && m.Role != "assistant" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
2026-02-16 13:34:55 +00:00
|
|
|
msgTokens := len(m.Content) / 2
|
2026-02-11 11:27:36 +00:00
|
|
|
if msgTokens > maxMessageTokens {
|
|
|
|
|
omitted = true
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
validMessages = append(validMessages, m)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(validMessages) == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-09 05:41:41 +00:00
|
|
|
const (
|
|
|
|
|
maxSummarizationMessages = 10
|
|
|
|
|
llmMaxRetries = 3
|
|
|
|
|
llmTemperature = 0.3
|
|
|
|
|
fallbackMaxContentLength = 200
|
|
|
|
|
)
|
|
|
|
|
|
2026-02-11 11:27:36 +00:00
|
|
|
// Multi-Part Summarization
|
|
|
|
|
var finalSummary string
|
2026-03-09 05:41:41 +00:00
|
|
|
if len(validMessages) > maxSummarizationMessages {
|
2026-02-11 11:27:36 +00:00
|
|
|
mid := len(validMessages) / 2
|
2026-03-09 05:41:41 +00:00
|
|
|
|
|
|
|
|
mid = al.findNearestUserMessage(validMessages, mid)
|
|
|
|
|
|
2026-02-11 11:27:36 +00:00
|
|
|
part1 := validMessages[:mid]
|
|
|
|
|
part2 := validMessages[mid:]
|
|
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
s1, _ := al.summarizeBatch(ctx, agent, part1, "")
|
|
|
|
|
s2, _ := al.summarizeBatch(ctx, agent, part2, "")
|
2026-02-11 11:27:36 +00:00
|
|
|
|
2026-02-20 18:03:11 +00:00
|
|
|
mergePrompt := fmt.Sprintf(
|
|
|
|
|
"Merge these two conversation summaries into one cohesive summary:\n\n1: %s\n\n2: %s",
|
|
|
|
|
s1,
|
|
|
|
|
s2,
|
|
|
|
|
)
|
2026-03-09 05:41:41 +00:00
|
|
|
|
|
|
|
|
resp, err := al.retryLLMCall(ctx, agent, mergePrompt, llmMaxRetries)
|
|
|
|
|
if err == nil && resp.Content != "" {
|
2026-02-11 11:27:36 +00:00
|
|
|
finalSummary = resp.Content
|
|
|
|
|
} else {
|
|
|
|
|
finalSummary = s1 + " " + s2
|
|
|
|
|
}
|
|
|
|
|
} else {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
finalSummary, _ = al.summarizeBatch(ctx, agent, validMessages, summary)
|
2026-02-11 11:27:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if omitted && finalSummary != "" {
|
|
|
|
|
finalSummary += "\n[Note: Some oversized messages were omitted from this summary for efficiency.]"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if finalSummary != "" {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
agent.Sessions.SetSummary(sessionKey, finalSummary)
|
2026-03-13 06:20:24 +00:00
|
|
|
agent.Sessions.TruncateHistory(sessionKey, keepCount)
|
2026-02-13 15:24:26 +00:00
|
|
|
agent.Sessions.Save(sessionKey)
|
2026-03-20 07:29:52 +00:00
|
|
|
al.emitEvent(
|
|
|
|
|
EventKindSessionSummarize,
|
|
|
|
|
turnScope.meta(0, "summarizeSession", "turn.session.summarize"),
|
|
|
|
|
SessionSummarizePayload{
|
|
|
|
|
SummarizedMessages: len(validMessages),
|
|
|
|
|
KeptMessages: keepCount,
|
|
|
|
|
SummaryLen: len(finalSummary),
|
|
|
|
|
OmittedOversized: omitted,
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-11 11:27:36 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-09 05:41:41 +00:00
|
|
|
// findNearestUserMessage finds the nearest user message to the given index.
|
|
|
|
|
// It searches backward first, then forward if no user message is found.
|
|
|
|
|
func (al *AgentLoop) findNearestUserMessage(messages []providers.Message, mid int) int {
|
|
|
|
|
originalMid := mid
|
|
|
|
|
|
|
|
|
|
for mid > 0 && messages[mid].Role != "user" {
|
|
|
|
|
mid--
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if messages[mid].Role == "user" {
|
|
|
|
|
return mid
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
mid = originalMid
|
|
|
|
|
for mid < len(messages) && messages[mid].Role != "user" {
|
|
|
|
|
mid++
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if mid < len(messages) {
|
|
|
|
|
return mid
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return originalMid
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// retryLLMCall calls the LLM with retry logic.
|
|
|
|
|
func (al *AgentLoop) retryLLMCall(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
agent *AgentInstance,
|
|
|
|
|
prompt string,
|
|
|
|
|
maxRetries int,
|
|
|
|
|
) (*providers.LLMResponse, error) {
|
|
|
|
|
const (
|
|
|
|
|
llmTemperature = 0.3
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var resp *providers.LLMResponse
|
|
|
|
|
var err error
|
|
|
|
|
|
|
|
|
|
for attempt := 0; attempt < maxRetries; attempt++ {
|
2026-03-13 06:27:46 +00:00
|
|
|
al.activeRequests.Add(1)
|
|
|
|
|
resp, err = func() (*providers.LLMResponse, error) {
|
|
|
|
|
defer al.activeRequests.Done()
|
|
|
|
|
return agent.Provider.Chat(
|
|
|
|
|
ctx,
|
|
|
|
|
[]providers.Message{{Role: "user", Content: prompt}},
|
|
|
|
|
nil,
|
|
|
|
|
agent.Model,
|
|
|
|
|
map[string]any{
|
|
|
|
|
"max_tokens": agent.MaxTokens,
|
|
|
|
|
"temperature": llmTemperature,
|
|
|
|
|
"prompt_cache_key": agent.ID,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
}()
|
|
|
|
|
|
2026-03-09 05:41:41 +00:00
|
|
|
if err == nil && resp != nil && resp.Content != "" {
|
|
|
|
|
return resp, nil
|
|
|
|
|
}
|
|
|
|
|
if attempt < maxRetries-1 {
|
|
|
|
|
time.Sleep(time.Duration(attempt+1) * 100 * time.Millisecond)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return resp, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-11 11:27:36 +00:00
|
|
|
// summarizeBatch summarizes a batch of messages.
|
2026-02-20 18:03:11 +00:00
|
|
|
func (al *AgentLoop) summarizeBatch(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
agent *AgentInstance,
|
|
|
|
|
batch []providers.Message,
|
|
|
|
|
existingSummary string,
|
|
|
|
|
) (string, error) {
|
2026-03-09 05:41:41 +00:00
|
|
|
const (
|
|
|
|
|
llmMaxRetries = 3
|
|
|
|
|
llmTemperature = 0.3
|
|
|
|
|
fallbackMinContentLength = 200
|
|
|
|
|
fallbackMaxContentPercent = 10
|
|
|
|
|
)
|
|
|
|
|
|
2026-02-20 07:06:33 +00:00
|
|
|
var sb strings.Builder
|
2026-03-01 00:53:13 +00:00
|
|
|
sb.WriteString(
|
|
|
|
|
"Provide a concise summary of this conversation segment, preserving core context and key points.\n",
|
|
|
|
|
)
|
2026-02-11 11:27:36 +00:00
|
|
|
if existingSummary != "" {
|
2026-02-20 07:06:33 +00:00
|
|
|
sb.WriteString("Existing context: ")
|
|
|
|
|
sb.WriteString(existingSummary)
|
|
|
|
|
sb.WriteString("\n")
|
2026-02-11 11:27:36 +00:00
|
|
|
}
|
2026-02-20 07:06:33 +00:00
|
|
|
sb.WriteString("\nCONVERSATION:\n")
|
2026-02-11 11:27:36 +00:00
|
|
|
for _, m := range batch {
|
2026-02-20 07:06:33 +00:00
|
|
|
fmt.Fprintf(&sb, "%s: %s\n", m.Role, m.Content)
|
2026-02-09 18:25:46 +00:00
|
|
|
}
|
2026-02-20 07:06:33 +00:00
|
|
|
prompt := sb.String()
|
2026-02-11 11:27:36 +00:00
|
|
|
|
2026-03-09 05:41:41 +00:00
|
|
|
response, err := al.retryLLMCall(ctx, agent, prompt, llmMaxRetries)
|
|
|
|
|
if err == nil && response.Content != "" {
|
|
|
|
|
return strings.TrimSpace(response.Content), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var fallback strings.Builder
|
|
|
|
|
fallback.WriteString("Conversation summary: ")
|
|
|
|
|
for i, m := range batch {
|
|
|
|
|
if i > 0 {
|
|
|
|
|
fallback.WriteString(" | ")
|
|
|
|
|
}
|
|
|
|
|
content := strings.TrimSpace(m.Content)
|
|
|
|
|
runes := []rune(content)
|
|
|
|
|
if len(runes) == 0 {
|
|
|
|
|
fallback.WriteString(fmt.Sprintf("%s: ", m.Role))
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
keepLength := len(runes) * fallbackMaxContentPercent / 100
|
|
|
|
|
if keepLength < fallbackMinContentLength {
|
|
|
|
|
keepLength = fallbackMinContentLength
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if keepLength > len(runes) {
|
|
|
|
|
keepLength = len(runes)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
content = string(runes[:keepLength])
|
|
|
|
|
if keepLength < len(runes) {
|
|
|
|
|
content += "..."
|
|
|
|
|
}
|
|
|
|
|
fallback.WriteString(fmt.Sprintf("%s: %s", m.Role, content))
|
2026-02-11 11:27:36 +00:00
|
|
|
}
|
2026-03-09 05:41:41 +00:00
|
|
|
return fallback.String(), nil
|
2026-02-11 11:27:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// estimateTokens estimates the number of tokens in a message list.
|
2026-03-13 06:20:24 +00:00
|
|
|
// Counts Content, ToolCalls arguments, and ToolCallID metadata so that
|
|
|
|
|
// tool-heavy conversations are not systematically undercounted.
|
2026-02-11 11:27:36 +00:00
|
|
|
func (al *AgentLoop) estimateTokens(messages []providers.Message) int {
|
2026-03-13 06:20:24 +00:00
|
|
|
total := 0
|
2026-02-11 11:27:36 +00:00
|
|
|
for _, m := range messages {
|
2026-03-13 06:20:24 +00:00
|
|
|
total += estimateMessageTokens(m)
|
2026-02-10 15:33:28 +00:00
|
|
|
}
|
2026-03-13 06:20:24 +00:00
|
|
|
return total
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
|
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
func (al *AgentLoop) handleCommand(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
msg bus.InboundMessage,
|
|
|
|
|
agent *AgentInstance,
|
2026-03-09 08:39:33 +00:00
|
|
|
opts *processOptions,
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
) (string, bool) {
|
|
|
|
|
if !commands.HasCommandPrefix(msg.Content) {
|
2026-02-16 08:30:54 +00:00
|
|
|
return "", false
|
|
|
|
|
}
|
|
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
if al.cmdRegistry == nil {
|
2026-02-16 08:30:54 +00:00
|
|
|
return "", false
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-09 08:39:33 +00:00
|
|
|
rt := al.buildCommandsRuntime(agent, opts)
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
executor := commands.NewExecutor(al.cmdRegistry, rt)
|
2026-02-16 08:30:54 +00:00
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
var commandReply string
|
|
|
|
|
result := executor.Execute(ctx, commands.Request{
|
|
|
|
|
Channel: msg.Channel,
|
|
|
|
|
ChatID: msg.ChatID,
|
|
|
|
|
SenderID: msg.SenderID,
|
|
|
|
|
Text: msg.Content,
|
|
|
|
|
Reply: func(text string) error {
|
|
|
|
|
commandReply = text
|
|
|
|
|
return nil
|
|
|
|
|
},
|
|
|
|
|
})
|
2026-02-16 08:30:54 +00:00
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
switch result.Outcome {
|
|
|
|
|
case commands.OutcomeHandled:
|
|
|
|
|
if result.Err != nil {
|
|
|
|
|
return mapCommandError(result), true
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
if commandReply != "" {
|
|
|
|
|
return commandReply, true
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
return "", true
|
|
|
|
|
default: // OutcomePassthrough — let the message fall through to LLM
|
|
|
|
|
return "", false
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-16 08:30:54 +00:00
|
|
|
|
2026-03-09 08:39:33 +00:00
|
|
|
func (al *AgentLoop) buildCommandsRuntime(agent *AgentInstance, opts *processOptions) *commands.Runtime {
|
2026-03-13 06:27:46 +00:00
|
|
|
registry := al.GetRegistry()
|
|
|
|
|
cfg := al.GetConfig()
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
rt := &commands.Runtime{
|
2026-03-13 06:27:46 +00:00
|
|
|
Config: cfg,
|
|
|
|
|
ListAgentIDs: registry.ListAgentIDs,
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
ListDefinitions: al.cmdRegistry.Definitions,
|
|
|
|
|
GetEnabledChannels: func() []string {
|
|
|
|
|
if al.channelManager == nil {
|
|
|
|
|
return nil
|
2026-02-16 13:34:55 +00:00
|
|
|
}
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
return al.channelManager.GetEnabledChannels()
|
|
|
|
|
},
|
|
|
|
|
SwitchChannel: func(value string) error {
|
2026-02-16 08:30:54 +00:00
|
|
|
if al.channelManager == nil {
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
return fmt.Errorf("channel manager not initialized")
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
|
|
|
|
if _, exists := al.channelManager.GetChannel(value); !exists && value != "cli" {
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
return fmt.Errorf("channel '%s' not found or not enabled", value)
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
return nil
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
if agent != nil {
|
|
|
|
|
rt.GetModelInfo = func() (string, string) {
|
2026-03-13 06:27:46 +00:00
|
|
|
return agent.Model, cfg.Agents.Defaults.Provider
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
}
|
|
|
|
|
rt.SwitchModel = func(value string) (string, error) {
|
|
|
|
|
oldModel := agent.Model
|
|
|
|
|
agent.Model = value
|
|
|
|
|
return oldModel, nil
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
2026-03-09 08:39:33 +00:00
|
|
|
|
|
|
|
|
rt.ClearHistory = func() error {
|
|
|
|
|
if opts == nil {
|
|
|
|
|
return fmt.Errorf("process options not available")
|
|
|
|
|
}
|
|
|
|
|
if agent.Sessions == nil {
|
|
|
|
|
return fmt.Errorf("sessions not initialized for agent")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
agent.Sessions.SetHistory(opts.SessionKey, make([]providers.Message, 0))
|
|
|
|
|
agent.Sessions.SetSummary(opts.SessionKey, "")
|
|
|
|
|
agent.Sessions.Save(opts.SessionKey)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2026-02-16 08:30:54 +00:00
|
|
|
}
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
return rt
|
|
|
|
|
}
|
2026-02-16 08:30:54 +00:00
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
func mapCommandError(result commands.ExecuteResult) string {
|
|
|
|
|
if result.Command == "" {
|
|
|
|
|
return fmt.Sprintf("Failed to execute command: %v", result.Err)
|
|
|
|
|
}
|
|
|
|
|
return fmt.Sprintf("Failed to execute /%s: %v", result.Command, result.Err)
|
2026-02-09 18:25:46 +00:00
|
|
|
}
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
|
2026-02-22 13:57:12 +00:00
|
|
|
// extractPeer extracts the routing peer from the inbound message's structured Peer field.
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
func extractPeer(msg bus.InboundMessage) *routing.RoutePeer {
|
2026-02-22 13:57:12 +00:00
|
|
|
if msg.Peer.Kind == "" {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
2026-02-22 13:57:12 +00:00
|
|
|
peerID := msg.Peer.ID
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
if peerID == "" {
|
2026-02-22 13:57:12 +00:00
|
|
|
if msg.Peer.Kind == "direct" {
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
peerID = msg.SenderID
|
|
|
|
|
} else {
|
|
|
|
|
peerID = msg.ChatID
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-22 13:57:12 +00:00
|
|
|
return &routing.RoutePeer{Kind: msg.Peer.Kind, ID: peerID}
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
}
|
|
|
|
|
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
func inboundMetadata(msg bus.InboundMessage, key string) string {
|
|
|
|
|
if msg.Metadata == nil {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
return msg.Metadata[key]
|
|
|
|
|
}
|
|
|
|
|
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
// extractParentPeer extracts the parent peer (reply-to) from inbound message metadata.
|
|
|
|
|
func extractParentPeer(msg bus.InboundMessage) *routing.RoutePeer {
|
feat(commands): centralized command registry with sub-command routing (#959)
* feat(commands): Session management [Phase 1/2] command centralization and registration
* docs: add design for command registry post-review fixes
Documents the architecture decisions for fixing 5 Important issues
from code review: SubCommand pattern, Deps struct, command-group files,
Executor caching, and Telegram registration dedup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add SubCommand type and EffectiveUsage method
Introduce SubCommand struct for declaring sub-commands structurally
within a parent command Definition. The EffectiveUsage() method
auto-generates usage strings from sub-command names and args,
preventing drift between help text and actual handler behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add Deps struct and secondToken helper, remove dead contains()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(commands): add sub-command routing to Executor
Uses Registry.Lookup for O(1) command dispatch instead of iterating
all definitions. Definitions with SubCommands are routed to matching
sub-command handlers. Missing or unknown sub-commands reply with
auto-generated usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): split into command-group files with Deps injection
Extract show/list/start/help into individual cmd_*.go files.
Replace config.Config parameter with Deps struct for runtime data.
Restore /show agents and /list agents sub-commands.
Use EffectiveUsage for auto-generated help text.
Bridge external callers (agent/loop.go, telegram.go) with Deps wrapper
until Task 5 fully wires the Deps fields.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* perf(commands): cache Executor in AgentLoop, wire Deps with runtime callbacks
Create Executor once in NewAgentLoop instead of per-message. Deps
closures capture AgentLoop pointer for late-bound access to
channelManager and runtime agent model.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(telegram): remove duplicate initBotCommands, keep async startCommandRegistration only
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(commands): restore Outcome comments and annotate Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): consolidate /switch into commands package, fix ! prefix
Move /switch model and /switch channel handling from inline loop.go
logic into cmd_switch.go using the SubCommand + Deps pattern. This
removes the OutcomePassthrough branch in handleCommand entirely.
Also replace the hardcoded "/" prefix check with commands.HasCommandPrefix
so that "!" prefixed commands are correctly routed to the Executor.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add docs/plans to .gitignore and untrack existing files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings
- Remove dead ExecuteResult.Reply field and unused branch in loop.go
- Extract shared agentsHandler for /show agents and /list agents
- Remove redundant firstToken/secondToken (use nthToken instead)
- Simplify Telegram startup: pass BuiltinDefinitions directly
- Centralize req.Reply nil guard in executeDefinition
- Extract unavailableMsg constant (was duplicated 5 times)
- Remove unused MessageID from Request
- Remove stale "reserved for Phase 2" comment on Deps.Config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): replace Deps with per-request Runtime
Separate stateless Registry (cached on AgentLoop) from per-request
Runtime (passed to handlers at execution time). This enables future
session management features to inject per-request context without
modifying the command registry.
- Rename Deps → Runtime, move to runtime.go
- Change Handler signature: func(ctx, req) error → func(ctx, req, rt *Runtime) error
- NewExecutor now takes (registry, runtime) — executor is created per-request
- BuiltinDefinitions() no longer takes parameters (stateless)
- AgentLoop caches cmdRegistry, builds Runtime via buildRuntime()
- Update all cmd_*.go handlers and tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style: fix gci import grouping and godoc formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(onboard): skip legacy AGENT.md when copying embedded workspace templates
The workspace/ directory contains both AGENT.md (legacy) and AGENTS.md
(current). copyEmbeddedToTarget was copying both, causing the test
TestCopyEmbeddedToTargetUsesAgentsMarkdown to fail. Skip AGENT.md
during the walk to match the expected behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(agent): address self-review comments on loop.go
- Move cmdRegistry init into struct literal (review comment #11)
- Rename buildRuntime → buildCommandsRuntime for clarity (review comment #12)
- Add comment to default switch case explaining passthrough (review comment #13)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): address code review findings on naming and correctness
- Rename dispatcher.go → request.go (no Dispatcher type remains)
- Rename cmd_agents.go → handler_agents.go (shared handler, not a top-level command)
- Add modelMu to protect AgentInstance.Model writes in SwitchModel
- Add ListDefinitions to Runtime so /help uses registry instead of BuiltinDefinitions()
- Fix SwitchChannel message: validation-only callback should not say "Switched"
- Propagate Reply errors in executor instead of discarding with _ =
- Add HasCommandPrefix unit test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(onboard): extract legacy filename to constant
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(agent): handle commands before route error check
Move handleCommand() before the routeErr gate so global commands
(/help, /show, /switch) remain available even when routing fails.
Context-dependent commands that need a routed agent will report
"unavailable" through their nil-Runtime guards.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert: remove unnecessary AGENT.md skip in onboard
Reverts 02d0c04 and 74deae1. The test failure was caused by a local
leftover workspace/AGENT.md file (gitignored but embedded by go:embed).
Deleting the local file fixes the root cause; the code-level skip was
never needed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: executeDefinition Unknown option
* fix(agent): use routed agent for model commands, restore Telegram command diff
- Remove modelMu: message processing is serial, no concurrent writes
- Pass routed agent to handleCommand/buildCommandsRuntime instead of
always using default agent
- GetModelInfo/SwitchModel are nil when agent is nil (route failed),
handlers reply "unavailable"
- Restore GetMyCommands + slices.Equal check before SetMyCommands to
avoid unnecessary Telegram API calls on restart
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(commands): remove unintended config mutation in SwitchModel
SwitchModel should only update the routed agent's runtime Model field.
Writing to cfg.Agents.Defaults.ModelName was a behavioral change that
corrupts the default agent config when switching a non-default agent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(commands): move /switch channel to /check channel
/switch channel only validates availability, not actually switching.
Rename to /check channel to match actual behavior. /switch channel
now shows a redirect message pointing users to the new command.
Addresses review feedback from yinwm on PR #959.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:31:40 +00:00
|
|
|
parentKind := inboundMetadata(msg, metadataKeyParentPeerKind)
|
|
|
|
|
parentID := inboundMetadata(msg, metadataKeyParentPeerID)
|
feat: add multi-agent routing with declarative bindings
Implement per-agent workspace/model/session isolation with 7-level
priority routing cascade (peer > parent_peer > guild > team > account >
channel > default). Backward compatible - empty agents.list creates
implicit "main" agent from defaults.
Core components:
- routing/agent_id.go: ID normalization with pre-compiled regex
- routing/session_key.go: 4 DM scope modes with identity links
- routing/route.go: RouteResolver with priority-based binding matcher
- agent/instance.go: Per-agent state (workspace, sessions, tools, model)
- agent/registry.go: Agent lifecycle, route resolution, subagent ACL
Integration:
- config.go: AgentModelConfig (flexible JSON), bindings, session config
- loop.go: Complete rewrite for multi-agent dispatch
- Channel adapters: peer_kind/peer_id metadata (telegram, discord, slack)
- spawn.go: Subagent allowlist enforcement per agent
Validated end-to-end with Discord channel-based bindings, default
fallback routing, and per-agent session persistence.
2026-02-13 15:12:33 +00:00
|
|
|
if parentKind == "" || parentID == "" {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
return &routing.RoutePeer{Kind: parentKind, ID: parentID}
|
|
|
|
|
}
|
2026-03-13 06:27:46 +00:00
|
|
|
|
|
|
|
|
// Helper to extract provider from registry for cleanup
|
|
|
|
|
func extractProvider(registry *AgentRegistry) (providers.LLMProvider, bool) {
|
|
|
|
|
if registry == nil {
|
|
|
|
|
return nil, false
|
|
|
|
|
}
|
|
|
|
|
// Get any agent to access the provider
|
|
|
|
|
defaultAgent := registry.GetDefaultAgent()
|
|
|
|
|
if defaultAgent == nil {
|
|
|
|
|
return nil, false
|
|
|
|
|
}
|
|
|
|
|
return defaultAgent.Provider, true
|
|
|
|
|
}
|