Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

26.5 KB
Raw Blame
import { createMediaJobPreparation } from '../../lib/mediaJobPreparation.js';
import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { maintenance } from '../../lib/maintenanceAdmission.js';
/**
 * Image Gen — Antigravity (`agy`) CLI provider.
 *
 * Agy is an opt-in cloud CLI backend. Each request runs in a throwaway scratch
 * directory and directs the built-in `generate_image` tool to one PortOS-owned
 * staging path. Only signature-verified image bytes are moved into the gallery.
 *
 * `generate_image` takes input images through its `ImagePaths` parameter — up
 * to 3, usable to "edit, combine, or use as references" — so an init image and
 * the reference slots both reach it. Unlike codex/grok, `Prompt` is a REQUIRED
 * tool parameter, so an image-only agy render is rejected up front.
 */

import { spawn } from '../../lib/childProcess.js';
import { mkdir, open, stat } from 'fs/promises';
import { randomUUID } from 'crypto';
import { basename, isAbsolute, join, resolve as pathResolve, sep } from 'path';
import { tmpdir } from 'os';
import sharp from 'sharp';
import {
  ANTIGRAVITY_CLI_ID,
  ensureAntigravityPrintArgs,
  isAntigravityModelId,
  parseAntigravityModelList,
  prepareAntigravityPrompt,
} from '../../lib/antigravity.js';
import {
  antigravityCatalogListsModel,
  pickAntigravityRelayModel,
  splitAntigravityModel,
} from '../../lib/providerModels.js';
import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
import { atomicWrite, copyFileGuarded, detectImageFormat, ensureDir, PATHS, rmGuarded, sleep, unlinkGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { renderTimingFields } from '../../lib/renderTiming.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer, dispatchTerminalEvent } from '../../lib/sseUtils.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { buildNoImageReason } from './noImageReason.js';
import { rejectDegenerateFrame } from './frameGuard.js';
import { checkFabrication, noFabricationClause } from './fabricationGuard.js';
import {
  AGY_IMAGEGEN_IMAGE_MODEL, IMAGE_GEN_MODE, IMAGE_TOOL_NAMES, describeFidelity,
  nearestAgyAspectRatio, visualReferenceRole,
} from './modes.js';
import { resolveInputImages } from './inputImages.js';
import { cloudPromptRequired } from './cloudProviderConfig.js';
import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
import { agentInstructionsAddition, carriedPromptAdditions, sentPromptRecord } from '../../lib/modelInput.js';

const AGY_TIMEOUT_MS = (() => {
  const n = Number(process.env.AGY_IMAGEGEN_TIMEOUT_MS);
  return Number.isFinite(n) && n > 0 ? n : 20 * 60 * 1000;
})();
const DEFAULT_BIN = 'agy';
const DEFAULT_HARVEST_TIMEOUT_MS = 5000;
let harvestTimeoutMs = DEFAULT_HARVEST_TIMEOUT_MS;

const jobs = new Map();
const activeProcs = new Map();
const activeJobs = new Map();

export const getActiveJob = () => {
  const entries = [...activeJobs.values()];
  return entries.length ? entries[entries.length - 1] : null;
};

export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);

const terminate = (jobId, proc) => {
  if (process.platform === 'win32') {
    killProcessTree(proc);
    return;
  }
  killWithEscalation(proc, {
    label: 'agy child',
    delayMs: 5000,
    stillRunning: () => activeProcs.get(jobId) === proc,
  });
};

const preparations = createMediaJobPreparation();

export const cancel = (jobId) => {
  if (!jobId) throw new Error('agy.cancel requires a jobId — use agy.cancelAll() to terminate every in-flight render');
  const pending = preparations.cancel(jobId);
  if (pending) return pending;
  const proc = activeProcs.get(jobId);
  if (!proc) return false;
  terminate(jobId, proc);
  return true;
};

export const cancelAll = () => {
  const ids = [...preparations.ids(), ...activeProcs.keys()];
  if (ids.length === 0) return false;
  for (const id of ids) cancel(id);
  return true;
};

export async function checkConnection({ agyPath } = {}) {
  const bin = agyPath || DEFAULT_BIN;
  const prepared = prepareCliSpawn(bin, ['--version']);
  const result = await bufferedSpawn(prepared.command, prepared.args, { timeoutMs: 15_000, shell: false });
  if (result.error) {
    return { connected: false, mode: IMAGE_GEN_MODE.AGY, reason: `Agy CLI not found (${result.error})` };
  }
  if (result.timedOut) {
    return { connected: false, mode: IMAGE_GEN_MODE.AGY, reason: 'agy --version timed out' };
  }
  if (result.code !== 0) {
    return { connected: false, mode: IMAGE_GEN_MODE.AGY, reason: `agy --version exited ${result.code}` };
  }
  const versionMatch = `${result.stdout}${result.stderr}`.match(/(\d+\.\d+\.\d+)/);
  return { connected: true, mode: IMAGE_GEN_MODE.AGY, model: versionMatch ? `agy ${versionMatch[1]}` : 'agy' };
}

// `agy models` waits for stdin EOF before printing its catalog, so this probe
// intentionally owns the child instead of using bufferedSpawn.
export function listModels({ agyPath } = {}) {
  const bin = agyPath || DEFAULT_BIN;
  const { command, args } = prepareCliSpawn(bin, ['models']);
  return new Promise((resolve) => {
    const proc = spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
    let stdout = '';
    let stderr = '';
    let settled = false;
    const finish = (result) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      resolve(result);
    };
    const timer = setTimeout(() => {
      killProcessTree(proc);
      finish({ models: [], error: 'agy models timed out' });
    }, 15_000);
    proc.stdin.on('error', () => {});
    proc.stdin.end();
    proc.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
    proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
    proc.on('error', (err) => finish({ models: [], error: `Failed to run ${bin}: ${err.message}` }));
    proc.on('close', (code) => {
      if (code !== 0) {
        finish({ models: [], error: stderr.trim() || `agy models exited ${code}` });
        return;
      }
      // Shared with the provider-catalog refresh so the two never disagree
      // about what a `models` row looks like — see parseAntigravityModelList.
      const models = parseAntigravityModelList(stdout);
      finish(models.length ? { models, error: null } : { models: [], error: 'agy models returned no model ids' });
    });
  });
}

const AGY_TOOL = IMAGE_TOOL_NAMES[IMAGE_GEN_MODE.AGY];

const AGY_NO_IMAGE_HINT =
  'Agy returned no image — the selected model may not expose generate_image, or the model declined. Check Settings → Image Gen → Agy CLI.';

export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail, {
  hint: AGY_NO_IMAGE_HINT,
  describe: (said) => `Agy did not produce an image at the directed path. Agy said: "${said}"`,
});

/**
 * Directs agy's `generate_image` at whatever input images the render carries.
 *
 * `ImagePaths` is a real tool parameter — "Optional absolute paths to the images
 * to use in generation. You can pass in images here if you would like to edit,
 * combine, or use as references… you cannot pass in more than 3 images" (schema
 * probed 2026-08-09). The 3-image ceiling is enforced upstream by
 * resolveInputImages, which also fixes the order and splits out the init image
 * — so this takes that resolver's `{ paths, initPath, referencePaths }` shape
 * directly rather than re-deriving "init leads" a second time.
 *
 * Naming the paths on their own line keeps them out of the tool's `Prompt`, for
 * the same reason the AspectRatio directive is separated: anything that lands
 * inside `Prompt` becomes part of what gets drawn.
 */
const agyImagePathsDirective = ({ paths, initPath, referencePaths, initImageStrength }) => {
  if (!paths.length) return '';
  const refCount = referencePaths.length;
  const role = initPath
    ? `The first is the source image to edit — ${describeFidelity(initImageStrength)}.${refCount ? ` The rest are ${visualReferenceRole(refCount)}.` : ''}`
    : `Use ${refCount === 1 ? 'it' : 'them'} as ${visualReferenceRole(refCount)}.`;
  return `\nPass these absolute paths to the tool's ImagePaths parameter, in this order: ${paths.join(', ')}\n${role}`;
};

export function buildAgyPrompt({
  prompt, negativePrompt, width, height, stagingPath,
  inputImages = { paths: [], initPath: null, referencePaths: [] }, initImageStrength,
}) {
  const avoid = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
  // `AspectRatio` is a real generate_image parameter and it defaults to '1:1'.
  // Naming the pixel dimensions alone is not enough — the agent has to be told
  // which ratio to pass, or every render comes back square regardless of the
  // requested size. Directed on its own line so it reads as an instruction to
  // the agent rather than as image content: anything that lands inside the
  // tool's `Prompt` becomes part of what gets drawn.
  //
  // The exact pixel dimensions are deliberately NOT stated. AspectRatio is the
  // only size knob generate_image exposes (#3231), so a "target dimensions"
  // line is an instruction the tool cannot satisfy — which invites the agent to
  // reach for code that can. It also leaks into the artwork: the render that
  // exposed this failure mode captioned itself "DIMENSIONS: 832 x 1216 (2:3)".
  const ratio = nearestAgyAspectRatio(width, height);
  const aspect = ratio ? `\nPass AspectRatio "${ratio}" to the tool.` : '';
  const images = agyImagePathsDirective({ ...inputImages, initImageStrength });
  return `Use your built-in ${AGY_TOOL} tool to generate exactly one image.
Image prompt: ${prompt.trim()}${avoid}${aspect}${images}
Save the generated image as a PNG file at exactly this path: ${stagingPath}
${noFabricationClause(AGY_TOOL)}
Do not create any other files, do not modify any code or workspace content, and do not run unrelated tools. When the file is written, you are done.`;
}

/**
 * The agy session model + catalog this render should drive.
 *
 * Two things want the catalog, and only a model carrying a baked effort tier
 * can need either — so an id with no tier (and a render with no pin at all)
 * skips the read. The shipped default does carry one, so a default-config
 * render always pays it; that is one cached provider-record read against a
 * multi-second CLI spawn.
 *
 *  - agy validates the (model, effort) PAIR and rejects a tier the base does
 *    not offer ("gemini-3.1-pro has no 'medium' effort"), so
 *    `ensureAntigravityPrintArgs` has to see `models` to clamp the ladder down
 *    to the tiers that base really has. Without it every suffixed id resolves
 *    against the full low/medium/high ladder and can emit an unsupported pair.
 *    Image gen was the last agy spawn site not passing the catalog through.
 *  - a SHIPPED default the vendor has retired is ours to re-point — see
 *    `AGY_IMAGEGEN_DEFAULT_MODEL` for the incident. `shippedDefault` is the
 *    provenance flag `cloudProviderConfig` sets, NOT a comparison against the
 *    constant: a user who types today's shipped id into Settings still owns
 *    that pin, and substituting it would hide agy's own "unknown model" error
 *    behind a silently different render. The re-point lands on the job's
 *    sidecar and returned record, which is what regen and provenance read.
 *
 * The catalog comes from the install's provider record (cache-fronted by the
 * provider service), NOT from an `agy models` spawn: the render path must not
 * pay a second child process, and a probe failure would stall it behind a
 * timeout. The deferred import keeps `services/providers.js` and the toolkit
 * subtree behind it out of every image-gen suite closure (server suite import
 * budget, `lib/importScoping.test.js`); `.catch` covers the uninitialized
 * toolkit, and no catalog means "leave the caller's model alone".
 */
async function resolveAgyDriverModel(model, shippedDefault) {
  if (!model || !splitAntigravityModel(model).effort) return { model: model || null, models: null };
  const models = await import('../providers.js')
    .then(({ getProviderById }) => getProviderById(ANTIGRAVITY_CLI_ID))
    .then((provider) => provider?.models)
    .catch(() => null);
  if (shippedDefault && !antigravityCatalogListsModel(model, models)) {
    const replacement = pickAntigravityRelayModel(models);
    if (replacement) {
      console.log(`🔀 agy default model ${model} is no longer listed — driving with ${replacement}`);
      return { model: replacement, models };
    }
  }
  return { model, models };
}

/**
 * The exact message agy receives and the record of what PortOS added to the
 * user's prompt (#11317). Shared by the render and the compose preview.
 */
export function agySentPrompt({ prompt = '', negativePrompt, width, height, stagingPath, inputImages, initImageStrength, promptAdditions = [] }) {
  const buildWith = (text) => buildAgyPrompt({
    prompt: text, negativePrompt, width, height, stagingPath, inputImages, initImageStrength,
  });
  const fullPrompt = buildWith(prompt);
  return {
    fullPrompt,
    record: sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
      added: [agentInstructionsAddition('Antigravity image tool instructions', buildWith)] }),
  };
}

export const generateImage = (params) => preparations.run(params, generateImagePrepared);

async function generateImagePrepared({
  promptAdditions = [],
  agyPath,
  model,
  modelIsShippedDefault = false,
  prompt = '',
  width,
  height,
  negativePrompt,
  initImagePath,
  initImageStrength,
  referenceImagePaths = [],
  visualConditioning = null,
  jobId: providedJobId = null,
  cleanC2PA = false,
  denoise = false,
}) {
  // The ingestion instant `renderTimingFields` measures from — the queue calls
  // generateImage the moment it picks this job up. See lib/renderTiming.js.
  const renderStartedAtMs = Date.now();
  // Re-anchors every path to the approved image roots and caps at agy's
  // 3-image ImagePaths ceiling — see inputImages.js.
  const inputImages = resolveInputImages({
    mode: IMAGE_GEN_MODE.AGY, initImagePath, referenceImagePaths,
  });
  // Unlike codex/grok, agy always needs a prompt even with input images:
  // `Prompt` is in generate_image's `required` list, which the provider spec
  // records as `promptRequiredWithInputImage`.
  if (cloudPromptRequired(IMAGE_GEN_MODE.AGY, inputImages.paths.length > 0) && !prompt.trim()) {
    throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
  }
  if (model && !isAntigravityModelId(model)) {
    throw new ServerError('Invalid Agy model id', { status: 400, code: 'VALIDATION_ERROR' });
  }

  await ensureDir(PATHS.images);
  const jobId = providedJobId || randomUUID();
  const filename = `${jobId}.png`;
  const outputPath = join(PATHS.images, filename);
  const scratchDir = join(tmpdir(), `portos-agy-${jobId}`);
  const stagingPath = join(scratchDir, 'output.png');

  const { fullPrompt, record: sentRecord } = agySentPrompt({
    prompt, negativePrompt, width, height, stagingPath, inputImages, initImageStrength, promptAdditions,
  });
  // `driverModel` is what agy actually runs on — a retired shipped default is
  // re-pointed here, so every record below reports the model that rendered
  // rather than the one the caller asked for. See resolveAgyDriverModel.
  const { model: driverModel, models } = await resolveAgyDriverModel(model, modelIsShippedDefault);
  const baseArgs = ensureAntigravityPrintArgs([], { model: driverModel, models });
  const { args } = prepareAntigravityPrompt(baseArgs, fullPrompt);
  const bin = agyPath || DEFAULT_BIN;
  const meta = {
    id: jobId,
    prompt: prompt.trim(),
    negativePrompt: negativePrompt || '',
    width: width ? Number(width) : null,
    height: height ? Number(height) : null,
    filename,
    mode: IMAGE_GEN_MODE.AGY,
    model: driverModel,
    // The agent/session model above drives the CLI; the image itself always
    // renders on Antigravity's fixed server-side backend — record it so
    // provenance names the model that actually produced the pixels (#3231).
    imageModel: AGY_IMAGEGEN_IMAGE_MODEL,
    inputProvenance: 'provider-inputs',
    initImageFilename: inputImages.initPath ? basename(inputImages.initPath) : null,
    referenceImageFilenames: inputImages.referencePaths.map(path => basename(path)),
    ...(visualConditioning ? { visualConditioning } : {}),
    ...sentRecord,
    createdAt: new Date().toISOString(),
  };
  // The scratch dir is the last fallible step before the job exists, so a
  // refusal above leaves nothing behind; from here on runAgy owns it.
  await mkdir(scratchDir, { recursive: true });
  const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
  jobs.set(jobId, job);
  activeJobs.set(jobId, {
    ...meta,
    generationId: jobId,
    totalSteps: 1,
    step: 0,
    progress: 0,
    currentImage: null,
  });
  console.log(`🎨 Generating image [${jobId.slice(0, 8)}] agy`);
  imageGenEvents.emit('started', { generationId: jobId, totalSteps: 1 });
  broadcastSse(job, { type: 'status', message: 'Spawning agy…' });

  runAgy(job, jobId, bin, args, {
    scratchDir,
    stagingPath,
    outputPath,
    filename,
    meta,
    cleanC2PA,
    denoise,
  });

  return {
    jobId,
    filename,
    path: `/data/images/${filename}`,
    generationId: jobId,
    mode: IMAGE_GEN_MODE.AGY,
    model: driverModel,
    status: 'running',
  };
}

// Launch is synchronous so every failure has one owner: a refusal before a
// child exists (shim resolution, or Node rejecting an invalid argv/bin
// synchronously) releases the scratch dir and settles the job here; a setup
// failure after spawn terminates the child and leaves the close handler to
// release the scratch dir once it has physically exited.
function runAgy(job, jobId, bin, args, {
  scratchDir,
  stagingPath,
  outputPath,
  filename,
  meta,
  cleanC2PA,
  denoise,
}) {
  // A failed removal keeps the maintenance settlement unsettled rather than
  // claiming the scratch dir was released; removal is idempotent.
  const removeScratch = () => maintenance.continueSettlement(
    () => rmGuarded(scratchDir, { recursive: true, force: true }),
  ).catch((err) => {
    maintenance.markCurrentUnsettled();
    console.error(`❌ agy scratch cleanup failed: ${err.message}`);
  });
  if (preparations.take(jobId)) {
    void removeScratch();
    return finalizeJobFailure.canceled(job, jobId);
  }
  let proc;
  try {
    const resolvedBin = (!isAbsolute(bin) && (bin.includes('/') || bin.includes(sep))) ? pathResolve(bin) : bin;
    const { command, args: spawnArgs } = prepareCliSpawn(resolvedBin, args);
    // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). agy reads
    // process.cwd(), so this is defensive rather than a live fix; it keeps every
    // scratch-dir spawn telling the child one consistent story about where it is.
    proc = spawn(command, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
  } catch (err) {
    removeScratch();
    return finalizeJobFailure(job, jobId, null, `Failed to spawn ${bin}: ${err?.message || err}`);
  }
  activeProcs.set(jobId, proc);
  let stdoutTail = '';
  let stderrTail = '';
  let timeoutTimer = null;
  let setupError = null;
  let processError;
  proc.on('error', (err) => {
    processError = err;
    // A failed kill/send on a live child is not physical exit.
    if (proc.pid) return;
    clearTimeout(timeoutTimer);
    removeScratch();
    finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
  });
  proc.on('close', async (code, signal) => {
    await withBackupAssetPublication(async () => {
      clearTimeout(timeoutTimer);
      try {
        if (setupError) {
          removeScratch();
          return finalizeJobFailure(job, jobId, proc, `Agy launch setup failed: ${setupError?.message || setupError}`);
        }
        if (code !== 0 || processError) {
          removeScratch();
          const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);
          return finalizeJobFailure(job, jobId, proc, `Agy generation failed: ${reason}\n${stderrTail.trim().split('\n').slice(-6).join('\n')}`);
        }
        const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);
        if (!harvested.found) {
          removeScratch();
          const prefix = harvested.invalid ? 'Agy wrote a non-image file at the directed path. ' : '';
          return finalizeJobFailure(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);
        }
        // A PNG landed — but the harvest gate only proves it is image bytes, not
        // that generate_image made them. Reject a file the agent drew itself.
        // The narration tail rides along like every other failure path here: it
        // carries WHY the tool was skipped (the 429 that triggers a fabricated
        // stand-in is only ever stated there), which the quota card then reads.
        const fabricated = await checkFabrication(scratchDir, AGY_TOOL);
        if (fabricated) {
          removeScratch();
          return finalizeJobFailure(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);
        }
        if (harvested.format === 'png') {
          await copyFileGuarded(stagingPath, outputPath);
          await unlinkGuarded(stagingPath).catch(() => {});
        } else {
          const pngBytes = await sharp(stagingPath).png().toBuffer();
          await atomicWrite(outputPath, pngBytes);
        }
        removeScratch();
        // Degenerate-frame gate (#4173) — before the sidecar, so a decodable but
        // contentless canvas never becomes a gallery record.
        const emptyFrame = await rejectDegenerateFrame(outputPath);
        if (emptyFrame) {
          return finalizeJobFailure(job, jobId, proc, emptyFrame);
        }
        const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
        // `job.renderStartedAtMs` is the queue-ingestion instant generateImage
        // captured, so the spread measures the render itself — not the time the
        // job spent queued behind other renders.
        await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) });
        await autoCleanGeneratedImage({
          cleanC2PA,
          denoise,
          pngPath: outputPath,
          sidecarPath: sidecar,
          mode: IMAGE_GEN_MODE.AGY,
        });
        try {
          const inputImageCount = (meta.initImageFilename ? 1 : 0) + (Array.isArray(meta.referenceImageFilenames) ? meta.referenceImageFilenames.length : 0);
          const { recordAgyImageUsage } = await import('../agyMediaUsage.js');
          await recordAgyImageUsage({
            jobId,
            createdAt: meta.createdAt,
            inputImages: inputImageCount,
            model: meta.imageModel || AGY_IMAGEGEN_IMAGE_MODEL,
          });
        } catch (usageErr) {
          console.error(`❌ Failed to record Antigravity image usage [${jobId.slice(0, 8)}]: ${usageErr.message}`);
        }
        job.status = 'complete';
        if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
        activeJobs.delete(jobId);
        console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (agy)`);
        const result = { filename, path: `/data/images/${filename}` };
        dispatchTerminalEvent(
          jobId,
          () => broadcastSse(job, { type: 'complete', result }),
          () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, path: result.path, filename }),
        );
        closeJobAfterDelay(jobs, jobId);
      } catch (err) {
        await Promise.all([outputPath, join(PATHS.images, `${jobId}.metadata.json`)].map(path => unlinkGuarded(path).catch(() => {})));
        removeScratch();
        // force: true — 'complete' is already stamped above; see
        // createJobFailureFinalizer's doc comment in sseUtils.js.
        finalizeJobFailure(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`, { force: true });
      }
    }).catch(err => {
      // Admission can reject before the publication callback is entered.
      // EventEmitter does not await this listener, so settle the job here too.
      clearTimeout(timeoutTimer);
      removeScratch();
      finalizeJobFailure(job, jobId, proc, `Agy publication admission failed: ${err?.message || err}`);
    });
  });

  // Post-spawn setup. The error/close owners above are already installed, so a
  // throw here must not settle the job or release its scratch dir under a live
  // child: record it, terminate the child, and let close settle after exit.
  try {
    timeoutTimer = setTimeout(() => {
      if (activeProcs.get(jobId) === proc) {
        console.log(`⏱️ agy timed out after ${AGY_TIMEOUT_MS}ms [${jobId.slice(0, 8)}]`);
        terminate(jobId, proc);
      }
    }, AGY_TIMEOUT_MS);

    proc.stdout.on('data', (chunk) => {
      stdoutTail = `${stdoutTail}${chunk}`.slice(-8192);
      broadcastSse(job, { type: 'status', message: 'Running…' });
    });
    proc.stderr.on('data', (chunk) => {
      stderrTail = `${stderrTail}${chunk}`.slice(-32768);
    });
  } catch (err) {
    setupError = err;
    clearTimeout(timeoutTimer);
    terminate(jobId, proc);
  }
}

const finalizeJobFailure = createJobFailureFinalizer({
  jobs,
  activeJobs,
  activeSlots: activeProcs,
  label: 'agy image generation',
  events: imageGenEvents,
  failedPayload: (jobId, reason) => ({ mode: IMAGE_GEN_MODE.AGY, generationId: jobId, error: reason }),
});

async function harvestStagedImage(stagingPath, timeoutMs) {
  const deadline = Date.now() + timeoutMs;
  let sawInvalid = false;
  while (Date.now() < deadline) {
    const fileStat = await stat(stagingPath).catch(() => null);
    if (fileStat?.size > 0) {
      const head = Buffer.alloc(16);
      const handle = await open(stagingPath, 'r').catch(() => null);
      if (handle) {
        const { bytesRead } = await handle.read(head, 0, 16, 0).catch(() => ({ bytesRead: 0 }));
        await handle.close().catch(() => {});
        const detected = detectImageFormat(head.subarray(0, bytesRead));
        if (detected) return { found: true, invalid: false, format: detected.format };
        sawInvalid = true;
      }
    }
    const remainingMs = Math.max(1, deadline - Date.now());
    await sleep(Math.min(250, remainingMs));
  }
  return { found: false, invalid: sawInvalid };
}

export const _internals = {
  harvestStagedImage,
  buildAgyPrompt,
  setHarvestTimeoutForTests: (timeoutMs = DEFAULT_HARVEST_TIMEOUT_MS) => {
    harvestTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
      ? timeoutMs
      : DEFAULT_HARVEST_TIMEOUT_MS;
  },
};