@agentcontract/core 0.1.0 → 0.1.1

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.
package/README.md CHANGED
@@ -101,6 +101,18 @@ See the [AgentContract specification](https://github.com/agentcontract/spec/blob
101
101
 
102
102
  ---
103
103
 
104
+ ## Roadmap
105
+
106
+ - [ ] `rollback` violation action (snapshot/restore support)
107
+ - [ ] `requires` and `invariant` clause evaluation
108
+ - [ ] HMAC-signed audit trail (mirrors Python implementation)
109
+ - [ ] `agentcontract serve` — local contract validation server
110
+ - [ ] LangChain.js and Vercel AI SDK middleware adapters
111
+
112
+ Contributions welcome — see the [spec](https://github.com/agentcontract/spec) for implementation requirements.
113
+
114
+ ---
115
+
104
116
  ## License
105
117
 
106
118
  Apache 2.0 — *Part of the [AgentContract](https://github.com/agentcontract) open standard.*
@@ -372,7 +372,7 @@ var ContractRunner = class {
372
372
  }
373
373
  const blocking = ["block", "rollback", "halt_and_alert"];
374
374
  const passed = !violations.some((v) => blocking.includes(v.actionTaken));
375
- return { passed, runId: rid, agent: c.agent, contractVersion: c.version, violations, context, outcome: passed ? "pass" : "violation" };
375
+ return { passed, runId: rid, agent: c.agent, contractVersion: c.version, violations, clausesChecked: c.assert.length, context, outcome: passed ? "pass" : "violation" };
376
376
  }
377
377
  _checkLimits(context) {
378
378
  const records = [];
@@ -508,7 +508,7 @@ async function checkPreconditions(contract, input) {
508
508
  }
509
509
 
510
510
  // src/index.ts
511
- var VERSION = "0.1.0";
511
+ var VERSION = "0.1.1";
512
512
  var SPEC_VERSION = "0.1.0";
513
513
 
514
514
  export {
@@ -523,4 +523,4 @@ export {
523
523
  VERSION,
524
524
  SPEC_VERSION
525
525
  };
526
- //# sourceMappingURL=chunk-UHNX2RBZ.mjs.map
526
+ //# sourceMappingURL=chunk-62IASCRF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../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/enforce.ts","../src/index.ts"],"sourcesContent":["/** 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 clausesChecked: number;\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, clausesChecked: c.assert.length, 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","/** 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","/**\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.1';\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"],"mappings":";AAEA,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,OAAO,UAAU;;;ACFjB,SAAS,SAAS;AAEX,IAAM,YAAY,EAAE,KAAK,CAAC,iBAAiB,KAAK,CAAC,EAAE,QAAQ,eAAe;AAG1E,IAAM,kBAAkB,EAAE,KAAK,CAAC,QAAQ,SAAS,YAAY,gBAAgB,CAAC,EAAE,QAAQ,OAAO;AAG/F,IAAM,gBAAgB,EAAE,KAAK,CAAC,WAAW,UAAU,OAAO,QAAQ,WAAW,QAAQ,CAAC;AAItF,IAAM,eAAe,EAAE,OAAO;AAAA,EACnC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,OAAO;AAAA,EACP,aAAa,EAAE,OAAO,EAAE,QAAQ,EAAE;AACpC,CAAC;AAGM,IAAM,SAAS,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,YAAY,CAAC;AAGxD,IAAM,qBAAqB,EAAE,MAAM;AAAA,EACxC,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChB,EAAE,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ACF;AAEA,WAAO;AAAA,EACT;AACF;AAEA,eAAe,mBAAmB,UAAoB,OAA8B;AAClF,aAAW,gBAAgB,SAAS,UAAU;AAC5C,QAAI;AACJ,QAAI;AACJ,QAAI;AAEJ,QAAI,OAAO,iBAAiB,UAAU;AACpC,aAAO;AACP,cAAQ;AACR,eAAS;AAAA,IACX,OAAO;AACL,aAAO,aAAa;AACpB,cAAQ,aAAa;AACrB,eAAS,aAAa;AAAA,IACxB;AAEA,QAAI,SAAS;AACb,QAAI,UAAU;AAEd,QAAI,UAAU,iBAAiB;AAC7B,UAAI,uBAAuB,KAAK,IAAI,GAAG;AACrC,iBAAS,MAAM,KAAK,EAAE,SAAS;AAC/B,kBAAU,SAAS,KAAK;AAAA,MAC1B;AAAA,IACF,WAAW,UAAU,OAAO;AAC1B,YAAM,MAAM,YAAY,EAAE,OAAO,QAAQ,GAAG,CAAC;AAC7C,YAAM,SAAS,MAAM,IAAI,aAAa,YAAY,KAAK,MAAM,GAAG,EAAE,CAAC,IAAI,MAAM,UAAU,EAAE,SAAS,GAAG;AACrG,eAAS,OAAO;AAChB,gBAAU,OAAO;AAAA,IACnB;AAEA,QAAI,CAAC,UAAU,WAAW,SAAS;AACjC,YAAM,IAAI,0BAA0B,MAAM,OAAO;AAAA,IACnD;AAAA,EACF;AACF;;;ACnGO,IAAM,UAAU;AAChB,IAAM,eAAe;","names":["AuditWriter"]}
package/dist/cli.js CHANGED
@@ -407,7 +407,7 @@ var ContractRunner = class {
407
407
  }
408
408
  const blocking = ["block", "rollback", "halt_and_alert"];
409
409
  const passed = !violations.some((v) => blocking.includes(v.actionTaken));
410
- return { passed, runId: rid, agent: c.agent, contractVersion: c.version, violations, context, outcome: passed ? "pass" : "violation" };
410
+ return { passed, runId: rid, agent: c.agent, contractVersion: c.version, violations, clausesChecked: c.assert.length, context, outcome: passed ? "pass" : "violation" };
411
411
  }
412
412
  _checkLimits(context) {
413
413
  const records = [];
@@ -479,18 +479,18 @@ init_cjs_shims();
479
479
 
480
480
  // src/index.ts
481
481
  init_audit();
482
- var VERSION = "0.1.0";
482
+ var VERSION = "0.1.1";
483
483
 
484
484
  // src/cli.ts
485
485
  import_commander.program.name("agentcontract").description("AgentContract \u2014 behavioral contracts for AI agents").version(VERSION);
486
486
  import_commander.program.command("check <contract>").description("Validate a contract file against the AgentContract schema").action((contractFile) => {
487
487
  try {
488
488
  const contract = loadContract(contractFile);
489
- console.log("\u2713 Contract is valid");
490
- console.log(` Agent: ${contract.agent}`);
491
- console.log(` Version: ${contract.version}`);
492
- console.log(` Spec: ${contract["spec-version"]}`);
493
- console.log(` Clauses: ${contract.must.length} must, ${contract.must_not.length} must_not, ${contract.assert.length} assertions`);
489
+ const nAssertions = contract.assert.length;
490
+ const limits = contract.limits;
491
+ const nLimits = (limits.max_latency_ms != null ? 1 : 0) + (limits.max_cost_usd != null ? 1 : 0) + (limits.max_tokens != null ? 1 : 0);
492
+ console.log(`\u2713 Contract valid: ${contract.agent} v${contract.version}`);
493
+ console.log(` ${nAssertions} assertions, ${nLimits} limits`);
494
494
  } catch (e) {
495
495
  console.error(`\u2717 Invalid contract: ${e instanceof Error ? e.message : e}`);
496
496
  process.exit(1);
package/dist/cli.js.map CHANGED
@@ -1 +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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CAAsC,EAClD,OAAO,CAAC,iBAAyB;AAChC,MAAI;AACF,UAAM,IAAI,aAAa,YAAY;AACnC,YAAQ,IAAI;AAAA,uBAAqB,EAAE,KAAK,KAAK,EAAE,OAAO,EAAE;AACxD,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,yBAAQ,MAAM;","names":["import_fs","yaml"]}
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 const nAssertions = contract.assert.length;\n const limits = contract.limits;\n const nLimits = (limits.max_latency_ms != null ? 1 : 0) + (limits.max_cost_usd != null ? 1 : 0) + (limits.max_tokens != null ? 1 : 0);\n console.log(`✓ Contract valid: ${contract.agent} v${contract.version}`);\n console.log(` ${nAssertions} assertions, ${nLimits} limits`);\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 clausesChecked: number;\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, clausesChecked: c.assert.length, 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.1';\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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E;AACvD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,yBAAQ,MAAM;","names":["import_fs","yaml"]}
package/dist/cli.mjs CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  VERSION,
5
5
  loadContract,
6
6
  makeContext
7
- } from "./chunk-UHNX2RBZ.mjs";
7
+ } from "./chunk-62IASCRF.mjs";
8
8
  import "./chunk-BVUHPJDU.mjs";
9
9
 
10
10
  // src/cli.ts
@@ -14,11 +14,11 @@ program.name("agentcontract").description("AgentContract \u2014 behavioral contr
14
14
  program.command("check <contract>").description("Validate a contract file against the AgentContract schema").action((contractFile) => {
15
15
  try {
16
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`);
17
+ const nAssertions = contract.assert.length;
18
+ const limits = contract.limits;
19
+ const nLimits = (limits.max_latency_ms != null ? 1 : 0) + (limits.max_cost_usd != null ? 1 : 0) + (limits.max_tokens != null ? 1 : 0);
20
+ console.log(`\u2713 Contract valid: ${contract.agent} v${contract.version}`);
21
+ console.log(` ${nAssertions} assertions, ${nLimits} limits`);
22
22
  } catch (e) {
23
23
  console.error(`\u2717 Invalid contract: ${e instanceof Error ? e.message : e}`);
24
24
  process.exit(1);
package/dist/cli.mjs.map CHANGED
@@ -1 +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,eAAe;AAMxB,QACG,KAAK,eAAe,EACpB,YAAY,yDAAoD,EAChE,QAAQ,OAAO;AAElB,QACG,QAAQ,kBAAkB,EAC1B,YAAY,2DAA2D,EACvE,OAAO,CAAC,iBAAyB;AAChC,MAAI;AACF,UAAM,WAAW,aAAa,YAAY;AAC1C,YAAQ,IAAI,0BAAqB;AACjC,YAAQ,IAAI,eAAe,SAAS,KAAK,EAAE;AAC3C,YAAQ,IAAI,eAAe,SAAS,OAAO,EAAE;AAC7C,YAAQ,IAAI,eAAe,SAAS,cAAc,CAAC,EAAE;AACrD,YAAQ,IAAI,eAAe,SAAS,KAAK,MAAM,UAAU,SAAS,SAAS,MAAM,cAAc,SAAS,OAAO,MAAM,aAAa;AAAA,EACpI,SAAS,GAAG;AACV,YAAQ,MAAM,4BAAuB,aAAa,QAAQ,EAAE,UAAU,CAAC,EAAE;AACzE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QACG,Q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AO,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":[]}
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 const nAssertions = contract.assert.length;\n const limits = contract.limits;\n const nLimits = (limits.max_latency_ms != null ? 1 : 0) + (limits.max_cost_usd != null ? 1 : 0) + (limits.max_tokens != null ? 1 : 0);\n console.log(`✓ Contract valid: ${contract.agent} v${contract.version}`);\n console.log(` ${nAssertions} assertions, ${nLimits} limits`);\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,eAAe;AAMxB,QACG,KAAK,eAAe,EACp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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":[]}
package/dist/index.d.mts CHANGED
@@ -202,6 +202,7 @@ interface RunResult {
202
202
  agent: string;
203
203
  contractVersion: string;
204
204
  violations: ViolationRecord[];
205
+ clausesChecked: number;
205
206
  context: RunContext;
206
207
  outcome: 'pass' | 'violation';
207
208
  }
@@ -253,7 +254,7 @@ declare class ContractViolation extends ContractError {
253
254
  * TypeScript reference implementation of the AgentContract specification.
254
255
  * https://github.com/agentcontract/spec
255
256
  */
256
- declare const VERSION = "0.1.0";
257
+ declare const VERSION = "0.1.1";
257
258
  declare const SPEC_VERSION = "0.1.0";
258
259
 
259
260
  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 };
package/dist/index.d.ts CHANGED
@@ -202,6 +202,7 @@ interface RunResult {
202
202
  agent: string;
203
203
  contractVersion: string;
204
204
  violations: ViolationRecord[];
205
+ clausesChecked: number;
205
206
  context: RunContext;
206
207
  outcome: 'pass' | 'violation';
207
208
  }
@@ -253,7 +254,7 @@ declare class ContractViolation extends ContractError {
253
254
  * TypeScript reference implementation of the AgentContract specification.
254
255
  * https://github.com/agentcontract/spec
255
256
  */
256
- declare const VERSION = "0.1.0";
257
+ declare const VERSION = "0.1.1";
257
258
  declare const SPEC_VERSION = "0.1.0";
258
259
 
259
260
  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 };
package/dist/index.js CHANGED
@@ -497,7 +497,7 @@ var ContractRunner = class {
497
497
  }
498
498
  const blocking = ["block", "rollback", "halt_and_alert"];
499
499
  const passed = !violations.some((v) => blocking.includes(v.actionTaken));
500
- return { passed, runId: rid, agent: c.agent, contractVersion: c.version, violations, context, outcome: passed ? "pass" : "violation" };
500
+ return { passed, runId: rid, agent: c.agent, contractVersion: c.version, violations, clausesChecked: c.assert.length, context, outcome: passed ? "pass" : "violation" };
501
501
  }
502
502
  _checkLimits(context) {
503
503
  const records = [];
@@ -635,7 +635,7 @@ async function checkPreconditions(contract, input) {
635
635
 
636
636
  // src/index.ts
637
637
  init_audit();
638
- var VERSION = "0.1.0";
638
+ var VERSION = "0.1.1";
639
639
  var SPEC_VERSION = "0.1.0";
640
640
  // Annotate the CommonJS export names for ESM import in node:
641
641
  0 && (module.exports = {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/audit.ts","../src/index.ts","../src/loader.ts","../src/models.ts","../src/exceptions.ts","../src/enforce.ts","../src/runner.ts","../src/validators/pattern.ts","../src/validators/cost.ts","../src/validators/latency.ts","../src/validators/llm.ts","../src/validators/base.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","/**\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","/** 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","/** 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","/** 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA,IAEAA,gBACAC,YAGa;AANb;AAAA;AAAA;AAAA;AAEA,IAAAD,iBAAuC;AACvC,IAAAC,aAA+B;AAGxB,IAAM,cAAN,MAAkB;AAAA,MACvB,YAAoB,UAAU,6BAA6B;AAAvC;AAAA,MAAwC;AAAA,MAE5D,MAAM,QAAmB,eAAe,IAA6B;AACnE,cAAM,QAAQ,KAAK,YAAY,QAAQ,YAAY;AACnD,uCAAe,KAAK,SAAS,KAAK,UAAU,KAAK,IAAI,MAAM,OAAO;AAClE,eAAO;AAAA,MACT;AAAA,MAEQ,YAAY,QAAmB,cAA+C;AACpF,cAAM,MAAM,OAAO;AACnB,cAAM,gBAAY,2BAAW,QAAQ,EAAE,OAAO,IAAI,KAAK,EAAE,OAAO,KAAK;AACrE,cAAM,iBAAa,2BAAW,QAAQ,EAAE,OAAO,IAAI,MAAM,EAAE,OAAO,KAAK;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AAe;","names":["import_crypto","import_fs","yaml","AuditWriter"]}
1
+ {"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/audit.ts","../src/index.ts","../src/loader.ts","../src/models.ts","../src/exceptions.ts","../src/enforce.ts","../src/runner.ts","../src/validators/pattern.ts","../src/validators/cost.ts","../src/validators/latency.ts","../src/validators/llm.ts","../src/validators/base.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","/**\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.1';\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","/** 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","/** 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","/** 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 clausesChecked: number;\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, clausesChecked: c.assert.length, 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA,IAEAA,gBACAC,YAGa;AANb;AAAA;AAAA;AAAA;AAEA,IAAAD,iBAAuC;AACvC,IAAAC,aAA+B;AAGxB,IAAM,cAAN,MAAkB;AAAA,MACvB,YAAoB,UAAU,6BAA6B;AAAvC;AAAA,MAAwC;AAAA,MAE5D,MAAM,QAAmB,eAAe,IAA6B;AACnE,cAAM,QAAQ,KAAK,YAAY,QAAQ,YAAY;AACnD,uCAAe,KAAK,SAAS,KAAK,UAAU,KAAK,IAAI,MAAM,OAAO;AAClE,eAAO;AAAA,MACT;AAAA,MAEQ,YAAY,QAAmB,cAA+C;AACpF,cAAM,MAAM,OAAO;AACnB,cAAM,gBAAY,2BAAW,QAAQ,EAAE,OAAO,IAAI,KAAK,EAA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AAW,SAAS;AACjC,YAAM,IAAI,0BAA0B,MAAM,OAAO;AAAA,IACnD;AAAA,EACF;AACF;;;AJ7FA;AANO,IAAM,UAAU;AAChB,IAAM,eAAe;","names":["import_crypto","import_fs","yaml","AuditWriter"]}
package/dist/index.mjs CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  enforce,
10
10
  loadContract,
11
11
  makeContext
12
- } from "./chunk-UHNX2RBZ.mjs";
12
+ } from "./chunk-62IASCRF.mjs";
13
13
  import {
14
14
  AuditWriter
15
15
  } from "./chunk-BVUHPJDU.mjs";
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@agentcontract/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Behavioral contracts for AI agents — TypeScript implementation of the AgentContract specification",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
8
8
  "exports": {
9
9
  ".": {
10
+ "types": "./dist/index.d.ts",
10
11
  "import": "./dist/index.mjs",
11
- "require": "./dist/index.js",
12
- "types": "./dist/index.d.ts"
12
+ "require": "./dist/index.js"
13
13
  }
14
14
  },
15
15
  "bin": {
@@ -28,7 +28,7 @@
28
28
  "license": "Apache-2.0",
29
29
  "repository": {
30
30
  "type": "git",
31
- "url": "https://github.com/agentcontract/agentcontract-ts.git"
31
+ "url": "git+https://github.com/agentcontract/agentcontract-ts.git"
32
32
  },
33
33
  "homepage": "https://github.com/agentcontract/spec",
34
34
  "bugs": { "url": "https://github.com/agentcontract/agentcontract-ts/issues" },
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../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/enforce.ts","../src/index.ts"],"sourcesContent":["/** 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","/** 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","/**\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"],"mappings":";AAEA,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,OAAO,UAAU;;;ACFjB,SAAS,SAAS;AAEX,IAAM,YAAY,EAAE,KAAK,CAAC,iBAAiB,KAAK,CAAC,EAAE,QAAQ,eAAe;AAG1E,IAAM,kBAAkB,EAAE,KAAK,CAAC,QAAQ,SAAS,YAAY,gBAAgB,CAAC,EAAE,QAAQ,OAAO;AAG/F,IAAM,gBAAgB,EAAE,KAAK,CAAC,WAAW,UAAU,OAAO,QAAQ,WAAW,QAAQ,CAAC;AAItF,IAAM,eAAe,EAAE,OAAO;AAAA,EACnC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,OAAO;AAAA,EACP,aAAa,EAAE,OAAO,EAAE,QAAQ,EAAE;AACpC,CAAC;AAGM,IAAM,SAAS,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,YAAY,CAAC;AAGxD,IAAM,qBAAqB,EAAE,MAAM;AAAA,EACxC,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChB,EAAE,OAAO;AAAA,IACP,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACtB,OAAO;AAAA,IACP,SAAS,EAAE,KAAK,CAAC,SAAS,MAAM,CAAC,EAAE,QAAQ,OAAO;AAAA,IAClD,aAAa,EAAE,OAAO,EAAE,QAAQ,EAAE;AAAA,EACpC,CAAC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