forked from docker/cagent-action
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction.yml
More file actions
825 lines (738 loc) · 31.2 KB
/
action.yml
File metadata and controls
825 lines (738 loc) · 31.2 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
name: "cagent Runner"
description: "Run a cagent AI agent with a single line"
author: "Docker"
branding:
icon: "cpu"
color: "blue"
inputs:
agent:
description: "Agent identifier (e.g., docker/code-analyzer from Docker Hub, or path to .yaml file)"
required: true
prompt:
description: "Prompt to pass to the agent. If not provided, uses a default based on the agent type"
required: false
mcp-gateway:
description: "Install mcp-gateway (true/false)"
required: false
default: "false"
mcp-gateway-version:
description: "Version of mcp-gateway to use (specifying this will enable mcp-gateway installation)"
required: false
default: "v0.22.0"
anthropic-api-key:
description: "Anthropic API key for Claude models (at least one API key required)"
required: false
openai-api-key:
description: "OpenAI API key (at least one API key required)"
required: false
google-api-key:
description: "Google API key for Gemini models (at least one API key required)"
required: false
aws-bearer-token-bedrock:
description: "AWS Bearer token for Bedrock models (at least one API key required)"
required: false
xai-api-key:
description: "xAI API key for Grok models (at least one API key required)"
required: false
nebius-api-key:
description: "Nebius API key (at least one API key required)"
required: false
mistral-api-key:
description: "Mistral API key (at least one API key required)"
required: false
github-token:
description: "GitHub token for API access (defaults to github.token)"
required: false
github-app-id:
description: "GitHub App ID for custom identity (comments/reviews appear as the app)"
required: false
github-app-private-key:
description: "GitHub App private key (required if github-app-id is provided)"
required: false
timeout:
description: "Timeout in seconds for agent execution (0 for no timeout)"
required: false
default: "0"
debug:
description: "Enable debug mode with verbose logging (true/false)"
required: false
default: "false"
working-directory:
description: "Working directory to run the agent in"
required: false
default: "."
yolo:
description: "Enable yolo mode - auto-approve all prompts (true/false)"
required: false
default: "true"
max-retries:
description: "Maximum number of retries on failure (0 = no retries)"
required: false
default: "2"
retry-delay:
description: "Base delay in seconds between retries (doubles each attempt)"
required: false
default: "5"
extra-args:
description: "Additional arguments to pass to cagent run"
required: false
default: ""
trusted-bot-app-id:
description: "GitHub App ID of a trusted bot that can bypass comment-based auth checks (e.g., for self-review triggers)"
required: false
default: ""
add-prompt-files:
description: "Comma-separated list of files to append to the prompt (e.g., 'AGENTS.md,CLAUDE.md')"
required: false
default: ""
outputs:
exit-code:
description: "Exit code from cagent run"
value: ${{ steps.run-agent.outputs.exit-code }}
output-file:
description: "Path to the output log file"
value: ${{ steps.run-agent.outputs.output-file }}
cagent-version:
description: "Version of cagent that was used"
value: ${{ steps.setup-binaries.outputs.cagent-version }}
mcp-gateway-installed:
description: "Whether mcp-gateway was installed (true/false)"
value: ${{ steps.setup-binaries.outputs.mcp-installed }}
execution-time:
description: "Agent execution time in seconds"
value: ${{ steps.run-agent.outputs.execution-time }}
verbose-log-file:
description: "Path to the full verbose agent log (includes tool calls)"
value: ${{ steps.run-agent.outputs.verbose-log-file }}
security-blocked:
description: "Whether execution was blocked due to security concerns (true/false)"
value: ${{ (steps.sanitize-input.outputs.blocked == 'true' || steps.sanitize-output.outputs.leaked == 'true') && 'true' || 'false' }}
secrets-detected:
description: "Whether secrets were detected in output"
value: ${{ steps.sanitize-output.outputs.leaked }}
prompt-suspicious:
description: "Whether suspicious content was stripped from the prompt (true/false)"
value: ${{ steps.sanitize-input.outputs.stripped }}
input-risk-level:
description: "Risk level of input (low/medium/high)"
value: ${{ steps.sanitize-input.outputs.risk-level }}
runs:
using: "composite"
steps:
# Single source of truth: reads cagent binary version from CAGENT_VERSION file.
- name: Set cagent version
id: cagent-version
shell: bash
run: echo "value=$(cat "${{ github.action_path }}/CAGENT_VERSION" | tr -d '[:space:]')" >> $GITHUB_OUTPUT
- name: Validate inputs
id: validate-inputs
shell: bash
env:
AGENT: ${{ inputs.agent }}
CAGENT_VERSION: ${{ steps.cagent-version.outputs.value }}
MCP_GATEWAY: ${{ inputs.mcp-gateway }}
MCP_GATEWAY_VERSION: ${{ inputs.mcp-gateway-version }}
DEBUG: ${{ inputs.debug }}
YOLO: ${{ inputs.yolo }}
EXTRA_ARGS: ${{ inputs.extra-args }}
# API keys (explicit inputs only - no env var fallback)
ANTHROPIC_API_KEY: ${{ inputs.anthropic-api-key }}
OPENAI_API_KEY: ${{ inputs.openai-api-key }}
GOOGLE_API_KEY: ${{ inputs.google-api-key }}
AWS_BEARER_TOKEN_BEDROCK: ${{ inputs.aws-bearer-token-bedrock }}
XAI_API_KEY: ${{ inputs.xai-api-key }}
NEBIUS_API_KEY: ${{ inputs.nebius-api-key }}
MISTRAL_API_KEY: ${{ inputs.mistral-api-key }}
run: |
# Validate agent is provided
if [[ -z "$AGENT" ]]; then
echo "::error::'agent' input is required"
exit 1
fi
# Validate cagent version format
if ! [[ "$CAGENT_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+.*$ ]]; then
echo "::error::Invalid cagent version format '$CAGENT_VERSION'. Expected format: v1.2.3"
exit 1
fi
# Validate mcp-gateway version format if it will be installed
if [[ "$MCP_GATEWAY" == "true" ]]; then
if ! [[ "$MCP_GATEWAY_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+.*$ ]]; then
echo "::error::Invalid mcp-gateway version format '$MCP_GATEWAY_VERSION'. Expected format: v1.2.3"
exit 1
fi
fi
# Validate at least one API key is provided (explicit input required)
if [[ -z "$ANTHROPIC_API_KEY" && -z "$OPENAI_API_KEY" && -z "$GOOGLE_API_KEY" && \
-z "$AWS_BEARER_TOKEN_BEDROCK" && -z "$XAI_API_KEY" && -z "$NEBIUS_API_KEY" && \
-z "$MISTRAL_API_KEY" ]]; then
echo "::error::At least one API key is required. Provide one of: anthropic-api-key, openai-api-key, google-api-key, aws-bearer-token-bedrock, xai-api-key, nebius-api-key, or mistral-api-key"
exit 1
fi
if [[ "$DEBUG" == "true" ]]; then
echo "::debug::Validation passed"
echo "::debug::agent: $AGENT"
echo "::debug::cagent version: $CAGENT_VERSION"
echo "::debug::mcp-gateway version: $MCP_GATEWAY_VERSION"
echo "::debug::mcp-gateway install: $MCP_GATEWAY"
fi
# ========================================
# SECURITY: Authorization Check
# Only enforced for comment-triggered events (the main abuse vector)
# PR-triggered workflows are controlled by the workflow author
# ========================================
- name: Check authorization
id: check-auth
shell: bash
env:
ACTION_PATH: ${{ github.action_path }}
TRUSTED_BOT_APP_ID: ${{ inputs.trusted-bot-app-id }}
DEBUG: ${{ inputs.debug }}
run: |
# Read comment fields directly from the event payload (cannot be overridden by workflow env vars)
COMMENT_ASSOCIATION=$(jq -r '.comment.author_association // empty' "$GITHUB_EVENT_PATH")
# Only enforce auth for comment-triggered events
# This prevents abuse via /commands while allowing PR-triggered workflows to run
if [ -z "$COMMENT_ASSOCIATION" ]; then
echo "ℹ️ Skipping auth check (not a comment-triggered event)"
echo "authorized=skipped" >> $GITHUB_OUTPUT
exit 0
fi
# Allow a trusted GitHub App bot to bypass auth (e.g., auto-triage posts /review).
# Verified via user type + app ID from the event payload to prevent spoofing.
if [ -n "$TRUSTED_BOT_APP_ID" ]; then
COMMENT_USER_TYPE=$(jq -r '.comment.user.type // empty' "$GITHUB_EVENT_PATH")
COMMENT_APP_ID=$(jq -r '.comment.performed_via_github_app.id // empty' "$GITHUB_EVENT_PATH")
if [ "$COMMENT_USER_TYPE" = "Bot" ] && [ -n "$COMMENT_APP_ID" ] && [ "$COMMENT_APP_ID" = "$TRUSTED_BOT_APP_ID" ]; then
COMMENT_USER_LOGIN=$(jq -r '.comment.user.login // empty' "$GITHUB_EVENT_PATH")
echo "ℹ️ Skipping auth check (trusted bot: $COMMENT_USER_LOGIN, app_id: $COMMENT_APP_ID)"
echo "authorized=true" >> $GITHUB_OUTPUT
exit 0
fi
fi
echo "Using comment author_association: $COMMENT_ASSOCIATION"
# Allowed roles (hardcoded for security - cannot be overridden)
ALLOWED_ROLES='["OWNER", "MEMBER", "COLLABORATOR"]'
# Run the authorization check
$ACTION_PATH/security/check-auth.sh "$COMMENT_ASSOCIATION" "$ALLOWED_ROLES"
# ========================================
# GitHub App Token (Optional)
# ========================================
# Generate token if GitHub App credentials are provided
- name: Generate GitHub App token
id: app-token
if: inputs.github-app-id != ''
uses: tibdex/github-app-token@3beb63f4bd073e61482598c45c71c1019b59b73a # v2
with:
app_id: ${{ inputs.github-app-id }}
private_key: ${{ inputs.github-app-private-key }}
- name: Resolve GitHub token
id: resolve-token
shell: bash
run: |
if [ -n "$APP_TOKEN" ]; then
echo "✅ Using GitHub App token"
echo "token=$APP_TOKEN" >> $GITHUB_OUTPUT
elif [ -n "$EXPLICIT_TOKEN" ]; then
echo "✅ Using provided github-token"
echo "token=$EXPLICIT_TOKEN" >> $GITHUB_OUTPUT
else
echo "ℹ️ Using default github.token"
echo "token=$DEFAULT_TOKEN" >> $GITHUB_OUTPUT
fi
env:
APP_TOKEN: ${{ steps.app-token.outputs.token }}
EXPLICIT_TOKEN: ${{ inputs.github-token }}
DEFAULT_TOKEN: ${{ github.token }}
# ========================================
# SECURITY: Sanitize and Analyze Input
# ========================================
- name: Sanitize and analyze input
if: inputs.prompt != ''
id: sanitize-input
shell: bash
env:
PROMPT_INPUT: ${{ inputs.prompt }}
ACTION_PATH: ${{ github.action_path }}
run: |
echo "🔍 Checking user-provided prompt for injection patterns..."
# Write prompt to temp file for analysis
printf '%s\n' "$PROMPT_INPUT" > /tmp/prompt-input.txt
# Run sanitization which outputs risk-level and blocked status
$ACTION_PATH/security/sanitize-input.sh /tmp/prompt-input.txt /tmp/prompt-clean.txt
- name: Cache cagent binary
id: cache-cagent
uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
path: ${{ github.workspace }}/cagent
key: cagent-${{ runner.os }}-${{ steps.cagent-version.outputs.value }}
- name: Cache mcp-gateway binary
id: cache-mcp
if: ${{ inputs.mcp-gateway == 'true' }}
uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
path: ~/.docker/cli-plugins/docker-mcp
key: mcp-gateway-${{ runner.os }}-${{ inputs.mcp-gateway-version }}
- name: Setup binaries
id: setup-binaries
shell: bash
env:
CAGENT_VERSION: ${{ steps.cagent-version.outputs.value }}
MCP_GATEWAY: ${{ inputs.mcp-gateway }}
MCP_GATEWAY_VERSION: ${{ inputs.mcp-gateway-version }}
DEBUG: ${{ inputs.debug }}
YOLO: ${{ inputs.yolo }}
EXTRA_ARGS: ${{ inputs.extra-args }}
CAGENT_CACHE_HIT: ${{ steps.cache-cagent.outputs.cache-hit }}
MCP_CACHE_HIT: ${{ steps.cache-mcp.outputs.cache-hit }}
run: |
set -e
MCP_INSTALLED="false"
if [[ "$DEBUG" == "true" ]]; then
set -x
fi
# Function to retry downloads
retry_download() {
local url=$1
local output=$2
local max_attempts=3
local attempt=1
while [ $attempt -le $max_attempts ]; do
echo "Attempt $attempt of $max_attempts: Downloading $url"
if curl -fL -o "$output" "$url"; then
echo "Download successful"
return 0
fi
echo "Download failed, retrying..."
attempt=$((attempt + 1))
sleep 2
done
echo "::error::Failed to download after $max_attempts attempts: $url"
return 1
}
# Detect platform
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$OS" in
linux)
PLATFORM="linux"
;;
darwin)
PLATFORM="darwin"
;;
mingw*|msys*|cygwin*)
PLATFORM="windows"
;;
*)
echo "::error::Unsupported operating system: $OS"
exit 1
;;
esac
case "$ARCH" in
x86_64|amd64)
ARCH_NAME="amd64"
;;
aarch64|arm64)
ARCH_NAME="arm64"
;;
*)
echo "::error::Unsupported architecture: $ARCH"
exit 1
;;
esac
CAGENT_BINARY="cagent-${PLATFORM}-${ARCH_NAME}"
if [[ "$PLATFORM" == "windows" ]]; then
CAGENT_BINARY="${CAGENT_BINARY}.exe"
fi
echo "Detected platform: $PLATFORM-$ARCH_NAME"
# Download cagent if not cached
if [[ "$CAGENT_CACHE_HIT" != "true" ]]; then
echo "Downloading cagent $CAGENT_VERSION for $PLATFORM-$ARCH_NAME..."
retry_download \
"https://github.com/docker/cagent/releases/download/$CAGENT_VERSION/$CAGENT_BINARY" \
"$GITHUB_WORKSPACE/cagent"
chmod +x "$GITHUB_WORKSPACE/cagent"
else
echo "Using cached cagent binary"
fi
# Verify cagent works
if ! "$GITHUB_WORKSPACE/cagent" version; then
echo "::error::cagent binary verification failed"
exit 1
fi
# Download mcp-gateway if needed and not cached
if [[ "$MCP_GATEWAY" == "true" ]]; then
if [[ "$MCP_CACHE_HIT" != "true" ]]; then
echo "Downloading mcp-gateway $MCP_GATEWAY_VERSION for $PLATFORM-$ARCH_NAME..."
MCP_BINARY="docker-mcp-${PLATFORM}-${ARCH_NAME}.tar.gz"
retry_download \
"https://github.com/docker/mcp-gateway/releases/download/$MCP_GATEWAY_VERSION/$MCP_BINARY" \
"mcp-gateway.tar.gz"
tar -xzf mcp-gateway.tar.gz
if [[ "$PLATFORM" == "windows" ]]; then
MCP_PLUGIN_DIR="$USERPROFILE/.docker/cli-plugins"
MCP_BINARY_NAME="docker-mcp.exe"
else
MCP_PLUGIN_DIR="$HOME/.docker/cli-plugins"
MCP_BINARY_NAME="docker-mcp"
fi
chmod +x docker-mcp
mkdir -p "$MCP_PLUGIN_DIR"
cp docker-mcp "$MCP_PLUGIN_DIR/$MCP_BINARY_NAME"
else
echo "Using cached mcp-gateway binary"
fi
# Verify mcp-gateway works
if ! docker mcp version; then
echo "::error::mcp-gateway binary verification failed"
exit 1
fi
MCP_INSTALLED="true"
fi
# Set outputs
echo "cagent-version=$CAGENT_VERSION" >> $GITHUB_OUTPUT
echo "mcp-installed=$MCP_INSTALLED" >> $GITHUB_OUTPUT
- name: Run cagent
id: run-agent
shell: bash
env:
ANTHROPIC_API_KEY: ${{ inputs.anthropic-api-key }}
OPENAI_API_KEY: ${{ inputs.openai-api-key }}
GOOGLE_API_KEY: ${{ inputs.google-api-key }}
AWS_BEARER_TOKEN_BEDROCK: ${{ inputs.aws-bearer-token-bedrock }}
XAI_API_KEY: ${{ inputs.xai-api-key }}
NEBIUS_API_KEY: ${{ inputs.nebius-api-key }}
MISTRAL_API_KEY: ${{ inputs.mistral-api-key }}
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
AGENT: ${{ inputs.agent }}
PROMPT_INPUT: ${{ inputs.prompt }}
ACTION_PATH: ${{ github.action_path }}
DEBUG: ${{ inputs.debug }}
YOLO: ${{ inputs.yolo }}
EXTRA_ARGS: ${{ inputs.extra-args }}
TIMEOUT: ${{ inputs.timeout }}
WORKING_DIR: ${{ inputs.working-directory }}
CAGENT_VERSION: ${{ steps.cagent-version.outputs.value }}
MCP_INSTALLED: ${{ steps.setup-binaries.outputs.mcp-installed }}
ADD_PROMPT_FILES: ${{ inputs.add-prompt-files }}
MAX_RETRIES: ${{ inputs.max-retries }}
RETRY_DELAY: ${{ inputs.retry-delay }}
TELEMETRY_TAGS: "source=github-actions,repo=${{ github.repository }},workflow=${{ github.workflow }},run_id=${{ github.run_id }}"
run: |
set -e
# Mask all API keys to prevent accidental exposure in logs
[ -n "$ANTHROPIC_API_KEY" ] && echo "::add-mask::$ANTHROPIC_API_KEY"
[ -n "$OPENAI_API_KEY" ] && echo "::add-mask::$OPENAI_API_KEY"
[ -n "$GOOGLE_API_KEY" ] && echo "::add-mask::$GOOGLE_API_KEY"
[ -n "$AWS_BEARER_TOKEN_BEDROCK" ] && echo "::add-mask::$AWS_BEARER_TOKEN_BEDROCK"
[ -n "$XAI_API_KEY" ] && echo "::add-mask::$XAI_API_KEY"
[ -n "$NEBIUS_API_KEY" ] && echo "::add-mask::$NEBIUS_API_KEY"
[ -n "$MISTRAL_API_KEY" ] && echo "::add-mask::$MISTRAL_API_KEY"
[ -n "$GH_TOKEN" ] && echo "::add-mask::$GH_TOKEN"
# Change to working directory
cd "$WORKING_DIR"
if [[ "$DEBUG" == "true" ]]; then
set -x
echo "::debug::Working directory: $(pwd)"
echo "::debug::GitHub workspace: $GITHUB_WORKSPACE"
fi
# Create output file early (before any validation exits)
# This ensures downstream steps always have a valid output file reference
OUTPUT_FILE=$(mktemp /tmp/cagent-output-XXXXXX)
if [ -z "$OUTPUT_FILE" ] || [ ! -f "$OUTPUT_FILE" ]; then
echo "::error::Failed to create output file"
exit 1
fi
echo "output-file=$OUTPUT_FILE" >> $GITHUB_OUTPUT
echo "Output file: $OUTPUT_FILE"
VERBOSE_LOG_FILE=$(mktemp /tmp/cagent-verbose-XXXXXX)
if [ -z "$VERBOSE_LOG_FILE" ] || [ ! -f "$VERBOSE_LOG_FILE" ]; then
echo "::error::Failed to create verbose log file"
exit 1
fi
echo "verbose-log-file=$VERBOSE_LOG_FILE" >> $GITHUB_OUTPUT
echo "Verbose log file: $VERBOSE_LOG_FILE"
VERBOSE_LOG_BASENAME=$(basename "$VERBOSE_LOG_FILE")
echo "verbose-log-artifact-name=cagent-verbose-log-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-${GITHUB_JOB}-${VERBOSE_LOG_BASENAME}" >> $GITHUB_OUTPUT
# Build command arguments array (SECURE: no eval!)
ARGS=("run" "--exec")
# Add flags
if [ "$YOLO" = "true" ]; then
ARGS+=("--yolo")
fi
# Set working directory so relative paths (e.g., memory toolset) resolve
# from the repo root, not from the agent YAML's parent directory
ARGS+=("--working-dir" "$(pwd)")
# Add extra args if provided
# Note: This uses simple word splitting. Quoted arguments with spaces are not supported.
# Using eval would be a security risk with user-provided input.
if [ -n "$EXTRA_ARGS" ]; then
read -ra EXTRA_ARGS_ARRAY <<< "$EXTRA_ARGS"
ARGS+=("${EXTRA_ARGS_ARRAY[@]}")
fi
# Add prompt files as --prompt-file flags (cagent handles file resolution)
if [ -n "$ADD_PROMPT_FILES" ]; then
echo "Adding prompt files: $ADD_PROMPT_FILES"
IFS=',' read -ra FILES <<< "$ADD_PROMPT_FILES"
for file in "${FILES[@]}"; do
file=$(echo "$file" | xargs) # trim whitespace
ARGS+=("--prompt-file" "$file")
done
fi
# Add agent
echo "Using agent: $AGENT"
ARGS+=("$AGENT")
# Always pass prompt via stdin to satisfy cagent run's required prompt arg
ARGS+=("-")
if [ -n "$PROMPT_INPUT" ]; then
echo "Running cagent with ${#ARGS[@]} arguments (prompt via stdin)"
else
echo "Running cagent with ${#ARGS[@]} arguments (empty prompt via stdin)"
fi
# Track execution time
START_TIME=$(date +%s)
# Retry loop with exponential backoff
ATTEMPT=0
CURRENT_DELAY="$RETRY_DELAY"
EXIT_CODE=1
while true; do
ATTEMPT=$((ATTEMPT + 1))
if [ "$ATTEMPT" -gt 1 ]; then
echo "🔄 Retry attempt $((ATTEMPT - 1)) of $MAX_RETRIES (waiting ${CURRENT_DELAY}s)..."
sleep "$CURRENT_DELAY"
CURRENT_DELAY=$((CURRENT_DELAY * 2))
# Reset clean output file; append a separator to verbose log to preserve earlier attempts
> "$OUTPUT_FILE"
echo "" >> "$VERBOSE_LOG_FILE"
echo "========== RETRY ATTEMPT $ATTEMPT ($(date -u +%Y-%m-%dT%H:%M:%SZ)) ==========" >> "$VERBOSE_LOG_FILE"
echo "" >> "$VERBOSE_LOG_FILE"
fi
# SECURE: Direct execution with quoted arguments (no eval!)
# Output goes to verbose log file only (keeps console clean)
# Prefer sanitized prompt file (comments stripped, suspicious lines removed)
# over raw $PROMPT_INPUT to enforce input sanitization.
# PIPESTATUS: [0]=cat/printf [1]=cagent/timeout
PROMPT_FILE="/tmp/prompt-clean.txt"
set +e # Don't exit on command failure
if [ "$TIMEOUT" != "0" ]; then
if [ -f "$PROMPT_FILE" ]; then
cat "$PROMPT_FILE" | timeout "$TIMEOUT" "$GITHUB_WORKSPACE/cagent" "${ARGS[@]}" >> "$VERBOSE_LOG_FILE" 2>&1
else
printf '%s\n' "$PROMPT_INPUT" | timeout "$TIMEOUT" "$GITHUB_WORKSPACE/cagent" "${ARGS[@]}" >> "$VERBOSE_LOG_FILE" 2>&1
fi
EXIT_CODE=${PIPESTATUS[1]}
if [ $EXIT_CODE -eq 124 ]; then
echo "::error::Agent execution timed out after $TIMEOUT seconds"
fi
else
if [ -f "$PROMPT_FILE" ]; then
cat "$PROMPT_FILE" | "$GITHUB_WORKSPACE/cagent" "${ARGS[@]}" >> "$VERBOSE_LOG_FILE" 2>&1
else
printf '%s\n' "$PROMPT_INPUT" | "$GITHUB_WORKSPACE/cagent" "${ARGS[@]}" >> "$VERBOSE_LOG_FILE" 2>&1
fi
EXIT_CODE=${PIPESTATUS[1]}
fi
set -e
# Success — no retry needed
if [ $EXIT_CODE -eq 0 ]; then
break
fi
# Timeout (124) — don't retry, would just timeout again
if [ $EXIT_CODE -eq 124 ]; then
break
fi
# Max retries exhausted
if [ "$ATTEMPT" -gt "$MAX_RETRIES" ]; then
echo "::warning::Agent failed after $MAX_RETRIES retries (exit code: $EXIT_CODE)"
break
fi
echo "::warning::Agent failed (exit code: $EXIT_CODE), will retry..."
done
# Produce clean output (strip tool calls/results) for downstream steps
awk '
/<thinking>/,/<\/thinking>/ { next }
/^\[thinking\]/,/^\[\/thinking\]/ { next }
/^Thinking:/ { next }
/^--- Tool:/ { in_tool=1; next }
in_tool && /^--- (Tool:|Agent:|$)/ { in_tool=0; next }
in_tool { next }
/^Calling [a-zA-Z_]+\(/ { in_call=1; next }
in_call && /^\)$/ { in_call=0; next }
in_call { next }
/^[a-zA-Z_]+ response →/ { in_resp=1; next }
in_resp && /^\)$/ { in_resp=0; next }
in_resp { next }
/^--- Agent:/ { next }
/^time=/ { next }
/^level=/ { next }
/^msg=/ { next }
/^> \[!NOTE\]/ { next }
/For any feedback/ { next }
/transfer_task/ { next }
/Delegating to/ { next }
/Task delegated/ { next }
NF==0 && !seen_content { next }
NF>0 { seen_content=1 }
{ print }
' "$VERBOSE_LOG_FILE" > "$OUTPUT_FILE"
END_TIME=$(date +%s)
EXECUTION_TIME=$((END_TIME - START_TIME))
# Set outputs (output-file already set at start of step)
echo "exit-code=$EXIT_CODE" >> $GITHUB_OUTPUT
echo "execution-time=$EXECUTION_TIME" >> $GITHUB_OUTPUT
# Create job summary
{
echo "## cagent Execution Summary"
echo ""
echo "| Property | Value |"
echo "|----------|-------|"
echo "| Agent | \`$AGENT\` |"
echo "| Exit Code | $EXIT_CODE |"
echo "| Execution Time | ${EXECUTION_TIME}s |"
echo "| cagent Version | $CAGENT_VERSION |"
echo "| MCP Gateway | $MCP_INSTALLED |"
if [ "$TIMEOUT" != "0" ]; then
echo "| Timeout | ${TIMEOUT}s |"
fi
echo ""
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ **Status:** Success"
elif [ $EXIT_CODE -eq 124 ]; then
echo "⏱️ **Status:** Timeout"
else
echo "❌ **Status:** Failed"
fi
} >> $GITHUB_STEP_SUMMARY
if [[ "$DEBUG" == "true" ]]; then
echo "::debug::Exit code: $EXIT_CODE"
echo "::debug::Execution time: ${EXECUTION_TIME}s"
echo "::debug::Output file: $OUTPUT_FILE"
fi
exit $EXIT_CODE
# ========================================
# SECURITY: Sanitize Output (UNIVERSAL - All Modes)
# ========================================
- name: Sanitize output
if: always()
id: sanitize-output
shell: bash
env:
OUTPUT_FILE: ${{ steps.run-agent.outputs.output-file }}
ACTION_PATH: ${{ github.action_path }}
run: |
echo "🔍 Scanning AI response for leaked secrets..."
OUTPUT_FILE="$OUTPUT_FILE"
# Defensive check: ensure output file exists
if [ -z "$OUTPUT_FILE" ] || [ ! -f "$OUTPUT_FILE" ]; then
echo "⚠️ No output file to scan (agent may have failed during validation)"
echo "leaked=false" >> $GITHUB_OUTPUT
exit 0
fi
$ACTION_PATH/security/sanitize-output.sh "$OUTPUT_FILE"
# Extract from cagent-output code block if present (overrides awk-filtered output)
# Note: the code fence may not be at the start of a line if the agent
# emits conversational text before it, so we avoid anchoring with ^.
if grep -q '```cagent-output' "$OUTPUT_FILE"; then
echo "🧹 Extracting clean output from cagent-output code block..."
awk '
/```cagent-output/ { capturing=1; next }
capturing && /```/ { capturing=0; next }
capturing { print }
' "$OUTPUT_FILE" > "${OUTPUT_FILE}.clean"
if [ -s "${OUTPUT_FILE}.clean" ]; then
mv "${OUTPUT_FILE}.clean" "$OUTPUT_FILE"
echo "✅ Extracted clean output from cagent-output code block"
else
echo "::warning::Extracted cagent-output code block is empty, keeping filtered output"
rm -f "${OUTPUT_FILE}.clean"
fi
fi
- name: Upload verbose agent log
if: always() && steps.run-agent.outputs.verbose-log-file != ''
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: ${{ steps.run-agent.outputs.verbose-log-artifact-name }}
path: ${{ steps.run-agent.outputs.verbose-log-file }}
retention-days: 14
if-no-files-found: ignore
- name: Update job summary with cleaned output
if: always()
shell: bash
env:
OUTPUT_FILE: ${{ steps.run-agent.outputs.output-file }}
run: |
OUTPUT_FILE="$OUTPUT_FILE"
# Check if output file exists (may not exist if agent failed during validation)
if [ -z "$OUTPUT_FILE" ] || [ ! -f "$OUTPUT_FILE" ]; then
echo "⚠️ Output file not available, skipping summary update"
exit 0
fi
# Append cleaned output to job summary
{
echo ""
echo "<hr />"
echo ""
echo "<h2>Agent Output</h2>"
echo ""
cat "$OUTPUT_FILE"
echo ""
} >> $GITHUB_STEP_SUMMARY
# ========================================
# SECURITY: Handle Security Incident
# ========================================
- name: Handle security incident
if: steps.sanitize-output.outputs.leaked == 'true'
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
REPOSITORY: ${{ github.repository }}
RUN_ID: ${{ github.run_id }}
run: |
cat <<'ERROR_MSG' >&2
═══════════════════════════════════════════════════════
🚨 SECURITY INCIDENT: SECRET LEAK DETECTED
═══════════════════════════════════════════════════════
A secret was detected in the AI agent response
Check the workflow logs for the leaked secret
IMMEDIATE ACTIONS REQUIRED:
1. Review workflow logs for the leaked secret
2. Investigate the prompt/input that triggered this
3. Review who triggered this workflow
4. ROTATE ALL SECRETS IMMEDIATELY
═══════════════════════════════════════════════════════
ERROR_MSG
# Create security incident issue
BODY="**CRITICAL SECURITY INCIDENT**
A secret was detected in the AI agent response for workflow run $RUN_ID
## Actions Taken
✓ Workflow failed with error
✓ Security incident issue created
## Required Actions
1. Review workflow logs: https://github.com/$REPOSITORY/actions
2. **ROTATE COMPROMISED SECRETS IMMEDIATELY**
- ANTHROPIC_API_KEY
- GITHUB_TOKEN
- OPENAI_API_KEY
- GOOGLE_API_KEY
- AWS_BEARER_TOKEN_BEDROCK
- XAI_API_KEY
- NEBIUS_API_KEY
- MISTRAL_API_KEY
- Any other exposed credentials
3. Investigate the workflow trigger and input prompt
4. Review workflow run history for suspicious patterns
## Timeline
- Incident detected: $(date -u +%Y-%m-%dT%H:%M:%SZ)
- Workflow run: https://github.com/$REPOSITORY/actions/runs/$RUN_ID
## Next Steps
- [ ] Secrets rotated
- [ ] Logs reviewed
- [ ] Incident investigated
- [ ] Incident report filed
- [ ] Post-mortem completed"
gh issue create \
--repo "$REPOSITORY" \
--title "🚨 Security Alert: Secret Leak Detected in Agent Execution" \
--label "security" \
--body "$BODY"
echo "🚨 Security incident issue created"
exit 1