Commit Graph

25 Commits

Author SHA1 Message Date
viettranx 1e2ca2df7c fix(agent): improve team lead delegation messaging + group chat reply hint
- Team lead: no completion language after delegating, no question phrasing
- Group chat: inject reply context hint (NO_REPLY when reply addresses others)
- Both v1 and v2 team lead sections updated
2026-03-19 13:35:57 +07:00
viettranx 08a2d95c0c feat: agent heartbeat system — periodic proactive check-ins (#245)
Phase 1 (Core):
- Migration 000022: agent_heartbeats, heartbeat_run_logs, agent_config_permissions tables
- HeartbeatStore + ConfigPermissionStore interfaces with PG implementations
- HeartbeatTicker: background poll → active hours filter → queue-aware skip → run → smart suppression → deliver/log
- Heartbeat tool: status/get/set/toggle/set_checklist/get_checklist/test/logs actions
- Permission check with wildcard scope matching + TTL cache (60s)
- RPC methods: heartbeat.get/set/toggle/test/logs/checklist.get/checklist.set
- HEARTBEAT.md routed via context file interceptor (read/write for both open + predefined agents)
- Session keys: agent:{id}:heartbeat or agent:{id}💓{ts} (isolated)
- PromptMinimal for heartbeat sessions (like cron/subagent)
- Event broadcasting + cache invalidation via bus (heartbeat + config_perms)
- Gateway wiring: ticker init, event wiring, graceful shutdown

Phase 2 (Integration):
- wakeMode: CronPayload.WakeHeartbeat triggers heartbeat after cron job completes
- Queue-aware: Scheduler.HasActiveSessionsForAgent() skips busy agents
- Stagger: deterministic FNV offset spreads heartbeats across interval
- lightContext: RunRequest.LightContext skips context files, only injects checklist
- System prompt distinguishes cron (user-scheduled tasks) vs heartbeat (autonomous monitoring)
2026-03-18 13:11:44 +07:00
viettranx ca44b7279f feat(bootstrap): predefined agents keep full system prompt during onboarding
Predefined agents now retain all tools and system prompt sections when
BOOTSTRAP.md is present, instead of entering slim mode with only write_file.
Open agents keep the existing slim bootstrap mode.

- Gate tool filtering and IsBootstrap on agentType != "predefined"
- Add FIRST RUN reminder for predefined agents (without tool restriction)
- Skip bootstrap/user seeding for team-dispatched sessions (IsTeamSession)
- Group chats skip BOOTSTRAP.md entirely
- Track bootstrapWriteDetected + inject nudge after 2 turns without write_file
- Update templates: never reveal process, no capability listing, no "locked"
- Cache LoadContextFiles via existing agentCache/userCache (TTL 5min)
2026-03-17 09:25:23 +07:00
viettranx b6df6c9286 refactor(agent): consolidate system prompt sections into AGENTS.md template
Merge §5 (Memory Recall), §9 (Messaging), §12 (Silent Replies) from
hardcoded system prompt into AGENTS.md — single source of truth.
Add recency reinforcement at §16 to compensate for mid-prompt position.
Clean up SOUL.md and IDENTITY.md template duplication.

Saves ~175 tokens/turn across all LLM calls.
2026-03-14 10:30:35 +07:00
Luan Vu a4f2d02a80 fix(channels): annotate DM messages with sender identity (#120)
* fix(channels): annotate DM messages with sender identity

Telegram and Zalo group messages already include [From: sender] prefix
so the agent knows who is talking, but DM messages were sent without
any sender context — the agent had no way to address the user by name.

- Telegram DM: add [From: @username] (or FirstName if no username)
- Zalo DM: add [From: displayName] when dName is present in payload

* fix(tests): add missing EnsureUserProfile to test stubs

AgentStore interface gained EnsureUserProfile in 4fce731 but the test
stub implementations were not updated, breaking CI on main.

---------

Co-authored-by: Luvu182 <208665161+Luvu182@users.noreply.github.com>
2026-03-10 19:25:55 +07:00
viettranx bdb60de7ae chore: upgrade Go 1.25 → 1.26 and apply go fix modernizations
- Update go.mod and Dockerfile to Go 1.26
- Apply `go fix ./...` stdlib modernizations across 170+ files
- Add `go fix` to post-implementation checklist in CLAUDE.md
- Fix go fix misapplied rewrite in loop_history.go
2026-03-10 00:09:15 +07:00
viettranx a1db0fb666 fix: silent bootstrap file ops + rename channel instance Name to Key
- Add "do silently" instruction to BOOTSTRAP.md templates so agents
  don't narrate internal file processing steps to users
- Rename channel instance form label from "Name" to "Key" for clarity
2026-03-09 19:30:56 +07:00
viettranx 47cc11bfc0 feat(metadata): add JSONB metadata to sessions, profiles, and pairing
Persist friendly names (display_name, username, chat_title) from channel
handlers into sessions, user profiles, and pairing records. Web UI renders
metadata with graceful fallback to raw IDs.

- Add migration 000011: metadata JSONB columns on sessions,
  user_agent_profiles, pairing_requests, paired_devices
- Extend SessionStore/AgentStore/PairingStore interfaces with metadata ops
- Extract and persist channel metadata in gateway consumer
- Extend sessions.patch and add PATCH instances metadata HTTP endpoint
- Update frontend sessions page, detail page, and instances tab
- Delete legacy file-based internal/pairing/service.go
- Update docs references to reflect DB-backed pairing
2026-03-08 15:42:44 +07:00
viettranx ea185b3f6c feat(agents): add self-evolution config and instances management for predefined agents
Self-Evolution: predefined agents can now optionally evolve their SOUL.md
(communication style/tone only) when self_evolve is enabled in other_config.
Identity, name, and operating instructions remain locked. Context propagation
flows through LoopConfig → Loop → context.WithValue → interceptor carve-out.
System prompt guides the agent on what it can/cannot evolve.

Instances Tab: new HTTP endpoints and UI tab for viewing/editing per-user
USER.md files on predefined agents. Includes owner-only access checks,
fileName validation (USER.md only), and cache invalidation.

UI: self-evolve toggle in General tab, create dialog, and setup wizard.
Agent type and evolve/static badges with tooltip explanations on cards
and detail header. TooltipProvider added to agents list and detail pages.
2026-03-08 14:27:40 +07:00
Songlin Yang fadc9377f9 fix(ut): remove legacy function TestSeedUserFiles_PredefinedAgent_BootstrapUsesCorrectTemplate (#67) 2026-03-07 01:11:52 +07:00
Luan Vu 95885da14e feat(zalo): add file and image upload/send support (#62)
## Summary
- Implement UploadImage, SendImage, UploadFile, SendFile in Zalo Personal protocol
- Handle WebSocket control events (cmd=601) for async file upload callbacks
- Add media attachment routing in channel.Send() — auto-detects image vs file
- Add MEDIA: prefix support in message tool for agent file attachments
- Add group_id metadata routing for correct Zalo group API selection

## Review fixes (dc475bc)
- Fix CI: %s for json.Number (was %d)
- Fix path traversal: parseMediaPath restricted to os.TempDir()
- Add 25MB file size limit before upload reads
- Drain stale uploadCallbacks on Listener.reset()
- Split send.go (688 LOC) into send.go, send_image.go, send_file.go, send_helpers.go
- Add 12 unit tests for parseMediaPath
2026-03-06 23:20:50 +07:00
Viet Tran 6895e369f6 refactor: remove standalone mode, consolidate to managed-only (PostgreSQL) (#70)
- Remove standalone mode code: file-based stores, standalone gateway,
  heartbeat service, SQLite memory, standalone docker-compose
- Rename docker-compose.managed.yml → docker-compose.postgres.yml
- Clean up ~130 Go comments referencing "managed mode" qualifier
- Simplify docker-compose.yml env vars (providers/channels via web UI)
- Update .env.example to essential vars only (token + encryption key)
- Add setup wizard UI (provider → agent → channel bootstrap flow)
- Add logs.tail WebSocket handler for live log streaming
- Add cursor-pointer to interactive UI components
- Clean up config page (remove standalone-only sections)
- Update README and docs for managed-only architecture
2026-03-06 18:51:11 +07:00
viettranx d49596a805 feat: Add USER_PREDEFINED.md for predefined agents with token count sidebar
Add shared agent-level USER_PREDEFINED.md file for predefined agents to define
baseline user-handling rules (owner info, audience, language, communication norms)
that apply to ALL users. Individual USER.md per-user supplements but never overrides.

- Seed USER_PREDEFINED.md template in SeedToStore for new predefined agents
- Backfill existing agents via ensureUserPredefined in summon/regenerate flows
- AI optionally generates/updates the file when description mentions people/user context
- Add to context file interceptor, RPC allowlist, and system prompt injection
- Update summoning modal with optional file progress tracking
- Show estimated token count (Unicode-aware) instead of bytes in file sidebar

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 12:27:43 +07:00
viettranx 5a4d40f458 enhance: rewrite AGENTS.md for managed mode, add Style section to SOUL.md
Remove ~60% redundant content from AGENTS.md (safety, bootstrap, tools, workspace
sections already covered by system prompt). Add Conversational Style rules to reduce
bot-like behavior. Add customizable Style section to SOUL.md template with summoner
metaprompt support. Migration 000010 force-updates all existing AGENTS.md in DB.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 18:33:23 +07:00
viettranx 4da116292a feat(teams): add CancelTask with dependency unblocking and delegation cancellation
- Add CancelTask store method: guards against completed tasks, unblocks dependents, transitions blocked→pending
- Cancel running delegation when team task is cancelled via CancelByTeamTaskID
- Prevent delegate agents from completing/cancelling tasks directly
- Wire DelegateManager into TeamToolManager for task-delegation lifecycle
- Remove BOOTSTRAP.md from predefined agent seed (predefined agents already have full context)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 23:11:10 +07:00
viettranx 4387f6b1ba fix: improve spawn tool team_task_id validation and orphan detection
When LLMs call team_tasks create + spawn in parallel, the spawn
tool receives a hallucinated task_id that fails uuid.Parse, causing
a misleading error and bypassing orphan detection.

- Include pending task IDs in spawn error message so LLM can retry
  with the correct UUID
- Move spawn counting to post-execution so failed spawns don't
  increment teamTaskSpawns, allowing orphan detection to fire

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 11:36:46 +07:00
viettranx 6ed62b8506 feat: channel-isolated workspace, resolvePath fix, create_image workspace, summoner Expertise section, bus Topic constants
- Fix resolvePath for nested non-existent dirs (use resolveThroughExistingAncestors)
- Channel-isolated workspace: user_agent_profiles.workspace stores channel prefix,
  used as source of truth with backward compat for existing users
- Loop caches workspace per-user with CacheKindUserWorkspace invalidation via pubsub
- ContractHome/ExpandHome for portable ~-based paths in DB
- create_image saves to workspace/generated/YYYY-MM-DD/ instead of OS temp dir
- SOUL.md template: add ## Expertise section for domain knowledge
- Summoner buildEditPrompt: section guide, complete file output, frontmatter update
- Bus: Topic* constants for Subscribe/Broadcast keys, CacheKind* for payload kinds
- Teams, delegates, sessions, agent links: various enhancements

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 10:52:32 +07:00
viettranx 82ce20a029 refactor: add AgentStore.GetDefault() to replace full List scan in heartbeat setup
Replaces List(ctx, "") + loop with a single-row query
(ORDER BY is_default DESC, created_at ASC LIMIT 1).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 21:34:09 +07:00
therichardngai-code 3cbdd8d778 fix(agents): predefined agents visible in web UI for channel members (#34)
* fix: SeedUserFiles uses agent-level USER.md as seed for predefined agents

For predefined agents, the wizard writes a populated USER.md (owner
name, language, notes) via agents.files.set into agent_context_files
(agent-level). On the first chat message, SeedUserFiles was seeding a
blank embedded template into user_context_files (per-user level).

LoadContextFiles for predefined agents lets per-user content override
agent-level content, so the blank per-user USER.md shadowed the
wizard-written content. The owner profile was stored in the DB but
never served to the agent, triggering unnecessary onboarding.

Fix: before falling back to the embedded template, check whether
agent_context_files already has a non-empty USER.md for the agent.
If it does, use that content as the per-user seed. The check is
conditional (predefined agent + USER.md not yet seeded per-user) so
it adds at most one extra DB read per new user.

The existing "don't overwrite" guard (hasFile check) is unchanged —
personalized per-user content written through conversation is still
never overwritten.

* test: add unit tests for SeedUserFiles agent-level USER.md seeding

Covers:
- Predefined agent: wizard-written USER.md at agent level is used as
  per-user seed (primary regression test for the bug fix)
- Predefined agent: falls back to blank embedded template when no
  agent-level USER.md exists
- Predefined agent: existing per-user content is never overwritten
- Open agent: embedded template path is unaffected
- Predefined agent: BOOTSTRAP.md uses BOOTSTRAP_PREDEFINED.md template
- Idempotency: second SeedUserFiles call seeds nothing

* fix(bootstrap): SeedUserFiles uses agent-level USER.md as seed for predefined agents

Use map[string]string for agent-level files (more general, extensible)
and clean continue-based loop flow, matching the investigation spec
in plans/goclaw-pr/goclaw-pr-seed-user-files.md exactly.

Previous implementation used a single string and if/else structure —
functionally correct but diverged from the spec in variable type,
load condition, and loop exit pattern.

* fix(agents): predefined agents visible in web UI for channel members

Two bugs combined to make wizard-installed predefined agents invisible
in the web UI for all real users.

Bug 1 — agents.create WS hardcoded owner_id = "system":
- Add `owner_ids []string` to WS params struct (omitempty, backward compat)
- Resolve ownerID: use first entry if provided, fall back to "system"
- Allows external provisioning tools to set a real user as owner

Bug 2 — ListAccessible SQL excluded system-owned predefined agents:
- Extend WHERE clause with 4th OR: predefined agents are visible when
  the requesting user appears in any enabled channel's allow_from list
- Uses EXISTS + jsonb_array_elements_text(ci.config->'allow_from')
- No schema migration needed — allow_from already populated by wizard

Also adds 4 unit tests for Bug 1 (agents_create_owner_test.go):
- UsesProvidedOwnerID, FallsBackToSystem_WhenAbsent,
  FallsBackToSystem_WhenEmpty, MultipleOwnerIDs_UsesFirst
2026-03-01 21:17:32 +07:00
viettranx 0e75c21e55 feat: overhaul team delegation, Telegram resilience, and artifact forwarding
Team delegation:
- Unify spawn/subagent/delegate into single spawn tool
- Sibling-aware announce suppression with artifact accumulation
- Fix auto-complete race (isLastDelegation guard)
- Add team tasks list limit (20) with search guidance
- Multi-round orchestration patterns in TEAM.md
- Communication guidance for initial vs follow-up delegations

Telegram resilience:
- Add retrySend wrapper (3 attempts, escalating delay) for network errors
- Fix HTML fallback: strip tags + unescape entities instead of showing raw HTML
- Pre-process HTML tags in LLM output to markdown before conversion pipeline
- Skip caption truncation entirely when > 1024 bytes, send text separately
- Auto-send large images (>5MB) as documents to avoid compression

Artifact forwarding:
- Fix missing ContentType on forwarded media (mimeFromExt for result.Media/ForwardMedia)
- Add deliver parameter to write_file for file attachment delivery
- Extend mimeFromExt with document MIME types

UI: fix regenerate dialog overflow, improve task list layout, delegation detail view

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:34:36 +07:00
viettranx f3d2baa0bc feat: Implement agent resummoning, add Discord require_mention setting, and streamline agent file templates by removing TOOLS.md and HEARTBEAT.md. 2026-02-27 18:22:07 +07:00
viettranx dfd91556f8 feat: Introduce agent teams, agent linking, and advanced agent orchestration features. 2026-02-25 23:24:52 +07:00
viettranx 16022d77be feat: Implement agent resummoning with UI retry, add provider verification, and introduce created_at timestamps to various tables. 2026-02-24 15:18:25 +07:00
viettranx 08ced252b2 feat: Introduce agent summoning flow with a dedicated modal and updated bootstrap process for predefined agents. 2026-02-24 10:19:49 +07:00
Viet Tran f3f4c67b36 Initial commit: GoClaw AI agent gateway
Multi-agent AI gateway with WebSocket RPC, HTTP API, and messaging channel integrations.
Go port of OpenClaw with multi-tenant PostgreSQL, per-user isolation, security hardening,
and production observability.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 14:58:07 +07:00