Compare commits

..
Author SHA1 Message Date
Peter Steinberger 0b5f672353 docs(changelog): mention Dockerfile Bun install (#284) 2026-01-06 15:02:27 +01:00
Peter Steinberger 9c13819f39 Merge remote-tracking branch 'origin/main' into fix/dockerfile-install-bun 2026-01-06 15:00:54 +01:00
Peter Steinberger dbac51e60f chore(protocol): regenerate GatewayModels.swift 2026-01-06 09:55:58 +01:00
Peter Steinberger ddba2c6912 docs: point docs links to GitHub while docs down 2026-01-06 09:45:03 +01:00
Peter Steinberger 3693449d7e feat: sandbox session tool visibility 2026-01-06 08:40:30 +00:00
Lukáš LoukotaandClaude Opus 4.5 971153f4de fix: install Bun in Dockerfile for build scripts
The build script was updated to use Bun (`bun scripts/canvas-a2ui-copy.ts`)
but the Dockerfile was not updated to install Bun, causing Docker builds to fail
with "bun: not found".

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 09:40:27 +01:00
Peter Steinberger ef58399fcd docs(changelog): note auth rotation + configure order 2026-01-06 09:25:42 +01:00
Peter Steinberger 5926a98c52 fix(configure): don’t write auth.order by default 2026-01-06 09:25:36 +01:00
Peter Steinberger f2d353459f test(auth): stop prioritizing lastGood 2026-01-06 09:25:33 +01:00
Peter Steinberger ed2075ce69 test(gateway): deflake cron finished event wait 2026-01-06 09:25:31 +01:00
Muhammed Mukhthar CM 9e49c762e0 fix(auth): prioritize round-robin over lastGood for multi-account rotation (#281)
* fix(auth): prioritize round-robin over lastGood for multi-account rotation

When multiple OAuth accounts are configured, the round-robin rotation was
not working because lastGood was always prioritized, defeating the sort by
lastUsed.

Changes:
- Remove lastGood prioritization in resolveAuthProfileOrder
- Always apply orderProfilesByMode (sorts by lastUsed, oldest first)
- Only respect configuredOrder when explicitly set in config
- preferredProfile still takes priority for explicit user choice

Tested with 2 Google Antigravity accounts - verified alternating usage.

Follow-up to PR #269.

* style: fix formatting
2026-01-06 08:16:35 +00:00
Peter Steinberger cf1a1d107e fix: add OpenAI Codex OAuth to configure 2026-01-06 09:13:51 +01:00
Peter Steinberger 30b6c417c7 docs(changelog): note bun UI build 2026-01-06 09:13:51 +01:00
Muhammed Mukhthar CM 42d1c2448e fix(cron-tool): use generic object schema for job/patch to fix Claude via Antigravity (#280) 2026-01-06 02:13:09 -06:00
Peter Steinberger c27dd75135 build(control-ui): prefer bun for UI build 2026-01-06 09:08:25 +01:00
Peter Steinberger 5774b4f300 fix(control-ui): pad chat composer in focus mode 2026-01-06 08:59:05 +01:00
Peter Steinberger df6d545050 docs: update docs domain + link labels 2026-01-06 08:57:58 +01:00
Peter Steinberger a279bcfeb1 feat: add sessions_spawn sub-agent tool 2026-01-06 08:41:45 +01:00
Peter Steinberger 952657d55c feat(tui): add /elev alias 2026-01-06 08:41:04 +01:00
Peter Steinberger 882048d90b feat(control-ui): add chat focus mode 2026-01-06 08:16:21 +01:00
Peter Steinberger 173e9f103e docs: add changelog entry for bun migration (#278) 2026-01-06 08:15:20 +01:00
Peter Steinberger e03a5628e3 docs: prefer bun-first TypeScript execution 2026-01-06 08:15:03 +01:00
Ayaan Zaidi 7a48b908e4 refactor: replace tsx with bun for TypeScript execution (#278) 2026-01-06 07:14:08 +00:00
Peter Steinberger b472143882 chore: update terminal css 2026-01-06 07:58:09 +01:00
Peter Steinberger d14505ff78 Merge pull request #274 from kiranjd/fix/chat-scroll-to-bottom
fix(ui): scroll chat to bottom on initial load
2026-01-06 06:49:29 +00:00
Peter Steinberger 5b183b4fe3 fix(ui): scroll chat to bottom on initial load 2026-01-06 07:49:12 +01:00
Peter Steinberger dbb51006cd feat: unify group policy allowlists 2026-01-06 06:40:42 +00:00
Peter Steinberger 51e8bbd2a8 style: normalize type definitions 2026-01-06 07:21:10 +01:00
Peter Steinberger aa16b679ad fix: improve auth profile failover 2026-01-06 07:18:06 +01:00
Peter Steinberger a7b5753dc4 Merge pull request #269 from mukhtharcm/feat/multi-account-roundrobin
feat: Multi-account OAuth with round-robin rotation
2026-01-06 06:13:19 +00:00
Peter Steinberger b5c604b7b7 fix: require slash for control commands 2026-01-06 07:05:17 +01:00
Peter Steinberger 7d896b5f67 fix: doctor memory hint 2026-01-06 06:01:24 +00:00
Kiran Jd b584770055 Merge branch 'main' into fix/chat-scroll-to-bottom 2026-01-06 11:27:57 +05:30
Shadow f29efb9862 docs: add issue templates 2026-01-05 23:55:51 -06:00
kiranjd 511632f47c fix(ui): scroll chat to bottom on initial load
The chat view was starting at the top showing oldest messages instead of
scrolling to the bottom to show the latest messages (like WhatsApp).

Root causes:
1. scheduleChatScroll() was called without force flag in refreshActiveTab()
2. The scroll was targeting .chat-thread element which has overflow:visible
   and doesn't actually scroll - the window scrolls instead

Fixes:
- Pass force flag (!chatHasAutoScrolled) when loading chat tab
- Wait for Lit updateComplete before scrolling to ensure DOM is ready
- Scroll the window instead of the .chat-thread container
- Use behavior: 'instant' for immediate scroll without animation
2026-01-06 11:23:27 +05:30
Shadow 91cb2c02a7 fix: allow optional reply body 2026-01-05 23:47:33 -06:00
Shadow 4be6ec39dd docs: add recent contributors 2026-01-05 23:44:48 -06:00
Shadow 0204f45352 docs: add PR 272 changelog entry 2026-01-05 23:37:37 -06:00
Shadow 69f285c5ca chore: fixed CI 2026-01-05 23:36:48 -06:00
Ayaan Zaidi a79c100594 fix: targetDir symlink handling in postinstall script (#272) 2026-01-05 23:36:11 -06:00
Peter Steinberger b759cb6f37 feat(providers): normalize location parsing 2026-01-06 06:31:09 +01:00
Nacho Iacovino 255e77f530 feat(telegram): parse location and venue messages
- Add TelegramLocation, TelegramVenue, and TelegramMessageWithLocation types
- Add formatLocationMessage() to convert location/venue shares to text
- Add extractLocationData() for structured location access in ctxPayload
- Handle both raw location pins and venue shares (places with names)
- Include location in reply-to context for quoted messages

Location messages now appear as:
- [Location: lat, lon ±accuracy] for raw pins
- [Venue: Name - Address (lat, lon)] for places

ctxPayload includes LocationLat, LocationLon, LocationAccuracy,
VenueName, and VenueAddress fields for programmatic access.
2026-01-06 06:31:09 +01:00
Peter Steinberger 9ffea23f31 templates: Add memory maintenance during heartbeats
New section explaining how to periodically review daily memory files
and update MEMORY.md with distilled learnings. Like a human reviewing
their journal and updating their mental model.
2026-01-06 05:21:09 +00:00
Muhammed Mukhthar CM 18c7795ee0 feat: treat timeout as rate limit for profile rotation
Antigravity rate limits cause requests to hang indefinitely rather than
returning 429 errors. This change detects timeouts and treats them as
potential rate limits:

- Added timedOut flag to track timeout-triggered aborts
- Timeout now triggers profile cooldown + rotation
- Logs: "Profile X timed out (possible rate limit). Trying next account..."

This ensures automatic failover when Antigravity hangs due to rate limiting.
2026-01-06 05:20:01 +00:00
Iamadig 29a89ff9fa nano-banana: emit MEDIA token for generated images (#271) 2026-01-05 23:19:50 -06:00
Peter Steinberger 7d1fee70e7 templates: Add MEMORY.md long-term memory concept
- Updated session start to include MEMORY.md loading for main sessions
- Added 🧠 MEMORY.md section explaining:
  - Only load in main sessions (direct with human), not shared contexts
  - Security boundary: personal context shouldn't leak to strangers
  - Can freely read/edit/update in main sessions
  - Write significant events, thoughts, decisions, opinions
  - Curated memory vs raw daily logs

This gives new agents proper long-term memory that's secure and personal.
2026-01-06 05:19:24 +00:00
Muhammed Mukhthar CM ce6c7737c1 feat: add round-robin rotation and cooldown for auth profiles
Adds usage tracking to auth profiles for automatic rotation:

- ProfileUsageStats type with lastUsed, cooldownUntil, errorCount
- markAuthProfileUsed(): tracks successful usage, resets errors
- markAuthProfileCooldown(): applies exponential backoff (1/5/25/60min)
- isProfileInCooldown(): checks if profile should be skipped
- orderProfilesByMode(): now sorts by lastUsed (oldest first)

On auth/rate-limit failures, profiles are marked for cooldown before
rotation. On success, usage is recorded for round-robin ordering.

This enables automatic load distribution across multiple accounts
(e.g., Antigravity 5-hour rate limit windows).
2026-01-06 05:17:59 +00:00
Muhammed Mukhthar CM 06df6a955a feat: use email-based profile IDs for OAuth providers
Changes writeOAuthCredentials and applyAuthProfileConfig calls to use
the email from OAuth response as part of the profile ID instead of
hardcoded ":default".

This enables multiple accounts per provider - each login creates a
separate profile (e.g., google-antigravity:user@gmail.com) instead
of overwriting the same :default profile.

Affected files:
- src/commands/onboard-auth.ts (generic writeOAuthCredentials)
- src/commands/configure.ts (Antigravity flow)
- src/wizard/onboarding.ts (Antigravity flow)
2026-01-06 05:17:59 +00:00
Shadow 88cb13dc82 Auto-reply: fix typing stop race (#270) 2026-01-05 22:57:04 -06:00
Peter Steinberger 35a2140e48 fix: clean up poll merge 2026-01-06 04:51:05 +00:00
Peter SteinbergerandDBH 0b27964693 feat: unify poll support
Co-authored-by: DBH <5251425+dbhurley@users.noreply.github.com>
2026-01-06 04:51:05 +00:00
Sreekaran SrinathandShadow 1f4d9e83ff fix(ui): add anyOf/oneOf support in config form (#268)
* fix(ui): add anyOf/oneOf support in config form

- Handle literal unions as dropdowns with type preservation
- Handle primitive unions (string|number, boolean|string) as text inputs
- Unwrap single-variant optional types
- Fix enum handler to preserve types via index-based values
- Update normalizeUnion to support primitive unions in schema analysis
- Exclude allOf from union normalization (stays unsupported)

Fields like Thinking Default, Allow From, Memory now render properly
instead of showing 'unsupported schema node' errors.

* UI: fix enum placeholder collision

* Docs: update changelog for PR #268

---------

Co-authored-by: Shadow <hi@shadowing.dev>
2026-01-05 22:50:07 -06:00
AsleepandPeter Steinberger 8880128ebf Format messages so they work with Gemini API (#266)
* fix: Gemini stops working after one message in a session

* fix: small issue in test file

* test: cover google role-merge behavior

---------

Co-authored-by: Peter Steinberger <steipete@gmail.com>
2026-01-06 04:45:40 +00:00
DBH 2737e17c67 feat: Add WhatsApp poll support (#248)
Implements issue #123 - WhatsApp Poll Support

## Gateway Protocol
- Add `poll` RPC method with params: to, question, options (2-12), selectableCount

## ActiveWebListener
- Add `sendPoll(to, poll)` method to interface
- Implementation uses Baileys poll message type

## CLI Command
- `clawdbot poll --to <jid> -q <question> -o <opt1> -o <opt2> [-s count]`
- Supports --dry-run, --json, --verbose flags
- Validates 2-12 options

## Changes
- src/gateway/protocol/schema.ts: Add PollParamsSchema
- src/gateway/protocol/index.ts: Export validator and types
- src/web/active-listener.ts: Add sendPoll to interface
- src/web/inbound.ts: Implement sendPoll using Baileys
- src/web/outbound.ts: Add sendPollWhatsApp function
- src/gateway/server-methods/send.ts: Add poll handler
- src/commands/poll.ts: New CLI command
- src/cli/program.ts: Register poll command

Closes #123
2026-01-06 04:44:15 +00:00
Peter Steinberger ea6ee16461 chore: fix lint warnings 2026-01-06 05:41:24 +01:00
Peter Steinberger 77789cb9a8 fix: improve compaction queueing and oauth flows 2026-01-06 05:41:24 +01:00
9ab0b88ac6 feat(whatsapp,telegram): add groupPolicy config option (#216)
Co-authored-by: Marcus Neves <conhecendo.contato@gmail.com>
Co-authored-by: Shadow <hi@shadowing.dev>
2026-01-05 22:41:19 -06:00
Peter SteinbergerandKevin Kern f6d9d3ce67 docs: credit Kevin Kern for mention gating
Co-authored-by: Kevin Kern <hello@regenrek.at>
2026-01-06 04:22:02 +00:00
Peter Steinberger 53c9feb597 test: cover slack thread reply routing 2026-01-06 05:11:06 +01:00
Peter Steinberger e54865bbd2 Merge pull request #251 from scald/fix/slack-thread-replies
fix(slack): preserve thread context in auto-replies
2026-01-06 04:10:53 +00:00
Steve Caldwell 7034d4f807 fix(slack): preserve thread context in auto-replies
When replying to a message in a Slack thread, the response now stays
in the thread instead of going to the channel root.

Only threads replies when the incoming message was already in a thread
(has thread_ts). Top-level messages get top-level replies.

Fixes #250
2026-01-06 05:09:04 +01:00
Shadow 7b343f995c Changelog: add entries for PRs 220 and 261 2026-01-05 22:07:29 -06:00
Ayaan Zaidi bd735182b6 feat(telegram): support media groups (multi-image messages) (#220) 2026-01-05 22:04:33 -06:00
VACIncandVAC fb2513e265 fix(discord): Use channel ID for DMs instead of user ID (#261)
Co-authored-by: VAC <vac@vacs-mac-mini.localdomain>
2026-01-05 22:02:33 -06:00
Peter Steinberger 13eb9c9ee9 refactor: centralize reply dispatch 2026-01-06 04:55:00 +01:00
Peter Steinberger 319dd14e8e docs: clarify group allowlists in README 2026-01-06 04:47:41 +01:00
Peter Steinberger e14a0b3746 Merge pull request #265 from clawdbot/chore/pr-241-reopen
PR #241 reconciliation
2026-01-06 03:42:47 +00:00
Peter Steinberger 5946f4c341 test: extend typing idle coverage 2026-01-06 03:42:33 +00:00
Peter Steinberger 241a215528 chore: reconcile PR #241 2026-01-06 04:42:18 +01:00
kitze 97afd3a388 chore: credit @kitze for PR #241 2026-01-06 04:31:08 +01:00
Peter Steinberger 1a4f7d3388 feat: add ack reaction defaults 2026-01-06 03:28:47 +00:00
Peter Steinberger 58186aa56e test: cover typing idle gate 2026-01-06 03:28:47 +00:00
Peter Steinberger ca8f66f844 refactor: unify group allowlist policy 2026-01-06 04:27:51 +01:00
Ayaan Zaidi b1bb3ff6a6 feat: add reaction to acknowledge message in createTelegramBot 2026-01-06 03:21:56 +00:00
Peter Steinberger 9d656f4269 style: satisfy lint 2026-01-06 03:11:42 +00:00
Peter Steinberger d5f088978a fix: stop typing after dispatcher idle 2026-01-06 03:09:49 +00:00
Josh PalmerandPeter Steinberger cbc39bd005 use process PATH for bash tool (#202)
what: default bash PATH to process.env.PATH

why: ensure Nix-provided tools on PATH inside sessions

tests: not run

Co-authored-by: Peter Steinberger <steipete@gmail.com>
2026-01-06 03:05:21 +00:00
Peter Steinberger 070f7db196 docs: thank @joshp123 for PR #202 2026-01-06 04:04:42 +01:00
Peter Steinberger 20a361a3cf refactor: centralize agent timeout defaults 2026-01-06 02:48:44 +00:00
Martin Schürrerandclawd@msch d83ca74c18 gateway: honor agent timeout for chat.send (#229)
Co-authored-by: clawd@msch <clawd@msch>
2026-01-06 02:45:02 +00:00
Peter Steinberger 9b5610aa45 style: format telegram bot test 2026-01-06 03:43:05 +01:00
Peter Steinberger 92ff3311ee chore: remove unused patch file 2026-01-06 03:41:56 +01:00
Peter Steinberger 3211fee063 docs: note legacy patch file 2026-01-06 03:41:56 +01:00
Peter Steinberger c1698b6975 docs: add bun install support 2026-01-06 03:41:56 +01:00
Peter Steinberger 9623bd7763 fix: route agent CLI via gateway 2026-01-06 03:41:56 +01:00
Ayaan Zaidi e5e8ed4aef chore: credit PR #226 contribution 2026-01-06 02:40:29 +00:00
Peter Steinberger 77ac45b90e docs: update contributors 2026-01-06 02:33:27 +00:00
Peter Steinberger 0398f684e7 fix: add gateway stop/restart commands 2026-01-06 03:25:32 +01:00
183 changed files with 8446 additions and 1206 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
---
name: Bug report
about: Report a problem or unexpected behavior in Clawdbot.
title: "[Bug]: "
labels: bug
---
## Summary
What went wrong?
## Steps to reproduce
1.
2.
3.
## Expected behavior
What did you expect to happen?
## Actual behavior
What actually happened?
## Environment
- Clawdbot version:
- OS:
- Install method (pnpm/npx/docker/etc):
## Logs or screenshots
Paste relevant logs or add screenshots (redact secrets).
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: Onboarding
url: https://discord.gg/clawd
about: New to Clawdbot? Join Discord for setup guidance from Krill in #help.
- name: Support
url: https://discord.gg/clawd
about: Get help from Krill and the community on Discord in #help.
+18
View File
@@ -0,0 +1,18 @@
---
name: Feature request
about: Suggest an idea or improvement for Clawdbot.
title: "[Feature]: "
labels: enhancement
---
## Summary
Describe the problem you are trying to solve or the opportunity you see.
## Proposed solution
What would you like Clawdbot to do?
## Alternatives considered
Any other approaches you have considered?
## Additional context
Links, screenshots, or related issues.
+2 -13
View File
@@ -52,32 +52,21 @@ jobs:
exit 1
- name: Setup Node.js
if: matrix.runtime == 'node'
uses: actions/setup-node@v4
with:
node-version: 24
check-latest: true
- name: Setup Bun
if: matrix.runtime == 'bun'
uses: oven-sh/setup-bun@v2
with:
# bun.sh downloads currently fail with:
# "Failed to list releases from GitHub: 401" -> "Unexpected HTTP response: 400"
bun-download-url: "https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64.zip"
- name: Setup Node.js (tooling for bun)
if: matrix.runtime == 'bun'
uses: actions/setup-node@v4
with:
node-version: 24
check-latest: true
bun-version: latest
- name: Runtime versions
run: |
node -v
npm -v
if [ "${{ matrix.runtime }}" = "bun" ]; then bun -v; fi
bun -v
- name: Capture node path
run: echo "NODE_BIN=$(dirname \"$(node -p \"process.execPath\")\")" >> "$GITHUB_ENV"
+2
View File
@@ -3,6 +3,8 @@ node_modules
dist
*.bun-build
pnpm-lock.yaml
bun.lock
bun.lockb
coverage
.pnpm-store
.worktrees/
+7 -1
View File
@@ -7,7 +7,9 @@
## Build, Test, and Development Commands
- Install deps: `pnpm install`
- Run CLI in dev: `pnpm clawdbot ...` (tsx entry) or `pnpm dev` for `src/index.ts`.
- Prefer Bun for TypeScript execution (scripts, dev, tests): `bun <file.ts>` / `bunx <tool>`.
- Run CLI in dev: `pnpm clawdbot ...` (bun) or `pnpm dev`.
- Node remains supported for running built output (`dist/*`) and production installs.
- Type-check/build: `pnpm build` (tsc)
- Lint/format: `pnpm lint` (biome check), `pnpm format` (biome format)
- Tests: `pnpm test` (vitest); coverage: `pnpm test:coverage`
@@ -30,6 +32,10 @@
- Follow concise, action-oriented commit messages (e.g., `CLI: add verbose flag to send`).
- Group related changes; avoid bundling unrelated refactors.
- PRs should summarize scope, note testing performed, and mention any user-facing changes or new flags.
- When working on a PR: add a changelog entry with the PR ID and thank the contributor.
- When working on an issue: reference the issue in the changelog entry.
- When merging a PR: leave a PR comment that explains exactly what we did.
- When merging a PR from a new contributor: add their avatar to the README “Thanks to all clawtributors” thumbnail list.
## Security & Configuration Tips
- Web provider stores creds at `~/.clawdbot/credentials/`; rerun `clawdbot login` if logged out.
+45 -3
View File
@@ -8,11 +8,30 @@
- Timestamps in agent envelopes are now UTC (compact `YYYY-MM-DDTHH:mmZ`); removed `messages.timestampPrefix`. Add `agent.userTimezone` to tell the model the user’s local time (system prompt only).
- Model config schema changes (auth profiles + model lists); doctor auto-migrates and the gateway rewrites legacy configs on startup.
- Commands: gate all slash commands to authorized senders; add `/compact` to manually compact session context.
- Groups: `whatsapp.groups`, `telegram.groups`, and `imessage.groups` now act as allowlists when set. Add `"*"` to keep allow-all behavior.
### Fixes
- Messages: stop defaulting ack reactions to 👀 when identity emoji is missing.
- Auto-reply: require slash for control commands to avoid false triggers in normal text.
- Auto-reply: treat steer during compaction as a follow-up, queued until compaction completes.
- Auth: lock auth profile refreshes to avoid multi-instance OAuth logouts; keep credentials on refresh failure.
- Onboarding: prompt immediately for OpenAI Codex redirect URL on remote/headless logins.
- Configure: add OpenAI Codex (ChatGPT OAuth) auth choice (align with onboarding).
- Doctor: suggest adding the workspace memory system when missing (opt-out via `--no-workspace-suggestions`).
- Build: fix duplicate protocol export, align Codex OAuth options, and add proper-lockfile typings.
- Build: install Bun in the Dockerfile so `pnpm build` can run Bun scripts. Thanks @loukotal for PR #284.
- Typing indicators: stop typing once the reply dispatcher drains to prevent stuck typing across Discord/Telegram/WhatsApp.
- Typing indicators: fix a race that could keep the typing indicator stuck after quick replies. Thanks @thewilloftheshadow for PR #270.
- Google: merge consecutive messages to satisfy strict role alternation for Google provider models. Thanks @Asleep123 for PR #266.
- Postinstall: handle targetDir symlinks in the install script. Thanks @obviyus for PR #272.
- WhatsApp/Telegram: add groupPolicy handling for group messages and normalize allowFrom matching (tg/telegram prefixes). Thanks @mneves75.
- Auto-reply: add configurable ack reactions for inbound messages (default 👀 or `identity.emoji`) with scope controls. Thanks @obviyus for PR #178.
- Polls: unify WhatsApp + Discord poll sends via the gateway + CLI (`clawdbot poll`). (#123) — thanks @dbhurley
- Onboarding: resolve CLI entrypoint when running via `npx` so gateway daemon install works without a build step.
- Onboarding: when OpenAI Codex OAuth is used, default to `openai-codex/gpt-5.2` and warn if the selected model lacks auth.
- CLI: auto-migrate legacy config entries on command start (same behavior as gateway startup).
- Gateway: add `gateway stop|restart` helpers and surface launchd/systemd/schtasks stop hints when the gateway is already running.
- Gateway: honor `agent.timeoutSeconds` for `chat.send` and share timeout defaults across chat/cron/auto-reply. Thanks @MSch for PR #229.
- Auth: prioritize OAuth profiles but fall back to API keys when refresh fails; stored profiles now load without explicit auth order.
- Control UI: harden config Form view with schema normalization, map editing, and guardrails to prevent data loss on save.
- Cron: normalize cron.add/update inputs, align channel enums/status fields across gateway/CLI/UI/macOS, and add protocol conformance tests. Thanks @mneves75 for PR #256.
@@ -20,6 +39,7 @@
- Gmail: stop restart loop when `gog gmail watch serve` fails to bind (address already in use).
- Linux: auto-attempt lingering during onboarding (try without sudo, fallback to sudo) and prompt on install/restart to keep the gateway alive after logout/idle. Thanks @tobiasbischoff for PR #237.
- TUI: migrate key handling to the updated pi-tui Key matcher API.
- TUI: add `/elev` alias for `/elevated`.
- Logging: redact sensitive tokens in verbose tool summaries by default (configurable patterns).
- macOS: prefer gateway config reads/writes in local mode (fall back to disk if the gateway is unavailable).
- macOS: local gateway now connects via tailnet IP when bind mode is `tailnet`/`auto`.
@@ -33,31 +53,47 @@
- Auth: when `openai` has no API key but Codex OAuth exists, suggest `openai-codex/gpt-5.2` vs `OPENAI_API_KEY`.
- Docs: clarify auth storage, migration, and OpenAI Codex OAuth onboarding.
- Sandbox: copy inbound media into sandbox workspaces so agent tools can read attachments.
- Sandbox: enable session tools in sandboxed sessions with spawned-only visibility by default (opt-in `agent.sandbox.sessionToolsVisibility = "all"`).
- Control UI: show a reading indicator bubble while the assistant is responding.
- Control UI: animate reading indicator dots (honors reduced-motion).
- Control UI: stabilize chat streaming during tool runs (no flicker/vanishing text; correct run scoping).
- Control UI: let config-form enums select empty-string values. Thanks @sreekaransrinath for PR #268.
- Control UI: scroll chat to bottom on initial load. Thanks @kiranjd for PR #274.
- Control UI: add Chat focus mode toggle to collapse header + sidebar.
- Control UI: standardize UI build instructions on `bun run ui:*` (fallback supported).
- Status: show runtime (docker/direct) and move shortcuts to `/help`.
- Status: show model auth source (api-key/oauth).
- Block streaming: avoid splitting Markdown fenced blocks and reopen fences when forced to split.
- Block streaming: preserve leading indentation in block replies (lists, indented fences).
- Docs: document systemd lingering and logged-in session requirements on macOS/Windows.
- Auto-reply: unify tool/block/final delivery across providers and apply consistent heartbeat/prefix handling. Thanks @MSch for PR #225 (superseded commit 92c953d0749143eb2a3f31f3cd6ad0e8eabf48c3).
- Auto-reply: centralize tool/block/final dispatch across providers for consistent streaming + heartbeat/prefix handling. Thanks @MSch for PR #225.
- Heartbeat: make HEARTBEAT_OK ack padding configurable across heartbeat and cron delivery. (#238) — thanks @jalehman
- Skills: emit MEDIA token after Nano Banana Pro image generation. Thanks @Iamadig for PR #271.
- WhatsApp: set sender E.164 for direct chats so owner commands work in DMs.
- Slack: keep auto-replies in the original thread when responding to thread messages. Thanks @scald for PR #251.
- Discord: surface missing-permission hints (muted/role overrides) when replies fail.
- Discord: use channel IDs for DMs instead of user IDs. Thanks @VACInc for PR #261.
- Docs: clarify Slack manifest scopes (current vs optional) with references. Thanks @jarvis-medmatic for PR #235.
- Control UI: avoid Slack config ReferenceError by reading slack config snapshots. Thanks @sreekaransrinath for PR #249.
- Telegram: honor routing.groupChat.mentionPatterns for group mention gating. Thanks @regenrek for PR #242.
- Auth: rotate across multiple OAuth profiles with cooldown tracking and email-based profile IDs. Thanks @mukhtharcm for PR #269.
- Auth: fix multi-account OAuth rotation so round-robin alternates instead of pinning to lastGood. Thanks @mukhtharcm for PR #281.
- Configure: stop auto-writing `auth.order` for newly added auth profiles (round-robin default unless explicitly pinned).
- Telegram: honor routing.groupChat.mentionPatterns for group mention gating. Thanks Kevin Kern (@regenrek) for PR #242.
- Telegram: gate groups via `telegram.groups` allowlist (align with WhatsApp/iMessage). Thanks @kitze for PR #241.
- Telegram: support media groups (multi-image messages). Thanks @obviyus for PR #220.
- Telegram/WhatsApp: parse shared locations (pins, places, live) and expose structured ctx fields. Thanks @nachoiacovino for PR #194.
- Auto-reply: block unauthorized `/reset` and infer WhatsApp senders from E.164 inputs.
- Auto-reply: track compaction count in session status; verbose mode announces auto-compactions.
- Telegram: send GIF media as animations (auto-play) and improve filename sniffing.
- Bash tool: inherit gateway PATH so Nix-provided tools resolve during commands. Thanks @joshp123 for PR #202.
### Maintenance
- Tooling: replace tsx with bun for TypeScript execution. Thanks @obviyus for PR #278.
- Deps: bump pi-* stack, Slack SDK, discord-api-types, file-type, zod, and Biome.
- Skills: add CodexBar model usage helper with macOS requirement metadata.
- Skills: add 1Password CLI skill with op examples.
- Lint: organize imports and wrap long lines in reply commands.
- Refactor: centralize group allowlist/mention policy across providers.
- Deps: update to latest across the repo.
## 2026.1.5-3
@@ -84,6 +120,7 @@
- Agent tools: new `image` tool routed to the image model (when configured).
- Config: default model shorthands (`opus`, `sonnet`, `gpt`, `gpt-mini`, `gemini`, `gemini-flash`).
- Docs: document built-in model shorthands + precedence (user config wins).
- Bun: optional local install/build workflow without maintaining a Bun lockfile (see `docs/bun.md`).
### Fixes
- Control UI: render Markdown in tool result cards.
@@ -102,11 +139,16 @@
- Env: load global `$CLAWDBOT_STATE_DIR/.env` (`~/.clawdbot/.env`) as a fallback after CWD `.env`.
- Env: optional login-shell env fallback (opt-in; imports expected keys without overriding existing env).
- Agent tools: OpenAI-compatible tool JSON Schemas (fix `browser`, normalize union schemas).
- Onboarding: when running from source, auto-build missing Control UI assets (`pnpm ui:build`).
- Onboarding: when running from source, auto-build missing Control UI assets (`bun run ui:build`).
- Discord/Slack: route reaction + system notifications to the correct session (no main-session bleed).
- Agent tools: honor `agent.tools` allow/deny policy even when sandbox is off.
- Discord: avoid duplicate replies when OpenAI emits repeated `message_end` events.
- Commands: unify /status (inline) and command auth across providers; group bypass for authorized control commands; remove Discord /clawd slash handler.
- CLI: run `clawdbot agent` via the Gateway by default; use `--local` to force embedded mode.
## 2026.1.5
### Fixes
- Control UI: render Markdown in chat messages (sanitized).
+4
View File
@@ -1,5 +1,9 @@
FROM node:22-bookworm
# Install Bun (required for build scripts)
RUN curl -fsSL https://bun.sh/install | bash
ENV PATH="/root/.bun/bin:${PATH}"
RUN corepack enable
WORKDIR /app
+123 -111
View File
@@ -20,7 +20,7 @@ It answers you on the surfaces you already use (WhatsApp, Telegram, Slack, Disco
If you want a personal, single-user assistant that feels local, fast, and always-on, this is it.
Website: [https://clawdbot.com](https://clawdbot.com) · Docs: [https://docs.clawdbot.com](https://docs.clawdbot.com/) · Showcase: [https://docs.clawdbot.com/showcase](https://docs.clawdbot.com/showcase) · FAQ: [https://docs.clawdbot.com/faq](https://docs.clawdbot.com/faq) · Wizard: [https://docs.clawdbot.com/wizard](https://docs.clawdbot.com/wizard) · Nix: [https://github.com/clawdbot/nix-clawdbot](https://github.com/clawdbot/nix-clawdbot) · Docker: [https://docs.clawdbot.com/docker](https://docs.clawdbot.com/docker) · Discord: [https://discord.gg/clawd](https://discord.gg/clawd)
[Website](https://clawdbot.com) · [Docs](https://github.com/clawdbot/clawdbot/blob/main/docs/index.md) · Showcase: [https://github.com/clawdbot/clawdbot/blob/main/docs/showcase.md](https://github.com/clawdbot/clawdbot/blob/main/docs/showcase.md) · FAQ: [https://github.com/clawdbot/clawdbot/blob/main/docs/faq.md](https://github.com/clawdbot/clawdbot/blob/main/docs/faq.md) · Wizard: [https://github.com/clawdbot/clawdbot/blob/main/docs/wizard.md](https://github.com/clawdbot/clawdbot/blob/main/docs/wizard.md) · Nix: [https://github.com/clawdbot/nix-clawdbot](https://github.com/clawdbot/nix-clawdbot) · Docker: [https://github.com/clawdbot/clawdbot/blob/main/docs/docker.md](https://github.com/clawdbot/clawdbot/blob/main/docs/docker.md) · Discord: [https://discord.gg/clawd](https://discord.gg/clawd)
Preferred setup: run the onboarding wizard (`clawdbot onboard`). It walks through gateway, workspace, providers, and skills. The CLI wizard is the recommended path and works on **macOS, Windows, and Linux**.
Works with npm, pnpm, or bun.
@@ -29,7 +29,7 @@ Works with npm, pnpm, or bun.
- **Anthropic** (Claude Pro/Max)
- **OpenAI** (ChatGPT/Codex)
Model note: while any model is supported, I strongly recommend **Anthropic Pro/Max (100/200) + Opus 4.5** for long‑context strength and better prompt‑injection resistance. See [Onboarding](https://docs.clawdbot.com/onboarding).
Model note: while any model is supported, I strongly recommend **Anthropic Pro/Max (100/200) + Opus 4.5** for long‑context strength and better prompt‑injection resistance. See [Onboarding](https://github.com/clawdbot/clawdbot/blob/main/docs/onboarding.md).
## Recommended setup (from source)
@@ -40,85 +40,93 @@ Do **not** download prebuilt binaries. Build from source.
git clone https://github.com/clawdbot/clawdbot.git
cd clawdbot
pnpm install
pnpm build
pnpm ui:build
pnpm clawdbot onboard
bun install
bun run build
bun run ui:build
bun run clawdbot onboard
```
## Quick start (from source)
Runtime: **Node ≥22** + **pnpm**.
Runtime: **Node ≥22**.
From source, **pnpm** is the default workflow. Bun is supported as an optional local workflow; see [`docs/bun.md`](docs/bun.md).
```bash
pnpm install
pnpm build
pnpm ui:build
# Install deps (no Bun lockfile)
bun install --no-save
# Build TypeScript
bun run build
# Build Control UI
bun install --cwd ui --no-save
bun run --cwd ui build
# Recommended: run the onboarding wizard
pnpm clawdbot onboard
bun run clawdbot onboard
# Link WhatsApp (stores creds in ~/.clawdbot/credentials)
pnpm clawdbot login
bun run clawdbot login
# Start the gateway
pnpm clawdbot gateway --port 18789 --verbose
bun run clawdbot gateway --port 18789 --verbose
# Dev loop (auto-reload on TS changes)
pnpm gateway:watch
bun run gateway:watch
# Send a message
pnpm clawdbot send --to +1234567890 --message "Hello from Clawdbot"
bun run clawdbot send --to +1234567890 --message "Hello from Clawdbot"
# Talk to the assistant (optionally deliver back to WhatsApp/Telegram/Slack/Discord)
pnpm clawdbot agent --message "Ship checklist" --thinking high
bun run clawdbot agent --message "Ship checklist" --thinking high
```
Upgrading? `clawdbot doctor`.
If you run from source, prefer `pnpm clawdbot …` (not global `clawdbot`).
If you run from source, prefer `bun run clawdbot …` or `pnpm clawdbot …` (not global `clawdbot`).
## Highlights
- **[Local-first Gateway](https://docs.clawdbot.com/gateway)** — single control plane for sessions, providers, tools, and events.
- **[Multi-surface inbox](https://docs.clawdbot.com/surface)** — WhatsApp, Telegram, Slack, Discord, Signal, iMessage, WebChat, macOS, iOS/Android.
- **[Voice Wake](https://docs.clawdbot.com/voicewake) + [Talk Mode](https://docs.clawdbot.com/talk)** — always-on speech for macOS/iOS/Android with ElevenLabs.
- **[Live Canvas](https://docs.clawdbot.com/mac/canvas)** — agent-driven visual workspace with [A2UI](https://docs.clawdbot.com/refactor/canvas-a2ui).
- **[First-class tools](https://docs.clawdbot.com/tools)** — browser, canvas, nodes, cron, sessions, and Discord/Slack actions.
- **[Companion apps](https://docs.clawdbot.com/macos)** — macOS menu bar app + iOS/Android [nodes](https://docs.clawdbot.com/nodes).
- **[Onboarding](https://docs.clawdbot.com/wizard) + [skills](https://docs.clawdbot.com/skills)** — wizard-driven setup with bundled/managed/workspace skills.
- **[Local-first Gateway](https://github.com/clawdbot/clawdbot/blob/main/docs/gateway.md)** — single control plane for sessions, providers, tools, and events.
- **[Multi-surface inbox](https://github.com/clawdbot/clawdbot/blob/main/docs/surface.md)** — WhatsApp, Telegram, Slack, Discord, Signal, iMessage, WebChat, macOS, iOS/Android.
- **[Voice Wake](https://github.com/clawdbot/clawdbot/blob/main/docs/voicewake.md) + [Talk Mode](https://github.com/clawdbot/clawdbot/blob/main/docs/talk.md)** — always-on speech for macOS/iOS/Android with ElevenLabs.
- **[Live Canvas](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md)** — agent-driven visual workspace with [A2UI](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md#canvas-a2ui).
- **[First-class tools](https://github.com/clawdbot/clawdbot/blob/main/docs/tools.md)** — browser, canvas, nodes, cron, sessions, and Discord/Slack actions.
- **[Companion apps](https://github.com/clawdbot/clawdbot/blob/main/docs/macos.md)** — macOS menu bar app + iOS/Android [nodes](https://github.com/clawdbot/clawdbot/blob/main/docs/nodes.md).
- **[Onboarding](https://github.com/clawdbot/clawdbot/blob/main/docs/wizard.md) + [skills](https://github.com/clawdbot/clawdbot/blob/main/docs/skills.md)** — wizard-driven setup with bundled/managed/workspace skills.
## Everything we built so far
### Core platform
- [Gateway WS control plane](https://docs.clawdbot.com/gateway) with sessions, presence, config, cron, webhooks, [Control UI](https://docs.clawdbot.com/web), and [Canvas host](https://docs.clawdbot.com/refactor/canvas-a2ui).
- [CLI surface](https://docs.clawdbot.com/agent-send): gateway, agent, send, [wizard](https://docs.clawdbot.com/wizard), and [doctor](https://docs.clawdbot.com/doctor).
- [Pi agent runtime](https://docs.clawdbot.com/agent) in RPC mode with tool streaming and block streaming.
- [Session model](https://docs.clawdbot.com/session): `main` for direct chats, group isolation, activation modes, queue modes, reply-back. Group rules: [Groups](https://docs.clawdbot.com/groups).
- [Media pipeline](https://docs.clawdbot.com/images): images/audio/video, transcription hooks, size caps, temp file lifecycle. Audio details: [Audio](https://docs.clawdbot.com/audio).
- [Gateway WS control plane](https://github.com/clawdbot/clawdbot/blob/main/docs/gateway.md) with sessions, presence, config, cron, webhooks, [Control UI](https://github.com/clawdbot/clawdbot/blob/main/docs/web.md), and [Canvas host](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md#canvas-a2ui).
- [CLI surface](https://github.com/clawdbot/clawdbot/blob/main/docs/agent-send.md): gateway, agent, send, [wizard](https://github.com/clawdbot/clawdbot/blob/main/docs/wizard.md), and [doctor](https://github.com/clawdbot/clawdbot/blob/main/docs/doctor.md).
- [Pi agent runtime](https://github.com/clawdbot/clawdbot/blob/main/docs/agent.md) in RPC mode with tool streaming and block streaming.
- [Session model](https://github.com/clawdbot/clawdbot/blob/main/docs/session.md): `main` for direct chats, group isolation, activation modes, queue modes, reply-back. Group rules: [Groups](https://github.com/clawdbot/clawdbot/blob/main/docs/groups.md).
- [Media pipeline](https://github.com/clawdbot/clawdbot/blob/main/docs/images.md): images/audio/video, transcription hooks, size caps, temp file lifecycle. Audio details: [Audio](https://github.com/clawdbot/clawdbot/blob/main/docs/audio.md).
### Surfaces + providers
- [Providers](https://docs.clawdbot.com/surface): [WhatsApp](https://docs.clawdbot.com/whatsapp) (Baileys), [Telegram](https://docs.clawdbot.com/telegram) (grammY), [Slack](https://docs.clawdbot.com/slack) (Bolt), [Discord](https://docs.clawdbot.com/discord) (discord.js), [Signal](https://docs.clawdbot.com/signal) (signal-cli), [iMessage](https://docs.clawdbot.com/imessage) (imsg), [WebChat](https://docs.clawdbot.com/webchat).
- [Group routing](https://docs.clawdbot.com/group-messages): mention gating, reply tags, per-surface chunking and routing. Surface rules: [Surface routing](https://docs.clawdbot.com/surface).
- [Providers](https://github.com/clawdbot/clawdbot/blob/main/docs/surface.md): [WhatsApp](https://github.com/clawdbot/clawdbot/blob/main/docs/whatsapp.md) (Baileys), [Telegram](https://github.com/clawdbot/clawdbot/blob/main/docs/telegram.md) (grammY), [Slack](https://github.com/clawdbot/clawdbot/blob/main/docs/slack.md) (Bolt), [Discord](https://github.com/clawdbot/clawdbot/blob/main/docs/discord.md) (discord.js), [Signal](https://github.com/clawdbot/clawdbot/blob/main/docs/signal.md) (signal-cli), [iMessage](https://github.com/clawdbot/clawdbot/blob/main/docs/imessage.md) (imsg), [WebChat](https://github.com/clawdbot/clawdbot/blob/main/docs/webchat.md).
- [Group routing](https://github.com/clawdbot/clawdbot/blob/main/docs/group-messages.md): mention gating, reply tags, per-surface chunking and routing. Surface rules: [Surface routing](https://github.com/clawdbot/clawdbot/blob/main/docs/surface.md).
### Apps + nodes
- [macOS app](https://docs.clawdbot.com/macos): menu bar control plane, [Voice Wake](https://docs.clawdbot.com/voicewake)/PTT, [Talk Mode](https://docs.clawdbot.com/talk) overlay, [WebChat](https://docs.clawdbot.com/webchat), debug tools, [remote gateway](https://docs.clawdbot.com/remote) control.
- [iOS node](https://docs.clawdbot.com/ios): [Canvas](https://docs.clawdbot.com/mac/canvas), [Voice Wake](https://docs.clawdbot.com/voicewake), [Talk Mode](https://docs.clawdbot.com/talk), camera, screen recording, Bonjour pairing.
- [Android node](https://docs.clawdbot.com/android): [Canvas](https://docs.clawdbot.com/mac/canvas), [Talk Mode](https://docs.clawdbot.com/talk), camera, screen recording, optional SMS.
- [macOS node mode](https://docs.clawdbot.com/nodes): system.run/notify + canvas/camera exposure.
- [macOS app](https://github.com/clawdbot/clawdbot/blob/main/docs/macos.md): menu bar control plane, [Voice Wake](https://github.com/clawdbot/clawdbot/blob/main/docs/voicewake.md)/PTT, [Talk Mode](https://github.com/clawdbot/clawdbot/blob/main/docs/talk.md) overlay, [WebChat](https://github.com/clawdbot/clawdbot/blob/main/docs/webchat.md), debug tools, [remote gateway](https://github.com/clawdbot/clawdbot/blob/main/docs/remote.md) control.
- [iOS node](https://github.com/clawdbot/clawdbot/blob/main/docs/ios.md): [Canvas](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md), [Voice Wake](https://github.com/clawdbot/clawdbot/blob/main/docs/voicewake.md), [Talk Mode](https://github.com/clawdbot/clawdbot/blob/main/docs/talk.md), camera, screen recording, Bonjour pairing.
- [Android node](https://github.com/clawdbot/clawdbot/blob/main/docs/android.md): [Canvas](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md), [Talk Mode](https://github.com/clawdbot/clawdbot/blob/main/docs/talk.md), camera, screen recording, optional SMS.
- [macOS node mode](https://github.com/clawdbot/clawdbot/blob/main/docs/nodes.md): system.run/notify + canvas/camera exposure.
### Tools + automation
- [Browser control](https://docs.clawdbot.com/browser): dedicated clawd Chrome/Chromium, snapshots, actions, uploads, profiles.
- [Canvas](https://docs.clawdbot.com/mac/canvas): [A2UI](https://docs.clawdbot.com/refactor/canvas-a2ui) push/reset, eval, snapshot.
- [Nodes](https://docs.clawdbot.com/nodes): camera snap/clip, screen record, [location.get](https://docs.clawdbot.com/location-command), notifications.
- [Cron + wakeups](https://docs.clawdbot.com/cron); [webhooks](https://docs.clawdbot.com/webhook); [Gmail Pub/Sub](https://docs.clawdbot.com/gmail-pubsub).
- [Skills platform](https://docs.clawdbot.com/skills): bundled, managed, and workspace skills with install gating + UI.
- [Browser control](https://github.com/clawdbot/clawdbot/blob/main/docs/browser.md): dedicated clawd Chrome/Chromium, snapshots, actions, uploads, profiles.
- [Canvas](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md): [A2UI](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md#canvas-a2ui) push/reset, eval, snapshot.
- [Nodes](https://github.com/clawdbot/clawdbot/blob/main/docs/nodes.md): camera snap/clip, screen record, [location.get](https://github.com/clawdbot/clawdbot/blob/main/docs/location-command.md), notifications.
- [Cron + wakeups](https://github.com/clawdbot/clawdbot/blob/main/docs/cron.md); [webhooks](https://github.com/clawdbot/clawdbot/blob/main/docs/webhook.md); [Gmail Pub/Sub](https://github.com/clawdbot/clawdbot/blob/main/docs/gmail-pubsub.md).
- [Skills platform](https://github.com/clawdbot/clawdbot/blob/main/docs/skills.md): bundled, managed, and workspace skills with install gating + UI.
### Ops + packaging
- [Control UI](https://docs.clawdbot.com/web) + [WebChat](https://docs.clawdbot.com/webchat) served directly from the Gateway.
- [Tailscale Serve/Funnel](https://docs.clawdbot.com/tailscale) or [SSH tunnels](https://docs.clawdbot.com/remote) with token/password auth.
- [Nix mode](https://docs.clawdbot.com/nix) for declarative config; [Docker](https://docs.clawdbot.com/docker)-based installs.
- [Doctor](https://docs.clawdbot.com/doctor) migrations, [logging](https://docs.clawdbot.com/logging).
- [Control UI](https://github.com/clawdbot/clawdbot/blob/main/docs/web.md) + [WebChat](https://github.com/clawdbot/clawdbot/blob/main/docs/webchat.md) served directly from the Gateway.
- [Tailscale Serve/Funnel](https://github.com/clawdbot/clawdbot/blob/main/docs/tailscale.md) or [SSH tunnels](https://github.com/clawdbot/clawdbot/blob/main/docs/remote.md) with token/password auth.
- [Nix mode](https://github.com/clawdbot/clawdbot/blob/main/docs/nix.md) for declarative config; [Docker](https://github.com/clawdbot/clawdbot/blob/main/docs/docker.md)-based installs.
- [Doctor](https://github.com/clawdbot/clawdbot/blob/main/docs/doctor.md) migrations, [logging](https://github.com/clawdbot/clawdbot/blob/main/docs/logging.md).
## How it works (short)
@@ -140,12 +148,12 @@ WhatsApp / Telegram / Slack / Discord / Signal / iMessage / WebChat
## Key subsystems
- **[Gateway WebSocket network](https://docs.clawdbot.com/architecture)** — single WS control plane for clients, tools, and events (plus ops: [Gateway runbook](https://docs.clawdbot.com/gateway)).
- **[Tailscale exposure](https://docs.clawdbot.com/tailscale)** — Serve/Funnel for the Gateway dashboard + WS (remote access: [Remote](https://docs.clawdbot.com/remote)).
- **[Browser control](https://docs.clawdbot.com/browser)** — clawd‑managed Chrome/Chromium with CDP control.
- **[Canvas + A2UI](https://docs.clawdbot.com/mac/canvas)** — agent‑driven visual workspace (A2UI host: [Canvas/A2UI](https://docs.clawdbot.com/refactor/canvas-a2ui)).
- **[Voice Wake](https://docs.clawdbot.com/voicewake) + [Talk Mode](https://docs.clawdbot.com/talk)** — always‑on speech and continuous conversation.
- **[Nodes](https://docs.clawdbot.com/nodes)** — Canvas, camera snap/clip, screen record, `location.get`, notifications, plus macOS‑only `system.run`/`system.notify`.
- **[Gateway WebSocket network](https://github.com/clawdbot/clawdbot/blob/main/docs/architecture.md)** — single WS control plane for clients, tools, and events (plus ops: [Gateway runbook](https://github.com/clawdbot/clawdbot/blob/main/docs/gateway.md)).
- **[Tailscale exposure](https://github.com/clawdbot/clawdbot/blob/main/docs/tailscale.md)** — Serve/Funnel for the Gateway dashboard + WS (remote access: [Remote](https://github.com/clawdbot/clawdbot/blob/main/docs/remote.md)).
- **[Browser control](https://github.com/clawdbot/clawdbot/blob/main/docs/browser.md)** — clawd‑managed Chrome/Chromium with CDP control.
- **[Canvas + A2UI](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md)** — agent‑driven visual workspace (A2UI host: [Canvas/A2UI](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/canvas.md#canvas-a2ui)).
- **[Voice Wake](https://github.com/clawdbot/clawdbot/blob/main/docs/voicewake.md) + [Talk Mode](https://github.com/clawdbot/clawdbot/blob/main/docs/talk.md)** — always‑on speech and continuous conversation.
- **[Nodes](https://github.com/clawdbot/clawdbot/blob/main/docs/nodes.md)** — Canvas, camera snap/clip, screen record, `location.get`, notifications, plus macOS‑only `system.run`/`system.notify`.
## Tailscale access (Gateway dashboard)
@@ -161,7 +169,7 @@ Notes:
- Funnel refuses to start unless `gateway.auth.mode: "password"` is set.
- Optional: `gateway.tailscale.resetOnExit` to undo Serve/Funnel on shutdown.
Details: [Tailscale guide](https://docs.clawdbot.com/tailscale) · [Web surfaces](https://docs.clawdbot.com/web)
Details: [Tailscale guide](https://github.com/clawdbot/clawdbot/blob/main/docs/tailscale.md) · [Web surfaces](https://github.com/clawdbot/clawdbot/blob/main/docs/web.md)
## Remote Gateway (Linux is great)
@@ -171,7 +179,7 @@ It’s perfectly fine to run the Gateway on a small Linux instance. Clients (mac
- **Device nodes** run device‑local actions (`system.run`, camera, screen recording, notifications) via `node.invoke`.
In short: bash runs where the Gateway lives; device actions run where the device lives.
Details: [Remote access](https://docs.clawdbot.com/remote) · [Nodes](https://docs.clawdbot.com/nodes) · [Security](https://docs.clawdbot.com/security)
Details: [Remote access](https://github.com/clawdbot/clawdbot/blob/main/docs/remote.md) · [Nodes](https://github.com/clawdbot/clawdbot/blob/main/docs/nodes.md) · [Security](https://github.com/clawdbot/clawdbot/blob/main/docs/security.md)
## macOS permissions via the Gateway protocol
@@ -186,7 +194,7 @@ Elevated bash (host permissions) is separate from macOS TCC:
- Use `/elevated on|off` to toggle per‑session elevated access when enabled + allowlisted.
- Gateway persists the per‑session toggle via `sessions.patch` (WS method) alongside `thinkingLevel`, `verboseLevel`, `model`, `sendPolicy`, and `groupActivation`.
Details: [Nodes](https://docs.clawdbot.com/nodes) · [macOS app](https://docs.clawdbot.com/macos) · [Gateway protocol](https://docs.clawdbot.com/architecture)
Details: [Nodes](https://github.com/clawdbot/clawdbot/blob/main/docs/nodes.md) · [macOS app](https://github.com/clawdbot/clawdbot/blob/main/docs/macos.md) · [Gateway protocol](https://github.com/clawdbot/clawdbot/blob/main/docs/architecture.md)
## Agent to Agent (sessions_* tools)
@@ -195,7 +203,7 @@ Details: [Nodes](https://docs.clawdbot.com/nodes) · [macOS app](https://docs.cl
- `sessions_history` — fetch transcript logs for a session.
- `sessions_send` — message another session; optional reply‑back ping‑pong + announce step (`REPLY_SKIP`, `ANNOUNCE_SKIP`).
Details: [Session tools](https://docs.clawdbot.com/session-tool)
Details: [Session tools](https://github.com/clawdbot/clawdbot/blob/main/docs/session-tool.md)
## Skills registry (ClawdHub)
@@ -241,13 +249,13 @@ Note: signed builds required for macOS permissions to stick across rebuilds (see
- Voice trigger forwarding + Canvas surface.
- Controlled via `clawdbot nodes …`.
Runbook: [iOS connect](https://docs.clawdbot.com/ios).
Runbook: [iOS connect](https://github.com/clawdbot/clawdbot/blob/main/docs/ios.md).
### Android node (optional)
- Pairs via the same Bridge + pairing flow as iOS.
- Exposes Canvas, Camera, and Screen capture commands.
- Runbook: [Android connect](https://docs.clawdbot.com/android).
- Runbook: [Android connect](https://github.com/clawdbot/clawdbot/blob/main/docs/android.md).
## Agent workspace + skills
@@ -267,7 +275,7 @@ Minimal `~/.clawdbot/clawdbot.json` (model + defaults):
}
```
[Full configuration reference (all keys + examples).](https://docs.clawdbot.com/configuration)
[Full configuration reference (all keys + examples).](https://github.com/clawdbot/clawdbot/blob/main/docs/configuration.md)
## Security model (important)
@@ -275,17 +283,18 @@ Minimal `~/.clawdbot/clawdbot.json` (model + defaults):
- **Group/channel safety:** set `agent.sandbox.mode: "non-main"` to run **non‑main sessions** (groups/channels) inside per‑session Docker sandboxes; bash then runs in Docker for those sessions.
- **Sandbox defaults:** allowlist `bash`, `process`, `read`, `write`, `edit`; denylist `browser`, `canvas`, `nodes`, `cron`, `discord`, `gateway`.
Details: [Security guide](https://docs.clawdbot.com/security) · [Docker + sandboxing](https://docs.clawdbot.com/docker) · [Sandbox config](https://docs.clawdbot.com/configuration)
Details: [Security guide](https://github.com/clawdbot/clawdbot/blob/main/docs/security.md) · [Docker + sandboxing](https://github.com/clawdbot/clawdbot/blob/main/docs/docker.md) · [Sandbox config](https://github.com/clawdbot/clawdbot/blob/main/docs/configuration.md)
### [WhatsApp](https://docs.clawdbot.com/whatsapp)
### [WhatsApp](https://github.com/clawdbot/clawdbot/blob/main/docs/whatsapp.md)
- Link the device: `pnpm clawdbot login` (stores creds in `~/.clawdbot/credentials`).
- Allowlist who can talk to the assistant via `whatsapp.allowFrom`.
- If `whatsapp.groups` is set, it becomes a group allowlist; include `"*"` to allow all.
### [Telegram](https://docs.clawdbot.com/telegram)
### [Telegram](https://github.com/clawdbot/clawdbot/blob/main/docs/telegram.md)
- Set `TELEGRAM_BOT_TOKEN` or `telegram.botToken` (env wins).
- Optional: set `telegram.groups` (with `telegram.groups."*".requireMention`), `telegram.allowFrom`, or `telegram.webhookUrl` as needed.
- Optional: set `telegram.groups` (with `telegram.groups."*".requireMention`); when set, it is a group allowlist (include `"*"` to allow all). Also `telegram.allowFrom` or `telegram.webhookUrl` as needed.
```json5
{
@@ -295,11 +304,11 @@ Details: [Security guide](https://docs.clawdbot.com/security) · [Docker + sandb
}
```
### [Slack](https://docs.clawdbot.com/slack)
### [Slack](https://github.com/clawdbot/clawdbot/blob/main/docs/slack.md)
- Set `SLACK_BOT_TOKEN` + `SLACK_APP_TOKEN` (or `slack.botToken` + `slack.appToken`).
### [Discord](https://docs.clawdbot.com/discord)
### [Discord](https://github.com/clawdbot/clawdbot/blob/main/docs/discord.md)
- Set `DISCORD_BOT_TOKEN` or `discord.token` (env wins).
- Optional: set `discord.slashCommand`, `discord.dm.allowFrom`, `discord.guilds`, or `discord.mediaMaxMb` as needed.
@@ -312,15 +321,16 @@ Details: [Security guide](https://docs.clawdbot.com/security) · [Docker + sandb
}
```
### [Signal](https://docs.clawdbot.com/signal)
### [Signal](https://github.com/clawdbot/clawdbot/blob/main/docs/signal.md)
- Requires `signal-cli` and a `signal` config section.
### [iMessage](https://docs.clawdbot.com/imessage)
### [iMessage](https://github.com/clawdbot/clawdbot/blob/main/docs/imessage.md)
- macOS only; Messages must be signed in.
- If `imessage.groups` is set, it becomes a group allowlist; include `"*"` to allow all.
### [WebChat](https://docs.clawdbot.com/webchat)
### [WebChat](https://github.com/clawdbot/clawdbot/blob/main/docs/webchat.md)
- Uses the Gateway WebSocket; no separate WebChat port/config.
@@ -339,69 +349,69 @@ Browser control (optional):
## Docs
Use these when you’re past the onboarding flow and want the deeper reference.
- [Start with the docs index for navigation and “what’s where.”](https://docs.clawdbot.com/)
- [Read the architecture overview for the gateway + protocol model.](https://docs.clawdbot.com/architecture)
- [Use the full configuration reference when you need every key and example.](https://docs.clawdbot.com/configuration)
- [Run the Gateway by the book with the operational runbook.](https://docs.clawdbot.com/gateway)
- [Learn how the Control UI/Web surfaces work and how to expose them safely.](https://docs.clawdbot.com/web)
- [Understand remote access over SSH tunnels or tailnets.](https://docs.clawdbot.com/remote)
- [Follow the onboarding wizard flow for a guided setup.](https://docs.clawdbot.com/wizard)
- [Wire external triggers via the webhook surface.](https://docs.clawdbot.com/webhook)
- [Set up Gmail Pub/Sub triggers.](https://docs.clawdbot.com/gmail-pubsub)
- [Learn the macOS menu bar companion details.](https://docs.clawdbot.com/mac/menu-bar)
- [Platform guides: Windows](https://docs.clawdbot.com/windows), [Linux](https://docs.clawdbot.com/linux), [macOS](https://docs.clawdbot.com/macos), [iOS](https://docs.clawdbot.com/ios), [Android](https://docs.clawdbot.com/android)
- [Debug common failures with the troubleshooting guide.](https://docs.clawdbot.com/troubleshooting)
- [Review security guidance before exposing anything.](https://docs.clawdbot.com/security)
- [Start with the docs index for navigation and “what’s where.”](https://github.com/clawdbot/clawdbot/blob/main/docs/index.md)
- [Read the architecture overview for the gateway + protocol model.](https://github.com/clawdbot/clawdbot/blob/main/docs/architecture.md)
- [Use the full configuration reference when you need every key and example.](https://github.com/clawdbot/clawdbot/blob/main/docs/configuration.md)
- [Run the Gateway by the book with the operational runbook.](https://github.com/clawdbot/clawdbot/blob/main/docs/gateway.md)
- [Learn how the Control UI/Web surfaces work and how to expose them safely.](https://github.com/clawdbot/clawdbot/blob/main/docs/web.md)
- [Understand remote access over SSH tunnels or tailnets.](https://github.com/clawdbot/clawdbot/blob/main/docs/remote.md)
- [Follow the onboarding wizard flow for a guided setup.](https://github.com/clawdbot/clawdbot/blob/main/docs/wizard.md)
- [Wire external triggers via the webhook surface.](https://github.com/clawdbot/clawdbot/blob/main/docs/webhook.md)
- [Set up Gmail Pub/Sub triggers.](https://github.com/clawdbot/clawdbot/blob/main/docs/gmail-pubsub.md)
- [Learn the macOS menu bar companion details.](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/menu-bar.md)
- [Platform guides: Windows](https://github.com/clawdbot/clawdbot/blob/main/docs/windows.md), [Linux](https://github.com/clawdbot/clawdbot/blob/main/docs/linux.md), [macOS](https://github.com/clawdbot/clawdbot/blob/main/docs/macos.md), [iOS](https://github.com/clawdbot/clawdbot/blob/main/docs/ios.md), [Android](https://github.com/clawdbot/clawdbot/blob/main/docs/android.md)
- [Debug common failures with the troubleshooting guide.](https://github.com/clawdbot/clawdbot/blob/main/docs/troubleshooting.md)
- [Review security guidance before exposing anything.](https://github.com/clawdbot/clawdbot/blob/main/docs/security.md)
## Advanced docs (discovery + control)
- [Discovery + transports](https://docs.clawdbot.com/discovery)
- [Bonjour/mDNS](https://docs.clawdbot.com/bonjour)
- [Gateway pairing](https://docs.clawdbot.com/gateway/pairing)
- [Remote gateway README](https://docs.clawdbot.com/remote-gateway-readme)
- [Control UI](https://docs.clawdbot.com/control-ui)
- [Dashboard](https://docs.clawdbot.com/dashboard)
- [Discovery + transports](https://github.com/clawdbot/clawdbot/blob/main/docs/discovery.md)
- [Bonjour/mDNS](https://github.com/clawdbot/clawdbot/blob/main/docs/bonjour.md)
- [Gateway pairing](https://github.com/clawdbot/clawdbot/blob/main/docs/gateway/pairing.md)
- [Remote gateway README](https://github.com/clawdbot/clawdbot/blob/main/docs/remote-gateway-readme.md)
- [Control UI](https://github.com/clawdbot/clawdbot/blob/main/docs/control-ui.md)
- [Dashboard](https://github.com/clawdbot/clawdbot/blob/main/docs/dashboard.md)
## Operations & troubleshooting
- [Health checks](https://docs.clawdbot.com/health)
- [Gateway lock](https://docs.clawdbot.com/gateway-lock)
- [Background process](https://docs.clawdbot.com/background-process)
- [Browser troubleshooting (Linux)](https://docs.clawdbot.com/browser-linux-troubleshooting)
- [Logging](https://docs.clawdbot.com/logging)
- [Health checks](https://github.com/clawdbot/clawdbot/blob/main/docs/health.md)
- [Gateway lock](https://github.com/clawdbot/clawdbot/blob/main/docs/gateway-lock.md)
- [Background process](https://github.com/clawdbot/clawdbot/blob/main/docs/background-process.md)
- [Browser troubleshooting (Linux)](https://github.com/clawdbot/clawdbot/blob/main/docs/browser-linux-troubleshooting.md)
- [Logging](https://github.com/clawdbot/clawdbot/blob/main/docs/logging.md)
## Deep dives
- [Agent loop](https://docs.clawdbot.com/agent-loop)
- [Presence](https://docs.clawdbot.com/presence)
- [TypeBox schemas](https://docs.clawdbot.com/typebox)
- [RPC adapters](https://docs.clawdbot.com/rpc)
- [Queue](https://docs.clawdbot.com/queue)
- [Agent loop](https://github.com/clawdbot/clawdbot/blob/main/docs/agent-loop.md)
- [Presence](https://github.com/clawdbot/clawdbot/blob/main/docs/presence.md)
- [TypeBox schemas](https://github.com/clawdbot/clawdbot/blob/main/docs/typebox.md)
- [RPC adapters](https://github.com/clawdbot/clawdbot/blob/main/docs/rpc.md)
- [Queue](https://github.com/clawdbot/clawdbot/blob/main/docs/queue.md)
## Workspace & skills
- [Skills config](https://docs.clawdbot.com/skills-config)
- [Default AGENTS](https://docs.clawdbot.com/AGENTS.default)
- [Templates: AGENTS](https://docs.clawdbot.com/templates/AGENTS)
- [Templates: BOOTSTRAP](https://docs.clawdbot.com/templates/BOOTSTRAP)
- [Templates: IDENTITY](https://docs.clawdbot.com/templates/IDENTITY)
- [Templates: SOUL](https://docs.clawdbot.com/templates/SOUL)
- [Templates: TOOLS](https://docs.clawdbot.com/templates/TOOLS)
- [Templates: USER](https://docs.clawdbot.com/templates/USER)
- [Skills config](https://github.com/clawdbot/clawdbot/blob/main/docs/skills-config.md)
- [Default AGENTS](https://github.com/clawdbot/clawdbot/blob/main/docs/AGENTS.default.md)
- [Templates: AGENTS](https://github.com/clawdbot/clawdbot/blob/main/docs/templates/AGENTS.md)
- [Templates: BOOTSTRAP](https://github.com/clawdbot/clawdbot/blob/main/docs/templates/BOOTSTRAP.md)
- [Templates: IDENTITY](https://github.com/clawdbot/clawdbot/blob/main/docs/templates/IDENTITY.md)
- [Templates: SOUL](https://github.com/clawdbot/clawdbot/blob/main/docs/templates/SOUL.md)
- [Templates: TOOLS](https://github.com/clawdbot/clawdbot/blob/main/docs/templates/TOOLS.md)
- [Templates: USER](https://github.com/clawdbot/clawdbot/blob/main/docs/templates/USER.md)
## Platform internals
- [macOS dev setup](https://docs.clawdbot.com/mac/dev-setup)
- [macOS menu bar](https://docs.clawdbot.com/mac/menu-bar)
- [macOS voice wake](https://docs.clawdbot.com/mac/voicewake)
- [iOS node](https://docs.clawdbot.com/ios)
- [Android node](https://docs.clawdbot.com/android)
- [Windows app](https://docs.clawdbot.com/windows)
- [Linux app](https://docs.clawdbot.com/linux)
- [macOS dev setup](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/dev-setup.md)
- [macOS menu bar](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/menu-bar.md)
- [macOS voice wake](https://github.com/clawdbot/clawdbot/blob/main/docs/mac/voicewake.md)
- [iOS node](https://github.com/clawdbot/clawdbot/blob/main/docs/ios.md)
- [Android node](https://github.com/clawdbot/clawdbot/blob/main/docs/android.md)
- [Windows app](https://github.com/clawdbot/clawdbot/blob/main/docs/windows.md)
- [Linux app](https://github.com/clawdbot/clawdbot/blob/main/docs/linux.md)
## Email hooks (Gmail)
[Gmail Pub/Sub wiring (gcloud + gogcli), hook tokens, and auto-watch behavior are documented here.](https://docs.clawdbot.com/gmail-pubsub)
[Gmail Pub/Sub wiring (gcloud + gogcli), hook tokens, and auto-watch behavior are documented here.](https://github.com/clawdbot/clawdbot/blob/main/docs/gmail-pubsub.md)
Gateway auto-starts the watcher when `hooks.enabled=true` and `hooks.gmail.account` is set; `clawdbot hooks gmail run` is the manual daemon wrapper if you don’t want auto-start.
@@ -431,4 +441,6 @@ Thanks to all clawtributors:
<a href="https://github.com/mbelinky"><img src="https://avatars.githubusercontent.com/u/132747814?v=4&s=48" width="48" height="48" alt="mbelinky" title="mbelinky"/></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/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/omniwired"><img src="https://avatars.githubusercontent.com/u/322761?v=4&s=48" width="48" height="48" alt="omniwired" title="omniwired"/></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/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/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/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/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/vsabavat"><img src="https://avatars.githubusercontent.com/u/50385532?v=4&s=48" width="48" height="48" alt="vsabavat" title="vsabavat"/></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/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/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/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/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/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/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/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/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/djangonavarro220"><img src="https://avatars.githubusercontent.com/u/251162586?v=4&s=48" width="48" height="48" alt="djangonavarro220" title="djangonavarro220"/></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/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/adamgall"><img src="https://avatars.githubusercontent.com/u/706929?v=4&s=48" width="48" height="48" alt="adamgall" title="adamgall"/></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/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/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/regenrek"><img src="https://avatars.githubusercontent.com/u/5182020?v=4&s=48" width="48" height="48" alt="regenrek" title="regenrek"/></a> <a href="https://github.com/tobiasbischoff"><img src="https://avatars.githubusercontent.com/u/711564?v=4&s=48" width="48" height="48" alt="tobiasbischoff" title="tobiasbischoff"/></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/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/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/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/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/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/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/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/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/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/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/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/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>
</p>
@@ -369,6 +369,43 @@ public struct SendParams: Codable, Sendable {
}
}
public struct PollParams: Codable, Sendable {
public let to: String
public let question: String
public let options: [String]
public let maxselections: Int?
public let durationhours: Int?
public let provider: String?
public let idempotencykey: String
public init(
to: String,
question: String,
options: [String],
maxselections: Int?,
durationhours: Int?,
provider: String?,
idempotencykey: String
) {
self.to = to
self.question = question
self.options = options
self.maxselections = maxselections
self.durationhours = durationhours
self.provider = provider
self.idempotencykey = idempotencykey
}
private enum CodingKeys: String, CodingKey {
case to
case question
case options
case maxselections = "maxSelections"
case durationhours = "durationHours"
case provider
case idempotencykey = "idempotencyKey"
}
}
public struct AgentParams: Codable, Sendable {
public let message: String
public let to: String?
@@ -618,23 +655,27 @@ public struct SessionsListParams: Codable, Sendable {
public let activeminutes: Int?
public let includeglobal: Bool?
public let includeunknown: Bool?
public let spawnedby: String?
public init(
limit: Int?,
activeminutes: Int?,
includeglobal: Bool?,
includeunknown: Bool?
includeunknown: Bool?,
spawnedby: String?
) {
self.limit = limit
self.activeminutes = activeminutes
self.includeglobal = includeglobal
self.includeunknown = includeunknown
self.spawnedby = spawnedby
}
private enum CodingKeys: String, CodingKey {
case limit
case activeminutes = "activeMinutes"
case includeglobal = "includeGlobal"
case includeunknown = "includeUnknown"
case spawnedby = "spawnedBy"
}
}
@@ -644,6 +685,7 @@ public struct SessionsPatchParams: Codable, Sendable {
public let verboselevel: AnyCodable?
public let elevatedlevel: AnyCodable?
public let model: AnyCodable?
public let spawnedby: AnyCodable?
public let sendpolicy: AnyCodable?
public let groupactivation: AnyCodable?
@@ -653,6 +695,7 @@ public struct SessionsPatchParams: Codable, Sendable {
verboselevel: AnyCodable?,
elevatedlevel: AnyCodable?,
model: AnyCodable?,
spawnedby: AnyCodable?,
sendpolicy: AnyCodable?,
groupactivation: AnyCodable?
) {
@@ -661,6 +704,7 @@ public struct SessionsPatchParams: Codable, Sendable {
self.verboselevel = verboselevel
self.elevatedlevel = elevatedlevel
self.model = model
self.spawnedby = spawnedby
self.sendpolicy = sendpolicy
self.groupactivation = groupactivation
}
@@ -670,6 +714,7 @@ public struct SessionsPatchParams: Codable, Sendable {
case verboselevel = "verboseLevel"
case elevatedlevel = "elevatedLevel"
case model
case spawnedby = "spawnedBy"
case sendpolicy = "sendPolicy"
case groupactivation = "groupActivation"
}
+5 -2
View File
@@ -70,11 +70,14 @@ html[data-theme="dark"] {
box-sizing: border-box;
}
html,
body {
html {
height: 100%;
}
body {
min-height: 100%;
}
body {
margin: 0;
font-family: var(--font-body);
+56
View File
@@ -0,0 +1,56 @@
# Bun (optional)
Goal: allow running this repo with Bun without maintaining a Bun lockfile or losing pnpm patch behavior.
## Status
- pnpm remains the primary package manager/runtime for this repo.
- Bun can be used for local installs/builds/tests, but Bun currently **cannot use** `pnpm-lock.yaml` and will ignore it.
## Install (no Bun lockfile)
Use Bun without writing `bun.lock`/`bun.lockb`:
```sh
bun install --no-save
```
This avoids maintaining two lockfiles. (`bun.lock`/`bun.lockb` are gitignored.)
## Build / Test (Bun)
```sh
bun run build
bun run vitest run
```
## pnpm patchedDependencies under Bun
pnpm supports `package.json#pnpm.patchedDependencies` and records it in `pnpm-lock.yaml`.
Bun does not support pnpm patches, so we apply them in `postinstall` when Bun is detected:
- `scripts/postinstall.js` runs only for Bun installs and applies every entry from `package.json#pnpm.patchedDependencies` into `node_modules/...` using `git apply` (idempotent).
To add a new patch that works in both pnpm + Bun:
1. Add an entry to `package.json#pnpm.patchedDependencies`
2. Add the patch file under `patches/`
3. Run `pnpm install` (updates `pnpm-lock.yaml` patch hash)
## Bun lifecycle scripts (blocked by default)
Bun may block dependency lifecycle scripts unless explicitly trusted (`bun pm untrusted` / `bun pm trust`).
For this repo, the commonly blocked scripts are not required:
- `@whiskeysockets/baileys` `preinstall`: checks Node major >= 20 (we run Node 22+).
- `protobufjs` `postinstall`: emits warnings about incompatible version schemes (no build artifacts).
If you hit a real runtime issue that requires these scripts, trust them explicitly:
```sh
bun pm trust @whiskeysockets/baileys protobufjs
```
## Caveats
- Some scripts still hardcode pnpm (e.g. `docs:build`, `ui:*`, `protocol:check`). Run those via pnpm for now.
+64 -6
View File
@@ -9,7 +9,7 @@ CLAWDBOT reads an optional **JSON5** config from `~/.clawdbot/clawdbot.json` (co
If the file is missing, CLAWDBOT uses safe-ish defaults (embedded Pi agent + per-sender sessions + workspace `~/clawd`). You usually only need a config to:
- restrict who can trigger the bot (`whatsapp.allowFrom`, `telegram.allowFrom`, etc.)
- control group mention behavior (`whatsapp.groups`, `telegram.groups`, `discord.guilds`, `routing.groupChat`)
- control group allowlists + mention behavior (`whatsapp.groups`, `telegram.groups`, `discord.guilds`, `routing.groupChat`)
- customize message prefixes (`messages`)
- set the agent's workspace (`agent.workspace`)
- tune the embedded agent (`agent`) and session behavior (`session`)
@@ -131,7 +131,7 @@ rotation order used for failover.
Optional agent identity used for defaults and UX. This is written by the macOS onboarding assistant.
If set, CLAWDBOT derives defaults (only when you haven’t set them explicitly):
- `messages.responsePrefix` from `identity.emoji`
- `messages.ackReaction` from `identity.emoji` (falls back to 👀)
- `routing.groupChat.mentionPatterns` from `identity.name` (so “@Samantha” works in groups across Telegram/Slack/Discord/iMessage/WhatsApp)
```json5
@@ -186,8 +186,9 @@ Metadata written by CLI wizards (`onboard`, `configure`, `doctor`, `update`).
### `whatsapp.allowFrom`
Allowlist of E.164 phone numbers that may trigger WhatsApp auto-replies (DMs only).
Allowlist of E.164 phone numbers that may trigger WhatsApp auto-replies (**DMs only**).
If empty, the default allowlist is your own WhatsApp number (self-chat mode).
For groups, use `whatsapp.groupPolicy` + `whatsapp.groupAllowFrom`.
```json5
{
@@ -218,7 +219,7 @@ Group messages default to **require mention** (either metadata mention or regex
}
```
Mention gating defaults live per provider (`whatsapp.groups`, `telegram.groups`, `imessage.groups`, `discord.guilds`).
Mention gating defaults live per provider (`whatsapp.groups`, `telegram.groups`, `imessage.groups`, `discord.guilds`). When `*.groups` is set, it also acts as a group allowlist; include `"*"` to allow all groups.
To respond **only** to specific text triggers (ignoring native @-mentions):
```json5
@@ -237,6 +238,51 @@ To respond **only** to specific text triggers (ignoring native @-mentions):
}
```
### Group policy (per provider)
Use `*.groupPolicy` to control whether group/room messages are accepted at all:
```json5
{
whatsapp: {
groupPolicy: "allowlist",
groupAllowFrom: ["+15551234567"]
},
telegram: {
groupPolicy: "allowlist",
groupAllowFrom: ["tg:123456789", "@alice"]
},
signal: {
groupPolicy: "allowlist",
groupAllowFrom: ["+15551234567"]
},
imessage: {
groupPolicy: "allowlist",
groupAllowFrom: ["chat_id:123"]
},
discord: {
groupPolicy: "allowlist",
guilds: {
"GUILD_ID": {
channels: { help: { allow: true } }
}
}
},
slack: {
groupPolicy: "allowlist",
channels: { "#general": { allow: true } }
}
}
```
Notes:
- `"open"` (default): groups bypass allowlists; mention-gating still applies.
- `"disabled"`: block all group/room messages.
- `"allowlist"`: only allow groups/rooms that match the configured allowlist.
- WhatsApp/Telegram/Signal/iMessage use `groupAllowFrom` (fallback: explicit `allowFrom`).
- Discord/Slack use channel allowlists (`discord.guilds.*.channels`, `slack.channels`).
- Group DMs (Discord/Slack) are still controlled by `dm.groupEnabled` + `dm.groupChannels`.
### `routing.queue`
Controls how inbound messages behave when an agent run is already active.
@@ -477,13 +523,15 @@ message envelopes). If unset, Clawdbot uses the host timezone at runtime.
### `messages`
Controls inbound/outbound prefixes.
Controls inbound/outbound prefixes and optional ack reactions.
```json5
{
messages: {
messagePrefix: "[clawdbot]",
responsePrefix: "🦞"
responsePrefix: "🦞",
ackReaction: "👀",
ackReactionScope: "group-mentions"
}
}
```
@@ -491,6 +539,16 @@ Controls inbound/outbound prefixes.
`responsePrefix` is applied to **all outbound replies** (tool summaries, block
streaming, final replies) across providers unless already present.
`ackReaction` sends a best-effort emoji reaction to acknowledge inbound messages
on providers that support reactions (Slack/Discord/Telegram). Defaults to the
configured `identity.emoji` when set, otherwise `"👀"`. Set it to `""` to disable.
`ackReactionScope` controls when reactions fire:
- `group-mentions` (default): only when a group/room requires mentions **and** the bot was mentioned
- `group-all`: all group/room messages
- `direct`: direct messages only
- `all`: all messages
### `talk`
Defaults for Talk mode (macOS/iOS/Android). Voice IDs fall back to `ELEVENLABS_VOICE_ID` or `SAG_VOICE_ID` when unset.
+5 -5
View File
@@ -63,21 +63,21 @@ Paste the token into the UI settings (sent as `connect.params.auth.token`).
The Gateway serves static files from `dist/control-ui`. Build them with:
```bash
pnpm ui:install
pnpm ui:build
bun run ui:install
bun run ui:build
```
Optional absolute base (when you want fixed asset URLs):
```bash
CLAWDBOT_CONTROL_UI_BASE_PATH=/clawdbot/ pnpm ui:build
CLAWDBOT_CONTROL_UI_BASE_PATH=/clawdbot/ bun run ui:build
```
For local development (separate dev server):
```bash
pnpm ui:install
pnpm ui:dev
bun run ui:install
bun run ui:dev
```
Then point the UI at your Gateway WS URL (e.g. `ws://127.0.0.1:18789`).
+5
View File
@@ -155,6 +155,7 @@ Notes:
discord: {
enabled: true,
token: "abc.123",
groupPolicy: "open",
mediaMaxMb: 8,
actions: {
reactions: true,
@@ -203,10 +204,14 @@ Notes:
}
```
Ack reactions are controlled globally via `messages.ackReaction` +
`messages.ackReactionScope`.
- `dm.enabled`: set `false` to ignore all DMs (default `true`).
- `dm.allowFrom`: DM allowlist (user ids or names). Omit or set to `["*"]` to allow any DM sender.
- `dm.groupEnabled`: enable group DMs (default `false`).
- `dm.groupChannels`: optional allowlist for group DM channel ids or slugs.
- `groupPolicy`: controls guild channel handling (`open|disabled|allowlist`); `allowlist` requires channel allowlists.
- `guilds`: per-guild rules keyed by guild id (preferred) or slug.
- `guilds."*"`: default per-guild settings applied when no explicit entry exists.
- `guilds.<id>.slug`: optional friendly slug used for display names.
+11 -1
View File
@@ -492,6 +492,9 @@ The gateway runs under a supervisor that auto-restarts it. You need to stop the
# Check if running
launchctl list | grep clawdbot
# Stop (disable does NOT stop a running job)
clawdbot gateway stop
# Stop and disable
launchctl disable gui/$UID/com.clawdbot.gateway
launchctl bootout gui/$UID/com.clawdbot.gateway
@@ -499,6 +502,9 @@ launchctl bootout gui/$UID/com.clawdbot.gateway
# Re-enable later
launchctl enable gui/$UID/com.clawdbot.gateway
launchctl bootstrap gui/$UID ~/Library/LaunchAgents/com.clawdbot.gateway.plist
# Or just restart
clawdbot gateway restart
```
**Linux (systemd)**
@@ -508,7 +514,11 @@ launchctl bootstrap gui/$UID ~/Library/LaunchAgents/com.clawdbot.gateway.plist
systemctl list-units | grep -i clawdbot
# Stop and disable
sudo systemctl disable --now clawdbot
clawdbot gateway stop
systemctl --user disable --now clawdbot-gateway.service
# Or just restart
clawdbot gateway restart
```
**pm2 (if used)**
+3
View File
@@ -159,6 +159,8 @@ See also: `docs/presence.md` for how presence is produced/deduped and why `insta
Bundled mac app:
- Clawdbot.app can bundle a bun-compiled gateway binary and install a per-user LaunchAgent labeled `com.clawdbot.gateway`.
- To stop it cleanly, use `clawdbot gateway stop` (or `launchctl bootout gui/$UID/com.clawdbot.gateway`).
- To restart, use `clawdbot gateway restart` (or `launchctl kickstart -k gui/$UID/com.clawdbot.gateway`).
## Supervision (systemd user unit)
Create `~/.config/systemd/user/clawdbot-gateway.service`:
@@ -217,6 +219,7 @@ sudo systemctl enable --now clawdbot-gateway.service
- `clawdbot gateway send --to <num> --message "hi" [--media-url ...]` — send via Gateway (idempotent).
- `clawdbot gateway agent --message "hi" [--to ...]` — run an agent turn (waits for final by default).
- `clawdbot gateway call <method> --params '{"k":"v"}'` — raw method invoker for debugging.
- `clawdbot gateway stop|restart` — stop/restart the supervised gateway service (launchd/systemd/schtasks).
- Gateway helper subcommands assume a running gateway on `--url`; they no longer auto-spawn one.
## Migration guidance
+1 -1
View File
@@ -18,7 +18,7 @@ Updated: 2025-12-07
- **Proxy:** optional `telegram.proxy` uses `undici.ProxyAgent` through grammY’s `client.baseFetch`.
- **Webhook support:** `webhook-set.ts` wraps `setWebhook/deleteWebhook`; `webhook.ts` hosts the callback with health + graceful shutdown. Gateway enables webhook mode when `telegram.webhookUrl` is set (otherwise it long-polls).
- **Sessions:** direct chats map to `main`; groups map to `telegram:group:<chatId>`; replies route back to the same surface.
- **Config knobs:** `telegram.botToken`, `telegram.groups`, `telegram.allowFrom`, `telegram.mediaMaxMb`, `telegram.proxy`, `telegram.webhookSecret`, `telegram.webhookUrl`.
- **Config knobs:** `telegram.botToken`, `telegram.groups` (allowlist + mention defaults), `telegram.allowFrom`, `telegram.mediaMaxMb`, `telegram.proxy`, `telegram.webhookSecret`, `telegram.webhookUrl`.
- **Tests:** grammy mocks cover DM + group mention gating and outbound send; more media/webhook fixtures still welcome.
Open questions
+2 -2
View File
@@ -10,8 +10,8 @@ Goal: let Clawd sit in WhatsApp groups, wake up only when pinged, and keep that
Note: `routing.groupChat.mentionPatterns` is now used by Telegram/Discord/Slack/iMessage as well; this doc focuses on WhatsApp-specific behavior.
## What’s implemented (2025-12-03)
- Activation modes: `mention` (default) or `always`. `mention` requires a ping (real WhatsApp @-mentions via `mentionedJids`, regex patterns, or the bot’s E.164 anywhere in the text). `always` wakes the agent on every message but it should reply only when it can add meaningful value; otherwise it returns the silent token `NO_REPLY`. Defaults can be set in config (`whatsapp.groups`) and overridden per group via `/activation`.
- Group allowlist bypass: we still enforce `whatsapp.allowFrom` on the participant at inbox ingest, but group JIDs themselves no longer block replies.
- Activation modes: `mention` (default) or `always`. `mention` requires a ping (real WhatsApp @-mentions via `mentionedJids`, regex patterns, or the bot’s E.164 anywhere in the text). `always` wakes the agent on every message but it should reply only when it can add meaningful value; otherwise it returns the silent token `NO_REPLY`. Defaults can be set in config (`whatsapp.groups`) and overridden per group via `/activation`. When `whatsapp.groups` is set, it also acts as a group allowlist (include `"*"` to allow all).
- Group policy: `whatsapp.groupPolicy` controls whether group messages are accepted (`open|disabled|allowlist`). `allowlist` uses `whatsapp.groupAllowFrom` (fallback: explicit `whatsapp.allowFrom`).
- Per-group sessions: session keys look like `whatsapp:group:<jid>` so commands such as `/verbose on` or `/think:high` are scoped to that group; personal DM state is untouched. Heartbeats are skipped for group threads.
- Context injection: last N (default 50) group messages are prefixed under `[Chat messages since your last reply - for context]`, with the triggering line under `[Current message - respond to this]`.
- Sender surfacing: every group batch now ends with `[from: Sender Name (+E164)]` so Pi knows who is speaking.
+53 -2
View File
@@ -1,11 +1,11 @@
---
summary: "Group chat behavior across surfaces (WhatsApp/Telegram/Discord/iMessage)"
summary: "Group chat behavior across surfaces (WhatsApp/Telegram/Discord/Slack/Signal/iMessage)"
read_when:
- Changing group chat behavior or mention gating
---
# Groups
Clawdbot treats group chats consistently across surfaces: WhatsApp, Telegram, Discord, iMessage.
Clawdbot treats group chats consistently across surfaces: WhatsApp, Telegram, Discord, Slack, Signal, iMessage.
## Session keys
- Group sessions use `surface:group:<id>` session keys (rooms/channels use `surface:channel:<id>`).
@@ -16,6 +16,54 @@ Clawdbot treats group chats consistently across surfaces: WhatsApp, Telegram, Di
- UI labels use `displayName` when available, formatted as `surface:<token>`.
- `#room` is reserved for rooms/channels; group chats use `g-<slug>` (lowercase, spaces -> `-`, keep `#@+._-`).
## Group policy
Control how group/room messages are handled per provider:
```json5
{
whatsapp: {
groupPolicy: "disabled", // "open" | "disabled" | "allowlist"
groupAllowFrom: ["+15551234567"]
},
telegram: {
groupPolicy: "disabled",
groupAllowFrom: ["123456789", "@username"]
},
signal: {
groupPolicy: "disabled",
groupAllowFrom: ["+15551234567"]
},
imessage: {
groupPolicy: "disabled",
groupAllowFrom: ["chat_id:123"]
},
discord: {
groupPolicy: "allowlist",
guilds: {
"GUILD_ID": { channels: { help: { allow: true } } }
}
},
slack: {
groupPolicy: "allowlist",
channels: { "#general": { allow: true } }
}
}
```
| Policy | Behavior |
|--------|----------|
| `"open"` | Default. Groups bypass allowlists; mention-gating still applies. |
| `"disabled"` | Block all group messages entirely. |
| `"allowlist"` | Only allow groups/rooms that match the configured allowlist. |
Notes:
- `groupPolicy` is separate from mention-gating (which requires @mentions).
- WhatsApp/Telegram/Signal/iMessage: use `groupAllowFrom` (fallback: explicit `allowFrom`).
- Discord: allowlist uses `discord.guilds.<id>.channels`.
- Slack: allowlist uses `slack.channels`.
- Group DMs are controlled separately (`discord.dm.*`, `slack.dm.*`).
- Telegram allowlist can match user IDs (`"123456789"`, `"telegram:123456789"`, `"tg:123456789"`) or usernames (`"@alice"` or `"alice"`); prefixes are case-insensitive.
## Mention gating (default)
Group messages require a mention unless overridden per group. Defaults live per subsystem under `*.groups."*"`.
@@ -54,6 +102,9 @@ Notes:
- Mention gating is only enforced when mention detection is possible (native mentions or `mentionPatterns` are configured).
- Discord defaults live in `discord.guilds."*"` (overridable per guild/channel).
## Group allowlists
When `whatsapp.groups`, `telegram.groups`, or `imessage.groups` is configured, the keys act as a group allowlist. Use `"*"` to allow all groups while still setting default mention behavior.
## Activation (owner-only)
Group owners can toggle per-group activation:
- `/activation mention`
+1 -1
View File
@@ -22,7 +22,7 @@ Short guide to verify the WhatsApp Web / Baileys stack without guessing.
## When something fails
- `logged out` or status 409–515 → relink with `clawdbot logout` then `clawdbot login`.
- Gateway unreachable → start it: `clawdbot gateway --port 18789` (use `--force` if the port is busy).
- No inbound messages → confirm linked phone is online and the sender is allowed (`whatsapp.allowFrom`); for group chats, ensure mention rules match (`routing.groupChat.mentionPatterns` and `whatsapp.groups`).
- No inbound messages → confirm linked phone is online and the sender is allowed (`whatsapp.allowFrom`); for group chats, ensure allowlist + mention rules match (`whatsapp.groups`, `routing.groupChat.mentionPatterns`).
## Dedicated "health" command
`clawdbot health --json` asks the running Gateway for its health snapshot (no direct Baileys socket from the CLI). It reports linked creds, auth age, Baileys connect result/status code, session-store summary, and a probe duration. It exits non-zero if the Gateway is unreachable or the probe fails/timeouts. Use `--timeout <ms>` to override the 10s default.
+5 -1
View File
@@ -27,6 +27,8 @@ Status: external CLI integration. No daemon.
cliPath: "imsg",
dbPath: "~/Library/Messages/chat.db",
allowFrom: ["+15555550123", "user@example.com", "chat_id:123"],
groupPolicy: "open",
groupAllowFrom: ["chat_id:123"],
includeAttachments: false,
mediaMaxMb: 16,
service: "auto",
@@ -37,6 +39,8 @@ Status: external CLI integration. No daemon.
Notes:
- `allowFrom` accepts handles (phone/email) or `chat_id:<id>` entries.
- `groupPolicy` controls group handling (`open|disabled|allowlist`).
- `groupAllowFrom` accepts the same entries as `allowFrom`.
- `service` defaults to `auto` (use `imessage` or `sms` to pin).
- `region` is only used for SMS targeting.
@@ -55,7 +59,7 @@ imsg chats --limit 20
## Group chat behavior
- Group messages set `ChatType=group`, `GroupSubject`, and `GroupMembers`.
- Group activation respects `imessage.groups."*".requireMention` and `routing.groupChat.mentionPatterns` (patterns are required to detect mentions on iMessage).
- Group activation respects `imessage.groups."*".requireMention` and `routing.groupChat.mentionPatterns` (patterns are required to detect mentions on iMessage). When `imessage.groups` is set, it also acts as a group allowlist; include `"*"` to allow all groups.
- Replies go back to the same `chat_id` (group or direct).
## Troubleshooting
+2 -1
View File
@@ -19,7 +19,7 @@ read_when:
<p align="center">
<a href="https://github.com/clawdbot/clawdbot">GitHub</a> ·
<a href="https://github.com/clawdbot/clawdbot/releases">Releases</a> ·
<a href="https://docs.clawdbot.com/">Docs</a> ·
<a href="https://github.com/clawdbot/clawdbot/blob/main/docs/index.md">Docs</a> ·
<a href="./clawd.md">Clawd setup</a>
</p>
@@ -181,6 +181,7 @@ Example:
## Core Contributors
- **Maxim Vovshin** (@Hyaxia, 36747317+Hyaxia@users.noreply.github.com) — Blogwatcher skill
- **Nacho Iacovino** (@nachoiacovino, nacho.iacovino@gmail.com) — Location parsing (Telegram + WhatsApp)
## License
+46
View File
@@ -0,0 +1,46 @@
---
summary: "Inbound provider location parsing (Telegram + WhatsApp) and context fields"
read_when:
- Adding or modifying provider location parsing
- Using location context fields in agent prompts or tools
---
# Provider location parsing
Clawdbot normalizes shared locations from chat providers into:
- human-readable text appended to the inbound body, and
- structured fields in the auto-reply context payload.
Currently supported:
- **Telegram** (location pins + venues + live locations)
- **WhatsApp** (locationMessage + liveLocationMessage)
## Text formatting
Locations are rendered as friendly lines without brackets:
- Pin:
- `📍 48.858844, 2.294351 ±12m`
- Named place:
- `📍 Eiffel Tower — Champ de Mars, Paris (48.858844, 2.294351 ±12m)`
- Live share:
- `🛰 Live location: 48.858844, 2.294351 ±12m`
If the provider includes a caption/comment, it is appended on the next line:
```
📍 48.858844, 2.294351 ±12m
Meet here
```
## Context fields
When a location is present, these fields are added to `ctx`:
- `LocationLat` (number)
- `LocationLon` (number)
- `LocationAccuracy` (number, meters; optional)
- `LocationName` (string; optional)
- `LocationAddress` (string; optional)
- `LocationSource` (`pin | place | live`)
- `LocationIsLive` (boolean)
## Provider notes
- **Telegram**: venues map to `LocationName/LocationAddress`; live locations use `live_period`.
- **WhatsApp**: `locationMessage.comment` and `liveLocationMessage.caption` are appended as the caption line.
+75
View File
@@ -0,0 +1,75 @@
---
summary: "How Clawdbot rotates auth profiles and falls back across models"
read_when:
- Diagnosing auth profile rotation, cooldowns, or model fallback behavior
- Updating failover rules for auth profiles or models
---
# Model failover
Clawdbot handles failures in two stages:
1) **Auth profile rotation** within the current provider.
2) **Model fallback** to the next model in `agent.model.fallbacks`.
This doc explains the runtime rules and the data that backs them.
## Profile IDs
OAuth logins create distinct profiles so multiple accounts can coexist.
- Default: `provider:default` when no email is available.
- OAuth with email: `provider:<email>` (for example `google-antigravity:user@gmail.com`).
Profiles live in `~/.clawdbot/agent/auth-profiles.json` under `profiles`.
## Rotation order
When a provider has multiple profiles, Clawdbot chooses an order like this:
1) **Explicit config**: `auth.order[provider]` (if set).
2) **Configured profiles**: `auth.profiles` filtered by provider.
3) **Stored profiles**: entries in `auth-profiles.json` for the provider.
If no explicit order is configured, Clawdbot uses a round‑robin order:
- **Primary key:** `usageStats.lastUsed` (oldest first).
- **Secondary key:** profile type (OAuth before API keys).
- **Cooldown profiles** are moved to the end, ordered by soonest cooldown expiry.
## Cooldowns
When a profile fails due to auth/rate‑limit errors (or a timeout that looks
like rate limiting), Clawdbot marks it in cooldown and moves to the next profile.
Cooldowns use exponential backoff:
- 1 minute
- 5 minutes
- 25 minutes
- 1 hour (cap)
State is stored in `auth-profiles.json` under `usageStats`:
```json
{
"usageStats": {
"provider:profile": {
"lastUsed": 1736160000000,
"cooldownUntil": 1736160600000,
"errorCount": 2
}
}
}
```
## Model fallback
If all profiles for a provider fail, Clawdbot moves to the next model in
`agent.model.fallbacks`. This applies to auth failures, rate limits, and
timeouts that exhausted profile rotation.
## Related config
See `docs/configuration.md` for:
- `auth.profiles` / `auth.order`
- `agent.model.primary` / `agent.model.fallbacks`
- `agent.imageModel` routing
See `docs/models.md` for the broader model selection and fallback overview.
+1
View File
@@ -77,6 +77,7 @@ Output
- Image routing uses `agent.imageModel` **only when configured** and the primary
model lacks image input.
- Persist last successful provider/model to session entry; auth profile success is global.
- See `docs/model-failover.md` for auth profile rotation, cooldowns, and timeout handling.
## Tests
+121
View File
@@ -0,0 +1,121 @@
# Engineering Execution Spec: groupPolicy Hardening (Telegram Allowlist Parity)
**Date**: 2026-01-05
**Status**: Complete
**PR**: #216 (feat/whatsapp-group-policy)
---
## Executive Summary
Follow-up hardening work ensures Telegram allowlists behave consistently across inbound group/DM filtering and outbound send normalization. The focus is on prefix parity (`telegram:` / `tg:`), case-insensitive matching for prefixes, and resilience to accidental whitespace in config entries. Documentation and tests were updated to reflect and lock in this behavior.
---
## Findings Analysis
### [MED] F1: Telegram Allowlist Prefix Handling Is Case-Sensitive and Excludes `tg:`
**Location**: `src/telegram/bot.ts`
**Problem**: Inbound allowlist normalization only stripped a lowercase `telegram:` prefix. This rejected `TG:123` / `Telegram:123` and did not accept the `tg:` shorthand even though outbound send normalization already accepts `tg:` and case-insensitive prefixes.
**Impact**:
- DMs and group allowlists fail when users copy/paste prefixed IDs from logs or existing send format.
- Behavior is inconsistent between inbound filtering and outbound send normalization.
**Fix**: Normalize allowlist entries by trimming whitespace and stripping `telegram:` / `tg:` prefixes case-insensitively at pre-compute time.
---
### [LOW] F2: Allowlist Entries Are Not Trimmed
**Location**: `src/telegram/bot.ts`
**Problem**: Allowlist entries are not trimmed; accidental whitespace causes mismatches.
**Fix**: Trim and drop empty entries while normalizing allowlist inputs.
---
## Implementation Phases
### Phase 1: Normalize Telegram Allowlist Inputs
**File**: `src/telegram/bot.ts`
**Changes**:
1. Trim allowlist entries and drop empty values.
2. Strip `telegram:` / `tg:` prefixes case-insensitively.
3. Simplify DM allowlist check to rely on normalized values.
---
### Phase 2: Add Coverage for Prefix + Whitespace
**File**: `src/telegram/bot.test.ts`
**Add Tests**:
- DM allowlist accepts `TG:` prefix with surrounding whitespace.
- Group allowlist accepts `TG:` prefix case-insensitively.
---
### Phase 3: Documentation Updates
**Files**:
- `docs/groups.md`
- `docs/telegram.md`
**Changes**:
- Document `tg:` alias and case-insensitive prefixes for Telegram allowlists.
---
### Phase 4: Verification
1. Run targeted Telegram tests (`pnpm test -- src/telegram/bot.test.ts`).
2. If time allows, run full suite (`pnpm test`).
---
## Files Modified
| File | Change Type | Description |
|------|-------------|-------------|
| `src/telegram/bot.ts` | Fix | Trim allowlist values; strip `telegram:` / `tg:` prefixes case-insensitively |
| `src/telegram/bot.test.ts` | Test | Add DM + group allowlist coverage for `TG:` prefix + whitespace |
| `docs/groups.md` | Docs | Mention `tg:` alias + case-insensitive prefixes |
| `docs/telegram.md` | Docs | Mention `tg:` alias + case-insensitive prefixes |
---
## Success Criteria
- [x] Telegram allowlist accepts `telegram:` / `tg:` prefixes case-insensitively.
- [x] Telegram allowlist tolerates whitespace in config entries.
- [x] DM and group allowlist tests cover prefixed cases.
- [x] Docs updated to reflect allowlist formats.
- [x] Targeted tests pass.
- [x] Full test suite passes.
---
## Risk Assessment
| Risk | Severity | Mitigation |
|------|----------|------------|
| Behavior change for malformed entries | Low | Normalization is additive and trims only whitespace |
| Test fragility | Low | Isolated unit tests; no external dependencies |
| Doc drift | Low | Updated docs alongside code |
---
## Estimated Complexity
- **Phase 1**: Low (normalization helpers)
- **Phase 2**: Low (2 new tests)
- **Phase 3**: Low (doc edits)
- **Phase 4**: Low (verification)
**Total**: ~20 minutes
+52
View File
@@ -0,0 +1,52 @@
---
summary: "Poll sending via gateway + CLI"
read_when:
- Adding or modifying poll support
- Debugging poll sends from the CLI or gateway
---
# Polls
Updated: 2026-01-06
## Supported providers
- WhatsApp (web provider)
- Discord
## CLI
```bash
# WhatsApp
clawdbot poll --to +15555550123 -q "Lunch today?" -o "Yes" -o "No" -o "Maybe"
clawdbot poll --to 123456789@g.us -q "Meeting time?" -o "10am" -o "2pm" -o "4pm" -s 2
# Discord
clawdbot poll --to channel:123456789 -q "Snack?" -o "Pizza" -o "Sushi" --provider discord
clawdbot poll --to channel:123456789 -q "Plan?" -o "A" -o "B" --provider discord --duration-hours 48
```
Options:
- `--provider`: `whatsapp` (default) or `discord`
- `--max-selections`: how many choices a voter can select (default: 1)
- `--duration-hours`: Discord-only (defaults to 24 when omitted)
## Gateway RPC
Method: `poll`
Params:
- `to` (string, required)
- `question` (string, required)
- `options` (string[], required)
- `maxSelections` (number, optional)
- `durationHours` (number, optional)
- `provider` (string, optional, default: `whatsapp`)
- `idempotencyKey` (string, required)
## Provider differences
- WhatsApp: 2-12 options, `maxSelections` must be within option count, ignores `durationHours`.
- Discord: 2-10 options, `durationHours` clamped to 1-768 hours (default 24). `maxSelections > 1` enables multi-select; Discord does not support a strict selection count.
## Agent tool (Discord)
The Discord tool action `poll` still uses `question`, `answers`, optional `allowMultiselect`, `durationHours`, and `content`. The gateway/CLI poll model maps `allowMultiselect` to `maxSelections > 1`.
Note: Discord has no “pick exactly N” mode; `maxSelections` is treated as a boolean (`> 1` = multiselect).
+35
View File
@@ -12,6 +12,7 @@ Goal: small, hard-to-misuse tool surface so agents can list sessions, fetch hist
- `sessions_list`
- `sessions_history`
- `sessions_send`
- `sessions_spawn`
## Key Model
- Main direct chat bucket is always the literal key `"main"`.
@@ -34,6 +35,7 @@ Parameters:
Behavior:
- `messageLimit > 0` fetches `chat.history` per session and includes the last N messages.
- Tool results are filtered out in list output; use `sessions_history` for tool messages.
- When running in a **sandboxed** agent session, session tools default to **spawned-only visibility** (see below).
Row shape (JSON):
- `key`: session key (string)
@@ -117,3 +119,36 @@ Runtime override (per session entry):
Enforcement points:
- `chat.send` / `agent` (gateway)
- auto-reply delivery logic
## sessions_spawn
Spawn a sub-agent run in an isolated session and announce the result back to the requester chat surface.
Parameters:
- `task` (required)
- `label?` (optional; used for logs/UI)
- `timeoutSeconds?` (default 0; 0 = fire-and-forget)
- `cleanup?` (`delete|keep`, default `delete`)
Behavior:
- Starts a new `subagent:<uuid>` session with `deliver: false`.
- Sub-agents default to the full tool surface **minus session tools** (configurable via `agent.subagents.tools`).
- Sub-agents are not allowed to call `sessions_spawn` (no sub-agent → sub-agent spawning).
- After completion (or best-effort wait), Clawdbot runs a sub-agent **announce step** and posts the result to the requester chat surface.
- Reply exactly `ANNOUNCE_SKIP` during the announce step to stay silent.
## Sandbox Session Visibility
Sandboxed sessions can use session tools, but by default they only see sessions they spawned via `sessions_spawn`.
Config:
```json5
{
agent: {
sandbox: {
// default: "spawned"
sessionToolsVisibility: "spawned" // or "all"
}
}
}
```
+6 -2
View File
@@ -50,8 +50,12 @@ You can still run Clawdbot on your own Signal account if your goal is “respond
httpHost: "127.0.0.1",
httpPort: 8080,
// Who is allowed to talk to the bot
allowFrom: ["+15557654321"] // your personal number (or "*")
// Who is allowed to talk to the bot (DMs)
allowFrom: ["+15557654321"], // your personal number (or "*")
// Group policy + allowlist
groupPolicy: "open",
groupAllowFrom: ["+15557654321"]
}
}
```
+8
View File
@@ -145,6 +145,7 @@ Slack uses Socket Mode only (no HTTP webhook server). Provide both tokens:
"enabled": true,
"botToken": "xoxb-...",
"appToken": "xapp-...",
"groupPolicy": "open",
"dm": {
"enabled": true,
"allowFrom": ["U123", "U456", "*"],
@@ -180,11 +181,18 @@ Tokens can also be supplied via env vars:
- `SLACK_BOT_TOKEN`
- `SLACK_APP_TOKEN`
Ack reactions are controlled globally via `messages.ackReaction` +
`messages.ackReactionScope`.
## Sessions + routing
- DMs share the `main` session (like WhatsApp/Telegram).
- Channels map to `slack:channel:<channelId>` sessions.
- Slash commands use `slack:slash:<userId>` sessions.
## Group policy
- `slack.groupPolicy` controls channel handling (`open|disabled|allowlist`).
- `allowlist` requires channels to be listed in `slack.channels`.
## Delivery targets
Use these with cron/CLI sends:
- `user:<id>` for DMs
+72
View File
@@ -0,0 +1,72 @@
---
summary: "Sub-agents: spawning isolated agent runs that announce results back to the requester chat"
read_when:
- You want background/parallel work via the agent
- You are changing sessions_spawn or sub-agent tool policy
---
# Sub-agents
Sub-agents are background agent runs spawned from an existing agent run. They run in their own session (`subagent:<uuid>`) and, when finished, **announce** their result back to the requester chat surface.
Primary goals:
- Parallelize “research / long task / slow tool” work without blocking the main run.
- Keep sub-agents isolated by default (session separation + optional sandboxing).
- Keep the tool surface hard to misuse: sub-agents do **not** get session tools by default.
- Avoid nested fan-out: sub-agents cannot spawn sub-agents.
## Tool
Use `sessions_spawn`:
- Starts a sub-agent run (`deliver: false`, global lane: `subagent`)
- Then runs an announce step and posts the announce reply to the requester chat surface
Tool params:
- `task` (required)
- `label?` (optional)
- `timeoutSeconds?` (default `0`; `0` = fire-and-forget)
- `cleanup?` (`delete|keep`, default `delete`)
## Announce
Sub-agents report back via an announce step:
- The announce step runs inside the sub-agent session (not the requester session).
- If the sub-agent replies exactly `ANNOUNCE_SKIP`, nothing is posted.
- Otherwise the announce reply is posted to the requester chat surface via the gateway `send` method.
## Tool Policy (sub-agent tools)
By default, sub-agents get **all tools except session tools**:
- `sessions_list`
- `sessions_history`
- `sessions_send`
- `sessions_spawn`
Override via config:
```json5
{
agent: {
subagents: {
maxConcurrent: 1,
tools: {
// deny wins
deny: ["gateway", "cron"],
// if allow is set, it becomes allow-only (deny still wins)
// allow: ["read", "bash", "process"]
}
}
}
}
```
## Concurrency
Sub-agents use a dedicated in-process queue lane:
- Lane name: `subagent`
- Concurrency: `agent.subagents.maxConcurrent` (default `1`)
## Limitations
- Sub-agent announce is **best-effort**. If the gateway restarts, pending “announce back” work is lost.
- Sub-agents still share the same gateway process resources; treat `maxConcurrent` as a safety valve.
+10 -5
View File
@@ -24,8 +24,10 @@ Status: ready for bot-mode use with grammY (long-polling by default; webhook sup
- The webhook listener currently binds to `0.0.0.0:8787` and serves `POST /telegram-webhook` by default.
- If you need a different public port/host, set `telegram.webhookUrl` to the externally reachable URL and use a reverse proxy to forward to `:8787`.
4) Direct chats: user sends the first message; all subsequent turns land in the shared `main` session (default, no extra config).
5) Groups: add the bot, disable privacy mode (or make it admin) so it can read messages; group threads stay on `telegram:group:<chatId>` and require mention/command by default (override via `telegram.groups`).
6) Optional allowlist: use `telegram.allowFrom` for direct chats by chat id (`123456789` or `telegram:123456789`).
5) Groups: add the bot, disable privacy mode (or make it admin) so it can read messages; group threads stay on `telegram:group:<chatId>`. When `telegram.groups` is set, it becomes a group allowlist (use `"*"` to allow all). Mention/command gating defaults come from `telegram.groups`.
6) Optional allowlist:
- Direct chats: `telegram.allowFrom` by chat id (`123456789`, `telegram:123456789`, or `tg:123456789`; prefixes are case-insensitive).
- Groups: set `telegram.groupPolicy = "allowlist"` and list senders in `telegram.groupAllowFrom` (fallback: explicit `telegram.allowFrom`).
## Capabilities & limits (Bot API)
- Sees only messages sent after it’s added to a chat; no pre-history access.
@@ -37,7 +39,8 @@ Status: ready for bot-mode use with grammY (long-polling by default; webhook sup
- Library: grammY is the only client for send + gateway (fetch fallback removed); grammY throttler is enabled by default to stay under Bot API limits.
- Inbound normalization: maps Bot API updates to `MsgContext` with `Surface: "telegram"`, `ChatType: direct|group`, `SenderName`, `MediaPath`/`MediaType` when attachments arrive, `Timestamp`, and reply-to metadata (`ReplyToId`, `ReplyToBody`, `ReplyToSender`) when the user replies; reply context is appended to `Body` as a `[Replying to ...]` block (includes `id:` when available); groups require @bot mention or a `routing.groupChat.mentionPatterns` match by default (override per chat in config).
- Outbound: text and media (photo/video/audio/document) with optional caption; chunked to limits. Typing cue sent best-effort.
- Config: `TELEGRAM_BOT_TOKEN` env or `telegram.botToken` required; `telegram.groups`, `telegram.allowFrom`, `telegram.mediaMaxMb`, `telegram.replyToMode`, `telegram.proxy`, `telegram.webhookSecret`, `telegram.webhookUrl`, `telegram.webhookPath` supported.
- Config: `TELEGRAM_BOT_TOKEN` env or `telegram.botToken` required; `telegram.groups` (group allowlist + mention defaults), `telegram.allowFrom`, `telegram.groupAllowFrom`, `telegram.groupPolicy`, `telegram.mediaMaxMb`, `telegram.replyToMode`, `telegram.proxy`, `telegram.webhookSecret`, `telegram.webhookUrl`, `telegram.webhookPath` supported.
- Ack reactions are controlled globally via `messages.ackReaction` + `messages.ackReactionScope`.
- Mention gating precedence (most specific wins): `telegram.groups.<chatId>.requireMention` → `telegram.groups."*".requireMention` → default `true`.
Example config:
@@ -48,10 +51,12 @@ Example config:
botToken: "123:abc",
replyToMode: "off",
groups: {
"*": { requireMention: true },
"*": { requireMention: true }, // allow all groups
"123456789": { requireMention: false } // group chat id
},
allowFrom: ["123456789"], // direct chat ids allowed (or "*")
groupPolicy: "allowlist",
groupAllowFrom: ["tg:123456789", "@alice"],
mediaMaxMb: 5,
proxy: "socks5://localhost:9050",
webhookSecret: "mysecret",
@@ -65,7 +70,7 @@ Example config:
## Group etiquette
- Keep privacy mode off if you expect the bot to read all messages; with privacy on, it only sees commands/mentions.
- Make the bot an admin if you need it to send in restricted groups or channels.
- Mention the bot (`@yourbot`) or use a `routing.groupChat.mentionPatterns` trigger; per-group overrides live in `telegram.groups` if you want always-on behavior.
- Mention the bot (`@yourbot`) or use a `routing.groupChat.mentionPatterns` trigger; per-group overrides live in `telegram.groups` if you want always-on behavior. If `telegram.groups` is set, add `"*"` to keep existing allow-all behavior.
## Reply tags
To request a threaded reply, the model can include one tag in its output:
+23 -3
View File
@@ -16,18 +16,28 @@ If `BOOTSTRAP.md` exists, that's your birth certificate. Follow it, figure out w
Before doing anything else:
1. Read `SOUL.md` — this is who you are
2. Read `USER.md` — this is who you're helping
3. Read `memory.md` + today's and yesterday's files in `memory/`
3. Read `memory/YYYY-MM-DD.md` (today + yesterday) for recent context
4. **If in MAIN SESSION** (direct chat with your human): Also read `MEMORY.md`
Don't ask permission. Just do it.
## Memory
You wake up fresh each session. These files are your continuity:
- **Daily notes:** `memory/YYYY-MM-DD.md` (create `memory/` if needed)
- **Long-term:** `memory.md` for durable facts, preferences, open loops
- **Daily notes:** `memory/YYYY-MM-DD.md` (create `memory/` if needed) — raw logs of what happened
- **Long-term:** `MEMORY.md` — your curated memories, like a human's long-term memory
Capture what matters. Decisions, context, things to remember. Skip the secrets unless asked to keep them.
### 🧠 MEMORY.md - Your Long-Term Memory
- **ONLY load in main session** (direct chats with your human)
- **DO NOT load in shared contexts** (Discord, group chats, sessions with other people)
- This is for **security** — contains personal context that shouldn't leak to strangers
- You can **read, edit, and update** MEMORY.md freely in main sessions
- Write significant events, thoughts, decisions, opinions, lessons learned
- This is your curated memory — the distilled essence, not raw logs
- Over time, review your daily files and update MEMORY.md with what's worth keeping
### 📝 Write It Down - No "Mental Notes"!
- **Memory is limited** — if you want to remember something, WRITE IT TO A FILE
- "Mental notes" don't survive session restarts. Files do.
@@ -141,6 +151,16 @@ When you receive a `HEARTBEAT` message, don't just reply `HEARTBEAT_OK` every ti
- Check on projects (git status, etc.)
- Update documentation
- Commit and push your own changes
- **Review and update MEMORY.md** (see below)
### 🔄 Memory Maintenance (During Heartbeats)
Periodically (every few days), use a heartbeat to:
1. Read through recent `memory/YYYY-MM-DD.md` files
2. Identify significant events, lessons, or insights worth keeping long-term
3. Update `MEMORY.md` with distilled learnings
4. Remove outdated info from MEMORY.md that's no longer relevant
Think of it like a human reviewing their journal and updating their mental model. Daily files are raw notes; MEMORY.md is curated wisdom.
The goal: Be helpful without being annoying. Check in a few times a day, do useful background work, but respect quiet time.
+1 -1
View File
@@ -14,7 +14,7 @@ read_when:
Script: `scripts/bench-model.ts`
Usage:
- `source ~/.profile && pnpm tsx scripts/bench-model.ts --runs 10`
- `source ~/.profile && bun scripts/bench-model.ts --runs 10`
- Optional env: `MINIMAX_API_KEY`, `MINIMAX_BASE_URL`, `MINIMAX_MODEL`, `ANTHROPIC_API_KEY`
- Default prompt: “Reply with a single word: ok. No punctuation or extra text.”
+7
View File
@@ -160,6 +160,13 @@ lsof -nP -i :18789
kill -9 <PID>
```
If the gateway is supervised by launchd, killing the PID will just respawn it.
Stop the supervisor instead:
```bash
clawdbot gateway stop
# Or: launchctl bootout gui/$UID/com.clawdbot.gateway
```
**Fix 2: Check embedded gateway**
Ensure the gateway relay was properly bundled. Run `./scripts/package-mac-app.sh` and ensure `bun` is installed.
+1
View File
@@ -52,6 +52,7 @@ Use SSH tunneling or Tailscale to reach the Gateway WS.
- `/think <off|minimal|low|medium|high>`
- `/verbose <on|off>`
- `/elevated <on|off>`
- `/elev <on|off>`
- `/activation <mention|always>`
- `/deliver <on|off>`
- `/new` or `/reset`
+2 -2
View File
@@ -110,6 +110,6 @@ Open:
The Gateway serves static files from `dist/control-ui`. Build them with:
```bash
pnpm ui:install
pnpm ui:build
bun run ui:install
bun run ui:build
```
+1 -1
View File
@@ -91,7 +91,7 @@ Mapping options (summary):
- `hooks.mappings` lets you define `match`, `action`, and templates in config.
- `hooks.transformsDir` + `transform.module` loads a JS/TS module for custom logic.
- Use `match.source` to keep a generic ingest endpoint (payload-driven routing).
- TS transforms require a TS loader (e.g. `tsx`) or precompiled `.js` at runtime.
- TS transforms require a TS loader (e.g. `bun`) or precompiled `.js` at runtime.
- `clawdbot hooks gmail setup` writes `hooks.gmail` config for `clawdbot hooks gmail run`.
## Responses
+6 -1
View File
@@ -49,6 +49,8 @@ WhatsApp requires a real mobile number for verification. VoIP and virtual number
- Direct chats use E.164; groups use group JID.
- **Allowlist**: `whatsapp.allowFrom` enforced for direct chats only.
- If `whatsapp.allowFrom` is empty, default allowlist = self number (self-chat mode).
- **Group policy**: `whatsapp.groupPolicy` controls group handling (`open|disabled|allowlist`).
- `allowlist` uses `whatsapp.groupAllowFrom` (fallback: explicit `whatsapp.allowFrom`).
- **Self-chat mode**: avoids auto read receipts and ignores mention JIDs.
- Read receipts sent for non-self-chat DMs.
@@ -69,6 +71,7 @@ WhatsApp requires a real mobile number for verification. VoIP and virtual number
## Groups
- Groups map to `whatsapp:group:<jid>` sessions.
- Group policy: `whatsapp.groupPolicy = open|disabled|allowlist` (default `open`).
- Activation modes:
- `mention` (default): requires @mention or regex match.
- `always`: always triggers.
@@ -118,7 +121,9 @@ WhatsApp requires a real mobile number for verification. VoIP and virtual number
## Config quick map
- `whatsapp.allowFrom` (DM allowlist).
- `whatsapp.groups` (group mention gating defaults/overrides)
- `whatsapp.groupAllowFrom` (group sender allowlist).
- `whatsapp.groupPolicy` (group policy).
- `whatsapp.groups` (group allowlist + mention gating defaults; use `"*"` to allow all)
- `routing.groupChat.mentionPatterns`
- `routing.groupChat.historyLimit`
- `messages.messagePrefix` (inbound prefix)
+21 -19
View File
@@ -44,19 +44,20 @@
"LICENSE"
],
"scripts": {
"dev": "tsx src/entry.ts",
"docs:list": "tsx scripts/docs-list.ts",
"dev": "bun src/entry.ts",
"postinstall": "node scripts/postinstall.js",
"docs:list": "bun scripts/docs-list.ts",
"docs:dev": "cd docs && mint dev",
"docs:build": "cd docs && pnpm dlx mint broken-links",
"build": "tsc -p tsconfig.json && tsx scripts/canvas-a2ui-copy.ts",
"release:check": "tsx scripts/release-check.ts",
"ui:install": "pnpm -C ui install",
"ui:dev": "pnpm -C ui dev",
"ui:build": "pnpm -C ui build",
"start": "tsx src/entry.ts",
"clawdbot": "tsx src/entry.ts",
"gateway:watch": "tsx watch --clear-screen=false --include 'src/**/*.ts' src/entry.ts gateway --force",
"clawdbot:rpc": "tsx src/entry.ts agent --mode rpc --json",
"build": "tsc -p tsconfig.json && bun scripts/canvas-a2ui-copy.ts",
"release:check": "bun scripts/release-check.ts",
"ui:install": "node scripts/ui.js install",
"ui:dev": "node scripts/ui.js dev",
"ui:build": "node scripts/ui.js build",
"start": "bun src/entry.ts",
"clawdbot": "bun src/entry.ts",
"gateway:watch": "bun --watch src/entry.ts gateway --force",
"clawdbot:rpc": "bun src/entry.ts agent --mode rpc --json",
"lint": "biome check src test && oxlint --type-aware src test --ignore-pattern src/canvas-host/a2ui/a2ui.bundle.js",
"lint:swift": "swiftlint lint --config .swiftlint.yml && (cd apps/ios && swiftlint lint --config .swiftlint.yml)",
"lint:fix": "biome check --write --unsafe src && biome format --write src",
@@ -64,12 +65,12 @@
"format:swift": "swiftformat --lint --config .swiftformat apps/macos/Sources apps/ios/Sources apps/shared/ClawdbotKit/Sources",
"format:fix": "biome format src --write",
"test": "vitest",
"test:force": "tsx scripts/test-force.ts",
"test:force": "bun scripts/test-force.ts",
"test:coverage": "vitest run --coverage",
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"test:docker:qr": "bash scripts/e2e/qr-import-docker.sh",
"protocol:gen": "tsx scripts/protocol-gen.ts",
"protocol:gen:swift": "tsx scripts/protocol-gen-swift.ts",
"protocol:gen": "bun scripts/protocol-gen.ts",
"protocol:gen:swift": "bun scripts/protocol-gen-swift.ts",
"protocol:check": "pnpm protocol:gen && pnpm protocol:gen:swift && git diff --exit-code -- dist/protocol.schema.json apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift",
"canvas:a2ui:bundle": "bash scripts/bundle-a2ui.sh"
},
@@ -84,10 +85,10 @@
"@clack/prompts": "^0.11.0",
"@grammyjs/transformer-throttler": "^1.2.1",
"@homebridge/ciao": "^1.3.4",
"@mariozechner/pi-agent-core": "^0.36.0",
"@mariozechner/pi-ai": "^0.36.0",
"@mariozechner/pi-coding-agent": "^0.36.0",
"@mariozechner/pi-tui": "^0.36.0",
"@mariozechner/pi-agent-core": "^0.37.2",
"@mariozechner/pi-ai": "^0.37.2",
"@mariozechner/pi-coding-agent": "^0.37.2",
"@mariozechner/pi-tui": "^0.37.2",
"@sinclair/typebox": "0.34.46",
"@slack/bolt": "^4.6.0",
"@slack/web-api": "^7.13.0",
@@ -109,6 +110,7 @@
"json5": "^2.2.3",
"long": "5.3.2",
"playwright-core": "1.57.0",
"proper-lockfile": "^4.1.2",
"qrcode-terminal": "^0.12.0",
"sharp": "^0.34.5",
"tslog": "^4.10.2",
@@ -125,6 +127,7 @@
"@types/express": "^5.0.6",
"@types/markdown-it": "^14.1.2",
"@types/node": "^25.0.3",
"@types/proper-lockfile": "^4.1.4",
"@types/qrcode-terminal": "^0.12.2",
"@types/ws": "^8.18.1",
"@vitest/coverage-v8": "^4.0.16",
@@ -139,7 +142,6 @@
"quicktype-core": "^23.2.6",
"rolldown": "1.0.0-beta.58",
"signal-utils": "^0.21.1",
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"vitest": "^4.0.16",
"wireit": "^0.14.12"
+86 -5
View File
@@ -1,8 +1,52 @@
diff --git a/dist/providers/google-shared.js b/dist/providers/google-shared.js
index 7bc0a9f5d6241f191cd607ecb37b3acac8d58267..76166a34784cbc0718d4b9bd1fa6336a6dd394ec 100644
index 7bc0a9f5d6241f191cd607ecb37b3acac8d58267..56866774e47444b5d333961c9b20fce582363124 100644
--- a/dist/providers/google-shared.js
+++ b/dist/providers/google-shared.js
@@ -51,9 +51,19 @@ export function convertMessages(model, context) {
@@ -10,13 +10,27 @@ import { transformMessages } from "./transorm-messages.js";
export function convertMessages(model, context) {
const contents = [];
const transformedMessages = transformMessages(context.messages, model);
+
+ /**
+ * Helper to add content while merging consecutive messages of the same role.
+ * Gemini/Cloud Code Assist requires strict role alternation (user/model/user/model).
+ * Consecutive messages of the same role cause "function call turn" errors.
+ */
+ function addContent(role, parts) {
+ if (parts.length === 0) return;
+ const lastContent = contents[contents.length - 1];
+ if (lastContent?.role === role) {
+ // Merge into existing message of same role
+ lastContent.parts.push(...parts);
+ } else {
+ contents.push({ role, parts });
+ }
+ }
+
for (const msg of transformedMessages) {
if (msg.role === "user") {
if (typeof msg.content === "string") {
- contents.push({
- role: "user",
- parts: [{ text: sanitizeSurrogates(msg.content) }],
- });
+ addContent("user", [{ text: sanitizeSurrogates(msg.content) }]);
}
else {
const parts = msg.content.map((item) => {
@@ -35,10 +49,7 @@ export function convertMessages(model, context) {
const filteredParts = !model.input.includes("image") ? parts.filter((p) => p.text !== undefined) : parts;
if (filteredParts.length === 0)
continue;
- contents.push({
- role: "user",
- parts: filteredParts,
- });
+ addContent("user", filteredParts);
}
}
else if (msg.role === "assistant") {
@@ -51,9 +62,19 @@ export function convertMessages(model, context) {
parts.push({ text: sanitizeSurrogates(block.text) });
}
else if (block.type === "thinking") {
@@ -25,7 +69,7 @@ index 7bc0a9f5d6241f191cd607ecb37b3acac8d58267..76166a34784cbc0718d4b9bd1fa6336a
parts.push({
thought: true,
text: sanitizeSurrogates(block.thinking),
@@ -61,6 +71,7 @@ export function convertMessages(model, context) {
@@ -61,6 +82,7 @@ export function convertMessages(model, context) {
});
}
else {
@@ -33,7 +77,44 @@ index 7bc0a9f5d6241f191cd607ecb37b3acac8d58267..76166a34784cbc0718d4b9bd1fa6336a
parts.push({
text: `<thinking>\n${sanitizeSurrogates(block.thinking)}\n</thinking>`,
});
@@ -146,6 +157,77 @@ export function convertMessages(model, context) {
@@ -85,10 +107,7 @@ export function convertMessages(model, context) {
}
if (parts.length === 0)
continue;
- contents.push({
- role: "model",
- parts,
- });
+ addContent("model", parts);
}
else if (msg.role === "toolResult") {
// Extract text and image content
@@ -125,27 +144,94 @@ export function convertMessages(model, context) {
}
// Cloud Code Assist API requires all function responses to be in a single user turn.
// Check if the last content is already a user turn with function responses and merge.
+ // Use addContent for proper role alternation handling.
const lastContent = contents[contents.length - 1];
if (lastContent?.role === "user" && lastContent.parts?.some((p) => p.functionResponse)) {
lastContent.parts.push(functionResponsePart);
}
else {
- contents.push({
- role: "user",
- parts: [functionResponsePart],
- });
+ addContent("user", [functionResponsePart]);
}
// For older models, add images in a separate user message
+ // Note: This may create consecutive user messages, but addContent will merge them
if (hasImages && !supportsMultimodalFunctionResponse) {
- contents.push({
- role: "user",
- parts: [{ text: "Tool result image:" }, ...imageParts],
- });
+ addContent("user", [{ text: "Tool result image:" }, ...imageParts]);
}
}
}
return contents;
}
@@ -111,7 +192,7 @@ index 7bc0a9f5d6241f191cd607ecb37b3acac8d58267..76166a34784cbc0718d4b9bd1fa6336a
/**
* Convert tools to Gemini function declarations format.
*/
@@ -157,7 +239,7 @@ export function convertTools(tools) {
@@ -157,7 +243,7 @@ export function convertTools(tools) {
functionDeclarations: tools.map((tool) => ({
name: tool.name,
description: tool.description,
@@ -1,17 +0,0 @@
diff --git a/dist/config.js b/dist/config.js
index 7caa66d2676933b102431ec8d92c571eb9d6d82c..77103b9d9573e56c26014c8c7c918e1f853afcdc 100644
--- a/dist/config.js
+++ b/dist/config.js
@@ -10,8 +10,11 @@ const __dirname = dirname(__filename);
/**
* Detect if we're running as a Bun compiled binary.
* Bun binaries have import.meta.url containing "$bunfs", "~BUN", or "%7EBUN" (Bun's virtual filesystem path)
+ * Some packaging workflows keep import.meta.url as a file:// path, so fall back to execPath next to package.json.
*/
-export const isBunBinary = import.meta.url.includes("$bunfs") || import.meta.url.includes("~BUN") || import.meta.url.includes("%7EBUN");
+const bunBinaryByUrl = import.meta.url.includes("$bunfs") || import.meta.url.includes("~BUN") || import.meta.url.includes("%7EBUN");
+const bunBinaryByExecPath = existsSync(join(dirname(process.execPath), "package.json"));
+export const isBunBinary = bunBinaryByUrl || bunBinaryByExecPath;
// =============================================================================
// Package Asset Paths (shipped with executable)
// =============================================================================
+49 -30
View File
@@ -9,7 +9,7 @@ overrides:
patchedDependencies:
'@mariozechner/pi-ai':
hash: 628fb051b6f4886984a846a5ee7aa0a571c3360d35b8d114e4684e5edcd100c5
hash: b49275c3e2023970d8248ababef6df60e093e58a3ba3127c2ba4de1df387d06a
path: patches/@mariozechner__pi-ai.patch
qrcode-terminal:
hash: ed82029850dbdf551f5df1de320945af52b8ea8500cc7bd4f39258e7a3d92e12
@@ -29,17 +29,17 @@ importers:
specifier: ^1.3.4
version: 1.3.4
'@mariozechner/pi-agent-core':
specifier: ^0.36.0
version: 0.36.0(ws@8.19.0)(zod@4.3.5)
specifier: ^0.37.2
version: 0.37.2(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-ai':
specifier: ^0.36.0
version: 0.36.0(patch_hash=628fb051b6f4886984a846a5ee7aa0a571c3360d35b8d114e4684e5edcd100c5)(ws@8.19.0)(zod@4.3.5)
specifier: ^0.37.2
version: 0.37.2(patch_hash=b49275c3e2023970d8248ababef6df60e093e58a3ba3127c2ba4de1df387d06a)(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-coding-agent':
specifier: ^0.36.0
version: 0.36.0(ws@8.19.0)(zod@4.3.5)
specifier: ^0.37.2
version: 0.37.2(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-tui':
specifier: ^0.36.0
version: 0.36.0
specifier: ^0.37.2
version: 0.37.2
'@sinclair/typebox':
specifier: 0.34.46
version: 0.34.46
@@ -103,6 +103,9 @@ importers:
playwright-core:
specifier: 1.57.0
version: 1.57.0
proper-lockfile:
specifier: ^4.1.2
version: 4.1.2
qrcode-terminal:
specifier: ^0.12.0
version: 0.12.0(patch_hash=ed82029850dbdf551f5df1de320945af52b8ea8500cc7bd4f39258e7a3d92e12)
@@ -146,6 +149,9 @@ importers:
'@types/node':
specifier: ^25.0.3
version: 25.0.3
'@types/proper-lockfile':
specifier: ^4.1.4
version: 4.1.4
'@types/qrcode-terminal':
specifier: ^0.12.2
version: 0.12.2
@@ -188,9 +194,6 @@ importers:
signal-utils:
specifier: ^0.21.1
version: 0.21.1(signal-polyfill@0.2.2)
tsx:
specifier: ^4.21.0
version: 4.21.0
typescript:
specifier: ^5.9.3
version: 5.9.3
@@ -804,22 +807,22 @@ packages:
peerDependencies:
lit: ^3.3.1
'@mariozechner/pi-agent-core@0.36.0':
resolution: {integrity: sha512-86BI1/j/MLxQHSWRXVLz8+NuSmDvLQebNb40+lFDI9XI9YBh8+r5fkYgU43u4j2TvANZ7iW6SFFnhWhzy8y6dg==}
'@mariozechner/pi-agent-core@0.37.2':
resolution: {integrity: sha512-GAN1lDVmlY1yH/FCfvpH29f2WBoqqMQkda7zKthOJO9l8tagxnlCWtq078CjzUGYlTDhKSf388XlOuDByBGYLA==}
engines: {node: '>=20.0.0'}
'@mariozechner/pi-ai@0.36.0':
resolution: {integrity: sha512-xkzTgvdMzAZ/L/TgMH8z9Zi+aH0EWc54l5ygiafwvCgDk7xvfbylQG6pa9yn5zEn9T4NF9byJNk+nMHnycZvMQ==}
'@mariozechner/pi-ai@0.37.2':
resolution: {integrity: sha512-IhhvlPrgkdrlbS7QnV+qJPmlzKyae/aI1kenclG18/dXCypxUU50OuzGoVwrXvXw/RIHRwodhd7w4IH38Z7W4Q==}
engines: {node: '>=20.0.0'}
hasBin: true
'@mariozechner/pi-coding-agent@0.36.0':
resolution: {integrity: sha512-lKdpuGE0yVs/96GnDhrPLEEFhRteHRtnkfX04KIBpcsEXXg2vyAlpxtjtZ9nlhYqLLIY7qJRkeyjbhcFFfbAAA==}
'@mariozechner/pi-coding-agent@0.37.2':
resolution: {integrity: sha512-wRFqcyY76h4mONO1si2oAn9WVKnhmVV28dPHjQXVPrl7uSwMCLn+Fcde/nmbL29pYfiU1il4GmUR+iSyoxBUVQ==}
engines: {node: '>=20.0.0'}
hasBin: true
'@mariozechner/pi-tui@0.36.0':
resolution: {integrity: sha512-4n+nmTd36q0AVCbqWmjtTHTjIEwlGayKKhc+4QbpN9U3Z9jyQQa8Za1P2OHRmi6Jeu+ISuf4VBDvgmgCaxPZYg==}
'@mariozechner/pi-tui@0.37.2':
resolution: {integrity: sha512-XNV+jEeWJxQ8U3r5njRotVs6DnEIunkLHSA4nnF4OaRRgrcsafD8M4Pm/3RywSucclVK8P7+KoGiBB2Lokkmuw==}
engines: {node: '>=20.0.0'}
'@mistralai/mistralai@1.10.0':
@@ -1272,6 +1275,9 @@ packages:
'@types/node@25.0.3':
resolution: {integrity: sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==}
'@types/proper-lockfile@4.1.4':
resolution: {integrity: sha512-uo2ABllncSqg9F1D4nugVl9v93RmjxF6LJzQLMLDdPaXCUIDPeOJ21Gbqi43xNKzBi/WQ0Q0dICqufzQbMjipQ==}
'@types/qrcode-terminal@0.12.2':
resolution: {integrity: sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q==}
@@ -1284,6 +1290,9 @@ packages:
'@types/retry@0.12.0':
resolution: {integrity: sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==}
'@types/retry@0.12.5':
resolution: {integrity: sha512-3xSjTp3v03X/lSQLkczaN9UIEwJMoMCA1+Nb5HfbJEQWogdeQIyVtTvxPXDQjZ5zws8rFQfVfRdz03ARihPJgw==}
'@types/send@1.2.1':
resolution: {integrity: sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==}
@@ -3588,10 +3597,10 @@ snapshots:
transitivePeerDependencies:
- tailwindcss
'@mariozechner/pi-agent-core@0.36.0(ws@8.19.0)(zod@4.3.5)':
'@mariozechner/pi-agent-core@0.37.2(ws@8.19.0)(zod@4.3.5)':
dependencies:
'@mariozechner/pi-ai': 0.36.0(patch_hash=628fb051b6f4886984a846a5ee7aa0a571c3360d35b8d114e4684e5edcd100c5)(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-tui': 0.36.0
'@mariozechner/pi-ai': 0.37.2(patch_hash=b49275c3e2023970d8248ababef6df60e093e58a3ba3127c2ba4de1df387d06a)(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-tui': 0.37.2
transitivePeerDependencies:
- '@modelcontextprotocol/sdk'
- bufferutil
@@ -3600,7 +3609,7 @@ snapshots:
- ws
- zod
'@mariozechner/pi-ai@0.36.0(patch_hash=628fb051b6f4886984a846a5ee7aa0a571c3360d35b8d114e4684e5edcd100c5)(ws@8.19.0)(zod@4.3.5)':
'@mariozechner/pi-ai@0.37.2(patch_hash=b49275c3e2023970d8248ababef6df60e093e58a3ba3127c2ba4de1df387d06a)(ws@8.19.0)(zod@4.3.5)':
dependencies:
'@anthropic-ai/sdk': 0.71.2(zod@4.3.5)
'@google/genai': 1.34.0
@@ -3620,12 +3629,12 @@ snapshots:
- ws
- zod
'@mariozechner/pi-coding-agent@0.36.0(ws@8.19.0)(zod@4.3.5)':
'@mariozechner/pi-coding-agent@0.37.2(ws@8.19.0)(zod@4.3.5)':
dependencies:
'@crosscopy/clipboard': 0.2.8
'@mariozechner/pi-agent-core': 0.36.0(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-ai': 0.36.0(patch_hash=628fb051b6f4886984a846a5ee7aa0a571c3360d35b8d114e4684e5edcd100c5)(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-tui': 0.36.0
'@mariozechner/pi-agent-core': 0.37.2(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-ai': 0.37.2(patch_hash=b49275c3e2023970d8248ababef6df60e093e58a3ba3127c2ba4de1df387d06a)(ws@8.19.0)(zod@4.3.5)
'@mariozechner/pi-tui': 0.37.2
chalk: 5.6.2
cli-highlight: 2.1.11
diff: 8.0.2
@@ -3633,6 +3642,7 @@ snapshots:
glob: 11.1.0
jiti: 2.6.1
marked: 15.0.12
proper-lockfile: 4.1.2
sharp: 0.34.5
transitivePeerDependencies:
- '@modelcontextprotocol/sdk'
@@ -3642,7 +3652,7 @@ snapshots:
- ws
- zod
'@mariozechner/pi-tui@0.36.0':
'@mariozechner/pi-tui@0.37.2':
dependencies:
'@types/mime-types': 2.1.4
chalk: 5.6.2
@@ -4038,6 +4048,10 @@ snapshots:
dependencies:
undici-types: 7.16.0
'@types/proper-lockfile@4.1.4':
dependencies:
'@types/retry': 0.12.5
'@types/qrcode-terminal@0.12.2': {}
'@types/qs@6.14.0': {}
@@ -4046,6 +4060,8 @@ snapshots:
'@types/retry@0.12.0': {}
'@types/retry@0.12.5': {}
'@types/send@1.2.1':
dependencies:
'@types/node': 25.0.3
@@ -4773,6 +4789,7 @@ snapshots:
get-tsconfig@4.13.0:
dependencies:
resolve-pkg-maps: 1.0.0
optional: true
glob-parent@5.1.2:
dependencies:
@@ -5534,7 +5551,8 @@ snapshots:
require-from-string@2.0.2: {}
resolve-pkg-maps@1.0.0: {}
resolve-pkg-maps@1.0.0:
optional: true
retry@0.12.0: {}
@@ -5858,6 +5876,7 @@ snapshots:
get-tsconfig: 4.13.0
optionalDependencies:
fsevents: 2.3.3
optional: true
type-is@2.0.1:
dependencies:
Regular → Executable
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env tsx
#!/usr/bin/env bun
import { readdirSync, readFileSync } from 'node:fs';
import { join, relative } from 'node:path';
+2 -2
View File
@@ -146,8 +146,8 @@ else
fi
if [[ "${SKIP_UI_BUILD:-0}" != "1" ]]; then
echo "🖥 Building Control UI (pnpm ui:build)"
(cd "$ROOT_DIR" && pnpm ui:build)
echo "🖥 Building Control UI (ui:build)"
(cd "$ROOT_DIR" && node scripts/ui.js build)
else
echo "🖥 Skipping Control UI build (SKIP_UI_BUILD=1)"
fi
+110
View File
@@ -0,0 +1,110 @@
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
function isBunInstall() {
const ua = process.env.npm_config_user_agent ?? "";
return ua.includes("bun/");
}
function getRepoRoot() {
const here = path.dirname(fileURLToPath(import.meta.url));
return path.resolve(here, "..");
}
function run(cmd, args, opts = {}) {
const res = spawnSync(cmd, args, { stdio: "inherit", ...opts });
if (typeof res.status === "number") return res.status;
return 1;
}
function applyPatchIfNeeded(opts) {
const patchPath = path.resolve(opts.patchPath);
if (!fs.existsSync(patchPath)) {
throw new Error(`missing patch: ${patchPath}`);
}
let targetDir = path.resolve(opts.targetDir);
if (!fs.existsSync(targetDir) || !fs.statSync(targetDir).isDirectory()) {
console.warn(`[postinstall] skip missing target: ${targetDir}`);
return;
}
// Resolve symlinks to avoid "beyond a symbolic link" errors from git apply
// (bun/pnpm use symlinks in node_modules)
targetDir = fs.realpathSync(targetDir);
const gitArgsBase = ["apply", "--unsafe-paths", "--whitespace=nowarn"];
const reverseCheck = [
...gitArgsBase,
"--reverse",
"--check",
"--directory",
targetDir,
patchPath,
];
const forwardCheck = [
...gitArgsBase,
"--check",
"--directory",
targetDir,
patchPath,
];
const apply = [...gitArgsBase, "--directory", targetDir, patchPath];
// Already applied?
if (run("git", reverseCheck, { stdio: "ignore" }) === 0) {
return;
}
if (run("git", forwardCheck, { stdio: "ignore" }) !== 0) {
throw new Error(`patch does not apply cleanly: ${path.basename(patchPath)}`);
}
const status = run("git", apply);
if (status !== 0) {
throw new Error(`failed applying patch: ${path.basename(patchPath)}`);
}
}
function extractPackageName(key) {
if (key.startsWith("@")) {
const idx = key.indexOf("@", 1);
if (idx === -1) return key;
return key.slice(0, idx);
}
const idx = key.lastIndexOf("@");
if (idx <= 0) return key;
return key.slice(0, idx);
}
function main() {
if (!isBunInstall()) return;
const repoRoot = getRepoRoot();
process.chdir(repoRoot);
const pkgPath = path.join(repoRoot, "package.json");
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
const patched = pkg?.pnpm?.patchedDependencies ?? {};
// Bun does not support pnpm.patchedDependencies. Apply these patch files to
// node_modules packages as a best-effort compatibility layer.
for (const [key, relPatchPath] of Object.entries(patched)) {
if (typeof relPatchPath !== "string" || !relPatchPath.trim()) continue;
const pkgName = extractPackageName(String(key));
if (!pkgName) continue;
applyPatchIfNeeded({
targetDir: path.join("node_modules", ...pkgName.split("/")),
patchPath: relPatchPath,
});
}
}
try {
main();
} catch (err) {
console.error(String(err));
process.exit(1);
}
Regular → Executable
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env tsx
#!/usr/bin/env bun
import { execSync } from "node:child_process";
Regular → Executable
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env tsx
#!/usr/bin/env bun
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "..");
const uiDir = path.join(repoRoot, "ui");
function usage() {
// keep this tiny; it's invoked from npm scripts too
process.stderr.write(
"Usage: node scripts/ui.js <install|dev|build|test> [...args]\n",
);
}
function which(cmd) {
try {
const key = process.platform === "win32" ? "Path" : "PATH";
const paths = (process.env[key] ?? process.env.PATH ?? "")
.split(path.delimiter)
.filter(Boolean);
const extensions =
process.platform === "win32"
? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM")
.split(";")
.filter(Boolean)
: [""];
for (const entry of paths) {
for (const ext of extensions) {
const candidate = path.join(entry, process.platform === "win32" ? `${cmd}${ext}` : cmd);
try {
if (fs.existsSync(candidate)) return candidate;
} catch {
// ignore
}
}
}
} catch {
// ignore
}
return null;
}
function resolveRunner() {
const bun = which("bun");
if (bun) return { cmd: bun, kind: "bun" };
const pnpm = which("pnpm");
if (pnpm) return { cmd: pnpm, kind: "pnpm" };
return null;
}
function run(cmd, args) {
const child = spawn(cmd, args, {
cwd: uiDir,
stdio: "inherit",
env: process.env,
});
child.on("exit", (code, signal) => {
if (signal) process.exit(1);
process.exit(code ?? 1);
});
}
const [, , action, ...rest] = process.argv;
if (!action) {
usage();
process.exit(2);
}
const runner = resolveRunner();
if (!runner) {
process.stderr.write(
"Missing UI runner: install bun or pnpm, then retry.\n",
);
process.exit(1);
}
const script =
action === "install"
? null
: action === "dev"
? "dev"
: action === "build"
? "build"
: action === "test"
? "test"
: null;
if (action !== "install" && !script) {
usage();
process.exit(2);
}
if (runner.kind === "bun") {
if (action === "install") run(runner.cmd, ["install", ...rest]);
else run(runner.cmd, ["run", script, ...rest]);
} else {
if (action === "install") run(runner.cmd, ["install", ...rest]);
else run(runner.cmd, ["run", script, ...rest]);
}
+1
View File
@@ -26,4 +26,5 @@ API key
Notes
- Resolutions: `1K` (default), `2K`, `4K`.
- Use timestamps in filenames: `yyyy-mm-dd-hh-mm-ss-name.png`.
- The script prints a `MEDIA:` line for Clawdbot to auto-attach on supported chat providers.
- Do not read the image back; report the saved path only.
@@ -154,6 +154,8 @@ def main():
if image_saved:
full_path = output_path.resolve()
print(f"\nImage saved: {full_path}")
# Clawdbot parses MEDIA tokens and will attach the file on supported providers.
print(f"MEDIA: {full_path}")
else:
print("Error: No image was generated in the response.", file=sys.stderr)
sys.exit(1)
+94 -3
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
type AuthProfileStore,
calculateAuthProfileCooldownMs,
resolveAuthProfileOrder,
} from "./auth-profiles.js";
@@ -49,13 +50,20 @@ describe("resolveAuthProfileOrder", () => {
expect(order).toContain("anthropic:default");
});
it("prioritizes last-good profile when no preferred override", () => {
it("does not prioritize lastGood over round-robin ordering", () => {
const order = resolveAuthProfileOrder({
cfg,
store: { ...store, lastGood: { anthropic: "anthropic:work" } },
store: {
...store,
lastGood: { anthropic: "anthropic:work" },
usageStats: {
"anthropic:default": { lastUsed: 100 },
"anthropic:work": { lastUsed: 200 },
},
},
provider: "anthropic",
});
expect(order[0]).toBe("anthropic:work");
expect(order[0]).toBe("anthropic:default");
});
it("uses explicit profiles when order is missing", () => {
@@ -105,4 +113,87 @@ describe("resolveAuthProfileOrder", () => {
});
expect(order).toEqual(["anthropic:oauth", "anthropic:default"]);
});
it("orders by lastUsed when no explicit order exists", () => {
const order = resolveAuthProfileOrder({
store: {
version: 1,
profiles: {
"anthropic:a": {
type: "oauth",
provider: "anthropic",
access: "access-token",
refresh: "refresh-token",
expires: Date.now() + 60_000,
},
"anthropic:b": {
type: "api_key",
provider: "anthropic",
key: "sk-b",
},
"anthropic:c": {
type: "api_key",
provider: "anthropic",
key: "sk-c",
},
},
usageStats: {
"anthropic:a": { lastUsed: 200 },
"anthropic:b": { lastUsed: 100 },
"anthropic:c": { lastUsed: 300 },
},
},
provider: "anthropic",
});
expect(order).toEqual(["anthropic:b", "anthropic:a", "anthropic:c"]);
});
it("pushes cooldown profiles to the end, ordered by cooldown expiry", () => {
const now = Date.now();
const order = resolveAuthProfileOrder({
store: {
version: 1,
profiles: {
"anthropic:ready": {
type: "api_key",
provider: "anthropic",
key: "sk-ready",
},
"anthropic:cool1": {
type: "oauth",
provider: "anthropic",
access: "access-token",
refresh: "refresh-token",
expires: now + 60_000,
},
"anthropic:cool2": {
type: "api_key",
provider: "anthropic",
key: "sk-cool",
},
},
usageStats: {
"anthropic:ready": { lastUsed: 50 },
"anthropic:cool1": { cooldownUntil: now + 5_000 },
"anthropic:cool2": { cooldownUntil: now + 1_000 },
},
},
provider: "anthropic",
});
expect(order).toEqual([
"anthropic:ready",
"anthropic:cool2",
"anthropic:cool1",
]);
});
});
describe("auth profile cooldowns", () => {
it("applies exponential backoff with a 1h cap", () => {
expect(calculateAuthProfileCooldownMs(1)).toBe(60_000);
expect(calculateAuthProfileCooldownMs(2)).toBe(5 * 60_000);
expect(calculateAuthProfileCooldownMs(3)).toBe(25 * 60_000);
expect(calculateAuthProfileCooldownMs(4)).toBe(60 * 60_000);
expect(calculateAuthProfileCooldownMs(5)).toBe(60 * 60_000);
});
});
+269 -36
View File
@@ -6,6 +6,7 @@ import {
type OAuthCredentials,
type OAuthProvider,
} from "@mariozechner/pi-ai";
import lockfile from "proper-lockfile";
import type { ClawdbotConfig } from "../config/config.js";
import { resolveOAuthPath } from "../config/paths.js";
@@ -31,10 +32,19 @@ export type OAuthCredential = OAuthCredentials & {
export type AuthProfileCredential = ApiKeyCredential | OAuthCredential;
/** Per-profile usage statistics for round-robin and cooldown tracking */
export type ProfileUsageStats = {
lastUsed?: number;
cooldownUntil?: number;
errorCount?: number;
};
export type AuthProfileStore = {
version: number;
profiles: Record<string, AuthProfileCredential>;
lastGood?: Record<string, string>;
/** Usage statistics per profile for round-robin rotation */
usageStats?: Record<string, ProfileUsageStats>;
};
type LegacyAuthStore = Record<string, AuthProfileCredential>;
@@ -68,6 +78,83 @@ function saveJsonFile(pathname: string, data: unknown) {
fs.chmodSync(pathname, 0o600);
}
function ensureAuthStoreFile(pathname: string) {
if (fs.existsSync(pathname)) return;
const payload: AuthProfileStore = {
version: AUTH_STORE_VERSION,
profiles: {},
};
saveJsonFile(pathname, payload);
}
function buildOAuthApiKey(
provider: OAuthProvider,
credentials: OAuthCredentials,
): string {
const needsProjectId =
provider === "google-gemini-cli" || provider === "google-antigravity";
return needsProjectId
? JSON.stringify({
token: credentials.access,
projectId: credentials.projectId,
})
: credentials.access;
}
async function refreshOAuthTokenWithLock(params: {
profileId: string;
provider: OAuthProvider;
}): Promise<{ apiKey: string; newCredentials: OAuthCredentials } | null> {
const authPath = resolveAuthStorePath();
ensureAuthStoreFile(authPath);
let release: (() => Promise<void>) | undefined;
try {
release = await lockfile.lock(authPath, {
retries: {
retries: 10,
factor: 2,
minTimeout: 100,
maxTimeout: 10_000,
randomize: true,
},
stale: 30_000,
});
const store = ensureAuthProfileStore();
const cred = store.profiles[params.profileId];
if (!cred || cred.type !== "oauth") return null;
if (Date.now() < cred.expires) {
return {
apiKey: buildOAuthApiKey(cred.provider, cred),
newCredentials: cred,
};
}
const oauthCreds: Record<string, OAuthCredentials> = {
[cred.provider]: cred,
};
const result = await getOAuthApiKey(cred.provider, oauthCreds);
if (!result) return null;
store.profiles[params.profileId] = {
...cred,
...result.newCredentials,
type: "oauth",
};
saveAuthProfileStore(store);
return result;
} finally {
if (release) {
try {
await release();
} catch {
// ignore unlock errors
}
}
}
}
function coerceLegacyStore(raw: unknown): LegacyAuthStore | null {
if (!raw || typeof raw !== "object") return null;
const record = raw as Record<string, unknown>;
@@ -105,6 +192,10 @@ function coerceAuthStore(raw: unknown): AuthProfileStore | null {
record.lastGood && typeof record.lastGood === "object"
? (record.lastGood as Record<string, string>)
: undefined,
usageStats:
record.usageStats && typeof record.usageStats === "object"
? (record.usageStats as Record<string, ProfileUsageStats>)
: undefined,
};
}
@@ -222,6 +313,7 @@ export function saveAuthProfileStore(store: AuthProfileStore): void {
version: AUTH_STORE_VERSION,
profiles: store.profiles,
lastGood: store.lastGood ?? undefined,
usageStats: store.usageStats ?? undefined,
} satisfies AuthProfileStore;
saveJsonFile(authPath, payload);
}
@@ -244,6 +336,90 @@ export function listProfilesForProvider(
.map(([id]) => id);
}
/**
* Check if a profile is currently in cooldown (due to rate limiting or errors).
*/
export function isProfileInCooldown(
store: AuthProfileStore,
profileId: string,
): boolean {
const stats = store.usageStats?.[profileId];
if (!stats?.cooldownUntil) return false;
return Date.now() < stats.cooldownUntil;
}
/**
* Mark a profile as successfully used. Resets error count and updates lastUsed.
*/
export function markAuthProfileUsed(params: {
store: AuthProfileStore;
profileId: string;
}): void {
const { store, profileId } = params;
if (!store.profiles[profileId]) return;
store.usageStats = store.usageStats ?? {};
store.usageStats[profileId] = {
...store.usageStats[profileId],
lastUsed: Date.now(),
errorCount: 0,
cooldownUntil: undefined,
};
saveAuthProfileStore(store);
}
export function calculateAuthProfileCooldownMs(errorCount: number): number {
const normalized = Math.max(1, errorCount);
return Math.min(
60 * 60 * 1000, // 1 hour max
60 * 1000 * 5 ** Math.min(normalized - 1, 3),
);
}
/**
* Mark a profile as failed/rate-limited. Applies exponential backoff cooldown.
* Cooldown times: 1min, 5min, 25min, max 1 hour.
*/
export function markAuthProfileCooldown(params: {
store: AuthProfileStore;
profileId: string;
}): void {
const { store, profileId } = params;
if (!store.profiles[profileId]) return;
store.usageStats = store.usageStats ?? {};
const existing = store.usageStats[profileId] ?? {};
const errorCount = (existing.errorCount ?? 0) + 1;
// Exponential backoff: 1min, 5min, 25min, capped at 1h
const backoffMs = calculateAuthProfileCooldownMs(errorCount);
store.usageStats[profileId] = {
...existing,
errorCount,
cooldownUntil: Date.now() + backoffMs,
};
saveAuthProfileStore(store);
}
/**
* Clear cooldown for a profile (e.g., manual reset).
*/
export function clearAuthProfileCooldown(params: {
store: AuthProfileStore;
profileId: string;
}): void {
const { store, profileId } = params;
if (!store.usageStats?.[profileId]) return;
store.usageStats[profileId] = {
...store.usageStats[profileId],
errorCount: 0,
cooldownUntil: undefined,
};
saveAuthProfileStore(store);
}
export function resolveAuthProfileOrder(params: {
cfg?: ClawdbotConfig;
store: AuthProfileStore;
@@ -257,19 +433,14 @@ export function resolveAuthProfileOrder(params: {
.filter(([, profile]) => profile.provider === provider)
.map(([profileId]) => profileId)
: [];
const lastGood = store.lastGood?.[provider];
const baseOrder =
configuredOrder ??
(explicitProfiles.length > 0
? explicitProfiles
: listProfilesForProvider(store, provider));
if (baseOrder.length === 0) return [];
const order =
configuredOrder && configuredOrder.length > 0
? baseOrder
: orderProfilesByMode(baseOrder, store);
const filtered = order.filter((profileId) => {
const filtered = baseOrder.filter((profileId) => {
const cred = store.profiles[profileId];
return cred ? cred.provider === provider : true;
});
@@ -277,35 +448,79 @@ export function resolveAuthProfileOrder(params: {
for (const entry of filtered) {
if (!deduped.includes(entry)) deduped.push(entry);
}
if (preferredProfile && deduped.includes(preferredProfile)) {
const rest = deduped.filter((entry) => entry !== preferredProfile);
if (lastGood && rest.includes(lastGood)) {
// If user specified explicit order in config, respect it exactly
if (configuredOrder && configuredOrder.length > 0) {
// Still put preferredProfile first if specified
if (preferredProfile && deduped.includes(preferredProfile)) {
return [
preferredProfile,
lastGood,
...rest.filter((entry) => entry !== lastGood),
...deduped.filter((e) => e !== preferredProfile),
];
}
return [preferredProfile, ...rest];
return deduped;
}
if (lastGood && deduped.includes(lastGood)) {
return [lastGood, ...deduped.filter((entry) => entry !== lastGood)];
// Otherwise, use round-robin: sort by lastUsed (oldest first)
// preferredProfile goes first if specified (for explicit user choice)
// lastGood is NOT prioritized - that would defeat round-robin
const sorted = orderProfilesByMode(deduped, store);
if (preferredProfile && sorted.includes(preferredProfile)) {
return [preferredProfile, ...sorted.filter((e) => e !== preferredProfile)];
}
return deduped;
return sorted;
}
function orderProfilesByMode(
order: string[],
store: AuthProfileStore,
): string[] {
const scored = order.map((profileId) => {
const now = Date.now();
// Partition into available and in-cooldown
const available: string[] = [];
const inCooldown: string[] = [];
for (const profileId of order) {
if (isProfileInCooldown(store, profileId)) {
inCooldown.push(profileId);
} else {
available.push(profileId);
}
}
// Sort available profiles by lastUsed (oldest first = round-robin)
// Then by type (oauth preferred over api_key)
const scored = available.map((profileId) => {
const type = store.profiles[profileId]?.type;
const score = type === "oauth" ? 0 : type === "api_key" ? 1 : 2;
return { profileId, score };
const typeScore = type === "oauth" ? 0 : type === "api_key" ? 1 : 2;
const lastUsed = store.usageStats?.[profileId]?.lastUsed ?? 0;
return { profileId, typeScore, lastUsed };
});
return scored
.sort((a, b) => a.score - b.score)
// Primary sort: lastUsed (oldest first for round-robin)
// Secondary sort: type preference (oauth > api_key)
const sorted = scored
.sort((a, b) => {
// First by lastUsed (oldest first)
if (a.lastUsed !== b.lastUsed) return a.lastUsed - b.lastUsed;
// Then by type
return a.typeScore - b.typeScore;
})
.map((entry) => entry.profileId);
// Append cooldown profiles at the end (sorted by cooldown expiry, soonest first)
const cooldownSorted = inCooldown
.map((profileId) => ({
profileId,
cooldownUntil: store.usageStats?.[profileId]?.cooldownUntil ?? now,
}))
.sort((a, b) => a.cooldownUntil - b.cooldownUntil)
.map((entry) => entry.profileId);
return [...sorted, ...cooldownSorted];
}
export async function resolveApiKeyForProfile(params: {
@@ -323,23 +538,41 @@ export async function resolveApiKeyForProfile(params: {
if (cred.type === "api_key") {
return { apiKey: cred.key, provider: cred.provider, email: cred.email };
}
if (Date.now() < cred.expires) {
return {
apiKey: buildOAuthApiKey(cred.provider, cred),
provider: cred.provider,
email: cred.email,
};
}
const oauthCreds: Record<string, OAuthCredentials> = {
[cred.provider]: cred,
};
const result = await getOAuthApiKey(cred.provider, oauthCreds);
if (!result) return null;
store.profiles[profileId] = {
...cred,
...result.newCredentials,
type: "oauth",
};
saveAuthProfileStore(store);
return {
apiKey: result.apiKey,
provider: cred.provider,
email: cred.email,
};
try {
const result = await refreshOAuthTokenWithLock({
profileId,
provider: cred.provider,
});
if (!result) return null;
return {
apiKey: result.apiKey,
provider: cred.provider,
email: cred.email,
};
} catch (error) {
const refreshedStore = ensureAuthProfileStore();
const refreshed = refreshedStore.profiles[profileId];
if (refreshed?.type === "oauth" && Date.now() < refreshed.expires) {
return {
apiKey: buildOAuthApiKey(refreshed.provider, refreshed),
provider: refreshed.provider,
email: refreshed.email ?? cred.email,
};
}
const message = error instanceof Error ? error.message : String(error);
throw new Error(
`OAuth token refresh failed for ${cred.provider}: ${message}. ` +
"Please try again or re-authenticate.",
);
}
}
export function markAuthProfileGood(params: {
+1
View File
@@ -36,6 +36,7 @@ const DEFAULT_MAX_OUTPUT = clampNumber(
150_000,
);
const DEFAULT_PATH =
process.env.PATH ??
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const stringEnum = (
+204
View File
@@ -0,0 +1,204 @@
import { describe, expect, it, vi } from "vitest";
const callGatewayMock = vi.fn();
vi.mock("../gateway/call.js", () => ({
callGateway: (opts: unknown) => callGatewayMock(opts),
}));
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../config/config.js")>();
return {
...actual,
loadConfig: () => ({
session: {
mainKey: "main",
scope: "per-sender",
},
}),
resolveGatewayPort: () => 18789,
};
});
import { createClawdbotTools } from "./clawdbot-tools.js";
describe("subagents", () => {
it("sessions_spawn announces back to the requester group surface", async () => {
callGatewayMock.mockReset();
const calls: Array<{ method?: string; params?: unknown }> = [];
let agentCallCount = 0;
let lastWaitedRunId: string | undefined;
const replyByRunId = new Map<string, string>();
let sendParams: { to?: string; provider?: string; message?: string } = {};
let deletedKey: string | undefined;
callGatewayMock.mockImplementation(async (opts: unknown) => {
const request = opts as { method?: string; params?: unknown };
calls.push(request);
if (request.method === "agent") {
agentCallCount += 1;
const runId = `run-${agentCallCount}`;
const params = request.params as
| { message?: string; sessionKey?: string }
| undefined;
const message = params?.message ?? "";
const reply =
message === "Sub-agent announce step." ? "announce now" : "result";
replyByRunId.set(runId, reply);
return {
runId,
status: "accepted",
acceptedAt: 1000 + agentCallCount,
};
}
if (request.method === "agent.wait") {
const params = request.params as { runId?: string } | undefined;
lastWaitedRunId = params?.runId;
return { runId: params?.runId ?? "run-1", status: "ok" };
}
if (request.method === "chat.history") {
const text =
(lastWaitedRunId && replyByRunId.get(lastWaitedRunId)) ?? "";
return {
messages: [{ role: "assistant", content: [{ type: "text", text }] }],
};
}
if (request.method === "send") {
const params = request.params as
| { to?: string; provider?: string; message?: string }
| undefined;
sendParams = {
to: params?.to,
provider: params?.provider,
message: params?.message,
};
return { messageId: "m-announce" };
}
if (request.method === "sessions.delete") {
const params = request.params as { key?: string } | undefined;
deletedKey = params?.key;
return { ok: true };
}
return {};
});
const tool = createClawdbotTools({
agentSessionKey: "discord:group:req",
agentSurface: "discord",
}).find((candidate) => candidate.name === "sessions_spawn");
if (!tool) throw new Error("missing sessions_spawn tool");
const result = await tool.execute("call1", {
task: "do thing",
timeoutSeconds: 1,
});
expect(result.details).toMatchObject({ status: "ok", reply: "result" });
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise((resolve) => setTimeout(resolve, 0));
const agentCalls = calls.filter((call) => call.method === "agent");
expect(agentCalls).toHaveLength(2);
const first = agentCalls[0]?.params as
| { lane?: string; deliver?: boolean; sessionKey?: string }
| undefined;
expect(first?.lane).toBe("subagent");
expect(first?.deliver).toBe(false);
expect(first?.sessionKey?.startsWith("subagent:")).toBe(true);
expect(sendParams).toMatchObject({
provider: "discord",
to: "channel:req",
message: "announce now",
});
expect(deletedKey?.startsWith("subagent:")).toBe(true);
});
it("sessions_spawn resolves main announce target from sessions.list", async () => {
callGatewayMock.mockReset();
const calls: Array<{ method?: string; params?: unknown }> = [];
let agentCallCount = 0;
let lastWaitedRunId: string | undefined;
const replyByRunId = new Map<string, string>();
let sendParams: { to?: string; provider?: string; message?: string } = {};
callGatewayMock.mockImplementation(async (opts: unknown) => {
const request = opts as { method?: string; params?: unknown };
calls.push(request);
if (request.method === "sessions.list") {
return {
sessions: [
{
key: "main",
lastChannel: "whatsapp",
lastTo: "+123",
},
],
};
}
if (request.method === "agent") {
agentCallCount += 1;
const runId = `run-${agentCallCount}`;
const params = request.params as
| { message?: string; sessionKey?: string }
| undefined;
const message = params?.message ?? "";
const reply =
message === "Sub-agent announce step." ? "hello from sub" : "done";
replyByRunId.set(runId, reply);
return {
runId,
status: "accepted",
acceptedAt: 2000 + agentCallCount,
};
}
if (request.method === "agent.wait") {
const params = request.params as { runId?: string } | undefined;
lastWaitedRunId = params?.runId;
return { runId: params?.runId ?? "run-1", status: "ok" };
}
if (request.method === "chat.history") {
const text =
(lastWaitedRunId && replyByRunId.get(lastWaitedRunId)) ?? "";
return {
messages: [{ role: "assistant", content: [{ type: "text", text }] }],
};
}
if (request.method === "send") {
const params = request.params as
| { to?: string; provider?: string; message?: string }
| undefined;
sendParams = {
to: params?.to,
provider: params?.provider,
message: params?.message,
};
return { messageId: "m1" };
}
if (request.method === "sessions.delete") {
return { ok: true };
}
return {};
});
const tool = createClawdbotTools({
agentSessionKey: "main",
agentSurface: "whatsapp",
}).find((candidate) => candidate.name === "sessions_spawn");
if (!tool) throw new Error("missing sessions_spawn tool");
const result = await tool.execute("call2", {
task: "do thing",
timeoutSeconds: 1,
});
expect(result.details).toMatchObject({ status: "ok", reply: "done" });
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(sendParams).toMatchObject({
provider: "whatsapp",
to: "+123",
message: "hello from sub",
});
});
});
+16 -2
View File
@@ -10,12 +10,14 @@ import { createNodesTool } from "./tools/nodes-tool.js";
import { createSessionsHistoryTool } from "./tools/sessions-history-tool.js";
import { createSessionsListTool } from "./tools/sessions-list-tool.js";
import { createSessionsSendTool } from "./tools/sessions-send-tool.js";
import { createSessionsSpawnTool } from "./tools/sessions-spawn-tool.js";
import { createSlackTool } from "./tools/slack-tool.js";
export function createClawdbotTools(options?: {
browserControlUrl?: string;
agentSessionKey?: string;
agentSurface?: string;
sandboxed?: boolean;
config?: ClawdbotConfig;
}): AnyAgentTool[] {
const imageTool = createImageTool({ config: options?.config });
@@ -27,11 +29,23 @@ export function createClawdbotTools(options?: {
createDiscordTool(),
createSlackTool(),
createGatewayTool(),
createSessionsListTool(),
createSessionsHistoryTool(),
createSessionsListTool({
agentSessionKey: options?.agentSessionKey,
sandboxed: options?.sandboxed,
}),
createSessionsHistoryTool({
agentSessionKey: options?.agentSessionKey,
sandboxed: options?.sandboxed,
}),
createSessionsSendTool({
agentSessionKey: options?.agentSessionKey,
agentSurface: options?.agentSurface,
sandboxed: options?.sandboxed,
}),
createSessionsSpawnTool({
agentSessionKey: options?.agentSessionKey,
agentSurface: options?.agentSurface,
sandboxed: options?.sandboxed,
}),
...(imageTool ? [imageTool] : []),
];
+53 -22
View File
@@ -24,7 +24,11 @@ import {
} from "../process/command-queue.js";
import { resolveUserPath } from "../utils.js";
import { resolveClawdbotAgentDir } from "./agent-paths.js";
import { markAuthProfileGood } from "./auth-profiles.js";
import {
markAuthProfileCooldown,
markAuthProfileGood,
markAuthProfileUsed,
} from "./auth-profiles.js";
import type { BashElevatedDefaults } from "./bash-tools.js";
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from "./defaults.js";
import {
@@ -113,6 +117,7 @@ export type EmbeddedPiCompactResult = {
type EmbeddedPiQueueHandle = {
queueMessage: (text: string) => Promise<void>;
isStreaming: () => boolean;
isCompacting: () => boolean;
abort: () => void;
};
@@ -212,6 +217,7 @@ export function queueEmbeddedPiMessage(
const handle = ACTIVE_EMBEDDED_RUNS.get(sessionId);
if (!handle) return false;
if (!handle.isStreaming()) return false;
if (handle.isCompacting()) return false;
void handle.queueMessage(text);
return true;
}
@@ -806,25 +812,13 @@ export async function runEmbeddedPiAgent(params: {
session.agent.replaceMessages(prior);
}
let aborted = Boolean(params.abortSignal?.aborted);
const abortRun = () => {
let timedOut = false;
const abortRun = (isTimeout = false) => {
aborted = true;
if (isTimeout) timedOut = true;
void session.abort();
};
const queueHandle: EmbeddedPiQueueHandle = {
queueMessage: async (text: string) => {
await session.steer(text);
},
isStreaming: () => session.isStreaming,
abort: abortRun,
};
ACTIVE_EMBEDDED_RUNS.set(params.sessionId, queueHandle);
const {
assistantTexts,
toolMetas,
unsubscribe,
waitForCompactionRetry,
} = subscribeEmbeddedPiSession({
const subscription = subscribeEmbeddedPiSession({
session,
runId: params.runId,
verboseLevel: params.verboseLevel,
@@ -837,6 +831,22 @@ export async function runEmbeddedPiAgent(params: {
onAgentEvent: params.onAgentEvent,
enforceFinalTag: params.enforceFinalTag,
});
const {
assistantTexts,
toolMetas,
unsubscribe,
waitForCompactionRetry,
} = subscription;
const queueHandle: EmbeddedPiQueueHandle = {
queueMessage: async (text: string) => {
await session.steer(text);
},
isStreaming: () => session.isStreaming,
isCompacting: () => subscription.isCompacting(),
abort: abortRun,
};
ACTIVE_EMBEDDED_RUNS.set(params.sessionId, queueHandle);
let abortWarnTimer: NodeJS.Timeout | undefined;
const abortTimer = setTimeout(
@@ -844,7 +854,7 @@ export async function runEmbeddedPiAgent(params: {
log.warn(
`embedded run timeout: runId=${params.runId} sessionId=${params.sessionId} timeoutMs=${params.timeoutMs}`,
);
abortRun();
abortRun(true);
if (!abortWarnTimer) {
abortWarnTimer = setTimeout(() => {
if (!session.isStreaming) return;
@@ -949,7 +959,24 @@ export async function runEmbeddedPiAgent(params: {
(params.config?.agent?.model?.fallbacks?.length ?? 0) > 0;
const authFailure = isAuthAssistantError(lastAssistant);
const rateLimitFailure = isRateLimitAssistantError(lastAssistant);
if (!aborted && (authFailure || rateLimitFailure)) {
// Treat timeout as potential rate limit (Antigravity hangs on rate limit)
const shouldRotate =
(!aborted && (authFailure || rateLimitFailure)) || timedOut;
if (shouldRotate) {
// Mark current profile for cooldown before rotating
if (lastProfileId) {
markAuthProfileCooldown({
store: authStore,
profileId: lastProfileId,
});
if (timedOut) {
log.warn(
`Profile ${lastProfileId} timed out (possible rate limit). Trying next account...`,
);
}
}
const rotated = await advanceAuthProfile();
if (rotated) {
continue;
@@ -960,9 +987,11 @@ export async function runEmbeddedPiAgent(params: {
(lastAssistant
? formatAssistantErrorText(lastAssistant)
: "") ||
(rateLimitFailure
? "LLM request rate limited."
: "LLM request unauthorized.");
(timedOut
? "LLM request timed out."
: rateLimitFailure
? "LLM request rate limited."
: "LLM request unauthorized.");
throw new Error(message);
}
}
@@ -1036,6 +1065,8 @@ export async function runEmbeddedPiAgent(params: {
provider,
profileId: lastProfileId,
});
// Track usage for round-robin rotation
markAuthProfileUsed({ store: authStore, profileId: lastProfileId });
}
return {
payloads: payloads.length ? payloads : undefined,
+4
View File
@@ -968,6 +968,7 @@ describe("subscribeEmbeddedPiSession", () => {
});
}
expect(subscription.isCompacting()).toBe(true);
expect(subscription.assistantTexts.length).toBe(0);
let resolved = false;
@@ -1004,6 +1005,8 @@ describe("subscribeEmbeddedPiSession", () => {
listener({ type: "auto_compaction_start" });
}
expect(subscription.isCompacting()).toBe(true);
let resolved = false;
const waitPromise = subscription.waitForCompactionRetry().then(() => {
resolved = true;
@@ -1018,6 +1021,7 @@ describe("subscribeEmbeddedPiSession", () => {
await waitPromise;
expect(resolved).toBe(true);
expect(subscription.isCompacting()).toBe(false);
});
it("waits for multiple compaction retries before resolving", async () => {
+1
View File
@@ -604,6 +604,7 @@ export function subscribeEmbeddedPiSession(params: {
assistantTexts,
toolMetas,
unsubscribe,
isCompacting: () => compactionInFlight || pendingCompactionRetry > 0,
waitForCompactionRetry: () => {
if (compactionInFlight || pendingCompactionRetry > 0) {
ensureCompactionPromise();
+30
View File
@@ -116,6 +116,36 @@ describe("createClawdbotCodingTools", () => {
expect(slack.some((tool) => tool.name === "slack")).toBe(true);
});
it("filters session tools for sub-agent sessions by default", () => {
const tools = createClawdbotCodingTools({ sessionKey: "subagent:test" });
const names = new Set(tools.map((tool) => tool.name));
expect(names.has("sessions_list")).toBe(false);
expect(names.has("sessions_history")).toBe(false);
expect(names.has("sessions_send")).toBe(false);
expect(names.has("sessions_spawn")).toBe(false);
expect(names.has("read")).toBe(true);
expect(names.has("bash")).toBe(true);
expect(names.has("process")).toBe(true);
});
it("supports allow-only sub-agent tool policy", () => {
const tools = createClawdbotCodingTools({
sessionKey: "subagent:test",
// Intentionally partial config; only fields used by pi-tools are provided.
config: {
agent: {
subagents: {
tools: {
allow: ["read"],
},
},
},
},
});
expect(tools.map((tool) => tool.name)).toEqual(["read"]);
});
it("keeps read tool image metadata intact", async () => {
const tools = createClawdbotCodingTools();
const readTool = tools.find((tool) => tool.name === "read");
+31 -1
View File
@@ -333,6 +333,28 @@ function normalizeToolNames(list?: string[]) {
return list.map((entry) => entry.trim().toLowerCase()).filter(Boolean);
}
const DEFAULT_SUBAGENT_TOOL_DENY = [
"sessions_list",
"sessions_history",
"sessions_send",
"sessions_spawn",
];
function isSubagentSessionKey(sessionKey?: string): boolean {
const key = sessionKey?.trim().toLowerCase() ?? "";
return key.startsWith("subagent:");
}
function resolveSubagentToolPolicy(cfg?: ClawdbotConfig): SandboxToolPolicy {
const configured = cfg?.agent?.subagents?.tools;
const deny = [
...DEFAULT_SUBAGENT_TOOL_DENY,
...(Array.isArray(configured?.deny) ? configured.deny : []),
];
const allow = Array.isArray(configured?.allow) ? configured.allow : undefined;
return { allow, deny };
}
function filterToolsByPolicy(
tools: AnyAgentTool[],
policy?: SandboxToolPolicy,
@@ -534,6 +556,7 @@ export function createClawdbotCodingTools(options?: {
browserControlUrl: sandbox?.browser?.controlUrl,
agentSessionKey: options?.sessionKey,
agentSurface: options?.surface,
sandboxed: !!sandbox,
config: options?.config,
}),
];
@@ -553,7 +576,14 @@ export function createClawdbotCodingTools(options?: {
const sandboxed = sandbox
? filterToolsByPolicy(globallyFiltered, sandbox.tools)
: globallyFiltered;
const subagentFiltered =
isSubagentSessionKey(options?.sessionKey) && options?.sessionKey
? filterToolsByPolicy(
sandboxed,
resolveSubagentToolPolicy(options.config),
)
: sandboxed;
// Always normalize tool JSON Schemas before handing them to pi-agent/pi-ai.
// Without this, some providers (notably OpenAI) will reject root-level union schemas.
return sandboxed.map(normalizeToolParameters);
return subagentFiltered.map(normalizeToolParameters);
}
+11 -1
View File
@@ -114,7 +114,17 @@ const DEFAULT_SANDBOX_CONTAINER_PREFIX = "clawdbot-sbx-";
const DEFAULT_SANDBOX_WORKDIR = "/workspace";
const DEFAULT_SANDBOX_IDLE_HOURS = 24;
const DEFAULT_SANDBOX_MAX_AGE_DAYS = 7;
const DEFAULT_TOOL_ALLOW = ["bash", "process", "read", "write", "edit"];
const DEFAULT_TOOL_ALLOW = [
"bash",
"process",
"read",
"write",
"edit",
"sessions_list",
"sessions_history",
"sessions_send",
"sessions_spawn",
];
const DEFAULT_TOOL_DENY = [
"browser",
"canvas",
+35
View File
@@ -0,0 +1,35 @@
import type { ClawdbotConfig } from "../config/config.js";
const DEFAULT_AGENT_TIMEOUT_SECONDS = 600;
const normalizeNumber = (value: unknown): number | undefined =>
typeof value === "number" && Number.isFinite(value)
? Math.floor(value)
: undefined;
export function resolveAgentTimeoutSeconds(cfg?: ClawdbotConfig): number {
const raw = normalizeNumber(cfg?.agent?.timeoutSeconds);
const seconds = raw ?? DEFAULT_AGENT_TIMEOUT_SECONDS;
return Math.max(seconds, 1);
}
export function resolveAgentTimeoutMs(opts: {
cfg?: ClawdbotConfig;
overrideMs?: number | null;
overrideSeconds?: number | null;
minMs?: number;
}): number {
const minMs = Math.max(normalizeNumber(opts.minMs) ?? 1, 1);
const defaultMs = resolveAgentTimeoutSeconds(opts.cfg) * 1000;
const overrideMs = normalizeNumber(opts.overrideMs);
if (overrideMs !== undefined) {
if (overrideMs <= 0) return defaultMs;
return Math.max(overrideMs, minMs);
}
const overrideSeconds = normalizeNumber(opts.overrideSeconds);
if (overrideSeconds !== undefined) {
if (overrideSeconds <= 0) return defaultMs;
return Math.max(overrideSeconds * 1000, minMs);
}
return Math.max(defaultMs, minMs);
}
+5
View File
@@ -165,6 +165,11 @@
"title": "Session Send",
"detailKeys": ["sessionKey", "timeoutSeconds"]
},
"sessions_spawn": {
"emoji": "🧑‍🔧",
"title": "Sub-agent",
"detailKeys": ["label", "timeoutSeconds", "cleanup"]
},
"whatsapp_login": {
"emoji": "🟢",
"title": "WhatsApp Login",
+56
View File
@@ -0,0 +1,56 @@
import crypto from "node:crypto";
import { callGateway } from "../../gateway/call.js";
import { extractAssistantText, stripToolMessages } from "./sessions-helpers.js";
export async function readLatestAssistantReply(params: {
sessionKey: string;
limit?: number;
}): Promise<string | undefined> {
const history = (await callGateway({
method: "chat.history",
params: { sessionKey: params.sessionKey, limit: params.limit ?? 50 },
})) as { messages?: unknown[] };
const filtered = stripToolMessages(
Array.isArray(history?.messages) ? history.messages : [],
);
const last = filtered.length > 0 ? filtered[filtered.length - 1] : undefined;
return last ? extractAssistantText(last) : undefined;
}
export async function runAgentStep(params: {
sessionKey: string;
message: string;
extraSystemPrompt: string;
timeoutMs: number;
lane?: string;
}): Promise<string | undefined> {
const stepIdem = crypto.randomUUID();
const response = (await callGateway({
method: "agent",
params: {
message: params.message,
sessionKey: params.sessionKey,
idempotencyKey: stepIdem,
deliver: false,
lane: params.lane ?? "nested",
extraSystemPrompt: params.extraSystemPrompt,
},
timeoutMs: 10_000,
})) as { runId?: string; acceptedAt?: number };
const stepRunId =
typeof response?.runId === "string" && response.runId ? response.runId : "";
const resolvedRunId = stepRunId || stepIdem;
const stepWaitMs = Math.min(params.timeoutMs, 60_000);
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: resolvedRunId,
timeoutMs: stepWaitMs,
},
timeoutMs: stepWaitMs + 2000,
})) as { status?: string };
if (wait?.status !== "ok") return undefined;
return await readLatestAssistantReply({ sessionKey: params.sessionKey });
}
+18 -7
View File
@@ -1,14 +1,25 @@
import { Type } from "@sinclair/typebox";
import { type AnyAgentTool, jsonResult, readStringParam } from "./common.js";
import { callGatewayTool, type GatewayCallOptions } from "./gateway.js";
import { CronAddParamsSchema } from "../../gateway/protocol/schema.js";
import {
normalizeCronJobCreate,
normalizeCronJobPatch,
} from "../../cron/normalize.js";
import { type AnyAgentTool, jsonResult, readStringParam } from "./common.js";
import { callGatewayTool, type GatewayCallOptions } from "./gateway.js";
const CronJobPatchSchema = Type.Partial(CronAddParamsSchema);
// NOTE: We use Type.Object({}, { additionalProperties: true }) for job/patch
// instead of CronAddParamsSchema/CronJobPatchSchema because:
//
// 1. CronAddParamsSchema contains nested Type.Union (for schedule, payload, etc.)
// 2. TypeBox compiles Type.Union to JSON Schema `anyOf`
// 3. pi-ai's sanitizeSchemaForGoogle() strips `anyOf` from nested properties
// 4. This leaves empty schemas `{}` which Claude rejects as invalid
//
// The actual validation happens at runtime via normalizeCronJobCreate/Patch
// and the gateway's validateCronAddParams. This schema just needs to accept
// any object so the AI can pass through the job definition.
//
// See: https://github.com/anthropics/anthropic-cookbook/blob/main/misc/tool_use_best_practices.md
// Claude requires valid JSON Schema 2020-12 with explicit types.
const CronToolSchema = Type.Union([
Type.Object({
@@ -29,7 +40,7 @@ const CronToolSchema = Type.Union([
gatewayUrl: Type.Optional(Type.String()),
gatewayToken: Type.Optional(Type.String()),
timeoutMs: Type.Optional(Type.Number()),
job: CronAddParamsSchema,
job: Type.Object({}, { additionalProperties: true }),
}),
Type.Object({
action: Type.Literal("update"),
@@ -37,7 +48,7 @@ const CronToolSchema = Type.Union([
gatewayToken: Type.Optional(Type.String()),
timeoutMs: Type.Optional(Type.Number()),
id: Type.String(),
patch: CronJobPatchSchema,
patch: Type.Object({}, { additionalProperties: true }),
}),
Type.Object({
action: Type.Literal("remove"),
@@ -126,9 +126,10 @@ export async function handleDiscordMessagingAction(
typeof durationRaw === "number" && Number.isFinite(durationRaw)
? durationRaw
: undefined;
const maxSelections = allowMultiselect ? Math.max(2, answers.length) : 1;
await sendPollDiscord(
to,
{ question, answers, allowMultiselect, durationHours },
{ question, options: answers, maxSelections, durationHours },
{ content },
);
return jsonResult({ ok: true });
@@ -0,0 +1,36 @@
import { callGateway } from "../../gateway/call.js";
import type { AnnounceTarget } from "./sessions-send-helpers.js";
import { resolveAnnounceTargetFromKey } from "./sessions-send-helpers.js";
export async function resolveAnnounceTarget(params: {
sessionKey: string;
displayKey: string;
}): Promise<AnnounceTarget | null> {
const parsed = resolveAnnounceTargetFromKey(params.sessionKey);
if (parsed) return parsed;
const parsedDisplay = resolveAnnounceTargetFromKey(params.displayKey);
if (parsedDisplay) return parsedDisplay;
try {
const list = (await callGateway({
method: "sessions.list",
params: {
includeGlobal: true,
includeUnknown: true,
limit: 200,
},
})) as { sessions?: Array<Record<string, unknown>> };
const sessions = Array.isArray(list?.sessions) ? list.sessions : [];
const match =
sessions.find((entry) => entry?.key === params.sessionKey) ??
sessions.find((entry) => entry?.key === params.displayKey);
const channel =
typeof match?.lastChannel === "string" ? match.lastChannel : undefined;
const to = typeof match?.lastTo === "string" ? match.lastTo : undefined;
if (channel && to) return { channel, to };
} catch {
// ignore
}
return null;
}
+57 -1
View File
@@ -17,7 +17,37 @@ const SessionsHistoryToolSchema = Type.Object({
includeTools: Type.Optional(Type.Boolean()),
});
export function createSessionsHistoryTool(): AnyAgentTool {
function resolveSandboxSessionToolsVisibility(
cfg: ReturnType<typeof loadConfig>,
) {
return cfg.agent?.sandbox?.sessionToolsVisibility ?? "spawned";
}
async function isSpawnedSessionAllowed(params: {
requesterSessionKey: string;
targetSessionKey: string;
}): Promise<boolean> {
try {
const list = (await callGateway({
method: "sessions.list",
params: {
includeGlobal: false,
includeUnknown: false,
limit: 500,
spawnedBy: params.requesterSessionKey,
},
})) as { sessions?: Array<Record<string, unknown>> };
const sessions = Array.isArray(list?.sessions) ? list.sessions : [];
return sessions.some((entry) => entry?.key === params.targetSessionKey);
} catch {
return false;
}
}
export function createSessionsHistoryTool(opts?: {
agentSessionKey?: string;
sandboxed?: boolean;
}): AnyAgentTool {
return {
label: "Session History",
name: "sessions_history",
@@ -30,11 +60,37 @@ export function createSessionsHistoryTool(): AnyAgentTool {
});
const cfg = loadConfig();
const { mainKey, alias } = resolveMainSessionAlias(cfg);
const visibility = resolveSandboxSessionToolsVisibility(cfg);
const requesterInternalKey =
typeof opts?.agentSessionKey === "string" && opts.agentSessionKey.trim()
? resolveInternalSessionKey({
key: opts.agentSessionKey,
alias,
mainKey,
})
: undefined;
const resolvedKey = resolveInternalSessionKey({
key: sessionKey,
alias,
mainKey,
});
const restrictToSpawned =
opts?.sandboxed === true &&
visibility === "spawned" &&
requesterInternalKey &&
!requesterInternalKey.toLowerCase().startsWith("subagent:");
if (restrictToSpawned) {
const ok = await isSpawnedSessionAllowed({
requesterSessionKey: requesterInternalKey,
targetSessionKey: resolvedKey,
});
if (!ok) {
return jsonResult({
status: "forbidden",
error: `Session not visible from this sandboxed agent session: ${sessionKey}`,
});
}
}
const limit =
typeof params.limit === "number" && Number.isFinite(params.limit)
? Math.max(1, Math.floor(params.limit))
+27 -3
View File
@@ -44,7 +44,16 @@ const SessionsListToolSchema = Type.Object({
messageLimit: Type.Optional(Type.Integer({ minimum: 0 })),
});
export function createSessionsListTool(): AnyAgentTool {
function resolveSandboxSessionToolsVisibility(
cfg: ReturnType<typeof loadConfig>,
) {
return cfg.agent?.sandbox?.sessionToolsVisibility ?? "spawned";
}
export function createSessionsListTool(opts?: {
agentSessionKey?: string;
sandboxed?: boolean;
}): AnyAgentTool {
return {
label: "Sessions",
name: "sessions_list",
@@ -54,6 +63,20 @@ export function createSessionsListTool(): AnyAgentTool {
const params = args as Record<string, unknown>;
const cfg = loadConfig();
const { mainKey, alias } = resolveMainSessionAlias(cfg);
const visibility = resolveSandboxSessionToolsVisibility(cfg);
const requesterInternalKey =
typeof opts?.agentSessionKey === "string" && opts.agentSessionKey.trim()
? resolveInternalSessionKey({
key: opts.agentSessionKey,
alias,
mainKey,
})
: undefined;
const restrictToSpawned =
opts?.sandboxed === true &&
visibility === "spawned" &&
requesterInternalKey &&
!requesterInternalKey.toLowerCase().startsWith("subagent:");
const kindsRaw = readStringArrayParam(params, "kinds")?.map((value) =>
value.trim().toLowerCase(),
@@ -86,8 +109,9 @@ export function createSessionsListTool(): AnyAgentTool {
params: {
limit,
activeMinutes,
includeGlobal: true,
includeUnknown: true,
includeGlobal: !restrictToSpawned,
includeUnknown: !restrictToSpawned,
spawnedBy: restrictToSpawned ? requesterInternalKey : undefined,
},
})) as {
path?: string;
+65 -85
View File
@@ -4,8 +4,10 @@ import { Type } from "@sinclair/typebox";
import { loadConfig } from "../../config/config.js";
import { callGateway } from "../../gateway/call.js";
import { readLatestAssistantReply, runAgentStep } from "./agent-step.js";
import type { AnyAgentTool } from "./common.js";
import { jsonResult, readStringParam } from "./common.js";
import { resolveAnnounceTarget } from "./sessions-announce-target.js";
import {
extractAssistantText,
resolveDisplaySessionKey,
@@ -14,13 +16,11 @@ import {
stripToolMessages,
} from "./sessions-helpers.js";
import {
type AnnounceTarget,
buildAgentToAgentAnnounceContext,
buildAgentToAgentMessageContext,
buildAgentToAgentReplyContext,
isAnnounceSkip,
isReplySkip,
resolveAnnounceTargetFromKey,
resolvePingPongTurns,
} from "./sessions-send-helpers.js";
@@ -33,6 +33,7 @@ const SessionsSendToolSchema = Type.Object({
export function createSessionsSendTool(opts?: {
agentSessionKey?: string;
agentSurface?: string;
sandboxed?: boolean;
}): AnyAgentTool {
return {
label: "Session Send",
@@ -47,11 +48,64 @@ export function createSessionsSendTool(opts?: {
const message = readStringParam(params, "message", { required: true });
const cfg = loadConfig();
const { mainKey, alias } = resolveMainSessionAlias(cfg);
const visibility =
cfg.agent?.sandbox?.sessionToolsVisibility ?? "spawned";
const requesterInternalKey =
typeof opts?.agentSessionKey === "string" && opts.agentSessionKey.trim()
? resolveInternalSessionKey({
key: opts.agentSessionKey,
alias,
mainKey,
})
: undefined;
const resolvedKey = resolveInternalSessionKey({
key: sessionKey,
alias,
mainKey,
});
const restrictToSpawned =
opts?.sandboxed === true &&
visibility === "spawned" &&
requesterInternalKey &&
!requesterInternalKey.toLowerCase().startsWith("subagent:");
if (restrictToSpawned) {
try {
const list = (await callGateway({
method: "sessions.list",
params: {
includeGlobal: false,
includeUnknown: false,
limit: 500,
spawnedBy: requesterInternalKey,
},
})) as { sessions?: Array<Record<string, unknown>> };
const sessions = Array.isArray(list?.sessions) ? list.sessions : [];
const ok = sessions.some((entry) => entry?.key === resolvedKey);
if (!ok) {
return jsonResult({
runId: crypto.randomUUID(),
status: "forbidden",
error: `Session not visible from this sandboxed agent session: ${sessionKey}`,
sessionKey: resolveDisplaySessionKey({
key: sessionKey,
alias,
mainKey,
}),
});
}
} catch {
return jsonResult({
runId: crypto.randomUUID(),
status: "forbidden",
error: `Session not visible from this sandboxed agent session: ${sessionKey}`,
sessionKey: resolveDisplaySessionKey({
key: sessionKey,
alias,
mainKey,
}),
});
}
}
const timeoutSeconds =
typeof params.timeoutSeconds === "number" &&
Number.isFinite(params.timeoutSeconds)
@@ -83,87 +137,6 @@ export function createSessionsSendTool(opts?: {
const requesterSurface = opts?.agentSurface;
const maxPingPongTurns = resolvePingPongTurns(cfg);
const resolveAnnounceTarget =
async (): Promise<AnnounceTarget | null> => {
const parsed = resolveAnnounceTargetFromKey(resolvedKey);
if (parsed) return parsed;
try {
const list = (await callGateway({
method: "sessions.list",
params: {
includeGlobal: true,
includeUnknown: true,
limit: 200,
},
})) as { sessions?: Array<Record<string, unknown>> };
const sessions = Array.isArray(list?.sessions) ? list.sessions : [];
const match =
sessions.find((entry) => entry?.key === resolvedKey) ??
sessions.find((entry) => entry?.key === displayKey);
const channel =
typeof match?.lastChannel === "string"
? match.lastChannel
: undefined;
const to =
typeof match?.lastTo === "string" ? match.lastTo : undefined;
if (channel && to) return { channel, to };
} catch {
// ignore; fall through to null
}
return null;
};
const readLatestAssistantReply = async (
sessionKeyToRead: string,
): Promise<string | undefined> => {
const history = (await callGateway({
method: "chat.history",
params: { sessionKey: sessionKeyToRead, limit: 50 },
})) as { messages?: unknown[] };
const filtered = stripToolMessages(
Array.isArray(history?.messages) ? history.messages : [],
);
const last =
filtered.length > 0 ? filtered[filtered.length - 1] : undefined;
return last ? extractAssistantText(last) : undefined;
};
const runAgentStep = async (step: {
sessionKey: string;
message: string;
extraSystemPrompt: string;
timeoutMs: number;
}): Promise<string | undefined> => {
const stepIdem = crypto.randomUUID();
const response = (await callGateway({
method: "agent",
params: {
message: step.message,
sessionKey: step.sessionKey,
idempotencyKey: stepIdem,
deliver: false,
lane: "nested",
extraSystemPrompt: step.extraSystemPrompt,
},
timeoutMs: 10_000,
})) as { runId?: string; acceptedAt?: number };
const stepRunId =
typeof response?.runId === "string" && response.runId
? response.runId
: stepIdem;
const stepWaitMs = Math.min(step.timeoutMs, 60_000);
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: stepRunId,
timeoutMs: stepWaitMs,
},
timeoutMs: stepWaitMs + 2000,
})) as { status?: string };
if (wait?.status !== "ok") return undefined;
return readLatestAssistantReply(step.sessionKey);
};
const runAgentToAgentFlow = async (
roundOneReply?: string,
runInfo?: { runId: string },
@@ -182,12 +155,17 @@ export function createSessionsSendTool(opts?: {
timeoutMs: waitMs + 2000,
})) as { status?: string };
if (wait?.status === "ok") {
primaryReply = await readLatestAssistantReply(resolvedKey);
primaryReply = await readLatestAssistantReply({
sessionKey: resolvedKey,
});
latestReply = primaryReply;
}
}
if (!latestReply) return;
const announceTarget = await resolveAnnounceTarget();
const announceTarget = await resolveAnnounceTarget({
sessionKey: resolvedKey,
displayKey,
});
const targetChannel = announceTarget?.channel ?? "unknown";
if (
maxPingPongTurns > 0 &&
@@ -216,6 +194,7 @@ export function createSessionsSendTool(opts?: {
message: incomingMessage,
extraSystemPrompt: replyPrompt,
timeoutMs: announceTimeoutMs,
lane: "nested",
});
if (!replyText || isReplySkip(replyText)) {
break;
@@ -241,6 +220,7 @@ export function createSessionsSendTool(opts?: {
message: "Agent-to-agent announce step.",
extraSystemPrompt: announcePrompt,
timeoutMs: announceTimeoutMs,
lane: "nested",
});
if (
announceTarget &&
+369
View File
@@ -0,0 +1,369 @@
import crypto from "node:crypto";
import { Type } from "@sinclair/typebox";
import { loadConfig } from "../../config/config.js";
import { callGateway } from "../../gateway/call.js";
import { readLatestAssistantReply, runAgentStep } from "./agent-step.js";
import type { AnyAgentTool } from "./common.js";
import { jsonResult, readStringParam } from "./common.js";
import { resolveAnnounceTarget } from "./sessions-announce-target.js";
import {
resolveDisplaySessionKey,
resolveInternalSessionKey,
resolveMainSessionAlias,
} from "./sessions-helpers.js";
import { isAnnounceSkip } from "./sessions-send-helpers.js";
const SessionsSpawnToolSchema = Type.Object({
task: Type.String(),
label: Type.Optional(Type.String()),
timeoutSeconds: Type.Optional(Type.Integer({ minimum: 0 })),
cleanup: Type.Optional(
Type.Union([Type.Literal("delete"), Type.Literal("keep")]),
),
});
function buildSubagentSystemPrompt(params: {
requesterSessionKey?: string;
requesterSurface?: string;
childSessionKey: string;
label?: string;
}) {
const lines = [
"Sub-agent context:",
params.label ? `Label: ${params.label}` : undefined,
params.requesterSessionKey
? `Requester session: ${params.requesterSessionKey}.`
: undefined,
params.requesterSurface
? `Requester surface: ${params.requesterSurface}.`
: undefined,
`Your session: ${params.childSessionKey}.`,
"Run the task. Provide a clear final answer (plain text).",
'After you finish, you may be asked to produce an "announce" message to post back to the requester chat.',
].filter(Boolean);
return lines.join("\n");
}
function buildSubagentAnnouncePrompt(params: {
requesterSessionKey?: string;
requesterSurface?: string;
announceChannel: string;
task: string;
subagentReply?: string;
}) {
const lines = [
"Sub-agent announce step:",
params.requesterSessionKey
? `Requester session: ${params.requesterSessionKey}.`
: undefined,
params.requesterSurface
? `Requester surface: ${params.requesterSurface}.`
: undefined,
`Post target surface: ${params.announceChannel}.`,
`Original task: ${params.task}`,
params.subagentReply
? `Sub-agent result: ${params.subagentReply}`
: "Sub-agent result: (not available).",
'Reply exactly "ANNOUNCE_SKIP" to stay silent.',
"Any other reply will be posted to the requester chat surface.",
].filter(Boolean);
return lines.join("\n");
}
async function runSubagentAnnounceFlow(params: {
childSessionKey: string;
childRunId: string;
requesterSessionKey: string;
requesterSurface?: string;
requesterDisplayKey: string;
task: string;
timeoutMs: number;
cleanup: "delete" | "keep";
roundOneReply?: string;
}) {
try {
let reply = params.roundOneReply;
if (!reply) {
const waitMs = Math.min(params.timeoutMs, 60_000);
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: params.childRunId,
timeoutMs: waitMs,
},
timeoutMs: waitMs + 2000,
})) as { status?: string };
if (wait?.status !== "ok") return;
reply = await readLatestAssistantReply({
sessionKey: params.childSessionKey,
});
}
const announceTarget = await resolveAnnounceTarget({
sessionKey: params.requesterSessionKey,
displayKey: params.requesterDisplayKey,
});
if (!announceTarget) return;
const announcePrompt = buildSubagentAnnouncePrompt({
requesterSessionKey: params.requesterSessionKey,
requesterSurface: params.requesterSurface,
announceChannel: announceTarget.channel,
task: params.task,
subagentReply: reply,
});
const announceReply = await runAgentStep({
sessionKey: params.childSessionKey,
message: "Sub-agent announce step.",
extraSystemPrompt: announcePrompt,
timeoutMs: params.timeoutMs,
lane: "nested",
});
if (
!announceReply ||
!announceReply.trim() ||
isAnnounceSkip(announceReply)
)
return;
await callGateway({
method: "send",
params: {
to: announceTarget.to,
message: announceReply.trim(),
provider: announceTarget.channel,
idempotencyKey: crypto.randomUUID(),
},
timeoutMs: 10_000,
});
} catch {
// Best-effort follow-ups; ignore failures to avoid breaking the caller response.
} finally {
if (params.cleanup === "delete") {
try {
await callGateway({
method: "sessions.delete",
params: { key: params.childSessionKey, deleteTranscript: true },
timeoutMs: 10_000,
});
} catch {
// ignore
}
}
}
}
export function createSessionsSpawnTool(opts?: {
agentSessionKey?: string;
agentSurface?: string;
sandboxed?: boolean;
}): AnyAgentTool {
return {
label: "Sessions",
name: "sessions_spawn",
description:
"Spawn a background sub-agent run in an isolated session and announce the result back to the requester chat.",
parameters: SessionsSpawnToolSchema,
execute: async (_toolCallId, args) => {
const params = args as Record<string, unknown>;
const task = readStringParam(params, "task", { required: true });
const label = typeof params.label === "string" ? params.label.trim() : "";
const cleanup =
params.cleanup === "keep" || params.cleanup === "delete"
? (params.cleanup as "keep" | "delete")
: "delete";
const timeoutSeconds =
typeof params.timeoutSeconds === "number" &&
Number.isFinite(params.timeoutSeconds)
? Math.max(0, Math.floor(params.timeoutSeconds))
: 0;
const timeoutMs = timeoutSeconds * 1000;
const cfg = loadConfig();
const { mainKey, alias } = resolveMainSessionAlias(cfg);
const requesterSessionKey = opts?.agentSessionKey;
if (
typeof requesterSessionKey === "string" &&
requesterSessionKey.trim().toLowerCase().startsWith("subagent:")
) {
return jsonResult({
status: "forbidden",
error: "sessions_spawn is not allowed from sub-agent sessions",
});
}
const requesterInternalKey = requesterSessionKey
? resolveInternalSessionKey({
key: requesterSessionKey,
alias,
mainKey,
})
: alias;
const requesterDisplayKey = resolveDisplaySessionKey({
key: requesterInternalKey,
alias,
mainKey,
});
const childSessionKey = `subagent:${crypto.randomUUID()}`;
if (opts?.sandboxed === true) {
try {
await callGateway({
method: "sessions.patch",
params: { key: childSessionKey, spawnedBy: requesterInternalKey },
timeoutMs: 10_000,
});
} catch {
// best-effort; scoping relies on this metadata but spawning still works without it
}
}
const childSystemPrompt = buildSubagentSystemPrompt({
requesterSessionKey,
requesterSurface: opts?.agentSurface,
childSessionKey,
label: label || undefined,
});
const childIdem = crypto.randomUUID();
let childRunId: string = childIdem;
try {
const response = (await callGateway({
method: "agent",
params: {
message: task,
sessionKey: childSessionKey,
idempotencyKey: childIdem,
deliver: false,
lane: "subagent",
extraSystemPrompt: childSystemPrompt,
},
timeoutMs: 10_000,
})) as { runId?: string };
if (typeof response?.runId === "string" && response.runId) {
childRunId = response.runId;
}
} catch (err) {
const messageText =
err instanceof Error
? err.message
: typeof err === "string"
? err
: "error";
return jsonResult({
status: "error",
error: messageText,
childSessionKey,
runId: childRunId,
});
}
if (timeoutSeconds === 0) {
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
});
return jsonResult({
status: "accepted",
childSessionKey,
runId: childRunId,
});
}
let waitStatus: string | undefined;
let waitError: string | undefined;
try {
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: childRunId,
timeoutMs,
},
timeoutMs: timeoutMs + 2000,
})) as { status?: string; error?: string };
waitStatus = typeof wait?.status === "string" ? wait.status : undefined;
waitError = typeof wait?.error === "string" ? wait.error : undefined;
} catch (err) {
const messageText =
err instanceof Error
? err.message
: typeof err === "string"
? err
: "error";
return jsonResult({
status: messageText.includes("gateway timeout") ? "timeout" : "error",
error: messageText,
childSessionKey,
runId: childRunId,
});
}
if (waitStatus === "timeout") {
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
});
return jsonResult({
status: "timeout",
error: waitError,
childSessionKey,
runId: childRunId,
});
}
if (waitStatus === "error") {
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
});
return jsonResult({
status: "error",
error: waitError ?? "agent error",
childSessionKey,
runId: childRunId,
});
}
const replyText = await readLatestAssistantReply({
sessionKey: childSessionKey,
});
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
roundOneReply: replyText,
});
return jsonResult({
status: "ok",
childSessionKey,
runId: childRunId,
reply: replyText,
});
},
};
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { hasControlCommand } from "./command-detection.js";
import { parseActivationCommand } from "./group-activation.js";
import { parseSendPolicyCommand } from "./send-policy.js";
describe("control command parsing", () => {
it("requires slash for send policy", () => {
expect(parseSendPolicyCommand("/send on")).toEqual({
hasCommand: true,
mode: "allow",
});
expect(parseSendPolicyCommand("/send")).toEqual({ hasCommand: true });
expect(parseSendPolicyCommand("send on")).toEqual({ hasCommand: false });
expect(parseSendPolicyCommand("send")).toEqual({ hasCommand: false });
});
it("requires slash for activation", () => {
expect(parseActivationCommand("/activation mention")).toEqual({
hasCommand: true,
mode: "mention",
});
expect(parseActivationCommand("activation mention")).toEqual({
hasCommand: false,
});
});
it("treats bare commands as non-control", () => {
expect(hasControlCommand("/send")).toBe(true);
expect(hasControlCommand("send")).toBe(false);
expect(hasControlCommand("/help")).toBe(true);
expect(hasControlCommand("help")).toBe(false);
expect(hasControlCommand("/status")).toBe(true);
expect(hasControlCommand("status")).toBe(false);
});
});
-8
View File
@@ -2,21 +2,13 @@ const CONTROL_COMMAND_RE =
/(?:^|\s)\/(?:status|help|thinking|think|t|verbose|v|elevated|elev|model|queue|activation|send|restart|reset|new|compact)(?=$|\s|:)\b/i;
const CONTROL_COMMAND_EXACT = new Set([
"help",
"/help",
"status",
"/status",
"restart",
"/restart",
"activation",
"/activation",
"send",
"/send",
"reset",
"/reset",
"new",
"/new",
"compact",
"/compact",
]);
+1 -1
View File
@@ -16,7 +16,7 @@ export function parseActivationCommand(raw?: string): {
if (!raw) return { hasCommand: false };
const trimmed = raw.trim();
if (!trimmed) return { hasCommand: false };
const match = trimmed.match(/^\/?activation\b(?:\s+([a-zA-Z]+))?/i);
const match = trimmed.match(/^\/activation\b(?:\s+([a-zA-Z]+))?/i);
if (!match) return { hasCommand: false };
const mode = normalizeGroupActivation(match[1]);
return { hasCommand: true, mode };
+3 -2
View File
@@ -11,6 +11,7 @@ import {
resolveEmbeddedSessionLane,
} from "../agents/pi-embedded.js";
import { ensureSandboxWorkspaceForSession } from "../agents/sandbox.js";
import { resolveAgentTimeoutMs } from "../agents/timeout.js";
import {
DEFAULT_AGENT_WORKSPACE_DIR,
ensureAgentWorkspace,
@@ -221,8 +222,7 @@ export async function getReplyFromConfig(
ensureBootstrapFiles: true,
});
const workspaceDir = workspace.dir;
const timeoutSeconds = Math.max(agentCfg?.timeoutSeconds ?? 600, 1);
const timeoutMs = timeoutSeconds * 1000;
const timeoutMs = resolveAgentTimeoutMs({ cfg });
const configuredTypingSeconds =
agentCfg?.typingIntervalSeconds ?? sessionCfg?.typingIntervalSeconds;
const typingIntervalSeconds =
@@ -233,6 +233,7 @@ export async function getReplyFromConfig(
silentToken: SILENT_REPLY_TOKEN,
log: defaultRuntime.log,
});
opts?.onTypingController?.(typing);
let transcribedText: string | undefined;
if (cfg.routing?.transcribeAudio && isAudio(ctx.MediaType)) {
@@ -50,6 +50,8 @@ function createTyping(): TypingController {
startTypingLoop: vi.fn(async () => {}),
startTypingOnText: vi.fn(async () => {}),
refreshTypingTtl: vi.fn(),
markRunComplete: vi.fn(),
markDispatchIdle: vi.fn(),
cleanup: vi.fn(),
};
}
+3 -2
View File
@@ -237,7 +237,8 @@ export async function runReplyAgent(params: {
: undefined,
onAgentEvent: (evt) => {
if (evt.stream !== "compaction") return;
const phase = String(evt.data.phase ?? "");
const phase =
typeof evt.data.phase === "string" ? evt.data.phase : "";
const willRetry = Boolean(evt.data.willRetry);
if (phase === "end" && !willRetry) {
autoCompactionCompleted = true;
@@ -514,6 +515,6 @@ export async function runReplyAgent(params: {
finalPayloads.length === 1 ? finalPayloads[0] : finalPayloads,
);
} finally {
typing.cleanup();
typing.markRunComplete();
}
}
+3 -14
View File
@@ -102,11 +102,7 @@ function extractCompactInstructions(params: {
const trimmed = stripped.trim();
if (!trimmed) return undefined;
const lowered = trimmed.toLowerCase();
const prefix = lowered.startsWith("/compact")
? "/compact"
: lowered.startsWith("compact")
? "compact"
: null;
const prefix = lowered.startsWith("/compact") ? "/compact" : null;
if (!prefix) return undefined;
let rest = trimmed.slice(prefix.length).trimStart();
if (rest.startsWith(":")) rest = rest.slice(1).trimStart();
@@ -197,9 +193,7 @@ export async function handleCommands(params: {
const resetRequested =
command.commandBodyNormalized === "/reset" ||
command.commandBodyNormalized === "reset" ||
command.commandBodyNormalized === "/new" ||
command.commandBodyNormalized === "new";
command.commandBodyNormalized === "/new";
if (resetRequested && !command.isAuthorizedSender) {
logVerbose(
`Ignoring /reset from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
@@ -300,7 +294,6 @@ export async function handleCommands(params: {
if (
command.commandBodyNormalized === "/restart" ||
command.commandBodyNormalized === "restart" ||
command.commandBodyNormalized.startsWith("/restart ")
) {
if (!command.isAuthorizedSender) {
@@ -320,7 +313,6 @@ export async function handleCommands(params: {
const helpRequested =
command.commandBodyNormalized === "/help" ||
command.commandBodyNormalized === "help" ||
/(?:^|\s)\/help(?=$|\s|:)\b/i.test(command.commandBodyNormalized);
if (helpRequested) {
if (!command.isAuthorizedSender) {
@@ -335,7 +327,6 @@ export async function handleCommands(params: {
const statusRequested =
directives.hasStatusDirective ||
command.commandBodyNormalized === "/status" ||
command.commandBodyNormalized === "status" ||
command.commandBodyNormalized.startsWith("/status ");
if (statusRequested) {
if (!command.isAuthorizedSender) {
@@ -383,9 +374,7 @@ export async function handleCommands(params: {
const compactRequested =
command.commandBodyNormalized === "/compact" ||
command.commandBodyNormalized === "compact" ||
command.commandBodyNormalized.startsWith("/compact ") ||
command.commandBodyNormalized.startsWith("compact ");
command.commandBodyNormalized.startsWith("/compact ");
if (compactRequested) {
if (!command.isAuthorizedSender) {
logVerbose(
@@ -0,0 +1,46 @@
import type { ClawdbotConfig } from "../../config/config.js";
import { getReplyFromConfig } from "../reply.js";
import type { MsgContext } from "../templating.js";
import type { GetReplyOptions, ReplyPayload } from "../types.js";
import type { ReplyDispatcher, ReplyDispatchKind } from "./reply-dispatcher.js";
type DispatchFromConfigResult = {
queuedFinal: boolean;
counts: Record<ReplyDispatchKind, number>;
};
export async function dispatchReplyFromConfig(params: {
ctx: MsgContext;
cfg: ClawdbotConfig;
dispatcher: ReplyDispatcher;
replyOptions?: Omit<GetReplyOptions, "onToolResult" | "onBlockReply">;
replyResolver?: typeof getReplyFromConfig;
}): Promise<DispatchFromConfigResult> {
const replyResult = await (params.replyResolver ?? getReplyFromConfig)(
params.ctx,
{
...params.replyOptions,
onToolResult: (payload: ReplyPayload) => {
params.dispatcher.sendToolResult(payload);
},
onBlockReply: (payload: ReplyPayload) => {
params.dispatcher.sendBlockReply(payload);
},
},
params.cfg,
);
const replies = replyResult
? Array.isArray(replyResult)
? replyResult
: [replyResult]
: [];
let queuedFinal = false;
for (const reply of replies) {
queuedFinal = params.dispatcher.sendFinalReply(reply) || queuedFinal;
}
await params.dispatcher.waitForIdle();
return { queuedFinal, counts: params.dispatcher.getQueuedCounts() };
}
@@ -37,6 +37,8 @@ function createTyping(): TypingController {
startTypingLoop: vi.fn(async () => {}),
startTypingOnText: vi.fn(async () => {}),
refreshTypingTtl: vi.fn(),
markRunComplete: vi.fn(),
markDispatchIdle: vi.fn(),
cleanup: vi.fn(),
};
}
+144 -137
View File
@@ -58,153 +58,160 @@ export function createFollowupRunner(params: {
};
return async (queued: FollowupRun) => {
const runId = crypto.randomUUID();
if (queued.run.sessionKey) {
registerAgentRunContext(runId, { sessionKey: queued.run.sessionKey });
}
let autoCompactionCompleted = false;
let runResult: Awaited<ReturnType<typeof runEmbeddedPiAgent>>;
let fallbackProvider = queued.run.provider;
let fallbackModel = queued.run.model;
try {
const fallbackResult = await runWithModelFallback({
cfg: queued.run.config,
provider: queued.run.provider,
model: queued.run.model,
run: (provider, model) =>
runEmbeddedPiAgent({
sessionId: queued.run.sessionId,
sessionKey: queued.run.sessionKey,
surface: queued.run.surface,
sessionFile: queued.run.sessionFile,
workspaceDir: queued.run.workspaceDir,
config: queued.run.config,
skillsSnapshot: queued.run.skillsSnapshot,
prompt: queued.prompt,
extraSystemPrompt: queued.run.extraSystemPrompt,
ownerNumbers: queued.run.ownerNumbers,
enforceFinalTag: queued.run.enforceFinalTag,
provider,
model,
authProfileId: queued.run.authProfileId,
thinkLevel: queued.run.thinkLevel,
verboseLevel: queued.run.verboseLevel,
bashElevated: queued.run.bashElevated,
timeoutMs: queued.run.timeoutMs,
runId,
blockReplyBreak: queued.run.blockReplyBreak,
onAgentEvent: (evt) => {
if (evt.stream !== "compaction") return;
const phase = String(evt.data.phase ?? "");
const willRetry = Boolean(evt.data.willRetry);
if (phase === "end" && !willRetry) {
autoCompactionCompleted = true;
}
},
}),
});
runResult = fallbackResult.result;
fallbackProvider = fallbackResult.provider;
fallbackModel = fallbackResult.model;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
defaultRuntime.error?.(`Followup agent failed before reply: ${message}`);
return;
}
const payloadArray = runResult.payloads ?? [];
if (payloadArray.length === 0) return;
const sanitizedPayloads = payloadArray.flatMap((payload) => {
const text = payload.text;
if (!text || !text.includes("HEARTBEAT_OK")) return [payload];
const stripped = stripHeartbeatToken(text, { mode: "message" });
const hasMedia =
Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
if (stripped.shouldSkip && !hasMedia) return [];
return [{ ...payload, text: stripped.text }];
});
const replyTaggedPayloads: ReplyPayload[] = sanitizedPayloads
.map((payload) => {
const { cleaned, replyToId } = extractReplyToTag(payload.text);
return {
...payload,
text: cleaned ? cleaned : undefined,
replyToId: replyToId ?? payload.replyToId,
};
})
.filter(
(payload) =>
payload.text ||
payload.mediaUrl ||
(payload.mediaUrls && payload.mediaUrls.length > 0),
);
if (replyTaggedPayloads.length === 0) return;
if (autoCompactionCompleted) {
const count = await incrementCompactionCount({
sessionEntry,
sessionStore,
sessionKey,
storePath,
});
if (queued.run.verboseLevel === "on") {
const suffix = typeof count === "number" ? ` (count ${count})` : "";
replyTaggedPayloads.unshift({
text: `🧹 Auto-compaction complete${suffix}.`,
const runId = crypto.randomUUID();
if (queued.run.sessionKey) {
registerAgentRunContext(runId, { sessionKey: queued.run.sessionKey });
}
let autoCompactionCompleted = false;
let runResult: Awaited<ReturnType<typeof runEmbeddedPiAgent>>;
let fallbackProvider = queued.run.provider;
let fallbackModel = queued.run.model;
try {
const fallbackResult = await runWithModelFallback({
cfg: queued.run.config,
provider: queued.run.provider,
model: queued.run.model,
run: (provider, model) =>
runEmbeddedPiAgent({
sessionId: queued.run.sessionId,
sessionKey: queued.run.sessionKey,
surface: queued.run.surface,
sessionFile: queued.run.sessionFile,
workspaceDir: queued.run.workspaceDir,
config: queued.run.config,
skillsSnapshot: queued.run.skillsSnapshot,
prompt: queued.prompt,
extraSystemPrompt: queued.run.extraSystemPrompt,
ownerNumbers: queued.run.ownerNumbers,
enforceFinalTag: queued.run.enforceFinalTag,
provider,
model,
authProfileId: queued.run.authProfileId,
thinkLevel: queued.run.thinkLevel,
verboseLevel: queued.run.verboseLevel,
bashElevated: queued.run.bashElevated,
timeoutMs: queued.run.timeoutMs,
runId,
blockReplyBreak: queued.run.blockReplyBreak,
onAgentEvent: (evt) => {
if (evt.stream !== "compaction") return;
const phase =
typeof evt.data.phase === "string" ? evt.data.phase : "";
const willRetry = Boolean(evt.data.willRetry);
if (phase === "end" && !willRetry) {
autoCompactionCompleted = true;
}
},
}),
});
runResult = fallbackResult.result;
fallbackProvider = fallbackResult.provider;
fallbackModel = fallbackResult.model;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
defaultRuntime.error?.(
`Followup agent failed before reply: ${message}`,
);
return;
}
}
if (sessionStore && sessionKey) {
const usage = runResult.meta.agentMeta?.usage;
const modelUsed =
runResult.meta.agentMeta?.model ?? fallbackModel ?? defaultModel;
const contextTokensUsed =
agentCfgContextTokens ??
lookupContextTokens(modelUsed) ??
sessionEntry?.contextTokens ??
DEFAULT_CONTEXT_TOKENS;
const payloadArray = runResult.payloads ?? [];
if (payloadArray.length === 0) return;
const sanitizedPayloads = payloadArray.flatMap((payload) => {
const text = payload.text;
if (!text || !text.includes("HEARTBEAT_OK")) return [payload];
const stripped = stripHeartbeatToken(text, { mode: "message" });
const hasMedia =
Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
if (stripped.shouldSkip && !hasMedia) return [];
return [{ ...payload, text: stripped.text }];
});
if (usage) {
const entry = sessionStore[sessionKey];
if (entry) {
const input = usage.input ?? 0;
const output = usage.output ?? 0;
const promptTokens =
input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
sessionStore[sessionKey] = {
...entry,
inputTokens: input,
outputTokens: output,
totalTokens:
promptTokens > 0 ? promptTokens : (usage.total ?? input),
modelProvider: fallbackProvider ?? entry.modelProvider,
model: modelUsed,
contextTokens: contextTokensUsed ?? entry.contextTokens,
updatedAt: Date.now(),
const replyTaggedPayloads: ReplyPayload[] = sanitizedPayloads
.map((payload) => {
const { cleaned, replyToId } = extractReplyToTag(payload.text);
return {
...payload,
text: cleaned ? cleaned : undefined,
replyToId: replyToId ?? payload.replyToId,
};
if (storePath) {
await saveSessionStore(storePath, sessionStore);
}
})
.filter(
(payload) =>
payload.text ||
payload.mediaUrl ||
(payload.mediaUrls && payload.mediaUrls.length > 0),
);
if (replyTaggedPayloads.length === 0) return;
if (autoCompactionCompleted) {
const count = await incrementCompactionCount({
sessionEntry,
sessionStore,
sessionKey,
storePath,
});
if (queued.run.verboseLevel === "on") {
const suffix = typeof count === "number" ? ` (count ${count})` : "";
replyTaggedPayloads.unshift({
text: `🧹 Auto-compaction complete${suffix}.`,
});
}
} else if (modelUsed || contextTokensUsed) {
const entry = sessionStore[sessionKey];
if (entry) {
sessionStore[sessionKey] = {
...entry,
modelProvider: fallbackProvider ?? entry.modelProvider,
model: modelUsed ?? entry.model,
contextTokens: contextTokensUsed ?? entry.contextTokens,
};
if (storePath) {
await saveSessionStore(storePath, sessionStore);
}
if (sessionStore && sessionKey) {
const usage = runResult.meta.agentMeta?.usage;
const modelUsed =
runResult.meta.agentMeta?.model ?? fallbackModel ?? defaultModel;
const contextTokensUsed =
agentCfgContextTokens ??
lookupContextTokens(modelUsed) ??
sessionEntry?.contextTokens ??
DEFAULT_CONTEXT_TOKENS;
if (usage) {
const entry = sessionStore[sessionKey];
if (entry) {
const input = usage.input ?? 0;
const output = usage.output ?? 0;
const promptTokens =
input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
sessionStore[sessionKey] = {
...entry,
inputTokens: input,
outputTokens: output,
totalTokens:
promptTokens > 0 ? promptTokens : (usage.total ?? input),
modelProvider: fallbackProvider ?? entry.modelProvider,
model: modelUsed,
contextTokens: contextTokensUsed ?? entry.contextTokens,
updatedAt: Date.now(),
};
if (storePath) {
await saveSessionStore(storePath, sessionStore);
}
}
} else if (modelUsed || contextTokensUsed) {
const entry = sessionStore[sessionKey];
if (entry) {
sessionStore[sessionKey] = {
...entry,
modelProvider: fallbackProvider ?? entry.modelProvider,
model: modelUsed ?? entry.model,
contextTokens: contextTokensUsed ?? entry.contextTokens,
};
if (storePath) {
await saveSessionStore(storePath, sessionStore);
}
}
}
}
}
await sendFollowupPayloads(replyTaggedPayloads);
await sendFollowupPayloads(replyTaggedPayloads);
} finally {
typing.markRunComplete();
}
};
}
+11 -32
View File
@@ -1,4 +1,5 @@
import type { ClawdbotConfig } from "../../config/config.js";
import { resolveProviderGroupRequireMention } from "../../config/group-policy.js";
import type {
GroupKeyResolution,
SessionEntry,
@@ -53,38 +54,16 @@ export function resolveGroupRequireMention(params: {
const groupId = groupResolution?.id ?? ctx.From?.replace(/^group:/, "");
const groupRoom = ctx.GroupRoom?.trim() ?? ctx.GroupSubject?.trim();
const groupSpace = ctx.GroupSpace?.trim();
if (surface === "telegram") {
if (groupId) {
const groupConfig = cfg.telegram?.groups?.[groupId];
if (typeof groupConfig?.requireMention === "boolean") {
return groupConfig.requireMention;
}
}
const groupDefault = cfg.telegram?.groups?.["*"]?.requireMention;
if (typeof groupDefault === "boolean") return groupDefault;
return true;
}
if (surface === "whatsapp") {
if (groupId) {
const groupConfig = cfg.whatsapp?.groups?.[groupId];
if (typeof groupConfig?.requireMention === "boolean") {
return groupConfig.requireMention;
}
}
const groupDefault = cfg.whatsapp?.groups?.["*"]?.requireMention;
if (typeof groupDefault === "boolean") return groupDefault;
return true;
}
if (surface === "imessage") {
if (groupId) {
const groupConfig = cfg.imessage?.groups?.[groupId];
if (typeof groupConfig?.requireMention === "boolean") {
return groupConfig.requireMention;
}
}
const groupDefault = cfg.imessage?.groups?.["*"]?.requireMention;
if (typeof groupDefault === "boolean") return groupDefault;
return true;
if (
surface === "telegram" ||
surface === "whatsapp" ||
surface === "imessage"
) {
return resolveProviderGroupRequireMention({
cfg,
surface,
groupId,
});
}
if (surface === "discord") {
const guildEntry = resolveDiscordGuildEntry(
@@ -79,4 +79,18 @@ describe("createReplyDispatcher", () => {
await dispatcher.waitForIdle();
expect(delivered).toEqual(["tool", "block", "final"]);
});
it("fires onIdle when the queue drains", async () => {
const deliver = vi.fn(
async () => await new Promise((resolve) => setTimeout(resolve, 5)),
);
const onIdle = vi.fn();
const dispatcher = createReplyDispatcher({ deliver, onIdle });
dispatcher.sendToolResult({ text: "one" });
dispatcher.sendFinalReply({ text: "two" });
await dispatcher.waitForIdle();
expect(onIdle).toHaveBeenCalledTimes(1);
});
});
+11 -1
View File
@@ -18,10 +18,11 @@ export type ReplyDispatcherOptions = {
deliver: ReplyDispatchDeliverer;
responsePrefix?: string;
onHeartbeatStrip?: () => void;
onIdle?: () => void;
onError?: ReplyDispatchErrorHandler;
};
type ReplyDispatcher = {
export type ReplyDispatcher = {
sendToolResult: (payload: ReplyPayload) => boolean;
sendBlockReply: (payload: ReplyPayload) => boolean;
sendFinalReply: (payload: ReplyPayload) => boolean;
@@ -70,6 +71,8 @@ export function createReplyDispatcher(
options: ReplyDispatcherOptions,
): ReplyDispatcher {
let sendChain: Promise<void> = Promise.resolve();
// Track in-flight deliveries so we can emit a reliable "idle" signal.
let pending = 0;
// Serialize outbound replies to preserve tool/block/final order.
const queuedCounts: Record<ReplyDispatchKind, number> = {
tool: 0,
@@ -81,10 +84,17 @@ export function createReplyDispatcher(
const normalized = normalizeReplyPayload(payload, options);
if (!normalized) return false;
queuedCounts[kind] += 1;
pending += 1;
sendChain = sendChain
.then(() => options.deliver(normalized, { kind }))
.catch((err) => {
options.onError?.(err, { kind });
})
.finally(() => {
pending -= 1;
if (pending === 0) {
options.onIdle?.();
}
});
return true;
};
+54
View File
@@ -0,0 +1,54 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTypingController } from "./typing.js";
describe("typing controller", () => {
afterEach(() => {
vi.useRealTimers();
});
it("stops after run completion and dispatcher idle", async () => {
vi.useFakeTimers();
const onReplyStart = vi.fn(async () => {});
const typing = createTypingController({
onReplyStart,
typingIntervalSeconds: 1,
typingTtlMs: 30_000,
});
await typing.startTypingLoop();
expect(onReplyStart).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(2_000);
expect(onReplyStart).toHaveBeenCalledTimes(3);
typing.markRunComplete();
vi.advanceTimersByTime(1_000);
expect(onReplyStart).toHaveBeenCalledTimes(4);
typing.markDispatchIdle();
vi.advanceTimersByTime(2_000);
expect(onReplyStart).toHaveBeenCalledTimes(4);
});
it("keeps typing until both idle and run completion are set", async () => {
vi.useFakeTimers();
const onReplyStart = vi.fn(async () => {});
const typing = createTypingController({
onReplyStart,
typingIntervalSeconds: 1,
typingTtlMs: 30_000,
});
await typing.startTypingLoop();
expect(onReplyStart).toHaveBeenCalledTimes(1);
typing.markDispatchIdle();
vi.advanceTimersByTime(2_000);
expect(onReplyStart).toHaveBeenCalledTimes(3);
typing.markRunComplete();
vi.advanceTimersByTime(2_000);
expect(onReplyStart).toHaveBeenCalledTimes(3);
});
});
+34
View File
@@ -3,6 +3,8 @@ export type TypingController = {
startTypingLoop: () => Promise<void>;
startTypingOnText: (text?: string) => Promise<void>;
refreshTypingTtl: () => void;
markRunComplete: () => void;
markDispatchIdle: () => void;
cleanup: () => void;
};
@@ -21,6 +23,9 @@ export function createTypingController(params: {
log,
} = params;
let started = false;
let active = false;
let runComplete = false;
let dispatchIdle = false;
let typingTimer: NodeJS.Timeout | undefined;
let typingTtlTimer: NodeJS.Timeout | undefined;
const typingIntervalMs = typingIntervalSeconds * 1000;
@@ -30,6 +35,13 @@ export function createTypingController(params: {
return `${Math.round(ms / 1000)}s`;
};
const resetCycle = () => {
started = false;
active = false;
runComplete = false;
dispatchIdle = false;
};
const cleanup = () => {
if (typingTtlTimer) {
clearTimeout(typingTtlTimer);
@@ -39,6 +51,7 @@ export function createTypingController(params: {
clearInterval(typingTimer);
typingTimer = undefined;
}
resetCycle();
};
const refreshTypingTtl = () => {
@@ -61,11 +74,20 @@ export function createTypingController(params: {
};
const ensureStart = async () => {
if (!active) {
active = true;
}
if (started) return;
started = true;
await triggerTyping();
};
const maybeStopOnIdle = () => {
if (!active) return;
// Stop only when the model run is done and the dispatcher queue is empty.
if (runComplete && dispatchIdle) cleanup();
};
const startTypingLoop = async () => {
if (!onReplyStart) return;
if (typingIntervalMs <= 0) return;
@@ -85,11 +107,23 @@ export function createTypingController(params: {
await startTypingLoop();
};
const markRunComplete = () => {
runComplete = true;
maybeStopOnIdle();
};
const markDispatchIdle = () => {
dispatchIdle = true;
maybeStopOnIdle();
};
return {
onReplyStart: ensureStart,
startTypingLoop,
startTypingOnText,
refreshTypingTtl,
markRunComplete,
markDispatchIdle,
cleanup,
};
}
+1 -1
View File
@@ -17,7 +17,7 @@ export function parseSendPolicyCommand(raw?: string): {
if (!raw) return { hasCommand: false };
const trimmed = raw.trim();
if (!trimmed) return { hasCommand: false };
const match = trimmed.match(/^\/?send\b(?:\s+([a-zA-Z]+))?/i);
const match = trimmed.match(/^\/send\b(?:\s+([a-zA-Z]+))?/i);
if (!match) return { hasCommand: false };
const token = match[1]?.trim().toLowerCase();
if (!token) return { hasCommand: true };
+3
View File
@@ -10,6 +10,9 @@ export type MsgContext = {
MediaPath?: string;
MediaUrl?: string;
MediaType?: string;
MediaPaths?: string[];
MediaUrls?: string[];
MediaTypes?: string[];
Transcript?: string;
ChatType?: string;
GroupSubject?: string;
+3
View File
@@ -1,5 +1,8 @@
import type { TypingController } from "./reply/typing.js";
export type GetReplyOptions = {
onReplyStart?: () => Promise<void> | void;
onTypingController?: (typing: TypingController) => void;
isHeartbeat?: boolean;
onPartialReply?: (payload: ReplyPayload) => Promise<void> | void;
onBlockReply?: (payload: ReplyPayload) => Promise<void> | void;
+1 -1
View File
@@ -15,7 +15,7 @@ let resolvingA2uiRoot: Promise<string | null> | null = null;
async function resolveA2uiRoot(): Promise<string | null> {
const here = path.dirname(fileURLToPath(import.meta.url));
const candidates = [
// Running from source (tsx) or dist (tsc + copied assets).
// Running from source (bun) or dist (tsc + copied assets).
path.resolve(here, "a2ui"),
// Running from dist without copied assets (fallback to source).
path.resolve(here, "../../src/canvas-host/a2ui"),
-1
View File
@@ -4,7 +4,6 @@ import { defaultRuntime } from "../runtime.js";
import type { GatewayRpcOpts } from "./gateway-rpc.js";
import { addGatewayClientOptions, callGatewayFromCli } from "./gateway-rpc.js";
async function warnIfCronSchedulerDisabled(opts: GatewayRpcOpts) {
try {
const res = (await callGatewayFromCli("cron.status", opts, {})) as {
+62
View File
@@ -13,6 +13,9 @@ const forceFreePortAndWait = vi.fn(async () => ({
waitedMs: 0,
escalatedToSigkill: false,
}));
const serviceStop = vi.fn().mockResolvedValue(undefined);
const serviceRestart = vi.fn().mockResolvedValue(undefined);
const serviceIsLoaded = vi.fn().mockResolvedValue(true);
const runtimeLogs: string[] = [];
const runtimeErrors: string[] = [];
@@ -74,6 +77,20 @@ vi.mock("./ports.js", () => ({
forceFreePortAndWait: (port: number) => forceFreePortAndWait(port),
}));
vi.mock("../daemon/service.js", () => ({
resolveGatewayService: () => ({
label: "LaunchAgent",
loadedText: "loaded",
notLoadedText: "not loaded",
install: vi.fn(),
uninstall: vi.fn(),
stop: serviceStop,
restart: serviceRestart,
isLoaded: serviceIsLoaded,
readCommand: vi.fn(),
}),
}));
describe("gateway-cli coverage", () => {
it("registers call/health/status/send/agent commands and routes to callGateway", async () => {
runtimeLogs.length = 0;
@@ -228,6 +245,51 @@ describe("gateway-cli coverage", () => {
}
});
it("supports gateway stop/restart via service helper", async () => {
runtimeLogs.length = 0;
runtimeErrors.length = 0;
serviceStop.mockClear();
serviceRestart.mockClear();
serviceIsLoaded.mockResolvedValue(true);
const { registerGatewayCli } = await import("./gateway-cli.js");
const program = new Command();
program.exitOverride();
registerGatewayCli(program);
await program.parseAsync(["gateway", "stop"], { from: "user" });
await program.parseAsync(["gateway", "restart"], { from: "user" });
expect(serviceStop).toHaveBeenCalledTimes(1);
expect(serviceRestart).toHaveBeenCalledTimes(1);
});
it("prints stop hints on GatewayLockError when service is loaded", async () => {
runtimeLogs.length = 0;
runtimeErrors.length = 0;
serviceIsLoaded.mockResolvedValue(true);
const { GatewayLockError } = await import("../infra/gateway-lock.js");
startGatewayServer.mockRejectedValueOnce(
new GatewayLockError("another gateway instance is already listening"),
);
const { registerGatewayCli } = await import("./gateway-cli.js");
const program = new Command();
program.exitOverride();
registerGatewayCli(program);
await expect(
program.parseAsync(["gateway", "--allow-unconfigured"], {
from: "user",
}),
).rejects.toThrow("__exit__:1");
expect(startGatewayServer).toHaveBeenCalled();
expect(runtimeErrors.join("\n")).toContain("Gateway failed to start:");
expect(runtimeErrors.join("\n")).toContain("clawdbot gateway stop");
});
it("uses env/config port when --port is omitted", async () => {
await withEnvOverride({ CLAWDBOT_GATEWAY_PORT: "19001" }, async () => {
runtimeLogs.length = 0;
+155 -4
View File
@@ -6,6 +6,12 @@ import {
loadConfig,
resolveGatewayPort,
} from "../config/config.js";
import {
GATEWAY_LAUNCH_AGENT_LABEL,
GATEWAY_SYSTEMD_SERVICE_NAME,
GATEWAY_WINDOWS_TASK_NAME,
} from "../daemon/constants.js";
import { resolveGatewayService } from "../daemon/service.js";
import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
import { startGatewayServer } from "../gateway/server.js";
import {
@@ -45,6 +51,80 @@ function parsePort(raw: unknown): number | null {
return parsed;
}
function describeUnknownError(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === "string") return err;
if (typeof err === "number" || typeof err === "bigint") return err.toString();
if (typeof err === "boolean") return err ? "true" : "false";
if (err && typeof err === "object") {
if ("message" in err && typeof err.message === "string") {
return err.message;
}
try {
return JSON.stringify(err);
} catch {
return "Unknown error";
}
}
return "Unknown error";
}
function renderGatewayServiceStopHints(): string[] {
switch (process.platform) {
case "darwin":
return [
"Tip: clawdbot gateway stop",
`Or: launchctl bootout gui/$UID/${GATEWAY_LAUNCH_AGENT_LABEL}`,
];
case "linux":
return [
"Tip: clawdbot gateway stop",
`Or: systemctl --user stop ${GATEWAY_SYSTEMD_SERVICE_NAME}.service`,
];
case "win32":
return [
"Tip: clawdbot gateway stop",
`Or: schtasks /End /TN "${GATEWAY_WINDOWS_TASK_NAME}"`,
];
default:
return ["Tip: clawdbot gateway stop"];
}
}
function renderGatewayServiceStartHints(): string[] {
switch (process.platform) {
case "darwin":
return [
`launchctl bootstrap gui/$UID ~/Library/LaunchAgents/${GATEWAY_LAUNCH_AGENT_LABEL}.plist`,
];
case "linux":
return [`systemctl --user start ${GATEWAY_SYSTEMD_SERVICE_NAME}.service`];
case "win32":
return [`schtasks /Run /TN "${GATEWAY_WINDOWS_TASK_NAME}"`];
default:
return [];
}
}
async function maybeExplainGatewayServiceStop() {
const service = resolveGatewayService();
let loaded: boolean | null = null;
try {
loaded = await service.isLoaded({ env: process.env });
} catch {
loaded = null;
}
if (loaded === false) return;
defaultRuntime.error(
loaded
? `Gateway service appears ${service.loadedText}. Stop it first.`
: "Gateway service status unknown; if supervised, stop it first.",
);
for (const hint of renderGatewayServiceStopHints()) {
defaultRuntime.error(hint);
}
}
async function runGatewayLoop(params: {
start: () => Promise<Awaited<ReturnType<typeof startGatewayServer>>>;
runtime: typeof defaultRuntime;
@@ -285,8 +365,17 @@ export function registerGatewayCli(program: Command) {
}),
});
} catch (err) {
if (err instanceof GatewayLockError) {
defaultRuntime.error(`Gateway failed to start: ${err.message}`);
if (
err instanceof GatewayLockError ||
(err &&
typeof err === "object" &&
(err as { name?: string }).name === "GatewayLockError")
) {
const errMessage = describeUnknownError(err);
defaultRuntime.error(
`Gateway failed to start: ${errMessage}\nIf the gateway is supervised, stop it with: clawdbot gateway stop`,
);
await maybeExplainGatewayServiceStop();
defaultRuntime.exit(1);
return;
}
@@ -486,8 +575,17 @@ export function registerGatewayCli(program: Command) {
}),
});
} catch (err) {
if (err instanceof GatewayLockError) {
defaultRuntime.error(`Gateway failed to start: ${err.message}`);
if (
err instanceof GatewayLockError ||
(err &&
typeof err === "object" &&
(err as { name?: string }).name === "GatewayLockError")
) {
const errMessage = describeUnknownError(err);
defaultRuntime.error(
`Gateway failed to start: ${errMessage}\nIf the gateway is supervised, stop it with: clawdbot gateway stop`,
);
await maybeExplainGatewayServiceStop();
defaultRuntime.exit(1);
return;
}
@@ -635,6 +733,59 @@ export function registerGatewayCli(program: Command) {
}),
);
gateway
.command("stop")
.description("Stop the Gateway service (launchd/systemd/schtasks)")
.action(async () => {
const service = resolveGatewayService();
let loaded = false;
try {
loaded = await service.isLoaded({ env: process.env });
} catch (err) {
defaultRuntime.error(`Gateway service check failed: ${String(err)}`);
defaultRuntime.exit(1);
return;
}
if (!loaded) {
defaultRuntime.log(`Gateway service ${service.notLoadedText}.`);
return;
}
try {
await service.stop({ stdout: process.stdout });
} catch (err) {
defaultRuntime.error(`Gateway stop failed: ${String(err)}`);
defaultRuntime.exit(1);
}
});
gateway
.command("restart")
.description("Restart the Gateway service (launchd/systemd/schtasks)")
.action(async () => {
const service = resolveGatewayService();
let loaded = false;
try {
loaded = await service.isLoaded({ env: process.env });
} catch (err) {
defaultRuntime.error(`Gateway service check failed: ${String(err)}`);
defaultRuntime.exit(1);
return;
}
if (!loaded) {
defaultRuntime.log(`Gateway service ${service.notLoadedText}.`);
for (const hint of renderGatewayServiceStartHints()) {
defaultRuntime.log(`Start with: ${hint}`);
}
return;
}
try {
await service.restart({ stdout: process.stdout });
} catch (err) {
defaultRuntime.error(`Gateway restart failed: ${String(err)}`);
defaultRuntime.exit(1);
}
});
// Build default deps (keeps parity with other commands; future-proofing).
void createDefaultDeps();
}
+1 -3
View File
@@ -90,10 +90,8 @@ describe("gateway SIGTERM", () => {
const err: string[] = [];
child = spawn(
process.execPath,
"bun",
[
"--import",
"tsx",
"src/index.ts",
"gateway",
"--port",
+68 -8
View File
@@ -1,10 +1,11 @@
import chalk from "chalk";
import { Command } from "commander";
import { agentCommand } from "../commands/agent.js";
import { agentCliCommand } from "../commands/agent-via-gateway.js";
import { configureCommand } from "../commands/configure.js";
import { doctorCommand } from "../commands/doctor.js";
import { healthCommand } from "../commands/health.js";
import { onboardCommand } from "../commands/onboard.js";
import { pollCommand } from "../commands/poll.js";
import { sendCommand } from "../commands/send.js";
import { sessionsCommand } from "../commands/sessions.js";
import { setupCommand } from "../commands/setup.js";
@@ -288,9 +289,16 @@ export function buildProgram() {
program
.command("doctor")
.description("Health checks + quick fixes for the gateway and providers")
.action(async () => {
.option(
"--no-workspace-suggestions",
"Disable workspace memory system suggestions",
false,
)
.action(async (opts) => {
try {
await doctorCommand(defaultRuntime);
await doctorCommand(defaultRuntime, {
workspaceSuggestions: opts.workspaceSuggestions,
});
} catch (err) {
defaultRuntime.error(String(err));
defaultRuntime.exit(1);
@@ -386,10 +394,57 @@ Examples:
});
program
.command("agent")
.description(
"Talk directly to the configured agent (no chat send; optional delivery)",
.command("poll")
.description("Create a poll via WhatsApp or Discord")
.requiredOption(
"-t, --to <id>",
"Recipient: WhatsApp JID/number or Discord channel/user",
)
.requiredOption("-q, --question <text>", "Poll question")
.requiredOption(
"-o, --option <choice>",
"Poll option (use multiple times, 2-12 required)",
(value: string, previous: string[]) => previous.concat([value]),
[] as string[],
)
.option(
"-s, --max-selections <n>",
"How many options can be selected (default: 1)",
)
.option(
"--duration-hours <n>",
"Poll duration in hours (Discord only, default: 24)",
)
.option(
"--provider <provider>",
"Delivery provider: whatsapp|discord (default: whatsapp)",
)
.option("--dry-run", "Print payload and skip sending", false)
.option("--json", "Output result as JSON", false)
.option("--verbose", "Verbose logging", false)
.addHelpText(
"after",
`
Examples:
clawdbot poll --to +15555550123 -q "Lunch today?" -o "Yes" -o "No" -o "Maybe"
clawdbot poll --to 123456789@g.us -q "Meeting time?" -o "10am" -o "2pm" -o "4pm" -s 2
clawdbot poll --to channel:123456789 -q "Snack?" -o "Pizza" -o "Sushi" --provider discord
clawdbot poll --to channel:123456789 -q "Plan?" -o "A" -o "B" --provider discord --duration-hours 48`,
)
.action(async (opts) => {
setVerbose(Boolean(opts.verbose));
const deps = createDefaultDeps();
try {
await pollCommand(opts, deps, defaultRuntime);
} catch (err) {
defaultRuntime.error(String(err));
defaultRuntime.exit(1);
}
});
program
.command("agent")
.description("Run an agent turn via the Gateway (use --local for embedded)")
.requiredOption("-m, --message <text>", "Message body for the agent")
.option(
"-t, --to <number>",
@@ -405,6 +460,11 @@ Examples:
"--provider <provider>",
"Delivery provider: whatsapp|telegram|discord|slack|signal|imessage (default: whatsapp)",
)
.option(
"--local",
"Run the embedded agent locally (requires provider API keys in your shell)",
false,
)
.option(
"--deliver",
"Send the agent's reply back to the selected provider (requires --to)",
@@ -430,9 +490,9 @@ Examples:
typeof opts.verbose === "string" ? opts.verbose.toLowerCase() : "";
setVerbose(verboseLevel === "on");
// Build default deps (keeps parity with other commands; future-proofing).
void createDefaultDeps();
const deps = createDefaultDeps();
try {
await agentCommand(opts, defaultRuntime);
await agentCliCommand(opts, defaultRuntime, deps);
} catch (err) {
defaultRuntime.error(String(err));
defaultRuntime.exit(1);
+126
View File
@@ -0,0 +1,126 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../gateway/call.js", () => ({
callGateway: vi.fn(),
randomIdempotencyKey: () => "idem-1",
}));
vi.mock("./agent.js", () => ({
agentCommand: vi.fn(),
}));
import type { ClawdbotConfig } from "../config/config.js";
import * as configModule from "../config/config.js";
import { callGateway } from "../gateway/call.js";
import type { RuntimeEnv } from "../runtime.js";
import { agentCommand } from "./agent.js";
import { agentCliCommand } from "./agent-via-gateway.js";
const runtime: RuntimeEnv = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
const configSpy = vi.spyOn(configModule, "loadConfig");
function mockConfig(storePath: string, overrides?: Partial<ClawdbotConfig>) {
configSpy.mockReturnValue({
agent: {
timeoutSeconds: 600,
...overrides?.agent,
},
session: {
store: storePath,
mainKey: "main",
...overrides?.session,
},
gateway: overrides?.gateway,
});
}
beforeEach(() => {
vi.clearAllMocks();
});
describe("agentCliCommand", () => {
it("uses gateway by default", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-agent-cli-"));
const store = path.join(dir, "sessions.json");
mockConfig(store);
vi.mocked(callGateway).mockResolvedValue({
runId: "idem-1",
status: "ok",
result: {
payloads: [{ text: "hello" }],
meta: { stub: true },
},
});
try {
await agentCliCommand({ message: "hi", to: "+1555" }, runtime);
expect(callGateway).toHaveBeenCalledTimes(1);
expect(agentCommand).not.toHaveBeenCalled();
expect(runtime.log).toHaveBeenCalledWith("hello");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("falls back to embedded agent when gateway fails", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-agent-cli-"));
const store = path.join(dir, "sessions.json");
mockConfig(store);
vi.mocked(callGateway).mockRejectedValue(
new Error("gateway not connected"),
);
vi.mocked(agentCommand).mockImplementationOnce(async (_opts, rt) => {
rt.log?.("local");
return { payloads: [{ text: "local" }], meta: { stub: true } };
});
try {
await agentCliCommand({ message: "hi", to: "+1555" }, runtime);
expect(callGateway).toHaveBeenCalledTimes(1);
expect(agentCommand).toHaveBeenCalledTimes(1);
expect(runtime.log).toHaveBeenCalledWith("local");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("skips gateway when --local is set", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-agent-cli-"));
const store = path.join(dir, "sessions.json");
mockConfig(store);
vi.mocked(agentCommand).mockImplementationOnce(async (_opts, rt) => {
rt.log?.("local");
return { payloads: [{ text: "local" }], meta: { stub: true } };
});
try {
await agentCliCommand(
{
message: "hi",
to: "+1555",
local: true,
},
runtime,
);
expect(callGateway).not.toHaveBeenCalled();
expect(agentCommand).toHaveBeenCalledTimes(1);
expect(runtime.log).toHaveBeenCalledWith("local");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
+194
View File
@@ -0,0 +1,194 @@
import type { CliDeps } from "../cli/deps.js";
import { loadConfig } from "../config/config.js";
import {
loadSessionStore,
resolveSessionKey,
resolveStorePath,
} from "../config/sessions.js";
import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
import type { RuntimeEnv } from "../runtime.js";
import { agentCommand } from "./agent.js";
type AgentGatewayResult = {
payloads?: Array<{
text?: string;
mediaUrl?: string | null;
mediaUrls?: string[];
}>;
meta?: unknown;
};
type GatewayAgentResponse = {
runId?: string;
status?: string;
summary?: string;
result?: AgentGatewayResult;
};
export type AgentCliOpts = {
message: string;
to?: string;
sessionId?: string;
thinking?: string;
verbose?: string;
json?: boolean;
timeout?: string;
deliver?: boolean;
provider?: string;
bestEffortDeliver?: boolean;
lane?: string;
runId?: string;
extraSystemPrompt?: string;
local?: boolean;
};
function resolveGatewaySessionKey(opts: {
cfg: ReturnType<typeof loadConfig>;
to?: string;
sessionId?: string;
}): string | undefined {
const sessionCfg = opts.cfg.session;
const scope = sessionCfg?.scope ?? "per-sender";
const mainKey = sessionCfg?.mainKey ?? "main";
const storePath = resolveStorePath(sessionCfg?.store);
const store = loadSessionStore(storePath);
const ctx = opts.to?.trim() ? ({ From: opts.to } as { From: string }) : null;
let sessionKey: string | undefined = ctx
? resolveSessionKey(scope, ctx, mainKey)
: undefined;
if (
opts.sessionId &&
(!sessionKey || store[sessionKey]?.sessionId !== opts.sessionId)
) {
const foundKey = Object.keys(store).find(
(key) => store[key]?.sessionId === opts.sessionId,
);
if (foundKey) sessionKey = foundKey;
}
return sessionKey;
}
function parseTimeoutSeconds(opts: {
cfg: ReturnType<typeof loadConfig>;
timeout?: string;
}) {
const raw =
opts.timeout !== undefined
? Number.parseInt(String(opts.timeout), 10)
: (opts.cfg.agent?.timeoutSeconds ?? 600);
if (Number.isNaN(raw) || raw <= 0) {
throw new Error("--timeout must be a positive integer (seconds)");
}
return raw;
}
function normalizeProvider(raw?: string): string | undefined {
const normalized = raw?.trim().toLowerCase();
if (!normalized) return undefined;
return normalized === "imsg" ? "imessage" : normalized;
}
function formatPayloadForLog(payload: {
text?: string;
mediaUrls?: string[];
mediaUrl?: string | null;
}) {
const lines: string[] = [];
if (payload.text) lines.push(payload.text.trimEnd());
const mediaUrl =
typeof payload.mediaUrl === "string" && payload.mediaUrl.trim()
? payload.mediaUrl.trim()
: undefined;
const media = payload.mediaUrls ?? (mediaUrl ? [mediaUrl] : []);
for (const url of media) lines.push(`MEDIA:${url}`);
return lines.join("\n").trimEnd();
}
export async function agentViaGatewayCommand(
opts: AgentCliOpts,
runtime: RuntimeEnv,
) {
const body = (opts.message ?? "").trim();
if (!body) throw new Error("Message (--message) is required");
if (!opts.to && !opts.sessionId) {
throw new Error("Pass --to <E.164> or --session-id to choose a session");
}
const cfg = loadConfig();
const timeoutSeconds = parseTimeoutSeconds({ cfg, timeout: opts.timeout });
const gatewayTimeoutMs = Math.max(10_000, (timeoutSeconds + 30) * 1000);
const sessionKey = resolveGatewaySessionKey({
cfg,
to: opts.to,
sessionId: opts.sessionId,
});
const channel = normalizeProvider(opts.provider) ?? "whatsapp";
const idempotencyKey = opts.runId?.trim() || randomIdempotencyKey();
const response = await callGateway<GatewayAgentResponse>({
method: "agent",
params: {
message: body,
to: opts.to,
sessionId: opts.sessionId,
sessionKey,
thinking: opts.thinking,
deliver: Boolean(opts.deliver),
channel,
timeout: timeoutSeconds,
lane: opts.lane,
extraSystemPrompt: opts.extraSystemPrompt,
idempotencyKey,
},
expectFinal: true,
timeoutMs: gatewayTimeoutMs,
clientName: "cli",
mode: "cli",
});
if (opts.json) {
runtime.log(JSON.stringify(response, null, 2));
return response;
}
const result = response?.result;
const payloads = result?.payloads ?? [];
if (payloads.length === 0) {
runtime.log(
response?.summary ? String(response.summary) : "No reply from agent.",
);
return response;
}
for (const payload of payloads) {
const out = formatPayloadForLog(payload);
if (out) runtime.log(out);
}
return response;
}
export async function agentCliCommand(
opts: AgentCliOpts,
runtime: RuntimeEnv,
deps?: CliDeps,
) {
if (opts.local === true) {
return await agentCommand(opts, runtime, deps);
}
try {
return await agentViaGatewayCommand(opts, runtime);
} catch (err) {
runtime.error?.(
`Gateway agent failed; falling back to embedded: ${String(err)}`,
);
return await agentCommand(opts, runtime, deps);
}
}
+21 -5
View File
@@ -16,6 +16,7 @@ import {
} from "../agents/model-selection.js";
import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";
import { buildWorkspaceSkillSnapshot } from "../agents/skills.js";
import { resolveAgentTimeoutMs } from "../agents/timeout.js";
import {
DEFAULT_AGENT_WORKSPACE_DIR,
ensureAgentWorkspace,
@@ -190,11 +191,17 @@ export async function agentCommand(
const timeoutSecondsRaw =
opts.timeout !== undefined
? Number.parseInt(String(opts.timeout), 10)
: (agentCfg?.timeoutSeconds ?? 600);
if (Number.isNaN(timeoutSecondsRaw) || timeoutSecondsRaw <= 0) {
: undefined;
if (
timeoutSecondsRaw !== undefined &&
(Number.isNaN(timeoutSecondsRaw) || timeoutSecondsRaw <= 0)
) {
throw new Error("--timeout must be a positive integer (seconds)");
}
const timeoutMs = Math.max(timeoutSecondsRaw, 1) * 1000;
const timeoutMs = resolveAgentTimeoutMs({
cfg,
overrideSeconds: timeoutSecondsRaw,
});
const sessionResolution = resolveSession({
cfg,
@@ -598,12 +605,14 @@ export async function agentCommand(
2,
),
);
if (!deliver) return;
if (!deliver) {
return { payloads: normalizedPayloads, meta: result.meta };
}
}
if (payloads.length === 0) {
runtime.log("No reply from agent.");
return;
return { payloads: [], meta: result.meta };
}
const deliveryTextLimit =
@@ -787,4 +796,11 @@ export async function agentCommand(
}
}
}
const normalizedPayloads = payloads.map((p) => ({
text: p.text ?? "",
mediaUrl: p.mediaUrl ?? null,
mediaUrls: p.mediaUrls ?? (p.mediaUrl ? [p.mediaUrl] : undefined),
}));
return { payloads: normalizedPayloads, meta: result.meta };
}
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more