@agentcontract/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/audit.ts","../src/cli.ts","../src/loader.ts","../src/models.ts","../src/exceptions.ts","../src/runner.ts","../src/validators/pattern.ts","../src/validators/cost.ts","../src/validators/latency.ts","../src/validators/llm.ts","../src/validators/base.ts","../src/index.ts","../src/enforce.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/** Audit trail — tamper-evident JSONL entries for every run. */\n\nimport { createHash, createHmac } from 'crypto';\nimport { appendFileSync } from 'fs';\nimport type { RunResult } from './runner.js';\n\nexport class AuditWriter {\n constructor(private logPath = 'agentcontract-audit.jsonl') {}\n\n write(result: RunResult, contractPath = ''): Record<string, unknown> {\n const entry = this._buildEntry(result, contractPath);\n appendFileSync(this.logPath, JSON.stringify(entry) + '\\n', 'utf-8');\n return entry;\n }\n\n private _buildEntry(result: RunResult, contractPath: string): Record<string, unknown> {\n const ctx = result.context;\n const inputHash = createHash('sha256').update(ctx.input).digest('hex');\n const outputHash = createHash('sha256').update(ctx.output).digest('hex');\n\n const entry: Record<string, unknown> = {\n run_id: result.runId,\n agent: result.agent,\n contract: contractPath,\n contract_version: result.contractVersion,\n timestamp: new Date().toISOString(),\n input_hash: inputHash,\n output_hash: outputHash,\n duration_ms: Math.round(ctx.durationMs * 100) / 100,\n cost_usd: Math.round(ctx.costUsd * 1_000_000) / 1_000_000,\n violations: result.violations.map((v) => ({\n clause_type: v.clauseType,\n clause_name: v.clauseName,\n clause_text: v.clauseText,\n severity: v.severity,\n action_taken: v.actionTaken,\n judge: v.judge,\n details: v.details,\n })),\n outcome: result.outcome,\n };\n\n const auditKey = process.env['AGENTCONTRACT_AUDIT_KEY'];\n if (auditKey) {\n const payload = JSON.stringify(entry, Object.keys(entry).sort());\n entry['signature'] = createHmac('sha256', auditKey).update(payload).digest('hex');\n }\n\n return entry;\n }\n}\n","#!/usr/bin/env node\n/** AgentContract CLI */\n\nimport { readFileSync } from 'fs';\nimport { program } from 'commander';\nimport { loadContract } from './loader.js';\nimport { ContractRunner } from './runner.js';\nimport { makeContext } from './validators/base.js';\nimport { VERSION } from './index.js';\n\nprogram\n .name('agentcontract')\n .description('AgentContract — behavioral contracts for AI agents')\n .version(VERSION);\n\nprogram\n .command('check <contract>')\n .description('Validate a contract file against the AgentContract schema')\n .action((contractFile: string) => {\n try {\n const contract = loadContract(contractFile);\n console.log('✓ Contract is valid');\n console.log(` Agent: ${contract.agent}`);\n console.log(` Version: ${contract.version}`);\n console.log(` Spec: ${contract['spec-version']}`);\n console.log(` Clauses: ${contract.must.length} must, ${contract.must_not.length} must_not, ${contract.assert.length} assertions`);\n } catch (e) {\n console.error(`✗ Invalid contract: ${e instanceof Error ? e.message : e}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('validate <contract> <runLog>')\n .description('Validate a JSONL run log against a contract')\n .option('--format <format>', 'Output format: text or json', 'text')\n .action(async (contractFile: string, runLogFile: string, opts: { format: string }) => {\n let contract;\n try {\n contract = loadContract(contractFile);\n } catch (e) {\n console.error(`✗ ${e instanceof Error ? e.message : e}`);\n process.exit(1);\n }\n\n const runner = new ContractRunner(contract);\n const lines = readFileSync(runLogFile, 'utf-8').split('\\n').filter(Boolean);\n const results = [];\n let failed = 0;\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line);\n const ctx = makeContext({\n input: entry.input ?? '',\n output: entry.output ?? '',\n durationMs: entry.duration_ms ?? 0,\n costUsd: entry.cost_usd ?? 0,\n });\n const result = await runner.run(ctx);\n results.push(result);\n if (!result.passed) failed++;\n } catch {\n // skip invalid lines\n }\n }\n\n if (opts.format === 'json') {\n console.log(JSON.stringify(results.map((r) => ({\n run_id: r.runId,\n outcome: r.outcome,\n violations: r.violations,\n })), null, 2));\n } else {\n const total = results.length;\n const passed = total - failed;\n console.log(`\\nAgentContract Validation Report`);\n console.log(`Contract: ${contractFile} | Runs: ${total} | Passed: ${passed} | Failed: ${failed}`);\n for (const r of results) {\n if (r.violations.length > 0) {\n console.log(`\\n Run ${r.runId.slice(0, 8)}... — VIOLATION`);\n for (const v of r.violations) {\n const icon = v.actionTaken !== 'warn' ? '✗' : '⚠';\n console.log(` ${icon} [${v.actionTaken.toUpperCase()}] ${v.clauseType}: \"${v.clauseText}\"`);\n if (v.details) console.log(` ${v.details}`);\n }\n }\n }\n }\n\n process.exit(failed > 0 ? 1 : 0);\n });\n\nprogram\n .command('info <contract>')\n .description('Display a summary of a contract file')\n .action((contractFile: string) => {\n try {\n const c = loadContract(contractFile);\n console.log(`\\nAgentContract — ${c.agent} v${c.version}`);\n console.log(` Spec version : ${c['spec-version']}`);\n if (c.description) console.log(` Description : ${c.description}`);\n if (c.author) console.log(` Author : ${c.author}`);\n if (c.tags.length) console.log(` Tags : ${c.tags.join(', ')}`);\n console.log(`\\n Clauses:`);\n console.log(` must : ${c.must.length}`);\n console.log(` must_not : ${c.must_not.length}`);\n console.log(` can : ${c.can.length}`);\n console.log(` requires : ${c.requires.length}`);\n console.log(` ensures : ${c.ensures.length}`);\n console.log(` assert : ${c.assert.length}`);\n console.log(`\\n Violation default: ${c.on_violation.default}`);\n } catch (e) {\n console.error(`✗ ${e instanceof Error ? e.message : e}`);\n process.exit(1);\n }\n });\n\nprogram.parse();\n","/** Contract loading and validation. */\n\nimport { readFileSync } from 'fs';\nimport { extname } from 'path';\nimport yaml from 'js-yaml';\nimport { Contract } from './models.js';\nimport { ContractLoadError } from './exceptions.js';\n\nexport function loadContract(filePath: string): Contract {\n const ext = extname(filePath).toLowerCase();\n if (!['.yaml', '.yml', '.json'].includes(ext)) {\n throw new ContractLoadError(\n `Unsupported file format: ${ext}. Use .contract.yaml or .contract.json`\n );\n }\n\n let raw: string;\n try {\n raw = readFileSync(filePath, 'utf-8');\n } catch {\n throw new ContractLoadError(`Contract file not found: ${filePath}`);\n }\n\n let data: unknown;\n try {\n data = ext === '.json' ? JSON.parse(raw) : yaml.load(raw);\n } catch (e) {\n throw new ContractLoadError(`Failed to parse contract file: ${e}`);\n }\n\n if (typeof data !== 'object' || data === null || Array.isArray(data)) {\n throw new ContractLoadError('Contract file must be a YAML/JSON object at the root level.');\n }\n\n const result = Contract.safeParse(data);\n if (!result.success) {\n const issues = result.error.issues\n .map((i) => ` ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n throw new ContractLoadError(`Contract schema validation failed:\\n${issues}`);\n }\n\n return result.data;\n}\n","/** Zod schemas for the AgentContract specification. */\n\nimport { z } from 'zod';\n\nexport const JudgeType = z.enum(['deterministic', 'llm']).default('deterministic');\nexport type JudgeType = z.infer<typeof JudgeType>;\n\nexport const ViolationAction = z.enum(['warn', 'block', 'rollback', 'halt_and_alert']).default('block');\nexport type ViolationAction = z.infer<typeof ViolationAction>;\n\nexport const AssertionType = z.enum(['pattern', 'schema', 'llm', 'cost', 'latency', 'custom']);\nexport type AssertionType = z.infer<typeof AssertionType>;\n\n/** A clause is either a plain string or an object with text + judge. */\nexport const ClauseObject = z.object({\n text: z.string().min(1),\n judge: JudgeType,\n description: z.string().default(''),\n});\nexport type ClauseObject = z.infer<typeof ClauseObject>;\n\nexport const Clause = z.union([z.string().min(1), ClauseObject]);\nexport type Clause = z.infer<typeof Clause>;\n\nexport const PreconditionClause = z.union([\n z.string().min(1),\n z.object({\n text: z.string().min(1),\n judge: JudgeType,\n on_fail: z.enum(['block', 'warn']).default('block'),\n description: z.string().default(''),\n }),\n]);\nexport type PreconditionClause = z.infer<typeof PreconditionClause>;\n\nexport const Assertion = z.object({\n name: z.string().regex(/^[a-z][a-z0-9_]*$/),\n type: AssertionType,\n description: z.string().default(''),\n // pattern\n must_not_match: z.string().optional(),\n must_match: z.string().optional(),\n // schema\n schema: z.record(z.string(), z.unknown()).optional(),\n // llm\n prompt: z.string().optional(),\n pass_when: z.string().optional(),\n model: z.string().optional(),\n // cost\n max_usd: z.number().nonnegative().optional(),\n // latency\n max_ms: z.number().int().positive().optional(),\n // custom\n plugin: z.string().optional(),\n}).passthrough();\nexport type Assertion = z.infer<typeof Assertion>;\n\nexport const Limits = z.object({\n max_tokens: z.number().int().positive().optional(),\n max_input_tokens: z.number().int().positive().optional(),\n max_latency_ms: z.number().int().positive().optional(),\n max_cost_usd: z.number().nonnegative().optional(),\n max_tool_calls: z.number().int().nonnegative().optional(),\n max_steps: z.number().int().positive().optional(),\n}).default({});\nexport type Limits = z.infer<typeof Limits>;\n\nexport const OnViolation = z.object({\n default: ViolationAction,\n}).catchall(z.string()).default({ default: 'block' });\nexport type OnViolation = z.infer<typeof OnViolation>;\n\nexport const Contract = z.object({\n agent: z.string().min(1),\n 'spec-version': z.string(),\n version: z.string(),\n description: z.string().default(''),\n author: z.string().default(''),\n created: z.string().default(''),\n tags: z.array(z.string()).default([]),\n extends: z.string().optional(),\n must: z.array(Clause).default([]),\n must_not: z.array(Clause).default([]),\n can: z.array(z.string()).default([]),\n requires: z.array(PreconditionClause).default([]),\n ensures: z.array(Clause).default([]),\n invariant: z.array(Clause).default([]),\n assert: z.array(Assertion).default([]),\n limits: Limits,\n on_violation: OnViolation,\n});\nexport type Contract = z.infer<typeof Contract>;\n\n/** Helpers */\nexport function getClauseText(clause: Clause): string {\n return typeof clause === 'string' ? clause : clause.text;\n}\n\nexport function getClauseJudge(clause: Clause): JudgeType {\n return typeof clause === 'string' ? 'deterministic' : clause.judge;\n}\n\nexport function getViolationAction(onViolation: OnViolation, name: string): string {\n return (onViolation as Record<string, string>)[name] ?? onViolation.default;\n}\n","/** AgentContract exceptions. */\n\nexport class ContractError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ContractError';\n }\n}\n\nexport class ContractLoadError extends ContractError {\n constructor(message: string) {\n super(message);\n this.name = 'ContractLoadError';\n }\n}\n\nexport class ContractPreconditionError extends ContractError {\n clause: string;\n details: string;\n\n constructor(clause: string, details = '') {\n super(`[PRECONDITION FAILED] ${clause}${details ? ': ' + details : ''}`);\n this.name = 'ContractPreconditionError';\n this.clause = clause;\n this.details = details;\n }\n}\n\nexport class ContractViolation extends ContractError {\n violations: Array<{ clause_type: string; clause_text: string; action_taken: string }>;\n\n constructor(violations: Array<{ clause_type: string; clause_text: string; action_taken: string }>) {\n const lines = violations.map(\n (v) => `[${v.action_taken.toUpperCase()}] ${v.clause_type.toUpperCase()}: \"${v.clause_text}\"`\n );\n super('AgentContractViolation:\\n' + lines.join('\\n'));\n this.name = 'ContractViolation';\n this.violations = violations;\n }\n}\n","/** Contract validation runner — orchestrates all validators per spec §6.1. */\n\nimport { randomUUID } from 'crypto';\nimport {\n Contract,\n Assertion,\n getClauseText,\n getClauseJudge,\n getViolationAction,\n} from './models.js';\nimport type { RunContext, ValidationResult } from './validators/base.js';\nimport { PatternValidator } from './validators/pattern.js';\nimport { CostValidator } from './validators/cost.js';\nimport { LatencyValidator } from './validators/latency.js';\nimport { LLMValidator } from './validators/llm.js';\n\nexport interface ViolationRecord {\n clauseType: string;\n clauseName: string;\n clauseText: string;\n severity: string;\n actionTaken: string;\n judge: string;\n details: string;\n}\n\nexport interface RunResult {\n passed: boolean;\n runId: string;\n agent: string;\n contractVersion: string;\n violations: ViolationRecord[];\n context: RunContext;\n outcome: 'pass' | 'violation';\n}\n\nexport class ContractRunner {\n constructor(private contract: Contract) {}\n\n async run(context: RunContext, runId?: string): Promise<RunResult> {\n const rid = runId ?? randomUUID();\n const violations: ViolationRecord[] = [];\n const c = this.contract;\n const ov = c.on_violation;\n\n // 1. limits\n violations.push(...this._checkLimits(context));\n\n // 2. assert\n for (const assertion of c.assert) {\n const result = await this._runAssertion(assertion, context);\n if (!result.passed) {\n const action = getViolationAction(ov, assertion.name);\n violations.push({\n clauseType: 'assert',\n clauseName: assertion.name,\n clauseText: result.clauseText,\n severity: action,\n actionTaken: action,\n judge: result.judge,\n details: result.details,\n });\n }\n }\n\n // 3. must\n for (const clause of c.must) {\n const text = getClauseText(clause);\n const judge = getClauseJudge(clause);\n const result = await this._evaluateClause(text, 'must', judge, context);\n if (!result.passed) {\n const action = getViolationAction(ov, `must:${text.slice(0, 30)}`);\n violations.push({ clauseType: 'must', clauseName: `must:${text.slice(0, 30)}`, clauseText: text, severity: action, actionTaken: action, judge, details: result.details });\n }\n }\n\n // 4. must_not\n for (const clause of c.must_not) {\n const text = getClauseText(clause);\n const judge = getClauseJudge(clause);\n const result = await this._evaluateClause(text, 'must_not', judge, context);\n if (!result.passed) {\n const action = getViolationAction(ov, `must_not:${text.slice(0, 30)}`);\n violations.push({ clauseType: 'must_not', clauseName: `must_not:${text.slice(0, 30)}`, clauseText: text, severity: action, actionTaken: action, judge, details: result.details });\n }\n }\n\n // 5. ensures\n for (const clause of c.ensures) {\n const text = getClauseText(clause);\n const judge = getClauseJudge(clause);\n const result = await this._evaluateClause(text, 'ensures', judge, context);\n if (!result.passed) {\n const action = getViolationAction(ov, `ensures:${text.slice(0, 30)}`);\n violations.push({ clauseType: 'ensures', clauseName: `ensures:${text.slice(0, 30)}`, clauseText: text, severity: action, actionTaken: action, judge, details: result.details });\n }\n }\n\n const blocking = ['block', 'rollback', 'halt_and_alert'];\n const passed = !violations.some((v) => blocking.includes(v.actionTaken));\n\n return { passed, runId: rid, agent: c.agent, contractVersion: c.version, violations, context, outcome: passed ? 'pass' : 'violation' };\n }\n\n private _checkLimits(context: RunContext): ViolationRecord[] {\n const records: ViolationRecord[] = [];\n const limits = this.contract.limits;\n const ov = this.contract.on_violation;\n\n if (limits.max_latency_ms != null) {\n const r = new LatencyValidator('max_latency_ms', limits.max_latency_ms).validate(context);\n if (!r.passed) {\n const action = getViolationAction(ov, 'max_latency_ms');\n records.push({ clauseType: 'limits', clauseName: 'max_latency_ms', clauseText: r.clauseText, severity: action, actionTaken: action, judge: 'deterministic', details: r.details });\n }\n }\n\n if (limits.max_cost_usd != null) {\n const r = new CostValidator('max_cost_usd', limits.max_cost_usd).validate(context);\n if (!r.passed) {\n const action = getViolationAction(ov, 'max_cost_usd');\n records.push({ clauseType: 'limits', clauseName: 'max_cost_usd', clauseText: r.clauseText, severity: action, actionTaken: action, judge: 'deterministic', details: r.details });\n }\n }\n\n if (limits.max_tokens != null && context.output) {\n const estimated = Math.floor(context.output.length / 4);\n if (estimated > limits.max_tokens) {\n const action = getViolationAction(ov, 'max_tokens');\n records.push({ clauseType: 'limits', clauseName: 'max_tokens', clauseText: `output must not exceed ${limits.max_tokens} tokens`, severity: action, actionTaken: action, judge: 'deterministic', details: `Estimated ${estimated} tokens exceeds limit of ${limits.max_tokens}` });\n }\n }\n\n return records;\n }\n\n private async _runAssertion(assertion: Assertion, context: RunContext): Promise<ValidationResult> {\n switch (assertion.type) {\n case 'pattern':\n return new PatternValidator(assertion.name, assertion.must_not_match, assertion.must_match, assertion.description).validate(context);\n case 'cost':\n return new CostValidator(assertion.name, assertion.max_usd ?? 0, assertion.description).validate(context);\n case 'latency':\n return new LatencyValidator(assertion.name, assertion.max_ms ?? 0, assertion.description).validate(context);\n case 'llm':\n return new LLMValidator(assertion.name, assertion.description || assertion.name, 'assert', assertion.prompt, assertion.pass_when ?? 'NO', assertion.model).validate(context);\n default:\n return { passed: false, clauseName: assertion.name, clauseText: assertion.description || assertion.name, clauseType: 'assert', judge: 'deterministic', details: `Unsupported assertion type: ${assertion.type}` };\n }\n }\n\n private async _evaluateClause(text: string, clauseType: string, judge: string, context: RunContext): Promise<ValidationResult> {\n if (judge === 'llm') {\n return new LLMValidator(`${clauseType}:${text.slice(0, 30)}`, text, clauseType).validate(context);\n }\n // Deterministic natural language: pass by default (no handler registered)\n return { passed: true, clauseName: `${clauseType}:${text.slice(0, 30)}`, clauseText: text, clauseType, judge: 'deterministic', details: '' };\n }\n}\n","/** Regex pattern validator. */\n\nimport type { RunContext, ValidationResult, Validator } from './base.js';\n\nexport class PatternValidator implements Validator {\n constructor(\n private name: string,\n private mustNotMatch?: string,\n private mustMatch?: string,\n private description = '',\n ) {}\n\n validate(context: RunContext): ValidationResult {\n const output = context.output;\n\n if (this.mustNotMatch) {\n const re = new RegExp(this.mustNotMatch);\n const match = re.exec(output);\n if (match) {\n return {\n passed: false,\n clauseName: this.name,\n clauseText: this.description || `must_not_match: ${this.mustNotMatch}`,\n clauseType: 'assert',\n judge: 'deterministic',\n details: `Forbidden pattern found: '${match[0].slice(0, 50)}'`,\n };\n }\n }\n\n if (this.mustMatch) {\n const re = new RegExp(this.mustMatch);\n if (!re.test(output)) {\n return {\n passed: false,\n clauseName: this.name,\n clauseText: this.description || `must_match: ${this.mustMatch}`,\n clauseType: 'assert',\n judge: 'deterministic',\n details: 'Required pattern not found in output.',\n };\n }\n }\n\n return {\n passed: true,\n clauseName: this.name,\n clauseText: this.description || this.name,\n clauseType: 'assert',\n judge: 'deterministic',\n details: '',\n };\n }\n}\n","/** Cost validator. */\n\nimport type { RunContext, ValidationResult, Validator } from './base.js';\n\nexport class CostValidator implements Validator {\n constructor(\n private name: string,\n private maxUsd: number,\n private description = '',\n ) {}\n\n validate(context: RunContext): ValidationResult {\n const passed = context.costUsd <= this.maxUsd;\n return {\n passed,\n clauseName: this.name,\n clauseText: this.description || `cost must not exceed $${this.maxUsd.toFixed(4)} USD`,\n clauseType: 'assert',\n judge: 'deterministic',\n details: passed\n ? ''\n : `Run cost $${context.costUsd.toFixed(4)} exceeded limit $${this.maxUsd.toFixed(4)}`,\n };\n }\n}\n","/** Latency validator. */\n\nimport type { RunContext, ValidationResult, Validator } from './base.js';\n\nexport class LatencyValidator implements Validator {\n constructor(\n private name: string,\n private maxMs: number,\n private description = '',\n ) {}\n\n validate(context: RunContext): ValidationResult {\n const passed = context.durationMs <= this.maxMs;\n return {\n passed,\n clauseName: this.name,\n clauseText: this.description || `latency must not exceed ${this.maxMs}ms`,\n clauseType: 'assert',\n judge: 'deterministic',\n details: passed\n ? ''\n : `Run took ${Math.round(context.durationMs)}ms, exceeded limit of ${this.maxMs}ms`,\n };\n }\n}\n","/** LLM judge validator. */\n\nimport type { RunContext, ValidationResult, Validator } from './base.js';\n\nconst DEFAULT_JUDGE_MODEL = 'claude-haiku-4-5-20251001';\n\nconst JUDGE_SYSTEM_PROMPT =\n 'You are an impartial compliance judge evaluating an AI agent\\'s behavior against a specific ' +\n 'contract clause. Evaluate objectively based only on the evidence provided. ' +\n 'Your response must be a single word: YES or NO, followed optionally by one sentence of reasoning.';\n\nexport class LLMValidator implements Validator {\n constructor(\n private name: string,\n private clauseText: string,\n private clauseType: string,\n private prompt?: string,\n private passWhen = 'NO',\n private model = DEFAULT_JUDGE_MODEL,\n private description = '',\n ) {}\n\n async validate(context: RunContext): Promise<ValidationResult> {\n let Anthropic: typeof import('@anthropic-ai/sdk').default;\n try {\n const mod = await import('@anthropic-ai/sdk');\n Anthropic = mod.default;\n } catch {\n return {\n passed: false,\n clauseName: this.name,\n clauseText: this.clauseText,\n clauseType: this.clauseType,\n judge: 'llm',\n details: '@anthropic-ai/sdk not installed. Run: npm install @anthropic-ai/sdk',\n };\n }\n\n const client = new Anthropic();\n const userPrompt = this.prompt\n ? `${this.prompt}\\n\\n--- AGENT INPUT ---\\n${context.input}\\n\\n--- AGENT OUTPUT ---\\n${context.output}`\n : `Contract clause: \"${this.clauseText}\"\\n\\n--- AGENT INPUT ---\\n${context.input}\\n\\n--- AGENT OUTPUT ---\\n${context.output}\\n\\nDoes the agent's output satisfy the contract clause? Answer YES if satisfied, NO if violated.`;\n\n try {\n const response = await client.messages.create({\n model: this.model,\n max_tokens: 64,\n system: JUDGE_SYSTEM_PROMPT,\n messages: [{ role: 'user', content: userPrompt }],\n });\n\n const raw = response.content[0].type === 'text' ? response.content[0].text.trim() : '';\n const firstWord = raw.split(/\\s+/)[0]?.toUpperCase().replace(/[.,;:]$/, '') ?? '';\n const passed = firstWord === this.passWhen.toUpperCase();\n const reasoning = raw.slice(firstWord.length).trim();\n\n return {\n passed,\n clauseName: this.name,\n clauseText: this.clauseText,\n clauseType: this.clauseType,\n judge: 'llm',\n details: reasoning,\n };\n } catch (e) {\n return {\n passed: false,\n clauseName: this.name,\n clauseText: this.clauseText,\n clauseType: this.clauseType,\n judge: 'llm',\n details: `Judge model error: ${e}`,\n };\n }\n }\n}\n","/** Base validator types. */\n\nexport interface RunContext {\n input: string;\n output: string;\n durationMs: number;\n costUsd: number;\n toolCalls: unknown[];\n steps: number;\n metadata: Record<string, unknown>;\n}\n\nexport function makeContext(partial: Partial<RunContext> & { input: string; output: string }): RunContext {\n return {\n durationMs: 0,\n costUsd: 0,\n toolCalls: [],\n steps: 0,\n metadata: {},\n ...partial,\n };\n}\n\nexport interface ValidationResult {\n passed: boolean;\n clauseName: string;\n clauseText: string;\n clauseType: string;\n judge: 'deterministic' | 'llm';\n details: string;\n}\n\nexport interface Validator {\n validate(context: RunContext): ValidationResult | Promise<ValidationResult>;\n}\n","/**\n * @agentcontract/core — Behavioral contracts for AI agents.\n * TypeScript reference implementation of the AgentContract specification.\n * https://github.com/agentcontract/spec\n */\n\nexport const VERSION = '0.1.0';\nexport const SPEC_VERSION = '0.1.0';\n\nexport { loadContract } from './loader.js';\nexport { enforce } from './enforce.js';\nexport { ContractRunner } from './runner.js';\nexport { AuditWriter } from './audit.js';\nexport { makeContext } from './validators/base.js';\n\nexport type { Contract, Clause, Assertion, Limits, OnViolation } from './models.js';\nexport type { RunContext, ValidationResult, Validator } from './validators/base.js';\nexport type { RunResult, ViolationRecord } from './runner.js';\nexport type { EnforceOptions } from './enforce.js';\n\nexport {\n ContractError,\n ContractLoadError,\n ContractPreconditionError,\n ContractViolation,\n} from './exceptions.js';\n","/** enforce() — wraps any agent function with contract validation. */\n\nimport { Contract, getViolationAction, PreconditionClause } from './models.js';\nimport { ContractPreconditionError, ContractViolation } from './exceptions.js';\nimport { ContractRunner } from './runner.js';\nimport { makeContext } from './validators/base.js';\nimport { LLMValidator } from './validators/llm.js';\n\nexport interface EnforceOptions {\n audit?: boolean;\n auditPath?: string;\n costFn?: (result: unknown) => number;\n}\n\ntype AgentFn<T extends string | Promise<string>> = (input: string) => T;\n\nexport function enforce<T extends string | Promise<string>>(\n contract: Contract,\n fn: AgentFn<T>,\n options: EnforceOptions = {},\n): AgentFn<Promise<string>> {\n const { audit = true, auditPath = 'agentcontract-audit.jsonl', costFn } = options;\n const runner = new ContractRunner(contract);\n\n return async (input: string): Promise<string> => {\n // Preconditions\n await checkPreconditions(contract, input);\n\n // Run agent with timing\n const start = performance.now();\n const result = await Promise.resolve(fn(input));\n const durationMs = performance.now() - start;\n\n const output = String(result ?? '');\n const costUsd = costFn ? costFn(result) : 0;\n\n const ctx = makeContext({ input, output, durationMs, costUsd });\n const runResult = await runner.run(ctx);\n\n if (audit) {\n const { AuditWriter } = await import('./audit.js');\n new AuditWriter(auditPath).write(runResult);\n }\n\n // Warn violations → stderr\n const warnViolations = runResult.violations.filter((v) => v.actionTaken === 'warn');\n for (const v of warnViolations) {\n process.stderr.write(\n `[AgentContract WARN] ${v.clauseType.toUpperCase()}: \"${v.clauseText}\" — ${v.details}\\n`\n );\n }\n\n // Blocking violations → throw\n const blocking = runResult.violations.filter((v) =>\n ['block', 'rollback', 'halt_and_alert'].includes(v.actionTaken)\n );\n if (blocking.length > 0) {\n throw new ContractViolation(\n blocking.map((v) => ({\n clause_type: v.clauseType,\n clause_text: v.clauseText,\n action_taken: v.actionTaken,\n }))\n );\n }\n\n return output;\n };\n}\n\nasync function checkPreconditions(contract: Contract, input: string): Promise<void> {\n for (const precondition of contract.requires) {\n let text: string;\n let judge: string;\n let onFail: string;\n\n if (typeof precondition === 'string') {\n text = precondition;\n judge = 'deterministic';\n onFail = 'block';\n } else {\n text = precondition.text;\n judge = precondition.judge;\n onFail = precondition.on_fail;\n }\n\n let passed = true;\n let details = '';\n\n if (judge === 'deterministic') {\n if (/non-empty|not empty/i.test(text)) {\n passed = input.trim().length > 0;\n details = passed ? '' : 'Input is empty.';\n }\n } else if (judge === 'llm') {\n const ctx = makeContext({ input, output: '' });\n const result = await new LLMValidator(`requires:${text.slice(0, 30)}`, text, 'requires').validate(ctx);\n passed = result.passed;\n details = result.details;\n }\n\n if (!passed && onFail === 'block') {\n throw new ContractPreconditionError(text, details);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAGA,IAAAA,aAA6B;AAC7B,uBAAwB;;;ACJxB;AAEA,gBAA6B;AAC7B,kBAAwB;AACxB,qBAAiB;;;ACJjB;AAEA,iBAAkB;AAEX,IAAM,YAAY,aAAE,KAAK,CAAC,iBAAiB,KAAK,CAAC,EAAE,QAAQ,eAAe;AAG1E,IAAM,kBAAkB,aAAE,KAAK,CAAC,QAAQ,SAAS,YAAY,gBAAgB,CAAC,EAAE,QAAQ,OAAO;AAG/F,IAAM,gBAAgB,aAAE,KAAK,CAAC,WAAW,UAAU,OAAO,QAAQ,WAAW,QAAQ,CAAC;AAItF,IAAM,eAAe,aAAE,OAAO;AAAA,EACnC,MAAM,aAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,OAAO;AAAA,EACP,aAAa,aAAE,OAAO,EAAE,QAAQ,EAAE;AACpC,CAAC;AAGM,IAAM,SAAS,aAAE,MAAM,CAAC,aAAE,OAAO,EAAE,IAAI,CAAC,GAAG,YAAY,CAAC;AAGxD,IAAM,qBAAqB,aAAE,MAAM;AAAA,EACxC,aAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChB,aAAE,OAAO;AAAA,IACP,MAAM,aAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACtB,OAAO;AAAA,IACP,SAA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AE;AACrD,YAAQ,IAAI,sBAAsB,EAAE,QAAQ,MAAM,EAAE;AACpD,YAAQ,IAAI,sBAAsB,EAAE,OAAO,MAAM,EAAE;AACnD,YAAQ,IAAI;AAAA,uBAA0B,EAAE,aAAa,OAAO,EAAE;AAAA,EAChE,SAAS,GAAG;AACV,YAAQ,MAAM,UAAK,aAAa,QAAQ,EAAE,UAAU,CAAC,EAAE;AACvD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,yBAAQ,MAAM;","names":["import_fs","yaml"]}
package/dist/cli.mjs ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ContractRunner,
4
+ VERSION,
5
+ loadContract,
6
+ makeContext
7
+ } from "./chunk-UHNX2RBZ.mjs";
8
+ import "./chunk-BVUHPJDU.mjs";
9
+
10
+ // src/cli.ts
11
+ import { readFileSync } from "fs";
12
+ import { program } from "commander";
13
+ program.name("agentcontract").description("AgentContract \u2014 behavioral contracts for AI agents").version(VERSION);
14
+ program.command("check <contract>").description("Validate a contract file against the AgentContract schema").action((contractFile) => {
15
+ try {
16
+ const contract = loadContract(contractFile);
17
+ console.log("\u2713 Contract is valid");
18
+ console.log(` Agent: ${contract.agent}`);
19
+ console.log(` Version: ${contract.version}`);
20
+ console.log(` Spec: ${contract["spec-version"]}`);
21
+ console.log(` Clauses: ${contract.must.length} must, ${contract.must_not.length} must_not, ${contract.assert.length} assertions`);
22
+ } catch (e) {
23
+ console.error(`\u2717 Invalid contract: ${e instanceof Error ? e.message : e}`);
24
+ process.exit(1);
25
+ }
26
+ });
27
+ program.command("validate <contract> <runLog>").description("Validate a JSONL run log against a contract").option("--format <format>", "Output format: text or json", "text").action(async (contractFile, runLogFile, opts) => {
28
+ let contract;
29
+ try {
30
+ contract = loadContract(contractFile);
31
+ } catch (e) {
32
+ console.error(`\u2717 ${e instanceof Error ? e.message : e}`);
33
+ process.exit(1);
34
+ }
35
+ const runner = new ContractRunner(contract);
36
+ const lines = readFileSync(runLogFile, "utf-8").split("\n").filter(Boolean);
37
+ const results = [];
38
+ let failed = 0;
39
+ for (const line of lines) {
40
+ try {
41
+ const entry = JSON.parse(line);
42
+ const ctx = makeContext({
43
+ input: entry.input ?? "",
44
+ output: entry.output ?? "",
45
+ durationMs: entry.duration_ms ?? 0,
46
+ costUsd: entry.cost_usd ?? 0
47
+ });
48
+ const result = await runner.run(ctx);
49
+ results.push(result);
50
+ if (!result.passed) failed++;
51
+ } catch {
52
+ }
53
+ }
54
+ if (opts.format === "json") {
55
+ console.log(JSON.stringify(results.map((r) => ({
56
+ run_id: r.runId,
57
+ outcome: r.outcome,
58
+ violations: r.violations
59
+ })), null, 2));
60
+ } else {
61
+ const total = results.length;
62
+ const passed = total - failed;
63
+ console.log(`
64
+ AgentContract Validation Report`);
65
+ console.log(`Contract: ${contractFile} | Runs: ${total} | Passed: ${passed} | Failed: ${failed}`);
66
+ for (const r of results) {
67
+ if (r.violations.length > 0) {
68
+ console.log(`
69
+ Run ${r.runId.slice(0, 8)}... \u2014 VIOLATION`);
70
+ for (const v of r.violations) {
71
+ const icon = v.actionTaken !== "warn" ? "\u2717" : "\u26A0";
72
+ console.log(` ${icon} [${v.actionTaken.toUpperCase()}] ${v.clauseType}: "${v.clauseText}"`);
73
+ if (v.details) console.log(` ${v.details}`);
74
+ }
75
+ }
76
+ }
77
+ }
78
+ process.exit(failed > 0 ? 1 : 0);
79
+ });
80
+ program.command("info <contract>").description("Display a summary of a contract file").action((contractFile) => {
81
+ try {
82
+ const c = loadContract(contractFile);
83
+ console.log(`
84
+ AgentContract \u2014 ${c.agent} v${c.version}`);
85
+ console.log(` Spec version : ${c["spec-version"]}`);
86
+ if (c.description) console.log(` Description : ${c.description}`);
87
+ if (c.author) console.log(` Author : ${c.author}`);
88
+ if (c.tags.length) console.log(` Tags : ${c.tags.join(", ")}`);
89
+ console.log(`
90
+ Clauses:`);
91
+ console.log(` must : ${c.must.length}`);
92
+ console.log(` must_not : ${c.must_not.length}`);
93
+ console.log(` can : ${c.can.length}`);
94
+ console.log(` requires : ${c.requires.length}`);
95
+ console.log(` ensures : ${c.ensures.length}`);
96
+ console.log(` assert : ${c.assert.length}`);
97
+ console.log(`
98
+ Violation default: ${c.on_violation.default}`);
99
+ } catch (e) {
100
+ console.error(`\u2717 ${e instanceof Error ? e.message : e}`);
101
+ process.exit(1);
102
+ }
103
+ });
104
+ program.parse();
105
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/** AgentContract CLI */\n\nimport { readFileSync } from 'fs';\nimport { program } from 'commander';\nimport { loadContract } from './loader.js';\nimport { ContractRunner } from './runner.js';\nimport { makeContext } from './validators/base.js';\nimport { VERSION } from './index.js';\n\nprogram\n .name('agentcontract')\n .description('AgentContract — behavioral contracts for AI agents')\n .version(VERSION);\n\nprogram\n .command('check <contract>')\n .description('Validate a contract file against the AgentContract schema')\n .action((contractFile: string) => {\n try {\n const contract = loadContract(contractFile);\n console.log('✓ Contract is valid');\n console.log(` Agent: ${contract.agent}`);\n console.log(` Version: ${contract.version}`);\n console.log(` Spec: ${contract['spec-version']}`);\n console.log(` Clauses: ${contract.must.length} must, ${contract.must_not.length} must_not, ${contract.assert.length} assertions`);\n } catch (e) {\n console.error(`✗ Invalid contract: ${e instanceof Error ? e.message : e}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('validate <contract> <runLog>')\n .description('Validate a JSONL run log against a contract')\n .option('--format <format>', 'Output format: text or json', 'text')\n .action(async (contractFile: string, runLogFile: string, opts: { format: string }) => {\n let contract;\n try {\n contract = loadContract(contractFile);\n } catch (e) {\n console.error(`✗ ${e instanceof Error ? e.message : e}`);\n process.exit(1);\n }\n\n const runner = new ContractRunner(contract);\n const lines = readFileSync(runLogFile, 'utf-8').split('\\n').filter(Boolean);\n const results = [];\n let failed = 0;\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line);\n const ctx = makeContext({\n input: entry.input ?? '',\n output: entry.output ?? '',\n durationMs: entry.duration_ms ?? 0,\n costUsd: entry.cost_usd ?? 0,\n });\n const result = await runner.run(ctx);\n results.push(result);\n if (!result.passed) failed++;\n } catch {\n // skip invalid lines\n }\n }\n\n if (opts.format === 'json') {\n console.log(JSON.stringify(results.map((r) => ({\n run_id: r.runId,\n outcome: r.outcome,\n violations: r.violations,\n })), null, 2));\n } else {\n const total = results.length;\n const passed = total - failed;\n console.log(`\\nAgentContract Validation Report`);\n console.log(`Contract: ${contractFile} | Runs: ${total} | Passed: ${passed} | Failed: ${failed}`);\n for (const r of results) {\n if (r.violations.length > 0) {\n console.log(`\\n Run ${r.runId.slice(0, 8)}... — VIOLATION`);\n for (const v of r.violations) {\n const icon = v.actionTaken !== 'warn' ? '✗' : '⚠';\n console.log(` ${icon} [${v.actionTaken.toUpperCase()}] ${v.clauseType}: \"${v.clauseText}\"`);\n if (v.details) console.log(` ${v.details}`);\n }\n }\n }\n }\n\n process.exit(failed > 0 ? 1 : 0);\n });\n\nprogram\n .command('info <contract>')\n .description('Display a summary of a contract file')\n .action((contractFile: string) => {\n try {\n const c = loadContract(contractFile);\n console.log(`\\nAgentContract — ${c.agent} v${c.version}`);\n console.log(` Spec version : ${c['spec-version']}`);\n if (c.description) console.log(` Description : ${c.description}`);\n if (c.author) console.log(` Author : ${c.author}`);\n if (c.tags.length) console.log(` Tags : ${c.tags.join(', ')}`);\n console.log(`\\n Clauses:`);\n console.log(` must : ${c.must.length}`);\n console.log(` must_not : ${c.must_not.length}`);\n console.log(` can : ${c.can.length}`);\n console.log(` requires : ${c.requires.length}`);\n console.log(` ensures : ${c.ensures.length}`);\n console.log(` assert : ${c.assert.length}`);\n console.log(`\\n Violation default: ${c.on_violation.default}`);\n } catch (e) {\n console.error(`✗ ${e instanceof Error ? e.message : e}`);\n process.exit(1);\n }\n });\n\nprogram.parse();\n"],"mappings":";;;;;;;;;;AAGA,SAAS,oBAAoB;AAC7B,SAAS,eAA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D,YAAQ,IAAI,oBAAoB,EAAE,cAAc,CAAC,EAAE;AACnD,QAAI,EAAE,YAAa,SAAQ,IAAI,oBAAoB,EAAE,WAAW,EAAE;AAClE,QAAI,EAAE,OAAQ,SAAQ,IAAI,oBAAoB,EAAE,MAAM,EAAE;AACxD,QAAI,EAAE,KAAK,OAAQ,SAAQ,IAAI,oBAAoB,EAAE,KAAK,KAAK,IAAI,CAAC,EAAE;AACtE,YAAQ,IAAI;AAAA,WAAc;AAC1B,YAAQ,IAAI,sBAAsB,EAAE,KAAK,MAAM,EAAE;AACjD,YAAQ,IAAI,sBAAsB,EAAE,SAAS,MAAM,EAAE;AACrD,YAAQ,IAAI,sBAAsB,EAAE,IAAI,MAAM,EAAE;AAChD,YAAQ,IAAI,sBAAsB,EAAE,SAAS,MAAM,EAAE;AACrD,YAAQ,IAAI,sBAAsB,EAAE,QAAQ,MAAM,EAAE;AACpD,YAAQ,IAAI,sBAAsB,EAAE,OAAO,MAAM,EAAE;AACnD,YAAQ,IAAI;AAAA,uBAA0B,EAAE,aAAa,OAAO,EAAE;AAAA,EAChE,SAAS,GAAG;AACV,YAAQ,MAAM,UAAK,aAAa,QAAQ,EAAE,UAAU,CAAC,EAAE;AACvD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QAAQ,MAAM;","names":[]}
@@ -0,0 +1,259 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Zod schemas for the AgentContract specification. */
4
+
5
+ declare const Clause: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
6
+ text: z.ZodString;
7
+ judge: z.ZodDefault<z.ZodEnum<{
8
+ deterministic: "deterministic";
9
+ llm: "llm";
10
+ }>>;
11
+ description: z.ZodDefault<z.ZodString>;
12
+ }, z.core.$strip>]>;
13
+ type Clause = z.infer<typeof Clause>;
14
+ declare const Assertion: z.ZodObject<{
15
+ name: z.ZodString;
16
+ type: z.ZodEnum<{
17
+ llm: "llm";
18
+ pattern: "pattern";
19
+ schema: "schema";
20
+ cost: "cost";
21
+ latency: "latency";
22
+ custom: "custom";
23
+ }>;
24
+ description: z.ZodDefault<z.ZodString>;
25
+ must_not_match: z.ZodOptional<z.ZodString>;
26
+ must_match: z.ZodOptional<z.ZodString>;
27
+ schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
28
+ prompt: z.ZodOptional<z.ZodString>;
29
+ pass_when: z.ZodOptional<z.ZodString>;
30
+ model: z.ZodOptional<z.ZodString>;
31
+ max_usd: z.ZodOptional<z.ZodNumber>;
32
+ max_ms: z.ZodOptional<z.ZodNumber>;
33
+ plugin: z.ZodOptional<z.ZodString>;
34
+ }, z.core.$loose>;
35
+ type Assertion = z.infer<typeof Assertion>;
36
+ declare const Limits: z.ZodDefault<z.ZodObject<{
37
+ max_tokens: z.ZodOptional<z.ZodNumber>;
38
+ max_input_tokens: z.ZodOptional<z.ZodNumber>;
39
+ max_latency_ms: z.ZodOptional<z.ZodNumber>;
40
+ max_cost_usd: z.ZodOptional<z.ZodNumber>;
41
+ max_tool_calls: z.ZodOptional<z.ZodNumber>;
42
+ max_steps: z.ZodOptional<z.ZodNumber>;
43
+ }, z.core.$strip>>;
44
+ type Limits = z.infer<typeof Limits>;
45
+ declare const OnViolation: z.ZodDefault<z.ZodObject<{
46
+ default: z.ZodDefault<z.ZodEnum<{
47
+ warn: "warn";
48
+ block: "block";
49
+ rollback: "rollback";
50
+ halt_and_alert: "halt_and_alert";
51
+ }>>;
52
+ }, z.core.$catchall<z.ZodString>>>;
53
+ type OnViolation = z.infer<typeof OnViolation>;
54
+ declare const Contract: z.ZodObject<{
55
+ agent: z.ZodString;
56
+ 'spec-version': z.ZodString;
57
+ version: z.ZodString;
58
+ description: z.ZodDefault<z.ZodString>;
59
+ author: z.ZodDefault<z.ZodString>;
60
+ created: z.ZodDefault<z.ZodString>;
61
+ tags: z.ZodDefault<z.ZodArray<z.ZodString>>;
62
+ extends: z.ZodOptional<z.ZodString>;
63
+ must: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
64
+ text: z.ZodString;
65
+ judge: z.ZodDefault<z.ZodEnum<{
66
+ deterministic: "deterministic";
67
+ llm: "llm";
68
+ }>>;
69
+ description: z.ZodDefault<z.ZodString>;
70
+ }, z.core.$strip>]>>>;
71
+ must_not: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
72
+ text: z.ZodString;
73
+ judge: z.ZodDefault<z.ZodEnum<{
74
+ deterministic: "deterministic";
75
+ llm: "llm";
76
+ }>>;
77
+ description: z.ZodDefault<z.ZodString>;
78
+ }, z.core.$strip>]>>>;
79
+ can: z.ZodDefault<z.ZodArray<z.ZodString>>;
80
+ requires: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
81
+ text: z.ZodString;
82
+ judge: z.ZodDefault<z.ZodEnum<{
83
+ deterministic: "deterministic";
84
+ llm: "llm";
85
+ }>>;
86
+ on_fail: z.ZodDefault<z.ZodEnum<{
87
+ warn: "warn";
88
+ block: "block";
89
+ }>>;
90
+ description: z.ZodDefault<z.ZodString>;
91
+ }, z.core.$strip>]>>>;
92
+ ensures: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
93
+ text: z.ZodString;
94
+ judge: z.ZodDefault<z.ZodEnum<{
95
+ deterministic: "deterministic";
96
+ llm: "llm";
97
+ }>>;
98
+ description: z.ZodDefault<z.ZodString>;
99
+ }, z.core.$strip>]>>>;
100
+ invariant: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
101
+ text: z.ZodString;
102
+ judge: z.ZodDefault<z.ZodEnum<{
103
+ deterministic: "deterministic";
104
+ llm: "llm";
105
+ }>>;
106
+ description: z.ZodDefault<z.ZodString>;
107
+ }, z.core.$strip>]>>>;
108
+ assert: z.ZodDefault<z.ZodArray<z.ZodObject<{
109
+ name: z.ZodString;
110
+ type: z.ZodEnum<{
111
+ llm: "llm";
112
+ pattern: "pattern";
113
+ schema: "schema";
114
+ cost: "cost";
115
+ latency: "latency";
116
+ custom: "custom";
117
+ }>;
118
+ description: z.ZodDefault<z.ZodString>;
119
+ must_not_match: z.ZodOptional<z.ZodString>;
120
+ must_match: z.ZodOptional<z.ZodString>;
121
+ schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
122
+ prompt: z.ZodOptional<z.ZodString>;
123
+ pass_when: z.ZodOptional<z.ZodString>;
124
+ model: z.ZodOptional<z.ZodString>;
125
+ max_usd: z.ZodOptional<z.ZodNumber>;
126
+ max_ms: z.ZodOptional<z.ZodNumber>;
127
+ plugin: z.ZodOptional<z.ZodString>;
128
+ }, z.core.$loose>>>;
129
+ limits: z.ZodDefault<z.ZodObject<{
130
+ max_tokens: z.ZodOptional<z.ZodNumber>;
131
+ max_input_tokens: z.ZodOptional<z.ZodNumber>;
132
+ max_latency_ms: z.ZodOptional<z.ZodNumber>;
133
+ max_cost_usd: z.ZodOptional<z.ZodNumber>;
134
+ max_tool_calls: z.ZodOptional<z.ZodNumber>;
135
+ max_steps: z.ZodOptional<z.ZodNumber>;
136
+ }, z.core.$strip>>;
137
+ on_violation: z.ZodDefault<z.ZodObject<{
138
+ default: z.ZodDefault<z.ZodEnum<{
139
+ warn: "warn";
140
+ block: "block";
141
+ rollback: "rollback";
142
+ halt_and_alert: "halt_and_alert";
143
+ }>>;
144
+ }, z.core.$catchall<z.ZodString>>>;
145
+ }, z.core.$strip>;
146
+ type Contract = z.infer<typeof Contract>;
147
+
148
+ /** Contract loading and validation. */
149
+
150
+ declare function loadContract(filePath: string): Contract;
151
+
152
+ /** enforce() — wraps any agent function with contract validation. */
153
+
154
+ interface EnforceOptions {
155
+ audit?: boolean;
156
+ auditPath?: string;
157
+ costFn?: (result: unknown) => number;
158
+ }
159
+ type AgentFn<T extends string | Promise<string>> = (input: string) => T;
160
+ declare function enforce<T extends string | Promise<string>>(contract: Contract, fn: AgentFn<T>, options?: EnforceOptions): AgentFn<Promise<string>>;
161
+
162
+ /** Base validator types. */
163
+ interface RunContext {
164
+ input: string;
165
+ output: string;
166
+ durationMs: number;
167
+ costUsd: number;
168
+ toolCalls: unknown[];
169
+ steps: number;
170
+ metadata: Record<string, unknown>;
171
+ }
172
+ declare function makeContext(partial: Partial<RunContext> & {
173
+ input: string;
174
+ output: string;
175
+ }): RunContext;
176
+ interface ValidationResult {
177
+ passed: boolean;
178
+ clauseName: string;
179
+ clauseText: string;
180
+ clauseType: string;
181
+ judge: 'deterministic' | 'llm';
182
+ details: string;
183
+ }
184
+ interface Validator {
185
+ validate(context: RunContext): ValidationResult | Promise<ValidationResult>;
186
+ }
187
+
188
+ /** Contract validation runner — orchestrates all validators per spec §6.1. */
189
+
190
+ interface ViolationRecord {
191
+ clauseType: string;
192
+ clauseName: string;
193
+ clauseText: string;
194
+ severity: string;
195
+ actionTaken: string;
196
+ judge: string;
197
+ details: string;
198
+ }
199
+ interface RunResult {
200
+ passed: boolean;
201
+ runId: string;
202
+ agent: string;
203
+ contractVersion: string;
204
+ violations: ViolationRecord[];
205
+ context: RunContext;
206
+ outcome: 'pass' | 'violation';
207
+ }
208
+ declare class ContractRunner {
209
+ private contract;
210
+ constructor(contract: Contract);
211
+ run(context: RunContext, runId?: string): Promise<RunResult>;
212
+ private _checkLimits;
213
+ private _runAssertion;
214
+ private _evaluateClause;
215
+ }
216
+
217
+ /** Audit trail — tamper-evident JSONL entries for every run. */
218
+
219
+ declare class AuditWriter {
220
+ private logPath;
221
+ constructor(logPath?: string);
222
+ write(result: RunResult, contractPath?: string): Record<string, unknown>;
223
+ private _buildEntry;
224
+ }
225
+
226
+ /** AgentContract exceptions. */
227
+ declare class ContractError extends Error {
228
+ constructor(message: string);
229
+ }
230
+ declare class ContractLoadError extends ContractError {
231
+ constructor(message: string);
232
+ }
233
+ declare class ContractPreconditionError extends ContractError {
234
+ clause: string;
235
+ details: string;
236
+ constructor(clause: string, details?: string);
237
+ }
238
+ declare class ContractViolation extends ContractError {
239
+ violations: Array<{
240
+ clause_type: string;
241
+ clause_text: string;
242
+ action_taken: string;
243
+ }>;
244
+ constructor(violations: Array<{
245
+ clause_type: string;
246
+ clause_text: string;
247
+ action_taken: string;
248
+ }>);
249
+ }
250
+
251
+ /**
252
+ * @agentcontract/core — Behavioral contracts for AI agents.
253
+ * TypeScript reference implementation of the AgentContract specification.
254
+ * https://github.com/agentcontract/spec
255
+ */
256
+ declare const VERSION = "0.1.0";
257
+ declare const SPEC_VERSION = "0.1.0";
258
+
259
+ export { Assertion, AuditWriter, Clause, Contract, ContractError, ContractLoadError, ContractPreconditionError, ContractRunner, ContractViolation, type EnforceOptions, Limits, OnViolation, type RunContext, type RunResult, SPEC_VERSION, VERSION, type ValidationResult, type Validator, type ViolationRecord, enforce, loadContract, makeContext };