Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 | 3x 3x 3x 30x 27x 11x 52x 52x 52x 2x 50x 50x 50x 79x 79x 35x 35x 35x 79x 52x 52x 1x 52x 52x 52x 91x 52x 52x 52x 52x 2x 50x 50x 91x 52x 52x 27x 52x 35x 7x 52x 1x 52x 36x 7x 52x 61x 1x 12x 20x 5x 52x 2x 2x 2x 18x 18x 18x 2x 3x 18x 18x 18x 15x 3x 3x 18x 16x 2x 18x 18x 18x 18x 2x 54x 2x 18x 18x 72x 2x 2x 18x 71x 15x 15x 71x 15x 15x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 32x 15x 15x 19x 19x 19x 19x 19x 19x 2x 2x 1x 18x 18x 18x 18x 19x 19x 19x 18x 17x 18x 19x 18x 18x 18x 18x 18x 32x 32x 32x 32x 32x 32x 18x 18x 14x 32x 14x 14x 18x 19x 19x 19x 32x 19x 19x 19x 31x 18x 18x 28x 13x 18x 28x 13x 18x 28x 13x 18x 18x 18x 18x 3x 3x 3x | import { join } from 'node:path';
import { existsSync } from 'node:fs';
import { performance } from 'node:perf_hooks';
import { parse as parseYaml } from 'yaml';
import { aggregateUsage } from '../sdk/usage.js';
import type { Runtime } from '../sdk/runtimes/index.js';
import { runStructuredSkillBuilderAgent, StructuredSkillBuilderAgentError } from './agentic.js';
import type { UsageStats } from '../types/index.js';
import { clearGeneratedSkillArtifacts, readGeneratedSkillArtifactFiles } from './definition.js';
import { resolveAuthoringProvider } from './authoring-provider.js';
import {
type SkillBuildOutline,
type SkillBuildSource,
outlineHash,
} from './outline-contract.js';
import {
getBuildStatePath,
readSkillBuildState,
writeSkillBuildState,
} from './outline-state.js';
import {
GeneratedSkillAuthoringPlanSchema,
type GeneratedSkillAuthoringMode,
GeneratedSkillBuildError,
GeneratedSkillWriterResultSchema,
GeneratedSkillReviewResultSchema,
type GeneratedSkillArtifact,
type GeneratedSkillReviewResult,
type GeneratedSkillWriterResult,
type SkillBuildAuthoringProvider,
type SkillBuildExternalSource,
} from './skill-contract.js';
export { GeneratedSkillBuildError } from './skill-contract.js';
import {
authoringSystemPrompt,
buildAuthoringImplementationPrompt,
buildAuthoringPlanPrompt,
buildAuthoringRevisionPrompt,
buildAuthoringValidationPrompt,
defaultBuildMaxTurns,
defaultValidationMaxTurns,
} from './skill-prompts.js';
const GENERATED_SKILL_ARTIFACT_SCHEMA_VERSION = 5;
const MAX_SKILL_REVIEW_REVISIONS = 3;
const SKILL_FRONTMATTER_PATTERN = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
interface SkillBuilderStepMetrics {
usage: UsageStats;
responseModel?: string;
numTurns?: number;
}
interface SkillBuilderReviewResult extends SkillBuilderStepMetrics {
data: GeneratedSkillReviewResult;
}
interface GeneratedSkillArtifactFile {
path: string;
content: string;
bytes?: number;
}
interface GeneratedSkillArtifactSnapshot {
summary: string;
files: GeneratedSkillArtifactFile[];
validationNotes: string[];
missingInputs: string[];
externalSources: SkillBuildExternalSource[];
}
function filesByteLength(files: { content: string }[]): number {
return files.reduce((sum, file) => sum + Buffer.byteLength(file.content, 'utf-8'), 0);
}
function fileManifest(files: { path: string; content: string }[]): {
path: string;
bytes: number;
}[] {
return files.map((file) => ({
path: file.path,
bytes: Buffer.byteLength(file.content, 'utf-8'),
})).sort((a, b) => a.path.localeCompare(b.path));
}
function skillFrontmatter(content: string): Record<string, unknown> | undefined {
const match = content.match(SKILL_FRONTMATTER_PATTERN);
const frontmatter = match?.[1];
if (!frontmatter) {
return undefined;
}
try {
const parsed = parseYaml(frontmatter);
return parsed && typeof parsed === 'object'
? parsed as Record<string, unknown>
: undefined;
} catch {
return undefined;
}
}
function referencedSkillPaths(content: string): string[] {
const paths = new Set<string>();
for (const match of content.matchAll(/references\/[a-zA-Z0-9][a-zA-Z0-9._/-]*/g)) {
const path = match[0].replace(/[.,;:!?]+$/g, '');
Eif (/[a-zA-Z0-9]$/.test(path)) {
paths.add(path);
}
}
return [...paths].sort();
}
function referencedArtifactPaths(content: string): string[] {
const paths = new Set<string>();
for (const match of content.matchAll(/\b(?:SPEC|SOURCES|EVAL)\.md\b/g)) {
paths.add(match[0]);
}
return [...paths].sort();
}
function deterministicValidation(args: {
files: {
path: string;
content: string;
}[];
targetName: string;
}): {
errors: string[];
warnings: string[];
} {
// Deterministic validation is intentionally mechanical. It protects the
// filesystem and catches non-runnable local references; depth, segmentation,
// source adequacy, and skill-writer compliance belong to the qualitative
// reviewer.
const errors: string[] = [];
const warnings: string[] = [];
const files = new Map(args.files.map((file) => [file.path, file.content]));
const skillMd = files.get('SKILL.md');
Iif (!skillMd) {
errors.push('Generated skill artifacts must include SKILL.md');
return { errors, warnings };
}
const frontmatter = skillFrontmatter(skillMd);
if (!frontmatter) {
errors.push('SKILL.md must start with YAML frontmatter');
} else {
Iif (frontmatter['name'] !== args.targetName) {
errors.push(`SKILL.md frontmatter name must be "${args.targetName}"`);
}
Iif (typeof frontmatter['description'] !== 'string' || !frontmatter['description'].trim()) {
errors.push('SKILL.md frontmatter description is required');
}
}
const referenceFiles = args.files.filter((file) => file.path.startsWith('references/'));
const routedReferenceFiles = referenceFiles.filter((file) => skillMd.includes(file.path));
const routeDocuments = [
skillMd,
...routedReferenceFiles.map((file) => file.content),
];
for (const path of [...new Set(routeDocuments.flatMap(referencedSkillPaths))].sort()) {
if (!files.has(path)) {
warnings.push(`SKILL.md routes ${path} but the generated artifacts do not include it`);
}
}
for (const path of referencedArtifactPaths(skillMd)) {
Iif (!files.has(path)) {
warnings.push(`SKILL.md references ${path} but the generated artifacts do not include it`);
}
}
for (const reference of referenceFiles) {
if (!routeDocuments.some((content) => content.includes(reference.path))) {
warnings.push(`SKILL.md does not route runtime reference ${reference.path}`);
}
}
return { errors, warnings };
}
function formatDeterministicIssues(validation: {
errors: string[];
warnings: string[];
}): string[] {
return [
...validation.errors.map((message) => `error: ${message}`),
...validation.warnings.map((message) => `warning: ${message}`),
];
}
function hasMissingGeneratedFileWarning(validation: {
warnings: string[];
}): boolean {
return validation.warnings.some((warning) =>
warning.includes('generated artifacts do not include it'),
);
}
function reviewNeedsRevision(review: GeneratedSkillReviewResult): boolean {
return !review.valid || review.issues.length > 0;
}
function formatReviewIssue(issue: GeneratedSkillReviewResult['issues'][number]): string {
const location = issue.path ? `${issue.path}: ` : '';
const fix = issue.suggestedFix ? ` Suggested fix: ${issue.suggestedFix}` : '';
return `${location}${issue.message}${fix}`;
}
function finalMechanicalBlockingIssues(deterministic: {
errors: string[];
warnings: string[];
}): string[] {
// Only mechanical runnability blocks the final write. Qualitative reviewer
// feedback is handled by the bounded review loop and recorded as warnings if
// the reviewer still wants changes after the cap.
const issues: string[] = [];
issues.push(...deterministic.errors);
if (hasMissingGeneratedFileWarning(deterministic)) {
issues.push(...deterministic.warnings.filter((warning) =>
warning.includes('generated artifacts do not include it')
));
}
return uniqueStrings(issues);
}
function throwIfMechanicalValidationFailed(args: {
targetName: string;
deterministic: {
errors: string[];
warnings: string[];
};
}): void {
const issues = finalMechanicalBlockingIssues(args.deterministic);
if (issues.length === 0) {
return;
}
throw new GeneratedSkillBuildError(
`Generated skill failed mechanical validation for ${args.targetName}:\n` +
issues.map((issue) => `- ${issue}`).join('\n'),
);
}
function boundedReviewWarnings(args: {
review?: GeneratedSkillReviewResult;
maxRevisions: number;
}): string[] {
if (!args.review || !reviewNeedsRevision(args.review)) {
return [];
}
const plural = args.maxRevisions === 1 ? 'revision pass' : 'revision passes';
const warnings = [
`Authoring reviewer still requested changes after ${args.maxRevisions} ${plural}; using the latest writer draft.`,
];
const issues = args.review.issues.length === 0
? ['Authoring reviewer marked the generated skill invalid without issue details']
: args.review.issues.map(formatReviewIssue);
warnings.push(...issues.slice(0, 5).map((issue) => `Reviewer: ${issue}`));
Iif (issues.length > 5) {
warnings.push(`Reviewer: ${issues.length - 5} more issues omitted from summary`);
}
return warnings;
}
function uniqueStrings(values: string[]): string[] {
return [...new Set(values)].filter((value) => value.trim().length > 0);
}
function isExternalSourceUrl(url: string): boolean {
return /^https?:\/\//i.test(url);
}
function mergeExternalSources(
...sourceSets: SkillBuildExternalSource[][]
): SkillBuildExternalSource[] {
const sources = new Map<string, SkillBuildExternalSource>();
for (const sourceSet of sourceSets) {
for (const source of sourceSet) {
Iif (!isExternalSourceUrl(source.url)) {
continue;
}
sources.set(`${source.title}\n${source.url}`, source);
}
}
return [...sources.values()];
}
function summarizeResponseModel(models: (string | undefined)[]): string | undefined {
const distinct = [...new Set(models.filter((model): model is string => Boolean(model)))];
Eif (distinct.length === 0) {
return undefined;
}
if (distinct.length === 1) {
return distinct[0];
}
return 'multiple';
}
function summarizeTurns(turns: (number | undefined)[]): number | undefined {
const values = turns.filter((turn): turn is number => Number.isFinite(turn));
Eif (values.length === 0) {
return undefined;
}
return values.reduce((sum, value) => sum + value, 0);
}
function zeroUsage(): UsageStats {
return { inputTokens: 0, outputTokens: 0, costUSD: 0 };
}
function loadExistingArtifact(args: {
rootDir: string;
files: {
path: string;
content: string;
}[];
name: string;
}): GeneratedSkillArtifact | undefined {
const validation = deterministicValidation({
files: args.files,
targetName: args.name,
});
Iif (
validation.errors.length > 0 ||
hasMissingGeneratedFileWarning(validation)
) {
return undefined;
}
return {
kind: 'generated-skill',
source: 'cache',
name: args.name,
path: args.rootDir,
bytes: filesByteLength(args.files),
durationMs: 0,
usage: zeroUsage(),
externalSources: [],
missingInputs: [],
warnings: [],
};
}
function loadCachedArtifact(args: {
rootDir: string;
outline: SkillBuildOutline;
source: SkillBuildSource;
authoringProvider: SkillBuildAuthoringProvider;
}): GeneratedSkillArtifact | undefined {
Iif (!existsSync(join(args.rootDir, 'SKILL.md'))) {
return undefined;
}
const files = readGeneratedSkillArtifactFiles(args.rootDir);
const state = readSkillBuildState(getBuildStatePath(args.rootDir));
const metadata = state?.artifact;
if (!metadata) {
return loadExistingArtifact({
rootDir: args.rootDir,
files,
name: args.outline.skill,
});
}
const manifest = fileManifest(files);
const bytes = filesByteLength(files);
Iif (
metadata.sourceHash !== args.source.hash ||
metadata.outlineHash !== outlineHash(args.outline) ||
metadata.buildVersion !== args.outline.buildVersion ||
metadata.authoringProvider.name !== args.authoringProvider.name ||
metadata.authoringProvider.contentHash !== args.authoringProvider.contentHash ||
JSON.stringify(metadata.fileManifest) !== JSON.stringify(manifest) ||
metadata.bytes !== bytes
) {
return undefined;
}
const validation = deterministicValidation({
files,
targetName: metadata.name,
});
Eif (
validation.errors.length > 0 ||
hasMissingGeneratedFileWarning(validation)
) {
return undefined;
}
return {
kind: 'generated-skill',
source: 'cache',
name: metadata.name,
path: args.rootDir,
bytes,
durationMs: metadata.durationMs,
usage: metadata.usage,
externalSources: metadata.externalSources,
missingInputs: metadata.missingInputs,
warnings: metadata.authoringWarnings,
responseModel: metadata.responseModel,
numTurns: metadata.numTurns,
};
}
function readArtifactSnapshot(args: {
rootDir: string;
writer: GeneratedSkillWriterResult;
}): GeneratedSkillArtifactSnapshot {
return {
summary: args.writer.summary,
files: readGeneratedSkillArtifactFiles(args.rootDir),
validationNotes: args.writer.validationNotes,
missingInputs: args.writer.missingInputs,
externalSources: args.writer.externalSources,
};
}
function artifactFromDisk(args: {
rootDir: string;
name: string;
durationMs: number;
usage: UsageStats;
externalSources: SkillBuildExternalSource[];
missingInputs: string[];
warnings: string[];
responseModel?: string;
numTurns?: number;
}): GeneratedSkillArtifact {
const files = readGeneratedSkillArtifactFiles(args.rootDir);
return {
kind: 'generated-skill',
source: 'generated',
name: args.name,
path: args.rootDir,
bytes: filesByteLength(files),
durationMs: args.durationMs,
usage: args.usage,
externalSources: args.externalSources,
missingInputs: args.missingInputs,
warnings: args.warnings,
responseModel: args.responseModel,
numTurns: args.numTurns,
};
}
export async function buildGeneratedSkill(args: {
outline: SkillBuildOutline;
source: SkillBuildSource;
rootDir: string;
runtime: Runtime;
repoPath: string;
mode?: GeneratedSkillAuthoringMode;
improvementPrompt?: string;
model?: string;
maxTurns?: number;
abortController?: AbortController;
regenerate?: boolean;
apiKey?: string;
repairModel?: string;
repairMaxRetries?: number;
authoringSkillRoot?: string;
onStatus?: (message: string) => void;
}): Promise<GeneratedSkillArtifact> {
const startedAt = performance.now();
const statePath = getBuildStatePath(args.rootDir);
const mode = args.mode ?? 'build';
const authoringProvider = resolveAuthoringProvider({
authoringSkillRoot: args.authoringSkillRoot,
});
try {
if (mode === 'build' && !args.regenerate) {
const cached = loadCachedArtifact({
rootDir: args.rootDir,
outline: args.outline,
source: args.source,
authoringProvider,
});
if (cached) {
return cached;
}
}
const previousState = readSkillBuildState(statePath);
Iif (!previousState) {
throw new GeneratedSkillBuildError(
`Missing generated skill outline state for ${args.outline.skill}`,
);
}
Iif (mode === 'improve' && !args.improvementPrompt?.trim()) {
throw new GeneratedSkillBuildError(
`Missing improvement brief for ${args.outline.skill}`,
);
}
const maxTurns = args.maxTurns ?? defaultBuildMaxTurns();
const repair = {
apiKey: args.apiKey,
model: args.repairModel,
maxRetries: args.repairMaxRetries,
};
args.onStatus?.('Planning authoring run');
const plan = await runStructuredSkillBuilderAgent({
runtime: args.runtime,
repoPath: args.repoPath,
skillName: `${args.outline.skill}:authoring-plan`,
systemPrompt: authoringSystemPrompt(),
userPrompt: buildAuthoringPlanPrompt({
outline: args.outline,
source: args.source,
authoringSkillRoot: authoringProvider.rootDir,
targetName: args.outline.skill,
targetRootDir: args.rootDir,
mode,
improvementPrompt: args.improvementPrompt,
}),
schema: GeneratedSkillAuthoringPlanSchema,
model: args.model,
maxTurns,
apiKey: args.apiKey,
abortController: args.abortController,
repair,
});
if (mode === 'build') {
clearGeneratedSkillArtifacts(args.rootDir);
}
args.onStatus?.(mode === 'improve' ? 'Improving skill artifacts' : 'Writing skill artifacts');
const implementation = await runStructuredSkillBuilderAgent({
runtime: args.runtime,
repoPath: args.rootDir,
skillName: `${args.outline.skill}:authoring-implementation`,
systemPrompt: authoringSystemPrompt(),
userPrompt: buildAuthoringImplementationPrompt({
outline: args.outline,
source: args.source,
authoringSkillRoot: authoringProvider.rootDir,
targetName: args.outline.skill,
targetRootDir: args.rootDir,
plan: plan.data,
mode,
improvementPrompt: args.improvementPrompt,
}),
schema: GeneratedSkillWriterResultSchema,
model: args.model,
maxTurns,
apiKey: args.apiKey,
writeAccess: true,
abortController: args.abortController,
repair,
});
let workingArtifact = readArtifactSnapshot({
rootDir: args.rootDir,
writer: implementation.data,
});
const reviewResults: SkillBuilderReviewResult[] = [];
const revisionResults: SkillBuilderStepMetrics[] = [];
let latestReview: GeneratedSkillReviewResult | undefined;
let reviewHitRevisionLimit = false;
for (let reviewRound = 0; ; reviewRound += 1) {
const deterministic = deterministicValidation({
files: workingArtifact.files,
targetName: args.outline.skill,
});
// The reviewer is the quality gate: it judges whether the generated skill
// satisfies skill-writer, the source-depth plan, and Warden's runtime bar.
// The deterministic notes below are only rough mechanical signals.
args.onStatus?.(reviewRound === 0
? 'Reviewing generated skill'
: 'Reviewing revised skill');
const review = await runStructuredSkillBuilderAgent({
runtime: args.runtime,
repoPath: args.rootDir,
skillName: `${args.outline.skill}:authoring-validation`,
systemPrompt: authoringSystemPrompt(),
userPrompt: buildAuthoringValidationPrompt({
outline: args.outline,
source: args.source,
authoringSkillRoot: authoringProvider.rootDir,
targetName: args.outline.skill,
targetRootDir: args.rootDir,
plan: plan.data,
artifact: workingArtifact,
deterministicIssues: formatDeterministicIssues(deterministic),
mode,
improvementPrompt: args.improvementPrompt,
}),
schema: GeneratedSkillReviewResultSchema,
model: args.model,
maxTurns: Math.min(maxTurns, defaultValidationMaxTurns()),
apiKey: args.apiKey,
abortController: args.abortController,
repair,
});
reviewResults.push(review);
latestReview = review.data;
if (
!reviewNeedsRevision(review.data) ||
revisionResults.length >= MAX_SKILL_REVIEW_REVISIONS
) {
reviewHitRevisionLimit = reviewNeedsRevision(review.data) &&
revisionResults.length >= MAX_SKILL_REVIEW_REVISIONS;
break;
}
args.onStatus?.(`Revising generated skill (${revisionResults.length + 1}/${MAX_SKILL_REVIEW_REVISIONS})`);
const revision = await runStructuredSkillBuilderAgent({
runtime: args.runtime,
repoPath: args.rootDir,
skillName: `${args.outline.skill}:authoring-revision`,
systemPrompt: authoringSystemPrompt(),
userPrompt: buildAuthoringRevisionPrompt({
outline: args.outline,
source: args.source,
authoringSkillRoot: authoringProvider.rootDir,
targetName: args.outline.skill,
targetRootDir: args.rootDir,
plan: plan.data,
artifact: workingArtifact,
review: review.data,
deterministicIssues: formatDeterministicIssues(deterministic),
mode,
improvementPrompt: args.improvementPrompt,
}),
schema: GeneratedSkillWriterResultSchema,
model: args.model,
maxTurns,
apiKey: args.apiKey,
writeAccess: true,
abortController: args.abortController,
repair,
});
revisionResults.push(revision);
workingArtifact = readArtifactSnapshot({
rootDir: args.rootDir,
writer: revision.data,
});
}
const previousArtifactExternalSources = mode === 'improve'
? previousState.artifact?.externalSources ?? []
: [];
const previousArtifactMissingInputs = mode === 'improve'
? previousState.artifact?.missingInputs ?? []
: [];
const finalExternalSources = mergeExternalSources(
previousArtifactExternalSources,
args.outline.build.externalSources ?? [],
plan.data.externalSources,
workingArtifact.externalSources,
);
const finalMissingInputs = uniqueStrings([
...previousArtifactMissingInputs,
...plan.data.missingInputs,
...workingArtifact.missingInputs,
...reviewResults.flatMap((result) => result.data.missingInputs),
]);
const finalWarnings = uniqueStrings([
...boundedReviewWarnings({
review: reviewHitRevisionLimit ? latestReview : undefined,
maxRevisions: MAX_SKILL_REVIEW_REVISIONS,
}),
]);
workingArtifact = {
...workingArtifact,
externalSources: finalExternalSources,
missingInputs: finalMissingInputs,
};
const finalDeterministic = deterministicValidation({
files: workingArtifact.files,
targetName: args.outline.skill,
});
Iif (!workingArtifact.files.some((file) => file.path === 'SKILL.md')) {
throw new GeneratedSkillBuildError(
`Generated skill build did not produce SKILL.md for ${args.outline.skill}`,
);
}
throwIfMechanicalValidationFailed({
targetName: args.outline.skill,
deterministic: finalDeterministic,
});
const usage = aggregateUsage([
plan.usage,
implementation.usage,
...reviewResults.map((result) => result.usage),
...revisionResults.map((result) => result.usage),
]);
const responseModel = summarizeResponseModel([
plan.responseModel,
implementation.responseModel,
...reviewResults.map((result) => result.responseModel),
...revisionResults.map((result) => result.responseModel),
]);
const numTurns = summarizeTurns([
plan.numTurns,
implementation.numTurns,
...reviewResults.map((result) => result.numTurns),
...revisionResults.map((result) => result.numTurns),
]);
const artifact = artifactFromDisk({
rootDir: args.rootDir,
name: args.outline.skill,
durationMs: performance.now() - startedAt,
usage,
externalSources: finalExternalSources,
missingInputs: finalMissingInputs,
warnings: finalWarnings,
responseModel,
numTurns,
});
const writtenFiles = readGeneratedSkillArtifactFiles(args.rootDir);
writeSkillBuildState(statePath, {
...previousState,
artifact: {
version: GENERATED_SKILL_ARTIFACT_SCHEMA_VERSION,
sourceHash: args.source.hash,
outlineHash: outlineHash(args.outline),
buildVersion: args.outline.buildVersion,
authoringProvider,
name: artifact.name,
fileManifest: fileManifest(writtenFiles),
deterministicWarnings: formatDeterministicIssues(finalDeterministic),
bytes: artifact.bytes,
durationMs: artifact.durationMs,
usage: artifact.usage,
externalSources: artifact.externalSources,
missingInputs: finalMissingInputs,
authoringWarnings: finalWarnings,
responseModel: artifact.responseModel,
numTurns: artifact.numTurns,
generatedAt: new Date().toISOString(),
},
updatedAt: new Date().toISOString(),
});
return {
...artifact,
missingInputs: finalMissingInputs,
warnings: finalWarnings,
};
} catch (error) {
Eif (error instanceof GeneratedSkillBuildError) {
throw error;
}
const operation = mode === 'improve' ? 'improvement' : 'build';
Iif (error instanceof StructuredSkillBuilderAgentError) {
throw new GeneratedSkillBuildError(
`Generated skill ${operation} failed for ${args.outline.skill}: ${error.message}`,
{ cause: error },
);
}
if (error instanceof Error) {
throw new GeneratedSkillBuildError(
`Generated skill ${operation} failed for ${args.outline.skill}: ${error.message}`,
{ cause: error },
);
}
throw error;
}
}
|