Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
#!/usr/bin/env node
// Upstream resilience audit.
//
// npm run audit:upstreams human table, exits non-zero on a regression
// npm run audit:upstreams -- --json machine-readable report
// npm run audit:upstreams -- --map regenerate docs/resilience.md
// npm run audit:upstreams -- --accept re-baseline after a deliberate change
//
// Why a ratchet instead of a threshold. Every third-party call in this repo was
// once written without a deadline, and each was added by someone who had no way
// to see that they were adding the fifty-ninth one. A number in a doc does not
// stop that; a baseline that fails the build the moment an unguarded call
// appears does. The baseline records the grade of every call site we know
// about, so a NEW unguarded call fails while the existing tail is free to be
// paid down at its own pace, and paying it down updates the baseline downward
// automatically (it can never drift back up without --accept).
//
// See docs/resilience.md for the generated map and scripts/resilience/analyze.mjs
// for how a call site is classified.
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { resolve, dirname, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execSync } from 'node:child_process';
import { analyzeFiles, gradeOf, byHost, PROTECTIONS } from './resilience/analyze.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const BASELINE = resolve(ROOT, 'data/upstream-baseline.json');
const MAP_DOC = resolve(ROOT, 'docs/resilience.md');
const args = new Set(process.argv.slice(2));
const asJson = args.has('--json');
const writeMap = args.has('--map');
const accept = args.has('--accept');
// Directories that ship runtime code. Tests are deliberately excluded: a test
// SHOULD be able to call a bare fetch against a stub.
const SCAN_DIRS = ['api', 'src', 'server', 'workers', 'mcp-server/src', 'avatar-sdk/src', 'public'];
// Built output is not source: grading a bundled asset reports findings nobody
// can act on, because the fix belongs in the module it was compiled from.
//
// The content-hash suffix has to be matched precisely. An earlier version of
// this pattern was `-[A-Za-z0-9_-]{8,}\.js$`, which also matched perfectly
// ordinary kebab-case source names (`market-fallbacks.js`,
// `guard-proof-upstream.js`) and silently dropped them from the audit. A
// bundler hash always carries an uppercase letter or a digit; a hand-written
// filename in this repo is lowercase words, so requiring one of those in the
// final segment separates them without excluding real source.
const SKIP_RE =
/(?:^|\/)(?:node_modules|dist|dist-lib|build|coverage|\.deploy-wt|assets|vendor)(?:\/|$)|\.min\.js$|\.test\.js$|\.spec\.js$|-[a-z0-9_-]*[A-Z0-9][A-Za-z0-9_-]{7,}\.js$/;
function sourceFiles() {
const out = [];
for (const dir of SCAN_DIRS) {
const abs = resolve(ROOT, dir);
if (!existsSync(abs)) continue;
let listing;
try {
listing = execSync(`find ${JSON.stringify(abs)} -type f \\( -name '*.js' -o -name '*.mjs' \\)`, {
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
});
} catch {
continue;
}
for (const line of listing.split('\n')) {
const f = line.trim();
if (!f) continue;
if (SKIP_RE.test(relative(ROOT, f))) continue;
out.push(f);
}
}
return out.sort();
}
/** Stable id for a call site, so the baseline survives edits above it. */
function siteKey(site) {
return `${site.file}::${site.host}::${site.via}`;
}
function loadBaseline() {
if (!existsSync(BASELINE)) return null;
try {
return JSON.parse(readFileSync(BASELINE, 'utf8'));
} catch {
return null;
}
}
const GRADE_RANK = { F: 0, D: 1, C: 2, B: 3, A: 4 };
function summarize(callSites) {
const grades = { A: 0, B: 0, C: 0, D: 0, F: 0 };
const counts = Object.fromEntries(PROTECTIONS.map((p) => [p, 0]));
for (const s of callSites) {
grades[gradeOf(s)] += 1;
for (const p of s.protections) if (p in counts) counts[p] += 1;
}
return { total: callSites.length, grades, protections: counts };
}
/** Worst grade per site key, which is what the baseline pins. */
function gradeIndex(callSites) {
const idx = {};
for (const s of callSites) {
const k = siteKey(s);
const g = gradeOf(s);
if (!(k in idx) || GRADE_RANK[g] < GRADE_RANK[idx[k]]) idx[k] = g;
}
return idx;
}
function renderMap(callSites, summary) {
const hosts = byHost(callSites);
const worst = hosts.filter((h) => h.worst === 'F' || h.worst === 'D');
const lines = [];
lines.push('<!-- GENERATED by scripts/audit-upstreams.mjs. Run `npm run audit:upstreams -- --map`. -->');
lines.push('# Upstream resilience map');
lines.push('');
lines.push('Every third-party service this platform calls, and what happens to a user when');
lines.push('that service is down. Generated from the source by an AST pass, so it cannot');
lines.push('drift from the code the way a hand-written list does.');
lines.push('');
lines.push('## How a call site is graded');
lines.push('');
lines.push('| Grade | Meaning |');
lines.push('|---|---|');
lines.push('| A | Bounded, and survives the upstream being down (a second source, plus a remembered value or a retry) |');
lines.push('| B | Bounded, with one way to survive: either another source or a remembered value |');
lines.push('| C | Bounded, retries or trips a breaker, but has no second source |');
lines.push('| D | Bounded only: a deadline and nothing behind it |');
lines.push('| F | Unbounded: one stalled socket can outlive the request that opened it |');
lines.push('');
lines.push('A deadline is the floor rather than one grade among five, because without one');
lines.push('no other protection ever gets a turn.');
lines.push('');
lines.push('## Totals');
lines.push('');
lines.push(`${summary.total} outbound call sites across ${hosts.length} upstreams.`);
lines.push('');
lines.push('| A | B | C | D | F |');
lines.push('|---|---|---|---|---|');
lines.push(
`| ${summary.grades.A} | ${summary.grades.B} | ${summary.grades.C} | ${summary.grades.D} | ${summary.grades.F} |`,
);
lines.push('');
if (worst.length) {
lines.push('## Weakest upstreams');
lines.push('');
lines.push('These carry at least one call site with no second source behind it. They are');
lines.push('the list to work down, worst first.');
lines.push('');
lines.push('| Upstream | Call sites | Worst grade |');
lines.push('|---|---|---|');
for (const h of worst.slice(0, 25)) {
lines.push(`| \`${h.host}\` | ${h.sites} | ${h.worst} |`);
}
lines.push('');
}
lines.push('## Every upstream');
lines.push('');
lines.push('| Upstream | Call sites | Worst grade | A | B | C | D | F |');
lines.push('|---|---|---|---|---|---|---|---|');
for (const h of hosts) {
lines.push(
`| \`${h.host}\` | ${h.sites} | ${h.worst} | ${h.grades.A} | ${h.grades.B} | ${h.grades.C} | ${h.grades.D} | ${h.grades.F} |`,
);
}
lines.push('');
lines.push('## Keeping this true');
lines.push('');
lines.push('`npm run audit:upstreams` fails when a call site regresses below the grade');
lines.push('recorded in `data/upstream-baseline.json`, or when a new unbounded call appears.');
lines.push('Improving a call site lowers the baseline automatically; raising it back needs an');
lines.push('explicit `--accept`, which is a reviewable line in the diff.');
lines.push('');
return lines.join('\n');
}
function main() {
const files = sourceFiles();
const { callSites, parseErrors } = analyzeFiles(files, ROOT);
const summary = summarize(callSites);
const index = gradeIndex(callSites);
if (asJson) {
process.stdout.write(
`${JSON.stringify({ summary, hosts: byHost(callSites), callSites, parseErrors }, null, '\t')}\n`,
);
return 0;
}
if (writeMap) {
writeFileSync(MAP_DOC, `${renderMap(callSites, summary)}`);
console.log(`audit:upstreams: wrote ${relative(ROOT, MAP_DOC)}`);
}
const baseline = loadBaseline();
if (accept || !baseline) {
writeFileSync(
BASELINE,
`${JSON.stringify({ generated: 'scripts/audit-upstreams.mjs', summary, sites: index }, null, '\t')}\n`,
);
console.log(
`audit:upstreams: baseline ${baseline ? 're-recorded' : 'created'} for ${summary.total} call sites ` +
`(A:${summary.grades.A} B:${summary.grades.B} C:${summary.grades.C} D:${summary.grades.D} F:${summary.grades.F})`,
);
return 0;
}
// Regressions: a known site that got worse, or a new site below the floor.
const regressed = [];
const newUnbounded = [];
for (const site of callSites) {
const key = siteKey(site);
const grade = gradeOf(site);
const was = baseline.sites?.[key];
if (was === undefined) {
if (grade === 'F') newUnbounded.push({ site, grade });
continue;
}
if (GRADE_RANK[grade] < GRADE_RANK[was]) regressed.push({ site, grade, was });
}
// Improvements ratchet the baseline down on their own, so the floor only ever
// rises and nobody has to remember to re-record a fix. New call sites are
// recorded at whatever grade they arrive with: a bounded one that goes in
// unrecorded could later weaken to D without tripping anything, because an
// unknown key is only checked against the F floor.
let improved = 0;
let added = 0;
let removed = 0;
const nextSites = { ...(baseline.sites || {}) };
for (const [key, grade] of Object.entries(index)) {
const was = nextSites[key];
if (was === undefined) {
added += 1;
nextSites[key] = grade;
} else if (GRADE_RANK[grade] > GRADE_RANK[was]) {
improved += 1;
nextSites[key] = grade;
}
}
for (const key of Object.keys(nextSites)) {
if (!(key in index)) {
delete nextSites[key]; // call site removed
removed += 1;
}
}
console.log(
`audit:upstreams: ${summary.total} outbound call sites across ${byHost(callSites).length} upstreams ` +
`(A:${summary.grades.A} B:${summary.grades.B} C:${summary.grades.C} D:${summary.grades.D} F:${summary.grades.F})`,
);
if (parseErrors.length) {
console.log(`audit:upstreams: ${parseErrors.length} file(s) could not be parsed and were skipped`);
}
if (regressed.length || newUnbounded.length) {
console.error('');
for (const r of regressed) {
console.error(
`[upstreams] ${r.site.file}:${r.site.line} ${r.site.host} ${r.was} -> ${r.grade}`,
);
console.error(` protections: ${r.site.protections.join(', ') || 'none'}`);
}
for (const n of newUnbounded) {
console.error(`[upstreams] ${n.site.file}:${n.site.line} ${n.site.host} NEW unbounded call`);
console.error(' wrap it with fetchUpstream from api/_lib/upstream-fetch.js,');
console.error(' or fetchFirst from src/shared/failover-fetch.js in browser code.');
}
console.error('');
console.error(
`audit:upstreams: ${regressed.length} regression(s), ${newUnbounded.length} new unbounded call(s).`,
);
console.error('If the change is deliberate, re-baseline with: npm run audit:upstreams -- --accept');
return 1;
}
if (improved || added || removed) {
writeFileSync(
BASELINE,
`${JSON.stringify({ generated: 'scripts/audit-upstreams.mjs', summary, sites: nextSites }, null, '\t')}\n`,
);
const parts = [];
if (improved) parts.push(`${improved} improved`);
if (added) parts.push(`${added} new`);
if (removed) parts.push(`${removed} removed`);
console.log(`audit:upstreams: baseline updated (${parts.join(', ')})`);
}
console.log('audit:upstreams: no regressions');
return 0;
}
process.exit(main());