Replace NodeJS dict aliases with maps and named field reads
Co-authored-by: Danny Kim <temeddix@gmail.com> Co-committed-by: Danny Kim <temeddix@gmail.com>
This commit was merged in pull request #24.
This commit is contained in:
+173
-86
@@ -24,8 +24,13 @@ import {
|
||||
retryInvalidToken,
|
||||
stageCodexAuth,
|
||||
} from "#agents";
|
||||
import { isObject } from "#common";
|
||||
import { echo, exitCode, killProfileProcesses, readProfileFile } from "#processes";
|
||||
import { field, isObject } from "#common";
|
||||
import {
|
||||
echo,
|
||||
exitCode,
|
||||
killProfileProcesses,
|
||||
readProfileFile,
|
||||
} from "#processes";
|
||||
import {
|
||||
AgentAuthError,
|
||||
agentEnvironment,
|
||||
@@ -35,7 +40,11 @@ import {
|
||||
sanitizedEnvironment,
|
||||
withProfile,
|
||||
} from "#profiles";
|
||||
import { readRuntimeManifest, type RuntimeOutcome, type RuntimeProfile } from "#runtime";
|
||||
import {
|
||||
readRuntimeManifest,
|
||||
type RuntimeOutcome,
|
||||
type RuntimeProfile,
|
||||
} from "#runtime";
|
||||
|
||||
interface AttemptResult {
|
||||
body: string;
|
||||
@@ -58,15 +67,17 @@ interface RenderedPrompt {
|
||||
|
||||
const env = (name: string): string => {
|
||||
const value = process.env[name];
|
||||
if (value === undefined) throw new Error(`${name} is not set`);
|
||||
if (value === undefined) {
|
||||
throw new Error(`${name} is not set`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
function definedEnvironment(): NodeJS.ProcessEnv {
|
||||
const result: NodeJS.ProcessEnv = {};
|
||||
function definedEnvironment(): Map<string, string> {
|
||||
const result = new Map<string, string>();
|
||||
for (const [name, value] of Object.entries(process.env)) {
|
||||
if (value !== undefined) {
|
||||
result[name] = value;
|
||||
result.set(name, value);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -104,21 +115,36 @@ async function postAuthorComment(body: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function runRoot(command: string, args: string[]): Promise<void> {
|
||||
const code = await exitCode(spawn(command, args, { env: PROCESS_ENV, stdio: "ignore" }));
|
||||
if (code !== 0) throw new Error(`${command} ${args[0]} exited with ${code}`);
|
||||
const code = await exitCode(
|
||||
spawn(command, args, {
|
||||
env: Object.fromEntries(PROCESS_ENV),
|
||||
stdio: "ignore",
|
||||
}),
|
||||
);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${command} ${args[0]} exited with ${code}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function configureGitAuthor(): Promise<void> {
|
||||
const user: unknown = await (await gitea("user")).json();
|
||||
if (!isObject(user) || typeof user["login"] !== "string" || typeof user["email"] !== "string") {
|
||||
throw new Error("user: unexpected Gitea response");
|
||||
const userResponse = await gitea("user");
|
||||
const user: unknown = await userResponse.json();
|
||||
const login = field(user, "login");
|
||||
const email = field(user, "email");
|
||||
if (typeof login !== "string" || typeof email !== "string") {
|
||||
throw new TypeError("user: unexpected Gitea response");
|
||||
}
|
||||
await runRoot("git", ["config", "user.name", user["login"]]);
|
||||
await runRoot("git", ["config", "user.email", user["email"]]);
|
||||
await runRoot("git", ["config", "user.name", login]);
|
||||
await runRoot("git", ["config", "user.email", email]);
|
||||
}
|
||||
|
||||
async function readProfileToken(profile: RuntimeProfile): Promise<string | null> {
|
||||
const token = profile.tokenFile === null ? null : await readFile(profile.tokenFile, "utf8");
|
||||
async function readProfileToken(
|
||||
profile: RuntimeProfile,
|
||||
): Promise<string | null> {
|
||||
const token =
|
||||
profile.tokenFile === null
|
||||
? null
|
||||
: await readFile(profile.tokenFile, "utf8");
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -130,13 +156,27 @@ async function runAgentCommand(
|
||||
): Promise<void> {
|
||||
const child = spawn(command, args, {
|
||||
cwd: WORKSPACE,
|
||||
env: agentEnvironment(PROCESS_ENV, profile, token),
|
||||
env: Object.fromEntries(agentEnvironment(PROCESS_ENV, profile, token)),
|
||||
uid: profile.uid,
|
||||
gid: profile.gid,
|
||||
stdio: "ignore",
|
||||
});
|
||||
const code = await exitCode(child);
|
||||
if (code !== 0) throw new Error(`${command} ${args[0]} exited with ${code}`);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${command} ${args[0]} exited with ${code}`);
|
||||
}
|
||||
}
|
||||
|
||||
// The agent name the skills installer knows each profile type by.
|
||||
function skillsAgent(type: RuntimeProfile["type"]): string {
|
||||
switch (type) {
|
||||
case "CLAUDE":
|
||||
return "claude-code";
|
||||
case "CODEX":
|
||||
return "codex";
|
||||
case "OPENCODE":
|
||||
return "opencode";
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareProfile(profile: RuntimeProfile): Promise<void> {
|
||||
@@ -152,50 +192,68 @@ async function prepareProfile(profile: RuntimeProfile): Promise<void> {
|
||||
...SKILLS_INSTALL.split(" "),
|
||||
"--global",
|
||||
"--agent",
|
||||
profile.type === "claude" ? "claude-code" : profile.type,
|
||||
skillsAgent(profile.type),
|
||||
"--yes",
|
||||
]);
|
||||
}
|
||||
|
||||
// One issue comment as the prompt quotes it.
|
||||
function formatComment(comment: unknown): string {
|
||||
const { user, created_at: createdAt, body } = isObject(comment) ? comment : {};
|
||||
const login = isObject(user) ? user["login"] : undefined;
|
||||
const login = field(field(comment, "user"), "login");
|
||||
const createdAt = field(comment, "created_at");
|
||||
const body = field(comment, "body");
|
||||
return `## ${String(login)} at ${String(createdAt)}\n\n${String(body)}\n`;
|
||||
}
|
||||
|
||||
async function renderPrompt(profile: RuntimeProfile): Promise<RenderedPrompt> {
|
||||
const reviewPath = await makeProfileFile(profile, "review.md");
|
||||
const anchorsPath = await makeProfileFile(profile, "anchors.json");
|
||||
const comments: unknown = await (
|
||||
await gitea(`repos/${REPO}/issues/${INDEX}/comments?limit=100`)
|
||||
).json();
|
||||
const commentsResponse = await gitea(
|
||||
`repos/${REPO}/issues/${INDEX}/comments?limit=100`,
|
||||
);
|
||||
const comments: unknown = await commentsResponse.json();
|
||||
if (!Array.isArray(comments)) {
|
||||
throw new TypeError("comments: unexpected Gitea response");
|
||||
}
|
||||
const values: NodeJS.ProcessEnv = {
|
||||
COMMENT: env("COMMENT"),
|
||||
ISSUE_COMMENTS: comments.map((comment: unknown) => formatComment(comment)).join("\n"),
|
||||
CODE_RULES: await (await gitea(RULES_PATH)).text(),
|
||||
EVENT_NAME: EVENT,
|
||||
GITEA_API_URL: API,
|
||||
GITEA_REPOSITORY: REPO,
|
||||
ISSUE_INDEX: INDEX,
|
||||
REVIEW_PATH: reviewPath,
|
||||
ANCHORS_PATH: anchorsPath,
|
||||
};
|
||||
const template = await readFile(new URL("../../prompt.md", import.meta.url), "utf8");
|
||||
const rulesResponse = await gitea(RULES_PATH);
|
||||
const codeRules = await rulesResponse.text();
|
||||
const values = new Map<string, string>([
|
||||
["COMMENT", env("COMMENT")],
|
||||
[
|
||||
"ISSUE_COMMENTS",
|
||||
comments.map((comment: unknown) => formatComment(comment)).join("\n"),
|
||||
],
|
||||
["CODE_RULES", codeRules],
|
||||
["EVENT_NAME", EVENT],
|
||||
["GITEA_API_URL", API],
|
||||
["GITEA_REPOSITORY", REPO],
|
||||
["ISSUE_INDEX", INDEX],
|
||||
["REVIEW_PATH", reviewPath],
|
||||
["ANCHORS_PATH", anchorsPath],
|
||||
]);
|
||||
const template = await readFile(
|
||||
new URL("../../prompt.md", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
return {
|
||||
prompt: template.replaceAll(
|
||||
/\$\{(\w+)\}/gu,
|
||||
(match: string, name: string) => values[name] ?? match,
|
||||
/\$\{(?<name>\w+)\}/gu,
|
||||
(match: string, ...args: unknown[]) => {
|
||||
const groups = args.at(-1);
|
||||
const name = isObject(groups) ? field(groups, "name") : undefined;
|
||||
return typeof name === "string" ? (values.get(name) ?? match) : match;
|
||||
},
|
||||
),
|
||||
reviewPath,
|
||||
anchorsPath,
|
||||
};
|
||||
}
|
||||
|
||||
async function runClaude(profile: RuntimeProfile, token: string, prompt: string): Promise<string> {
|
||||
async function runClaude(
|
||||
profile: RuntimeProfile,
|
||||
token: string,
|
||||
prompt: string,
|
||||
): Promise<string> {
|
||||
const claude = spawn(
|
||||
"claude",
|
||||
[
|
||||
@@ -210,10 +268,9 @@ async function runClaude(profile: RuntimeProfile, token: string, prompt: string)
|
||||
],
|
||||
{
|
||||
cwd: WORKSPACE,
|
||||
env: {
|
||||
...agentEnvironment(PROCESS_ENV, profile, token),
|
||||
IS_SANDBOX: "1",
|
||||
},
|
||||
env: Object.fromEntries(
|
||||
agentEnvironment(PROCESS_ENV, profile, token).set("IS_SANDBOX", "1"),
|
||||
),
|
||||
uid: profile.uid,
|
||||
gid: profile.gid,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
@@ -230,26 +287,36 @@ async function runClaude(profile: RuntimeProfile, token: string, prompt: string)
|
||||
console.error(part);
|
||||
}
|
||||
})();
|
||||
for await (const line of createInterface({ input: claude.stdout, crlfDelay: Infinity })) {
|
||||
for await (const line of createInterface({
|
||||
input: claude.stdout,
|
||||
crlfDelay: Infinity,
|
||||
})) {
|
||||
if (line !== "") {
|
||||
const event: unknown = JSON.parse(line);
|
||||
if (isObject(event)) {
|
||||
const content = isObject(event["message"]) ? event["message"]["content"] : undefined;
|
||||
const content = field(field(event, "message"), "content");
|
||||
for (const part of Array.isArray(content) ? content : []) {
|
||||
if (isObject(part)) {
|
||||
const text = part["thinking"] ?? part["text"] ?? part["name"];
|
||||
const text =
|
||||
field(part, "thinking") ??
|
||||
field(part, "text") ??
|
||||
field(part, "name");
|
||||
if (typeof text === "string" && text !== "") {
|
||||
console.log(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (event["type"] === "result") {
|
||||
const { is_error: isError, result: answer, subtype, api_error_status: apiStatus } = event;
|
||||
if (field(event, "type") === "result") {
|
||||
const isError = field(event, "is_error");
|
||||
const answer = field(event, "result");
|
||||
const subtype = field(event, "subtype");
|
||||
const apiStatus = field(event, "api_error_status");
|
||||
result = {
|
||||
isError: typeof isError === "boolean" ? isError : undefined,
|
||||
result: typeof answer === "string" ? answer : undefined,
|
||||
subtype: String(subtype),
|
||||
apiErrorStatus: typeof apiStatus === "number" ? apiStatus : undefined,
|
||||
apiErrorStatus:
|
||||
typeof apiStatus === "number" ? apiStatus : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -257,14 +324,18 @@ async function runClaude(profile: RuntimeProfile, token: string, prompt: string)
|
||||
}
|
||||
const [code] = await Promise.all([status, copyError]);
|
||||
if (result?.isError === true) {
|
||||
const failure = new Error(result.result ?? `claude ended with ${result.subtype}`);
|
||||
const failure = new Error(
|
||||
result.result ?? `claude ended with ${result.subtype}`,
|
||||
);
|
||||
if (isClaudeAuthFailure(result)) {
|
||||
throw new AgentAuthError("claude sign-in failed", { cause: failure });
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
if (result?.result === undefined) {
|
||||
throw new Error(error.trim() || `claude ended with ${result?.subtype ?? "no result"}`);
|
||||
throw new Error(
|
||||
error.trim() || `claude ended with ${result?.subtype ?? "no result"}`,
|
||||
);
|
||||
}
|
||||
if (code !== 0) {
|
||||
throw new Error(error.trim() || `claude exited with ${code}`);
|
||||
@@ -272,28 +343,13 @@ async function runClaude(profile: RuntimeProfile, token: string, prompt: string)
|
||||
return result.result;
|
||||
}
|
||||
|
||||
// Polls every 100 ms until the login prints something, failing if it exits first.
|
||||
async function pollForInstructions(
|
||||
shownText: () => string,
|
||||
status: Promise<number>,
|
||||
): Promise<void> {
|
||||
if (shownText().trim() !== "") {
|
||||
return;
|
||||
}
|
||||
const exited = await Promise.race([status.then(() => true), sleep(100, false)]);
|
||||
if (exited) {
|
||||
throw new AgentAuthError("AI bot login produced no instructions");
|
||||
}
|
||||
await pollForInstructions(shownText, status);
|
||||
}
|
||||
|
||||
async function codexDeviceLogin(
|
||||
profile: RuntimeProfile,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
environment: ReadonlyMap<string, string>,
|
||||
): Promise<void> {
|
||||
const login = spawn("codex", ["login", "--device-auth"], {
|
||||
cwd: WORKSPACE,
|
||||
env: environment,
|
||||
env: Object.fromEntries(environment),
|
||||
uid: profile.uid,
|
||||
gid: profile.gid,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
@@ -308,7 +364,15 @@ async function codexDeviceLogin(
|
||||
};
|
||||
const drained = Promise.all([collect(login.stdout), collect(login.stderr)]);
|
||||
await sleep(3000);
|
||||
await pollForInstructions(() => shown, status);
|
||||
while (shown.trim() === "") {
|
||||
const exited = await Promise.race([
|
||||
status.then(() => true),
|
||||
sleep(100, false),
|
||||
]);
|
||||
if (exited) {
|
||||
throw new AgentAuthError("AI bot login produced no instructions");
|
||||
}
|
||||
}
|
||||
await postAuthorComment(withProfile(shown, profile));
|
||||
const [code] = await Promise.all([status, drained]);
|
||||
if (code !== 0) {
|
||||
@@ -318,12 +382,12 @@ async function codexDeviceLogin(
|
||||
|
||||
async function codexApiLogin(
|
||||
profile: RuntimeProfile,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
environment: ReadonlyMap<string, string>,
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
const login = spawn("codex", ["login", "--with-api-key"], {
|
||||
cwd: WORKSPACE,
|
||||
env: environment,
|
||||
env: Object.fromEntries(environment),
|
||||
uid: profile.uid,
|
||||
gid: profile.gid,
|
||||
stdio: ["pipe", "inherit", "pipe"],
|
||||
@@ -337,7 +401,10 @@ async function codexApiLogin(
|
||||
}
|
||||
}
|
||||
|
||||
async function makeProfileFile(profile: RuntimeProfile, name: string): Promise<string> {
|
||||
async function makeProfileFile(
|
||||
profile: RuntimeProfile,
|
||||
name: string,
|
||||
): Promise<string> {
|
||||
const path = `${profile.home}/${name}`;
|
||||
await writeFile(path, "", { mode: 0o600 });
|
||||
await chmod(path, 0o600);
|
||||
@@ -350,19 +417,22 @@ async function runCodex(
|
||||
prompt: string,
|
||||
authentication: CodexAuthentication,
|
||||
): Promise<string> {
|
||||
const token = authentication.kind === "api-key" ? authentication.token : undefined;
|
||||
const token =
|
||||
authentication.kind === "api-key" ? authentication.token : undefined;
|
||||
const environment = agentEnvironment(PROCESS_ENV, profile, token);
|
||||
if (authentication.kind === "api-key") {
|
||||
await codexApiLogin(profile, environment, authentication.token);
|
||||
} else {
|
||||
const check = spawn("codex", ["login", "status"], {
|
||||
cwd: WORKSPACE,
|
||||
env: environment,
|
||||
env: Object.fromEntries(environment),
|
||||
uid: profile.uid,
|
||||
gid: profile.gid,
|
||||
stdio: "ignore",
|
||||
});
|
||||
if ((await exitCode(check)) !== 0) await codexDeviceLogin(profile, environment);
|
||||
if ((await exitCode(check)) !== 0) {
|
||||
await codexDeviceLogin(profile, environment);
|
||||
}
|
||||
}
|
||||
const outputPath = await makeProfileFile(profile, "result.md");
|
||||
const attempt = async (): Promise<CommandResult> => {
|
||||
@@ -379,7 +449,7 @@ async function runCodex(
|
||||
],
|
||||
{
|
||||
cwd: WORKSPACE,
|
||||
env: environment,
|
||||
env: Object.fromEntries(environment),
|
||||
uid: profile.uid,
|
||||
gid: profile.gid,
|
||||
stdio: ["ignore", "inherit", "pipe"],
|
||||
@@ -404,7 +474,9 @@ async function runCodex(
|
||||
await codexDeviceLogin(profile, environment);
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
const failure = new Error(result.error.trim() || `codex exited with ${result.code}`);
|
||||
const failure = new Error(
|
||||
result.error.trim() || `codex exited with ${result.code}`,
|
||||
);
|
||||
if (isCodexAuthFailure(result.error)) {
|
||||
throw new AgentAuthError("codex sign-in failed", { cause: failure });
|
||||
}
|
||||
@@ -420,7 +492,7 @@ async function runOpenCode(
|
||||
): Promise<string> {
|
||||
const child = spawn("opencode", openCodeArgs(profile.model, prompt), {
|
||||
cwd: WORKSPACE,
|
||||
env: agentEnvironment(PROCESS_ENV, profile, token),
|
||||
env: Object.fromEntries(agentEnvironment(PROCESS_ENV, profile, token)),
|
||||
uid: profile.uid,
|
||||
gid: profile.gid,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
@@ -429,20 +501,28 @@ async function runOpenCode(
|
||||
const collected = collectOpenCodeOutput(
|
||||
child.stdout,
|
||||
child.stderr,
|
||||
(chunk) => echo(process.stdout, chunk),
|
||||
(chunk) => echo(process.stderr, chunk),
|
||||
async (chunk) => {
|
||||
await echo(process.stdout, chunk);
|
||||
},
|
||||
async (chunk) => {
|
||||
await echo(process.stderr, chunk);
|
||||
},
|
||||
);
|
||||
const [code, streams] = await Promise.all([status, collected]);
|
||||
const error = streams.stderr.trim();
|
||||
if (code !== 0) {
|
||||
throw openCodeError(streams.stdout) ?? new Error(error || `opencode exited with ${code}`);
|
||||
throw (
|
||||
openCodeError(streams.stdout) ??
|
||||
new Error(error || `opencode exited with ${code}`)
|
||||
);
|
||||
}
|
||||
return parseOpenCodeEvents(streams.stdout);
|
||||
}
|
||||
|
||||
async function runProfile(profile: RuntimeProfile): Promise<AttemptResult> {
|
||||
const token = await readProfileToken(profile);
|
||||
const authentication = profile.type === "codex" ? codexAuthentication(token ?? undefined) : null;
|
||||
const authentication =
|
||||
profile.type === "CODEX" ? codexAuthentication(token ?? undefined) : null;
|
||||
let stagedCodexAuth: string | null = null;
|
||||
let body: string | null = null;
|
||||
let resultPath: string | null = null;
|
||||
@@ -450,15 +530,20 @@ async function runProfile(profile: RuntimeProfile): Promise<AttemptResult> {
|
||||
let anchorsPath: string | null = null;
|
||||
try {
|
||||
if (authentication?.kind === "persistent") {
|
||||
stagedCodexAuth = await stageCodexAuth(CODEX_AUTH, profile.home, profile.uid, profile.gid);
|
||||
stagedCodexAuth = await stageCodexAuth(
|
||||
CODEX_AUTH,
|
||||
profile.home,
|
||||
profile.uid,
|
||||
profile.gid,
|
||||
);
|
||||
}
|
||||
await prepareProfile(profile);
|
||||
const rendered = await renderPrompt(profile);
|
||||
reviewPath = rendered.reviewPath;
|
||||
anchorsPath = rendered.anchorsPath;
|
||||
if (profile.type === "claude") {
|
||||
if (profile.type === "CLAUDE") {
|
||||
body = await runClaude(profile, token ?? "", rendered.prompt);
|
||||
} else if (profile.type === "codex") {
|
||||
} else if (profile.type === "CODEX") {
|
||||
resultPath = await runCodex(
|
||||
profile,
|
||||
rendered.prompt,
|
||||
@@ -473,7 +558,9 @@ async function runProfile(profile: RuntimeProfile): Promise<AttemptResult> {
|
||||
await persistCodexAuth(stagedCodexAuth, CODEX_AUTH);
|
||||
}
|
||||
}
|
||||
if (resultPath !== null) body = await readProfileFile(profile, resultPath);
|
||||
if (resultPath !== null) {
|
||||
body = await readProfileFile(profile, resultPath);
|
||||
}
|
||||
if (body === null || reviewPath === null || anchorsPath === null) {
|
||||
throw new Error("agent attempt produced no result");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user