]*\\bdata-impeccable-variant=(?:"${attr}"|'${attr}')[^>]*>`, 'i');
const match = open.exec(body);
if (!match) throw workerError('worker_output_source_delta_variant_missing', { variant });
const json = JSON.stringify(params[String(variant)])
.replaceAll('&', '&')
.replaceAll("'", ''');
const nextOpen = match[0]
.replace(/\sdata-impeccable-params=(?:"[^"]*"|'[^']*')/i, '')
.replace(/>$/, ` data-impeccable-params='${json}'>`);
body = body.slice(0, match.index) + nextOpen + body.slice(match.index + match[0].length);
}
return source.slice(0, wrapper.openStart) + body + source.slice(wrapper.closeEnd);
}
function findSessionEndMarker(source, sessionId, wrapper) {
const marker = `impeccable-variants-end ${sessionId}`;
const markerAt = source.indexOf(marker, wrapper.openStart);
if (markerAt < 0 || markerAt >= wrapper.closeStart) return null;
const lineStart = source.lastIndexOf('\n', markerAt) + 1;
const indent = source.slice(lineStart, markerAt).match(/^\s*/)?.[0] || '';
return { lineStart, indent };
}
function normalizeVariantPlan(plan, expectedVariants) {
if (!plan || typeof plan !== 'object' || Array.isArray(plan)) {
throw workerError('worker_output_plan_invalid');
}
const identityLock = Array.isArray(plan.identityLock)
? plan.identityLock.map((item) => String(item || '').trim()).filter(Boolean)
: [];
const directions = Array.isArray(plan.directions) ? plan.directions : [];
if (identityLock.length < 1 || identityLock.length > 8 || directions.length !== Number(expectedVariants)) {
throw workerError('worker_output_plan_invalid');
}
const normalizedDirections = directions.map((direction) => ({
variantId: Number(direction?.variantId),
name: String(direction?.name || '').trim(),
axis: String(direction?.axis || '').trim(),
intent: String(direction?.intent || '').trim(),
}));
const expectedIds = Array.from({ length: Number(expectedVariants) }, (_, index) => index + 1);
const sortedIds = normalizedDirections.map((direction) => direction.variantId).sort((a, b) => a - b);
if (normalizedDirections.some((direction) => (
!Number.isInteger(direction.variantId)
|| !direction.name
|| !direction.axis
|| !direction.intent
)) || sortedIds.some((id, index) => id !== expectedIds[index])) {
throw workerError('worker_output_plan_invalid');
}
return { identityLock, directions: normalizedDirections };
}
export function prepareCodexWorkerPhase({ id, sourceFile, cwd = process.cwd() }) {
const prepared = prepareGenerationArtifact({ id, sourceFile, cwd });
if (!prepared.ok) throw workerError(`prepare_${prepared.error}`, prepared);
return prepared;
}
export function publishCodexWorkerPhase({
event,
prepared,
arrivedVariants,
phase,
cwd = process.cwd(),
}) {
const published = publishGenerationArtifact({
id: event.id,
epoch: prepared.epoch,
sourceFile: event.scaffold.file,
artifactFile: prepared.artifactFile,
expectedSourceHash: prepared.expectedSourceHash,
arrivedVariants,
expectedVariants: Number(event.count || arrivedVariants),
publicationKind: ['remainder', 'params', 'atomic'].includes(phase) ? 'params' : 'variants',
cwd,
});
if (!published.ok) throw workerError(`publish_${published.error}`, published);
return published;
}
export function generationIsCanceled(eventId, { cwd = process.cwd() } = {}) {
const snapshot = createLiveSessionStore({ cwd, sessionId: eventId }).getSnapshot(eventId, { includeCompleted: true });
return snapshot?.generationCanceled === true;
}
export function codexWorkerStateIsOwned(state, cwd) {
return codexWorkerOwnerMatches(state, cwd)
&& typeof state?.threadId === 'string'
&& state.threadId.length > 0;
}
export function isCodexComponentPreviewMode(value) {
return value === 'svelte-component' || value === 'vue-component';
}
export function codexWorkerProcessStateIsOwned(state, cwd) {
return codexWorkerOwnerMatches(state, cwd)
&& Number.isInteger(state?.pid)
&& state.pid > 0;
}
function codexWorkerOwnerMatches(state, cwd) {
return state?.owner === CODEX_WORKER_OWNER
&& canonicalPath(state?.cwd) === canonicalPath(cwd);
}
function canonicalPath(value) {
if (!value || typeof value !== 'string') return null;
const resolved = path.resolve(value);
try { return fs.realpathSync.native(resolved); } catch { return resolved; }
}
function sanitizeEvent(event) {
const copy = { ...event };
delete copy.agentAction;
delete copy._acceptResult;
delete copy._completionAck;
return copy;
}
function findSessionWrapper(source, sessionId) {
const escapedId = escapeRegExp(sessionId);
const open = new RegExp(`
]*\\bdata-impeccable-variants=(?:"${escapedId}"|'${escapedId}')[^>]*>`, 'i');
const wrapperOpen = open.exec(source);
if (!wrapperOpen) return null;
const token = /
]*\/\s*>|
]*>|<\/div\s*>/gi;
token.lastIndex = wrapperOpen.index;
let depth = 0;
let match;
while ((match = token.exec(source))) {
if (/^<\/div/i.test(match[0])) {
depth -= 1;
if (depth === 0) {
const lineStart = source.lastIndexOf('\n', wrapperOpen.index) + 1;
const indent = source.slice(lineStart, wrapperOpen.index).match(/^\s*/)?.[0] || '';
return {
openStart: wrapperOpen.index,
closeStart: match.index,
closeEnd: token.lastIndex,
indent,
};
}
} else if (!/\/\s*>$/.test(match[0])) {
depth += 1;
}
}
return null;
}
function extractSourceVariantBlock(source, variantId) {
const attr = escapeRegExp(String(variantId));
return new RegExp(`
]*\\bdata-impeccable-variant=(?:"${attr}"|'${attr}')[^>]*>`, 'i').test(source);
}
function parseWorkerJson(value) {
const text = String(value || '').trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
try {
return JSON.parse(text);
} catch (error) {
throw workerError('worker_output_json_invalid', { message: error.message });
}
}
function parseBoolean(value) {
if (value == null || value === '') return null;
if (/^(?:1|true|yes|on)$/i.test(String(value))) return true;
if (/^(?:0|false|no|off)$/i.test(String(value))) return false;
return null;
}
function nonEmpty(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function positiveInteger(value, fallback) {
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}
function resolveInside(root, value) {
if (!value || typeof value !== 'string') return null;
const resolvedRoot = path.resolve(root);
const resolved = path.resolve(resolvedRoot, value);
const relative = path.relative(resolvedRoot, resolved);
if (!relative || (!relative.startsWith('..') && !path.isAbsolute(relative))) return resolved;
return null;
}
function readBounded(file, maxBytes) {
const stat = fs.statSync(file);
if (stat.size > maxBytes) throw workerError('artifact_too_large', { bytes: stat.size });
return fs.readFileSync(file, 'utf-8');
}
function workerError(code, detail = {}) {
const error = new Error(code);
error.code = code;
Object.assign(error, detail);
return error;
}
function escapeRegExp(value) {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}