Skip to main content
Low-level building blocks exposed from @withboundary/contract. All are pure, synchronous, and side-effect free.
import {
  clean,
  verify,
  classify,
  repair,
  instructions,
  createConsoleLogger,
} from "@withboundary/contract";
Usage guide: Engine primitives.

clean

function clean(raw: string | null | undefined): unknown;
Normalize raw LLM output into a parsed JSON value.
InputOutput
null / ""null
"```json\n{\"a\":1}\n```"{ a: 1 }
"Here's the answer: {\"a\":1}"{ a: 1 }
"no json here"null
Malformed JSONnull (or the original raw — callers should still validate)

verify

function verify<T>(
  data: unknown,
  schema: ContractSchema<T>,
  rules?: Rule<T>[],
): ContractResult<T>;
Validate data against schema and, if provided, every rule. Returns the same ContractResult<T> shape contract.accept returns. No LLM involved.
  • result.ok === true → data passed schema and all rules. result.data is typed T.
  • result.ok === falseresult.error.attempts[0] has the failure category ("VALIDATION_ERROR" or "RULE_ERROR") and the list of issues.

classify

function classify(raw: string, cleaned: unknown): FailureCategory;
Categorize a failed response. Returns one of:
"EMPTY_RESPONSE" | "REFUSAL" | "NO_JSON" | "TRUNCATED" |
"PARSE_ERROR" | "VALIDATION_ERROR" | "RULE_ERROR" | "RUN_ERROR"
Based on the combination of raw string and parsed result:
rawcleanedCategory
"" / nullEMPTY_RESPONSE
contains refusal languagenullREFUSAL
has text but no JSONnullNO_JSON
starts valid, ends mid-tokennull / partialTRUNCATED
malformed JSONnullPARSE_ERROR
valid JSON, wrong typesunknownVALIDATION_ERROR
right types, rule failedTRULE_ERROR

repair

function repair(
  detail: AttemptDetail,
  overrides?: Partial<Record<FailureCategory, RepairFn | false>>,
): Message[] | false;
Generate repair messages for a failed attempt. Returns:
  • Message[] — messages to feed back to the model.
  • false — the category is disabled (via overrides[category] = false), caller should not retry.

overrides shape

type RepairFn = (detail: AttemptDetail) => Message[];

type RepairOverrides = Partial<Record<FailureCategory, RepairFn | false>>;
  • false — skip retry for this category.
  • (detail) => Message[] — build custom repair messages for this category.

instructions

function instructions(schema: ContractSchema<unknown>): string;
Generate prompt text from a Zod schema. Includes field types, enums, ranges, and .describe() annotations.
const schema = z.object({
  tier: z.enum(["hot", "warm", "cold"]).describe("lead temperature"),
  score: z.number().min(0).max(100),
});

console.log(instructions(schema));
// Return JSON matching:
// {
//   "tier": one of "hot" | "warm" | "cold" — lead temperature,
//   "score": number (0-100)
// }
Called automatically inside contract.accept and available on attempt.instructions. The primitive does not take an options object. If you want to append stable text to the generated instructions used by contract.accept, configure the contract instead:
defineContract({
  name: "lead-scoring",
  schema,
  rules,
  instructions: {
    suffix: "\nUse concise strings and include the source signal in each reason.",
  },
});

createConsoleLogger

function createConsoleLogger<T = unknown>(
  options?: ConsoleLoggerOptions,
): ContractLogger<T>;
Built-in human-readable logger. Implements the full ContractLogger surface and prints formatted traces to console.log.

ConsoleLoggerOptions

OptionTypeDefaultDescription
prefixstring"[contract]"Prepended to every line
showInstructionsbooleanfalsePrint the auto-generated prompt on onAttemptStart
showRepairsbooleanfalsePrint repair messages on onRepairGenerated
showRawOutputbooleanfalsePrint raw on onRawOutput
showCleanedOutputbooleanfalsePrint cleaned on onCleanedOutput
showSuccessDatabooleanfalsePrint the accepted data on onRunSuccess
maxStringLengthnumber1000Truncate printed strings over this length
defineContract({
  schema,
  rules,
  logger: createConsoleLogger({
    showInstructions: true,
    showRepairs: true,
    maxStringLength: 500,
  }),
});
The debug: true option on defineContract / enforce is equivalent to logger: createConsoleLogger().

See also

Engine primitives guide

Recipes and custom pipelines

Testing contracts

Use verify() for unit tests