All files / src/skill-builder agentic.ts

21.05% Statements 16/76
16.21% Branches 12/74
10% Functions 1/10
21.62% Lines 16/74

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                  4x 4x 4x 4x                                                                                                                                                                                                                                                                                                                                                                                                                       82x 82x 82x                             82x     82x           82x             82x 82x       82x                                                                                       82x                                   82x   82x                
import { performance } from 'node:perf_hooks';
import { z } from 'zod';
import type { ToolName } from '../config/schema.js';
import type { UsageStats } from '../types/index.js';
import { parseJsonFromOutput, type ParseJsonFromOutputResult } from '../sdk/json-output.js';
import { buildJsonOutputSection, buildTaggedSection, joinPromptSections } from '../sdk/prompt-sections.js';
import { aggregateUsage, emptyUsage } from '../sdk/usage.js';
import type { Runtime, SkillRunResult } from '../sdk/runtimes/index.js';
 
const SKILL_BUILDER_READ_TOOLS: ToolName[] = ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch'];
const SKILL_BUILDER_WRITE_TOOLS: ToolName[] = ['Read', 'Grep', 'Glob', 'Write', 'Edit', 'Bash', 'WebFetch', 'WebSearch'];
const STRUCTURED_REPAIR_MAX_TURNS = 1;
const STRUCTURED_REPAIR_MAX_CHARS = 60_000;
 
export interface StructuredSkillBuilderAgentResult<T> {
  data: T;
  usage: UsageStats;
  durationMs: number;
  responseModel?: string;
  numTurns?: number;
}
 
interface StructuredSkillBuilderAgentFailureDetails {
  rawText?: string;
  stderr?: string;
  usage?: UsageStats;
  durationMs?: number;
  responseModel?: string;
  numTurns?: number;
}
 
export class StructuredSkillBuilderAgentError extends Error {
  constructor(message: string, options?: { cause?: unknown }) {
    super(message, options);
    this.name = 'StructuredSkillBuilderAgentError';
  }
}
 
function formatRuntimeFailure(result: SkillRunResult): string {
  if (result.errors.length > 0) {
    return result.errors.join('; ');
  }
  return `Runtime status: ${result.status}`;
}
 
function previewText(value: string | undefined, maxLength = 1200): string {
  const trimmed = value?.trim();
  if (!trimmed) return '<empty>';
  if (trimmed.length <= maxLength) return trimmed;
  return `${trimmed.slice(0, maxLength)}...`;
}
 
function formatAgentFailure(message: string, details: StructuredSkillBuilderAgentFailureDetails): string {
  const lines = [message];
  if (details.responseModel) {
    lines.push(`  Model: ${details.responseModel}`);
  }
  if (details.durationMs !== undefined) {
    lines.push(`  Duration: ${(details.durationMs / 1000).toFixed(1)}s`);
  }
  if (details.usage) {
    lines.push(
      `  Usage: ${details.usage.inputTokens.toLocaleString()} input / ` +
      `${details.usage.outputTokens.toLocaleString()} output tokens / ` +
      `$${details.usage.costUSD.toFixed(4)}`
    );
  }
  if (details.numTurns !== undefined) {
    lines.push(`  Turns: ${details.numTurns}`);
  }
  if (details.stderr?.trim()) {
    lines.push('  Claude Code stderr:');
    lines.push(`  ${previewText(details.stderr).replace(/\n/g, '\n  ')}`);
  }
  if (details.rawText !== undefined) {
    lines.push('  Raw output:');
    lines.push(`  ${previewText(details.rawText).replace(/\n/g, '\n  ')}`);
  }
  return lines.join('\n');
}
 
function resultFailureDetails(
  result: SkillRunResult | undefined,
  stderr: string | undefined,
  startedAt: number,
): StructuredSkillBuilderAgentFailureDetails {
  return {
    rawText: result?.text,
    stderr,
    usage: result?.usage,
    durationMs: result?.durationMs ?? performance.now() - startedAt,
    responseModel: result?.responseModel,
    numTurns: result?.numTurns,
  };
}
 
function truncateForRepair(output: string): string {
  if (output.length <= STRUCTURED_REPAIR_MAX_CHARS) {
    return output;
  }
  return `${output.slice(0, STRUCTURED_REPAIR_MAX_CHARS)}\n[... truncated]`;
}
 
function structuredRepairSystemPrompt(): string {
  return `You repair model output into strict JSON for Warden.
 
Return only valid JSON matching the provided JSON Schema. Do not include markdown, prose, code fences, or explanations. Preserve the original structured content whenever possible and do not invent extra fields.`;
}
 
function structuredRepairPrompt<T>(args: {
  schema: z.ZodType<T>;
  output: string;
  reason: string;
}): string {
  return joinPromptSections([
    `<task>
Repair this model output into valid JSON that matches the provided JSON Schema.
</task>`,
    buildJsonOutputSection(`Remove surrounding prose or markdown only when needed.
Preserve the original structured content as much as possible.
Do not invent extra fields.`),
    buildTaggedSection('parse_error', args.reason),
    buildTaggedSection('json_schema', JSON.stringify(z.toJSONSchema(args.schema), null, 2)),
    buildTaggedSection('model_output', truncateForRepair(args.output)),
  ]);
}
 
async function repairStructuredSkillBuilderOutput<T>(args: {
  runtime: Runtime;
  repoPath: string;
  skillName: string;
  apiKey?: string;
  schema: z.ZodType<T>;
  output: string;
  reason: string;
  model?: string;
  abortController?: AbortController;
}): Promise<ParseJsonFromOutputResult<T>> {
  const response = await args.runtime.runSkill({
    apiKey: args.apiKey,
    systemPrompt: structuredRepairSystemPrompt(),
    userPrompt: structuredRepairPrompt({
      schema: args.schema,
      output: args.output,
      reason: args.reason,
    }),
    repoPath: args.repoPath,
    skillName: `${args.skillName}:structured-output-repair`,
    tools: { allowed: [] },
    options: {
      model: args.model,
      maxTurns: STRUCTURED_REPAIR_MAX_TURNS,
      abortController: args.abortController,
    },
  });
 
  if (response.authError) {
    return {
      success: false,
      error: `repair_failed: ${response.authError}`,
    };
  }
  if (!response.result) {
    return {
      success: false,
      error: 'repair_failed: no_result',
    };
  }
  if (response.result.status !== 'success') {
    return {
      success: false,
      error: `repair_failed: ${formatRuntimeFailure(response.result)}`,
      usage: response.result.usage,
    };
  }
 
  const parsed = await parseJsonFromOutput({
    output: response.result.text,
    schema: args.schema,
  });
  if (!parsed.success) {
    return {
      success: false,
      error: `repair_failed: ${parsed.error}`,
      json: parsed.json,
      usage: response.result.usage,
    };
  }
 
  return {
    success: true,
    data: parsed.data,
    json: parsed.json,
    repaired: true,
    usage: response.result.usage,
  };
}
 
export async function runStructuredSkillBuilderAgent<T>(args: {
  runtime: Runtime;
  repoPath: string;
  skillName: string;
  systemPrompt: string;
  userPrompt: string;
  schema: z.ZodType<T>;
  model?: string;
  maxTurns?: number;
  writeAccess?: boolean;
  abortController?: AbortController;
  apiKey?: string;
  repair?: {
    apiKey?: string;
    model?: string;
    maxRetries?: number;
  };
}): Promise<StructuredSkillBuilderAgentResult<T>> {
  const startedAt = performance.now();
  const { runtime } = args;
  const response = await runtime.runSkill({
    apiKey: args.apiKey ?? args.repair?.apiKey,
    systemPrompt: args.systemPrompt,
    userPrompt: args.userPrompt,
    repoPath: args.repoPath,
    skillName: args.skillName,
    tools: { allowed: args.writeAccess ? SKILL_BUILDER_WRITE_TOOLS : SKILL_BUILDER_READ_TOOLS },
    allowMutatingTools: args.writeAccess,
    options: {
      model: args.model,
      maxTurns: args.maxTurns,
      abortController: args.abortController,
    },
  });
 
  Iif (response.authError) {
    throw new StructuredSkillBuilderAgentError(response.authError);
  }
  Iif (!response.result) {
    throw new StructuredSkillBuilderAgentError(formatAgentFailure(
      'Skill builder agent returned no result',
      resultFailureDetails(undefined, response.stderr, startedAt),
    ));
  }
  Iif (response.result.status !== 'success') {
    throw new StructuredSkillBuilderAgentError(formatAgentFailure(
      formatRuntimeFailure(response.result),
      resultFailureDetails(response.result, response.stderr, startedAt),
    ));
  }
 
  const repairUsages: UsageStats[] = [];
  let parsed = await parseJsonFromOutput({
    output: response.result.text,
    schema: args.schema,
  });
  Iif (!parsed.success) {
    const skillRepair = await repairStructuredSkillBuilderOutput({
      runtime,
      repoPath: args.repoPath,
      skillName: args.skillName,
      apiKey: args.apiKey ?? args.repair?.apiKey,
      schema: args.schema,
      output: response.result.text,
      reason: parsed.error,
      model: args.repair?.model ?? args.model,
      abortController: args.abortController,
    });
    if (skillRepair.usage) {
      repairUsages.push(skillRepair.usage);
    }
    if (skillRepair.success) {
      parsed = skillRepair;
    } else if (args.repair?.apiKey) {
      const auxiliaryRepair = await parseJsonFromOutput({
        output: response.result.text,
        schema: args.schema,
        repair: {
          runtime,
          agentName: args.skillName,
          apiKey: args.repair.apiKey,
          model: args.repair.model,
          maxRetries: args.repair.maxRetries,
        },
      });
      if (auxiliaryRepair.usage) {
        repairUsages.push(auxiliaryRepair.usage);
      }
      parsed = auxiliaryRepair.success
        ? auxiliaryRepair
        : {
          ...auxiliaryRepair,
          error: `${skillRepair.error}; ${auxiliaryRepair.error}`,
          json: auxiliaryRepair.json ?? skillRepair.json ?? parsed.json,
        };
    } else {
      parsed = skillRepair;
    }
  }
 
  Iif (!parsed.success) {
    const label = parsed.error.startsWith('no_json')
      ? `Skill builder agent returned no JSON: ${parsed.error}`
      : parsed.error.startsWith('invalid_json')
        ? `Skill builder agent returned invalid JSON: ${parsed.error}`
        : `Skill builder agent output failed validation or repair: ${parsed.error}`;
    throw new StructuredSkillBuilderAgentError(
      formatAgentFailure(
        label,
        {
          ...resultFailureDetails(response.result, response.stderr, startedAt),
          rawText: parsed.json ?? response.result.text,
          usage: aggregateUsage([response.result.usage ?? emptyUsage(), ...repairUsages]),
        },
      ),
    );
  }
 
  const usage = aggregateUsage([response.result.usage ?? emptyUsage(), ...repairUsages]);
 
  return {
    data: parsed.data,
    usage,
    durationMs: response.result.durationMs ?? performance.now() - startedAt,
    responseModel: response.result.responseModel,
    numTurns: response.result.numTurns,
  };
}