claude-nights-watch-marketplace
Official marketplace for Claude Nights Watch plugin
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/aniketkarne-claudenightswatch)HTML
<a href="/listings/aniketkarne-claudenightswatch"><img src="/api/listings/aniketkarne-claudenightswatch/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Prerequisites
1. [Claude CLI](https://docs.anthropic.com/en/docs/claude-code/quickstart) installed and configured 2. (Optional) [ccusage](https://www.npmjs.com/package/ccusage) for accurate timing:
npm install -g ccusage
---
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 16 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "claude-nights-watch-marketplace",
- "description": "Official marketplace for Claude Nights Watch plugin",
- "owner": {
- "name": "Aniket Karne",
- "email": "[email protected]",
- "url": "https://github.com/aniketkarne/ClaudeNightsWatch"
- },
- "plugins": [
- {
- "name": "claude-nights-watch",
- "source": "./",
- "description": "Autonomous task execution daemon for Claude CLI"
- }
- ]
- }
README.md · README · 618 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # Claude Nights Watch 🌙
- [](https://opensource.org/licenses/MIT)
- [](https://www.gnu.org/software/bash/)
- [](https://docs.anthropic.com/claude-code)
- [](https://github.com/aniketkarne/ClaudeNightsWatch)
- **🚀 NEW: Now available as a Claude Code Plugin!** 🎉
- Autonomous task execution system for Claude CLI that monitors your usage windows and executes predefined tasks automatically. Built on top of the claude-auto-renew concept but instead of simple renewals, it executes complex tasks from a task.md file.
- **⚠️ Warning**: This tool uses `--dangerously-skip-permissions` for autonomous execution. Use with caution!
- ## 🎯 Two Ways to Use Claude Nights Watch
- Choose your preferred installation method:
- ### 🔥 **Recommended: Claude Code Plugin** (NEW!)
- - **Seamless Integration**: Works directly within Claude Code
- - **7 Slash Commands**: `/nights-watch start/stop/status/logs/task/setup/restart`
- - **AI Agent Integration**: Built-in Task Executor agent for autonomous guidance
- - **Smart Hooks**: Automatic session integration and activity logging
- - **MCP Server**: Programmatic control tools for Claude
- - **Enhanced UX**: Better error handling and user experience
- ### ⚡ **Original Daemon Method** (Legacy)
- - **Standalone Operation**: Works independently of Claude Code
- - **Script-based Control**: Direct shell script execution
- - **Proven Reliability**: Battle-tested daemon implementation
- - **Full Feature Set**: All core functionality available
- ## 🎯 Overview
- Claude Nights Watch extends the auto-renewal concept to create a fully autonomous task execution system. When your Claude usage window is about to expire, instead of just saying "hi", it reads your `task.md` file and executes the defined tasks autonomously.
- ### Key Features
- - 🤖 **Autonomous Execution**: Runs tasks without manual intervention
- - 📋 **Task-Based Workflow**: Define tasks in a simple markdown file
- - 🛡️ **Safety Rules**: Configure safety constraints in `rules.md`
- - ⏰ **Smart Timing**: Uses ccusage for accurate timing or falls back to time-based checking
- - 📅 **Scheduled Start**: Can be configured to start at a specific time
- - 📊 **Comprehensive Logging**: Track all activities and executions
- - 🔄 **Based on Proven Code**: Built on the reliable claude-auto-renew daemon
- ## 🚀 Quick Start
- ### Prerequisites
- 1. [Claude CLI](https://docs.anthropic.com/en/docs/claude-code/quickstart) installed and configured
- 2. (Optional) [ccusage](https://www.npmjs.com/package/ccusage) for accurate timing:
- ```bash
- npm install -g ccusage
- ```
- ---
- ## 🔥 Plugin Installation (Recommended)
- ### Option 1: As Claude Code Plugin
- #### Standard Installation
- ```bash
- # Method 1: From marketplace
- claude plugin marketplace add https://github.com/aniketkarne/ClaudeNightsWatch
- claude plugin install claude-nights-watch@claude-nights-watch-marketplace
- # Method 2: Direct from GitHub
- claude plugin install https://github.com/aniketkarne/ClaudeNightsWatch
- # Method 3: From local directory (for development)
- claude plugin marketplace add /path/to/ClaudeNightsWatch
- claude plugin install claude-nights-watch@claude-nights-watch-marketplace
- ```
- #### One-Command Installation
- Use the [Claude Plugins CLI](https://claude-plugins.dev) to skip the marketplace setup:
- ```bash
- npx claude-plugins install @aniketkarne/claude-nights-watch-marketplace/claude-nights-watch
- ```
- This automatically adds the marketplace and installs the plugin in a single step.
- ### Plugin Usage
- ```bash
- # Interactive setup
- /nights-watch setup
- # Start daemon
- /nights-watch start
- # Check status
- /nights-watch status
- # View logs in real-time
- /nights-watch logs -f
- # Stop daemon
- /nights-watch stop
- ```
- **Plugin Features:**
- - 🎯 **7 Slash Commands**: `/nights-watch start/stop/status/logs/task/setup/restart`
- - 🧠 **AI Agent**: Built-in Task Executor for autonomous guidance
- - 🔗 **MCP Server**: 8 programmatic tools for Claude control
- - 🎣 **Smart Hooks**: Automatic session integration
- ---
- ## ⚡ Original Daemon Installation (Legacy)
- ### Option 2: Install as Standalone Daemon
- 1. Clone this repository:
- ```bash
- git clone https://github.com/aniketkarne/ClaudeNightsWatch.git
- cd ClaudeNightsWatch
- ```
- 2. Make scripts executable:
- ```bash
- chmod +x *.sh
- ```
- 3. Run the interactive setup:
- ```bash
- ./setup-nights-watch.sh
- ```
- ### Daemon Usage
- 1. **Create your task file** (`task.md`):
- ```markdown
- # Daily Development Tasks
- 1. Run linting on all source files
- 2. Update dependencies to latest versions
- 3. Run the test suite
- 4. Generate coverage report
- 5. Create a summary of changes
- ```
- 2. **Create safety rules** (`rules.md`):
- ```markdown
- # Safety Rules
- - Never delete files without backing up
- - Only work within the project directory
- - Always create feature branches for changes
- - Never commit sensitive information
- ```
- 3. **Start the daemon**:
- ```bash
- ./claude-nights-watch-manager.sh start
- ```
- **Legacy Commands:**
- ```bash
- ./claude-nights-watch-manager.sh start [--at TIME] # Start daemon
- ./claude-nights-watch-manager.sh stop # Stop daemon
- ./claude-nights-watch-manager.sh status # Check status
- ./claude-nights-watch-manager.sh logs [-f] # View logs
- ./claude-nights-watch-manager.sh task # View task/rules
- ./claude-nights-watch-manager.sh restart # Restart daemon
- ```
- ## 📝 Configuration
- ### Task File (task.md)
- The task file contains the instructions that Claude will execute. It should be clear, specific, and well-structured. See `examples/task.example.md` for a comprehensive example.
- ### Rules File (rules.md)
- The rules file defines safety constraints and best practices. It's prepended to every task execution to ensure safe autonomous operation. See `examples/rules.example.md` for recommended rules.
- ### Environment Variables
- - `CLAUDE_NIGHTS_WATCH_DIR`: Set the directory containing task.md and rules.md (default: current directory)
- ## 🎮 Commands
- ### 🔥 Plugin Commands (NEW!)
- When using as a Claude Code plugin, use slash commands:
- ```bash
- # Start the daemon
- /nights-watch start
- # Start with scheduled time
- /nights-watch start --at "09:00"
- /nights-watch start --at "2025-01-28 14:30"
- # Stop the daemon
- /nights-watch stop
- # Check status
- /nights-watch status
- # View logs
- /nights-watch logs
- /nights-watch logs -f # Follow mode
- # View current task and rules
- /nights-watch task
- # Interactive setup
- /nights-watch setup
- # Restart daemon
- /nights-watch restart
- ```
- ### ⚡ Original Daemon Commands (Legacy)
- For standalone daemon usage:
- ```bash
- # Start the daemon
- ./claude-nights-watch-manager.sh start
- # Start with scheduled time
- ./claude-nights-watch-manager.sh start --at "09:00"
- ./claude-nights-watch-manager.sh start --at "2025-01-28 14:30"
- # Stop the daemon
- ./claude-nights-watch-manager.sh stop
- # Check status
- ./claude-nights-watch-manager.sh status
- # View logs
- ./claude-nights-watch-manager.sh logs
- ./claude-nights-watch-manager.sh logs -f # Follow mode
- # Use interactive log viewer
- ./view-logs.sh
- # View current task and rules
- ./claude-nights-watch-manager.sh task
- # Restart daemon
- ./claude-nights-watch-manager.sh restart
- ```
- ---
- ## 🧠 Plugin Features (NEW!)
- ### Task Executor Agent
- Built-in AI agent that helps with:
- - **Autonomous Task Planning**: Designing effective autonomous workflows
- - **Safety Rule Creation**: Building comprehensive safety constraints
- - **Daemon Management**: Starting, stopping, and troubleshooting
- - **Log Analysis**: Interpreting execution results and identifying issues
- **Usage:**
- ```
- User: "Help me create an autonomous code review workflow"
- Agent: Provides expert guidance and can execute /nights-watch commands
- User: "My daemon isn't working, help debug"
- Agent: Analyzes logs and suggests solutions
- ```
- ### MCP Server Integration
- Provides 8 programmatic tools for Claude:
- - `get_daemon_status` - Query daemon state
- - `start_daemon` - Start with optional schedule
- - `stop_daemon` - Stop the daemon
- - `get_logs` - Retrieve log entries
- - `read_task` - Read task.md content
- - `read_rules` - Read rules.md content
- - `write_task` - Update task.md
- - `write_rules` - Update rules.md
- ### Smart Hooks
- Automatic integration with Claude Code sessions:
- - **SessionStart**: Shows daemon status when starting Claude Code
- - **SessionEnd**: Prompts to start daemon if tasks are configured
- - **PostToolUse**: Logs file modifications for audit trail
- These hooks run silently in the background, enhancing your workflow.
- ## 🔧 How It Works
- 1. **Monitoring**: The daemon continuously monitors your Claude usage windows
- 2. **Timing**: When approaching the 5-hour limit (within 2 minutes), it prepares for execution
- 3. **Task Preparation**: Reads both `rules.md` and `task.md`, combining them into a single prompt
- 4. **Autonomous Execution**: Executes the task using `claude --dangerously-skip-permissions`
- 5. **Logging**: All activities are logged to `logs/claude-nights-watch-daemon.log`
- ### Timing Logic
- - **With ccusage**: Gets accurate remaining time from the API
- - **Without ccusage**: Falls back to timestamp-based checking
- - **Adaptive intervals**:
- - \>30 minutes remaining: Check every 10 minutes
- - 5-30 minutes remaining: Check every 2 minutes
- - <5 minutes remaining: Check every 30 seconds
- ## ⚠️ Safety Considerations
- **IMPORTANT**: This tool runs Claude with the `--dangerously-skip-permissions` flag, meaning it will execute tasks without asking for confirmation.
- ### Best Practices:
- 1. **Always test tasks manually first** before setting up autonomous execution
- 2. **Use comprehensive rules.md** to prevent destructive actions
- 3. **Start with simple, safe tasks** and gradually increase complexity
- 4. **Monitor logs regularly** to ensure proper execution
- 5. **Keep backups** of important data
- 6. **Run in isolated environments** when possible
- ### Recommended Restrictions:
- - Limit file system access to project directories
- - Prohibit deletion commands
- - Prevent system modifications
- - Restrict network access
- - Set resource limits
- ## 📁 File Structure
- ### 🔥 Plugin Structure (NEW!)
- When installed as a Claude Code plugin, the following structure is used:
- ```
- claude-nights-watch/
- ├── .claude-plugin/ # Plugin metadata (NEW!)
- │ └── plugin.json # Plugin manifest
- ├── commands/ # Slash command definitions (NEW!)
- │ ├── bin/nights-watch # Command wrapper
- │ ├── start.md # Start command documentation
- │ ├── stop.md # Stop command documentation
- │ ├── status.md # Status command documentation
- │ ├── logs.md # Logs command documentation
- │ ├── task.md # Task command documentation
- │ ├── setup.md # Setup command documentation
- │ └── restart.md # Restart command documentation
- ├── agents/ # AI agents (NEW!)
- │ └── task-executor.md # Autonomous task planning agent
- ├── hooks/ # Event handlers (NEW!)
- │ ├── hooks.json # Hook configuration
- │ └── scripts/ # Hook implementation scripts
- │ ├── check-daemon-status.sh # Session start hook
- │ ├── session-end-prompt.sh # Session end hook
- │ └── log-file-changes.sh # File modification hook
- ├── mcp-server/ # Model Context Protocol (NEW!)
- │ └── nights-watch-server.sh # MCP server implementation
- ├── .mcp.json # MCP server configuration (NEW!)
- └── [original files continue below...]
- ```
- ### ⚡ Original Daemon Structure (Legacy)
- The original standalone daemon structure:
- ```
- claude-nights-watch/
- ├── claude-nights-watch-daemon.sh # Core daemon process
- ├── claude-nights-watch-manager.sh # Daemon management interface
- ├── setup-nights-watch.sh # Interactive setup script
- ├── view-logs.sh # Interactive log viewer
- ├── README.md # This file
- ├── LICENSE # MIT License
- ├── CONTRIBUTING.md # Contribution guidelines
- ├── CHANGELOG.md # Version history
- ├── SUMMARY.md # Project summary
- ├── .gitignore # Git ignore file
- ├── .github/ # GitHub templates
- │ ├── ISSUE_TEMPLATE/
- │ │ ├── bug_report.md
- │ │ └── feature_request.md
- │ └── pull_request_template.md
- ├── logs/ # All logs stored here (created on first run)
- ├── examples/ # Example files
- │ ├── task.example.md # Example task file
- │ └── rules.example.md # Example rules file
- └── test/ # Test scripts and files
- ├── README.md # Testing documentation
- ├── test-immediate-execution.sh # Direct task execution test
- ├── test-simple.sh # Simple functionality test
- ├── test-task-simple.md # Simple test task
- ├── test-rules-simple.md # Simple test rules
- ├── test-plugin-comprehensive.sh # Plugin functionality tests (NEW!)
- └── test-functional-realworld.sh # Real-world testing suite (NEW!)
- ```
- ## 📊 Logging
- All logs are stored in the `logs/` directory within the project. Each log contains:
- - **Timestamps**: Every action is timestamped
- - **Full Prompts**: Complete prompt sent to Claude (rules + task)
- - **Full Responses**: Everything Claude outputs
- - **Status Messages**: Success/failure indicators
- ### Viewing Logs
- Use the interactive log viewer:
- ```bash
- ./view-logs.sh
- ```
- Features:
- - Browse all log files
- - View full logs or last 50 lines
- - Filter to see only prompts sent to Claude
- - Filter to see only Claude's responses
- - Search for errors
- - Follow logs in real-time
- ## 🧪 Testing
- ### Plugin Testing (NEW!)
- Comprehensive test suites for the Claude Code plugin:
- ```bash
- cd test
- # Run comprehensive plugin structure tests
- ./test-plugin-comprehensive.sh
- # Run functional and real-world testing
- ./test-functional-realworld.sh
- # Run immediate execution test (no waiting)
- ./test-immediate-execution.sh
- # Run simple functionality test
- ./test-simple.sh
- ```
- ### Original Daemon Testing (Legacy)
- ```bash
- cd test
- ./test-simple.sh # Run a simple test
- ```
- See `test/README.md` for detailed testing instructions.
- **New Testing Features:**
- - **Plugin Structure Validation**: Tests all plugin components
- - **Functional Testing**: Validates script execution and integration
- - **Real-World Simulation**: Tests complete user workflows
- - **Environment Testing**: Validates plugin environment variables
- - **Error Handling**: Tests graceful failure scenarios
- ## 🐛 Troubleshooting
- ### Plugin Issues (NEW!)
- **Plugin not loading:**
- ```bash
- # Check plugin installation
- claude plugin list | grep claude-nights-watch
- # Reinstall if needed
- claude plugin uninstall claude-nights-watch
- claude plugin install https://github.com/aniketkarne/ClaudeNightsWatch
- # Debug mode
- claude --debug
- ```
- **Commands not working:**
- ```bash
- # Verify command scripts are executable
- ls -la ~/.claude/plugins/claude-nights-watch/commands/bin/
- # Make executable if needed
- chmod +x ~/.claude/plugins/claude-nights-watch/commands/bin/nights-watch
- ```
- **Agent not responding:**
- - Ensure plugin is properly installed
- - Check that agent file exists in `agents/task-executor.md`
- - Verify MCP server is running
- ### Original Daemon Issues (Legacy)
- **Daemon won't start:**
- - Check if Claude CLI is installed: `which claude`
- - Verify task.md exists in the working directory
- - Check logs: `./claude-nights-watch-manager.sh logs`
- **Tasks not executing:**
- - Verify you have remaining Claude usage: `ccusage blocks`
- - Check if past scheduled start time
- - Ensure task.md is not empty
- - Review logs for errors
- **Timing issues:**
- - Install ccusage for better accuracy: `npm install -g ccusage`
- - Check system time is correct
- - Verify `.claude-last-activity` timestamp
- ### Common Issues (Both Methods)
- **Permission errors:**
- ```bash
- # Ensure all scripts are executable
- chmod +x *.sh
- chmod +x commands/bin/nights-watch
- chmod +x hooks/scripts/*.sh
- chmod +x mcp-server/*.sh
- ```
- **Missing dependencies:**
- - Install Claude CLI: https://docs.anthropic.com/claude-code
- - Install ccusage: `npm install -g ccusage` (recommended)
- - Verify bash is available: `which bash`
- **Configuration issues:**
- - Check task.md exists and has content
- - Verify rules.md exists (recommended)
- - Ensure proper file permissions
- - Check environment variables
- ## 🤝 Contributing
- Contributions are welcome! Please follow these steps:
- 1. **Fork the repository** on GitHub
- 2. **Clone your fork** locally
- 3. **Create a feature branch** (`git checkout -b feature/amazing-feature`)
- 4. **Make your changes** following our guidelines
- 5. **Test thoroughly** using the test suite
- 6. **Commit your changes** (`git commit -m 'Add amazing feature'`)
- 7. **Push to your fork** (`git push origin feature/amazing-feature`)
- 8. **Create a Pull Request** on GitHub
- Please ensure:
- - Code follows existing style
- - Safety is prioritized
- - Documentation is updated
- - Examples are provided
- - Tests pass
- See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.
- ## 📄 License
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
- ## 🙏 Acknowledgments
- - **Created by**: [Aniket Karne](https://github.com/aniketkarne)
- - **Built on top of**: The excellent [CCAutoRenew](https://github.com/aniketkarne/CCAutoRenew) project
- - **Plugin Development**: Complete Claude Code plugin implementation with slash commands, AI agents, MCP server, and smart hooks
- - **Enhanced Features**: Task Executor agent, comprehensive testing suites, and dual installation methods
- - **Thanks to**: The Claude CLI team for the amazing tool and plugin system
- ---
- ---
- ## 🔄 Migration Guide
- ### From Daemon to Plugin
- If you're currently using the standalone daemon and want to migrate to the plugin:
- 1. **Install the plugin**:
- ```bash
- claude plugin install https://github.com/aniketkarne/ClaudeNightsWatch
- ```
- 2. **Copy your existing files**:
- ```bash
- # Copy your task.md and rules.md to the new location
- cp task.md rules.md ~/.claude/plugins/claude-nights-watch/
- ```
- 3. **Update your workflow**:
- - Replace `./claude-nights-watch-manager.sh start` with `/nights-watch start`
- - Replace `./claude-nights-watch-manager.sh logs` with `/nights-watch logs`
- - Use `/nights-watch setup` for configuration
- 4. **Benefits you'll gain**:
- - 🤖 **AI Agent Integration**: Get help from the Task Executor agent
- - 🎯 **Better Commands**: More intuitive slash command interface
- - 🔗 **MCP Integration**: Programmatic control for Claude
- - 🎣 **Smart Hooks**: Automatic session integration
- ### From Plugin to Daemon
- If you prefer the standalone approach:
- 1. **Install as daemon**:
- ```bash
- git clone https://github.com/aniketkarne/ClaudeNightsWatch.git
- cd ClaudeNightsWatch
- chmod +x *.sh
- ```
- 2. **Copy your plugin files**:
- ```bash
- # Copy from plugin location to daemon location
- cp ~/.claude/plugins/claude-nights-watch/task.md .
- cp ~/.claude/plugins/claude-nights-watch/rules.md .
- ```
- 3. **Use daemon commands**:
- ```bash
- ./claude-nights-watch-manager.sh start
- ```
- **Note**: The plugin method is recommended for new users due to better integration and enhanced features.
- ---
- **Remember**: With great automation comes great responsibility. Always review your tasks and rules carefully before enabling autonomous execution! 🚨
claude-nights-watch-daemon.sh · Bundled script · 409 lines · 1 finding marked
- #!/bin/bash
- # Claude Nights Watch Daemon - Autonomous Task Execution
- # Based on claude-auto-renew-daemon but executes tasks instead of simple renewals
- LOG_FILE="${CLAUDE_NIGHTS_WATCH_DIR:-$(dirname "$0")}/logs/claude-nights-watch-daemon.log"
- PID_FILE="${CLAUDE_NIGHTS_WATCH_DIR:-$(dirname "$0")}/logs/claude-nights-watch-daemon.pid"
- LAST_ACTIVITY_FILE="$HOME/.claude-last-activity"
- START_TIME_FILE="${CLAUDE_NIGHTS_WATCH_DIR:-$(dirname "$0")}/logs/claude-nights-watch-start-time"
- TASK_FILE="task.md"
- RULES_FILE="rules.md"
- TASK_DIR="${CLAUDE_NIGHTS_WATCH_DIR:-$(pwd)}"
- # Ensure logs directory exists
- mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null
- # Function to log messages
- log_message() {
- echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
- }
- # Function to handle shutdown
- cleanup() {
- log_message "Daemon shutting down..."
- rm -f "$PID_FILE"
- exit 0
- }
- # Set up signal handlers
- trap cleanup SIGTERM SIGINT
- # Function to check if we're past the start time
- is_start_time_reached() {
- if [ ! -f "$START_TIME_FILE" ]; then
- # No start time set, always active
- return 0
- fi
- local start_epoch=$(cat "$START_TIME_FILE")
- local current_epoch=$(date +%s)
- if [ "$current_epoch" -ge "$start_epoch" ]; then
- return 0 # Start time reached
- else
- return 1 # Still waiting
- fi
- }
- # Function to get time until start
- get_time_until_start() {
- if [ ! -f "$START_TIME_FILE" ]; then
- echo "0"
- return
- fi
- local start_epoch=$(cat "$START_TIME_FILE")
- local current_epoch=$(date +%s)
- local diff=$((start_epoch - current_epoch))
- if [ "$diff" -le 0 ]; then
- echo "0"
- else
- echo "$diff"
- fi
- }
- # Function to get ccusage command
- get_ccusage_cmd() {
- if command -v ccusage &> /dev/null; then
- echo "ccusage"
- elif command -v bunx &> /dev/null; then
- echo "bunx ccusage"
- elif command -v npx &> /dev/null; then
- echo "npx ccusage@latest"
- else
- return 1
- fi
- }
- # Function to get minutes until reset
- get_minutes_until_reset() {
- local ccusage_cmd=$(get_ccusage_cmd)
- if [ $? -ne 0 ]; then
- return 1
- fi
- # Use JSON output with --active flag to get only the active block
- local json_output=$($ccusage_cmd blocks --json --active 2>/dev/null)
- if [ -z "$json_output" ]; then
- # No active block - fallback to 0 like original behavior
- echo "0"
- return 0
- fi
- # Extract endTime from the active block
- local end_time=$(echo "$json_output" | grep '"endTime"' | head -1 | sed 's/.*"endTime": *"\([^"]*\)".*/\1/')
- if [ -z "$end_time" ]; then
- echo "0"
- return 0
- fi
- # Convert ISO timestamp to Unix epoch for calculation
- local end_epoch
- if command -v date &> /dev/null; then
- # Try different date command formats (macOS vs Linux)
- # Linux format (handles UTC properly)
- if end_epoch=$(date -d "$end_time" +%s 2>/dev/null); then
- :
- # macOS format - need to specify UTC timezone
- elif end_epoch=$(TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%S.000Z" "$end_time" +%s 2>/dev/null); then
- :
- # macOS format without milliseconds in UTC
- elif end_epoch=$(TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%SZ" "$end_time" +%s 2>/dev/null); then
- :
- # Try stripping the .000Z and parsing in UTC
- elif stripped_time=$(echo "$end_time" | sed 's/\.000Z$/Z/') && end_epoch=$(TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%SZ" "$stripped_time" +%s 2>/dev/null); then
- :
- else
- log_message "Could not parse ccusage endTime format: $end_time" >&2
- echo "0"
- return 0
- fi
- else
- echo "0"
- return 0
- fi
- local current_epoch=$(date +%s)
- local time_diff=$((end_epoch - current_epoch))
- local remaining_minutes=$((time_diff / 60))
- if [ "$remaining_minutes" -gt 0 ]; then
- echo $remaining_minutes
- else
- echo "0"
- return 0
- fi
- }
- # Function to prepare task with rules
- prepare_task_prompt() {
- local prompt=""
- # Add rules if they exist
- if [ -f "$TASK_DIR/$RULES_FILE" ]; then
- prompt="IMPORTANT RULES TO FOLLOW:\n\n"
- prompt+=$(cat "$TASK_DIR/$RULES_FILE")
- prompt+="\n\n---END OF RULES---\n\n"
- log_message "Applied rules from $RULES_FILE"
- fi
- # Add task content
- if [ -f "$TASK_DIR/$TASK_FILE" ]; then
- prompt+="TASK TO EXECUTE:\n\n"
- prompt+=$(cat "$TASK_DIR/$TASK_FILE")
- prompt+="\n\n---END OF TASK---\n\n"
- prompt+="Please read the above task, create a todo list from it, and then execute it step by step."
- else
- log_message "ERROR: Task file not found at $TASK_DIR/$TASK_FILE"
- return 1
- fi
- echo -e "$prompt"
- }
- # Function to execute task
- execute_task() {
- log_message "Starting task execution from $TASK_FILE..."
- if ! command -v claude &> /dev/null; then
- log_message "ERROR: claude command not found"
- return 1
- fi
- # Check if task file exists
- if [ ! -f "$TASK_DIR/$TASK_FILE" ]; then
- log_message "ERROR: Task file not found at $TASK_DIR/$TASK_FILE"
- return 1
- fi
- # Prepare the full prompt with rules and task
- local full_prompt=$(prepare_task_prompt)
- if [ $? -ne 0 ]; then
- return 1
- fi
- log_message "Executing task with Claude (autonomous mode)..."
- # Log the full prompt being sent
- echo "" >> "$LOG_FILE"
- echo "=== PROMPT SENT TO CLAUDE ===" >> "$LOG_FILE"
- echo -e "$full_prompt" >> "$LOG_FILE"
- echo "=== END OF PROMPT ===" >> "$LOG_FILE"
- echo "" >> "$LOG_FILE"
- # Execute task with Claude in autonomous mode
- # Log everything - both the execution and the response
- log_message "=== CLAUDE RESPONSE START ==="
- (echo -e "$full_prompt" | claude --dangerously-skip-permissions 2>&1) | tee -a "$LOG_FILE" &
- Note: Starts a coding agent with its permission prompts off
- Line 201 on GitHub
- local pid=$!
- # Monitor execution (no timeout for complex tasks)
- log_message "Task execution started (PID: $pid)"
- # Wait for completion
- wait $pid
- local result=$?
- log_message "=== CLAUDE RESPONSE END ==="
- if [ $result -eq 0 ]; then
- log_message "Task execution completed successfully"
- date +%s > "$LAST_ACTIVITY_FILE"
- return 0
- else
- log_message "ERROR: Task execution failed with code $result"
- return 1
- fi
- }
- # Function to calculate next check time
- calculate_sleep_duration() {
- local minutes_remaining=$(get_minutes_until_reset)
- if [ -n "$minutes_remaining" ] && [ "$minutes_remaining" -gt 0 ]; then
- log_message "Time remaining: $minutes_remaining minutes" >&2
- if [ "$minutes_remaining" -le 5 ]; then
- # Check every 30 seconds when close to reset
- echo 30
- elif [ "$minutes_remaining" -le 30 ]; then
- # Check every 2 minutes when within 30 minutes
- echo 120
- else
- # Check every 10 minutes otherwise
- echo 600
- fi
- else
- # Fallback: check based on last activity
- if [ -f "$LAST_ACTIVITY_FILE" ]; then
- local last_activity=$(cat "$LAST_ACTIVITY_FILE")
- local current_time=$(date +%s)
- local time_diff=$((current_time - last_activity))
- local remaining=$((18000 - time_diff)) # 5 hours = 18000 seconds
- if [ "$remaining" -le 300 ]; then # 5 minutes
- echo 30
- elif [ "$remaining" -le 1800 ]; then # 30 minutes
- echo 120
- else
- echo 600
- fi
- else
- # No info available, check every 5 minutes
- echo 300
- fi
- fi
- }
- # Main daemon loop
- main() {
- # Check if already running
- if [ -f "$PID_FILE" ]; then
- OLD_PID=$(cat "$PID_FILE")
- if kill -0 "$OLD_PID" 2>/dev/null; then
- echo "Daemon already running with PID $OLD_PID"
- exit 1
- else
- log_message "Removing stale PID file"
- rm -f "$PID_FILE"
- fi
- fi
- # Save PID
- echo $$ > "$PID_FILE"
- log_message "=== Claude Nights Watch Daemon Started ==="
- log_message "PID: $$"
- log_message "Logs: $LOG_FILE"
- log_message "Task directory: $TASK_DIR"
- # Check for task file
- if [ ! -f "$TASK_DIR/$TASK_FILE" ]; then
- log_message "WARNING: Task file not found at $TASK_DIR/$TASK_FILE"
- log_message "Please create a task.md file with your tasks"
- fi
- # Check for rules file
- if [ -f "$TASK_DIR/$RULES_FILE" ]; then
- log_message "Rules file found at $TASK_DIR/$RULES_FILE"
- else
- log_message "No rules file found. Consider creating $RULES_FILE for safety constraints"
- fi
- # Check for start time
- if [ -f "$START_TIME_FILE" ]; then
- start_epoch=$(cat "$START_TIME_FILE")
- log_message "Start time configured: $(date -d "@$start_epoch" 2>/dev/null || date -r "$start_epoch")"
- else
- log_message "No start time set - will begin monitoring immediately"
- fi
- # Check ccusage availability
- if ! get_ccusage_cmd &> /dev/null; then
- log_message "WARNING: ccusage not found. Using time-based checking."
- log_message "Install ccusage for more accurate timing: npm install -g ccusage"
- fi
- # Main loop
- while true; do
- # Check if we're past start time
- if ! is_start_time_reached; then
- time_until_start=$(get_time_until_start)
- hours=$((time_until_start / 3600))
- minutes=$(((time_until_start % 3600) / 60))
- seconds=$((time_until_start % 60))
- if [ "$hours" -gt 0 ]; then
- log_message "Waiting for start time (${hours}h ${minutes}m remaining)..."
- sleep 300 # Check every 5 minutes when waiting
- elif [ "$minutes" -gt 2 ]; then
- log_message "Waiting for start time (${minutes}m ${seconds}s remaining)..."
- sleep 60 # Check every minute when close
- elif [ "$time_until_start" -gt 10 ]; then
- log_message "Waiting for start time (${minutes}m ${seconds}s remaining)..."
- sleep 10 # Check every 10 seconds when very close
- else
- log_message "Waiting for start time (${seconds}s remaining)..."
- sleep 2 # Check every 2 seconds when imminent
- fi
- continue
- fi
- # If we just reached start time, log it
- if [ -f "$START_TIME_FILE" ]; then
- # Check if this is the first time we're active
- if [ ! -f "${START_TIME_FILE}.activated" ]; then
- log_message "✅ Start time reached! Beginning task execution monitoring..."
- touch "${START_TIME_FILE}.activated"
- fi
- fi
- # Get minutes until reset
- minutes_remaining=$(get_minutes_until_reset)
- # Check if we should execute task
- should_execute=false
- if [ -n "$minutes_remaining" ] && [ "$minutes_remaining" -gt 0 ]; then
- if [ "$minutes_remaining" -le 2 ]; then
- should_execute=true
- log_message "Reset imminent ($minutes_remaining minutes), preparing to execute task..."
- fi
- else
- # Fallback check
- if [ -f "$LAST_ACTIVITY_FILE" ]; then
- last_activity=$(cat "$LAST_ACTIVITY_FILE")
- current_time=$(date +%s)
- time_diff=$((current_time - last_activity))
- if [ $time_diff -ge 18000 ]; then
- should_execute=true
- log_message "5 hours elapsed since last activity, executing task..."
- fi
- else
- # No activity recorded, safe to start
- should_execute=true
- log_message "No previous activity recorded, starting initial task execution..."
- fi
- fi
- # Execute task if needed
- if [ "$should_execute" = true ]; then
- # Check if task file exists before execution
- if [ ! -f "$TASK_DIR/$TASK_FILE" ]; then
- log_message "ERROR: Cannot execute - task file not found at $TASK_DIR/$TASK_FILE"
- log_message "Waiting 5 minutes before next check..."
- sleep 300
- continue
- fi
- # Wait a bit to ensure we're in the renewal window
- sleep 60
- # Try to execute task
- if execute_task; then
- log_message "Task execution completed!"
- # Sleep for 5 minutes after successful execution
- sleep 300
- else
- log_message "Task execution failed, will retry in 1 minute"
- sleep 60
- fi
- fi
- # Calculate how long to sleep
- sleep_duration=$(calculate_sleep_duration)
- log_message "Next check in $((sleep_duration / 60)) minutes"
- # Sleep until next check
- sleep "$sleep_duration"
- done
- }
- # Start the daemon
- main
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.