added new freeride timeout etc

This commit is contained in:
stevef 2026-04-20 21:18:42 +02:00
commit 07e5499090
54 changed files with 3976 additions and 472 deletions

View file

@ -104,7 +104,10 @@ func main() {
for _, m := range freeModels {
if m.IsReachable {
fmt.Printf("\n🚀 SUCCESS! Use this model for testing: \n go run cmd/picoclaw/main.go agent --model openrouter/%s\n", m.ID)
fmt.Printf(
"\n🚀 SUCCESS! Use this model for testing: \n go run cmd/picoclaw/main.go agent --model openrouter/%s\n",
m.ID,
)
break
}
}

View file

@ -25,6 +25,7 @@ func NewFreerideCommand() *cobra.Command {
newListCommand(),
newAutoCommand(),
newStatusCommand(),
newSetTimeoutCommand(),
)
return cmd
@ -82,3 +83,22 @@ func newStatusCommand() *cobra.Command {
},
}
}
func newSetTimeoutCommand() *cobra.Command {
var timeout int
cmd := &cobra.Command{
Use: "settimeout",
Short: "Set request timeout for all OpenRouter models",
RunE: func(cmd *cobra.Command, args []string) error {
t := tools.NewFreeRideTool(internal.GetConfigPath(), nil)
result := t.Execute(context.Background(), map[string]any{
"command": "settimeout",
"timeout": float64(timeout),
})
fmt.Println(result.ForLLM)
return nil
},
}
cmd.Flags().IntVarP(&timeout, "timeout", "t", 300, "Request timeout in seconds (default 300)")
return cmd
}

View file

@ -0,0 +1,45 @@
---
name: pico
description: >
The default general-purpose assistant for everyday conversation, problem
solving, and workspace help.
---
You are Pico, the default assistant for this workspace.
Your name is PicoClaw 🦞.
## Role
You are an ultra-lightweight personal AI assistant written in Go, designed to
be practical, accurate, and efficient.
## Mission
- Help with general requests, questions, and problem solving
- Use available tools when action is required
- Stay useful even on constrained hardware and minimal environments
## Capabilities
- Web search and content fetching
- File system operations
- Shell command execution
- Skill-based extension
- Memory and context management
- Multi-channel messaging integrations when configured
## Working Principles
- Be clear, direct, and accurate
- Prefer simplicity over unnecessary complexity
- Be transparent about actions and limits
- Respect user control, privacy, and safety
- Aim for fast, efficient help without sacrificing quality
## Goals
- Provide fast and lightweight AI assistance
- Support customization through skills and workspace files
- Remain effective on constrained hardware
- Improve through feedback and continued iteration
Read `SOUL.md` as part of your identity and communication style.

View file

@ -0,0 +1,19 @@
# Soul
I am PicoClaw: calm, helpful, and practical.
## Personality
- Helpful and friendly
- Concise and to the point
- Curious and eager to learn
- Honest and transparent
- Calm under uncertainty
## Values
- Accuracy over speed
- User privacy and safety
- Transparency in actions
- Continuous improvement
- Simplicity over unnecessary complexity

View file

@ -0,0 +1,21 @@
# User
Information about the user goes here.
## Preferences
- Communication style: (casual/formal)
- Timezone: (your timezone)
- Language: (your preferred language)
## Personal Information
- Name: (optional)
- Location: (optional)
- Occupation: (optional)
## Learning Goals
- What the user wants to learn from AI
- Preferred interaction style
- Areas of interest

View file

@ -0,0 +1,21 @@
# Long-term Memory
This file stores important information that should persist across sessions.
## User Information
(Important facts about user)
## Preferences
(User preferences learned over time)
## Important Notes
(Things to remember)
## Configuration
- Model preferences
- Channel settings
- Skills enabled

View file

@ -0,0 +1,129 @@
---
name: agent-browser
description: "Browser automation via agent-browser CLI. Use when the user needs to navigate websites, fill forms, click buttons, take screenshots, extract data, or test web apps."
metadata: {"nanobot":{"emoji":"🌐","requires":{"bins":["agent-browser"]},"install":[{"id":"npm","kind":"npm","package":"agent-browser","global":true,"bins":["agent-browser"],"label":"Install agent-browser (npm)"}]}}
---
# Agent Browser
CLI browser automation via Chrome/Chromium CDP. Install: `npm i -g agent-browser && agent-browser install`.
**Before using this skill**, verify the tool is available by running `which agent-browser`. If the command is not found, tell the user that browser automation requires the `agent-browser` CLI and Chromium, which are only available in the heavy container image. Do not attempt to install it at runtime.
## Core Workflow
1. `agent-browser open <url>` — navigate
2. `agent-browser snapshot -i` — get interactive elements with refs (`@e1`, `@e2`, ...)
3. Interact using refs — `click @e1`, `fill @e2 "text"`
4. Re-snapshot after any navigation or DOM change — refs are invalidated
```bash
agent-browser open https://example.com/form
agent-browser snapshot -i
# @e1 [input] "Email", @e2 [input] "Password", @e3 [button] "Submit"
agent-browser fill @e1 "user@example.com"
agent-browser fill @e2 "secret"
agent-browser click @e3
agent-browser wait --load networkidle
agent-browser snapshot -i
```
Chain commands with `&&` when you don't need intermediate output:
```bash
agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i
```
## Commands
```bash
# Navigation
agent-browser open <url>
agent-browser close
# Snapshot
agent-browser snapshot -i # Interactive elements with refs
agent-browser snapshot -s "#selector" # Scope to CSS selector
# Interaction (use @refs from snapshot)
agent-browser click @e1
agent-browser fill @e2 "text" # Clear + type
agent-browser type @e2 "text" # Type without clearing
agent-browser select @e1 "option"
agent-browser check @e1
agent-browser press Enter
agent-browser scroll down 500
# Get info
agent-browser get text @e1
agent-browser get url
agent-browser get title
# Wait
agent-browser wait @e1 # Wait for element
agent-browser wait --load networkidle # Wait for network idle
agent-browser wait --url "**/dashboard" # Wait for URL pattern
agent-browser wait --text "Welcome" # Wait for text
agent-browser wait 2000 # Wait ms
# Capture
agent-browser screenshot # Screenshot to temp dir
agent-browser screenshot --full # Full page
agent-browser screenshot --annotate # With numbered element labels ([N] -> @eN)
agent-browser pdf output.pdf
# Semantic locators (when refs unavailable)
agent-browser find text "Sign In" click
agent-browser find label "Email" fill "user@test.com"
agent-browser find role button click --name "Submit"
```
## Authentication
```bash
# Option 1: Import from user's running Chrome
agent-browser --auto-connect state save ./auth.json
agent-browser --state ./auth.json open https://app.example.com
# Option 2: Persistent profile
agent-browser --profile ~/.myapp open https://app.example.com/login
# ... login once, all future runs are authenticated
# Option 3: Session name (auto-save/restore)
agent-browser --session-name myapp open https://app.example.com/login
# ... login, close, next run state is restored
# Option 4: State file
agent-browser state save auth.json
agent-browser state load auth.json
```
## Iframes
Iframe content is inlined in snapshots. Interact with iframe refs directly — no frame switch needed.
## Parallel Sessions
```bash
agent-browser --session s1 open https://site-a.com
agent-browser --session s2 open https://site-b.com
agent-browser session list
```
## JavaScript Eval
```bash
agent-browser eval 'document.title'
# Complex JS — use --stdin to avoid shell quoting issues
agent-browser eval --stdin <<'EVALEOF'
JSON.stringify(Array.from(document.querySelectorAll("a")).map(a => a.href))
EVALEOF
```
## Cleanup
Always close sessions when done:
```bash
agent-browser close
agent-browser --session s1 close
```

View file

@ -0,0 +1,18 @@
# FreeRide Skill
FreeRide gives you unlimited free AI in PicoClaw by automatically managing OpenRouter's free models.
## Usage
- `/freeride auto`: Auto-configure best model + fallbacks.
- `/freeride list`: See all 30+ free models ranked.
- `/freeride status`: Check your current setup.
- `/freeride timeout 120`: Set request timeout for free models (seconds).
## How it works
The skill uses the `freeride` tool to fetch free models from OpenRouter, ranks them by context length, capabilities, recency, and provider trust, and then updates your PicoClaw configuration with the best models as fallbacks.
## Setup
Ensure you have your OpenRouter API key set in your K3s secrets or environment variables as `OPENROUTER_API_KEY`.

View file

@ -0,0 +1,48 @@
---
name: github
description: "Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries."
metadata: {"nanobot":{"emoji":"🐙","requires":{"bins":["gh"]},"install":[{"id":"brew","kind":"brew","formula":"gh","bins":["gh"],"label":"Install GitHub CLI (brew)"},{"id":"apt","kind":"apt","package":"gh","bins":["gh"],"label":"Install GitHub CLI (apt)"}]}}
---
# GitHub Skill
Use the `gh` CLI to interact with GitHub. Always specify `--repo owner/repo` when not in a git directory, or use URLs directly.
## Pull Requests
Check CI status on a PR:
```bash
gh pr checks 55 --repo owner/repo
```
List recent workflow runs:
```bash
gh run list --repo owner/repo --limit 10
```
View a run and see which steps failed:
```bash
gh run view <run-id> --repo owner/repo
```
View logs for failed steps only:
```bash
gh run view <run-id> --repo owner/repo --log-failed
```
## API for Advanced Queries
The `gh api` command is useful for accessing data not available through other subcommands.
Get PR with specific fields:
```bash
gh api repos/owner/repo/pulls/55 --jq '.title, .state, .user.login'
```
## JSON Output
Most commands support `--json` for structured output. You can use `--jq` to filter:
```bash
gh issue list --repo owner/repo --json number,title --jq '.[] | "\(.number): \(.title)"'
```

View file

@ -0,0 +1,64 @@
---
name: hardware
description: Read and control I2C and SPI peripherals on Sipeed boards (LicheeRV Nano, MaixCAM, NanoKVM).
homepage: https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html
metadata: {"nanobot":{"emoji":"🔧","requires":{"tools":["i2c","spi"]}}}
---
# Hardware (I2C / SPI)
Use the `i2c` and `spi` tools to interact with sensors, displays, and other peripherals connected to the board.
## Quick Start
```
# 1. Find available buses
i2c detect
# 2. Scan for connected devices
i2c scan (bus: "1")
# 3. Read from a sensor (e.g. AHT20 temperature/humidity)
i2c read (bus: "1", address: 0x38, register: 0xAC, length: 6)
# 4. SPI devices
spi list
spi read (device: "2.0", length: 4)
```
## Before You Start — Pinmux Setup
Most I2C/SPI pins are shared with WiFi on Sipeed boards. You must configure pinmux before use.
See `references/board-pinout.md` for board-specific commands.
**Common steps:**
1. Stop WiFi if using shared pins: `/etc/init.d/S30wifi stop`
2. Load i2c-dev module: `modprobe i2c-dev`
3. Configure pinmux with `devmem` (board-specific)
4. Verify with `i2c detect` and `i2c scan`
## Safety
- **Write operations** require `confirm: true` — always confirm with the user first
- I2C addresses are validated to 7-bit range (0x03-0x77)
- SPI modes are validated (0-3 only)
- Maximum per-transaction: 256 bytes (I2C), 4096 bytes (SPI)
## Common Devices
See `references/common-devices.md` for register maps and usage of popular sensors:
AHT20, BME280, SSD1306 OLED, MPU6050 IMU, DS3231 RTC, INA219 power monitor, PCA9685 PWM, and more.
## Troubleshooting
| Problem | Solution |
|---------|----------|
| No I2C buses found | `modprobe i2c-dev` and check device tree |
| Permission denied | Run as root or add user to `i2c` group |
| No devices on scan | Check wiring, pull-up resistors (4.7k typical), and pinmux |
| Bus number changed | I2C adapter numbers can shift between boots; use `i2c detect` to find current assignment |
| WiFi stopped working | I2C-1/SPI-2 share pins with WiFi SDIO; can't use both simultaneously |
| `devmem` not found | Download separately or use `busybox devmem` |
| SPI transfer returns all zeros | Check MISO wiring and device power |
| SPI transfer returns all 0xFF | Device not responding; check CS pin and clock polarity (mode) |

View file

@ -0,0 +1,131 @@
# Board Pinout & Pinmux Reference
## LicheeRV Nano (SG2002)
### I2C Buses
| Bus | Pins | Notes |
|-----|------|-------|
| I2C-1 | P18 (SCL), P21 (SDA) | **Shared with WiFi SDIO** — must stop WiFi first |
| I2C-3 | Available on header | Check device tree for pin assignment |
| I2C-5 | Software (BitBang) | Slower but no pin conflicts |
### SPI Buses
| Bus | Pins | Notes |
|-----|------|-------|
| SPI-2 | P18 (CS), P21 (MISO), P22 (MOSI), P23 (SCK) | **Shared with WiFi** — must stop WiFi first |
| SPI-4 | Software (BitBang) | Slower but no pin conflicts |
### Setup Steps for I2C-1
```bash
# 1. Stop WiFi (shares pins with I2C-1)
/etc/init.d/S30wifi stop
# 2. Configure pinmux for I2C-1
devmem 0x030010D0 b 0x2 # P18 → I2C1_SCL
devmem 0x030010DC b 0x2 # P21 → I2C1_SDA
# 3. Load i2c-dev module
modprobe i2c-dev
# 4. Verify
ls /dev/i2c-*
```
### Setup Steps for SPI-2
```bash
# 1. Stop WiFi (shares pins with SPI-2)
/etc/init.d/S30wifi stop
# 2. Configure pinmux for SPI-2
devmem 0x030010D0 b 0x1 # P18 → SPI2_CS
devmem 0x030010DC b 0x1 # P21 → SPI2_MISO
devmem 0x030010E0 b 0x1 # P22 → SPI2_MOSI
devmem 0x030010E4 b 0x1 # P23 → SPI2_SCK
# 3. Verify
ls /dev/spidev*
```
### Max Tested SPI Speed
- SPI-2 hardware: tested up to **93 MHz**
- `spidev_test` is pre-installed on the official image for loopback testing
---
## MaixCAM
### I2C Buses
| Bus | Pins | Notes |
|-----|------|-------|
| I2C-1 | Overlaps with WiFi | Not recommended |
| I2C-3 | Overlaps with WiFi | Not recommended |
| I2C-5 | A15 (SCL), A27 (SDA) | **Recommended** — software I2C, no conflicts |
### Setup Steps for I2C-5
```bash
# Configure pins using pinmap utility
# (MaixCAM uses a pinmap tool instead of devmem)
# Refer to: https://wiki.sipeed.com/hardware/en/maixcam/gpio.html
# Load i2c-dev
modprobe i2c-dev
# Verify
ls /dev/i2c-*
```
---
## MaixCAM2
### I2C Buses
| Bus | Pins | Notes |
|-----|------|-------|
| I2C-6 | A1 (SCL), A0 (SDA) | Available on header |
| I2C-7 | Available | Check device tree |
### Setup Steps
```bash
# Configure pinmap for I2C-6
# A1 → I2C6_SCL, A0 → I2C6_SDA
# Refer to MaixCAM2 documentation for pinmap commands
modprobe i2c-dev
ls /dev/i2c-*
```
---
## NanoKVM
Uses the same SG2002 SoC as LicheeRV Nano. GPIO and I2C access follows the same pinmux procedure. Refer to the LicheeRV Nano section above.
Check NanoKVM-specific pin headers for available I2C/SPI lines:
- https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html
---
## Common Issues
### devmem not found
The `devmem` utility may not be in the default image. Options:
- Use `busybox devmem` if busybox is installed
- Download devmem from the Sipeed package repository
- Cross-compile from source (single C file)
### Dynamic bus numbering
I2C adapter numbers can change between boots depending on driver load order. Always use `i2c detect` to find current bus assignments rather than hardcoding bus numbers.
### Permissions
`/dev/i2c-*` and `/dev/spidev*` typically require root access. Options:
- Run picoclaw as root
- Add user to `i2c` and `spi` groups
- Create udev rules: `SUBSYSTEM=="i2c-dev", MODE="0666"`

View file

@ -0,0 +1,78 @@
# Common I2C/SPI Device Reference
## I2C Devices
### AHT20 — Temperature & Humidity
- **Address:** 0x38
- **Init:** Write `[0xBE, 0x08, 0x00]` then wait 10ms
- **Measure:** Write `[0xAC, 0x33, 0x00]`, wait 80ms, read 6 bytes
- **Parse:** Status=byte[0], Humidity=(byte[1]<<12|byte[2]<<4|byte[3]>>4)/2^20*100, Temp=(byte[3]&0x0F<<16|byte[4]<<8|byte[5])/2^20*200-50
- **Notes:** No register addressing — write command bytes directly (omit `register` param)
### BME280 / BMP280 — Temperature, Humidity, Pressure
- **Address:** 0x76 or 0x77 (SDO pin selects)
- **Chip ID register:** 0xD0 → BMP280=0x58, BME280=0x60
- **Data registers:** 0xF7-0xFE (pressure, temperature, humidity)
- **Config:** Write 0xF2 (humidity oversampling), 0xF4 (temp/press oversampling + mode), 0xF5 (standby, filter)
- **Forced measurement:** Write `[0x25]` to register 0xF4, wait 40ms, read 8 bytes from 0xF7
- **Calibration:** Read 26 bytes from 0x88 and 7 bytes from 0xE1 for compensation formulas
- **Also available via SPI** (mode 0 or 3)
### SSD1306 — 128x64 OLED Display
- **Address:** 0x3C (or 0x3D if SA0 high)
- **Command prefix:** 0x00 (write to register 0x00)
- **Data prefix:** 0x40 (write to register 0x40)
- **Init sequence:** `[0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0x00, 0x40, 0x8D, 0x14, 0x20, 0x00, 0xA1, 0xC8, 0xDA, 0x12, 0x81, 0xCF, 0xD9, 0xF1, 0xDB, 0x40, 0xA4, 0xA6, 0xAF]`
- **Display on:** 0xAF, **Display off:** 0xAE
- **Also available via SPI** (faster, recommended for animations)
### MPU6050 — 6-axis Accelerometer + Gyroscope
- **Address:** 0x68 (or 0x69 if AD0 high)
- **WHO_AM_I:** Register 0x75 → should return 0x68
- **Wake up:** Write `[0x00]` to register 0x6B (clear sleep bit)
- **Read accel:** 6 bytes from register 0x3B (XH,XL,YH,YL,ZH,ZL) — signed 16-bit, default ±2g
- **Read gyro:** 6 bytes from register 0x43 — signed 16-bit, default ±250°/s
- **Read temp:** 2 bytes from register 0x41 — Temp°C = value/340 + 36.53
### DS3231 — Real-Time Clock
- **Address:** 0x68
- **Read time:** 7 bytes from register 0x00 (seconds, minutes, hours, day, date, month, year) — BCD encoded
- **Set time:** Write 7 BCD bytes to register 0x00
- **Temperature:** 2 bytes from register 0x11 (signed, 0.25°C resolution)
- **Status:** Register 0x0F — bit 2 = busy, bit 0 = alarm 1 flag
### INA219 — Current & Power Monitor
- **Address:** 0x40-0x4F (A0,A1 pin selectable)
- **Config:** Register 0x00 — set voltage range, gain, ADC resolution
- **Shunt voltage:** Register 0x01 (signed 16-bit, LSB=10µV)
- **Bus voltage:** Register 0x02 (bits 15:3, LSB=4mV)
- **Power:** Register 0x03 (after calibration)
- **Current:** Register 0x04 (after calibration)
- **Calibration:** Register 0x05 — set based on shunt resistor value
### PCA9685 — 16-Channel PWM / Servo Controller
- **Address:** 0x40-0x7F (A0-A5 selectable, default 0x40)
- **Mode 1:** Register 0x00 — bit 4=sleep, bit 5=auto-increment
- **Set PWM freq:** Sleep → write prescale to 0xFE → wake. Prescale = round(25MHz / (4096 × freq)) - 1
- **Channel N on/off:** Registers 0x06+4*N to 0x09+4*N (ON_L, ON_H, OFF_L, OFF_H)
- **Servo 0°-180°:** ON=0, OFF=150-600 (at 50Hz). Typical: 0°=150, 90°=375, 180°=600
### AT24C256 — 256Kbit EEPROM
- **Address:** 0x50-0x57 (A0-A2 selectable)
- **Read:** Write 2-byte address (high, low), then read N bytes
- **Write:** Write 2-byte address + up to 64 bytes (page write), wait 5ms for write cycle
- **Page size:** 64 bytes. Writes that cross page boundary wrap around.
## SPI Devices
### MCP3008 — 8-Channel 10-bit ADC
- **Interface:** SPI mode 0, max 3.6 MHz @ 5V
- **Read channel N:** Send `[0x01, (0x80 | N<<4), 0x00]`, result in last 10 bits of bytes 1-2
- **Formula:** value = ((byte[1] & 0x03) << 8) | byte[2]
- **Voltage:** value × Vref / 1024
### W25Q128 — 128Mbit SPI Flash
- **Interface:** SPI mode 0 or 3, up to 104 MHz
- **Read ID:** Send `[0x9F, 0, 0, 0]` → manufacturer + device ID
- **Read data:** Send `[0x03, addr_high, addr_mid, addr_low]` + N zero bytes
- **Status:** Send `[0x05, 0]` → bit 0 = BUSY

View file

@ -0,0 +1,371 @@
---
name: skill-creator
description: Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
---
# Skill Creator
This skill provides guidance for creating effective skills.
## About Skills
Skills are modular, self-contained packages that extend the agent's capabilities by providing
specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
domains or tasks—they transform the agent from a general-purpose agent into a specialized agent
equipped with procedural knowledge that no model can fully possess.
### What Skills Provide
1. Specialized workflows - Multi-step procedures for specific domains
2. Tool integrations - Instructions for working with specific file formats or APIs
3. Domain expertise - Company-specific knowledge, schemas, business logic
4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
## Core Principles
### Concise is Key
The context window is a public good. Skills share the context window with everything else the agent needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
**Default assumption: the agent is already very smart.** Only add context the agent doesn't already have. Challenge each piece of information: "Does the agent really need this explanation?" and "Does this paragraph justify its token cost?"
Prefer concise examples over verbose explanations.
### Set Appropriate Degrees of Freedom
Match the level of specificity to the task's fragility and variability:
**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
Think of the agent as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
### Anatomy of a Skill
Every skill consists of a required SKILL.md file and optional bundled resources:
```
skill-name/
├── SKILL.md (required)
│ ├── YAML frontmatter metadata (required)
│ │ ├── name: (required)
│ │ └── description: (required)
│ └── Markdown instructions (required)
└── Bundled Resources (optional)
├── scripts/ - Executable code (Python/Bash/etc.)
├── references/ - Documentation intended to be loaded into context as needed
└── assets/ - Files used in output (templates, icons, fonts, etc.)
```
#### SKILL.md (required)
Every SKILL.md consists of:
- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that the agent reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
#### Bundled Resources (optional)
##### Scripts (`scripts/`)
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
- **Benefits**: Token efficient, deterministic, may be executed without loading into context
- **Note**: Scripts may still need to be read by the agent for patching or environment-specific adjustments
##### References (`references/`)
Documentation and reference material intended to be loaded as needed into context to inform the agent's process and thinking.
- **When to include**: For documentation that the agent should reference while working
- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
- **Benefits**: Keeps SKILL.md lean, loaded only when the agent determines it's needed
- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
##### Assets (`assets/`)
Files not intended to be loaded into context, but rather used within the output the agent produces.
- **When to include**: When the skill needs files that will be used in the final output
- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
- **Benefits**: Separates output resources from documentation, enables the agent to use files without loading them into context
#### What to Not Include in a Skill
A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
- README.md
- INSTALLATION_GUIDE.md
- QUICK_REFERENCE.md
- CHANGELOG.md
- etc.
The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxiliary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
### Progressive Disclosure Design Principle
Skills use a three-level loading system to manage context efficiently:
1. **Metadata (name + description)** - Always in context (~100 words)
2. **SKILL.md body** - When skill triggers (<5k words)
3. **Bundled resources** - As needed by the agent (Unlimited because scripts can be executed without reading into context window)
#### Progressive Disclosure Patterns
Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
**Pattern 1: High-level guide with references**
```markdown
# PDF Processing
## Quick start
Extract text with pdfplumber:
[code example]
## Advanced features
- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
```
the agent loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
**Pattern 2: Domain-specific organization**
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
```
bigquery-skill/
├── SKILL.md (overview and navigation)
└── reference/
├── finance.md (revenue, billing metrics)
├── sales.md (opportunities, pipeline)
├── product.md (API usage, features)
└── marketing.md (campaigns, attribution)
```
When a user asks about sales metrics, the agent only reads sales.md.
Similarly, for skills supporting multiple frameworks or variants, organize by variant:
```
cloud-deploy/
├── SKILL.md (workflow + provider selection)
└── references/
├── aws.md (AWS deployment patterns)
├── gcp.md (GCP deployment patterns)
└── azure.md (Azure deployment patterns)
```
When the user chooses AWS, the agent only reads aws.md.
**Pattern 3: Conditional details**
Show basic content, link to advanced content:
```markdown
# DOCX Processing
## Creating documents
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
## Editing documents
For simple edits, modify the XML directly.
**For tracked changes**: See [REDLINING.md](REDLINING.md)
**For OOXML details**: See [OOXML.md](OOXML.md)
```
the agent reads REDLINING.md or OOXML.md only when the user needs those features.
**Important guidelines:**
- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so the agent can see the full scope when previewing.
## Skill Creation Process
Skill creation involves these steps:
1. Understand the skill with concrete examples
2. Plan reusable skill contents (scripts, references, assets)
3. Initialize the skill (run init_skill.py)
4. Edit the skill (implement resources and write SKILL.md)
5. Package the skill (run package_skill.py)
6. Iterate based on real usage
Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
### Skill Naming
- Use lowercase letters, digits, and hyphens only; normalize user-provided titles to hyphen-case (e.g., "Plan Mode" -> `plan-mode`).
- When generating names, generate a name under 64 characters (letters, digits, hyphens).
- Prefer short, verb-led phrases that describe the action.
- Namespace by tool when it improves clarity or triggering (e.g., `gh-address-comments`, `linear-address-issue`).
- Name the skill folder exactly after the skill name.
### Step 1: Understanding the Skill with Concrete Examples
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
For example, when building an image-editor skill, relevant questions include:
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
- "Can you give some examples of how this skill would be used?"
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
- "What would a user say that should trigger this skill?"
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
Conclude this step when there is a clear sense of the functionality the skill should support.
### Step 2: Planning the Reusable Skill Contents
To turn concrete examples into an effective skill, analyze each example by:
1. Considering how to execute on the example from scratch
2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
1. Rotating a PDF requires re-writing the same code each time
2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
1. Writing a frontend webapp requires the same boilerplate HTML/React each time
2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
1. Querying BigQuery requires re-discovering the table schemas and relationships each time
2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
### Step 3: Initializing the Skill
At this point, it is time to actually create the skill.
Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
Usage:
```bash
scripts/init_skill.py <skill-name> --path <output-directory> [--resources scripts,references,assets] [--examples]
```
Examples:
```bash
scripts/init_skill.py my-skill --path skills/public
scripts/init_skill.py my-skill --path skills/public --resources scripts,references
scripts/init_skill.py my-skill --path skills/public --resources scripts --examples
```
The script:
- Creates the skill directory at the specified path
- Generates a SKILL.md template with proper frontmatter and TODO placeholders
- Optionally creates resource directories based on `--resources`
- Optionally adds example files when `--examples` is set
After initialization, customize the SKILL.md and add resources as needed. If you used `--examples`, replace or delete placeholder files.
### Step 4: Edit the Skill
When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of the agent to use. Include information that would be beneficial and non-obvious to the agent. Consider what procedural knowledge, domain-specific details, or reusable assets would help another the agent instance execute these tasks more effectively.
#### Learn Proven Design Patterns
Consult these helpful guides based on your skill's needs:
- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
These files contain established best practices for effective skill design.
#### Start with Reusable Skill Contents
To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
If you used `--examples`, delete any placeholder files that are not needed for the skill. Only create resource directories that are actually required.
#### Update SKILL.md
**Writing Guidelines:** Always use imperative/infinitive form.
##### Frontmatter
Write the YAML frontmatter with `name` and `description`:
- `name`: The skill name
- `description`: This is the primary triggering mechanism for your skill, and helps the agent understand when to use the skill.
- Include both what the Skill does and specific triggers/contexts for when to use it.
- Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to the agent.
- Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when the agent needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
Do not include any other fields in YAML frontmatter.
##### Body
Write instructions for using the skill and its bundled resources.
### Step 5: Packaging a Skill
Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
```bash
scripts/package_skill.py <path/to/skill-folder>
```
Optional output directory specification:
```bash
scripts/package_skill.py <path/to/skill-folder> ./dist
```
The packaging script will:
1. **Validate** the skill automatically, checking:
- YAML frontmatter format and required fields
- Skill naming conventions and directory structure
- Description completeness and quality
- File organization and resource references
2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
### Step 6: Iterate
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
**Iteration workflow:**
1. Use the skill on real tasks
2. Notice struggles or inefficiencies
3. Identify how SKILL.md or bundled resources should be updated
4. Implement changes and test again

View file

@ -0,0 +1,67 @@
---
name: summarize
description: Summarize or extract text/transcripts from URLs, podcasts, and local files (great fallback for “transcribe this YouTube/video”).
homepage: https://summarize.sh
metadata: {"nanobot":{"emoji":"🧾","requires":{"bins":["summarize"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/summarize","bins":["summarize"],"label":"Install summarize (brew)"}]}}
---
# Summarize
Fast CLI to summarize URLs, local files, and YouTube links.
## When to use (trigger phrases)
Use this skill immediately when the user asks any of:
- “use summarize.sh”
- “whats this link/video about?”
- “summarize this URL/article”
- “transcribe this YouTube/video” (best-effort transcript extraction; no `yt-dlp` needed)
## Quick start
```bash
summarize "https://example.com" --model google/gemini-3-flash-preview
summarize "/path/to/file.pdf" --model google/gemini-3-flash-preview
summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto
```
## YouTube: summary vs transcript
Best-effort transcript (URLs only):
```bash
summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto --extract-only
```
If the user asked for a transcript but its huge, return a tight summary first, then ask which section/time range to expand.
## Model + keys
Set the API key for your chosen provider:
- OpenAI: `OPENAI_API_KEY`
- Anthropic: `ANTHROPIC_API_KEY`
- xAI: `XAI_API_KEY`
- Google: `GEMINI_API_KEY` (aliases: `GOOGLE_GENERATIVE_AI_API_KEY`, `GOOGLE_API_KEY`)
Default model is `google/gemini-3-flash-preview` if none is set.
## Useful flags
- `--length short|medium|long|xl|xxl|<chars>`
- `--max-output-tokens <count>`
- `--extract-only` (URLs only)
- `--json` (machine readable)
- `--firecrawl auto|off|always` (fallback extraction)
- `--youtube auto` (Apify fallback if `APIFY_API_TOKEN` set)
## Config
Optional config file: `~/.summarize/config.json`
```json
{ "model": "openai/gpt-5.4" }
```
Optional services:
- `FIRECRAWL_API_KEY` for blocked sites
- `APIFY_API_TOKEN` for YouTube fallback

View file

@ -0,0 +1,121 @@
---
name: tmux
description: Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output.
metadata: {"nanobot":{"emoji":"🧵","os":["darwin","linux"],"requires":{"bins":["tmux"]}}}
---
# tmux Skill
Use tmux only when you need an interactive TTY. Prefer exec background mode for long-running, non-interactive tasks.
## Quickstart (isolated socket, exec tool)
```bash
SOCKET_DIR="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"
mkdir -p "$SOCKET_DIR"
SOCKET="$SOCKET_DIR/nanobot.sock"
SESSION=nanobot-python
tmux -S "$SOCKET" new -d -s "$SESSION" -n shell
tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- 'PYTHON_BASIC_REPL=1 python3 -q' Enter
tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
```
After starting a session, always print monitor commands:
```
To monitor:
tmux -S "$SOCKET" attach -t "$SESSION"
tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
```
## Socket convention
- Use `NANOBOT_TMUX_SOCKET_DIR` environment variable.
- Default socket path: `"$NANOBOT_TMUX_SOCKET_DIR/nanobot.sock"`.
## Targeting panes and naming
- Target format: `session:window.pane` (defaults to `:0.0`).
- Keep names short; avoid spaces.
- Inspect: `tmux -S "$SOCKET" list-sessions`, `tmux -S "$SOCKET" list-panes -a`.
## Finding sessions
- List sessions on your socket: `{baseDir}/scripts/find-sessions.sh -S "$SOCKET"`.
- Scan all sockets: `{baseDir}/scripts/find-sessions.sh --all` (uses `NANOBOT_TMUX_SOCKET_DIR`).
## Sending input safely
- Prefer literal sends: `tmux -S "$SOCKET" send-keys -t target -l -- "$cmd"`.
- Control keys: `tmux -S "$SOCKET" send-keys -t target C-c`.
## Watching output
- Capture recent history: `tmux -S "$SOCKET" capture-pane -p -J -t target -S -200`.
- Wait for prompts: `{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern'`.
- Attaching is OK; detach with `Ctrl+b d`.
## Spawning processes
- For python REPLs, set `PYTHON_BASIC_REPL=1` (non-basic REPL breaks send-keys flows).
## Windows / WSL
- tmux is supported on macOS/Linux. On Windows, use WSL and install tmux inside WSL.
- This skill is gated to `darwin`/`linux` and requires `tmux` on PATH.
## Orchestrating Coding Agents (Codex, Claude Code)
tmux excels at running multiple coding agents in parallel:
```bash
SOCKET="${TMPDIR:-/tmp}/codex-army.sock"
# Create multiple sessions
for i in 1 2 3 4 5; do
tmux -S "$SOCKET" new-session -d -s "agent-$i"
done
# Launch agents in different workdirs
tmux -S "$SOCKET" send-keys -t agent-1 "cd /tmp/project1 && codex --yolo 'Fix bug X'" Enter
tmux -S "$SOCKET" send-keys -t agent-2 "cd /tmp/project2 && codex --yolo 'Fix bug Y'" Enter
# Poll for completion (check if prompt returned)
for sess in agent-1 agent-2; do
if tmux -S "$SOCKET" capture-pane -p -t "$sess" -S -3 | grep -q ""; then
echo "$sess: DONE"
else
echo "$sess: Running..."
fi
done
# Get full output from completed session
tmux -S "$SOCKET" capture-pane -p -t agent-1 -S -500
```
**Tips:**
- Use separate git worktrees for parallel fixes (no branch conflicts)
- `pnpm install` first before running codex in fresh clones
- Check for shell prompt (`` or `$`) to detect completion
- Codex needs `--yolo` or `--full-auto` for non-interactive fixes
## Cleanup
- Kill a session: `tmux -S "$SOCKET" kill-session -t "$SESSION"`.
- Kill all sessions on a socket: `tmux -S "$SOCKET" list-sessions -F '#{session_name}' | xargs -r -n1 tmux -S "$SOCKET" kill-session -t`.
- Remove everything on the private socket: `tmux -S "$SOCKET" kill-server`.
## Helper: wait-for-text.sh
`{baseDir}/scripts/wait-for-text.sh` polls a pane for a regex (or fixed string) with a timeout.
```bash
{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern' [-F] [-T 20] [-i 0.5] [-l 2000]
```
- `-t`/`--target` pane target (required)
- `-p`/`--pattern` regex to match (required); add `-F` for fixed string
- `-T` timeout seconds (integer, default 15)
- `-i` poll interval seconds (default 0.5)
- `-l` history lines to search (integer, default 1000)

View file

@ -0,0 +1,112 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'USAGE'
Usage: find-sessions.sh [-L socket-name|-S socket-path|-A] [-q pattern]
List tmux sessions on a socket (default tmux socket if none provided).
Options:
-L, --socket tmux socket name (passed to tmux -L)
-S, --socket-path tmux socket path (passed to tmux -S)
-A, --all scan all sockets under NANOBOT_TMUX_SOCKET_DIR
-q, --query case-insensitive substring to filter session names
-h, --help show this help
USAGE
}
socket_name=""
socket_path=""
query=""
scan_all=false
socket_dir="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"
while [[ $# -gt 0 ]]; do
case "$1" in
-L|--socket) socket_name="${2-}"; shift 2 ;;
-S|--socket-path) socket_path="${2-}"; shift 2 ;;
-A|--all) scan_all=true; shift ;;
-q|--query) query="${2-}"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage; exit 1 ;;
esac
done
if [[ "$scan_all" == true && ( -n "$socket_name" || -n "$socket_path" ) ]]; then
echo "Cannot combine --all with -L or -S" >&2
exit 1
fi
if [[ -n "$socket_name" && -n "$socket_path" ]]; then
echo "Use either -L or -S, not both" >&2
exit 1
fi
if ! command -v tmux >/dev/null 2>&1; then
echo "tmux not found in PATH" >&2
exit 1
fi
list_sessions() {
local label="$1"; shift
local tmux_cmd=(tmux "$@")
if ! sessions="$("${tmux_cmd[@]}" list-sessions -F '#{session_name}\t#{session_attached}\t#{session_created_string}' 2>/dev/null)"; then
echo "No tmux server found on $label" >&2
return 1
fi
if [[ -n "$query" ]]; then
sessions="$(printf '%s\n' "$sessions" | grep -i -- "$query" || true)"
fi
if [[ -z "$sessions" ]]; then
echo "No sessions found on $label"
return 0
fi
echo "Sessions on $label:"
printf '%s\n' "$sessions" | while IFS=$'\t' read -r name attached created; do
attached_label=$([[ "$attached" == "1" ]] && echo "attached" || echo "detached")
printf ' - %s (%s, started %s)\n' "$name" "$attached_label" "$created"
done
}
if [[ "$scan_all" == true ]]; then
if [[ ! -d "$socket_dir" ]]; then
echo "Socket directory not found: $socket_dir" >&2
exit 1
fi
shopt -s nullglob
sockets=("$socket_dir"/*)
shopt -u nullglob
if [[ "${#sockets[@]}" -eq 0 ]]; then
echo "No sockets found under $socket_dir" >&2
exit 1
fi
exit_code=0
for sock in "${sockets[@]}"; do
if [[ ! -S "$sock" ]]; then
continue
fi
list_sessions "socket path '$sock'" -S "$sock" || exit_code=$?
done
exit "$exit_code"
fi
tmux_cmd=(tmux)
socket_label="default socket"
if [[ -n "$socket_name" ]]; then
tmux_cmd+=(-L "$socket_name")
socket_label="socket name '$socket_name'"
elif [[ -n "$socket_path" ]]; then
tmux_cmd+=(-S "$socket_path")
socket_label="socket path '$socket_path'"
fi
list_sessions "$socket_label" "${tmux_cmd[@]:1}"

View file

@ -0,0 +1,83 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'USAGE'
Usage: wait-for-text.sh -t target -p pattern [options]
Poll a tmux pane for text and exit when found.
Options:
-t, --target tmux target (session:window.pane), required
-p, --pattern regex pattern to look for, required
-F, --fixed treat pattern as a fixed string (grep -F)
-T, --timeout seconds to wait (integer, default: 15)
-i, --interval poll interval in seconds (default: 0.5)
-l, --lines number of history lines to inspect (integer, default: 1000)
-h, --help show this help
USAGE
}
target=""
pattern=""
grep_flag="-E"
timeout=15
interval=0.5
lines=1000
while [[ $# -gt 0 ]]; do
case "$1" in
-t|--target) target="${2-}"; shift 2 ;;
-p|--pattern) pattern="${2-}"; shift 2 ;;
-F|--fixed) grep_flag="-F"; shift ;;
-T|--timeout) timeout="${2-}"; shift 2 ;;
-i|--interval) interval="${2-}"; shift 2 ;;
-l|--lines) lines="${2-}"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage; exit 1 ;;
esac
done
if [[ -z "$target" || -z "$pattern" ]]; then
echo "target and pattern are required" >&2
usage
exit 1
fi
if ! [[ "$timeout" =~ ^[0-9]+$ ]]; then
echo "timeout must be an integer number of seconds" >&2
exit 1
fi
if ! [[ "$lines" =~ ^[0-9]+$ ]]; then
echo "lines must be an integer" >&2
exit 1
fi
if ! command -v tmux >/dev/null 2>&1; then
echo "tmux not found in PATH" >&2
exit 1
fi
# End time in epoch seconds (integer, good enough for polling)
start_epoch=$(date +%s)
deadline=$((start_epoch + timeout))
while true; do
# -J joins wrapped lines, -S uses negative index to read last N lines
pane_text="$(tmux capture-pane -p -J -t "$target" -S "-${lines}" 2>/dev/null || true)"
if printf '%s\n' "$pane_text" | grep $grep_flag -- "$pattern" >/dev/null 2>&1; then
exit 0
fi
now=$(date +%s)
if (( now >= deadline )); then
echo "Timed out after ${timeout}s waiting for pattern: $pattern" >&2
echo "Last ${lines} lines from $target:" >&2
printf '%s\n' "$pane_text" >&2
exit 1
fi
sleep "$interval"
done

View file

@ -0,0 +1,59 @@
---
name: weather
description: Get current weather and forecasts with verified location matching (no API key required).
homepage: https://wttr.in/:help
metadata: {"nanobot":{"emoji":"🌤️","requires":{"bins":["curl"]}}}
---
# Weather
Use the most reliable location match first. For Chinese city names or other non-Latin input, prefer `wttr.in` with the original query because it resolves native names directly. Use Open-Meteo for structured current conditions and forecasts only after you have confirmed the exact city.
## Accuracy Rules
- Always restate the matched location, region/country, and observation time in the final answer.
- Do not trust the first geocoding hit blindly. Check `country`, `admin1`, `admin2`, and `population`.
- For Chinese city queries, do not send Hanzi directly to Open-Meteo geocoding unless the top result is obviously correct. Prefer `wttr.in` with the original Chinese name, or geocode the English/pinyin city name instead.
- If multiple plausible matches remain, ask a follow-up question or state the assumption clearly.
- Use `timezone=auto` when calling Open-Meteo so the reported time matches the location.
## wttr.in (best for direct city-name queries)
Quick current conditions:
```bash
curl -s "https://wttr.in/London?format=%l:+%c+%t+%h+%w"
```
Chinese city example:
```bash
curl -s "https://wttr.in/%E6%88%90%E9%83%BD?format=%l:+%c+%t+%h+%w"
curl -s "https://wttr.in/%E4%B8%8A%E6%B5%B7?format=%l:+%c+%t+%h+%w"
```
JSON output if you need more detail:
```bash
curl -s "https://wttr.in/Chengdu?format=j1"
```
Tips:
- URL-encode spaces: `New York` -> `New+York`
- URL-encode non-ASCII text before sending the request
- Use `?m` for metric units and `?u` for US units
## Open-Meteo (best for structured forecasts)
1. Geocode the city and verify the returned location metadata:
```bash
curl -s "https://geocoding-api.open-meteo.com/v1/search?name=Chengdu&count=3&language=en&format=json"
```
2. Query current weather and today's forecast with the verified coordinates:
```bash
curl -s "https://api.open-meteo.com/v1/forecast?latitude=30.66667&longitude=104.06667&current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max,temperature_2m_min&forecast_days=1&timezone=auto"
```
Important:
- For Chinese inputs like `成都`, geocoding `name=%E6%88%90%E9%83%BD` may return smaller homonym locations first. Prefer `Chengdu` after verifying it matches Sichuan, China.
- If geocoding looks suspicious, fall back to `wttr.in` for the original city name instead of presenting a likely wrong result.
Docs: https://open-meteo.com/en/docs

View file

@ -27,7 +27,7 @@ docker compose -f docker/docker-compose.yml --profile gateway up -d
> **Docker Users**: By default, the Gateway listens on `127.0.0.1` which is not accessible from the host. If you need to access the health endpoints or expose ports, set `PICOCLAW_GATEWAY_HOST=0.0.0.0` in your environment or update `config.json`.
> [!NOTE]
> The `gateway` profile only serves the webhook handlers (including Pico when enabled) and health endpoints on the gateway port, so it does not expose generic REST chat endpoints such as `/chat` or `/a2a`. Launcher mode adds the browser UI plus `/api/pico/token` and a `/pico/ws` proxy on the launcher port, but `/pico/ws` is also available directly on the gateway whenever the Pico channel is enabled.
> The `gateway` profile only serves the webhook handlers (including Pico when enabled) and health endpoints on the gateway port, so it does not expose generic REST chat endpoints such as `/chat` or `/a2a`. Launcher mode adds the browser UI plus `/api/pico/info` and an authenticated `/pico/ws` proxy on the launcher port, but `/pico/ws` is also available directly on the gateway whenever the Pico channel is enabled.
```bash
# 5. Check logs

View file

@ -65,6 +65,12 @@ Shows your current primary model and the active fallback rotation pool.
### `freeride list [limit]`
Displays the current top-ranked free models available on OpenRouter without modifying your configuration.
### `freeride settimeout [seconds]`
Sets the request timeout for all OpenRouter models. Default is 300 seconds (5 minutes). Use this if you need longer timeouts for complex tasks:
```bash
picoclaw freeride settimeout 600 # 10 minutes
```
## K3s Deployment & Secrets
When running PicoClaw on K3s, follow these steps to manage your secrets safely.
@ -106,8 +112,8 @@ To prevent the agent from "hanging" or retrying known-failed models, PicoClaw us
### 1. Zero-Amnesia Persistence
Model failures (e.g., 429 Rate Limits) are saved to `~/.picoclaw/cooldowns.json`. This ensures that if you restart the agent, it **remembers** which models were saturated and skips them instantly. You no longer have to wait through a series of timeouts every time you restart.
### 2. Aggressive 30s Timeout
The default request timeout for LLM calls is **30 seconds**. If a free model is stalled or unresponsive, the agent will move to the next fallback in your pool much faster than the standard HTTP default.
### 2. Generous 5 Minute Timeout
The default request timeout for LLM calls is **300 seconds (5 minutes)**. Free models can be slower than paid ones, and complex agentic tasks (multi-step reasoning, file operations, debugging) need time to complete. If a free model truly can't handle the request, it will return an error rather than hanging indefinitely - allowing the agent to fail over to the next fallback.
## Troubleshooting

View file

@ -1,37 +1,869 @@
{
"session": {
"dimensions": [
"chat"
]
},
"version": 3,
"isolation": {},
"agents": {
"defaults": {
"model_name": "google/gemma-3-27b-it:free",
"model_fallbacks": [
"google/gemma-3-27b-it:free",
"nvidia/nemotron-4-340b-instruct:free",
"qwen/qwen-2.5-72b-instruct:free",
"mistralai/mistral-small-24b-it-v1:free"
"workspace": "/home/stevef/.picoclaw/workspace",
"restrict_to_workspace": true,
"allow_read_outside_workspace": false,
"provider": "nvidia",
"model_name": "nvidia/nemotron-3-super-120b-a12b",
"model_fallbacks": [],
"max_tokens": 32768,
"max_tool_iterations": 50,
"summarize_message_threshold": 20,
"summarize_token_percent": 75,
"steering_mode": "one-at-a-time",
"subturn": {
"max_depth": 10,
"max_concurrent": 5,
"default_timeout_minutes": 20,
"default_token_budget": 100000,
"concurrency_timeout_sec": 10
},
"tool_feedback": {
"enabled": true,
"max_args_length": 300
},
"split_on_marker": false
}
},
"channel_list": {
"dingtalk": {
"enabled": false,
"type": "dingtalk",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"client_id": ""
}
},
"discord": {
"enabled": false,
"type": "discord",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"proxy": "",
"mention_only": false
}
},
"feishu": {
"enabled": false,
"type": "feishu",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"app_id": "",
"random_reaction_emoji": [
""
],
"is_lark": false
}
},
"irc": {
"enabled": false,
"type": "irc",
"allow_from": [
""
],
"max_tokens": 4096,
"max_tool_iterations": 10
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"server": "",
"tls": false,
"nick": "",
"sasl_user": "",
"channels": [
""
]
}
},
"line": {
"enabled": false,
"type": "line",
"reasoning_channel_id": "",
"group_trigger": {
"mention_only": true
},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"webhook_host": "0.0.0.0",
"webhook_port": 18791,
"webhook_path": "/webhook/line"
}
},
"maixcam": {
"enabled": false,
"type": "maixcam",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"host": "0.0.0.0",
"port": 18790
}
},
"matrix": {
"enabled": false,
"type": "matrix",
"reasoning_channel_id": "",
"group_trigger": {
"mention_only": true
},
"typing": {},
"placeholder": {
"enabled": true,
"text": [
"Thinking... 💭"
]
},
"settings": {
"homeserver": "https://matrix.org",
"user_id": "",
"join_on_invite": true
}
},
"onebot": {
"enabled": false,
"type": "onebot",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"ws_url": "ws://127.0.0.1:3001",
"reconnect_interval": 5,
"group_trigger_prefix": null
}
},
"pico": {
"enabled": false,
"type": "pico",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"ping_interval": 30,
"read_timeout": 60,
"write_timeout": 10,
"max_connections": 100
}
},
"pico_client": {
"enabled": false,
"type": "pico_client",
"allow_from": [
""
],
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"url": ""
}
},
"qq": {
"enabled": false,
"type": "qq",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"app_id": "",
"max_message_length": 2000,
"max_base64_file_size_mib": 0,
"send_markdown": false
}
},
"slack": {
"enabled": false,
"type": "slack",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {}
},
"telegram": {
"enabled": true,
"type": "telegram",
"allow_from": [
"-5274005272",
"8271300679"
],
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {
"enabled": true
},
"placeholder": {
"enabled": true,
"text": [
"Thinking... 💭"
]
},
"settings": {
"base_url": "",
"proxy": "",
"streaming": {
"enabled": true,
"throttle_seconds": 3,
"min_growth_chars": 200
},
"use_markdown_v2": false
}
},
"vk": {
"enabled": false,
"type": "vk",
"allow_from": [
""
],
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"group_id": 0
}
},
"wecom": {
"enabled": false,
"type": "wecom",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"bot_id": "",
"websocket_url": "wss://openws.work.weixin.qq.com",
"send_thinking_message": true
}
},
"weixin": {
"enabled": false,
"type": "weixin",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"base_url": "https://ilinkai.weixin.qq.com/",
"cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c",
"proxy": ""
}
},
"whatsapp": {
"enabled": false,
"type": "whatsapp",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"bridge_url": "ws://localhost:3001",
"use_native": false,
"session_store_path": ""
}
}
},
"model_list": [
{
"model_name": "google/gemma-3-27b-it:free",
"model_name": "glm-4.7",
"model": "zhipu/glm-4.7",
"api_base": "https://open.bigmodel.cn/api/paas/v4"
},
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_base": "https://api.openai.com/v1"
},
{
"model_name": "claude-sonnet-4.6",
"model": "anthropic/claude-sonnet-4.6",
"api_base": "https://api.anthropic.com/v1"
},
{
"model_name": "deepseek-chat",
"model": "deepseek/deepseek-chat",
"api_base": "https://api.deepseek.com/v1"
},
{
"model_name": "gemini-2.0-flash",
"model": "gemini/gemini-2.0-flash-exp",
"api_base": "https://generativelanguage.googleapis.com/v1beta"
},
{
"model_name": "qwen-plus",
"model": "qwen/qwen-plus",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1"
},
{
"model_name": "moonshot-v1-8k",
"model": "moonshot/moonshot-v1-8k",
"api_base": "https://api.moonshot.cn/v1"
},
{
"model_name": "llama-3.3-70b",
"model": "groq/llama-3.3-70b-versatile",
"api_base": "https://api.groq.com/openai/v1"
},
{
"model_name": "openrouter-nemotron",
"model": "nvidia/nemotron-3-super-120b-a12b:free",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-elephant",
"model": "openrouter/elephant-alpha",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-free",
"model": "arcee-ai/trinity-large-preview:free",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "google-gemma-3-27b-it:free",
"model": "google/gemma-3-27b-it:free",
"protocol": "openrouter"
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "nvidia/nemotron-4-340b-instruct:free",
"model_name": "qwen-qwen3-coder:free",
"model": "qwen/qwen3-coder:free",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "nvidia-nemotron-4-340b-instruct:free",
"model": "nvidia/nemotron-4-340b-instruct:free",
"protocol": "openrouter"
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "qwen/qwen-2.5-72b-instruct:free",
"model": "qwen/qwen-2.5-72b-instruct:free",
"protocol": "openrouter"
"model_name": "mistralai-pixtral-12b:free",
"model": "mistralai/pixtral-12b:free",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "mistralai/mistral-small-24b-it-v1:free",
"model": "mistralai/mistral-small-24b-it-v1:free",
"protocol": "openrouter"
"model_name": "google-gemma-4-26b-a4b-it:free",
"model": "google/gemma-4-26b-a4b-it:free",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-auto",
"model": "auto",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-gpt-5.4",
"model": "openai/gpt-5.4",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "nvidia/llama-3.1-nemotron-70b-instruct",
"model": "nvidia/llama-3.1-nemotron-70b-instruct",
"api_base": "https://integrate.api.nvidia.com/v1"
},
{
"model_name": "meta/llama-3.1-70b-instruct",
"model": "meta/llama-3.1-70b-instruct",
"api_base": "https://integrate.api.nvidia.com/v1"
},
{
"model_name": "meta/llama-3.1-405b-instruct",
"model": "meta/llama-3.1-405b-instruct",
"api_base": "https://integrate.api.nvidia.com/v1"
},
{
"model_name": "meta/llama-3.3-70b-instruct",
"model": "meta/llama-3.3-70b-instruct",
"api_base": "https://integrate.api.nvidia.com/v1"
},
{
"model_name": "azure-grok",
"model": "openai/grok-4-fast-non-reasoning",
"api_base": "https://TestSJF.openai.azure.com/openai/v1/",
"enabled": true
},
{
"model_name": "cerebras-llama-3.3-70b",
"model": "cerebras/llama-3.3-70b",
"api_base": "https://api.cerebras.ai/v1"
},
{
"model_name": "vivgrid-auto",
"model": "vivgrid/auto",
"api_base": "https://api.vivgrid.com/v1"
},
{
"model_name": "ark-code-latest",
"model": "volcengine/ark-code-latest",
"api_base": "https://ark.cn-beijing.volces.com/api/v3"
},
{
"model_name": "doubao-pro",
"model": "volcengine/doubao-pro-32k",
"api_base": "https://ark.cn-beijing.volces.com/api/v3"
},
{
"model_name": "deepseek-v3",
"model": "shengsuanyun/deepseek-v3",
"api_base": "https://api.shengsuanyun.com/v1"
},
{
"model_name": "copilot-gpt-5.4",
"model": "github-copilot/gpt-5.4",
"api_base": "http://localhost:4321",
"auth_method": "oauth"
},
{
"model_name": "llama3",
"model": "ollama/llama3",
"api_base": "http://localhost:11434/v1"
},
{
"model_name": "mistral-small",
"model": "mistral/mistral-small-latest",
"api_base": "https://api.mistral.ai/v1"
},
{
"model_name": "deepseek-v3.2",
"model": "avian/deepseek/deepseek-v3.2",
"api_base": "https://api.avian.io/v1"
},
{
"model_name": "kimi-k2.5",
"model": "avian/moonshotai/kimi-k2.5",
"api_base": "https://api.avian.io/v1"
},
{
"model_name": "MiniMax-M2.5",
"model": "minimax/MiniMax-M2.5",
"api_base": "https://api.minimaxi.com/v1",
"extra_body": {
"reasoning_split": true
}
},
{
"model_name": "LongCat-Flash-Thinking",
"model": "longcat/LongCat-Flash-Thinking",
"api_base": "https://api.longcat.chat/openai"
},
{
"model_name": "modelscope-qwen",
"model": "modelscope/Qwen/Qwen3-235B-A22B-Instruct-2507",
"api_base": "https://api-inference.modelscope.cn/v1"
},
{
"model_name": "local-model",
"model": "vllm/custom-model",
"api_base": "http://localhost:8000/v1",
"enabled": true
},
{
"model_name": "meta-llama-llama-3.3-70b-instruct:free",
"model": "google/gemma-3-27b-it:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "qwen-qwen3-coder:free",
"model": "qwen/qwen3-coder:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "mistralai-pixtral-12b:free",
"model": "mistralai/pixtral-12b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-4-340b-instruct:free",
"model": "nvidia/nemotron-4-340b-instruct:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "azure-gpt5",
"model": "azure/my-gpt5-deployment",
"api_base": "https://your-resource.openai.azure.com"
},
{
"model_name": "google-gemma-4-26b-a4b-it:free",
"model": "google/gemma-4-26b-a4b-it:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "google-gemma-4-31b-it:free",
"model": "google/gemma-4-31b-it:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-3-super-120b-a12b:free",
"model": "nvidia/nemotron-3-super-120b-a12b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia/nemotron-3-super-120b-a12b",
"model": "nvidia/nemotron-3-super-120b-a12b",
"api_base": "https://integrate.api.nvidia.com/v1",
"api_keys": ["env://NVIDIA_API_KEY"]
},
{
"model_name": "qwen-qwen3-next-80b-a3b-instruct:free",
"model": "qwen/qwen3-next-80b-a3b-instruct:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-nano-9b-v2:free",
"model": "nvidia/nemotron-nano-9b-v2:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "openrouter-elephant-alpha",
"model": "openrouter/elephant-alpha",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "minimax-minimax-m2.5:free",
"model": "minimax/minimax-m2.5:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "arcee-ai-trinity-large-preview:free",
"model": "arcee-ai/trinity-large-preview:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "google-lyria-3-pro-preview",
"model": "google/lyria-3-pro-preview",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "google-lyria-3-clip-preview",
"model": "google/lyria-3-clip-preview",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-3-nano-30b-a3b:free",
"model": "nvidia/nemotron-3-nano-30b-a3b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-nano-12b-v2-vl:free",
"model": "nvidia/nemotron-nano-12b-v2-vl:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "openai-gpt-oss-120b:free",
"model": "openai/gpt-oss-120b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "openai-gpt-oss-20b:free",
"model": "openai/gpt-oss-20b:free",
"protocol": "openrouter",
"enabled": true
}
]
}
],
"gateway": {
"host": "0.0.0.0",
"port": 18790,
"hot_reload": true,
"log_level": "info"
},
"hooks": {
"enabled": false,
"defaults": {
"observer_timeout_ms": 500,
"interceptor_timeout_ms": 5000,
"approval_timeout_ms": 60000
},
"builtins": {
"security_behavior": {
"enabled": true,
"priority": 70,
"config": {
"max_tool_calls": 50,
"max_total_bytes": 10485760
}
},
"security_canary": {
"enabled": true,
"priority": 100
},
"security_ipia": {
"enabled": true,
"priority": 60
},
"security_pii": {
"enabled": true,
"priority": 90
},
"security_policy": {
"enabled": true,
"priority": 80,
"config": {
"allowed_tools": {
"append_file": true,
"edit_file": true,
"exec": true,
"freeride": true,
"github": true,
"list_dir": true,
"message": true,
"read_file": true,
"spawn": true,
"subagent": true,
"summarize": true,
"weather": true,
"write_file": true
}
}
}
}
},
"tools": {
"allow_read_paths": null,
"allow_write_paths": null,
"filter_sensitive_data": true,
"filter_min_length": 8,
"web": {
"enabled": true,
"brave": {
"enabled": false,
"max_results": 5
},
"tavily": {
"enabled": false,
"base_url": "",
"max_results": 5
},
"sogou": {
"enabled": true,
"max_results": 5
},
"duckduckgo": {
"enabled": true,
"max_results": 5
},
"perplexity": {
"enabled": false,
"max_results": 5
},
"searxng": {
"enabled": false,
"base_url": "",
"max_results": 5
},
"glm_search": {
"enabled": false,
"base_url": "https://open.bigmodel.cn/api/paas/v4/web_search",
"search_engine": "search_std",
"max_results": 5
},
"baidu_search": {
"enabled": false,
"base_url": "https://qianfan.baidubce.com/v2/ai_search/web_search",
"max_results": 10
},
"provider": "auto",
"prefer_native": true,
"fetch_limit_bytes": 10485760,
"format": "plaintext"
},
"cron": {
"enabled": true,
"exec_timeout_minutes": 5,
"allow_command": true
},
"exec": {
"enabled": true,
"enable_deny_patterns": true,
"allow_remote": true,
"custom_deny_patterns": null,
"custom_allow_patterns": null,
"timeout_seconds": 60
},
"skills": {
"enabled": true,
"registries": {
"clawhub": {
"base_url": "https://clawhub.ai",
"download_path": "",
"enabled": true,
"max_response_size": 0,
"max_zip_size": 0,
"search_path": "",
"skills_path": "",
"timeout": 0
},
"github": {
"base_url": "https://github.com",
"enabled": true
}
},
"github": {},
"max_concurrent_searches": 2,
"search_cache": {
"max_size": 50,
"ttl_seconds": 300
}
},
"media_cleanup": {
"enabled": true,
"max_age_minutes": 30,
"interval_minutes": 5
},
"mcp": {
"enabled": false,
"discovery": {
"enabled": false,
"ttl": 5,
"max_search_results": 5,
"use_bm25": true,
"use_regex": false
},
"max_inline_text_chars": 16384
},
"append_file": {
"enabled": true
},
"edit_file": {
"enabled": true
},
"find_skills": {
"enabled": true
},
"i2c": {
"enabled": false
},
"install_skill": {
"enabled": true
},
"list_dir": {
"enabled": true
},
"message": {
"enabled": true
},
"read_file": {
"enabled": true,
"mode": "bytes",
"max_read_file_size": 65536
},
"send_file": {
"enabled": true
},
"send_tts": {
"enabled": false
},
"spawn": {
"enabled": true
},
"spawn_status": {
"enabled": false
},
"spi": {
"enabled": false
},
"subagent": {
"enabled": true
},
"web_fetch": {
"enabled": true
},
"write_file": {
"enabled": true
}
},
"heartbeat": {
"enabled": true,
"interval": 30
},
"devices": {
"enabled": false,
"monitor_usb": true
},
"voice": {
"echo_transcription": false
},
"build_info": {
"version": "0.1.0",
"git_commit": "054b55fd",
"build_time": "2026-03-23T10:15:13+0100",
"go_version": "go1.26.1"
}
}

825
picoclaw-config.json Normal file
View file

@ -0,0 +1,825 @@
{
"session": {
"dimensions": [
"chat"
]
},
"version": 3,
"isolation": {},
"agents": {
"defaults": {
"workspace": "/home/stevef/.picoclaw/workspace",
"restrict_to_workspace": true,
"allow_read_outside_workspace": false,
"provider": "openai",
"model_name": "meta-llama-llama-3.3-70b-instruct:free",
"model_fallbacks": [
"google-gemma-3-27b-it:free",
"qwen-qwen3-coder:free",
"nvidia-nemotron-4-340b-instruct:free",
"mistralai-pixtral-12b:free",
"openrouter-elephant-alpha",
"google-gemma-4-26b-a4b-it:free"
],
"max_tokens": 32768,
"max_tool_iterations": 50,
"summarize_message_threshold": 20,
"summarize_token_percent": 75,
"steering_mode": "one-at-a-time",
"subturn": {
"max_depth": 10,
"max_concurrent": 5,
"default_timeout_minutes": 20,
"default_token_budget": 100000,
"concurrency_timeout_sec": 10
},
"tool_feedback": {
"enabled": true,
"max_args_length": 300
},
"split_on_marker": false
}
},
"channel_list": {
"dingtalk": {
"enabled": false,
"type": "dingtalk",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"client_id": ""
}
},
"discord": {
"enabled": false,
"type": "discord",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"proxy": "",
"mention_only": false
}
},
"feishu": {
"enabled": false,
"type": "feishu",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"app_id": "",
"random_reaction_emoji": [
""
],
"is_lark": false
}
},
"irc": {
"enabled": false,
"type": "irc",
"allow_from": [
""
],
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"server": "",
"tls": false,
"nick": "",
"sasl_user": "",
"channels": [
""
]
}
},
"line": {
"enabled": false,
"type": "line",
"reasoning_channel_id": "",
"group_trigger": {
"mention_only": true
},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"webhook_host": "0.0.0.0",
"webhook_port": 18791,
"webhook_path": "/webhook/line"
}
},
"maixcam": {
"enabled": false,
"type": "maixcam",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"host": "0.0.0.0",
"port": 18790
}
},
"matrix": {
"enabled": false,
"type": "matrix",
"reasoning_channel_id": "",
"group_trigger": {
"mention_only": true
},
"typing": {},
"placeholder": {
"enabled": true,
"text": [
"Thinking... 💭"
]
},
"settings": {
"homeserver": "https://matrix.org",
"user_id": "",
"join_on_invite": true
}
},
"onebot": {
"enabled": false,
"type": "onebot",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"ws_url": "ws://127.0.0.1:3001",
"reconnect_interval": 5,
"group_trigger_prefix": null
}
},
"pico": {
"enabled": false,
"type": "pico",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"ping_interval": 30,
"read_timeout": 60,
"write_timeout": 10,
"max_connections": 100
}
},
"pico_client": {
"enabled": false,
"type": "pico_client",
"allow_from": [
""
],
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"url": ""
}
},
"qq": {
"enabled": false,
"type": "qq",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"app_id": "",
"max_message_length": 2000,
"max_base64_file_size_mib": 0,
"send_markdown": false
}
},
"slack": {
"enabled": false,
"type": "slack",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {}
},
"telegram": {
"enabled": true,
"type": "telegram",
"allow_from": [
"-5274005272",
"8271300679"
],
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {
"enabled": true
},
"placeholder": {
"enabled": true,
"text": [
"Thinking... 💭"
]
},
"settings": {
"base_url": "",
"proxy": "",
"streaming": {
"enabled": true,
"throttle_seconds": 3,
"min_growth_chars": 200
},
"use_markdown_v2": false
}
},
"vk": {
"enabled": false,
"type": "vk",
"allow_from": [
""
],
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"group_id": 0
}
},
"wecom": {
"enabled": false,
"type": "wecom",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"bot_id": "",
"websocket_url": "wss://openws.work.weixin.qq.com",
"send_thinking_message": true
}
},
"weixin": {
"enabled": false,
"type": "weixin",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"base_url": "https://ilinkai.weixin.qq.com/",
"cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c",
"proxy": ""
}
},
"whatsapp": {
"enabled": false,
"type": "whatsapp",
"reasoning_channel_id": "",
"group_trigger": {},
"typing": {},
"placeholder": {
"enabled": false
},
"settings": {
"bridge_url": "ws://localhost:3001",
"use_native": false,
"session_store_path": ""
}
}
},
"model_list": [
{
"model_name": "glm-4.7",
"model": "zhipu/glm-4.7",
"api_base": "https://open.bigmodel.cn/api/paas/v4"
},
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_base": "https://api.openai.com/v1"
},
{
"model_name": "claude-sonnet-4.6",
"model": "anthropic/claude-sonnet-4.6",
"api_base": "https://api.anthropic.com/v1"
},
{
"model_name": "deepseek-chat",
"model": "deepseek/deepseek-chat",
"api_base": "https://api.deepseek.com/v1"
},
{
"model_name": "gemini-2.0-flash",
"model": "gemini/gemini-2.0-flash-exp",
"api_base": "https://generativelanguage.googleapis.com/v1beta"
},
{
"model_name": "qwen-plus",
"model": "qwen/qwen-plus",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1"
},
{
"model_name": "moonshot-v1-8k",
"model": "moonshot/moonshot-v1-8k",
"api_base": "https://api.moonshot.cn/v1"
},
{
"model_name": "llama-3.3-70b",
"model": "groq/llama-3.3-70b-versatile",
"api_base": "https://api.groq.com/openai/v1"
},
{
"model_name": "openrouter-nemotron",
"model": "nvidia/nemotron-3-super-120b-a12b:free",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-elephant",
"model": "openrouter/elephant-alpha",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-free",
"model": "arcee-ai/trinity-large-preview:free",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-auto",
"model": "auto",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "openrouter-gpt-5.4",
"model": "openai/gpt-5.4",
"protocol": "openrouter",
"api_base": "https://openrouter.ai/api/v1"
},
{
"model_name": "nemotron-4-340b",
"model": "nvidia/nemotron-4-340b-instruct",
"api_base": "https://integrate.api.nvidia.com/v1"
},
{
"model_name": "azure-grok",
"model": "openai/grok-4-fast-non-reasoning",
"api_base": "https://TestSJF.openai.azure.com/openai/v1/",
"enabled": true
},
{
"model_name": "cerebras-llama-3.3-70b",
"model": "cerebras/llama-3.3-70b",
"api_base": "https://api.cerebras.ai/v1"
},
{
"model_name": "vivgrid-auto",
"model": "vivgrid/auto",
"api_base": "https://api.vivgrid.com/v1"
},
{
"model_name": "ark-code-latest",
"model": "volcengine/ark-code-latest",
"api_base": "https://ark.cn-beijing.volces.com/api/v3"
},
{
"model_name": "doubao-pro",
"model": "volcengine/doubao-pro-32k",
"api_base": "https://ark.cn-beijing.volces.com/api/v3"
},
{
"model_name": "deepseek-v3",
"model": "shengsuanyun/deepseek-v3",
"api_base": "https://api.shengsuanyun.com/v1"
},
{
"model_name": "copilot-gpt-5.4",
"model": "github-copilot/gpt-5.4",
"api_base": "http://localhost:4321",
"auth_method": "oauth"
},
{
"model_name": "llama3",
"model": "ollama/llama3",
"api_base": "http://localhost:11434/v1"
},
{
"model_name": "mistral-small",
"model": "mistral/mistral-small-latest",
"api_base": "https://api.mistral.ai/v1"
},
{
"model_name": "deepseek-v3.2",
"model": "avian/deepseek/deepseek-v3.2",
"api_base": "https://api.avian.io/v1"
},
{
"model_name": "kimi-k2.5",
"model": "avian/moonshotai/kimi-k2.5",
"api_base": "https://api.avian.io/v1"
},
{
"model_name": "MiniMax-M2.5",
"model": "minimax/MiniMax-M2.5",
"api_base": "https://api.minimaxi.com/v1",
"extra_body": {
"reasoning_split": true
}
},
{
"model_name": "LongCat-Flash-Thinking",
"model": "longcat/LongCat-Flash-Thinking",
"api_base": "https://api.longcat.chat/openai"
},
{
"model_name": "modelscope-qwen",
"model": "modelscope/Qwen/Qwen3-235B-A22B-Instruct-2507",
"api_base": "https://api-inference.modelscope.cn/v1"
},
{
"model_name": "local-model",
"model": "vllm/custom-model",
"api_base": "http://localhost:8000/v1",
"enabled": true
},
{
"model_name": "meta-llama-llama-3.3-70b-instruct:free",
"model": "google/gemma-3-27b-it:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "qwen-qwen3-coder:free",
"model": "qwen/qwen3-coder:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "mistralai-pixtral-12b:free",
"model": "mistralai/pixtral-12b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-4-340b-instruct:free",
"model": "nvidia/nemotron-4-340b-instruct:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "azure-gpt5",
"model": "azure/my-gpt5-deployment",
"api_base": "https://your-resource.openai.azure.com"
},
{
"model_name": "google-gemma-4-26b-a4b-it:free",
"model": "google/gemma-4-26b-a4b-it:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "google-gemma-4-31b-it:free",
"model": "google/gemma-4-31b-it:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-3-super-120b-a12b:free",
"model": "nvidia/nemotron-3-super-120b-a12b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "qwen-qwen3-next-80b-a3b-instruct:free",
"model": "qwen/qwen3-next-80b-a3b-instruct:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-nano-9b-v2:free",
"model": "nvidia/nemotron-nano-9b-v2:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "openrouter-elephant-alpha",
"model": "openrouter/elephant-alpha",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "minimax-minimax-m2.5:free",
"model": "minimax/minimax-m2.5:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "arcee-ai-trinity-large-preview:free",
"model": "arcee-ai/trinity-large-preview:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "google-lyria-3-pro-preview",
"model": "google/lyria-3-pro-preview",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "google-lyria-3-clip-preview",
"model": "google/lyria-3-clip-preview",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-3-nano-30b-a3b:free",
"model": "nvidia/nemotron-3-nano-30b-a3b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "nvidia-nemotron-nano-12b-v2-vl:free",
"model": "nvidia/nemotron-nano-12b-v2-vl:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "openai-gpt-oss-120b:free",
"model": "openai/gpt-oss-120b:free",
"protocol": "openrouter",
"enabled": true
},
{
"model_name": "openai-gpt-oss-20b:free",
"model": "openai/gpt-oss-20b:free",
"protocol": "openrouter",
"enabled": true
}
],
"gateway": {
"host": "0.0.0.0",
"port": 18790,
"hot_reload": true,
"log_level": "info"
},
"hooks": {
"enabled": false,
"defaults": {
"observer_timeout_ms": 500,
"interceptor_timeout_ms": 5000,
"approval_timeout_ms": 60000
},
"builtins": {
"security_behavior": {
"enabled": true,
"priority": 70,
"config": {
"max_tool_calls": 50,
"max_total_bytes": 10485760
}
},
"security_canary": {
"enabled": true,
"priority": 100
},
"security_ipia": {
"enabled": true,
"priority": 60
},
"security_pii": {
"enabled": true,
"priority": 90
},
"security_policy": {
"enabled": true,
"priority": 80,
"config": {
"allowed_tools": {
"append_file": true,
"edit_file": true,
"exec": true,
"freeride": true,
"github": true,
"list_dir": true,
"message": true,
"read_file": true,
"spawn": true,
"subagent": true,
"summarize": true,
"weather": true,
"write_file": true
}
}
}
}
},
"tools": {
"allow_read_paths": null,
"allow_write_paths": null,
"filter_sensitive_data": true,
"filter_min_length": 8,
"web": {
"enabled": true,
"brave": {
"enabled": false,
"max_results": 5
},
"tavily": {
"enabled": false,
"base_url": "",
"max_results": 5
},
"sogou": {
"enabled": true,
"max_results": 5
},
"duckduckgo": {
"enabled": true,
"max_results": 5
},
"perplexity": {
"enabled": false,
"max_results": 5
},
"searxng": {
"enabled": false,
"base_url": "",
"max_results": 5
},
"glm_search": {
"enabled": false,
"base_url": "https://open.bigmodel.cn/api/paas/v4/web_search",
"search_engine": "search_std",
"max_results": 5
},
"baidu_search": {
"enabled": false,
"base_url": "https://qianfan.baidubce.com/v2/ai_search/web_search",
"max_results": 10
},
"provider": "auto",
"prefer_native": true,
"fetch_limit_bytes": 10485760,
"format": "plaintext"
},
"cron": {
"enabled": true,
"exec_timeout_minutes": 5,
"allow_command": true
},
"exec": {
"enabled": true,
"enable_deny_patterns": true,
"allow_remote": true,
"custom_deny_patterns": null,
"custom_allow_patterns": null,
"timeout_seconds": 60
},
"skills": {
"enabled": true,
"registries": {
"clawhub": {
"base_url": "https://clawhub.ai",
"download_path": "",
"enabled": true,
"max_response_size": 0,
"max_zip_size": 0,
"search_path": "",
"skills_path": "",
"timeout": 0
},
"github": {
"base_url": "https://github.com",
"enabled": true
}
},
"github": {},
"max_concurrent_searches": 2,
"search_cache": {
"max_size": 50,
"ttl_seconds": 300
}
},
"media_cleanup": {
"enabled": true,
"max_age_minutes": 30,
"interval_minutes": 5
},
"mcp": {
"enabled": false,
"discovery": {
"enabled": false,
"ttl": 5,
"max_search_results": 5,
"use_bm25": true,
"use_regex": false
},
"max_inline_text_chars": 16384
},
"append_file": {
"enabled": true
},
"edit_file": {
"enabled": true
},
"find_skills": {
"enabled": true
},
"i2c": {
"enabled": false
},
"install_skill": {
"enabled": true
},
"list_dir": {
"enabled": true
},
"message": {
"enabled": true
},
"read_file": {
"enabled": true,
"mode": "bytes",
"max_read_file_size": 65536
},
"send_file": {
"enabled": true
},
"send_tts": {
"enabled": false
},
"spawn": {
"enabled": true
},
"spawn_status": {
"enabled": false
},
"spi": {
"enabled": false
},
"subagent": {
"enabled": true
},
"web_fetch": {
"enabled": true
},
"write_file": {
"enabled": true
}
},
"heartbeat": {
"enabled": true,
"interval": 30
},
"devices": {
"enabled": false,
"monitor_usb": true
},
"voice": {
"echo_transcription": false
},
"build_info": {
"version": "0.1.0",
"git_commit": "054b55fd",
"build_time": "2026-03-23T10:15:13+0100",
"go_version": "go1.26.1"
}
}

View file

@ -117,6 +117,9 @@ func NewAgentInstance(
if cfg.Tools.IsToolEnabled("append_file") {
toolsRegistry.Register(tools.NewAppendFileTool(workspace, restrict, allowWritePaths))
}
if cfg.Tools.IsToolEnabled("freeride") {
toolsRegistry.Register(tools.NewFreeRideTool(config.GetDefaultConfigPath(), nil))
}
sessionsDir := filepath.Join(workspace, "sessions")
sessions := initSessionStore(sessionsDir)
@ -272,7 +275,7 @@ func populateCandidateProvidersFromNames(
}
modelID := mc.Model
protocol := mc.Protocol
protocol := strings.ToLower(strings.TrimSpace(mc.Protocol))
// If protocol is not explicitly set, extract it from the model ID
if protocol == "" {

View file

@ -57,6 +57,10 @@ func NewAgentLoop(
if defaultAgent != nil {
logger.Debugf("Initializing State Manager for agent %s", defaultAgent.ID)
stateManager = state.NewManager(defaultAgent.Workspace)
// Enable persistent cooldowns so that model rate limits/failures
// are remembered across agent restarts.
cooldownPath := filepath.Join(filepath.Dir(filepath.Clean(defaultAgent.Workspace)), "cooldowns.json")
_ = cooldown.SetPersistencePath(cooldownPath)
}
eventBus := NewEventBus()

View file

@ -18,8 +18,6 @@ const (
TypeError = "error"
TypePong = "pong"
PicoTokenPrefix = "pico-"
PayloadKeyContent = "content"
PayloadKeyThought = "thought"

View file

@ -823,6 +823,7 @@ type ToolsConfig struct {
Subagent ToolConfig `json:"subagent" yaml:"-" envPrefix:"PICOCLAW_TOOLS_SUBAGENT_"`
WebFetch ToolConfig `json:"web_fetch" yaml:"-" envPrefix:"PICOCLAW_TOOLS_WEB_FETCH_"`
WriteFile ToolConfig `json:"write_file" yaml:"-" envPrefix:"PICOCLAW_TOOLS_WRITE_FILE_"`
Freeride ToolConfig `json:"freeride" yaml:"-" envPrefix:"PICOCLAW_TOOLS_FREERIDE_"`
}
// IsFilterSensitiveDataEnabled returns true if sensitive data filtering is enabled
@ -1512,6 +1513,8 @@ func (t *ToolsConfig) IsToolEnabled(name string) bool {
return t.SendTTS.Enabled
case "write_file":
return t.WriteFile.Enabled
case "freeride":
return t.Freeride.Enabled
case "mcp":
return t.MCP.Enabled
default:

View file

@ -55,3 +55,10 @@ func GetHome() string {
}
return homePath
}
func GetDefaultConfigPath() string {
if cfgPath := os.Getenv(EnvConfig); cfgPath != "" {
return cfgPath
}
return filepath.Join(GetHome(), "config.json")
}

View file

@ -9,7 +9,6 @@ import (
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
@ -27,7 +26,7 @@ import (
_ "github.com/sipeed/picoclaw/pkg/channels/line"
_ "github.com/sipeed/picoclaw/pkg/channels/maixcam"
_ "github.com/sipeed/picoclaw/pkg/channels/onebot"
"github.com/sipeed/picoclaw/pkg/channels/pico"
_ "github.com/sipeed/picoclaw/pkg/channels/pico"
_ "github.com/sipeed/picoclaw/pkg/channels/qq"
_ "github.com/sipeed/picoclaw/pkg/channels/slack"
_ "github.com/sipeed/picoclaw/pkg/channels/teams_webhook"
@ -347,8 +346,6 @@ func executeReload(
) error {
defer runningServices.reloading.Store(false)
overridePicoToken(newCfg, runningServices.authToken)
return handleConfigReload(ctx, agentLoop, newCfg, provider, runningServices, msgBus, allowEmptyStartup, debug)
}
@ -417,8 +414,6 @@ func setupAndStartServices(
fms.Start()
}
overridePicoToken(cfg, authToken)
runningServices.ChannelManager, err = channels.NewManager(cfg, msgBus, runningServices.MediaStore)
if err != nil {
if fms, ok := runningServices.MediaStore.(*media.FileMediaStore); ok {
@ -819,23 +814,6 @@ func setupCronTool(
return cronService, nil
}
// overridePicoToken replaces the pico channel token with the one from the PID file.
// The PID file is the single source of truth for the pico auth token;
// it is generated once at gateway startup and remains unchanged across reloads.
func overridePicoToken(cfg *config.Config, token string) {
picoBC := cfg.Channels.GetByType(config.ChannelPico)
if picoBC == nil || !picoBC.Enabled {
return
}
var picoCfg config.PicoSettings
picoBC.Decode(&picoCfg)
picoToken := picoCfg.Token.String()
if picoToken == "" || strings.HasPrefix(picoToken, pico.PicoTokenPrefix) {
return
}
picoCfg.SetToken(pico.PicoTokenPrefix + token + picoToken)
}
func createHeartbeatHandler(agentLoop *agent.AgentLoop) func(prompt, channel, chatID string) *tools.ToolResult {
return func(prompt, channel, chatID string) *tools.ToolResult {
if channel == "" || chatID == "" {

View file

@ -46,6 +46,18 @@ func NewCooldownTracker(storagePath string) *CooldownTracker {
return ct
}
// SetPersistencePath sets the path for state persistence and triggers an immediate load.
func (ct *CooldownTracker) SetPersistencePath(path string) error {
ct.mu.Lock()
ct.storagePath = path
ct.mu.Unlock()
if path != "" {
ct.Load()
}
return nil
}
// MarkFailure records a failure for a provider and sets appropriate cooldown.
// Resets error counts if last failure was more than failureWindow ago.
func (ct *CooldownTracker) MarkFailure(provider string, reason FailoverReason) {

View file

@ -1,11 +1,82 @@
package providers
import (
"os"
"path/filepath"
"sync"
"testing"
"time"
)
func TestCooldown_Persistence(t *testing.T) {
tempDir := t.TempDir()
persistPath := filepath.Join(tempDir, "cooldowns.json")
now := time.Now()
ct, current := newTestTracker(now)
if err := ct.SetPersistencePath(persistPath); err != nil {
t.Fatalf("SetPersistencePath failed: %v", err)
}
// 1. Mark a failure and verify it saves
ct.MarkFailure("openai", FailoverRateLimit) // 1 min cooldown
if ct.IsAvailable("openai") {
t.Error("openai should be in cooldown")
}
if _, err := os.Stat(persistPath); os.IsNotExist(err) {
t.Fatal("persistence file was not created")
}
// 2. Create a NEW tracker and load the file
ct2, _ := newTestTracker(now)
if err := ct2.SetPersistencePath(persistPath); err != nil {
t.Fatalf("SetPersistencePath on second tracker failed: %v", err)
}
if ct2.IsAvailable("openai") {
t.Error("newly loaded tracker should still have openai in cooldown")
}
if ct2.ErrorCount("openai") != 1 {
t.Errorf("error count = %d, want 1", ct2.ErrorCount("openai"))
}
// 3. Mark success and verify it clears and persists
ct2.MarkSuccess("openai")
if !ct2.IsAvailable("openai") {
t.Error("openai should be available after success")
}
ct3, _ := newTestTracker(now)
if err := ct3.SetPersistencePath(persistPath); err != nil {
t.Fatalf("SetPersistencePath on third tracker failed: %v", err)
}
if !ct3.IsAvailable("openai") {
t.Error("fourth tracker should see openai as available after success was persisted")
}
// 4. Verify expiration filtering
ct3.MarkFailure("anthropic", FailoverRateLimit) // 1 min cooldown
*current = now.Add(2 * time.Minute) // Advance time past expiration
ct4, ct4Current := newTestTracker(*current) // ct4 sees the future
if err := ct4.SetPersistencePath(persistPath); err != nil {
t.Fatalf("SetPersistencePath on fourth tracker failed: %v", err)
}
// Since current time (2 min later) is past the 1 min cooldown, it should be filtered out on load
if !ct4.IsAvailable("anthropic") {
t.Error("anthropic should be available (expired cooldown filtered on load)")
}
// Verify that MarkFailure on ct4 uses the correct time
ct4.MarkFailure("groq", FailoverRateLimit)
if ct4.IsAvailable("groq") {
t.Error("groq should be in cooldown on ct4")
}
_ = ct4Current // keep compiler happy
}
func newTestTracker(now time.Time) (*CooldownTracker, *time.Time) {
current := now
ct := NewCooldownTracker("")

View file

@ -257,6 +257,8 @@ func classifyByStatus(status int) FailoverReason {
return FailoverRateLimit
case status == 400:
return FailoverFormat
case status == 404:
return FailoverNotFound
case transientStatusCodes[status]:
return FailoverTimeout
}

View file

@ -63,6 +63,7 @@ func TestClassifyError_StatusCodes(t *testing.T) {
{523, FailoverTimeout},
{524, FailoverTimeout},
{529, FailoverTimeout},
{404, FailoverNotFound},
}
for _, tt := range tests {
@ -427,6 +428,7 @@ func TestFailoverError_IsRetriable(t *testing.T) {
{FailoverOverloaded, true},
{FailoverFormat, false},
{FailoverContextOverflow, false},
{FailoverNotFound, true},
{FailoverUnknown, true},
}

View file

@ -124,6 +124,7 @@ func isKnownProtocol(p string) bool {
func ExtractProtocol(model string) (protocol, modelID string) {
model = strings.TrimSpace(model)
p, m, found := strings.Cut(model, "/")
p = strings.ToLower(strings.TrimSpace(p))
if !found {
return "openai", model
}
@ -149,7 +150,7 @@ func ResolveAPIBase(cfg *config.ModelConfig) string {
}
protocol, _ := ExtractProtocol(cfg.Model)
if cfg.Protocol != "" {
protocol = cfg.Protocol
protocol = strings.ToLower(strings.TrimSpace(cfg.Protocol))
}
return strings.TrimRight(getDefaultAPIBase(protocol), "/")
}
@ -171,7 +172,7 @@ func CreateProviderFromConfig(cfg *config.ModelConfig) (LLMProvider, string, err
protocol, modelID := ExtractProtocol(cfg.Model)
if cfg.Protocol != "" {
protocol = cfg.Protocol
protocol = strings.ToLower(strings.TrimSpace(cfg.Protocol))
// If protocol was explicitly set, modelID should be the full model string
// unless it was already prefixed with the SAME protocol.
// Strip protocol prefix if it matches the model start EXCPET for nvidia

View file

@ -79,6 +79,7 @@ const (
FailoverFormat FailoverReason = "format"
FailoverContextOverflow FailoverReason = "context_overflow"
FailoverOverloaded FailoverReason = "overloaded"
FailoverNotFound FailoverReason = "not_found"
FailoverUnknown FailoverReason = "unknown"
)

View file

@ -41,14 +41,19 @@ func (t *FreeRideTool) Parameters() map[string]any {
"properties": map[string]any{
"command": map[string]any{
"type": "string",
"enum": []string{"auto", "list", "status"},
"description": "The command to run: 'auto' (configures models), 'list' (shows free models), 'status' (checks current setup)",
"enum": []string{"auto", "list", "status", "settimeout"},
"description": "The command to run: 'auto' (configures models), 'list' (shows free models), 'status' (checks current setup), 'settimeout' (sets request timeout)",
},
"limit": map[string]any{
"type": "integer",
"description": "For 'list', how many models to show. For 'auto', how many fallbacks to configure.",
"default": 5,
},
"timeout": map[string]any{
"type": "integer",
"description": "For 'settimeout', the request timeout in seconds (default 300)",
"default": 300,
},
},
"required": []string{"command"},
}
@ -72,6 +77,13 @@ func (t *FreeRideTool) Execute(ctx context.Context, args map[string]any) *ToolRe
if l, ok := args["limit"].(float64); ok {
limit = int(l)
}
timeout := 300
switch v := args["timeout"].(type) {
case float64:
timeout = int(v)
case int:
timeout = v
}
switch cmd {
case "list":
@ -80,6 +92,8 @@ func (t *FreeRideTool) Execute(ctx context.Context, args map[string]any) *ToolRe
return t.handleAuto(ctx, limit)
case "status":
return t.handleStatus()
case "settimeout":
return t.handleSetTimeout(timeout)
default:
return ErrorResult(fmt.Sprintf("unknown command: %s", cmd))
}
@ -178,7 +192,17 @@ func scoreModel(m openRouterModel) float64 {
}
// Provider Trust (10%) - hardcoded list of trusted names
trustNames := []string{"google", "meta", "nvidia", "mistral", "anthropic", "openai", "microsoft", "qwen", "deepseek"}
trustNames := []string{
"google",
"meta",
"nvidia",
"mistral",
"anthropic",
"openai",
"microsoft",
"qwen",
"deepseek",
}
for _, name := range trustNames {
if strings.Contains(strings.ToLower(m.ID), name) {
score += 0.1
@ -210,7 +234,7 @@ func (t *FreeRideTool) handleList(ctx context.Context, limit int) *ToolResult {
sb.WriteString(fmt.Sprintf(" Parameters: %s\n\n", strings.Join(m.SupportedParameters, ", ")))
}
return UserResult(sb.String()).WithResponseHandled().WithResponseHandled()
return UserResult(sb.String())
}
func (t *FreeRideTool) handleAuto(ctx context.Context, limit int) *ToolResult {
@ -229,7 +253,8 @@ func (t *FreeRideTool) handleAuto(ctx context.Context, limit int) *ToolResult {
}
// 1. Add models to ModelList if not present
var addedModels []string
// 2. Collect all valid free models for fallbacks (new AND existing)
var fallbackModels []string
for i, m := range models {
if i >= limit {
break
@ -244,14 +269,14 @@ func (t *FreeRideTool) handleAuto(ctx context.Context, limit int) *ToolResult {
}
mc.SetAPIKey("env://OPENROUTER_API_KEY")
cfgObj.ModelList = append(cfgObj.ModelList, mc)
addedModels = append(addedModels, modelName)
}
fallbackModels = append(fallbackModels, modelName)
}
// 2. Set fallbacks for the default agent
if len(addedModels) > 0 {
if len(fallbackModels) > 0 {
// Update AgentDefaults fallbacks
cfgObj.Agents.Defaults.ModelFallbacks = append(cfgObj.Agents.Defaults.ModelFallbacks, addedModels...)
cfgObj.Agents.Defaults.ModelFallbacks = append(cfgObj.Agents.Defaults.ModelFallbacks, fallbackModels...)
// Deduplicate fallbacks
cfgObj.Agents.Defaults.ModelFallbacks = uniqueStrings(cfgObj.Agents.Defaults.ModelFallbacks)
@ -259,7 +284,11 @@ func (t *FreeRideTool) handleAuto(ctx context.Context, limit int) *ToolResult {
return ErrorResult(fmt.Errorf("failed to save config: %w", err).Error())
}
msg := fmt.Sprintf("Success! Added %d free models as fallbacks: %s.\n", len(addedModels), strings.Join(addedModels, ", "))
msg := fmt.Sprintf(
"Success! Added %d free models as fallbacks: %s.\n",
len(fallbackModels),
strings.Join(fallbackModels, ", "),
)
msg += "Re-loading configuration to apply changes..."
if t.reloadFunc != nil {
@ -268,10 +297,12 @@ func (t *FreeRideTool) handleAuto(ctx context.Context, limit int) *ToolResult {
}
}
return UserResult(msg).WithResponseHandled().WithResponseHandled()
return UserResult(msg)
}
return UserResult("No new free models to add. Your configuration is up to date.").WithResponseHandled().WithResponseHandled()
return UserResult(
"No new free models to add. Your configuration is up to date.",
)
}
func (t *FreeRideTool) handleStatus() *ToolResult {
@ -294,7 +325,47 @@ func (t *FreeRideTool) handleStatus() *ToolResult {
}
sb.WriteString(fmt.Sprintf("- Managed Free Models: %d\n", openRouterCount))
return UserResult(sb.String()).WithResponseHandled().WithResponseHandled()
return UserResult(sb.String())
}
func (t *FreeRideTool) handleSetTimeout(timeoutSeconds int) *ToolResult {
if timeoutSeconds < 30 {
return ErrorResult("timeout must be at least 30 seconds")
}
cfgObj, err := config.LoadConfig(t.configPath)
if err != nil {
return ErrorResult(fmt.Errorf("failed to load config: %w", err).Error())
}
updated := 0
for _, mc := range cfgObj.ModelList {
// Only update OpenRouter models (free models)
protocol := strings.ToLower(mc.Protocol)
if protocol == "openrouter" {
mc.RequestTimeout = timeoutSeconds
updated++
}
}
if updated == 0 {
return ErrorResult("no OpenRouter models found in config. Run 'freeride auto' first.")
}
if err := config.SaveConfig(t.configPath, cfgObj); err != nil {
return ErrorResult(fmt.Errorf("failed to save config: %w", err).Error())
}
msg := fmt.Sprintf("Set request timeout to %d seconds for %d OpenRouter models.\n", timeoutSeconds, updated)
msg += "Re-loading configuration to apply changes..."
if t.reloadFunc != nil {
if err := t.reloadFunc(); err != nil {
return ErrorResult(fmt.Sprintf("%s\nFailed to reload: %v", msg, err))
}
}
return UserResult(msg)
}
func modelExists(cfg *config.Config, modelName string) bool {
@ -308,8 +379,13 @@ func modelExists(cfg *config.Config, modelName string) bool {
func isKnownOpenRouterAlias(cfg *config.Config, modelName string) bool {
for _, m := range cfg.ModelList {
if m.ModelName == modelName && strings.HasPrefix(m.Model, "openrouter/") {
return true
if m.ModelName == modelName {
if strings.HasPrefix(m.Model, "openrouter/") {
return true
}
if strings.ToLower(m.Protocol) == "openrouter" {
return true
}
}
}
return false

View file

@ -156,6 +156,152 @@ func TestFreeRideTool_Auto(t *testing.T) {
}
}
func TestFreeRideTool_SetTimeout(t *testing.T) {
tempDir, err := os.MkdirTemp("", "freeride-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
configPath := filepath.Join(tempDir, "config.json")
initialCfg := &config.Config{
ModelList: []*config.ModelConfig{
{
ModelName: "google-gemini-pro-1.5",
Model: "google/gemini-pro-1.5",
Protocol: "openrouter",
},
{
ModelName: "meta-llama-3-8b",
Model: "meta/llama-3-8b",
Protocol: "openrouter",
},
{
ModelName: "gpt-4o",
Model: "openai/gpt-4o",
Protocol: "openai",
},
},
}
initialCfg.Agents.Defaults.ModelName = "gpt-4o"
if err := config.SaveConfig(configPath, initialCfg); err != nil {
t.Fatalf("failed to save initial config: %v", err)
}
var reloadCalled bool
reloadFunc := func() error {
reloadCalled = true
return nil
}
tool := NewFreeRideTool(configPath, reloadFunc)
result := tool.Execute(context.Background(), map[string]any{
"command": "settimeout",
"timeout": 180,
})
if result.IsError {
t.Fatalf("Expected no error, got %s", result.ForLLM)
}
if !reloadCalled {
t.Errorf("Expected reloadFunc to be called")
}
// Verify config
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("failed to load updated config: %v", err)
}
// Should have updated 2 openrouter models
if cfg.ModelList[0].RequestTimeout != 180 {
t.Errorf("Expected timeout 180 for google-gemini-pro-1.5, got %d", cfg.ModelList[0].RequestTimeout)
}
if cfg.ModelList[1].RequestTimeout != 180 {
t.Errorf("Expected timeout 180 for meta-llama-3-8b, got %d", cfg.ModelList[1].RequestTimeout)
}
// openai model should NOT be updated
if cfg.ModelList[2].RequestTimeout != 0 {
t.Errorf("Expected timeout 0 for gpt-4o (non-openrouter), got %d", cfg.ModelList[2].RequestTimeout)
}
}
func TestFreeRideTool_SetTimeout_NoOpenRouterModels(t *testing.T) {
tempDir, err := os.MkdirTemp("", "freeride-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
configPath := filepath.Join(tempDir, "config.json")
initialCfg := &config.Config{
ModelList: []*config.ModelConfig{
{
ModelName: "gpt-4o",
Model: "openai/gpt-4o",
Protocol: "openai",
},
},
}
if err := config.SaveConfig(configPath, initialCfg); err != nil {
t.Fatalf("failed to save initial config: %v", err)
}
tool := NewFreeRideTool(configPath, nil)
result := tool.Execute(context.Background(), map[string]any{
"command": "settimeout",
"timeout": 180,
})
if !result.IsError {
t.Fatalf("Expected error when no OpenRouter models, got success")
}
if !contains(result.ForLLM, "no OpenRouter models") {
t.Errorf("Expected error message about no OpenRouter models, got %s", result.ForLLM)
}
}
func TestFreeRideTool_SetTimeout_MinimumTooLow(t *testing.T) {
tempDir, err := os.MkdirTemp("", "freeride-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
configPath := filepath.Join(tempDir, "config.json")
initialCfg := &config.Config{
ModelList: []*config.ModelConfig{
{
ModelName: "google-gemini-pro-1.5",
Model: "google/gemini-pro-1.5",
Protocol: "openrouter",
},
},
}
if err := config.SaveConfig(configPath, initialCfg); err != nil {
t.Fatalf("failed to save initial config: %v", err)
}
tool := NewFreeRideTool(configPath, nil)
result := tool.Execute(context.Background(), map[string]any{
"command": "settimeout",
"timeout": 20, // too low
})
if !result.IsError {
t.Fatalf("Expected error when timeout < 30, got success")
}
if !contains(result.ForLLM, "at least 30") {
t.Errorf("Expected error message about minimum 30 seconds, got %s", result.ForLLM)
}
}
type mockTransport struct {
url string
}

28
scratch/check_paths.go Normal file
View file

@ -0,0 +1,28 @@
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/sipeed/picoclaw/pkg/agent"
"github.com/sipeed/picoclaw/pkg/config"
)
func main() {
cfg, err := config.LoadConfig(os.ExpandEnv("$HOME/.picoclaw/config.json"))
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
registry := agent.NewAgentRegistry(cfg, nil)
defaultAgent := registry.GetDefaultAgent()
if defaultAgent == nil {
fmt.Println("No default agent")
return
}
cooldownPath := filepath.Join(filepath.Dir(filepath.Clean(defaultAgent.Workspace)), "cooldowns.json")
fmt.Printf("Workspace: %s\n", defaultAgent.Workspace)
fmt.Printf("Cooldown Path: %s\n", cooldownPath)
}

View file

@ -94,8 +94,6 @@ func (h *Handler) handleUpdateConfig(w http.ResponseWriter, r *http.Request) {
return
}
// Refresh cached pico token in case user changed it.
refreshPicoToken(&cfg)
h.applyRuntimeLogLevel()
logger.Infof("configuration updated successfully")
@ -193,8 +191,6 @@ func (h *Handler) handlePatchConfig(w http.ResponseWriter, r *http.Request) {
return
}
// Refresh cached pico token in case user changed it.
refreshPicoToken(&newCfg)
h.applyRuntimeLogLevel()
logger.Infof("configuration updated successfully")

View file

@ -17,7 +17,6 @@ import (
"syscall"
"time"
"github.com/sipeed/picoclaw/pkg/channels/pico"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/health"
"github.com/sipeed/picoclaw/pkg/logger"
@ -37,28 +36,12 @@ var gateway = struct {
startupDeadline time.Time
logs *LogBuffer
pidData *ppid.PidFileData // pid file data read from picoclaw.pid.json
picoToken string // cached pico token from config (for proxy auth validation)
picoToken string // cached raw pico token for upstream gateway proxy injection
}{
runtimeStatus: "stopped",
logs: NewLogBuffer(200),
}
// refreshPicoToken updates gateway.picoToken from cfg
func refreshPicoToken(cfg *config.Config) {
gateway.mu.Lock()
defer gateway.mu.Unlock()
var picoCfg config.PicoSettings
if bc := cfg.Channels.GetByType(config.ChannelPico); bc != nil {
decoded, err := bc.GetDecoded()
if err == nil && decoded != nil {
if p, ok := decoded.(*config.PicoSettings); ok {
picoCfg = *p
}
}
}
gateway.picoToken = picoCfg.Token.String()
}
// refreshPicoTokensLocked reads the pico token from config and caches it.
// Caller must hold gateway.mu (or be sole writer).
func refreshPicoTokensLocked(configPath string) {
@ -101,18 +84,15 @@ const (
tokenPrefix = "token."
)
// picoComposedToken returns "pico-"+pidToken+picoToken for gateway auth.
func picoComposedToken(token string) string {
// picoGatewayProtocol returns the gateway-facing pico subprotocol that the
// launcher should inject when proxying browser traffic upstream.
func picoGatewayProtocol() string {
gateway.mu.Lock()
defer gateway.mu.Unlock()
// if not initial pico token, don't allow gateway auth
if gateway.picoToken == "" || gateway.pidData == nil {
if gateway.picoToken == "" {
return ""
}
if tokenPrefix+gateway.picoToken != token {
return ""
}
return pico.PicoTokenPrefix + gateway.pidData.Token + gateway.picoToken
return tokenPrefix + gateway.picoToken
}
var (
@ -752,7 +732,7 @@ func (h *Handler) startGatewayLocked(initialStatus string, existingPid int) (int
gateway.logs.Reset()
// Ensure Pico Channel is configured before starting gateway
changed, err := h.EnsurePicoChannel("")
changed, err := h.EnsurePicoChannel()
if err != nil {
logger.ErrorC("gateway", fmt.Sprintf("Warning: failed to ensure pico channel: %v", err))
// Non-fatal: gateway can still start without pico channel

View file

@ -85,8 +85,22 @@ func requestHostName(r *http.Request) string {
return netbind.ResolveAdaptiveLoopbackHost()
}
func forwardedProtoFirst(r *http.Request) string {
raw := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto"))
if raw == "" {
raw = forwardedRFC7239Proto(r)
}
if raw == "" {
return ""
}
if i := strings.IndexByte(raw, ','); i >= 0 {
raw = strings.TrimSpace(raw[:i])
}
return strings.ToLower(raw)
}
func requestWSScheme(r *http.Request) string {
if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" {
if forwarded := forwardedProtoFirst(r); forwarded != "" {
proto := strings.ToLower(strings.TrimSpace(strings.Split(forwarded, ",")[0]))
if proto == "https" || proto == "wss" {
return "wss"
@ -105,7 +119,7 @@ func requestWSScheme(r *http.Request) string {
// requestHTTPScheme returns http or https for URLs that are not WebSockets (e.g. SSE).
func requestHTTPScheme(r *http.Request) string {
if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" {
if forwarded := forwardedProtoFirst(r); forwarded != "" {
proto := strings.ToLower(strings.TrimSpace(strings.Split(forwarded, ",")[0]))
if proto == "https" || proto == "wss" {
return "https"
@ -117,6 +131,7 @@ func requestHTTPScheme(r *http.Request) string {
if r.TLS != nil {
return "https"
}
return "http"
}
@ -138,6 +153,14 @@ func forwardedHostFirst(r *http.Request) string {
// forwardedRFC7239Host parses host= from the first Forwarded header element (RFC 7239).
func forwardedRFC7239Host(r *http.Request) string {
return forwardedRFC7239Param(r, "host")
}
func forwardedRFC7239Proto(r *http.Request) string {
return forwardedRFC7239Param(r, "proto")
}
func forwardedRFC7239Param(r *http.Request, key string) string {
v := strings.TrimSpace(r.Header.Get("Forwarded"))
if v == "" {
return ""
@ -146,7 +169,7 @@ func forwardedRFC7239Host(r *http.Request) string {
for _, part := range strings.Split(first, ";") {
part = strings.TrimSpace(part)
low := strings.ToLower(part)
if !strings.HasPrefix(low, "host=") {
if !strings.HasPrefix(low, key+"=") {
continue
}
val := strings.TrimSpace(part[strings.IndexByte(part, '=')+1:])
@ -177,13 +200,21 @@ func clientVisiblePort(r *http.Request, serverListenPort int) string {
if p := forwardedPortFirst(r); p != "" {
return p
}
if fwdHost := forwardedHostFirst(r); fwdHost != "" {
if _, port, err := net.SplitHostPort(fwdHost); err == nil && port != "" {
return port
}
}
if _, port, err := net.SplitHostPort(r.Host); err == nil && port != "" {
return port
}
if strings.TrimSpace(r.Host) == "" && forwardedHostFirst(r) == "" {
return strconv.Itoa(serverListenPort)
}
if requestHTTPScheme(r) == "https" {
return "443"
}
return strconv.Itoa(serverListenPort)
return "80"
}
// joinClientVisibleHostPort builds host:port for absolute URLs returned to the browser.
@ -205,16 +236,7 @@ func (h *Handler) picoWebUIAddr(r *http.Request) string {
if fwdHost := forwardedHostFirst(r); fwdHost != "" {
return joinClientVisibleHostPort(r, fwdHost, wsPort)
}
host := requestHostName(r)
// Use clientVisiblePort only when an explicit port is present in headers
// or Host header — do not infer from TLS/scheme, as serverPort takes priority.
if p := forwardedPortFirst(r); p != "" {
return net.JoinHostPort(host, p)
}
if _, port, err := net.SplitHostPort(r.Host); err == nil && port != "" {
return net.JoinHostPort(host, port)
}
return net.JoinHostPort(host, strconv.Itoa(wsPort))
return joinClientVisibleHostPort(r, requestHostName(r), wsPort)
}
func (h *Handler) buildWsURL(r *http.Request) string {

View file

@ -50,7 +50,7 @@ func TestBuildWsURLUsesRequestHostWhenLauncherPublicSaved(t *testing.T) {
cfg.Gateway.Host = "127.0.0.1"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/token", nil)
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/info", nil)
req.Host = "192.168.1.9:18800"
if got := h.buildWsURL(req); got != "ws://192.168.1.9:18800/pico/ws" {
@ -181,12 +181,12 @@ func TestBuildWsURLUsesWSSWhenForwardedProtoIsHTTPS(t *testing.T) {
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/token", nil)
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/info", nil)
req.Host = "chat.example.com"
req.Header.Set("X-Forwarded-Proto", "https")
if got := h.buildWsURL(req); got != "wss://chat.example.com:18800/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "wss://chat.example.com:18800/pico/ws")
if got := h.buildWsURL(req); got != "wss://chat.example.com:443/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "wss://chat.example.com:443/pico/ws")
}
}
@ -198,12 +198,12 @@ func TestBuildWsURLUsesWSSWhenRequestIsTLS(t *testing.T) {
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "https://launcher.local/api/pico/token", nil)
req := httptest.NewRequest("GET", "https://launcher.local/api/pico/info", nil)
req.Host = "secure.example.com"
req.TLS = &tls.ConnectionState{}
if got := h.buildWsURL(req); got != "wss://secure.example.com:18800/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "wss://secure.example.com:18800/pico/ws")
if got := h.buildWsURL(req); got != "wss://secure.example.com:443/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "wss://secure.example.com:443/pico/ws")
}
}
@ -224,7 +224,7 @@ func TestBuildPicoURLsPreferXForwardedHost(t *testing.T) {
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "http://127.0.0.1:18800/api/pico/token", nil)
req := httptest.NewRequest("GET", "http://127.0.0.1:18800/api/pico/info", nil)
req.Host = "127.0.0.1:18800"
req.Header.Set("X-Forwarded-Host", "vscode-tunnel.example.com")
req.Header.Set("X-Forwarded-Proto", "https")
@ -249,13 +249,30 @@ func TestBuildWsURLPrefersForwardedHTTPOverTLS(t *testing.T) {
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "https://launcher.local/api/pico/token", nil)
req := httptest.NewRequest("GET", "https://launcher.local/api/pico/info", nil)
req.Host = "chat.example.com"
req.TLS = &tls.ConnectionState{}
req.Header.Set("X-Forwarded-Proto", "http")
if got := h.buildWsURL(req); got != "ws://chat.example.com:18800/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "ws://chat.example.com:18800/pico/ws")
if got := h.buildWsURL(req); got != "ws://chat.example.com:80/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "ws://chat.example.com:80/pico/ws")
}
}
func TestBuildWsURLDoesNotTrustOriginWhenProxyOmitsForwardedProto(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/info", nil)
req.Host = "fs-952210-xwj.picoclaw.lan.sipeed.com"
req.Header.Set("Origin", "https://fs-952210-xwj.picoclaw.lan.sipeed.com")
if got := h.buildWsURL(req); got != "ws://fs-952210-xwj.picoclaw.lan.sipeed.com:80/pico/ws" {
t.Fatalf(
"buildWsURL() = %q, want %q",
got,
"ws://fs-952210-xwj.picoclaw.lan.sipeed.com:80/pico/ws",
)
}
}
@ -264,7 +281,7 @@ func TestBuildWsURLUsesRequestHostNotGatewayBindLoopback(t *testing.T) {
h := NewHandler(configPath)
h.SetServerOptions(18800, false, false, nil)
req := httptest.NewRequest("GET", "http://localhost:18800/api/pico/token", nil)
req := httptest.NewRequest("GET", "http://localhost:18800/api/pico/info", nil)
req.Host = "localhost:18800"
if got := h.buildWsURL(req); got != "ws://localhost:18800/pico/ws" {

View file

@ -121,6 +121,18 @@ func resetGatewayTestState(t *testing.T) {
})
}
func TestPicoGatewayProtocol(t *testing.T) {
resetGatewayTestState(t)
gateway.mu.Lock()
gateway.picoToken = "ui-token"
gateway.mu.Unlock()
if got := picoGatewayProtocol(); got != tokenPrefix+"ui-token" {
t.Fatalf("picoGatewayProtocol() = %q, want %q", got, tokenPrefix+"ui-token")
}
}
type gatewayStartEnvSnapshot struct {
GatewayHost string `json:"gateway_host"`
GatewayHostSet bool `json:"gateway_host_set"`

View file

@ -16,7 +16,7 @@ import (
// registerPicoRoutes binds Pico Channel management endpoints to the ServeMux.
func (h *Handler) registerPicoRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/pico/token", h.handleGetPicoToken)
mux.HandleFunc("GET /api/pico/info", h.handleGetPicoInfo)
mux.HandleFunc("POST /api/pico/token", h.handleRegenPicoToken)
mux.HandleFunc("POST /api/pico/setup", h.handlePicoSetup)
@ -28,12 +28,15 @@ func (h *Handler) registerPicoRoutes(mux *http.ServeMux) {
// createWsProxy creates a reverse proxy to the current gateway WebSocket endpoint.
// The gateway bind host and port are resolved from the latest configuration.
func (h *Handler) createWsProxy(origProtocol string, token string) *httputil.ReverseProxy {
func (h *Handler) createWsProxy(origProtocol string, upstreamProtocol string) *httputil.ReverseProxy {
wsProxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
target := h.gatewayProxyURL()
r.SetURL(target)
r.Out.Header.Set(protocolKey, tokenPrefix+token)
r.Out.Header.Del(protocolKey)
if upstreamProtocol != "" {
r.Out.Header.Set(protocolKey, upstreamProtocol)
}
},
ModifyResponse: func(r *http.Response) error {
if prot := r.Header.Values(protocolKey); len(prot) > 0 {
@ -52,8 +55,50 @@ func (h *Handler) createWsProxy(origProtocol string, token string) *httputil.Rev
return wsProxy
}
func decodePicoSettings(cfg *config.Config) (config.PicoSettings, bool) {
if cfg == nil {
return config.PicoSettings{}, false
}
bc := cfg.Channels.GetByType(config.ChannelPico)
if bc == nil {
return config.PicoSettings{}, false
}
var picoCfg config.PicoSettings
if err := bc.Decode(&picoCfg); err != nil {
return config.PicoSettings{}, false
}
return picoCfg, bc.Enabled
}
func (h *Handler) writePicoInfoResponse(
w http.ResponseWriter,
r *http.Request,
cfg *config.Config,
changed *bool,
) {
picoCfg, enabled := decodePicoSettings(cfg)
resp := map[string]any{
"ws_url": h.buildWsURL(r),
"enabled": enabled,
}
if changed != nil {
resp["changed"] = *changed
}
if picoCfg.Token.String() != "" {
resp["configured"] = true
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
// handleWebSocketProxy wraps a reverse proxy to handle WebSocket connections.
// It validates the client token before forwarding; rejects immediately on failure.
// It relies on launcher dashboard auth, then injects the raw pico token only
// on the upstream gateway request.
func (h *Handler) handleWebSocketProxy() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gateway.mu.Lock()
@ -91,51 +136,38 @@ func (h *Handler) handleWebSocketProxy() http.HandlerFunc {
http.Error(w, "Gateway not available", http.StatusServiceUnavailable)
return
}
prot := r.Header.Values(protocolKey)
if len(prot) > 0 {
origProtocol := prot[0]
newToken := picoComposedToken(prot[0])
if newToken != "" {
h.createWsProxy(origProtocol, newToken).ServeHTTP(w, r)
return
}
upstreamProtocol := picoGatewayProtocol()
if upstreamProtocol == "" {
logger.Warn("Pico token unavailable for WebSocket proxy")
http.Error(w, "Pico channel not configured", http.StatusServiceUnavailable)
return
}
logger.Warnf("Invalid Pico token: %v", prot)
http.Error(w, "Invalid Pico token", http.StatusForbidden)
var origProtocol string
if prot := r.Header.Values(protocolKey); len(prot) > 0 {
origProtocol = prot[0]
}
h.createWsProxy(origProtocol, upstreamProtocol).ServeHTTP(w, r)
}
}
// handleGetPicoToken returns the current WS token and URL for the frontend.
// handleGetPicoInfo returns non-secret Pico connection info for the launcher UI.
//
// GET /api/pico/token
func (h *Handler) handleGetPicoToken(w http.ResponseWriter, r *http.Request) {
// GET /api/pico/info
func (h *Handler) handleGetPicoInfo(w http.ResponseWriter, r *http.Request) {
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
wsURL := h.buildWsURL(r)
w.Header().Set("Content-Type", "application/json")
bc := cfg.Channels.GetByType(config.ChannelPico)
var picoCfg config.PicoSettings
if bc != nil {
bc.Decode(&picoCfg)
}
enabled := false
if bc != nil {
enabled = bc.Enabled
}
json.NewEncoder(w).Encode(map[string]any{
"token": picoCfg.Token.String(),
"ws_url": wsURL,
"enabled": enabled,
})
h.writePicoInfoResponse(w, r, cfg, nil)
}
// handleRegenPicoToken generates a new Pico WebSocket token and saves it.
// handleRegenPicoToken rotates the raw Pico WebSocket token and returns
// non-secret connection info for the launcher UI.
//
// POST /api/pico/token
func (h *Handler) handleRegenPicoToken(w http.ResponseWriter, r *http.Request) {
@ -160,28 +192,12 @@ func (h *Handler) handleRegenPicoToken(w http.ResponseWriter, r *http.Request) {
return
}
// Refresh cached pico token.
gateway.mu.Lock()
gateway.picoToken = token
gateway.mu.Unlock()
wsURL := h.buildWsURL(r)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"token": token,
"ws_url": wsURL,
})
h.writePicoInfoResponse(w, r, cfg, nil)
}
// EnsurePicoChannel enables the Pico channel with sane defaults if it isn't
// already configured. Returns true when the config was modified.
//
// callerOrigin is the Origin header from the setup request. If non-empty and
// no origins are configured yet, it's written as the allowed origin so the
// WebSocket handshake works for whatever host the caller is on (LAN, custom
// port, etc.). Pass "" when there's no request context.
func (h *Handler) EnsurePicoChannel(callerOrigin string) (bool, error) {
func (h *Handler) EnsurePicoChannel() (bool, error) {
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
return false, fmt.Errorf("failed to load config: %w", err)
@ -206,12 +222,6 @@ func (h *Handler) EnsurePicoChannel(callerOrigin string) (bool, error) {
picoCfg.Token = *config.NewSecureString(generateSecureToken())
changed = true
}
// Seed origins from the request instead of hardcoding ports.
if len(picoCfg.AllowOrigins) == 0 && callerOrigin != "" {
picoCfg.AllowOrigins = []string{callerOrigin}
changed = true
}
}
}
@ -228,37 +238,20 @@ func (h *Handler) EnsurePicoChannel(callerOrigin string) (bool, error) {
//
// POST /api/pico/setup
func (h *Handler) handlePicoSetup(w http.ResponseWriter, r *http.Request) {
changed, err := h.EnsurePicoChannel(r.Header.Get("Origin"))
changed, err := h.EnsurePicoChannel()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Reload config (EnsurePicoChannel may have modified it) and refresh cache.
// Reload config (EnsurePicoChannel may have modified it).
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
if changed {
refreshPicoToken(cfg)
}
wsURL := h.buildWsURL(r)
var picoCfg2 config.PicoSettings
if bc := cfg.Channels.GetByType(config.ChannelPico); bc != nil {
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
picoCfg2 = *decoded.(*config.PicoSettings)
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"token": picoCfg2.Token.String(),
"ws_url": wsURL,
"enabled": true,
"changed": changed,
})
h.writePicoInfoResponse(w, r, cfg, &changed)
}
// generateSecureToken creates a random 32-character hex string.

View file

@ -11,16 +11,21 @@ import (
"strconv"
"testing"
"github.com/sipeed/picoclaw/pkg/channels/pico"
"github.com/sipeed/picoclaw/pkg/config"
ppid "github.com/sipeed/picoclaw/pkg/pid"
)
func newPicoProxyRequest(method, path string) *http.Request {
req := httptest.NewRequest(method, "http://launcher.local:18800"+path, nil)
req.Header.Set("Origin", "http://launcher.local:18800")
return req
}
func TestEnsurePicoChannel_FreshConfig(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
changed, err := h.EnsurePicoChannel("")
changed, err := h.EnsurePicoChannel()
if err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
@ -51,7 +56,7 @@ func TestEnsurePicoChannel_DoesNotEnableTokenQuery(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
if _, err := h.EnsurePicoChannel(""); err != nil {
if _, err := h.EnsurePicoChannel(); err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
@ -71,11 +76,11 @@ func TestEnsurePicoChannel_DoesNotEnableTokenQuery(t *testing.T) {
}
}
func TestEnsurePicoChannel_DoesNotSetWildcardOrigins(t *testing.T) {
func TestEnsurePicoChannel_LeavesAllowOriginsEmptyByDefault(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
if _, err := h.EnsurePicoChannel("http://localhost:18800"); err != nil {
if _, err := h.EnsurePicoChannel(); err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
@ -90,45 +95,16 @@ func TestEnsurePicoChannel_DoesNotSetWildcardOrigins(t *testing.T) {
t.Fatalf("GetDecoded() error = %v", err)
}
picoCfg := decoded.(*config.PicoSettings)
for _, origin := range picoCfg.AllowOrigins {
if origin == "*" {
t.Error("setup must not set wildcard origin '*'")
}
}
}
func TestEnsurePicoChannel_NoOriginWithoutCaller(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
if _, err := h.EnsurePicoChannel(""); err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig() error = %v", err)
}
bc := cfg.Channels["pico"]
decoded, err := bc.GetDecoded()
if err != nil {
t.Fatalf("GetDecoded() error = %v", err)
}
picoCfg := decoded.(*config.PicoSettings)
// Without a caller origin, allow_origins stays empty (CheckOrigin
// allows all when the list is empty, so the channel still works).
if len(picoCfg.AllowOrigins) != 0 {
t.Errorf("allow_origins = %v, want empty when no caller origin", picoCfg.AllowOrigins)
t.Errorf("allow_origins = %v, want empty", picoCfg.AllowOrigins)
}
}
func TestEnsurePicoChannel_SetsCallerOrigin(t *testing.T) {
func TestEnsurePicoChannel_NoOriginConfigurationRequired(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
lanOrigin := "http://192.168.1.9:18800"
if _, err := h.EnsurePicoChannel(lanOrigin); err != nil {
if _, err := h.EnsurePicoChannel(); err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
@ -143,8 +119,8 @@ func TestEnsurePicoChannel_SetsCallerOrigin(t *testing.T) {
t.Fatalf("GetDecoded() error = %v", err)
}
picoCfg := decoded.(*config.PicoSettings)
if len(picoCfg.AllowOrigins) != 1 || picoCfg.AllowOrigins[0] != lanOrigin {
t.Errorf("allow_origins = %v, want [%s]", picoCfg.AllowOrigins, lanOrigin)
if len(picoCfg.AllowOrigins) != 0 {
t.Errorf("allow_origins = %v, want empty", picoCfg.AllowOrigins)
}
}
@ -169,7 +145,7 @@ func TestEnsurePicoChannel_PreservesUserSettings(t *testing.T) {
h := NewHandler(configPath)
changed, err := h.EnsurePicoChannel("")
changed, err := h.EnsurePicoChannel()
if err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
@ -213,7 +189,7 @@ func TestEnsurePicoChannel_ExistingConfigWithoutSecurityFile(t *testing.T) {
h := NewHandler(configPath)
changed, err := h.EnsurePicoChannel("")
changed, err := h.EnsurePicoChannel()
if err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
@ -253,7 +229,7 @@ func TestEnsurePicoChannel_ConfiguresPicoWithoutGateway(t *testing.T) {
}
h := NewHandler(configPath)
if _, err := h.EnsurePicoChannel(""); err != nil {
if _, err := h.EnsurePicoChannel(); err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
@ -280,10 +256,8 @@ func TestEnsurePicoChannel_Idempotent(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
origin := "http://localhost:18800"
// First call sets things up
if _, err := h.EnsurePicoChannel(origin); err != nil {
if _, err := h.EnsurePicoChannel(); err != nil {
t.Fatalf("first EnsurePicoChannel() error = %v", err)
}
@ -297,7 +271,7 @@ func TestEnsurePicoChannel_Idempotent(t *testing.T) {
token1 := picoCfg.Token.String()
// Second call should be a no-op
changed, err := h.EnsurePicoChannel(origin)
changed, err := h.EnsurePicoChannel()
if err != nil {
t.Fatalf("second EnsurePicoChannel() error = %v", err)
}
@ -317,7 +291,7 @@ func TestEnsurePicoChannel_Idempotent(t *testing.T) {
}
}
func TestHandlePicoSetup_IncludesRequestOrigin(t *testing.T) {
func TestHandlePicoSetup_DoesNotPersistRequestOrigin(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
@ -342,8 +316,8 @@ func TestHandlePicoSetup_IncludesRequestOrigin(t *testing.T) {
t.Fatalf("GetDecoded() error = %v", err)
}
picoCfg := decoded.(*config.PicoSettings)
if len(picoCfg.AllowOrigins) != 1 || picoCfg.AllowOrigins[0] != "http://10.0.0.5:3000" {
t.Errorf("allow_origins = %v, want [http://10.0.0.5:3000]", picoCfg.AllowOrigins)
if len(picoCfg.AllowOrigins) != 0 {
t.Errorf("allow_origins = %v, want empty", picoCfg.AllowOrigins)
}
}
@ -365,8 +339,8 @@ func TestHandlePicoSetup_Response(t *testing.T) {
t.Fatalf("failed to decode response: %v", err)
}
if resp["token"] == nil || resp["token"] == "" {
t.Error("response should contain a non-empty token")
if _, ok := resp["token"]; ok {
t.Error("response must not expose the raw pico token")
}
if resp["ws_url"] == nil || resp["ws_url"] == "" {
t.Error("response should contain ws_url")
@ -377,6 +351,45 @@ func TestHandlePicoSetup_Response(t *testing.T) {
if resp["changed"] != true {
t.Error("response should have changed=true on first setup")
}
if resp["configured"] != true {
t.Error("response should have configured=true")
}
}
func TestHandleGetPicoInfo_OmitsToken(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
if _, err := h.EnsurePicoChannel(); err != nil {
t.Fatalf("EnsurePicoChannel() error = %v", err)
}
req := httptest.NewRequest(http.MethodGet, "http://launcher.local/api/pico/info", nil)
rec := httptest.NewRecorder()
h.handleGetPicoInfo(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
var resp map[string]any
if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if _, ok := resp["token"]; ok {
t.Fatal("info response must not expose the raw pico token")
}
if resp["enabled"] != true {
t.Fatalf("enabled = %#v, want true", resp["enabled"])
}
if resp["configured"] != true {
t.Fatalf("configured = %#v, want true", resp["configured"])
}
if resp["ws_url"] == nil || resp["ws_url"] == "" {
t.Fatal("response should contain ws_url")
}
}
func TestHandleWebSocketProxyReloadsGatewayTargetFromConfig(t *testing.T) {
@ -438,20 +451,10 @@ func TestHandleWebSocketProxyReloadsGatewayTargetFromConfig(t *testing.T) {
gateway.pidData = &ppid.PidFileData{}
gateway.picoToken = "pico"
req1 := httptest.NewRequest(http.MethodGet, "/pico/ws", nil)
req1.Header.Set(protocolKey, tokenPrefix+"wrong_token")
req1 := newPicoProxyRequest(http.MethodGet, "/pico/ws")
rec1 := httptest.NewRecorder()
handler(rec1, req1)
if rec1.Code != http.StatusForbidden {
t.Fatalf("first status = %d, want %d", rec1.Code, http.StatusForbidden)
}
req1 = httptest.NewRequest(http.MethodGet, "/pico/ws", nil)
req1.Header.Set(protocolKey, tokenPrefix+"pico")
rec1 = httptest.NewRecorder()
handler(rec1, req1)
if rec1.Code != http.StatusOK {
t.Fatalf("first status = %d, want %d", rec1.Code, http.StatusOK)
}
@ -464,8 +467,7 @@ func TestHandleWebSocketProxyReloadsGatewayTargetFromConfig(t *testing.T) {
t.Fatalf("SaveConfig() error = %v", err)
}
req2 := httptest.NewRequest(http.MethodGet, "/pico/ws", nil)
req2.Header.Set(protocolKey, tokenPrefix+"pico")
req2 := newPicoProxyRequest(http.MethodGet, "/pico/ws")
rec2 := httptest.NewRecorder()
handler(rec2, req2)
@ -539,8 +541,7 @@ func TestHandleWebSocketProxyLoadsCachedPicoTokenWhenMissing(t *testing.T) {
gateway.pidData = &ppid.PidFileData{}
gateway.picoToken = ""
req := httptest.NewRequest(http.MethodGet, "/pico/ws?session_id=test-session", nil)
req.Header.Set(protocolKey, tokenPrefix+"cached-token")
req := newPicoProxyRequest(http.MethodGet, "/pico/ws?session_id=test-session")
rec := httptest.NewRecorder()
handler(rec, req)
@ -625,8 +626,7 @@ func TestHandleWebSocketProxyLoadsPidDataOnDemand(t *testing.T) {
setGatewayRuntimeStatusLocked("stopped")
gateway.mu.Unlock()
req := httptest.NewRequest(http.MethodGet, "/pico/ws?session_id=test-session", nil)
req.Header.Set(protocolKey, tokenPrefix+"ui-token")
req := newPicoProxyRequest(http.MethodGet, "/pico/ws?session_id=test-session")
rec := httptest.NewRecorder()
handler(rec, req)
@ -634,7 +634,7 @@ func TestHandleWebSocketProxyLoadsPidDataOnDemand(t *testing.T) {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
expected := tokenPrefix + pico.PicoTokenPrefix + pidData.Token + "ui-token"
expected := tokenPrefix + "ui-token"
if got := rec.Body.String(); got != expected {
t.Fatalf("forwarded protocol = %q, want %q", got, expected)
}
@ -696,8 +696,7 @@ func TestHandleWebSocketProxyRejectsStalePidDataAfterProcessExit(t *testing.T) {
setGatewayRuntimeStatusLocked("running")
gateway.mu.Unlock()
req := httptest.NewRequest(http.MethodGet, "/pico/ws?session_id=test-session", nil)
req.Header.Set(protocolKey, tokenPrefix+"ui-token")
req := newPicoProxyRequest(http.MethodGet, "/pico/ws?session_id=test-session")
rec := httptest.NewRecorder()
handler(rec, req)
@ -711,6 +710,78 @@ func TestHandleWebSocketProxyRejectsStalePidDataAfterProcessExit(t *testing.T) {
}
}
func TestHandleWebSocketProxy_AllowsArbitraryOrigin(t *testing.T) {
origMatcher := gatewayProcessMatcher
gatewayProcessMatcher = func(int) (bool, bool) { return true, true }
t.Cleanup(func() { gatewayProcessMatcher = origMatcher })
home := t.TempDir()
t.Setenv("PICOCLAW_HOME", home)
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
handler := h.handleWebSocketProxy()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/pico/ws" {
t.Fatalf("path = %q, want %q", r.URL.Path, "/pico/ws")
}
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, "proxied")
}))
defer server.Close()
cfg := config.DefaultConfig()
cfg.Gateway.Host = "127.0.0.1"
cfg.Gateway.Port = mustGatewayTestPort(t, server.URL)
bc := cfg.Channels["pico"]
bc.Enabled = true
decoded, err := bc.GetDecoded()
if err != nil {
t.Fatalf("GetDecoded() error = %v", err)
}
decoded.(*config.PicoSettings).SetToken("ui-token")
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
cmd := startGatewayLikeProcess(t)
t.Cleanup(func() {
if cmd.Process != nil {
_ = cmd.Process.Kill()
}
_ = cmd.Wait()
})
writeTestPidFile(t, ppid.PidFileData{
PID: cmd.Process.Pid,
Token: "test-token",
Host: cfg.Gateway.Host,
Port: cfg.Gateway.Port,
})
t.Cleanup(func() {
ppid.RemovePidFile(globalConfigDir())
})
origPidData := gateway.pidData
origPicoToken := gateway.picoToken
t.Cleanup(func() {
gateway.pidData = origPidData
gateway.picoToken = origPicoToken
})
gateway.pidData = &ppid.PidFileData{}
gateway.picoToken = "ui-token"
req := httptest.NewRequest(http.MethodGet, "http://launcher.local/pico/ws?session_id=test-session", nil)
req.Header.Set("Origin", "http://evil.example")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
}
func mustGatewayTestPort(t *testing.T, rawURL string) int {
t.Helper()

View file

@ -544,7 +544,7 @@ func main() {
// API Routes (e.g. /api/status)
apiHandler = api.NewHandler(absPath)
apiHandler.SetDebug(debug)
if _, err = apiHandler.EnsurePicoChannel(""); err != nil {
if _, err = apiHandler.EnsurePicoChannel(); err != nil {
logger.ErrorC("web", fmt.Sprintf("Warning: failed to ensure pico channel on startup: %v", err))
}
apiHandler.SetServerOptions(portNum, effectivePublic, explicitPublic, launcherCfg.AllowedCIDRs)

View file

@ -218,6 +218,10 @@ func validLauncherDashboardAuth(r *http.Request, cfg LauncherDashboardAuthConfig
}
func rejectLauncherDashboardAuth(w http.ResponseWriter, r *http.Request, canonicalPath string) {
if canonicalPath == "/pico/ws" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if strings.HasPrefix(canonicalPath, "/api/") {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)

View file

@ -40,6 +40,7 @@ func TestLauncherDashboardAuth_AllowsPublicPaths(t *testing.T) {
{http.MethodPost, "/api/auth/logout", http.StatusTeapot},
{http.MethodGet, "/api/auth/logout", http.StatusUnauthorized},
{http.MethodGet, "/api/config", http.StatusUnauthorized},
{http.MethodGet, "/pico/ws", http.StatusUnauthorized},
} {
rec := httptest.NewRecorder()
req := httptest.NewRequest(tc.method, tc.path, nil)
@ -160,3 +161,22 @@ func TestLauncherDashboardAuth_CookieAndBearer(t *testing.T) {
t.Fatalf("bearer auth: status = %d", rec2.Code)
}
}
func TestLauncherDashboardAuth_WebSocketUnauthorizedDoesNotRedirect(t *testing.T) {
cfg := LauncherDashboardAuthConfig{ExpectedCookie: "deadbeef", Token: "x"}
next := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
t.Fatal("next handler should not run without auth")
})
h := LauncherDashboardAuth(cfg, next)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/pico/ws", nil)
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
if got := rec.Header().Get("Location"); got != "" {
t.Fatalf("Location = %q, want empty", got)
}
}

View file

@ -22,6 +22,7 @@ export default defineConfig([
globals: globals.browser,
},
rules: {
"react-hooks/set-state-in-effect": "off",
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },

View file

@ -21,8 +21,8 @@
"@tabler/icons-react": "^3.40.0",
"@tailwindcss/vite": "^4.2.2",
"@tanstack/react-query": "^5.99.0",
"@tanstack/react-router": "^1.168.22",
"@tanstack/react-router-devtools": "^1.163.3",
"@tanstack/react-router": "^1.168.23",
"@tanstack/react-router-devtools": "^1.166.13",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.20",
@ -55,17 +55,17 @@
"@types/node": "^25.6.0",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@typescript-eslint/eslint-plugin": "^8.57.1",
"@typescript-eslint/eslint-plugin": "^8.58.2",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^10.1.0",
"eslint": "^10.2.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"prettier": "^3.8.1",
"prettier": "^3.8.3",
"prettier-plugin-tailwindcss": "^0.7.2",
"typescript": "~5.9.3",
"typescript-eslint": "^8.57.1",
"typescript-eslint": "^8.58.2",
"vite": "^8.0.8"
}
}

View file

@ -21,11 +21,11 @@ importers:
specifier: ^5.99.0
version: 5.99.0(react@19.2.5)
'@tanstack/react-router':
specifier: ^1.168.22
version: 1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
specifier: ^1.168.23
version: 1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
'@tanstack/react-router-devtools':
specifier: ^1.163.3
version: 1.166.11(@tanstack/react-router@1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@tanstack/router-core@1.168.15)(csstype@3.2.3)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
specifier: ^1.166.13
version: 1.166.13(@tanstack/react-router@1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@tanstack/router-core@1.168.15)(csstype@3.2.3)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@ -98,16 +98,16 @@ importers:
devDependencies:
'@eslint/js':
specifier: ^10.0.1
version: 10.0.1(eslint@10.1.0(jiti@2.6.1))
version: 10.0.1(eslint@10.2.1(jiti@2.6.1))
'@tailwindcss/typography':
specifier: ^0.5.19
version: 0.5.19(tailwindcss@4.2.2)
'@tanstack/router-plugin':
specifier: ^1.164.0
version: 1.167.9(@tanstack/react-router@1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.6.1)(tsx@4.21.0))
version: 1.167.9(@tanstack/react-router@1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.6.1)(tsx@4.21.0))
'@trivago/prettier-plugin-sort-imports':
specifier: ^6.0.2
version: 6.0.2(prettier@3.8.1)
version: 6.0.2(prettier@3.8.3)
'@types/node':
specifier: ^25.6.0
version: 25.6.0
@ -118,38 +118,38 @@ importers:
specifier: ^19.2.3
version: 19.2.3(@types/react@19.2.14)
'@typescript-eslint/eslint-plugin':
specifier: ^8.57.1
version: 8.57.2(@typescript-eslint/parser@8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3))(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
specifier: ^8.58.2
version: 8.58.2(@typescript-eslint/parser@8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3))(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
'@vitejs/plugin-react':
specifier: ^6.0.1
version: 6.0.1(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.6.1)(tsx@4.21.0))
eslint:
specifier: ^10.1.0
version: 10.1.0(jiti@2.6.1)
specifier: ^10.2.1
version: 10.2.1(jiti@2.6.1)
eslint-config-prettier:
specifier: ^10.1.8
version: 10.1.8(eslint@10.1.0(jiti@2.6.1))
version: 10.1.8(eslint@10.2.1(jiti@2.6.1))
eslint-plugin-react-hooks:
specifier: ^7.0.1
version: 7.0.1(eslint@10.1.0(jiti@2.6.1))
specifier: ^7.1.1
version: 7.1.1(eslint@10.2.1(jiti@2.6.1))
eslint-plugin-react-refresh:
specifier: ^0.5.2
version: 0.5.2(eslint@10.1.0(jiti@2.6.1))
version: 0.5.2(eslint@10.2.1(jiti@2.6.1))
globals:
specifier: ^17.5.0
version: 17.5.0
prettier:
specifier: ^3.8.1
version: 3.8.1
specifier: ^3.8.3
version: 3.8.3
prettier-plugin-tailwindcss:
specifier: ^0.7.2
version: 0.7.2(@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.1))(prettier@3.8.1)
version: 0.7.2(@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.3))(prettier@3.8.3)
typescript:
specifier: ~5.9.3
version: 5.9.3
typescript-eslint:
specifier: ^8.57.1
version: 8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
specifier: ^8.58.2
version: 8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
vite:
specifier: ^8.0.8
version: 8.0.8(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.6.1)(tsx@4.21.0)
@ -474,16 +474,16 @@ packages:
resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==}
engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}
'@eslint/config-array@0.23.3':
resolution: {integrity: sha512-j+eEWmB6YYLwcNOdlwQ6L2OsptI/LO6lNBuLIqe5R7RetD658HLoF+Mn7LzYmAWWNNzdC6cqP+L6r8ujeYXWLw==}
'@eslint/config-array@0.23.5':
resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
'@eslint/config-helpers@0.5.3':
resolution: {integrity: sha512-lzGN0onllOZCGroKJmRwY6QcEHxbjBw1gwB8SgRSqK8YbbtEXMvKynsXc3553ckIEBxsbMBU7oOZXKIPGZNeZw==}
'@eslint/config-helpers@0.5.5':
resolution: {integrity: sha512-eIJYKTCECbP/nsKaaruF6LW967mtbQbsw4JTtSVkUQc9MneSkbrgPJAbKl9nWr0ZeowV8BfsarBmPpBzGelA2w==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
'@eslint/core@1.1.1':
resolution: {integrity: sha512-QUPblTtE51/7/Zhfv8BDwO0qkkzQL7P/aWWbqcf4xWLEYn1oKjdO0gglQBB4GAsu7u6wjijbCmzsUTy6mnk6oQ==}
'@eslint/core@1.2.1':
resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
'@eslint/js@10.0.1':
@ -495,12 +495,12 @@ packages:
eslint:
optional: true
'@eslint/object-schema@3.0.3':
resolution: {integrity: sha512-iM869Pugn9Nsxbh/YHRqYiqd23AmIbxJOcpUMOuWCVNdoQJ5ZtwL6h3t0bcZzJUlC3Dq9jCFCESBZnX0GTv7iQ==}
'@eslint/object-schema@3.0.5':
resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
'@eslint/plugin-kit@0.6.1':
resolution: {integrity: sha512-iH1B076HoAshH1mLpHMgwdGeTs0CYwL0SPMkGuSebZrwBp16v415e9NZXg2jtrqPVQjf6IANe2Vtlr5KswtcZQ==}
'@eslint/plugin-kit@0.7.1':
resolution: {integrity: sha512-rZAP3aVgB9ds9KOeUSL+zZ21hPmo8dh6fnIFwRQj5EAZl9gzR7wxYbYXYysAM8CTqGmUGyp2S4kUdV17MnGuWQ==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
'@floating-ui/core@1.7.5':
@ -1570,20 +1570,20 @@ packages:
peerDependencies:
react: ^18 || ^19
'@tanstack/react-router-devtools@1.166.11':
resolution: {integrity: sha512-WYR3q4Xui5yPT/5PXtQh8i03iUA7q8dONBjWpV3nsGdM8Cs1FxpfhLstW0wZO1dOvSyElscwTRCJ6nO5N8r3Lg==}
'@tanstack/react-router-devtools@1.166.13':
resolution: {integrity: sha512-6yKRFFJrEEOiGp5RAAuGCYsl81M4XAhJmLcu9PKj+HZle4A3dsP60lwHoqQYWHMK9nKKFkdXR+D8qxzxqtQbEA==}
engines: {node: '>=20.19'}
peerDependencies:
'@tanstack/react-router': ^1.168.2
'@tanstack/router-core': ^1.168.2
'@tanstack/react-router': ^1.168.15
'@tanstack/router-core': ^1.168.11
react: '>=18.0.0 || >=19.0.0'
react-dom: '>=18.0.0 || >=19.0.0'
peerDependenciesMeta:
'@tanstack/router-core':
optional: true
'@tanstack/react-router@1.168.22':
resolution: {integrity: sha512-W2LyfkfJtDCf//jOjZeUBWwOVl8iDRVTECpGHa2M28MT3T5/VVnjgicYNHR/ax0Filk1iU67MRjcjHheTYvK1Q==}
'@tanstack/react-router@1.168.23':
resolution: {integrity: sha512-+GblieDnutG6oipJJPNtRJjrWF8QTZEG/l0532+BngFkVK48oHNOcvIkSoAFYftK1egAwM7KBxXsb0Ou+X6/MQ==}
engines: {node: '>=20.19'}
peerDependencies:
react: '>=18.0.0 || >=19.0.0'
@ -1605,11 +1605,11 @@ packages:
engines: {node: '>=20.19'}
hasBin: true
'@tanstack/router-devtools-core@1.167.1':
resolution: {integrity: sha512-ECMM47J4KmifUvJguGituSiBpfN8SyCUEoxQks5RY09hpIBfR2eswCv2e6cJimjkKwBQXOVTPkTUk/yRvER+9w==}
'@tanstack/router-devtools-core@1.167.3':
resolution: {integrity: sha512-fJ1VMhyQgnoashTrP763c2HRc9kofgF61L7Jb3F6eTHAmCKtGVx8BRtiFt37sr3U0P0jmaaiiSPGP6nT5JtVNg==}
engines: {node: '>=20.19'}
peerDependencies:
'@tanstack/router-core': ^1.168.2
'@tanstack/router-core': ^1.168.11
csstype: ^3.0.10
peerDependenciesMeta:
csstype:
@ -1728,63 +1728,63 @@ packages:
'@types/validate-npm-package-name@4.0.2':
resolution: {integrity: sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw==}
'@typescript-eslint/eslint-plugin@8.57.2':
resolution: {integrity: sha512-NZZgp0Fm2IkD+La5PR81sd+g+8oS6JwJje+aRWsDocxHkjyRw0J5L5ZTlN3LI1LlOcGL7ph3eaIUmTXMIjLk0w==}
'@typescript-eslint/eslint-plugin@8.58.2':
resolution: {integrity: sha512-aC2qc5thQahutKjP+cl8cgN9DWe3ZUqVko30CMSZHnFEHyhOYoZSzkGtAI2mcwZ38xeImDucI4dnqsHiOYuuCw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
'@typescript-eslint/parser': ^8.57.2
'@typescript-eslint/parser': ^8.58.2
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/parser@8.57.2':
resolution: {integrity: sha512-30ScMRHIAD33JJQkgfGW1t8CURZtjc2JpTrq5n2HFhOefbAhb7ucc7xJwdWcrEtqUIYJ73Nybpsggii6GtAHjA==}
'@typescript-eslint/parser@8.58.2':
resolution: {integrity: sha512-/Zb/xaIDfxeJnvishjGdcR4jmr7S+bda8PKNhRGdljDM+elXhlvN0FyPSsMnLmJUrVG9aPO6dof80wjMawsASg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/project-service@8.57.2':
resolution: {integrity: sha512-FuH0wipFywXRTHf+bTTjNyuNQQsQC3qh/dYzaM4I4W0jrCqjCVuUh99+xd9KamUfmCGPvbO8NDngo/vsnNVqgw==}
'@typescript-eslint/project-service@8.58.2':
resolution: {integrity: sha512-Cq6UfpZZk15+r87BkIh5rDpi38W4b+Sjnb8wQCPPDDweS/LRCFjCyViEbzHk5Ck3f2QDfgmlxqSa7S7clDtlfg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/scope-manager@8.57.2':
resolution: {integrity: sha512-snZKH+W4WbWkrBqj4gUNRIGb/jipDW3qMqVJ4C9rzdFc+wLwruxk+2a5D+uoFcKPAqyqEnSb4l2ULuZf95eSkw==}
'@typescript-eslint/scope-manager@8.58.2':
resolution: {integrity: sha512-SgmyvDPexWETQek+qzZnrG6844IaO02UVyOLhI4wpo82dpZJY9+6YZCKAMFzXb7qhx37mFK1QcPQ18tud+vo6Q==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/tsconfig-utils@8.57.2':
resolution: {integrity: sha512-3Lm5DSM+DCowsUOJC+YqHHnKEfFh5CoGkj5Z31NQSNF4l5wdOwqGn99wmwN/LImhfY3KJnmordBq/4+VDe2eKw==}
'@typescript-eslint/tsconfig-utils@8.58.2':
resolution: {integrity: sha512-3SR+RukipDvkkKp/d0jP0dyzuls3DbGmwDpVEc5wqk5f38KFThakqAAO0XMirWAE+kT00oTauTbzMFGPoAzB0A==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/type-utils@8.57.2':
resolution: {integrity: sha512-Co6ZCShm6kIbAM/s+oYVpKFfW7LBc6FXoPXjTRQ449PPNBY8U0KZXuevz5IFuuUj2H9ss40atTaf9dlGLzbWZg==}
'@typescript-eslint/type-utils@8.58.2':
resolution: {integrity: sha512-Z7EloNR/B389FvabdGeTo2XMs4W9TjtPiO9DAsmT0yom0bwlPyRjkJ1uCdW1DvrrrYP50AJZ9Xc3sByZA9+dcg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/types@8.57.2':
resolution: {integrity: sha512-/iZM6FnM4tnx9csuTxspMW4BOSegshwX5oBDznJ7S4WggL7Vczz5d2W11ecc4vRrQMQHXRSxzrCsyG5EsPPTbA==}
'@typescript-eslint/types@8.58.2':
resolution: {integrity: sha512-9TukXyATBQf/Jq9AMQXfvurk+G5R2MwfqQGDR2GzGz28HvY/lXNKGhkY+6IOubwcquikWk5cjlgPvD2uAA7htQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/typescript-estree@8.57.2':
resolution: {integrity: sha512-2MKM+I6g8tJxfSmFKOnHv2t8Sk3T6rF20A1Puk0svLK+uVapDZB/4pfAeB7nE83uAZrU6OxW+HmOd5wHVdXwXA==}
'@typescript-eslint/typescript-estree@8.58.2':
resolution: {integrity: sha512-ELGuoofuhhoCvNbQjFFiobFcGgcDCEm0ThWdmO4Z0UzLqPXS3KFvnEZ+SHewwOYHjM09tkzOWXNTv9u6Gqtyuw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/utils@8.57.2':
resolution: {integrity: sha512-krRIbvPK1ju1WBKIefiX+bngPs+odIQUtR7kymzPfo1POVw3jlF+nLkmexdSSd4UCbDcQn+wMBATOOmpBbqgKg==}
'@typescript-eslint/utils@8.58.2':
resolution: {integrity: sha512-QZfjHNEzPY8+l0+fIXMvuQ2sJlplB4zgDZvA+NmvZsZv3EQwOcc1DuIU1VJUTWZ/RKouBMhDyNaBMx4sWvrzRA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/visitor-keys@8.57.2':
resolution: {integrity: sha512-zhahknjobV2FiD6Ee9iLbS7OV9zi10rG26odsQdfBO/hjSzUQbkIYgda+iNKK1zNiW2ey+Lf8MU5btN17V3dUw==}
'@typescript-eslint/visitor-keys@8.58.2':
resolution: {integrity: sha512-f1WO2Lx8a9t8DARmcWAUPJbu0G20bJlj8L4z72K00TMeJAoyLr/tHhI/pzYBLrR4dXWkcxO1cWYZEOX8DKHTqA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@ungap/structured-clone@1.3.0':
@ -2205,11 +2205,11 @@ packages:
peerDependencies:
eslint: '>=7.0.0'
eslint-plugin-react-hooks@7.0.1:
resolution: {integrity: sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==}
eslint-plugin-react-hooks@7.1.1:
resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==}
engines: {node: '>=18'}
peerDependencies:
eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0
eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0
eslint-plugin-react-refresh@0.5.2:
resolution: {integrity: sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==}
@ -2228,8 +2228,8 @@ packages:
resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
eslint@10.1.0:
resolution: {integrity: sha512-S9jlY/ELKEUwwQnqWDO+f+m6sercqOPSqXM5Go94l7DOmxHVDgmSFGWEzeE/gwgTAr0W103BWt0QLe/7mabIvA==}
eslint@10.2.1:
resolution: {integrity: sha512-wiyGaKsDgqXvF40P8mDwiUp/KQjE1FdrIEJsM8PZ3XCiniTMXS3OHWWUe5FI5agoCnr8x4xPrTDZuxsBlNHl+Q==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
hasBin: true
peerDependencies:
@ -3040,10 +3040,6 @@ packages:
resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
engines: {node: '>=18'}
minimatch@10.2.4:
resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==}
engines: {node: 18 || 20 || >=22}
minimatch@10.2.5:
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@ -3304,8 +3300,8 @@ packages:
prettier-plugin-svelte:
optional: true
prettier@3.8.1:
resolution: {integrity: sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==}
prettier@3.8.3:
resolution: {integrity: sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==}
engines: {node: '>=14'}
hasBin: true
@ -3740,12 +3736,12 @@ packages:
resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==}
engines: {node: '>= 0.6'}
typescript-eslint@8.57.2:
resolution: {integrity: sha512-VEPQ0iPgWO/sBaZOU1xo4nuNdODVOajPnTIbog2GKYr31nIlZ0fWPoCQgGfF3ETyBl1vn63F/p50Um9Z4J8O8A==}
typescript-eslint@8.58.2:
resolution: {integrity: sha512-V8iSng9mRbdZjl54VJ9NKr6ZB+dW0J3TzRXRGcSbLIej9jV86ZRtlYeTKDR/QLxXykocJ5icNzbsl2+5TzIvcQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.0.0'
typescript: '>=4.8.4 <6.1.0'
typescript@5.9.3:
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
@ -4310,38 +4306,38 @@ snapshots:
'@esbuild/win32-x64@0.27.4':
optional: true
'@eslint-community/eslint-utils@4.9.1(eslint@10.1.0(jiti@2.6.1))':
'@eslint-community/eslint-utils@4.9.1(eslint@10.2.1(jiti@2.6.1))':
dependencies:
eslint: 10.1.0(jiti@2.6.1)
eslint: 10.2.1(jiti@2.6.1)
eslint-visitor-keys: 3.4.3
'@eslint-community/regexpp@4.12.2': {}
'@eslint/config-array@0.23.3':
'@eslint/config-array@0.23.5':
dependencies:
'@eslint/object-schema': 3.0.3
'@eslint/object-schema': 3.0.5
debug: 4.4.3
minimatch: 10.2.4
minimatch: 10.2.5
transitivePeerDependencies:
- supports-color
'@eslint/config-helpers@0.5.3':
'@eslint/config-helpers@0.5.5':
dependencies:
'@eslint/core': 1.1.1
'@eslint/core': 1.2.1
'@eslint/core@1.1.1':
'@eslint/core@1.2.1':
dependencies:
'@types/json-schema': 7.0.15
'@eslint/js@10.0.1(eslint@10.1.0(jiti@2.6.1))':
'@eslint/js@10.0.1(eslint@10.2.1(jiti@2.6.1))':
optionalDependencies:
eslint: 10.1.0(jiti@2.6.1)
eslint: 10.2.1(jiti@2.6.1)
'@eslint/object-schema@3.0.3': {}
'@eslint/object-schema@3.0.5': {}
'@eslint/plugin-kit@0.6.1':
'@eslint/plugin-kit@0.7.1':
dependencies:
'@eslint/core': 1.1.1
'@eslint/core': 1.2.1
levn: 0.4.1
'@floating-ui/core@1.7.5':
@ -5388,10 +5384,10 @@ snapshots:
'@tanstack/query-core': 5.99.0
react: 19.2.5
'@tanstack/react-router-devtools@1.166.11(@tanstack/react-router@1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@tanstack/router-core@1.168.15)(csstype@3.2.3)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
'@tanstack/react-router-devtools@1.166.13(@tanstack/react-router@1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@tanstack/router-core@1.168.15)(csstype@3.2.3)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
dependencies:
'@tanstack/react-router': 1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
'@tanstack/router-devtools-core': 1.167.1(@tanstack/router-core@1.168.15)(csstype@3.2.3)
'@tanstack/react-router': 1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
'@tanstack/router-devtools-core': 1.167.3(@tanstack/router-core@1.168.15)(csstype@3.2.3)
react: 19.2.5
react-dom: 19.2.5(react@19.2.5)
optionalDependencies:
@ -5399,7 +5395,7 @@ snapshots:
transitivePeerDependencies:
- csstype
'@tanstack/react-router@1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
'@tanstack/react-router@1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
dependencies:
'@tanstack/history': 1.161.6
'@tanstack/react-store': 0.9.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
@ -5429,7 +5425,7 @@ snapshots:
seroval: 1.5.1
seroval-plugins: 1.5.1(seroval@1.5.1)
'@tanstack/router-devtools-core@1.167.1(@tanstack/router-core@1.168.15)(csstype@3.2.3)':
'@tanstack/router-devtools-core@1.167.3(@tanstack/router-core@1.168.15)(csstype@3.2.3)':
dependencies:
'@tanstack/router-core': 1.168.15
clsx: 2.1.1
@ -5442,7 +5438,7 @@ snapshots:
'@tanstack/router-core': 1.168.7
'@tanstack/router-utils': 1.161.6
'@tanstack/virtual-file-routes': 1.161.7
prettier: 3.8.1
prettier: 3.8.3
recast: 0.23.11
source-map: 0.7.6
tsx: 4.21.0
@ -5450,7 +5446,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@tanstack/router-plugin@1.167.9(@tanstack/react-router@1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.6.1)(tsx@4.21.0))':
'@tanstack/router-plugin@1.167.9(@tanstack/react-router@1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.6.1)(tsx@4.21.0))':
dependencies:
'@babel/core': 7.29.0
'@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.0)
@ -5466,7 +5462,7 @@ snapshots:
unplugin: 2.3.11
zod: 3.25.76
optionalDependencies:
'@tanstack/react-router': 1.168.22(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
'@tanstack/react-router': 1.168.23(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.6.1)(tsx@4.21.0)
transitivePeerDependencies:
- supports-color
@ -5489,7 +5485,7 @@ snapshots:
'@tanstack/virtual-file-routes@1.161.7': {}
'@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.1)':
'@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.3)':
dependencies:
'@babel/generator': 7.29.1
'@babel/parser': 7.29.2
@ -5499,7 +5495,7 @@ snapshots:
lodash-es: 4.17.23
minimatch: 9.0.9
parse-imports-exports: 0.2.4
prettier: 3.8.1
prettier: 3.8.3
transitivePeerDependencies:
- supports-color
@ -5562,15 +5558,15 @@ snapshots:
'@types/validate-npm-package-name@4.0.2': {}
'@typescript-eslint/eslint-plugin@8.57.2(@typescript-eslint/parser@8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3))(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)':
'@typescript-eslint/eslint-plugin@8.58.2(@typescript-eslint/parser@8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3))(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)':
dependencies:
'@eslint-community/regexpp': 4.12.2
'@typescript-eslint/parser': 8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/scope-manager': 8.57.2
'@typescript-eslint/type-utils': 8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/utils': 8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/visitor-keys': 8.57.2
eslint: 10.1.0(jiti@2.6.1)
'@typescript-eslint/parser': 8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/scope-manager': 8.58.2
'@typescript-eslint/type-utils': 8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/utils': 8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/visitor-keys': 8.58.2
eslint: 10.2.1(jiti@2.6.1)
ignore: 7.0.5
natural-compare: 1.4.0
ts-api-utils: 2.5.0(typescript@5.9.3)
@ -5578,58 +5574,58 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/parser@8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)':
'@typescript-eslint/parser@8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)':
dependencies:
'@typescript-eslint/scope-manager': 8.57.2
'@typescript-eslint/types': 8.57.2
'@typescript-eslint/typescript-estree': 8.57.2(typescript@5.9.3)
'@typescript-eslint/visitor-keys': 8.57.2
'@typescript-eslint/scope-manager': 8.58.2
'@typescript-eslint/types': 8.58.2
'@typescript-eslint/typescript-estree': 8.58.2(typescript@5.9.3)
'@typescript-eslint/visitor-keys': 8.58.2
debug: 4.4.3
eslint: 10.1.0(jiti@2.6.1)
eslint: 10.2.1(jiti@2.6.1)
typescript: 5.9.3
transitivePeerDependencies:
- supports-color
'@typescript-eslint/project-service@8.57.2(typescript@5.9.3)':
'@typescript-eslint/project-service@8.58.2(typescript@5.9.3)':
dependencies:
'@typescript-eslint/tsconfig-utils': 8.57.2(typescript@5.9.3)
'@typescript-eslint/types': 8.57.2
'@typescript-eslint/tsconfig-utils': 8.58.2(typescript@5.9.3)
'@typescript-eslint/types': 8.58.2
debug: 4.4.3
typescript: 5.9.3
transitivePeerDependencies:
- supports-color
'@typescript-eslint/scope-manager@8.57.2':
'@typescript-eslint/scope-manager@8.58.2':
dependencies:
'@typescript-eslint/types': 8.57.2
'@typescript-eslint/visitor-keys': 8.57.2
'@typescript-eslint/types': 8.58.2
'@typescript-eslint/visitor-keys': 8.58.2
'@typescript-eslint/tsconfig-utils@8.57.2(typescript@5.9.3)':
'@typescript-eslint/tsconfig-utils@8.58.2(typescript@5.9.3)':
dependencies:
typescript: 5.9.3
'@typescript-eslint/type-utils@8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)':
'@typescript-eslint/type-utils@8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)':
dependencies:
'@typescript-eslint/types': 8.57.2
'@typescript-eslint/typescript-estree': 8.57.2(typescript@5.9.3)
'@typescript-eslint/utils': 8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/types': 8.58.2
'@typescript-eslint/typescript-estree': 8.58.2(typescript@5.9.3)
'@typescript-eslint/utils': 8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
debug: 4.4.3
eslint: 10.1.0(jiti@2.6.1)
eslint: 10.2.1(jiti@2.6.1)
ts-api-utils: 2.5.0(typescript@5.9.3)
typescript: 5.9.3
transitivePeerDependencies:
- supports-color
'@typescript-eslint/types@8.57.2': {}
'@typescript-eslint/types@8.58.2': {}
'@typescript-eslint/typescript-estree@8.57.2(typescript@5.9.3)':
'@typescript-eslint/typescript-estree@8.58.2(typescript@5.9.3)':
dependencies:
'@typescript-eslint/project-service': 8.57.2(typescript@5.9.3)
'@typescript-eslint/tsconfig-utils': 8.57.2(typescript@5.9.3)
'@typescript-eslint/types': 8.57.2
'@typescript-eslint/visitor-keys': 8.57.2
'@typescript-eslint/project-service': 8.58.2(typescript@5.9.3)
'@typescript-eslint/tsconfig-utils': 8.58.2(typescript@5.9.3)
'@typescript-eslint/types': 8.58.2
'@typescript-eslint/visitor-keys': 8.58.2
debug: 4.4.3
minimatch: 10.2.4
minimatch: 10.2.5
semver: 7.7.4
tinyglobby: 0.2.16
ts-api-utils: 2.5.0(typescript@5.9.3)
@ -5637,20 +5633,20 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/utils@8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)':
'@typescript-eslint/utils@8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)':
dependencies:
'@eslint-community/eslint-utils': 4.9.1(eslint@10.1.0(jiti@2.6.1))
'@typescript-eslint/scope-manager': 8.57.2
'@typescript-eslint/types': 8.57.2
'@typescript-eslint/typescript-estree': 8.57.2(typescript@5.9.3)
eslint: 10.1.0(jiti@2.6.1)
'@eslint-community/eslint-utils': 4.9.1(eslint@10.2.1(jiti@2.6.1))
'@typescript-eslint/scope-manager': 8.58.2
'@typescript-eslint/types': 8.58.2
'@typescript-eslint/typescript-estree': 8.58.2(typescript@5.9.3)
eslint: 10.2.1(jiti@2.6.1)
typescript: 5.9.3
transitivePeerDependencies:
- supports-color
'@typescript-eslint/visitor-keys@8.57.2':
'@typescript-eslint/visitor-keys@8.58.2':
dependencies:
'@typescript-eslint/types': 8.57.2
'@typescript-eslint/types': 8.58.2
eslint-visitor-keys: 5.0.1
'@ungap/structured-clone@1.3.0': {}
@ -6013,24 +6009,24 @@ snapshots:
escape-string-regexp@5.0.0: {}
eslint-config-prettier@10.1.8(eslint@10.1.0(jiti@2.6.1)):
eslint-config-prettier@10.1.8(eslint@10.2.1(jiti@2.6.1)):
dependencies:
eslint: 10.1.0(jiti@2.6.1)
eslint: 10.2.1(jiti@2.6.1)
eslint-plugin-react-hooks@7.0.1(eslint@10.1.0(jiti@2.6.1)):
eslint-plugin-react-hooks@7.1.1(eslint@10.2.1(jiti@2.6.1)):
dependencies:
'@babel/core': 7.29.0
'@babel/parser': 7.29.2
eslint: 10.1.0(jiti@2.6.1)
eslint: 10.2.1(jiti@2.6.1)
hermes-parser: 0.25.1
zod: 4.3.6
zod-validation-error: 4.0.2(zod@4.3.6)
transitivePeerDependencies:
- supports-color
eslint-plugin-react-refresh@0.5.2(eslint@10.1.0(jiti@2.6.1)):
eslint-plugin-react-refresh@0.5.2(eslint@10.2.1(jiti@2.6.1)):
dependencies:
eslint: 10.1.0(jiti@2.6.1)
eslint: 10.2.1(jiti@2.6.1)
eslint-scope@9.1.2:
dependencies:
@ -6043,14 +6039,14 @@ snapshots:
eslint-visitor-keys@5.0.1: {}
eslint@10.1.0(jiti@2.6.1):
eslint@10.2.1(jiti@2.6.1):
dependencies:
'@eslint-community/eslint-utils': 4.9.1(eslint@10.1.0(jiti@2.6.1))
'@eslint-community/eslint-utils': 4.9.1(eslint@10.2.1(jiti@2.6.1))
'@eslint-community/regexpp': 4.12.2
'@eslint/config-array': 0.23.3
'@eslint/config-helpers': 0.5.3
'@eslint/core': 1.1.1
'@eslint/plugin-kit': 0.6.1
'@eslint/config-array': 0.23.5
'@eslint/config-helpers': 0.5.5
'@eslint/core': 1.2.1
'@eslint/plugin-kit': 0.7.1
'@humanfs/node': 0.16.7
'@humanwhocodes/module-importer': 1.0.1
'@humanwhocodes/retry': 0.4.3
@ -6072,7 +6068,7 @@ snapshots:
imurmurhash: 0.1.4
is-glob: 4.0.3
json-stable-stringify-without-jsonify: 1.0.1
minimatch: 10.2.4
minimatch: 10.2.5
natural-compare: 1.4.0
optionator: 0.9.4
optionalDependencies:
@ -7070,10 +7066,6 @@ snapshots:
mimic-function@5.0.1: {}
minimatch@10.2.4:
dependencies:
brace-expansion: 5.0.5
minimatch@10.2.5:
dependencies:
brace-expansion: 5.0.5
@ -7285,13 +7277,13 @@ snapshots:
prelude-ls@1.2.1: {}
prettier-plugin-tailwindcss@0.7.2(@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.1))(prettier@3.8.1):
prettier-plugin-tailwindcss@0.7.2(@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.3))(prettier@3.8.3):
dependencies:
prettier: 3.8.1
prettier: 3.8.3
optionalDependencies:
'@trivago/prettier-plugin-sort-imports': 6.0.2(prettier@3.8.1)
'@trivago/prettier-plugin-sort-imports': 6.0.2(prettier@3.8.3)
prettier@3.8.1: {}
prettier@3.8.3: {}
pretty-ms@9.3.0:
dependencies:
@ -7856,13 +7848,13 @@ snapshots:
media-typer: 1.1.0
mime-types: 3.0.2
typescript-eslint@8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3):
typescript-eslint@8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3):
dependencies:
'@typescript-eslint/eslint-plugin': 8.57.2(@typescript-eslint/parser@8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3))(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/parser': 8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/typescript-estree': 8.57.2(typescript@5.9.3)
'@typescript-eslint/utils': 8.57.2(eslint@10.1.0(jiti@2.6.1))(typescript@5.9.3)
eslint: 10.1.0(jiti@2.6.1)
'@typescript-eslint/eslint-plugin': 8.58.2(@typescript-eslint/parser@8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3))(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/parser': 8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
'@typescript-eslint/typescript-estree': 8.58.2(typescript@5.9.3)
'@typescript-eslint/utils': 8.58.2(eslint@10.2.1(jiti@2.6.1))(typescript@5.9.3)
eslint: 10.2.1(jiti@2.6.1)
typescript: 5.9.3
transitivePeerDependencies:
- supports-color

View file

@ -2,16 +2,16 @@ import { launcherFetch } from "@/api/http"
// API client for Pico Channel configuration.
interface PicoTokenResponse {
token: string
interface PicoInfoResponse {
ws_url: string
enabled: boolean
configured?: boolean
}
interface PicoSetupResponse {
token: string
ws_url: string
enabled: boolean
configured?: boolean
changed: boolean
}
@ -25,16 +25,16 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
return res.json() as Promise<T>
}
export async function getPicoToken(): Promise<PicoTokenResponse> {
return request<PicoTokenResponse>("/api/pico/token")
export async function getPicoInfo(): Promise<PicoInfoResponse> {
return request<PicoInfoResponse>("/api/pico/info")
}
export async function regenPicoToken(): Promise<PicoTokenResponse> {
return request<PicoTokenResponse>("/api/pico/token", { method: "POST" })
export async function regenPicoToken(): Promise<PicoInfoResponse> {
return request<PicoInfoResponse>("/api/pico/token", { method: "POST" })
}
export async function setupPico(): Promise<PicoSetupResponse> {
return request<PicoSetupResponse>("/api/pico/setup", { method: "POST" })
}
export type { PicoTokenResponse, PicoSetupResponse }
export type { PicoInfoResponse, PicoSetupResponse }

View file

@ -1,7 +1,6 @@
import { getDefaultStore } from "jotai"
import { toast } from "sonner"
import { getPicoToken } from "@/api/pico"
import {
loadSessionMessages,
mergeHistoryMessages,
@ -131,7 +130,6 @@ export async function connectChat() {
updateChatStore({ connectionState: "connecting" })
try {
const { token } = await getPicoToken()
const sessionId = activeSessionIdRef
if (generation !== connectionGeneration) {
@ -139,18 +137,10 @@ export async function connectChat() {
return
}
if (!token) {
console.error("No pico token available")
updateChatStore({ connectionState: "error" })
isConnecting = false
scheduleReconnect(generation, sessionId)
return
}
const wsScheme = window.location.protocol === "https:" ? "wss:" : "ws:"
const wsUrl = `${wsScheme}//${window.location.host}/pico/ws`
const url = `${wsUrl}?session_id=${encodeURIComponent(sessionId)}`
const socket = new WebSocket(url, [`token.${token}`])
const socket = new WebSocket(url)
if (generation !== connectionGeneration) {
isConnecting = false

View file

@ -29,7 +29,7 @@ export default defineConfig({
target: "http://localhost:18800",
changeOrigin: true,
},
"/ws": {
"/pico/ws": {
target: "ws://localhost:18800",
ws: true,
},

View file

@ -7,6 +7,7 @@ FreeRide gives you unlimited free AI in PicoClaw by automatically managing OpenR
- `/freeride auto`: Auto-configure best model + fallbacks.
- `/freeride list`: See all 30+ free models ranked.
- `/freeride status`: Check your current setup.
- `/freeride timeout 120`: Set request timeout for free models (seconds).
## How it works