Claude Code Task
by @vsevolodustinov
Launch Claude Code async in background with automatic delivery to Telegram/WhatsApp. Use for coding, refactoring, codebase research, file generation, and com...
clawhub install claude-code-taskπ About This Skill
name: claude-code-task description: "Launch Claude Code async in background with automatic delivery to Telegram/WhatsApp. Use for coding, refactoring, codebase research, file generation, and complex multi-step automations. NOT for quick one-off questions or real-time interactive tasks. Includes strict thread-safe routing + E2E operator validation workflow."
Claude Code Task (Async)
Run Claude Code in background β zero OpenClaw tokens while it works. Results delivered to WhatsApp or Telegram automatically.
Important: Claude Code = General AI Agent
Claude Code is NOT just a coding tool. It's a full-powered AI agent with web search, file access, and deep reasoning. Use it for ANY complex task:
Give it prompts the same way you'd talk to a smart human β natural language, focused on WHAT you need, not HOW to do it.
NOT for:
Quick Start
What "run tests" means for this skill (critical)
When user asks things like:
it means run the full E2E operator validation flow for run-task.py routing + notifications.
It does NOT mean pytest/unittest discovery by default.
Required behavior:
1. Run routing validation first (--validate-only).
2. Launch smoke/E2E scenario via nohup and file-based prompt.
3. Wait for completion through normal async flow (wake/event), not same-turn blocking.
4. Report PASS/FAIL against E2E criteria (routing, heartbeat, mid-task update, completion delivery).
Use the canonical protocol: references/testing-protocol.md and the section below Full E2E Test (reference).
Async Boundary Rule (mandatory)
run-task.py is asynchronous orchestration.
After a successful nohup launch, the correct behavior is:
1. Send a short launch acknowledgment (PID/log/session), then
2. Stop this turn immediately.
3. Continue only when wake/completion event arrives in the same session.
Do not keep waiting in the same turn for Claude Code completion. Do not poll and then summarize in the same turn unless user explicitly asked for active live monitoring.
Anti-pattern:
run-task.py and keep responding as if completion should appear in this turn.Correct pattern:
run-task.py β acknowledge launch β stop β wait for wake.Launch Confirmation Gate (mandatory)
Never claim "launched" until you have positive launch proof.
Required proof checklist (all):
1. nohup command returned a PID,
2. process is alive (ps -p ),
3. run log contains π§ Starting Claude Code... (or equivalent startup marker),
4. routing was validated (--validate-only) for Telegram thread runs.
If launch fails with β Invalid routing:
sessions_list,--notify-channel telegram --notify-thread-id --notify-session-id ,Do not send "Claude Code ΡΡΡΠ» Π² ΡΠ°Π±ΠΎΡΡ" before this gate is satisfied.
Pre-launch planning note (mandatory)
Before launching Claude Code, post a short plan in chat:
If staged: explicitly say this run is "phase 1" and what signal will decide phase 2.
Telegram Thread Safety (must-follow)
For Telegram thread runs, run-task.py is designed to either route correctly or fail immediately.
Mandatory step before launch
Resolve the current runtime session key first (source of truth), then launch with it.sessions_list (or existing runtime context)agent:main:main:thread: β use it directly in --session--session from chat_id/sender id heuristicsRules
--session "agent:main:main:thread:" for thread tasksagent:main:telegram:user: for thread tasksβ Invalid routing--telegram-routing-mode auto:agent:main:telegram:user:) unless explicitly forced
- blocks non-thread launch if a recent thread session exists for same target (likely misroute)
--telegram-routing-mode thread-only--telegram-routing-mode allow-non-thread or --allow-main-telegramThis is intentional: abort fast > silent misroute.
β οΈ ALWAYS launch via nohup β exec timeout (2 min) will kill the process!
β οΈ NEVER put the task text directly in the shell command β quotes, special characters, and newlines WILL break argument parsing. Always save the prompt to a file first, then use $(cat file).
# Step 1: Save prompt to a temp file
write /tmp/cc-prompt.txt with your task textStep 2: Launch with $(cat ...)
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:whatsapp:group:" \
--timeout 900 \
> /tmp/cc-run.log 2>&1 &
The --session key (e.g. agent:main:whatsapp:group:120363425246977860@g.us) is used to auto-detect the WhatsApp target.
Telegram (thread-safe default)
# ALWAYS use the current thread session key from context:
agent:main:main:thread:
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:" \
--timeout 900 \
> /tmp/cc-run.log 2>&1 &
> Do NOT use agent:main:telegram:user: for thread tests/runs.
> That routes to main chat scope and can drift from the source thread.
Telegram Threaded Mode (1:1 DM with threads)
When Marvin is used in Telegram Threaded Mode, each thread has its own session key like agent:main:main:thread:369520.
Fail-safe routing (NEW): run-task.py now enforces strict thread routing.
--session contains :thread:, the script refuses to start unless Telegram target + thread session UUID are resolved.sessions_list when possible.~/.openclaw/agents/main/sessions/*-topic-.jsonl .--notify-session-id mismatches the session key, it exits with error.Use --notify-session-id to wake the exact thread session:
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:369520" \
--timeout 900 \
> /tmp/cc-run.log 2>&1 &
All 5 notification types route to the DM thread when --session key contains :thread: β
--notify-session-id β optional override. Usually auto-resolved from session metadata/files.--notify-thread-id β optional override. Usually auto-extracted from --session.--reply-to-message-id β optional debug field; avoid for DM thread routing.--validate-only β resolve routing and exit (no Claude run). Use this to verify thread launch args safely.--notify-channel β optional channel hint (telegram/whatsapp); target is always auto-resolved from session metadata--timeout β max runtime in seconds (default: 7200 = 2 hours)--completion-mode β optional legacy hint (single default, iterate if explicitly needed)--max-iterations β optional budget hint when using iterate mode--trace-live β emit live technical trace markers into the same chat/thread (debug mode)Why file-based prompts?
Research/complex prompts contain single quotes, double quotes, markdown, backticks β any of these break shell argument parsing. Saving to a file and reading with$(cat ...) avoids all quoting issues.Channel Detection
The detect_channel() function determines where to send notifications:
1. Deterministic auto-resolve β target is resolved from session metadata/session key (no manual target flag)
2. WhatsApp auto-detect β if the session key contains @g.us (WhatsApp group JID), WhatsApp is used
3. Fail fast on unresolved Telegram target β script exits with β Invalid routing instead of silent misroute
def detect_channel(session_key):
if NOTIFY_CHANNEL_OVERRIDE and NOTIFY_TARGET_OVERRIDE:
return NOTIFY_CHANNEL_OVERRIDE, NOTIFY_TARGET_OVERRIDE
jid = extract_group_jid(session_key)
if jid:
return "whatsapp", jid
return None, None
How It Works
βββββββββββββββ nohup ββββββββββββββββ
β Agent β βββββββββββββββΆβ run-task.py β
β (OpenClaw) β β (detached) β
βββββββββββββββ ββββββββ¬ββββββββ
β
βΌ
ββββββββββββββββ
β Claude Code β β runs on Max subscription ($0 API)
β (-p mode) β
ββββββββ¬ββββββββ
β
βββββββββββββΌββββββββββββ
βΌ βΌ βΌ
Every 60s On complete On error/timeout
ββββββββββ ββββββββββββ ββββββββββββββββ
β β³ ping β β β
result β β β/β°/π₯ errorβ
β silent β β channel β β channel β
ββββββββββ ββββββββββββ ββββββββββββββββ
WhatsApp notification flow:
1. Heartbeat pings (every 60s) β WhatsApp direct (informational, no agent wake) 2. Final result β WhatsApp direct (human sees immediately) +sessions_send (agent wakes up)
3. Agent receives completion payload via sessions_send β processes it β sends summary via message(send) to WhatsApp group
4. Human sees both: raw result + agent's analysis/next stepsIterative continuation mode (wake behavior)
--completion-mode is optional (default single) and acts as a hint:
single = one run β continuation summary β stopiterate = continuation summary + exactly one next iteration when gaps remainWake payload now frames continuation as the same ongoing assistant conversation (same agent identity, same session, same history) after Claude Code replies to the previous launch.
In iterate mode the continuation flow is:
Deterministic wake guard (anti-duplicate)
run_id and wake_id in wake payload.run-task.py keeps per-project state in /tmp/cc-orchestrator-state-.json .--trace-live), skipped wakes are announced as [TRACE][TECH][TELEGRAM][WAKE][SKIP].No silent launch policy (always-on)
[TRACE][AGENT][WAKE_RECEIVED] ...
- [TRACE][AGENT][DECISION] continue|stop ...
Telegram notification flow (DM Threaded Mode β full pipeline):
1. π Launch notification β thread β (silent; HTML; for prompt; via send_telegram_direct; includes Resume: )
2. β³ Heartbeat (every 60s) β thread β
(silent; plain text; via send_telegram_direct)
3. π‘ Claude Code mid-task updates β thread β
(on-disk Python script /tmp/cc-notify-{pid}.py; CC calls file; prefix "π‘ π’ CC: " auto-added)
4. β
/β/β°/π₯ Result notification β thread β
(HTML; for result; via send_telegram_direct)
5. π€ Agent continuation reply β delivered to chat via openclaw agent --deliver β
(same session continuation is visible to user)send_telegram_direct() is the core mechanism for all thread-targeted notifications from external scripts. It calls api.telegram.org directly with message_thread_id β bypasses the OpenClaw message tool entirely (which cannot route to DM threads from outside a session context).
Fallback β if agent wake fails (session locked/busy): already_sent=True is set after the direct send, so no duplicate is sent.
Key detail: Telegram vs WhatsApp delivery
WhatsApp: Raw result sent directly (human sees it immediately) + sessions_send wakes agent for analysis.
Telegram: Result sent via send_telegram_direct β then agent is woken via openclaw agent --session-id --deliver so the continuation turn is visible in chat by default. This is the intended βsame agent, same conversationβ behavior after Claude completion.
Why not sessions_send for Telegram? sessions_send is blocked in the HTTP /tools/invoke deny list by architectural design. The openclaw agent CLI bypasses this limitation.
Reliability Features
Timeout (default 2 hours)
--timeout 7200 β after 7200s: SIGTERM β wait 10s β SIGKILLCrash safety
try/except wraps entire main β crash notification always sentPID tracking
skills/claude-code-task/pids/ls skills/claude-code-task/pids/Silent mode (Telegram only)
Telegram supports silent notifications (no sound).Current policy: all Claude Code notifications are silent in Telegram:
silent=Truesilent=Trueπ‘ π’ CC) β silent=Truesilent=Truesilent=TrueWhatsApp does NOT support silent mode β the flag is ignored for WhatsApp.
Telegram DM Threads vs Forum Groups
Telegram has two distinct thread models. The key difference for run-task.py is how to route messages to the thread.
The core problem with external scripts:
message tool's threadId parameter is Discord-specific β ignored for Telegram"chatId:topic:threadId" is rejected by the message tool's target resolvercurrentThreadTs) works ONLY inside active sessions β external scripts have no session contextsend_telegram_direct() bypasses the message tool entirely; calls api.telegram.org directly with message_thread_idDM Threaded Mode (bot-user private chat with threads):
send_telegram_direct(chat_id, text, thread_id=..., parse_mode=...) β
thread_id auto-extracted from session key *:thread: by extract_thread_id()parse_mode="HTML" with for prompt/resultparse_mode=None (plain text, avoid Markdown parse errors)parse_mode="Markdown" trap: finish messages contain text (CommonMark bold); Telegram MarkdownV1 rejects this with HTTP 400 β messages silently don't arrivereplyTo trap: combining replyTo + message_thread_id β Telegram rejects request β fallback strips thread_id β message lands in main chatopenclaw agent --session-id --deliver publishes the wake turn to chat so the user sees the same ongoing assistant conversation.Forum Groups (supergroup with Forum topics enabled):
send_telegram_direct() approach works; message_thread_id is standard Bot API for Forum topics*:thread:Claude Code mid-task updates:
/tmp/cc-notify-{pid}.py to disk before launching Claude Code[Automation context: ... python3 /tmp/cc-notify-{pid}.py 'msg' ...]"π‘ π’ CC: " to all messages; cleaned up in finally blockNotification types
| Event | Emoji | WhatsApp delivery | Telegram delivery | DM thread? |
|-------|-------|-------------------|-------------------|------------|
| Launch | π | send_channel (Markdown) | send_telegram_direct (HTML, silent) | β
message_thread_id |
| Heartbeat | β³ | send_channel (Markdown) | send_telegram_direct (plain, silent) | β
message_thread_id |
| CC mid-task update | π‘ | β | /tmp/cc-notify-{pid}.py (Bot API, silent) | β
message_thread_id |
| Success | β
| send_channel + sessions_send | send_telegram_direct (HTML) + openclaw agent | β
message_thread_id |
| Error | β | send_channel + sessions_send | send_telegram_direct (HTML) + openclaw agent | β
message_thread_id |
| Timeout | β° | send_channel + sessions_send | send_telegram_direct (HTML) + openclaw agent | β
message_thread_id |
| Crash | π₯ | send_channel + sessions_send | send_telegram_direct (HTML) + openclaw agent | β
message_thread_id |
| Agent continuation reply | π€ | β | openclaw agent wake (--deliver) | β
visible in chat |
Claude Code Flags
-p "task" β print mode (non-interactive, outputs result)--dangerously-skip-permissions β no confirmation prompts--verbose --output-format stream-json β real-time activity tracking for heartbeatsWhy NOT exec/pty?
exec has 2 min default timeout β kills long taskspty:true, output has escape codes, hard to parsenohup + -p mode: clean, detached, reliableGit requirement
Claude Code needs a git repo.run-task.py auto-inits if missing.Python 3.9 Compatibility
run-task.py uses Optional[X] from typing (not X | None) for compatibility with Python 3.9. The union syntax (X | None) requires Python 3.10+.
# Correct (3.9+)
from typing import Optional
def foo(x: Optional[str]) -> Optional[str]: ...Would break on 3.9
def foo(x: str | None) -> str | None: ...
Full E2E Test (reference)
Use this when you need to validate the entire pipeline in one run:
Pass criteria
1. Launch message appears in the same thread (with expandable prompt quote) 2. At least one wrapper heartbeat appears after ~60s 3. At least one mid-task CC update appears (via/tmp/cc-notify-.py )
4. Final result appears in the same thread (expandable result quote)
5. Agent wake continuation is delivered (openclaw agent --session-id ... --deliver) and appears visibly in chatInteractive test rule (time budget)
For interactive/iterate-mode testing, do exactly one continuation step after phase 1.Reason: keeps regression runs fast (minutes, not 20+ minutes) while still validating the critical iterate path.
Visibility rule (mandatory)
Betweenβ
Claude Code completed and any next π Claude Code started, there must be a user-facing analysis message in the thread.
Canonical full test prompt pattern
sleep 70) to trigger wrapper heartbeatLong-running task guidance
If a Claude Code task is expected to run longer than ~1 minute, explicitly ask Claude to send intermediate progress updates during execution.
Recommended wording to include in prompt:
For thread-safe Telegram runs, updates should use the injected automation script (/tmp/cc-notify-).
Canonical launch (minimal mode)
cat > /tmp/cc-full-test-prompt.txt << 'EOF'
~10 lines, but total >4500 chars:
1) notify script now
2) create test file with repeated text (to exceed 4500 chars)
3) sleep 70 + notify script again
4) run several shell commands
5) return short structured report
EOFpython3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-full-test-prompt.txt)" \
--project /tmp/cc-e2e-project \
--session "agent:main:main:thread:" \
--validate-only
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-full-test-prompt.txt)" \
--project /tmp/cc-e2e-project \
--session "agent:main:main:thread:" \
--timeout 900 \
> /tmp/cc-full-test.log 2>&1 &
Verification artifacts
/tmp/cc-full-test.log/tmp/cc-YYYYMMDD-HHMMSS.txt~/.openclaw/claude_sessions.jsonExamples
WhatsApp: Create a tool
nohup python3 {baseDir}/run-task.py \
-t "Create a Python CLI tool that converts markdown to HTML with syntax highlighting. Save as convert.py" \
-p ~/projects/md-converter \
-s "agent:main:whatsapp:group:120363425246977860@g.us" \
> /tmp/cc-run.log 2>&1 &
Telegram: Research codebase (thread-safe)
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:" \
--timeout 1800 \
> /tmp/cc-run.log 2>&1 &
Telegram Threaded Mode: Research codebase
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:369520" \
--timeout 1800 \
> /tmp/cc-run.log 2>&1 &
thread_id auto-extracted from session key
target + session UUID auto-resolved from API/local session files
Telegram Threaded Mode: Mid-task updates from Claude Code
run-task.py automatically creates an on-disk notification script before launching Claude Code, so CC can send progress updates without seeing the bot token in the prompt (which triggers safety refusals):
# Just write a normal task prompt β run-task.py handles the rest
cat > /tmp/cc-prompt.txt << 'EOF'
STEP 1: Write analysis to /tmp/report.txt (600+ words)...After step 1, send a progress notification using the script from the
automation context above: python3 /tmp/cc-notify-.py "Step 1 done."
STEP 2: Write summary to /tmp/summary.txt...
EOF
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:" \
--timeout 1800 \
> /tmp/cc-run.log 2>&1 &
run-task.py writes /tmp/cc-notify-{pid}.py before launch
Prepends "[Automation context: use python3 /tmp/cc-notify-{pid}.py 'msg']" to task
Claude Code calls the file; prefix "π‘ π’ CC: " auto-added; file cleaned up on exit
> β οΈ Never embed bot tokens or curl commands in the task prompt β Claude Code correctly identifies hardcoded tokens + external API calls as prompt injection and refuses. Use the on-disk script pattern above instead.
> Quick reference: launching from a Telegram DM thread (minimal mode) >
> # 1) Validate routing first (no Claude run)
> python3 {baseDir}/run-task.py \
> --task "probe" \
> --project ~/projects/x \
> --session "agent:main:main:thread:" \
> --validate-only
>
> # 2) Real launch (only 3 required params)
> nohup python3 {baseDir}/run-task.py \
> --task "$(cat /tmp/prompt.txt)" \
> --project ~/projects/x \
> --session "agent:main:main:thread:" \
> --timeout 900 \
> > /tmp/cc-run.log 2>&1 &
>
> - Required: --task, --project, --session
:thread: are blocked by default (β Unsafe routing blocked)--telegram-routing-mode allow-non-thread.THREAD_ID is auto-extracted from session key
> - Target + session UUID are auto-resolved (API, then local session-file fallback)
> - If routing is inconsistent/unresolved, script exits with β Invalid routing before run
> - All notifications from run-task (launch/heartbeat/result) stay on the source thread β
Long task with extended timeout
nohup python3 {baseDir}/run-task.py \
-t "Refactor the entire auth module to use JWT tokens" \
-p ~/projects/backend \
-s "agent:main:whatsapp:group:120363425246977860@g.us" \
--timeout 3600 \
> /tmp/cc-run.log 2>&1 &
Cost
Session Resumption
Claude Code sessions can be resumed to continue previous conversations. This is useful for:
β οΈ Resume ID β Critical Rule
--resume takes the Claude Code session ID, not the run_id or wake_id.Correct source β look for this line in the run log:
π Session registered:
That is the value to pass as --resume .Do NOT use:
run_id from wake payloadwake_id from wake payloadWhen in doubt: skip --resume and start fresh.
How to Resume
When a task completes, the session ID is automatically captured and saved to the registry (~/.openclaw/claude_sessions.json).
To resume a session, use the --resume flag:
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "SESSION_KEY" \
--resume \
> /tmp/cc-run.log 2>&1 &
Session Labels
Use --session-label to give sessions human-readable names for easier tracking:
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "SESSION_KEY" \
--session-label "Research on Jackson Berler" \
> /tmp/cc-run.log 2>&1 &
Listing Recent Sessions
The agent can read the session registry to find recent sessions:
# Python code (for agent automation)
from session_registry import list_recent_sessions, find_session_by_labelList sessions from last 72 hours
recent = list_recent_sessions(hours=72)
for session in recent:
print(f"{session['session_id']}: {session['label']} ({session['status']})")Find session by label (fuzzy match)
session = find_session_by_label("Jackson")
if session:
print(f"Found: {session['session_id']}")
Or manually inspect the registry:
cat ~/.openclaw/claude_sessions.json
When to Resume vs Start Fresh
Resume when:
Start fresh when:
Resume Failure Handling
If a session ID is invalid or expired:
/tmp/cc-run.log for detailsCommon resume failures:
Example Workflow
Step 1: Initial research
# Save prompt
write /tmp/research-prompt.txt with "Research the codebase architecture for project X"Launch task (Telegram thread-safe example)
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/research-prompt.txt)" \
--project ~/projects/project-x \
--session "agent:main:main:thread:" \
--session-label "Project X architecture research" \
> /tmp/cc-run.log 2>&1 &
Step 2: Check result and find session ID
# Session ID printed in stderr: "π Session registered: "
tail /tmp/cc-run.logOr read from registry
cat ~/.openclaw/claude_sessions.json | grep "Project X"
Step 3: Follow-up implementation
# Save follow-up prompt
write /tmp/implement-prompt.txt with "Based on your research, implement the authentication module"Resume session
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/implement-prompt.txt)" \
--project ~/projects/project-x \
--session "SESSION_KEY" \
--resume \
--session-label "Project X auth implementation" \
> /tmp/cc-run2.log 2>&1 &
Wake Troubleshooting
When the agent wake / continue chain fails (no agent summary, wrong thread, session not resolved, iterative loop stalls, etc.), see the dedicated guide:
Includes a Quick Triage Checklist (60 seconds) plus detailed items: agent not waking,
double messages, wrong thread routing, UUID resolution failures, session-locked wake,
β Invalid routing, Telegram HTTP 400 silent drops, mid-task update failures, stale/duplicate wake skips, and more.
Current Stable Behavior (2026-03-03)
This is the version validated in live Telegram thread tests.
openclaw agent --deliver) so continuation turns are visible in chat.wake_id/output dedupe.--trace-live emits technical milestones (RUN_TASK START/COMPLETE, WAKE, WAKE SKIP) into the same thread.--resume must use the Claude session id from π Session registered: ... in the run log.sub: (example: π’ CC (3min) | sub:1 | 12K tok | 18 calls | π§ Bash).output_tokens is aggregated from all assistant stream messages (main agent + subagents).last_activity / last tool signal is unified: whichever actor (main or subagent) emitted the latest tool event is shown.tool_use id add, matching tool_result/task_notification remove).Files
skills/claude-code-task/
βββ SKILL.md # This file
βββ WAKE-TROUBLESHOOTING.md # Wake/continue chain diagnostics
βββ run-task.py # Async runner with notifications
βββ session_registry.py # Session metadata storage
βββ pids/ # PID files for running tasks (auto-managed)
π‘ Examples
WhatsApp: Create a tool
nohup python3 {baseDir}/run-task.py \
-t "Create a Python CLI tool that converts markdown to HTML with syntax highlighting. Save as convert.py" \
-p ~/projects/md-converter \
-s "agent:main:whatsapp:group:120363425246977860@g.us" \
> /tmp/cc-run.log 2>&1 &
Telegram: Research codebase (thread-safe)
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:" \
--timeout 1800 \
> /tmp/cc-run.log 2>&1 &
Telegram Threaded Mode: Research codebase
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:369520" \
--timeout 1800 \
> /tmp/cc-run.log 2>&1 &
thread_id auto-extracted from session key
target + session UUID auto-resolved from API/local session files
Telegram Threaded Mode: Mid-task updates from Claude Code
run-task.py automatically creates an on-disk notification script before launching Claude Code, so CC can send progress updates without seeing the bot token in the prompt (which triggers safety refusals):
# Just write a normal task prompt β run-task.py handles the rest
cat > /tmp/cc-prompt.txt << 'EOF'
STEP 1: Write analysis to /tmp/report.txt (600+ words)...After step 1, send a progress notification using the script from the
automation context above: python3 /tmp/cc-notify-.py "Step 1 done."
STEP 2: Write summary to /tmp/summary.txt...
EOF
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:" \
--timeout 1800 \
> /tmp/cc-run.log 2>&1 &
run-task.py writes /tmp/cc-notify-{pid}.py before launch
Prepends "[Automation context: use python3 /tmp/cc-notify-{pid}.py 'msg']" to task
Claude Code calls the file; prefix "π‘ π’ CC: " auto-added; file cleaned up on exit
> β οΈ Never embed bot tokens or curl commands in the task prompt β Claude Code correctly identifies hardcoded tokens + external API calls as prompt injection and refuses. Use the on-disk script pattern above instead.
> Quick reference: launching from a Telegram DM thread (minimal mode) >
> # 1) Validate routing first (no Claude run)
> python3 {baseDir}/run-task.py \
> --task "probe" \
> --project ~/projects/x \
> --session "agent:main:main:thread:" \
> --validate-only
>
> # 2) Real launch (only 3 required params)
> nohup python3 {baseDir}/run-task.py \
> --task "$(cat /tmp/prompt.txt)" \
> --project ~/projects/x \
> --session "agent:main:main:thread:" \
> --timeout 900 \
> > /tmp/cc-run.log 2>&1 &
>
> - Required: --task, --project, --session
:thread: are blocked by default (β Unsafe routing blocked)--telegram-routing-mode allow-non-thread.THREAD_ID is auto-extracted from session key
> - Target + session UUID are auto-resolved (API, then local session-file fallback)
> - If routing is inconsistent/unresolved, script exits with β Invalid routing before run
> - All notifications from run-task (launch/heartbeat/result) stay on the source thread β
Long task with extended timeout
nohup python3 {baseDir}/run-task.py \
-t "Refactor the entire auth module to use JWT tokens" \
-p ~/projects/backend \
-s "agent:main:whatsapp:group:120363425246977860@g.us" \
--timeout 3600 \
> /tmp/cc-run.log 2>&1 &
π Constraints
--session "agent:main:main:thread:" for thread tasksagent:main:telegram:user: for thread tasksβ Invalid routing--telegram-routing-mode auto:agent:main:telegram:user:) unless explicitly forced
- blocks non-thread launch if a recent thread session exists for same target (likely misroute)
--telegram-routing-mode thread-only--telegram-routing-mode allow-non-thread or --allow-main-telegramThis is intentional: abort fast > silent misroute.
β οΈ ALWAYS launch via nohup β exec timeout (2 min) will kill the process!
β οΈ NEVER put the task text directly in the shell command β quotes, special characters, and newlines WILL break argument parsing. Always save the prompt to a file first, then use $(cat file).
# Step 1: Save prompt to a temp file
write /tmp/cc-prompt.txt with your task textStep 2: Launch with $(cat ...)
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:whatsapp:group:" \
--timeout 900 \
> /tmp/cc-run.log 2>&1 &
The --session key (e.g. agent:main:whatsapp:group:120363425246977860@g.us) is used to auto-detect the WhatsApp target.
Telegram (thread-safe default)
# ALWAYS use the current thread session key from context:
agent:main:main:thread:
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:" \
--timeout 900 \
> /tmp/cc-run.log 2>&1 &
> Do NOT use agent:main:telegram:user: for thread tests/runs.
> That routes to main chat scope and can drift from the source thread.
Telegram Threaded Mode (1:1 DM with threads)
When Marvin is used in Telegram Threaded Mode, each thread has its own session key like agent:main:main:thread:369520.
Fail-safe routing (NEW): run-task.py now enforces strict thread routing.
--session contains :thread:, the script refuses to start unless Telegram target + thread session UUID are resolved.sessions_list when possible.~/.openclaw/agents/main/sessions/*-topic-.jsonl .--notify-session-id mismatches the session key, it exits with error.Use --notify-session-id to wake the exact thread session:
nohup python3 {baseDir}/run-task.py \
--task "$(cat /tmp/cc-prompt.txt)" \
--project ~/projects/my-project \
--session "agent:main:main:thread:369520" \
--timeout 900 \
> /tmp/cc-run.log 2>&1 &
All 5 notification types route to the DM thread when --session key contains :thread: β
--notify-session-id β optional override. Usually auto-resolved from session metadata/files.--notify-thread-id β optional override. Usually auto-extracted from --session.--reply-to-message-id β optional debug field; avoid for DM thread routing.--validate-only β resolve routing and exit (no Claude run). Use this to verify thread launch args safely.--notify-channel β optional channel hint (telegram/whatsapp); target is always auto-resolved from session metadata--timeout β max runtime in seconds (default: 7200 = 2 hours)--completion-mode β optional legacy hint (single default, iterate if explicitly needed)--max-iterations β optional budget hint when using iterate mode--trace-live β emit live technical trace markers into the same chat/thread (debug mode)Why file-based prompts?
Research/complex prompts contain single quotes, double quotes, markdown, backticks β any of these break shell argument parsing. Saving to a file and reading with$(cat ...) avoids all quoting issues.