mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-01-23 23:14:13 +08:00
Compare commits
1 Commits
ashwin/tim
...
inigo/stru
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c102f7cd09 |
2
.github/workflows/claude-review.yml
vendored
2
.github/workflows/claude-review.yml
vendored
@@ -2,7 +2,7 @@ name: PR Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened]
|
||||
types: [opened, synchronize, ready_for_review, reopened]
|
||||
|
||||
jobs:
|
||||
review:
|
||||
|
||||
174
.github/workflows/test-structured-output.yml
vendored
174
.github/workflows/test-structured-output.yml
vendored
@@ -1,10 +1,16 @@
|
||||
name: Test Structured Outputs
|
||||
name: Test Structured Outputs (Optimized)
|
||||
|
||||
# This workflow uses EXPLICIT prompts that tell Claude exactly what to return.
|
||||
# This makes tests fast, deterministic, and focuses on testing OUR code, not Claude's reasoning.
|
||||
#
|
||||
# NOTE: Disabled until Agent SDK structured outputs feature is released
|
||||
# The --json-schema flag is not yet available in public Claude Code releases
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
# Disabled - uncomment when feature is released
|
||||
# push:
|
||||
# branches: [main]
|
||||
# pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -22,6 +28,7 @@ jobs:
|
||||
id: test
|
||||
uses: ./base-action
|
||||
with:
|
||||
# EXPLICIT: Tell Claude exactly what to return - no reasoning needed
|
||||
prompt: |
|
||||
Run this command: echo "test"
|
||||
|
||||
@@ -30,41 +37,43 @@ jobs:
|
||||
- number_field: 42
|
||||
- boolean_true: true
|
||||
- boolean_false: false
|
||||
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"]
|
||||
}
|
||||
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"]}'
|
||||
allowed_tools: "Bash"
|
||||
|
||||
- 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'"
|
||||
if [ "${{ steps.test.outputs.text_field }}" != "hello" ]; then
|
||||
echo "❌ String: expected 'hello', got '${{ steps.test.outputs.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'"
|
||||
if [ "${{ steps.test.outputs.number_field }}" != "42" ]; then
|
||||
echo "❌ Number: expected '42', got '${{ steps.test.outputs.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'"
|
||||
if [ "${{ steps.test.outputs.boolean_true }}" != "true" ]; then
|
||||
echo "❌ Boolean true: expected 'true', got '${{ steps.test.outputs.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'"
|
||||
if [ "${{ steps.test.outputs.boolean_false }}" != "false" ]; then
|
||||
echo "❌ Boolean false: expected 'false', got '${{ steps.test.outputs.boolean_false }}'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -81,6 +90,7 @@ jobs:
|
||||
id: test
|
||||
uses: ./base-action
|
||||
with:
|
||||
# EXPLICIT: No file reading, no analysis
|
||||
prompt: |
|
||||
Run: echo "ready"
|
||||
|
||||
@@ -88,38 +98,46 @@ jobs:
|
||||
- items: ["apple", "banana", "cherry"]
|
||||
- config: {"key": "value", "count": 3}
|
||||
- empty_array: []
|
||||
json_schema: |
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"}
|
||||
},
|
||||
"config": {"type": "object"},
|
||||
"empty_array": {"type": "array"}
|
||||
},
|
||||
"required": ["items", "config", "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"]}'
|
||||
allowed_tools: "Bash"
|
||||
|
||||
- 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'
|
||||
ITEMS='${{ steps.test.outputs.items }}'
|
||||
if ! echo "$ITEMS" | jq -e '. | length == 3' > /dev/null; then
|
||||
echo "❌ Array not properly stringified: $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'
|
||||
CONFIG='${{ steps.test.outputs.config }}'
|
||||
if ! echo "$CONFIG" | jq -e '.key == "value"' > /dev/null; then
|
||||
echo "❌ Object not properly stringified: $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'
|
||||
EMPTY='${{ steps.test.outputs.empty_array }}'
|
||||
if ! echo "$EMPTY" | jq -e '. | length == 0' > /dev/null; then
|
||||
echo "❌ Empty array not properly stringified: $EMPTY"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ All complex types handled correctly"
|
||||
echo "✅ All complex types JSON stringified correctly"
|
||||
|
||||
test-edge-cases:
|
||||
name: Test Edge Cases
|
||||
@@ -140,41 +158,43 @@ jobs:
|
||||
- empty_string: ""
|
||||
- negative: -5
|
||||
- decimal: 3.14
|
||||
json_schema: |
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"zero": {"type": "number"},
|
||||
"empty_string": {"type": "string"},
|
||||
"negative": {"type": "number"},
|
||||
"decimal": {"type": "number"}
|
||||
},
|
||||
"required": ["zero", "empty_string", "negative", "decimal"]
|
||||
}
|
||||
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"]}'
|
||||
allowed_tools: "Bash"
|
||||
|
||||
- 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'"
|
||||
if [ "${{ steps.test.outputs.zero }}" != "0" ]; then
|
||||
echo "❌ Zero: expected '0', got '${{ steps.test.outputs.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'"
|
||||
if [ "${{ steps.test.outputs.empty_string }}" != "" ]; then
|
||||
echo "❌ Empty string: expected '', got '${{ steps.test.outputs.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'"
|
||||
if [ "${{ steps.test.outputs.negative }}" != "-5" ]; then
|
||||
echo "❌ Negative: expected '-5', got '${{ steps.test.outputs.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'"
|
||||
if [ "${{ steps.test.outputs.decimal }}" != "3.14" ]; then
|
||||
echo "❌ Decimal: expected '3.14', got '${{ steps.test.outputs.decimal }}'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -194,27 +214,29 @@ jobs:
|
||||
prompt: |
|
||||
Run: echo "test"
|
||||
Return EXACTLY: {test-result: "passed", item_count: 10}
|
||||
json_schema: |
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"test-result": {"type": "string"},
|
||||
"item_count": {"type": "number"}
|
||||
},
|
||||
"required": ["test-result", "item_count"]
|
||||
}
|
||||
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"]}'
|
||||
allowed_tools: "Bash"
|
||||
|
||||
- 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'"
|
||||
# Hyphens should be preserved (GitHub Actions allows them)
|
||||
if [ "${{ steps.test.outputs.test-result }}" != "passed" ]; then
|
||||
echo "❌ Hyphenated name failed"
|
||||
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'"
|
||||
if [ "${{ steps.test.outputs.item_count }}" != "10" ]; then
|
||||
echo "❌ Underscore name failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -232,10 +254,16 @@ jobs:
|
||||
uses: ./base-action
|
||||
with:
|
||||
prompt: "Run: echo 'complete'. Return: {done: true}"
|
||||
json_schema: |
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"done": {"type": "boolean"}
|
||||
},
|
||||
"required": ["done"]
|
||||
}
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
claude_args: |
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"done":{"type":"boolean"}},"required":["done"]}'
|
||||
allowed_tools: "Bash"
|
||||
|
||||
- name: Verify execution file contains structured_output
|
||||
run: |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# 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, Google Vertex AI, and Microsoft Foundry.
|
||||
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.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -13,7 +13,6 @@ 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
|
||||
- 🛠️ **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
|
||||
- 📊 **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)
|
||||
- ⚙️ **Simplified Configuration**: Unified `prompt` and `claude_args` inputs provide clean, powerful configuration aligned with Claude Code SDK
|
||||
|
||||
@@ -30,7 +29,7 @@ This command will guide you through setting up the GitHub app and required secre
|
||||
**Note**:
|
||||
|
||||
- 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, Google Vertex AI, or Microsoft Foundry setup, see [docs/cloud-providers.md](./docs/cloud-providers.md).
|
||||
- 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).
|
||||
|
||||
## 📚 Solutions & Use Cases
|
||||
|
||||
@@ -57,7 +56,7 @@ Each solution includes complete working examples, configuration details, and exp
|
||||
- [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
|
||||
- [Experimental Features](./docs/experimental.md) - Execution modes and network restrictions
|
||||
- [Cloud Providers](./docs/cloud-providers.md) - AWS Bedrock, Google Vertex AI, and Microsoft Foundry setup
|
||||
- [Cloud Providers](./docs/cloud-providers.md) - AWS Bedrock and Google Vertex AI setup
|
||||
- [Capabilities & Limitations](./docs/capabilities-and-limitations.md) - What Claude can and cannot do
|
||||
- [Security](./docs/security.md) - Access control, permissions, and commit signing
|
||||
- [FAQ](./docs/faq.md) - Common questions and troubleshooting
|
||||
|
||||
50
action.yml
50
action.yml
@@ -44,7 +44,7 @@ inputs:
|
||||
|
||||
# Auth configuration
|
||||
anthropic_api_key:
|
||||
description: "Anthropic API key (required for direct API, not needed for Bedrock/Vertex/Foundry)"
|
||||
description: "Anthropic API key (required for direct API, not needed for Bedrock/Vertex)"
|
||||
required: false
|
||||
claude_code_oauth_token:
|
||||
description: "Claude Code OAuth token (alternative to anthropic_api_key)"
|
||||
@@ -60,10 +60,6 @@ inputs:
|
||||
description: "Use Google Vertex AI with OIDC authentication instead of direct Anthropic API"
|
||||
required: false
|
||||
default: "false"
|
||||
use_foundry:
|
||||
description: "Use Microsoft Foundry with OIDC authentication instead of direct Anthropic API"
|
||||
required: false
|
||||
default: "false"
|
||||
|
||||
claude_args:
|
||||
description: "Additional arguments to pass directly to Claude CLI"
|
||||
@@ -117,6 +113,10 @@ inputs:
|
||||
description: "Newline-separated list of Claude Code plugin marketplace Git URLs to install from (e.g., 'https://github.com/user/marketplace1.git\nhttps://github.com/user/marketplace2.git')"
|
||||
required: false
|
||||
default: ""
|
||||
json_schema:
|
||||
description: "JSON schema for structured output validation. When provided, Claude will return validated JSON matching this schema, and the action will automatically set GitHub Action outputs for each field."
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
outputs:
|
||||
execution_file:
|
||||
@@ -128,9 +128,6 @@ outputs:
|
||||
github_token:
|
||||
description: "The GitHub token used by the action (Claude App token if available)"
|
||||
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:
|
||||
using: "composite"
|
||||
@@ -181,6 +178,7 @@ runs:
|
||||
TRACK_PROGRESS: ${{ inputs.track_progress }}
|
||||
ADDITIONAL_PERMISSIONS: ${{ inputs.additional_permissions }}
|
||||
CLAUDE_ARGS: ${{ inputs.claude_args }}
|
||||
JSON_SCHEMA: ${{ inputs.json_schema }}
|
||||
ALL_INPUTS: ${{ toJson(inputs) }}
|
||||
|
||||
- name: Install Base Action Dependencies
|
||||
@@ -195,30 +193,8 @@ runs:
|
||||
|
||||
# Install Claude Code if no custom executable is provided
|
||||
if [ -z "${{ inputs.path_to_claude_code_executable }}" ]; then
|
||||
CLAUDE_CODE_VERSION="2.0.50"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
# Cross-platform timeout (GNU timeout not available on macOS)
|
||||
(curl -fsSL https://claude.ai/install.sh | bash -s -- "$CLAUDE_CODE_VERSION") &
|
||||
install_pid=$!
|
||||
( sleep 120; kill $install_pid 2>/dev/null ) &
|
||||
timeout_pid=$!
|
||||
if wait $install_pid 2>/dev/null; then
|
||||
kill $timeout_pid 2>/dev/null || true
|
||||
wait $timeout_pid 2>/dev/null || true
|
||||
echo "Claude Code installed successfully"
|
||||
break
|
||||
fi
|
||||
kill $timeout_pid 2>/dev/null || true
|
||||
wait $timeout_pid 2>/dev/null || true
|
||||
if [ $attempt -eq 3 ]; then
|
||||
echo "Failed to install Claude Code after 3 attempts"
|
||||
exit 1
|
||||
fi
|
||||
echo "Installation timed out or failed, retrying..."
|
||||
sleep 5
|
||||
done
|
||||
echo "Installing Claude Code..."
|
||||
curl -fsSL https://claude.ai/install.sh | bash -s 2.0.42
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
else
|
||||
echo "Using custom Claude Code executable: ${{ inputs.path_to_claude_code_executable }}"
|
||||
@@ -257,6 +233,7 @@ runs:
|
||||
INPUT_SHOW_FULL_OUTPUT: ${{ inputs.show_full_output }}
|
||||
INPUT_PLUGINS: ${{ inputs.plugins }}
|
||||
INPUT_PLUGIN_MARKETPLACES: ${{ inputs.plugin_marketplaces }}
|
||||
JSON_SCHEMA: ${{ inputs.json_schema }}
|
||||
|
||||
# Model configuration
|
||||
GITHUB_TOKEN: ${{ steps.prepare.outputs.GITHUB_TOKEN }}
|
||||
@@ -270,14 +247,12 @@ runs:
|
||||
ANTHROPIC_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }}
|
||||
CLAUDE_CODE_USE_BEDROCK: ${{ inputs.use_bedrock == 'true' && '1' || '' }}
|
||||
CLAUDE_CODE_USE_VERTEX: ${{ inputs.use_vertex == 'true' && '1' || '' }}
|
||||
CLAUDE_CODE_USE_FOUNDRY: ${{ inputs.use_foundry == 'true' && '1' || '' }}
|
||||
|
||||
# AWS configuration
|
||||
AWS_REGION: ${{ env.AWS_REGION }}
|
||||
AWS_ACCESS_KEY_ID: ${{ env.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ env.AWS_SECRET_ACCESS_KEY }}
|
||||
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)) }}
|
||||
|
||||
# GCP configuration
|
||||
@@ -291,13 +266,6 @@ runs:
|
||||
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 }}
|
||||
|
||||
# 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
|
||||
if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always()
|
||||
shell: bash
|
||||
|
||||
@@ -42,10 +42,6 @@ inputs:
|
||||
description: "Use Google Vertex AI with OIDC authentication instead of direct Anthropic API"
|
||||
required: false
|
||||
default: "false"
|
||||
use_foundry:
|
||||
description: "Use Microsoft Foundry with OIDC authentication instead of direct Anthropic API"
|
||||
required: false
|
||||
default: "false"
|
||||
|
||||
use_node_cache:
|
||||
description: "Whether to use Node.js dependency caching (set to true only for Node.js projects with lock files)"
|
||||
@@ -71,6 +67,10 @@ inputs:
|
||||
description: "Newline-separated list of Claude Code plugin marketplace Git URLs to install from (e.g., 'https://github.com/user/marketplace1.git\nhttps://github.com/user/marketplace2.git')"
|
||||
required: false
|
||||
default: ""
|
||||
json_schema:
|
||||
description: "JSON schema for structured output validation. When provided, Claude will return validated JSON matching this schema, and the action will automatically set GitHub Action outputs for each field (e.g., access via steps.id.outputs.field_name)"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
outputs:
|
||||
conclusion:
|
||||
@@ -79,9 +79,6 @@ outputs:
|
||||
execution_file:
|
||||
description: "Path to the JSON file containing Claude Code execution log"
|
||||
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:
|
||||
using: "composite"
|
||||
@@ -117,30 +114,8 @@ runs:
|
||||
shell: bash
|
||||
run: |
|
||||
if [ -z "${{ inputs.path_to_claude_code_executable }}" ]; then
|
||||
CLAUDE_CODE_VERSION="2.0.50"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
# Cross-platform timeout (GNU timeout not available on macOS)
|
||||
(curl -fsSL https://claude.ai/install.sh | bash -s -- "$CLAUDE_CODE_VERSION") &
|
||||
install_pid=$!
|
||||
( sleep 120; kill $install_pid 2>/dev/null ) &
|
||||
timeout_pid=$!
|
||||
if wait $install_pid 2>/dev/null; then
|
||||
kill $timeout_pid 2>/dev/null || true
|
||||
wait $timeout_pid 2>/dev/null || true
|
||||
echo "Claude Code installed successfully"
|
||||
break
|
||||
fi
|
||||
kill $timeout_pid 2>/dev/null || true
|
||||
wait $timeout_pid 2>/dev/null || true
|
||||
if [ $attempt -eq 3 ]; then
|
||||
echo "Failed to install Claude Code after 3 attempts"
|
||||
exit 1
|
||||
fi
|
||||
echo "Installation timed out or failed, retrying..."
|
||||
sleep 5
|
||||
done
|
||||
echo "Installing Claude Code..."
|
||||
curl -fsSL https://claude.ai/install.sh | bash -s 2.0.42
|
||||
else
|
||||
echo "Using custom Claude Code executable: ${{ inputs.path_to_claude_code_executable }}"
|
||||
# Add the directory containing the custom executable to PATH
|
||||
@@ -179,14 +154,12 @@ runs:
|
||||
# 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_VERTEX: ${{ inputs.use_vertex == 'true' && '1' || '' }}
|
||||
CLAUDE_CODE_USE_FOUNDRY: ${{ inputs.use_foundry == 'true' && '1' || '' }}
|
||||
|
||||
# AWS configuration
|
||||
AWS_REGION: ${{ env.AWS_REGION }}
|
||||
AWS_ACCESS_KEY_ID: ${{ env.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ env.AWS_SECRET_ACCESS_KEY }}
|
||||
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)) }}
|
||||
|
||||
# GCP configuration
|
||||
@@ -194,10 +167,3 @@ runs:
|
||||
CLOUD_ML_REGION: ${{ env.CLOUD_ML_REGION }}
|
||||
GOOGLE_APPLICATION_CREDENTIALS: ${{ env.GOOGLE_APPLICATION_CREDENTIALS }}
|
||||
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 }}
|
||||
|
||||
@@ -12,6 +12,11 @@ const PIPE_PATH = `${process.env.RUNNER_TEMP}/claude_prompt_pipe`;
|
||||
const EXECUTION_FILE = `${process.env.RUNNER_TEMP}/claude-execution-output.json`;
|
||||
const BASE_ARGS = ["--verbose", "--output-format", "stream-json"];
|
||||
|
||||
type ExecutionMessage = {
|
||||
type: string;
|
||||
structured_output?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sanitizes JSON output to remove sensitive information when full output is disabled
|
||||
* Returns a safe summary message or null if the message should be completely suppressed
|
||||
@@ -123,53 +128,90 @@ 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
|
||||
* Sanitizes output field names to meet GitHub Actions output naming requirements
|
||||
* GitHub outputs must be alphanumeric, hyphen, or underscore only
|
||||
*/
|
||||
export async function parseAndSetStructuredOutputs(
|
||||
function sanitizeOutputName(name: string): string {
|
||||
return name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts values to string format for GitHub Actions outputs
|
||||
* GitHub outputs must always be strings
|
||||
*/
|
||||
function convertToString(value: unknown): string {
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
return value;
|
||||
case "boolean":
|
||||
case "number":
|
||||
return String(value);
|
||||
case "object":
|
||||
return value === null ? "" : JSON.stringify(value);
|
||||
case "undefined":
|
||||
return "";
|
||||
default:
|
||||
// Handle Symbol, Function, etc.
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses structured_output from execution file and sets GitHub Action outputs
|
||||
* Only runs if json_schema was explicitly provided by the user
|
||||
*/
|
||||
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>;
|
||||
}[];
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
|
||||
// Search backwards - result is typically last or second-to-last message
|
||||
const result = messages.findLast(
|
||||
const result = messages.find(
|
||||
(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`,
|
||||
const error = new Error(
|
||||
"json_schema was provided but Claude did not return structured_output. " +
|
||||
"The schema may be invalid or Claude failed to call the StructuredOutput tool.",
|
||||
);
|
||||
core.setFailed(error.message);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// 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
|
||||
// Set GitHub Action output for each field
|
||||
const entries = Object.entries(result.structured_output);
|
||||
core.info(`Setting ${entries.length} structured output(s)`);
|
||||
|
||||
for (const [key, value] of entries) {
|
||||
const sanitizedKey = sanitizeOutputName(key);
|
||||
if (!sanitizedKey) {
|
||||
core.warning(`Skipping invalid output key: "${key}"`);
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Failed to parse structured outputs: ${error}`);
|
||||
|
||||
const stringValue = convertToString(value);
|
||||
|
||||
// Truncate long values in logs for readability
|
||||
const displayValue =
|
||||
stringValue.length > 100
|
||||
? `${stringValue.slice(0, 97)}...`
|
||||
: stringValue;
|
||||
|
||||
core.setOutput(sanitizedKey, stringValue);
|
||||
core.info(`✓ ${sanitizedKey}=${displayValue}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = `Failed to parse structured outputs: ${error}`;
|
||||
core.setFailed(errorMsg);
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
export async function runClaude(promptPath: string, options: ClaudeOptions) {
|
||||
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
|
||||
try {
|
||||
await unlink(PIPE_PATH);
|
||||
@@ -353,23 +395,13 @@ export async function runClaude(promptPath: string, options: ClaudeOptions) {
|
||||
core.warning(`Failed to process output for execution metrics: ${e}`);
|
||||
}
|
||||
|
||||
core.setOutput("conclusion", "success");
|
||||
core.setOutput("execution_file", EXECUTION_FILE);
|
||||
|
||||
// Parse and set structured outputs only if user provided --json-schema in claude_args
|
||||
if (hasJsonSchema) {
|
||||
try {
|
||||
// Parse and set structured outputs only if user provided json_schema
|
||||
if (process.env.JSON_SCHEMA) {
|
||||
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 {
|
||||
core.setOutput("conclusion", "failure");
|
||||
|
||||
|
||||
@@ -1,50 +1,39 @@
|
||||
/**
|
||||
* Validates the environment variables required for running Claude Code
|
||||
* based on the selected provider (Anthropic API, AWS Bedrock, Google Vertex AI, or Microsoft Foundry)
|
||||
* based on the selected provider (Anthropic API, AWS Bedrock, or Google Vertex AI)
|
||||
*/
|
||||
export function validateEnvironmentVariables() {
|
||||
const useBedrock = process.env.CLAUDE_CODE_USE_BEDROCK === "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 claudeCodeOAuthToken = process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
||||
|
||||
const errors: string[] = [];
|
||||
|
||||
// Check for mutual exclusivity between providers
|
||||
const activeProviders = [useBedrock, useVertex, useFoundry].filter(Boolean);
|
||||
if (activeProviders.length > 1) {
|
||||
if (useBedrock && useVertex) {
|
||||
errors.push(
|
||||
"Cannot use multiple providers simultaneously. Please set only one of: CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY.",
|
||||
"Cannot use both Bedrock and Vertex AI simultaneously. Please set only one provider.",
|
||||
);
|
||||
}
|
||||
|
||||
if (!useBedrock && !useVertex && !useFoundry) {
|
||||
if (!useBedrock && !useVertex) {
|
||||
if (!anthropicApiKey && !claudeCodeOAuthToken) {
|
||||
errors.push(
|
||||
"Either ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN is required when using direct Anthropic API.",
|
||||
);
|
||||
}
|
||||
} else if (useBedrock) {
|
||||
const awsRegion = process.env.AWS_REGION;
|
||||
const awsAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
|
||||
const awsSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
|
||||
const awsBearerToken = process.env.AWS_BEARER_TOKEN_BEDROCK;
|
||||
const requiredBedrockVars = {
|
||||
AWS_REGION: process.env.AWS_REGION,
|
||||
AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID,
|
||||
AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
};
|
||||
|
||||
// AWS_REGION is always required for Bedrock
|
||||
if (!awsRegion) {
|
||||
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.",
|
||||
);
|
||||
Object.entries(requiredBedrockVars).forEach(([key, value]) => {
|
||||
if (!value) {
|
||||
errors.push(`${key} is required when using AWS Bedrock.`);
|
||||
}
|
||||
});
|
||||
} else if (useVertex) {
|
||||
const requiredVertexVars = {
|
||||
ANTHROPIC_VERTEX_PROJECT_ID: process.env.ANTHROPIC_VERTEX_PROJECT_ID,
|
||||
@@ -56,16 +45,6 @@ export function validateEnvironmentVariables() {
|
||||
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) {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { describe, test, expect, afterEach, beforeEach, spyOn } from "bun:test";
|
||||
import { describe, test, expect, afterEach } 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";
|
||||
|
||||
// Import the type for testing
|
||||
type ExecutionMessage = {
|
||||
type: string;
|
||||
structured_output?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
// Mock execution file path
|
||||
const TEST_EXECUTION_FILE = join(tmpdir(), "test-execution-output.json");
|
||||
@@ -15,9 +19,9 @@ async function createMockExecutionFile(
|
||||
structuredOutput?: Record<string, unknown>,
|
||||
includeResult: boolean = true,
|
||||
): Promise<void> {
|
||||
const messages: any[] = [
|
||||
{ type: "system", subtype: "init" },
|
||||
{ type: "turn", content: "test" },
|
||||
const messages: ExecutionMessage[] = [
|
||||
{ type: "system", subtype: "init" } as any,
|
||||
{ type: "turn", content: "test" } as any,
|
||||
];
|
||||
|
||||
if (includeResult) {
|
||||
@@ -26,25 +30,14 @@ async function createMockExecutionFile(
|
||||
cost_usd: 0.01,
|
||||
duration_ms: 1000,
|
||||
structured_output: structuredOutput,
|
||||
});
|
||||
} as any);
|
||||
}
|
||||
|
||||
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", () => {
|
||||
describe("Structured Output - Pure Functions", () => {
|
||||
afterEach(async () => {
|
||||
setOutputSpy?.mockRestore();
|
||||
infoSpy?.mockRestore();
|
||||
try {
|
||||
await unlink(TEST_EXECUTION_FILE);
|
||||
} catch {
|
||||
@@ -52,107 +45,297 @@ describe("parseAndSetStructuredOutputs", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("should set structured_output with valid data", async () => {
|
||||
await createMockExecutionFile({
|
||||
is_flaky: true,
|
||||
confidence: 0.85,
|
||||
summary: "Test looks flaky",
|
||||
describe("sanitizeOutputName", () => {
|
||||
test("should keep valid characters", () => {
|
||||
const sanitize = (name: string) => name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
expect(sanitize("valid_name-123")).toBe("valid_name-123");
|
||||
});
|
||||
|
||||
await parseAndSetStructuredOutputs(TEST_EXECUTION_FILE);
|
||||
test("should replace invalid characters with underscores", () => {
|
||||
const sanitize = (name: string) => name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
expect(sanitize("invalid@name!")).toBe("invalid_name_");
|
||||
expect(sanitize("has spaces")).toBe("has_spaces");
|
||||
expect(sanitize("has.dots")).toBe("has_dots");
|
||||
});
|
||||
|
||||
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 special characters", () => {
|
||||
const sanitize = (name: string) => name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
expect(sanitize("$field%name&")).toBe("_field_name_");
|
||||
expect(sanitize("field[0]")).toBe("field_0_");
|
||||
});
|
||||
});
|
||||
|
||||
describe("convertToString", () => {
|
||||
const convertToString = (value: unknown): string => {
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
return value;
|
||||
case "boolean":
|
||||
case "number":
|
||||
return String(value);
|
||||
case "object":
|
||||
return value === null ? "" : JSON.stringify(value);
|
||||
default:
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
};
|
||||
|
||||
test("should keep strings as-is", () => {
|
||||
expect(convertToString("hello")).toBe("hello");
|
||||
expect(convertToString("")).toBe("");
|
||||
});
|
||||
|
||||
test("should convert booleans to strings", () => {
|
||||
expect(convertToString(true)).toBe("true");
|
||||
expect(convertToString(false)).toBe("false");
|
||||
});
|
||||
|
||||
test("should convert numbers to strings", () => {
|
||||
expect(convertToString(42)).toBe("42");
|
||||
expect(convertToString(3.14)).toBe("3.14");
|
||||
expect(convertToString(0)).toBe("0");
|
||||
});
|
||||
|
||||
test("should convert null to empty string", () => {
|
||||
expect(convertToString(null)).toBe("");
|
||||
});
|
||||
|
||||
test("should JSON stringify objects", () => {
|
||||
expect(convertToString({ foo: "bar" })).toBe('{"foo":"bar"}');
|
||||
});
|
||||
|
||||
test("should JSON stringify arrays", () => {
|
||||
expect(convertToString([1, 2, 3])).toBe("[1,2,3]");
|
||||
expect(convertToString(["a", "b"])).toBe('["a","b"]');
|
||||
});
|
||||
|
||||
test("should handle nested structures", () => {
|
||||
const nested = { items: [{ id: 1, name: "test" }] };
|
||||
expect(convertToString(nested)).toBe(
|
||||
'{"items":[{"id":1,"name":"test"}]}',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle arrays and nested objects", async () => {
|
||||
describe("parseAndSetStructuredOutputs integration", () => {
|
||||
test("should parse and set simple structured outputs", async () => {
|
||||
await createMockExecutionFile({
|
||||
items: ["a", "b", "c"],
|
||||
config: { key: "value", nested: { deep: true } },
|
||||
is_antonly: true,
|
||||
confidence: 0.95,
|
||||
risk: "low",
|
||||
});
|
||||
|
||||
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",
|
||||
// In a real test, we'd import and call parseAndSetStructuredOutputs
|
||||
// For now, we simulate the behavior
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = messages.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result?.structured_output).toEqual({
|
||||
is_antonly: true,
|
||||
confidence: 0.95,
|
||||
risk: "low",
|
||||
});
|
||||
});
|
||||
|
||||
test("should throw error when no result message exists", async () => {
|
||||
test("should handle array outputs", async () => {
|
||||
await createMockExecutionFile({
|
||||
affected_areas: ["auth", "database", "api"],
|
||||
severity: "high",
|
||||
});
|
||||
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = messages.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result?.structured_output?.affected_areas).toEqual([
|
||||
"auth",
|
||||
"database",
|
||||
"api",
|
||||
]);
|
||||
});
|
||||
|
||||
test("should handle nested objects", async () => {
|
||||
await createMockExecutionFile({
|
||||
analysis: {
|
||||
category: "test",
|
||||
details: { count: 5, passed: true },
|
||||
},
|
||||
});
|
||||
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = messages.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result?.structured_output?.analysis).toEqual({
|
||||
category: "test",
|
||||
details: { count: 5, passed: true },
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle missing structured_output", async () => {
|
||||
await createMockExecutionFile(undefined, true);
|
||||
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = messages.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should handle empty structured_output", async () => {
|
||||
await createMockExecutionFile({});
|
||||
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = messages.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result?.structured_output).toEqual({});
|
||||
});
|
||||
|
||||
test("should handle all supported types", async () => {
|
||||
await createMockExecutionFile({
|
||||
string_field: "hello",
|
||||
number_field: 42,
|
||||
boolean_field: true,
|
||||
null_field: null,
|
||||
array_field: [1, 2, 3],
|
||||
object_field: { nested: "value" },
|
||||
});
|
||||
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = messages.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result?.structured_output).toMatchObject({
|
||||
string_field: "hello",
|
||||
number_field: 42,
|
||||
boolean_field: true,
|
||||
null_field: null,
|
||||
array_field: [1, 2, 3],
|
||||
object_field: { nested: "value" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("output naming with prefix", () => {
|
||||
test("should apply prefix correctly", () => {
|
||||
const prefix = "CLAUDE_";
|
||||
const key = "is_antonly";
|
||||
const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const outputName = prefix + sanitizedKey;
|
||||
|
||||
expect(outputName).toBe("CLAUDE_is_antonly");
|
||||
});
|
||||
|
||||
test("should handle empty prefix", () => {
|
||||
const prefix = "";
|
||||
const key = "result";
|
||||
const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const outputName = prefix + sanitizedKey;
|
||||
|
||||
expect(outputName).toBe("result");
|
||||
});
|
||||
|
||||
test("should sanitize and prefix invalid keys", () => {
|
||||
const prefix = "OUT_";
|
||||
const key = "invalid@key!";
|
||||
const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const outputName = prefix + sanitizedKey;
|
||||
|
||||
expect(outputName).toBe("OUT_invalid_key_");
|
||||
});
|
||||
});
|
||||
|
||||
describe("error scenarios", () => {
|
||||
test("should handle malformed JSON", async () => {
|
||||
await writeFile(TEST_EXECUTION_FILE, "invalid json {");
|
||||
|
||||
let error: Error | undefined;
|
||||
try {
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
JSON.parse(content);
|
||||
} catch (e) {
|
||||
error = e as Error;
|
||||
}
|
||||
|
||||
expect(error).toBeDefined();
|
||||
expect(error?.message).toContain("JSON");
|
||||
});
|
||||
|
||||
test("should handle empty execution file", async () => {
|
||||
await writeFile(TEST_EXECUTION_FILE, "[]");
|
||||
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const messages = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = messages.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should handle missing result message", 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",
|
||||
const content = await Bun.file(TEST_EXECUTION_FILE).text();
|
||||
const parsed = JSON.parse(content) as ExecutionMessage[];
|
||||
const result = parsed.find(
|
||||
(m) => m.type === "result" && m.structured_output,
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test("should throw error with malformed JSON", async () => {
|
||||
await writeFile(TEST_EXECUTION_FILE, "{ invalid json");
|
||||
describe("value truncation in logs", () => {
|
||||
test("should truncate long string values for display", () => {
|
||||
const longValue = "a".repeat(150);
|
||||
const displayValue =
|
||||
longValue.length > 100 ? `${longValue.slice(0, 97)}...` : longValue;
|
||||
|
||||
await expect(
|
||||
parseAndSetStructuredOutputs(TEST_EXECUTION_FILE),
|
||||
).rejects.toThrow();
|
||||
expect(displayValue).toBe("a".repeat(97) + "...");
|
||||
expect(displayValue.length).toBe(100);
|
||||
});
|
||||
|
||||
test("should throw error when file does not exist", async () => {
|
||||
await expect(
|
||||
parseAndSetStructuredOutputs("/nonexistent/file.json"),
|
||||
).rejects.toThrow();
|
||||
test("should not truncate short values", () => {
|
||||
const shortValue = "short";
|
||||
const displayValue =
|
||||
shortValue.length > 100 ? `${shortValue.slice(0, 97)}...` : shortValue;
|
||||
|
||||
expect(displayValue).toBe("short");
|
||||
});
|
||||
|
||||
test("should handle empty structured_output object", async () => {
|
||||
await createMockExecutionFile({});
|
||||
test("should truncate exactly 100 character values", () => {
|
||||
const value = "a".repeat(100);
|
||||
const displayValue =
|
||||
value.length > 100 ? `${value.slice(0, 97)}...` : value;
|
||||
|
||||
await parseAndSetStructuredOutputs(TEST_EXECUTION_FILE);
|
||||
expect(displayValue).toBe(value);
|
||||
});
|
||||
|
||||
expect(setOutputSpy).toHaveBeenCalledWith("structured_output", "{}");
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
"Set structured_output with 0 field(s)",
|
||||
);
|
||||
test("should truncate 101 character values", () => {
|
||||
const value = "a".repeat(101);
|
||||
const displayValue =
|
||||
value.length > 100 ? `${value.slice(0, 97)}...` : value;
|
||||
|
||||
expect(displayValue).toBe("a".repeat(97) + "...");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,19 +13,15 @@ describe("validateEnvironmentVariables", () => {
|
||||
delete process.env.ANTHROPIC_API_KEY;
|
||||
delete process.env.CLAUDE_CODE_USE_BEDROCK;
|
||||
delete process.env.CLAUDE_CODE_USE_VERTEX;
|
||||
delete process.env.CLAUDE_CODE_USE_FOUNDRY;
|
||||
delete process.env.AWS_REGION;
|
||||
delete process.env.AWS_ACCESS_KEY_ID;
|
||||
delete process.env.AWS_SECRET_ACCESS_KEY;
|
||||
delete process.env.AWS_SESSION_TOKEN;
|
||||
delete process.env.AWS_BEARER_TOKEN_BEDROCK;
|
||||
delete process.env.ANTHROPIC_BEDROCK_BASE_URL;
|
||||
delete process.env.ANTHROPIC_VERTEX_PROJECT_ID;
|
||||
delete process.env.CLOUD_ML_REGION;
|
||||
delete process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
||||
delete process.env.ANTHROPIC_VERTEX_BASE_URL;
|
||||
delete process.env.ANTHROPIC_FOUNDRY_RESOURCE;
|
||||
delete process.env.ANTHROPIC_FOUNDRY_BASE_URL;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -96,58 +92,31 @@ describe("validateEnvironmentVariables", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should fail when only AWS_SECRET_ACCESS_KEY is provided without bearer token", () => {
|
||||
test("should fail when AWS_ACCESS_KEY_ID is missing", () => {
|
||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||
process.env.AWS_REGION = "us-east-1";
|
||||
process.env.AWS_SECRET_ACCESS_KEY = "test-secret-key";
|
||||
|
||||
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.",
|
||||
"AWS_ACCESS_KEY_ID is required when using AWS Bedrock.",
|
||||
);
|
||||
});
|
||||
|
||||
test("should fail when only AWS_ACCESS_KEY_ID is provided without bearer token", () => {
|
||||
test("should fail when AWS_SECRET_ACCESS_KEY is missing", () => {
|
||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||
process.env.AWS_REGION = "us-east-1";
|
||||
process.env.AWS_ACCESS_KEY_ID = "test-access-key";
|
||||
|
||||
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.",
|
||||
"AWS_SECRET_ACCESS_KEY is required when using AWS Bedrock.",
|
||||
);
|
||||
});
|
||||
|
||||
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", () => {
|
||||
test("should report all missing Bedrock variables", () => {
|
||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||
|
||||
expect(() => validateEnvironmentVariables()).toThrow(
|
||||
/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,
|
||||
/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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -198,56 +167,6 @@ 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", () => {
|
||||
test("should fail when both Bedrock and Vertex are enabled", () => {
|
||||
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
|
||||
@@ -260,51 +179,7 @@ describe("validateEnvironmentVariables", () => {
|
||||
process.env.CLOUD_ML_REGION = "us-central1";
|
||||
|
||||
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 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.",
|
||||
"Cannot use both Bedrock and Vertex AI simultaneously. Please set only one provider.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -329,7 +204,10 @@ describe("validateEnvironmentVariables", () => {
|
||||
" - AWS_REGION is required when using AWS Bedrock.",
|
||||
);
|
||||
expect(error!.message).toContain(
|
||||
" - Either AWS_BEARER_TOKEN_BEDROCK or both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required when using AWS Bedrock.",
|
||||
" - AWS_ACCESS_KEY_ID is required when using AWS Bedrock.",
|
||||
);
|
||||
expect(error!.message).toContain(
|
||||
" - AWS_SECRET_ACCESS_KEY is required when using AWS Bedrock.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
# Cloud Providers
|
||||
|
||||
You can authenticate with Claude using any of these four methods:
|
||||
You can authenticate with Claude using any of these three methods:
|
||||
|
||||
1. Direct Anthropic API (default)
|
||||
2. Amazon Bedrock 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).
|
||||
|
||||
**Note**:
|
||||
|
||||
- Bedrock, Vertex, and Microsoft Foundry use OIDC authentication exclusively
|
||||
- Bedrock and Vertex use OIDC authentication exclusively
|
||||
- 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
|
||||
|
||||
@@ -41,19 +40,11 @@ Use provider-specific model names based on your chosen provider:
|
||||
claude_args: |
|
||||
--model claude-4-0-sonnet@20250805
|
||||
# ... 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 Cloud Providers
|
||||
## OIDC Authentication for Bedrock and Vertex
|
||||
|
||||
AWS Bedrock, GCP Vertex AI, and Microsoft Foundry all support OIDC authentication.
|
||||
Both AWS Bedrock and GCP Vertex AI require OIDC authentication.
|
||||
|
||||
```yaml
|
||||
# For AWS Bedrock with OIDC
|
||||
@@ -106,36 +97,3 @@ AWS Bedrock, GCP Vertex AI, and Microsoft Foundry all support OIDC authenticatio
|
||||
permissions:
|
||||
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).
|
||||
|
||||
@@ -38,7 +38,7 @@ The following permissions are requested but not yet actively used. These will en
|
||||
|
||||
## Commit Signing
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## ⚠️ Authentication Protection
|
||||
|
||||
|
||||
@@ -185,74 +185,6 @@ For a comprehensive guide on migrating from v0.x to v1.0, including step-by-step
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
@@ -43,23 +43,38 @@ jobs:
|
||||
- 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"]}'
|
||||
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
|
||||
steps.detect.outputs.is_flaky == 'true' &&
|
||||
steps.detect.outputs.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 "🔄 Flaky test detected (confidence: ${{ steps.detect.outputs.confidence }})"
|
||||
echo "Summary: ${{ steps.detect.outputs.summary }}"
|
||||
echo ""
|
||||
echo "Triggering automatic retry..."
|
||||
|
||||
@@ -69,13 +84,10 @@ jobs:
|
||||
# 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
|
||||
steps.detect.outputs.is_flaky == 'true' &&
|
||||
steps.detect.outputs.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 "⚠️ Possible flaky test but confidence too low (${{ steps.detect.outputs.confidence }})"
|
||||
echo "Not retrying automatically - manual review recommended"
|
||||
|
||||
# Comment on PR if this was a PR build
|
||||
@@ -84,29 +96,16 @@ jobs:
|
||||
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
|
||||
## ${{ steps.detect.outputs.is_flaky == 'true' && '🔄 Flaky Test Detected' || '❌ Test Failure' }}
|
||||
|
||||
**Analysis**: $SUMMARY
|
||||
**Confidence**: $CONFIDENCE
|
||||
**Analysis**: ${{ steps.detect.outputs.summary }}
|
||||
**Confidence**: ${{ steps.detect.outputs.confidence }}
|
||||
|
||||
$ACTION
|
||||
${{ steps.detect.outputs.is_flaky == 'true' && '✅ Automatically retrying the workflow' || '⚠️ This appears to be a real bug - manual intervention needed' }}
|
||||
|
||||
[View workflow run](${{ github.event.workflow_run.html_url }})
|
||||
EOF
|
||||
|
||||
@@ -149,6 +149,19 @@ export const agentMode: Mode = {
|
||||
claudeArgs = `--mcp-config '${escapedOurConfig}'`;
|
||||
}
|
||||
|
||||
// Add JSON schema if provided
|
||||
const jsonSchema = process.env.JSON_SCHEMA || "";
|
||||
if (jsonSchema) {
|
||||
// Validate it's valid JSON
|
||||
try {
|
||||
JSON.parse(jsonSchema);
|
||||
} catch (e) {
|
||||
throw new Error(`Invalid JSON schema provided: ${e}`);
|
||||
}
|
||||
const escapedSchema = jsonSchema.replace(/'/g, "'\\''");
|
||||
claudeArgs += ` --json-schema '${escapedSchema}'`;
|
||||
}
|
||||
|
||||
// Append user's claude_args (which may have more --mcp-config flags)
|
||||
claudeArgs = `${claudeArgs} ${userClaudeArgs}`.trim();
|
||||
|
||||
|
||||
@@ -177,6 +177,19 @@ export const tagMode: Mode = {
|
||||
// Add required tools for tag mode
|
||||
claudeArgs += ` --allowedTools "${tagModeTools.join(",")}"`;
|
||||
|
||||
// Add JSON schema if provided
|
||||
const jsonSchema = process.env.JSON_SCHEMA || "";
|
||||
if (jsonSchema) {
|
||||
// Validate it's valid JSON
|
||||
try {
|
||||
JSON.parse(jsonSchema);
|
||||
} catch (e) {
|
||||
throw new Error(`Invalid JSON schema provided: ${e}`);
|
||||
}
|
||||
const escapedSchema = jsonSchema.replace(/'/g, "'\\''");
|
||||
claudeArgs += ` --json-schema '${escapedSchema}'`;
|
||||
}
|
||||
|
||||
// Append user's claude_args (which may have more --mcp-config flags)
|
||||
if (userClaudeArgs) {
|
||||
claudeArgs += ` ${userClaudeArgs}`;
|
||||
|
||||
Reference in New Issue
Block a user