Compare commits

..
Author SHA1 Message Date
Peter Steinberger 4c151760df fix: show account counts in connections UI (#813) (thanks @dbhurley) 2026-01-13 01:52:36 +00:00
DB Hurley 32c93aefbe feat(ui): display per-account status for multi-account Telegram
When multiple Telegram accounts are configured, the Connections UI now
displays individual status cards for each account showing:
- Bot username and account ID
- Running/configured status
- Last inbound message time
- Per-account errors

Falls back to the existing summary view for single-account configs.
No changes needed to types (already added upstream).
2026-01-13 01:52:36 +00:00
Peter Steinberger e0ddc488d0 Merge pull request #810 from mcinteerj/fix/runtime-reasoning-enforcement
fix(auto-reply): enforce reasoning tags on fallback providers
2026-01-13 01:46:41 +00:00
Peter Steinberger c012019a8a fix: enforce reasoning tags on fallback providers (#810) (thanks @mcinteerj) 2026-01-13 01:46:21 +00:00
Keith the Silly Goose 7896b30489 fix(auto-reply): enforce reasoning tags on fallback providers 2026-01-13 01:40:55 +00:00
Peter Steinberger ffc465394e fix: enforce message context isolation 2026-01-13 01:19:14 +00:00
Peter Steinberger 0edbdb1948 fix: downgrade Gemini tool history 2026-01-13 01:19:13 +00:00
hsrvc 5dc187f00c fix: accept Claude/Gemini tool param aliases 2026-01-13 01:19:13 +00:00
Peter Steinberger 231d2d5fdf fix(config): require doctor for invalid configs (#764 — thanks @mukhtharcm) 2026-01-13 01:18:18 +00:00
Muhammed Mukhthar CM 20ba8d4891 fix(config): preserve config data when validation fails
When readConfigFileSnapshot encounters validation errors, it now:
1. Returns the resolved config data instead of empty object
2. Uses passthrough() on main schema to preserve unknown fields

This prevents config loss when:
- User has custom/unknown fields
- Legacy config issues are detected but config is otherwise valid
- Zod schema does not recognize newer fields

Fixes config being overwritten with empty object on validation failure.
2026-01-13 01:16:13 +00:00
Peter Steinberger b32f6a0e00 docs: update clawtributors 2026-01-13 01:12:34 +00:00
Peter SteinbergerandThomsenDrake e5c77315ce chore: credit @ThomsenDrake
Co-authored-by: ThomsenDrake <ThomsenDrake@users.noreply.github.com>
2026-01-13 01:11:29 +00:00
Peter Steinberger dd8f7552ad refactor: reuse dispatcher helper for native commands 2026-01-13 01:07:59 +00:00
Peter Steinberger 92760de472 Merge pull request #781 from ronyrus/fix/update-doctor-noninteractive
fix: pass --non-interactive to doctor during update
2026-01-13 00:59:52 +00:00
Peter Steinberger 24190d09da fix: document non-interactive update doctor (#781) (thanks @ronyrus) 2026-01-13 00:58:56 +00:00
Rony Kelner 07bdb8af7e fix: pass --non-interactive to doctor during update 2026-01-13 00:57:18 +00:00
Peter Steinberger 6a48688c09 fix: stream native slash tool replies 2026-01-13 00:53:30 +00:00
Peter Steinberger c03a745f61 test: expand Minimax XML strip coverage 2026-01-13 00:43:59 +00:00
Peter Steinberger 48fdf3775d test: cover user turn merging 2026-01-13 00:42:15 +00:00
Peter Steinberger e5708d443a Merge pull request #809 from latitudeki5223/fix/minimax-tool-xml-leak
fix(minimax): strip tool invocation XML from assistant text
2026-01-13 00:37:29 +00:00
Peter Steinberger e2ea20f862 fix: gate minimax XML stripping (#809) (thanks @latitudeki5223) 2026-01-13 00:36:39 +00:00
L36 Server 1eb924739b style: fix import order in pi-embedded-utils.test.ts 2026-01-13 00:34:01 +00:00
L36 Server 350f956f2c fix(minimax): strip tool invocation XML from assistant text 2026-01-13 00:34:01 +00:00
Peter Steinberger 1f3ae2346e docs: clarify memory search auth 2026-01-13 00:26:01 +00:00
Peter Steinberger 4f3bedfdb7 fix: align discord autoThread config types 2026-01-13 00:22:42 +00:00
Peter Steinberger 6f75feaeb8 refactor: reuse model selection assertions 2026-01-13 00:20:08 +00:00
Peter Steinberger e949cc383f docs: update changelog 2026-01-13 00:16:15 +00:00
Peter Steinberger a4bd960880 refactor: streamline thread reply planning 2026-01-13 00:15:29 +00:00
Peter Steinberger 3636a2bf51 refactor: unify message tool + CLI 2026-01-13 00:12:57 +00:00
Peter Steinberger 103003d9ff docs: add provider shorthand redirects 2026-01-13 00:08:11 +00:00
Peter Steinberger ce23c70855 fix: validate Anthropic turn order (#804) (thanks @ThomsenDrake) 2026-01-12 23:43:25 +00:00
Drake Thomsen c5fa757ef6 fix(agents): prevent Anthropic 400 'Incorrect role information' error
Add validateAnthropicTurns() to merge consecutive user messages that can
occur when steering messages are injected during streaming. This prevents
the API from rejecting requests due to improper role alternation.

Changes:
- Add validateAnthropicTurns() function in pi-embedded-helpers.ts
- Integrate validation into sanitization pipeline in pi-embedded-runner.ts
- Add user-friendly error message for role ordering errors
- Add comprehensive tests for the new validation function
2026-01-12 23:42:13 +00:00
Peter Steinberger bb9a9633a8 fix: align reply threading refs 2026-01-12 23:41:40 +00:00
Peter Steinberger ca98f87b2f chore: reinforce memory recall prompts 2026-01-12 23:29:56 +00:00
Peter Steinberger df64771ecf test: cover fuzzy model selection 2026-01-12 23:16:54 +00:00
Peter Steinberger cbe11e3de0 fix: address lint warnings 2026-01-12 23:13:40 +00:00
Peter Steinberger daa753112c fix: unblock auto-reply lint/typecheck 2026-01-12 23:13:39 +00:00
David GuttmanandShadow 2e654e8d63 Fix Discord autoThread thread-only replies (#807)
Co-authored-by: Shadow <shadow@clawd.bot>
2026-01-12 17:11:48 -06:00
Peter Steinberger cf92099d40 test(auto-reply): fix heartbeat typing block reply assertions 2026-01-12 23:01:53 +00:00
Peter Steinberger a55c880191 docs: add changelog for sandbox memory shorthand 2026-01-12 22:59:36 +00:00
Peter Steinberger a8680f9a09 fix(auto-reply): fix streaming block reply media handling 2026-01-12 22:59:36 +00:00
Peter Steinberger 2e08a868a7 style: format native commands bits 2026-01-12 22:59:36 +00:00
Peter Steinberger 2785009c6f fix(config): resolve native commands schemas 2026-01-12 22:59:36 +00:00
Peter Steinberger 73d9469bf8 fix(telegram): tolerate missing native command APIs 2026-01-12 22:59:36 +00:00
Peter Steinberger 72100ba3ab refactor(sandbox): drop legacy memory shorthand 2026-01-12 22:59:36 +00:00
Peter Steinberger ec5099db89 fix: pick best fuzzy model match 2026-01-12 22:59:35 +00:00
Peter Steinberger 209380edf8 Merge pull request #801 from mcinteerj/fix/restore-reasoning-tag-check
fix(agent): restore reasoning tag enforcement for non-ollama providers
2026-01-12 22:59:13 +00:00
Peter Steinberger cf8251bb81 test: cover typing signals from block and tool streams 2026-01-12 22:55:17 +00:00
Jake eceb41f6f7 fix(agent): restore reasoning tag enforcement for non-ollama providers
This restores the fix from PR #754 which was accidentally reverted in bf11a42c3.
2026-01-13 09:47:04 +13:00
70 changed files with 3542 additions and 2012 deletions

No files matched your search

+27 -2
View File
@@ -1,5 +1,27 @@
# Changelog
## 2026.1.12-4
### Fixes
- Onboarding/Configure: refuse to proceed with invalid configs; run `clawdbot doctor` first to avoid wiping custom fields. (#764 — thanks @mukhtharcm)
- Anthropic: merge consecutive user turns (preserve newest metadata) before validation to avoid “Incorrect role information” errors. (#804 — thanks @ThomsenDrake)
- Connections UI: show account counts for multi-account providers and keep Telegram per-account cards. (#813 — thanks @dbhurley)
- Discord/Slack: centralize reply-thread planning so auto-thread replies stay in the created thread without parent reply refs.
- Update: run `clawdbot doctor --non-interactive` during updates to avoid TTY hangs. (#781 — thanks @ronyrus)
- Tools: allow Claude/Gemini tool param aliases (`file_path`, `old_string`, `new_string`) while enforcing required params at runtime. (#793 — thanks @hsrvc)
- Gemini: downgrade tool-call history missing `thought_signature` to avoid INVALID_ARGUMENT errors. (#793 — thanks @hsrvc)
- Messaging: enforce context isolation for message tool sends across providers (normalized targets + tests). (#793 — thanks @hsrvc)
- Auto-reply: re-evaluate reasoning tag enforcement on fallback providers to prevent leaked reasoning. (#810 — thanks @mcinteerj)
## 2026.1.12-3
### Changes
- Sandbox: drop legacy `memory` tool-policy shorthand; require explicit `group:memory`.
### Fixes
- Telegram: tolerate mocked bots missing native-command APIs (`setMyCommands`, `command`) during tests.
- Auto-reply: fix streaming block reply media handling (no redeclared/use-before-declare vars).
## 2026.1.12-2
### Changes
@@ -8,8 +30,10 @@
- Sandbox: support tool-policy groups in `tools.sandbox.tools` (e.g. `group:memory`, `group:fs`) to reduce config churn.
### Fixes
- Models/MiniMax: strip malformed tool invocation XML (`<invoke>...</invoke>` and `</minimax:tool_call>`) from assistant text to prevent tool call leaks into user messages. (#809 — thanks @latitudeki5223)
- Tools/Models: MiniMax vision now uses the Coding Plan VLM endpoint (`/v1/coding_plan/vlm`) so the `image` tool works with MiniMax keys (also accepts `@/path/to/file.png`-style inputs).
- Gateway/macOS: reduce noisy loopback WS “closed before connect” logs during tests.
- Gateway/macOS: reduce noisy loopback WS "closed before connect" logs during tests.
- Auto-reply: resolve ambiguous `/model` fuzzy matches by picking the best candidate instead of erroring.
## 2026.1.12-1
@@ -23,6 +47,7 @@
- Memory: add vector search for agent memories (Markdown-only scope) with SQLite index, chunking, lazy sync + file watch, and per-agent enablement/fallback.
### Changes
- Agents: strengthen memory recall guidance (memory_search mandatory for past work/preferences; system prompt injects conditional recall section; memory_get now described as safe snippet fetch).
- Browser: add `scrollintoview` action to scroll refs into view before click/type.
- Memory: embedding providers support OpenAI or local `node-llama-cpp`; config adds defaults + per-agent overrides, provider/fallback metadata surfaced in tools/CLI.
- CLI/Tools: new `clawdbot memory` commands plus `memory_search`/`memory_get` tools returning snippets + line ranges and provider info.
@@ -34,7 +59,6 @@
### Fixes
- Auto-reply: inline `/status` now honors allowlists (authorized stripped + replied inline; unauthorized leaves text for the agent) to match command gating tests.
- Auto-reply: enforce `<final>` tag for all reasoning-tag providers (Gemini Antigravity, MiniMax, etc.), not just Ollama. (#801 — thanks @mcinteerj)
- Models: normalize `${ENV_VAR}` apiKey config values and auto-fill missing provider `apiKey` from env/auth when custom provider models are configured (fixes MiniMax “Unknown model” on fresh installs).
- Models/Tools: include `MiniMax-VL-01` in implicit MiniMax provider so image pairing uses a real vision model.
- Telegram: show typing indicator in General forum topics. (#779) — thanks @azade-c.
@@ -47,6 +71,7 @@
- Auto-reply: elevated/reasoning toggles now enqueue system events so the model sees the mode change immediately.
- Tools: keep `image` available in sandbox and fail over when image models return empty output (fixes “(no text returned)”).
- Discord: add per-channel `autoThread` to auto-create threads for top-level messages. (#800) — thanks @davidguttman.
- Discord: fix autoThread routing so replies stay in the created thread and avoid reply references. (#807) — thanks @davidguttman.
- Onboarding: TUI defaults to `deliver: false` to avoid cross-provider auto-delivery leaks; onboarding spawns the TUI with explicit `deliver: false`. (#791 — thanks @roshanasingh4)
## 2026.1.11
+16 -15
View File
@@ -458,20 +458,21 @@ Special thanks to @andrewting19 for the Anthropic OAuth tool-name fix.
Thanks to all clawtributors:
<p align="left">
<a href="https://github.com/steipete"><img src="https://avatars.githubusercontent.com/u/58493?v=4&s=48" width="48" height="48" alt="steipete" title="steipete"/></a> <a href="https://github.com/joaohlisboa"><img src="https://avatars.githubusercontent.com/u/8200873?v=4&s=48" width="48" height="48" alt="joaohlisboa" title="joaohlisboa"/></a> <a href="https://github.com/mneves75"><img src="https://avatars.githubusercontent.com/u/2423436?v=4&s=48" width="48" height="48" alt="mneves75" title="mneves75"/></a> <a href="https://github.com/rahthakor"><img src="https://avatars.githubusercontent.com/u/8470553?v=4&s=48" width="48" height="48" alt="rahthakor" title="rahthakor"/></a> <a href="https://github.com/joshp123"><img src="https://avatars.githubusercontent.com/u/1497361?v=4&s=48" width="48" height="48" alt="joshp123" title="joshp123"/></a> <a href="https://github.com/mukhtharcm"><img src="https://avatars.githubusercontent.com/u/56378562?v=4&s=48" width="48" height="48" alt="mukhtharcm" title="mukhtharcm"/></a> <a href="https://github.com/maxsumrall"><img src="https://avatars.githubusercontent.com/u/628843?v=4&s=48" width="48" height="48" alt="maxsumrall" title="maxsumrall"/></a> <a href="https://github.com/xadenryan"><img src="https://avatars.githubusercontent.com/u/165437834?v=4&s=48" width="48" height="48" alt="xadenryan" title="xadenryan"/></a> <a href="https://github.com/tobiasbischoff"><img src="https://avatars.githubusercontent.com/u/711564?v=4&s=48" width="48" height="48" alt="Tobias Bischoff" title="Tobias Bischoff"/></a> <a href="https://github.com/magimetal"><img src="https://avatars.githubusercontent.com/u/36491250?v=4&s=48" width="48" height="48" alt="magimetal" title="magimetal"/></a>
<a href="https://github.com/NicholasSpisak"><img src="https://avatars.githubusercontent.com/u/129075147?v=4&s=48" width="48" height="48" alt="NicholasSpisak" title="NicholasSpisak"/></a> <a href="https://github.com/hsrvc"><img src="https://avatars.githubusercontent.com/u/129702169?v=4&s=48" width="48" height="48" alt="hsrvc" title="hsrvc"/></a> <a href="https://github.com/claude"><img src="https://avatars.githubusercontent.com/u/81847?v=4&s=48" width="48" height="48" alt="claude" title="claude"/></a> <a href="https://github.com/jamesgroat"><img src="https://avatars.githubusercontent.com/u/2634024?v=4&s=48" width="48" height="48" alt="jamesgroat" title="jamesgroat"/></a> <a href="https://github.com/dantelex"><img src="https://avatars.githubusercontent.com/u/631543?v=4&s=48" width="48" height="48" alt="dantelex" title="dantelex"/></a> <a href="https://github.com/daveonkels"><img src="https://avatars.githubusercontent.com/u/533642?v=4&s=48" width="48" height="48" alt="daveonkels" title="daveonkels"/></a> <a href="https://github.com/radek-paclt"><img src="https://avatars.githubusercontent.com/u/50451445?v=4&s=48" width="48" height="48" alt="radek-paclt" title="radek-paclt"/></a> <a href="https://github.com/jeffersonwarrior"><img src="https://avatars.githubusercontent.com/u/89030989?v=4&s=48" width="48" height="48" alt="jeffersonwarrior" title="jeffersonwarrior"/></a> <a href="https://github.com/mteam88"><img src="https://avatars.githubusercontent.com/u/84196639?v=4&s=48" width="48" height="48" alt="mteam88" title="mteam88"/></a> <a href="https://github.com/omniwired"><img src="https://avatars.githubusercontent.com/u/322761?v=4&s=48" width="48" height="48" alt="Eng. Juan Combetto" title="Eng. Juan Combetto"/></a>
<a href="https://github.com/steipete"><img src="https://avatars.githubusercontent.com/u/58493?v=4&s=48" width="48" height="48" alt="steipete" title="steipete"/></a> <a href="https://github.com/joaohlisboa"><img src="https://avatars.githubusercontent.com/u/8200873?v=4&s=48" width="48" height="48" alt="joaohlisboa" title="joaohlisboa"/></a> <a href="https://github.com/mneves75"><img src="https://avatars.githubusercontent.com/u/2423436?v=4&s=48" width="48" height="48" alt="mneves75" title="mneves75"/></a> <a href="https://github.com/rahthakor"><img src="https://avatars.githubusercontent.com/u/8470553?v=4&s=48" width="48" height="48" alt="rahthakor" title="rahthakor"/></a> <a href="https://github.com/joshp123"><img src="https://avatars.githubusercontent.com/u/1497361?v=4&s=48" width="48" height="48" alt="joshp123" title="joshp123"/></a> <a href="https://github.com/mukhtharcm"><img src="https://avatars.githubusercontent.com/u/56378562?v=4&s=48" width="48" height="48" alt="mukhtharcm" title="mukhtharcm"/></a> <a href="https://github.com/maxsumrall"><img src="https://avatars.githubusercontent.com/u/628843?v=4&s=48" width="48" height="48" alt="maxsumrall" title="maxsumrall"/></a> <a href="https://github.com/xadenryan"><img src="https://avatars.githubusercontent.com/u/165437834?v=4&s=48" width="48" height="48" alt="xadenryan" title="xadenryan"/></a> <a href="https://github.com/tobiasbischoff"><img src="https://avatars.githubusercontent.com/u/711564?v=4&s=48" width="48" height="48" alt="Tobias Bischoff" title="Tobias Bischoff"/></a> <a href="https://github.com/hsrvc"><img src="https://avatars.githubusercontent.com/u/129702169?v=4&s=48" width="48" height="48" alt="hsrvc" title="hsrvc"/></a>
<a href="https://github.com/magimetal"><img src="https://avatars.githubusercontent.com/u/36491250?v=4&s=48" width="48" height="48" alt="magimetal" title="magimetal"/></a> <a href="https://github.com/NicholasSpisak"><img src="https://avatars.githubusercontent.com/u/129075147?v=4&s=48" width="48" height="48" alt="NicholasSpisak" title="NicholasSpisak"/></a> <a href="https://github.com/claude"><img src="https://avatars.githubusercontent.com/u/81847?v=4&s=48" width="48" height="48" alt="claude" title="claude"/></a> <a href="https://github.com/jamesgroat"><img src="https://avatars.githubusercontent.com/u/2634024?v=4&s=48" width="48" height="48" alt="jamesgroat" title="jamesgroat"/></a> <a href="https://github.com/dantelex"><img src="https://avatars.githubusercontent.com/u/631543?v=4&s=48" width="48" height="48" alt="dantelex" title="dantelex"/></a> <a href="https://github.com/daveonkels"><img src="https://avatars.githubusercontent.com/u/533642?v=4&s=48" width="48" height="48" alt="daveonkels" title="daveonkels"/></a> <a href="https://github.com/radek-paclt"><img src="https://avatars.githubusercontent.com/u/50451445?v=4&s=48" width="48" height="48" alt="radek-paclt" title="radek-paclt"/></a> <a href="https://github.com/jeffersonwarrior"><img src="https://avatars.githubusercontent.com/u/89030989?v=4&s=48" width="48" height="48" alt="jeffersonwarrior" title="jeffersonwarrior"/></a> <a href="https://github.com/mteam88"><img src="https://avatars.githubusercontent.com/u/84196639?v=4&s=48" width="48" height="48" alt="mteam88" title="mteam88"/></a> <a href="https://github.com/omniwired"><img src="https://avatars.githubusercontent.com/u/322761?v=4&s=48" width="48" height="48" alt="Eng. Juan Combetto" title="Eng. Juan Combetto"/></a>
<a href="https://github.com/mbelinky"><img src="https://avatars.githubusercontent.com/u/132747814?v=4&s=48" width="48" height="48" alt="Mariano Belinky" title="Mariano Belinky"/></a> <a href="https://github.com/julianengel"><img src="https://avatars.githubusercontent.com/u/10634231?v=4&s=48" width="48" height="48" alt="julianengel" title="julianengel"/></a> <a href="https://github.com/benithors"><img src="https://avatars.githubusercontent.com/u/20652882?v=4&s=48" width="48" height="48" alt="benithors" title="benithors"/></a> <a href="https://github.com/sreekaransrinath"><img src="https://avatars.githubusercontent.com/u/50989977?v=4&s=48" width="48" height="48" alt="sreekaransrinath" title="sreekaransrinath"/></a> <a href="https://github.com/dbhurley"><img src="https://avatars.githubusercontent.com/u/5251425?v=4&s=48" width="48" height="48" alt="dbhurley" title="dbhurley"/></a> <a href="https://github.com/gupsammy"><img src="https://avatars.githubusercontent.com/u/20296019?v=4&s=48" width="48" height="48" alt="gupsammy" title="gupsammy"/></a> <a href="https://github.com/cristip73"><img src="https://avatars.githubusercontent.com/u/24499421?v=4&s=48" width="48" height="48" alt="cristip73" title="cristip73"/></a> <a href="https://github.com/nachoiacovino"><img src="https://avatars.githubusercontent.com/u/50103937?v=4&s=48" width="48" height="48" alt="nachoiacovino" title="nachoiacovino"/></a> <a href="https://github.com/vsabavat"><img src="https://avatars.githubusercontent.com/u/50385532?v=4&s=48" width="48" height="48" alt="Vasanth Rao Naik Sabavat" title="Vasanth Rao Naik Sabavat"/></a> <a href="https://github.com/lc0rp"><img src="https://avatars.githubusercontent.com/u/2609441?v=4&s=48" width="48" height="48" alt="lc0rp" title="lc0rp"/></a>
<a href="https://github.com/scald"><img src="https://avatars.githubusercontent.com/u/1215913?v=4&s=48" width="48" height="48" alt="scald" title="scald"/></a> <a href="https://github.com/andranik-sahakyan"><img src="https://avatars.githubusercontent.com/u/8908029?v=4&s=48" width="48" height="48" alt="andranik-sahakyan" title="andranik-sahakyan"/></a> <a href="https://github.com/Nachx639"><img src="https://avatars.githubusercontent.com/u/71144023?v=4&s=48" width="48" height="48" alt="nachx639" title="nachx639"/></a> <a href="https://github.com/sircrumpet"><img src="https://avatars.githubusercontent.com/u/4436535?v=4&s=48" width="48" height="48" alt="sircrumpet" title="sircrumpet"/></a> <a href="https://github.com/peschee"><img src="https://avatars.githubusercontent.com/u/63866?v=4&s=48" width="48" height="48" alt="peschee" title="peschee"/></a> <a href="https://github.com/rafaelreis-r"><img src="https://avatars.githubusercontent.com/u/57492577?v=4&s=48" width="48" height="48" alt="rafaelreis-r" title="rafaelreis-r"/></a> <a href="https://github.com/meaningfool"><img src="https://avatars.githubusercontent.com/u/2862331?v=4&s=48" width="48" height="48" alt="meaningfool" title="meaningfool"/></a> <a href="https://github.com/ratulsarna"><img src="https://avatars.githubusercontent.com/u/105903728?v=4&s=48" width="48" height="48" alt="ratulsarna" title="ratulsarna"/></a> <a href="https://github.com/lutr0"><img src="https://avatars.githubusercontent.com/u/76906369?v=4&s=48" width="48" height="48" alt="lutr0" title="lutr0"/></a> <a href="https://github.com/AbhisekBasu1"><img src="https://avatars.githubusercontent.com/u/40645221?v=4&s=48" width="48" height="48" alt="abhisekbasu1" title="abhisekbasu1"/></a>
<a href="https://github.com/thewilloftheshadow"><img src="https://avatars.githubusercontent.com/u/35580099?v=4&s=48" width="48" height="48" alt="thewilloftheshadow" title="thewilloftheshadow"/></a> <a href="https://github.com/emanuelst"><img src="https://avatars.githubusercontent.com/u/9994339?v=4&s=48" width="48" height="48" alt="emanuelst" title="emanuelst"/></a> <a href="https://github.com/KristijanJovanovski"><img src="https://avatars.githubusercontent.com/u/8942284?v=4&s=48" width="48" height="48" alt="KristijanJovanovski" title="KristijanJovanovski"/></a> <a href="https://github.com/osolmaz"><img src="https://avatars.githubusercontent.com/u/2453968?v=4&s=48" width="48" height="48" alt="osolmaz" title="osolmaz"/></a> <a href="https://github.com/kiranjd"><img src="https://avatars.githubusercontent.com/u/25822851?v=4&s=48" width="48" height="48" alt="kiranjd" title="kiranjd"/></a> <a href="https://github.com/sebslight"><img src="https://avatars.githubusercontent.com/u/19554889?v=4&s=48" width="48" height="48" alt="Sebastian Barrios" title="Sebastian Barrios"/></a> <a href="https://github.com/search?q=sheeek"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="sheeek" title="sheeek"/></a> <a href="https://github.com/onutc"><img src="https://avatars.githubusercontent.com/u/152018508?v=4&s=48" width="48" height="48" alt="onutc" title="onutc"/></a> <a href="https://github.com/CashWilliams"><img src="https://avatars.githubusercontent.com/u/613573?v=4&s=48" width="48" height="48" alt="CashWilliams" title="CashWilliams"/></a> <a href="https://github.com/ManuelHettich"><img src="https://avatars.githubusercontent.com/u/17690367?v=4&s=48" width="48" height="48" alt="manuelhettich" title="manuelhettich"/></a>
<a href="https://github.com/minghinmatthewlam"><img src="https://avatars.githubusercontent.com/u/14224566?v=4&s=48" width="48" height="48" alt="minghinmatthewlam" title="minghinmatthewlam"/></a> <a href="https://github.com/myfunc"><img src="https://avatars.githubusercontent.com/u/19294627?v=4&s=48" width="48" height="48" alt="myfunc" title="myfunc"/></a> <a href="https://github.com/buddyh"><img src="https://avatars.githubusercontent.com/u/31752869?v=4&s=48" width="48" height="48" alt="buddyh" title="buddyh"/></a> <a href="https://github.com/mcinteerj"><img src="https://avatars.githubusercontent.com/u/3613653?v=4&s=48" width="48" height="48" alt="mcinteerj" title="mcinteerj"/></a> <a href="https://github.com/timkrase"><img src="https://avatars.githubusercontent.com/u/38947626?v=4&s=48" width="48" height="48" alt="timkrase" title="timkrase"/></a> <a href="https://github.com/azade-c"><img src="https://avatars.githubusercontent.com/u/252790079?v=4&s=48" width="48" height="48" alt="azade-c" title="azade-c"/></a> <a href="https://github.com/obviyus"><img src="https://avatars.githubusercontent.com/u/22031114?v=4&s=48" width="48" height="48" alt="obviyus" title="obviyus"/></a> <a href="https://github.com/bjesuiter"><img src="https://avatars.githubusercontent.com/u/2365676?v=4&s=48" width="48" height="48" alt="bjesuiter" title="bjesuiter"/></a> <a href="https://github.com/superman32432432"><img src="https://avatars.githubusercontent.com/u/7228420?v=4&s=48" width="48" height="48" alt="superman32432432" title="superman32432432"/></a> <a href="https://github.com/search?q=Yurii%20Chukhlib"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Yurii Chukhlib" title="Yurii Chukhlib"/></a>
<a href="https://github.com/antons"><img src="https://avatars.githubusercontent.com/u/129705?v=4&s=48" width="48" height="48" alt="antons" title="antons"/></a> <a href="https://github.com/austinm911"><img src="https://avatars.githubusercontent.com/u/31991302?v=4&s=48" width="48" height="48" alt="austinm911" title="austinm911"/></a> <a href="https://github.com/apps/blacksmith-sh"><img src="https://avatars.githubusercontent.com/in/807020?v=4&s=48" width="48" height="48" alt="blacksmith-sh[bot]" title="blacksmith-sh[bot]"/></a> <a href="https://github.com/imfing"><img src="https://avatars.githubusercontent.com/u/5097752?v=4&s=48" width="48" height="48" alt="imfing" title="imfing"/></a> <a href="https://github.com/jarvis-medmatic"><img src="https://avatars.githubusercontent.com/u/252428873?v=4&s=48" width="48" height="48" alt="jarvis-medmatic" title="jarvis-medmatic"/></a> <a href="https://github.com/mahmoudashraf93"><img src="https://avatars.githubusercontent.com/u/9130129?v=4&s=48" width="48" height="48" alt="mahmoudashraf93" title="mahmoudashraf93"/></a> <a href="https://github.com/petter-b"><img src="https://avatars.githubusercontent.com/u/62076402?v=4&s=48" width="48" height="48" alt="petter-b" title="petter-b"/></a> <a href="https://github.com/pkrmf"><img src="https://avatars.githubusercontent.com/u/1714267?v=4&s=48" width="48" height="48" alt="pkrmf" title="pkrmf"/></a> <a href="https://github.com/RandyVentures"><img src="https://avatars.githubusercontent.com/u/149904821?v=4&s=48" width="48" height="48" alt="RandyVentures" title="RandyVentures"/></a> <a href="https://github.com/dan-dr"><img src="https://avatars.githubusercontent.com/u/6669808?v=4&s=48" width="48" height="48" alt="dan-dr" title="dan-dr"/></a>
<a href="https://github.com/HeimdallStrategy"><img src="https://avatars.githubusercontent.com/u/223014405?v=4&s=48" width="48" height="48" alt="HeimdallStrategy" title="HeimdallStrategy"/></a> <a href="https://github.com/jalehman"><img src="https://avatars.githubusercontent.com/u/550978?v=4&s=48" width="48" height="48" alt="jalehman" title="jalehman"/></a> <a href="https://github.com/jonasjancarik"><img src="https://avatars.githubusercontent.com/u/2459191?v=4&s=48" width="48" height="48" alt="jonasjancarik" title="jonasjancarik"/></a> <a href="https://github.com/neist"><img src="https://avatars.githubusercontent.com/u/1029724?v=4&s=48" width="48" height="48" alt="neist" title="neist"/></a> <a href="https://github.com/Iamadig"><img src="https://avatars.githubusercontent.com/u/102129234?v=4&s=48" width="48" height="48" alt="iamadig" title="iamadig"/></a> <a href="https://github.com/koala73"><img src="https://avatars.githubusercontent.com/u/996596?v=4&s=48" width="48" height="48" alt="koala73" title="koala73"/></a> <a href="https://github.com/manmal"><img src="https://avatars.githubusercontent.com/u/142797?v=4&s=48" width="48" height="48" alt="manmal" title="manmal"/></a> <a href="https://github.com/ogulcancelik"><img src="https://avatars.githubusercontent.com/u/7064011?v=4&s=48" width="48" height="48" alt="ogulcancelik" title="ogulcancelik"/></a> <a href="https://github.com/pasogott"><img src="https://avatars.githubusercontent.com/u/23458152?v=4&s=48" width="48" height="48" alt="pasogott" title="pasogott"/></a> <a href="https://github.com/petradonka"><img src="https://avatars.githubusercontent.com/u/7353770?v=4&s=48" width="48" height="48" alt="petradonka" title="petradonka"/></a>
<a href="https://github.com/VACInc"><img src="https://avatars.githubusercontent.com/u/3279061?v=4&s=48" width="48" height="48" alt="VACInc" title="VACInc"/></a> <a href="https://github.com/zats"><img src="https://avatars.githubusercontent.com/u/2688806?v=4&s=48" width="48" height="48" alt="zats" title="zats"/></a> <a href="https://github.com/search?q=Chris%20Taylor"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Chris Taylor" title="Chris Taylor"/></a> <a href="https://github.com/djangonavarro220"><img src="https://avatars.githubusercontent.com/u/251162586?v=4&s=48" width="48" height="48" alt="Django Navarro" title="Django Navarro"/></a> <a href="https://github.com/gabriel-trigo"><img src="https://avatars.githubusercontent.com/u/38991125?v=4&s=48" width="48" height="48" alt="gabriel-trigo" title="gabriel-trigo"/></a> <a href="https://github.com/search?q=Kit"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Kit" title="Kit"/></a> <a href="https://github.com/search?q=L36%20Server"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="L36 Server" title="L36 Server"/></a> <a href="https://github.com/ngutman"><img src="https://avatars.githubusercontent.com/u/1540134?v=4&s=48" width="48" height="48" alt="ngutman" title="ngutman"/></a> <a href="https://github.com/pcty-nextgen-service-account"><img src="https://avatars.githubusercontent.com/u/112553441?v=4&s=48" width="48" height="48" alt="pcty-nextgen-service-account" title="pcty-nextgen-service-account"/></a> <a href="https://github.com/rubyrunsstuff"><img src="https://avatars.githubusercontent.com/u/246602379?v=4&s=48" width="48" height="48" alt="rubyrunsstuff" title="rubyrunsstuff"/></a>
<a href="https://github.com/Syhids"><img src="https://avatars.githubusercontent.com/u/671202?v=4&s=48" width="48" height="48" alt="Syhids" title="Syhids"/></a> <a href="https://github.com/danielz1z"><img src="https://avatars.githubusercontent.com/u/235270390?v=4&s=48" width="48" height="48" alt="danielz1z" title="danielz1z"/></a> <a href="https://github.com/erik-agens"><img src="https://avatars.githubusercontent.com/u/80908960?v=4&s=48" width="48" height="48" alt="erik-agens" title="erik-agens"/></a> <a href="https://github.com/erikpr1994"><img src="https://avatars.githubusercontent.com/u/6299331?v=4&s=48" width="48" height="48" alt="erikpr1994" title="erikpr1994"/></a> <a href="https://github.com/fcatuhe"><img src="https://avatars.githubusercontent.com/u/17382215?v=4&s=48" width="48" height="48" alt="fcatuhe" title="fcatuhe"/></a> <a href="https://github.com/henrino3"><img src="https://avatars.githubusercontent.com/u/4260288?v=4&s=48" width="48" height="48" alt="henrino3" title="henrino3"/></a> <a href="https://github.com/jayhickey"><img src="https://avatars.githubusercontent.com/u/1676460?v=4&s=48" width="48" height="48" alt="jayhickey" title="jayhickey"/></a> <a href="https://github.com/jdrhyne"><img src="https://avatars.githubusercontent.com/u/7828464?v=4&s=48" width="48" height="48" alt="Jonathan D. Rhyne (DJ-D)" title="Jonathan D. Rhyne (DJ-D)"/></a> <a href="https://github.com/juanpablodlc"><img src="https://avatars.githubusercontent.com/u/92012363?v=4&s=48" width="48" height="48" alt="juanpablodlc" title="juanpablodlc"/></a> <a href="https://github.com/jverdi"><img src="https://avatars.githubusercontent.com/u/345050?v=4&s=48" width="48" height="48" alt="jverdi" title="jverdi"/></a>
<a href="https://github.com/search?q=Keith%20the%20Silly%20Goose"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Keith the Silly Goose" title="Keith the Silly Goose"/></a> <a href="https://github.com/mitschabaude-bot"><img src="https://avatars.githubusercontent.com/u/247582884?v=4&s=48" width="48" height="48" alt="mitschabaude-bot" title="mitschabaude-bot"/></a> <a href="https://github.com/mjrussell"><img src="https://avatars.githubusercontent.com/u/1641895?v=4&s=48" width="48" height="48" alt="mjrussell" title="mjrussell"/></a> <a href="https://github.com/oswalpalash"><img src="https://avatars.githubusercontent.com/u/6431196?v=4&s=48" width="48" height="48" alt="oswalpalash" title="oswalpalash"/></a> <a href="https://github.com/p6l-richard"><img src="https://avatars.githubusercontent.com/u/18185649?v=4&s=48" width="48" height="48" alt="p6l-richard" title="p6l-richard"/></a> <a href="https://github.com/philipp-spiess"><img src="https://avatars.githubusercontent.com/u/458591?v=4&s=48" width="48" height="48" alt="philipp-spiess" title="philipp-spiess"/></a> <a href="https://github.com/search?q=Sash%20Catanzarite"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Sash Catanzarite" title="Sash Catanzarite"/></a> <a href="https://github.com/search?q=VAC"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="VAC" title="VAC"/></a> <a href="https://github.com/adam91holt"><img src="https://avatars.githubusercontent.com/u/9592417?v=4&s=48" width="48" height="48" alt="adam91holt" title="adam91holt"/></a> <a href="https://github.com/search?q=alejandro%20maza"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="alejandro maza" title="alejandro maza"/></a>
<a href="https://github.com/andrewting19"><img src="https://avatars.githubusercontent.com/u/10536704?v=4&s=48" width="48" height="48" alt="andrewting19" title="andrewting19"/></a> <a href="https://github.com/Asleep123"><img src="https://avatars.githubusercontent.com/u/122379135?v=4&s=48" width="48" height="48" alt="Asleep123" title="Asleep123"/></a> <a href="https://github.com/bolismauro"><img src="https://avatars.githubusercontent.com/u/771999?v=4&s=48" width="48" height="48" alt="bolismauro" title="bolismauro"/></a> <a href="https://github.com/cash-echo-bot"><img src="https://avatars.githubusercontent.com/u/252747386?v=4&s=48" width="48" height="48" alt="cash-echo-bot" title="cash-echo-bot"/></a> <a href="https://github.com/search?q=Clawd"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Clawd" title="Clawd"/></a> <a href="https://github.com/conhecendocontato"><img src="https://avatars.githubusercontent.com/u/82890727?v=4&s=48" width="48" height="48" alt="conhecendocontato" title="conhecendocontato"/></a> <a href="https://github.com/evalexpr"><img src="https://avatars.githubusercontent.com/u/23485511?v=4&s=48" width="48" height="48" alt="evalexpr" title="evalexpr"/></a> <a href="https://github.com/gtsifrikas"><img src="https://avatars.githubusercontent.com/u/8904378?v=4&s=48" width="48" height="48" alt="gtsifrikas" title="gtsifrikas"/></a> <a href="https://github.com/HazAT"><img src="https://avatars.githubusercontent.com/u/363802?v=4&s=48" width="48" height="48" alt="HazAT" title="HazAT"/></a> <a href="https://github.com/hrdwdmrbl"><img src="https://avatars.githubusercontent.com/u/554881?v=4&s=48" width="48" height="48" alt="hrdwdmrbl" title="hrdwdmrbl"/></a>
<a href="https://github.com/hugobarauna"><img src="https://avatars.githubusercontent.com/u/2719?v=4&s=48" width="48" height="48" alt="hugobarauna" title="hugobarauna"/></a> <a href="https://github.com/search?q=Jarvis"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Jarvis" title="Jarvis"/></a> <a href="https://github.com/kitze"><img src="https://avatars.githubusercontent.com/u/1160594?v=4&s=48" width="48" height="48" alt="kitze" title="kitze"/></a> <a href="https://github.com/kkarimi"><img src="https://avatars.githubusercontent.com/u/875218?v=4&s=48" width="48" height="48" alt="kkarimi" title="kkarimi"/></a> <a href="https://github.com/levifig"><img src="https://avatars.githubusercontent.com/u/1605?v=4&s=48" width="48" height="48" alt="levifig" title="levifig"/></a> <a href="https://github.com/search?q=Lloyd"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Lloyd" title="Lloyd"/></a> <a href="https://github.com/loukotal"><img src="https://avatars.githubusercontent.com/u/18210858?v=4&s=48" width="48" height="48" alt="loukotal" title="loukotal"/></a> <a href="https://github.com/martinpucik"><img src="https://avatars.githubusercontent.com/u/5503097?v=4&s=48" width="48" height="48" alt="martinpucik" title="martinpucik"/></a> <a href="https://github.com/mickahouan"><img src="https://avatars.githubusercontent.com/u/31423109?v=4&s=48" width="48" height="48" alt="mickahouan" title="mickahouan"/></a> <a href="https://github.com/search?q=Miles"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Miles" title="Miles"/></a>
<a href="https://github.com/mrdbstn"><img src="https://avatars.githubusercontent.com/u/58957632?v=4&s=48" width="48" height="48" alt="mrdbstn" title="mrdbstn"/></a> <a href="https://github.com/MSch"><img src="https://avatars.githubusercontent.com/u/7475?v=4&s=48" width="48" height="48" alt="MSch" title="MSch"/></a> <a href="https://github.com/nexty5870"><img src="https://avatars.githubusercontent.com/u/3869659?v=4&s=48" width="48" height="48" alt="nexty5870" title="nexty5870"/></a> <a href="https://github.com/prathamdby"><img src="https://avatars.githubusercontent.com/u/134331217?v=4&s=48" width="48" height="48" alt="prathamdby" title="prathamdby"/></a> <a href="https://github.com/reeltimeapps"><img src="https://avatars.githubusercontent.com/u/637338?v=4&s=48" width="48" height="48" alt="reeltimeapps" title="reeltimeapps"/></a> <a href="https://github.com/RLTCmpe"><img src="https://avatars.githubusercontent.com/u/10762242?v=4&s=48" width="48" height="48" alt="RLTCmpe" title="RLTCmpe"/></a> <a href="https://github.com/search?q=Rolf%20Fredheim"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Rolf Fredheim" title="Rolf Fredheim"/></a> <a href="https://github.com/roshanasingh4"><img src="https://avatars.githubusercontent.com/u/88576930?v=4&s=48" width="48" height="48" alt="roshanasingh4" title="roshanasingh4"/></a> <a href="https://github.com/search?q=Samrat%20Jha"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Samrat Jha" title="Samrat Jha"/></a> <a href="https://github.com/snopoke"><img src="https://avatars.githubusercontent.com/u/249606?v=4&s=48" width="48" height="48" alt="snopoke" title="snopoke"/></a>
<a href="https://github.com/search?q=The%20Admiral"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="The Admiral" title="The Admiral"/></a> <a href="https://github.com/wes-davis"><img src="https://avatars.githubusercontent.com/u/16506720?v=4&s=48" width="48" height="48" alt="wes-davis" title="wes-davis"/></a> <a href="https://github.com/wstock"><img src="https://avatars.githubusercontent.com/u/1394687?v=4&s=48" width="48" height="48" alt="wstock" title="wstock"/></a> <a href="https://github.com/YuriNachos"><img src="https://avatars.githubusercontent.com/u/19365375?v=4&s=48" width="48" height="48" alt="YuriNachos" title="YuriNachos"/></a> <a href="https://github.com/search?q=Zach%20Knickerbocker"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Zach Knickerbocker" title="Zach Knickerbocker"/></a> <a href="https://github.com/zknicker"><img src="https://avatars.githubusercontent.com/u/1164085?v=4&s=48" width="48" height="48" alt="zknicker" title="zknicker"/></a> <a href="https://github.com/search?q=Azade"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Azade" title="Azade"/></a> <a href="https://github.com/carlulsoe"><img src="https://avatars.githubusercontent.com/u/34673973?v=4&s=48" width="48" height="48" alt="carlulsoe" title="carlulsoe"/></a> <a href="https://github.com/search?q=ddyo"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="ddyo" title="ddyo"/></a> <a href="https://github.com/search?q=Erik"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Erik" title="Erik"/></a>
<a href="https://github.com/latitudeki5223"><img src="https://avatars.githubusercontent.com/u/119656367?v=4&s=48" width="48" height="48" alt="latitudeki5223" title="latitudeki5223"/></a> <a href="https://github.com/search?q=Manuel%20Maly"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Manuel Maly" title="Manuel Maly"/></a> <a href="https://github.com/search?q=Mourad%20Boustani"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Mourad Boustani" title="Mourad Boustani"/></a> <a href="https://github.com/pcty-nextgen-ios-builder"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="pcty-nextgen-ios-builder" title="pcty-nextgen-ios-builder"/></a> <a href="https://github.com/search?q=Quentin"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Quentin" title="Quentin"/></a> <a href="https://github.com/search?q=Randy%20Torres"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Randy Torres" title="Randy Torres"/></a> <a href="https://github.com/thesash"><img src="https://avatars.githubusercontent.com/u/1166151?v=4&s=48" width="48" height="48" alt="thesash" title="thesash"/></a> <a href="https://github.com/search?q=William%20Stock"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="William Stock" title="William Stock"/></a>
<a href="https://github.com/scald"><img src="https://avatars.githubusercontent.com/u/1215913?v=4&s=48" width="48" height="48" alt="scald" title="scald"/></a> <a href="https://github.com/andranik-sahakyan"><img src="https://avatars.githubusercontent.com/u/8908029?v=4&s=48" width="48" height="48" alt="andranik-sahakyan" title="andranik-sahakyan"/></a> <a href="https://github.com/Nachx639"><img src="https://avatars.githubusercontent.com/u/71144023?v=4&s=48" width="48" height="48" alt="nachx639" title="nachx639"/></a> <a href="https://github.com/davidguttman"><img src="https://avatars.githubusercontent.com/u/431696?v=4&s=48" width="48" height="48" alt="davidguttman" title="davidguttman"/></a> <a href="https://github.com/sircrumpet"><img src="https://avatars.githubusercontent.com/u/4436535?v=4&s=48" width="48" height="48" alt="sircrumpet" title="sircrumpet"/></a> <a href="https://github.com/peschee"><img src="https://avatars.githubusercontent.com/u/63866?v=4&s=48" width="48" height="48" alt="peschee" title="peschee"/></a> <a href="https://github.com/rafaelreis-r"><img src="https://avatars.githubusercontent.com/u/57492577?v=4&s=48" width="48" height="48" alt="rafaelreis-r" title="rafaelreis-r"/></a> <a href="https://github.com/meaningfool"><img src="https://avatars.githubusercontent.com/u/2862331?v=4&s=48" width="48" height="48" alt="meaningfool" title="meaningfool"/></a> <a href="https://github.com/ratulsarna"><img src="https://avatars.githubusercontent.com/u/105903728?v=4&s=48" width="48" height="48" alt="ratulsarna" title="ratulsarna"/></a> <a href="https://github.com/lutr0"><img src="https://avatars.githubusercontent.com/u/76906369?v=4&s=48" width="48" height="48" alt="lutr0" title="lutr0"/></a>
<a href="https://github.com/AbhisekBasu1"><img src="https://avatars.githubusercontent.com/u/40645221?v=4&s=48" width="48" height="48" alt="abhisekbasu1" title="abhisekbasu1"/></a> <a href="https://github.com/thewilloftheshadow"><img src="https://avatars.githubusercontent.com/u/35580099?v=4&s=48" width="48" height="48" alt="thewilloftheshadow" title="thewilloftheshadow"/></a> <a href="https://github.com/emanuelst"><img src="https://avatars.githubusercontent.com/u/9994339?v=4&s=48" width="48" height="48" alt="emanuelst" title="emanuelst"/></a> <a href="https://github.com/KristijanJovanovski"><img src="https://avatars.githubusercontent.com/u/8942284?v=4&s=48" width="48" height="48" alt="KristijanJovanovski" title="KristijanJovanovski"/></a> <a href="https://github.com/osolmaz"><img src="https://avatars.githubusercontent.com/u/2453968?v=4&s=48" width="48" height="48" alt="osolmaz" title="osolmaz"/></a> <a href="https://github.com/kiranjd"><img src="https://avatars.githubusercontent.com/u/25822851?v=4&s=48" width="48" height="48" alt="kiranjd" title="kiranjd"/></a> <a href="https://github.com/sebslight"><img src="https://avatars.githubusercontent.com/u/19554889?v=4&s=48" width="48" height="48" alt="Sebastian Barrios" title="Sebastian Barrios"/></a> <a href="https://github.com/search?q=sheeek"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="sheeek" title="sheeek"/></a> <a href="https://github.com/onutc"><img src="https://avatars.githubusercontent.com/u/152018508?v=4&s=48" width="48" height="48" alt="onutc" title="onutc"/></a> <a href="https://github.com/CashWilliams"><img src="https://avatars.githubusercontent.com/u/613573?v=4&s=48" width="48" height="48" alt="CashWilliams" title="CashWilliams"/></a>
<a href="https://github.com/ManuelHettich"><img src="https://avatars.githubusercontent.com/u/17690367?v=4&s=48" width="48" height="48" alt="manuelhettich" title="manuelhettich"/></a> <a href="https://github.com/minghinmatthewlam"><img src="https://avatars.githubusercontent.com/u/14224566?v=4&s=48" width="48" height="48" alt="minghinmatthewlam" title="minghinmatthewlam"/></a> <a href="https://github.com/myfunc"><img src="https://avatars.githubusercontent.com/u/19294627?v=4&s=48" width="48" height="48" alt="myfunc" title="myfunc"/></a> <a href="https://github.com/buddyh"><img src="https://avatars.githubusercontent.com/u/31752869?v=4&s=48" width="48" height="48" alt="buddyh" title="buddyh"/></a> <a href="https://github.com/mcinteerj"><img src="https://avatars.githubusercontent.com/u/3613653?v=4&s=48" width="48" height="48" alt="mcinteerj" title="mcinteerj"/></a> <a href="https://github.com/timkrase"><img src="https://avatars.githubusercontent.com/u/38947626?v=4&s=48" width="48" height="48" alt="timkrase" title="timkrase"/></a> <a href="https://github.com/obviyus"><img src="https://avatars.githubusercontent.com/u/22031114?v=4&s=48" width="48" height="48" alt="obviyus" title="obviyus"/></a> <a href="https://github.com/azade-c"><img src="https://avatars.githubusercontent.com/u/252790079?v=4&s=48" width="48" height="48" alt="azade-c" title="azade-c"/></a> <a href="https://github.com/bjesuiter"><img src="https://avatars.githubusercontent.com/u/2365676?v=4&s=48" width="48" height="48" alt="bjesuiter" title="bjesuiter"/></a> <a href="https://github.com/superman32432432"><img src="https://avatars.githubusercontent.com/u/7228420?v=4&s=48" width="48" height="48" alt="superman32432432" title="superman32432432"/></a>
<a href="https://github.com/search?q=Yurii%20Chukhlib"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Yurii Chukhlib" title="Yurii Chukhlib"/></a> <a href="https://github.com/antons"><img src="https://avatars.githubusercontent.com/u/129705?v=4&s=48" width="48" height="48" alt="antons" title="antons"/></a> <a href="https://github.com/austinm911"><img src="https://avatars.githubusercontent.com/u/31991302?v=4&s=48" width="48" height="48" alt="austinm911" title="austinm911"/></a> <a href="https://github.com/apps/blacksmith-sh"><img src="https://avatars.githubusercontent.com/in/807020?v=4&s=48" width="48" height="48" alt="blacksmith-sh[bot]" title="blacksmith-sh[bot]"/></a> <a href="https://github.com/imfing"><img src="https://avatars.githubusercontent.com/u/5097752?v=4&s=48" width="48" height="48" alt="imfing" title="imfing"/></a> <a href="https://github.com/jarvis-medmatic"><img src="https://avatars.githubusercontent.com/u/252428873?v=4&s=48" width="48" height="48" alt="jarvis-medmatic" title="jarvis-medmatic"/></a> <a href="https://github.com/mahmoudashraf93"><img src="https://avatars.githubusercontent.com/u/9130129?v=4&s=48" width="48" height="48" alt="mahmoudashraf93" title="mahmoudashraf93"/></a> <a href="https://github.com/petter-b"><img src="https://avatars.githubusercontent.com/u/62076402?v=4&s=48" width="48" height="48" alt="petter-b" title="petter-b"/></a> <a href="https://github.com/pkrmf"><img src="https://avatars.githubusercontent.com/u/1714267?v=4&s=48" width="48" height="48" alt="pkrmf" title="pkrmf"/></a> <a href="https://github.com/RandyVentures"><img src="https://avatars.githubusercontent.com/u/149904821?v=4&s=48" width="48" height="48" alt="RandyVentures" title="RandyVentures"/></a>
<a href="https://github.com/dan-dr"><img src="https://avatars.githubusercontent.com/u/6669808?v=4&s=48" width="48" height="48" alt="dan-dr" title="dan-dr"/></a> <a href="https://github.com/HeimdallStrategy"><img src="https://avatars.githubusercontent.com/u/223014405?v=4&s=48" width="48" height="48" alt="HeimdallStrategy" title="HeimdallStrategy"/></a> <a href="https://github.com/jalehman"><img src="https://avatars.githubusercontent.com/u/550978?v=4&s=48" width="48" height="48" alt="jalehman" title="jalehman"/></a> <a href="https://github.com/jonasjancarik"><img src="https://avatars.githubusercontent.com/u/2459191?v=4&s=48" width="48" height="48" alt="jonasjancarik" title="jonasjancarik"/></a> <a href="https://github.com/search?q=L36%20Server"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="L36 Server" title="L36 Server"/></a> <a href="https://github.com/neist"><img src="https://avatars.githubusercontent.com/u/1029724?v=4&s=48" width="48" height="48" alt="neist" title="neist"/></a> <a href="https://github.com/Iamadig"><img src="https://avatars.githubusercontent.com/u/102129234?v=4&s=48" width="48" height="48" alt="iamadig" title="iamadig"/></a> <a href="https://github.com/search?q=Keith%20the%20Silly%20Goose"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Keith the Silly Goose" title="Keith the Silly Goose"/></a> <a href="https://github.com/search?q=Kit"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Kit" title="Kit"/></a> <a href="https://github.com/koala73"><img src="https://avatars.githubusercontent.com/u/996596?v=4&s=48" width="48" height="48" alt="koala73" title="koala73"/></a>
<a href="https://github.com/manmal"><img src="https://avatars.githubusercontent.com/u/142797?v=4&s=48" width="48" height="48" alt="manmal" title="manmal"/></a> <a href="https://github.com/ogulcancelik"><img src="https://avatars.githubusercontent.com/u/7064011?v=4&s=48" width="48" height="48" alt="ogulcancelik" title="ogulcancelik"/></a> <a href="https://github.com/pasogott"><img src="https://avatars.githubusercontent.com/u/23458152?v=4&s=48" width="48" height="48" alt="pasogott" title="pasogott"/></a> <a href="https://github.com/petradonka"><img src="https://avatars.githubusercontent.com/u/7353770?v=4&s=48" width="48" height="48" alt="petradonka" title="petradonka"/></a> <a href="https://github.com/VACInc"><img src="https://avatars.githubusercontent.com/u/3279061?v=4&s=48" width="48" height="48" alt="VACInc" title="VACInc"/></a> <a href="https://github.com/zats"><img src="https://avatars.githubusercontent.com/u/2688806?v=4&s=48" width="48" height="48" alt="zats" title="zats"/></a> <a href="https://github.com/search?q=Chris%20Taylor"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Chris Taylor" title="Chris Taylor"/></a> <a href="https://github.com/djangonavarro220"><img src="https://avatars.githubusercontent.com/u/251162586?v=4&s=48" width="48" height="48" alt="Django Navarro" title="Django Navarro"/></a> <a href="https://github.com/gabriel-trigo"><img src="https://avatars.githubusercontent.com/u/38991125?v=4&s=48" width="48" height="48" alt="gabriel-trigo" title="gabriel-trigo"/></a> <a href="https://github.com/ngutman"><img src="https://avatars.githubusercontent.com/u/1540134?v=4&s=48" width="48" height="48" alt="ngutman" title="ngutman"/></a>
<a href="https://github.com/pcty-nextgen-service-account"><img src="https://avatars.githubusercontent.com/u/112553441?v=4&s=48" width="48" height="48" alt="pcty-nextgen-service-account" title="pcty-nextgen-service-account"/></a> <a href="https://github.com/rubyrunsstuff"><img src="https://avatars.githubusercontent.com/u/246602379?v=4&s=48" width="48" height="48" alt="rubyrunsstuff" title="rubyrunsstuff"/></a> <a href="https://github.com/Syhids"><img src="https://avatars.githubusercontent.com/u/671202?v=4&s=48" width="48" height="48" alt="Syhids" title="Syhids"/></a> <a href="https://github.com/search?q=Aaron%20Konyer"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Aaron Konyer" title="Aaron Konyer"/></a> <a href="https://github.com/danielz1z"><img src="https://avatars.githubusercontent.com/u/235270390?v=4&s=48" width="48" height="48" alt="danielz1z" title="danielz1z"/></a> <a href="https://github.com/erik-agens"><img src="https://avatars.githubusercontent.com/u/80908960?v=4&s=48" width="48" height="48" alt="erik-agens" title="erik-agens"/></a> <a href="https://github.com/erikpr1994"><img src="https://avatars.githubusercontent.com/u/6299331?v=4&s=48" width="48" height="48" alt="erikpr1994" title="erikpr1994"/></a> <a href="https://github.com/fcatuhe"><img src="https://avatars.githubusercontent.com/u/17382215?v=4&s=48" width="48" height="48" alt="fcatuhe" title="fcatuhe"/></a> <a href="https://github.com/henrino3"><img src="https://avatars.githubusercontent.com/u/4260288?v=4&s=48" width="48" height="48" alt="henrino3" title="henrino3"/></a> <a href="https://github.com/jayhickey"><img src="https://avatars.githubusercontent.com/u/1676460?v=4&s=48" width="48" height="48" alt="jayhickey" title="jayhickey"/></a>
<a href="https://github.com/jdrhyne"><img src="https://avatars.githubusercontent.com/u/7828464?v=4&s=48" width="48" height="48" alt="Jonathan D. Rhyne (DJ-D)" title="Jonathan D. Rhyne (DJ-D)"/></a> <a href="https://github.com/juanpablodlc"><img src="https://avatars.githubusercontent.com/u/92012363?v=4&s=48" width="48" height="48" alt="juanpablodlc" title="juanpablodlc"/></a> <a href="https://github.com/jverdi"><img src="https://avatars.githubusercontent.com/u/345050?v=4&s=48" width="48" height="48" alt="jverdi" title="jverdi"/></a> <a href="https://github.com/mitschabaude-bot"><img src="https://avatars.githubusercontent.com/u/247582884?v=4&s=48" width="48" height="48" alt="mitschabaude-bot" title="mitschabaude-bot"/></a> <a href="https://github.com/mjrussell"><img src="https://avatars.githubusercontent.com/u/1641895?v=4&s=48" width="48" height="48" alt="mjrussell" title="mjrussell"/></a> <a href="https://github.com/oswalpalash"><img src="https://avatars.githubusercontent.com/u/6431196?v=4&s=48" width="48" height="48" alt="oswalpalash" title="oswalpalash"/></a> <a href="https://github.com/p6l-richard"><img src="https://avatars.githubusercontent.com/u/18185649?v=4&s=48" width="48" height="48" alt="p6l-richard" title="p6l-richard"/></a> <a href="https://github.com/philipp-spiess"><img src="https://avatars.githubusercontent.com/u/458591?v=4&s=48" width="48" height="48" alt="philipp-spiess" title="philipp-spiess"/></a> <a href="https://github.com/roshanasingh4"><img src="https://avatars.githubusercontent.com/u/88576930?v=4&s=48" width="48" height="48" alt="roshanasingh4" title="roshanasingh4"/></a> <a href="https://github.com/search?q=Sash%20Catanzarite"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Sash Catanzarite" title="Sash Catanzarite"/></a>
<a href="https://github.com/search?q=VAC"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="VAC" title="VAC"/></a> <a href="https://github.com/zknicker"><img src="https://avatars.githubusercontent.com/u/1164085?v=4&s=48" width="48" height="48" alt="zknicker" title="zknicker"/></a> <a href="https://github.com/adam91holt"><img src="https://avatars.githubusercontent.com/u/9592417?v=4&s=48" width="48" height="48" alt="adam91holt" title="adam91holt"/></a> <a href="https://github.com/search?q=alejandro%20maza"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="alejandro maza" title="alejandro maza"/></a> <a href="https://github.com/andrewting19"><img src="https://avatars.githubusercontent.com/u/10536704?v=4&s=48" width="48" height="48" alt="andrewting19" title="andrewting19"/></a> <a href="https://github.com/Asleep123"><img src="https://avatars.githubusercontent.com/u/122379135?v=4&s=48" width="48" height="48" alt="Asleep123" title="Asleep123"/></a> <a href="https://github.com/bolismauro"><img src="https://avatars.githubusercontent.com/u/771999?v=4&s=48" width="48" height="48" alt="bolismauro" title="bolismauro"/></a> <a href="https://github.com/cash-echo-bot"><img src="https://avatars.githubusercontent.com/u/252747386?v=4&s=48" width="48" height="48" alt="cash-echo-bot" title="cash-echo-bot"/></a> <a href="https://github.com/search?q=Clawd"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Clawd" title="Clawd"/></a> <a href="https://github.com/conhecendocontato"><img src="https://avatars.githubusercontent.com/u/82890727?v=4&s=48" width="48" height="48" alt="conhecendocontato" title="conhecendocontato"/></a>
<a href="https://github.com/search?q=Drake%20Thomsen"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Drake Thomsen" title="Drake Thomsen"/></a> <a href="https://github.com/evalexpr"><img src="https://avatars.githubusercontent.com/u/23485511?v=4&s=48" width="48" height="48" alt="evalexpr" title="evalexpr"/></a> <a href="https://github.com/gtsifrikas"><img src="https://avatars.githubusercontent.com/u/8904378?v=4&s=48" width="48" height="48" alt="gtsifrikas" title="gtsifrikas"/></a> <a href="https://github.com/HazAT"><img src="https://avatars.githubusercontent.com/u/363802?v=4&s=48" width="48" height="48" alt="HazAT" title="HazAT"/></a> <a href="https://github.com/hrdwdmrbl"><img src="https://avatars.githubusercontent.com/u/554881?v=4&s=48" width="48" height="48" alt="hrdwdmrbl" title="hrdwdmrbl"/></a> <a href="https://github.com/hugobarauna"><img src="https://avatars.githubusercontent.com/u/2719?v=4&s=48" width="48" height="48" alt="hugobarauna" title="hugobarauna"/></a> <a href="https://github.com/search?q=Jarvis"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Jarvis" title="Jarvis"/></a> <a href="https://github.com/kitze"><img src="https://avatars.githubusercontent.com/u/1160594?v=4&s=48" width="48" height="48" alt="kitze" title="kitze"/></a> <a href="https://github.com/kkarimi"><img src="https://avatars.githubusercontent.com/u/875218?v=4&s=48" width="48" height="48" alt="kkarimi" title="kkarimi"/></a> <a href="https://github.com/levifig"><img src="https://avatars.githubusercontent.com/u/1605?v=4&s=48" width="48" height="48" alt="levifig" title="levifig"/></a>
<a href="https://github.com/search?q=Lloyd"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Lloyd" title="Lloyd"/></a> <a href="https://github.com/loukotal"><img src="https://avatars.githubusercontent.com/u/18210858?v=4&s=48" width="48" height="48" alt="loukotal" title="loukotal"/></a> <a href="https://github.com/martinpucik"><img src="https://avatars.githubusercontent.com/u/5503097?v=4&s=48" width="48" height="48" alt="martinpucik" title="martinpucik"/></a> <a href="https://github.com/mickahouan"><img src="https://avatars.githubusercontent.com/u/31423109?v=4&s=48" width="48" height="48" alt="mickahouan" title="mickahouan"/></a> <a href="https://github.com/search?q=Miles"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Miles" title="Miles"/></a> <a href="https://github.com/mrdbstn"><img src="https://avatars.githubusercontent.com/u/58957632?v=4&s=48" width="48" height="48" alt="mrdbstn" title="mrdbstn"/></a> <a href="https://github.com/MSch"><img src="https://avatars.githubusercontent.com/u/7475?v=4&s=48" width="48" height="48" alt="MSch" title="MSch"/></a> <a href="https://github.com/search?q=Mustafa%20Tag%20Eldeen"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Mustafa Tag Eldeen" title="Mustafa Tag Eldeen"/></a> <a href="https://github.com/nexty5870"><img src="https://avatars.githubusercontent.com/u/3869659?v=4&s=48" width="48" height="48" alt="nexty5870" title="nexty5870"/></a> <a href="https://github.com/prathamdby"><img src="https://avatars.githubusercontent.com/u/134331217?v=4&s=48" width="48" height="48" alt="prathamdby" title="prathamdby"/></a>
<a href="https://github.com/reeltimeapps"><img src="https://avatars.githubusercontent.com/u/637338?v=4&s=48" width="48" height="48" alt="reeltimeapps" title="reeltimeapps"/></a> <a href="https://github.com/RLTCmpe"><img src="https://avatars.githubusercontent.com/u/10762242?v=4&s=48" width="48" height="48" alt="RLTCmpe" title="RLTCmpe"/></a> <a href="https://github.com/search?q=Rolf%20Fredheim"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Rolf Fredheim" title="Rolf Fredheim"/></a> <a href="https://github.com/search?q=Rony%20Kelner"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Rony Kelner" title="Rony Kelner"/></a> <a href="https://github.com/search?q=Samrat%20Jha"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Samrat Jha" title="Samrat Jha"/></a> <a href="https://github.com/snopoke"><img src="https://avatars.githubusercontent.com/u/249606?v=4&s=48" width="48" height="48" alt="snopoke" title="snopoke"/></a> <a href="https://github.com/search?q=The%20Admiral"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="The Admiral" title="The Admiral"/></a> <a href="https://github.com/wes-davis"><img src="https://avatars.githubusercontent.com/u/16506720?v=4&s=48" width="48" height="48" alt="wes-davis" title="wes-davis"/></a> <a href="https://github.com/wstock"><img src="https://avatars.githubusercontent.com/u/1394687?v=4&s=48" width="48" height="48" alt="wstock" title="wstock"/></a> <a href="https://github.com/YuriNachos"><img src="https://avatars.githubusercontent.com/u/19365375?v=4&s=48" width="48" height="48" alt="YuriNachos" title="YuriNachos"/></a>
<a href="https://github.com/search?q=Zach%20Knickerbocker"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Zach Knickerbocker" title="Zach Knickerbocker"/></a> <a href="https://github.com/search?q=Azade"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Azade" title="Azade"/></a> <a href="https://github.com/carlulsoe"><img src="https://avatars.githubusercontent.com/u/34673973?v=4&s=48" width="48" height="48" alt="carlulsoe" title="carlulsoe"/></a> <a href="https://github.com/search?q=ddyo"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="ddyo" title="ddyo"/></a> <a href="https://github.com/search?q=Erik"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Erik" title="Erik"/></a> <a href="https://github.com/latitudeki5223"><img src="https://avatars.githubusercontent.com/u/119656367?v=4&s=48" width="48" height="48" alt="latitudeki5223" title="latitudeki5223"/></a> <a href="https://github.com/search?q=Manuel%20Maly"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Manuel Maly" title="Manuel Maly"/></a> <a href="https://github.com/search?q=Mourad%20Boustani"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Mourad Boustani" title="Mourad Boustani"/></a> <a href="https://github.com/pcty-nextgen-ios-builder"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="pcty-nextgen-ios-builder" title="pcty-nextgen-ios-builder"/></a> <a href="https://github.com/search?q=Quentin"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Quentin" title="Quentin"/></a>
<a href="https://github.com/search?q=Randy%20Torres"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Randy Torres" title="Randy Torres"/></a> <a href="https://github.com/thesash"><img src="https://avatars.githubusercontent.com/u/1166151?v=4&s=48" width="48" height="48" alt="thesash" title="thesash"/></a> <a href="https://github.com/search?q=William%20Stock"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="William Stock" title="William Stock"/></a>
</p>
+2 -2
View File
@@ -46,7 +46,7 @@ Target formats (`--to`):
- Providers: WhatsApp/Telegram/Discord/Slack/Signal/iMessage/MS Teams
- Required: `--to`, `--message`
- Optional: `--media`, `--reply-to`, `--thread-id`, `--gif-playback`
- Telegram only: `--buttons-json` (requires `"inlineButtons"` in `telegram.capabilities` or `telegram.accounts.<id>.capabilities`)
- Telegram only: `--buttons` (requires `"inlineButtons"` in `telegram.capabilities` or `telegram.accounts.<id>.capabilities`)
- Telegram only: `--thread-id` (forum topic id)
- Slack only: `--thread-id` (thread timestamp; `--reply-to` uses the same field)
- WhatsApp only: `--gif-playback`
@@ -206,5 +206,5 @@ clawdbot message react --provider slack \
Send Telegram inline buttons:
```
clawdbot message send --provider telegram --to @mychat --message "Choose:" \
--buttons-json '[ [{"text":"Yes","callback_data":"cmd:yes"}], [{"text":"No","callback_data":"cmd:no"}] ]'
--buttons '[ [{"text":"Yes","callback_data":"cmd:yes"}], [{"text":"No","callback_data":"cmd:no"}] ]'
```
+6
View File
@@ -79,6 +79,12 @@ Defaults:
- Uses remote embeddings (OpenAI) unless configured for local.
- Local mode uses node-llama-cpp and may require `pnpm approve-builds`.
Remote embeddings **require** an OpenAI API key (`OPENAI_API_KEY` or
`models.providers.openai.apiKey`). Codex OAuth only covers chat/completions and
does **not** satisfy embeddings for memory search. If you don't want to set an
API key, use `memorySearch.provider = "local"` or set
`memorySearch.fallback = "none"`.
Config example:
```json5
+74 -2
View File
@@ -45,6 +45,70 @@
"source": "/messages/",
"destination": "/concepts/messages"
},
{
"source": "/minimax",
"destination": "/providers/minimax"
},
{
"source": "/minimax/",
"destination": "/providers/minimax"
},
{
"source": "/openai",
"destination": "/providers/openai"
},
{
"source": "/openai/",
"destination": "/providers/openai"
},
{
"source": "/anthropic",
"destination": "/providers/anthropic"
},
{
"source": "/anthropic/",
"destination": "/providers/anthropic"
},
{
"source": "/moonshot",
"destination": "/providers/moonshot"
},
{
"source": "/moonshot/",
"destination": "/providers/moonshot"
},
{
"source": "/openrouter",
"destination": "/providers/openrouter"
},
{
"source": "/openrouter/",
"destination": "/providers/openrouter"
},
{
"source": "/opencode",
"destination": "/providers/opencode"
},
{
"source": "/opencode/",
"destination": "/providers/opencode"
},
{
"source": "/glm",
"destination": "/providers/glm"
},
{
"source": "/glm/",
"destination": "/providers/glm"
},
{
"source": "/zai",
"destination": "/providers/zai"
},
{
"source": "/zai/",
"destination": "/providers/zai"
},
{
"source": "/message",
"destination": "/cli/message"
@@ -675,14 +739,22 @@
{
"group": "Providers",
"pages": [
"providers/whatsapp",
"broadcast-groups",
"providers/openai",
"providers/anthropic",
"providers/moonshot",
"providers/minimax",
"providers/openrouter",
"providers/opencode",
"providers/glm",
"providers/zai",
"providers/telegram",
"providers/grammy",
"providers/discord",
"providers/slack",
"providers/signal",
"providers/imessage",
"providers/whatsapp",
"broadcast-groups",
"providers/msteams",
"providers/troubleshooting",
"providers/location"
@@ -79,8 +79,6 @@ Available groups:
- `group:sessions`: `sessions_list`, `sessions_history`, `sessions_send`, `sessions_spawn`, `session_status`
- `group:memory`: `memory_search`, `memory_get`
Legacy shorthand: `memory` expands to `group:memory`.
## Elevated: exec-only “run on host”
Elevated does **not** grant extra tools; it only affects `exec`.
-2
View File
@@ -182,8 +182,6 @@ Sandbox tool policy supports `group:*` entries that expand to multiple concrete
- `group:sessions`: `sessions_list`, `sessions_history`, `sessions_send`, `sessions_spawn`, `session_status`
- `group:memory`: `memory_search`, `memory_get`
Legacy shorthand: `memory` expands to `group:memory`.
### Elevated Mode
`tools.elevated` is the global baseline (sender-based allowlist). `agents.list[].tools.elevated` can further restrict elevated for specific agents (both must allow).
+8
View File
@@ -231,6 +231,14 @@ Clawdbot also runs a **silent pre-compaction memory flush** to remind the model
to write durable notes before auto-compaction. This only runs when the workspace
is writable (read-only sandboxes skip it). See [Memory](/concepts/memory).
### Why does memory search need an OpenAI API key if I already signed in with Codex?
Vector memory search uses **embeddings**. Codex OAuth only covers
chat/completions and does **not** grant embeddings access, so the upstream
memory indexer needs a real OpenAI API key (`OPENAI_API_KEY` or
`models.providers.openai.apiKey`). If you don’t want to set a key, switch to
`memorySearch.provider = "local"` or set `memorySearch.fallback = "none"`.
## Where things live on disk
### Where does Clawdbot store its data?
+2
View File
@@ -64,6 +64,8 @@ Tip: `--json` does **not** imply non-interactive mode. Use `--non-interactive` (
1) **Existing config detection**
- If `~/.clawdbot/clawdbot.json` exists, choose **Keep / Modify / Reset**.
- If the config is invalid or contains legacy keys, the wizard stops and asks
you to run `clawdbot doctor` before continuing.
- Reset uses `trash` (never `rm`) and offers scopes:
- Config only
- Config + credentials + sessions
+1
View File
@@ -179,6 +179,7 @@ Core actions:
Notes:
- `send` routes WhatsApp via the Gateway; other providers go direct.
- `poll` uses the Gateway for WhatsApp and MS Teams; Discord polls go direct.
- When a message tool call is bound to an active chat session, sends are constrained to that session’s target to avoid cross-context leaks.
### `cron`
Manage Gateway cron jobs and wakeups.
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import {
isMessagingToolDuplicate,
normalizeTextForComparison,
} from "./pi-embedded-helpers.js";
describe("normalizeTextForComparison", () => {
it("lowercases text", () => {
expect(normalizeTextForComparison("Hello World")).toBe("hello world");
});
it("trims whitespace", () => {
expect(normalizeTextForComparison(" hello ")).toBe("hello");
});
it("collapses multiple spaces", () => {
expect(normalizeTextForComparison("hello world")).toBe("hello world");
});
it("strips emoji", () => {
expect(normalizeTextForComparison("Hello 👋 World 🌍")).toBe("hello world");
});
it("handles mixed normalization", () => {
expect(normalizeTextForComparison(" Hello 👋 WORLD 🌍 ")).toBe(
"hello world",
);
});
});
describe("isMessagingToolDuplicate", () => {
it("returns false for empty sentTexts", () => {
expect(isMessagingToolDuplicate("hello world", [])).toBe(false);
});
it("returns false for short texts", () => {
expect(isMessagingToolDuplicate("short", ["short"])).toBe(false);
});
it("detects exact duplicates", () => {
expect(
isMessagingToolDuplicate("Hello, this is a test message!", [
"Hello, this is a test message!",
]),
).toBe(true);
});
it("detects duplicates with different casing", () => {
expect(
isMessagingToolDuplicate("HELLO, THIS IS A TEST MESSAGE!", [
"hello, this is a test message!",
]),
).toBe(true);
});
it("detects duplicates with emoji variations", () => {
expect(
isMessagingToolDuplicate("Hello! 👋 This is a test message!", [
"Hello! This is a test message!",
]),
).toBe(true);
});
it("detects substring duplicates (LLM elaboration)", () => {
expect(
isMessagingToolDuplicate(
'I sent the message: "Hello, this is a test message!"',
["Hello, this is a test message!"],
),
).toBe(true);
});
it("detects when sent text contains block reply (reverse substring)", () => {
expect(
isMessagingToolDuplicate("Hello, this is a test message!", [
'I sent the message: "Hello, this is a test message!"',
]),
).toBe(true);
});
it("returns false for non-matching texts", () => {
expect(
isMessagingToolDuplicate("This is completely different content.", [
"Hello, this is a test message!",
]),
).toBe(false);
});
});
+9 -226
View File
@@ -10,12 +10,9 @@ import {
isCompactionFailureError,
isContextOverflowError,
isFailoverErrorMessage,
isMessagingToolDuplicate,
normalizeTextForComparison,
sanitizeGoogleTurnOrdering,
sanitizeSessionMessagesImages,
sanitizeToolCallId,
validateGeminiTurns,
} from "./pi-embedded-helpers.js";
import {
DEFAULT_AGENTS_FILENAME,
@@ -31,146 +28,6 @@ const makeFile = (
missing: false,
...overrides,
});
describe("validateGeminiTurns", () => {
it("should return empty array unchanged", () => {
const result = validateGeminiTurns([]);
expect(result).toEqual([]);
});
it("should return single message unchanged", () => {
const msgs: AgentMessage[] = [
{
role: "user",
content: "Hello",
},
];
const result = validateGeminiTurns(msgs);
expect(result).toEqual(msgs);
});
it("should leave alternating user/assistant unchanged", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: [{ type: "text", text: "Hi" }] },
{ role: "user", content: "How are you?" },
{ role: "assistant", content: [{ type: "text", text: "Good!" }] },
];
const result = validateGeminiTurns(msgs);
expect(result).toHaveLength(4);
expect(result).toEqual(msgs);
});
it("should merge consecutive assistant messages", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: "Hello" },
{
role: "assistant",
content: [{ type: "text", text: "Part 1" }],
stopReason: "end_turn",
},
{
role: "assistant",
content: [{ type: "text", text: "Part 2" }],
stopReason: "end_turn",
},
{ role: "user", content: "How are you?" },
];
const result = validateGeminiTurns(msgs);
expect(result).toHaveLength(3);
expect(result[0]).toEqual({ role: "user", content: "Hello" });
expect(result[1].role).toBe("assistant");
expect(result[1].content).toHaveLength(2);
expect(result[2]).toEqual({ role: "user", content: "How are you?" });
});
it("should preserve metadata from later message when merging", () => {
const msgs: AgentMessage[] = [
{
role: "assistant",
content: [{ type: "text", text: "Part 1" }],
usage: { input: 10, output: 5 },
},
{
role: "assistant",
content: [{ type: "text", text: "Part 2" }],
usage: { input: 10, output: 10 },
stopReason: "end_turn",
},
];
const result = validateGeminiTurns(msgs);
expect(result).toHaveLength(1);
const merged = result[0] as Extract<AgentMessage, { role: "assistant" }>;
expect(merged.usage).toEqual({ input: 10, output: 10 });
expect(merged.stopReason).toBe("end_turn");
expect(merged.content).toHaveLength(2);
});
it("should handle toolResult messages without merging", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: "Use tool" },
{
role: "assistant",
content: [{ type: "toolUse", id: "tool-1", name: "test", input: {} }],
},
{
role: "toolResult",
toolUseId: "tool-1",
content: [{ type: "text", text: "Result" }],
},
{ role: "user", content: "Next request" },
];
const result = validateGeminiTurns(msgs);
expect(result).toHaveLength(4);
expect(result).toEqual(msgs);
});
it("should handle real-world corrupted sequence", () => {
// This is the pattern that causes Gemini errors:
// user → assistant → assistant (consecutive, wrong!)
const msgs: AgentMessage[] = [
{ role: "user", content: "Request 1" },
{
role: "assistant",
content: [{ type: "text", text: "Response A" }],
},
{
role: "assistant",
content: [{ type: "toolUse", id: "t1", name: "search", input: {} }],
},
{
role: "toolResult",
toolUseId: "t1",
content: [{ type: "text", text: "Found data" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Here's the answer" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Extra thoughts" }],
},
{ role: "user", content: "Request 2" },
];
const result = validateGeminiTurns(msgs);
// Should merge the consecutive assistants
expect(result[0].role).toBe("user");
expect(result[1].role).toBe("assistant");
expect(result[2].role).toBe("toolResult");
expect(result[3].role).toBe("assistant");
expect(result[4].role).toBe("user");
});
});
describe("buildBootstrapContextFiles", () => {
it("keeps missing markers", () => {
const files = [makeFile({ missing: true, content: undefined })];
@@ -334,6 +191,15 @@ describe("formatAssistantErrorText", () => {
const msg = makeAssistantError("request_too_large");
expect(formatAssistantErrorText(msg)).toContain("Context overflow");
});
it("returns a friendly message for Anthropic role ordering", () => {
const msg = makeAssistantError(
'messages: roles must alternate between "user" and "assistant"',
);
expect(formatAssistantErrorText(msg)).toContain(
"Message ordering conflict",
);
});
});
describe("sanitizeToolCallId", () => {
@@ -614,86 +480,3 @@ describe("sanitizeSessionMessagesImages", () => {
]);
});
});
describe("normalizeTextForComparison", () => {
it("lowercases text", () => {
expect(normalizeTextForComparison("Hello World")).toBe("hello world");
});
it("trims whitespace", () => {
expect(normalizeTextForComparison(" hello ")).toBe("hello");
});
it("collapses multiple spaces", () => {
expect(normalizeTextForComparison("hello world")).toBe("hello world");
});
it("strips emoji", () => {
expect(normalizeTextForComparison("Hello 👋 World 🌍")).toBe("hello world");
});
it("handles mixed normalization", () => {
expect(normalizeTextForComparison(" Hello 👋 WORLD 🌍 ")).toBe(
"hello world",
);
});
});
describe("isMessagingToolDuplicate", () => {
it("returns false for empty sentTexts", () => {
expect(isMessagingToolDuplicate("hello world", [])).toBe(false);
});
it("returns false for short texts", () => {
expect(isMessagingToolDuplicate("short", ["short"])).toBe(false);
});
it("detects exact duplicates", () => {
expect(
isMessagingToolDuplicate("Hello, this is a test message!", [
"Hello, this is a test message!",
]),
).toBe(true);
});
it("detects duplicates with different casing", () => {
expect(
isMessagingToolDuplicate("HELLO, THIS IS A TEST MESSAGE!", [
"hello, this is a test message!",
]),
).toBe(true);
});
it("detects duplicates with emoji variations", () => {
expect(
isMessagingToolDuplicate("Hello! 👋 This is a test message!", [
"Hello! This is a test message!",
]),
).toBe(true);
});
it("detects substring duplicates (LLM elaboration)", () => {
expect(
isMessagingToolDuplicate(
'I sent the message: "Hello, this is a test message!"',
["Hello, this is a test message!"],
),
).toBe(true);
});
it("detects when sent text contains block reply (reverse substring)", () => {
expect(
isMessagingToolDuplicate("Hello, this is a test message!", [
'I sent the message: "Hello, this is a test message!"',
]),
).toBe(true);
});
it("returns false for non-matching texts", () => {
expect(
isMessagingToolDuplicate("This is completely different content.", [
"Hello, this is a test message!",
]),
).toBe(false);
});
});
+232
View File
@@ -297,6 +297,16 @@ export function formatAssistantErrorText(
);
}
// Check for role ordering errors (Anthropic 400 "Incorrect role information")
// This typically happens when consecutive user messages are sent without
// an assistant response between them, often due to steering/queueing timing.
if (/incorrect role information|roles must alternate/i.test(raw)) {
return (
"Message ordering conflict - please try again. " +
"If this persists, use /new to start a fresh session."
);
}
const invalidRequest = raw.match(
/"type":"invalid_request_error".*?"message":"([^"]+)"/,
);
@@ -553,6 +563,83 @@ export function validateGeminiTurns(messages: AgentMessage[]): AgentMessage[] {
return result;
}
export function mergeConsecutiveUserTurns(
previous: Extract<AgentMessage, { role: "user" }>,
current: Extract<AgentMessage, { role: "user" }>,
): Extract<AgentMessage, { role: "user" }> {
const mergedContent = [
...(Array.isArray(previous.content) ? previous.content : []),
...(Array.isArray(current.content) ? current.content : []),
];
// Preserve newest metadata while backfilling timestamp if the latest is missing.
return {
...current, // newest wins for metadata
content: mergedContent,
timestamp: current.timestamp ?? previous.timestamp,
};
}
/**
* Validates and fixes conversation turn sequences for Anthropic API.
* Anthropic requires strict alternating user→assistant pattern.
* This function:
* 1. Detects consecutive user messages
* 2. Merges consecutive user messages together
* 3. Preserves timestamps from the later message
*
* This prevents the "400 Incorrect role information" error that occurs
* when steering messages are injected during streaming and create
* consecutive user messages.
*/
export function validateAnthropicTurns(
messages: AgentMessage[],
): AgentMessage[] {
if (!Array.isArray(messages) || messages.length === 0) {
return messages;
}
const result: AgentMessage[] = [];
let lastRole: string | undefined;
for (const msg of messages) {
if (!msg || typeof msg !== "object") {
result.push(msg);
continue;
}
const msgRole = (msg as { role?: unknown }).role as string | undefined;
if (!msgRole) {
result.push(msg);
continue;
}
// Check if this message has the same role as the last one
if (msgRole === lastRole && lastRole === "user") {
// Merge consecutive user messages. Base on the newest message so we keep
// fresh metadata (attachments, timestamps, future fields) while
// appending prior content.
const lastMsg = result[result.length - 1];
const currentMsg = msg as Extract<AgentMessage, { role: "user" }>;
if (lastMsg && typeof lastMsg === "object") {
const lastUser = lastMsg as Extract<AgentMessage, { role: "user" }>;
const merged = mergeConsecutiveUserTurns(lastUser, currentMsg);
// Replace the last message with merged version
result[result.length - 1] = merged;
continue;
}
}
// Not a consecutive duplicate, add normally
result.push(msg);
lastRole = msgRole;
}
return result;
}
// ── Messaging tool duplicate detection ──────────────────────────────────────
// When the agent uses a messaging tool (telegram, discord, slack, message, sessions_send)
// to send a message, we track the text so we can suppress duplicate block replies.
@@ -617,3 +704,148 @@ export function isMessagingToolDuplicate(
sentTexts.map(normalizeTextForComparison),
);
}
/**
* Downgrades tool calls that are missing `thought_signature` (required by Gemini)
* into text representations, to prevent 400 INVALID_ARGUMENT errors.
* Also converts corresponding tool results into user messages.
*/
type GeminiToolCallBlock = {
type?: unknown;
thought_signature?: unknown;
id?: unknown;
toolCallId?: unknown;
name?: unknown;
toolName?: unknown;
arguments?: unknown;
input?: unknown;
};
export function downgradeGeminiHistory(
messages: AgentMessage[],
): AgentMessage[] {
const downgradedIds = new Set<string>();
const out: AgentMessage[] = [];
const resolveToolResultId = (
msg: Extract<AgentMessage, { role: "toolResult" }>,
): string | undefined => {
const toolCallId = (msg as { toolCallId?: unknown }).toolCallId;
if (typeof toolCallId === "string" && toolCallId) return toolCallId;
const toolUseId = (msg as { toolUseId?: unknown }).toolUseId;
if (typeof toolUseId === "string" && toolUseId) return toolUseId;
return undefined;
};
for (const msg of messages) {
if (!msg || typeof msg !== "object") {
out.push(msg);
continue;
}
const role = (msg as { role?: unknown }).role;
if (role === "assistant") {
const assistantMsg = msg as Extract<AgentMessage, { role: "assistant" }>;
if (!Array.isArray(assistantMsg.content)) {
out.push(msg);
continue;
}
let hasDowngraded = false;
const newContent = assistantMsg.content.map((block) => {
if (!block || typeof block !== "object") return block;
const blockRecord = block as GeminiToolCallBlock;
const type = blockRecord.type;
// Check for tool calls / function calls
if (
type === "toolCall" ||
type === "functionCall" ||
type === "toolUse"
) {
// Check if thought_signature is missing
// Note: TypeScript doesn't know about thought_signature on standard types
const hasSignature = Boolean(blockRecord.thought_signature);
if (!hasSignature) {
const id =
typeof blockRecord.id === "string"
? blockRecord.id
: typeof blockRecord.toolCallId === "string"
? blockRecord.toolCallId
: undefined;
const name =
typeof blockRecord.name === "string"
? blockRecord.name
: typeof blockRecord.toolName === "string"
? blockRecord.toolName
: undefined;
const args =
blockRecord.arguments !== undefined
? blockRecord.arguments
: blockRecord.input;
if (id) downgradedIds.add(id);
hasDowngraded = true;
const argsText =
typeof args === "string" ? args : JSON.stringify(args, null, 2);
return {
type: "text",
text: `[Tool Call: ${name ?? "unknown"}${
id ? ` (ID: ${id})` : ""
}]\nArguments: ${argsText}`,
};
}
}
return block;
});
if (hasDowngraded) {
out.push({ ...assistantMsg, content: newContent } as AgentMessage);
} else {
out.push(msg);
}
continue;
}
if (role === "toolResult") {
const toolMsg = msg as Extract<AgentMessage, { role: "toolResult" }>;
const toolResultId = resolveToolResultId(toolMsg);
if (toolResultId && downgradedIds.has(toolResultId)) {
// Convert to User message
let textContent = "";
if (Array.isArray(toolMsg.content)) {
textContent = toolMsg.content
.map((entry) => {
if (entry && typeof entry === "object") {
const text = (entry as { text?: unknown }).text;
if (typeof text === "string") return text;
}
return JSON.stringify(entry);
})
.join("\n");
} else {
textContent = JSON.stringify(toolMsg.content);
}
out.push({
role: "user",
content: [
{
type: "text",
text: `[Tool Result for ID ${toolResultId}]\n${textContent}`,
},
],
} as AgentMessage);
continue;
}
}
out.push(msg);
}
return out;
}
@@ -0,0 +1,352 @@
import type { AgentMessage } from "@mariozechner/pi-agent-core";
import { describe, expect, it } from "vitest";
import {
mergeConsecutiveUserTurns,
validateAnthropicTurns,
validateGeminiTurns,
} from "./pi-embedded-helpers.js";
describe("validateGeminiTurns", () => {
it("should return empty array unchanged", () => {
const result = validateGeminiTurns([]);
expect(result).toEqual([]);
});
it("should return single message unchanged", () => {
const msgs: AgentMessage[] = [
{
role: "user",
content: "Hello",
},
];
const result = validateGeminiTurns(msgs);
expect(result).toEqual(msgs);
});
it("should leave alternating user/assistant unchanged", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: [{ type: "text", text: "Hi" }] },
{ role: "user", content: "How are you?" },
{ role: "assistant", content: [{ type: "text", text: "Good!" }] },
];
const result = validateGeminiTurns(msgs);
expect(result).toHaveLength(4);
expect(result).toEqual(msgs);
});
it("should merge consecutive assistant messages", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: "Hello" },
{
role: "assistant",
content: [{ type: "text", text: "Part 1" }],
stopReason: "end_turn",
},
{
role: "assistant",
content: [{ type: "text", text: "Part 2" }],
stopReason: "end_turn",
},
{ role: "user", content: "How are you?" },
];
const result = validateGeminiTurns(msgs);
expect(result).toHaveLength(3);
expect(result[0]).toEqual({ role: "user", content: "Hello" });
expect(result[1].role).toBe("assistant");
expect(result[1].content).toHaveLength(2);
expect(result[2]).toEqual({ role: "user", content: "How are you?" });
});
it("should preserve metadata from later message when merging", () => {
const msgs: AgentMessage[] = [
{
role: "assistant",
content: [{ type: "text", text: "Part 1" }],
usage: { input: 10, output: 5 },
},
{
role: "assistant",
content: [{ type: "text", text: "Part 2" }],
usage: { input: 10, output: 10 },
stopReason: "end_turn",
},
];
const result = validateGeminiTurns(msgs);
expect(result).toHaveLength(1);
const merged = result[0] as Extract<AgentMessage, { role: "assistant" }>;
expect(merged.usage).toEqual({ input: 10, output: 10 });
expect(merged.stopReason).toBe("end_turn");
expect(merged.content).toHaveLength(2);
});
it("should handle toolResult messages without merging", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: "Use tool" },
{
role: "assistant",
content: [{ type: "toolUse", id: "tool-1", name: "test", input: {} }],
},
{
role: "toolResult",
toolUseId: "tool-1",
content: [{ type: "text", text: "Found data" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Here's the answer" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Extra thoughts" }],
},
{ role: "user", content: "Request 2" },
];
const result = validateGeminiTurns(msgs);
// Should merge the consecutive assistants
expect(result[0].role).toBe("user");
expect(result[1].role).toBe("assistant");
expect(result[2].role).toBe("toolResult");
expect(result[3].role).toBe("assistant");
expect(result[4].role).toBe("user");
});
});
describe("validateAnthropicTurns", () => {
it("should return empty array unchanged", () => {
const result = validateAnthropicTurns([]);
expect(result).toEqual([]);
});
it("should return single message unchanged", () => {
const msgs: AgentMessage[] = [
{
role: "user",
content: [{ type: "text", text: "Hello" }],
},
];
const result = validateAnthropicTurns(msgs);
expect(result).toEqual(msgs);
});
it("should return alternating user/assistant unchanged", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: [{ type: "text", text: "Question" }] },
{
role: "assistant",
content: [{ type: "text", text: "Answer" }],
},
{ role: "user", content: [{ type: "text", text: "Follow-up" }] },
];
const result = validateAnthropicTurns(msgs);
expect(result).toEqual(msgs);
});
it("should merge consecutive user messages", () => {
const msgs: AgentMessage[] = [
{
role: "user",
content: [{ type: "text", text: "First message" }],
timestamp: 1000,
},
{
role: "user",
content: [{ type: "text", text: "Second message" }],
timestamp: 2000,
},
];
const result = validateAnthropicTurns(msgs);
expect(result).toHaveLength(1);
expect(result[0].role).toBe("user");
const content = (result[0] as { content: unknown[] }).content;
expect(content).toHaveLength(2);
expect(content[0]).toEqual({ type: "text", text: "First message" });
expect(content[1]).toEqual({ type: "text", text: "Second message" });
// Should take timestamp from the newer message
expect((result[0] as { timestamp?: number }).timestamp).toBe(2000);
});
it("should merge three consecutive user messages", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: [{ type: "text", text: "One" }] },
{ role: "user", content: [{ type: "text", text: "Two" }] },
{ role: "user", content: [{ type: "text", text: "Three" }] },
];
const result = validateAnthropicTurns(msgs);
expect(result).toHaveLength(1);
const content = (result[0] as { content: unknown[] }).content;
expect(content).toHaveLength(3);
});
it("keeps newest metadata when merging consecutive users", () => {
const msgs: AgentMessage[] = [
{
role: "user",
content: [{ type: "text", text: "Old" }],
timestamp: 1000,
attachments: [{ type: "image", url: "old.png" }],
},
{
role: "user",
content: [{ type: "text", text: "New" }],
timestamp: 2000,
attachments: [{ type: "image", url: "new.png" }],
someCustomField: "keep-me",
} as AgentMessage,
];
const result = validateAnthropicTurns(msgs) as Extract<
AgentMessage,
{ role: "user" }
>[];
expect(result).toHaveLength(1);
const merged = result[0];
expect(merged.timestamp).toBe(2000);
expect((merged as { attachments?: unknown[] }).attachments).toEqual([
{ type: "image", url: "new.png" },
]);
expect((merged as { someCustomField?: string }).someCustomField).toBe(
"keep-me",
);
expect(merged.content).toEqual([
{ type: "text", text: "Old" },
{ type: "text", text: "New" },
]);
});
it("merges consecutive users with images and preserves order", () => {
const msgs: AgentMessage[] = [
{
role: "user",
content: [
{ type: "text", text: "first" },
{ type: "image", url: "img1" },
],
},
{
role: "user",
content: [
{ type: "image", url: "img2" },
{ type: "text", text: "second" },
],
},
];
const [merged] = validateAnthropicTurns(msgs) as Extract<
AgentMessage,
{ role: "user" }
>[];
expect(merged.content).toEqual([
{ type: "text", text: "first" },
{ type: "image", url: "img1" },
{ type: "image", url: "img2" },
{ type: "text", text: "second" },
]);
});
it("should not merge consecutive assistant messages", () => {
const msgs: AgentMessage[] = [
{ role: "user", content: [{ type: "text", text: "Question" }] },
{
role: "assistant",
content: [{ type: "text", text: "Answer 1" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Answer 2" }],
},
];
const result = validateAnthropicTurns(msgs);
// validateAnthropicTurns only merges user messages, not assistant
expect(result).toHaveLength(3);
});
it("should handle mixed scenario with steering messages", () => {
// Simulates: user asks -> assistant errors -> steering user message injected
const msgs: AgentMessage[] = [
{ role: "user", content: [{ type: "text", text: "Original question" }] },
{
role: "assistant",
content: [],
stopReason: "error",
errorMessage: "Overloaded",
},
{
role: "user",
content: [{ type: "text", text: "Steering: try again" }],
},
{ role: "user", content: [{ type: "text", text: "Another follow-up" }] },
];
const result = validateAnthropicTurns(msgs);
// The two consecutive user messages at the end should be merged
expect(result).toHaveLength(3);
expect(result[0].role).toBe("user");
expect(result[1].role).toBe("assistant");
expect(result[2].role).toBe("user");
const lastContent = (result[2] as { content: unknown[] }).content;
expect(lastContent).toHaveLength(2);
});
});
describe("mergeConsecutiveUserTurns", () => {
it("keeps newest metadata while merging content", () => {
const previous: Extract<AgentMessage, { role: "user" }> = {
role: "user",
content: [{ type: "text", text: "before" }],
timestamp: 1000,
attachments: [{ type: "image", url: "old.png" }],
};
const current: Extract<AgentMessage, { role: "user" }> = {
role: "user",
content: [{ type: "text", text: "after" }],
timestamp: 2000,
attachments: [{ type: "image", url: "new.png" }],
someCustomField: "keep-me",
} as AgentMessage;
const merged = mergeConsecutiveUserTurns(previous, current);
expect(merged.content).toEqual([
{ type: "text", text: "before" },
{ type: "text", text: "after" },
]);
expect((merged as { attachments?: unknown[] }).attachments).toEqual([
{ type: "image", url: "new.png" },
]);
expect((merged as { someCustomField?: string }).someCustomField).toBe(
"keep-me",
);
expect(merged.timestamp).toBe(2000);
});
it("backfills timestamp from earlier message when missing", () => {
const previous: Extract<AgentMessage, { role: "user" }> = {
role: "user",
content: [{ type: "text", text: "before" }],
timestamp: 1000,
};
const current: Extract<AgentMessage, { role: "user" }> = {
role: "user",
content: [{ type: "text", text: "after" }],
};
const merged = mergeConsecutiveUserTurns(previous, current);
expect(merged.timestamp).toBe(1000);
});
});
+15 -3
View File
@@ -85,6 +85,7 @@ export type { MessagingToolSend } from "./pi-embedded-messaging.js";
import {
buildBootstrapContextFiles,
classifyFailoverReason,
downgradeGeminiHistory,
type EmbeddedContextFile,
ensureSessionHeader,
formatAssistantErrorText,
@@ -100,6 +101,7 @@ import {
pickFallbackThinkingLevel,
sanitizeGoogleTurnOrdering,
sanitizeSessionMessagesImages,
validateAnthropicTurns,
validateGeminiTurns,
} from "./pi-embedded-helpers.js";
import {
@@ -492,8 +494,14 @@ async function sanitizeSessionHistory(params: {
},
);
const repairedTools = sanitizeToolUseResultPairing(sanitizedImages);
// Downgrade tool calls missing thought_signature if using Gemini
const downgraded = isGoogleModelApi(params.modelApi)
? downgradeGeminiHistory(repairedTools)
: repairedTools;
return applyGoogleTurnOrderingFix({
messages: repairedTools,
messages: downgraded,
modelApi: params.modelApi,
sessionManager: params.sessionManager,
sessionId: params.sessionId,
@@ -1291,7 +1299,9 @@ export async function compactEmbeddedPiSession(params: {
sessionManager,
sessionId: params.sessionId,
});
const validated = validateGeminiTurns(prior);
// Validate turn ordering for both Gemini (consecutive assistant) and Anthropic (consecutive user)
const validatedGemini = validateGeminiTurns(prior);
const validated = validateAnthropicTurns(validatedGemini);
const limited = limitHistoryTurns(
validated,
getDmHistoryLimitFromSessionKey(params.sessionKey, params.config),
@@ -1714,7 +1724,9 @@ export async function runEmbeddedPiAgent(params: {
sessionManager,
sessionId: params.sessionId,
});
const validated = validateGeminiTurns(prior);
// Validate turn ordering for both Gemini (consecutive assistant) and Anthropic (consecutive user)
const validatedGemini = validateGeminiTurns(prior);
const validated = validateAnthropicTurns(validatedGemini);
const limited = limitHistoryTurns(
validated,
getDmHistoryLimitFromSessionKey(params.sessionKey, params.config),
+260
View File
@@ -0,0 +1,260 @@
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { describe, expect, it } from "vitest";
import { extractAssistantText } from "./pi-embedded-utils.js";
describe("extractAssistantText", () => {
it("strips Minimax tool invocation XML from text", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `<invoke name="Bash">
<parameter name="command">netstat -tlnp | grep 18789</parameter>
</invoke>
</minimax:tool_call>`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("");
});
it("strips multiple tool invocations", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `Let me check that.<invoke name="Read">
<parameter name="path">/home/admin/test.txt</parameter>
</invoke>
</minimax:tool_call>`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("Let me check that.");
});
it("keeps invoke snippets without Minimax markers", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `Example:\n<invoke name="Bash">\n<parameter name="command">ls</parameter>\n</invoke>`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe(
`Example:\n<invoke name="Bash">\n<parameter name="command">ls</parameter>\n</invoke>`,
);
});
it("preserves normal text without tool invocations", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: "This is a normal response without any tool calls.",
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("This is a normal response without any tool calls.");
});
it("strips Minimax tool invocations with extra attributes", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `Before<invoke name='Bash' data-foo="bar">\n<parameter name="command">ls</parameter>\n</invoke>\n</minimax:tool_call>After`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("Before\nAfter");
});
it("strips minimax tool_call open and close tags", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: "Start<minimax:tool_call>Inner</minimax:tool_call>End",
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("StartInnerEnd");
});
it("ignores invoke blocks without minimax markers", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: "Before<invoke>Keep</invoke>After",
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("Before<invoke>Keep</invoke>After");
});
it("strips invoke blocks when minimax markers are present elsewhere", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: "Before<invoke>Drop</invoke><minimax:tool_call>After",
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("BeforeAfter");
});
it("strips invoke blocks with nested tags", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `A<invoke name="Bash"><param><deep>1</deep></param></invoke></minimax:tool_call>B`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("AB");
});
it("strips tool XML mixed with regular content", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `I'll help you with that.<invoke name="Bash">
<parameter name="command">ls -la</parameter>
</invoke>
</minimax:tool_call>Here are the results.`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("I'll help you with that.\nHere are the results.");
});
it("handles multiple invoke blocks in one message", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `First check.<invoke name="Read">
<parameter name="path">file1.txt</parameter>
</invoke>
</minimax:tool_call>Second check.<invoke name="Bash">
<parameter name="command">pwd</parameter>
</invoke>
</minimax:tool_call>Done.`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("First check.\nSecond check.\nDone.");
});
it("handles stray closing tags without opening tags", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: "Some text here.</minimax:tool_call>More text.",
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("Some text here.More text.");
});
it("returns empty string when message is only tool invocations", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: `<invoke name="Bash">
<parameter name="command">test</parameter>
</invoke>
</minimax:tool_call>`,
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("");
});
it("handles multiple text blocks", () => {
const msg: AssistantMessage = {
role: "assistant",
content: [
{
type: "text",
text: "First block.",
},
{
type: "text",
text: `<invoke name="Bash">
<parameter name="command">ls</parameter>
</invoke>
</minimax:tool_call>`,
},
{
type: "text",
text: "Third block.",
},
],
timestamp: Date.now(),
};
const result = extractAssistantText(msg);
expect(result).toBe("First block.\nThird block.");
});
});
+21 -1
View File
@@ -1,6 +1,26 @@
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { formatToolDetail, resolveToolDisplay } from "./tool-display.js";
/**
* Strip malformed Minimax tool invocations that leak into text content.
* Minimax sometimes embeds tool calls as XML in text blocks instead of
* proper structured tool calls. This removes:
* - <invoke name="...">...</invoke> blocks
* - </minimax:tool_call> closing tags
*/
function stripMinimaxToolCallXml(text: string): string {
if (!text) return text;
if (!/minimax:tool_call/i.test(text)) return text;
// Remove <invoke ...>...</invoke> blocks (non-greedy to handle multiple).
let cleaned = text.replace(/<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "");
// Remove stray minimax tool tags.
cleaned = cleaned.replace(/<\/?minimax:tool_call>/gi, "");
return cleaned;
}
export function extractAssistantText(msg: AssistantMessage): string {
const isTextBlock = (
block: unknown,
@@ -13,7 +33,7 @@ export function extractAssistantText(msg: AssistantMessage): string {
const blocks = Array.isArray(msg.content)
? msg.content
.filter(isTextBlock)
.map((c) => c.text.trim())
.map((c) => stripMinimaxToolCallXml(c.text).trim())
.filter(Boolean)
: [];
return blocks.join("\n").trim();
+1
View File
@@ -545,6 +545,7 @@ function createSandboxedEditTool(root: string) {
root,
);
}
// Normalize tool parameters from Claude Code conventions to pi-coding-agent conventions.
// Claude Code uses file_path/old_string/new_string while pi-coding-agent uses path/oldText/newText.
// This prevents models trained on Claude Code from getting stuck in tool-call loops.
+2 -2
View File
@@ -65,7 +65,7 @@ describe("sandbox explain helpers", () => {
]);
});
it("supports legacy 'memory' shorthand and deny wins after expansion", () => {
it("denies still win after group expansion", () => {
const cfg: ClawdbotConfig = {
agents: {
defaults: {
@@ -75,7 +75,7 @@ describe("sandbox explain helpers", () => {
tools: {
sandbox: {
tools: {
allow: ["memory"],
allow: ["group:memory"],
deny: ["memory_get"],
},
},
-3
View File
@@ -269,9 +269,6 @@ function expandToolGroupEntry(entry: string): string[] {
if (!raw) return [];
const lower = raw.toLowerCase();
// Back-compat shorthand: "memory" => "group:memory"
if (lower === "memory") return TOOL_GROUPS["group:memory"];
const group = TOOL_GROUPS[lower];
if (group) return group;
return [raw];
+9
View File
@@ -183,6 +183,14 @@ export function buildAgentSystemPrompt(params: {
"",
]
: [];
const memorySection =
availableTools.has("memory_search") || availableTools.has("memory_get")
? [
"## Memory Recall",
"Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search on MEMORY.md + memory/*.md; then use memory_get to pull only the needed lines. If low confidence after search, say you checked.",
"",
]
: [];
const lines = [
"You are a personal assistant running inside Clawdbot.",
@@ -212,6 +220,7 @@ export function buildAgentSystemPrompt(params: {
"If a task is more complex or takes longer, spawn a sub-agent. It will do the work for you and ping you when it's done. You can always check up on it.",
"",
...skillsSection,
...memorySection,
hasGateway ? "## Clawdbot Self-Update" : "",
hasGateway
? [
-283
View File
@@ -1,283 +0,0 @@
import { Type } from "@sinclair/typebox";
import { createReactionSchema } from "./reaction-schema.js";
export const DiscordToolSchema = Type.Union([
createReactionSchema({
ids: {
channelId: Type.String(),
messageId: Type.String(),
},
includeRemove: true,
}),
Type.Object({
action: Type.Literal("reactions"),
channelId: Type.String(),
messageId: Type.String(),
limit: Type.Optional(Type.Number()),
}),
Type.Object({
action: Type.Literal("sticker"),
to: Type.String(),
stickerIds: Type.Array(Type.String()),
content: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("poll"),
to: Type.String(),
question: Type.String(),
answers: Type.Array(Type.String()),
allowMultiselect: Type.Optional(Type.Boolean()),
durationHours: Type.Optional(Type.Number()),
content: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("permissions"),
channelId: Type.String(),
}),
Type.Union([
Type.Object({
action: Type.Literal("fetchMessage"),
messageLink: Type.String(),
guildId: Type.Optional(Type.String()),
channelId: Type.Optional(Type.String()),
messageId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("fetchMessage"),
guildId: Type.String(),
channelId: Type.String(),
messageId: Type.String(),
}),
]),
Type.Object({
action: Type.Literal("readMessages"),
channelId: Type.String(),
limit: Type.Optional(Type.Number()),
before: Type.Optional(Type.String()),
after: Type.Optional(Type.String()),
around: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("sendMessage"),
to: Type.String(),
content: Type.String(),
mediaUrl: Type.Optional(Type.String()),
replyTo: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("editMessage"),
channelId: Type.String(),
messageId: Type.String(),
content: Type.String(),
}),
Type.Object({
action: Type.Literal("deleteMessage"),
channelId: Type.String(),
messageId: Type.String(),
}),
Type.Object({
action: Type.Literal("threadCreate"),
channelId: Type.String(),
name: Type.String(),
messageId: Type.Optional(Type.String()),
autoArchiveMinutes: Type.Optional(Type.Number()),
}),
Type.Object({
action: Type.Literal("threadList"),
guildId: Type.String(),
channelId: Type.Optional(Type.String()),
includeArchived: Type.Optional(Type.Boolean()),
before: Type.Optional(Type.String()),
limit: Type.Optional(Type.Number()),
}),
Type.Object({
action: Type.Literal("threadReply"),
channelId: Type.String(),
content: Type.String(),
mediaUrl: Type.Optional(Type.String()),
replyTo: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("pinMessage"),
channelId: Type.String(),
messageId: Type.String(),
}),
Type.Object({
action: Type.Literal("unpinMessage"),
channelId: Type.String(),
messageId: Type.String(),
}),
Type.Object({
action: Type.Literal("listPins"),
channelId: Type.String(),
}),
Type.Object({
action: Type.Literal("searchMessages"),
guildId: Type.String(),
content: Type.String(),
channelId: Type.Optional(Type.String()),
channelIds: Type.Optional(Type.Array(Type.String())),
authorId: Type.Optional(Type.String()),
authorIds: Type.Optional(Type.Array(Type.String())),
limit: Type.Optional(Type.Number()),
}),
Type.Object({
action: Type.Literal("memberInfo"),
guildId: Type.String(),
userId: Type.String(),
}),
Type.Object({
action: Type.Literal("roleInfo"),
guildId: Type.String(),
}),
Type.Object({
action: Type.Literal("emojiList"),
guildId: Type.String(),
}),
Type.Object({
action: Type.Literal("emojiUpload"),
guildId: Type.String(),
name: Type.String(),
mediaUrl: Type.String(),
roleIds: Type.Optional(Type.Array(Type.String())),
}),
Type.Object({
action: Type.Literal("stickerUpload"),
guildId: Type.String(),
name: Type.String(),
description: Type.String(),
tags: Type.String(),
mediaUrl: Type.String(),
}),
Type.Object({
action: Type.Literal("roleAdd"),
guildId: Type.String(),
userId: Type.String(),
roleId: Type.String(),
}),
Type.Object({
action: Type.Literal("roleRemove"),
guildId: Type.String(),
userId: Type.String(),
roleId: Type.String(),
}),
Type.Object({
action: Type.Literal("channelInfo"),
channelId: Type.String(),
}),
Type.Object({
action: Type.Literal("channelList"),
guildId: Type.String(),
}),
Type.Object({
action: Type.Literal("voiceStatus"),
guildId: Type.String(),
userId: Type.String(),
}),
Type.Object({
action: Type.Literal("eventList"),
guildId: Type.String(),
}),
Type.Object({
action: Type.Literal("eventCreate"),
guildId: Type.String(),
name: Type.String(),
startTime: Type.String(),
endTime: Type.Optional(Type.String()),
description: Type.Optional(Type.String()),
channelId: Type.Optional(Type.String()),
entityType: Type.Optional(
Type.Union([
Type.Literal("voice"),
Type.Literal("stage"),
Type.Literal("external"),
]),
),
location: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("timeout"),
guildId: Type.String(),
userId: Type.String(),
durationMinutes: Type.Optional(Type.Number()),
until: Type.Optional(Type.String()),
reason: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("kick"),
guildId: Type.String(),
userId: Type.String(),
reason: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("ban"),
guildId: Type.String(),
userId: Type.String(),
reason: Type.Optional(Type.String()),
deleteMessageDays: Type.Optional(Type.Number()),
}),
// Channel management actions
Type.Object({
action: Type.Literal("channelCreate"),
guildId: Type.String(),
name: Type.String(),
type: Type.Optional(Type.Number()),
parentId: Type.Optional(Type.String()),
topic: Type.Optional(Type.String()),
position: Type.Optional(Type.Number()),
nsfw: Type.Optional(Type.Boolean()),
}),
Type.Object({
action: Type.Literal("channelEdit"),
channelId: Type.String(),
name: Type.Optional(Type.String()),
topic: Type.Optional(Type.String()),
position: Type.Optional(Type.Number()),
parentId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
nsfw: Type.Optional(Type.Boolean()),
rateLimitPerUser: Type.Optional(Type.Number()),
}),
Type.Object({
action: Type.Literal("channelDelete"),
channelId: Type.String(),
}),
Type.Object({
action: Type.Literal("channelMove"),
guildId: Type.String(),
channelId: Type.String(),
parentId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
position: Type.Optional(Type.Number()),
}),
// Category management actions (convenience aliases)
Type.Object({
action: Type.Literal("categoryCreate"),
guildId: Type.String(),
name: Type.String(),
position: Type.Optional(Type.Number()),
}),
Type.Object({
action: Type.Literal("categoryEdit"),
categoryId: Type.String(),
name: Type.Optional(Type.String()),
position: Type.Optional(Type.Number()),
}),
Type.Object({
action: Type.Literal("categoryDelete"),
categoryId: Type.String(),
}),
// Permission overwrite actions
Type.Object({
action: Type.Literal("channelPermissionSet"),
channelId: Type.String(),
targetId: Type.String(),
targetType: Type.Union([Type.Literal("role"), Type.Literal("member")]),
allow: Type.Optional(Type.String()),
deny: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("channelPermissionRemove"),
channelId: Type.String(),
targetId: Type.String(),
}),
]);
-18
View File
@@ -1,18 +0,0 @@
import { loadConfig } from "../../config/config.js";
import type { AnyAgentTool } from "./common.js";
import { handleDiscordAction } from "./discord-actions.js";
import { DiscordToolSchema } from "./discord-schema.js";
export function createDiscordTool(): AnyAgentTool {
return {
label: "Discord",
name: "discord",
description: "Manage Discord messages, reactions, and moderation.",
parameters: DiscordToolSchema,
execute: async (_toolCallId, args) => {
const params = args as Record<string, unknown>;
const cfg = loadConfig();
return await handleDiscordAction(params, cfg);
},
};
}
+3 -2
View File
@@ -34,7 +34,7 @@ export function createMemorySearchTool(options: {
label: "Memory Search",
name: "memory_search",
description:
"Search agent memory files (MEMORY.md + memory/*.md) using semantic vectors.",
"Mandatory recall step: semantically search MEMORY.md + memory/*.md before answering questions about prior work, decisions, dates, people, preferences, or todos; returns top snippets with path + lines.",
parameters: MemorySearchSchema,
execute: async (_toolCallId, params) => {
const query = readStringParam(params, "query", { required: true });
@@ -77,7 +77,8 @@ export function createMemoryGetTool(options: {
return {
label: "Memory Get",
name: "memory_get",
description: "Read a memory file by path (workspace-relative).",
description:
"Safe snippet read from MEMORY.md or memory/*.md with optional from/lines; use after memory_search to pull only the needed lines and keep context small.",
parameters: MemoryGetSchema,
execute: async (_toolCallId, params) => {
const relPath = readStringParam(params, "path", { required: true });
+17 -200
View File
@@ -1,74 +1,25 @@
import { Type } from "@sinclair/typebox";
import { parseReplyDirectives } from "../../auto-reply/reply/reply-directives.js";
import type { ClawdbotConfig } from "../../config/config.js";
import { loadConfig } from "../../config/config.js";
import {
type MessagePollResult,
type MessageSendResult,
sendMessage,
sendPoll,
} from "../../infra/outbound/message.js";
import { resolveMessageProviderSelection } from "../../infra/outbound/provider-selection.js";
GATEWAY_CLIENT_IDS,
GATEWAY_CLIENT_MODES,
} from "../../gateway/protocol/client-info.js";
import { runMessageAction } from "../../infra/outbound/message-action-runner.js";
import {
dispatchProviderMessageAction,
listProviderMessageActions,
supportsProviderMessageButtons,
} from "../../providers/plugins/message-actions.js";
import type { ProviderMessageActionName } from "../../providers/plugins/types.js";
import {
PROVIDER_MESSAGE_ACTION_NAMES,
type ProviderMessageActionName,
} from "../../providers/plugins/types.js";
import { normalizeAccountId } from "../../routing/session-key.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../../utils/message-provider.js";
import type { AnyAgentTool } from "./common.js";
import {
jsonResult,
readNumberParam,
readStringArrayParam,
readStringParam,
} from "./common.js";
import { jsonResult, readNumberParam, readStringParam } from "./common.js";
const AllMessageActions = [
"send",
"poll",
"react",
"reactions",
"read",
"edit",
"delete",
"pin",
"unpin",
"list-pins",
"permissions",
"thread-create",
"thread-list",
"thread-reply",
"search",
"sticker",
"member-info",
"role-info",
"emoji-list",
"emoji-upload",
"sticker-upload",
"role-add",
"role-remove",
"channel-info",
"channel-list",
"channel-create",
"channel-edit",
"channel-delete",
"channel-move",
"category-create",
"category-edit",
"category-delete",
"voice-status",
"event-list",
"event-create",
"timeout",
"kick",
"ban",
];
const AllMessageActions = PROVIDER_MESSAGE_ACTION_NAMES;
const MessageToolCommonSchema = {
provider: Type.Optional(Type.String()),
@@ -148,7 +99,7 @@ const MessageToolCommonSchema = {
};
function buildMessageToolSchemaFromActions(
actions: string[],
actions: readonly string[],
options: { includeButtons: boolean },
) {
const props: Record<string, unknown> = { ...MessageToolCommonSchema };
@@ -227,20 +178,13 @@ export function createMessageTool(options?: MessageToolOptions): AnyAgentTool {
const action = readStringParam(params, "action", {
required: true,
}) as ProviderMessageActionName;
const providerSelection = await resolveMessageProviderSelection({
cfg,
provider: readStringParam(params, "provider"),
});
const provider = providerSelection.provider;
const accountId = readStringParam(params, "accountId") ?? agentAccountId;
const dryRun = Boolean(params.dryRun);
const gateway = {
url: readStringParam(params, "gatewayUrl", { trim: false }),
token: readStringParam(params, "gatewayToken", { trim: false }),
timeoutMs: readNumberParam(params, "timeoutMs"),
clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
clientName: GATEWAY_CLIENT_IDS.GATEWAY_CLIENT,
clientDisplayName: "agent",
mode: GATEWAY_CLIENT_MODES.BACKEND,
};
@@ -258,144 +202,17 @@ export function createMessageTool(options?: MessageToolOptions): AnyAgentTool {
}
: undefined;
if (action === "send") {
const to = readStringParam(params, "to", { required: true });
let message = readStringParam(params, "message", {
required: true,
allowEmpty: true,
});
// Let send accept the same inline directives we use elsewhere.
// Provider plugins consume `replyTo` / `media` / `buttons` from params.
const parsed = parseReplyDirectives(message);
message = parsed.text;
params.message = message;
if (!params.replyTo && parsed.replyToId)
params.replyTo = parsed.replyToId;
if (!params.media) {
params.media = parsed.mediaUrls?.[0] || parsed.mediaUrl || undefined;
}
const mediaUrl = readStringParam(params, "media", { trim: false });
const gifPlayback =
typeof params.gifPlayback === "boolean" ? params.gifPlayback : false;
const bestEffort =
typeof params.bestEffort === "boolean"
? params.bestEffort
: undefined;
if (dryRun) {
const result: MessageSendResult = await sendMessage({
to,
content: message,
mediaUrl: mediaUrl || undefined,
provider: provider || undefined,
accountId: accountId ?? undefined,
gifPlayback,
dryRun,
bestEffort,
gateway,
});
return jsonResult(result);
}
const handled = await dispatchProviderMessageAction({
provider,
action,
cfg,
params,
accountId,
gateway,
toolContext,
dryRun,
});
if (handled) return handled;
const result: MessageSendResult = await sendMessage({
to,
content: message,
mediaUrl: mediaUrl || undefined,
provider: provider || undefined,
accountId: accountId ?? undefined,
gifPlayback,
dryRun,
bestEffort,
gateway,
});
return jsonResult(result);
}
if (action === "poll") {
const to = readStringParam(params, "to", { required: true });
const question = readStringParam(params, "pollQuestion", {
required: true,
});
const options =
readStringArrayParam(params, "pollOption", { required: true }) ?? [];
const allowMultiselect =
typeof params.pollMulti === "boolean" ? params.pollMulti : undefined;
const durationHours = readNumberParam(params, "pollDurationHours", {
integer: true,
});
const maxSelections = allowMultiselect
? Math.max(2, options.length)
: 1;
if (dryRun) {
const result: MessagePollResult = await sendPoll({
to,
question,
options,
maxSelections,
durationHours: durationHours ?? undefined,
provider,
dryRun,
gateway,
});
return jsonResult(result);
}
const handled = await dispatchProviderMessageAction({
provider,
action,
cfg,
params,
accountId,
gateway,
toolContext,
dryRun,
});
if (handled) return handled;
const result: MessagePollResult = await sendPoll({
to,
question,
options,
maxSelections,
durationHours: durationHours ?? undefined,
provider,
dryRun,
gateway,
});
return jsonResult(result);
}
const handled = await dispatchProviderMessageAction({
provider,
action,
const result = await runMessageAction({
cfg,
action,
params,
accountId,
defaultAccountId: accountId ?? undefined,
gateway,
toolContext,
dryRun,
});
if (handled) return handled;
throw new Error(
`Message action ${action} not supported for provider ${provider}.`,
);
if (result.toolResult) return result.toolResult;
return jsonResult(result.payload);
},
};
}
-24
View File
@@ -1,24 +0,0 @@
import { type TSchema, Type } from "@sinclair/typebox";
type ReactionSchemaOptions = {
action?: string;
ids: Record<string, TSchema>;
emoji?: TSchema;
includeRemove?: boolean;
extras?: Record<string, TSchema>;
};
export function createReactionSchema(options: ReactionSchemaOptions) {
const schema: Record<string, TSchema> = {
action: Type.Literal(options.action ?? "react"),
...options.ids,
emoji: options.emoji ?? Type.String(),
};
if (options.includeRemove) {
schema.remove = Type.Optional(Type.Boolean());
}
if (options.extras) {
Object.assign(schema, options.extras);
}
return Type.Object(schema);
}
-77
View File
@@ -1,77 +0,0 @@
import { Type } from "@sinclair/typebox";
import { createReactionSchema } from "./reaction-schema.js";
export const SlackToolSchema = Type.Union([
createReactionSchema({
ids: {
channelId: Type.String(),
messageId: Type.String(),
},
includeRemove: true,
extras: {
accountId: Type.Optional(Type.String()),
},
}),
Type.Object({
action: Type.Literal("reactions"),
channelId: Type.String(),
messageId: Type.String(),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("sendMessage"),
to: Type.String(),
content: Type.String(),
mediaUrl: Type.Optional(Type.String()),
threadTs: Type.Optional(Type.String()),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("editMessage"),
channelId: Type.String(),
messageId: Type.String(),
content: Type.String(),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("deleteMessage"),
channelId: Type.String(),
messageId: Type.String(),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("readMessages"),
channelId: Type.String(),
limit: Type.Optional(Type.Number()),
before: Type.Optional(Type.String()),
after: Type.Optional(Type.String()),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("pinMessage"),
channelId: Type.String(),
messageId: Type.String(),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("unpinMessage"),
channelId: Type.String(),
messageId: Type.String(),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("listPins"),
channelId: Type.String(),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("memberInfo"),
userId: Type.String(),
accountId: Type.Optional(Type.String()),
}),
Type.Object({
action: Type.Literal("emojiList"),
accountId: Type.Optional(Type.String()),
}),
]);
-85
View File
@@ -1,85 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const handleSlackActionMock = vi.fn();
vi.mock("./slack-actions.js", () => ({
handleSlackAction: (params: unknown, cfg: unknown) =>
handleSlackActionMock(params, cfg),
}));
import { createSlackTool } from "./slack-tool.js";
describe("slack tool", () => {
beforeEach(() => {
handleSlackActionMock.mockReset();
handleSlackActionMock.mockResolvedValue({
content: [],
details: { ok: true },
});
});
it("injects agentAccountId when accountId is missing", async () => {
const tool = createSlackTool({
agentAccountId: " Kev ",
config: { slack: { accounts: { kev: {} } } },
});
await tool.execute("call-1", {
action: "sendMessage",
to: "channel:C1",
content: "hello",
});
expect(handleSlackActionMock).toHaveBeenCalledTimes(1);
const [params] = handleSlackActionMock.mock.calls[0] ?? [];
expect(params).toMatchObject({ accountId: "kev" });
});
it("keeps explicit accountId when provided", async () => {
const tool = createSlackTool({
agentAccountId: "kev",
config: {},
});
await tool.execute("call-2", {
action: "sendMessage",
to: "channel:C1",
content: "hello",
accountId: "rex",
});
expect(handleSlackActionMock).toHaveBeenCalledTimes(1);
const [params] = handleSlackActionMock.mock.calls[0] ?? [];
expect(params).toMatchObject({ accountId: "rex" });
});
it("does not inject accountId when agentAccountId is missing", async () => {
const tool = createSlackTool({ config: {} });
await tool.execute("call-3", {
action: "sendMessage",
to: "channel:C1",
content: "hello",
});
expect(handleSlackActionMock).toHaveBeenCalledTimes(1);
const [params] = handleSlackActionMock.mock.calls[0] ?? [];
expect(params).not.toHaveProperty("accountId");
});
it("does not inject unknown agentAccountId when not configured", async () => {
const tool = createSlackTool({
agentAccountId: "unknown",
config: { slack: { accounts: { kev: {} } } },
});
await tool.execute("call-4", {
action: "sendMessage",
to: "channel:C1",
content: "hello",
});
const [params] = handleSlackActionMock.mock.calls[0] ?? [];
expect(params).not.toHaveProperty("accountId");
});
});
-82
View File
@@ -1,82 +0,0 @@
import type { ClawdbotConfig } from "../../config/config.js";
import { loadConfig } from "../../config/config.js";
import { logVerbose } from "../../globals.js";
import { normalizeAccountId } from "../../routing/session-key.js";
import type { AnyAgentTool } from "./common.js";
import { handleSlackAction } from "./slack-actions.js";
import { SlackToolSchema } from "./slack-schema.js";
type SlackToolOptions = {
agentAccountId?: string;
config?: ClawdbotConfig;
/** Current channel ID for auto-threading. */
currentChannelId?: string;
/** Current thread timestamp for auto-threading. */
currentThreadTs?: string;
/** Reply-to mode for auto-threading. */
replyToMode?: "off" | "first" | "all";
/** Mutable ref to track if a reply was sent (for "first" mode). */
hasRepliedRef?: { value: boolean };
};
function resolveAgentAccountId(value?: string): string | undefined {
const trimmed = value?.trim();
if (!trimmed) return undefined;
return normalizeAccountId(trimmed);
}
function resolveConfiguredAccountId(
cfg: ClawdbotConfig,
accountId: string,
): string | undefined {
if (accountId === "default") return accountId;
const accounts = cfg.slack?.accounts;
if (!accounts || typeof accounts !== "object") return undefined;
if (accountId in accounts) return accountId;
const match = Object.keys(accounts).find(
(key) => key.toLowerCase() === accountId.toLowerCase(),
);
return match;
}
function hasAccountId(params: Record<string, unknown>): boolean {
const raw = params.accountId;
if (typeof raw !== "string") return false;
return raw.trim().length > 0;
}
export function createSlackTool(options?: SlackToolOptions): AnyAgentTool {
const agentAccountId = resolveAgentAccountId(options?.agentAccountId);
return {
label: "Slack",
name: "slack",
description: "Manage Slack messages, reactions, and pins.",
parameters: SlackToolSchema,
execute: async (_toolCallId, args) => {
const params = args as Record<string, unknown>;
const cfg = options?.config ?? loadConfig();
const resolvedAccountId = agentAccountId
? resolveConfiguredAccountId(cfg, agentAccountId)
: undefined;
const resolvedParams =
resolvedAccountId && !hasAccountId(params)
? { ...params, accountId: resolvedAccountId }
: params;
if (hasAccountId(resolvedParams)) {
const action =
typeof params.action === "string" ? params.action : "unknown";
logVerbose(
`slack tool: action=${action} accountId=${String(
resolvedParams.accountId,
).trim()}`,
);
}
return await handleSlackAction(resolvedParams, cfg, {
currentChannelId: options?.currentChannelId,
currentThreadTs: options?.currentThreadTs,
replyToMode: options?.replyToMode,
hasRepliedRef: options?.hasRepliedRef,
});
},
};
}
-34
View File
@@ -1,34 +0,0 @@
import { Type } from "@sinclair/typebox";
import { createReactionSchema } from "./reaction-schema.js";
// NOTE: chatId and messageId use Type.String() instead of Type.Union([Type.String(), Type.Number()])
// because nested anyOf schemas cause JSON Schema validation failures with Claude API on Vertex AI.
// Telegram IDs are coerced to strings at runtime in telegram-actions.ts.
export const TelegramToolSchema = Type.Union([
createReactionSchema({
ids: {
chatId: Type.String(),
messageId: Type.String(),
},
includeRemove: true,
}),
Type.Object({
action: Type.Literal("sendMessage"),
to: Type.String({ description: "Chat ID, @username, or t.me/username" }),
content: Type.String({ description: "Message text to send" }),
mediaUrl: Type.Optional(
Type.String({ description: "URL of image/video/audio to attach" }),
),
replyToMessageId: Type.Optional(
Type.Union([Type.String(), Type.Number()], {
description: "Message ID to reply to (for threading)",
}),
),
messageThreadId: Type.Optional(
Type.Union([Type.String(), Type.Number()], {
description: "Forum topic thread ID (for forum supergroups)",
}),
),
}),
]);
-18
View File
@@ -1,18 +0,0 @@
import { loadConfig } from "../../config/config.js";
import type { AnyAgentTool } from "./common.js";
import { handleTelegramAction } from "./telegram-actions.js";
import { TelegramToolSchema } from "./telegram-schema.js";
export function createTelegramTool(): AnyAgentTool {
return {
label: "Telegram",
name: "telegram",
description: "Send messages and manage reactions on Telegram.",
parameters: TelegramToolSchema,
execute: async (_toolCallId, args) => {
const params = args as Record<string, unknown>;
const cfg = loadConfig();
return await handleTelegramAction(params, cfg);
},
};
}
-18
View File
@@ -1,18 +0,0 @@
import { Type } from "@sinclair/typebox";
import { createReactionSchema } from "./reaction-schema.js";
export const WhatsAppToolSchema = Type.Union([
createReactionSchema({
ids: {
chatJid: Type.String(),
messageId: Type.String(),
},
includeRemove: true,
extras: {
participant: Type.Optional(Type.String()),
accountId: Type.Optional(Type.String()),
fromMe: Type.Optional(Type.Boolean()),
},
}),
]);
-18
View File
@@ -1,18 +0,0 @@
import { loadConfig } from "../../config/config.js";
import type { AnyAgentTool } from "./common.js";
import { handleWhatsAppAction } from "./whatsapp-actions.js";
import { WhatsAppToolSchema } from "./whatsapp-schema.js";
export function createWhatsAppTool(): AnyAgentTool {
return {
label: "WhatsApp",
name: "whatsapp",
description: "Manage WhatsApp reactions.",
parameters: WhatsAppToolSchema,
execute: async (_toolCallId, args) => {
const params = args as Record<string, unknown>;
const cfg = loadConfig();
return await handleWhatsAppAction(params, cfg);
},
};
}
+180 -36
View File
@@ -44,6 +44,17 @@ async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
);
}
function assertModelSelection(
storePath: string,
selection: { model?: string; provider?: string } = {},
) {
const store = loadSessionStore(storePath);
const entry = store[MAIN_SESSION_KEY];
expect(entry).toBeDefined();
expect(entry?.modelOverride).toBe(selection.model);
expect(entry?.providerOverride).toBe(selection.provider);
}
describe("directive behavior", () => {
beforeEach(() => {
vi.mocked(runEmbeddedPiAgent).mockReset();
@@ -1750,7 +1761,7 @@ describe("directive behavior", () => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
const res = await getReplyFromConfig(
await getReplyFromConfig(
{ Body: "/model openai/gpt-4.1-mini", From: "+1222", To: "+1222" },
{},
{
@@ -1768,12 +1779,10 @@ describe("directive behavior", () => {
},
);
const text = Array.isArray(res) ? res[0]?.text : res?.text;
expect(text).toContain("Model set to openai/gpt-4.1-mini");
const store = loadSessionStore(storePath);
const entry = store["agent:main:main"];
expect(entry.modelOverride).toBe("gpt-4.1-mini");
expect(entry.providerOverride).toBe("openai");
assertModelSelection(storePath, {
model: "gpt-4.1-mini",
provider: "openai",
});
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
@@ -1783,7 +1792,7 @@ describe("directive behavior", () => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
const res = await getReplyFromConfig(
await getReplyFromConfig(
{ Body: "/model Opus", From: "+1222", To: "+1222" },
{},
{
@@ -1801,13 +1810,10 @@ describe("directive behavior", () => {
},
);
const text = Array.isArray(res) ? res[0]?.text : res?.text;
expect(text).toContain("Model set to Opus");
expect(text).toContain("anthropic/claude-opus-4-5");
const store = loadSessionStore(storePath);
const entry = store["agent:main:main"];
expect(entry.modelOverride).toBe("claude-opus-4-5");
expect(entry.providerOverride).toBe("anthropic");
assertModelSelection(storePath, {
model: "claude-opus-4-5",
provider: "anthropic",
});
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
@@ -1817,7 +1823,7 @@ describe("directive behavior", () => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
const res = await getReplyFromConfig(
await getReplyFromConfig(
{ Body: "/model kimi", From: "+1222", To: "+1222" },
{},
{
@@ -1846,12 +1852,10 @@ describe("directive behavior", () => {
},
);
const text = Array.isArray(res) ? res[0]?.text : res?.text;
expect(text).toContain("Model set to moonshot/kimi-k2-0905-preview");
const store = loadSessionStore(storePath);
const entry = store["agent:main:main"];
expect(entry.modelOverride).toBe("kimi-k2-0905-preview");
expect(entry.providerOverride).toBe("moonshot");
assertModelSelection(storePath, {
model: "kimi-k2-0905-preview",
provider: "moonshot",
});
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
@@ -1861,7 +1865,7 @@ describe("directive behavior", () => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
const res = await getReplyFromConfig(
await getReplyFromConfig(
{ Body: "/model kimi-k2-0905-preview", From: "+1222", To: "+1222" },
{},
{
@@ -1890,12 +1894,10 @@ describe("directive behavior", () => {
},
);
const text = Array.isArray(res) ? res[0]?.text : res?.text;
expect(text).toContain("Model set to moonshot/kimi-k2-0905-preview");
const store = loadSessionStore(storePath);
const entry = store["agent:main:main"];
expect(entry.modelOverride).toBe("kimi-k2-0905-preview");
expect(entry.providerOverride).toBe("moonshot");
assertModelSelection(storePath, {
model: "kimi-k2-0905-preview",
provider: "moonshot",
});
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
@@ -1905,7 +1907,7 @@ describe("directive behavior", () => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
const res = await getReplyFromConfig(
await getReplyFromConfig(
{ Body: "/model moonshot/kimi", From: "+1222", To: "+1222" },
{},
{
@@ -1934,12 +1936,154 @@ describe("directive behavior", () => {
},
);
const text = Array.isArray(res) ? res[0]?.text : res?.text;
expect(text).toContain("Model set to moonshot/kimi-k2-0905-preview");
const store = loadSessionStore(storePath);
const entry = store["agent:main:main"];
expect(entry.modelOverride).toBe("kimi-k2-0905-preview");
expect(entry.providerOverride).toBe("moonshot");
assertModelSelection(storePath, {
model: "kimi-k2-0905-preview",
provider: "moonshot",
});
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
it("picks the best fuzzy match when multiple models match", async () => {
await withTempHome(async (home) => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
await getReplyFromConfig(
{ Body: "/model minimax", From: "+1222", To: "+1222" },
{},
{
agents: {
defaults: {
model: { primary: "minimax/MiniMax-M2.1" },
workspace: path.join(home, "clawd"),
models: {
"minimax/MiniMax-M2.1": {},
"minimax/MiniMax-M2.1-lightning": {},
"lmstudio/minimax-m2.1-gs32": {},
},
},
},
models: {
mode: "merge",
providers: {
minimax: {
baseUrl: "https://api.minimax.io/anthropic",
apiKey: "sk-test",
api: "anthropic-messages",
models: [{ id: "MiniMax-M2.1", name: "MiniMax M2.1" }],
},
lmstudio: {
baseUrl: "http://127.0.0.1:1234/v1",
apiKey: "lmstudio",
api: "openai-responses",
models: [
{ id: "minimax-m2.1-gs32", name: "MiniMax M2.1 GS32" },
],
},
},
},
session: { store: storePath },
},
);
assertModelSelection(storePath);
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
it("picks the best fuzzy match within a provider", async () => {
await withTempHome(async (home) => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
await getReplyFromConfig(
{ Body: "/model minimax/m2.1", From: "+1222", To: "+1222" },
{},
{
agents: {
defaults: {
model: { primary: "minimax/MiniMax-M2.1" },
workspace: path.join(home, "clawd"),
models: {
"minimax/MiniMax-M2.1": {},
"minimax/MiniMax-M2.1-lightning": {},
},
},
},
models: {
mode: "merge",
providers: {
minimax: {
baseUrl: "https://api.minimax.io/anthropic",
apiKey: "sk-test",
api: "anthropic-messages",
models: [
{ id: "MiniMax-M2.1", name: "MiniMax M2.1" },
{
id: "MiniMax-M2.1-lightning",
name: "MiniMax M2.1 Lightning",
},
],
},
},
},
session: { store: storePath },
},
);
assertModelSelection(storePath);
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
it("prefers alias matches when fuzzy selection is ambiguous", async () => {
await withTempHome(async (home) => {
vi.mocked(runEmbeddedPiAgent).mockReset();
const storePath = path.join(home, "sessions.json");
await getReplyFromConfig(
{ Body: "/model ki", From: "+1222", To: "+1222" },
{},
{
agents: {
defaults: {
model: { primary: "anthropic/claude-opus-4-5" },
workspace: path.join(home, "clawd"),
models: {
"anthropic/claude-opus-4-5": {},
"moonshot/kimi-k2-0905-preview": { alias: "Kimi" },
"lmstudio/kimi-k2-0905-preview": {},
},
},
},
models: {
mode: "merge",
providers: {
moonshot: {
baseUrl: "https://api.moonshot.ai/v1",
apiKey: "sk-test",
api: "openai-completions",
models: [{ id: "kimi-k2-0905-preview", name: "Kimi K2" }],
},
lmstudio: {
baseUrl: "http://127.0.0.1:1234/v1",
apiKey: "lmstudio",
api: "openai-responses",
models: [
{ id: "kimi-k2-0905-preview", name: "Kimi K2 (Local)" },
],
},
},
},
session: { store: storePath },
},
);
assertModelSelection(storePath, {
model: "kimi-k2-0905-preview",
provider: "moonshot",
});
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
});
});
@@ -1,83 +0,0 @@
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { withTempHome as withTempHomeBase } from "../../test/helpers/temp-home.js";
import { loadModelCatalog } from "../agents/model-catalog.js";
import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";
import { getReplyFromConfig } from "./reply.js";
vi.mock("../agents/pi-embedded.js", () => ({
abortEmbeddedPiRun: vi.fn().mockReturnValue(false),
runEmbeddedPiAgent: vi.fn(),
queueEmbeddedPiMessage: vi.fn().mockReturnValue(false),
resolveEmbeddedSessionLane: (key: string) =>
`session:${key.trim() || "main"}`,
isEmbeddedPiRunActive: vi.fn().mockReturnValue(false),
isEmbeddedPiRunStreaming: vi.fn().mockReturnValue(false),
}));
vi.mock("../agents/model-catalog.js", () => ({
loadModelCatalog: vi.fn(),
}));
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
return withTempHomeBase(
async (home) => {
return await fn(home);
},
{ prefix: "clawdbot-reasoning-tags-" },
);
}
describe("reasoning tag enforcement", () => {
const reasoningModel = "google-antigravity/gemini-3";
beforeEach(() => {
vi.mocked(runEmbeddedPiAgent).mockReset();
vi.mocked(loadModelCatalog).mockResolvedValue([
{ id: "gemini-3", name: "Gemini 3", provider: "google-antigravity" },
]);
});
afterEach(() => {
vi.clearAllMocks();
});
it("sets enforceFinalTag for providers that require reasoning tags", async () => {
await withTempHome(async (home) => {
vi.mocked(runEmbeddedPiAgent).mockResolvedValue({
payloads: [{ text: "ok" }],
meta: {
durationMs: 1,
agentMeta: {
sessionId: "s",
provider: "google-antigravity",
model: "gemini-3",
},
},
});
await getReplyFromConfig(
{ Body: "hello", From: "+1999", To: "+2000" },
{},
{
agents: {
defaults: {
model: reasoningModel,
models: { [reasoningModel]: {} },
workspace: path.join(home, "clawd"),
},
},
whatsapp: { allowFrom: ["*"] },
session: { store: path.join(home, "sessions.json") },
},
);
expect(runEmbeddedPiAgent).toHaveBeenCalledTimes(1);
const args = vi.mocked(runEmbeddedPiAgent).mock.calls[0]?.[0];
expect(args?.enforceFinalTag).toBe(true);
expect(args?.provider).toBe("google-antigravity");
});
});
});
+1 -2
View File
@@ -849,8 +849,7 @@ export async function getReplyFromConfig(
formatModelSwitchEvent,
agentCfg,
modelState: {
resolveDefaultThinkingLevel: async () =>
(await modelState.resolveDefaultThinkingLevel()) ?? "off",
resolveDefaultThinkingLevel: modelState.resolveDefaultThinkingLevel,
allowedModelKeys: modelState.allowedModelKeys,
allowedModelCatalog: modelState.allowedModelCatalog,
resetModelOverride: modelState.resetModelOverride,
@@ -47,7 +47,18 @@ vi.mock("./queue.js", async () => {
import { runReplyAgent } from "./agent-runner.js";
type EmbeddedPiAgentParams = {
onPartialReply?: (payload: { text?: string }) => Promise<void> | void;
onPartialReply?: (payload: {
text?: string;
mediaUrls?: string[];
}) => Promise<void> | void;
onBlockReply?: (payload: {
text?: string;
mediaUrls?: string[];
}) => Promise<void> | void;
onToolResult?: (payload: {
text?: string;
mediaUrls?: string[];
}) => Promise<void> | void;
};
function createMinimalRun(params?: {
@@ -58,6 +69,7 @@ function createMinimalRun(params?: {
sessionKey?: string;
storePath?: string;
typingMode?: TypingMode;
blockStreamingEnabled?: boolean;
}) {
const typing = createMockTypingController();
const opts = params?.opts;
@@ -117,7 +129,7 @@ function createMinimalRun(params?: {
defaultModel: "anthropic/claude-opus-4-5",
resolvedVerboseLevel: params?.resolvedVerboseLevel ?? "off",
isNewSession: false,
blockStreamingEnabled: false,
blockStreamingEnabled: params?.blockStreamingEnabled ?? false,
resolvedBlockStreamingBreak: "message_end",
shouldInjectGroupIntro: false,
typingMode: params?.typingMode ?? "instant",
@@ -257,6 +269,73 @@ describe("runReplyAgent typing (heartbeat)", () => {
expect(typing.startTypingLoop).not.toHaveBeenCalled();
});
it("signals typing on block replies", async () => {
const onBlockReply = vi.fn();
runEmbeddedPiAgentMock.mockImplementationOnce(
async (params: EmbeddedPiAgentParams) => {
await params.onBlockReply?.({ text: "chunk", mediaUrls: [] });
return { payloads: [{ text: "final" }], meta: {} };
},
);
const { run, typing } = createMinimalRun({
typingMode: "message",
blockStreamingEnabled: true,
opts: { onBlockReply },
});
await run();
expect(typing.startTypingOnText).toHaveBeenCalledWith("chunk");
expect(onBlockReply).toHaveBeenCalled();
const [blockPayload, blockOpts] = onBlockReply.mock.calls[0] ?? [];
expect(blockPayload).toMatchObject({ text: "chunk", audioAsVoice: false });
expect(blockOpts).toMatchObject({
abortSignal: expect.any(AbortSignal),
timeoutMs: expect.any(Number),
});
});
it("signals typing on tool results", async () => {
const onToolResult = vi.fn();
runEmbeddedPiAgentMock.mockImplementationOnce(
async (params: EmbeddedPiAgentParams) => {
await params.onToolResult?.({ text: "tooling", mediaUrls: [] });
return { payloads: [{ text: "final" }], meta: {} };
},
);
const { run, typing } = createMinimalRun({
typingMode: "message",
opts: { onToolResult },
});
await run();
expect(typing.startTypingOnText).toHaveBeenCalledWith("tooling");
expect(onToolResult).toHaveBeenCalledWith({
text: "tooling",
mediaUrls: [],
});
});
it("skips typing for silent tool results", async () => {
const onToolResult = vi.fn();
runEmbeddedPiAgentMock.mockImplementationOnce(
async (params: EmbeddedPiAgentParams) => {
await params.onToolResult?.({ text: "NO_REPLY", mediaUrls: [] });
return { payloads: [{ text: "final" }], meta: {} };
},
);
const { run, typing } = createMinimalRun({
typingMode: "message",
opts: { onToolResult },
});
await run();
expect(typing.startTypingOnText).not.toHaveBeenCalled();
expect(onToolResult).not.toHaveBeenCalled();
});
it("announces auto-compaction in verbose mode and tracks count", async () => {
const storePath = path.join(
await fs.mkdtemp(path.join(tmpdir(), "clawdbot-compaction-")),
@@ -0,0 +1,178 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { SessionEntry } from "../../config/sessions.js";
import type { TemplateContext } from "../templating.js";
import { DEFAULT_MEMORY_FLUSH_PROMPT } from "./memory-flush.js";
import type { FollowupRun, QueueSettings } from "./queue.js";
import { createMockTypingController } from "./test-helpers.js";
const runEmbeddedPiAgentMock = vi.fn();
const runWithModelFallbackMock = vi.fn();
vi.mock("../../agents/model-fallback.js", () => ({
runWithModelFallback: (params: {
provider: string;
model: string;
run: (provider: string, model: string) => Promise<unknown>;
}) => runWithModelFallbackMock(params),
}));
vi.mock("../../agents/pi-embedded.js", () => ({
queueEmbeddedPiMessage: vi.fn().mockReturnValue(false),
runEmbeddedPiAgent: (params: unknown) => runEmbeddedPiAgentMock(params),
}));
vi.mock("./queue.js", async () => {
const actual =
await vi.importActual<typeof import("./queue.js")>("./queue.js");
return {
...actual,
enqueueFollowupRun: vi.fn(),
scheduleFollowupDrain: vi.fn(),
};
});
import { runReplyAgent } from "./agent-runner.js";
type EmbeddedPiAgentParams = {
enforceFinalTag?: boolean;
prompt?: string;
};
function createRun(params?: {
sessionEntry?: SessionEntry;
sessionKey?: string;
agentCfgContextTokens?: number;
}) {
const typing = createMockTypingController();
const sessionCtx = {
Provider: "whatsapp",
OriginatingTo: "+15550001111",
AccountId: "primary",
MessageSid: "msg",
} as unknown as TemplateContext;
const resolvedQueue = { mode: "interrupt" } as unknown as QueueSettings;
const sessionKey = params?.sessionKey ?? "main";
const followupRun = {
prompt: "hello",
summaryLine: "hello",
enqueuedAt: Date.now(),
run: {
agentId: "main",
agentDir: "/tmp/agent",
sessionId: "session",
sessionKey,
messageProvider: "whatsapp",
sessionFile: "/tmp/session.jsonl",
workspaceDir: "/tmp",
config: {},
skillsSnapshot: {},
provider: "anthropic",
model: "claude",
thinkLevel: "low",
verboseLevel: "off",
elevatedLevel: "off",
bashElevated: {
enabled: false,
allowed: false,
defaultLevel: "off",
},
timeoutMs: 1_000,
blockReplyBreak: "message_end",
},
} as unknown as FollowupRun;
return runReplyAgent({
commandBody: "hello",
followupRun,
queueKey: "main",
resolvedQueue,
shouldSteer: false,
shouldFollowup: false,
isActive: false,
isStreaming: false,
typing,
sessionCtx,
sessionEntry: params?.sessionEntry,
sessionKey,
defaultModel: "anthropic/claude-opus-4-5",
agentCfgContextTokens: params?.agentCfgContextTokens,
resolvedVerboseLevel: "off",
isNewSession: false,
blockStreamingEnabled: false,
resolvedBlockStreamingBreak: "message_end",
shouldInjectGroupIntro: false,
typingMode: "instant",
});
}
describe("runReplyAgent fallback reasoning tags", () => {
beforeEach(() => {
runEmbeddedPiAgentMock.mockReset();
runWithModelFallbackMock.mockReset();
});
it("enforces <final> when the fallback provider requires reasoning tags", async () => {
runEmbeddedPiAgentMock.mockResolvedValueOnce({
payloads: [{ text: "ok" }],
meta: {},
});
runWithModelFallbackMock.mockImplementationOnce(
async ({
run,
}: {
run: (provider: string, model: string) => Promise<unknown>;
}) => ({
result: await run("google-antigravity", "gemini-3"),
provider: "google-antigravity",
model: "gemini-3",
}),
);
await createRun();
const call = runEmbeddedPiAgentMock.mock.calls[0]?.[0] as
| EmbeddedPiAgentParams
| undefined;
expect(call?.enforceFinalTag).toBe(true);
});
it("enforces <final> during memory flush on fallback providers", async () => {
runEmbeddedPiAgentMock.mockImplementation(
async (params: EmbeddedPiAgentParams) => {
if (params.prompt === DEFAULT_MEMORY_FLUSH_PROMPT) {
return { payloads: [], meta: {} };
}
return { payloads: [{ text: "ok" }], meta: {} };
},
);
runWithModelFallbackMock.mockImplementation(
async ({
run,
}: {
run: (provider: string, model: string) => Promise<unknown>;
}) => ({
result: await run("google-antigravity", "gemini-3"),
provider: "google-antigravity",
model: "gemini-3",
}),
);
await createRun({
sessionEntry: {
sessionId: "session",
updatedAt: Date.now(),
totalTokens: 1_000_000,
compactionCount: 0,
},
});
const flushCall = runEmbeddedPiAgentMock.mock.calls.find(
([params]) =>
(params as EmbeddedPiAgentParams | undefined)?.prompt ===
DEFAULT_MEMORY_FLUSH_PROMPT,
)?.[0] as EmbeddedPiAgentParams | undefined;
expect(flushCall?.enforceFinalTag).toBe(true);
});
});
+17 -9
View File
@@ -40,6 +40,7 @@ import { getProviderDock } from "../../providers/dock.js";
import type { ProviderThreadingToolContext } from "../../providers/plugins/types.js";
import { normalizeProviderId } from "../../providers/registry.js";
import { defaultRuntime } from "../../runtime.js";
import { isReasoningTagProvider } from "../../utils/provider-utils.js";
import {
estimateUsageCost,
formatTokenCount,
@@ -411,7 +412,9 @@ export async function runReplyAgent(params: {
prompt: memoryFlushSettings.prompt,
extraSystemPrompt: flushSystemPrompt,
ownerNumbers: followupRun.run.ownerNumbers,
enforceFinalTag: followupRun.run.enforceFinalTag,
enforceFinalTag:
followupRun.run.enforceFinalTag ||
isReasoningTagProvider(provider),
provider,
model,
authProfileId: followupRun.run.authProfileId,
@@ -565,8 +568,9 @@ export async function runReplyAgent(params: {
}
text = stripped.text;
}
if (isSilentReplyText(text, SILENT_REPLY_TOKEN))
if (isSilentReplyText(text, SILENT_REPLY_TOKEN)) {
return { skip: true };
}
return { text, skip: false };
};
const handlePartialForTyping = async (
@@ -658,7 +662,9 @@ export async function runReplyAgent(params: {
prompt: commandBody,
extraSystemPrompt: followupRun.run.extraSystemPrompt,
ownerNumbers: followupRun.run.ownerNumbers,
enforceFinalTag: followupRun.run.enforceFinalTag,
enforceFinalTag:
followupRun.run.enforceFinalTag ||
isReasoningTagProvider(provider),
provider,
model,
authProfileId: followupRun.run.authProfileId,
@@ -714,6 +720,9 @@ export async function runReplyAgent(params: {
blockStreamingEnabled && opts?.onBlockReply
? async (payload) => {
const { text, skip } = normalizeStreamingText(payload);
const hasPayloadMedia =
(payload.mediaUrls?.length ?? 0) > 0;
if (skip && !hasPayloadMedia) return;
const taggedPayload = applyReplyTagsToPayload(
{
text,
@@ -722,10 +731,6 @@ export async function runReplyAgent(params: {
},
sessionCtx.MessageSid,
);
const hasMedia =
Boolean(taggedPayload.mediaUrl) ||
(taggedPayload.mediaUrls?.length ?? 0) > 0;
if (skip && !hasMedia) return;
// Let through payloads with audioAsVoice flag even if empty (need to track it)
if (
!isRenderablePayload(taggedPayload) &&
@@ -740,15 +745,18 @@ export async function runReplyAgent(params: {
},
);
const cleaned = parsed.text || undefined;
const hasRenderableMedia =
Boolean(taggedPayload.mediaUrl) ||
(taggedPayload.mediaUrls?.length ?? 0) > 0;
// Skip empty payloads unless they have audioAsVoice flag (need to track it)
if (
!cleaned &&
!hasMedia &&
!hasRenderableMedia &&
!payload.audioAsVoice &&
!parsed.audioAsVoice
)
return;
if (parsed.isSilent && !hasMedia) return;
if (parsed.isSilent && !hasRenderableMedia) return;
const blockPayload: ReplyPayload = applyReplyToMode({
...taggedPayload,
+1 -1
View File
@@ -632,7 +632,7 @@ export async function applyInlineDirectivesFastLane(params: {
formatModelSwitchEvent: (label: string, alias?: string) => string;
agentCfg?: NonNullable<ClawdbotConfig["agents"]>["defaults"];
modelState: {
resolveDefaultThinkingLevel: () => Promise<ThinkLevel>;
resolveDefaultThinkingLevel: () => Promise<ThinkLevel | undefined>;
allowedModelKeys: Set<string>;
allowedModelCatalog: Awaited<
ReturnType<
+140 -14
View File
@@ -28,10 +28,115 @@ type ModelSelectionState = {
allowedModelKeys: Set<string>;
allowedModelCatalog: ModelCatalog;
resetModelOverride: boolean;
resolveDefaultThinkingLevel: () => Promise<ThinkLevel | undefined>;
resolveDefaultThinkingLevel: () => Promise<ThinkLevel>;
needsModelCatalog: boolean;
};
const FUZZY_VARIANT_TOKENS = [
"lightning",
"preview",
"mini",
"fast",
"turbo",
"lite",
"beta",
"small",
"nano",
];
function scoreFuzzyMatch(params: {
provider: string;
model: string;
fragment: string;
aliasIndex: ModelAliasIndex;
defaultProvider: string;
defaultModel: string;
}): {
score: number;
isDefault: boolean;
variantCount: number;
variantMatchCount: number;
modelLength: number;
key: string;
} {
const provider = normalizeProviderId(params.provider);
const model = params.model;
const fragment = params.fragment.trim().toLowerCase();
const providerLower = provider.toLowerCase();
const modelLower = model.toLowerCase();
const haystack = `${providerLower}/${modelLower}`;
const key = modelKey(provider, model);
const scoreFragment = (
value: string,
weights: { exact: number; starts: number; includes: number },
) => {
if (!fragment) return 0;
let score = 0;
if (value === fragment) score = Math.max(score, weights.exact);
if (value.startsWith(fragment)) score = Math.max(score, weights.starts);
if (value.includes(fragment)) score = Math.max(score, weights.includes);
return score;
};
let score = 0;
score += scoreFragment(haystack, { exact: 220, starts: 140, includes: 110 });
score += scoreFragment(providerLower, {
exact: 180,
starts: 120,
includes: 90,
});
score += scoreFragment(modelLower, {
exact: 160,
starts: 110,
includes: 80,
});
const aliases = params.aliasIndex.byKey.get(key) ?? [];
for (const alias of aliases) {
score += scoreFragment(alias.toLowerCase(), {
exact: 140,
starts: 90,
includes: 60,
});
}
if (modelLower.startsWith(providerLower)) {
score += 30;
}
const fragmentVariants = FUZZY_VARIANT_TOKENS.filter((token) =>
fragment.includes(token),
);
const modelVariants = FUZZY_VARIANT_TOKENS.filter((token) =>
modelLower.includes(token),
);
const variantMatchCount = fragmentVariants.filter((token) =>
modelLower.includes(token),
).length;
const variantCount = modelVariants.length;
if (fragmentVariants.length === 0 && variantCount > 0) {
score -= variantCount * 30;
} else if (fragmentVariants.length > 0) {
if (variantMatchCount > 0) score += variantMatchCount * 40;
if (variantMatchCount === 0) score -= 20;
}
const defaultProvider = normalizeProviderId(params.defaultProvider);
const isDefault =
provider === defaultProvider && model === params.defaultModel;
if (isDefault) score += 20;
return {
score,
isDefault,
variantCount,
variantMatchCount,
modelLength: modelLower.length,
key,
};
}
export async function createModelSelectionState(params: {
cfg: ClawdbotConfig;
agentCfg:
@@ -147,12 +252,16 @@ export async function createModelSelectionState(params: {
modelCatalog = await loadModelCatalog({ config: cfg });
catalogForThinking = modelCatalog;
}
defaultThinkingLevel = resolveThinkingDefault({
const resolved = resolveThinkingDefault({
cfg,
provider,
model,
catalog: catalogForThinking,
});
defaultThinkingLevel =
resolved ??
(agentCfg?.thinkingDefault as ThinkLevel | undefined) ??
"off";
return defaultThinkingLevel;
};
@@ -250,18 +359,35 @@ export function resolveModelDirectiveSelection(params: {
if (!match) return {};
return { selection: buildSelection(match.provider, match.model) };
}
if (candidates.length > 1) {
const shown = candidates
.slice(0, 5)
.map((c) => `${c.provider}/${c.model}`)
.join(", ");
const more =
candidates.length > 5 ? ` (+${candidates.length - 5} more)` : "";
return {
error: `Ambiguous model "${rawTrimmed}". Matches: ${shown}${more}. Use /model to list or specify provider/model.`,
};
}
return {};
if (candidates.length === 0) return {};
const scored = candidates
.map((candidate) => {
const details = scoreFuzzyMatch({
provider: candidate.provider,
model: candidate.model,
fragment,
aliasIndex,
defaultProvider,
defaultModel,
});
return { candidate, ...details };
})
.sort((a, b) => {
if (b.score !== a.score) return b.score - a.score;
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
if (a.variantMatchCount !== b.variantMatchCount)
return b.variantMatchCount - a.variantMatchCount;
if (a.variantCount !== b.variantCount)
return a.variantCount - b.variantCount;
if (a.modelLength !== b.modelLength)
return a.modelLength - b.modelLength;
return a.key.localeCompare(b.key);
});
const best = scored[0]?.candidate;
if (!best) return {};
return { selection: buildSelection(best.provider, best.model) };
};
const resolved = resolveModelRefFromString({
@@ -4,7 +4,9 @@ import type { GetReplyOptions } from "../types.js";
import type { DispatchFromConfigResult } from "./dispatch-from-config.js";
import { dispatchReplyFromConfig } from "./dispatch-from-config.js";
import {
createReplyDispatcher,
createReplyDispatcherWithTyping,
type ReplyDispatcherOptions,
type ReplyDispatcherWithTypingOptions,
} from "./reply-dispatcher.js";
@@ -32,3 +34,24 @@ export async function dispatchReplyWithBufferedBlockDispatcher(params: {
markDispatchIdle();
return result;
}
export async function dispatchReplyWithDispatcher(params: {
ctx: MsgContext;
cfg: ClawdbotConfig;
dispatcherOptions: ReplyDispatcherOptions;
replyOptions?: Omit<GetReplyOptions, "onToolResult" | "onBlockReply">;
replyResolver?: typeof import("../reply.js").getReplyFromConfig;
}): Promise<DispatchFromConfigResult> {
const dispatcher = createReplyDispatcher(params.dispatcherOptions);
const result = await dispatchReplyFromConfig({
ctx: params.ctx,
cfg: params.cfg,
dispatcher,
replyResolver: params.replyResolver,
replyOptions: params.replyOptions,
});
await dispatcher.waitForIdle();
return result;
}
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { createReplyReferencePlanner } from "./reply-reference.js";
describe("createReplyReferencePlanner", () => {
it("disables references when mode is off", () => {
const planner = createReplyReferencePlanner({
replyToMode: "off",
startId: "parent",
});
expect(planner.use()).toBeUndefined();
expect(planner.hasReplied()).toBe(false);
});
it("uses startId once when mode is first", () => {
const planner = createReplyReferencePlanner({
replyToMode: "first",
startId: "parent",
});
expect(planner.use()).toBe("parent");
expect(planner.hasReplied()).toBe(true);
planner.markSent();
expect(planner.use()).toBeUndefined();
});
it("returns startId for every call when mode is all", () => {
const planner = createReplyReferencePlanner({
replyToMode: "all",
startId: "parent",
});
expect(planner.use()).toBe("parent");
expect(planner.use()).toBe("parent");
});
it("prefers existing thread id regardless of mode", () => {
const planner = createReplyReferencePlanner({
replyToMode: "off",
existingId: "thread-1",
startId: "parent",
});
expect(planner.use()).toBe("thread-1");
expect(planner.hasReplied()).toBe(true);
});
it("honors allowReference=false", () => {
const planner = createReplyReferencePlanner({
replyToMode: "all",
startId: "parent",
allowReference: false,
});
expect(planner.use()).toBeUndefined();
expect(planner.hasReplied()).toBe(false);
planner.markSent();
expect(planner.hasReplied()).toBe(true);
});
});
+56
View File
@@ -0,0 +1,56 @@
import type { ReplyToMode } from "../../config/types.js";
export type ReplyReferencePlanner = {
/** Returns the effective reply/thread id for the next send and updates state. */
use(): string | undefined;
/** Mark that a reply was sent (needed when no reference is used). */
markSent(): void;
/** Whether a reply has been sent in this flow. */
hasReplied(): boolean;
};
export function createReplyReferencePlanner(options: {
replyToMode: ReplyToMode;
/** Existing thread/reference id (always used when present). */
existingId?: string;
/** Id to start a new thread/reference when allowed (e.g., parent message id). */
startId?: string;
/** Disable reply references entirely (e.g., when posting inside a new thread). */
allowReference?: boolean;
/** Seed the planner with prior reply state. */
hasReplied?: boolean;
}): ReplyReferencePlanner {
let hasReplied = options.hasReplied ?? false;
const allowReference = options.allowReference !== false;
const existingId = options.existingId?.trim();
const startId = options.startId?.trim();
const use = (): string | undefined => {
if (!allowReference) return undefined;
if (existingId) {
hasReplied = true;
return existingId;
}
if (!startId) return undefined;
if (options.replyToMode === "off") return undefined;
if (options.replyToMode === "all") {
hasReplied = true;
return startId;
}
if (!hasReplied) {
hasReplied = true;
return startId;
}
return undefined;
};
const markSent = () => {
hasReplied = true;
};
return {
use,
markSent,
hasReplied: () => hasReplied,
};
}
+14 -6
View File
@@ -611,7 +611,10 @@ Examples:
clawdbot message poll --provider discord --to channel:123 --poll-question "Snack?" --poll-option Pizza --poll-option Sushi
clawdbot message react --provider discord --to 123 --message-id 456 --emoji "✅"
${theme.muted("Docs:")} ${formatDocsLink("/message", "docs.clawd.bot/message")}`,
${theme.muted("Docs:")} ${formatDocsLink(
"/cli/message",
"docs.clawd.bot/cli/message",
)}`,
)
.action(() => {
message.help({ error: true });
@@ -620,7 +623,7 @@ ${theme.muted("Docs:")} ${formatDocsLink("/message", "docs.clawd.bot/message")}`
const withMessageBase = (command: Command) =>
command
.option("--provider <provider>", `Provider: ${messageProviderOptions}`)
.option("--account <id>", "Provider account id")
.option("--account <id>", "Provider account id (accountId)")
.option("--json", "Output result as JSON", false)
.option("--dry-run", "Print payload and skip sending", false)
.option("--verbose", "Verbose logging", false);
@@ -645,15 +648,20 @@ ${theme.muted("Docs:")} ${formatDocsLink("/message", "docs.clawd.bot/message")}`
try {
await messageCommand(
{
...opts,
...(() => {
const { account, ...rest } = opts;
return {
...rest,
accountId: typeof account === "string" ? account : undefined,
};
})(),
action,
account: opts.account as string | undefined,
},
deps,
defaultRuntime,
);
} catch (err) {
defaultRuntime.error(String(err));
defaultRuntime.error(danger(String(err)));
defaultRuntime.exit(1);
}
};
@@ -670,7 +678,7 @@ ${theme.muted("Docs:")} ${formatDocsLink("/message", "docs.clawd.bot/message")}`
"Attach media (image/audio/video/document). Accepts local paths or URLs.",
)
.option(
"--buttons-json <json>",
"--buttons <json>",
"Telegram inline keyboard buttons as JSON (array of button rows)",
)
.option("--reply-to <id>", "Reply-to message id")
+5 -8
View File
@@ -586,7 +586,7 @@ export async function runConfigureWizard(
const prompter = createClackPrompter();
const snapshot = await readConfigFileSnapshot();
let baseConfig: ClawdbotConfig = snapshot.valid ? snapshot.config : {};
const baseConfig: ClawdbotConfig = snapshot.valid ? snapshot.config : {};
if (snapshot.exists) {
const title = snapshot.valid
@@ -604,14 +604,11 @@ export async function runConfigureWizard(
);
}
if (!snapshot.valid) {
const reset = guardCancel(
await confirm({
message: "Config invalid. Start fresh?",
initialValue: true,
}),
runtime,
outro(
"Config invalid. Run `clawdbot doctor` to repair it, then re-run configure.",
);
if (reset) baseConfig = {};
runtime.exit(1);
return;
}
}
+385
View File
@@ -0,0 +1,385 @@
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
import {
formatGatewaySummary,
formatOutboundDeliverySummary,
} from "../infra/outbound/format.js";
import type { MessageActionRunResult } from "../infra/outbound/message-action-runner.js";
import { getProviderPlugin } from "../providers/plugins/index.js";
import type {
ProviderId,
ProviderMessageActionName,
} from "../providers/plugins/types.js";
import { renderTable } from "../terminal/table.js";
import { isRich, theme } from "../terminal/theme.js";
const shortenText = (value: string, maxLen: number) => {
const chars = Array.from(value);
if (chars.length <= maxLen) return value;
return `${chars.slice(0, Math.max(0, maxLen - 1)).join("")}…`;
};
const resolveProviderLabel = (provider: ProviderId) =>
getProviderPlugin(provider)?.meta.label ?? provider;
function extractMessageId(payload: unknown): string | null {
if (!payload || typeof payload !== "object") return null;
const direct = (payload as { messageId?: unknown }).messageId;
if (typeof direct === "string" && direct.trim()) return direct.trim();
const result = (payload as { result?: unknown }).result;
if (result && typeof result === "object") {
const nested = (result as { messageId?: unknown }).messageId;
if (typeof nested === "string" && nested.trim()) return nested.trim();
}
return null;
}
export type MessageCliJsonEnvelope = {
action: ProviderMessageActionName;
provider: ProviderId;
dryRun: boolean;
handledBy: "plugin" | "core" | "dry-run";
payload: unknown;
};
export function buildMessageCliJson(
result: MessageActionRunResult,
): MessageCliJsonEnvelope {
return {
action: result.action,
provider: result.provider,
dryRun: result.dryRun,
handledBy: result.handledBy,
payload: result.payload,
};
}
type FormatOpts = {
width: number;
};
function renderObjectSummary(payload: unknown, opts: FormatOpts): string[] {
if (!payload || typeof payload !== "object") {
return [String(payload)];
}
const obj = payload as Record<string, unknown>;
const keys = Object.keys(obj);
if (keys.length === 0) return [theme.muted("(empty)")];
const rows = keys.slice(0, 20).map((k) => {
const v = obj[k];
const value =
v == null
? "null"
: Array.isArray(v)
? `${v.length} items`
: typeof v === "object"
? "object"
: typeof v === "string"
? v
: typeof v === "number"
? String(v)
: typeof v === "boolean"
? v
? "true"
: "false"
: typeof v === "bigint"
? v.toString()
: typeof v === "symbol"
? v.toString()
: typeof v === "function"
? "function"
: "unknown";
return { Key: k, Value: shortenText(value, 96) };
});
return [
renderTable({
width: opts.width,
columns: [
{ key: "Key", header: "Key", minWidth: 16 },
{ key: "Value", header: "Value", flex: true, minWidth: 24 },
],
rows,
}).trimEnd(),
];
}
function renderMessageList(
messages: unknown[],
opts: FormatOpts,
emptyLabel: string,
): string[] {
const rows = messages.slice(0, 25).map((m) => {
const msg = m as Record<string, unknown>;
const id =
(typeof msg.id === "string" && msg.id) ||
(typeof msg.ts === "string" && msg.ts) ||
(typeof msg.messageId === "string" && msg.messageId) ||
"";
const authorObj = msg.author as Record<string, unknown> | undefined;
const author =
(typeof msg.authorTag === "string" && msg.authorTag) ||
(typeof authorObj?.username === "string" && authorObj.username) ||
(typeof msg.user === "string" && msg.user) ||
"";
const time =
(typeof msg.timestamp === "string" && msg.timestamp) ||
(typeof msg.ts === "string" && msg.ts) ||
"";
const text =
(typeof msg.content === "string" && msg.content) ||
(typeof msg.text === "string" && msg.text) ||
"";
return {
Time: shortenText(time, 28),
Author: shortenText(author, 22),
Text: shortenText(text.replace(/\s+/g, " ").trim(), 90),
Id: shortenText(id, 22),
};
});
if (rows.length === 0) {
return [theme.muted(emptyLabel)];
}
return [
renderTable({
width: opts.width,
columns: [
{ key: "Time", header: "Time", minWidth: 14 },
{ key: "Author", header: "Author", minWidth: 10 },
{ key: "Text", header: "Text", flex: true, minWidth: 24 },
{ key: "Id", header: "Id", minWidth: 10 },
],
rows,
}).trimEnd(),
];
}
function renderMessagesFromPayload(
payload: unknown,
opts: FormatOpts,
): string[] | null {
if (!payload || typeof payload !== "object") return null;
const messages = (payload as { messages?: unknown }).messages;
if (!Array.isArray(messages)) return null;
return renderMessageList(messages, opts, "No messages.");
}
function renderPinsFromPayload(
payload: unknown,
opts: FormatOpts,
): string[] | null {
if (!payload || typeof payload !== "object") return null;
const pins = (payload as { pins?: unknown }).pins;
if (!Array.isArray(pins)) return null;
return renderMessageList(pins, opts, "No pins.");
}
function extractDiscordSearchResultsMessages(
results: unknown,
): unknown[] | null {
if (!results || typeof results !== "object") return null;
const raw = (results as { messages?: unknown }).messages;
if (!Array.isArray(raw)) return null;
// Discord search returns messages as array-of-array; first element is the message.
const flattened: unknown[] = [];
for (const entry of raw) {
if (Array.isArray(entry) && entry.length > 0) {
flattened.push(entry[0]);
} else if (entry && typeof entry === "object") {
flattened.push(entry);
}
}
return flattened.length ? flattened : null;
}
function renderReactions(payload: unknown, opts: FormatOpts): string[] | null {
if (!payload || typeof payload !== "object") return null;
const reactions = (payload as { reactions?: unknown }).reactions;
if (!Array.isArray(reactions)) return null;
const rows = reactions.slice(0, 50).map((r) => {
const entry = r as Record<string, unknown>;
const emojiObj = entry.emoji as Record<string, unknown> | undefined;
const emoji =
(typeof emojiObj?.raw === "string" && emojiObj.raw) ||
(typeof entry.name === "string" && entry.name) ||
(typeof entry.emoji === "string" && (entry.emoji as string)) ||
"";
const count = typeof entry.count === "number" ? String(entry.count) : "";
const userList = Array.isArray(entry.users)
? (entry.users as unknown[])
.slice(0, 8)
.map((u) => {
if (typeof u === "string") return u;
if (!u || typeof u !== "object") return "";
const user = u as Record<string, unknown>;
return (
(typeof user.tag === "string" && user.tag) ||
(typeof user.username === "string" && user.username) ||
(typeof user.id === "string" && user.id) ||
""
);
})
.filter(Boolean)
: [];
return {
Emoji: emoji,
Count: count,
Users: shortenText(userList.join(", "), 72),
};
});
if (rows.length === 0) return [theme.muted("No reactions.")];
return [
renderTable({
width: opts.width,
columns: [
{ key: "Emoji", header: "Emoji", minWidth: 8 },
{ key: "Count", header: "Count", align: "right", minWidth: 6 },
{ key: "Users", header: "Users", flex: true, minWidth: 20 },
],
rows,
}).trimEnd(),
];
}
export function formatMessageCliText(result: MessageActionRunResult): string[] {
const rich = isRich();
const ok = (text: string) => (rich ? theme.success(text) : text);
const muted = (text: string) => (rich ? theme.muted(text) : text);
const heading = (text: string) => (rich ? theme.heading(text) : text);
const width = Math.max(60, (process.stdout.columns ?? 120) - 1);
const opts: FormatOpts = { width };
if (result.handledBy === "dry-run") {
return [
muted(`[dry-run] would run ${result.action} via ${result.provider}`),
];
}
if (result.kind === "send") {
if (result.handledBy === "core" && result.sendResult) {
const send = result.sendResult;
if (send.via === "direct") {
const directResult = send.result as OutboundDeliveryResult | undefined;
return [ok(formatOutboundDeliverySummary(send.provider, directResult))];
}
const gatewayResult = send.result as { messageId?: string } | undefined;
return [
ok(
formatGatewaySummary({
provider: send.provider,
messageId: gatewayResult?.messageId ?? null,
}),
),
];
}
const label = resolveProviderLabel(result.provider);
const msgId = extractMessageId(result.payload);
return [ok(`✅ Sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`)];
}
if (result.kind === "poll") {
if (result.handledBy === "core" && result.pollResult) {
const poll = result.pollResult;
const pollId = (poll.result as { pollId?: string } | undefined)?.pollId;
const msgId = poll.result?.messageId ?? null;
const lines = [
ok(
formatGatewaySummary({
action: "Poll sent",
provider: poll.provider,
messageId: msgId,
}),
),
];
if (pollId) lines.push(ok(`Poll id: ${pollId}`));
return lines;
}
const label = resolveProviderLabel(result.provider);
const msgId = extractMessageId(result.payload);
return [
ok(`✅ Poll sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`),
];
}
// provider actions (non-send/poll)
const payload = result.payload;
const lines: string[] = [];
if (result.action === "react") {
const added = (payload as { added?: unknown }).added;
const removed = (payload as { removed?: unknown }).removed;
if (typeof added === "string" && added.trim()) {
lines.push(ok(`✅ Reaction added: ${added.trim()}`));
return lines;
}
if (typeof removed === "string" && removed.trim()) {
lines.push(ok(`✅ Reaction removed: ${removed.trim()}`));
return lines;
}
if (Array.isArray(removed)) {
const list = removed
.map((x) => String(x).trim())
.filter(Boolean)
.join(", ");
lines.push(ok(`✅ Reactions removed${list ? `: ${list}` : ""}`));
return lines;
}
lines.push(ok("✅ Reaction updated."));
return lines;
}
const reactionsTable = renderReactions(payload, opts);
if (reactionsTable && result.action === "reactions") {
lines.push(heading("Reactions"));
lines.push(reactionsTable[0] ?? "");
return lines;
}
if (result.action === "read") {
const messagesTable = renderMessagesFromPayload(payload, opts);
if (messagesTable) {
lines.push(heading("Messages"));
lines.push(messagesTable[0] ?? "");
return lines;
}
}
if (result.action === "list-pins") {
const pinsTable = renderPinsFromPayload(payload, opts);
if (pinsTable) {
lines.push(heading("Pinned messages"));
lines.push(pinsTable[0] ?? "");
return lines;
}
}
if (result.action === "search") {
const results = (payload as { results?: unknown }).results;
const list = extractDiscordSearchResultsMessages(results);
if (list) {
lines.push(heading("Search results"));
lines.push(renderMessageList(list, opts, "No results.")[0] ?? "");
return lines;
}
}
// Generic success + compact details table.
lines.push(
ok(`✅ ${result.action} via ${resolveProviderLabel(result.provider)}.`),
);
const summary = renderObjectSummary(payload, opts);
if (summary.length) {
lines.push("");
lines.push(...summary);
lines.push("");
lines.push(muted("Tip: use --json for full output."));
}
return lines;
}
+36 -465
View File
@@ -1,286 +1,32 @@
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
import type { CliDeps } from "../cli/deps.js";
import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js";
import { success } from "../globals.js";
import type {
OutboundDeliveryResult,
OutboundSendDeps,
} from "../infra/outbound/deliver.js";
import { buildOutboundResultEnvelope } from "../infra/outbound/envelope.js";
import type { OutboundSendDeps } from "../infra/outbound/deliver.js";
import { runMessageAction } from "../infra/outbound/message-action-runner.js";
import {
buildOutboundDeliveryJson,
formatGatewaySummary,
formatOutboundDeliverySummary,
} from "../infra/outbound/format.js";
import {
type MessagePollResult,
type MessageSendResult,
sendMessage,
sendPoll,
} from "../infra/outbound/message.js";
import { resolveMessageProviderSelection } from "../infra/outbound/provider-selection.js";
import { dispatchProviderMessageAction } from "../providers/plugins/message-actions.js";
import type { ProviderMessageActionName } from "../providers/plugins/types.js";
PROVIDER_MESSAGE_ACTION_NAMES,
type ProviderMessageActionName,
} from "../providers/plugins/types.js";
import type { RuntimeEnv } from "../runtime.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
type MessageAction =
| "send"
| "poll"
| "react"
| "reactions"
| "read"
| "edit"
| "delete"
| "pin"
| "unpin"
| "list-pins"
| "permissions"
| "thread-create"
| "thread-list"
| "thread-reply"
| "search"
| "sticker"
| "member-info"
| "role-info"
| "emoji-list"
| "emoji-upload"
| "sticker-upload"
| "role-add"
| "role-remove"
| "channel-info"
| "channel-list"
| "voice-status"
| "event-list"
| "event-create"
| "timeout"
| "kick"
| "ban";
type MessageCommandOpts = {
action?: string;
provider?: string;
to?: string;
message?: string;
media?: string;
buttonsJson?: string;
messageId?: string;
replyTo?: string;
threadId?: string;
account?: string;
emoji?: string;
remove?: boolean;
limit?: string;
before?: string;
after?: string;
around?: string;
pollQuestion?: string;
pollOption?: string[] | string;
pollDurationHours?: string;
pollMulti?: boolean;
channelId?: string;
channelIds?: string[] | string;
guildId?: string;
userId?: string;
authorId?: string;
authorIds?: string[] | string;
roleId?: string;
roleIds?: string[] | string;
emojiName?: string;
stickerId?: string[] | string;
stickerName?: string;
stickerDesc?: string;
stickerTags?: string;
threadName?: string;
autoArchiveMin?: string;
query?: string;
eventName?: string;
eventType?: string;
startTime?: string;
endTime?: string;
desc?: string;
location?: string;
durationMin?: string;
until?: string;
reason?: string;
deleteDays?: string;
includeArchived?: boolean;
participant?: string;
fromMe?: boolean;
dryRun?: boolean;
json?: boolean;
gifPlayback?: boolean;
};
type MessageSendOpts = {
to: string;
message: string;
provider: string;
json?: boolean;
dryRun?: boolean;
media?: string;
gifPlayback?: boolean;
account?: string;
};
function normalizeAction(value?: string): MessageAction {
const raw = value?.trim().toLowerCase() || "send";
return raw as MessageAction;
}
function parseIntOption(value: unknown, label: string): number | undefined {
if (value === undefined || value === null) return undefined;
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value !== "string" || value.trim().length === 0) return undefined;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed)) {
throw new Error(`${label} must be a number`);
}
return parsed;
}
function requireString(value: unknown, label: string): string {
if (typeof value !== "string") {
throw new Error(`${label} required`);
}
const trimmed = value.trim();
if (!trimmed) {
throw new Error(`${label} required`);
}
return trimmed;
}
function optionalString(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
return trimmed ? trimmed : undefined;
}
function toStringArray(value: unknown): string[] {
if (Array.isArray(value)) {
return value.map((entry) => String(entry).trim()).filter(Boolean);
}
if (typeof value === "string") {
const trimmed = value.trim();
return trimmed ? [trimmed] : [];
}
return [];
}
function extractToolPayload(result: AgentToolResult<unknown>): unknown {
if (result.details !== undefined) return result.details;
const textBlock = Array.isArray(result.content)
? result.content.find(
(block) =>
block &&
typeof block === "object" &&
(block as { type?: unknown }).type === "text" &&
typeof (block as { text?: unknown }).text === "string",
)
: undefined;
const text = (textBlock as { text?: string } | undefined)?.text;
if (text) {
try {
return JSON.parse(text);
} catch {
return text;
}
}
return result.content ?? result;
}
function logSendDryRun(opts: MessageSendOpts, runtime: RuntimeEnv) {
runtime.log(
`[dry-run] would send via ${opts.provider} -> ${opts.to}: ${opts.message}${
opts.media ? ` (media ${opts.media})` : ""
}`,
);
}
function logPollDryRun(result: MessagePollResult, runtime: RuntimeEnv) {
runtime.log(
`[dry-run] would send poll via ${result.provider} -> ${result.to}:\n Question: ${result.question}\n Options: ${result.options.join(
", ",
)}\n Max selections: ${result.maxSelections}`,
);
}
function logSendResult(
result: MessageSendResult,
opts: MessageSendOpts,
runtime: RuntimeEnv,
) {
if (result.via === "direct") {
const directResult = result.result as OutboundDeliveryResult | undefined;
const summary = formatOutboundDeliverySummary(
result.provider,
directResult,
);
runtime.log(success(summary));
if (opts.json) {
runtime.log(
JSON.stringify(
buildOutboundDeliveryJson({
provider: result.provider,
via: "direct",
to: opts.to,
result: directResult,
mediaUrl: opts.media ?? null,
}),
null,
2,
),
);
}
return;
}
const gatewayResult = result.result as { messageId?: string } | undefined;
runtime.log(
success(
formatGatewaySummary({
provider: result.provider,
messageId: gatewayResult?.messageId ?? null,
}),
),
);
if (opts.json) {
runtime.log(
JSON.stringify(
buildOutboundResultEnvelope({
delivery: buildOutboundDeliveryJson({
provider: result.provider,
via: "gateway",
to: opts.to,
result: gatewayResult,
mediaUrl: opts.media ?? null,
}),
}),
null,
2,
),
);
}
}
import { buildMessageCliJson, formatMessageCliText } from "./message-format.js";
export async function messageCommand(
opts: MessageCommandOpts,
opts: Record<string, unknown>,
deps: CliDeps,
runtime: RuntimeEnv,
) {
const cfg = loadConfig();
const action = normalizeAction(opts.action);
const providerSelection = await resolveMessageProviderSelection({
cfg,
provider: opts.provider,
});
const provider = providerSelection.provider;
const accountId = optionalString(opts.account);
const actionParams = opts as Record<string, unknown>;
const rawAction =
typeof opts.action === "string" ? opts.action.trim().toLowerCase() : "";
const action = (rawAction || "send") as ProviderMessageActionName;
if (!(PROVIDER_MESSAGE_ACTION_NAMES as readonly string[]).includes(action)) {
throw new Error(`Unknown message action: ${action}`);
}
const outboundDeps: OutboundSendDeps = {
sendWhatsApp: deps.sendMessageWhatsApp,
sendTelegram: deps.sendMessageTelegram,
@@ -292,215 +38,40 @@ export async function messageCommand(
deps.sendMessageMSTeams({ cfg, to, text, mediaUrl: opts?.mediaUrl }),
};
if (opts.dryRun && action !== "send" && action !== "poll") {
runtime.log(`[dry-run] would run ${action} via ${provider}`);
return;
}
if (action === "send") {
const to = requireString(opts.to, "to");
const message = requireString(opts.message, "message");
const sendOpts: MessageSendOpts = {
to,
message,
provider,
json: opts.json,
dryRun: opts.dryRun,
media: optionalString(opts.media),
gifPlayback: opts.gifPlayback,
account: accountId,
};
if (opts.dryRun) {
logSendDryRun(sendOpts, runtime);
return;
}
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
const run = async () =>
await runMessageAction({
cfg,
params: actionParams,
accountId,
action,
params: opts,
deps: outboundDeps,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
const payload = extractToolPayload(handled);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
runtime.log(success(`Sent via ${provider}.`));
}
return;
}
const result = await withProgress(
{
label: `Sending via ${provider}...`,
indeterminate: true,
enabled: opts.json !== true,
},
async () =>
await sendMessage({
cfg,
to,
content: message,
provider,
mediaUrl: optionalString(opts.media),
gifPlayback: opts.gifPlayback,
accountId,
dryRun: opts.dryRun,
deps: outboundDeps,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}),
);
logSendResult(result, sendOpts, runtime);
return;
}
const json = opts.json === true;
const dryRun = opts.dryRun === true;
const needsSpinner =
!json && !dryRun && (action === "send" || action === "poll");
if (action === "poll") {
const to = requireString(opts.to, "to");
const question = requireString(opts.pollQuestion, "poll-question");
const options = toStringArray(opts.pollOption);
if (options.length < 2) {
throw new Error("poll-option requires at least two values");
}
const durationHours = parseIntOption(
opts.pollDurationHours,
"poll-duration-hours",
);
const allowMultiselect = Boolean(opts.pollMulti);
const maxSelections = allowMultiselect ? Math.max(2, options.length) : 1;
if (opts.dryRun) {
const result = await sendPoll({
cfg,
to,
question,
options,
maxSelections,
durationHours,
provider,
dryRun: true,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
const result = needsSpinner
? await withProgress(
{
label: action === "poll" ? "Sending poll..." : "Sending...",
indeterminate: true,
enabled: true,
},
});
logPollDryRun(result, runtime);
return;
}
run,
)
: await run();
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
cfg,
params: actionParams,
accountId,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
const payload = extractToolPayload(handled);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
runtime.log(success(`Poll sent via ${provider}.`));
}
return;
}
const result = await withProgress(
{
label: `Sending poll via ${provider}...`,
indeterminate: true,
enabled: opts.json !== true,
},
async () =>
await sendPoll({
cfg,
to,
question,
options,
maxSelections,
durationHours,
provider,
dryRun: opts.dryRun,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}),
);
runtime.log(
success(
formatGatewaySummary({
action: "Poll sent",
provider,
messageId: result.result?.messageId ?? null,
}),
),
);
const pollId = (result.result as { pollId?: string } | undefined)?.pollId;
if (pollId) {
runtime.log(success(`Poll id: ${pollId}`));
}
if (opts.json) {
runtime.log(
JSON.stringify(
{
...buildOutboundResultEnvelope({
delivery: buildOutboundDeliveryJson({
provider,
via: "gateway",
to,
result: result.result,
mediaUrl: null,
}),
}),
question: result.question,
options: result.options,
maxSelections: result.maxSelections,
durationHours: result.durationHours,
pollId,
},
null,
2,
),
);
}
if (json) {
runtime.log(JSON.stringify(buildMessageCliJson(result), null, 2));
return;
}
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
cfg,
params: actionParams,
accountId,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
runtime.log(JSON.stringify(extractToolPayload(handled), null, 2));
return;
for (const line of formatMessageCliText(result)) {
runtime.log(line);
}
throw new Error(
`Action ${action} is not supported for provider ${provider}.`,
);
}
+7
View File
@@ -128,6 +128,13 @@ export async function runNonInteractiveOnboarding(
runtime: RuntimeEnv = defaultRuntime,
) {
const snapshot = await readConfigFileSnapshot();
if (snapshot.exists && !snapshot.valid) {
runtime.error(
"Config invalid. Run `clawdbot doctor` to repair it, then re-run onboarding.",
);
runtime.exit(1);
return;
}
const baseConfig: ClawdbotConfig = snapshot.valid ? snapshot.config : {};
const mode = opts.mode ?? "local";
if (mode !== "local" && mode !== "remote") {
+43
View File
@@ -1685,3 +1685,46 @@ describe("multi-agent agentDir validation", () => {
});
});
});
describe("config preservation on validation failure", () => {
it("preserves unknown fields via passthrough", async () => {
vi.resetModules();
const { validateConfigObject } = await import("./config.js");
const res = validateConfigObject({
agents: { list: [{ id: "pi" }] },
customUnknownField: { nested: "value" },
});
expect(res.ok).toBe(true);
expect(
(res as { config: Record<string, unknown> }).config.customUnknownField,
).toEqual({
nested: "value",
});
});
it("preserves config data when validation fails", async () => {
await withTempHome(async (home) => {
const configDir = path.join(home, ".clawdbot");
await fs.mkdir(configDir, { recursive: true });
await fs.writeFile(
path.join(configDir, "clawdbot.json"),
JSON.stringify({
agents: { list: [{ id: "pi" }] },
routing: { allowFrom: ["+15555550123"] },
customData: { preserved: true },
}),
"utf-8",
);
vi.resetModules();
const { readConfigFileSnapshot } = await import("./config.js");
const snap = await readConfigFileSnapshot();
expect(snap.valid).toBe(false);
expect(snap.legacyIssues.length).toBeGreaterThan(0);
expect((snap.config as Record<string, unknown>).customData).toEqual({
preserved: true,
});
});
});
});
+5 -1
View File
@@ -287,6 +287,10 @@ export function createConfigIO(overrides: ConfigIoDeps = {}) {
}
const legacyIssues = findLegacyConfigIssues(resolved);
const resolvedConfig =
typeof resolved === "object" && resolved !== null
? (resolved as ClawdbotConfig)
: {};
const validated = validateConfigObject(resolved);
if (!validated.ok) {
@@ -296,7 +300,7 @@ export function createConfigIO(overrides: ConfigIoDeps = {}) {
raw,
parsed: parsedRes.parsed,
valid: false,
config: {},
config: resolvedConfig,
issues: validated.issues,
legacyIssues,
};
+1
View File
@@ -1757,6 +1757,7 @@ export const ClawdbotSchema = z
})
.optional(),
})
.passthrough()
.superRefine((cfg, ctx) => {
const agents = cfg.agents?.list ?? [];
if (agents.length === 0) return;
+6 -5
View File
@@ -251,10 +251,11 @@ export async function runCronIsolatedAgentTurn(params: {
const agentId = agentConfigOverride
? (normalizedRequested ?? defaultAgentId)
: defaultAgentId;
const agentCfg: AgentDefaultsConfig = {
...(params.cfg.agents?.defaults ?? {}),
...(agentOverrideRest as Partial<AgentDefaultsConfig>),
};
const agentCfg: AgentDefaultsConfig = Object.assign(
{},
params.cfg.agents?.defaults,
agentOverrideRest as Partial<AgentDefaultsConfig>,
);
if (typeof overrideModel === "string") {
agentCfg.model = { primary: overrideModel };
} else if (overrideModel) {
@@ -262,7 +263,7 @@ export async function runCronIsolatedAgentTurn(params: {
}
const cfgWithAgentDefaults: ClawdbotConfig = {
...params.cfg,
agents: { ...(params.cfg.agents ?? {}), defaults: agentCfg },
agents: Object.assign({}, params.cfg.agents, { defaults: agentCfg }),
};
const baseSessionKey = (
+83
View File
@@ -0,0 +1,83 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const dispatchMock = vi.fn();
vi.mock("@buape/carbon", () => ({
ChannelType: { DM: "dm", GroupDM: "group" },
MessageType: {
ChatInputCommand: 1,
ContextMenuCommand: 2,
Default: 0,
},
Command: class {},
Client: class {},
MessageCreateListener: class {},
MessageReactionAddListener: class {},
MessageReactionRemoveListener: class {},
}));
vi.mock("../auto-reply/reply/dispatch-from-config.js", () => ({
dispatchReplyFromConfig: (...args: unknown[]) => dispatchMock(...args),
}));
beforeEach(() => {
dispatchMock.mockReset().mockImplementation(async ({ dispatcher }) => {
dispatcher.sendToolResult({ text: "tool update" });
dispatcher.sendFinalReply({ text: "final reply" });
return { queuedFinal: true, counts: { tool: 1, block: 0, final: 1 } };
});
});
describe("discord native commands", () => {
it(
"streams tool results for native slash commands",
{ timeout: 10_000 },
async () => {
const { ChannelType } = await import("@buape/carbon");
const { createDiscordNativeCommand } = await import("./monitor.js");
const cfg = {
agents: {
defaults: {
model: "anthropic/claude-opus-4-5",
workspace: "/tmp/clawd",
},
},
session: { store: "/tmp/clawdbot-sessions.json" },
discord: { dm: { enabled: true, policy: "open" } },
} as ReturnType<typeof import("../config/config.js").loadConfig>;
const command = createDiscordNativeCommand({
command: {
name: "verbose",
description: "Toggle verbose mode.",
acceptsArgs: true,
},
cfg,
discordConfig: cfg.discord,
accountId: "default",
sessionPrefix: "discord:slash",
ephemeralDefault: true,
});
const reply = vi.fn().mockResolvedValue(undefined);
const followUp = vi.fn().mockResolvedValue(undefined);
await command.run({
user: { id: "u1", username: "Ada", globalName: "Ada" },
channel: { type: ChannelType.DM },
guild: null,
rawData: { id: "i1" },
options: { getString: vi.fn().mockReturnValue("on") },
reply,
followUp,
});
expect(dispatchMock).toHaveBeenCalledTimes(1);
expect(reply).toHaveBeenCalledTimes(1);
expect(followUp).toHaveBeenCalledTimes(1);
expect(reply.mock.calls[0]?.[0]?.content).toContain("tool");
expect(followUp.mock.calls[0]?.[0]?.content).toContain("final");
},
);
});
+16
View File
@@ -12,6 +12,7 @@ import {
resolveDiscordReplyTarget,
resolveDiscordShouldRequireMention,
resolveGroupDmAllow,
sanitizeDiscordThreadName,
shouldEmitDiscordReactionNotification,
} from "./monitor.js";
@@ -326,6 +327,21 @@ describe("discord reply target selection", () => {
});
});
describe("discord autoThread name sanitization", () => {
it("strips mentions and collapses whitespace", () => {
const name = sanitizeDiscordThreadName(
" <@123> <@&456> <#789> Help here ",
"msg-1",
);
expect(name).toBe("Help here");
});
it("falls back to thread + id when empty after cleaning", () => {
const name = sanitizeDiscordThreadName(" <@123>", "abc");
expect(name).toBe("Thread abc");
});
});
describe("discord reaction notification gating", () => {
it("defaults to own when mode is unset", () => {
expect(
+147 -74
View File
@@ -46,11 +46,9 @@ import {
buildMentionRegexes,
matchesMentionPatterns,
} from "../auto-reply/reply/mentions.js";
import {
createReplyDispatcher,
createReplyDispatcherWithTyping,
} from "../auto-reply/reply/reply-dispatcher.js";
import { getReplyFromConfig } from "../auto-reply/reply.js";
import { dispatchReplyWithDispatcher } from "../auto-reply/reply/provider-dispatcher.js";
import { createReplyDispatcherWithTyping } from "../auto-reply/reply/reply-dispatcher.js";
import { createReplyReferencePlanner } from "../auto-reply/reply/reply-reference.js";
import type { ReplyPayload } from "../auto-reply/types.js";
import {
isNativeCommandsExplicitlyDisabled,
@@ -350,6 +348,87 @@ export function resolveDiscordReplyTarget(opts: {
return opts.hasReplied ? undefined : replyToId;
}
export function sanitizeDiscordThreadName(
rawName: string,
fallbackId: string,
): string {
const cleanedName = rawName
.replace(/<@!?\d+>/g, "") // user mentions
.replace(/<@&\d+>/g, "") // role mentions
.replace(/<#\d+>/g, "") // channel mentions
.replace(/\s+/g, " ")
.trim();
const baseSource = cleanedName || `Thread ${fallbackId}`;
const base = truncateUtf16Safe(baseSource, 80);
return truncateUtf16Safe(base, 100) || `Thread ${fallbackId}`;
}
type DiscordReplyDeliveryPlan = {
deliverTarget: string;
replyTarget: string;
replyReference: ReturnType<typeof createReplyReferencePlanner>;
};
async function maybeCreateDiscordAutoThread(params: {
client: Client;
message: DiscordMessageEvent["message"];
isGuildMessage: boolean;
channelConfig?: DiscordChannelConfigResolved | null;
threadChannel?: DiscordThreadChannel | null;
baseText: string;
combinedBody: string;
}): Promise<string | undefined> {
if (!params.isGuildMessage) return undefined;
if (!params.channelConfig?.autoThread) return undefined;
if (params.threadChannel) return undefined;
try {
const threadName = sanitizeDiscordThreadName(
params.baseText || params.combinedBody || "Thread",
params.message.id,
);
const created = (await params.client.rest.post(
`${Routes.channelMessage(params.message.channelId, params.message.id)}/threads`,
{
body: {
name: threadName,
auto_archive_duration: 60,
},
},
)) as { id?: string };
const createdId = created?.id ? String(created.id) : "";
return createdId || undefined;
} catch (err) {
logVerbose(
`discord: autoThread failed for ${params.message.channelId}/${params.message.id}: ${String(err)}`,
);
return undefined;
}
}
function resolveDiscordReplyDeliveryPlan(params: {
replyTarget: string;
replyToMode: ReplyToMode;
messageId: string;
threadChannel?: DiscordThreadChannel | null;
createdThreadId?: string | null;
}): DiscordReplyDeliveryPlan {
const originalReplyTarget = params.replyTarget;
let deliverTarget = originalReplyTarget;
let replyTarget = originalReplyTarget;
if (params.createdThreadId) {
deliverTarget = `channel:${params.createdThreadId}`;
replyTarget = deliverTarget;
}
const allowReference = deliverTarget === originalReplyTarget;
const replyReference = createReplyReferencePlanner({
replyToMode: allowReference ? params.replyToMode : "off",
existingId: params.threadChannel ? params.messageId : undefined,
startId: params.messageId,
allowReference,
});
return { deliverTarget, replyTarget, replyReference };
}
function summarizeAllowList(list?: Array<string | number>) {
if (!list || list.length === 0) return "any";
const sample = list.slice(0, 4).map((entry) => String(entry));
@@ -456,6 +535,11 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
publicKey: "a",
token,
autoDeploy: nativeEnabled,
eventQueue: {
// Auto-threading (create thread + generate reply + post) can exceed the default
// 30s listener timeout in some environments.
listenerTimeout: 120_000,
},
},
{
commands,
@@ -1179,44 +1263,30 @@ export function createDiscordMessageHandler(params: {
OriginatingChannel: "discord" as const,
OriginatingTo: discordTo,
};
const replyTarget = ctxPayload.To ?? undefined;
let replyTarget = ctxPayload.To ?? undefined;
if (!replyTarget) {
runtime.error?.(danger("discord: missing reply target"));
return;
}
let deliverTarget = replyTarget;
if (isGuildMessage && channelConfig?.autoThread && !threadChannel) {
try {
const base = truncateUtf16Safe(
(baseText || combinedBody || "Thread").replace(/\s+/g, " ").trim(),
80,
);
const authorLabel = author.username ?? author.id;
const threadName =
truncateUtf16Safe(`${authorLabel}: ${base}`.trim(), 100) ||
`Thread ${message.id}`;
const created = (await client.rest.post(
`${Routes.channelMessage(message.channelId, message.id)}/threads`,
{
body: {
name: threadName,
auto_archive_duration: 60,
},
},
)) as { id?: string };
const createdId = created?.id ? String(created.id) : "";
if (createdId) {
deliverTarget = `channel:${createdId}`;
}
} catch (err) {
logVerbose(
`discord: autoThread failed for ${message.channelId}/${message.id}: ${String(err)}`,
);
}
}
const createdThreadId = await maybeCreateDiscordAutoThread({
client,
message,
isGuildMessage,
channelConfig,
threadChannel,
baseText: baseText ?? "",
combinedBody,
});
const replyPlan = resolveDiscordReplyDeliveryPlan({
replyTarget,
replyToMode,
messageId: message.id,
threadChannel,
createdThreadId,
});
const deliverTarget = replyPlan.deliverTarget;
replyTarget = replyPlan.replyTarget;
const replyReference = replyPlan.replyReference;
if (isDirectMessage) {
const sessionCfg = cfg.session;
@@ -1249,6 +1319,7 @@ export function createDiscordMessageHandler(params: {
.responsePrefix,
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
deliver: async (payload) => {
const replyToId = replyReference.use();
await deliverDiscordReply({
replies: [payload],
target: deliverTarget,
@@ -1256,11 +1327,12 @@ export function createDiscordMessageHandler(params: {
accountId,
rest: client.rest,
runtime,
replyToMode: deliverTarget !== replyTarget ? "off" : replyToMode,
replyToId,
textLimit,
maxLinesPerMessage: discordConfig?.maxLinesPerMessage,
});
didSendReply = true;
replyReference.markSent();
},
onError: (err, info) => {
runtime.error?.(
@@ -1528,7 +1600,7 @@ async function handleDiscordReactionEvent(params: {
}
}
function createDiscordNativeCommand(params: {
export function createDiscordNativeCommand(params: {
command: {
name: string;
description: string;
@@ -1758,41 +1830,37 @@ function createDiscordNativeCommand(params: {
};
let didReply = false;
const dispatcher = createReplyDispatcher({
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId)
.responsePrefix,
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
deliver: async (payload, _info) => {
await deliverDiscordInteractionReply({
interaction,
payload,
textLimit: resolveTextChunkLimit(cfg, "discord", accountId, {
fallbackLimit: 2000,
}),
maxLinesPerMessage: discordConfig?.maxLinesPerMessage,
preferFollowUp: didReply,
});
didReply = true;
await dispatchReplyWithDispatcher({
ctx: ctxPayload,
cfg,
dispatcherOptions: {
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId)
.responsePrefix,
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
deliver: async (payload) => {
await deliverDiscordInteractionReply({
interaction,
payload,
textLimit: resolveTextChunkLimit(cfg, "discord", accountId, {
fallbackLimit: 2000,
}),
maxLinesPerMessage: discordConfig?.maxLinesPerMessage,
preferFollowUp: didReply,
});
didReply = true;
},
onError: (err, info) => {
console.error(`discord slash ${info.kind} reply failed`, err);
},
},
onError: (err) => {
console.error(err);
replyOptions: {
skillFilter: channelConfig?.skills,
disableBlockStreaming:
typeof discordConfig?.blockStreaming === "boolean"
? !discordConfig.blockStreaming
: undefined,
},
});
const replyResult = await getReplyFromConfig(
ctxPayload,
{ skillFilter: channelConfig?.skills },
cfg,
);
const replies = replyResult
? Array.isArray(replyResult)
? replyResult
: [replyResult]
: [];
for (const reply of replies) {
dispatcher.sendFinalReply(reply);
}
await dispatcher.waitForIdle();
}
})();
}
@@ -1885,7 +1953,7 @@ async function deliverDiscordReply(params: {
runtime: RuntimeEnv;
textLimit: number;
maxLinesPerMessage?: number;
replyToMode: ReplyToMode;
replyToId?: string;
}) {
const chunkLimit = Math.min(params.textLimit, 2000);
for (const payload of params.replies) {
@@ -1893,8 +1961,10 @@ async function deliverDiscordReply(params: {
payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
const text = payload.text ?? "";
if (!text && mediaList.length === 0) continue;
const replyTo = params.replyToId?.trim() || undefined;
if (mediaList.length === 0) {
let isFirstChunk = true;
for (const chunk of chunkDiscordText(text, {
maxChars: chunkLimit,
maxLines: params.maxLinesPerMessage,
@@ -1905,7 +1975,9 @@ async function deliverDiscordReply(params: {
token: params.token,
rest: params.rest,
accountId: params.accountId,
replyTo: isFirstChunk ? replyTo : undefined,
});
isFirstChunk = false;
}
continue;
}
@@ -1917,6 +1989,7 @@ async function deliverDiscordReply(params: {
rest: params.rest,
mediaUrl: firstMedia,
accountId: params.accountId,
replyTo,
});
for (const extra of mediaList.slice(1)) {
await sendMessageDiscord(params.target, "", {
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import type { ClawdbotConfig } from "../../config/config.js";
import { runMessageAction } from "./message-action-runner.js";
const slackConfig = {
slack: {
botToken: "xoxb-test",
appToken: "xapp-test",
},
} as ClawdbotConfig;
describe("runMessageAction context isolation", () => {
it("allows send when target matches current channel", async () => {
const result = await runMessageAction({
cfg: slackConfig,
action: "send",
params: {
provider: "slack",
to: "#C123",
message: "hi",
},
toolContext: { currentChannelId: "C123" },
dryRun: true,
});
expect(result.kind).toBe("send");
});
it("blocks send when target differs from current channel", async () => {
await expect(
runMessageAction({
cfg: slackConfig,
action: "send",
params: {
provider: "slack",
to: "channel:C999",
message: "hi",
},
toolContext: { currentChannelId: "C123" },
dryRun: true,
}),
).rejects.toThrow(/Cross-context messaging denied/);
});
it("blocks thread-reply when channelId differs from current channel", async () => {
await expect(
runMessageAction({
cfg: slackConfig,
action: "thread-reply",
params: {
provider: "slack",
channelId: "C999",
message: "hi",
},
toolContext: { currentChannelId: "C123" },
dryRun: true,
}),
).rejects.toThrow(/Cross-context messaging denied/);
});
});
+392
View File
@@ -0,0 +1,392 @@
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
import { normalizeTargetForProvider } from "../../agents/pi-embedded-messaging.js";
import {
readNumberParam,
readStringArrayParam,
readStringParam,
} from "../../agents/tools/common.js";
import { parseReplyDirectives } from "../../auto-reply/reply/reply-directives.js";
import type { ClawdbotConfig } from "../../config/config.js";
import { dispatchProviderMessageAction } from "../../providers/plugins/message-actions.js";
import type {
ProviderId,
ProviderMessageActionName,
ProviderThreadingToolContext,
} from "../../providers/plugins/types.js";
import type {
GatewayClientMode,
GatewayClientName,
} from "../../utils/message-provider.js";
import type { OutboundSendDeps } from "./deliver.js";
import type { MessagePollResult, MessageSendResult } from "./message.js";
import { sendMessage, sendPoll } from "./message.js";
import { resolveMessageProviderSelection } from "./provider-selection.js";
export type MessageActionRunnerGateway = {
url?: string;
token?: string;
timeoutMs?: number;
clientName: GatewayClientName;
clientDisplayName?: string;
mode: GatewayClientMode;
};
export type RunMessageActionParams = {
cfg: ClawdbotConfig;
action: ProviderMessageActionName;
params: Record<string, unknown>;
defaultAccountId?: string;
toolContext?: ProviderThreadingToolContext;
gateway?: MessageActionRunnerGateway;
deps?: OutboundSendDeps;
dryRun?: boolean;
};
export type MessageActionRunResult =
| {
kind: "send";
provider: ProviderId;
action: "send";
to: string;
handledBy: "plugin" | "core";
payload: unknown;
toolResult?: AgentToolResult<unknown>;
sendResult?: MessageSendResult;
dryRun: boolean;
}
| {
kind: "poll";
provider: ProviderId;
action: "poll";
to: string;
handledBy: "plugin" | "core";
payload: unknown;
toolResult?: AgentToolResult<unknown>;
pollResult?: MessagePollResult;
dryRun: boolean;
}
| {
kind: "action";
provider: ProviderId;
action: Exclude<ProviderMessageActionName, "send" | "poll">;
handledBy: "plugin" | "dry-run";
payload: unknown;
toolResult?: AgentToolResult<unknown>;
dryRun: boolean;
};
function extractToolPayload(result: AgentToolResult<unknown>): unknown {
if (result.details !== undefined) return result.details;
const textBlock = Array.isArray(result.content)
? result.content.find(
(block) =>
block &&
typeof block === "object" &&
(block as { type?: unknown }).type === "text" &&
typeof (block as { text?: unknown }).text === "string",
)
: undefined;
const text = (textBlock as { text?: string } | undefined)?.text;
if (text) {
try {
return JSON.parse(text);
} catch {
return text;
}
}
return result.content ?? result;
}
function readBooleanParam(
params: Record<string, unknown>,
key: string,
): boolean | undefined {
const raw = params[key];
if (typeof raw === "boolean") return raw;
if (typeof raw === "string") {
const trimmed = raw.trim().toLowerCase();
if (trimmed === "true") return true;
if (trimmed === "false") return false;
}
return undefined;
}
function parseButtonsParam(params: Record<string, unknown>): void {
const raw = params.buttons;
if (typeof raw !== "string") return;
const trimmed = raw.trim();
if (!trimmed) {
delete params.buttons;
return;
}
try {
params.buttons = JSON.parse(trimmed) as unknown;
} catch {
throw new Error("--buttons must be valid JSON");
}
}
const CONTEXT_GUARDED_ACTIONS = new Set<ProviderMessageActionName>([
"send",
"poll",
"thread-create",
"thread-reply",
"sticker",
]);
function resolveContextGuardTarget(
action: ProviderMessageActionName,
params: Record<string, unknown>,
): string | undefined {
if (!CONTEXT_GUARDED_ACTIONS.has(action)) return undefined;
if (action === "thread-reply" || action === "thread-create") {
return (
readStringParam(params, "channelId") ?? readStringParam(params, "to")
);
}
return readStringParam(params, "to") ?? readStringParam(params, "channelId");
}
function enforceContextIsolation(params: {
provider: ProviderId;
action: ProviderMessageActionName;
params: Record<string, unknown>;
toolContext?: ProviderThreadingToolContext;
}): void {
const currentTarget = params.toolContext?.currentChannelId?.trim();
if (!currentTarget) return;
if (!CONTEXT_GUARDED_ACTIONS.has(params.action)) return;
const target = resolveContextGuardTarget(params.action, params.params);
if (!target) return;
const normalizedTarget =
normalizeTargetForProvider(params.provider, target) ?? target.toLowerCase();
const normalizedCurrent =
normalizeTargetForProvider(params.provider, currentTarget) ??
currentTarget.toLowerCase();
if (!normalizedTarget || !normalizedCurrent) return;
if (normalizedTarget === normalizedCurrent) return;
throw new Error(
`Cross-context messaging denied: action=${params.action} target="${target}" while bound to "${currentTarget}" (provider=${params.provider}).`,
);
}
async function resolveProvider(
cfg: ClawdbotConfig,
params: Record<string, unknown>,
) {
const providerHint = readStringParam(params, "provider");
const selection = await resolveMessageProviderSelection({
cfg,
provider: providerHint,
});
return selection.provider;
}
export async function runMessageAction(
input: RunMessageActionParams,
): Promise<MessageActionRunResult> {
const cfg = input.cfg;
const params = { ...input.params };
parseButtonsParam(params);
const action = input.action;
const provider = await resolveProvider(cfg, params);
const accountId =
readStringParam(params, "accountId") ?? input.defaultAccountId;
const dryRun = Boolean(input.dryRun ?? readBooleanParam(params, "dryRun"));
enforceContextIsolation({
provider,
action,
params,
toolContext: input.toolContext,
});
const gateway = input.gateway
? {
url: input.gateway.url,
token: input.gateway.token,
timeoutMs: input.gateway.timeoutMs,
clientName: input.gateway.clientName,
clientDisplayName: input.gateway.clientDisplayName,
mode: input.gateway.mode,
}
: undefined;
if (action === "send") {
const to = readStringParam(params, "to", { required: true });
let message = readStringParam(params, "message", {
required: true,
allowEmpty: true,
});
const parsed = parseReplyDirectives(message);
message = parsed.text;
params.message = message;
if (!params.replyTo && parsed.replyToId) params.replyTo = parsed.replyToId;
if (!params.media) {
params.media = parsed.mediaUrls?.[0] || parsed.mediaUrl || undefined;
}
const mediaUrl = readStringParam(params, "media", { trim: false });
const gifPlayback = readBooleanParam(params, "gifPlayback") ?? false;
const bestEffort = readBooleanParam(params, "bestEffort");
if (!dryRun) {
const handled = await dispatchProviderMessageAction({
provider,
action,
cfg,
params,
accountId: accountId ?? undefined,
gateway,
toolContext: input.toolContext,
dryRun,
});
if (handled) {
return {
kind: "send",
provider,
action,
to,
handledBy: "plugin",
payload: extractToolPayload(handled),
toolResult: handled,
dryRun,
};
}
}
const result: MessageSendResult = await sendMessage({
cfg,
to,
content: message,
mediaUrl: mediaUrl || undefined,
provider: provider || undefined,
accountId: accountId ?? undefined,
gifPlayback,
dryRun,
bestEffort: bestEffort ?? undefined,
deps: input.deps,
gateway,
});
return {
kind: "send",
provider,
action,
to,
handledBy: "core",
payload: result,
sendResult: result,
dryRun,
};
}
if (action === "poll") {
const to = readStringParam(params, "to", { required: true });
const question = readStringParam(params, "pollQuestion", {
required: true,
});
const options =
readStringArrayParam(params, "pollOption", { required: true }) ?? [];
if (options.length < 2) {
throw new Error("pollOption requires at least two values");
}
const allowMultiselect = readBooleanParam(params, "pollMulti") ?? false;
const durationHours = readNumberParam(params, "pollDurationHours", {
integer: true,
});
const maxSelections = allowMultiselect ? Math.max(2, options.length) : 1;
if (!dryRun) {
const handled = await dispatchProviderMessageAction({
provider,
action,
cfg,
params,
accountId: accountId ?? undefined,
gateway,
toolContext: input.toolContext,
dryRun,
});
if (handled) {
return {
kind: "poll",
provider,
action,
to,
handledBy: "plugin",
payload: extractToolPayload(handled),
toolResult: handled,
dryRun,
};
}
}
const result: MessagePollResult = await sendPoll({
cfg,
to,
question,
options,
maxSelections,
durationHours: durationHours ?? undefined,
provider,
dryRun,
gateway,
});
return {
kind: "poll",
provider,
action,
to,
handledBy: "core",
payload: result,
pollResult: result,
dryRun,
};
}
if (dryRun) {
return {
kind: "action",
provider,
action,
handledBy: "dry-run",
payload: { ok: true, dryRun: true, provider, action },
dryRun: true,
};
}
const handled = await dispatchProviderMessageAction({
provider,
action,
cfg,
params,
accountId: accountId ?? undefined,
gateway,
toolContext: input.toolContext,
dryRun,
});
if (!handled) {
throw new Error(
`Message action ${action} not supported for provider ${provider}.`,
);
}
return {
kind: "action",
provider,
action,
handledBy: "plugin",
payload: extractToolPayload(handled),
toolResult: handled,
dryRun,
};
}
+1 -1
View File
@@ -417,7 +417,7 @@ export async function runGatewayUpdate(
const doctorStep = await runStep(
step(
"clawdbot doctor",
managerScriptArgs(manager, "clawdbot", ["doctor"]),
managerScriptArgs(manager, "clawdbot", ["doctor", "--non-interactive"]),
gitRoot,
{ CLAWDBOT_UPDATE_IN_PROGRESS: "1" },
),
+11 -27
View File
@@ -109,41 +109,25 @@ describe("voice-call plugin", () => {
it("tool get_status returns json payload", async () => {
const { tools } = setup({ provider: "mock" });
type VoiceTool = {
execute: (
id: string,
params: unknown,
) =>
| Promise<{ details: Record<string, unknown> }>
| {
details: Record<string, unknown>;
};
const tool = tools[0] as {
execute: (id: string, params: unknown) => Promise<unknown>;
};
const tool = tools[0] as VoiceTool;
const result = await tool.execute("id", {
const result = (await tool.execute("id", {
action: "get_status",
callId: "call-1",
});
expect((result.details as { found?: boolean }).found).toBe(true);
})) as { details: { found?: boolean } };
expect(result.details.found).toBe(true);
});
it("legacy tool status without sid returns error payload", async () => {
const { tools } = setup({ provider: "mock" });
type VoiceTool = {
execute: (
id: string,
params: unknown,
) =>
| Promise<{ details: Record<string, unknown> }>
| {
details: Record<string, unknown>;
};
const tool = tools[0] as {
execute: (id: string, params: unknown) => Promise<unknown>;
};
const tool = tools[0] as VoiceTool;
const result = await tool.execute("id", { mode: "status" });
expect(String((result.details as { error?: unknown }).error)).toContain(
"sid required",
);
const result = (await tool.execute("id", { mode: "status" })) as {
details: { error?: unknown };
};
expect(String(result.details.error)).toContain("sid required");
});
it("CLI start prints JSON", async () => {
+38
View File
@@ -102,6 +102,11 @@ const DOCKS: Record<ProviderId, ProviderDock> = {
},
threading: {
resolveReplyToMode: ({ cfg }) => cfg.telegram?.replyToMode ?? "first",
buildToolContext: ({ context, hasRepliedRef }) => ({
currentChannelId: context.To?.trim() || undefined,
currentThreadTs: context.ReplyToId,
hasRepliedRef,
}),
},
},
whatsapp: {
@@ -142,6 +147,13 @@ const DOCKS: Record<ProviderId, ProviderDock> = {
return [escaped, `@${escaped}`];
},
},
threading: {
buildToolContext: ({ context, hasRepliedRef }) => ({
currentChannelId: context.To?.trim() || undefined,
currentThreadTs: context.ReplyToId,
hasRepliedRef,
}),
},
},
discord: {
id: "discord",
@@ -175,6 +187,11 @@ const DOCKS: Record<ProviderId, ProviderDock> = {
},
threading: {
resolveReplyToMode: ({ cfg }) => cfg.discord?.replyToMode ?? "off",
buildToolContext: ({ context, hasRepliedRef }) => ({
currentChannelId: context.To?.trim() || undefined,
currentThreadTs: context.ReplyToId,
hasRepliedRef,
}),
},
},
slack: {
@@ -246,6 +263,13 @@ const DOCKS: Record<ProviderId, ProviderDock> = {
)
.filter(Boolean),
},
threading: {
buildToolContext: ({ context, hasRepliedRef }) => ({
currentChannelId: context.To?.trim() || undefined,
currentThreadTs: context.ReplyToId,
hasRepliedRef,
}),
},
},
imessage: {
id: "imessage",
@@ -266,6 +290,13 @@ const DOCKS: Record<ProviderId, ProviderDock> = {
groups: {
resolveRequireMention: resolveIMessageGroupRequireMention,
},
threading: {
buildToolContext: ({ context, hasRepliedRef }) => ({
currentChannelId: context.To?.trim() || undefined,
currentThreadTs: context.ReplyToId,
hasRepliedRef,
}),
},
},
msteams: {
id: "msteams",
@@ -280,6 +311,13 @@ const DOCKS: Record<ProviderId, ProviderDock> = {
resolveAllowFrom: ({ cfg }) => cfg.msteams?.allowFrom ?? [],
formatAllowFrom: ({ allowFrom }) => formatLower(allowFrom),
},
threading: {
buildToolContext: ({ context, hasRepliedRef }) => ({
currentChannelId: context.To?.trim() || undefined,
currentThreadTs: context.ReplyToId,
hasRepliedRef,
}),
},
},
};
+1 -13
View File
@@ -63,19 +63,7 @@ export const telegramMessageActions: ProviderMessageActionAdapter = {
const mediaUrl = readStringParam(params, "media", { trim: false });
const replyTo = readStringParam(params, "replyTo");
const threadId = readStringParam(params, "threadId");
let buttons = params.buttons;
if (!buttons) {
const buttonsJson = readStringParam(params, "buttonsJson", {
trim: false,
});
if (buttonsJson) {
try {
buttons = JSON.parse(buttonsJson);
} catch {
throw new Error("buttons-json must be valid JSON");
}
}
}
const buttons = params.buttons;
return await handleTelegramAction(
{
action: "sendMessage",
@@ -0,0 +1,43 @@
export const PROVIDER_MESSAGE_ACTION_NAMES = [
"send",
"poll",
"react",
"reactions",
"read",
"edit",
"delete",
"pin",
"unpin",
"list-pins",
"permissions",
"thread-create",
"thread-list",
"thread-reply",
"search",
"sticker",
"member-info",
"role-info",
"emoji-list",
"emoji-upload",
"sticker-upload",
"role-add",
"role-remove",
"channel-info",
"channel-list",
"channel-create",
"channel-edit",
"channel-delete",
"channel-move",
"category-create",
"category-edit",
"category-delete",
"voice-status",
"event-list",
"event-create",
"timeout",
"kick",
"ban",
] as const;
export type ProviderMessageActionName =
(typeof PROVIDER_MESSAGE_ACTION_NAMES)[number];
+4 -39
View File
@@ -13,8 +13,11 @@ import type {
GatewayClientName,
} from "../../utils/message-provider.js";
import type { ChatProviderId } from "../registry.js";
import type { ProviderMessageActionName as ProviderMessageActionNameFromList } from "./message-action-names.js";
import type { ProviderOnboardingAdapter } from "./onboarding-types.js";
export { PROVIDER_MESSAGE_ACTION_NAMES } from "./message-action-names.js";
export type ProviderId = ChatProviderId;
export type ProviderOutboundTargetMode = "explicit" | "implicit" | "heartbeat";
@@ -478,45 +481,7 @@ export type ProviderMessagingAdapter = {
normalizeTarget?: (raw: string) => string | undefined;
};
export type ProviderMessageActionName =
| "send"
| "poll"
| "react"
| "reactions"
| "read"
| "edit"
| "delete"
| "pin"
| "unpin"
| "list-pins"
| "permissions"
| "thread-create"
| "thread-list"
| "thread-reply"
| "search"
| "sticker"
| "member-info"
| "role-info"
| "emoji-list"
| "emoji-upload"
| "sticker-upload"
| "role-add"
| "role-remove"
| "channel-info"
| "channel-list"
| "channel-create"
| "channel-edit"
| "channel-delete"
| "channel-move"
| "category-create"
| "category-edit"
| "category-delete"
| "voice-status"
| "event-list"
| "event-create"
| "timeout"
| "kick"
| "ban";
export type ProviderMessageActionName = ProviderMessageActionNameFromList;
export type ProviderMessageActionContext = {
provider: ProviderId;
+86 -37
View File
@@ -34,8 +34,9 @@ import {
buildMentionRegexes,
matchesMentionPatterns,
} from "../auto-reply/reply/mentions.js";
import { dispatchReplyWithDispatcher } from "../auto-reply/reply/provider-dispatcher.js";
import { createReplyDispatcherWithTyping } from "../auto-reply/reply/reply-dispatcher.js";
import { getReplyFromConfig } from "../auto-reply/reply.js";
import { createReplyReferencePlanner } from "../auto-reply/reply/reply-reference.js";
import { isSilentReplyText, SILENT_REPLY_TOKEN } from "../auto-reply/tokens.js";
import type { ReplyPayload } from "../auto-reply/types.js";
import { resolveNativeCommandsEnabled } from "../config/commands.js";
@@ -1135,6 +1136,12 @@ export async function monitorSlackProvider(opts: MonitorSlackOpts = {}) {
// Shared mutable ref for tracking if a reply was sent (used by both
// auto-reply path and tool path for "first" threading mode).
const hasRepliedRef = { value: false };
const replyPlan = createSlackReplyDeliveryPlan({
replyToMode,
incomingThreadTs,
messageTs,
hasRepliedRef,
});
const onReplyStart = async () => {
didSetStatus = true;
await setSlackThreadStatus({
@@ -1150,12 +1157,7 @@ export async function monitorSlackProvider(opts: MonitorSlackOpts = {}) {
.responsePrefix,
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
deliver: async (payload) => {
const effectiveThreadTs = resolveSlackThreadTs({
replyToMode,
incomingThreadTs,
messageTs,
hasReplied: hasRepliedRef.value,
});
const replyThreadTs = replyPlan.nextThreadTs();
await deliverReplies({
replies: [payload],
target: replyTarget,
@@ -1163,10 +1165,10 @@ export async function monitorSlackProvider(opts: MonitorSlackOpts = {}) {
accountId: account.accountId,
runtime,
textLimit,
replyThreadTs: effectiveThreadTs,
replyThreadTs,
});
didSendReply = true;
hasRepliedRef.value = true;
replyPlan.markSent();
},
onError: (err, info) => {
runtime.error?.(
@@ -1919,23 +1921,36 @@ export async function monitorSlackProvider(opts: MonitorSlackOpts = {}) {
OriginatingTo: `user:${command.user_id}`,
};
const replyResult = await getReplyFromConfig(
ctxPayload,
{ skillFilter: channelConfig?.skills },
const { counts } = await dispatchReplyWithDispatcher({
ctx: ctxPayload,
cfg,
);
const replies = replyResult
? Array.isArray(replyResult)
? replyResult
: [replyResult]
: [];
await deliverSlackSlashReplies({
replies,
respond,
ephemeral: slashCommand.ephemeral,
textLimit,
dispatcherOptions: {
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId)
.responsePrefix,
deliver: async (payload) => {
await deliverSlackSlashReplies({
replies: [payload],
respond,
ephemeral: slashCommand.ephemeral,
textLimit,
});
},
onError: (err, info) => {
runtime.error?.(
danger(`slack slash ${info.kind} reply failed: ${String(err)}`),
);
},
},
replyOptions: { skillFilter: channelConfig?.skills },
});
if (counts.final + counts.tool + counts.block === 0) {
await deliverSlackSlashReplies({
replies: [],
respond,
ephemeral: slashCommand.ephemeral,
textLimit,
});
}
} catch (err) {
runtime.error?.(danger(`slack slash handler failed: ${String(err)}`));
await respond({
@@ -2071,19 +2086,53 @@ export function resolveSlackThreadTs(params: {
messageTs: string | undefined;
hasReplied: boolean;
}): string | undefined {
const { replyToMode, incomingThreadTs, messageTs, hasReplied } = params;
if (incomingThreadTs) return incomingThreadTs;
if (!messageTs) return undefined;
if (replyToMode === "all") {
// All replies go to thread
return messageTs;
}
if (replyToMode === "first") {
// "first": only first reply goes to thread
return hasReplied ? undefined : messageTs;
}
// "off": never start a thread
return undefined;
const planner = createSlackReplyReferencePlanner({
replyToMode: params.replyToMode,
incomingThreadTs: params.incomingThreadTs,
messageTs: params.messageTs,
hasReplied: params.hasReplied,
});
return planner.use();
}
type SlackReplyDeliveryPlan = {
nextThreadTs: () => string | undefined;
markSent: () => void;
};
function createSlackReplyReferencePlanner(params: {
replyToMode: "off" | "first" | "all";
incomingThreadTs: string | undefined;
messageTs: string | undefined;
hasReplied?: boolean;
}) {
return createReplyReferencePlanner({
replyToMode: params.replyToMode,
existingId: params.incomingThreadTs,
startId: params.messageTs,
hasReplied: params.hasReplied,
});
}
function createSlackReplyDeliveryPlan(params: {
replyToMode: "off" | "first" | "all";
incomingThreadTs: string | undefined;
messageTs: string | undefined;
hasRepliedRef: { value: boolean };
}): SlackReplyDeliveryPlan {
const replyReference = createSlackReplyReferencePlanner({
replyToMode: params.replyToMode,
incomingThreadTs: params.incomingThreadTs,
messageTs: params.messageTs,
hasReplied: params.hasRepliedRef.value,
});
return {
nextThreadTs: () => replyReference.use(),
markSent: () => {
replyReference.markSent();
params.hasRepliedRef.value = replyReference.hasReplied();
},
};
}
async function deliverSlackSlashReplies(params: {
+43
View File
@@ -1871,6 +1871,49 @@ describe("createTelegramBot", () => {
);
});
it("streams tool summaries for native slash commands", async () => {
onSpy.mockReset();
sendMessageSpy.mockReset();
commandSpy.mockReset();
const replySpy = replyModule.__replySpy as unknown as ReturnType<
typeof vi.fn
>;
replySpy.mockReset();
replySpy.mockImplementation(async (_ctx, opts) => {
await opts?.onToolResult?.({ text: "tool update" });
return { text: "final reply" };
});
loadConfig.mockReturnValue({
commands: { native: true },
telegram: {
dmPolicy: "open",
allowFrom: ["*"],
},
});
createTelegramBot({ token: "tok" });
const verboseHandler = commandSpy.mock.calls.find(
(call) => call[0] === "verbose",
)?.[1] as ((ctx: Record<string, unknown>) => Promise<void>) | undefined;
if (!verboseHandler) throw new Error("verbose command handler missing");
await verboseHandler({
message: {
chat: { id: 12345, type: "private" },
from: { id: 12345, username: "testuser" },
text: "/verbose on",
date: 1736380800,
message_id: 42,
},
match: "on",
});
expect(sendMessageSpy).toHaveBeenCalledTimes(2);
expect(sendMessageSpy.mock.calls[0]?.[1]).toContain("tool update");
expect(sendMessageSpy.mock.calls[1]?.[1]).toContain("final reply");
});
it("dedupes duplicate message updates by update_id", async () => {
onSpy.mockReset();
const replySpy = replyModule.__replySpy as unknown as ReturnType<
+58 -31
View File
@@ -31,7 +31,6 @@ import {
matchesMentionPatterns,
} from "../auto-reply/reply/mentions.js";
import { dispatchReplyWithBufferedBlockDispatcher } from "../auto-reply/reply/provider-dispatcher.js";
import { getReplyFromConfig } from "../auto-reply/reply.js";
import type { ReplyPayload } from "../auto-reply/types.js";
import {
isNativeCommandsExplicitlyDisabled,
@@ -932,8 +931,13 @@ export function createTelegramBot(opts: TelegramBotOptions) {
? listNativeCommandSpecsForConfig(cfg)
: [];
if (nativeCommands.length > 0) {
if (typeof bot.api.setMyCommands === "function") {
bot.api
const api = bot.api as unknown as {
setMyCommands?: (
commands: Array<{ command: string; description: string }>,
) => Promise<unknown>;
};
if (typeof api.setMyCommands === "function") {
api
.setMyCommands(
nativeCommands.map((command) => ({
command: command.name,
@@ -946,15 +950,13 @@ export function createTelegramBot(opts: TelegramBotOptions) {
);
});
} else {
runtime.info?.(
"telegram: setMyCommands not available on api mock; skipping",
);
logVerbose("telegram: setMyCommands unavailable; skipping registration");
}
if (typeof bot.command !== "function") {
runtime.info?.(
"telegram: bot.command not available on api mock; skipping native command handlers",
);
if (
typeof (bot as unknown as { command?: unknown }).command !== "function"
) {
logVerbose("telegram: bot.command unavailable; skipping native handlers");
} else {
for (const command of nativeCommands) {
bot.command(command.name, async (ctx) => {
@@ -1125,33 +1127,58 @@ export function createTelegramBot(opts: TelegramBotOptions) {
IsForum: isForum,
};
const replyResult = await getReplyFromConfig(
ctxPayload,
{ skillFilter },
const disableBlockStreaming =
typeof telegramCfg.blockStreaming === "boolean"
? !telegramCfg.blockStreaming
: undefined;
await dispatchReplyWithBufferedBlockDispatcher({
ctx: ctxPayload,
cfg,
);
const replies = replyResult
? Array.isArray(replyResult)
? replyResult
: [replyResult]
: [];
await deliverReplies({
replies,
chatId: String(chatId),
token: opts.token,
runtime,
bot,
replyToMode,
textLimit,
messageThreadId,
dispatcherOptions: {
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId)
.responsePrefix,
deliver: async (payload) => {
await deliverReplies({
replies: [payload],
chatId: String(chatId),
token: opts.token,
runtime,
bot,
replyToMode,
textLimit,
messageThreadId,
});
},
onError: (err, info) => {
runtime.error?.(
danger(
`telegram slash ${info.kind} reply failed: ${String(err)}`,
),
);
},
},
replyOptions: {
skillFilter,
disableBlockStreaming,
},
});
});
}
}
} else if (nativeDisabledExplicit) {
bot.api.setMyCommands([]).catch((err) => {
runtime.error?.(danger(`telegram clear commands failed: ${String(err)}`));
});
const api = bot.api as unknown as {
setMyCommands?: (commands: []) => Promise<unknown>;
};
if (typeof api.setMyCommands === "function") {
api.setMyCommands([]).catch((err) => {
runtime.error?.(
danger(`telegram clear commands failed: ${String(err)}`),
);
});
} else {
logVerbose("telegram: setMyCommands unavailable; skipping clear");
}
}
bot.on("callback_query", async (ctx) => {
+52
View File
@@ -80,6 +80,58 @@ vi.mock("../tui/tui.js", () => ({
}));
describe("runOnboardingWizard", () => {
it("exits when config is invalid", async () => {
readConfigFileSnapshot.mockResolvedValueOnce({
path: "/tmp/.clawdbot/clawdbot.json",
exists: true,
raw: "{}",
parsed: {},
valid: false,
config: {},
issues: [{ path: "routing.allowFrom", message: "Legacy key" }],
legacyIssues: [{ path: "routing.allowFrom", message: "Legacy key" }],
});
const select: WizardPrompter["select"] = vi.fn(async () => "quickstart");
const prompter: WizardPrompter = {
intro: vi.fn(async () => {}),
outro: vi.fn(async () => {}),
note: vi.fn(async () => {}),
select,
multiselect: vi.fn(async () => []),
text: vi.fn(async () => ""),
confirm: vi.fn(async () => false),
progress: vi.fn(() => ({ update: vi.fn(), stop: vi.fn() })),
};
const runtime: RuntimeEnv = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn((code: number) => {
throw new Error(`exit:${code}`);
}),
};
await expect(
runOnboardingWizard(
{
flow: "quickstart",
authChoice: "skip",
installDaemon: false,
skipProviders: true,
skipSkills: true,
skipHealth: true,
skipUi: true,
},
runtime,
prompter,
),
).rejects.toThrow("exit:1");
expect(select).not.toHaveBeenCalled();
expect(prompter.outro).toHaveBeenCalled();
});
it("skips prompts and setup steps when flags are set", async () => {
const select: WizardPrompter["select"] = vi.fn(async () => "quickstart");
const multiselect: WizardPrompter["multiselect"] = vi.fn(async () => []);
+8 -2
View File
@@ -96,6 +96,14 @@ export async function runOnboardingWizard(
);
}
if (!snapshot.valid) {
await prompter.outro(
"Config invalid. Run `clawdbot doctor` to repair it, then re-run onboarding.",
);
runtime.exit(1);
return;
}
const action = (await prompter.select({
message: "Config handling",
options: [
@@ -124,8 +132,6 @@ export async function runOnboardingWizard(
})) as ResetScope;
await handleReset(resetScope, resolveUserPath(workspaceDefault), runtime);
baseConfig = {};
} else if (action === "keep" && !snapshot.valid) {
baseConfig = {};
}
}
+118 -37
View File
@@ -4,6 +4,7 @@ import { formatAgo } from "../format";
import type {
DiscordStatus,
IMessageStatus,
ProviderAccountSnapshot,
ProvidersStatusSnapshot,
SignalStatus,
SlackStatus,
@@ -132,6 +133,7 @@ export function renderConnections(props: ConnectionsProps) {
slack,
signal,
imessage,
providerAccounts: props.snapshot?.providerAccounts ?? null,
}),
)}
</section>
@@ -206,6 +208,26 @@ function providerEnabled(key: ProviderKey, props: ConnectionsProps) {
}
}
function getProviderAccountCount(
key: ProviderKey,
providerAccounts?: Record<string, ProviderAccountSnapshot[]> | null,
): number {
return providerAccounts?.[key]?.length ?? 0;
}
function renderProviderAccountCount(
key: ProviderKey,
providerAccounts?: Record<string, ProviderAccountSnapshot[]> | null,
) {
const count = getProviderAccountCount(key, providerAccounts);
if (count < 2) return nothing;
return html`
<div class="muted" style="margin-top: 8px; font-weight: 500;">
Accounts (${count})
</div>
`;
}
function renderProvider(
key: ProviderKey,
props: ConnectionsProps,
@@ -216,15 +238,21 @@ function renderProvider(
slack?: SlackStatus | null;
signal?: SignalStatus | null;
imessage?: IMessageStatus | null;
providerAccounts?: Record<string, ProviderAccountSnapshot[]> | null;
},
) {
const accountCountLabel = renderProviderAccountCount(
key,
data.providerAccounts,
);
switch (key) {
case "whatsapp": {
const whatsapp = data.whatsapp;
return html`
<div class="card">
<div class="card-title">WhatsApp</div>
<div class="card-sub">Link WhatsApp Web and monitor connection health.</div>
<div class="card">
<div class="card-title">WhatsApp</div>
<div class="card-sub">Link WhatsApp Web and monitor connection health.</div>
${accountCountLabel}
<div class="status-list" style="margin-top: 16px;">
<div>
@@ -321,33 +349,82 @@ function renderProvider(
}
case "telegram": {
const telegram = data.telegram;
const telegramAccounts = data.providerAccounts?.telegram ?? [];
const hasMultipleAccounts = telegramAccounts.length > 1;
const renderAccountCard = (account: ProviderAccountSnapshot) => {
const probe =
(account.probe as { bot?: { username?: string } } | undefined) ??
undefined;
const botUsername = probe?.bot?.username;
const label = account.name || account.accountId;
return html`
<div style="border: 1px solid var(--border); border-radius: 6px; padding: 12px; margin-bottom: 8px;">
<div style="font-weight: 500; margin-bottom: 8px;">
${botUsername ? `@${botUsername}` : label}
<span class="muted" style="font-weight: normal;">(${account.accountId})</span>
</div>
<div class="status-list" style="font-size: 13px;">
<div>
<span class="label">Running</span>
<span>${account.running ? "Yes" : "No"}</span>
</div>
<div>
<span class="label">Configured</span>
<span>${account.configured ? "Yes" : "No"}</span>
</div>
<div>
<span class="label">Last inbound</span>
<span>${account.lastInboundAt ? formatAgo(account.lastInboundAt) : "n/a"}</span>
</div>
${account.lastError
? html`
<div style="color: var(--danger); margin-top: 4px;">
${account.lastError}
</div>
`
: nothing}
</div>
</div>
`;
};
return html`
<div class="card">
<div class="card-title">Telegram</div>
<div class="card-sub">Bot token and delivery options.</div>
${accountCountLabel}
<div class="status-list" style="margin-top: 16px;">
<div>
<span class="label">Configured</span>
<span>${telegram?.configured ? "Yes" : "No"}</span>
</div>
<div>
<span class="label">Running</span>
<span>${telegram?.running ? "Yes" : "No"}</span>
</div>
<div>
<span class="label">Mode</span>
<span>${telegram?.mode ?? "n/a"}</span>
</div>
<div>
<span class="label">Last start</span>
<span>${telegram?.lastStartAt ? formatAgo(telegram.lastStartAt) : "n/a"}</span>
</div>
<div>
<span class="label">Last probe</span>
<span>${telegram?.lastProbeAt ? formatAgo(telegram.lastProbeAt) : "n/a"}</span>
</div>
</div>
${hasMultipleAccounts
? html`
<div style="margin-top: 16px; margin-bottom: 8px;">
${telegramAccounts.map((account) => renderAccountCard(account))}
</div>
`
: html`
<div class="status-list" style="margin-top: 16px;">
<div>
<span class="label">Configured</span>
<span>${telegram?.configured ? "Yes" : "No"}</span>
</div>
<div>
<span class="label">Running</span>
<span>${telegram?.running ? "Yes" : "No"}</span>
</div>
<div>
<span class="label">Mode</span>
<span>${telegram?.mode ?? "n/a"}</span>
</div>
<div>
<span class="label">Last start</span>
<span>${telegram?.lastStartAt ? formatAgo(telegram.lastStartAt) : "n/a"}</span>
</div>
<div>
<span class="label">Last probe</span>
<span>${telegram?.lastProbeAt ? formatAgo(telegram.lastProbeAt) : "n/a"}</span>
</div>
</div>
`}
${telegram?.lastError
? html`<div class="callout danger" style="margin-top: 12px;">
@@ -513,9 +590,10 @@ function renderProvider(
const discord = data.discord;
const botName = discord?.probe?.bot?.username;
return html`
<div class="card">
<div class="card-title">Discord</div>
<div class="card-sub">Bot connection and probe status.</div>
<div class="card">
<div class="card-title">Discord</div>
<div class="card-sub">Bot connection and probe status.</div>
${accountCountLabel}
<div class="status-list" style="margin-top: 16px;">
<div>
@@ -1037,9 +1115,10 @@ function renderProvider(
const botName = slack?.probe?.bot?.name;
const teamName = slack?.probe?.team?.name;
return html`
<div class="card">
<div class="card-title">Slack</div>
<div class="card-sub">Socket mode status and bot details.</div>
<div class="card">
<div class="card-title">Slack</div>
<div class="card-sub">Socket mode status and bot details.</div>
${accountCountLabel}
<div class="status-list" style="margin-top: 16px;">
<div>
@@ -1418,9 +1497,10 @@ function renderProvider(
case "signal": {
const signal = data.signal;
return html`
<div class="card">
<div class="card-title">Signal</div>
<div class="card-sub">REST daemon status and probe details.</div>
<div class="card">
<div class="card-title">Signal</div>
<div class="card-sub">REST daemon status and probe details.</div>
${accountCountLabel}
<div class="status-list" style="margin-top: 16px;">
<div>
@@ -1647,9 +1727,10 @@ function renderProvider(
case "imessage": {
const imessage = data.imessage;
return html`
<div class="card">
<div class="card-title">iMessage</div>
<div class="card-sub">imsg CLI and database availability.</div>
<div class="card">
<div class="card-title">iMessage</div>
<div class="card-sub">imsg CLI and database availability.</div>
${accountCountLabel}
<div class="status-list" style="margin-top: 16px;">
<div>