Files

177 lines
7.5 KiB
JavaScript

const fs = require('fs');
const path = require('path');
console.log('[Patch PaperClip] Starting runtime patches...');
// ---------------------------------------------------------------------------
// 1. Fix Hermes E2BIG: Write prompt to --query-file instead of passing in argv
// ---------------------------------------------------------------------------
const hermesExecutePath = '/app/packages/adapters/hermes/src/server/execute.ts';
if (fs.existsSync(hermesExecutePath)) {
let content = fs.readFileSync(hermesExecutePath, 'utf8');
// Replace "-q", prompt with --query-file
const oldArgs = 'const args: string[] = ["chat", "-q", prompt];';
const newArgs = `const promptFile = path.join("/tmp", \`hermes-prompt-\${ctx.runId || Date.now()}.txt\`);
await fs.writeFile(promptFile, prompt, "utf-8");
const args: string[] = ["chat", "--query-file", promptFile];`;
if (content.includes(oldArgs)) {
content = content.replace(oldArgs, newArgs);
// Add cleanup in finally block
const oldRun = ` const result = await runChildProcess(ctx.runId, hermesCmd, args, {
cwd,
env,
timeoutSec,
graceSec,
onLog: wrappedOnLog,
onSpawn: ctx.onSpawn,
});`;
const newRun = ` let result;
try {
result = await runChildProcess(ctx.runId, hermesCmd, args, {
cwd,
env,
timeoutSec,
graceSec,
onLog: wrappedOnLog,
onSpawn: ctx.onSpawn,
});
} finally {
await fs.unlink(promptFile).catch(() => {});
}`;
if (content.includes(oldRun)) {
content = content.replace(oldRun, newRun);
}
fs.writeFileSync(hermesExecutePath, content, 'utf8');
console.log('[Patch PaperClip] Successfully patched hermes execute.ts for --query-file (fixes spawn E2BIG)!');
} else {
console.log('[Patch PaperClip] hermes execute.ts already patched or target pattern not found.');
}
}
// ---------------------------------------------------------------------------
// 2. Fix server-utils E2BIG: filter monster environment variables (>32KB)
// ---------------------------------------------------------------------------
const serverUtilsPath = '/app/packages/adapter-utils/src/server-utils.ts';
if (fs.existsSync(serverUtilsPath)) {
let content = fs.readFileSync(serverUtilsPath, 'utf8');
const oldEnvLoop = ` for (const [key, value] of Object.entries(childEnv)) {
if (value === undefined) delete childEnv[key];
}`;
const newEnvLoop = ` for (const [key, value] of Object.entries(childEnv)) {
if (value === undefined || (typeof value === "string" && value.length > 32768)) delete childEnv[key];
}`;
if (content.includes(oldEnvLoop)) {
content = content.replace(oldEnvLoop, newEnvLoop);
fs.writeFileSync(serverUtilsPath, content, 'utf8');
console.log('[Patch PaperClip] Successfully patched server-utils.ts to guard against env E2BIG!');
} else {
console.log('[Patch PaperClip] server-utils.ts already patched or target pattern not found.');
}
}
// ---------------------------------------------------------------------------
// 3. Fix AI Connection endpoint for OpenRouter / custom base URLs
// ---------------------------------------------------------------------------
const aiConnPath = '/app/server/dist/routes/ai-connections.js';
if (fs.existsSync(aiConnPath)) {
let content = fs.readFileSync(aiConnPath, 'utf8');
const target = '"https://api.openai.com/v1/models"';
const replacement = 'process.env.OPENAI_BASE_URL ? process.env.OPENAI_BASE_URL + "/models" : "https://api.openai.com/v1/models"';
if (content.includes(target)) {
content = content.split(target).join(replacement);
fs.writeFileSync(aiConnPath, content, 'utf8');
console.log('[Patch PaperClip] Successfully patched ai-connections.js for OPENAI_BASE_URL!');
}
}
// ---------------------------------------------------------------------------
// 4. Mark runs as failed when Hermes reports a terminal provider error
// (Hermes exits 0 even when the final LLM call failed, e.g. HTTP 429)
// ---------------------------------------------------------------------------
if (fs.existsSync(hermesExecutePath)) {
let content = fs.readFileSync(hermesExecutePath, 'utf8');
const marker = '[paperclip-patch] terminal provider error detection';
const anchor = ' const parsed = parseHermesOutput(result.stdout || "", result.stderr || "");';
if (!content.includes(marker) && content.includes(anchor)) {
const injection = anchor + `
// ${marker}
if (!parsed.errorMessage) {
const fatalPatterns = [
/API call failed after \\d+ retries?:\\s*([^\\n]+)/,
/Final error:\\s*([^\\n]+)/,
/insufficient_balance_error[^\\n]*/,
];
const haystack = \`\${result.stdout || ""}\\n\${result.stderr || ""}\`;
for (const pattern of fatalPatterns) {
const match = haystack.match(pattern);
if (match) {
parsed.errorMessage = (\`Hermes provider error: \${match[0]}\`).slice(0, 500);
break;
}
}
}`;
content = content.replace(anchor, injection);
fs.writeFileSync(hermesExecutePath, content, 'utf8');
console.log('[Patch PaperClip] Patched hermes execute.ts to surface terminal provider errors.');
} else {
console.log('[Patch PaperClip] hermes terminal-error detection already patched or anchor not found.');
}
}
// ---------------------------------------------------------------------------
// 5. Ignore stale issue ids in workspace_operations (FK violation fails the run)
// Wake payloads can carry issue ids that no longer exist. Inserting them
// violates workspace_operations_issue_id_issues_id_fk and fails the run
// even when the agent's work succeeded.
// ---------------------------------------------------------------------------
const workspaceOpsPath = '/app/server/src/services/workspace-operations.ts';
if (fs.existsSync(workspaceOpsPath)) {
let content = fs.readFileSync(workspaceOpsPath, 'utf8');
const marker = '[paperclip-patch] stale issueId guard';
const importLine = 'import { asc, desc, eq, gte, inArray, isNull, lt, or, and } from "drizzle-orm";';
const anchor = ` if (runtimeControlAction) liveRuntimeControlOperationIds.add(id);
try {`;
if (!content.includes(marker) && content.includes(anchor) && content.includes('issueId: input.issueId ?? null,')) {
if (content.includes(importLine)) {
content = content.replace(importLine, 'import { asc, desc, eq, gte, inArray, isNull, lt, or, and, sql } from "drizzle-orm";');
}
const guard = ` if (runtimeControlAction) liveRuntimeControlOperationIds.add(id);
// ${marker}
let resolvedIssueId = input.issueId ?? null;
if (resolvedIssueId) {
try {
const issueLookup = await db.execute(
sql\`select 1 from issues where id = \${resolvedIssueId} limit 1\`,
);
const lookupRows = Array.isArray(issueLookup)
? issueLookup
: ((issueLookup as { rows?: unknown[] }).rows ?? []);
if (lookupRows.length === 0) resolvedIssueId = null;
} catch {
// Lookup failure must not block recording the operation.
}
}
try {`;
content = content.replace(anchor, guard).replace('issueId: input.issueId ?? null,', 'issueId: resolvedIssueId,');
fs.writeFileSync(workspaceOpsPath, content, 'utf8');
console.log('[Patch PaperClip] Patched workspace-operations.ts to drop stale issue ids (FK fix).');
} else {
console.log('[Patch PaperClip] workspace-operations.ts already patched or anchor not found.');
}
}
console.log('[Patch PaperClip] All patches completed.');