agentcomply / tree / src/core.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// AgentComply core: validate -> run live checks -> apply policy -> sealed, hash-chained receipt.
import * as C from './checks.js';
import { decide } from './policy.js';
import { seal, sha256hex, canonicalize, verifyReceipt } from './receipt.js';

export const VERSION = 'agentcomply-0.1.0';
const DISCLAIMER = 'Automated pre-payment screening record. Informational only; not legal, compliance or financial advice. "ok" means no known risk signal was found by the listed checks at the listed time, not that the counterparty is lawful or trustworthy. OFAC sanctions also apply to persons and property not listed by address.';

export function validate(raw, policy) {
  const errors = [];
  const s = (v) => (typeof v === 'string' ? v.trim() : v);
  const input = {
    payTo: s(raw.payTo),
    chain: s(raw.chain || 'base')?.toLowerCase(),
    intent: s(raw.intent || 'pay'),
    amount_usd: raw.amount_usd === undefined || raw.amount_usd === '' ? undefined : Number(raw.amount_usd),
    asset: s(raw.asset),
    token: s(raw.token),
    merchantDomain: s(raw.merchantDomain),
    instructions: typeof raw.instructions === 'string' ? raw.instructions : undefined,
    agentId: s(raw.agentId),
    sign: raw.sign && typeof raw.sign === 'object' ? { to: s(raw.sign.to), data: s(raw.sign.data), value: s(raw.sign.value), chain: s(raw.sign.chain), from: s(raw.sign.from) } : undefined,
    reference: typeof raw.reference === 'string' ? raw.reference.slice(0, 200) : undefined,
  };
  if (!input.payTo || typeof input.payTo !== 'string') errors.push('payTo is required (0x address, Solana address, ENS name or Basename)');
  else if (input.payTo.length > 128) errors.push('payTo is too long');
  if (policy.allowed_chains && !policy.allowed_chains.includes(input.chain)) errors.push(`chain "${input.chain}" is not allowed by policy (${policy.allowed_chains.join(', ')})`);
  if (!['pay', 'approve', 'interact'].includes(input.intent)) errors.push('intent must be pay, approve or interact');
  if (input.amount_usd !== undefined && (!Number.isFinite(input.amount_usd) || input.amount_usd < 0)) errors.push('amount_usd must be a non-negative number');
  if (input.merchantDomain && !/^[a-z0-9.-]{3,253}$/i.test(input.merchantDomain.replace(/^https?:\/\//, '').split('/')[0])) errors.push('merchantDomain is not a valid hostname');
  if (input.merchantDomain) input.merchantDomain = input.merchantDomain.replace(/^https?:\/\//, '').split('/')[0].toLowerCase();
  if (input.token && !/^0x[0-9a-fA-F]{40}$/.test(input.token)) errors.push('token must be a 0x token contract address (Base)');
  if (input.sign && (!input.sign.to || !/^0x[0-9a-fA-F]*$/.test(input.sign.data || ''))) errors.push('sign needs {to, data} (hex calldata)');
  if (input.instructions && input.instructions.length > 20000) errors.push('instructions longer than 20,000 characters');
  return { input, errors };
}

// deps: { fetch, signer, store, policy, mode, creditsKey, base, now, timeoutMs, retryDelayMs, issuer }
export async function screen(raw, deps) {
  const policy = deps.policy;
  const { input, errors } = validate(raw || {}, policy);
  if (errors.length) return { status: 400, body: { error: 'invalid_input', errors } };

  const ctx = { fetch: deps.fetch, base: deps.base || C.DEFAULT_BASE, mode: deps.mode || 'preview', creditsKey: deps.creditsKey, policy, timeoutMs: deps.timeoutMs, retryDelayMs: deps.retryDelayMs };
  const isName = /\.eth$/i.test(input.payTo);

  // Counterparty first when a name must be resolved; otherwise everything runs in parallel.
  const checks = [];
  let cp;
  if (isName) {
    cp = await C.counterparty(ctx, { address: input.payTo, chain: input.chain, intent: input.intent });
    if (cp.input_error) return { status: 400, body: { error: 'invalid_input', errors: [cp.input_error], upstream: 'CounterpartyCheck' } };
  }
  const resolved = cp?.resolved_address || (isName ? null : input.payTo);
  const jobs = [];
  if (!cp) jobs.push(C.counterparty(ctx, { address: input.payTo, chain: input.chain, intent: input.intent }));
  if (resolved) jobs.push(C.sanctions(ctx, { address: resolved }));
  if (input.sign) jobs.push(C.presign(ctx, { sign: input.sign, chain: input.chain }));
  if (input.token) jobs.push(C.token(ctx, { token: input.token }));
  if (input.merchantDomain) jobs.push(C.merchant(ctx, { domain: input.merchantDomain }));
  if (input.instructions) jobs.push(C.instructions(ctx, { text: input.instructions }));
  if (input.agentId) jobs.push(C.agentIdentity(ctx, { agentId: input.agentId }));
  const results = await Promise.all(jobs);
  if (cp) checks.push(cp);
  checks.push(...results);
  const cpc = checks.find((c) => c.check === 'counterparty');
  if (cpc?.input_error) return { status: 400, body: { error: 'invalid_input', errors: [cpc.input_error], upstream: 'CounterpartyCheck' } };
  if (isName && !resolved) {
    // Name lookup failed upstream: we could not screen the real address. Caution, low confidence.
    checks.push({ check: 'sanctions', tool: 'PayGuard', outcome: 'caution', confidence: 'low', retryable: true, signals: ['name_unresolved'], sources_failed: ['name_resolution'], reasons: [`Could not resolve ${input.payTo} to an address; sanctions screen not run`] });
  }

  const decision = decide(input, checks, policy);
  const now = (deps.now || (() => new Date()))();
  const instructionsHash = input.instructions ? await sha256hex(input.instructions) : undefined;
  const recordedInput = { ...input, instructions: input.instructions ? { sha256: instructionsHash, excerpt: input.instructions.slice(0, 280) } : undefined };
  const requestHash = await sha256hex(canonicalize(recordedInput));
  const policyHash = await sha256hex(canonicalize(policy));

  // Optimistic append: if another request extended the chain meanwhile, re-seal on the new head.
  let receipt;
  for (let attempt = 0; attempt < 5; attempt++) {
    const head = (await deps.store.head()) || { seq: 0, hash: null };
    const body = {
      receipt_version: '1',
      receipt_id: crypto.randomUUID(),
      issued_at: now.toISOString(),
      issuer: { service: 'AgentComply', version: VERSION, ...(deps.issuer || {}) },
      subject: { payTo: input.payTo, resolved_address: resolved || null, chain: input.chain, intent: input.intent, amount_usd: input.amount_usd ?? null, reference: input.reference ?? null },
      request: { sha256: requestHash, input: recordedInput },
      policy: { id: policy.id, version: policy.version, sha256: policyHash },
      mode: ctx.mode,
      checks: checks.map(strip),
      decision,
      chain: { seq: head.seq + 1, prev_hash: head.hash },
      disclaimer: DISCLAIMER,
    };
    receipt = await seal(body, deps.signer);
    const ok = await deps.store.append(receipt);
    if (ok !== false) break;
    receipt = null;
  }
  if (!receipt) return { status: 503, body: { error: 'ledger_busy', retryable: true, verdict: decision.verdict === 'block' ? 'block' : 'caution', message: 'could not append the receipt; treat as not screened and retry' } };
  return {
    status: 200,
    body: { verdict: decision.verdict, action: decision.action, retryable: decision.retryable, reasons: decision.reasons, sources_failed: decision.sources_failed, receipt },
  };
}

function strip(c) {
  const o = {};
  for (const [k, v] of Object.entries(c)) if (v !== undefined && !(Array.isArray(v) && v.length === 0 && !['sources_failed'].includes(k))) o[k] = v;
  if (!o.sources_failed) o.sources_failed = [];
  return o;
}

export async function verify(receipt, publicJwk) {
  const v = await verifyReceipt(receipt, publicJwk);
  return { ...v, receipt_id: receipt?.receipt_id, seq: receipt?.chain?.seq, verdict: receipt?.decision?.verdict };
}

agentgate-source: code mirror on Cloudflare Pages. All repos