Compare commits

..
2 Commits
Author SHA1 Message Date
GitHub Actions b5e37652b7 chore: bump Claude Code to 2.1.331 and Agent SDK to 0.3.331 2026-11-23 21:35:39 +00:00
423df53bc5 Stop the session and revoke the app token when a run is cancelled (#2112)
* Stop the session and revoke the app token when a run is cancelled

The runner signals only the step's own process, which was bash, so Bun and the
session kept running and the step that revokes the app token was skipped. Bun now
replaces bash, and on a cancel it stops what the session started, restores the files
later steps trust and writes its outputs.

Co-authored-by: mhegazy <[email protected]>

* Log only the code of an error in the cancel cleanup

Also handle the signal that the Windows runner sends second.

Co-authored-by: mhegazy <[email protected]>

* Reflow a comment

Co-authored-by: mhegazy <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-11-23 13:13:10 -08:00
13 changed files with 533 additions and 56 deletions
+7 -10
View File
@@ -289,16 +289,13 @@ runs:
# takes its settings from the action's directory. Bun before 1.4.3 logs
# "directory mismatch" for --tsconfig-override (oven-sh/bun#25730).
#
# Bash reads this script as it runs. The braces and exit make it read the
# rest first and stop there. With exec instead, cancelling the run would
# interrupt Bun at once, before it can clean up.
{
bun --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts
exit
}
# Bash reads this script as it runs, so exec also keeps it from running what a
# session adds. When the run is cancelled, the runner signals only this step's
# own process, and Bun has to get that signal to stop the session.
exec bun --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts
env:
# Turns off Bun's cache of transpiled files, which is outside the action's
# directory. Set it wherever the action runs its own scripts.
+5 -8
View File
@@ -147,7 +147,7 @@ runs:
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
run: |
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
CLAUDE_CODE_VERSION="2.1.330"
CLAUDE_CODE_VERSION="2.1.331"
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
for attempt in 1 2 3; do
echo "Installation attempt $attempt..."
@@ -183,13 +183,10 @@ runs:
echo "Changing directory to CLAUDE_WORKING_DIR: $CLAUDE_WORKING_DIR"
cd "$CLAUDE_WORKING_DIR"
fi
# Bash reads this script as it runs. The braces and exit make it read the
# rest first and stop there. With exec instead, cancelling the run would
# interrupt Bun at once, before it can clean up.
{
bun run ${GITHUB_ACTION_PATH}/src/index.ts
exit
}
# Bash reads this script as it runs, so exec also keeps it from running what a
# session adds. When the run is cancelled, the runner signals only this step's
# own process, and Bun has to get that signal to stop the session.
exec bun run ${GITHUB_ACTION_PATH}/src/index.ts
env:
# Turns off Bun's cache of transpiled files, which is outside the action's
# directory
+10 -10
View File
@@ -6,7 +6,7 @@
"name": "@anthropic-ai/claude-code-base-action",
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
"shell-quote": "^1.8.4",
},
"devDependencies": {
@@ -27,23 +27,23 @@
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]0", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.330" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-7om9Xus6tfkeCUCfzg6ilJuN6Z7okkEvJ0mx+ukXa/Id5U/6BGtPkOYni+3ebedwa3b9SVF7A05+ln+/9EoU/w=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]1", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.331" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-ml/MPqgO95tG5zcApBFxEyoDk57d9htP09R8AtPbKPUCHpsobf84IjkN4zhGvQgk8zsA9dXoeMGrQcCc8gQE/w=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J9nqvcfD2V90O5uoR8At66R51VYtSMKnxSmPc0S4A4F5oX1VbokcpJLXU1yVCOuTtzr/OIHjRr9nn2vKi/S6rQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "x64" }, "sha512-woe+f9qeZYWML5fACibNyth0xMDf22riNRNDryIYuhdteh7IoWrK6zC31cC2MrZRoqDZcPVtfOLND79+iZbrLA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-2Q+kfzaoTvJv1rsyu+iR4UHDZ3nxiOfdXISk+2ydQShU9DqXNlgQAt3BdJMh0Yx4MrxB66TMphVvVQeRslwwhA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-fXmuAEegw31v+kiBd51yn7RVhjs7Rz2lnhfx/+XJXqt5lyqR2v7Ul/U/9r1CQZKuIw8M3ms9jQqGpmKbgKndqQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9w4uMdA3vNZXocwOUhivOGotXoRDxN/C/xPMkZMY9WPpKLAlj8upMZskNgPjQKlVRXhxPfNagcBijGPUH4WepA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kooZMdp6tFwNFkDXbGoNTZMgFcPQfJVfG+gZ2qAdkk11S6MFts9ybHRLQmzUK3VrqlahH7T9fmI2mNfzYgOXkw=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "arm64" }, "sha512-6jscch7vk/XBSn7mm1i6zwTeiz05q98nKrQ3HdTavQEDGvXycMcB/QxIdMrs3vrdNEjWuoxwrL1qlT1lOyAWLg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "x64" }, "sha512-ooThWbUXlXKTDgj2VgWBXQ/6vSOTaAbBDWPvvCGNHi20haoSkw4uPX9gczkX+HJuVTslvvLiYIfe8zleVPzi7A=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "x64" }, "sha512-AsLur4ov9MGTQTrnZ49ZDPasQ35U3X/rZDdF/rPhytN3h1F3w/0IkC6esW3OzldvPlci60QvggOLVGnFlUzdxw=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
+1 -1
View File
@@ -11,7 +11,7 @@
},
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
"shell-quote": "^1.8.4"
},
"devDependencies": {
+146
View File
@@ -0,0 +1,146 @@
import { spawnSync } from "child_process";
import { readdirSync, readFileSync } from "fs";
// The runner sends SIGINT, SIGTERM after 7.5 seconds, and kills the step 2.5 seconds
// later, so a cancel that starts with SIGTERM has to fit into that.
const GRACE_MS = 1000;
const PAUSE_MS = 500;
const POLL_MS = 50;
type Process = { pid: number; parent: number };
function listProcesses(): Process[] {
if (process.platform === "linux") {
return readdirSync("/proc")
.filter((name) => /^\d+$/.test(name))
.flatMap((name) => {
try {
const stat = readFileSync(`/proc/${name}/stat`, "utf8");
// The command's name comes before these fields and can hold anything.
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
const threads = Number(fields[17]);
// This process can't reap its children while it waits for them. One whose
// first thread has ended, but not its others, is a zombie here too.
if (fields[0] === "Z" && threads <= 1) return [];
return [{ pid: Number(name), parent: Number(fields[1]) }];
} catch {
return []; // It has ended
}
});
}
if (process.platform === "win32") return []; // The runner's Ctrl+C reaches these
// By path, because a session may be able to write to a directory in PATH
const ps = spawnSync("/bin/ps", ["-A", "-o", "pid=,ppid=,state="], {
encoding: "utf8",
});
if (ps.error) throw ps.error;
if (ps.status !== 0) throw new Error("ps failed");
return ps.stdout.split("\n").flatMap((line) => {
const [pid, parent, state] = line.trim().split(/\s+/);
if (!pid || Number(pid) === ps.pid || state!.startsWith("Z")) return [];
return [{ pid: Number(pid), parent: Number(parent) }];
});
}
/** What these processes have started, and they themselves, if still running. */
function listTree(roots: Iterable<number>): Set<number> {
const processes = listProcesses();
const running = new Set(processes.map(({ pid }) => pid));
const children = new Map<number, number[]>();
for (const { pid, parent } of processes) {
children.set(parent, [...(children.get(parent) ?? []), pid]);
}
const tree = new Set([...roots].filter((pid) => running.has(pid)));
// A set's iterator also visits what is added meanwhile.
for (const pid of tree)
children.get(pid)?.forEach((child) => tree.add(child));
tree.delete(process.pid);
return tree;
}
const cannotSignal = new Set<number>();
function signal(pids: Iterable<number>, name: NodeJS.Signals): void {
for (const pid of pids) {
try {
process.kill(pid, name);
} catch (error) {
if ((error as { code?: string }).code === "EPERM") cannotSignal.add(pid);
}
}
}
/**
* Stops everything this process started that is still in its process tree. Programs
* first get to clean up after themselves, as git does with its lock files. They are
* paused before each signal, because what a process starts while it is being stopped
* would leave the tree.
*/
export function stopDescendants(): void {
const known = new Set<number>();
// What one of these started stays known once that one has ended.
const update = () => {
const running = listTree([process.pid, ...known]);
known.clear();
running.forEach((pid) => known.add(pid));
return known;
};
const pause = () => {
const paused = new Set<number>();
for (const end = Date.now() + PAUSE_MS; Date.now() < end; ) {
const added = [...update()].filter((pid) => !paused.has(pid));
if (added.length === 0) return;
signal(added, "SIGSTOP");
added.forEach((pid) => paused.add(pid));
}
};
try {
pause();
signal(known, "SIGTERM");
signal(known, "SIGCONT");
for (const end = Date.now() + GRACE_MS; Date.now() < end; ) {
if (update().size === 0) return;
Bun.sleepSync(POLL_MS);
}
pause();
} finally {
// Also when the processes can't be listed, so that none stays paused.
signal(known, "SIGKILL");
const left = [...known].filter((pid) => cannotSignal.has(pid));
if (left.length > 0) {
console.log(
`::warning::Processes of another user could not be stopped: ${left.join(", ")}`,
);
}
}
}
/**
* Stops the session, cleans up and exits when the run is cancelled or times out. The
* steps are synchronous, and each runs whether or not the ones before it failed. Once
* isFinishing returns true, only the runner's second signal does this.
*/
export function onCancel(
steps: (() => void)[],
isFinishing: () => boolean = () => false,
): void {
let cancelled = false;
const cancel = (name: NodeJS.Signals) => {
if (cancelled || (name === "SIGINT" && isFinishing())) return;
cancelled = true;
for (const step of [stopDescendants, ...steps]) {
try {
step();
} catch (error) {
// A message could hold anything, such as a value that was being written.
const { code, name } = error as { code?: string; name?: string };
console.error(`Error cleaning up the cancelled run (${code ?? name})`);
}
}
process.exit(130);
};
process.on("SIGINT", cancel);
process.on("SIGTERM", cancel);
process.on("SIGBREAK", cancel); // The runner's second signal on Windows
}
+10
View File
@@ -6,6 +6,7 @@ import { runClaude } from "./run-claude";
import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
import { validateEnvironmentVariables } from "./validate-env";
import { installPlugins } from "./install-plugins";
import { onCancel } from "./cancel";
import { setExecutionFileOutputIfPresent } from "./execution-file";
import { setupWorkloadIdentity } from "./workload-identity";
import type { WorkloadIdentityHandle } from "./workload-identity";
@@ -15,6 +16,14 @@ async function run() {
delete process.env.BUN_RUNTIME_TRANSPILER_CACHE_PATH;
let workloadIdentity: WorkloadIdentityHandle | undefined;
let isFinishing = false;
onCancel(
[
() => workloadIdentity?.stop(),
() => isFinishing || core.setOutput("conclusion", "failure"),
],
() => isFinishing,
);
try {
// When workload identity federation is configured, fetch the GitHub OIDC
// identity token and expose it to the CLI before validating auth env vars.
@@ -62,6 +71,7 @@ async function run() {
});
// Set outputs for the standalone base-action
isFinishing = true;
core.setOutput("conclusion", result.conclusion);
if (result.executionFile) {
core.setOutput("execution_file", result.executionFile);
+10 -10
View File
@@ -7,7 +7,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
@@ -37,23 +37,23 @@
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]0", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.330" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-7om9Xus6tfkeCUCfzg6ilJuN6Z7okkEvJ0mx+ukXa/Id5U/6BGtPkOYni+3ebedwa3b9SVF7A05+ln+/9EoU/w=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]1", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.331" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-ml/MPqgO95tG5zcApBFxEyoDk57d9htP09R8AtPbKPUCHpsobf84IjkN4zhGvQgk8zsA9dXoeMGrQcCc8gQE/w=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J9nqvcfD2V90O5uoR8At66R51VYtSMKnxSmPc0S4A4F5oX1VbokcpJLXU1yVCOuTtzr/OIHjRr9nn2vKi/S6rQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "x64" }, "sha512-woe+f9qeZYWML5fACibNyth0xMDf22riNRNDryIYuhdteh7IoWrK6zC31cC2MrZRoqDZcPVtfOLND79+iZbrLA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-2Q+kfzaoTvJv1rsyu+iR4UHDZ3nxiOfdXISk+2ydQShU9DqXNlgQAt3BdJMh0Yx4MrxB66TMphVvVQeRslwwhA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-fXmuAEegw31v+kiBd51yn7RVhjs7Rz2lnhfx/+XJXqt5lyqR2v7Ul/U/9r1CQZKuIw8M3ms9jQqGpmKbgKndqQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9w4uMdA3vNZXocwOUhivOGotXoRDxN/C/xPMkZMY9WPpKLAlj8upMZskNgPjQKlVRXhxPfNagcBijGPUH4WepA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kooZMdp6tFwNFkDXbGoNTZMgFcPQfJVfG+gZ2qAdkk11S6MFts9ybHRLQmzUK3VrqlahH7T9fmI2mNfzYgOXkw=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "arm64" }, "sha512-6jscch7vk/XBSn7mm1i6zwTeiz05q98nKrQ3HdTavQEDGvXycMcB/QxIdMrs3vrdNEjWuoxwrL1qlT1lOyAWLg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "x64" }, "sha512-ooThWbUXlXKTDgj2VgWBXQ/6vSOTaAbBDWPvvCGNHi20haoSkw4uPX9gczkX+HJuVTslvvLiYIfe8zleVPzi7A=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "x64" }, "sha512-AsLur4ov9MGTQTrnZ49ZDPasQ35U3X/rZDdF/rPhytN3h1F3w/0IkC6esW3OzldvPlci60QvggOLVGnFlUzdxw=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
+2 -2
View File
@@ -130,7 +130,7 @@ Bots often open pull requests from branches in your own repository. Runs there u
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on. What a session writes to `GITHUB_OUTPUT` and `GITHUB_STEP_SUMMARY` is kept, unless it replaced the file with a link or something else that isn't a file.
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is cancelled before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is killed before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
The action's own git commands use `safe.bareRepository=explicit` too. If the action starts in a bare repository, it doesn't set this before the session, unless `restrict_untrusted_prs` applies. On pull requests that `restrict_untrusted_prs` applies to, the action also checks out the pull request with `GIT_LFS_SKIP_SMUDGE=1`, so files that Git LFS hasn't downloaded yet stay as pointer files. The variable is set for that checkout only.
@@ -139,7 +139,7 @@ Claude's wrapper scripts for `git add`, `git rm`, `git commit` and `git push` al
This has limits:
- It is not a sandbox. Code running on the runner, for example through an allowed `npm test`, can stop the action before it restores anything, or change the files later steps run, including the code of this and other actions. An allow rule for `Write` can reach those files too, so treat it like allowing code to run.
- A run that is cancelled or times out during the session does not restore anything, and later `always()` and post steps still run.
- When a run is cancelled or times out during the session, the action stops Claude and what it started, restores these files and has the app token revoked. It also drops what the session wrote to `GITHUB_OUTPUT`. Later `always()` and post steps still run, and the tracking comment isn't updated. Processes that run as another user or no longer belong to one that Claude started keep running, and on Windows Claude itself can too. Nothing is restored or revoked when the action doesn't get the runner's signal, as in a job with `container:`, or can't react before the runner kills it, as during a long `git fetch`.
- Submodule config, a repository checked out to a subdirectory, and an `include.path` target that does not exist yet are not restored.
- The git settings need git 2.31 or newer, and `safe.bareRepository` needs 2.38. On older versions they have no effect.
+1 -1
View File
@@ -12,7 +12,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
+29 -4
View File
@@ -74,6 +74,7 @@ import { validateEnvironmentVariables } from "../../base-action/src/validate-env
import { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code-settings";
import { installPlugins } from "../../base-action/src/install-plugins";
import { preparePrompt } from "../../base-action/src/prepare-prompt";
import { onCancel } from "../../base-action/src/cancel";
import { runClaude } from "../../base-action/src/run-claude";
import type { ClaudeRunResult } from "../../base-action/src/run-claude-sdk";
import { setExecutionFileOutputIfPresent } from "../../base-action/src/execution-file";
@@ -109,7 +110,7 @@ async function installClaudeCode(): Promise<string> {
return customExecutable;
}
const claudeCodeVersion = "2.1.330";
const claudeCodeVersion = "2.1.331";
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
for (let attempt = 1; attempt <= 3; attempt++) {
@@ -202,6 +203,29 @@ async function run() {
let restoredConfigPaths: string[] = [];
// Track whether we've completed prepare phase, so we can attribute errors correctly
let prepareCompleted = false;
// Set while a session could be running
let restoreSessionFiles: ReturnType<typeof snapshotSessionFiles> | undefined;
let isFinishing = false;
// Revoking the app token depends on this output, and a session can write it.
const keepRevocationOn = () =>
core.setOutput("skipped_due_to_workflow_validation_mismatch", "false");
onCancel(
[
() => restoreSessionFiles?.({ cancelled: true }),
() => restoreSessionFiles && keepRevocationOn(),
// The step that revokes the app token reads it from here.
() => githubToken && core.setOutput("github_token", githubToken),
() => core.setOutput("branch_name", claudeBranch),
// A session can write this one too.
() => core.setOutput("conclusion", claudeSuccess ? "success" : "failure"),
clearSessionState,
() => workloadIdentity?.stop(),
],
() => isFinishing,
);
try {
// Phase 1: Prepare
const actionInputsPresent = collectActionInputsPresence();
@@ -430,7 +454,7 @@ async function run() {
process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
}
const restoreSessionFiles = snapshotSessionFiles(() =>
restoreSessionFiles = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: hooksOff }),
);
@@ -451,8 +475,8 @@ async function run() {
// The action's own git commands from here on hold the job's credentials,
// and the session could have edited a tracked hook.
disableGitPrograms({ hooks: true });
// Revoking the app token depends on this output, and a session can write it.
core.setOutput("skipped_due_to_workflow_validation_mismatch", "false");
keepRevocationOn();
restoreSessionFiles = undefined;
}
claudeSuccess = claudeResult.conclusion === "success";
@@ -480,6 +504,7 @@ async function run() {
core.setFailed(`Action failed with error: ${redactSecrets(errorMessage)}`);
} finally {
// Phase 4: Cleanup (always runs)
isFinishing = true;
clearSessionState();
// Stop refreshing the workload identity token file and delete the token
+13 -6
View File
@@ -216,28 +216,35 @@ function isItsOwnFile(before: FileSnapshot): boolean {
/**
* Records the files later steps trust, and returns a function that puts them
* back. Call the returned function as soon as the session ends and before the
* action runs git again. Replacing a file rather than writing to it means a
* session cannot redirect the write by swapping in a symlink.
* action runs git again. If the session was cancelled, that also drops the outputs it
* wrote, because a half-written one would take the action's own with it. Replacing a
* file rather than writing to it means a session cannot redirect the write by swapping
* in a symlink.
*
* This stops a session that can only write through its tools. It is not a
* sandbox: code running as the runner's user can stop the action before it
* restores anything.
*/
export function snapshotSessionFiles(beforeSession?: () => void): () => void {
export function snapshotSessionFiles(
beforeSession?: () => void,
): (options?: { cancelled: boolean }) => void {
const files = filesLaterStepsTrust();
const snapshots = files.map(readSnapshot);
// What the action changes for the session goes back too, without a warning.
beforeSession?.();
const atStart = files.map(readSnapshot);
return () => {
return ({ cancelled } = { cancelled: false }) => {
const restored: string[] = [];
for (const [index, before] of snapshots.entries()) {
try {
const now = readSnapshot(before);
if (before.keepsWrites && isItsOwnFile(before)) continue;
const dropsWrites = cancelled && before.label === "GITHUB_OUTPUT";
const ownFile = before.keepsWrites && isItsOwnFile(before);
if (ownFile && !dropsWrites) continue;
// The file it leads to can have the same content so far.
const leadsElsewhere = before.keepsWrites && now.state === "file";
const leadsElsewhere =
before.keepsWrites && !ownFile && now.state === "file";
if (!leadsElsewhere && isUnchanged(before, now)) continue;
const changedBySession =
leadsElsewhere || !isUnchanged(atStart[index]!, now);
+4 -4
View File
@@ -120,15 +120,15 @@ describe("action metadata", () => {
},
);
test("should let Bun finish when the shell is interrupted", async () => {
test("should let Bun clean up when the step is interrupted", async () => {
const { output, exitCode } = await runStep(
path,
`exec "${process.execPath}" -e 'console.log("started"); setTimeout(() => console.log("finished"), 500)'`,
`exec "${process.execPath}" -e 'process.once("SIGINT", () => { console.log("cleaned up"); process.exit(130) }); setTimeout(() => {}, 5000); console.log("started")'`,
true,
);
expect(output).toBe("started\nfinished\n");
expect(exitCode).toBe(0);
expect(output).toBe("started\ncleaned up\n");
expect(exitCode).toBe(130);
});
});
+295
View File
@@ -0,0 +1,295 @@
import { describe, expect, test } from "bun:test";
import { execFileSync } from "child_process";
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { join } from "path";
const isRunning = (pid: number) => {
try {
process.kill(pid, 0);
// A process that has ended but that nobody waited for still has an entry.
return !/^\S+ \(.*\) Z/s.test(readFileSync(`/proc/${pid}/stat`, "utf8"));
} catch (error) {
return (error as { code?: string }).code === "ENOENT"
? process.platform !== "linux"
: false;
}
};
async function until(condition: () => boolean, what: string) {
for (let i = 0; i < 200; i++) {
if (condition()) return;
await Bun.sleep(50);
}
throw new Error(`Timed out waiting for ${what}`);
}
// Like a session. Its child is in its own process group, and both ignore SIGTERM. A
// third process takes SIGTERM as git does, which removes its lock files.
const SESSION = `#!/bin/bash
trap '' TERM INT
perl -e 'use POSIX; POSIX::setsid(); sleep 300' &
child=$!
perl -e '$SIG{TERM} = sub { unlink "$ENV{TEST_DIR}/lock"; exit }; open(F, ">$ENV{TEST_DIR}/lock"); sleep 300' &
git_like=$!
echo "$$ $child $git_like" > "$TEST_DIR/pids"
until [ -e "$TEST_DIR/lock" ]; do sleep 0.05; done
echo 'ADDED=1' >> "$GITHUB_ENV"
printf '%s\\n' skipped_due_to_workflow_validation_mismatch=true conclusion=success >> "$GITHUB_OUTPUT"
eval "$IN_SESSION"
touch "$TEST_DIR/started"
while :; do sleep 1; done
`;
const stepScript = (metadata: string) =>
metadata
.split(/^ - name: /m)
.find((step) => step.includes("${GITHUB_ACTION_PATH}/src/"))!
.match(/^ run: \|\n((?: {8}.*\n|\n)+)/m)![1]!
.replace(/^ {8}/gm, "");
const parseOutputs = (file: string) =>
Object.fromEntries(
[
...readFileSync(file, "utf8").matchAll(
/^([^=\n]+?)(?:=|<<(\S+)\n)(.*)$(?:\n\2$)?/gm,
),
].map(([, name, , value]) => [name, value]),
);
/** Runs an action's step, as the runner does, and cancels it during the session. */
async function cancelStep(
actionDir: string,
{ signals = ["SIGINT"] as NodeJS.Signals[], inSession = ":" } = {},
) {
const source = join(import.meta.dir, "..", actionDir);
const dir = mkdtempSync(join(tmpdir(), "cancel-"));
const path = (file: string) => join(dir, file);
const server = Bun.serve({
port: 0,
hostname: "127.0.0.1",
fetch: () =>
Response.json({ login: "writer", type: "User", value: "identity" }),
});
const pids = () =>
existsSync(path("pids"))
? [...readFileSync(path("pids"), "utf8").matchAll(/\d+/g)].map(Number)
: [];
let step: Bun.Subprocess | undefined;
try {
// The action keeps files for the session in its own directory.
for (const name of ["repo", "bin", "outputs", "action", "action/scripts"]) {
mkdirSync(path(name));
}
for (const name of readdirSync(source)) {
if (name === "scripts") continue;
symlinkSync(join(source, name), path(join("action", name)));
}
execFileSync("git", ["init", "-q", path("repo")]);
for (const file of ["outputs/output", "env", "path"]) {
writeFileSync(path(file), "");
}
writeFileSync(path("event.json"), JSON.stringify({ inputs: {} }));
writeFileSync(path("prompt.txt"), "x");
writeFileSync(path("claude"), SESSION, { mode: 0o755 });
writeFileSync(
path("step.sh"),
stepScript(readFileSync(join(source, "action.yml"), "utf8")),
);
writeFileSync(
path("bin/bun"),
`#!/bin/bash\nexec "${process.execPath}" "$@"\n`,
{ mode: 0o755 },
);
const running = Bun.spawn(
[
"bash",
"--noprofile",
"--norc",
"-e",
"-o",
"pipefail",
path("step.sh"),
],
{
cwd: path("repo"),
stdout: "ignore",
stderr: "ignore",
env: {
PATH: `${path("bin")}:${process.env.PATH}`,
HOME: dir,
RUNNER_TEMP: dir,
TEST_DIR: dir,
IN_SESSION: inSession,
GITHUB_ACTION_PATH: path("action"),
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
GITHUB_EVENT_NAME: "workflow_dispatch",
GITHUB_EVENT_PATH: path("event.json"),
GITHUB_REPOSITORY: "o/r",
GITHUB_ACTOR: "writer",
GITHUB_RUN_ID: "1",
GITHUB_OUTPUT: path("outputs/output"),
GITHUB_ENV: path("env"),
GITHUB_PATH: path("path"),
OVERRIDE_GITHUB_TOKEN: "the-token",
ANTHROPIC_FEDERATION_RULE_ID: "rule",
ANTHROPIC_ORGANIZATION_ID: "org",
ACTIONS_ID_TOKEN_REQUEST_URL: `http://127.0.0.1:${server.port}/?`,
ACTIONS_ID_TOKEN_REQUEST_TOKEN: "unused",
PROMPT: "x",
INPUT_PROMPT_FILE: path("prompt.txt"),
PATH_TO_CLAUDE_CODE_EXECUTABLE: path("claude"),
INPUT_PATH_TO_CLAUDE_CODE_EXECUTABLE: path("claude"),
},
},
);
step = running;
await until(() => existsSync(path("started")), "the session");
expect(pids().slice(0, 3).map(isRunning)).toEqual([true, true, true]);
const identity = path("claude-workload-identity");
expect(existsSync(identity)).toBe(true);
// The runner signals the step's own process and nothing else.
for (const name of signals) running.kill(name);
const exitCode = await running.exited;
// What was killed can take a moment to be gone.
await until(() => !pids().some(isRunning), "the session to end");
return {
exitCode,
outputs: parseOutputs(path("outputs/output")),
env: readFileSync(path("env"), "utf8"),
leftBehind: [path("lock"), identity]
.filter(existsSync)
.concat(readdirSync(path("action/scripts"))),
};
} finally {
step?.kill("SIGKILL");
chmodSync(path("outputs"), 0o755);
for (const pid of pids().filter(isRunning)) process.kill(pid, "SIGKILL");
server.stop(true);
rmSync(dir, { recursive: true, force: true });
}
}
describe.skipIf(process.platform === "win32")("a cancelled run", () => {
test.each([
[["SIGINT"]],
[["SIGTERM"]],
[["SIGINT", "SIGINT", "SIGTERM"]],
] as [NodeJS.Signals[]][])(
"stops the session and has the app token revoked (%p)",
async (signals) => {
const result = await cancelStep("", { signals });
expect(result).toMatchObject({
exitCode: 130,
leftBehind: [],
outputs: {
github_token: "the-token",
// A session can't have the revocation skipped, or report success.
skipped_due_to_workflow_validation_mismatch: "false",
conclusion: "failure",
},
});
expect(result.env).not.toContain("ADDED");
},
20_000,
);
test("stops every process a session keeps starting", async () => {
const result = await cancelStep("", {
inSession:
'bash -c "while :; do sleep 30.25 & echo \\$! >> \\"$TEST_DIR/pids\\"; sleep 0.005; done" & until [ $(wc -l < "$TEST_DIR/pids") -gt 9 ]; do sleep 0.05; done',
});
expect(result).toMatchObject({ exitCode: 130, leftBehind: [] });
}, 20_000);
test("writes its outputs when the session was in the middle of one", async () => {
const result = await cancelStep("", {
inSession: `echo 'report<<END' >> "$GITHUB_OUTPUT"`,
});
expect(result.outputs).toEqual({
skipped_due_to_workflow_validation_mismatch: "false",
github_token: "the-token",
branch_name: "",
conclusion: "failure",
});
}, 20_000);
test("stops the session in the base action", async () => {
const result = await cancelStep("base-action");
expect(result).toMatchObject({
exitCode: 130,
leftBehind: [],
outputs: { conclusion: "failure" },
});
}, 20_000);
test.skipIf(process.getuid?.() === 0)(
"cleans up what it can when outputs can't be written",
async () => {
const result = await cancelStep("", {
inSession: 'chmod a-w "$GITHUB_OUTPUT" "$(dirname "$GITHUB_OUTPUT")"',
});
expect(result).toMatchObject({ exitCode: 130, leftBehind: [] });
expect(result.env).not.toContain("ADDED");
},
20_000,
);
});
describe("onCancel", () => {
// Prints once it is ready, and finishes by itself after a second.
const finishing = (...signals: NodeJS.Signals[]) => {
const source = join(import.meta.dir, "../base-action/src/cancel.ts");
const child = Bun.spawn(
[
process.execPath,
"-e",
`import { onCancel } from ${JSON.stringify(source)};
onCancel([() => console.log("stopped")], () => true);
setTimeout(() => { console.log("finished"); process.exit(0); }, 1000);
console.log("ready");`,
],
{ stdout: "pipe" },
);
return (async () => {
let output = "";
for await (const chunk of child.stdout) {
output += new TextDecoder().decode(chunk);
if (output === "ready\n") signals.forEach((name) => child.kill(name));
}
return { output, exitCode: await child.exited };
})();
};
test.skipIf(process.platform === "win32")(
"lets a run whose session has ended finish until the second signal",
async () => {
expect(await finishing("SIGINT")).toEqual({
output: "ready\nfinished\n",
exitCode: 0,
});
expect(await finishing("SIGINT", "SIGTERM")).toEqual({
output: "ready\nstopped\n",
exitCode: 130,
});
},
);
});