-
Notifications
You must be signed in to change notification settings - Fork 41
401 lines (364 loc) · 17.4 KB
/
Copy pathai-agent.yml
File metadata and controls
401 lines (364 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# AI Agent triggered by @mentions in issues/PRs
#
# Listens for @<agent-name> please <request> mentions from authorized users
# and runs Claude Code to respond.
#
# Authenticates as the `ai4c-agent` GitHub App (installation token minted per
# job), not as a machine account PAT. Same app and secret names already used by
# claude-code-review.yml.
#
# Required secrets:
# - AI4C_AGENT_APP_ID
# - AI4C_AGENT_PRIVATE_KEY
# - CLAUDE_CODE_OAUTH_TOKEN
#
# Configuration:
# - .github/ai-controllers.json (list of authorized usernames)
#
name: AI Agent GitHub Mentions
env:
# The handle controllers type to invoke the agent. NOT a real GitHub account:
# the app's login is AGENT_LOGIN (`<name>[bot]`), and apps cannot be
# @-mentioned, so "@ai4c-agent" renders as plain text.
AGENT_MENTION: ai4c-agent
# Deprecated handles still honoured as triggers (comma-separated). Also the
# only logins that can work as assignment triggers -- see ASSIGNMENT below.
AGENT_MENTION_LEGACY: dragon-ai-agent
# GitHub App bot identity, for commit attribution. AGENT_USER_ID is the
# numeric id of the ai4c-agent[bot] *account*
# (`gh api /users/ai4c-agent%5Bbot%5D`), NOT the app id in
# AI4C_AGENT_APP_ID -- different numbers. Public, hence plain env.
AGENT_LOGIN: ai4c-agent[bot]
AGENT_USER_ID: 242316268
MODEL: claude-opus-4-7
TOOLS_DIR: ${{ github.workspace }}/tools
TIMEOUT_MINUTES: 30
on:
workflow_dispatch:
inputs:
issue_number:
description: "Issue or PR number to respond to"
required: true
item_type:
description: "Type of item (issue or pull_request)"
required: true
type: choice
options:
- issue
- pull_request
prompt:
description: "The request/prompt for the agent"
required: true
# ASSIGNMENT: `assigned` lets authorized controllers dispatch work by
# assigning the agent directly. NOTE this cannot work with the GitHub App --
# `ai4c-agent[bot]` is not an assignable user, so only the legacy
# `dragon-ai-agent` machine account can still trigger this path, and only for
# as long as that account exists. See `agentAssignees` in the check script.
issues:
types: [opened, edited, assigned]
issue_comment:
types: [created, edited]
pull_request:
types: [opened, edited, assigned, synchronize]
pull_request_review_comment:
types: [created, edited]
jobs:
check-mention:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
pull-requests: write
outputs:
result: ${{ steps.check.outputs.result }}
steps:
# Minted per-job: installation tokens are short-lived (1h) and must not be
# passed between jobs, since GitHub's log masking does not follow job
# outputs.
- name: Mint app token
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ secrets.AI4C_AGENT_APP_ID }}
private-key: ${{ secrets.AI4C_AGENT_PRIVATE_KEY }}
- name: Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 1
token: ${{ steps.app-token.outputs.token }}
- name: Check for qualifying mention
id: check
uses: actions/github-script@v8
with:
github-token: ${{ steps.app-token.outputs.token }}
script: |
const fs = require("fs");
let allowedUsers = [];
try {
const configContent = fs.readFileSync(".github/ai-controllers.json", "utf8");
allowedUsers = JSON.parse(configContent);
} catch (error) {
console.log("Error loading allowed users:", error);
allowedUsers = ["cmungall"];
}
// Trigger on the canonical handle plus any legacy aliases, with an
// optional [bot] suffix (people paste back what they see the bot
// signing as).
const agentName = process.env.AGENT_MENTION;
const legacyNames = (process.env.AGENT_MENTION_LEGACY || "")
.split(",").map((s) => s.trim()).filter(Boolean);
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const mentionAlternation = [agentName, ...legacyNames].map(escapeRe).join("|");
// Assignment dispatch can only ever match a real, assignable user
// account. The app's `ai4c-agent[bot]` login is not assignable, so
// this is the legacy names only.
const agentAssignees = legacyNames;
if (context.eventName === "workflow_dispatch") {
const inputs = context.payload.inputs;
const itemType = inputs.item_type;
const itemNumber = parseInt(inputs.issue_number, 10);
const prompt = inputs.prompt;
const combined = `${prompt}`.toLowerCase();
const skipOdk = combined.includes("skip_odk") || combined.includes("quick question");
return {
qualifiedMention: true,
itemType,
itemNumber,
user: context.actor,
prompt,
branchName: `${agentName}-${itemType}-${itemNumber}-run${context.runNumber}`,
useOdkContainer: !skipOdk,
skipOdkNote: skipOdk
? "NOTE: This is NOT running in the ODK container (SKIP_ODK or quick question was specified), so ODK tools like ROBOT may be unavailable."
: "",
};
}
let content = "";
let userLogin = "";
let itemType = "";
let itemNumber = 0;
let commentId = null;
let reactionTarget = "issue";
if (context.eventName === "issues") {
content = context.payload.issue.body || "";
userLogin = context.payload.action === "assigned"
? (context.payload.sender?.login || context.payload.issue.user.login)
: context.payload.issue.user.login;
itemType = "issue";
itemNumber = context.payload.issue.number;
} else if (context.eventName === "pull_request") {
content = context.payload.pull_request.body || "";
userLogin = context.payload.action === "assigned"
? (context.payload.sender?.login || context.payload.pull_request.user.login)
: context.payload.pull_request.user.login;
itemType = "pull_request";
itemNumber = context.payload.pull_request.number;
} else if (context.eventName === "issue_comment") {
content = context.payload.comment.body || "";
userLogin = context.payload.comment.user.login;
itemType = context.payload.issue.pull_request ? "pull_request" : "issue";
itemNumber = context.payload.issue.number;
commentId = context.payload.comment.id;
reactionTarget = "issue_comment";
} else if (context.eventName === "pull_request_review_comment") {
content = context.payload.comment.body || "";
userLogin = context.payload.comment.user.login;
itemType = "pull_request";
itemNumber = context.payload.pull_request.number;
commentId = context.payload.comment.id;
reactionTarget = "pull_request_review_comment";
}
// Never act on our own output. Unlike GITHUB_TOKEN, events authored
// with an app installation token do retrigger workflows.
if (userLogin.endsWith("[bot]")) {
console.log(`Ignoring bot author: ${userLogin}`);
return { qualifiedMention: false };
}
const isAllowed = allowedUsers.includes(userLogin);
const mentionRegex = new RegExp(
`@(${mentionAlternation})(?:\\[bot\\])?\\s+please\\s+([\\s\\S]*)`, "i");
const mentionMatch = content.match(mentionRegex);
// On synchronize we want this workflow to revalidate on push without
// re-dispatching the agent from a stale PR body mention.
const shouldHonorBodyMention =
(context.eventName === "issues" && ["opened", "edited"].includes(context.payload.action)) ||
(context.eventName === "pull_request" && ["opened", "edited"].includes(context.payload.action)) ||
context.eventName === "issue_comment" ||
context.eventName === "pull_request_review_comment";
const isAgentAssignment =
(context.eventName === "issues" || context.eventName === "pull_request") &&
context.payload.action === "assigned" &&
agentAssignees.includes(context.payload.assignee?.login);
const hasQualifiedBodyMention =
isAllowed && shouldHonorBodyMention && mentionMatch !== null;
const qualifiedMention =
hasQualifiedBodyMention || (isAllowed && isAgentAssignment);
const prompt = hasQualifiedBodyMention
? mentionMatch[2].trim()
: (isAgentAssignment
? "You were assigned to this item. Read the full GitHub context, identify the next concrete action, and carry it through."
: "");
const mentionUsed = mentionMatch ? mentionMatch[1] : "";
const usedLegacyMention =
hasQualifiedBodyMention && mentionUsed.toLowerCase() !== agentName.toLowerCase();
console.log(
`User: ${userLogin}, Allowed: ${isAllowed}, Has mention: ${mentionMatch !== null}, ` +
`Handle: ${mentionUsed}, ` +
`Honor body mention: ${shouldHonorBodyMention}, ` +
`Agent assignment: ${isAgentAssignment}`
);
if (!qualifiedMention) {
return { qualifiedMention: false };
}
try {
if (reactionTarget === "issue_comment") {
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: commentId,
content: "eyes",
});
} else if (reactionTarget === "pull_request_review_comment") {
await github.rest.reactions.createForPullRequestReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: commentId,
content: "eyes",
});
} else {
await github.rest.reactions.createForIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: itemNumber,
content: "eyes",
});
}
} catch (error) {
console.log("Could not add reaction:", error.message);
}
try {
const runUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
const deprecationNote = usedLegacyMention
? `\n\n> [!NOTE]\n> \`@${mentionUsed}\` is deprecated and will stop working. Please use \`@${agentName} please ...\` from now on.`
: "";
const commentBody = `🤖 Working on it...\n\nFollow along: [View workflow run](${runUrl})${deprecationNote}\n\n*— @${agentName}*`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: itemNumber,
body: commentBody,
});
} catch (error) {
console.log("Could not post comment:", error.message);
}
const baseBody =
context.payload.issue?.body ||
context.payload.pull_request?.body ||
"";
const combined = `${baseBody}\n${content}`.toLowerCase();
const skipOdk = combined.includes("skip_odk") || combined.includes("quick question");
return {
qualifiedMention: true,
itemType,
itemNumber,
user: userLogin,
prompt,
branchName: `${agentName}-${itemType}-${itemNumber}-run${context.runNumber}`,
useOdkContainer: !skipOdk,
skipOdkNote: skipOdk
? "NOTE: This is NOT running in the ODK container (SKIP_ODK or quick question was specified), so ODK tools like ROBOT may be unavailable."
: "",
};
respond-to-mention:
needs: check-mention
if: fromJSON(needs.check-mention.outputs.result).qualifiedMention == true
timeout-minutes: 30
permissions:
contents: write
issues: write
pull-requests: write
runs-on: ubuntu-latest
container: ${{ fromJSON(needs.check-mention.outputs.result).useOdkContainer && 'obolibrary/odkfull:v1.6' || null }}
steps:
# Must precede checkout: the token is persisted as the git credential and
# is what later `git push` calls authenticate with. Valid for 1h, which
# bounds how far timeout-minutes above can safely be raised.
- name: Mint app token
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ secrets.AI4C_AGENT_APP_ID }}
private-key: ${{ secrets.AI4C_AGENT_PRIVATE_KEY }}
- name: Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 1
token: ${{ steps.app-token.outputs.token }}
- name: Configure Git
run: |
git config --global user.name "${{ env.AGENT_LOGIN }}"
git config --global user.email "${{ env.AGENT_USER_ID }}+${{ env.AGENT_LOGIN }}@users.noreply.github.com"
- name: Create tools directory
run: mkdir -p "${{ env.TOOLS_DIR }}"
- name: Add tools to PATH
run: echo "${{ env.TOOLS_DIR }}" >> "$GITHUB_PATH"
- name: Add obo-scripts to PATH
run: |
git clone --depth 1 https://github.com/cmungall/obo-scripts.git "${{ env.TOOLS_DIR }}/obo-scripts"
echo "${{ env.TOOLS_DIR }}/obo-scripts" >> "$GITHUB_PATH"
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install Python tools
run: |
uv venv
. .venv/bin/activate
uv pip install aurelian jinja2-cli "wrapt>=1.17.2"
echo "${{ github.workspace }}/.venv/bin" >> "$GITHUB_PATH"
- name: Export GitHub token for gh CLI
run: echo "GH_TOKEN=${{ steps.app-token.outputs.token }}" >> "$GITHUB_ENV"
- name: Run Claude Code
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github_token: ${{ steps.app-token.outputs.token }}
allowed_bots: "claude,github-actions"
show_full_output: true
claude_args: |
--allowedTools "Bash,Read,Write,Edit,Glob,Grep,LS,MultiEdit,NotebookEdit,TodoRead,TodoWrite,WebFetch,WebSearch"
--model "${{ env.MODEL }}"
prompt: |
You are @${{ env.AGENT_MENTION }}, responding to a request from @${{ fromJSON(needs.check-mention.outputs.result).user }} on GitHub ${{ fromJSON(needs.check-mention.outputs.result).itemType }} #${{ fromJSON(needs.check-mention.outputs.result).itemNumber }}.
Follow the repository instructions in `CLAUDE.md`.
${{ fromJSON(needs.check-mention.outputs.result).skipOdkNote }}
THE REQUEST:
```
${{ fromJSON(needs.check-mention.outputs.result).prompt }}
```
GETTING CONTEXT:
Use `gh` to read the full context. Examples:
- `gh issue view ${{ fromJSON(needs.check-mention.outputs.result).itemNumber }} --json title,body,comments`
- `gh pr view ${{ fromJSON(needs.check-mention.outputs.result).itemNumber }} --json title,body,comments,reviews`
- Check for linked issues or PRs mentioned in the body
MAKING CHANGES:
If you need to modify files:
1. Create a branch: `git checkout -b ${{ fromJSON(needs.check-mention.outputs.result).branchName }}`
(unless requested to update an existing branch or PR, in which case check out and work on that branch)
2. Make your changes and commit with descriptive messages
3. Push the branch: `git push -u origin ${{ fromJSON(needs.check-mention.outputs.result).branchName }}`
4. Create a PR using `gh pr create` with a clear title and description
COMMUNICATING:
- Use `gh` CLI directly to interact with the user on GitHub
- Use `gh issue comment` or `gh pr comment` to post updates
- Always inform the user what you did (or could not do)
- If you created a PR, reference it in your comment on the original issue or PR
- If the request is ambiguous, ask a clarifying question via `gh`
SIGNATURE:
Always include the following signature block in commit messages and GitHub comments:
```
---
🤖 **Generated by @${{ env.AGENT_MENTION }}**
- Model: `${{ env.MODEL }}`
- Agent harness: claude-code
- Triggered by: @${{ fromJSON(needs.check-mention.outputs.result).user }}
- Run: [View workflow run](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }})
```