* feat(cli): add workspace, config-dir, tools, and skills override flags Add --workspace, --config-dir, --tools, and --skills flags to `picoclaw agent` for single-shot invocations. Supports workspace override with bootstrap file injection (AGENTS.md, IDENTITY.md, SOUL.md, USER.md), tool allowlisting, and skills filtering. Also extracts FormatSkillsSummary from SkillsLoader for reuse, adds SetSkillsFilter to ContextBuilder, and wires SkillsFilter from agent config into the context builder. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(channels): add MagicForm webhook channel plugin Implement MagicForm channel for webhook-based agentic task delegation. Supports Bearer token auth, async processing with HTTP callback, workspace path validation against configurable workspace_root, bootstrap file injection, tool/skill filtering via metadata, and per-conversation session key isolation. Includes Bus() accessor on BaseChannel for direct message publishing, MagicFormConfig with workspace_root for path traversal prevention, request body size limits, and TTL cleanup for stale request contexts. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(agent): support per-request workspace, tool, and skill overrides Add workspace override, tool allowlisting, and skills filtering to the agent loop via processOptions metadata. When a workspace override is active (e.g. from MagicForm channel), creates isolated SessionManager and ContextBuilder instances per request. Threads effSessions/effContextBuilder through all downstream paths including runLLMIteration, forceCompression, maybeSummarize, and summarizeSession to ensure full workspace isolation. Adds defense-in- depth tool execution guard alongside LLM-facing tool definition filter. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(auth): add response body size limits to OAuth HTTP calls Wrap all io.ReadAll(resp.Body) calls in the OAuth flow with io.LimitReader capped at 1 MB to prevent memory exhaustion from malicious or unexpectedly large server responses. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(tools): add response body size limits to search providers Add 2 MB LimitReader to BraveSearch, Tavily, DuckDuckGo, and Perplexity search providers to prevent memory exhaustion from unexpectedly large responses. Matches existing pattern used by GLMSearchProvider. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(tools): add 20 MB file write size limit Reject writes exceeding 20 MB in WriteFileTool to prevent disk exhaustion from unexpectedly large LLM-generated file content. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(tools): use crypto/rand for temp file naming Replace predictable PID+nanosecond temp file names with cryptographically random hex strings to prevent symlink pre-placement attacks. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(skills): validate GitHub repo format and limit download size Add regex validation for 'owner/repo' format to prevent URL injection in InstallFromGitHub. Add 5 MB LimitReader on skill file downloads to prevent memory exhaustion. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(auth): allow OAuth credentials to be overridden via env vars Add PICOCLAW_OPENAI_CLIENT_ID, PICOCLAW_GOOGLE_CLIENT_ID, and PICOCLAW_GOOGLE_CLIENT_SECRET env var overrides. Hardcoded values remain as fallback defaults for backward compatibility. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(auth): sanitize OAuth error messages Replace raw HTTP response bodies in error messages with generic status-code-only messages. Full response details are logged at debug level for troubleshooting. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(launcher): HTML-escape error messages in auth callback Use html.EscapeString on all error text rendered in HTML responses to prevent XSS via crafted OAuth error parameters or error messages. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(launcher): remove internal details from HTTP error responses Log detailed errors server-side and return generic messages to clients to prevent information disclosure of file paths and internal state. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(launcher): add HTTP security headers middleware Add SecurityHeaders middleware setting X-Content-Type-Options, X-Frame-Options, and Content-Security-Policy on all responses to mitigate MIME sniffing, clickjacking, and content injection. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(skills): validate ClawHub registry base URL scheme Reject non-HTTPS registry URLs (unless localhost) to prevent config-based redirection to malicious skill servers. Falls back to the default https://clawhub.ai with a warning. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(skills): prevent workspace skills from shadowing builtins Builtin skill names are now reserved — workspace and global skills with the same name as a builtin are skipped with a warning log. LoadSkill also checks builtins first. This prevents supply chain attacks where a malicious skill replaces a trusted builtin. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(skills): warn when safety metadata is unavailable Add MetadataAvailable flag to InstallResult. When the registry metadata fetch fails (silent fallback), the user now sees a warning that safety checks could not be completed. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * security(shell): add opt-in environment variable filtering When filter_env is enabled in config, shell commands run with a minimal allowlist of environment variables (PATH, HOME, LANG, TERM, etc. plus PICOCLAW_* prefix), preventing accidental leakage of sensitive env vars like API keys to spawned processes. Disabled by default for backward compat. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(config): add workspace-local config.json overlay for per-tenant isolation Support per-workspace config overrides via --config-dir (CLI) or configDir (webhook), enabling different API keys, models, and agent settings per tenant. - Add LoadWorkspaceConfig/MergeWorkspaceConfig with raw JSON overlay to preserve unmentioned bool fields (prevents clobbering tool enabled flags) - Add Config.Clone() for safe per-request config copies in gateway mode - Gateway: per-request provider creation from workspace config, with effProvider/effModel threaded through all LLM call sites and summarization - CLI: workspace config merged before provider creation, CLI flags win - MagicForm: replace inline bootstrap fields with configDir path; agent loop copies bootstrap files and loads config.json from configDir - Fix --session flag: format as agent:main:cli:{key} so router honors it - Fix cron session key: format as agent:main:cron:{id} for isolation - Add shared CopyBootstrapFiles helper in pkg/agent/bootstrap.go - Add config/workspace.config.example.json Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(agent): honor workspace config overrides in model routing selectCandidates uses agent.Model/Candidates baked in at startup, which ignores per-request workspace config overrides (effProvider/effModel). When the workspace overrides the provider, skip routing and fallback candidates entirely to avoid cross-provider credential issues. When only the model is overridden, allow routing but use the effective model. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: fix linter errors (gci, gofumpt, golines, govet, unused) - gci: alphabetize magicform import in gateway/helpers.go - gofumpt: reformat multi-line function signature in agent/helpers.go - golines: wrap lines exceeding 120 chars across 5 files - govet: rename shadowed variables (err → wcErr, s → trimmed) - unused: remove maybeSummarize, forceCompression, summarizeSession wrappers superseded by their *With variants Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: nuestraai <nuestraai@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: admin-mf <admin@magicform.ai>
335 lines
10 KiB
Go
335 lines
10 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/sipeed/picoclaw/pkg/bus"
|
|
"github.com/sipeed/picoclaw/pkg/config"
|
|
"github.com/sipeed/picoclaw/pkg/cron"
|
|
"github.com/sipeed/picoclaw/pkg/utils"
|
|
)
|
|
|
|
// JobExecutor is the interface for executing cron jobs through the agent
|
|
type JobExecutor interface {
|
|
ProcessDirectWithChannel(ctx context.Context, content, sessionKey, channel, chatID string) (string, error)
|
|
}
|
|
|
|
// CronTool provides scheduling capabilities for the agent
|
|
type CronTool struct {
|
|
cronService *cron.CronService
|
|
executor JobExecutor
|
|
msgBus *bus.MessageBus
|
|
execTool *ExecTool
|
|
}
|
|
|
|
// NewCronTool creates a new CronTool
|
|
// execTimeout: 0 means no timeout, >0 sets the timeout duration
|
|
func NewCronTool(
|
|
cronService *cron.CronService, executor JobExecutor, msgBus *bus.MessageBus, workspace string, restrict bool,
|
|
execTimeout time.Duration, config *config.Config,
|
|
) (*CronTool, error) {
|
|
execTool, err := NewExecToolWithConfig(workspace, restrict, config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to configure exec tool: %w", err)
|
|
}
|
|
|
|
execTool.SetTimeout(execTimeout)
|
|
return &CronTool{
|
|
cronService: cronService,
|
|
executor: executor,
|
|
msgBus: msgBus,
|
|
execTool: execTool,
|
|
}, nil
|
|
}
|
|
|
|
// Name returns the tool name
|
|
func (t *CronTool) Name() string {
|
|
return "cron"
|
|
}
|
|
|
|
// Description returns the tool description
|
|
func (t *CronTool) Description() string {
|
|
return "Schedule reminders, tasks, or system commands. IMPORTANT: When user asks to be reminded or scheduled, you MUST call this tool. Use 'at_seconds' for one-time reminders (e.g., 'remind me in 10 minutes' → at_seconds=600). Use 'every_seconds' ONLY for recurring tasks (e.g., 'every 2 hours' → every_seconds=7200). Use 'cron_expr' for complex recurring schedules. Use 'command' to execute shell commands directly."
|
|
}
|
|
|
|
// Parameters returns the tool parameters schema
|
|
func (t *CronTool) Parameters() map[string]any {
|
|
return map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"action": map[string]any{
|
|
"type": "string",
|
|
"enum": []string{"add", "list", "remove", "enable", "disable"},
|
|
"description": "Action to perform. Use 'add' when user wants to schedule a reminder or task.",
|
|
},
|
|
"message": map[string]any{
|
|
"type": "string",
|
|
"description": "The reminder/task message to display when triggered. If 'command' is used, this describes what the command does.",
|
|
},
|
|
"command": map[string]any{
|
|
"type": "string",
|
|
"description": "Optional: Shell command to execute directly (e.g., 'df -h'). If set, the agent will run this command and report output instead of just showing the message. 'deliver' will be forced to false for commands.",
|
|
},
|
|
"at_seconds": map[string]any{
|
|
"type": "integer",
|
|
"description": "One-time reminder: seconds from now when to trigger (e.g., 600 for 10 minutes later). Use this for one-time reminders like 'remind me in 10 minutes'.",
|
|
},
|
|
"every_seconds": map[string]any{
|
|
"type": "integer",
|
|
"description": "Recurring interval in seconds (e.g., 3600 for every hour). Use this ONLY for recurring tasks like 'every 2 hours' or 'daily reminder'.",
|
|
},
|
|
"cron_expr": map[string]any{
|
|
"type": "string",
|
|
"description": "Cron expression for complex recurring schedules (e.g., '0 9 * * *' for daily at 9am). Use this for complex recurring schedules.",
|
|
},
|
|
"job_id": map[string]any{
|
|
"type": "string",
|
|
"description": "Job ID (for remove/enable/disable)",
|
|
},
|
|
"deliver": map[string]any{
|
|
"type": "boolean",
|
|
"description": "If true, send message directly to channel. If false, let agent process message (for complex tasks). Default: true",
|
|
},
|
|
},
|
|
"required": []string{"action"},
|
|
}
|
|
}
|
|
|
|
// Execute runs the tool with the given arguments
|
|
func (t *CronTool) Execute(ctx context.Context, args map[string]any) *ToolResult {
|
|
action, ok := args["action"].(string)
|
|
if !ok {
|
|
return ErrorResult("action is required")
|
|
}
|
|
|
|
switch action {
|
|
case "add":
|
|
return t.addJob(ctx, args)
|
|
case "list":
|
|
return t.listJobs()
|
|
case "remove":
|
|
return t.removeJob(args)
|
|
case "enable":
|
|
return t.enableJob(args, true)
|
|
case "disable":
|
|
return t.enableJob(args, false)
|
|
default:
|
|
return ErrorResult(fmt.Sprintf("unknown action: %s", action))
|
|
}
|
|
}
|
|
|
|
func (t *CronTool) addJob(ctx context.Context, args map[string]any) *ToolResult {
|
|
channel := ToolChannel(ctx)
|
|
chatID := ToolChatID(ctx)
|
|
|
|
if channel == "" || chatID == "" {
|
|
return ErrorResult("no session context (channel/chat_id not set). Use this tool in an active conversation.")
|
|
}
|
|
|
|
message, ok := args["message"].(string)
|
|
if !ok || message == "" {
|
|
return ErrorResult("message is required for add")
|
|
}
|
|
|
|
var schedule cron.CronSchedule
|
|
|
|
// Check for at_seconds (one-time), every_seconds (recurring), or cron_expr
|
|
atSeconds, hasAt := args["at_seconds"].(float64)
|
|
everySeconds, hasEvery := args["every_seconds"].(float64)
|
|
cronExpr, hasCron := args["cron_expr"].(string)
|
|
|
|
// Fix: type assertions return true for zero values, need additional validity checks
|
|
// This prevents LLMs that fill unused optional parameters with defaults (0) from triggering wrong type
|
|
hasAt = hasAt && atSeconds > 0
|
|
hasEvery = hasEvery && everySeconds > 0
|
|
hasCron = hasCron && cronExpr != ""
|
|
|
|
// Priority: at_seconds > every_seconds > cron_expr
|
|
if hasAt {
|
|
atMS := time.Now().UnixMilli() + int64(atSeconds)*1000
|
|
schedule = cron.CronSchedule{
|
|
Kind: "at",
|
|
AtMS: &atMS,
|
|
}
|
|
} else if hasEvery {
|
|
everyMS := int64(everySeconds) * 1000
|
|
schedule = cron.CronSchedule{
|
|
Kind: "every",
|
|
EveryMS: &everyMS,
|
|
}
|
|
} else if hasCron {
|
|
schedule = cron.CronSchedule{
|
|
Kind: "cron",
|
|
Expr: cronExpr,
|
|
}
|
|
} else {
|
|
return ErrorResult("one of at_seconds, every_seconds, or cron_expr is required")
|
|
}
|
|
|
|
// Read deliver parameter, default to true
|
|
deliver := true
|
|
if d, ok := args["deliver"].(bool); ok {
|
|
deliver = d
|
|
}
|
|
|
|
command, _ := args["command"].(string)
|
|
if command != "" {
|
|
// Commands must be processed by agent/exec tool, so deliver must be false (or handled specifically)
|
|
// Actually, let's keep deliver=false to let the system know it's not a simple chat message
|
|
// But for our new logic in ExecuteJob, we can handle it regardless of deliver flag if Payload.Command is set.
|
|
// However, logically, it's not "delivered" to chat directly as is.
|
|
deliver = false
|
|
}
|
|
|
|
// Truncate message for job name (max 30 chars)
|
|
messagePreview := utils.Truncate(message, 30)
|
|
|
|
job, err := t.cronService.AddJob(
|
|
messagePreview,
|
|
schedule,
|
|
message,
|
|
deliver,
|
|
channel,
|
|
chatID,
|
|
)
|
|
if err != nil {
|
|
return ErrorResult(fmt.Sprintf("Error adding job: %v", err))
|
|
}
|
|
|
|
if command != "" {
|
|
job.Payload.Command = command
|
|
// Need to save the updated payload
|
|
t.cronService.UpdateJob(job)
|
|
}
|
|
|
|
return SilentResult(fmt.Sprintf("Cron job added: %s (id: %s)", job.Name, job.ID))
|
|
}
|
|
|
|
func (t *CronTool) listJobs() *ToolResult {
|
|
jobs := t.cronService.ListJobs(false)
|
|
|
|
if len(jobs) == 0 {
|
|
return SilentResult("No scheduled jobs")
|
|
}
|
|
|
|
var result strings.Builder
|
|
result.WriteString("Scheduled jobs:\n")
|
|
for _, j := range jobs {
|
|
var scheduleInfo string
|
|
if j.Schedule.Kind == "every" && j.Schedule.EveryMS != nil {
|
|
scheduleInfo = fmt.Sprintf("every %ds", *j.Schedule.EveryMS/1000)
|
|
} else if j.Schedule.Kind == "cron" {
|
|
scheduleInfo = j.Schedule.Expr
|
|
} else if j.Schedule.Kind == "at" {
|
|
scheduleInfo = "one-time"
|
|
} else {
|
|
scheduleInfo = "unknown"
|
|
}
|
|
result.WriteString(fmt.Sprintf("- %s (id: %s, %s)\n", j.Name, j.ID, scheduleInfo))
|
|
}
|
|
|
|
return SilentResult(result.String())
|
|
}
|
|
|
|
func (t *CronTool) removeJob(args map[string]any) *ToolResult {
|
|
jobID, ok := args["job_id"].(string)
|
|
if !ok || jobID == "" {
|
|
return ErrorResult("job_id is required for remove")
|
|
}
|
|
|
|
if t.cronService.RemoveJob(jobID) {
|
|
return SilentResult(fmt.Sprintf("Cron job removed: %s", jobID))
|
|
}
|
|
return ErrorResult(fmt.Sprintf("Job %s not found", jobID))
|
|
}
|
|
|
|
func (t *CronTool) enableJob(args map[string]any, enable bool) *ToolResult {
|
|
jobID, ok := args["job_id"].(string)
|
|
if !ok || jobID == "" {
|
|
return ErrorResult("job_id is required for enable/disable")
|
|
}
|
|
|
|
job := t.cronService.EnableJob(jobID, enable)
|
|
if job == nil {
|
|
return ErrorResult(fmt.Sprintf("Job %s not found", jobID))
|
|
}
|
|
|
|
status := "enabled"
|
|
if !enable {
|
|
status = "disabled"
|
|
}
|
|
return SilentResult(fmt.Sprintf("Cron job '%s' %s", job.Name, status))
|
|
}
|
|
|
|
// ExecuteJob executes a cron job through the agent
|
|
func (t *CronTool) ExecuteJob(ctx context.Context, job *cron.CronJob) string {
|
|
// Get channel/chatID from job payload
|
|
channel := job.Payload.Channel
|
|
chatID := job.Payload.To
|
|
|
|
// Default values if not set
|
|
if channel == "" {
|
|
channel = "cli"
|
|
}
|
|
if chatID == "" {
|
|
chatID = "direct"
|
|
}
|
|
|
|
// Execute command if present
|
|
if job.Payload.Command != "" {
|
|
args := map[string]any{
|
|
"command": job.Payload.Command,
|
|
}
|
|
|
|
result := t.execTool.Execute(ctx, args)
|
|
var output string
|
|
if result.IsError {
|
|
output = fmt.Sprintf("Error executing scheduled command: %s", result.ForLLM)
|
|
} else {
|
|
output = fmt.Sprintf("Scheduled command '%s' executed:\n%s", job.Payload.Command, result.ForLLM)
|
|
}
|
|
|
|
pubCtx, pubCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer pubCancel()
|
|
t.msgBus.PublishOutbound(pubCtx, bus.OutboundMessage{
|
|
Channel: channel,
|
|
ChatID: chatID,
|
|
Content: output,
|
|
})
|
|
return "ok"
|
|
}
|
|
|
|
// If deliver=true, send message directly without agent processing
|
|
if job.Payload.Deliver {
|
|
pubCtx, pubCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer pubCancel()
|
|
t.msgBus.PublishOutbound(pubCtx, bus.OutboundMessage{
|
|
Channel: channel,
|
|
ChatID: chatID,
|
|
Content: job.Payload.Message,
|
|
})
|
|
return "ok"
|
|
}
|
|
|
|
// For deliver=false, process through agent (for complex tasks)
|
|
sessionKey := fmt.Sprintf("agent:main:cron:%s", job.ID)
|
|
|
|
// Call agent with job's message
|
|
response, err := t.executor.ProcessDirectWithChannel(
|
|
ctx,
|
|
job.Payload.Message,
|
|
sessionKey,
|
|
channel,
|
|
chatID,
|
|
)
|
|
if err != nil {
|
|
return fmt.Sprintf("Error: %v", err)
|
|
}
|
|
|
|
// Response is automatically sent via MessageBus by AgentLoop
|
|
_ = response // Will be sent by AgentLoop
|
|
return "ok"
|
|
}
|