// SoftwareCannery board-inspection agent: the brintOS inspector station uploads a camera // photo of a board; this finds the board in the frame, crops to it, and sends it to Claude // vision with the board's checklist, the station's golden-master photo and the operators' // lessons (inspect-knowledge.mjs), and returns a structured verdict. Every photo, crop and // result is kept under ./inspections// for traceability and replay (inspect-replay.mjs). // // API key: ANTHROPIC_API_KEY in the environment, else the first line of ~/.anthropic-key. // Tuning: inspect-config.json (re-read on every inspection, no restart needed). import Anthropic from '@anthropic-ai/sdk'; import sharp from 'sharp'; import { readFileSync, mkdirSync, writeFileSync, existsSync, copyFileSync, appendFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { getNotes, knowledgeInfo, submitFeedback, recordLabel } from './inspect-knowledge.mjs'; const HERE = fileURLToPath(new URL('.', import.meta.url)); const OUT = join(HERE, 'inspections'); const DEFAULTS = { model: 'claude-opus-5-5', // the inspection model effort: 'medium', reference: 'golden', // 'golden' = station golden master if set, 'catalog' = product photo, 'none' crop: true, // find the board in the frame and send only the board locateModel: 'claude-haiku-5-5', maxEdge: 2576, // Opus 5.5 reads up to 2576 px on the long edge brief: true, // short per-item notes (faster) }; export function config(over = {}) { let file = {}; try { file = JSON.parse(readFileSync(join(HERE, 'inspect-config.json'), 'utf8')); } catch {} return { ...DEFAULTS, ...file, ...over }; } // ---- boards: what to look for, in the order the station lists it ---- export const BOARDS = { 'som-stm32h753-2a-top': { name: 'Emcraft SOM-STM32H753 2A, top side (TPSys layout SOM-STM32H753-2A-T, 31 parts)', ref: 'inspect-ref/som-stm32h753-2a-top.jpg', checks: [ 'MCU: STM32H753IIK6 BGA (U1), centre of the board, ARM / ST logo, seated flat', 'SDRAM: Alliance Memory AS4C16M16SA-6BIN BGA (U3), top left', 'NOR flash: Spansion S29GL128S BGA (U2), top centre', 'Ethernet PHY: Micrel KSZ8081RNB QFN (U5), right side', 'Crystals: Y1 and Y3 25 MHz (ECS-250, 3.2x2.5 mm) and Y2 32.768 kHz (FC-135) present', 'Passives: all 31 top-side parts populated - R5-R17 (incl. 33R array R7-R13), R38, R43, C6, C8, C9, C12, C19, C22, C44-C47 - no tombstones or missing parts', 'Solder: no bridges, no insufficient or excess solder, no stray solder balls', 'Orientation: ICs and polarized parts match their silkscreen pin-1 / polarity marks', 'Board condition: no cracks, scratches, burns, flux residue or foreign objects', ], }, 'som-stm32h753-2a-bottom': { name: 'Emcraft SOM-STM32H753 2A, bottom side (TPSys layout SOM-STM32H753-2A-B, 58 parts)', ref: 'inspect-ref/som-stm32h753-2a-bottom.jpg', checks: [ 'Connectors: P1 and P2 Hirose DF40C-80DP 0.4 mm board-to-board, seated flat, no bent, missing or bridged pins', 'Diode D1: BAT54A SOT-23 near P1, orientation matches the silkscreen', 'Ferrites: L1, L2, L3 (BLM18PG121, 0603) present', 'Bulk capacitors: C13 and C21 (10 uF 0603), C15 and C18 (22 uF 0805), C27 and C28 (2.2 uF 0402) present', 'Decoupling: all 33 x 100 nF 0402 capacitors present (C1-C5, C7, C14, C16, C17, C20, C23-C26, C29-C43, C48-C51)', 'Resistors: R1-R4, R37 (24k), R16, R36, R39-R42 (10k), R18 (33R), R24 (22R) present', 'Solder: no bridges (especially between the fine-pitch P1 / P2 pins), no insufficient or excess solder, no solder balls', 'Orientation: polarized parts match their silkscreen marks', 'Board condition: no cracks, scratches, burns, flux residue or foreign objects', ], }, 'som-stm32f7-v2a': { name: 'Emcraft SOM-STM32F7 V2A (STM32F7-SOM-1A), top side', ref: 'inspect-ref/som-stm32f7-v2a.jpg', checks: [ 'MCU: STM32F746NGH6 BGA, centre of the board, ST logo, seated flat', 'SDRAM: ESMT M12L2561616A BGA, bottom right (U3)', 'NOR flash: Spansion S29GL128S BGA, bottom centre (U2)', 'Ethernet PHY: Micrel KSZ8081RNB QFN, left side (U5)', 'Crystals / oscillators: Y1, Y2 and the 25 MHz oscillator Y3 present', 'Passives: every resistor and capacitor pad populated, no tombstoned or missing parts', 'Solder: no bridges, no insufficient or excess solder, no stray solder balls', 'Orientation: ICs and polarized parts match their silkscreen pin-1 / polarity marks', 'Board condition: no cracks, scratches, burns, flux residue or foreign objects', ], }, }; const goldenPath = (board) => join(HERE, 'inspect-ref', `${board}-golden.jpg`); const STATUS = ['pass', 'fail', 'uncertain', 'not_visible']; const SCHEMA = { type: 'object', additionalProperties: false, required: ['verdict', 'summary', 'image_quality', 'checks', 'defects'], properties: { verdict: { type: 'string', enum: ['pass', 'fail', 'retake'] }, summary: { type: 'string' }, image_quality: { type: 'string' }, checks: { type: 'array', items: { type: 'object', additionalProperties: false, required: ['item', 'status', 'note'], properties: { item: { type: 'string' }, status: { type: 'string', enum: STATUS }, note: { type: 'string' } }, }, }, defects: { type: 'array', items: { type: 'object', additionalProperties: false, required: ['location', 'description', 'severity'], properties: { location: { type: 'string' }, description: { type: 'string' }, severity: { type: 'string', enum: ['minor', 'major', 'critical'] } }, }, }, }, }; const SYSTEM = `You are an automated optical inspection (AOI) agent on a PCB assembly line. You get a photo of one assembled board taken by the station camera (cropped to the board), a known-good reference photo of the same board type, the operators' notes for this board type, and a numbered checklist. Answer every checklist item, in the same order, using the item text as given. For each one say pass, fail, uncertain (visible but you cannot be sure) or not_visible (not in frame, out of focus, or hidden by glare), with a short concrete note (what you saw and where). List every defect you can see, including ones outside the checklist, with its location on the board as you see it in the photo. Verdict: "pass" only when every item passes and there are no major or critical defects; "retake" when the photo is too blurry, dark, glared, cropped or angled to judge most items; otherwise "fail". Be conservative: an assembly line would rather re-check a good board than ship a bad one. Keep the summary to one or two sentences an operator can act on.`; const BRIEF = `\nBe brief: each check note under 15 words, the summary one sentence, image_quality under 15 words.`; function apiKey() { if (process.env.ANTHROPIC_API_KEY) return process.env.ANTHROPIC_API_KEY.trim(); try { return readFileSync(join(process.env.HOME || '/root', '.anthropic-key'), 'utf8').split('\n')[0].trim() || null; } catch { return null; } } let client = null, clientKey = null; function getClient() { const k = apiKey(); if (!k) return null; if (k !== clientKey) { client = new Anthropic({ apiKey: k }); clientKey = k; } return client; } const textOf = (resp) => resp.content.filter((b) => b.type === 'text').map((b) => b.text).join(''); // server-side fallback (retry on another model after a refusal) exists for Opus; not for Haiku const fallbackFor = (model) => (model.startsWith('claude-opus') ? { betas: ['server-side-fallback-2026-07-01'], fallbacks: 'default' } : {}); function readRaw(req, limit) { return new Promise((resolve, reject) => { const parts = []; let n = 0; req.on('data', (c) => { n += c.length; if (n > limit) { reject(new Error('image too large')); req.destroy(); } else parts.push(c); }); req.on('end', () => resolve(Buffer.concat(parts))); req.on('error', reject); }); } // ---- find the board in the frame (fast model, small image), crop to it ---- const BOX = { type: 'object', additionalProperties: false, required: ['found', 'left', 'top', 'right', 'bottom'], properties: { found: { type: 'boolean' }, left: { type: 'integer' }, top: { type: 'integer' }, right: { type: 'integer' }, bottom: { type: 'integer' } }, }; export async function cropToBoard(jpeg, cfg) { const t0 = Date.now(); const { data: full, info } = await sharp(jpeg).rotate().toBuffer({ resolveWithObject: true }); const W = info.width, H = info.height; const fit = (buf) => sharp(buf).resize({ width: cfg.maxEdge, height: cfg.maxEdge, fit: 'inside', withoutEnlargement: true }).jpeg({ quality: 90 }).toBuffer(); if (!cfg.crop) return { jpeg: await fit(full), box: null, ms: Date.now() - t0 }; const c = getClient(); const small = await sharp(full).resize({ width: 768, height: 768, fit: 'inside' }).jpeg({ quality: 80 }).toBuffer(); let box = null; try { const resp = await c.beta.messages.create({ model: cfg.locateModel, max_tokens: 2000, output_config: { effort: 'low', format: { type: 'json_schema', schema: BOX } }, messages: [{ role: 'user', content: [ { type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: small.toString('base64') } }, { type: 'text', text: 'Find the printed circuit board in this photo. Give its bounding box in coordinates from 0 to 1000 (left, top, right, bottom as fractions of the image width and height times 1000). found=false if there is no board.' }, ] }], }); if (resp.stop_reason === 'end_turn') box = JSON.parse(textOf(resp)); } catch (e) { console.log('[inspect] locate failed:', e.message); } if (!box || !box.found || box.right - box.left < 50 || box.bottom - box.top < 50) return { jpeg: await fit(full), box: null, ms: Date.now() - t0 }; const pad = 0.07; const bw = box.right - box.left, bh = box.bottom - box.top; const l = Math.max(0, Math.floor((box.left - bw * pad) / 1000 * W)), t = Math.max(0, Math.floor((box.top - bh * pad) / 1000 * H)); const r = Math.min(W, Math.ceil((box.right + bw * pad) / 1000 * W)), b = Math.min(H, Math.ceil((box.bottom + bh * pad) / 1000 * H)); const cropped = await sharp(full).extract({ left: l, top: t, width: r - l, height: b - t }).toBuffer(); return { jpeg: await fit(cropped), box: [l, t, r - l, b - t], ms: Date.now() - t0 }; } // ---- golden master: a known-good board photographed at this station ---- export async function setGolden(boardKey, inspectionId) { if (!BOARDS[boardKey]) return { ok: false, error: 'unknown board' }; const dir = join(OUT, String(inspectionId).slice(0, 10)); const crop = join(dir, inspectionId + '-crop.jpg'), raw = join(dir, inspectionId + '.jpg'); let jpeg; if (existsSync(crop)) jpeg = readFileSync(crop); else if (existsSync(raw)) jpeg = (await cropToBoard(readFileSync(raw), config({ crop: true }))).jpeg; else return { ok: false, error: 'no photo for that inspection' }; const g = goldenPath(boardKey); mkdirSync(join(HERE, 'inspect-ref', 'history'), { recursive: true }); if (existsSync(g)) copyFileSync(g, join(HERE, 'inspect-ref', 'history', `${boardKey}-golden-${new Date().toISOString().replace(/[:.]/g, '-')}.jpg`)); writeFileSync(g, jpeg); writeFileSync(g.replace(/\.jpg$/, '.json'), JSON.stringify({ from: inspectionId, t: new Date().toISOString() }, null, 1)); console.log(`[inspect] golden master for ${boardKey} set from ${inspectionId}`); return { ok: true }; } // analyze(photo, board, overrides) -> { ok, result, ms, model, usage, timing, crop } export async function analyze(jpeg, boardKey, over = {}) { const board = BOARDS[boardKey]; if (!board) return { ok: false, error: `unknown board "${boardKey}"` }; const c = getClient(); if (!c) return { ok: false, error: 'server has no Anthropic API key (install ~/.anthropic-key on the server)' }; const cfg = config(over); const t0 = Date.now(); const located = over.cropped ? { jpeg: over.cropped, box: 'given', ms: 0 } : await cropToBoard(jpeg, cfg); const content = []; const golden = goldenPath(boardKey); if (cfg.reference === 'golden' && existsSync(golden)) { content.push({ type: 'text', text: 'Golden master: a known-good board of this exact build, photographed at this station (it may be rotated or placed differently). Differences from it are what matter:' }); content.push({ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: readFileSync(golden).toString('base64') } }); } else if (cfg.reference !== 'none' && existsSync(join(HERE, board.ref))) { content.push({ type: 'text', text: 'Known-good reference photo (product photo, may be lit differently):' }); content.push({ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: readFileSync(join(HERE, board.ref)).toString('base64') } }); } content.push({ type: 'text', text: `Board: ${board.name}\nChecklist:\n${board.checks.map((t, i) => `${i + 1}. ${t}`).join('\n')}` }); const notes = getNotes(boardKey).trim(); if (notes) content.push({ type: 'text', text: `Notes for this board type, taught by the line's operators. Follow them; where they conflict with the checklist wording, the notes win:\n${notes}` }); // everything above is the same for every board of this type: cache it content[content.length - 1] = { ...content[content.length - 1], cache_control: { type: 'ephemeral' } }; content.push({ type: 'text', text: 'Station photo of the board under inspection:' }); content.push({ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: located.jpeg.toString('base64') } }); const t1 = Date.now(); let resp; try { resp = await c.beta.messages.create({ model: cfg.model, max_tokens: 16000, ...fallbackFor(cfg.model), system: SYSTEM + (cfg.brief ? BRIEF : ''), output_config: { effort: cfg.effort, format: { type: 'json_schema', schema: SCHEMA } }, messages: [{ role: 'user', content }], }); } catch (e) { if (e instanceof Anthropic.AuthenticationError) return { ok: false, error: 'Anthropic API key rejected' }; if (e instanceof Anthropic.RateLimitError) return { ok: false, error: 'rate limited by the API, try again shortly' }; if (e instanceof Anthropic.APIStatusError) return { ok: false, error: `API error ${e.status}: ${e.message}` }; if (e instanceof Anthropic.APIConnectionError) return { ok: false, error: 'server could not reach the Anthropic API' }; throw e; } const timing = { locate_ms: located.ms, model_ms: Date.now() - t1 }; const ms = Date.now() - t0; if (resp.stop_reason === 'refusal') return { ok: false, error: 'the model declined this image', ms, timing }; if (resp.stop_reason === 'max_tokens') return { ok: false, error: 'analysis was cut off (max_tokens)', ms, timing }; let result; try { result = JSON.parse(textOf(resp)); } catch { return { ok: false, error: 'analysis was not valid JSON', ms, timing }; } // keep the station's row order even if the model renamed an item result.checks = board.checks.map((item, i) => { const r = result.checks?.[i] || {}; return { item, status: STATUS.includes(r.status) ? r.status : 'uncertain', note: String(r.note || '') }; }); const u = resp.usage || {}; return { ok: true, result, ms, timing, model: resp.model, crop: located.box, cropJpeg: located.jpeg, config: { model: cfg.model, effort: cfg.effort, reference: cfg.reference, crop: cfg.crop, brief: cfg.brief }, usage: { input: u.input_tokens, output: u.output_tokens, cache_read: u.cache_read_input_tokens || 0, cache_write: u.cache_creation_input_tokens || 0 }, }; } // quick labels need no AI call: "good", "bad", "this board is good", "pass", ... const LABEL = /^\s*(?:(?:this|that)\s+(?:board|one)\s+(?:is\s+)?)?(good|bad|pass(?:ed|es)?|fail(?:ed|s)?)\s*[.!]?\s*$/i; // Route /inspect/* for loader-server.mjs. Returns true when it handled the request. export async function handleInspect(req, res, p, url, json) { if (p === '/inspect/status') { json(res, 200, { key: !!apiKey(), config: config(), boards: Object.keys(BOARDS) }); return true; } if (p === '/inspect/analyze' && req.method === 'POST') { const boardKey = String(url.searchParams.get('board') || ''); const station = String(url.searchParams.get('station') || '').slice(0, 64); const jpeg = await readRaw(req, 15 * 1024 * 1024); if (jpeg.length < 1000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) { json(res, 400, { ok: false, error: 'body must be a JPEG photo' }); return true; } const stamp = new Date().toISOString().replace(/[:.]/g, '-'); const day = stamp.slice(0, 10); const id = `${stamp}-${boardKey}`; const dir = join(OUT, day); mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, id + '.jpg'), jpeg); let out; try { out = await analyze(jpeg, boardKey); } catch (e) { out = { ok: false, error: 'analysis failed: ' + (e && e.message || e) }; } out.id = id; if (out.cropJpeg) writeFileSync(join(dir, id + '-crop.jpg'), out.cropJpeg); delete out.cropJpeg; writeFileSync(join(dir, id + '.json'), JSON.stringify({ station, board: boardKey, bytes: jpeg.length, ...out }, null, 1)); console.log(`[inspect] ${id} ${station} ${out.ok ? out.result.verdict : 'ERROR ' + out.error} ${out.ms || 0} ms ${out.timing ? JSON.stringify(out.timing) : ''}`); json(res, 200, out); return true; } if (p === '/inspect/health' && req.method === 'POST') { try { const b = (await readRaw(req, 64 * 1024)).toString('utf8'); const j = JSON.parse(b); const d = join(HERE, 'health'); mkdirSync(d, { recursive: true }); const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || ''); appendFileSync(join(d, new Date().toISOString().slice(0, 10) + '.jsonl'), JSON.stringify({ at: new Date().toISOString(), ip, ...j }) + '\n'); } catch {} res.writeHead(204); res.end(); return true; } if (p === '/inspect/knowledge') { const board = String(url.searchParams.get('board') || ''); if (!BOARDS[board]) { json(res, 404, { ok: false, error: 'unknown board' }); return true; } json(res, 200, { ok: true, ...knowledgeInfo(board) }); return true; } if (p === '/inspect/feedback' && req.method === 'POST') { let m; try { m = JSON.parse((await readRaw(req, 64 * 1024)).toString('utf8')); } catch { json(res, 400, { ok: false, error: 'bad JSON' }); return true; } const board = String(m.board || ''), text = String(m.text || '').trim().slice(0, 2000); if (!BOARDS[board]) { json(res, 400, { ok: false, error: `unknown board "${board}"` }); return true; } if (!text) { json(res, 400, { ok: false, error: 'empty feedback' }); return true; } const item = { board, text, station: String(m.station || '').slice(0, 64), inspection: String(m.inspection || '') }; const lab = LABEL.exec(text); if (lab && item.inspection) { const v = /^(good|pass)/i.test(lab[1]) ? 'pass' : 'fail'; json(res, 200, recordLabel(item, v)); return true; } let golden = null; if (/\bgold(?:en)?\s*master\b/i.test(text) && item.inspection) golden = await setGolden(board, item.inspection); const out = await submitFeedback(apiKey, BOARDS[board], item); if (golden?.ok) out.ack = `Golden master set from this photo. ${out.ack || ''}`.trim(); json(res, 200, out); return true; } return false; }