feat: add Agent SDK support with USE_AGENT_SDK feature flag (#698)

* feat: add Agent SDK support with USE_AGENT_SDK feature flag

Add a feature-flagged code path that uses the Agent SDK instead of
spawning the CLI as a subprocess. When USE_AGENT_SDK=true is set,
the new SDK path is used; otherwise, existing CLI behavior is unchanged.

Changes:
- Add parse-sdk-options.ts for parsing ClaudeOptions into SDK format
- Add run-claude-sdk.ts for SDK execution with query() function
- Update run-claude.ts with feature flag check at entry point
- Update update-comment-link.ts to handle both cost_usd and total_cost_usd
- Add @anthropic-ai/claude-agent-sdk dependency

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: simplify SDK types by using @anthropic-ai/claude-agent-sdk types directly

- Remove duplicate SdkRunOptions and McpStdioServerConfig types
- Use SDK's Options and McpStdioServerConfig types directly
- Return { sdkOptions, showFullOutput, hasJsonSchema } from parseSdkOptions
- Remove unnecessary convertMcpServers function
- Net reduction of ~70 lines

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: use extraArgs for claudeArgs pass-through to CLI

Simplify option parsing by converting claudeArgs to extraArgs record
and letting the SDK/CLI handle --mcp-config, --json-schema, etc.

- Remove extractJsonSchema and parseMcpConfigs functions
- Add parseClaudeArgsToExtraArgs for simple flag parsing
- CLI handles complex args like --mcp-config directly

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* ci

* refactor: remove hardcoded permission bypass flags

The SDK path should match CLI path behavior - permissions are handled
by the CLI itself, not hardcoded in the action.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: add logging for SDK vs CLI path selection

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Ashwin Bhat
2025-12-03 17:22:04 -08:00
committed by GitHub
parent 90da6b6e15
commit 469fc9c1a4
12 changed files with 402 additions and 8 deletions

View File

@@ -0,0 +1,105 @@
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;
};
/**
* Parse claudeArgs string into extraArgs record for SDK pass-through
* The SDK/CLI will handle --mcp-config, --json-schema, etc.
*/
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("--")) {
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;
// 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
let systemPrompt: SdkOptions["systemPrompt"];
if (options.systemPrompt) {
systemPrompt = options.systemPrompt;
} else if (options.appendSystemPrompt) {
systemPrompt = {
type: "preset",
preset: "claude_code",
append: options.appendSystemPrompt,
};
}
// Build SDK options - use direct options for explicit inputs, extraArgs for claudeArgs pass-through
const sdkOptions: SdkOptions = {
// Direct options from ClaudeOptions inputs
model: options.model,
maxTurns: options.maxTurns ? parseInt(options.maxTurns, 10) : undefined,
allowedTools: options.allowedTools
? options.allowedTools.split(",").map((t) => t.trim())
: undefined,
disallowedTools: options.disallowedTools
? options.disallowedTools.split(",").map((t) => t.trim())
: undefined,
systemPrompt,
fallbackModel: options.fallbackModel,
pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable,
// Pass through claudeArgs as extraArgs - CLI handles --mcp-config, --json-schema, etc.
extraArgs,
env,
};
return {
sdkOptions,
showFullOutput,
hasJsonSchema,
};
}

View File

@@ -0,0 +1,148 @@
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}`);
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);
}
}

View File

@@ -5,6 +5,8 @@ import { unlink, writeFile, stat, readFile } from "fs/promises";
import { createWriteStream } from "fs";
import { spawn } from "child_process";
import { parse as parseShellArgs } from "shell-quote";
import { runClaudeWithSdk } from "./run-claude-sdk";
import { parseSdkOptions } from "./parse-sdk-options";
const execAsync = promisify(exec);
@@ -165,6 +167,17 @@ export async function parseAndSetStructuredOutputs(
}
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);
// Detect if --json-schema is present in claude args