forked from gqy20/IssueLab
-
Notifications
You must be signed in to change notification settings - Fork 0
434 lines (388 loc) · 18.3 KB
/
dispatch_agents.yml
File metadata and controls
434 lines (388 loc) · 18.3 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
name: Dispatch to User Agents
on:
issues:
types: [opened, edited]
issue_comment:
types: [created, edited]
permissions:
contents: read
issues: write
actions: write # 需要触发其他仓库的 workflows
jobs:
dispatch:
if: |
(github.event_name == 'issue_comment' &&
github.event.issue.state == 'open' &&
!contains(github.event.comment.body, '[Agent:') &&
(contains(github.event.comment.body, '相关人员:') || contains(github.event.comment.body, '协作请求:'))) ||
(github.event_name == 'issues' &&
github.event.issue.state == 'open' &&
(contains(github.event.issue.body, '相关人员:') || contains(github.event.issue.body, '协作请求:')))
runs-on: ubuntu-latest
# 允许 Agent 回复中的 @mention 触发分发
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v7
with:
python-version: '3.13'
enable-cache: true
- run: uv sync
- name: Parse mentions from Issue
if: github.event_name == 'issues'
id: parse_issue
env:
ISSUE_BODY_JSON: ${{ toJson(github.event.issue.body) }}
run: |
# 使用临时文件避免多行内容的 shell 解析问题
ISSUE_BODY_FILE=$(mktemp)
export ISSUE_BODY_FILE
python -c "import json, os; from pathlib import Path; content=json.loads(os.environ.get('ISSUE_BODY_JSON','\"\"')); Path(os.environ['ISSUE_BODY_FILE']).write_text(content or '', encoding='utf-8')"
uv run python scripts/parse_mentions.py \
--issue-body-file "$ISSUE_BODY_FILE" \
--controlled-section-only \
--output json
rm -f "$ISSUE_BODY_FILE"
- name: Parse mentions from Comment
if: github.event_name == 'issue_comment'
id: parse_comment
env:
COMMENT_BODY_JSON: ${{ toJson(github.event.comment.body) }}
run: |
# 使用临时文件避免多行内容的 shell 解析问题
COMMENT_BODY_FILE=$(mktemp)
export COMMENT_BODY_FILE
python -c "import json, os; from pathlib import Path; content=json.loads(os.environ.get('COMMENT_BODY_JSON','\"\"')); Path(os.environ['COMMENT_BODY_FILE']).write_text(content or '', encoding='utf-8')"
uv run python scripts/parse_mentions.py \
--comment-body-file "$COMMENT_BODY_FILE" \
--controlled-section-only \
--output json
rm -f "$COMMENT_BODY_FILE"
- name: Get labels
id: labels
run: |
# 将 JSON 转换为单行格式
labels=$(echo '${{ toJson(github.event.issue.labels.*.name) }}' | tr -d '\n' | tr -d ' ')
echo "labels=$labels" >> $GITHUB_OUTPUT
- name: Collect available agents
id: collect_agents
run: |
# 收集所有启用的agents信息
python << 'EOF'
import json
import yaml
from pathlib import Path
agents_dir = Path("agents")
agents_list = []
if agents_dir.exists():
for user_dir in agents_dir.iterdir():
if not user_dir.is_dir():
continue
# 跳过模板目录
if user_dir.name.startswith("_"):
continue
agent_yml = user_dir / "agent.yml"
if not agent_yml.exists():
continue
try:
with open(agent_yml) as f:
config = yaml.safe_load(f)
if config and config.get("enabled", True):
username = config.get("owner") or config.get("username")
triggers = config.get("triggers", [])
description = config.get("description", "")
if username:
trigger_name = triggers[0] if triggers else f"@{username}"
agents_list.append({
"name": trigger_name,
"description": description or f"{username} agent"
})
except Exception as e:
print(f"Warning: Failed to load {agent_yml}: {e}")
# 输出为JSON(单行,供workflow使用)
with open("/tmp/agents.json", "w") as f:
json.dump(agents_list, f, ensure_ascii=False, separators=(",", ":"))
print(json.dumps(agents_list, ensure_ascii=False, separators=(",", ":")))
EOF
agents_json=$(cat /tmp/agents.json)
echo "agents=$agents_json" >> $GITHUB_OUTPUT
agent_count=$(echo "$agents_json" | python -c 'import sys, json; print(len(json.load(sys.stdin)))')
echo "收集到 $agent_count 个可用智能体"
- name: Dispatch to user repositories
id: dispatch
continue-on-error: true # 允许部分失败
env:
PYTHONPATH: ${{ github.workspace }}/src
GITHUB_APP_ID: ${{ secrets.ISSUELAB_APP_ID }}
GITHUB_APP_PRIVATE_KEY: ${{ secrets.ISSUELAB_APP_PRIVATE_KEY }}
LOG_FILE: ${{ github.workspace }}/logs/dispatch_${{ github.event.issue.number }}.log
LOG_LEVEL: DEBUG
ISSUE_TITLE: ${{ github.event.issue.title }}
ISSUE_BODY_JSON: ${{ toJson(github.event.issue.body) }}
COMMENT_BODY_JSON: ${{ toJson(github.event.comment.body) }}
run: |
mkdir -p artifacts/observability
# 使用单引号包裹 JSON 以避免 bash 解析问题
mentions='${{ steps.parse_issue.outputs.mentions || steps.parse_comment.outputs.mentions }}'
if [ -z "$mentions" ] || [ "$mentions" = "[]" ]; then
echo "No mentions found, skipping dispatch"
: > artifacts/observability/dispatch_cli.log
exit 0
fi
# 将多行内容写入临时文件,避免命令行参数解析问题
ISSUE_BODY_FILE=$(mktemp)
COMMENT_BODY_FILE=$(mktemp)
export ISSUE_BODY_FILE
export COMMENT_BODY_FILE
python -c "import json, os; from pathlib import Path; issue=json.loads(os.environ.get('ISSUE_BODY_JSON','\"\"')); comment=json.loads(os.environ.get('COMMENT_BODY_JSON','\"\"')); Path(os.environ['ISSUE_BODY_FILE']).write_text(issue or '', encoding='utf-8'); Path(os.environ['COMMENT_BODY_FILE']).write_text(comment or '', encoding='utf-8')"
python -m issuelab.cli.dispatch \
--mentions "$mentions" \
--agents-dir agents \
--source-repo "${{ github.repository }}" \
--issue-number ${{ github.event.issue.number }} \
--issue-title "$ISSUE_TITLE" \
--issue-body-file "$ISSUE_BODY_FILE" \
${{ github.event_name == 'issue_comment' && format('--comment-id {0}', github.event.comment.id) || '' }} \
--comment-body-file "$COMMENT_BODY_FILE" \
--labels '${{ steps.labels.outputs.labels }}' \
--available-agents '${{ steps.collect_agents.outputs.agents }}' \
--app-id "$GITHUB_APP_ID" \
--app-private-key "$GITHUB_APP_PRIVATE_KEY" 2>&1 | tee artifacts/observability/dispatch_cli.log
# 清理临时文件
rm -f "$ISSUE_BODY_FILE" "$COMMENT_BODY_FILE"
- uses: actions/upload-artifact@v4
if: always() && hashFiles('logs/**') != ''
with:
name: dispatch-logs-${{ github.event.issue.number }}-${{ github.run_id }}
path: logs/
retention-days: 7
- name: Report dispatch results
if: always() && steps.dispatch.outcome != 'skipped'
run: |
echo "Dispatch completed with status: ${{ steps.dispatch.outcome }}"
if [ -n "${{ steps.dispatch.outputs.dispatched_count }}" ]; then
echo "Successfully dispatched to ${{ steps.dispatch.outputs.dispatched_count }}/${{ steps.dispatch.outputs.total_count }} agents"
fi
# 本地执行主仓库 Agents
- name: Run local agents
id: run_local
if: steps.dispatch.outputs.local_agents != '[]' && steps.dispatch.outputs.local_agents != ''
run: |
set +e
LOCAL_AGENTS='${{ steps.dispatch.outputs.local_agents }}'
echo "Running local agents: $LOCAL_AGENTS"
local_total=$(echo "$LOCAL_AGENTS" | jq 'length')
local_success=0
local_failed=0
# 解析 JSON 数组并逐个执行
while read -r agent; do
echo "[LOCAL] Executing agent: $agent"
MCP_EXPORTS=$(uv run python scripts/prepare_mcp_env.py --agent "$agent" --include-root-mcp --shell)
if [ -n "$MCP_EXPORTS" ]; then
eval "$MCP_EXPORTS"
fi
uv run python -m issuelab execute \
--issue ${{ github.event.issue.number }} \
--agents "$agent" \
--post
code=$?
if [ $code -eq 0 ]; then
local_success=$((local_success+1))
else
local_failed=$((local_failed+1))
echo "[WARNING] Failed to run $agent locally"
fi
done < <(echo "$LOCAL_AGENTS" | jq -r '.[]')
{
echo "total=$local_total"
echo "success=$local_success"
echo "failed=$local_failed"
} >> "$GITHUB_OUTPUT"
set -e
env:
GH_TOKEN: ${{ secrets.PAT_TOKEN }}
ANTHROPIC_AUTH_TOKEN: ${{ secrets.ANTHROPIC_AUTH_TOKEN }}
ANTHROPIC_BASE_URL: ${{ secrets.ANTHROPIC_BASE_URL || 'https://api.minimaxi.com/anthropic' }}
ANTHROPIC_MODEL: ${{ secrets.ANTHROPIC_MODEL || 'MiniMax-M2.1' }}
LOG_FILE: ${{ github.workspace }}/logs/local_agents_${{ github.event.issue.number }}.log
LOG_LEVEL: DEBUG
CLAUDE_AGENT_SDK_SKIP_VERSION_CHECK: "true"
CLAUDE_CODE_STREAM_CLOSE_TIMEOUT: "30000"
MCP_LOG_DETAIL: "1"
PROMPT_LOG: "1"
ISSUELAB_TRIGGER_COMMENT: ${{ github.event.comment.body }}
ISSUELAB_MCP_ENV_JSON: ${{ secrets.ISSUELAB_MCP_ENV_JSON }}
PAT_TOKEN: ${{ secrets.PAT_TOKEN }}
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN || secrets.GITHUB_TOKEN }}
ZOTERO_API_KEY: ${{ secrets.ZOTERO_API_KEY }}
ZOTERO_LIBRARY_ID: ${{ secrets.ZOTERO_LIBRARY_ID }}
TAVILY_API_KEY: ${{ secrets.TAVILY_API_KEY }}
SERPAPI_API_KEY: ${{ secrets.SERPAPI_API_KEY }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
- name: Emit observability summary
if: always()
env:
WF_NAME: ${{ github.workflow }}
JOB_NAME: dispatch
RUN_ID: ${{ github.run_id }}
REPO_NAME: ${{ github.repository }}
SHA: ${{ github.sha }}
EVENT_NAME: ${{ github.event_name }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
PARSE_ISSUE_OUTCOME: ${{ steps.parse_issue.outcome }}
PARSE_COMMENT_OUTCOME: ${{ steps.parse_comment.outcome }}
DISPATCH_OUTCOME: ${{ steps.dispatch.outcome }}
MENTIONS_COUNT_ISSUE: ${{ steps.parse_issue.outputs.count }}
MENTIONS_COUNT_COMMENT: ${{ steps.parse_comment.outputs.count }}
MATCHED_TOTAL: ${{ steps.dispatch.outputs.total_count }}
DISPATCHED_COUNT: ${{ steps.dispatch.outputs.dispatched_count }}
LOCAL_TOTAL: ${{ steps.run_local.outputs.total }}
LOCAL_SUCCESS: ${{ steps.run_local.outputs.success }}
LOCAL_FAILED: ${{ steps.run_local.outputs.failed }}
run: |
set -euo pipefail
mkdir -p artifacts/observability
python - << 'PY'
import json
import os
import re
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
def to_int(v: str | None) -> int:
try:
return int(v or "0")
except Exception:
return 0
mentions_count = to_int(os.getenv("MENTIONS_COUNT_ISSUE")) + to_int(os.getenv("MENTIONS_COUNT_COMMENT"))
matched_total = to_int(os.getenv("MATCHED_TOTAL"))
dispatched = to_int(os.getenv("DISPATCHED_COUNT"))
local_total = to_int(os.getenv("LOCAL_TOTAL"))
local_success = to_int(os.getenv("LOCAL_SUCCESS"))
local_failed = to_int(os.getenv("LOCAL_FAILED"))
# Standardized counters
# dispatched_count 已包含“本地 agent 预记成功”,因此需扣除本地失败以得到真实成功数。
input_count = mentions_count
success_count = max(dispatched - local_failed, 0)
failed_count = max(matched_total - success_count, 0)
skipped_count = 0
# Parse failure codes from dispatch CLI output
counters = Counter()
samples: dict[str, list[str]] = {}
log_path = Path("artifacts/observability/dispatch_cli.log")
if log_path.exists():
for line in log_path.read_text(encoding="utf-8", errors="ignore").splitlines():
m = re.search(r"^\s*-\s*([a-zA-Z0-9_-]+):\s*([A-Z0-9_]+)\s*$", line)
if not m:
continue
user = m.group(1)
code = m.group(2)
counters[code] += 1
samples.setdefault(code, [])
if len(samples[code]) < 3:
samples[code].append(user)
# Step-level fallback reasons
if os.getenv("PARSE_ISSUE_OUTCOME") == "failure" or os.getenv("PARSE_COMMENT_OUTCOME") == "failure":
counters["PARSE_FAILED"] += 1
if os.getenv("DISPATCH_OUTCOME") == "failure" and not counters:
counters["DISPATCH_FAILED"] += 1
if local_failed > 0:
counters["LOCAL_AGENT_FAILED"] += local_failed
failures_topn = []
for code, count in counters.most_common(5):
failures_topn.append(
{
"code": code,
"count": count,
"samples": samples.get(code, []),
}
)
status = "success"
if matched_total == 0:
status = "skipped"
elif failed_count > 0 and success_count > 0:
status = "partial"
elif success_count == 0 and (failed_count > 0 or os.getenv("DISPATCH_OUTCOME") == "failure"):
status = "failure"
payload = {
"schema_version": "v1",
"workflow": os.getenv("WF_NAME"),
"job": os.getenv("JOB_NAME"),
"run_id": os.getenv("RUN_ID"),
"repo": os.getenv("REPO_NAME"),
"sha": os.getenv("SHA"),
"event_name": os.getenv("EVENT_NAME"),
"issue_number": os.getenv("ISSUE_NUMBER"),
"finished_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
"metrics": {
"input_count": input_count,
"matched_count": matched_total,
"success_count": success_count,
"failed_count": failed_count,
"skipped_count": skipped_count,
"dispatch_success_count": dispatched,
"local_total": local_total,
"local_success": local_success,
"local_failed": local_failed,
},
"failures_topn": failures_topn,
"status": status,
}
out = Path("artifacts/observability/dispatch__job.json")
out.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
summary_lines = [
"## Observability (dispatch)",
"",
"| metric | value |",
"|---|---:|",
f"| input_count | {payload['metrics']['input_count']} |",
f"| matched_count | {payload['metrics']['matched_count']} |",
f"| success_count | {payload['metrics']['success_count']} |",
f"| failed_count | {payload['metrics']['failed_count']} |",
f"| skipped_count | {payload['metrics']['skipped_count']} |",
f"| status | {payload['status']} |",
"",
"### Failure TopN",
]
if failures_topn:
for item in failures_topn:
sample = ", ".join(item.get("samples", []))
summary_lines.append(f"- `{item['code']}`: {item['count']} ({sample})")
else:
summary_lines.append("- none")
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as fh:
fh.write("\n".join(summary_lines) + "\n")
PY
- name: Upload observability artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: dispatch-observability-${{ github.event.issue.number }}-${{ github.run_id }}
path: artifacts/observability/
retention-days: 14
- name: Comment on dispatch failure
if: steps.dispatch.outcome == 'failure' && steps.dispatch.outputs.dispatched_count == '0'
uses: actions/github-script@v7
with:
script: |
const totalCount = parseInt('${{ steps.dispatch.outputs.total_count }}') || 0;
const dispatchedCount = parseInt('${{ steps.dispatch.outputs.dispatched_count }}') || 0;
let message = '⚠️ **Agent Dispatch Report**\n\n';
if (dispatchedCount === 0 && totalCount > 0) {
message += `❌ Failed to dispatch to all ${totalCount} matched agents.\n\n`;
message += '**Possible reasons:**\n';
message += '- Fork repositories require `workflow_dispatch` mode\n';
message += '- Target workflows may not be enabled\n';
message += '- PAT_TOKEN may lack required permissions (`repo` + `workflow`)\n\n';
message += '**For fork repository owners:**\n';
message += '1. Update your workflow to use `workflow_dispatch` trigger\n';
message += '2. Update your registry file to set `dispatch_mode: workflow_dispatch`\n\n';
} else if (dispatchedCount < totalCount) {
message += `⚠️ Partially successful: ${dispatchedCount}/${totalCount} agents.\n\n`;
}
message += `[View detailed logs](${context.payload.repository.html_url}/actions/runs/${context.runId})`;
await github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: message
});