yatfa 1.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yatfa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,252 @@
1
+ # YATFA Agent (Yet Another Tool For Agents)
2
+
3
+ Run YATFA agents in any Docker container with Ruby.
4
+
5
+ ## Quick Start
6
+
7
+ The easiest way to get started is with the interactive setup wizard:
8
+
9
+ ```bash
10
+ npx yatfa-agent setup
11
+ ```
12
+
13
+ The wizard will guide you through:
14
+ 1. **YATFA Platform URL** - Your YATFA instance
15
+ 2. **Agent API Keys** - From the YATFA web UI
16
+ 3. **Git Configuration** - Identity for commits
17
+ 4. **GitHub Authentication** - Token or App credentials
18
+ 5. **Environment Variables** (optional) - API keys, secrets
19
+
20
+ The wizard validates everything before creating your configuration file.
21
+
22
+ ## Manual Setup
23
+
24
+ If you prefer to configure manually, create `Dockerfile.sandbox` in your project root (copy your existing Dockerfile).
25
+ Read INSTALLATION.md for detailed guide.
26
+
27
+ ## Configuration (yatfa.env.rb)
28
+
29
+ Agents are configured via a `yatfa.env.rb` file in your project root. This Ruby file allows you to define configuration and secrets (using heredocs).
30
+
31
+ **Do not commit `yatfa.env.rb` to git!** Add it to your `.gitignore`.
32
+
33
+ **Pro tip:** Use `npx yatfa-agent setup` to generate this file interactively with validation.
34
+
35
+ Example `yatfa.env.rb`:
36
+
37
+ ```ruby
38
+ {
39
+ yatfa_url: "https://yatfa.ai", # Platform URL
40
+
41
+ # Git Identity
42
+ git: {
43
+ user_name: "YATFA Agent",
44
+ user_email: "agent@example.com"
45
+ },
46
+
47
+ # GitHub Auth (Optional)
48
+ # GitHub authentication is now handled by the Rails backend
49
+ # The backend uses its own GitHub App to generate tokens for agents
50
+ # You can remove the 'github' section entirely, or use GH_TOKEN as fallback
51
+ github: {
52
+ token: "ghp_..." # Optional: for development/testing only
53
+ },
54
+
55
+ # Agent Specific Config
56
+ agents: {
57
+ worker: {
58
+ mcp_api_key: "...",
59
+ container_name: "yatfa-worker"
60
+ },
61
+ planner: {
62
+ mcp_api_key: "...",
63
+ container_name: "yatfa-planner"
64
+ }
65
+ },
66
+
67
+ # Environment Variables Injection
68
+ # Simple strings or Heredocs supported
69
+ dot_env: <<~ENV
70
+ PORT=3200
71
+ DB_HOST=localhost
72
+ SECRET_KEY_BASE=very_secret
73
+ ENV
74
+ }
75
+ ```
76
+
77
+ ## Environment Variables
78
+
79
+ | Variable | Required | Description |
80
+ |----------|----------|-------------|
81
+ | `AGENT_TYPE` | ✅ | `worker`, `planner`, `reviewer`, or `researcher` |
82
+ | `YATFA_URL` | ✅ | YATFA platform URL (WebSocket and API URLs are derived from this) |
83
+ | `YATFA_API_KEY` | | MCP API key (get from YATFA dashboard) |
84
+ | `GH_TOKEN` | | GitHub token for git operations |
85
+
86
+ ## Agent Types
87
+
88
+ | Type | Mode | Purpose |
89
+ |------|------|---------|
90
+ | `planner` | Interactive | Chat with human, create tickets |
91
+ | `worker` | Autonomous | Implement tickets, create PRs |
92
+ | `reviewer` | Autonomous | Review PRs, approve/reject |
93
+ | `researcher` | Autonomous | Analyze codebase, document findings |
94
+
95
+ ## Commands
96
+
97
+ ### Setup
98
+
99
+ ```bash
100
+ npx yatfa-agent setup
101
+ ```
102
+
103
+ Launches interactive setup wizard to configure `yatfa.env.rb`.
104
+
105
+ ### Run Agents
106
+
107
+ ```bash
108
+ # Start an agent
109
+ npx yatfa-agent worker
110
+ npx yatfa-agent planner
111
+ npx yatfa-agent reviewer
112
+ npx yatfa-agent researcher
113
+ ```
114
+
115
+ ### Attach to Running Agents
116
+
117
+ ```bash
118
+ npx yatfa-agent attach worker
119
+ ```
120
+
121
+ Opens tmux session to view agent activity.
122
+
123
+ ### List Running Agents
124
+
125
+ ```bash
126
+ npx yatfa-agent list
127
+ ```
128
+
129
+ ### Stop All Agents
130
+
131
+ ```bash
132
+ npx yatfa-agent stop-all
133
+ ```
134
+
135
+ ## What the Script Does
136
+
137
+ 1. **Validates requirements** - Checks for Ruby, Node, tmux, git, claude CLI
138
+ 2. **Creates `.mcp.json`** - Configures MCP tools for the agent type
139
+ 3. **Creates `CLAUDE.md`** - Role-specific instructions Claude sees on startup
140
+ 4. **Sets up GitHub auth** - Requests tokens from Rails backend for git operations
141
+ 5. **Downloads agent-bridge** - Binary that connects to YATFA via WebSocket
142
+ 6. **Starts tmux session** - With status bar showing connection state
143
+
144
+ **Note:** GitHub credentials are now managed centrally in the Rails backend. Agents request GitHub tokens via the API endpoint `/api/v1/github/token` using their MCP API key. This is more secure than storing private keys in each agent's configuration.
145
+
146
+ ## Knowledge Injection System
147
+
148
+ YATFA agents can automatically receive project-specific knowledge through the Knowledge Article system. This enables agents to learn project-specific patterns, conventions, and context without manual configuration.
149
+
150
+ ### How It Works
151
+
152
+ The knowledge injection system uses **Claude hooks** to fetch relevant knowledge articles from the Rails API and inject them into the agent's context at key moments:
153
+
154
+ 1. **Session Start Hook** (`sessionstart-input.sh`) - Injects agent-specific state knowledge when an agent session starts
155
+ 2. **Skill Hooks** - Injects skill-specific hints when particular skills are invoked (e.g., git-workflow, ticket-management)
156
+
157
+ ### Knowledge Categories
158
+
159
+ Knowledge articles are organized by purpose, not content type:
160
+
161
+ | Category | Purpose | Example |
162
+ |----------|---------|---------|
163
+ | `agent_state_worker` | Worker agent's evolving context | Git patterns, testing conventions |
164
+ | `agent_state_planner` | Planner agent's context | Ticket creation patterns |
165
+ | `agent_state_reviewer` | Reviewer agent's context | Code review standards |
166
+ | `agent_state_researcher` | Researcher agent's context | Analysis patterns |
167
+ | `skill_hint_git-workflow` | Git workflow guidance | Branch naming, commit conventions |
168
+ | `skill_hint_ticket-management` | Ticket management guidance | Ticket creation workflows |
169
+ | `project_knowledge` | General documentation | Architecture docs, troubleshooting |
170
+
171
+ ### Setup Requirements
172
+
173
+ The knowledge injection system requires these environment variables:
174
+
175
+ ```bash
176
+ YATFA_URL=https://yatfa.example.com
177
+ YATFA_API_KEY=your_api_key_here
178
+ AGENT_TYPE=worker
179
+ ```
180
+
181
+ Note: `YATFA_API_URL` and `YATFA_WS_URL` are derived from `YATFA_URL` by `setup-agent.rb`. Project is automatically determined by the API key authentication.
182
+
183
+ ### Agent Self-Update
184
+
185
+ Agents can modify their own knowledge via MCP tools:
186
+
187
+ ```ruby
188
+ # Agent updates its state
189
+ update_knowledge_article(
190
+ article_id: 42,
191
+ content: "Updated pattern based on recent work...",
192
+ category: "agent_state_worker"
193
+ )
194
+ ```
195
+
196
+ Changes take effect on the next `/new` command or session restart.
197
+
198
+ ### Managing Knowledge Articles
199
+
200
+ Knowledge articles are managed through the Rails API or MCP tools:
201
+
202
+ - **Create:** `store_knowledge_article` via MCP
203
+ - **Search:** `search_knowledge_articles` via MCP
204
+ - **Update:** Edit articles via Rails dashboard or MCP
205
+ - **Categorize:** Assign to appropriate category for automatic injection
206
+
207
+ ### Example Workflow
208
+
209
+ 1. **Human creates a knowledge article:**
210
+ ```ruby
211
+ # Via MCP or Rails API
212
+ create_article(
213
+ title: "Worker Git Conventions",
214
+ category: "agent_state_worker",
215
+ content: "Always use feature/ticket-id-description format..."
216
+ )
217
+ ```
218
+
219
+ 2. **Agent session starts:**
220
+ ```bash
221
+ # sessionstart-input.sh runs automatically
222
+ # Fetches agent_state_worker articles
223
+ # Injects them into Claude's context
224
+ ```
225
+
226
+ 3. **Agent has context:**
227
+ ```
228
+ # Worker sees this at session start:
229
+ ## Knowledge: Worker Git Conventions
230
+ Always use feature/ticket-id-description format...
231
+ ```
232
+
233
+ ### Hook Files
234
+
235
+ Hook scripts are located in `/hooks/`:
236
+
237
+ - `sessionstart-input.sh` - Runs when Claude session starts
238
+ - `skill-hooks/*.sh` - Runs when specific skills are loaded
239
+
240
+ See hook files for implementation details and customization options.
241
+
242
+ ## Attaching to Running Agent
243
+
244
+ ```bash
245
+ docker exec -it <container> tmux attach -t agent-wrapper
246
+ ```
247
+
248
+ Press `Ctrl+B` then `D` to detach.
249
+
250
+ ## License
251
+
252
+ MIT
package/agents.rb ADDED
@@ -0,0 +1,198 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Common sections shared across all agents
4
+ UNIVERSAL_CONSTRAINTS = <<~CONSTRAINTS
5
+ ## UNIVERSAL OPERATIONAL CONSTRAINTS
6
+ 1. **TOOL FORMATTING:** Do not use a colon before tool calls (e.g., write "Let me search." not "Let me search:").
7
+ 2. **URL SAFETY:** NEVER guess or hallucinate URLs. Use only known valid URLs.
8
+ 3. **REDIRECTS:** If `WebFetch` returns a redirect, follow it immediately.
9
+ 4. **CODE REFS:** Use the format `file_path:line_number` (e.g., `app/models/user.rb:42`).
10
+ CONSTRAINTS
11
+
12
+ TASK_TRACKING = <<~TRACKING
13
+ ## TASK TRACKING
14
+ * **TodoWrite:** Use for TEMPORAL, SESSION-SPECIFIC thinking (your scratchpad). Always update `TodoWrite` to reflect your current immediate step.
15
+ * **Ticket Tools:** Use for PERSISTENT project work (database storage).
16
+ TRACKING
17
+
18
+ # Planner sections
19
+ PLANNER_HEADER = <<~HEADER
20
+ **IDENTITY & ROLE**
21
+ You are the YATFA PLANNER. You act as the Architect.
22
+ Your goal is **Requirements Analysis and Work Definition**.
23
+ You operate in an **Interactive Chat** mode with the human user.
24
+ HEADER
25
+
26
+ PLANNER_BOUNDARIES = <<~BOUNDARIES
27
+ ## ROLE BOUNDARIES
28
+ **ABSOLUTELY FORBIDDEN:**
29
+ * Writing implementation code.
30
+ * Making git commits.
31
+ * Creating tickets without human confirmation (propose ticket in chat, then create after approval).
32
+
33
+ **When creating/updating tickets:**
34
+ ALWAYS use the `ticket-management` skill first - it covers ticket writing best practices.
35
+ BOUNDARIES
36
+
37
+ # Worker sections
38
+ WORKER_HEADER = <<~HEADER
39
+ You are the **YATFA WORKER** operating in **FULLY AUTONOMOUS MODE**.
40
+
41
+ **PRIMARY ROLE:** Code Implementation and Testing.
42
+ **HARD CONSTRAINT:** You must NOT create new tasks or reorganize work.
43
+
44
+ ### OPERATIONAL MODE (EVENT-DRIVEN)
45
+ * **Execution Flow:** Receive work via message -> Complete task -> Submit PR -> STOP.
46
+ * **No Polling:** Do not loop, check for new work, or wait for responses.
47
+ * **Status Management:** Mark yourself as 'busy' when starting and 'idle' when submitting the PR.
48
+
49
+ ### ENVIRONMENT
50
+ * Sandboxed Docker container with ROOT privileges.
51
+ * System dependencies may be installed freely.
52
+ * Git configured (GH_TOKEN active, repo synced on main).
53
+ HEADER
54
+
55
+ WORKER_BOUNDARIES = <<~BOUNDARIES
56
+ ### STRICT BOUNDARIES (FORBIDDEN)
57
+ * Creating new tickets, tasks, or breaking down epics (Planner role).
58
+ * Reorganizing or reprioritizing the backlog.
59
+ * Making architectural decisions without approval.
60
+ * Reviewing other workers' code or approving your own work.
61
+ * Strategic planning or project coordination.
62
+ * Committing directly to `main` branch.
63
+ * Merging your own pull requests.
64
+ * Splitting one task into multiple PRs (unless explicitly instructed).
65
+ BOUNDARIES
66
+
67
+ WORKER_ESCALATION = <<~ESCALATION
68
+ ### ESCALATION PROTOCOL
69
+ If blocked (e.g., missing tools, auth errors, ambiguous requirements):
70
+ 1. Use `create_ticket()`.
71
+ 2. **Title:** "Escalation: [brief description]"
72
+ 3. **Priority:** High or Critical.
73
+ 4. **Context:** Include action attempted, error details, related Ticket ID, and suggested fix.
74
+ ESCALATION
75
+
76
+ # Reviewer sections
77
+ REVIEWER_HEADER = <<~HEADER
78
+ You are the **YATFA REVIEWER** agent operating in **FULLY AUTONOMOUS MODE**.
79
+
80
+ **ROLE:** Code Review and Quality Assurance.
81
+ **PRIMARY CONSTRAINT:** You must **NOT** implement solutions. You **ONLY** review them.
82
+
83
+ ### EXECUTION MODEL
84
+ * **Event-Driven:** Do not wait, poll, or loop. Do not add "waiting" to TODOs.
85
+ * **One-Shot:** Receive message -> Review PR -> Pass/Fail Audit -> STOP.
86
+ * **Environment:** Sandboxed Docker container (Root privileges). System dependencies allowed. GH_TOKEN is configured.
87
+ HEADER
88
+
89
+ REVIEWER_BOUNDARIES = <<~BOUNDARIES
90
+ ### FORBIDDEN ACTIONS (STRICT)
91
+ * Do NOT implement new features or functionality.
92
+ * Do NOT write production code to "fix" issues.
93
+ * Do NOT modify reviewed code directly, make git commits, or create PRs.
94
+ * Do NOT create or edit migrations.
95
+ * Do NOT make architectural decisions (document them via comments/proposals instead).
96
+ * Do NOT use the "approve" transition (reserved for humans/PO).
97
+ * Do NOT use `gh pr review --approve` (GitHub forbids self-approval).
98
+ * Do NOT approve any PR without running tests first.
99
+ BOUNDARIES
100
+
101
+ REVIEWER_ESCALATION = <<~ESCALATION
102
+ ### ESCALATION PROTOCOL
103
+ If blocked or workflow is broken:
104
+ 1. Call `create_ticket()`.
105
+ 2. Title: "Escalation: [brief description]"
106
+ 3. Priority: High or Critical.
107
+ 4. Context: What you tried, the error/blocker, and Ticket ID.
108
+ ESCALATION
109
+
110
+ # Researcher sections
111
+ RESEARCHER_HEADER = <<~HEADER
112
+ You are the YATFA RESEARCHER agent operating in FULLY AUTONOMOUS MODE.
113
+ Your role is AUTONOMOUS ANALYSIS and PROPOSAL GENERATION.
114
+
115
+ ### CORE CONSTRAINT
116
+ You have READ-ONLY access to code, tickets, and memories.
117
+ **YOU MUST NOT MODIFY CODE, FILES, OR TICKETS DIRECTLY.**
118
+ You must use `create_proposal` to suggest actions.
119
+
120
+ ### SESSION ENVIRONMENT
121
+ - **Execution Model:** Event-driven. Do not wait, do not poll. When you receive a message: Analyze -> Create Proposals -> STOP.
122
+ - **Access:** Sandboxed Docker container (Root privileges). Read access to all systems.
123
+ - **Skills:** researcher-tactical, researcher-strategic, knowledge-management, memory.
124
+ HEADER
125
+
126
+ RESEARCHER_BOUNDARIES = <<~BOUNDARIES
127
+ ### ROLE BOUNDARIES
128
+
129
+ **ABSOLUTELY FORBIDDEN:**
130
+ - Modifying code, tickets, or files directly.
131
+ - Writing, editing, or refactoring code.
132
+ - Making git commits or pull requests.
133
+ - Sending messages to other agents.
134
+ - Changing your own busy/idle status.
135
+ BOUNDARIES
136
+
137
+ RESEARCHER_ESCALATION = <<~ESCALATION
138
+ ### ESCALATION PROCESS
139
+ If you encounter blocking problems or need to improve workflow:
140
+ 1. Use `create_proposal`.
141
+ 2. **Title:** "Escalation: [brief description]"
142
+ 3. **Type:** task
143
+ 4. **Priority:** high or critical
144
+ 5. **Context:** Include what you tried, the error/blocker, and suggested fix (e.g., "Escalation: Need additional MCP tools for research").
145
+ ESCALATION
146
+
147
+ # Dynamic banner builder
148
+ def build_banner(header:, boundaries:, escalation: nil, extra_sections: [])
149
+ [
150
+ header,
151
+ UNIVERSAL_CONSTRAINTS,
152
+ TASK_TRACKING,
153
+ *extra_sections,
154
+ boundaries,
155
+ escalation
156
+ ].compact.join("\n\n")
157
+ end
158
+
159
+ AGENT_CONFIGS = {
160
+ 'planner' => {
161
+ name: 'yatfa-planner',
162
+ skills: ['ticket-management', 'memory', 'knowledge-management', 'sentry-investigation'],
163
+ banner: build_banner(
164
+ header: PLANNER_HEADER,
165
+ boundaries: PLANNER_BOUNDARIES
166
+ )
167
+ },
168
+
169
+ 'worker' => {
170
+ name: 'yatfa-autonomous-worker',
171
+ skills: ['git-workflow', 'worker-workflow', 'memory'],
172
+ banner: build_banner(
173
+ header: WORKER_HEADER,
174
+ boundaries: WORKER_BOUNDARIES,
175
+ escalation: WORKER_ESCALATION
176
+ )
177
+ },
178
+
179
+ 'reviewer' => {
180
+ name: 'yatfa-autonomous-reviewer',
181
+ skills: ['reviewer-workflow', 'memory', 'proposal-reviewer'],
182
+ banner: build_banner(
183
+ header: REVIEWER_HEADER,
184
+ boundaries: REVIEWER_BOUNDARIES,
185
+ escalation: REVIEWER_ESCALATION
186
+ )
187
+ },
188
+
189
+ 'researcher' => {
190
+ name: 'yatfa-autonomous-researcher',
191
+ skills: ['researcher-tactical', 'researcher-strategic', 'researcher-digest', 'researcher-telegram-processor', 'memory', 'proposal-execution', 'proposal-rework-responder', 'memory-consolidation', 'retrospective', 'knowledge-management', 'sentry-investigation'],
192
+ banner: build_banner(
193
+ header: RESEARCHER_HEADER,
194
+ boundaries: RESEARCHER_BOUNDARIES,
195
+ escalation: RESEARCHER_ESCALATION
196
+ )
197
+ }
198
+ }.freeze
@@ -0,0 +1,63 @@
1
+ #!/bin/bash
2
+ # Wrapper script to run agent-bridge inside tmux with status bar
3
+
4
+ set -e
5
+
6
+ AGENT_TYPE="${AGENT_TYPE:-worker}"
7
+ AGENT_ID="${AGENT_ID:-}"
8
+ STATUS_FILE="/tmp/agent-bridge-status"
9
+
10
+ # Check if we're already inside tmux
11
+ if [ -n "$TMUX" ]; then
12
+ export STATUS_FILE
13
+ export AGENT_ID
14
+ exec agent-bridge
15
+ fi
16
+
17
+ # Check if tmux is available
18
+ if ! command -v tmux &> /dev/null; then
19
+ echo "❌ tmux not found. Running bridge directly..."
20
+ exec agent-bridge
21
+ fi
22
+
23
+ # Clean up status file on exit
24
+ cleanup() { rm -f "$STATUS_FILE"; }
25
+ trap cleanup EXIT
26
+
27
+ echo "⟳ connecting" > "$STATUS_FILE"
28
+
29
+ SESSION="agent"
30
+ tmux kill-session -t "$SESSION" 2>/dev/null || true
31
+
32
+ COLS=$(tput cols 2>/dev/null || echo 120)
33
+ LINES=$(tput lines 2>/dev/null || echo 40)
34
+ tmux new-session -d -s "$SESSION" -x "$COLS" -y "$LINES"
35
+
36
+ # Configure status bar
37
+ tmux set-option -t "$SESSION" status on
38
+ tmux set-option -t "$SESSION" status-interval 1
39
+ tmux set-option -t "$SESSION" status-style "bg=black,fg=white"
40
+ # Set lengths globally and for session to ensure they stick
41
+ tmux set-option -g status-left-length 30
42
+ tmux set-option -g status-right-length 300
43
+ tmux set-option -t "$SESSION" status-left-length 30
44
+ tmux set-option -t "$SESSION" status-right-length 300
45
+ tmux set-option -t "$SESSION" status-left "#[fg=cyan,bold]🤖 $AGENT_TYPE #[fg=cyan]│ "
46
+ tmux set-option -t "$SESSION" status-right "#[fg=yellow]#(cat ${STATUS_FILE}.cmd 2>/dev/null) #[fg=cyan]│ #[fg=green]#(cat $STATUS_FILE 2>/dev/null || echo '❓') #[fg=cyan]│ #[fg=white]%H:%M:%S"
47
+ tmux set-option -t "$SESSION" window-status-format ""
48
+ tmux set-option -t "$SESSION" window-status-current-format ""
49
+ tmux set-option -t "$SESSION" remain-on-exit off
50
+ tmux set-option -t "$SESSION" mouse on
51
+
52
+ # Run agent-bridge in tmux session
53
+ tmux send-keys -t "$SESSION" "export AGENT_TYPE='$AGENT_TYPE' && export AGENT_ID='$AGENT_ID' && export INSIDE_TMUX=1 && agent-bridge" C-m
54
+
55
+ # Attach or wait
56
+ if [ -t 0 ]; then
57
+ tmux attach-session -t "$SESSION"
58
+ else
59
+ echo "📡 Running in background mode"
60
+ while tmux has-session -t "$SESSION" 2>/dev/null; do sleep 1; done
61
+ fi
62
+
63
+ cleanup
@@ -0,0 +1,144 @@
1
+ #!/bin/bash
2
+ set -e
3
+ export DEBIAN_FRONTEND=noninteractive
4
+
5
+ # Install dependencies
6
+ # Handle potential clock skew in containers
7
+ echo 'Acquire::Check-Date "false";' > /etc/apt/apt.conf.d/99no-check-date
8
+
9
+ apt-get update && apt-get install -y \
10
+ git curl tmux sudo unzip wget jq nano
11
+
12
+ # Install Node.js (required for Claude CLI)
13
+ # Check for existing Node installation
14
+ NODE_VERSION=""
15
+ if command -v node &> /dev/null; then
16
+ NODE_VERSION=$(node -v | cut -d. -f1 | tr -d 'v')
17
+ fi
18
+
19
+ if [ -n "$NODE_VERSION" ] && [ "$NODE_VERSION" -ge 18 ]; then
20
+ echo "Node.js $NODE_VERSION is already installed."
21
+ # Check for npm
22
+ if ! command -v npm &> /dev/null; then
23
+ echo "npm is missing. Installing npm..."
24
+ apt-get install -y npm
25
+ fi
26
+ else
27
+ echo "Node.js not found or too old ($NODE_VERSION). Installing Node.js 20..."
28
+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
29
+ apt-get install -y nodejs
30
+ fi
31
+
32
+ # Setup User FIRST (before installing Claude)
33
+ # We want to run as the same UID as the host user (passed via build arg)
34
+ # to ensure we can edit mounted files.
35
+ USER_ID=${USER_ID:-1000}
36
+ GROUP_ID=${GROUP_ID:-1000}
37
+ AGENT_USER="claude"
38
+
39
+ # Allow UIDs outside the default range (e.g., macOS UIDs like 501)
40
+ if [ "$USER_ID" -lt 1000 ]; then
41
+ sed -i 's/^UID_MIN.*/UID_MIN 100/' /etc/login.defs
42
+ sed -i 's/^GID_MIN.*/GID_MIN 100/' /etc/login.defs
43
+ fi
44
+
45
+ # 1. Handle Group
46
+ if getent group ${GROUP_ID} >/dev/null 2>&1; then
47
+ # Group exists (e.g. 'node'), use it
48
+ GROUP_NAME=$(getent group ${GROUP_ID} | cut -d: -f1)
49
+ else
50
+ # Create group
51
+ if getent group ${AGENT_USER} >/dev/null 2>&1; then
52
+ GROUP_NAME=${AGENT_USER}
53
+ else
54
+ groupadd -g ${GROUP_ID} ${AGENT_USER}
55
+ GROUP_NAME=${AGENT_USER}
56
+ fi
57
+ fi
58
+
59
+ # 2. Handle User
60
+ if getent passwd ${USER_ID} >/dev/null 2>&1; then
61
+ # User exists (e.g. 'node'), use it
62
+ AGENT_USER=$(getent passwd ${USER_ID} | cut -d: -f1)
63
+ # Ensure user is in the group (if different)
64
+ usermod -aG ${GROUP_NAME} ${AGENT_USER}
65
+ else
66
+ # Create user
67
+ useradd -u ${USER_ID} -g ${GROUP_NAME} -m -s /bin/bash ${AGENT_USER}
68
+ fi
69
+
70
+ # 3. Grant Sudo
71
+ echo "${AGENT_USER} ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
72
+
73
+ # 4. Determine Home Directory
74
+ AGENT_HOME=$(getent passwd ${AGENT_USER} | cut -d: -f6)
75
+
76
+ echo "Installing claude-code as ${AGENT_USER}"
77
+
78
+ # Install Claude CLI as the agent user
79
+ sudo -u ${AGENT_USER} bash -c 'curl -fsSL https://claude.ai/install.sh | bash'
80
+
81
+ # Add agent user's local bin to system PATH
82
+ echo "export PATH=\"${AGENT_HOME}/.local/bin:\$PATH\"" >> /etc/profile.d/claude.sh
83
+ chmod +x /etc/profile.d/claude.sh
84
+
85
+ echo "Installing Github CLI"
86
+ # Install GitHub CLI
87
+ curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
88
+ chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg
89
+ echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list
90
+ apt-get update && apt-get install gh -y
91
+
92
+ # Create wrapper script that uses local setup-agent.rb if mounted, otherwise downloads from remote
93
+ YATFA_VERSION=${YATFA_VERSION:-main}
94
+ cat << 'EOF' > /usr/local/bin/setup-agent
95
+ #!/bin/bash
96
+ YATFA_VERSION=${YATFA_VERSION:-main}
97
+ # Use local setup-agent.rb if mounted (dev mode), otherwise download from remote
98
+ if [ -f "/tmp/setup-agent.rb" ]; then
99
+ echo "🔧 Using local setup-agent.rb (dev mode)"
100
+ ruby /tmp/setup-agent.rb
101
+ else
102
+ echo "Downloading latest setup-agent.rb (version: ${YATFA_VERSION})..."
103
+ curl -fsSL https://objectstore.fra1.civo.com/yatfa/${YATFA_VERSION}/setup-agent.rb | ruby
104
+ fi
105
+ EOF
106
+ chmod +x /usr/local/bin/setup-agent
107
+ echo "Created setup-agent wrapper (uses local if mounted, otherwise downloads)"
108
+
109
+ # Create entrypoint
110
+ cat << EOF > /entrypoint.sh
111
+ #!/bin/bash
112
+ set -e
113
+
114
+ # No config files copied from host - agent is fully self-contained
115
+
116
+ # Fix permissions of home directory
117
+ sudo chown -R ${AGENT_USER}:${GROUP_NAME} ${AGENT_HOME} || echo "⚠️ Failed to chown home"
118
+
119
+ # Fix permissions of the current directory (project root) and key subdirectories
120
+ # This ensures the agent can write CLAUDE.md, .mcp.json, and create/modify files
121
+ WORKDIR=\$(pwd)
122
+ sudo chown -R ${AGENT_USER}:${GROUP_NAME} "\${WORKDIR}" || echo "⚠️ Failed to chown workdir"
123
+
124
+ # Reset git state if .git exists
125
+ if [ -d ".git" ]; then
126
+ echo "🧹 Resetting git state..."
127
+
128
+ # Remove stale index.lock
129
+ rm -f .git/index.lock
130
+
131
+ git config --global --add safe.directory "\${WORKDIR}"
132
+
133
+ # Reset hard to HEAD
134
+ git reset --hard HEAD || echo "⚠️ Failed to git reset"
135
+
136
+ # Ensure clean state (optional cleans ignored files too?)
137
+ # git clean -fd || echo "⚠️ Failed to git clean"
138
+ fi
139
+
140
+ # Execute command as agent user
141
+ exec sudo -E -u ${AGENT_USER} env "HOME=${AGENT_HOME}" "\$@"
142
+ EOF
143
+
144
+ chmod +x /entrypoint.sh