← Files RivetARCHIVED FILE
node_modules/rivet-design/dist/services/VariantRunService.js
16.8 KB · Nov 7, 2026 · 13:16 UTC
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VariantRunService = void 0;
const guidance_1 = require("../types/guidance");
const guidanceDelivery_1 = require("./guidanceDelivery");
const ProjectStorage_1 = require("./ProjectStorage");
const profileContext_1 = require("./profiles/profileContext");
const profileAccount_1 = require("./profiles/profileAccount");
const generationGuidance_1 = require("./generationGuidance");
const crypto_1 = require("crypto");
const variantContext_1 = require("../agent-variants/variantContext");
const index_core_1 = require("../index-core");
const agent_variants_1 = require("../agent-variants");
const changeBatchClassification_1 = require("../mcp/changeBatchClassification");
const workerRuntime_1 = require("../agent-variants/workerRuntime");
const VariantGenerationService_1 = require("./VariantGenerationService");
const WorkerExecutorService_1 = require("../agent-variants/WorkerExecutorService");
const log = (0, index_core_1.createLogger)('VariantRunService');
const MAX_RELEVANT_FILES = 12;
const relevantFilesForTarget = (request) => Array.from(new Set([
...request.sourceFiles,
...request.changes.flatMap((change) => 'element' in change ? (change.element.filePaths ?? []) : []),
]
.map((file) => file.trim())
.filter(Boolean))).slice(0, MAX_RELEVANT_FILES);
class VariantRunService {
activeIntakes = 0;
storage;
projectPath;
prepareProfile;
prepareGuidance;
bridge;
orchestrator;
executor;
history;
elementVariantService;
constructor(options) {
this.prepareProfile = options.prepareProfile;
this.history = options.history;
this.prepareGuidance = options.prepareGuidance;
this.storage = options.storage;
this.projectPath = options.projectPath;
this.bridge = options.bridge;
this.orchestrator = options.orchestrator;
this.executor = options.executor;
this.elementVariantService = new VariantGenerationService_1.VariantGenerationService({
bridge: options.bridge,
storage: options.storage,
onGeneratedProject: options.onGeneratedProject,
orchestrator: options.orchestrator,
projectPath: options.projectPath,
staticEntry: options.staticEntry,
createSessionId: options.createSessionId,
...(options.executor ? { executor: options.executor } : {}),
recordGuidance: (args) => this.recordGuidance(args),
});
}
async startElementVariants(request) {
return this.runRequest(request, (prepared) => this.elementVariantService.processVariantRequest(prepared));
}
refineVariant(args) {
return this.orchestrator.refineVariant(args);
}
async completeHostWork(args) {
const workItem = this.orchestrator
.getHostWork(args.sessionId)
.find((item) => item.workId === args.workItemId);
if (!workItem) {
const acceptedStatus = this.orchestrator.getWorkItemStatus(args.sessionId, args.workItemId);
if (acceptedStatus === 'succeeded' ||
acceptedStatus === 'failed' ||
acceptedStatus === 'cancelled') {
return {
stage: this.orchestrator.getStage(args.sessionId),
progress: this.orchestrator.getProgress(args.sessionId),
acceptedStatus,
alreadyCompleted: true,
};
}
throw new agent_variants_1.AgentVariantsError('INVALID_STAGE_ACTION', `Host work item ${args.workItemId} is ${acceptedStatus} and has no active lease`);
}
if ((workItem.kind === 'static_preview' ||
workItem.kind === 'refine_variant') &&
args.output !== undefined) {
throw new agent_variants_1.AgentVariantsError('SCHEMA_VALIDATION_FAILED', 'Static host work completes from its assigned workspace; do not send inline output.');
}
const output = args.output ??
(workItem.kind === 'code_gen' &&
workItem.workspace.kind === 'git_worktree'
? { worktreePath: workItem.workspace.rootPath, changedFiles: [] }
: undefined);
const result = await this.orchestrator.reportComplete({
sessionId: args.sessionId,
workItemId: args.workItemId,
leaseId: workItem.leaseId,
attempt: workItem.attempt,
status: args.status,
...(output !== undefined ? { output } : {}),
...(args.error ? { error: args.error } : {}),
...(args.title ? { title: args.title } : {}),
...(args.description ? { description: args.description } : {}),
});
this.bridge.reportFeedback('__RIVET_REFRESH_GIT__');
if (result.requeuedForRegeneration) {
this.orchestrator.requestWork({
sessionId: args.sessionId,
workItemIds: [args.workItemId],
leaseOwner: 'rivet-host-agent',
});
return { ...result, acceptedStatus: 'pending' };
}
const acceptedStatus = this.orchestrator.getWorkItemStatus(args.sessionId, args.workItemId);
return { ...result, acceptedStatus };
}
async refineStaticPreviewBatch(request) {
return this.runRequest(request, (prepared) => this.startStaticPreviewRefinements(prepared));
}
async runRequest(request, generate) {
(0, workerRuntime_1.assertNativeWorkerSelection)({
initiator: request.initiator,
selection: request.workerSelection,
});
const prepared = await this.prepareRequest(request);
this.activeIntakes += 1;
this.bridge.setStatus('APPLYING');
try {
const result = await generate(prepared);
return await this.withProfileContext(prepared, result);
}
finally {
this.activeIntakes -= 1;
if (this.activeIntakes === 0)
this.bridge.setStatus('READY');
}
}
async withProfileContext(request, result) {
if (!result.success)
return result;
const profileContext = await (0, profileContext_1.recordProfileRequest)(request);
(0, generationGuidance_1.assertGenerationGuidance)(request);
const warning = (0, guidance_1.guidanceWarning)(request.guidance ?? []);
return {
...result,
...(warning ? { guidanceWarning: warning } : {}),
guidance: (request.guidance ?? []).map(({ id, title }) => ({
id,
title,
})),
...(profileContext ? { profileContext } : {}),
};
}
async prepareRequest(request) {
const prepared = this.prepareGuidance
? await this.prepareGuidance(request)
: request;
(0, generationGuidance_1.assertGenerationGuidance)(prepared);
const projectPath = this.projectPath ?? this.bridge.getProjectPath();
if (prepared.guidance?.some((document) => document.attachments?.length ||
document.references?.some((reference) => reference.kind !== 'directory' && reference.files?.length)) &&
!projectPath)
throw new Error('Guidance files require a project path for their retained context.');
(0, guidanceDelivery_1.validateGuidanceBudget)(prepared);
const guidance = projectPath
? await (0, guidanceDelivery_1.snapshotGuidance)({
documents: prepared.guidance ?? [],
dataDirectory: (this.storage ?? new ProjectStorage_1.ProjectStorage()).resolve(projectPath).dataDirectory,
})
: prepared.guidance;
const illustrated = { ...prepared, guidance };
const resolved = this.prepareProfile
? await this.prepareProfile(illustrated)
: illustrated;
(0, generationGuidance_1.assertGenerationGuidance)(resolved);
(0, guidanceDelivery_1.validateGuidanceBudget)(resolved);
return {
...resolved,
guidance: resolved.guidance ?? [],
agentRunId: resolved.agentRunId ?? resolved.traceId ?? (0, crypto_1.randomUUID)(),
};
}
recordGuidance(args) {
if (!this.history)
return;
const projectPath = this.projectPath ?? this.bridge.getProjectPath();
const requestId = args.request.agentRunId ?? args.request.traceId;
if (!projectPath || !requestId)
throw new Error('Cannot retain saved context without a project and request ID.');
(0, generationGuidance_1.assertGenerationGuidance)(args.request);
this.history.recordGuidance({
projectPath,
requestId,
workItemIds: args.workItemIds,
guidance: args.request.guidance ?? [],
accountId: args.request.guidanceAccountId,
});
(0, generationGuidance_1.assertGenerationGuidance)(args.request);
}
async startStaticPreviewRefinements(prepared) {
const assertContext = () => {
(0, generationGuidance_1.assertGenerationGuidance)(prepared);
for (const change of prepared.changes)
if (change.kind === 'comment')
(0, profileAccount_1.assertProfileAccount)(change);
};
assertContext();
const request = prepared;
const derived = (0, changeBatchClassification_1.withDerivedStaticPreviewTargets)(prepared);
const targets = (0, changeBatchClassification_1.collectStaticPreviewRefineTargetInstructions)(derived);
const sessionId = targets[0]?.target.sessionId;
if (!sessionId) {
return {
success: false,
error: 'Static preview refine batch carries no target',
};
}
const contextForTarget = (target) => {
const profileInputs = derived.changes.flatMap((change) => {
if (change.kind !== 'comment' || !change.variantRequest)
return [];
const sourceTarget = change.staticPreviewTarget ?? derived.staticPreviewTarget;
if (sourceTarget?.sessionId !== target.sessionId ||
sourceTarget?.variantId !== target.variantId)
return [];
return [
...(change.profileContext
? [
{
transport: 'text',
label: 'Design profile references',
content: change.profileContext,
references: (0, profileContext_1.profileReferences)(change),
},
]
: []),
...(change.images ?? []).map((dataUrl, index) => ({
transport: 'upload',
dataUrl,
references: (0, profileContext_1.profileReferences)(change, dataUrl),
label: `Reference ${index + 1}`,
})),
];
});
return profileInputs.length && this.projectPath && this.storage
? (0, variantContext_1.createVariantContextBundle)({
sessionId: (0, crypto_1.randomUUID)(),
prompt: '',
workspaceRoot: this.projectPath,
dataDirectory: this.storage.resolve(this.projectPath).dataDirectory,
userContextInputs: profileInputs,
})
: undefined;
};
const workerLease = await (0, WorkerExecutorService_1.chooseWorkerLeaseOwner)(this.executor, {
initiator: request.initiator,
selection: request.workerSelection,
});
this.bridge.reportFeedback(targets.some((target) => target.count != null)
? 'Generating new directions from this design.'
: 'Refining this design in place.');
let droppedRefinements = [];
let createdWorkItemIds = [];
try {
assertContext();
({ droppedRefinements, createdWorkItemIds } =
this.orchestrator.beginStaticPreviewRefinements({
beforeDispatch: (workItemIds) => this.recordGuidance({ request: prepared, workItemIds }),
sessionId,
targets: targets.map(({ target, instruction, count, briefs, runLabel, fidelity, element, requestId, }) => {
const relevantFiles = relevantFilesForTarget(derived);
const additionalContext = count != null ? contextForTarget(target) : undefined;
return {
workerSelection: request.workerSelection,
guidance: prepared.guidance ?? [],
variantId: target.variantId,
instruction,
count,
...(briefs ? { briefs } : {}),
...(runLabel ? { runLabel } : {}),
...(fidelity ? { fidelity } : {}),
...(relevantFiles.length > 0 ? { relevantFiles } : {}),
element,
requestId,
...(count != null && additionalContext
? {
additionalContext: {
...additionalContext,
userContext: additionalContext.userContext
.filter((source) => source.transport !== 'prompt')
.map((source) => ({
...source,
id: `${additionalContext.sessionId}_${source.id}`,
})),
},
}
: {}),
};
}),
}));
}
catch (error) {
if (!(error instanceof agent_variants_1.AgentVariantsError))
throw error;
const message = error.message;
log.warn(`Static preview refine intake failed: ${message}`);
this.bridge.reportFeedback(`Refinement failed: ${message}`);
return { success: false, error: message };
}
for (const dropped of droppedRefinements) {
this.bridge.reportFeedback(`Refinement skipped for one design: ${dropped.reason}`);
}
if (createdWorkItemIds.length > 0) {
try {
assertContext();
}
catch (error) {
await Promise.all(createdWorkItemIds.map((variantId) => this.orchestrator.cancelVariant({ sessionId, variantId })));
throw error;
}
log.info(`refine workers: ${workerLease.summary}`);
this.orchestrator.setWorkerRuntime(sessionId, workerLease.summary);
if (workerLease.runtime) {
const lease = this.orchestrator.requestWork({
sessionId,
workItemIds: createdWorkItemIds,
leaseOwner: WorkerExecutorService_1.EXECUTOR_LEASE_OWNER,
});
this.bridge.reportFeedback(`Rivet is building ${createdWorkItemIds.length} direction(s) with its own workers — watch status for progress.`);
void this.executor
?.run(sessionId, createdWorkItemIds, {
leaseId: lease.leaseId,
items: lease.leasedWorkItems,
}, workerLease.runtime, workerLease)
.catch((error) => log.warn('worker executor run failed', error));
}
else {
if (this.executor) {
this.bridge.reportFeedback(`Directions will run via ${workerLease.summary}.`);
}
this.orchestrator.requestWork({
sessionId,
workItemIds: createdWorkItemIds,
leaseOwner: 'rivet-host-agent',
});
}
}
if (droppedRefinements.length > 0) {
return {
success: createdWorkItemIds.length > 0,
error: droppedRefinements[0]?.reason,
};
}
return { success: true };
}
cancelVariants(args) {
this.executor?.cancelSession(args.sessionId);
return this.orchestrator.cancel(args);
}
interruptWorkers() {
const sessionId = this.orchestrator.getActiveSessionId();
if (sessionId)
this.executor?.cancelSession(sessionId);
}
getSnapshot() {
return this.orchestrator.buildActiveSnapshot();
}
}
exports.VariantRunService = VariantRunService;
//# sourceMappingURL=VariantRunService.js.mapSHA-256: f1bdee4682973fa90b6fbb39669dd330cf7097936fef23a6ca83a901189634dc