1 Commits

Author SHA1 Message Date
Danny Kim 449f00c736 Add ordered bot profiles
Check / deno (pull_request) Successful in 55s
2026-09-23 20:59:38 +09:00
4 changed files with 185 additions and 32 deletions
+8 -7
View File
@@ -2,13 +2,14 @@ name: Bot agents
description: Run a coding agent for approved Gitea issue/PR automation description: Run a coding agent for approved Gitea issue/PR automation
inputs: inputs:
profiles: profiles-file:
description: >- description: >-
Ordered YAML sequence of bot profiles. Each profile has `type` (`claude` Repository-relative path to an ordered YAML sequence of bot profiles.
or `codex`), an optional `model`, and a `token` containing a Claude setup Each profile has `type` (`claude` or `codex`), an optional `model`, and
token or Codex API key. Codex may omit `token` to use its persisted `token-env` naming a `BOT_PROFILE_...` environment variable containing
device login. A profile is tried only after the previous one exhausts its credential. Codex may omit `token-env` to use its persisted device
its usage allowance. login. A profile is tried only after the previous one exhausts its usage
allowance.
required: true required: true
author-token: author-token:
description: >- description: >-
@@ -39,7 +40,7 @@ runs:
run: deno run -A "${ACTION_PATH}/run.ts" run: deno run -A "${ACTION_PATH}/run.ts"
env: env:
ACTION_PATH: ${{ gitea.action_path }} ACTION_PATH: ${{ gitea.action_path }}
PROFILES: ${{ inputs.profiles }} PROFILES_FILE: ${{ inputs.profiles-file }}
GITEA_API_URL: ${{ gitea.api_url }} GITEA_API_URL: ${{ gitea.api_url }}
GITEA_REPOSITORY: ${{ gitea.repository }} GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_TOKEN: ${{ inputs.author-token }} GITEA_TOKEN: ${{ inputs.author-token }}
+74 -7
View File
@@ -1,9 +1,11 @@
import { parse } from "jsr:@std/yaml@1"; import { parse } from "jsr:@std/yaml@1";
import { isAbsolute, relative, resolve } from "jsr:@std/path@1";
export type BotProfile = { export type BotProfile = {
type: "claude" | "codex"; type: "claude" | "codex";
model: string; model: string;
token?: string; token?: string;
tokenEnv?: string;
}; };
const DEFAULT_MODELS: Record<BotProfile["type"], string> = { const DEFAULT_MODELS: Record<BotProfile["type"], string> = {
@@ -11,7 +13,48 @@ const DEFAULT_MODELS: Record<BotProfile["type"], string> = {
codex: "gpt-5.6-terra", codex: "gpt-5.6-terra",
}; };
export function parseProfiles(text: string): BotProfile[] { export type ProfileFileSystem = {
realPath(path: string): Promise<string>;
stat(path: string): Promise<{ isFile: boolean }>;
readTextFile(path: string): Promise<string>;
};
const systemFileSystem: ProfileFileSystem = {
realPath: Deno.realPath,
async stat(path) {
return { isFile: (await Deno.stat(path)).isFile };
},
readTextFile: Deno.readTextFile,
};
export async function readProfilesFile(
file: string,
workspace: string,
fileSystem: ProfileFileSystem = systemFileSystem,
): Promise<string> {
if (isAbsolute(file)) {
throw new Error("profiles-file must be repository-relative");
}
const root = await fileSystem.realPath(workspace);
const target = await fileSystem.realPath(resolve(root, file));
const pathFromRoot = relative(root, target);
if (
pathFromRoot === "" || pathFromRoot === ".." ||
pathFromRoot.startsWith("../") || pathFromRoot.startsWith("..\\") ||
isAbsolute(pathFromRoot)
) {
throw new Error("profiles-file must stay inside the repository");
}
if (!(await fileSystem.stat(target)).isFile) {
throw new Error("profiles-file must name a file");
}
return await fileSystem.readTextFile(target);
}
export function parseProfiles(
text: string,
environment: Record<string, string>,
): BotProfile[] {
const value: unknown = parse(text); const value: unknown = parse(text);
if (!Array.isArray(value) || value.length === 0) { if (!Array.isArray(value) || value.length === 0) {
throw new Error("profiles must contain at least one profile"); throw new Error("profiles must contain at least one profile");
@@ -21,23 +64,39 @@ export function parseProfiles(text: string): BotProfile[] {
if (typeof entry !== "object" || entry === null) { if (typeof entry !== "object" || entry === null) {
throw new Error(`${at}: expected a mapping`); throw new Error(`${at}: expected a mapping`);
} }
const { type, model, token } = entry as Record<string, unknown>; const allowed = new Set(["type", "model", "token-env"]);
for (const key of Object.keys(entry)) {
if (!allowed.has(key)) throw new Error(`${at}.${key}: unknown field`);
}
const { type, model, "token-env": tokenEnv } = entry as Record<
string,
unknown
>;
if (type !== "claude" && type !== "codex") { if (type !== "claude" && type !== "codex") {
throw new Error(`${at}.type: expected "claude" or "codex"`); throw new Error(`${at}.type: expected "claude" or "codex"`);
} }
if (model !== undefined && (typeof model !== "string" || model === "")) { if (model !== undefined && (typeof model !== "string" || model === "")) {
throw new Error(`${at}.model: expected a model name`); throw new Error(`${at}.model: expected a model name`);
} }
if (token !== undefined && (typeof token !== "string" || token === "")) { if (
throw new Error(`${at}.token: expected a token`); tokenEnv !== undefined &&
(typeof tokenEnv !== "string" ||
!/^BOT_PROFILE_[A-Z0-9_]+$/.test(tokenEnv))
) {
throw new Error(`${at}.token-env: must start with BOT_PROFILE_`);
} }
if (type === "claude" && token === undefined) { if (type === "claude" && tokenEnv === undefined) {
throw new Error(`${at}.token: required for Claude`); throw new Error(`${at}.token-env: required for Claude`);
}
const token = tokenEnv === undefined ? undefined : environment[tokenEnv];
if (tokenEnv !== undefined && !token) {
throw new Error(`${at}.token-env: ${tokenEnv} is not set`);
} }
return { return {
type, type,
model: model ?? DEFAULT_MODELS[type], model: model ?? DEFAULT_MODELS[type],
...(token && { token }), ...(token && { token }),
...(tokenEnv && { tokenEnv }),
}; };
}); });
} }
@@ -66,6 +125,7 @@ export async function runProfiles<T>(
export function sanitizedEnvironment( export function sanitizedEnvironment(
environment: Record<string, string>, environment: Record<string, string>,
profiles: BotProfile[],
): Record<string, string> { ): Record<string, string> {
const result = { ...environment }; const result = { ...environment };
for ( for (
@@ -83,14 +143,21 @@ export function sanitizedEnvironment(
) { ) {
delete result[name]; delete result[name];
} }
for (const name of Object.keys(result)) {
if (name.startsWith("BOT_PROFILE_")) delete result[name];
}
for (const profile of profiles) {
if (profile.tokenEnv) delete result[profile.tokenEnv];
}
return result; return result;
} }
export function agentEnvironment( export function agentEnvironment(
environment: Record<string, string>, environment: Record<string, string>,
profile: BotProfile, profile: BotProfile,
profiles: BotProfile[],
): Record<string, string> { ): Record<string, string> {
const result = sanitizedEnvironment(environment); const result = sanitizedEnvironment(environment, profiles);
if (profile.token) { if (profile.token) {
result[ result[
profile.type === "claude" ? "CLAUDE_CODE_OAUTH_TOKEN" : "OPENAI_API_KEY" profile.type === "claude" ? "CLAUDE_CODE_OAUTH_TOKEN" : "OPENAI_API_KEY"
+94 -14
View File
@@ -2,34 +2,101 @@ import { assertEquals, assertRejects, assertThrows } from "jsr:@std/assert@1";
import { import {
agentEnvironment, agentEnvironment,
parseProfiles, parseProfiles,
readProfilesFile,
runProfiles, runProfiles,
sanitizedEnvironment, sanitizedEnvironment,
} from "./profiles.ts"; } from "./profiles.ts";
Deno.test("parses profiles in fallback order with model defaults", () => { Deno.test("parses profiles in fallback order with model defaults", () => {
assertEquals( assertEquals(
parseProfiles(` parseProfiles(
`
- type: claude - type: claude
token: claude-token token-env: BOT_PROFILE_CLAUDE_PRIMARY
- type: codex - type: codex
model: gpt-custom model: gpt-custom
`), `,
{ BOT_PROFILE_CLAUDE_PRIMARY: "claude-token" },
),
[ [
{ type: "claude", model: "claude-sonnet-5", token: "claude-token" }, {
type: "claude",
model: "claude-sonnet-5",
token: "claude-token",
tokenEnv: "BOT_PROFILE_CLAUDE_PRIMARY",
},
{ type: "codex", model: "gpt-custom" }, { type: "codex", model: "gpt-custom" },
], ],
); );
}); });
Deno.test("rejects an empty profile list", () => { Deno.test("rejects an empty profile list", () => {
assertThrows(() => parseProfiles("[]"), Error, "at least one profile"); assertThrows(() => parseProfiles("[]", {}), Error, "at least one profile");
}); });
Deno.test("rejects a Claude profile without its setup token", () => { Deno.test("rejects a Claude profile without its token environment variable", () => {
assertThrows( assertThrows(
() => parseProfiles("- type: claude"), () => parseProfiles("- type: claude", {}),
Error, Error,
"profiles[0].token", "profiles[0].token-env",
);
assertThrows(
() =>
parseProfiles(
"- type: claude\n token-env: BOT_PROFILE_CLAUDE_PRIMARY",
{},
),
Error,
"BOT_PROFILE_CLAUDE_PRIMARY is not set",
);
});
Deno.test("rejects non-profile credentials and unknown fields", () => {
assertThrows(
() =>
parseProfiles(
"- type: claude\n token-env: REVIEWER_TOKEN",
{ REVIEWER_TOKEN: "secret" },
),
Error,
"must start with BOT_PROFILE_",
);
assertThrows(
() =>
parseProfiles(
"- type: codex\n token: committed-secret",
{},
),
Error,
"profiles[0].token: unknown field",
);
});
Deno.test("reads only a profile file contained by the workspace", async () => {
const fileSystem = {
realPath(path: string) {
return Promise.resolve(path === "/repo/escaped.yml" ? "/outside" : path);
},
stat(_path: string) {
return Promise.resolve({ isFile: true });
},
readTextFile(_path: string) {
return Promise.resolve("- type: codex\n");
},
};
assertEquals(
await readProfilesFile("profiles.yml", "/repo", fileSystem),
"- type: codex\n",
);
await assertRejects(
() => readProfilesFile("/outside", "/repo", fileSystem),
Error,
"repository-relative",
);
await assertRejects(
() => readProfilesFile("escaped.yml", "/repo", fileSystem),
Error,
"must stay inside",
); );
}); });
@@ -142,15 +209,28 @@ Deno.test("exposes only the selected profile credential to the agent", () => {
OPENAI_API_KEY: "old-openai", OPENAI_API_KEY: "old-openai",
CODEX_API_KEY: "old-codex-key", CODEX_API_KEY: "old-codex-key",
CODEX_ACCESS_TOKEN: "old-codex-token", CODEX_ACCESS_TOKEN: "old-codex-token",
BOT_PROFILE_CLAUDE_PRIMARY: "selected",
BOT_PROFILE_CLAUDE_FALLBACK: "fallback",
BOT_PROFILE_UNUSED: "unused",
}; };
const profiles = [
assertEquals( {
agentEnvironment(base, { type: "claude" as const,
type: "claude",
model: "claude-sonnet-5", model: "claude-sonnet-5",
token: "selected", token: "selected",
}), tokenEnv: "BOT_PROFILE_CLAUDE_PRIMARY",
},
{
type: "claude" as const,
model: "claude-sonnet-5",
token: "fallback",
tokenEnv: "BOT_PROFILE_CLAUDE_FALLBACK",
},
];
assertEquals(
agentEnvironment(base, profiles[0], profiles),
{ HOME: "/home/bot", CLAUDE_CODE_OAUTH_TOKEN: "selected" }, { HOME: "/home/bot", CLAUDE_CODE_OAUTH_TOKEN: "selected" },
); );
assertEquals(sanitizedEnvironment(base), { HOME: "/home/bot" }); assertEquals(sanitizedEnvironment(base, profiles), { HOME: "/home/bot" });
}); });
+9 -4
View File
@@ -8,6 +8,7 @@ import {
agentEnvironment, agentEnvironment,
type BotProfile, type BotProfile,
parseProfiles, parseProfiles,
readProfilesFile,
runProfiles, runProfiles,
sanitizedEnvironment, sanitizedEnvironment,
} from "./profiles.ts"; } from "./profiles.ts";
@@ -32,11 +33,15 @@ const API = env("GITEA_API_URL");
const REPO = env("GITEA_REPOSITORY"); const REPO = env("GITEA_REPOSITORY");
const INDEX = env("ISSUE_INDEX"); const INDEX = env("ISSUE_INDEX");
const EVENT = env("EVENT_NAME"); const EVENT = env("EVENT_NAME");
const PROFILES = parseProfiles(env("PROFILES")); const PROCESS_ENV = Deno.env.toObject();
const PROFILES = parseProfiles(
await readProfilesFile(env("PROFILES_FILE"), env("GITHUB_WORKSPACE")),
PROCESS_ENV,
);
const AUTHOR_TOKEN = env("GITEA_TOKEN"); const AUTHOR_TOKEN = env("GITEA_TOKEN");
const REVIEWER_TOKEN = env("REVIEWER_TOKEN"); const REVIEWER_TOKEN = env("REVIEWER_TOKEN");
const RULES_PATH = "repos/commons/code-rules/raw/README.md"; const RULES_PATH = "repos/commons/code-rules/raw/README.md";
const HELPER_ENV = sanitizedEnvironment(Deno.env.toObject()); const HELPER_ENV = sanitizedEnvironment(PROCESS_ENV, PROFILES);
async function gitea( async function gitea(
token: string, token: string,
@@ -230,7 +235,7 @@ async function runClaude(profile: BotProfile): Promise<string> {
], ],
// Claude refuses --dangerously-skip-permissions as root outside a sandbox. // Claude refuses --dangerously-skip-permissions as root outside a sandbox.
env: { env: {
...agentEnvironment(Deno.env.toObject(), profile), ...agentEnvironment(PROCESS_ENV, profile, PROFILES),
IS_SANDBOX: "1", IS_SANDBOX: "1",
}, },
clearEnv: true, clearEnv: true,
@@ -322,7 +327,7 @@ async function codexApiLogin(token: string, codexHome: string): Promise<void> {
} }
async function runCodex(profile: BotProfile): Promise<string> { async function runCodex(profile: BotProfile): Promise<string> {
const currentEnv = agentEnvironment(Deno.env.toObject(), profile); const currentEnv = agentEnvironment(PROCESS_ENV, profile, PROFILES);
const temporaryHome = profile.token ? await Deno.makeTempDir() : null; const temporaryHome = profile.token ? await Deno.makeTempDir() : null;
if (temporaryHome !== null) currentEnv.CODEX_HOME = temporaryHome; if (temporaryHome !== null) currentEnv.CODEX_HOME = temporaryHome;
try { try {