Files
gemini-cli/.gemini/skills/offload/scripts/orchestrator.ts
T

107 lines
4.1 KiB
TypeScript

/**
* Universal Offload Orchestrator (Local)
*
* Automatically connects to your dedicated worker and launches an isolated job container.
*/
import { spawnSync } from 'child_process';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, '../../../..');
const q = (str: string) => `'${str.replace(/'/g, "'\\''")}'`;
export async function runOrchestrator(args: string[], env: NodeJS.ProcessEnv = process.env) {
const prNumber = args[0];
const action = args[1] || 'review';
if (!prNumber) {
console.error('Usage: npm run offload <PR_NUMBER> [action]');
return 1;
}
// 1. Load Settings
const settingsPath = path.join(REPO_ROOT, '.gemini/settings.json');
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const config = settings.maintainer?.deepReview;
if (!config) {
console.error('❌ Settings not found. Run "npm run offload:setup" first.');
return 1;
}
const { projectId, zone, remoteHost, remoteWorkDir, useContainer } = config;
const targetVM = `gcli-offload-${env.USER || 'mattkorwel'}`;
// 2. Wake Worker
const statusCheck = spawnSync(`gcloud compute instances describe ${targetVM} --project ${projectId} --zone ${zone} --format="get(status)"`, { shell: true });
const status = statusCheck.stdout.toString().trim();
if (status !== 'RUNNING' && status !== 'PROVISIONING' && status !== 'STAGING') {
console.log(`⚠️ Worker ${targetVM} is ${status}. Waking it up...`);
spawnSync(`gcloud compute instances start ${targetVM} --project ${projectId} --zone ${zone}`, { shell: true, stdio: 'inherit' });
}
const remotePolicyPath = `~/.gemini/policies/offload-policy.toml`;
const persistentScripts = `~/.offload/scripts`;
const sessionName = `offload-${prNumber}-${action}`;
const remoteWorktreeDir = `~/dev/worktrees/offload-${prNumber}-${action}`;
// 3. Remote Context Setup (Executed on Host for efficiency)
console.log(`🚀 Provisioning clean worktree for ${action} on PR #${prNumber}...`);
const setupCmd = `
mkdir -p ~/dev/worktrees && \
cd ${remoteWorkDir} && \
git fetch upstream pull/${prNumber}/head && \
git worktree add -f ${remoteWorktreeDir} FETCH_HEAD
`;
spawnSync(`ssh ${remoteHost} ${q(setupCmd)}`, { shell: true, stdio: 'inherit' });
// 4. Launch Isolated Container for Playbook
// We mount the specific worktree as RW, and the rest as RO for maximum safety.
const containerImage = 'us-docker.pkg.dev/gemini-code-dev/gemini-cli/maintainer:latest';
const dockerRun = `
docker run --rm -it \
--name ${sessionName} \
-v ${remoteWorktreeDir}:/home/node/dev/worktree:rw \
-v ${remoteWorkDir}:/home/node/dev/main:ro \
-v ~/.gemini:/home/node/.gemini:ro \
-v ~/.offload:/home/node/.offload:ro \
-w /home/node/dev/worktree \
${containerImage} \
sh -c "tsx ${persistentScripts}/entrypoint.ts ${prNumber} remote-branch /home/node/.gemini/policies/offload-policy.toml ${action}; exec $SHELL"
`;
const finalSSH = `ssh -t ${remoteHost} ${q(dockerRun)}`;
// 5. Open in iTerm2
const isWithinGemini = !!env.GEMINI_CLI || !!env.GEMINI_SESSION_ID || !!env.GCLI_SESSION_ID;
if (isWithinGemini) {
const tempCmdPath = path.join(process.env.TMPDIR || '/tmp', `offload-ssh-${prNumber}.sh`);
fs.writeFileSync(tempCmdPath, `#!/bin/bash\n${finalSSH}\nrm "$0"`, { mode: 0o755 });
const appleScript = `
on run argv
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
write text (item 1 of argv) & return
end tell
activate
end tell
end run
`;
spawnSync('osascript', ['-', tempCmdPath], { input: appleScript });
console.log(`✅ iTerm2 window opened on ${remoteHost} (Isolated Container).`);
return 0;
}
spawnSync(finalSSH, { stdio: 'inherit', shell: true });
return 0;
}
if (import.meta.url === `file://${process.argv[1]}`) {
runOrchestrator(process.argv.slice(2)).catch(console.error);
}