mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-01-23 15:04:13 +08:00
Compare commits
41 Commits
claude/upd
...
claude/fix
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80591ffc11 | ||
|
|
f0c8eb2980 | ||
|
|
68a0348c20 | ||
|
|
dc06a34646 | ||
|
|
a3bb51dac1 | ||
|
|
6610520549 | ||
|
|
e2eb96f51d | ||
|
|
05c95aed79 | ||
|
|
bb4a3f68f7 | ||
|
|
2acd1f7011 | ||
|
|
469fc9c1a4 | ||
|
|
90da6b6e15 | ||
|
|
752ba96ea1 | ||
|
|
66bf95c07f | ||
|
|
6337623ebb | ||
|
|
6d79044f1d | ||
|
|
a7e4c51380 | ||
|
|
7febbb006b | ||
|
|
798cf0988d | ||
|
|
8458f4399d | ||
|
|
f9b2917716 | ||
|
|
f092d4cefd | ||
|
|
c2edeab4c3 | ||
|
|
4318310481 | ||
|
|
11571151c4 | ||
|
|
70193f466c | ||
|
|
9db20ef677 | ||
|
|
6902c227aa | ||
|
|
e45f28fae7 | ||
|
|
8c4e1e7eb1 | ||
|
|
906bd89c74 | ||
|
|
08f88abe2b | ||
|
|
14ab4250bb | ||
|
|
c7fdd19642 | ||
|
|
92d173475f | ||
|
|
108e982900 | ||
|
|
7bb53ae6ee | ||
|
|
804b418b93 | ||
|
|
500439cb9b | ||
|
|
4cda0ef6d1 | ||
|
|
037b85d0d2 |
2
.github/workflows/claude-review.yml
vendored
2
.github/workflows/claude-review.yml
vendored
@@ -2,7 +2,7 @@ name: PR Review
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
types: [opened, synchronize, ready_for_review, reopened]
|
types: [opened]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
review:
|
review:
|
||||||
|
|||||||
4
.github/workflows/sync-base-action.yml
vendored
4
.github/workflows/sync-base-action.yml
vendored
@@ -94,5 +94,5 @@ jobs:
|
|||||||
echo "✅ Successfully synced \`base-action\` directory to [anthropics/claude-code-base-action](https://github.com/anthropics/claude-code-base-action)" >> $GITHUB_STEP_SUMMARY
|
echo "✅ Successfully synced \`base-action\` directory to [anthropics/claude-code-base-action](https://github.com/anthropics/claude-code-base-action)" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "" >> $GITHUB_STEP_SUMMARY
|
echo "" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- **Source commit**: [\`${GITHUB_SHA:0:7}\`](https://github.com/anthropics/claude-code-action/commit/${GITHUB_SHA})" >> $GITHUB_STEP_SUMMARY
|
echo "- **Source commit**: [\`${GITHUB_SHA:0:7}\`](https://github.com/anthropics/claude-code-action/commit/${GITHUB_SHA})" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- **Triggered by**: ${{ github.event_name }}" >> $GITHUB_STEP_SUMMARY
|
echo "- **Triggered by**: $GITHUB_EVENT_NAME" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- **Actor**: @${{ github.actor }}" >> $GITHUB_STEP_SUMMARY
|
echo "- **Actor**: @$GITHUB_ACTOR" >> $GITHUB_STEP_SUMMARY
|
||||||
|
|||||||
58
.github/workflows/test-base-action.yml
vendored
58
.github/workflows/test-base-action.yml
vendored
@@ -118,3 +118,61 @@ jobs:
|
|||||||
echo "❌ Execution log file not found"
|
echo "❌ Execution log file not found"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
test-agent-sdk:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
|
|
||||||
|
- name: Test with Agent SDK
|
||||||
|
id: sdk-test
|
||||||
|
uses: ./base-action
|
||||||
|
env:
|
||||||
|
USE_AGENT_SDK: "true"
|
||||||
|
with:
|
||||||
|
prompt: ${{ github.event.inputs.test_prompt || 'List the files in the current directory starting with "package"' }}
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
allowed_tools: "LS,Read"
|
||||||
|
|
||||||
|
- name: Verify SDK output
|
||||||
|
run: |
|
||||||
|
OUTPUT_FILE="${{ steps.sdk-test.outputs.execution_file }}"
|
||||||
|
CONCLUSION="${{ steps.sdk-test.outputs.conclusion }}"
|
||||||
|
|
||||||
|
echo "Conclusion: $CONCLUSION"
|
||||||
|
echo "Output file: $OUTPUT_FILE"
|
||||||
|
|
||||||
|
if [ "$CONCLUSION" = "success" ]; then
|
||||||
|
echo "✅ Action completed successfully with Agent SDK"
|
||||||
|
else
|
||||||
|
echo "❌ Action failed with Agent SDK"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -f "$OUTPUT_FILE" ]; then
|
||||||
|
if [ -s "$OUTPUT_FILE" ]; then
|
||||||
|
echo "✅ Execution log file created successfully with content"
|
||||||
|
echo "Validating JSON format:"
|
||||||
|
if jq . "$OUTPUT_FILE" > /dev/null 2>&1; then
|
||||||
|
echo "✅ Output is valid JSON"
|
||||||
|
# Verify SDK output contains total_cost_usd (SDK field name)
|
||||||
|
if jq -e '.[] | select(.type == "result") | .total_cost_usd' "$OUTPUT_FILE" > /dev/null 2>&1; then
|
||||||
|
echo "✅ SDK output contains total_cost_usd field"
|
||||||
|
else
|
||||||
|
echo "❌ SDK output missing total_cost_usd field"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Content preview:"
|
||||||
|
head -c 500 "$OUTPUT_FILE"
|
||||||
|
else
|
||||||
|
echo "❌ Output is not valid JSON"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "❌ Execution log file is empty"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "❌ Execution log file not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|||||||
307
.github/workflows/test-structured-output.yml
vendored
Normal file
307
.github/workflows/test-structured-output.yml
vendored
Normal file
@@ -0,0 +1,307 @@
|
|||||||
|
name: Test Structured Outputs
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test-basic-types:
|
||||||
|
name: Test Basic Type Conversions
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
|
|
||||||
|
- name: Test with explicit values
|
||||||
|
id: test
|
||||||
|
uses: ./base-action
|
||||||
|
with:
|
||||||
|
prompt: |
|
||||||
|
Run this command: echo "test"
|
||||||
|
|
||||||
|
Then return EXACTLY these values:
|
||||||
|
- text_field: "hello"
|
||||||
|
- number_field: 42
|
||||||
|
- boolean_true: true
|
||||||
|
- boolean_false: false
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
claude_args: |
|
||||||
|
--allowedTools Bash
|
||||||
|
--json-schema '{"type":"object","properties":{"text_field":{"type":"string"},"number_field":{"type":"number"},"boolean_true":{"type":"boolean"},"boolean_false":{"type":"boolean"}},"required":["text_field","number_field","boolean_true","boolean_false"]}'
|
||||||
|
|
||||||
|
- name: Verify outputs
|
||||||
|
run: |
|
||||||
|
# Parse the structured_output JSON
|
||||||
|
OUTPUT='${{ steps.test.outputs.structured_output }}'
|
||||||
|
|
||||||
|
# Test string pass-through
|
||||||
|
TEXT_FIELD=$(echo "$OUTPUT" | jq -r '.text_field')
|
||||||
|
if [ "$TEXT_FIELD" != "hello" ]; then
|
||||||
|
echo "❌ String: expected 'hello', got '$TEXT_FIELD'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Test number → string conversion
|
||||||
|
NUMBER_FIELD=$(echo "$OUTPUT" | jq -r '.number_field')
|
||||||
|
if [ "$NUMBER_FIELD" != "42" ]; then
|
||||||
|
echo "❌ Number: expected '42', got '$NUMBER_FIELD'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Test boolean → "true" conversion
|
||||||
|
BOOLEAN_TRUE=$(echo "$OUTPUT" | jq -r '.boolean_true')
|
||||||
|
if [ "$BOOLEAN_TRUE" != "true" ]; then
|
||||||
|
echo "❌ Boolean true: expected 'true', got '$BOOLEAN_TRUE'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Test boolean → "false" conversion
|
||||||
|
BOOLEAN_FALSE=$(echo "$OUTPUT" | jq -r '.boolean_false')
|
||||||
|
if [ "$BOOLEAN_FALSE" != "false" ]; then
|
||||||
|
echo "❌ Boolean false: expected 'false', got '$BOOLEAN_FALSE'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ All basic type conversions correct"
|
||||||
|
|
||||||
|
test-complex-types:
|
||||||
|
name: Test Arrays and Objects
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
|
|
||||||
|
- name: Test complex types
|
||||||
|
id: test
|
||||||
|
uses: ./base-action
|
||||||
|
with:
|
||||||
|
prompt: |
|
||||||
|
Run: echo "ready"
|
||||||
|
|
||||||
|
Return EXACTLY:
|
||||||
|
- items: ["apple", "banana", "cherry"]
|
||||||
|
- config: {"key": "value", "count": 3}
|
||||||
|
- empty_array: []
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
claude_args: |
|
||||||
|
--allowedTools Bash
|
||||||
|
--json-schema '{"type":"object","properties":{"items":{"type":"array","items":{"type":"string"}},"config":{"type":"object"},"empty_array":{"type":"array"}},"required":["items","config","empty_array"]}'
|
||||||
|
|
||||||
|
- name: Verify JSON stringification
|
||||||
|
run: |
|
||||||
|
# Parse the structured_output JSON
|
||||||
|
OUTPUT='${{ steps.test.outputs.structured_output }}'
|
||||||
|
|
||||||
|
# Arrays should be JSON stringified
|
||||||
|
if ! echo "$OUTPUT" | jq -e '.items | length == 3' > /dev/null; then
|
||||||
|
echo "❌ Array not properly formatted"
|
||||||
|
echo "$OUTPUT" | jq '.items'
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Objects should be JSON stringified
|
||||||
|
if ! echo "$OUTPUT" | jq -e '.config.key == "value"' > /dev/null; then
|
||||||
|
echo "❌ Object not properly formatted"
|
||||||
|
echo "$OUTPUT" | jq '.config'
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Empty arrays should work
|
||||||
|
if ! echo "$OUTPUT" | jq -e '.empty_array | length == 0' > /dev/null; then
|
||||||
|
echo "❌ Empty array not properly formatted"
|
||||||
|
echo "$OUTPUT" | jq '.empty_array'
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ All complex types handled correctly"
|
||||||
|
|
||||||
|
test-edge-cases:
|
||||||
|
name: Test Edge Cases
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
|
|
||||||
|
- name: Test edge cases
|
||||||
|
id: test
|
||||||
|
uses: ./base-action
|
||||||
|
with:
|
||||||
|
prompt: |
|
||||||
|
Run: echo "test"
|
||||||
|
|
||||||
|
Return EXACTLY:
|
||||||
|
- zero: 0
|
||||||
|
- empty_string: ""
|
||||||
|
- negative: -5
|
||||||
|
- decimal: 3.14
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
claude_args: |
|
||||||
|
--allowedTools Bash
|
||||||
|
--json-schema '{"type":"object","properties":{"zero":{"type":"number"},"empty_string":{"type":"string"},"negative":{"type":"number"},"decimal":{"type":"number"}},"required":["zero","empty_string","negative","decimal"]}'
|
||||||
|
|
||||||
|
- name: Verify edge cases
|
||||||
|
run: |
|
||||||
|
# Parse the structured_output JSON
|
||||||
|
OUTPUT='${{ steps.test.outputs.structured_output }}'
|
||||||
|
|
||||||
|
# Zero should be "0", not empty or falsy
|
||||||
|
ZERO=$(echo "$OUTPUT" | jq -r '.zero')
|
||||||
|
if [ "$ZERO" != "0" ]; then
|
||||||
|
echo "❌ Zero: expected '0', got '$ZERO'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Empty string should be empty (not "null" or missing)
|
||||||
|
EMPTY_STRING=$(echo "$OUTPUT" | jq -r '.empty_string')
|
||||||
|
if [ "$EMPTY_STRING" != "" ]; then
|
||||||
|
echo "❌ Empty string: expected '', got '$EMPTY_STRING'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Negative numbers should work
|
||||||
|
NEGATIVE=$(echo "$OUTPUT" | jq -r '.negative')
|
||||||
|
if [ "$NEGATIVE" != "-5" ]; then
|
||||||
|
echo "❌ Negative: expected '-5', got '$NEGATIVE'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Decimals should preserve precision
|
||||||
|
DECIMAL=$(echo "$OUTPUT" | jq -r '.decimal')
|
||||||
|
if [ "$DECIMAL" != "3.14" ]; then
|
||||||
|
echo "❌ Decimal: expected '3.14', got '$DECIMAL'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ All edge cases handled correctly"
|
||||||
|
|
||||||
|
test-name-sanitization:
|
||||||
|
name: Test Output Name Sanitization
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
|
|
||||||
|
- name: Test special characters in field names
|
||||||
|
id: test
|
||||||
|
uses: ./base-action
|
||||||
|
with:
|
||||||
|
prompt: |
|
||||||
|
Run: echo "test"
|
||||||
|
Return EXACTLY: {test-result: "passed", item_count: 10}
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
claude_args: |
|
||||||
|
--allowedTools Bash
|
||||||
|
--json-schema '{"type":"object","properties":{"test-result":{"type":"string"},"item_count":{"type":"number"}},"required":["test-result","item_count"]}'
|
||||||
|
|
||||||
|
- name: Verify sanitized names work
|
||||||
|
run: |
|
||||||
|
# Parse the structured_output JSON
|
||||||
|
OUTPUT='${{ steps.test.outputs.structured_output }}'
|
||||||
|
|
||||||
|
# Hyphens should be preserved in the JSON
|
||||||
|
TEST_RESULT=$(echo "$OUTPUT" | jq -r '.["test-result"]')
|
||||||
|
if [ "$TEST_RESULT" != "passed" ]; then
|
||||||
|
echo "❌ Hyphenated name failed: expected 'passed', got '$TEST_RESULT'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Underscores should work
|
||||||
|
ITEM_COUNT=$(echo "$OUTPUT" | jq -r '.item_count')
|
||||||
|
if [ "$ITEM_COUNT" != "10" ]; then
|
||||||
|
echo "❌ Underscore name failed: expected '10', got '$ITEM_COUNT'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ Name sanitization works"
|
||||||
|
|
||||||
|
test-execution-file-structure:
|
||||||
|
name: Test Execution File Format
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
|
|
||||||
|
- name: Run with structured output
|
||||||
|
id: test
|
||||||
|
uses: ./base-action
|
||||||
|
with:
|
||||||
|
prompt: "Run: echo 'complete'. Return: {done: true}"
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
claude_args: |
|
||||||
|
--allowedTools Bash
|
||||||
|
--json-schema '{"type":"object","properties":{"done":{"type":"boolean"}},"required":["done"]}'
|
||||||
|
|
||||||
|
- name: Verify execution file contains structured_output
|
||||||
|
run: |
|
||||||
|
FILE="${{ steps.test.outputs.execution_file }}"
|
||||||
|
|
||||||
|
# Check file exists
|
||||||
|
if [ ! -f "$FILE" ]; then
|
||||||
|
echo "❌ Execution file missing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check for structured_output field
|
||||||
|
if ! jq -e '.[] | select(.type == "result") | .structured_output' "$FILE" > /dev/null; then
|
||||||
|
echo "❌ No structured_output in execution file"
|
||||||
|
cat "$FILE"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Verify the actual value
|
||||||
|
DONE=$(jq -r '.[] | select(.type == "result") | .structured_output.done' "$FILE")
|
||||||
|
if [ "$DONE" != "true" ]; then
|
||||||
|
echo "❌ Wrong value in execution file"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ Execution file format correct"
|
||||||
|
|
||||||
|
test-summary:
|
||||||
|
name: Summary
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs:
|
||||||
|
- test-basic-types
|
||||||
|
- test-complex-types
|
||||||
|
- test-edge-cases
|
||||||
|
- test-name-sanitization
|
||||||
|
- test-execution-file-structure
|
||||||
|
if: always()
|
||||||
|
steps:
|
||||||
|
- name: Generate Summary
|
||||||
|
run: |
|
||||||
|
echo "# Structured Output Tests (Optimized)" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "Fast, deterministic tests using explicit prompts" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "| Test | Result |" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "|------|--------|" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "| Basic Types | ${{ needs.test-basic-types.result == 'success' && '✅ PASS' || '❌ FAIL' }} |" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "| Complex Types | ${{ needs.test-complex-types.result == 'success' && '✅ PASS' || '❌ FAIL' }} |" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "| Edge Cases | ${{ needs.test-edge-cases.result == 'success' && '✅ PASS' || '❌ FAIL' }} |" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "| Name Sanitization | ${{ needs.test-name-sanitization.result == 'success' && '✅ PASS' || '❌ FAIL' }} |" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "| Execution File | ${{ needs.test-execution-file-structure.result == 'success' && '✅ PASS' || '❌ FAIL' }} |" >> $GITHUB_STEP_SUMMARY
|
||||||
|
|
||||||
|
# Check if all passed
|
||||||
|
ALL_PASSED=${{
|
||||||
|
needs.test-basic-types.result == 'success' &&
|
||||||
|
needs.test-complex-types.result == 'success' &&
|
||||||
|
needs.test-edge-cases.result == 'success' &&
|
||||||
|
needs.test-name-sanitization.result == 'success' &&
|
||||||
|
needs.test-execution-file-structure.result == 'success'
|
||||||
|
}}
|
||||||
|
|
||||||
|
if [ "$ALL_PASSED" = "true" ]; then
|
||||||
|
echo "" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "## ✅ All Tests Passed" >> $GITHUB_STEP_SUMMARY
|
||||||
|
else
|
||||||
|
echo "" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "## ❌ Some Tests Failed" >> $GITHUB_STEP_SUMMARY
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
# Claude Code Action
|
# Claude Code Action
|
||||||
|
|
||||||
A general-purpose [Claude Code](https://claude.ai/code) action for GitHub PRs and issues that can answer questions and implement code changes. This action intelligently detects when to activate based on your workflow context—whether responding to @claude mentions, issue assignments, or executing automation tasks with explicit prompts. It supports multiple authentication methods including Anthropic direct API, Amazon Bedrock, and Google Vertex AI.
|
A general-purpose [Claude Code](https://claude.ai/code) action for GitHub PRs and issues that can answer questions and implement code changes. This action intelligently detects when to activate based on your workflow context—whether responding to @claude mentions, issue assignments, or executing automation tasks with explicit prompts. It supports multiple authentication methods including Anthropic direct API, Amazon Bedrock, Google Vertex AI, and Microsoft Foundry.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@@ -13,6 +13,7 @@ A general-purpose [Claude Code](https://claude.ai/code) action for GitHub PRs an
|
|||||||
- 💬 **PR/Issue Integration**: Works seamlessly with GitHub comments and PR reviews
|
- 💬 **PR/Issue Integration**: Works seamlessly with GitHub comments and PR reviews
|
||||||
- 🛠️ **Flexible Tool Access**: Access to GitHub APIs and file operations (additional tools can be enabled via configuration)
|
- 🛠️ **Flexible Tool Access**: Access to GitHub APIs and file operations (additional tools can be enabled via configuration)
|
||||||
- 📋 **Progress Tracking**: Visual progress indicators with checkboxes that dynamically update as Claude completes tasks
|
- 📋 **Progress Tracking**: Visual progress indicators with checkboxes that dynamically update as Claude completes tasks
|
||||||
|
- 📊 **Structured Outputs**: Get validated JSON results that automatically become GitHub Action outputs for complex automations
|
||||||
- 🏃 **Runs on Your Infrastructure**: The action executes entirely on your own GitHub runner (Anthropic API calls go to your chosen provider)
|
- 🏃 **Runs on Your Infrastructure**: The action executes entirely on your own GitHub runner (Anthropic API calls go to your chosen provider)
|
||||||
- ⚙️ **Simplified Configuration**: Unified `prompt` and `claude_args` inputs provide clean, powerful configuration aligned with Claude Code SDK
|
- ⚙️ **Simplified Configuration**: Unified `prompt` and `claude_args` inputs provide clean, powerful configuration aligned with Claude Code SDK
|
||||||
|
|
||||||
@@ -29,7 +30,7 @@ This command will guide you through setting up the GitHub app and required secre
|
|||||||
**Note**:
|
**Note**:
|
||||||
|
|
||||||
- You must be a repository admin to install the GitHub app and add secrets
|
- You must be a repository admin to install the GitHub app and add secrets
|
||||||
- This quickstart method is only available for direct Anthropic API users. For AWS Bedrock or Google Vertex AI setup, see [docs/cloud-providers.md](./docs/cloud-providers.md).
|
- This quickstart method is only available for direct Anthropic API users. For AWS Bedrock, Google Vertex AI, or Microsoft Foundry setup, see [docs/cloud-providers.md](./docs/cloud-providers.md).
|
||||||
|
|
||||||
## 📚 Solutions & Use Cases
|
## 📚 Solutions & Use Cases
|
||||||
|
|
||||||
@@ -56,7 +57,7 @@ Each solution includes complete working examples, configuration details, and exp
|
|||||||
- [Custom Automations](./docs/custom-automations.md) - Examples of automated workflows and custom prompts
|
- [Custom Automations](./docs/custom-automations.md) - Examples of automated workflows and custom prompts
|
||||||
- [Configuration](./docs/configuration.md) - MCP servers, permissions, environment variables, and advanced settings
|
- [Configuration](./docs/configuration.md) - MCP servers, permissions, environment variables, and advanced settings
|
||||||
- [Experimental Features](./docs/experimental.md) - Execution modes and network restrictions
|
- [Experimental Features](./docs/experimental.md) - Execution modes and network restrictions
|
||||||
- [Cloud Providers](./docs/cloud-providers.md) - AWS Bedrock and Google Vertex AI setup
|
- [Cloud Providers](./docs/cloud-providers.md) - AWS Bedrock, Google Vertex AI, and Microsoft Foundry setup
|
||||||
- [Capabilities & Limitations](./docs/capabilities-and-limitations.md) - What Claude can and cannot do
|
- [Capabilities & Limitations](./docs/capabilities-and-limitations.md) - What Claude can and cannot do
|
||||||
- [Security](./docs/security.md) - Access control, permissions, and commit signing
|
- [Security](./docs/security.md) - Access control, permissions, and commit signing
|
||||||
- [FAQ](./docs/faq.md) - Common questions and troubleshooting
|
- [FAQ](./docs/faq.md) - Common questions and troubleshooting
|
||||||
|
|||||||
64
action.yml
64
action.yml
@@ -44,7 +44,7 @@ inputs:
|
|||||||
|
|
||||||
# Auth configuration
|
# Auth configuration
|
||||||
anthropic_api_key:
|
anthropic_api_key:
|
||||||
description: "Anthropic API key (required for direct API, not needed for Bedrock/Vertex)"
|
description: "Anthropic API key (required for direct API, not needed for Bedrock/Vertex/Foundry)"
|
||||||
required: false
|
required: false
|
||||||
claude_code_oauth_token:
|
claude_code_oauth_token:
|
||||||
description: "Claude Code OAuth token (alternative to anthropic_api_key)"
|
description: "Claude Code OAuth token (alternative to anthropic_api_key)"
|
||||||
@@ -60,6 +60,10 @@ inputs:
|
|||||||
description: "Use Google Vertex AI with OIDC authentication instead of direct Anthropic API"
|
description: "Use Google Vertex AI with OIDC authentication instead of direct Anthropic API"
|
||||||
required: false
|
required: false
|
||||||
default: "false"
|
default: "false"
|
||||||
|
use_foundry:
|
||||||
|
description: "Use Microsoft Foundry with OIDC authentication instead of direct Anthropic API"
|
||||||
|
required: false
|
||||||
|
default: "false"
|
||||||
|
|
||||||
claude_args:
|
claude_args:
|
||||||
description: "Additional arguments to pass directly to Claude CLI"
|
description: "Additional arguments to pass directly to Claude CLI"
|
||||||
@@ -89,10 +93,6 @@ inputs:
|
|||||||
description: "Force tag mode with tracking comments for pull_request and issue events. Only applicable to pull_request (opened, synchronize, ready_for_review, reopened) and issue (opened, edited, labeled, assigned) events."
|
description: "Force tag mode with tracking comments for pull_request and issue events. Only applicable to pull_request (opened, synchronize, ready_for_review, reopened) and issue (opened, edited, labeled, assigned) events."
|
||||||
required: false
|
required: false
|
||||||
default: "false"
|
default: "false"
|
||||||
experimental_allowed_domains:
|
|
||||||
description: "Restrict network access to these domains only (newline-separated). If not set, no restrictions are applied. Provider domains are auto-detected."
|
|
||||||
required: false
|
|
||||||
default: ""
|
|
||||||
path_to_claude_code_executable:
|
path_to_claude_code_executable:
|
||||||
description: "Optional path to a custom Claude Code executable. If provided, skips automatic installation and uses this executable instead. WARNING: Using an older version may cause problems if the action begins taking advantage of new Claude Code features. This input is typically not needed unless you're debugging something specific or have unique needs in your environment."
|
description: "Optional path to a custom Claude Code executable. If provided, skips automatic installation and uses this executable instead. WARNING: Using an older version may cause problems if the action begins taking advantage of new Claude Code features. This input is typically not needed unless you're debugging something specific or have unique needs in your environment."
|
||||||
required: false
|
required: false
|
||||||
@@ -124,6 +124,9 @@ outputs:
|
|||||||
github_token:
|
github_token:
|
||||||
description: "The GitHub token used by the action (Claude App token if available)"
|
description: "The GitHub token used by the action (Claude App token if available)"
|
||||||
value: ${{ steps.prepare.outputs.github_token }}
|
value: ${{ steps.prepare.outputs.github_token }}
|
||||||
|
structured_output:
|
||||||
|
description: "JSON string containing all structured output fields when --json-schema is provided in claude_args. Use fromJSON() to parse: fromJSON(steps.id.outputs.structured_output).field_name"
|
||||||
|
value: ${{ steps.claude-code.outputs.structured_output }}
|
||||||
|
|
||||||
runs:
|
runs:
|
||||||
using: "composite"
|
using: "composite"
|
||||||
@@ -137,10 +140,12 @@ runs:
|
|||||||
- name: Setup Custom Bun Path
|
- name: Setup Custom Bun Path
|
||||||
if: inputs.path_to_bun_executable != ''
|
if: inputs.path_to_bun_executable != ''
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
PATH_TO_BUN_EXECUTABLE: ${{ inputs.path_to_bun_executable }}
|
||||||
run: |
|
run: |
|
||||||
echo "Using custom Bun executable: ${{ inputs.path_to_bun_executable }}"
|
echo "Using custom Bun executable: $PATH_TO_BUN_EXECUTABLE"
|
||||||
# Add the directory containing the custom executable to PATH
|
# Add the directory containing the custom executable to PATH
|
||||||
BUN_DIR=$(dirname "${{ inputs.path_to_bun_executable }}")
|
BUN_DIR=$(dirname "$PATH_TO_BUN_EXECUTABLE")
|
||||||
echo "$BUN_DIR" >> "$GITHUB_PATH"
|
echo "$BUN_DIR" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
@@ -179,6 +184,8 @@ runs:
|
|||||||
- name: Install Base Action Dependencies
|
- name: Install Base Action Dependencies
|
||||||
if: steps.prepare.outputs.contains_trigger == 'true'
|
if: steps.prepare.outputs.contains_trigger == 'true'
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
|
||||||
run: |
|
run: |
|
||||||
echo "Installing base-action dependencies..."
|
echo "Installing base-action dependencies..."
|
||||||
cd ${GITHUB_ACTION_PATH}/base-action
|
cd ${GITHUB_ACTION_PATH}/base-action
|
||||||
@@ -187,26 +194,32 @@ runs:
|
|||||||
cd -
|
cd -
|
||||||
|
|
||||||
# Install Claude Code if no custom executable is provided
|
# Install Claude Code if no custom executable is provided
|
||||||
if [ -z "${{ inputs.path_to_claude_code_executable }}" ]; then
|
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
|
||||||
echo "Installing Claude Code..."
|
CLAUDE_CODE_VERSION="2.0.62"
|
||||||
curl -fsSL https://claude.ai/install.sh | bash -s 2.0.29
|
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||||
|
for attempt in 1 2 3; do
|
||||||
|
echo "Installation attempt $attempt..."
|
||||||
|
if command -v timeout &> /dev/null; then
|
||||||
|
timeout 120 bash -c "curl -fsSL https://claude.ai/install.sh | bash -s -- $CLAUDE_CODE_VERSION" && break
|
||||||
|
else
|
||||||
|
curl -fsSL https://claude.ai/install.sh | bash -s -- "$CLAUDE_CODE_VERSION" && break
|
||||||
|
fi
|
||||||
|
if [ $attempt -eq 3 ]; then
|
||||||
|
echo "Failed to install Claude Code after 3 attempts"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Installation failed, retrying..."
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo "Claude Code installed successfully"
|
||||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||||
else
|
else
|
||||||
echo "Using custom Claude Code executable: ${{ inputs.path_to_claude_code_executable }}"
|
echo "Using custom Claude Code executable: $PATH_TO_CLAUDE_CODE_EXECUTABLE"
|
||||||
# Add the directory containing the custom executable to PATH
|
# Add the directory containing the custom executable to PATH
|
||||||
CLAUDE_DIR=$(dirname "${{ inputs.path_to_claude_code_executable }}")
|
CLAUDE_DIR=$(dirname "$PATH_TO_CLAUDE_CODE_EXECUTABLE")
|
||||||
echo "$CLAUDE_DIR" >> "$GITHUB_PATH"
|
echo "$CLAUDE_DIR" >> "$GITHUB_PATH"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Setup Network Restrictions
|
|
||||||
if: steps.prepare.outputs.contains_trigger == 'true' && inputs.experimental_allowed_domains != ''
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
chmod +x ${GITHUB_ACTION_PATH}/scripts/setup-network-restrictions.sh
|
|
||||||
${GITHUB_ACTION_PATH}/scripts/setup-network-restrictions.sh
|
|
||||||
env:
|
|
||||||
EXPERIMENTAL_ALLOWED_DOMAINS: ${{ inputs.experimental_allowed_domains }}
|
|
||||||
|
|
||||||
- name: Run Claude Code
|
- name: Run Claude Code
|
||||||
id: claude-code
|
id: claude-code
|
||||||
if: steps.prepare.outputs.contains_trigger == 'true'
|
if: steps.prepare.outputs.contains_trigger == 'true'
|
||||||
@@ -241,12 +254,14 @@ runs:
|
|||||||
ANTHROPIC_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }}
|
ANTHROPIC_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }}
|
||||||
CLAUDE_CODE_USE_BEDROCK: ${{ inputs.use_bedrock == 'true' && '1' || '' }}
|
CLAUDE_CODE_USE_BEDROCK: ${{ inputs.use_bedrock == 'true' && '1' || '' }}
|
||||||
CLAUDE_CODE_USE_VERTEX: ${{ inputs.use_vertex == 'true' && '1' || '' }}
|
CLAUDE_CODE_USE_VERTEX: ${{ inputs.use_vertex == 'true' && '1' || '' }}
|
||||||
|
CLAUDE_CODE_USE_FOUNDRY: ${{ inputs.use_foundry == 'true' && '1' || '' }}
|
||||||
|
|
||||||
# AWS configuration
|
# AWS configuration
|
||||||
AWS_REGION: ${{ env.AWS_REGION }}
|
AWS_REGION: ${{ env.AWS_REGION }}
|
||||||
AWS_ACCESS_KEY_ID: ${{ env.AWS_ACCESS_KEY_ID }}
|
AWS_ACCESS_KEY_ID: ${{ env.AWS_ACCESS_KEY_ID }}
|
||||||
AWS_SECRET_ACCESS_KEY: ${{ env.AWS_SECRET_ACCESS_KEY }}
|
AWS_SECRET_ACCESS_KEY: ${{ env.AWS_SECRET_ACCESS_KEY }}
|
||||||
AWS_SESSION_TOKEN: ${{ env.AWS_SESSION_TOKEN }}
|
AWS_SESSION_TOKEN: ${{ env.AWS_SESSION_TOKEN }}
|
||||||
|
AWS_BEARER_TOKEN_BEDROCK: ${{ env.AWS_BEARER_TOKEN_BEDROCK }}
|
||||||
ANTHROPIC_BEDROCK_BASE_URL: ${{ env.ANTHROPIC_BEDROCK_BASE_URL || (env.AWS_REGION && format('https://bedrock-runtime.{0}.amazonaws.com', env.AWS_REGION)) }}
|
ANTHROPIC_BEDROCK_BASE_URL: ${{ env.ANTHROPIC_BEDROCK_BASE_URL || (env.AWS_REGION && format('https://bedrock-runtime.{0}.amazonaws.com', env.AWS_REGION)) }}
|
||||||
|
|
||||||
# GCP configuration
|
# GCP configuration
|
||||||
@@ -260,6 +275,13 @@ runs:
|
|||||||
VERTEX_REGION_CLAUDE_3_5_SONNET: ${{ env.VERTEX_REGION_CLAUDE_3_5_SONNET }}
|
VERTEX_REGION_CLAUDE_3_5_SONNET: ${{ env.VERTEX_REGION_CLAUDE_3_5_SONNET }}
|
||||||
VERTEX_REGION_CLAUDE_3_7_SONNET: ${{ env.VERTEX_REGION_CLAUDE_3_7_SONNET }}
|
VERTEX_REGION_CLAUDE_3_7_SONNET: ${{ env.VERTEX_REGION_CLAUDE_3_7_SONNET }}
|
||||||
|
|
||||||
|
# Microsoft Foundry configuration
|
||||||
|
ANTHROPIC_FOUNDRY_RESOURCE: ${{ env.ANTHROPIC_FOUNDRY_RESOURCE }}
|
||||||
|
ANTHROPIC_FOUNDRY_BASE_URL: ${{ env.ANTHROPIC_FOUNDRY_BASE_URL }}
|
||||||
|
ANTHROPIC_DEFAULT_SONNET_MODEL: ${{ env.ANTHROPIC_DEFAULT_SONNET_MODEL }}
|
||||||
|
ANTHROPIC_DEFAULT_HAIKU_MODEL: ${{ env.ANTHROPIC_DEFAULT_HAIKU_MODEL }}
|
||||||
|
ANTHROPIC_DEFAULT_OPUS_MODEL: ${{ env.ANTHROPIC_DEFAULT_OPUS_MODEL }}
|
||||||
|
|
||||||
- name: Update comment with job link
|
- name: Update comment with job link
|
||||||
if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always()
|
if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always()
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|||||||
@@ -42,6 +42,10 @@ inputs:
|
|||||||
description: "Use Google Vertex AI with OIDC authentication instead of direct Anthropic API"
|
description: "Use Google Vertex AI with OIDC authentication instead of direct Anthropic API"
|
||||||
required: false
|
required: false
|
||||||
default: "false"
|
default: "false"
|
||||||
|
use_foundry:
|
||||||
|
description: "Use Microsoft Foundry with OIDC authentication instead of direct Anthropic API"
|
||||||
|
required: false
|
||||||
|
default: "false"
|
||||||
|
|
||||||
use_node_cache:
|
use_node_cache:
|
||||||
description: "Whether to use Node.js dependency caching (set to true only for Node.js projects with lock files)"
|
description: "Whether to use Node.js dependency caching (set to true only for Node.js projects with lock files)"
|
||||||
@@ -75,6 +79,9 @@ outputs:
|
|||||||
execution_file:
|
execution_file:
|
||||||
description: "Path to the JSON file containing Claude Code execution log"
|
description: "Path to the JSON file containing Claude Code execution log"
|
||||||
value: ${{ steps.run_claude.outputs.execution_file }}
|
value: ${{ steps.run_claude.outputs.execution_file }}
|
||||||
|
structured_output:
|
||||||
|
description: "JSON string containing all structured output fields when --json-schema is provided in claude_args (use fromJSON() or jq to parse)"
|
||||||
|
value: ${{ steps.run_claude.outputs.structured_output }}
|
||||||
|
|
||||||
runs:
|
runs:
|
||||||
using: "composite"
|
using: "composite"
|
||||||
@@ -94,10 +101,12 @@ runs:
|
|||||||
- name: Setup Custom Bun Path
|
- name: Setup Custom Bun Path
|
||||||
if: inputs.path_to_bun_executable != ''
|
if: inputs.path_to_bun_executable != ''
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
PATH_TO_BUN_EXECUTABLE: ${{ inputs.path_to_bun_executable }}
|
||||||
run: |
|
run: |
|
||||||
echo "Using custom Bun executable: ${{ inputs.path_to_bun_executable }}"
|
echo "Using custom Bun executable: $PATH_TO_BUN_EXECUTABLE"
|
||||||
# Add the directory containing the custom executable to PATH
|
# Add the directory containing the custom executable to PATH
|
||||||
BUN_DIR=$(dirname "${{ inputs.path_to_bun_executable }}")
|
BUN_DIR=$(dirname "$PATH_TO_BUN_EXECUTABLE")
|
||||||
echo "$BUN_DIR" >> "$GITHUB_PATH"
|
echo "$BUN_DIR" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
@@ -108,14 +117,31 @@ runs:
|
|||||||
|
|
||||||
- name: Install Claude Code
|
- name: Install Claude Code
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
|
||||||
run: |
|
run: |
|
||||||
if [ -z "${{ inputs.path_to_claude_code_executable }}" ]; then
|
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
|
||||||
echo "Installing Claude Code..."
|
CLAUDE_CODE_VERSION="2.0.62"
|
||||||
curl -fsSL https://claude.ai/install.sh | bash -s 2.0.29
|
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||||
|
for attempt in 1 2 3; do
|
||||||
|
echo "Installation attempt $attempt..."
|
||||||
|
if command -v timeout &> /dev/null; then
|
||||||
|
timeout 120 bash -c "curl -fsSL https://claude.ai/install.sh | bash -s -- $CLAUDE_CODE_VERSION" && break
|
||||||
|
else
|
||||||
|
curl -fsSL https://claude.ai/install.sh | bash -s -- "$CLAUDE_CODE_VERSION" && break
|
||||||
|
fi
|
||||||
|
if [ $attempt -eq 3 ]; then
|
||||||
|
echo "Failed to install Claude Code after 3 attempts"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Installation failed, retrying..."
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo "Claude Code installed successfully"
|
||||||
else
|
else
|
||||||
echo "Using custom Claude Code executable: ${{ inputs.path_to_claude_code_executable }}"
|
echo "Using custom Claude Code executable: $PATH_TO_CLAUDE_CODE_EXECUTABLE"
|
||||||
# Add the directory containing the custom executable to PATH
|
# Add the directory containing the custom executable to PATH
|
||||||
CLAUDE_DIR=$(dirname "${{ inputs.path_to_claude_code_executable }}")
|
CLAUDE_DIR=$(dirname "$PATH_TO_CLAUDE_CODE_EXECUTABLE")
|
||||||
echo "$CLAUDE_DIR" >> "$GITHUB_PATH"
|
echo "$CLAUDE_DIR" >> "$GITHUB_PATH"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -150,12 +176,14 @@ runs:
|
|||||||
# Only set provider flags if explicitly true, since any value (including "false") is truthy
|
# Only set provider flags if explicitly true, since any value (including "false") is truthy
|
||||||
CLAUDE_CODE_USE_BEDROCK: ${{ inputs.use_bedrock == 'true' && '1' || '' }}
|
CLAUDE_CODE_USE_BEDROCK: ${{ inputs.use_bedrock == 'true' && '1' || '' }}
|
||||||
CLAUDE_CODE_USE_VERTEX: ${{ inputs.use_vertex == 'true' && '1' || '' }}
|
CLAUDE_CODE_USE_VERTEX: ${{ inputs.use_vertex == 'true' && '1' || '' }}
|
||||||
|
CLAUDE_CODE_USE_FOUNDRY: ${{ inputs.use_foundry == 'true' && '1' || '' }}
|
||||||
|
|
||||||
# AWS configuration
|
# AWS configuration
|
||||||
AWS_REGION: ${{ env.AWS_REGION }}
|
AWS_REGION: ${{ env.AWS_REGION }}
|
||||||
AWS_ACCESS_KEY_ID: ${{ env.AWS_ACCESS_KEY_ID }}
|
AWS_ACCESS_KEY_ID: ${{ env.AWS_ACCESS_KEY_ID }}
|
||||||
AWS_SECRET_ACCESS_KEY: ${{ env.AWS_SECRET_ACCESS_KEY }}
|
AWS_SECRET_ACCESS_KEY: ${{ env.AWS_SECRET_ACCESS_KEY }}
|
||||||
AWS_SESSION_TOKEN: ${{ env.AWS_SESSION_TOKEN }}
|
AWS_SESSION_TOKEN: ${{ env.AWS_SESSION_TOKEN }}
|
||||||
|
AWS_BEARER_TOKEN_BEDROCK: ${{ env.AWS_BEARER_TOKEN_BEDROCK }}
|
||||||
ANTHROPIC_BEDROCK_BASE_URL: ${{ env.ANTHROPIC_BEDROCK_BASE_URL || (env.AWS_REGION && format('https://bedrock-runtime.{0}.amazonaws.com', env.AWS_REGION)) }}
|
ANTHROPIC_BEDROCK_BASE_URL: ${{ env.ANTHROPIC_BEDROCK_BASE_URL || (env.AWS_REGION && format('https://bedrock-runtime.{0}.amazonaws.com', env.AWS_REGION)) }}
|
||||||
|
|
||||||
# GCP configuration
|
# GCP configuration
|
||||||
@@ -163,3 +191,10 @@ runs:
|
|||||||
CLOUD_ML_REGION: ${{ env.CLOUD_ML_REGION }}
|
CLOUD_ML_REGION: ${{ env.CLOUD_ML_REGION }}
|
||||||
GOOGLE_APPLICATION_CREDENTIALS: ${{ env.GOOGLE_APPLICATION_CREDENTIALS }}
|
GOOGLE_APPLICATION_CREDENTIALS: ${{ env.GOOGLE_APPLICATION_CREDENTIALS }}
|
||||||
ANTHROPIC_VERTEX_BASE_URL: ${{ env.ANTHROPIC_VERTEX_BASE_URL }}
|
ANTHROPIC_VERTEX_BASE_URL: ${{ env.ANTHROPIC_VERTEX_BASE_URL }}
|
||||||
|
|
||||||
|
# Microsoft Foundry configuration
|
||||||
|
ANTHROPIC_FOUNDRY_RESOURCE: ${{ env.ANTHROPIC_FOUNDRY_RESOURCE }}
|
||||||
|
ANTHROPIC_FOUNDRY_BASE_URL: ${{ env.ANTHROPIC_FOUNDRY_BASE_URL }}
|
||||||
|
ANTHROPIC_DEFAULT_SONNET_MODEL: ${{ env.ANTHROPIC_DEFAULT_SONNET_MODEL }}
|
||||||
|
ANTHROPIC_DEFAULT_HAIKU_MODEL: ${{ env.ANTHROPIC_DEFAULT_HAIKU_MODEL }}
|
||||||
|
ANTHROPIC_DEFAULT_OPUS_MODEL: ${{ env.ANTHROPIC_DEFAULT_OPUS_MODEL }}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
"name": "@anthropic-ai/claude-code-base-action",
|
"name": "@anthropic-ai/claude-code-base-action",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@actions/core": "^1.10.1",
|
"@actions/core": "^1.10.1",
|
||||||
|
"@anthropic-ai/claude-agent-sdk": "^0.1.52",
|
||||||
"shell-quote": "^1.8.3",
|
"shell-quote": "^1.8.3",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -25,8 +26,40 @@
|
|||||||
|
|
||||||
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||||
|
|
||||||
|
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.1.52", "", { "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.33.5", "@img/sharp-darwin-x64": "^0.33.5", "@img/sharp-linux-arm": "^0.33.5", "@img/sharp-linux-arm64": "^0.33.5", "@img/sharp-linux-x64": "^0.33.5", "@img/sharp-linuxmusl-arm64": "^0.33.5", "@img/sharp-linuxmusl-x64": "^0.33.5", "@img/sharp-win32-x64": "^0.33.5" }, "peerDependencies": { "zod": "^3.24.1" } }, "sha512-yF8N05+9NRbqYA/h39jQ726HTQFrdXXp7pEfDNKIJ2c4FdWvEjxBA/8ciZIebN6/PyvGDcbEp3yq2Co4rNpg6A=="],
|
||||||
|
|
||||||
"@fastify/busboy": ["@fastify/busboy@2.1.1", "", {}, "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA=="],
|
"@fastify/busboy": ["@fastify/busboy@2.1.1", "", {}, "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA=="],
|
||||||
|
|
||||||
|
"@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.0.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ=="],
|
||||||
|
|
||||||
|
"@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.0.4" }, "os": "darwin", "cpu": "x64" }, "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.0.5", "", { "os": "linux", "cpu": "arm" }, "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw=="],
|
||||||
|
|
||||||
|
"@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.0.5" }, "os": "linux", "cpu": "arm" }, "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ=="],
|
||||||
|
|
||||||
|
"@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.0.4" }, "os": "linux", "cpu": "arm64" }, "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA=="],
|
||||||
|
|
||||||
|
"@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.0.4" }, "os": "linux", "cpu": "x64" }, "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA=="],
|
||||||
|
|
||||||
|
"@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" }, "os": "linux", "cpu": "arm64" }, "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g=="],
|
||||||
|
|
||||||
|
"@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.0.4" }, "os": "linux", "cpu": "x64" }, "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw=="],
|
||||||
|
|
||||||
|
"@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.33.5", "", { "os": "win32", "cpu": "x64" }, "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg=="],
|
||||||
|
|
||||||
"@types/bun": ["@types/bun@1.2.19", "", { "dependencies": { "bun-types": "1.2.19" } }, "sha512-d9ZCmrH3CJ2uYKXQIUuZ/pUnTqIvLDS0SK7pFmbx8ma+ziH/FRMoAq5bYpRG7y+w1gl+HgyNZbtqgMq4W4e2Lg=="],
|
"@types/bun": ["@types/bun@1.2.19", "", { "dependencies": { "bun-types": "1.2.19" } }, "sha512-d9ZCmrH3CJ2uYKXQIUuZ/pUnTqIvLDS0SK7pFmbx8ma+ziH/FRMoAq5bYpRG7y+w1gl+HgyNZbtqgMq4W4e2Lg=="],
|
||||||
|
|
||||||
"@types/node": ["@types/node@20.19.9", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-cuVNgarYWZqxRJDQHEB58GEONhOK79QVR/qYx4S7kcUObQvUwvFnYxJuuHUKm2aieN9X3yZB4LZsuYNU1Qphsw=="],
|
"@types/node": ["@types/node@20.19.9", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-cuVNgarYWZqxRJDQHEB58GEONhOK79QVR/qYx4S7kcUObQvUwvFnYxJuuHUKm2aieN9X3yZB4LZsuYNU1Qphsw=="],
|
||||||
@@ -50,5 +83,7 @@
|
|||||||
"undici": ["undici@5.29.0", "", { "dependencies": { "@fastify/busboy": "^2.0.0" } }, "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg=="],
|
"undici": ["undici@5.29.0", "", { "dependencies": { "@fastify/busboy": "^2.0.0" } }, "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg=="],
|
||||||
|
|
||||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||||
|
|
||||||
|
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@actions/core": "^1.10.1",
|
"@actions/core": "^1.10.1",
|
||||||
|
"@anthropic-ai/claude-agent-sdk": "^0.1.52",
|
||||||
"shell-quote": "^1.8.3"
|
"shell-quote": "^1.8.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
149
base-action/src/parse-sdk-options.ts
Normal file
149
base-action/src/parse-sdk-options.ts
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
import { parse as parseShellArgs } from "shell-quote";
|
||||||
|
import type { ClaudeOptions } from "./run-claude";
|
||||||
|
import type { Options as SdkOptions } from "@anthropic-ai/claude-agent-sdk";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Result of parsing ClaudeOptions for SDK usage
|
||||||
|
*/
|
||||||
|
export type ParsedSdkOptions = {
|
||||||
|
sdkOptions: SdkOptions;
|
||||||
|
showFullOutput: boolean;
|
||||||
|
hasJsonSchema: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Flags that should accumulate multiple values instead of overwriting
|
||||||
|
const ACCUMULATING_FLAGS = new Set(["allowedTools", "disallowedTools"]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse claudeArgs string into extraArgs record for SDK pass-through
|
||||||
|
* The SDK/CLI will handle --mcp-config, --json-schema, etc.
|
||||||
|
* For allowedTools and disallowedTools, multiple occurrences are accumulated (comma-joined).
|
||||||
|
*/
|
||||||
|
function parseClaudeArgsToExtraArgs(
|
||||||
|
claudeArgs?: string,
|
||||||
|
): Record<string, string | null> {
|
||||||
|
if (!claudeArgs?.trim()) return {};
|
||||||
|
|
||||||
|
const result: Record<string, string | null> = {};
|
||||||
|
const args = parseShellArgs(claudeArgs).filter(
|
||||||
|
(arg): arg is string => typeof arg === "string",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (let i = 0; i < args.length; i++) {
|
||||||
|
const arg = args[i];
|
||||||
|
if (arg?.startsWith("--")) {
|
||||||
|
const flag = arg.slice(2);
|
||||||
|
const nextArg = args[i + 1];
|
||||||
|
|
||||||
|
// Check if next arg is a value (not another flag)
|
||||||
|
if (nextArg && !nextArg.startsWith("--")) {
|
||||||
|
// For accumulating flags, join multiple values with commas
|
||||||
|
if (ACCUMULATING_FLAGS.has(flag) && result[flag]) {
|
||||||
|
result[flag] = `${result[flag]},${nextArg}`;
|
||||||
|
} else {
|
||||||
|
result[flag] = nextArg;
|
||||||
|
}
|
||||||
|
i++; // Skip the value
|
||||||
|
} else {
|
||||||
|
result[flag] = null; // Boolean flag
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse ClaudeOptions into SDK-compatible options
|
||||||
|
* Uses extraArgs for CLI pass-through instead of duplicating option parsing
|
||||||
|
*/
|
||||||
|
export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
|
||||||
|
// Determine output verbosity
|
||||||
|
const isDebugMode = process.env.ACTIONS_STEP_DEBUG === "true";
|
||||||
|
const showFullOutput = options.showFullOutput === "true" || isDebugMode;
|
||||||
|
|
||||||
|
// Parse claudeArgs into extraArgs for CLI pass-through
|
||||||
|
const extraArgs = parseClaudeArgsToExtraArgs(options.claudeArgs);
|
||||||
|
|
||||||
|
// Detect if --json-schema is present (for hasJsonSchema flag)
|
||||||
|
const hasJsonSchema = "json-schema" in extraArgs;
|
||||||
|
|
||||||
|
// Extract and merge allowedTools from both sources:
|
||||||
|
// 1. From extraArgs (parsed from claudeArgs - contains tag mode's tools)
|
||||||
|
// 2. From options.allowedTools (direct input - may be undefined)
|
||||||
|
// This prevents duplicate flags being overwritten when claudeArgs contains --allowedTools
|
||||||
|
const extraArgsAllowedTools = extraArgs["allowedTools"]
|
||||||
|
? extraArgs["allowedTools"].split(",").map((t) => t.trim())
|
||||||
|
: [];
|
||||||
|
const directAllowedTools = options.allowedTools
|
||||||
|
? options.allowedTools.split(",").map((t) => t.trim())
|
||||||
|
: [];
|
||||||
|
const mergedAllowedTools = [
|
||||||
|
...new Set([...extraArgsAllowedTools, ...directAllowedTools]),
|
||||||
|
];
|
||||||
|
delete extraArgs["allowedTools"];
|
||||||
|
|
||||||
|
// Same for disallowedTools
|
||||||
|
const extraArgsDisallowedTools = extraArgs["disallowedTools"]
|
||||||
|
? extraArgs["disallowedTools"].split(",").map((t) => t.trim())
|
||||||
|
: [];
|
||||||
|
const directDisallowedTools = options.disallowedTools
|
||||||
|
? options.disallowedTools.split(",").map((t) => t.trim())
|
||||||
|
: [];
|
||||||
|
const mergedDisallowedTools = [
|
||||||
|
...new Set([...extraArgsDisallowedTools, ...directDisallowedTools]),
|
||||||
|
];
|
||||||
|
delete extraArgs["disallowedTools"];
|
||||||
|
|
||||||
|
// Build custom environment
|
||||||
|
const env: Record<string, string | undefined> = { ...process.env };
|
||||||
|
if (process.env.INPUT_ACTION_INPUTS_PRESENT) {
|
||||||
|
env.GITHUB_ACTION_INPUTS = process.env.INPUT_ACTION_INPUTS_PRESENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build system prompt option - default to claude_code preset
|
||||||
|
let systemPrompt: SdkOptions["systemPrompt"];
|
||||||
|
if (options.systemPrompt) {
|
||||||
|
systemPrompt = options.systemPrompt;
|
||||||
|
} else if (options.appendSystemPrompt) {
|
||||||
|
systemPrompt = {
|
||||||
|
type: "preset",
|
||||||
|
preset: "claude_code",
|
||||||
|
append: options.appendSystemPrompt,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// Default to claude_code preset when no custom prompt is specified
|
||||||
|
systemPrompt = {
|
||||||
|
type: "preset",
|
||||||
|
preset: "claude_code",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build SDK options - use merged tools from both direct options and claudeArgs
|
||||||
|
const sdkOptions: SdkOptions = {
|
||||||
|
// Direct options from ClaudeOptions inputs
|
||||||
|
model: options.model,
|
||||||
|
maxTurns: options.maxTurns ? parseInt(options.maxTurns, 10) : undefined,
|
||||||
|
allowedTools:
|
||||||
|
mergedAllowedTools.length > 0 ? mergedAllowedTools : undefined,
|
||||||
|
disallowedTools:
|
||||||
|
mergedDisallowedTools.length > 0 ? mergedDisallowedTools : undefined,
|
||||||
|
systemPrompt,
|
||||||
|
fallbackModel: options.fallbackModel,
|
||||||
|
pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable,
|
||||||
|
|
||||||
|
// Pass through claudeArgs as extraArgs - CLI handles --mcp-config, --json-schema, etc.
|
||||||
|
// Note: allowedTools and disallowedTools have been removed from extraArgs to prevent duplicates
|
||||||
|
extraArgs,
|
||||||
|
env,
|
||||||
|
|
||||||
|
// Load settings from all sources to pick up CLI-installed plugins, CLAUDE.md, etc.
|
||||||
|
settingSources: ["user", "project", "local"],
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
sdkOptions,
|
||||||
|
showFullOutput,
|
||||||
|
hasJsonSchema,
|
||||||
|
};
|
||||||
|
}
|
||||||
151
base-action/src/run-claude-sdk.ts
Normal file
151
base-action/src/run-claude-sdk.ts
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
import * as core from "@actions/core";
|
||||||
|
import { readFile, writeFile } from "fs/promises";
|
||||||
|
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||||
|
import type {
|
||||||
|
SDKMessage,
|
||||||
|
SDKResultMessage,
|
||||||
|
} from "@anthropic-ai/claude-agent-sdk";
|
||||||
|
import type { ParsedSdkOptions } from "./parse-sdk-options";
|
||||||
|
|
||||||
|
const EXECUTION_FILE = `${process.env.RUNNER_TEMP}/claude-execution-output.json`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitizes SDK output to match CLI sanitization behavior
|
||||||
|
*/
|
||||||
|
function sanitizeSdkOutput(
|
||||||
|
message: SDKMessage,
|
||||||
|
showFullOutput: boolean,
|
||||||
|
): string | null {
|
||||||
|
if (showFullOutput) {
|
||||||
|
return JSON.stringify(message, null, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// System initialization - safe to show
|
||||||
|
if (message.type === "system" && message.subtype === "init") {
|
||||||
|
return JSON.stringify(
|
||||||
|
{
|
||||||
|
type: "system",
|
||||||
|
subtype: "init",
|
||||||
|
message: "Claude Code initialized",
|
||||||
|
model: "model" in message ? message.model : "unknown",
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result messages - show sanitized summary
|
||||||
|
if (message.type === "result") {
|
||||||
|
const resultMsg = message as SDKResultMessage;
|
||||||
|
return JSON.stringify(
|
||||||
|
{
|
||||||
|
type: "result",
|
||||||
|
subtype: resultMsg.subtype,
|
||||||
|
is_error: resultMsg.is_error,
|
||||||
|
duration_ms: resultMsg.duration_ms,
|
||||||
|
num_turns: resultMsg.num_turns,
|
||||||
|
total_cost_usd: resultMsg.total_cost_usd,
|
||||||
|
permission_denials: resultMsg.permission_denials,
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Suppress other message types in non-full-output mode
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run Claude using the Agent SDK
|
||||||
|
*/
|
||||||
|
export async function runClaudeWithSdk(
|
||||||
|
promptPath: string,
|
||||||
|
{ sdkOptions, showFullOutput, hasJsonSchema }: ParsedSdkOptions,
|
||||||
|
): Promise<void> {
|
||||||
|
const prompt = await readFile(promptPath, "utf-8");
|
||||||
|
|
||||||
|
if (!showFullOutput) {
|
||||||
|
console.log(
|
||||||
|
"Running Claude Code via SDK (full output hidden for security)...",
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
"Rerun in debug mode or enable `show_full_output: true` in your workflow file for full output.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Running Claude with prompt from file: ${promptPath}`);
|
||||||
|
// Log SDK options without env (which could contain sensitive data)
|
||||||
|
const { env, ...optionsToLog } = sdkOptions;
|
||||||
|
console.log("SDK options:", JSON.stringify(optionsToLog, null, 2));
|
||||||
|
|
||||||
|
const messages: SDKMessage[] = [];
|
||||||
|
let resultMessage: SDKResultMessage | undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
for await (const message of query({ prompt, options: sdkOptions })) {
|
||||||
|
messages.push(message);
|
||||||
|
|
||||||
|
const sanitized = sanitizeSdkOutput(message, showFullOutput);
|
||||||
|
if (sanitized) {
|
||||||
|
console.log(sanitized);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.type === "result") {
|
||||||
|
resultMessage = message as SDKResultMessage;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("SDK execution error:", error);
|
||||||
|
core.setOutput("conclusion", "failure");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write execution file
|
||||||
|
try {
|
||||||
|
await writeFile(EXECUTION_FILE, JSON.stringify(messages, null, 2));
|
||||||
|
console.log(`Log saved to ${EXECUTION_FILE}`);
|
||||||
|
core.setOutput("execution_file", EXECUTION_FILE);
|
||||||
|
} catch (error) {
|
||||||
|
core.warning(`Failed to write execution file: ${error}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!resultMessage) {
|
||||||
|
core.setOutput("conclusion", "failure");
|
||||||
|
core.error("No result message received from Claude");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isSuccess = resultMessage.subtype === "success";
|
||||||
|
core.setOutput("conclusion", isSuccess ? "success" : "failure");
|
||||||
|
|
||||||
|
// Handle structured output
|
||||||
|
if (hasJsonSchema) {
|
||||||
|
if (
|
||||||
|
isSuccess &&
|
||||||
|
"structured_output" in resultMessage &&
|
||||||
|
resultMessage.structured_output
|
||||||
|
) {
|
||||||
|
const structuredOutputJson = JSON.stringify(
|
||||||
|
resultMessage.structured_output,
|
||||||
|
);
|
||||||
|
core.setOutput("structured_output", structuredOutputJson);
|
||||||
|
core.info(
|
||||||
|
`Set structured_output with ${Object.keys(resultMessage.structured_output as object).length} field(s)`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
core.setFailed(
|
||||||
|
`--json-schema was provided but Claude did not return structured_output. Result subtype: ${resultMessage.subtype}`,
|
||||||
|
);
|
||||||
|
core.setOutput("conclusion", "failure");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isSuccess) {
|
||||||
|
if ("errors" in resultMessage && resultMessage.errors) {
|
||||||
|
core.error(`Execution failed: ${resultMessage.errors.join(", ")}`);
|
||||||
|
}
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
import * as core from "@actions/core";
|
import * as core from "@actions/core";
|
||||||
import { exec } from "child_process";
|
import { exec } from "child_process";
|
||||||
import { promisify } from "util";
|
import { promisify } from "util";
|
||||||
import { unlink, writeFile, stat } from "fs/promises";
|
import { unlink, writeFile, stat, readFile } from "fs/promises";
|
||||||
import { createWriteStream } from "fs";
|
import { createWriteStream } from "fs";
|
||||||
import { spawn } from "child_process";
|
import { spawn } from "child_process";
|
||||||
import { parse as parseShellArgs } from "shell-quote";
|
import { parse as parseShellArgs } from "shell-quote";
|
||||||
|
import { runClaudeWithSdk } from "./run-claude-sdk";
|
||||||
|
import { parseSdkOptions } from "./parse-sdk-options";
|
||||||
|
|
||||||
const execAsync = promisify(exec);
|
const execAsync = promisify(exec);
|
||||||
|
|
||||||
@@ -122,9 +124,65 @@ export function prepareRunConfig(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses structured_output from execution file and sets GitHub Action outputs
|
||||||
|
* Only runs if --json-schema was explicitly provided in claude_args
|
||||||
|
* Exported for testing
|
||||||
|
*/
|
||||||
|
export async function parseAndSetStructuredOutputs(
|
||||||
|
executionFile: string,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const content = await readFile(executionFile, "utf-8");
|
||||||
|
const messages = JSON.parse(content) as {
|
||||||
|
type: string;
|
||||||
|
structured_output?: Record<string, unknown>;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
// Search backwards - result is typically last or second-to-last message
|
||||||
|
const result = messages.findLast(
|
||||||
|
(m) => m.type === "result" && m.structured_output,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!result?.structured_output) {
|
||||||
|
throw new Error(
|
||||||
|
`--json-schema was provided but Claude did not return structured_output.\n` +
|
||||||
|
`Found ${messages.length} messages. Result exists: ${!!result}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the complete structured output as a single JSON string
|
||||||
|
// This works around GitHub Actions limitation that composite actions can't have dynamic outputs
|
||||||
|
const structuredOutputJson = JSON.stringify(result.structured_output);
|
||||||
|
core.setOutput("structured_output", structuredOutputJson);
|
||||||
|
core.info(
|
||||||
|
`Set structured_output with ${Object.keys(result.structured_output).length} field(s)`,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error) {
|
||||||
|
throw error; // Preserve original error and stack trace
|
||||||
|
}
|
||||||
|
throw new Error(`Failed to parse structured outputs: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function runClaude(promptPath: string, options: ClaudeOptions) {
|
export async function runClaude(promptPath: string, options: ClaudeOptions) {
|
||||||
|
// Feature flag: use SDK path when USE_AGENT_SDK=true
|
||||||
|
const useAgentSdk = process.env.USE_AGENT_SDK === "true";
|
||||||
|
console.log(
|
||||||
|
`Using ${useAgentSdk ? "Agent SDK" : "CLI"} path (USE_AGENT_SDK=${process.env.USE_AGENT_SDK ?? "unset"})`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (useAgentSdk) {
|
||||||
|
const parsedOptions = parseSdkOptions(options);
|
||||||
|
return runClaudeWithSdk(promptPath, parsedOptions);
|
||||||
|
}
|
||||||
|
|
||||||
const config = prepareRunConfig(promptPath, options);
|
const config = prepareRunConfig(promptPath, options);
|
||||||
|
|
||||||
|
// Detect if --json-schema is present in claude args
|
||||||
|
const hasJsonSchema = options.claudeArgs?.includes("--json-schema") ?? false;
|
||||||
|
|
||||||
// Create a named pipe
|
// Create a named pipe
|
||||||
try {
|
try {
|
||||||
await unlink(PIPE_PATH);
|
await unlink(PIPE_PATH);
|
||||||
@@ -308,8 +366,23 @@ export async function runClaude(promptPath: string, options: ClaudeOptions) {
|
|||||||
core.warning(`Failed to process output for execution metrics: ${e}`);
|
core.warning(`Failed to process output for execution metrics: ${e}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
core.setOutput("conclusion", "success");
|
|
||||||
core.setOutput("execution_file", EXECUTION_FILE);
|
core.setOutput("execution_file", EXECUTION_FILE);
|
||||||
|
|
||||||
|
// Parse and set structured outputs only if user provided --json-schema in claude_args
|
||||||
|
if (hasJsonSchema) {
|
||||||
|
try {
|
||||||
|
await parseAndSetStructuredOutputs(EXECUTION_FILE);
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage =
|
||||||
|
error instanceof Error ? error.message : String(error);
|
||||||
|
core.setFailed(errorMessage);
|
||||||
|
core.setOutput("conclusion", "failure");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set conclusion to success if we reached here
|
||||||
|
core.setOutput("conclusion", "success");
|
||||||
} else {
|
} else {
|
||||||
core.setOutput("conclusion", "failure");
|
core.setOutput("conclusion", "failure");
|
||||||
|
|
||||||
|
|||||||
@@ -1,39 +1,50 @@
|
|||||||
/**
|
/**
|
||||||
* Validates the environment variables required for running Claude Code
|
* Validates the environment variables required for running Claude Code
|
||||||
* based on the selected provider (Anthropic API, AWS Bedrock, or Google Vertex AI)
|
* based on the selected provider (Anthropic API, AWS Bedrock, Google Vertex AI, or Microsoft Foundry)
|
||||||
*/
|
*/
|
||||||
export function validateEnvironmentVariables() {
|
export function validateEnvironmentVariables() {
|
||||||
const useBedrock = process.env.CLAUDE_CODE_USE_BEDROCK === "1";
|
const useBedrock = process.env.CLAUDE_CODE_USE_BEDROCK === "1";
|
||||||
const useVertex = process.env.CLAUDE_CODE_USE_VERTEX === "1";
|
const useVertex = process.env.CLAUDE_CODE_USE_VERTEX === "1";
|
||||||
|
const useFoundry = process.env.CLAUDE_CODE_USE_FOUNDRY === "1";
|
||||||
const anthropicApiKey = process.env.ANTHROPIC_API_KEY;
|
const anthropicApiKey = process.env.ANTHROPIC_API_KEY;
|
||||||
const claudeCodeOAuthToken = process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
const claudeCodeOAuthToken = process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
||||||
|
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
|
|
||||||
if (useBedrock && useVertex) {
|
// Check for mutual exclusivity between providers
|
||||||
|
const activeProviders = [useBedrock, useVertex, useFoundry].filter(Boolean);
|
||||||
|
if (activeProviders.length > 1) {
|
||||||
errors.push(
|
errors.push(
|
||||||
"Cannot use both Bedrock and Vertex AI simultaneously. Please set only one provider.",
|
"Cannot use multiple providers simultaneously. Please set only one of: CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!useBedrock && !useVertex) {
|
if (!useBedrock && !useVertex && !useFoundry) {
|
||||||
if (!anthropicApiKey && !claudeCodeOAuthToken) {
|
if (!anthropicApiKey && !claudeCodeOAuthToken) {
|
||||||
errors.push(
|
errors.push(
|
||||||
"Either ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN is required when using direct Anthropic API.",
|
"Either ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN is required when using direct Anthropic API.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if (useBedrock) {
|
} else if (useBedrock) {
|
||||||
const requiredBedrockVars = {
|
const awsRegion = process.env.AWS_REGION;
|
||||||
AWS_REGION: process.env.AWS_REGION,
|
const awsAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
|
||||||
AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID,
|
const awsSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
|
||||||
AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY,
|
const awsBearerToken = process.env.AWS_BEARER_TOKEN_BEDROCK;
|
||||||
};
|
|
||||||
|
|
||||||
Object.entries(requiredBedrockVars).forEach(([key, value]) => {
|
// AWS_REGION is always required for Bedrock
|
||||||
if (!value) {
|
if (!awsRegion) {
|
||||||
errors.push(`${key} is required when using AWS Bedrock.`);
|
errors.push("AWS_REGION is required when using AWS Bedrock.");
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
// Either bearer token OR access key credentials must be provided
|
||||||
|
const hasAccessKeyCredentials = awsAccessKeyId && awsSecretAccessKey;
|
||||||
|
const hasBearerToken = awsBearerToken;
|
||||||
|
|
||||||
|
if (!hasAccessKeyCredentials && !hasBearerToken) {
|
||||||
|
errors.push(
|
||||||
|
"Either AWS_BEARER_TOKEN_BEDROCK or both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required when using AWS Bedrock.",
|
||||||
|
);
|
||||||
|
}
|
||||||
} else if (useVertex) {
|
} else if (useVertex) {
|
||||||
const requiredVertexVars = {
|
const requiredVertexVars = {
|
||||||
ANTHROPIC_VERTEX_PROJECT_ID: process.env.ANTHROPIC_VERTEX_PROJECT_ID,
|
ANTHROPIC_VERTEX_PROJECT_ID: process.env.ANTHROPIC_VERTEX_PROJECT_ID,
|
||||||
@@ -45,6 +56,16 @@ export function validateEnvironmentVariables() {
|
|||||||
errors.push(`${key} is required when using Google Vertex AI.`);
|
errors.push(`${key} is required when using Google Vertex AI.`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
} else if (useFoundry) {
|
||||||
|
const foundryResource = process.env.ANTHROPIC_FOUNDRY_RESOURCE;
|
||||||
|
const foundryBaseUrl = process.env.ANTHROPIC_FOUNDRY_BASE_URL;
|
||||||
|
|
||||||
|
// Either resource name or base URL is required
|
||||||
|
if (!foundryResource && !foundryBaseUrl) {
|
||||||
|
errors.push(
|
||||||
|
"Either ANTHROPIC_FOUNDRY_RESOURCE or ANTHROPIC_FOUNDRY_BASE_URL is required when using Microsoft Foundry.",
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (errors.length > 0) {
|
if (errors.length > 0) {
|
||||||
|
|||||||
163
base-action/test/parse-sdk-options.test.ts
Normal file
163
base-action/test/parse-sdk-options.test.ts
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
#!/usr/bin/env bun
|
||||||
|
|
||||||
|
import { describe, test, expect } from "bun:test";
|
||||||
|
import { parseSdkOptions } from "../src/parse-sdk-options";
|
||||||
|
import type { ClaudeOptions } from "../src/run-claude";
|
||||||
|
|
||||||
|
describe("parseSdkOptions", () => {
|
||||||
|
describe("allowedTools merging", () => {
|
||||||
|
test("should extract allowedTools from claudeArgs", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--allowedTools "Edit,Read,Write"',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.allowedTools).toEqual(["Edit", "Read", "Write"]);
|
||||||
|
expect(result.sdkOptions.extraArgs?.["allowedTools"]).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should extract allowedTools from claudeArgs with MCP tools", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs:
|
||||||
|
'--allowedTools "Edit,Read,mcp__github_comment__update_claude_comment"',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.allowedTools).toEqual([
|
||||||
|
"Edit",
|
||||||
|
"Read",
|
||||||
|
"mcp__github_comment__update_claude_comment",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should accumulate multiple --allowedTools flags from claudeArgs", () => {
|
||||||
|
// This simulates tag mode adding its tools, then user adding their own
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs:
|
||||||
|
'--allowedTools "Edit,Read,mcp__github_comment__update_claude_comment" --model "claude-3" --allowedTools "Bash(npm install),mcp__github__get_issue"',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.allowedTools).toEqual([
|
||||||
|
"Edit",
|
||||||
|
"Read",
|
||||||
|
"mcp__github_comment__update_claude_comment",
|
||||||
|
"Bash(npm install)",
|
||||||
|
"mcp__github__get_issue",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should merge allowedTools from both claudeArgs and direct options", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--allowedTools "Edit,Read"',
|
||||||
|
allowedTools: "Write,Glob",
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.allowedTools).toEqual([
|
||||||
|
"Edit",
|
||||||
|
"Read",
|
||||||
|
"Write",
|
||||||
|
"Glob",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should deduplicate allowedTools when merging", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--allowedTools "Edit,Read"',
|
||||||
|
allowedTools: "Edit,Write",
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.allowedTools).toEqual(["Edit", "Read", "Write"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should use only direct options when claudeArgs has no allowedTools", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--model "claude-3-5-sonnet"',
|
||||||
|
allowedTools: "Edit,Read",
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.allowedTools).toEqual(["Edit", "Read"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should return undefined allowedTools when neither source has it", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--model "claude-3-5-sonnet"',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.allowedTools).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should remove allowedTools from extraArgs after extraction", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--allowedTools "Edit,Read" --model "claude-3-5-sonnet"',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.extraArgs?.["allowedTools"]).toBeUndefined();
|
||||||
|
expect(result.sdkOptions.extraArgs?.["model"]).toBe("claude-3-5-sonnet");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("disallowedTools merging", () => {
|
||||||
|
test("should extract disallowedTools from claudeArgs", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--disallowedTools "Bash,Write"',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.disallowedTools).toEqual(["Bash", "Write"]);
|
||||||
|
expect(result.sdkOptions.extraArgs?.["disallowedTools"]).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should merge disallowedTools from both sources", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: '--disallowedTools "Bash"',
|
||||||
|
disallowedTools: "Write",
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.disallowedTools).toEqual(["Bash", "Write"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("other extraArgs passthrough", () => {
|
||||||
|
test("should pass through mcp-config in extraArgs", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: `--mcp-config '{"mcpServers":{}}' --allowedTools "Edit"`,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.extraArgs?.["mcp-config"]).toBe(
|
||||||
|
'{"mcpServers":{}}',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should pass through json-schema in extraArgs", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs: `--json-schema '{"type":"object"}'`,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = parseSdkOptions(options);
|
||||||
|
|
||||||
|
expect(result.sdkOptions.extraArgs?.["json-schema"]).toBe(
|
||||||
|
'{"type":"object"}',
|
||||||
|
);
|
||||||
|
expect(result.hasJsonSchema).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -78,5 +78,19 @@ describe("prepareRunConfig", () => {
|
|||||||
"stream-json",
|
"stream-json",
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("should include json-schema flag when provided", () => {
|
||||||
|
const options: ClaudeOptions = {
|
||||||
|
claudeArgs:
|
||||||
|
'--json-schema \'{"type":"object","properties":{"result":{"type":"boolean"}}}\'',
|
||||||
|
};
|
||||||
|
|
||||||
|
const prepared = prepareRunConfig("/tmp/test-prompt.txt", options);
|
||||||
|
|
||||||
|
expect(prepared.claudeArgs).toContain("--json-schema");
|
||||||
|
expect(prepared.claudeArgs).toContain(
|
||||||
|
'{"type":"object","properties":{"result":{"type":"boolean"}}}',
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
158
base-action/test/structured-output.test.ts
Normal file
158
base-action/test/structured-output.test.ts
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
#!/usr/bin/env bun
|
||||||
|
|
||||||
|
import { describe, test, expect, afterEach, beforeEach, spyOn } from "bun:test";
|
||||||
|
import { writeFile, unlink } from "fs/promises";
|
||||||
|
import { tmpdir } from "os";
|
||||||
|
import { join } from "path";
|
||||||
|
import { parseAndSetStructuredOutputs } from "../src/run-claude";
|
||||||
|
import * as core from "@actions/core";
|
||||||
|
|
||||||
|
// Mock execution file path
|
||||||
|
const TEST_EXECUTION_FILE = join(tmpdir(), "test-execution-output.json");
|
||||||
|
|
||||||
|
// Helper to create mock execution file with structured output
|
||||||
|
async function createMockExecutionFile(
|
||||||
|
structuredOutput?: Record<string, unknown>,
|
||||||
|
includeResult: boolean = true,
|
||||||
|
): Promise<void> {
|
||||||
|
const messages: any[] = [
|
||||||
|
{ type: "system", subtype: "init" },
|
||||||
|
{ type: "turn", content: "test" },
|
||||||
|
];
|
||||||
|
|
||||||
|
if (includeResult) {
|
||||||
|
messages.push({
|
||||||
|
type: "result",
|
||||||
|
cost_usd: 0.01,
|
||||||
|
duration_ms: 1000,
|
||||||
|
structured_output: structuredOutput,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await writeFile(TEST_EXECUTION_FILE, JSON.stringify(messages));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Spy on core functions
|
||||||
|
let setOutputSpy: any;
|
||||||
|
let infoSpy: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
setOutputSpy = spyOn(core, "setOutput").mockImplementation(() => {});
|
||||||
|
infoSpy = spyOn(core, "info").mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parseAndSetStructuredOutputs", () => {
|
||||||
|
afterEach(async () => {
|
||||||
|
setOutputSpy?.mockRestore();
|
||||||
|
infoSpy?.mockRestore();
|
||||||
|
try {
|
||||||
|
await unlink(TEST_EXECUTION_FILE);
|
||||||
|
} catch {
|
||||||
|
// Ignore if file doesn't exist
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should set structured_output with valid data", async () => {
|
||||||
|
await createMockExecutionFile({
|
||||||
|
is_flaky: true,
|
||||||
|
confidence: 0.85,
|
||||||
|
summary: "Test looks flaky",
|
||||||
|
});
|
||||||
|
|
||||||
|
await parseAndSetStructuredOutputs(TEST_EXECUTION_FILE);
|
||||||
|
|
||||||
|
expect(setOutputSpy).toHaveBeenCalledWith(
|
||||||
|
"structured_output",
|
||||||
|
'{"is_flaky":true,"confidence":0.85,"summary":"Test looks flaky"}',
|
||||||
|
);
|
||||||
|
expect(infoSpy).toHaveBeenCalledWith(
|
||||||
|
"Set structured_output with 3 field(s)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should handle arrays and nested objects", async () => {
|
||||||
|
await createMockExecutionFile({
|
||||||
|
items: ["a", "b", "c"],
|
||||||
|
config: { key: "value", nested: { deep: true } },
|
||||||
|
});
|
||||||
|
|
||||||
|
await parseAndSetStructuredOutputs(TEST_EXECUTION_FILE);
|
||||||
|
|
||||||
|
const callArgs = setOutputSpy.mock.calls[0];
|
||||||
|
expect(callArgs[0]).toBe("structured_output");
|
||||||
|
const parsed = JSON.parse(callArgs[1]);
|
||||||
|
expect(parsed).toEqual({
|
||||||
|
items: ["a", "b", "c"],
|
||||||
|
config: { key: "value", nested: { deep: true } },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should handle special characters in field names", async () => {
|
||||||
|
await createMockExecutionFile({
|
||||||
|
"test-result": "passed",
|
||||||
|
"item.count": 10,
|
||||||
|
"user@email": "test",
|
||||||
|
});
|
||||||
|
|
||||||
|
await parseAndSetStructuredOutputs(TEST_EXECUTION_FILE);
|
||||||
|
|
||||||
|
const callArgs = setOutputSpy.mock.calls[0];
|
||||||
|
const parsed = JSON.parse(callArgs[1]);
|
||||||
|
expect(parsed["test-result"]).toBe("passed");
|
||||||
|
expect(parsed["item.count"]).toBe(10);
|
||||||
|
expect(parsed["user@email"]).toBe("test");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should throw error when result exists but structured_output is undefined", async () => {
|
||||||
|
const messages = [
|
||||||
|
{ type: "system", subtype: "init" },
|
||||||
|
{ type: "result", cost_usd: 0.01, duration_ms: 1000 },
|
||||||
|
];
|
||||||
|
await writeFile(TEST_EXECUTION_FILE, JSON.stringify(messages));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
parseAndSetStructuredOutputs(TEST_EXECUTION_FILE),
|
||||||
|
).rejects.toThrow(
|
||||||
|
"--json-schema was provided but Claude did not return structured_output",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should throw error when no result message exists", async () => {
|
||||||
|
const messages = [
|
||||||
|
{ type: "system", subtype: "init" },
|
||||||
|
{ type: "turn", content: "test" },
|
||||||
|
];
|
||||||
|
await writeFile(TEST_EXECUTION_FILE, JSON.stringify(messages));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
parseAndSetStructuredOutputs(TEST_EXECUTION_FILE),
|
||||||
|
).rejects.toThrow(
|
||||||
|
"--json-schema was provided but Claude did not return structured_output",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should throw error with malformed JSON", async () => {
|
||||||
|
await writeFile(TEST_EXECUTION_FILE, "{ invalid json");
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
parseAndSetStructuredOutputs(TEST_EXECUTION_FILE),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should throw error when file does not exist", async () => {
|
||||||
|
await expect(
|
||||||
|
parseAndSetStructuredOutputs("/nonexistent/file.json"),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should handle empty structured_output object", async () => {
|
||||||
|
await createMockExecutionFile({});
|
||||||
|
|
||||||
|
await parseAndSetStructuredOutputs(TEST_EXECUTION_FILE);
|
||||||
|
|
||||||
|
expect(setOutputSpy).toHaveBeenCalledWith("structured_output", "{}");
|
||||||
|
expect(infoSpy).toHaveBeenCalledWith(
|
||||||
|
"Set structured_output with 0 field(s)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -13,15 +13,19 @@ describe("validateEnvironmentVariables", () => {
|
|||||||
delete process.env.ANTHROPIC_API_KEY;
|
delete process.env.ANTHROPIC_API_KEY;
|
||||||
delete process.env.CLAUDE_CODE_USE_BEDROCK;
|
delete process.env.CLAUDE_CODE_USE_BEDROCK;
|
||||||
delete process.env.CLAUDE_CODE_USE_VERTEX;
|
delete process.env.CLAUDE_CODE_USE_VERTEX;
|
||||||
|
delete process.env.CLAUDE_CODE_USE_FOUNDRY;
|
||||||
delete process.env.AWS_REGION;
|
delete process.env.AWS_REGION;
|
||||||
delete process.env.AWS_ACCESS_KEY_ID;
|
delete process.env.AWS_ACCESS_KEY_ID;
|
||||||
delete process.env.AWS_SECRET_ACCESS_KEY;
|
delete process.env.AWS_SECRET_ACCESS_KEY;
|
||||||
delete process.env.AWS_SESSION_TOKEN;
|
delete process.env.AWS_SESSION_TOKEN;
|
||||||
|
delete process.env.AWS_BEARER_TOKEN_BEDROCK;
|
||||||
delete process.env.ANTHROPIC_BEDROCK_BASE_URL;
|
delete process.env.ANTHROPIC_BEDROCK_BASE_URL;
|
||||||
delete process.env.ANTHROPIC_VERTEX_PROJECT_ID;
|
delete process.env.ANTHROPIC_VERTEX_PROJECT_ID;
|
||||||
delete process.env.CLOUD_ML_REGION;
|
delete process.env.CLOUD_ML_REGION;
|
||||||
delete process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
delete process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
||||||
delete process.env.ANTHROPIC_VERTEX_BASE_URL;
|
delete process.env.ANTHROPIC_VERTEX_BASE_URL;
|
||||||
|
delete process.env.ANTHROPIC_FOUNDRY_RESOURCE;
|
||||||
|
delete process.env.ANTHROPIC_FOUNDRY_BASE_URL;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -92,31 +96,58 @@ describe("validateEnvironmentVariables", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("should fail when AWS_ACCESS_KEY_ID is missing", () => {
|
test("should fail when only AWS_SECRET_ACCESS_KEY is provided without bearer token", () => {
|
||||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
process.env.AWS_REGION = "us-east-1";
|
process.env.AWS_REGION = "us-east-1";
|
||||||
process.env.AWS_SECRET_ACCESS_KEY = "test-secret-key";
|
process.env.AWS_SECRET_ACCESS_KEY = "test-secret-key";
|
||||||
|
|
||||||
expect(() => validateEnvironmentVariables()).toThrow(
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
"AWS_ACCESS_KEY_ID is required when using AWS Bedrock.",
|
"Either AWS_BEARER_TOKEN_BEDROCK or both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required when using AWS Bedrock.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("should fail when AWS_SECRET_ACCESS_KEY is missing", () => {
|
test("should fail when only AWS_ACCESS_KEY_ID is provided without bearer token", () => {
|
||||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
process.env.AWS_REGION = "us-east-1";
|
process.env.AWS_REGION = "us-east-1";
|
||||||
process.env.AWS_ACCESS_KEY_ID = "test-access-key";
|
process.env.AWS_ACCESS_KEY_ID = "test-access-key";
|
||||||
|
|
||||||
expect(() => validateEnvironmentVariables()).toThrow(
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
"AWS_SECRET_ACCESS_KEY is required when using AWS Bedrock.",
|
"Either AWS_BEARER_TOKEN_BEDROCK or both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required when using AWS Bedrock.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("should report all missing Bedrock variables", () => {
|
test("should pass when AWS_BEARER_TOKEN_BEDROCK is provided instead of access keys", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
|
process.env.AWS_REGION = "us-east-1";
|
||||||
|
process.env.AWS_BEARER_TOKEN_BEDROCK = "test-bearer-token";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should pass when both bearer token and access keys are provided", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
|
process.env.AWS_REGION = "us-east-1";
|
||||||
|
process.env.AWS_BEARER_TOKEN_BEDROCK = "test-bearer-token";
|
||||||
|
process.env.AWS_ACCESS_KEY_ID = "test-access-key";
|
||||||
|
process.env.AWS_SECRET_ACCESS_KEY = "test-secret-key";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should fail when no authentication method is provided", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
|
process.env.AWS_REGION = "us-east-1";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
|
"Either AWS_BEARER_TOKEN_BEDROCK or both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required when using AWS Bedrock.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should report missing region and authentication", () => {
|
||||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
|
|
||||||
expect(() => validateEnvironmentVariables()).toThrow(
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
/AWS_REGION is required when using AWS Bedrock.*AWS_ACCESS_KEY_ID is required when using AWS Bedrock.*AWS_SECRET_ACCESS_KEY is required when using AWS Bedrock/s,
|
/AWS_REGION is required when using AWS Bedrock.*Either AWS_BEARER_TOKEN_BEDROCK or both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required when using AWS Bedrock/s,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -167,6 +198,56 @@ describe("validateEnvironmentVariables", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("Microsoft Foundry", () => {
|
||||||
|
test("should pass when ANTHROPIC_FOUNDRY_RESOURCE is provided", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_RESOURCE = "test-resource";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should pass when ANTHROPIC_FOUNDRY_BASE_URL is provided", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_BASE_URL =
|
||||||
|
"https://test-resource.services.ai.azure.com";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should pass when both resource and base URL are provided", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_RESOURCE = "test-resource";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_BASE_URL =
|
||||||
|
"https://custom.services.ai.azure.com";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should construct Foundry base URL from resource name when ANTHROPIC_FOUNDRY_BASE_URL is not provided", () => {
|
||||||
|
// This test verifies our action.yml change, which constructs:
|
||||||
|
// ANTHROPIC_FOUNDRY_BASE_URL: ${{ env.ANTHROPIC_FOUNDRY_BASE_URL || (env.ANTHROPIC_FOUNDRY_RESOURCE && format('https://{0}.services.ai.azure.com', env.ANTHROPIC_FOUNDRY_RESOURCE)) }}
|
||||||
|
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_RESOURCE = "my-foundry-resource";
|
||||||
|
// ANTHROPIC_FOUNDRY_BASE_URL is intentionally not set
|
||||||
|
|
||||||
|
// The actual URL construction happens in the composite action in action.yml
|
||||||
|
// This test is a placeholder to document the behavior
|
||||||
|
expect(() => validateEnvironmentVariables()).not.toThrow();
|
||||||
|
|
||||||
|
// In the actual action, ANTHROPIC_FOUNDRY_BASE_URL would be:
|
||||||
|
// https://my-foundry-resource.services.ai.azure.com
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should fail when neither ANTHROPIC_FOUNDRY_RESOURCE nor ANTHROPIC_FOUNDRY_BASE_URL is provided", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
|
"Either ANTHROPIC_FOUNDRY_RESOURCE or ANTHROPIC_FOUNDRY_BASE_URL is required when using Microsoft Foundry.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("Multiple providers", () => {
|
describe("Multiple providers", () => {
|
||||||
test("should fail when both Bedrock and Vertex are enabled", () => {
|
test("should fail when both Bedrock and Vertex are enabled", () => {
|
||||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
@@ -179,7 +260,51 @@ describe("validateEnvironmentVariables", () => {
|
|||||||
process.env.CLOUD_ML_REGION = "us-central1";
|
process.env.CLOUD_ML_REGION = "us-central1";
|
||||||
|
|
||||||
expect(() => validateEnvironmentVariables()).toThrow(
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
"Cannot use both Bedrock and Vertex AI simultaneously. Please set only one provider.",
|
"Cannot use multiple providers simultaneously. Please set only one of: CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should fail when both Bedrock and Foundry are enabled", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
// Provide all required vars to isolate the mutual exclusion error
|
||||||
|
process.env.AWS_REGION = "us-east-1";
|
||||||
|
process.env.AWS_ACCESS_KEY_ID = "test-access-key";
|
||||||
|
process.env.AWS_SECRET_ACCESS_KEY = "test-secret-key";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_RESOURCE = "test-resource";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
|
"Cannot use multiple providers simultaneously. Please set only one of: CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should fail when both Vertex and Foundry are enabled", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_VERTEX = "1";
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
// Provide all required vars to isolate the mutual exclusion error
|
||||||
|
process.env.ANTHROPIC_VERTEX_PROJECT_ID = "test-project";
|
||||||
|
process.env.CLOUD_ML_REGION = "us-central1";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_RESOURCE = "test-resource";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
|
"Cannot use multiple providers simultaneously. Please set only one of: CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should fail when all three providers are enabled", () => {
|
||||||
|
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||||
|
process.env.CLAUDE_CODE_USE_VERTEX = "1";
|
||||||
|
process.env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
||||||
|
// Provide all required vars to isolate the mutual exclusion error
|
||||||
|
process.env.AWS_REGION = "us-east-1";
|
||||||
|
process.env.AWS_ACCESS_KEY_ID = "test-access-key";
|
||||||
|
process.env.AWS_SECRET_ACCESS_KEY = "test-secret-key";
|
||||||
|
process.env.ANTHROPIC_VERTEX_PROJECT_ID = "test-project";
|
||||||
|
process.env.CLOUD_ML_REGION = "us-central1";
|
||||||
|
process.env.ANTHROPIC_FOUNDRY_RESOURCE = "test-resource";
|
||||||
|
|
||||||
|
expect(() => validateEnvironmentVariables()).toThrow(
|
||||||
|
"Cannot use multiple providers simultaneously. Please set only one of: CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -204,10 +329,7 @@ describe("validateEnvironmentVariables", () => {
|
|||||||
" - AWS_REGION is required when using AWS Bedrock.",
|
" - AWS_REGION is required when using AWS Bedrock.",
|
||||||
);
|
);
|
||||||
expect(error!.message).toContain(
|
expect(error!.message).toContain(
|
||||||
" - AWS_ACCESS_KEY_ID is required when using AWS Bedrock.",
|
" - Either AWS_BEARER_TOKEN_BEDROCK or both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required when using AWS Bedrock.",
|
||||||
);
|
|
||||||
expect(error!.message).toContain(
|
|
||||||
" - AWS_SECRET_ACCESS_KEY is required when using AWS Bedrock.",
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
33
bun.lock
33
bun.lock
@@ -6,6 +6,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@actions/core": "^1.10.1",
|
"@actions/core": "^1.10.1",
|
||||||
"@actions/github": "^6.0.1",
|
"@actions/github": "^6.0.1",
|
||||||
|
"@anthropic-ai/claude-agent-sdk": "^0.1.52",
|
||||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||||
"@octokit/graphql": "^8.2.2",
|
"@octokit/graphql": "^8.2.2",
|
||||||
"@octokit/rest": "^21.1.1",
|
"@octokit/rest": "^21.1.1",
|
||||||
@@ -35,8 +36,40 @@
|
|||||||
|
|
||||||
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||||
|
|
||||||
|
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.1.52", "", { "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.33.5", "@img/sharp-darwin-x64": "^0.33.5", "@img/sharp-linux-arm": "^0.33.5", "@img/sharp-linux-arm64": "^0.33.5", "@img/sharp-linux-x64": "^0.33.5", "@img/sharp-linuxmusl-arm64": "^0.33.5", "@img/sharp-linuxmusl-x64": "^0.33.5", "@img/sharp-win32-x64": "^0.33.5" }, "peerDependencies": { "zod": "^3.24.1" } }, "sha512-yF8N05+9NRbqYA/h39jQ726HTQFrdXXp7pEfDNKIJ2c4FdWvEjxBA/8ciZIebN6/PyvGDcbEp3yq2Co4rNpg6A=="],
|
||||||
|
|
||||||
"@fastify/busboy": ["@fastify/busboy@2.1.1", "", {}, "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA=="],
|
"@fastify/busboy": ["@fastify/busboy@2.1.1", "", {}, "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA=="],
|
||||||
|
|
||||||
|
"@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.0.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ=="],
|
||||||
|
|
||||||
|
"@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.0.4" }, "os": "darwin", "cpu": "x64" }, "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.0.5", "", { "os": "linux", "cpu": "arm" }, "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA=="],
|
||||||
|
|
||||||
|
"@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw=="],
|
||||||
|
|
||||||
|
"@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.0.5" }, "os": "linux", "cpu": "arm" }, "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ=="],
|
||||||
|
|
||||||
|
"@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.0.4" }, "os": "linux", "cpu": "arm64" }, "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA=="],
|
||||||
|
|
||||||
|
"@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.0.4" }, "os": "linux", "cpu": "x64" }, "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA=="],
|
||||||
|
|
||||||
|
"@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" }, "os": "linux", "cpu": "arm64" }, "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g=="],
|
||||||
|
|
||||||
|
"@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.33.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.0.4" }, "os": "linux", "cpu": "x64" }, "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw=="],
|
||||||
|
|
||||||
|
"@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.33.5", "", { "os": "win32", "cpu": "x64" }, "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg=="],
|
||||||
|
|
||||||
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.16.0", "", { "dependencies": { "ajv": "^6.12.6", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.0.1", "express-rate-limit": "^7.5.0", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.24.1" } }, "sha512-8ofX7gkZcLj9H9rSd50mCgm3SSF8C7XoclxJuLoV0Cz3rEQ1tv9MZRYYvJtm9n1BiEQQMzSmE/w2AEkNacLYfg=="],
|
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.16.0", "", { "dependencies": { "ajv": "^6.12.6", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.0.1", "express-rate-limit": "^7.5.0", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.24.1" } }, "sha512-8ofX7gkZcLj9H9rSd50mCgm3SSF8C7XoclxJuLoV0Cz3rEQ1tv9MZRYYvJtm9n1BiEQQMzSmE/w2AEkNacLYfg=="],
|
||||||
|
|
||||||
"@octokit/auth-token": ["@octokit/auth-token@4.0.0", "", {}, "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA=="],
|
"@octokit/auth-token": ["@octokit/auth-token@4.0.0", "", {}, "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA=="],
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
# Cloud Providers
|
# Cloud Providers
|
||||||
|
|
||||||
You can authenticate with Claude using any of these three methods:
|
You can authenticate with Claude using any of these four methods:
|
||||||
|
|
||||||
1. Direct Anthropic API (default)
|
1. Direct Anthropic API (default)
|
||||||
2. Amazon Bedrock with OIDC authentication
|
2. Amazon Bedrock with OIDC authentication
|
||||||
3. Google Vertex AI with OIDC authentication
|
3. Google Vertex AI with OIDC authentication
|
||||||
|
4. Microsoft Foundry with OIDC authentication
|
||||||
|
|
||||||
For detailed setup instructions for AWS Bedrock and Google Vertex AI, see the [official documentation](https://docs.anthropic.com/en/docs/claude-code/github-actions#using-with-aws-bedrock-%26-google-vertex-ai).
|
For detailed setup instructions for AWS Bedrock and Google Vertex AI, see the [official documentation](https://docs.anthropic.com/en/docs/claude-code/github-actions#using-with-aws-bedrock-%26-google-vertex-ai).
|
||||||
|
|
||||||
**Note**:
|
**Note**:
|
||||||
|
|
||||||
- Bedrock and Vertex use OIDC authentication exclusively
|
- Bedrock, Vertex, and Microsoft Foundry use OIDC authentication exclusively
|
||||||
- AWS Bedrock automatically uses cross-region inference profiles for certain models
|
- AWS Bedrock automatically uses cross-region inference profiles for certain models
|
||||||
- For cross-region inference profile models, you need to request and be granted access to the Claude models in all regions that the inference profile uses
|
- For cross-region inference profile models, you need to request and be granted access to the Claude models in all regions that the inference profile uses
|
||||||
|
|
||||||
@@ -40,11 +41,19 @@ Use provider-specific model names based on your chosen provider:
|
|||||||
claude_args: |
|
claude_args: |
|
||||||
--model claude-4-0-sonnet@20250805
|
--model claude-4-0-sonnet@20250805
|
||||||
# ... other inputs
|
# ... other inputs
|
||||||
|
|
||||||
|
# For Microsoft Foundry with OIDC
|
||||||
|
- uses: anthropics/claude-code-action@v1
|
||||||
|
with:
|
||||||
|
use_foundry: "true"
|
||||||
|
claude_args: |
|
||||||
|
--model claude-sonnet-4-5
|
||||||
|
# ... other inputs
|
||||||
```
|
```
|
||||||
|
|
||||||
## OIDC Authentication for Bedrock and Vertex
|
## OIDC Authentication for Cloud Providers
|
||||||
|
|
||||||
Both AWS Bedrock and GCP Vertex AI require OIDC authentication.
|
AWS Bedrock, GCP Vertex AI, and Microsoft Foundry all support OIDC authentication.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# For AWS Bedrock with OIDC
|
# For AWS Bedrock with OIDC
|
||||||
@@ -97,3 +106,36 @@ Both AWS Bedrock and GCP Vertex AI require OIDC authentication.
|
|||||||
permissions:
|
permissions:
|
||||||
id-token: write # Required for OIDC
|
id-token: write # Required for OIDC
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# For Microsoft Foundry with OIDC
|
||||||
|
- name: Authenticate to Azure
|
||||||
|
uses: azure/login@v2
|
||||||
|
with:
|
||||||
|
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
|
||||||
|
- name: Generate GitHub App token
|
||||||
|
id: app-token
|
||||||
|
uses: actions/create-github-app-token@v2
|
||||||
|
with:
|
||||||
|
app-id: ${{ secrets.APP_ID }}
|
||||||
|
private-key: ${{ secrets.APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
|
- uses: anthropics/claude-code-action@v1
|
||||||
|
with:
|
||||||
|
use_foundry: "true"
|
||||||
|
claude_args: |
|
||||||
|
--model claude-sonnet-4-5
|
||||||
|
# ... other inputs
|
||||||
|
env:
|
||||||
|
ANTHROPIC_FOUNDRY_BASE_URL: https://my-resource.services.ai.azure.com
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
id-token: write # Required for OIDC
|
||||||
|
```
|
||||||
|
|
||||||
|
## Microsoft Foundry Setup
|
||||||
|
|
||||||
|
For detailed setup instructions for Microsoft Foundry, see the [official documentation](https://docs.anthropic.com/en/docs/claude-code/microsoft-foundry).
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ To allow Claude to view workflow run results, job logs, and CI status:
|
|||||||
2. **Configure the action with additional permissions**:
|
2. **Configure the action with additional permissions**:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- uses: anthropics/claude-code-action@beta
|
- uses: anthropics/claude-code-action@v1
|
||||||
with:
|
with:
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
additional_permissions: |
|
additional_permissions: |
|
||||||
@@ -162,7 +162,7 @@ jobs:
|
|||||||
claude-ci-helper:
|
claude-ci-helper:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: anthropics/claude-code-action@beta
|
- uses: anthropics/claude-code-action@v1
|
||||||
with:
|
with:
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
additional_permissions: |
|
additional_permissions: |
|
||||||
|
|||||||
@@ -61,68 +61,3 @@ For specialized use cases, you can fine-tune behavior using `claude_args`:
|
|||||||
--system-prompt "You are a code review specialist"
|
--system-prompt "You are a code review specialist"
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Network Restrictions
|
|
||||||
|
|
||||||
For enhanced security, you can restrict Claude's network access to specific domains only. This feature is particularly useful for:
|
|
||||||
|
|
||||||
- Enterprise environments with strict security policies
|
|
||||||
- Preventing access to external services
|
|
||||||
- Limiting Claude to only your internal APIs and services
|
|
||||||
|
|
||||||
When `experimental_allowed_domains` is set, Claude can only access the domains you explicitly list. You'll need to include the appropriate provider domains based on your authentication method.
|
|
||||||
|
|
||||||
### Provider-Specific Examples
|
|
||||||
|
|
||||||
#### If using Anthropic API or subscription
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
- uses: anthropics/claude-code-action@v1
|
|
||||||
with:
|
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
|
||||||
# Or: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
|
||||||
experimental_allowed_domains: |
|
|
||||||
.anthropic.com
|
|
||||||
```
|
|
||||||
|
|
||||||
#### If using AWS Bedrock
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
- uses: anthropics/claude-code-action@v1
|
|
||||||
with:
|
|
||||||
use_bedrock: "true"
|
|
||||||
experimental_allowed_domains: |
|
|
||||||
bedrock.*.amazonaws.com
|
|
||||||
bedrock-runtime.*.amazonaws.com
|
|
||||||
```
|
|
||||||
|
|
||||||
#### If using Google Vertex AI
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
- uses: anthropics/claude-code-action@v1
|
|
||||||
with:
|
|
||||||
use_vertex: "true"
|
|
||||||
experimental_allowed_domains: |
|
|
||||||
*.googleapis.com
|
|
||||||
vertexai.googleapis.com
|
|
||||||
```
|
|
||||||
|
|
||||||
### Common GitHub Domains
|
|
||||||
|
|
||||||
In addition to your provider domains, you may need to include GitHub-related domains. For GitHub.com users, common domains include:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
- uses: anthropics/claude-code-action@v1
|
|
||||||
with:
|
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
|
||||||
experimental_allowed_domains: |
|
|
||||||
.anthropic.com # For Anthropic API
|
|
||||||
.github.com
|
|
||||||
.githubusercontent.com
|
|
||||||
ghcr.io
|
|
||||||
.blob.core.windows.net
|
|
||||||
```
|
|
||||||
|
|
||||||
For GitHub Enterprise users, replace the GitHub.com domains above with your enterprise domains (e.g., `.github.company.com`, `packages.company.com`, etc.).
|
|
||||||
|
|
||||||
To determine which domains your workflow needs, you can temporarily run without restrictions and monitor the network requests, or check your GitHub Enterprise configuration for the specific services you use.
|
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ The following permissions are requested but not yet actively used. These will en
|
|||||||
|
|
||||||
## Commit Signing
|
## Commit Signing
|
||||||
|
|
||||||
All commits made by Claude through this action are automatically signed with commit signatures. This ensures the authenticity and integrity of commits, providing a verifiable trail of changes made by the action.
|
Commits made by Claude through this action are no longer automatically signed with commit signatures. To enable commit signing set `use_commit_signing: True` in the workflow(s). This ensures the authenticity and integrity of commits, providing a verifiable trail of changes made by the action.
|
||||||
|
|
||||||
## ⚠️ Authentication Protection
|
## ⚠️ Authentication Protection
|
||||||
|
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ If you prefer to configure the app manually or need custom permissions:
|
|||||||
private-key: ${{ secrets.APP_PRIVATE_KEY }}
|
private-key: ${{ secrets.APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
# Use Claude with your custom app's token
|
# Use Claude with your custom app's token
|
||||||
- uses: anthropics/claude-code-action@beta
|
- uses: anthropics/claude-code-action@v1
|
||||||
with:
|
with:
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
github_token: ${{ steps.app-token.outputs.token }}
|
github_token: ${{ steps.app-token.outputs.token }}
|
||||||
|
|||||||
@@ -70,7 +70,6 @@ jobs:
|
|||||||
| `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` |
|
| `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` |
|
||||||
| `settings` | Claude Code settings as JSON string or path to settings JSON file | No | "" |
|
| `settings` | Claude Code settings as JSON string or path to settings JSON file | No | "" |
|
||||||
| `additional_permissions` | Additional permissions to enable. Currently supports 'actions: read' for viewing workflow results | No | "" |
|
| `additional_permissions` | Additional permissions to enable. Currently supports 'actions: read' for viewing workflow results | No | "" |
|
||||||
| `experimental_allowed_domains` | Restrict network access to these domains only (newline-separated). | No | "" |
|
|
||||||
| `use_commit_signing` | Enable commit signing using GitHub's commit signature verification. When false, Claude uses standard git commands | No | `false` |
|
| `use_commit_signing` | Enable commit signing using GitHub's commit signature verification. When false, Claude uses standard git commands | No | `false` |
|
||||||
| `bot_id` | GitHub user ID to use for git operations (defaults to Claude's bot ID) | No | `41898282` |
|
| `bot_id` | GitHub user ID to use for git operations (defaults to Claude's bot ID) | No | `41898282` |
|
||||||
| `bot_name` | GitHub username to use for git operations (defaults to Claude's bot name) | No | `claude[bot]` |
|
| `bot_name` | GitHub username to use for git operations (defaults to Claude's bot name) | No | `claude[bot]` |
|
||||||
@@ -185,6 +184,74 @@ For a comprehensive guide on migrating from v0.x to v1.0, including step-by-step
|
|||||||
Focus on the changed files in this PR.
|
Focus on the changed files in this PR.
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Structured Outputs
|
||||||
|
|
||||||
|
Get validated JSON results from Claude that automatically become GitHub Action outputs. This enables building complex automation workflows where Claude analyzes data and subsequent steps use the results.
|
||||||
|
|
||||||
|
### Basic Example
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Detect flaky tests
|
||||||
|
id: analyze
|
||||||
|
uses: anthropics/claude-code-action@v1
|
||||||
|
with:
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
prompt: |
|
||||||
|
Check the CI logs and determine if this is a flaky test.
|
||||||
|
Return: is_flaky (boolean), confidence (0-1), summary (string)
|
||||||
|
claude_args: |
|
||||||
|
--json-schema '{"type":"object","properties":{"is_flaky":{"type":"boolean"},"confidence":{"type":"number"},"summary":{"type":"string"}},"required":["is_flaky"]}'
|
||||||
|
|
||||||
|
- name: Retry if flaky
|
||||||
|
if: fromJSON(steps.analyze.outputs.structured_output).is_flaky == true
|
||||||
|
run: gh workflow run CI
|
||||||
|
```
|
||||||
|
|
||||||
|
### How It Works
|
||||||
|
|
||||||
|
1. **Define Schema**: Provide a JSON schema via `--json-schema` flag in `claude_args`
|
||||||
|
2. **Claude Executes**: Claude uses tools to complete your task
|
||||||
|
3. **Validated Output**: Result is validated against your schema
|
||||||
|
4. **JSON Output**: All fields are returned in a single `structured_output` JSON string
|
||||||
|
|
||||||
|
### Accessing Structured Outputs
|
||||||
|
|
||||||
|
All structured output fields are available in the `structured_output` output as a JSON string:
|
||||||
|
|
||||||
|
**In GitHub Actions expressions:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
if: fromJSON(steps.analyze.outputs.structured_output).is_flaky == true
|
||||||
|
run: |
|
||||||
|
CONFIDENCE=${{ fromJSON(steps.analyze.outputs.structured_output).confidence }}
|
||||||
|
```
|
||||||
|
|
||||||
|
**In bash with jq:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Process results
|
||||||
|
run: |
|
||||||
|
OUTPUT='${{ steps.analyze.outputs.structured_output }}'
|
||||||
|
IS_FLAKY=$(echo "$OUTPUT" | jq -r '.is_flaky')
|
||||||
|
SUMMARY=$(echo "$OUTPUT" | jq -r '.summary')
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: Due to GitHub Actions limitations, composite actions cannot expose dynamic outputs. All fields are bundled in the single `structured_output` JSON string.
|
||||||
|
|
||||||
|
### Complete Example
|
||||||
|
|
||||||
|
See `examples/test-failure-analysis.yml` for a working example that:
|
||||||
|
|
||||||
|
- Detects flaky test failures
|
||||||
|
- Uses confidence thresholds in conditionals
|
||||||
|
- Auto-retries workflows
|
||||||
|
- Comments on PRs
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
For complete details on JSON Schema syntax and Agent SDK structured outputs:
|
||||||
|
https://docs.claude.com/en/docs/agent-sdk/structured-outputs
|
||||||
|
|
||||||
## Ways to Tag @claude
|
## Ways to Tag @claude
|
||||||
|
|
||||||
These examples show how to interact with Claude using comments in PRs and issues. By default, Claude will be triggered anytime you mention `@claude`, but you can customize the exact trigger phrase using the `trigger_phrase` input in the workflow.
|
These examples show how to interact with Claude using comments in PRs and issues. By default, Claude will be triggered anytime you mention `@claude`, but you can customize the exact trigger phrase using the `trigger_phrase` input in the workflow.
|
||||||
|
|||||||
114
examples/test-failure-analysis.yml
Normal file
114
examples/test-failure-analysis.yml
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
name: Auto-Retry Flaky Tests
|
||||||
|
|
||||||
|
# This example demonstrates using structured outputs to detect flaky test failures
|
||||||
|
# and automatically retry them, reducing noise from intermittent failures.
|
||||||
|
#
|
||||||
|
# Use case: When CI fails, automatically determine if it's likely flaky and retry if so.
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["CI"]
|
||||||
|
types: [completed]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
actions: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
detect-flaky:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Detect flaky test failures
|
||||||
|
id: detect
|
||||||
|
uses: anthropics/claude-code-action@main
|
||||||
|
with:
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
prompt: |
|
||||||
|
The CI workflow failed: ${{ github.event.workflow_run.html_url }}
|
||||||
|
|
||||||
|
Check the logs: gh run view ${{ github.event.workflow_run.id }} --log-failed
|
||||||
|
|
||||||
|
Determine if this looks like a flaky test failure by checking for:
|
||||||
|
- Timeout errors
|
||||||
|
- Race conditions
|
||||||
|
- Network errors
|
||||||
|
- "Expected X but got Y" intermittent failures
|
||||||
|
- Tests that passed in previous commits
|
||||||
|
|
||||||
|
Return:
|
||||||
|
- is_flaky: true if likely flaky, false if real bug
|
||||||
|
- confidence: number 0-1 indicating confidence level
|
||||||
|
- summary: brief one-sentence explanation
|
||||||
|
claude_args: |
|
||||||
|
--json-schema '{"type":"object","properties":{"is_flaky":{"type":"boolean","description":"Whether this appears to be a flaky test failure"},"confidence":{"type":"number","minimum":0,"maximum":1,"description":"Confidence level in the determination"},"summary":{"type":"string","description":"One-sentence explanation of the failure"}},"required":["is_flaky","confidence","summary"]}'
|
||||||
|
|
||||||
|
# Auto-retry only if flaky AND high confidence (>= 0.7)
|
||||||
|
- name: Retry flaky tests
|
||||||
|
if: |
|
||||||
|
fromJSON(steps.detect.outputs.structured_output).is_flaky == true &&
|
||||||
|
fromJSON(steps.detect.outputs.structured_output).confidence >= 0.7
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
OUTPUT='${{ steps.detect.outputs.structured_output }}'
|
||||||
|
CONFIDENCE=$(echo "$OUTPUT" | jq -r '.confidence')
|
||||||
|
SUMMARY=$(echo "$OUTPUT" | jq -r '.summary')
|
||||||
|
|
||||||
|
echo "🔄 Flaky test detected (confidence: $CONFIDENCE)"
|
||||||
|
echo "Summary: $SUMMARY"
|
||||||
|
echo ""
|
||||||
|
echo "Triggering automatic retry..."
|
||||||
|
|
||||||
|
gh workflow run "${{ github.event.workflow_run.name }}" \
|
||||||
|
--ref "${{ github.event.workflow_run.head_branch }}"
|
||||||
|
|
||||||
|
# Low confidence flaky detection - skip retry
|
||||||
|
- name: Low confidence detection
|
||||||
|
if: |
|
||||||
|
fromJSON(steps.detect.outputs.structured_output).is_flaky == true &&
|
||||||
|
fromJSON(steps.detect.outputs.structured_output).confidence < 0.7
|
||||||
|
run: |
|
||||||
|
OUTPUT='${{ steps.detect.outputs.structured_output }}'
|
||||||
|
CONFIDENCE=$(echo "$OUTPUT" | jq -r '.confidence')
|
||||||
|
|
||||||
|
echo "⚠️ Possible flaky test but confidence too low ($CONFIDENCE)"
|
||||||
|
echo "Not retrying automatically - manual review recommended"
|
||||||
|
|
||||||
|
# Comment on PR if this was a PR build
|
||||||
|
- name: Comment on PR
|
||||||
|
if: github.event.workflow_run.event == 'pull_request'
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
OUTPUT='${{ steps.detect.outputs.structured_output }}'
|
||||||
|
IS_FLAKY=$(echo "$OUTPUT" | jq -r '.is_flaky')
|
||||||
|
CONFIDENCE=$(echo "$OUTPUT" | jq -r '.confidence')
|
||||||
|
SUMMARY=$(echo "$OUTPUT" | jq -r '.summary')
|
||||||
|
|
||||||
|
pr_number=$(gh pr list --head "${{ github.event.workflow_run.head_branch }}" --json number --jq '.[0].number')
|
||||||
|
|
||||||
|
if [ -n "$pr_number" ]; then
|
||||||
|
if [ "$IS_FLAKY" = "true" ]; then
|
||||||
|
TITLE="🔄 Flaky Test Detected"
|
||||||
|
ACTION="✅ Automatically retrying the workflow"
|
||||||
|
else
|
||||||
|
TITLE="❌ Test Failure"
|
||||||
|
ACTION="⚠️ This appears to be a real bug - manual intervention needed"
|
||||||
|
fi
|
||||||
|
|
||||||
|
gh pr comment "$pr_number" --body "$(cat <<EOF
|
||||||
|
## $TITLE
|
||||||
|
|
||||||
|
**Analysis**: $SUMMARY
|
||||||
|
**Confidence**: $CONFIDENCE
|
||||||
|
|
||||||
|
$ACTION
|
||||||
|
|
||||||
|
[View workflow run](${{ github.event.workflow_run.html_url }})
|
||||||
|
EOF
|
||||||
|
)"
|
||||||
|
fi
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@actions/core": "^1.10.1",
|
"@actions/core": "^1.10.1",
|
||||||
"@actions/github": "^6.0.1",
|
"@actions/github": "^6.0.1",
|
||||||
|
"@anthropic-ai/claude-agent-sdk": "^0.1.52",
|
||||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||||
"@octokit/graphql": "^8.2.2",
|
"@octokit/graphql": "^8.2.2",
|
||||||
"@octokit/rest": "^21.1.1",
|
"@octokit/rest": "^21.1.1",
|
||||||
|
|||||||
@@ -1,123 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# Setup Network Restrictions with Squid Proxy
|
|
||||||
# This script sets up a Squid proxy to restrict network access to whitelisted domains only.
|
|
||||||
|
|
||||||
set -e
|
|
||||||
|
|
||||||
# Check if experimental_allowed_domains is provided
|
|
||||||
if [ -z "$EXPERIMENTAL_ALLOWED_DOMAINS" ]; then
|
|
||||||
echo "ERROR: EXPERIMENTAL_ALLOWED_DOMAINS environment variable is required"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Check required environment variables
|
|
||||||
if [ -z "$RUNNER_TEMP" ]; then
|
|
||||||
echo "ERROR: RUNNER_TEMP environment variable is required"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -z "$GITHUB_ENV" ]; then
|
|
||||||
echo "ERROR: GITHUB_ENV environment variable is required"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Setting up network restrictions with Squid proxy..."
|
|
||||||
|
|
||||||
SQUID_START_TIME=$(date +%s.%N)
|
|
||||||
|
|
||||||
# Create whitelist file
|
|
||||||
echo "$EXPERIMENTAL_ALLOWED_DOMAINS" > $RUNNER_TEMP/whitelist.txt
|
|
||||||
|
|
||||||
# Ensure each domain has proper format
|
|
||||||
# If domain doesn't start with a dot and isn't an IP, add the dot for subdomain matching
|
|
||||||
mv $RUNNER_TEMP/whitelist.txt $RUNNER_TEMP/whitelist.txt.orig
|
|
||||||
while IFS= read -r domain; do
|
|
||||||
if [ -n "$domain" ]; then
|
|
||||||
# Trim whitespace
|
|
||||||
domain=$(echo "$domain" | xargs)
|
|
||||||
# If it's not empty and doesn't start with a dot, add one
|
|
||||||
if [[ "$domain" != .* ]] && [[ ! "$domain" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
|
||||||
echo ".$domain" >> $RUNNER_TEMP/whitelist.txt
|
|
||||||
else
|
|
||||||
echo "$domain" >> $RUNNER_TEMP/whitelist.txt
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
done < $RUNNER_TEMP/whitelist.txt.orig
|
|
||||||
|
|
||||||
# Create Squid config with whitelist
|
|
||||||
echo "http_port 3128" > $RUNNER_TEMP/squid.conf
|
|
||||||
echo "" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "# Define ACLs" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "acl whitelist dstdomain \"/etc/squid/whitelist.txt\"" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "acl localnet src 127.0.0.1/32" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "acl localnet src 172.17.0.0/16" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "acl SSL_ports port 443" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "acl Safe_ports port 80" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "acl Safe_ports port 443" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "acl CONNECT method CONNECT" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "# Deny requests to certain unsafe ports" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "http_access deny !Safe_ports" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "# Only allow CONNECT to SSL ports" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "http_access deny CONNECT !SSL_ports" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "# Allow localhost" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "http_access allow localhost" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "# Allow localnet access to whitelisted domains" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "http_access allow localnet whitelist" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "# Deny everything else" >> $RUNNER_TEMP/squid.conf
|
|
||||||
echo "http_access deny all" >> $RUNNER_TEMP/squid.conf
|
|
||||||
|
|
||||||
echo "Starting Squid proxy..."
|
|
||||||
# First, remove any existing container
|
|
||||||
sudo docker rm -f squid-proxy 2>/dev/null || true
|
|
||||||
|
|
||||||
# Ensure whitelist file is not empty (Squid fails with empty files)
|
|
||||||
if [ ! -s "$RUNNER_TEMP/whitelist.txt" ]; then
|
|
||||||
echo "WARNING: Whitelist file is empty, adding a dummy entry"
|
|
||||||
echo ".example.com" >> $RUNNER_TEMP/whitelist.txt
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Use sudo to prevent Claude from stopping the container
|
|
||||||
CONTAINER_ID=$(sudo docker run -d \
|
|
||||||
--name squid-proxy \
|
|
||||||
-p 127.0.0.1:3128:3128 \
|
|
||||||
-v $RUNNER_TEMP/squid.conf:/etc/squid/squid.conf:ro \
|
|
||||||
-v $RUNNER_TEMP/whitelist.txt:/etc/squid/whitelist.txt:ro \
|
|
||||||
ubuntu/squid:latest 2>&1) || {
|
|
||||||
echo "ERROR: Failed to start Squid container"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# Wait for proxy to be ready (usually < 1 second)
|
|
||||||
READY=false
|
|
||||||
for i in {1..30}; do
|
|
||||||
if nc -z 127.0.0.1 3128 2>/dev/null; then
|
|
||||||
TOTAL_TIME=$(echo "scale=3; $(date +%s.%N) - $SQUID_START_TIME" | bc)
|
|
||||||
echo "Squid proxy ready in ${TOTAL_TIME}s"
|
|
||||||
READY=true
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 0.1
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ "$READY" != "true" ]; then
|
|
||||||
echo "ERROR: Squid proxy failed to start within 3 seconds"
|
|
||||||
echo "Container logs:"
|
|
||||||
sudo docker logs squid-proxy 2>&1 || true
|
|
||||||
echo "Container status:"
|
|
||||||
sudo docker ps -a | grep squid-proxy || true
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Set proxy environment variables
|
|
||||||
echo "http_proxy=http://127.0.0.1:3128" >> $GITHUB_ENV
|
|
||||||
echo "https_proxy=http://127.0.0.1:3128" >> $GITHUB_ENV
|
|
||||||
echo "HTTP_PROXY=http://127.0.0.1:3128" >> $GITHUB_ENV
|
|
||||||
echo "HTTPS_PROXY=http://127.0.0.1:3128" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
echo "Network restrictions setup completed successfully"
|
|
||||||
@@ -192,11 +192,6 @@ export function prepareContext(
|
|||||||
if (!isPR) {
|
if (!isPR) {
|
||||||
throw new Error("IS_PR must be true for pull_request_review event");
|
throw new Error("IS_PR must be true for pull_request_review event");
|
||||||
}
|
}
|
||||||
if (!commentBody) {
|
|
||||||
throw new Error(
|
|
||||||
"COMMENT_BODY is required for pull_request_review event",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
eventData = {
|
eventData = {
|
||||||
eventName: "pull_request_review",
|
eventName: "pull_request_review",
|
||||||
isPR: true,
|
isPR: true,
|
||||||
@@ -464,6 +459,123 @@ export function generatePrompt(
|
|||||||
return mode.generatePrompt(context, githubData, useCommitSigning);
|
return mode.generatePrompt(context, githubData, useCommitSigning);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a simplified prompt for tag mode (opt-in via USE_SIMPLE_PROMPT env var)
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
function generateSimplePrompt(
|
||||||
|
context: PreparedContext,
|
||||||
|
githubData: FetchDataResult,
|
||||||
|
useCommitSigning: boolean = false,
|
||||||
|
): string {
|
||||||
|
const {
|
||||||
|
contextData,
|
||||||
|
comments,
|
||||||
|
changedFilesWithSHA,
|
||||||
|
reviewData,
|
||||||
|
imageUrlMap,
|
||||||
|
} = githubData;
|
||||||
|
const { eventData } = context;
|
||||||
|
|
||||||
|
const { triggerContext } = getEventTypeAndContext(context);
|
||||||
|
|
||||||
|
const formattedContext = formatContext(contextData, eventData.isPR);
|
||||||
|
const formattedComments = formatComments(comments, imageUrlMap);
|
||||||
|
const formattedReviewComments = eventData.isPR
|
||||||
|
? formatReviewComments(reviewData, imageUrlMap)
|
||||||
|
: "";
|
||||||
|
const formattedChangedFiles = eventData.isPR
|
||||||
|
? formatChangedFilesWithSHA(changedFilesWithSHA)
|
||||||
|
: "";
|
||||||
|
|
||||||
|
const hasImages = imageUrlMap && imageUrlMap.size > 0;
|
||||||
|
const imagesInfo = hasImages
|
||||||
|
? `\n\n<images_info>
|
||||||
|
Images from comments have been saved to disk. Paths are in the formatted content above. Use Read tool to view them.
|
||||||
|
</images_info>`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
const formattedBody = contextData?.body
|
||||||
|
? formatBody(contextData.body, imageUrlMap)
|
||||||
|
: "No description provided";
|
||||||
|
|
||||||
|
const entityType = eventData.isPR ? "pull request" : "issue";
|
||||||
|
const jobUrl = `${GITHUB_SERVER_URL}/${context.repository}/actions/runs/${process.env.GITHUB_RUN_ID}`;
|
||||||
|
|
||||||
|
let promptContent = `You were tagged on a GitHub ${entityType} via "${context.triggerPhrase}". Read the request and decide how to help.
|
||||||
|
|
||||||
|
<context>
|
||||||
|
${formattedContext}
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<${eventData.isPR ? "pr" : "issue"}_body>
|
||||||
|
${formattedBody}
|
||||||
|
</${eventData.isPR ? "pr" : "issue"}_body>
|
||||||
|
|
||||||
|
<comments>
|
||||||
|
${formattedComments || "No comments"}
|
||||||
|
</comments>
|
||||||
|
${
|
||||||
|
eventData.isPR
|
||||||
|
? `
|
||||||
|
<review_comments>
|
||||||
|
${formattedReviewComments || "No review comments"}
|
||||||
|
</review_comments>
|
||||||
|
|
||||||
|
<changed_files>
|
||||||
|
${formattedChangedFiles || "No files changed"}
|
||||||
|
</changed_files>`
|
||||||
|
: ""
|
||||||
|
}${imagesInfo}
|
||||||
|
|
||||||
|
<metadata>
|
||||||
|
repository: ${context.repository}
|
||||||
|
${eventData.isPR && eventData.prNumber ? `pr_number: ${eventData.prNumber}` : ""}
|
||||||
|
${!eventData.isPR && eventData.issueNumber ? `issue_number: ${eventData.issueNumber}` : ""}
|
||||||
|
trigger: ${triggerContext}
|
||||||
|
triggered_by: ${context.triggerUsername ?? "Unknown"}
|
||||||
|
claude_comment_id: ${context.claudeCommentId}
|
||||||
|
</metadata>
|
||||||
|
${
|
||||||
|
(eventData.eventName === "issue_comment" ||
|
||||||
|
eventData.eventName === "pull_request_review_comment" ||
|
||||||
|
eventData.eventName === "pull_request_review") &&
|
||||||
|
eventData.commentBody
|
||||||
|
? `
|
||||||
|
<trigger_comment>
|
||||||
|
${sanitizeContent(eventData.commentBody)}
|
||||||
|
</trigger_comment>`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
Your request is in <trigger_comment> above${eventData.eventName === "issues" ? ` (or the ${entityType} body for assigned/labeled events)` : ""}.
|
||||||
|
|
||||||
|
Decide what's being asked:
|
||||||
|
1. **Question or code review** - Answer directly or provide feedback
|
||||||
|
2. **Code change** - Implement the change, commit, and push
|
||||||
|
|
||||||
|
Communication:
|
||||||
|
- Your ONLY visible output is your GitHub comment - update it with progress and results
|
||||||
|
- Use mcp__github_comment__update_claude_comment to update (only "body" param needed)
|
||||||
|
- Use checklist format for tasks: - [ ] incomplete, - [x] complete
|
||||||
|
- Use ### headers (not #)
|
||||||
|
${getCommitInstructions(eventData, githubData, context, useCommitSigning)}
|
||||||
|
${
|
||||||
|
eventData.claudeBranch
|
||||||
|
? `
|
||||||
|
When done with changes, provide a PR link:
|
||||||
|
[Create a PR](${GITHUB_SERVER_URL}/${context.repository}/compare/${eventData.baseBranch}...${eventData.claudeBranch}?quick_pull=1&title=<url-encoded-title>&body=<url-encoded-body>)
|
||||||
|
Use THREE dots (...) between branches. URL-encode all parameters.`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
Always include at the bottom:
|
||||||
|
- Job link: [View job run](${jobUrl})
|
||||||
|
- Follow the repo's CLAUDE.md file for project-specific guidelines`;
|
||||||
|
|
||||||
|
return promptContent;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates the default prompt for tag mode
|
* Generates the default prompt for tag mode
|
||||||
* @internal
|
* @internal
|
||||||
@@ -473,6 +585,10 @@ export function generateDefaultPrompt(
|
|||||||
githubData: FetchDataResult,
|
githubData: FetchDataResult,
|
||||||
useCommitSigning: boolean = false,
|
useCommitSigning: boolean = false,
|
||||||
): string {
|
): string {
|
||||||
|
// Use simplified prompt if opted in
|
||||||
|
if (process.env.USE_SIMPLE_PROMPT === "true") {
|
||||||
|
return generateSimplePrompt(context, githubData, useCommitSigning);
|
||||||
|
}
|
||||||
const {
|
const {
|
||||||
contextData,
|
contextData,
|
||||||
comments,
|
comments,
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ type PullRequestReviewEvent = {
|
|||||||
eventName: "pull_request_review";
|
eventName: "pull_request_review";
|
||||||
isPR: true;
|
isPR: true;
|
||||||
prNumber: string;
|
prNumber: string;
|
||||||
commentBody: string;
|
commentBody?: string; // May be absent for approvals without comments
|
||||||
claudeBranch?: string;
|
claudeBranch?: string;
|
||||||
baseBranch?: string;
|
baseBranch?: string;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ export function collectActionInputsPresence(): void {
|
|||||||
max_turns: "",
|
max_turns: "",
|
||||||
use_sticky_comment: "false",
|
use_sticky_comment: "false",
|
||||||
use_commit_signing: "false",
|
use_commit_signing: "false",
|
||||||
experimental_allowed_domains: "",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const allInputsJson = process.env.ALL_INPUTS;
|
const allInputsJson = process.env.ALL_INPUTS;
|
||||||
|
|||||||
@@ -152,7 +152,7 @@ async function run() {
|
|||||||
|
|
||||||
// Check if action failed and read output file for execution details
|
// Check if action failed and read output file for execution details
|
||||||
let executionDetails: {
|
let executionDetails: {
|
||||||
cost_usd?: number;
|
total_cost_usd?: number;
|
||||||
duration_ms?: number;
|
duration_ms?: number;
|
||||||
duration_api_ms?: number;
|
duration_api_ms?: number;
|
||||||
} | null = null;
|
} | null = null;
|
||||||
@@ -179,11 +179,11 @@ async function run() {
|
|||||||
const lastElement = outputData[outputData.length - 1];
|
const lastElement = outputData[outputData.length - 1];
|
||||||
if (
|
if (
|
||||||
lastElement.type === "result" &&
|
lastElement.type === "result" &&
|
||||||
"cost_usd" in lastElement &&
|
"total_cost_usd" in lastElement &&
|
||||||
"duration_ms" in lastElement
|
"duration_ms" in lastElement
|
||||||
) {
|
) {
|
||||||
executionDetails = {
|
executionDetails = {
|
||||||
cost_usd: lastElement.cost_usd,
|
total_cost_usd: lastElement.total_cost_usd,
|
||||||
duration_ms: lastElement.duration_ms,
|
duration_ms: lastElement.duration_ms,
|
||||||
duration_api_ms: lastElement.duration_api_ms,
|
duration_api_ms: lastElement.duration_api_ms,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export const PR_QUERY = `
|
|||||||
headRefName
|
headRefName
|
||||||
headRefOid
|
headRefOid
|
||||||
createdAt
|
createdAt
|
||||||
|
updatedAt
|
||||||
|
lastEditedAt
|
||||||
additions
|
additions
|
||||||
deletions
|
deletions
|
||||||
state
|
state
|
||||||
@@ -96,6 +98,8 @@ export const ISSUE_QUERY = `
|
|||||||
login
|
login
|
||||||
}
|
}
|
||||||
createdAt
|
createdAt
|
||||||
|
updatedAt
|
||||||
|
lastEditedAt
|
||||||
state
|
state
|
||||||
comments(first: 100) {
|
comments(first: 100) {
|
||||||
nodes {
|
nodes {
|
||||||
|
|||||||
@@ -107,6 +107,38 @@ export function filterReviewsToTriggerTime<
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if the issue/PR body was edited after the trigger time.
|
||||||
|
* This prevents a race condition where an attacker could edit the issue/PR body
|
||||||
|
* between when an authorized user triggered Claude and when Claude processes the request.
|
||||||
|
*
|
||||||
|
* @param contextData - The PR or issue data containing body and edit timestamps
|
||||||
|
* @param triggerTime - ISO timestamp of when the trigger event occurred
|
||||||
|
* @returns true if the body is safe to use, false if it was edited after trigger
|
||||||
|
*/
|
||||||
|
export function isBodySafeToUse(
|
||||||
|
contextData: { createdAt: string; updatedAt?: string; lastEditedAt?: string },
|
||||||
|
triggerTime: string | undefined,
|
||||||
|
): boolean {
|
||||||
|
// If no trigger time is available, we can't validate - allow the body
|
||||||
|
// This maintains backwards compatibility for triggers that don't have timestamps
|
||||||
|
if (!triggerTime) return true;
|
||||||
|
|
||||||
|
const triggerTimestamp = new Date(triggerTime).getTime();
|
||||||
|
|
||||||
|
// Check if the body was edited after the trigger
|
||||||
|
// Use lastEditedAt if available (more accurate for body edits), otherwise fall back to updatedAt
|
||||||
|
const lastEditTime = contextData.lastEditedAt || contextData.updatedAt;
|
||||||
|
if (lastEditTime) {
|
||||||
|
const lastEditTimestamp = new Date(lastEditTime).getTime();
|
||||||
|
if (lastEditTimestamp >= triggerTimestamp) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
type FetchDataParams = {
|
type FetchDataParams = {
|
||||||
octokits: Octokits;
|
octokits: Octokits;
|
||||||
repository: string;
|
repository: string;
|
||||||
@@ -273,9 +305,13 @@ export async function fetchGitHubData({
|
|||||||
body: c.body,
|
body: c.body,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Add the main issue/PR body if it has content
|
// Add the main issue/PR body if it has content and wasn't edited after trigger
|
||||||
const mainBody: CommentWithImages[] = contextData.body
|
// This prevents a TOCTOU race condition where an attacker could edit the body
|
||||||
? [
|
// between when an authorized user triggered Claude and when Claude processes the request
|
||||||
|
let mainBody: CommentWithImages[] = [];
|
||||||
|
if (contextData.body) {
|
||||||
|
if (isBodySafeToUse(contextData, triggerTime)) {
|
||||||
|
mainBody = [
|
||||||
{
|
{
|
||||||
...(isPR
|
...(isPR
|
||||||
? {
|
? {
|
||||||
@@ -289,8 +325,14 @@ export async function fetchGitHubData({
|
|||||||
body: contextData.body,
|
body: contextData.body,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
: [];
|
} else {
|
||||||
|
console.warn(
|
||||||
|
`Security: ${isPR ? "PR" : "Issue"} #${prNumber} body was edited after the trigger event. ` +
|
||||||
|
`Excluding body content to prevent potential injection attacks.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const allComments = [
|
const allComments = [
|
||||||
...mainBody,
|
...mainBody,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { GITHUB_SERVER_URL } from "../api/config";
|
import { GITHUB_SERVER_URL } from "../api/config";
|
||||||
|
|
||||||
export type ExecutionDetails = {
|
export type ExecutionDetails = {
|
||||||
cost_usd?: number;
|
total_cost_usd?: number;
|
||||||
duration_ms?: number;
|
duration_ms?: number;
|
||||||
duration_api_ms?: number;
|
duration_api_ms?: number;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ export type GitHubPullRequest = {
|
|||||||
headRefName: string;
|
headRefName: string;
|
||||||
headRefOid: string;
|
headRefOid: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
lastEditedAt?: string;
|
||||||
additions: number;
|
additions: number;
|
||||||
deletions: number;
|
deletions: number;
|
||||||
state: string;
|
state: string;
|
||||||
@@ -83,6 +85,8 @@ export type GitHubIssue = {
|
|||||||
body: string;
|
body: string;
|
||||||
author: GitHubAuthor;
|
author: GitHubAuthor;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
lastEditedAt?: string;
|
||||||
state: string;
|
state: string;
|
||||||
comments: {
|
comments: {
|
||||||
nodes: GitHubComment[];
|
nodes: GitHubComment[];
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|||||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { readFile, stat } from "fs/promises";
|
import { readFile, stat } from "fs/promises";
|
||||||
import { join } from "path";
|
import { join, resolve, sep } from "path";
|
||||||
import { constants } from "fs";
|
import { constants } from "fs";
|
||||||
import fetch from "node-fetch";
|
import fetch from "node-fetch";
|
||||||
import { GITHUB_API_URL } from "../github/api/config";
|
import { GITHUB_API_URL } from "../github/api/config";
|
||||||
@@ -474,20 +474,21 @@ server.tool(
|
|||||||
throw new Error("GITHUB_TOKEN environment variable is required");
|
throw new Error("GITHUB_TOKEN environment variable is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert absolute paths to relative if they match CWD
|
// Normalize all paths and validate they're within the repository root
|
||||||
const cwd = process.cwd();
|
const cwd = process.cwd();
|
||||||
const processedPaths = paths.map((filePath) => {
|
const processedPaths = paths.map((filePath) => {
|
||||||
if (filePath.startsWith("/")) {
|
// Normalize the path to resolve any .. or . sequences
|
||||||
if (filePath.startsWith(cwd)) {
|
const normalizedPath = resolve(cwd, filePath);
|
||||||
// Strip CWD from absolute path
|
|
||||||
return filePath.slice(cwd.length + 1);
|
// Validate the normalized path is within the current working directory
|
||||||
} else {
|
if (!normalizedPath.startsWith(cwd + sep)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Path '${filePath}' must be relative to repository root or within current working directory`,
|
`Path '${filePath}' resolves outside the repository root`,
|
||||||
);
|
);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return filePath;
|
|
||||||
|
// Convert to relative path by stripping the cwd prefix
|
||||||
|
return normalizedPath.slice(cwd.length + 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 1. Get the branch reference (create if doesn't exist)
|
// 1. Get the branch reference (create if doesn't exist)
|
||||||
|
|||||||
@@ -258,7 +258,7 @@ describe("updateCommentBody", () => {
|
|||||||
const input = {
|
const input = {
|
||||||
...baseInput,
|
...baseInput,
|
||||||
executionDetails: {
|
executionDetails: {
|
||||||
cost_usd: 0.13382595,
|
total_cost_usd: 0.13382595,
|
||||||
duration_ms: 31033,
|
duration_ms: 31033,
|
||||||
duration_api_ms: 31034,
|
duration_api_ms: 31034,
|
||||||
},
|
},
|
||||||
@@ -301,7 +301,7 @@ describe("updateCommentBody", () => {
|
|||||||
const input = {
|
const input = {
|
||||||
...baseInput,
|
...baseInput,
|
||||||
executionDetails: {
|
executionDetails: {
|
||||||
cost_usd: 0.25,
|
total_cost_usd: 0.25,
|
||||||
},
|
},
|
||||||
triggerUsername: "testuser",
|
triggerUsername: "testuser",
|
||||||
};
|
};
|
||||||
@@ -322,7 +322,7 @@ describe("updateCommentBody", () => {
|
|||||||
branchName: "claude-branch-123",
|
branchName: "claude-branch-123",
|
||||||
prLink: "\n[Create a PR](https://github.com/owner/repo/pr-url)",
|
prLink: "\n[Create a PR](https://github.com/owner/repo/pr-url)",
|
||||||
executionDetails: {
|
executionDetails: {
|
||||||
cost_usd: 0.01,
|
total_cost_usd: 0.01,
|
||||||
duration_ms: 65000, // 1 minute 5 seconds
|
duration_ms: 65000, // 1 minute 5 seconds
|
||||||
},
|
},
|
||||||
triggerUsername: "trigger-user",
|
triggerUsername: "trigger-user",
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
fetchGitHubData,
|
fetchGitHubData,
|
||||||
filterCommentsToTriggerTime,
|
filterCommentsToTriggerTime,
|
||||||
filterReviewsToTriggerTime,
|
filterReviewsToTriggerTime,
|
||||||
|
isBodySafeToUse,
|
||||||
} from "../src/github/data/fetcher";
|
} from "../src/github/data/fetcher";
|
||||||
import {
|
import {
|
||||||
createMockContext,
|
createMockContext,
|
||||||
@@ -371,6 +372,139 @@ describe("filterReviewsToTriggerTime", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("isBodySafeToUse", () => {
|
||||||
|
const triggerTime = "2024-01-15T12:00:00Z";
|
||||||
|
|
||||||
|
const createMockContextData = (
|
||||||
|
createdAt: string,
|
||||||
|
updatedAt?: string,
|
||||||
|
lastEditedAt?: string,
|
||||||
|
) => ({
|
||||||
|
createdAt,
|
||||||
|
updatedAt,
|
||||||
|
lastEditedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("body edit time validation", () => {
|
||||||
|
it("should return true when body was never edited", () => {
|
||||||
|
const contextData = createMockContextData("2024-01-15T10:00:00Z");
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return true when body was edited before trigger time", () => {
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T11:00:00Z",
|
||||||
|
"2024-01-15T11:30:00Z",
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false when body was edited after trigger time (using updatedAt)", () => {
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T13:00:00Z",
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false when body was edited after trigger time (using lastEditedAt)", () => {
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
undefined,
|
||||||
|
"2024-01-15T13:00:00Z",
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false when body was edited exactly at trigger time", () => {
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T12:00:00Z",
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should prioritize lastEditedAt over updatedAt", () => {
|
||||||
|
// updatedAt is after trigger, but lastEditedAt is before - should be safe
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T13:00:00Z", // updatedAt after trigger
|
||||||
|
"2024-01-15T11:00:00Z", // lastEditedAt before trigger
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("edge cases", () => {
|
||||||
|
it("should return true when no trigger time is provided (backward compatibility)", () => {
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T13:00:00Z", // Would normally fail
|
||||||
|
"2024-01-15T14:00:00Z", // Would normally fail
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, undefined)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle millisecond precision correctly", () => {
|
||||||
|
// Edit 1ms after trigger - should be unsafe
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T12:00:00.001Z",
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle edit 1ms before trigger - should be safe", () => {
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T11:59:59.999Z",
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, triggerTime)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle various ISO timestamp formats", () => {
|
||||||
|
const contextData1 = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T11:00:00Z",
|
||||||
|
);
|
||||||
|
const contextData2 = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00+00:00",
|
||||||
|
"2024-01-15T11:00:00+00:00",
|
||||||
|
);
|
||||||
|
const contextData3 = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00.000Z",
|
||||||
|
"2024-01-15T11:00:00.000Z",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(isBodySafeToUse(contextData1, triggerTime)).toBe(true);
|
||||||
|
expect(isBodySafeToUse(contextData2, triggerTime)).toBe(true);
|
||||||
|
expect(isBodySafeToUse(contextData3, triggerTime)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("security scenarios", () => {
|
||||||
|
it("should detect race condition attack - body edited between trigger and processing", () => {
|
||||||
|
// Simulates: Owner triggers @claude at 12:00, attacker edits body at 12:00:30
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z", // Issue created
|
||||||
|
"2024-01-15T12:00:30Z", // Body edited after trigger
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, "2024-01-15T12:00:00Z")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should allow body that was stable at trigger time", () => {
|
||||||
|
// Body was last edited well before the trigger
|
||||||
|
const contextData = createMockContextData(
|
||||||
|
"2024-01-15T10:00:00Z",
|
||||||
|
"2024-01-15T10:30:00Z",
|
||||||
|
"2024-01-15T10:30:00Z",
|
||||||
|
);
|
||||||
|
expect(isBodySafeToUse(contextData, "2024-01-15T12:00:00Z")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("fetchGitHubData integration with time filtering", () => {
|
describe("fetchGitHubData integration with time filtering", () => {
|
||||||
it("should filter comments based on trigger time when provided", async () => {
|
it("should filter comments based on trigger time when provided", async () => {
|
||||||
const mockOctokits = {
|
const mockOctokits = {
|
||||||
@@ -696,4 +830,119 @@ describe("fetchGitHubData integration with time filtering", () => {
|
|||||||
// All three comments should be included as they're all before trigger time
|
// All three comments should be included as they're all before trigger time
|
||||||
expect(result.comments.length).toBe(3);
|
expect(result.comments.length).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should exclude issue body when edited after trigger time (TOCTOU protection)", async () => {
|
||||||
|
const mockOctokits = {
|
||||||
|
graphql: jest.fn().mockResolvedValue({
|
||||||
|
repository: {
|
||||||
|
issue: {
|
||||||
|
number: 555,
|
||||||
|
title: "Test Issue",
|
||||||
|
body: "Malicious body edited after trigger",
|
||||||
|
author: { login: "attacker" },
|
||||||
|
createdAt: "2024-01-15T10:00:00Z",
|
||||||
|
updatedAt: "2024-01-15T12:30:00Z", // Edited after trigger
|
||||||
|
lastEditedAt: "2024-01-15T12:30:00Z", // Edited after trigger
|
||||||
|
comments: { nodes: [] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
user: { login: "trigger-user" },
|
||||||
|
}),
|
||||||
|
rest: jest.fn() as any,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await fetchGitHubData({
|
||||||
|
octokits: mockOctokits as any,
|
||||||
|
repository: "test-owner/test-repo",
|
||||||
|
prNumber: "555",
|
||||||
|
isPR: false,
|
||||||
|
triggerUsername: "trigger-user",
|
||||||
|
triggerTime: "2024-01-15T12:00:00Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
// The body should be excluded from image processing due to TOCTOU protection
|
||||||
|
// We can verify this by checking that issue_body is NOT in the imageUrlMap keys
|
||||||
|
const hasIssueBodyInMap = Array.from(result.imageUrlMap.keys()).some(
|
||||||
|
(key) => key.includes("issue_body"),
|
||||||
|
);
|
||||||
|
expect(hasIssueBodyInMap).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should include issue body when not edited after trigger time", async () => {
|
||||||
|
const mockOctokits = {
|
||||||
|
graphql: jest.fn().mockResolvedValue({
|
||||||
|
repository: {
|
||||||
|
issue: {
|
||||||
|
number: 666,
|
||||||
|
title: "Test Issue",
|
||||||
|
body: "Safe body not edited after trigger",
|
||||||
|
author: { login: "author" },
|
||||||
|
createdAt: "2024-01-15T10:00:00Z",
|
||||||
|
updatedAt: "2024-01-15T11:00:00Z", // Edited before trigger
|
||||||
|
lastEditedAt: "2024-01-15T11:00:00Z", // Edited before trigger
|
||||||
|
comments: { nodes: [] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
user: { login: "trigger-user" },
|
||||||
|
}),
|
||||||
|
rest: jest.fn() as any,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await fetchGitHubData({
|
||||||
|
octokits: mockOctokits as any,
|
||||||
|
repository: "test-owner/test-repo",
|
||||||
|
prNumber: "666",
|
||||||
|
isPR: false,
|
||||||
|
triggerUsername: "trigger-user",
|
||||||
|
triggerTime: "2024-01-15T12:00:00Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
// The contextData should still contain the body
|
||||||
|
expect(result.contextData.body).toBe("Safe body not edited after trigger");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should exclude PR body when edited after trigger time (TOCTOU protection)", async () => {
|
||||||
|
const mockOctokits = {
|
||||||
|
graphql: jest.fn().mockResolvedValue({
|
||||||
|
repository: {
|
||||||
|
pullRequest: {
|
||||||
|
number: 777,
|
||||||
|
title: "Test PR",
|
||||||
|
body: "Malicious PR body edited after trigger",
|
||||||
|
author: { login: "attacker" },
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature",
|
||||||
|
headRefOid: "abc123",
|
||||||
|
createdAt: "2024-01-15T10:00:00Z",
|
||||||
|
updatedAt: "2024-01-15T12:30:00Z", // Edited after trigger
|
||||||
|
lastEditedAt: "2024-01-15T12:30:00Z", // Edited after trigger
|
||||||
|
additions: 10,
|
||||||
|
deletions: 5,
|
||||||
|
state: "OPEN",
|
||||||
|
commits: { totalCount: 1, nodes: [] },
|
||||||
|
files: { nodes: [] },
|
||||||
|
comments: { nodes: [] },
|
||||||
|
reviews: { nodes: [] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
user: { login: "trigger-user" },
|
||||||
|
}),
|
||||||
|
rest: jest.fn() as any,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await fetchGitHubData({
|
||||||
|
octokits: mockOctokits as any,
|
||||||
|
repository: "test-owner/test-repo",
|
||||||
|
prNumber: "777",
|
||||||
|
isPR: true,
|
||||||
|
triggerUsername: "trigger-user",
|
||||||
|
triggerTime: "2024-01-15T12:00:00Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
// The body should be excluded from image processing due to TOCTOU protection
|
||||||
|
const hasPrBodyInMap = Array.from(result.imageUrlMap.keys()).some((key) =>
|
||||||
|
key.includes("pr_body"),
|
||||||
|
);
|
||||||
|
expect(hasPrBodyInMap).toBe(false);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
2
test/fixtures/sample-turns.json
vendored
2
test/fixtures/sample-turns.json
vendored
@@ -189,7 +189,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "result",
|
"type": "result",
|
||||||
"cost_usd": 0.0347,
|
"total_cost_usd": 0.0347,
|
||||||
"duration_ms": 18750,
|
"duration_ms": 18750,
|
||||||
"result": "Successfully removed debug print statement from file and added review comment to document the change."
|
"result": "Successfully removed debug print statement from file and added review comment to document the change."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -401,6 +401,53 @@ export const mockPullRequestReviewContext: ParsedGitHubContext = {
|
|||||||
inputs: { ...defaultInputs, triggerPhrase: "@claude" },
|
inputs: { ...defaultInputs, triggerPhrase: "@claude" },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const mockPullRequestReviewWithoutCommentContext: ParsedGitHubContext = {
|
||||||
|
runId: "1234567890",
|
||||||
|
eventName: "pull_request_review",
|
||||||
|
eventAction: "dismissed",
|
||||||
|
repository: defaultRepository,
|
||||||
|
actor: "senior-developer",
|
||||||
|
payload: {
|
||||||
|
action: "submitted",
|
||||||
|
review: {
|
||||||
|
id: 11122233,
|
||||||
|
body: null, // Simulating approval without comment
|
||||||
|
user: {
|
||||||
|
login: "senior-developer",
|
||||||
|
id: 44444,
|
||||||
|
avatar_url: "https://avatars.githubusercontent.com/u/44444",
|
||||||
|
html_url: "https://github.com/senior-developer",
|
||||||
|
},
|
||||||
|
state: "approved",
|
||||||
|
html_url:
|
||||||
|
"https://github.com/test-owner/test-repo/pull/321#pullrequestreview-11122233",
|
||||||
|
submitted_at: "2024-01-15T15:30:00Z",
|
||||||
|
},
|
||||||
|
pull_request: {
|
||||||
|
number: 321,
|
||||||
|
title: "Refactor: Improve error handling in API layer",
|
||||||
|
body: "This PR improves error handling across all API endpoints",
|
||||||
|
user: {
|
||||||
|
login: "backend-developer",
|
||||||
|
id: 33333,
|
||||||
|
avatar_url: "https://avatars.githubusercontent.com/u/33333",
|
||||||
|
html_url: "https://github.com/backend-developer",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
repository: {
|
||||||
|
name: "test-repo",
|
||||||
|
full_name: "test-owner/test-repo",
|
||||||
|
private: false,
|
||||||
|
owner: {
|
||||||
|
login: "test-owner",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as PullRequestReviewEvent,
|
||||||
|
entityNumber: 321,
|
||||||
|
isPR: true,
|
||||||
|
inputs: { ...defaultInputs, triggerPhrase: "@claude" },
|
||||||
|
};
|
||||||
|
|
||||||
export const mockPullRequestReviewCommentContext: ParsedGitHubContext = {
|
export const mockPullRequestReviewCommentContext: ParsedGitHubContext = {
|
||||||
runId: "1234567890",
|
runId: "1234567890",
|
||||||
eventName: "pull_request_review_comment",
|
eventName: "pull_request_review_comment",
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
mockPullRequestCommentContext,
|
mockPullRequestCommentContext,
|
||||||
mockPullRequestReviewContext,
|
mockPullRequestReviewContext,
|
||||||
mockPullRequestReviewCommentContext,
|
mockPullRequestReviewCommentContext,
|
||||||
|
mockPullRequestReviewWithoutCommentContext,
|
||||||
} from "./mockContext";
|
} from "./mockContext";
|
||||||
|
|
||||||
const BASE_ENV = {
|
const BASE_ENV = {
|
||||||
@@ -126,6 +127,24 @@ describe("parseEnvVarsWithContext", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("pull_request_review event without comment", () => {
|
||||||
|
test("should parse pull_request_review event correctly", () => {
|
||||||
|
process.env = BASE_ENV;
|
||||||
|
const result = prepareContext(
|
||||||
|
mockPullRequestReviewWithoutCommentContext,
|
||||||
|
"12345",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.eventData.eventName).toBe("pull_request_review");
|
||||||
|
expect(result.eventData.isPR).toBe(true);
|
||||||
|
expect(result.triggerUsername).toBe("senior-developer");
|
||||||
|
if (result.eventData.eventName === "pull_request_review") {
|
||||||
|
expect(result.eventData.prNumber).toBe("321");
|
||||||
|
expect(result.eventData.commentBody).toBe("");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("pull_request_review_comment event", () => {
|
describe("pull_request_review_comment event", () => {
|
||||||
test("should parse pull_request_review_comment event correctly", () => {
|
test("should parse pull_request_review_comment event correctly", () => {
|
||||||
process.env = BASE_ENV;
|
process.env = BASE_ENV;
|
||||||
|
|||||||
Reference in New Issue
Block a user