Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 120 additions & 2 deletions cmd/picoclaw/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import (
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"os/user"
"path/filepath"
"runtime"
"strings"
Expand Down Expand Up @@ -179,7 +181,7 @@ func printHelp() {
fmt.Println(" onboard Initialize picoclaw configuration and workspace")
fmt.Println(" agent Interact with the agent directly")
fmt.Println(" auth Manage authentication (login, logout, status)")
fmt.Println(" gateway Start picoclaw gateway")
fmt.Println(" gateway Start gateway or install gateway service")
fmt.Println(" status Show picoclaw status")
fmt.Println(" cron Manage scheduled tasks")
fmt.Println(" migrate Migrate from OpenClaw to PicoClaw")
Expand Down Expand Up @@ -606,8 +608,19 @@ func simpleInteractiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
}

func gatewayCmd() {
// Check for --debug flag
args := os.Args[2:]
if len(args) > 0 {
switch args[0] {
case "install":
gatewayInstallCmd()
return
case "--help", "-h", "help":
gatewayHelp()
return
}
}

// Check for --debug flag
for _, arg := range args {
if arg == "--debug" || arg == "-d" {
logger.SetLevel(logger.DEBUG)
Expand Down Expand Up @@ -734,6 +747,109 @@ func gatewayCmd() {
fmt.Println("✓ Gateway stopped")
}

func gatewayHelp() {
fmt.Println("\nGateway commands:")
fmt.Println(" picoclaw gateway Start gateway")
fmt.Println(" picoclaw gateway install Install and start systemd service")
fmt.Println(" picoclaw gateway --debug Start gateway with debug logging")
fmt.Println()
}

func gatewayInstallCmd() {
if runtime.GOOS != "linux" {
fmt.Println("Error: gateway install is only supported on Linux with systemd")
os.Exit(1)
}

if os.Geteuid() != 0 {
fmt.Println("Error: gateway install requires root privileges")
fmt.Println("Run: sudo picoclaw gateway install")
os.Exit(1)
}

if _, err := exec.LookPath("systemctl"); err != nil {
fmt.Println("Error: systemctl not found")
os.Exit(1)
}

serviceUser, serviceHome, err := resolveGatewayServiceUser()
if err != nil {
fmt.Printf("Error resolving service user: %v\n", err)
os.Exit(1)
}

execPath, err := os.Executable()
if err != nil {
fmt.Printf("Error resolving executable path: %v\n", err)
os.Exit(1)
}
if resolved, err := filepath.EvalSymlinks(execPath); err == nil {
execPath = resolved
}

unitContent := buildGatewayServiceUnit(serviceUser, serviceHome, execPath)
servicePath := "/etc/systemd/system/picoclaw.service"
if err := os.WriteFile(servicePath, []byte(unitContent), 0644); err != nil {
fmt.Printf("Error writing service file: %v\n", err)
os.Exit(1)
}

if out, err := exec.Command("systemctl", "daemon-reload").CombinedOutput(); err != nil {
fmt.Printf("Error running systemctl daemon-reload: %v\n%s\n", err, strings.TrimSpace(string(out)))
os.Exit(1)
}
if out, err := exec.Command("systemctl", "enable", "--now", "picoclaw").CombinedOutput(); err != nil {
fmt.Printf("Error enabling/starting service: %v\n%s\n", err, strings.TrimSpace(string(out)))
os.Exit(1)
}

fmt.Println("✓ Installed systemd service: /etc/systemd/system/picoclaw.service")
fmt.Println("✓ Enabled and started: picoclaw")
fmt.Println("Check status: systemctl status picoclaw --no-pager")
fmt.Println("View logs: journalctl -u picoclaw -f")
}

func resolveGatewayServiceUser() (string, string, error) {
if sudoUser := strings.TrimSpace(os.Getenv("SUDO_USER")); sudoUser != "" {
u, err := user.Lookup(sudoUser)
if err != nil {
return "", "", err
}
return u.Username, u.HomeDir, nil
}

u, err := user.Current()
if err != nil {
return "", "", err
}
return u.Username, u.HomeDir, nil
}

func buildGatewayServiceUnit(serviceUser, serviceHome, execPath string) string {
return fmt.Sprintf(`[Unit]
Description=PicoClaw Gateway
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=%s
WorkingDirectory=%s
ExecStart=%s gateway
Restart=always
RestartSec=5
Environment=HOME=%s
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=false
ReadWritePaths=%s/.picoclaw

[Install]
WantedBy=multi-user.target
`, serviceUser, serviceHome, execPath, serviceHome, serviceHome)
}

func statusCmd() {
cfg, err := loadConfig()
if err != nil {
Expand Down Expand Up @@ -766,6 +882,7 @@ func statusCmd() {
hasOpenAI := cfg.Providers.OpenAI.APIKey != ""
hasGemini := cfg.Providers.Gemini.APIKey != ""
hasZhipu := cfg.Providers.Zhipu.APIKey != ""
hasZAI := cfg.Providers.ZAI.APIKey != ""
hasGroq := cfg.Providers.Groq.APIKey != ""
hasVLLM := cfg.Providers.VLLM.APIBase != ""

Expand All @@ -780,6 +897,7 @@ func statusCmd() {
fmt.Println("OpenAI API:", status(hasOpenAI))
fmt.Println("Gemini API:", status(hasGemini))
fmt.Println("Zhipu API:", status(hasZhipu))
fmt.Println("Z.AI API:", status(hasZAI))
fmt.Println("Groq API:", status(hasGroq))
if hasVLLM {
fmt.Printf("vLLM/Local: ✓ %s\n", cfg.Providers.VLLM.APIBase)
Expand Down
8 changes: 8 additions & 0 deletions config/config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@
"api_key": "YOUR_ZHIPU_API_KEY",
"api_base": ""
},
"zai": {
"api_key": "YOUR_ZAI_API_KEY",
"api_base": "https://api.z.ai/api/paas/v4"
},
"gemini": {
"api_key": "",
"api_base": ""
Expand All @@ -90,6 +94,10 @@
"moonshot": {
"api_key": "sk-xxx",
"api_base": ""
},
"zen": {
"api_key": "YOUR_OPENCODE_API_KEY",
"api_base": "https://opencode.ai/zen/v1"
}
},
"tools": {
Expand Down
86 changes: 30 additions & 56 deletions pkg/channels/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ type TelegramChannel struct {
config config.TelegramConfig
chatIDs map[string]int64
transcriber *voice.GroqTranscriber
placeholders sync.Map // chatID -> messageID
stopThinking sync.Map // chatID -> thinkingCancel
}

Expand Down Expand Up @@ -69,7 +68,6 @@ func NewTelegramChannel(cfg config.TelegramConfig, bus *bus.MessageBus) (*Telegr
config: cfg,
chatIDs: make(map[string]int64),
transcriber: nil,
placeholders: sync.Map{},
stopThinking: sync.Map{},
}, nil
}
Expand Down Expand Up @@ -139,18 +137,6 @@ func (c *TelegramChannel) Send(ctx context.Context, msg bus.OutboundMessage) err

htmlContent := markdownToTelegramHTML(msg.Content)

// Try to edit placeholder
if pID, ok := c.placeholders.Load(msg.ChatID); ok {
c.placeholders.Delete(msg.ChatID)
editMsg := tu.EditMessageText(tu.ID(chatID), pID.(int), htmlContent)
editMsg.ParseMode = telego.ModeHTML

if _, err = c.bot.EditMessageText(ctx, editMsg); err == nil {
return nil
}
// Fallback to new message if edit fails
}

tgMsg := tu.Message(tu.ID(chatID), htmlContent)
tgMsg.ParseMode = telego.ModeHTML

Expand Down Expand Up @@ -302,54 +288,34 @@ func (c *TelegramChannel) handleMessage(ctx context.Context, update telego.Updat
"preview": utils.Truncate(content, 50),
})

// Thinking indicator
err := c.bot.SendChatAction(ctx, tu.ChatAction(tu.ID(chatID), telego.ChatActionTyping))
if err != nil {
logger.ErrorCF("telegram", "Failed to send chat action", map[string]interface{}{
"error": err.Error(),
})
}

// Stop any previous thinking animation
// Stop any previous typing indicator
chatIDStr := fmt.Sprintf("%d", chatID)
if prevStop, ok := c.stopThinking.Load(chatIDStr); ok {
if cf, ok := prevStop.(*thinkingCancel); ok && cf != nil {
cf.Cancel()
}
}

// Create new context for thinking animation with timeout
// Keep typing status active while processing the request.
thinkCtx, thinkCancel := context.WithTimeout(ctx, 5*time.Minute)
c.stopThinking.Store(chatIDStr, &thinkingCancel{fn: thinkCancel})

pMsg, err := c.bot.SendMessage(ctx, tu.Message(tu.ID(chatID), "Thinking... 💭"))
if err == nil {
pID := pMsg.MessageID
c.placeholders.Store(chatIDStr, pID)

go func(cid int64, mid int) {
dots := []string{".", "..", "..."}
emotes := []string{"💭", "🤔", "☁️"}
i := 0
ticker := time.NewTicker(2000 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-thinkCtx.Done():
return
case <-ticker.C:
i++
text := fmt.Sprintf("Thinking%s %s", dots[i%len(dots)], emotes[i%len(emotes)])
_, editErr := c.bot.EditMessageText(thinkCtx, tu.EditMessageText(tu.ID(chatID), mid, text))
if editErr != nil {
logger.DebugCF("telegram", "Failed to edit thinking message", map[string]interface{}{
"error": editErr.Error(),
})
}
}
go func(cid int64) {
ticker := time.NewTicker(4 * time.Second)
defer ticker.Stop()
for {
if err := c.bot.SendChatAction(thinkCtx, tu.ChatAction(tu.ID(cid), telego.ChatActionTyping)); err != nil {
logger.DebugCF("telegram", "Failed to send chat action", map[string]interface{}{
"error": err.Error(),
})
}
}(chatID, pID)
}
select {
case <-thinkCtx.Done():
return
case <-ticker.C:
}
}
}(chatID)

metadata := map[string]string{
"message_id": fmt.Sprintf("%d", message.MessageID),
Expand Down Expand Up @@ -418,9 +384,9 @@ func markdownToTelegramHTML(text string) string {
inlineCodes := extractInlineCodes(text)
text = inlineCodes.text

text = regexp.MustCompile(`^#{1,6}\s+(.+)$`).ReplaceAllString(text, "$1")
text = regexp.MustCompile(`(?m)^#{1,6}\s+(.+)$`).ReplaceAllString(text, "$1")

text = regexp.MustCompile(`^>\s*(.*)$`).ReplaceAllString(text, "$1")
text = regexp.MustCompile(`(?m)^>\s*(.*)$`).ReplaceAllString(text, "$1")

text = escapeHTML(text)

Expand All @@ -441,7 +407,9 @@ func markdownToTelegramHTML(text string) string {

text = regexp.MustCompile(`~~(.+?)~~`).ReplaceAllString(text, "<s>$1</s>")

text = regexp.MustCompile(`^[-*]\s+`).ReplaceAllString(text, "• ")
text = regexp.MustCompile(`(?m)^[-*]\s+`).ReplaceAllString(text, "• ")

text = regexp.MustCompile(`(?m)^\d+\.\s+`).ReplaceAllString(text, "• ")

for i, code := range inlineCodes.codes {
escaped := escapeHTML(code)
Expand Down Expand Up @@ -470,8 +438,11 @@ func extractCodeBlocks(text string) codeBlockMatch {
codes = append(codes, match[1])
}

idx := 0
text = re.ReplaceAllStringFunc(text, func(m string) string {
return fmt.Sprintf("\x00CB%d\x00", len(codes)-1)
placeholder := fmt.Sprintf("\x00CB%d\x00", idx)
idx++
return placeholder
})

return codeBlockMatch{text: text, codes: codes}
Expand All @@ -491,8 +462,11 @@ func extractInlineCodes(text string) inlineCodeMatch {
codes = append(codes, match[1])
}

idx := 0
text = re.ReplaceAllStringFunc(text, func(m string) string {
return fmt.Sprintf("\x00IC%d\x00", len(codes)-1)
placeholder := fmt.Sprintf("\x00IC%d\x00", idx)
idx++
return placeholder
})

return inlineCodeMatch{text: text, codes: codes}
Expand Down
45 changes: 45 additions & 0 deletions pkg/channels/telegram_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package channels

import (
"strings"
"testing"
)

func TestMarkdownToTelegramHTML_MultilineFormatting(t *testing.T) {
input := "## Titulo\n- item um\n- item dois\n1. item tres\n> citação"
got := markdownToTelegramHTML(input)

if strings.Contains(got, "##") {
t.Fatalf("heading marker should be removed, got: %q", got)
}
if !strings.Contains(got, "• item um") || !strings.Contains(got, "• item dois") || !strings.Contains(got, "• item tres") {
t.Fatalf("list markers should be normalized, got: %q", got)
}
if strings.Contains(got, "> citação") {
t.Fatalf("blockquote marker should be removed, got: %q", got)
}
}

func TestMarkdownToTelegramHTML_MultipleCodeBlocks(t *testing.T) {
input := "```go\nfmt.Println(1)\n```\ntexto\n```js\nconsole.log(2)\n```"
got := markdownToTelegramHTML(input)

if strings.Count(got, "<pre><code>") != 2 {
t.Fatalf("expected 2 code blocks, got: %q", got)
}
if !strings.Contains(got, "fmt.Println(1)") || !strings.Contains(got, "console.log(2)") {
t.Fatalf("missing code block contents, got: %q", got)
}
}

func TestMarkdownToTelegramHTML_MultipleInlineCodes(t *testing.T) {
input := "use `foo` and `bar`"
got := markdownToTelegramHTML(input)

if strings.Count(got, "<code>") != 2 {
t.Fatalf("expected 2 inline code tags, got: %q", got)
}
if !strings.Contains(got, "<code>foo</code>") || !strings.Contains(got, "<code>bar</code>") {
t.Fatalf("missing inline code contents, got: %q", got)
}
}
Loading