← Commit history
Publish 1.1.0
17 files changed
+2555−605
Cargo.lock+32−1@@ -10,13 +10,14 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-ds2sf"-version = "0.8.1"+version = "0.9.0" dependencies = [ "anyhow", "clap", "serde", "serde_json", "sha2",+ "tiny_http", "ureq", ] @@ -76,6 +77,12 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]]+name = "ascii"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"+ [[package]] name = "base64" version = "0.22.1"@@ -107,6 +114,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]]+name = "chunked_transfer"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"+ [[package]] name = "clap" version = "4.6.1"@@ -254,6 +267,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+ [[package]] name = "icu_collections" version = "2.2.0"@@ -609,6 +628,18 @@ dependencies = [ "syn", ] +[[package]]+name = "tiny_http"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"+dependencies = [+ "ascii",+ "chunked_transfer",+ "httpdate",+ "log",+]+ [[package]] name = "tinystr" version = "0.8.3"
Cargo.toml+2−1@@ -1,6 +1,6 @@ [package] name = "adom-ds2sf"-version = "0.8.1"+version = "0.9.0" edition = "2021" description = "Datasheet → symbol + footprint + provenance JSON. Reads a chip's datasheet PDF and produces sym_create-shaped symbol JSON, footprint metadata, and a field-level provenance audit trail." @@ -15,6 +15,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" ureq = { version = "2", features = ["json"] }+tiny_http = "0.12" [profile.release] opt-level = "z"
README.md+123−555@@ -1,624 +1,192 @@ # adom-ds2sf -**Datasheet â symbol + footprint + provenance. Read a chip's PDF, extract its pins and pads, and emit structured JSON the rest of the Adom EDA tools build on.**+**Datasheet → symbol + footprint + provenance JSON.** -adom-ds2sf ("datasheet to symbol & footprint") reads a manufacturer datasheet PDF and extracts the part's electrical interface â pin names, numbers, types, and logical groups (POWER, GROUND, GPIO split by port, DEBUGâ¦) â plus the land pattern when the datasheet provides one, into `<MPN>-symbol.extracted.json` and `<MPN>-footprint.extracted.json` with **per-field provenance**: every pin and every dimension records the datasheet page it came from. It's the source that lets **adom-symbol** auto-generate a clean, balanced, grouped symbol straight from the datasheet â independent of any vendor's CAD draw.+A small Rust CLI that runs downstream of `chip-fetcher`: it reads a chip's datasheet PDF and produces the JSON inputs needed by Adom's `sym_create` MCP plus a footprint metadata file plus a field-level provenance audit trail. Built for both human use and **agent-to-agent calling** by an upstream automation (`chip-fetcher`, batch pipelines). -## What it does+Mirrors the `step2glb` naming convention. -- **`extract`** â datasheet PDF â symbol + footprint + provenance JSON.-- **`inspect`** â summarize an existing extraction in a chip directory.-- **`svg`** â regenerate the authoritative footprint SVG from cached JSON (no re-extraction).+--- -Note: a datasheet without a land-pattern table yields a symbol but no footprint pads â adom-ds2sf reports exactly what it could and couldn't extract, with provenance on every datapoint.+## The dashboard -# Seven worked examples+`adom-ds2sf show` opens a live dashboard over the chip-fetcher library: every chip with its extraction status, and for the selected chip the pins with their groups, the footprint SVG beside the KiCad stdlib baseline, every dimension, and provenance links that open the datasheet PDF at the exact page each fact was read from. Extractions started from the page or the CLI stream their log into the Log tab live. -Each example below was produced by `adom-ds2sf extract` on the manufacturer's own datasheet. For every part you can see the **generated symbol + footprint**, the **full extracted pin list**, the **provenance JSON** (with the datasheet page each datapoint came from), and **the actual datasheet pages** adom-ds2sf read â plus a link to the original PDF. Seven different part types, seven different packages.+ -## 1. DMG2305UX-7 â P-channel MOSFET--*Diodes Incorporated · SOT-23 · [original datasheet PDF](https://www.diodes.com/assets/Datasheets/DMG2305UX.pdf)*--P-channel enhancement-mode MOSFET in SOT-23. -20V Vds, -4.2A continuous Id at Ta=25°C (Vgs=-4.5V), Rds(on) typ 40 mΩ at Vgs=-4.5V / 52 mΩ at Vgs=-2.5V. Low-Vgs(th) load-switch / power-management device.--**Symbol + footprint, generated by adom-ds2sf:**----**Extracted pin list (3 pins):**--| # | Name | Type | Group |-|---|------|------|-------|-| 1 | G | `input` | CONTROL |-| 2 | S | `passive` | POWER |-| 3 | D | `passive` | POWER |--**Provenance** â every field traces back to a datasheet page:--```json-{- "mpn": "DMG2305UX-7",- "datasheet": {- "url": "https://www.diodes.com/assets/Datasheets/DMG2305UX.pdf",- "page_count": 6,- "sha256": "7421a75157a2e700â¦"- },- "symbol.pin_provenance": [- {- "confidence": "high",- "page": 1,- "pin_name": "G",- "pin_number": "1",- "table_caption": "Top View / Internal Schematic (page 1)"- },- {- "confidence": "high",- "page": 1,- "pin_name": "S",- "pin_number": "2",- "table_caption": "Top View / Internal Schematic (page 1)"- }- ],- "footprint.dimension_provenance": [- {- "field": "bodyDimensions.x",- "figure_label": "Package Outline Dimensions â SOT23 (Standard)",- "page": 5,- "value": 2.9- },- {- "field": "bodyDimensions.y",- "figure_label": "Package Outline Dimensions â SOT23 (Standard)",- "page": 5,- "value": 1.3- }- ]-}+```bash+adom-ds2sf --ai-thread "ds2sf" show # start if needed, open the Hydrogen webview tab+adom-ds2sf --ai-thread "ds2sf" show --surface pup # or the AI's Chrome on the desktop (background, maximized)+adom-ds2sf --ai-thread "ds2sf" ui select STM32L431RCT6TR # focus a chip+adom-ds2sf --ai-thread "ds2sf" ui extract STM32L431RCT6TR # run the extractor, watch the Log tab+adom-ds2sf ui log # the same log in the terminal+adom-ds2sf ls # running instances, version drift ``` -**The datasheet pages adom-ds2sf read** â the pin table (p.1) and the package drawing (p.5):------[â Open the original DMG2305UX-7 datasheet](https://www.diodes.com/assets/Datasheets/DMG2305UX.pdf)--## 2. LM358D â Dual op-amp--*Texas Instruments · SOIC-8 · [original datasheet PDF](https://www.ti.com/lit/ds/symlink/lm358.pdf)*--Industry-standard dual general-purpose operational amplifier. Operates from a single 3V to 32V supply (or split ±1.5V to ±16V), with an input common-mode range that includes ground and a typical 1.2 MHz gain-bandwidth product. SOIC-8 (D)â¦--**Symbol + footprint, generated by adom-ds2sf:**+Every state-changing call carries an ai-thread name (`--ai-thread`), one extraction runs at a time, the server registers itself under `~/.adom/instances/adom-ds2sf/` and reaps itself after 24 idle hours (never mid-extraction). Full endpoint table in [SKILL.md](SKILL.md). -+## What it produces -**Extracted pin list (8 pins):**+For a chip directory like `~/project/chip-fetcher/library/<MPN>/`, ds2sf writes four JSONs: -| # | Name | Type | Group |-|---|------|------|-------|-| 1 | OUT1 | `output` | OTHER |-| 2 | IN1- | `input` | OTHER |-| 3 | IN1+ | `input` | OTHER |-| 4 | V- | `power_in` | POWER |-| 5 | IN2+ | `input` | OTHER |-| 6 | IN2- | `input` | OTHER |-| 7 | OUT2 | `output` | OTHER |-| 8 | V+ | `power_in` | POWER |--**Provenance** â every field traces back to a datasheet page:--```json-{- "mpn": "LM358D",- "datasheet": {- "url": "https://www.ti.com/lit/ds/symlink/lm358.pdf",- "page_count": 68,- "sha256": "9c879c3a3e9291c5â¦"- },- "symbol.pin_provenance": [- {- "confidence": "high",- "page": 3,- "pin_name": "OUT1",- "pin_number": "1",- "table_caption": "Table 4-1. Pin Functions"- },- {- "confidence": "high",- "page": 3,- "pin_name": "IN1-",- "pin_number": "2",- "table_caption": "Table 4-1. Pin Functions"- }- ],- "footprint.dimension_provenance": [- {- "field": "bodyDimensions.x",- "figure_label": "D0008A Package Outline â SOIC - 1.75 mm max height",- "page": 59,- "value": 4.91- },- {- "field": "bodyDimensions.y",- "figure_label": "D0008A Package Outline â SOIC - 1.75 mm max height",- "page": 59,- "value": 3.9- }- ]-} ```+<MPN>-symbol.extracted.json # sym_create-shaped (drop-in MCP input)+<MPN>-footprint.extracted.json # padCount, bodyDimensions, leadDimensions,+ # padDescriptions, symbolPinMap, kicad_baseline+<MPN>-extraction.provenance.json # per-pin {page, table_caption}+ # per-dimension {field, value, page, figure_label}+<MPN>-extraction.result.json # agent-to-agent contract: status + exit_code + hints+``` -**The datasheet pages adom-ds2sf read** â the pin table (p.3) and the package drawing (p.60):----+The provenance JSON is the audit trail. Pick any pin or any dimension, follow the `page` field, open the PDF on that page, and confirm the value is visibly there. Same loop for footprint dimensions via `figure_label`. -[â Open the original LM358D datasheet](https://www.ti.com/lit/ds/symlink/lm358.pdf)+--- -## 3. TPS62840YBGR â Buck converter+## How it works -*Texas Instruments · WCSP-6 (YBG, DSBGA) · [original datasheet PDF](https://www.ti.com/lit/ds/symlink/tps62840.pdf)*+Two focused `claude -p` calls per datasheet: -1.8-V to 6.5-V input, 750-mA step-down (buck) converter with ultra-low 60-nA operating quiescent current and 100% duty-cycle mode (120-nA Iq). DCS-Control architecture with 1.8-MHz nominal switching, 16 selectable output voltages via VSETâ¦+1. **Symbol pass** — pinout tables, pin types, Adom logical groups (POWER / I2C / GPIO / etc.), per-pin page provenance.+2. **Footprint pass** — package outline, recommended land pattern, body + lead dimensions, per-dimension page provenance. -**Symbol + footprint, generated by adom-ds2sf:**+Each pass has its own JSON schema and its own validator. Failures retry once with the validation error fed back to the model. Symbol-pass receives the canonical pin-name → pin-number map for the footprint pass so the two outputs cannot disagree with themselves. -+After Claude finishes, ds2sf normalizes the package name against the **service-kicad standard library** (`Package_SO`, `Package_QFP`, `Package_DFN_QFN`, `Package_LQFP`, `Package_TO_SOT_SMD`, `Package_DIP`, …). When the package matches, downstream tools just pull the `.kicad_mod` from there. When it doesn't (custom OLGA packages, modules, optical sensors), `bodyDimensions` + `leadDimensions` carry the datasheet-extracted values and `kicad_baseline` is `null`. -**Extracted pin list (6 pins):**+--- -| # | Name | Type | Group |-|---|------|------|-------|-| A1 | GND | `power_in` | GROUND |-| A2 | VOS | `input` | POWER |-| B1 | VIN | `power_in` | POWER |-| B2 | SW | `power_out` | POWER |-| C1 | EN | `input` | CONTROL |-| C2 | VSET | `input` | CONTROL |+## Sample output -**Provenance** â every field traces back to a datasheet page:+### Top of `<MPN>-symbol.extracted.json` (ADS1115IDGSR) ```json {- "mpn": "TPS62840YBGR",- "datasheet": {- "url": "https://www.ti.com/lit/ds/symlink/tps62840.pdf",- "page_count": 45,- "sha256": "b715ae80beb8f08bâ¦"- },- "symbol.pin_provenance": [- {- "confidence": "high",- "page": 5,- "pin_name": "GND",- "pin_number": "A1",- "table_caption": "Pin Functions"- },- {- "confidence": "high",- "page": 5,- "pin_name": "VOS",- "pin_number": "A2",- "table_caption": "Pin Functions"- }+ "symbolName": "ADS1115",+ "manufacturer": "Texas Instruments",+ "package": "VSSOP-10",+ "description": "Ultra-small 16-bit sigma-delta ADC with PGA, internal reference, …",+ "category": "ic",+ "referencePrefix": "U",+ "datasheetUrl": "https://www.ti.com/lit/ds/symlink/ads1115.pdf",+ "pins": [+ { "number": "8", "name": "VDD", "type": "power_in", "group": "POWER", "description": "…" },+ { "number": "3", "name": "GND", "type": "passive", "group": "GROUND", "description": "…" },+ { "number": "9", "name": "SDA", "type": "bidirectional","group": "I2C", "description": "…" },+ { "number": "4", "name": "AIN0","type": "input", "group": "ADC", "description": "…" } ],- "footprint.dimension_provenance": [- {- "field": "bodyDimensions.x",- "figure_label": "YBG0006 Package Outline â DSBGA - 0.5 mm max height (D: 1.498/1.438 mm, E: 0.998/0.938 mm)",- "page": 39,- "value": 0.968- },- {- "field": "bodyDimensions.y",- "figure_label": "YBG0006 Package Outline â DSBGA - 0.5 mm max height (D: 1.498/1.438 mm, E: 0.998/0.938 mm)",- "page": 39,- "value": 1.468- }- ]+ "groups": [ { "name": "POWER", "description": "…" }, … ] } ``` -**The datasheet pages adom-ds2sf read** â the pin table (p.5) and the package drawing (p.40):------[â Open the original TPS62840YBGR datasheet](https://www.ti.com/lit/ds/symlink/tps62840.pdf)--## 4. INA226AIDGSR â Current / power monitor--*Texas Instruments · VSSOP-10 · [original datasheet PDF](https://www.ti.com/lit/ds/symlink/ina226.pdf)*--36V, 16-bit ultra-precise I²C/SMBus current, voltage, and power monitor with alert. Senses bus voltages from 0V to 36V (high- or low-side), with ±81.92 mV shunt range, 0.1% gain error, 10 µV offset, and configurable averaging. Operatesâ¦--**Symbol + footprint, generated by adom-ds2sf:**----**Extracted pin list (10 pins):**--| # | Name | Type | Group |-|---|------|------|-------|-| 1 | A1 | `input` | CONTROL |-| 2 | A0 | `input` | CONTROL |-| 3 | Alert | `output` | ALERT |-| 4 | SDA | `bidirectional` | I2C |-| 5 | SCL | `input` | I2C |-| 6 | VS | `power_in` | POWER |-| 7 | GND | `power_in` | GROUND |-| 8 | VBUS | `input` | ADC |-| 9 | IN- | `input` | ADC |-| 10 | IN+ | `input` | ADC |--**Provenance** â every field traces back to a datasheet page:+### Top of `<MPN>-extraction.provenance.json` ```json {- "mpn": "INA226AIDGSR", "datasheet": {- "url": "https://www.ti.com/lit/ds/symlink/ina226.pdf",- "page_count": 40,- "sha256": "8652754621863692â¦"+ "path": "/…/ADS1115IDGSR.pdf",+ "url": "https://www.ti.com/lit/ds/symlink/ads1115.pdf",+ "sha256": "65231e81…",+ "source_tier": "mfr",+ "source_host": "ti.com/lit",+ "page_count": 57 },- "symbol.pin_provenance": [- {- "confidence": "high",- "page": 3,- "pin_name": "A1",- "pin_number": "1",- "table_caption": "Table 4-1. Pin Functions"- },- {- "confidence": "high",- "page": 3,- "pin_name": "A0",- "pin_number": "2",- "table_caption": "Table 4-1. Pin Functions"- }- ],- "footprint.dimension_provenance": [- {- "field": "bodyDimensions.x",- "figure_label": "DGS0010A Package Outline â VSSOP - 1.1 mm max height (JEDEC MO-187 BA)",- "page": 37,- "value": 3.0- },- {- "field": "bodyDimensions.y",- "figure_label": "DGS0010A Package Outline â VSSOP - 1.1 mm max height (JEDEC MO-187 BA)",- "page": 37,- "value": 3.0- }- ]+ "symbol": {+ "pin_provenance": [+ { "pin_number": "1", "pin_name": "ADDR",+ "page": 3, "table_caption": "Table 4-1. Pin Functions: RUG, DYN, and DGS Packages",+ "confidence": "high" }+ ]+ },+ "footprint": {+ "dimension_provenance": [+ { "field": "bodyDimensions.x", "value": 3.1,+ "page": 52, "figure_label": "DGS0010A VSSOP - 1.1 mm max height Package Outline",+ "confidence": "high" }+ ]+ } } ``` -**The datasheet pages adom-ds2sf read** â the pin table (p.3) and the package drawing (p.38):----+--- -[â Open the original INA226AIDGSR datasheet](https://www.ti.com/lit/ds/symlink/ina226.pdf)+## Agent-to-agent contract -## 5. MSP430G2553IPW20 â 16-bit MCU+Every invocation writes `<MPN>-extraction.result.json` and exits with one of three codes: -*Texas Instruments · TSSOP-20 · [original datasheet PDF](https://www.ti.com/lit/ds/symlink/msp430g2553.pdf)*+| Exit | `status` | Caller action |+|---|---|---|+| 0 | `ok` | Accept the outputs. `review_required[]` may have informational entries. |+| 2 | `needs_better_pdf` | Try one of `hints[].candidates` and re-call with `--pdf <new>`. |+| 3 | `unrecoverable` | Surface to a human; inspect `.ds2sf-cache/` for the raw Claude responses. | -Ultra-low-power 16-bit RISC microcontroller with 16 KB flash, 512 B SRAM, 10-bit ADC, and integrated UART/SPI/I²C interfaces. Operates at 1.8â3.6 V with active mode consumption of 230 µA/MHz and RTC mode of 0.1 µA.+`hints[]` is a tagged-union list: -**Symbol + footprint, generated by adom-ds2sf:**+- `try_alternate_pdf` — `{reason, candidates: PathBuf[]}`. ds2sf already ranked the chip-dir's other PDFs; pick the first one not yet tried.+- `update_upstream_metadata` — `{file, key, current, extracted}`. e.g. `info.json`'s `package` disagrees with the datasheet; patch it and re-run.+- `use_datasheet_extracted_footprint` — `{package}`. Custom package; downstream footprint authoring should use the captured dimensions.+- `human_review` — `{reason, notes}`. Engineering nuance the schematic designer should see. -+This means an upstream agent like `chip-fetcher` can call ds2sf, walk `hints[].candidates` until it gets `status: ok`, and accept the extraction without human input. -**Extracted pin list (20 pins):**--| # | Name | Type | Group |-|---|------|------|-------|-| 1 | DVCC | `power_in` | POWER |-| 2 | P1.0/TA0CLK/ACLK/A0/CA0 | `bidirectional` | GPIO |-| 3 | P1.1/TA0.0/UCA0RXD/UCA0SOMI/A1/CA1 | `bidirectional` | GPIO |-| 4 | P1.2/TA0.1/UCA0TXD/UCA0SIMO/A2/CA2 | `bidirectional` | GPIO |-| 5 | P1.3/ADC10CLK/A3/VREF-/VREF+/CA3/CAOUT | `bidirectional` | GPIO |-| 6 | P1.4/SMCLK/UCB0STE/UCA0CLK/A4/VREF+/CA4/TCK | `bidirectional` | GPIO |-| 7 | P1.5/TA0.0/UCB0CLK/UCAOSSTE/A5/CA5/TMS | `bidirectional` | GPIO |-| 8 | P2.0/TA1.0 | `bidirectional` | GPIO |-| 9 | P2.1/TA1.1 | `bidirectional` | GPIO |-| 10 | P2.2/TA1.1 | `bidirectional` | GPIO |-| 11 | P2.3/TA1.0 | `bidirectional` | GPIO |-| 12 | P2.4/TA1.2 | `bidirectional` | GPIO |-| 13 | P2.5/TA1.2 | `bidirectional` | GPIO |-| 14 | NC | `unconnected` | NC |-| 15 | P1.6/TA0.1/A6/CA6/UCB0SOMI/UCB0SCL/TDI/TCLK | `bidirectional` | GPIO |-| 16 | P1.7/A7/CA7/CAOUT/UCB0SIMO/UCB0SDA/TDO/TDI | `bidirectional` | GPIO |-| 17 | TEST/SBWTCK | `input` | DEBUG |-| 18 | XOUT/P2.7 | `bidirectional` | TIMING |-| 19 | XIN/P2.6/TA0.1 | `bidirectional` | TIMING |-| 20 | DVSS | `power_in` | GROUND |--**Provenance** â every field traces back to a datasheet page:--```json-{- "mpn": "MSP430G2553IPW20",- "datasheet": {- "url": "https://www.ti.com/lit/ds/symlink/msp430g2553.pdf",- "page_count": 85,- "sha256": "c94b53fef9ba6065â¦"- },- "symbol.pin_provenance": [- {- "confidence": "high",- "page": 3,- "pin_name": "DVCC",- "pin_number": "1",- "table_caption": "Device Pinout, MSP430G2x13 and MSP430G2x53, 20-Pin Devices, TSSOP and PDIP"- },- {- "confidence": "high",- "notes": "Muxed pin with multiple peripheral functions; configure via software.",- "page": 6,- "pin_name": "P1.0/TA0CLK/ACLK/A0/CA0",- "pin_number": "2",- "table_caption": "Table 2. Terminal Functions"- }- ],- "footprint.dimension_provenance": [- {- "field": "bodyDimensions.x",- "figure_label": "PW0020A Package Outline",- "page": 76,- "value": 6.6- },- {- "field": "bodyDimensions.y",- "figure_label": "PW0020A Package Outline",- "page": 76,- "value": 4.5- }- ]+```rust+let mut tried = HashSet::new();+let mut r = run_ds2sf(chip_dir, None);+tried.insert(r.datasheet_used.clone());+while r.status == "needs_better_pdf" {+ let next = r.hints.iter()+ .filter_map(|h| if let Hint::TryAlternatePdf{candidates, ..} = h { Some(candidates) } else { None })+ .flatten().find(|c| !tried.contains(*c));+ let Some(next) = next else { break };+ tried.insert(next.clone());+ r = run_ds2sf(chip_dir, Some(next)); } ``` -**The datasheet pages adom-ds2sf read** â the pin table (p.6) and the package drawing (p.77):------[â Open the original MSP430G2553IPW20 datasheet](https://www.ti.com/lit/ds/symlink/msp430g2553.pdf)--## 6. BMI270 â 6-axis IMU--*Bosch · LGA-14 · [original datasheet PDF](https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bmi270-ds000.pdf)*--Ultra-low-power 16-bit 6-axis IMU (accelerometer + gyroscope) with integrated motion-triggered interrupts, gesture recognition, and advanced power management. Dual-protocol interface supporting I²C and SPI with optional auxiliary sensorâ¦--**Symbol + footprint, generated by adom-ds2sf:**--+Full reason / action enums and the calling recipe are in [SKILL.md](SKILL.md). -**Extracted pin list (14 pins):**+--- -| # | Name | Type | Group |-|---|------|------|-------|-| 1 | SDO | `output` | I2C |-| 2 | ASDx | `bidirectional` | OTHER |-| 3 | ASCx | `input` | OTHER |-| 4 | INT1 | `output` | ALERT |-| 5 | VDDIO | `power_in` | POWER |-| 6 | GNDIO | `passive` | GROUND |-| 7 | GND | `passive` | GROUND |-| 8 | VDD | `power_in` | POWER |-| 9 | INT2 | `output` | ALERT |-| 10 | OCSB | `input` | OTHER |-| 11 | OSDO | `output` | OTHER |-| 12 | CSB | `input` | SPI |-| 13 | SCx | `input` | I2C |-| 14 | SDx | `bidirectional` | I2C |+## CLI -**Provenance** â every field traces back to a datasheet page:--```json-{- "mpn": "BMI270",- "datasheet": {- "url": "https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bmi270-ds000.pdf",- "page_count": 150,- "sha256": "51818aed4619bcccâ¦"- },- "symbol.pin_provenance": [- {- "confidence": "high",- "notes": "SPI MISO (4-wire), I2C address bit-0 select; open-drain output",- "page": 135,- "pin_name": "SDO",- "pin_number": "1",- "table_caption": "Table 22: Pin-out and pin connections"- },- {- "confidence": "high",- "notes": "Secondary interface; muxed for Aux I2C SDA, OIS SDI, or DNC",- "page": 135,- "pin_name": "ASDx",- "pin_number": "2",- "table_caption": "Table 22: Pin-out and pin connections"- }- ],- "footprint.dimension_provenance": [- {- "field": "bodyDimensions.x",- "figure_label": "Section 8.1, Package outline dimensions",- "page": 143,- "value": 3.0- },- {- "field": "bodyDimensions.y",- "figure_label": "Section 8.1, Package outline dimensions",- "page": 143,- "value": 2.5- }- ]-} ```--**The datasheet pages adom-ds2sf read** â the pin table (p.135) and the package drawing (p.145):------[â Open the original BMI270 datasheet](https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bmi270-ds000.pdf)--## 7. ESP32-S3-WROOM-1-N4 â Wi-Fi + BLE module--*Espressif Systems · SMD-41 (18 x 25.5 x 3.1 mm castellated module, PCB antenna) · [original datasheet PDF](https://www.espressif.com/sites/default/files/documentation/esp32-s3-wroom-1_wroom-1u_datasheet_en.pdf)*--ESP32-S3-WROOM-1-N4 is a Wi-Fi (802.11 b/g/n) and Bluetooth LE 5 module built around the ESP32-S3 SoC (dual-core Xtensa LX7 @ 240 MHz, vector instructions for ML). The -N4 variant integrates 4 MB SPI flash and no PSRAM. Module exposes upâ¦--**Symbol + footprint, generated by adom-ds2sf:**----**Extracted pin list (41 pins):**--| # | Name | Type | Group |-|---|------|------|-------|-| 1 | GND | `power_in` | GROUND |-| 2 | 3V3 | `power_in` | POWER |-| 3 | EN | `input` | CONTROL |-| 4 | IO4 | `bidirectional` | GPIO |-| 5 | IO5 | `bidirectional` | GPIO |-| 6 | IO6 | `bidirectional` | GPIO |-| 7 | IO7 | `bidirectional` | GPIO |-| 8 | IO15 | `bidirectional` | GPIO |-| 9 | IO16 | `bidirectional` | GPIO |-| 10 | IO17 | `bidirectional` | GPIO |-| 11 | IO18 | `bidirectional` | GPIO |-| 12 | IO8 | `bidirectional` | GPIO |-| 13 | IO19 | `bidirectional` | USB |-| 14 | IO20 | `bidirectional` | USB |-| 15 | IO3 | `bidirectional` | GPIO |-| 16 | IO46 | `bidirectional` | GPIO |-| 17 | IO9 | `bidirectional` | GPIO |-| 18 | IO10 | `bidirectional` | GPIO |-| 19 | IO11 | `bidirectional` | GPIO |-| 20 | IO12 | `bidirectional` | GPIO |-| 21 | IO13 | `bidirectional` | GPIO |-| 22 | IO14 | `bidirectional` | GPIO |-| 23 | IO21 | `bidirectional` | GPIO |-| 24 | IO47 | `bidirectional` | GPIO |-| 25 | IO48 | `bidirectional` | GPIO |-| 26 | IO45 | `bidirectional` | GPIO |-| 27 | IO0 | `bidirectional` | GPIO |-| 28 | IO35 | `bidirectional` | GPIO |-| 29 | IO36 | `bidirectional` | GPIO |-| 30 | IO37 | `bidirectional` | GPIO |-| 31 | IO38 | `bidirectional` | GPIO |-| 32 | IO39 | `bidirectional` | DEBUG |-| 33 | IO40 | `bidirectional` | DEBUG |-| 34 | IO41 | `bidirectional` | DEBUG |-| 35 | IO42 | `bidirectional` | DEBUG |-| 36 | RXD0 | `bidirectional` | UART |-| 37 | TXD0 | `bidirectional` | UART |-| 38 | IO2 | `bidirectional` | GPIO |-| 39 | IO1 | `bidirectional` | GPIO |-| 40 | GND | `power_in` | GROUND |-| 41 | EPAD | `power_in` | GROUND |--**Provenance** â every field traces back to a datasheet page:--```json-{- "mpn": "ESP32-S3-WROOM-1-N4",- "datasheet": {- "url": "https://www.espressif.com/sites/default/files/documentation/esp32-s3-wroom-1_wroom-1u_datasheet_en.pdf",- "page_count": 87,- "sha256": "2d5a7cb7fd559d8dâ¦"- },- "symbol.pin_provenance": [- {- "confidence": "high",- "page": 11,- "pin_name": "GND",- "pin_number": "1",- "table_caption": "Table 3-1. Pin Definitions"- },- {- "confidence": "high",- "page": 11,- "pin_name": "3V3",- "pin_number": "2",- "table_caption": "Table 3-1. Pin Definitions"- }- ],- "footprint.dimension_provenance": [- {- "field": "bodyDimensions.x",- "figure_label": "Figure 10-1. ESP32-S3-WROOM-1 Physical Dimensions",- "page": 42,- "value": 18.0- },- {- "field": "bodyDimensions.y",- "figure_label": "Figure 10-1. ESP32-S3-WROOM-1 Physical Dimensions",- "page": 42,- "value": 25.5- }- ]-}+ds2sf extract <CHIP-DIR> # read PDF, emit symbol + footprint + provenance + result JSONs+ds2sf normalize <PACKAGE> # resolve a package string against service-kicad stdlib (debug)+ds2sf inspect <CHIP-DIR> # print summary of an existing extraction+ds2sf health # probe `claude` CLI + service-kicad reachability+ds2sf install # drop SKILL.md to ~/.claude/skills/ds2sf/ ``` -**The datasheet pages adom-ds2sf read** â the pin table (p.11) and the package drawing (p.45):--+`extract` flags: `--pdf`, `--mpn`, `--manufacturer`, `--datasheet-url`, `--source-tier`, `--out-dir`, `--model` (default `claude-opus-4-7`), `--force`, `--symbol-only`, `--footprint-only`, `--json-only`. -+--- -[â Open the original ESP32-S3-WROOM-1-N4 datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s3-wroom-1_wroom-1u_datasheet_en.pdf)+## Validated chips (initial release) -# Open source â check it out, vibe-code it, send it back+| MPN | Package | Stdlib | Pins | Note |+|---|---|---|---|---|+| ADS1115IDGSR | VSSOP-10 | ✅ `Package_SO:MSOP-10_3x3mm_P0.5mm` | 10 | clean |+| DRV8316RRGFR | VQFN-40 (7×5) | ❌ custom | 40 | caught chip-fetcher's info.json lying about package size |+| VL53L8CX | OLGA-16 | ❌ custom | 17 | all 5 muxed pins flagged, thermal pad called out |+| ESP32-S3-WROOM-1-N4 | SMD module | ❌ custom | 41 | castellated pads, boot-strapping pins, PSRAM variant conflicts | -adom-ds2sf is MIT and **fully open**. The complete Rust source is in this page's **Files** tab.+Failure-path also verified: feeding the SoC datasheet to a module product correctly returned `status: needs_better_pdf` with five ranked candidate PDFs in `hints[]`. -1. **Build it.** `cargo build --release` drops a standalone binary.-2. **Point your install at your checkout.** `adompkg link john/adom-ds2sf ./adom-ds2sf`.-3. **Vibe-code a change.** Open it in Claude Code â a new provenance field, a different grouping heuristic, another datasheet quirk to handle.-4. **Send it back.** Open a **pull request** on this page, or start a discussion thread.+--- -## Part of the Adom EDA family--adom-ds2sf is the extractor; its results are *viewed and used* through **adom-symbol** / **adom-footprint** (it has no viewer of its own). It feeds **adom-chip-fetcher**'s source carat as the "adom-ds2sf · datasheet" source.--## Run it+## Build ```bash-adom-ds2sf extract <chip-dir> # datasheet PDF â symbol + footprint + provenance JSON-adom-ds2sf inspect <chip-dir> # summarize an extraction+cargo build --release+sudo cp target/release/ds2sf /usr/local/bin/+ds2sf install ```-MIT, contributions welcome.--## Contributing & forking — open source under the Adom org--**adom-ds2sf** is **open source** under the **adom** org on the [Adom Wiki](https://wiki.adom.inc/adom/adom-ds2sf). The full source lives in this page's repo — open the **Files** tab, or `adompkg install adom/adom-ds2sf` and edit the package. Third-party developers are welcome to modify it and contribute back.--**Modify it**-- Get the source from the Files tab (or `adompkg install adom/adom-ds2sf`), make your changes, and rebuild. -**Contribute back to Adom — two paths**-1. **Pull request (preferred).** The wiki runs a PR-per-page flow: propose your change on this page and the maintainer reviews + merges it — no fork needed.-2. **Fork + breadcrumb.** Prefer your own fork or add-on? Publish it as your own wiki page, then drop a **breadcrumb on _this_ page** pointing at your fork so it's discoverable:- - Read existing trails: `GET https://wiki.adom.inc/api/v1/pages/adom-ds2sf/breadcrumbs`- - Attach a breadcrumb from your fork's page targeting this anchor (a short label + your slug).+Or just `./build.sh`. - The breadcrumb leaves a **linked path back here**, so **Adom's AI can auto-discover your fork** and surface it to users — the trail is followable both ways. Your fork stays yours; the original stays discoverable.+--- -## License+## Cost & latency (Haiku 4.5 baseline) -**MIT** — © 2026 Adom Industries Inc. Open source; see [LICENSE](LICENSE). Modify, fork, and redistribute freely.+- ~$0.20–0.30 per chip end-to-end+- ~2–3 min wall time per chip+- Anthropic prompt cache keeps the PDF warm across the symbol→footprint calls
SKILL.md+88−35@@ -1,37 +1,49 @@ --- name: adom-ds2sf-description: Datasheet â symbol + footprint + provenance JSON. Reads a chip's datasheet PDF and emits sym_create-shaped symbol JSON, footprint metadata, a field-level provenance audit trail, and an agent-to-agent result.json with stable exit codes for programmatic re-search-and-retry. Trigger words â adom-ds2sf, datasheet to symbol, datasheet to footprint, extract symbol from datasheet, extract footprint from datasheet, datasheet pinout extract, sym extracted json, fp extracted json, datasheet sym fp, chip pin grouping, pin provenance, footprint provenance, sym_create input from datasheet, adom-ds2sf result.json, datasheet extractor agent contract.+description: Datasheet to symbol + footprint + provenance JSON, plus a live AI-drivable dashboard over the chip-fetcher library. Reads a chip's datasheet PDF and emits sym_create-shaped symbol JSON, footprint metadata, a field-level provenance audit trail, and an agent-to-agent result.json with stable exit codes for programmatic re-search-and-retry. Trigger words: adom-ds2sf, ds2sf, ds2sf dashboard, show me ds2sf, run ds2sf on, extract the datasheet, datasheet to symbol, datasheet to footprint, extract symbol from datasheet, extract footprint from datasheet, datasheet pinout extract, sym extracted json, fp extracted json, datasheet sym fp, chip pin grouping, pin provenance, footprint provenance, sym_create input from datasheet, ds2sf result.json, datasheet extractor agent contract. --- -# adom-ds2sf â datasheet â symbol + footprint + provenance+# adom-ds2sf: datasheet to symbol + footprint + provenance -Pipeline: read a adom-chip-fetcher chip directory, send the datasheet PDF to Claude in two focused passes (symbol â footprint), normalize the package against the service-kicad standard library, and emit four JSON files alongside the existing adom-chip-fetcher artifacts.+Pipeline: read a chip-fetcher chip directory, send the datasheet PDF to Claude in two focused passes (symbol → footprint), normalize the package against the service-kicad standard library, and emit four JSON files alongside the existing chip-fetcher artifacts. -## â Always Opus, never Haiku+## ⚠ Always Opus, never Haiku Production runs MUST use the default `--model claude-opus-4-7`. EEs rely on this output to wire schematics; Haiku's chip-data misreads are not acceptable in that pipeline. Concur (the cross-source consensus check) does catch most Haiku errors via 4-source consensus, but the right answer is to not produce them in the first place. Override the model only for development experiments where a follow-up Opus pass is acceptable. ## When to use -- After `adom-chip-fetcher` lands a chip into `~/project/adom-chip-fetcher/library/<MPN>/`.-- When you want an Adom-grouped symbol (POWER / I2C / GPIO / etc.) â the UL bundle's `.kicad_sym` is flat and ungrouped.+- After `chip-fetcher` lands a chip into `~/project/chip-fetcher/library/<MPN>/`.+- When you want an Adom-grouped symbol (POWER / I2C / GPIO / etc.) — the UL bundle's `.kicad_sym` is flat and ungrouped. - When you need a downstream-ready `sym_create` input JSON. - When you need page-level provenance to deeplink the Adom user back to the datasheet PDF page each fact came from. +## Displaying this app (REQUIRED, read before showing anything)++To SHOW this app, use `adom-ds2sf --ai-thread "<name>" show` (it starts the dashboard if needed and opens the proper surface itself). For manual display, FIRST load the `webview` skill (adom-workspace-control) and follow it.+- **NEVER open this app in VS Code's "Simple Browser"**: not a webview in the Adom ecosystem: no live channel, no console read-back, no AI drivability. Using it is a bug.+- Surfaces: **wv** (Hydrogen webview panel, the default), **pup** (`show --surface pup`, the AI's own Chrome on the desktop, opened in the background and maximized once), the user's **real signed-in browser** (`--surface nb`), and **hbw** (Hydrogen's standalone browser window, Hydrogen only). Simple Browser is NEVER one of them.+- The default surface is a user preference stored in Settings (`default_surface`); do not re-decide it on every call.+- With more than one desktop connected, pass `--target <BoxName>` (`adom-bridge targets` lists them).++## The ai-thread name (every state-changing call)++Every verb that talks to the dashboard takes the global `--ai-thread "<name>"` flag, exactly like adom-bridge. Pick a short name a human recognizes for THIS conversation ("ds2sf", "stm32 board review") and reuse it on every Adom tool call. Calls without it are refused with `caller_identity_required`; read-only verbs (`ls`, `ui state`, `ui log`, `ui console`, `settings get`, `health`) stay open.+ ## Module products: pass `--pdf` explicitly -For **module products** (ESP32-WROOM, NORA, ATWINC, SARA-R5, etc.), adom-chip-fetcher's auto-named `<MPN>.pdf` may be the internal SoC datasheet â which has the SoC's pinout, not the module's external castellated-pad pinout. The extractor will refuse to hallucinate (writes a result.json with `status: "needs_better_pdf"` and a list of candidate PDFs already on disk).+For **module products** (ESP32-WROOM, NORA, ATWINC, SARA-R5, etc.), chip-fetcher's auto-named `<MPN>.pdf` may be the internal SoC datasheet — which has the SoC's pinout, not the module's external castellated-pad pinout. The extractor will refuse to hallucinate (writes a result.json with `status: "needs_better_pdf"` and a list of candidate PDFs already on disk). Look for the module-specific PDF in the chip-dir (`<MPN>-original.pdf`, `<MPN>-datasheethardware-guideline.pdf`, etc.) and pass it via `--pdf`: ```bash-adom-ds2sf extract /home/adom/project/adom-chip-fetcher/library/ESP32-S3-WROOM-1-N4 \- --pdf /home/adom/project/adom-chip-fetcher/library/ESP32-S3-WROOM-1-N4/ESP32-S3-WROOM-1-N4-original.pdf+ds2sf extract /home/adom/project/chip-fetcher/library/ESP32-S3-WROOM-1-N4 \+ --pdf /home/adom/project/chip-fetcher/library/ESP32-S3-WROOM-1-N4/ESP32-S3-WROOM-1-N4-original.pdf ``` ## Commands -### `adom-ds2sf extract <CHIP-DIR>`+### `ds2sf extract <CHIP-DIR>` Run the full pipeline against a chip directory. @@ -43,7 +55,7 @@ Run the full pipeline against a chip directory. | `--datasheet-url <url>` | Override the datasheet URL. | | `--source-tier <mfr\|snapmagic\|mouser\|digikey\|arrow\|cse\|lcsc\|unknown>` | Override the upstream provenance tier. | | `--out-dir <path>` | Output directory (default: chip-dir). |-| `--model <id>` | Claude model (default `claude-opus-4-7`). **Always use Opus for production EE work.** Haiku produces frequent misreads on chip data â pin-order swaps (DMG2305 GDSâGSD), pad undercounts (ICE40UP5K saw 24 of 48), package-variant confusion (WSL2010 â WSL2512), and JTAG-letter typos (MTDO â MTD0). Concur catches these via cross-source consensus, but the right answer is to never let them happen: use Opus. Only override to a cheaper model for development testing where a follow-up Opus run is acceptable. |+| `--model <id>` | Claude model (default `claude-opus-4-7`). **Always use Opus for production EE work.** Haiku produces frequent misreads on chip data — pin-order swaps (DMG2305 GDS↔GSD), pad undercounts (ICE40UP5K saw 24 of 48), package-variant confusion (WSL2010 → WSL2512), and JTAG-letter typos (MTDO → MTD0). Concur catches these via cross-source consensus, but the right answer is to never let them happen: use Opus. Only override to a cheaper model for development testing where a follow-up Opus run is acceptable. | | `--force` | Bypass cache, re-run Claude. | | `--symbol-only` | Skip footprint pass. | | `--footprint-only` | Re-run only footprint pass against cached symbol. |@@ -51,29 +63,70 @@ Run the full pipeline against a chip directory. **Example:** ```bash-adom-ds2sf extract /home/adom/project/adom-chip-fetcher/library/ADS1115IDGSR+ds2sf extract /home/adom/project/chip-fetcher/library/ADS1115IDGSR ``` -### `adom-ds2sf normalize <PACKAGE>`+### `ds2sf normalize <PACKAGE>` Resolve a package string against service-kicad's standard library (debug aid). ```bash-adom-ds2sf normalize "VSSOP-10"-# OK: VSSOP-10 â Package_SO:MSOP-10_3x3mm_P0.5mm (service-kicad stdlib)+ds2sf normalize "VSSOP-10"+# OK: VSSOP-10 → Package_SO:MSOP-10_3x3mm_P0.5mm (service-kicad stdlib) ``` -### `adom-ds2sf inspect <CHIP-DIR>`+### `ds2sf inspect <CHIP-DIR>` Print a summary of an existing extraction without re-running anything. -### `adom-ds2sf health`+### `ds2sf health` Probe `claude` CLI + service-kicad reachability. -### `adom-ds2sf install`+### `ds2sf install`++Drop this `SKILL.md` into `~/.claude/skills/ds2sf/`.++## The dashboard (v0.9)++`adom-ds2sf` ships a live dashboard over the chip-fetcher library: every chip with its extraction status (green extracted, yellow needs a better PDF, red failed, blue has a datasheet but not run yet, grey no datasheet), and for the selected chip the pins with their groups, the footprint SVG next to the KiCad stdlib baseline, every dimension, and the provenance page links that open the datasheet PDF at the page each fact was read from. Extractions started from the dashboard (or from the CLI) stream their log into the Log tab live.++```bash+adom-ds2sf --ai-thread "ds2sf" show # start if needed + open the wv tab+adom-ds2sf --ai-thread "ds2sf" show --surface pup # or the AI's Chrome on the desktop+adom-ds2sf ls # running instances, version drift+adom-ds2sf --ai-thread "ds2sf" ui select STM32L431RCT6TR # focus a chip+adom-ds2sf --ai-thread "ds2sf" ui extract STM32L431RCT6TR # run the extractor, log streams to the page+adom-ds2sf --ai-thread "ds2sf" ui extract BMI270 --force --pdf BMI270-datasheet.pdf+adom-ds2sf --ai-thread "ds2sf" ui tab provenance # switch the detail tab+adom-ds2sf --ai-thread "ds2sf" ui toast "checking pin 12" --kind info+adom-ds2sf --ai-thread "ds2sf" ui click "#btn-pdf" # AI cursor glides there, then clicks+adom-ds2sf ui log # the extraction log+adom-ds2sf ui state # full state JSON (chips, job, settings)+adom-ds2sf --ai-thread "ds2sf" settings set default_model claude-opus-4-7+adom-ds2sf --ai-thread "ds2sf" shutdown --reason "user said close the ds2sf dashboard"+```++Server contract (port 8791 by default, `--port auto` for a free one):++| Endpoint | What |+|---|---|+| `GET /state` | chips with status, current chip, running job (stage + elapsed), settings, proxy URL |+| `GET /events` | SSE live channel (`state`, `log`, `toast`, `chip`, `click`, `reveal`, `cursor`, `tab`, `reload`) |+| `GET /api/chip/<MPN>` | result + symbol + footprint + provenance + validation + info JSON in one call |+| `GET /api/chip/<MPN>/pdf?name=<file>` | the datasheet, `#page=N` deeplinks from the provenance tables |+| `GET /api/chip/<MPN>/svg/ds2sf|pcbnew|symbol` | the rendered SVGs |+| `POST /extract` | `{mpn, force?, pdf?, model?, symbolOnly?, footprintOnly?, aiThread}`; one job at a time, `job_running` otherwise |+| `POST /select`, `POST /ui/toast`, `POST /ui/click`, `POST /ui/reveal`, `POST /ui/tab` | drive the page |+| `GET/POST /settings` | `default_model`, `default_surface`, `open_in_background`, `ttl_hours`, `dev_mode`, `library_root` |+| `GET /console`, `GET /log` | the page's console ring buffer; the extraction log |+| `POST /shutdown` | reason-gated (>= 10 chars) |++Lifecycle: the server registers itself under `~/.adom/instances/adom-ds2sf/<thread>.json`, reaps itself after 24 idle hours (never mid-extraction; `--keep-alive` / `--ttl <h>` override; `ttl_hours` in Settings), snapshots its state per thread, and `serve` reuses a live same-version instance instead of spawning a second. `serve --print-url` is the Hydrogen Dock Bar contract: prints `http://127.0.0.1:<port>/`, self-backgrounds, exits 0.++Cloud-proxy note: `https://<slug>.adom.cloud/proxy/<port>/` buffers SSE, so the page also polls `GET /state` every 2s and stays correct either way. Direct (Hydrogen/localhost) connections get the live stream. -Drop this `SKILL.md` into `~/.claude/skills/adom-ds2sf/`.+When a chip has **no datasheet PDF** the dashboard says so and `POST /extract` refuses with `no_datasheet` and the exact chip-fetcher command to fetch one. If the container cannot reach the manufacturer (bot walls), fetch it through the desktop: open a pup tab on the manufacturer's site and `pup_eval` a same-origin `fetch()` of the PDF URL to base64, then write it to `<chip-dir>/<MPN>.pdf` (this is how the STM32L431RCT6TR datasheet landed on 2026-08-30). ## Outputs @@ -86,19 +139,19 @@ Drop this `SKILL.md` into `~/.claude/skills/adom-ds2sf/`. .ds2sf-cache/ # raw Claude responses for re-emit / debug ``` -The provenance JSON is the audit trail. Open the file, pick a pin, follow `pin_provenance[i].page` â open that page in the datasheet PDF â confirm the pin name + description are visibly there. Same for footprint dimensions via `dimension_provenance[i].page` + `figure_label`.+The provenance JSON is the audit trail. Open the file, pick a pin, follow `pin_provenance[i].page` → open that page in the datasheet PDF → confirm the pin name + description are visibly there. Same for footprint dimensions via `dimension_provenance[i].page` + `figure_label`. --- ## Agent-to-agent contract -adom-ds2sf is built so an upstream agent (adom-chip-fetcher, automation) can call it programmatically, read the result, and decide what to do next without human input.+ds2sf is built so an upstream agent (chip-fetcher, automation) can call it programmatically, read the result, and decide what to do next without human input. ### Exit codes | Exit | `status` | Meaning | Caller action | |---|---|---|---|-| 0 | `ok` | Extraction completed. `review_required[]` may still have entries â they're informational, not blocking. | Accept the outputs. |+| 0 | `ok` | Extraction completed. `review_required[]` may still have entries — they're informational, not blocking. | Accept the outputs. | | 2 | `needs_better_pdf` | Extractor refused because the supplied PDF doesn't have the right data (typically: SoC datasheet was passed for a module, or wrong package variant). | Try one of `hints[].candidates` and re-call with `--pdf <new>`. | | 3 | `unrecoverable` | Hard failure (Claude returned malformed output twice; pre-flight failure; emit error). | Surface to a human; inspect `.ds2sf-cache/`. | @@ -114,9 +167,9 @@ Always written. Stable schema (`schema_version: "1"`): "mpn": "ADS1115IDGSR", "manufacturer": "TI", "datasheet_used": "/home/.../ADS1115IDGSR.pdf",- "datasheet_sha256": "65231e81â¦",- "summary": "ADS1115IDGSR â 10 pins, package VSSOP-10 â¦",- "review_required": [ ⦠merged from symbol + footprint passes ⦠],+ "datasheet_sha256": "65231e81…",+ "summary": "ADS1115IDGSR — 10 pins, package VSSOP-10 …",+ "review_required": [ … merged from symbol + footprint passes … ], "hints": [ { "action": "try_alternate_pdf", "reason": "module_external_pinout_missing",@@ -124,13 +177,13 @@ Always written. Stable schema (`schema_version: "1"`): { "action": "update_upstream_metadata", "file": "/path/to/info.json", "key": "package",- "current": "VQFN-32 (5Ã5Ã0.9 mm)",- "extracted": "VQFN-40 (7Ã5Ã0.9 mm)" },+ "current": "VQFN-32 (5×5×0.9 mm)",+ "extracted": "VQFN-40 (7×5×0.9 mm)" }, { "action": "use_datasheet_extracted_footprint", "package": "Optical LGA-16" }, { "action": "human_review", "reason": "muxed_pin_protocol_select",- "notes": "â¦" }+ "notes": "…" } ], "outputs": { "symbol_json": "/path/to/X-symbol.extracted.json | null",@@ -146,9 +199,9 @@ Always written. Stable schema (`schema_version: "1"`): | Reason | When | Caller action | |---|---|---|-| `module_external_pinout_missing` | Empty pins[] returned because the supplied PDF was a SoC datasheet for a module product. | `hints[].try_alternate_pdf` â re-call with one of the candidate PDFs. |-| `package_mismatch_in_hint` | info.json's `package` disagrees with the datasheet's actual package. | `hints[].update_upstream_metadata` â patch info.json's `package` to match `extracted`, then accept. |-| `non_standard_package_no_kicad_baseline` | The package isn't in service-kicad's stdlib (custom OLGA, modules, optical). | `hints[].use_datasheet_extracted_footprint` â use `<MPN>-footprint.extracted.json`'s `bodyDimensions` + `leadDimensions` directly. |+| `module_external_pinout_missing` | Empty pins[] returned because the supplied PDF was a SoC datasheet for a module product. | `hints[].try_alternate_pdf` → re-call with one of the candidate PDFs. |+| `package_mismatch_in_hint` | info.json's `package` disagrees with the datasheet's actual package. | `hints[].update_upstream_metadata` → patch info.json's `package` to match `extracted`, then accept. |+| `non_standard_package_no_kicad_baseline` | The package isn't in service-kicad's stdlib (custom OLGA, modules, optical). | `hints[].use_datasheet_extracted_footprint` → use `<MPN>-footprint.extracted.json`'s `bodyDimensions` + `leadDimensions` directly. | | `muxed_pin_protocol_select` | Some pins (e.g. SDA/MOSI) are protocol-multiplexed. | Informational. Pin descriptions in provenance explain how. | | `pad_dimensions_from_example_layout` | Footprint dims came from an "Example Board Layout" rather than a formal recommended land pattern. | Informational; recommend cross-check vs IPC-7351. | | `boot_strapping_pins`, `vdd_spi_voltage_dependency`, `psram_variant_conflict`, `non_uniform_pad_pitch`, `power_supply_configuration`, `thermal_management`, `i2c_address_multidevice` | Engineering nuances Claude flagged for human review. | Surface to schematic designer. |@@ -157,10 +210,10 @@ Always written. Stable schema (`schema_version: "1"`): ### Agent calling recipe ```rust-// (Pseudo-Rust for adom-chip-fetcher's caller side.)+// (Pseudo-Rust for chip-fetcher's caller side.) fn run_ds2sf(chip_dir: &Path, pdf_override: Option<&Path>) -> ResultDoc {- let mut cmd = Command::new("adom-ds2sf");+ let mut cmd = Command::new("ds2sf"); cmd.arg("extract").arg(chip_dir).arg("--force").arg("--json-only"); if let Some(p) = pdf_override { cmd.arg("--pdf").arg(p); } let _ = cmd.status(); // exit code mirrored in result.json@@ -179,7 +232,7 @@ while r.status == "needs_better_pdf" { .flatten() .find(|c| !tried.contains(*c)); let Some(next) = next else {- // Out of candidates â escalate to human.+ // Out of candidates — escalate to human. log_for_review(&r); break; }; tried.insert(next.clone());@@ -203,4 +256,4 @@ match r.status.as_str() { ### Caching behavior under cache-hit -If `<MPN>-extraction.provenance.json` already exists and `--force` is not passed, adom-ds2sf skips the Claude calls entirely and exits with the cached result.json's exit code. Re-running is idempotent.+If `<MPN>-extraction.provenance.json` already exists and `--force` is not passed, ds2sf skips the Claude calls entirely and exits with the cached result.json's exit code. Re-running is idempotent.
bin/adom-ds2sf⋯ 1 unchanged line ⋯
build.sh+5−4@@ -1,9 +1,10 @@ #!/usr/bin/env bash-# Build + install ds2sf locally for development.+# Build + install adom-ds2sf locally for development. set -euo pipefail cd "$(dirname "$0")" cargo build --release-sudo cp target/release/ds2sf /usr/local/bin/ds2sf-ds2sf install-echo "OK: ds2sf $(ds2sf --version | awk '{print $2}') installed → /usr/local/bin/ds2sf"+mkdir -p "$HOME/.local/bin"+install -m 0755 target/release/adom-ds2sf "$HOME/.local/bin/adom-ds2sf"+"$HOME/.local/bin/adom-ds2sf" install+echo "OK: adom-ds2sf $("$HOME/.local/bin/adom-ds2sf" --version | awk '{print $2}') installed → $HOME/.local/bin/adom-ds2sf"
dockbar.jsonadded+44@@ -0,0 +1,44 @@+{+ "dock_manifest": "1.2.0",+ "say": [+ "run ds2sf on the STM32L431RCT6TR",+ "show me the ds2sf dashboard",+ "which pins on this chip need review",+ "re-extract the footprint for this chip with opus",+ "open the datasheet page where pin 12 came from"+ ],+ "webview": {+ "title": "DS2SF",+ "favicon": "docs/dock-ds2sf.svg"+ },+ "health": {+ "url": "/api/status",+ "poll_seconds": 15,+ "timeout_ms": 2000+ },+ "launch": {+ "mode": "container_command",+ "console": "show",+ "steps": [+ {+ "label": "Installing or updating DS2SF",+ "run": "sh -c 'PATH=\"$HOME/.local/bin:$PATH\"; if command -v adom-ds2sf >/dev/null 2>&1; then adom-wiki pkg update adom/adom-ds2sf || adom-wiki pkg install adom/adom-ds2sf; else adom-wiki pkg install adom/adom-ds2sf; fi'",+ "timeout_seconds": 300+ },+ {+ "label": "Starting the DS2SF dashboard",+ "run": "sh -c 'PATH=\"$HOME/.local/bin:$PATH\"; exec adom-ds2sf --ai-thread \"dock bar\" serve --print-url'",+ "await": "url",+ "timeout_seconds": 60+ }+ ],+ "on_ready": "navigate_placeholder",+ "ai": {+ "prompt": "The user just opened DS2SF from the dock. Read ~/.claude/skills/adom-ds2sf/SKILL.md, run `adom-ds2sf health`, then ask which chip in the chip-fetcher library they want extracted (or use `adom-ds2sf --ai-thread <name> ui select <MPN>` to focus one). Narrate progress with `adom-ds2sf --ai-thread <name> ui toast`.",+ "thread": "existing",+ "thread_fallback": "new",+ "submit": "staged",+ "typed": false+ }+ }+}
docs/dashboard.pngadded⋯ 1 unchanged line ⋯
docs/dock-ds2sf.svgadded+1@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#e6edf3" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 3.5h9l4 4V13"/><path d="M13 3.5v4h4"/><path d="M7 8.5h3M7 11.5h5"/><rect x="12" y="14" width="8" height="7" rx="1"/><path d="M14 14v-2M18 14v-2M14 21v1.5M18 21v1.5M12 16.5h-2M12 19h-2"/></svg>
package.json+32−4@@ -1,8 +1,8 @@ { "slug": "adom-ds2sf",- "version": "1.0.1",+ "version": "1.1.0", "type": "app",- "description": "Datasheet to symbol + footprint + provenance JSON \u2014 pins and pads, extracted from the PDF.",+ "description": "Datasheet to symbol + footprint + provenance JSON, with a live dashboard: pins, groups, land pattern, and the datasheet page every fact came from.", "dependencies": {}, "tags": [ "eda",@@ -24,5 +24,33 @@ "type": "image", "path": "adom-ds2sf.png" },- "license": "MIT"-}+ "license": "MIT",+ "discovery_triggers": [+ "run ds2sf on this chip",+ "extract the datasheet pins",+ "show me the ds2sf dashboard",+ "datasheet to symbol and footprint",+ "which pins need review",+ "where did this pin come from in the datasheet",+ "extract footprint from datasheet"+ ],+ "discovery_pitch": "Read a chip's manufacturer datasheet with Claude and get its pins, groups, land pattern, and the PDF page every fact came from, in a live dashboard over your chip-fetcher library.",+ "sample_prompts": [+ {+ "label": "Extract a chip",+ "prompt": "run ds2sf on the STM32L431RCT6TR"+ },+ {+ "label": "Open the dashboard",+ "prompt": "show me the ds2sf dashboard"+ },+ {+ "label": "Review flags",+ "prompt": "which pins on this chip did ds2sf flag for review?"+ },+ {+ "label": "Provenance",+ "prompt": "open the datasheet page where pin 12 came from"+ }+ ]+}
page.json+32−3@@ -1,8 +1,8 @@ { "slug": "adom-ds2sf",- "version": "1.0.1",+ "version": "1.1.0", "type": "app",- "description": "Datasheet to symbol + footprint + provenance JSON \u2014 pins and pads, extracted from the PDF.",+ "description": "Datasheet to symbol + footprint + provenance JSON, with a live dashboard: pins, groups, land pattern, and the datasheet page every fact came from.", "dependencies": {}, "tags": [ "eda",@@ -31,5 +31,34 @@ "binary_name": "adom-ds2sf" }, "org": "adom",- "source_visibility": "public"+ "source_visibility": "public",+ "license": "MIT",+ "discovery_triggers": [+ "run ds2sf on this chip",+ "extract the datasheet pins",+ "show me the ds2sf dashboard",+ "datasheet to symbol and footprint",+ "which pins need review",+ "where did this pin come from in the datasheet",+ "extract footprint from datasheet"+ ],+ "discovery_pitch": "Read a chip's manufacturer datasheet with Claude and get its pins, groups, land pattern, and the PDF page every fact came from, in a live dashboard over your chip-fetcher library.",+ "sample_prompts": [+ {+ "label": "Extract a chip",+ "prompt": "run ds2sf on the STM32L431RCT6TR"+ },+ {+ "label": "Open the dashboard",+ "prompt": "show me the ds2sf dashboard"+ },+ {+ "label": "Review flags",+ "prompt": "which pins on this chip did ds2sf flag for review?"+ },+ {+ "label": "Provenance",+ "prompt": "open the datasheet page where pin 12 came from"+ }+ ] }
src/app.htmladded+679@@ -0,0 +1,679 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>DS2SF</title>+<link rel="icon" type="image/svg+xml" href="favicon.svg">+<style>+@font-face{font-family:'Familjen Grotesk';src:url('https://adom.inc/fonts/familjen-grotesk/familjen-grotesk-latin-600-normal.woff2') format('woff2');font-weight:600;font-display:swap}+@font-face{font-family:'Familjen Grotesk';src:url('https://adom.inc/fonts/familjen-grotesk/familjen-grotesk-latin-700-normal.woff2') format('woff2');font-weight:700;font-display:swap}+@font-face{font-family:'Satoshi';src:url('https://adom.inc/fonts/satoshi/satoshi-400-normal.woff2') format('woff2');font-weight:400;font-display:swap}+@font-face{font-family:'Satoshi';src:url('https://adom.inc/fonts/satoshi/satoshi-500-normal.woff2') format('woff2');font-weight:500;font-display:swap}+@font-face{font-family:'Satoshi';src:url('https://adom.inc/fonts/satoshi/satoshi-700-normal.woff2') format('woff2');font-weight:700;font-display:swap}+@font-face{font-family:'JetBrains Mono';src:url('https://cdn.jsdelivr.net/npm/@fontsource/jetbrains-mono@5/files/jetbrains-mono-latin-400-normal.woff2') format('woff2');font-weight:400;font-display:swap}+:root{+ --bg:#0d1117;--surface:#161b22;--elevated:#1c2128;--overlay:#21262d;--border:#30363d;--line:#30363d;+ --text:#e6edf3;--text-body:#c9d1d9;--text-2:#8b949e;--text-3:#484f58;--muted:#8b949e;+ --accent:#00b8b1;--teal:#00b8b1;--accent-hover:#00d4cb;--accent-bright:#00e6dc;--on-accent:#05221f;+ --accent-10:rgba(0,184,177,.10);--accent-20:rgba(0,184,177,.20);--accent-35:rgba(0,184,177,.35);+ --green:#3fb950;--red:#f85149;--yellow:#d29922;--blue:#64abff;--purple:#8c6bf7;+ --green-10:rgba(63,185,80,.12);--red-10:rgba(248,81,73,.12);--yellow-10:rgba(210,153,34,.14);--neutral-10:rgba(139,148,158,.12);--blue-10:rgba(100,171,255,.12);+ --shadow:0 12px 40px rgba(0,0,0,.55);+ --brand-heading:'Familjen Grotesk',sans-serif;--brand-body:'Satoshi',sans-serif;--mono:'JetBrains Mono',ui-monospace,monospace;+ --z-hud:50;--z-toolbar:80;--z-menu:200;--z-toast:400;--z-modal:600;--z-tooltip:99999;+}+*{box-sizing:border-box;margin:0;padding:0}+html,body{height:100%}+body{background:var(--bg);color:var(--text-body);font:13px/1.45 var(--brand-body);-webkit-tap-highlight-color:transparent}+*{scrollbar-width:thin;scrollbar-color:rgba(139,148,158,.38) transparent}+::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-track{background:transparent}+::-webkit-scrollbar-thumb{background:rgba(139,148,158,.32);border-radius:999px;border:2px solid transparent;background-clip:padding-box}+::-webkit-scrollbar-thumb:hover{background:rgba(0,184,177,.55);background-clip:padding-box}+button{font-family:inherit;color:inherit;cursor:pointer;background:none;border:0}+button,select,input,.row,.pill,.tab{transition:background .15s ease,border-color .15s ease,color .15s ease,box-shadow .15s ease,transform .06s ease}+button:active:not(:disabled){transform:translateY(1px) scale(.97)}+:focus-visible{outline:2px solid var(--accent);outline-offset:2px}+input:focus-visible,select:focus-visible{outline:none;border-color:var(--accent)}+button:disabled{opacity:.5;cursor:not-allowed}+a{color:var(--accent)}+code,.mono{font-family:var(--mono);font-size:.92em}+[hidden]{display:none !important}++/* ── app shell ── */+.app{position:fixed;inset:0;display:flex;flex-direction:column;background:var(--bg)}+header{flex:0 0 44px;height:44px;display:flex;align-items:center;gap:12px;padding:0 16px;border-bottom:1px solid var(--line);background:var(--surface);position:relative;z-index:var(--z-toolbar)}+.brand{display:flex;align-items:baseline;gap:8px;flex-shrink:0;white-space:nowrap;cursor:default;position:relative;height:44px}+.brand svg.mark{width:18px;height:18px;align-self:center;color:var(--text);flex-shrink:0}+.brand .app-name{font-family:var(--brand-heading);font-weight:600;font-size:15px;color:var(--text);letter-spacing:-.01em;align-self:center}+.brand .app-sub{font-size:13px;color:var(--text-2);font-weight:400;align-self:center}+.vsep{width:1px;height:22px;background:var(--line);flex-shrink:0}+.subject{display:flex;align-items:center;gap:10px;min-width:0;flex:1}+.subject-name{font-family:var(--brand-heading);font-weight:600;font-size:14px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:36vw}+.subject-name.idle{color:var(--text-3);font-weight:400}+.subject-meta{font-family:var(--mono);font-size:11px;color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.pill{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:500;padding:2px 9px;border-radius:999px;border:1px solid var(--line);background:var(--neutral-10);color:var(--text-2);white-space:nowrap}+.pill .dot,.led{width:8px;height:8px;border-radius:50%;background:var(--text-3);flex-shrink:0}+.pill.ok{color:var(--green);border-color:rgba(63,185,80,.35);background:var(--green-10)}.pill.ok .dot{background:var(--green)}+.pill.needs_better_pdf{color:var(--yellow);border-color:rgba(210,153,34,.35);background:var(--yellow-10)}.pill.needs_better_pdf .dot{background:var(--yellow)}+.pill.unrecoverable{color:var(--red);border-color:rgba(248,81,73,.35);background:var(--red-10)}.pill.unrecoverable .dot{background:var(--red)}+.pill.running{color:var(--accent);border-color:var(--accent-35);background:var(--accent-10)}.pill.running .dot{background:var(--accent);animation:pulse 1.2s infinite}+.pill.not_extracted .dot{background:var(--blue)}.pill.no_datasheet .dot{background:var(--text-3)}+@keyframes pulse{0%,100%{opacity:1;box-shadow:0 0 0 0 var(--accent-35)}50%{opacity:.6;box-shadow:0 0 0 5px transparent}}+.target-chip{font-family:var(--mono);font-size:12px;color:var(--text-2);border:1px solid var(--line);border-radius:999px;padding:3px 10px;display:inline-flex;align-items:center;gap:7px;white-space:nowrap}+.target-chip b{color:var(--text);font-weight:400}+.target-chip .led.live{background:var(--accent);box-shadow:0 0 8px var(--accent)}+.actions{display:flex;align-items:center;gap:6px;margin-left:auto;flex-shrink:0}+.iconbtn{width:28px;height:28px;display:grid;place-items:center;border-radius:7px;color:var(--text-2)}+.iconbtn svg{width:18px;height:18px}+.iconbtn:hover{color:var(--teal);background:var(--accent-10)}+.iconbtn[aria-pressed="true"]{color:var(--teal);background:var(--accent-20);box-shadow:inset 0 0 0 1px var(--accent-35)}+.popover{position:absolute;top:44px;left:0;min-width:300px;background:var(--elevated);border:1px solid var(--line);border-radius:10px;box-shadow:var(--shadow);padding:12px 14px;z-index:var(--z-menu);opacity:0;pointer-events:none;transform:translateY(-4px);transition:opacity .18s,transform .18s;font-size:12px;white-space:normal}+.popover.show{opacity:1;pointer-events:auto;transform:none}+.popover .pt{font-family:var(--brand-heading);font-weight:600;font-size:14px;color:var(--text);margin-bottom:6px}+.popover .pr{display:flex;gap:10px;padding:3px 0}.popover .pr .k{color:var(--text-3);width:72px;flex-shrink:0}.popover .pr .v{color:var(--text-body)}++/* ── body ── */+.body{flex:1;display:flex;min-height:0}+aside{flex:0 0 260px;border-right:1px solid var(--line);background:var(--surface);display:flex;flex-direction:column;min-height:0}+.rail-head{padding:10px 12px 8px;border-bottom:1px solid var(--line);display:flex;flex-direction:column;gap:8px}+.search{width:100%;background:var(--bg);border:1px solid var(--line);border-radius:7px;color:var(--text);padding:6px 9px;font:12.5px var(--brand-body)}+.filters{display:flex;flex-wrap:wrap;gap:4px}+.fpill{font-size:11px;padding:2px 8px;border-radius:999px;border:1px solid var(--line);color:var(--text-2);background:transparent}+.fpill:hover{color:var(--text);border-color:var(--text-2)}+.fpill[aria-pressed="true"]{color:var(--teal);border-color:var(--accent-35);background:var(--accent-10)}+.fpill b{font-weight:500;color:inherit;opacity:.8;margin-left:4px}+.rail-list{flex:1;overflow:auto;padding:4px 0}+.row{display:flex;align-items:center;gap:9px;padding:7px 12px;cursor:pointer;border-left:2px solid transparent}+.row:hover{background:var(--accent-10)}+.row.cur{background:linear-gradient(90deg,var(--accent-20),transparent);border-left-color:var(--accent)}+.row .led.ok{background:var(--green)}.row .led.needs_better_pdf{background:var(--yellow)}.row .led.unrecoverable{background:var(--red)}+.row .led.not_extracted{background:var(--blue)}.row .led.no_datasheet{background:var(--text-3)}.row .led.running{background:var(--accent);animation:pulse 1.2s infinite}+.row .rmain{min-width:0;flex:1}+.row .rmpn{font-family:var(--mono);font-size:12px;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.row .rsub{font-size:11px;color:var(--text-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.row .rbadge{font-size:10px;color:var(--text-3);font-family:var(--mono)}+.rail-foot{padding:7px 12px;border-top:1px solid var(--line);font-size:10.5px;color:var(--text-3);line-height:1.4}+main{flex:1;min-width:0;display:flex;flex-direction:column;overflow:auto}++/* ── detail ── */+.empty{margin:auto;max-width:560px;text-align:center;padding:40px 24px;color:var(--text-2)}+.empty h2{font-family:var(--brand-heading);font-size:20px;color:var(--text);margin-bottom:8px}+.empty .say{margin-top:18px;text-align:left;background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:12px 14px}+.empty .say div{font-family:var(--mono);font-size:12px;color:var(--text-body);padding:4px 0}+.empty .say div::before{content:"say ";color:var(--text-3)}+.hero{display:grid;grid-template-columns:auto 1fr minmax(280px,360px);gap:16px;padding:16px 18px;border-bottom:1px solid var(--line);align-items:start}+.thumb{width:120px;height:120px;border-radius:10px;background:#404b55;border:1px solid var(--line);display:grid;place-items:center;overflow:hidden}+.thumb img{width:100%;height:100%;object-fit:contain}+.thumb .nothumb{color:rgba(230,237,243,.35);font-size:11px}+.title h1{font-family:var(--mono);font-size:22px;font-weight:400;color:var(--text);letter-spacing:-.01em}+.title .mfr{font-size:13px;color:var(--text-2);margin-top:2px}+.title .desc{margin-top:8px;color:var(--text-body);line-height:1.5;max-width:70ch}+.title .kv{display:flex;flex-wrap:wrap;gap:6px 16px;margin-top:10px;font-size:12px}+.title .kv span{color:var(--text-3)}.title .kv b{font-weight:500;color:var(--text-body);font-family:var(--mono)}+.card{background:var(--elevated);border:1px solid var(--line);border-left:3px solid var(--accent-35);border-radius:10px;padding:12px 14px}+.card .ct{font-family:var(--brand-heading);font-weight:600;font-size:13px;color:var(--text);display:flex;align-items:center;gap:10px;margin-bottom:6px}+.card .cd{font-size:12px;color:var(--text-2);line-height:1.5}+.card .kv{display:grid;grid-template-columns:auto 1fr;gap:3px 12px;font-size:12px;margin-top:8px}+.card .kv span{color:var(--text-3)}.card .kv b{font-weight:400;color:var(--text-body);font-family:var(--mono);font-size:11.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.card.status-ok{border-left-color:var(--green)}.card.status-needs_better_pdf{border-left-color:var(--yellow)}.card.status-unrecoverable{border-left-color:var(--red)}.card.status-running{border-left-color:var(--accent)}+.actionbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:10px 18px;border-bottom:1px solid var(--line);background:var(--surface)}+.btn{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;font-weight:500;padding:6px 12px;border-radius:7px;border:1px solid var(--line);background:var(--overlay);color:var(--text)}+.btn:hover:not(:disabled){border-color:var(--accent);color:var(--accent-hover)}+.btn.primary{background:var(--accent);color:var(--on-accent);border-color:var(--accent)}+.btn.primary:hover:not(:disabled){background:var(--accent-hover);color:var(--on-accent)}+.btn svg{width:14px;height:14px}+.actionbar select{background:var(--bg);border:1px solid var(--line);color:var(--text);border-radius:7px;padding:5px 8px;font:12px var(--brand-body)}+.actionbar .spacer{flex:1}+.actionbar .elapsed{font-family:var(--mono);font-size:11px;color:var(--accent)}+.hints{padding:12px 18px;display:flex;flex-direction:column;gap:8px;border-bottom:1px solid var(--line)}+.hint{display:flex;gap:12px;align-items:flex-start;background:var(--yellow-10);border:1px solid rgba(210,153,34,.3);border-radius:8px;padding:9px 12px;font-size:12px}+.hint.human_review{background:var(--blue-10);border-color:rgba(100,171,255,.3)}+.hint .ha{font-family:var(--mono);color:var(--text);font-size:11px;white-space:nowrap}+.hint .hb{flex:1;color:var(--text-body);line-height:1.5}+.hint .hb code{color:var(--text)}+.hint .btn{padding:3px 9px;font-size:11.5px}+.tabs{display:flex;gap:2px;padding:0 18px;border-bottom:1px solid var(--line);background:var(--surface);overflow-x:auto}+.tab{padding:9px 12px;font-size:12.5px;color:var(--text-2);border-bottom:2px solid transparent;white-space:nowrap}+.tab:hover{color:var(--text)}+.tab[aria-selected="true"]{color:var(--teal);border-bottom-color:var(--teal)}+.tab b{font-weight:500;font-size:10.5px;color:var(--text-3);margin-left:5px;font-family:var(--mono)}+.panel{padding:14px 18px;flex:1}+table{width:100%;border-collapse:collapse;font-size:12px}+th{text-align:left;font-weight:500;color:var(--text-3);font-size:11px;letter-spacing:.02em;padding:6px 8px;border-bottom:1px solid var(--line);position:sticky;top:0;background:var(--bg)}+td{padding:6px 8px;border-bottom:1px solid rgba(48,54,61,.5);vertical-align:top;color:var(--text-body)}+tr:hover td{background:var(--accent-10)}+td.mono,td.num{font-family:var(--mono);font-size:11.5px;color:var(--text)}+td.num{text-align:right}+.tag{display:inline-block;font-size:10.5px;padding:1px 7px;border-radius:999px;border:1px solid var(--line);color:var(--text-2);font-family:var(--mono)}+.tag.g-POWER,.tag.g-GROUND{color:var(--yellow);border-color:rgba(210,153,34,.35)}+.tag.g-I2C,.tag.g-SPI,.tag.g-UART,.tag.g-USB,.tag.g-CAN{color:var(--blue);border-color:rgba(100,171,255,.35)}+.tag.g-GPIO{color:var(--green);border-color:rgba(63,185,80,.35)}+.tag.g-DEBUG,.tag.g-TIMING,.tag.g-CONTROL{color:var(--purple);border-color:rgba(140,107,247,.35)}+.pg{font-family:var(--mono);font-size:11px;color:var(--accent);cursor:pointer;text-decoration:none;border-bottom:1px dotted var(--accent-35)}+.pg:hover{color:var(--accent-hover)}+.conf{width:7px;height:7px;border-radius:50%;display:inline-block;margin-right:5px}+.conf.high{background:var(--green)}.conf.medium{background:var(--yellow)}.conf.low{background:var(--red)}+.groups{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:10px}+.group{background:var(--elevated);border:1px solid var(--line);border-radius:10px;padding:11px 13px}+.group .gn{font-family:var(--mono);font-size:13px;color:var(--text);margin-bottom:4px}+.group .gd{font-size:12px;color:var(--text-2);line-height:1.5}+.group .gp{display:flex;flex-wrap:wrap;gap:4px;margin-top:8px}+.group .gp span{font-family:var(--mono);font-size:10.5px;padding:1px 6px;border-radius:5px;background:var(--bg);border:1px solid var(--line);color:var(--text-body)}+.svgs{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px;margin-bottom:14px}+.svgbox{background:radial-gradient(circle at 50% 42%,#121a26 0%,#0d1117 72%);border:1px solid var(--line);border-radius:10px;min-height:280px;display:flex;flex-direction:column;overflow:hidden}+.svgbox .sh{display:flex;justify-content:space-between;align-items:center;padding:7px 11px;border-bottom:1px solid var(--line);font-size:11px;color:var(--text-2)}+.svgbox .sh b{font-weight:500;color:var(--text)}+.svgbox img{flex:1;object-fit:contain;max-height:420px;padding:10px;width:100%}+.svgbox .none{flex:1;display:grid;place-items:center;color:var(--text-3);font-size:12px}+.two{display:grid;grid-template-columns:1fr 1fr;gap:18px}+h3.sec{font-family:var(--brand-heading);font-weight:600;font-size:12.5px;color:var(--text-2);letter-spacing:.02em;margin:10px 0 6px}+pre.log{font-family:var(--mono);font-size:11.5px;line-height:1.5;color:var(--text-body);background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:12px 14px;white-space:pre-wrap;word-break:break-word;max-height:calc(100vh - 260px);overflow:auto}+pre.log .ok{color:var(--green)}pre.log .err{color:var(--red)}pre.log .warn{color:var(--yellow)}pre.log .stage{color:var(--accent)}+pre.json{font-family:var(--mono);font-size:11.5px;line-height:1.45;color:var(--text-body);background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:12px 14px;white-space:pre;overflow:auto;max-height:calc(100vh - 300px)}+.jsonpick{display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap}+.review{display:flex;flex-direction:column;gap:8px}+.rv{background:var(--elevated);border:1px solid var(--line);border-radius:8px;padding:9px 12px;font-size:12px;display:flex;gap:12px}+.rv .rr{font-family:var(--mono);color:var(--yellow);white-space:nowrap;font-size:11px}+.rv .rn{color:var(--text-body);line-height:1.5}++/* ── toasts ── */+.toasts{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:var(--z-toast);display:flex;flex-direction:column-reverse;gap:8px;align-items:center;pointer-events:none}+.toast{pointer-events:auto;display:flex;align-items:center;gap:12px;min-width:280px;max-width:min(520px,calc(100vw - 32px));background:var(--surface);border:1px solid var(--line);border-left:3px solid var(--accent);border-radius:12px;padding:12px 16px;box-shadow:0 18px 50px rgba(0,0,0,.5);font-size:13px;color:var(--text);animation:tin .22s ease}+.toast.success{border-left-color:var(--green)}.toast.error{border-left-color:var(--red)}+.toast .x{margin-left:auto;color:var(--text-3);font-size:16px;line-height:1;padding:0 2px}.toast .x:hover{color:var(--text)}+@keyframes tin{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}++/* ── tooltip + AI cursor ── */+.tt{position:fixed;z-index:var(--z-tooltip);background:var(--elevated);border:1px solid var(--line);color:var(--text-body);font-size:12px;line-height:1.45;padding:7px 10px;border-radius:8px;max-width:300px;box-shadow:var(--shadow);opacity:0;transform:translateY(4px);transition:opacity .18s ease,transform .18s ease;pointer-events:none;text-transform:none}+.tt.show{opacity:1;transform:none}+.aicur{position:fixed;z-index:var(--z-tooltip);width:22px;height:22px;pointer-events:none;opacity:0;transition:left .3s ease,top .3s ease,opacity .2s}+.aicur.show{opacity:1}+.aicur svg{width:22px;height:22px;filter:drop-shadow(0 2px 4px rgba(0,0,0,.6))}+.aicur .lbl{position:absolute;left:22px;top:18px;white-space:nowrap;font-size:11px;background:var(--accent);color:var(--on-accent);padding:2px 7px;border-radius:5px;font-weight:500}++/* ── settings modal ── */+dialog{border:0;background:transparent;padding:0;max-width:none;max-height:none}+dialog::backdrop{background:rgba(0,0,0,.25)}+.modal{width:min(94vw,600px);max-height:88vh;overflow:auto;background:var(--surface);border:1px solid var(--line);border-radius:14px;box-shadow:var(--shadow);padding:18px 20px 14px;color:var(--text-body)}+.modal .mh{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}+.modal .mh h2{font-family:var(--brand-heading);font-size:16px;font-weight:600;color:var(--text)}+.scard{background:var(--elevated);border:1px solid var(--line);border-left:3px solid var(--accent-35);border-radius:10px;padding:.9rem 1.1rem 1rem;margin-bottom:1rem}+.scard .st{font-size:13px;font-weight:600;color:var(--text);display:flex;align-items:center;gap:10px}+.scard .ss{font-size:11px;color:var(--text-2);font-weight:400}.scard .ss.ok{color:var(--green)}+.scard .sd{font-size:12px;line-height:1.55;color:var(--text-2);margin-top:4px}+.scard .sd code{font-size:11px;background:rgba(110,118,129,.2);padding:1px 4px;border-radius:4px}+.srow{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:9px 0;border-top:1px solid var(--line);margin-top:8px}+.srow .sl{font-size:12.5px;color:var(--text)}.srow .sl em{font-style:normal;color:#8fd3d4}+.srow .sdef{font-size:10.5px;color:var(--text-3);margin-top:2px}+.srow select,.srow input{background:var(--bg);border:1px solid var(--line);color:var(--text);border-radius:7px;padding:5px 8px;font:12px var(--brand-body);min-width:150px}+.toggle{width:40px;height:22px;border-radius:999px;background:var(--overlay);border:1px solid var(--line);position:relative;flex-shrink:0}+.toggle::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--text-2);transition:left .15s,background .15s}+.toggle[aria-pressed="true"]{background:var(--accent-20);border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent-35)}+.toggle[aria-pressed="true"]::after{left:20px;background:var(--accent)}+.mfoot{display:flex;justify-content:space-between;align-items:center;font-size:11px;color:var(--text-3);padding-top:4px}++@media (max-width:900px){.hero{grid-template-columns:auto 1fr}.hero .card{grid-column:1/-1}.two{grid-template-columns:1fr}}+@media (max-width:720px){.brand .app-sub,.subject-meta,.vsep{display:none}aside{flex-basis:200px}.thumb{width:84px;height:84px}}+@media (hover:none),(pointer:coarse){.tt{display:none}}+</style>+</head>+<body>+<div class="app">+<header>+ <div class="brand" id="brand" tabindex="0">+ <svg class="mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 3.5h9l4 4V13"/><path d="M13 3.5v4h4"/><path d="M7 8.5h3M7 11.5h5"/><rect x="12" y="14" width="8" height="7" rx="1"/><path d="M14 14v-2M18 14v-2M14 21v1.5M18 21v1.5M12 16.5h-2M12 19h-2"/></svg>+ <span class="app-name">DS2SF</span>+ <span class="app-sub">datasheet to symbol and footprint</span>+ <div class="popover" id="appinfo" role="dialog" aria-label="App information">+ <div class="pt">Adom DS2SF</div>+ <div class="pr"><span class="k">about</span><span class="v">Reads a chip's manufacturer datasheet and extracts pins, groups, and the land pattern with page-level provenance, so every fact links back to the PDF page it came from.</span></div>+ <div class="pr"><span class="k">version</span><span class="v mono" id="popVersion">?</span></div>+ <div class="pr"><span class="k">library</span><span class="v mono" id="popLibrary">?</span></div>+ <div class="pr"><span class="k">thread</span><span class="v mono" id="popThread">?</span></div>+ <div class="pr"><span class="k">author</span><span class="v">Adom Industries, adom.inc</span></div>+ <div class="pr"><span class="k">wiki</span><span class="v"><a href="https://wiki.adom.inc/adom/adom-ds2sf" target="_blank" rel="noopener">wiki.adom.inc/adom/adom-ds2sf</a></span></div>+ </div>+ </div>+ <div class="vsep" aria-hidden="true"></div>+ <div class="subject">+ <span class="subject-name idle" id="subjectName">No chip selected</span>+ <span class="pill" id="subjectPill" hidden><span class="dot"></span><span id="subjectPillText"></span></span>+ <span class="target-chip" data-tooltip="Where this dashboard runs. Extraction happens in this container; the datasheet PDF is read here, not on your desktop."><span class="led live"></span>target: <b>this machine</b></span>+ <span class="subject-meta" id="subjectMeta"></span>+ </div>+ <div class="actions">+ <button class="iconbtn" id="btn-help" aria-label="Getting started" aria-pressed="false" data-tooltip="Show the say-it phrases and what each status colour means."><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9.5"/><path d="M9.5 9.5a2.5 2.5 0 0 1 5 0c0 1.7-2.5 2-2.5 3.7"/><path d="M12 17h.01"/></svg></button>+ <button class="iconbtn" id="btn-settings" aria-label="Settings" data-tooltip="Settings: default model, display surface, idle shutdown, dev mode."><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg></button>+ </div>+</header>++<div class="body">+ <aside>+ <div class="rail-head">+ <input class="search" id="search" placeholder="Filter chips" aria-label="Filter chips" data-tooltip="Type part of an MPN, manufacturer, or package. The list narrows as you type.">+ <div class="filters" id="filters" role="toolbar" aria-label="Status filters"></div>+ </div>+ <div class="rail-list" id="list" role="listbox" aria-label="Library chips"></div>+ <div class="rail-foot" id="railFoot">Library from chip-fetcher. Green: extracted. Yellow: needs a better PDF. Red: failed. Blue: has a datasheet, not run yet. Grey: no datasheet.</div>+ </aside>+ <main id="main">+ <div class="empty" id="empty">+ <h2>Pick a chip</h2>+ <p>DS2SF reads the manufacturer datasheet and pulls out every pin, its group, and the package land pattern, each with the PDF page it came from. Select a chip on the left, or ask your AI.</p>+ <div class="say">+ <div>run ds2sf on the STM32L431RCT6TR</div>+ <div>show me the ds2sf dashboard</div>+ <div>which pins on this chip need review</div>+ <div>re-extract the footprint for this chip with opus</div>+ </div>+ </div>+ <div id="detail" hidden></div>+ </main>+</div>+</div>++<div class="toasts" id="toasts" role="status" aria-live="polite"></div>+<div class="tt" id="tt" role="tooltip"></div>+<div class="aicur" id="aicur"><svg viewBox="0 0 24 24" fill="#00e6dc" stroke="#05221f" stroke-width="1.2"><path d="M4 3l7 17 2.5-6.5L20 11z"/></svg><span class="lbl" id="aicurlbl"></span></div>++<dialog id="settings">+ <div class="modal">+ <div class="mh"><h2>Settings</h2><button class="iconbtn" id="settingsClose" aria-label="Close"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg></button></div>+ <div class="scard">+ <div class="st">Extraction <span class="ss" id="ssModel"></span></div>+ <div class="sd">Which Claude model reads the datasheet. Production runs use Opus: engineers wire schematics from this output, and cheaper models misread pin orders, undercount pads, and confuse package variants. Only drop to a smaller model for a quick experiment you will re-run with Opus.</div>+ <div class="srow"><div><div class="sl">extraction <em>default model</em></div><div class="sdef">Default: claude-opus-4-7</div></div><select data-setting="default_model"></select></div>+ </div>+ <div class="scard">+ <div class="st">Display</div>+ <div class="sd">Where <code>adom-ds2sf show</code> opens this dashboard when no surface is given. <code>wv</code> is a Hydrogen webview tab beside your editor; <code>pup</code> is the AI's own Chrome window on your desktop; <code>hbw</code> is Hydrogen's standalone browser window; <code>nb</code> is your real signed-in browser.</div>+ <div class="srow"><div><div class="sl">display <em>default surface</em></div><div class="sdef">Default: wv</div></div><select data-setting="default_surface"></select></div>+ <div class="srow"><div><div class="sl">display <em>open windows in background</em></div><div class="sdef">Default: on. Windows open behind your work and flash the taskbar instead of stealing focus.</div></div><button class="toggle" data-setting="open_in_background" aria-pressed="true" aria-label="Open windows in background"></button></div>+ </div>+ <div class="scard">+ <div class="st">Lifecycle</div>+ <div class="sd">This server shuts itself down after sitting idle, so a container never fills with forgotten dashboards. Every request resets the clock; a running extraction is never interrupted. Its state is snapshotted per thread, so reopening restores what you were looking at. Start with <code>--keep-alive</code> for a daemon that must never reap.</div>+ <div class="srow"><div><div class="sl">lifecycle <em>idle shutdown</em> (hours)</div><div class="sdef">Default: 24</div></div><input type="number" min="1" max="720" data-setting="ttl_hours"></div>+ </div>+ <div class="scard">+ <div class="st">Developer</div>+ <div class="sd">Dev mode enables <code>POST /ui/eval</code>, which runs JavaScript inside this page and reports the result to <code>GET /console</code>. Useful while building the dashboard; leave it off otherwise.</div>+ <div class="srow"><div><div class="sl">developer <em>dev mode</em></div><div class="sdef">Default: off</div></div><button class="toggle" data-setting="dev_mode" aria-pressed="false" aria-label="Dev mode"></button></div>+ <div class="srow"><div><div class="sl">developer <em>library root</em></div><div class="sdef">Default: auto-detected chip-fetcher library. Leave blank to auto-detect.</div></div><input type="text" data-setting="library_root" placeholder="auto"></div>+ </div>+ <div class="mfoot"><span>adom-ds2sf <span class="mono" id="ssVersion"></span> · settings persist in ~/.config/adom-ds2sf/settings.json</span><button class="btn" id="settingsDefaults" style="padding:4px 9px;font-size:11px">Restore defaults</button></div>+ </div>+</dialog>++<script>+(() => {+// ── console relay (GET /console reads this) ──+const _post = (path, body) => fetch(path, {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body||{})}).then(r => r.json()).catch(e => ({ok:false,error:String(e)}));+for (const lvl of ['log','warn','error']) {+ const orig = console[lvl].bind(console);+ console[lvl] = (...a) => { orig(...a); try { _post('console', {level:lvl, msg:a.map(x => typeof x === 'string' ? x : JSON.stringify(x)).join(' ')}); } catch(e){} };+}+window.addEventListener('error', e => console.error('window.onerror: ' + e.message));+window.addEventListener('unhandledrejection', e => console.error('unhandledrejection: ' + (e.reason && e.reason.message || e.reason)));++const $ = (s, el=document) => el.querySelector(s);+const $$ = (s, el=document) => [...el.querySelectorAll(s)];+const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));+const AI_THREAD = 'ds2sf dashboard (user click)';++let state = { chips: [], current: '', job: null, settings: {} };+let detail = null;+let filter = 'all';+let tab = localStorage.getItem('ds2sf.tab') || 'pins';+let logLines = [];+let helpOn = false;++// ── toasts ──+function toast(text, kind='info', sticky=false) {+ const box = $('#toasts');+ const t = document.createElement('div');+ t.className = 'toast ' + kind; t.setAttribute('role', kind === 'error' ? 'alert' : 'status');+ t.innerHTML = `<span>${esc(text)}</span><button class="x" aria-label="Dismiss">×</button>`;+ $('.x', t).onclick = () => t.remove();+ box.appendChild(t);+ while (box.children.length > 4) box.firstChild.remove();+ if (!sticky && kind !== 'error') {+ let left = 4000, timer = setTimeout(() => t.remove(), left), start = Date.now();+ t.onmouseenter = () => { clearTimeout(timer); left -= Date.now() - start; };+ t.onmouseleave = () => { start = Date.now(); timer = setTimeout(() => t.remove(), Math.max(left, 800)); };+ }+}++// ── tooltips (body-appended, fixed, clamped on both axes) ──+const tt = $('#tt'); let ttTimer = null;+function showTip(el, x, y) {+ tt.textContent = el.getAttribute('data-tooltip'); tt.classList.add('show');+ const M = 8, w = tt.offsetWidth, h = tt.offsetHeight;+ let left = x + 14, top = y + 14;+ if (left + w + M > innerWidth) left = x - w - 14;+ if (top + h + M > innerHeight) top = y - h - 14;+ left = Math.max(M, Math.min(left, innerWidth - w - M)); top = Math.max(M, Math.min(top, innerHeight - h - M));+ tt.style.left = left + 'px'; tt.style.top = top + 'px';+}+document.addEventListener('mouseover', e => {+ const el = e.target.closest('[data-tooltip]'); if (!el) return;+ clearTimeout(ttTimer); ttTimer = setTimeout(() => showTip(el, e.clientX, e.clientY), 600);+});+document.addEventListener('mouseout', e => { if (e.target.closest && e.target.closest('[data-tooltip]')) { clearTimeout(ttTimer); tt.classList.remove('show'); } });+document.addEventListener('mousedown', () => { clearTimeout(ttTimer); tt.classList.remove('show'); });++// ── AI cursor ──+function aiCursor(sel, label) {+ const el = document.querySelector(sel); const c = $('#aicur'); if (!el) return false;+ const r = el.getBoundingClientRect();+ c.classList.add('show'); c.style.left = (r.left + r.width/2) + 'px'; c.style.top = (r.top + r.height/2) + 'px';+ $('#aicurlbl').textContent = label || ''; $('#aicurlbl').hidden = !label;+ clearTimeout(c._t); c._t = setTimeout(() => c.classList.remove('show'), 2500);+ return true;+}++// ── brand popover ──+{ const b = $('#brand'), p = $('#appinfo'); let st, ht;+ const open = () => { clearTimeout(ht); st = setTimeout(() => p.classList.add('show'), 600); };+ const close = () => { clearTimeout(st); ht = setTimeout(() => p.classList.remove('show'), 220); };+ b.addEventListener('mouseenter', open); b.addEventListener('mouseleave', close);+ b.addEventListener('click', () => p.classList.toggle('show')); }++// ── rendering: rail ──+const REVIEW_TEXT = {+ muxed_pin_protocol_select: 'These pins are protocol-multiplexed (oscillator or bus pins that double as GPIO). The symbol carries the primary function; confirm the mode your design uses.',+ boot_select_pin: 'A boot-mode strap. Its level at reset picks the boot source; give it a defined pull in the schematic.',+ alt_function_list_truncated_may_be_incomplete: 'The alternate-function list for these pins was longer than the extractor kept. Pin names and numbers are verified; the AF detail in the descriptions may be partial.',+ package_mismatch_in_hint: 'info.json disagrees with the datasheet about the package.',+ pad_dimensions_from_example_layout: 'Land pattern came from an example board layout rather than a formal recommended pattern; cross-check against IPC-7351.',+};+const STATUS_LABEL = { ok:'extracted', needs_better_pdf:'needs better PDF', unrecoverable:'failed', not_extracted:'not run yet', no_datasheet:'no datasheet', running:'extracting' };+function chipStatus(c) { return c.running ? 'running' : c.status; }+function renderFilters() {+ const c = state.counts || {};+ const defs = [['all','All',state.chips.length],['ok','Extracted',c.ok],['needs_better_pdf','Needs PDF',c.needs_better_pdf],['unrecoverable','Failed',c.unrecoverable],['not_extracted','Not run',c.not_extracted],['no_datasheet','No datasheet',c.no_datasheet]];+ $('#filters').innerHTML = defs.map(([k,l,n]) => `<button class="fpill" data-f="${k}" aria-pressed="${filter===k}">${l}<b>${n||0}</b></button>`).join('');+ $$('#filters .fpill').forEach(b => b.onclick = () => { filter = b.dataset.f; renderFilters(); renderList(); });+}+function renderList() {+ const q = $('#search').value.trim().toLowerCase();+ const rows = state.chips.filter(c => (filter === 'all' || c.status === filter) && (!q || [c.mpn, c.manufacturer, c.package].join(' ').toLowerCase().includes(q)));+ $('#list').innerHTML = rows.map(c => {+ const st = chipStatus(c);+ const sub = [c.manufacturer, c.package].filter(Boolean).join(' · ') || (c.has_pdf ? 'datasheet on disk' : 'no datasheet');+ return `<div class="row ${c.mpn === state.current ? 'cur' : ''}" role="option" aria-selected="${c.mpn === state.current}" data-mpn="${esc(c.mpn)}" data-tooltip="${esc(c.summary || STATUS_LABEL[st])}"><span class="led ${st}"></span><div class="rmain"><div class="rmpn">${esc(c.mpn)}</div><div class="rsub">${esc(sub)}</div></div>${c.pins ? `<span class="rbadge">${c.pins} pins</span>` : ''}</div>`;+ }).join('') || `<div style="padding:16px 12px;color:var(--text-3);font-size:12px">No chips match.</div>`;+ $$('#list .row').forEach(r => r.onclick = () => select(r.dataset.mpn));+}+$('#search').addEventListener('input', renderList);++async function select(mpn) {+ const r = await _post('select', { mpn, aiThread: AI_THREAD });+ if (!r.ok) toast(r.error || 'could not select', 'error');+}++// ── rendering: header subject ──+function renderSubject() {+ const c = state.chips.find(x => x.mpn === state.current);+ const name = $('#subjectName'), pill = $('#subjectPill'), meta = $('#subjectMeta');+ if (!c) { name.textContent = 'No chip selected'; name.classList.add('idle'); pill.hidden = true; meta.textContent = ''; return; }+ name.textContent = c.mpn; name.classList.remove('idle');+ const st = chipStatus(c);+ pill.hidden = false; pill.className = 'pill ' + st; $('#subjectPillText').textContent = STATUS_LABEL[st];+ const parts = [];+ if (c.pins) parts.push(c.pins + ' pins');+ if (c.package) parts.push(c.package);+ if (detail && detail.provenance && detail.provenance.datasheet && detail.provenance.datasheet.page_count) parts.push(detail.provenance.datasheet.page_count + ' pages');+ if (c.model) parts.push(c.model);+ meta.textContent = parts.join(' · ');+ $('#popVersion').textContent = state.version; $('#popLibrary').textContent = state.library_root || 'not found'; $('#popThread').textContent = state.thread || '';+}++// ── rendering: detail ──+const pdfUrl = (mpn, name, page) => `api/chip/${encodeURIComponent(mpn)}/pdf${name ? '?name=' + encodeURIComponent(name) : ''}${page ? '#page=' + page : ''}`;+function openPdf(page, name) { window.open(pdfUrl(state.current, name, page), '_blank', 'noopener'); }+const pgLink = (p, name) => p ? `<a class="pg" href="${pdfUrl(state.current, name, p)}" target="_blank" rel="noopener" data-tooltip="Open the datasheet at page ${p}, where this fact was read.">p.${p}</a>` : '<span style="color:var(--text-3)">?</span>';++function renderDetail() {+ const c = state.chips.find(x => x.mpn === state.current);+ $('#empty').hidden = !!c; $('#detail').hidden = !c;+ if (!c || !detail) return;+ const d = detail, res = d.result || {}, sym = d.symbol || {}, fp = d.footprint || {}, prov = d.provenance || {}, info = d.info || {};+ const st = chipStatus(c);+ const desc = sym.description || info.description || '';+ const ds = prov.datasheet || {};+ const pdfName = res.datasheet_used ? res.datasheet_used.split('/').pop() : (c.pdfs[0] || '');+ const model = state.settings.default_model || 'claude-opus-4-7';+ const pins = sym.pins || [], groups = sym.groups || [];+ const pinProv = (prov.symbol && prov.symbol.pin_provenance) || [];+ const dimProv = (prov.footprint && prov.footprint.dimension_provenance) || [];+ const review = res.review_required || [];+ const hints = res.hints || [];+ const provByPin = {}; pinProv.forEach(p => provByPin[p.pin_number] = p);++ const hintHtml = hints.map(h => {+ if (h.action === 'try_alternate_pdf') return `<div class="hint"><span class="ha">try another PDF</span><div class="hb">${esc(h.reason)}. Candidates already on disk:<br>${(h.candidates||[]).map(p => { const n = p.split('/').pop(); return `<button class="btn" data-extract-pdf="${esc(n)}" data-tooltip="Re-run the extraction against ${esc(n)}">${esc(n)}</button>`; }).join(' ')}</div></div>`;+ if (h.action === 'update_upstream_metadata') return `<div class="hint"><span class="ha">upstream metadata</span><div class="hb"><code>${esc(h.file.split('/').pop())}</code> says <code>${esc(h.key)}: ${esc(h.current)}</code> but the datasheet says <code>${esc(h.extracted)}</code>. Ask your AI to patch info.json, or accept the datasheet value downstream.</div></div>`;+ if (h.action === 'use_datasheet_extracted_footprint') return `<div class="hint"><span class="ha">non-standard package</span><div class="hb"><code>${esc(h.package)}</code> is not in the KiCad standard library. Downstream footprint tools should use the body and lead dimensions in the Footprint tab directly.</div></div>`;+ const rv = review.find(r => (r.reason || r.stage_reason) === h.reason) || {};+ const pinsOf = [].concat(rv.pins || []).map(n => { const p = pins.find(x => x.number === String(n)); return p ? `<span class="tag" data-tooltip="${esc(p.description || '')}">${esc(n)} ${esc(p.name)}</span>` : `<span class="tag">${esc(n)}</span>`; }).join(' ');+ return `<div class="hint human_review"><span class="ha">${esc(h.reason || h.action)}</span><div class="hb">${esc(h.notes || rv.notes || REVIEW_TEXT[h.reason] || 'Flagged by the extractor for a human look.')}${pinsOf ? `<div style="margin-top:5px;display:flex;flex-wrap:wrap;gap:4px">${pinsOf}</div>` : ''}</div></div>`;+ }).join('');++ const tabs = [['pins','Pins',pins.length],['groups','Groups',groups.length],['footprint','Footprint',fp.padCount||0],['provenance','Provenance',pinProv.length + dimProv.length],['review','Review',review.length],['log','Log',null],['json','JSON',null]];++ $('#detail').innerHTML = `+ <div class="hero">+ <div class="thumb">${c.has_3d ? `<img src="api/chip/${encodeURIComponent(c.mpn)}/png" alt="${esc(c.mpn)} 3D">` : `<span class="nothumb">no 3D preview</span>`}</div>+ <div class="title">+ <h1>${esc(c.mpn)}</h1>+ <div class="mfr">${esc(sym.manufacturer || info.manufacturer || res.manufacturer || 'manufacturer unknown')}${info.family ? ' · ' + esc(info.family) : ''}</div>+ <div class="desc">${esc(desc) || '<span style="color:var(--text-3)">No description yet. The symbol pass writes one from the datasheet.</span>'}</div>+ <div class="kv">+ <div><span>package </span><b>${esc(sym.package || fp.package || info.package || '?')}</b></div>+ <div><span>pins </span><b>${pins.length || '?'}</b></div>+ <div><span>pads </span><b>${fp.padCount || '?'}</b></div>+ <div><span>kicad baseline </span><b>${fp.kicad_baseline && fp.kicad_baseline.name ? esc(fp.kicad_baseline.library + ':' + fp.kicad_baseline.name) : 'none'}</b></div>+ <div><span>concur </span><b>${esc(c.concur || 'not run')}</b></div>+ </div>+ </div>+ <div class="card status-${st}">+ <div class="ct">Extraction <span class="pill ${st}"><span class="dot"></span>${STATUS_LABEL[st]}</span></div>+ <div class="cd">${state.job && state.job.mpn === c.mpn ? esc(state.job.stage) + ' <span class="elapsed" id="heroElapsed"></span>' : esc(res.summary || (c.has_pdf || c.pdfs.length ? 'Datasheet on disk. Press Extract to read it.' : 'No datasheet PDF in this chip directory. Ask your AI to fetch one with chip-fetcher first.'))}</div>+ <div class="kv">+ <span>datasheet</span><b>${pdfName ? `<a class="pg" href="${pdfUrl(c.mpn, pdfName)}" target="_blank" rel="noopener">${esc(pdfName)}</a>` : 'none'}</b>+ <span>pages</span><b>${ds.page_count || '?'}</b>+ <span>source</span><b>${esc(ds.source_tier || '')}${ds.source_host ? ' · ' + esc(ds.source_host) : ''}</b>+ <span>sha256</span><b title="${esc(res.datasheet_sha256||'')}">${esc((res.datasheet_sha256||'').slice(0,16))}${res.datasheet_sha256 ? '…' : ''}</b>+ <span>model</span><b>${esc(res.claude_model || '')}</b>+ <span>extractor</span><b>${esc(res.extractor_version || '')}${c.extracted_at ? ' · ' + new Date(c.extracted_at*1000).toLocaleString() : ''}</b>+ <span>review</span><b>${review.length} item${review.length===1?'':'s'} · ${hints.length} hint${hints.length===1?'':'s'}</b>+ </div>+ </div>+ </div>+ <div class="actionbar">+ <button class="btn primary" id="btn-extract" ${state.job ? 'disabled' : ''} data-tooltip="Run adom-ds2sf extract on this chip. Reuses cached Claude responses when the outputs already exist; use Re-extract to force a fresh read."><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M6 4l12 8-12 8z"/></svg>Extract</button>+ <button class="btn" id="btn-force" ${state.job ? 'disabled' : ''} data-tooltip="Bypass the cache and ask Claude to read the datasheet again, both passes. Costs a full Opus run."><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/></svg>Re-extract</button>+ <button class="btn" id="btn-symbol" ${state.job ? 'disabled' : ''} data-tooltip="Symbol pass only: pins, groups, descriptions. Skips the package drawing.">Symbol only</button>+ <button class="btn" id="btn-footprint" ${state.job ? 'disabled' : ''} data-tooltip="Footprint pass only, against the cached symbol pass. Re-reads the mechanical drawing.">Footprint only</button>+ ${c.pdfs.length > 1 ? `<select id="pdfPick" data-tooltip="Which PDF in the chip directory to read. Module products often need the module datasheet, not the SoC one.">${c.pdfs.map(p => `<option ${p === pdfName ? 'selected' : ''}>${esc(p)}</option>`).join('')}</select>` : ''}+ <select id="modelPick" data-tooltip="Claude model for this run. Opus is the production default; see Settings.">${['claude-opus-4-7','claude-sonnet-4-5','claude-haiku-4-5'].map(m => `<option ${m===model?'selected':''}>${m}</option>`).join('')}</select>+ <span class="spacer"></span>+ ${state.job && state.job.mpn === c.mpn ? `<span class="pill running"><span class="dot"></span>${esc(state.job.stage)}</span><span class="elapsed" id="barElapsed"></span>` : (state.job ? `<span class="pill running"><span class="dot"></span>busy with ${esc(state.job.mpn)}</span>` : '')}+ ${pdfName ? `<button class="btn" id="btn-pdf" data-tooltip="Open the datasheet PDF in a new tab."><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/></svg>Datasheet</button>` : ''}+ </div>+ ${hintHtml ? `<div class="hints">${hintHtml}</div>` : ''}+ <div class="tabs" role="tablist">${tabs.map(([k,l,n]) => `<button class="tab" role="tab" data-tab="${k}" aria-selected="${tab===k}">${l}${n!=null ? `<b>${n}</b>` : ''}</button>`).join('')}</div>+ <div class="panel" id="panel"></div>`;++ $$('#detail .tab').forEach(b => b.onclick = () => { tab = b.dataset.tab; localStorage.setItem('ds2sf.tab', tab); renderDetail(); });+ $('#btn-extract').onclick = () => extract({});+ $('#btn-force').onclick = () => extract({ force: true });+ $('#btn-symbol').onclick = () => extract({ force: true, symbolOnly: true });+ $('#btn-footprint').onclick = () => extract({ force: true, footprintOnly: true });+ if ($('#btn-pdf')) $('#btn-pdf').onclick = () => openPdf(0, pdfName);+ $$('[data-extract-pdf]').forEach(b => b.onclick = () => extract({ force: true, pdf: b.dataset.extractPdf }));++ const panel = $('#panel');+ if (tab === 'pins') {+ panel.innerHTML = pins.length ? `<table><thead><tr><th>#</th><th>Name</th><th>Type</th><th>Group</th><th>Description</th><th>Page</th></tr></thead><tbody>${pins.map(p => { const pv = provByPin[p.number] || {}; return `<tr><td class="num">${esc(p.number)}</td><td class="mono">${esc(p.name)}</td><td><span class="tag">${esc(p.type)}</span></td><td><span class="tag g-${esc(p.group)}">${esc(p.group)}</span></td><td>${esc(p.description || '')}${pv.notes ? `<div style="color:var(--text-3);margin-top:2px">${esc(pv.notes)}</div>` : ''}</td><td>${pv.confidence ? `<span class="conf ${esc(pv.confidence)}" data-tooltip="confidence: ${esc(pv.confidence)}"></span>` : ''}${pgLink(pv.page, pdfName)}</td></tr>`; }).join('')}</tbody></table>` : emptyPanel('No pins extracted yet.');+ } else if (tab === 'groups') {+ panel.innerHTML = groups.length ? `<div class="groups">${groups.map(g => `<div class="group"><div class="gn"><span class="tag g-${esc(g.name)}">${esc(g.name)}</span></div><div class="gd">${esc(g.description || '')}</div><div class="gp">${pins.filter(p => p.group === g.name).map(p => `<span data-tooltip="${esc(p.description||'')}">${esc(p.number)} ${esc(p.name)}</span>`).join('')}</div></div>`).join('')}</div>` : emptyPanel('No groups yet.');+ } else if (tab === 'footprint') {+ const bd = fp.bodyDimensions || {}, ld = fp.leadDimensions || {}, pads = fp.pads || [];+ const dims = [...Object.entries(bd).map(([k,v]) => ['bodyDimensions.'+k, v]), ...Object.entries(ld).map(([k,v]) => ['leadDimensions.'+k, v])];+ const dp = {}; dimProv.forEach(x => dp[x.field] = x);+ panel.innerHTML = `<div class="svgs">+ <div class="svgbox"><div class="sh"><b>Datasheet-derived</b><span>ds2sf, from the package drawing</span></div>${c.svgs.ds2sf ? `<img src="api/chip/${encodeURIComponent(c.mpn)}/svg/ds2sf?t=${c.extracted_at}" alt="ds2sf footprint">` : `<div class="none">No footprint SVG yet</div>`}</div>+ <div class="svgbox"><div class="sh"><b>KiCad stdlib</b><span>${fp.kicad_baseline && fp.kicad_baseline.name ? esc(fp.kicad_baseline.name) : 'no baseline match'}</span></div>${c.svgs.pcbnew ? `<img src="api/chip/${encodeURIComponent(c.mpn)}/svg/pcbnew?t=${c.extracted_at}" alt="pcbnew footprint">` : `<div class="none">No stdlib comparison</div>`}</div>+ </div>+ <div class="two">+ <div><h3 class="sec">Dimensions (mm)</h3>${dims.length ? `<table><thead><tr><th>Field</th><th>Value</th><th>Figure</th><th>Page</th></tr></thead><tbody>${dims.map(([k,v]) => { const p = dp[k] || {}; return `<tr><td class="mono">${esc(k)}</td><td class="num">${typeof v === 'object' ? esc(JSON.stringify(v)) : esc(v)}</td><td style="color:var(--text-2)">${esc(p.figure_label||'')}</td><td>${pgLink(p.page, pdfName)}</td></tr>`; }).join('')}</tbody></table>` : emptyPanel('No dimensions extracted.')}</div>+ <div><h3 class="sec">Pads (${pads.length})</h3>${pads.length ? `<div style="max-height:420px;overflow:auto"><table><thead><tr><th>#</th><th>At</th><th>Size</th><th>Shape</th><th>Pin</th></tr></thead><tbody>${pads.map(p => `<tr><td class="num">${esc(p.number)}</td><td class="mono">${(p.at||[]).map(n => (+n).toFixed(3)).join(', ')}</td><td class="mono">${(p.size||[]).join(' × ')}</td><td>${esc(p.shape||'')}</td><td class="mono">${esc((fp.symbolPinMap||{})[p.number] || (fp.padDescriptions||{})[p.number] || '')}</td></tr>`).join('')}</tbody></table></div>` : emptyPanel('No per-pad data.')}</div>+ </div>`;+ } else if (tab === 'provenance') {+ panel.innerHTML = `<div class="two">+ <div><h3 class="sec">Pin provenance (${pinProv.length})</h3>${pinProv.length ? `<table><thead><tr><th>#</th><th>Pin</th><th>Table</th><th>Page</th></tr></thead><tbody>${pinProv.map(p => `<tr><td class="num">${esc(p.pin_number)}</td><td class="mono">${esc(p.pin_name)}</td><td style="color:var(--text-2)">${esc(p.table_caption||'')}</td><td><span class="conf ${esc(p.confidence||'')}"></span>${pgLink(p.page, pdfName)}</td></tr>`).join('')}</tbody></table>` : emptyPanel('No pin provenance.')}</div>+ <div><h3 class="sec">Dimension provenance (${dimProv.length})</h3>${dimProv.length ? `<table><thead><tr><th>Field</th><th>Value</th><th>Figure</th><th>Page</th></tr></thead><tbody>${dimProv.map(p => `<tr><td class="mono">${esc(p.field)}</td><td class="num">${esc(p.value)}</td><td style="color:var(--text-2)">${esc(p.figure_label||'')}</td><td>${pgLink(p.page, pdfName)}</td></tr>`).join('')}</tbody></table>` : emptyPanel('No dimension provenance.')}+ <h3 class="sec" style="margin-top:16px">Datasheet</h3><div class="card"><div class="kv"><span>path</span><b>${esc(ds.path||'')}</b><span>url</span><b>${ds.url ? `<a href="${esc(ds.url)}" target="_blank" rel="noopener">${esc(ds.url)}</a>` : ''}</b><span>sha256</span><b>${esc(ds.sha256||'')}</b><span>fetched</span><b>${esc(ds.fetched_at||'')}</b><span>tooling</span><b>${esc(JSON.stringify(prov.tooling||{}))}</b></div></div></div>+ </div>`;+ } else if (tab === 'review') {+ panel.innerHTML = review.length ? `<div class="review">${review.map(r => `<div class="rv"><span class="rr">${esc(r.reason || r.stage_reason || '')}</span><div class="rn">${esc(r.notes || r.pin || '')}${r.pins ? '<div class="mono" style="color:var(--text-2);margin-top:3px">' + esc([].concat(r.pins).join(', ')) + '</div>' : ''}</div></div>`).join('')}</div>` : emptyPanel('Nothing flagged for review.');+ } else if (tab === 'log') {+ panel.innerHTML = `<pre class="log" id="logpre"></pre>`; renderLog();+ } else if (tab === 'json') {+ const keys = ['result','symbol','footprint','provenance','validation','concur','info'];+ const pick = localStorage.getItem('ds2sf.json') || 'result';+ panel.innerHTML = `<div class="jsonpick">${keys.map(k => `<button class="btn ${k===pick?'primary':''}" data-json="${k}" style="padding:4px 9px;font-size:11.5px">${k}</button>`).join('')}${(d.cache_files||[]).length ? `<span style="align-self:center;color:var(--text-3);font-size:11px;margin-left:8px">cache: ${d.cache_files.map(f => `<a class="pg" href="api/chip/${encodeURIComponent(c.mpn)}/cache/${encodeURIComponent(f)}" target="_blank" rel="noopener">${esc(f)}</a>`).join(' ')}</span>` : ''}</div><pre class="json">${esc(JSON.stringify(d[pick], null, 2) || 'null')}</pre>`;+ $$('[data-json]').forEach(b => b.onclick = () => { localStorage.setItem('ds2sf.json', b.dataset.json); renderDetail(); });+ }+ tickElapsed();+}+const emptyPanel = m => `<div style="padding:28px;text-align:center;color:var(--text-3)">${esc(m)}</div>`;+function tickElapsed() {+ if (!state.job) return;+ const s = Math.max(0, Math.floor(Date.now()/1000 - state.job.started));+ const t = `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;+ for (const id of ['heroElapsed','barElapsed']) { const e = document.getElementById(id); if (e) e.textContent = t; }+}+setInterval(tickElapsed, 1000);+function renderLog() {+ const pre = $('#logpre'); if (!pre) return;+ pre.innerHTML = logLines.map(l => { const c = l.startsWith('OK:') ? 'ok' : l.startsWith('ERROR:') ? 'err' : l.startsWith('WARN:') ? 'warn' : /^\[(1a|1b|svg|done)\]/.test(l) ? 'stage' : ''; return `<span class="${c}">${esc(l)}</span>`; }).join('\n') || '<span style="color:var(--text-3)">No extraction has run in this session yet.</span>';+ pre.scrollTop = pre.scrollHeight;+}++async function extract(opts) {+ const body = Object.assign({ mpn: state.current, aiThread: AI_THREAD, model: ($('#modelPick')||{}).value }, opts);+ if (!opts.pdf && $('#pdfPick')) body.pdf = $('#pdfPick').value;+ if (body.model && body.model !== 'claude-opus-4-7' && !confirm(`Run with ${body.model}? Only Opus is trusted for production pin data. Continue with ${body.model} for an experiment?`)) return;+ const r = await _post('extract', body);+ if (!r.ok) toast((r.error || 'extraction refused') + (r.hint ? ' ' + r.hint : ''), 'error');+ else { tab = 'log'; localStorage.setItem('ds2sf.tab', tab); }+}++async function loadDetail() {+ if (!state.current) { detail = null; renderDetail(); return; }+ const mpn = state.current;+ const d = await fetch(`api/chip/${encodeURIComponent(mpn)}`).then(r => r.json()).catch(() => null);+ if (state.current !== mpn) return;+ detail = d; renderDetail(); renderSubject();+}++function applyState(s) {+ const prev = state.current;+ const jobStarted = s.job && (!state.job || state.job.mpn !== s.job.mpn);+ const prevExtracted = detail && detail.summary ? detail.summary.extracted_at : null;+ const prevLogLen = state.log_len || 0;+ state = s;+ // Poll-mode parity with the live channel: execute directives we have not seen,+ // refresh the log when it grew, and reload the detail when its extraction changed.+ const uiEvents = s.ui || [];+ if (lastSeq === null) lastSeq = uiEvents.length ? uiEvents[uiEvents.length - 1].seq : 0;+ for (const e of uiEvents) if (e.seq > lastSeq) { lastSeq = e.seq; if (!(es && es.readyState === 1)) runDirective(e.event, e.data); }+ if ((s.log_len || 0) !== prevLogLen && !(es && es.readyState === 1)) fetch('log').then(r => r.json()).then(l => { logLines = l.lines || []; renderLog(); }).catch(() => {});+ const curNow = s.chips.find(c => c.mpn === s.current);+ const extractedChanged = curNow && prevExtracted !== null && curNow.extracted_at !== prevExtracted;+ // A job that just started for the chip on screen pulls the Log tab forward so the+ // person watching sees Claude's progress without hunting for it.+ if (jobStarted && s.job.mpn === s.current && tab !== 'log') { tab = 'log'; localStorage.setItem('ds2sf.tab', tab); }+ renderFilters(); renderList(); renderSubject();+ if (s.current !== prev || !detail || extractedChanged) loadDetail(); else renderDetail();+ fillSettings();+}++// ── settings ──+function fillSettings() {+ const s = state.settings || {}, en = (state.enums || {});+ $$('[data-setting]').forEach(el => {+ const k = el.dataset.setting, v = s[k];+ if (el.tagName === 'SELECT') {+ const vals = k === 'default_model' ? ['claude-opus-4-7','claude-sonnet-4-5','claude-haiku-4-5'] : ['wv','pup','hbw','nb'];+ if (!el.options.length) el.innerHTML = vals.map(x => `<option>${x}</option>`).join('');+ el.value = v;+ } else if (el.classList.contains('toggle')) el.setAttribute('aria-pressed', String(!!v));+ else el.value = v == null ? '' : v;+ });+ $('#ssModel').textContent = s.default_model === 'claude-opus-4-7' ? 'Opus (production)' : (s.default_model || '') + ' (experiment only)';+ $('#ssModel').className = 'ss ' + (s.default_model === 'claude-opus-4-7' ? 'ok' : '');+ $('#ssVersion').textContent = state.version || '';+}+async function setSetting(k, v) {+ const r = await _post('settings', { [k]: v, aiThread: AI_THREAD });+ if (r.ok) toast(`${k.replace(/_/g,' ')} set to ${v === '' ? 'auto' : v}`, 'success'); else toast(r.error + (r.hint ? ' ' + r.hint : ''), 'error');+}+$$('[data-setting]').forEach(el => {+ const k = el.dataset.setting;+ if (el.classList.contains('toggle')) el.onclick = () => setSetting(k, el.getAttribute('aria-pressed') !== 'true');+ else el.onchange = () => setSetting(k, el.type === 'number' ? Number(el.value) : (el.value === '' ? null : el.value));+});+$('#btn-settings').onclick = () => $('#settings').showModal();+$('#settingsClose').onclick = () => $('#settings').close();+$('#settings').addEventListener('click', e => { if (e.target === $('#settings')) $('#settings').close(); });+let defaultsArmed = false;+$('#settingsDefaults').onclick = async () => {+ if (!defaultsArmed) { defaultsArmed = true; $('#settingsDefaults').textContent = 'Click again to confirm'; setTimeout(() => { defaultsArmed = false; $('#settingsDefaults').textContent = 'Restore defaults'; }, 3000); return; }+ await _post('settings', { ttl_hours: 24, default_surface: 'wv', open_in_background: true, default_model: 'claude-opus-4-7', dev_mode: false, library_root: null, aiThread: AI_THREAD });+ toast('Settings restored to defaults', 'success'); defaultsArmed = false; $('#settingsDefaults').textContent = 'Restore defaults';+};+$('#btn-help').onclick = () => { helpOn = !helpOn; $('#btn-help').setAttribute('aria-pressed', String(helpOn)); if (helpOn) { $('#railFoot').hidden = false; toast('Say to your AI: "run ds2sf on <MPN>" or "show me the pins that need review"', 'info'); } };++// ── directives (from SSE or from the poll) ──+let lastSeq = null;+function runDirective(ev, d) {+ d = d || {};+ if (ev === 'toast') toast(d.text, d.kind || 'info', !!d.sticky);+ else if (ev === 'chip') { if (d.mpn === state.current) loadDetail(); }+ else if (ev === 'click') { const el = document.querySelector(d.selector); if (el) { aiCursor(d.selector, d.label || 'clicking'); setTimeout(() => el.click(), 350); console.log('ui click ' + d.selector); } else console.warn('ui click: no element for ' + d.selector); }+ else if (ev === 'reveal') { const el = document.querySelector(d.selector); if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); aiCursor(d.selector, d.label || ''); } }+ else if (ev === 'cursor') aiCursor(d.selector, d.label || '');+ else if (ev === 'tab') { tab = d.tab || d.name; localStorage.setItem('ds2sf.tab', tab); renderDetail(); }+ else if (ev === 'reload') location.reload();+ else if (ev === 'eval') { try { const r = eval(d.js || d.code); console.log('eval result: ' + JSON.stringify(r)); } catch (err) { console.error('eval error: ' + err.message); } }+}++// ── live channel ──+let es = null, pollTimer = null;+function connect() {+ try { es = new EventSource('events'); } catch (e) { startPoll(); return; }+ es.addEventListener('state', e => applyState(JSON.parse(e.data)));+ es.addEventListener('log', e => { logLines.push(JSON.parse(e.data).line); if (logLines.length > 600) logLines.shift(); renderLog(); });+ for (const ev of ['toast','chip','click','reveal','cursor','tab','reload','eval']) es.addEventListener(ev, e => { const d = JSON.parse(e.data); lastSeq = Math.max(lastSeq || 0, (state.ui || []).reduce((m, x) => Math.max(m, x.seq), 0)); runDirective(ev, d); });+ es.onopen = () => { $('.target-chip .led').classList.add('live'); if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } };+ es.onerror = () => { $('.target-chip .led').classList.remove('live'); startPoll(); };+}+async function refreshState() { try { applyState(await fetch('state').then(r => r.json())); } catch (e) { console.warn('state fetch failed: ' + e.message); } }+function startPoll() { if (pollTimer) return; pollTimer = setInterval(refreshState, 2000); }+// First paint never waits on the live channel: fetch state now, poll until SSE is open,+// and if the proxy never lets the stream through, keep polling.+refreshState();+startPoll();+connect();+setTimeout(() => { if (!es || es.readyState !== 1) { console.warn('SSE not open after 5s (readyState ' + (es && es.readyState) + '); staying on the 2s poll'); startPoll(); } }, 5000);+fetch('settings').then(r => r.json()).then(s => { state.enums = s.enums; }).catch(() => {});+window.ds2sf = { state: () => state, detail: () => detail, select, extract, toast, aiCursor };+})();+</script>+</body>+</html>
src/cli.rs+139−1@@ -16,6 +16,14 @@ use crate::{emit, extract, normalize}; #[derive(Parser)] #[command(name = "adom-ds2sf", version, about = "Datasheet → symbol + footprint + provenance JSON")] pub struct Cli {+ /// The ai-thread name: which conversation is asking. Required on every verb+ /// that changes dashboard state. A short name a human recognizes ("ds2sf",+ /// "stm32 board review"), reused on every Adom tool call. Never "agent" or a UUID.+ #[arg(long, global = true)]+ pub ai_thread: Option<String>,+ /// Desktop to drive when more than one Adom Bridge is connected (`adom-bridge targets`).+ #[arg(long, global = true)]+ pub target: Option<String>, #[command(subcommand)] pub command: Cmd, }@@ -91,9 +99,114 @@ pub enum Cmd { Health, /// Drop SKILL.md to ~/.claude/skills/adom-ds2sf/. Install,+ /// Run the dashboard server (idempotent, version-aware). With --print-url it+ /// prints the direct http://127.0.0.1:<port>/ URL, self-backgrounds and exits 0+ /// (the Hydrogen Dock Bar contract). Idle instances reap themselves after 24h.+ Serve {+ /// TCP port, or `auto` for a free one.+ #[arg(long, default_value = "8791")]+ port: String,+ /// Print the reachable URL and keep serving in the background.+ #[arg(long)]+ print_url: bool,+ #[arg(long, hide = true)]+ detached_child: bool,+ /// Never reap on idle (daemon mode).+ #[arg(long)]+ keep_alive: bool,+ /// Idle shutdown after this many hours (default: the ttl_hours setting, 24).+ #[arg(long)]+ ttl: Option<f64>,+ },+ /// Start the dashboard if needed and open it: wv (Hydrogen webview tab, default),+ /// pup (the AI's Chrome on the desktop, background, maximized), hbw, or nb.+ Show {+ /// wv | pup | hbw | nb (default: the default_surface setting).+ #[arg(long)]+ surface: Option<String>,+ #[arg(long, default_value = "8791")]+ port: String,+ },+ /// List running dashboard instances (pid, port, thread, version, idle) and flag version drift.+ Ls,+ /// Drive the RUNNING dashboard's front-end over the live channel.+ Ui {+ #[command(subcommand)]+ op: UiOp,+ #[arg(long, global = true, default_value = "8791")]+ port: String,+ },+ /// Read or change dashboard settings (persisted in ~/.config/adom-ds2sf/settings.json).+ Settings {+ #[command(subcommand)]+ op: SettingsOp,+ #[arg(long, global = true, default_value = "8791")]+ port: String,+ },+ /// Stop a dashboard instance. Reason-gated: other threads may be using it.+ Shutdown {+ /// Why (>= 10 chars), quoting what the user asked for.+ #[arg(long)]+ reason: Option<String>,+ #[arg(long, default_value = "8791")]+ port: String,+ },+}++#[derive(Subcommand)]+pub enum UiOp {+ /// Raise a toast on the open page (the AI's narration channel).+ Toast {+ text: String,+ /// info | success | error+ #[arg(long, default_value = "info")]+ kind: String,+ #[arg(long)]+ sticky: bool,+ },+ /// Click an element by CSS selector, with the AI cursor gliding to it first.+ Click { selector: String, #[arg(long)] label: Option<String> },+ /// Scroll an element into view and point the AI cursor at it.+ Reveal { selector: String, #[arg(long)] label: Option<String> },+ /// Glide the AI cursor to an element without clicking.+ Cursor { selector: String, #[arg(long)] label: Option<String> },+ /// Switch the detail tab: pins | groups | footprint | provenance | review | log | json.+ Tab { name: String },+ /// Reload the page (last resort; prefer state changes).+ Reload,+ /// Dev mode only: run JavaScript in the page, result lands in `ui console`.+ Eval { js: String },+ /// Focus a chip in the dashboard.+ Select { mpn: String },+ /// Run the extractor on a chip from the dashboard (streams into the Log tab).+ Extract {+ mpn: String,+ #[arg(long)] force: bool,+ /// PDF file name inside the chip dir (or absolute path) to read instead of <MPN>.pdf.+ #[arg(long)] pdf: Option<String>,+ #[arg(long)] model: Option<String>,+ #[arg(long)] symbol_only: bool,+ #[arg(long)] footprint_only: bool,+ },+ /// Print the full dashboard state JSON.+ State,+ /// Print the page's console ring buffer.+ Console,+ /// Print the current extraction log.+ Log,+}++#[derive(Subcommand)]+pub enum SettingsOp {+ /// Print settings with their allowed values.+ Get,+ /// Set one setting (value parsed as JSON, else a string).+ Set { key: String, value: String }, } pub fn run(cli: Cli) -> i32 {+ let ai_thread = cli.ai_thread.clone();+ crate::dashcli::set_target(cli.target.clone()); match cli.command { Cmd::Extract { chip_dir,@@ -202,6 +315,12 @@ pub fn run(cli: Cli) -> i32 { 1 } }+ Cmd::Serve { port, print_url, detached_child, keep_alive, ttl } => crate::dashcli::serve(ai_thread, &port, print_url, detached_child, keep_alive, ttl),+ Cmd::Show { surface, port } => crate::dashcli::show(ai_thread, surface, &port),+ Cmd::Ls => crate::dashcli::ls(),+ Cmd::Ui { op, port } => crate::dashcli::ui(ai_thread, op, &port),+ Cmd::Settings { op, port } => crate::dashcli::settings(ai_thread, op, &port),+ Cmd::Shutdown { reason, port } => crate::dashcli::shutdown(ai_thread, reason, &port), Cmd::Install => { let home = match std::env::var("HOME") { Ok(h) => h,@@ -577,7 +696,26 @@ fn run_svg_only(chip_dir: &Path) -> anyhow::Result<crate::fpsvg::SvgResult> { let fp_raw = std::fs::read_to_string(&fp_path).map_err(|e| { anyhow::anyhow!("reading {} — run `ds2sf extract` first: {e}", fp_path.display()) })?;- let fp_json: serde_json::Value = serde_json::from_str(&fp_raw)?;+ let mut fp_json: serde_json::Value = serde_json::from_str(&fp_raw)?;++ // A cached extraction with no stdlib baseline gets one more try here: the+ // normalizer learns new package families over time (JEDEC LQFP bodies by+ // pin count, for one), and `svg` is the cheap path to pick that up without+ // paying for another Claude pass. A hit is written back into the JSON.+ if fp_json.get("kicad_baseline").map(|v| v.is_null()).unwrap_or(true) {+ let pkg = fp_json.get("package").and_then(|v| v.as_str()).unwrap_or("").to_string();+ let bx = fp_json.pointer("/bodyDimensions/x").and_then(|v| v.as_f64());+ let by = fp_json.pointer("/bodyDimensions/y").and_then(|v| v.as_f64());+ let hint = match (bx, by) { (Some(x), Some(y)) => Some(format!("{x}x{y}")), _ => None };+ if let Ok(r) = normalize::resolve(&pkg, hint.as_deref()) {+ if let Some(b) = r.kicad_baseline.as_ref() {+ fp_json["kicad_baseline"] = json!({ "library": b.library, "name": b.name, "source": b.source });+ fp_json["package_outline_source"] = json!("service-kicad-stdlib");+ std::fs::write(&fp_path, serde_json::to_string_pretty(&fp_json)? + "\n")?;+ note(format!("[normalize] {pkg} → {}:{} (written back to {})", b.library, b.name, fp_path.display()));+ }+ }+ } // Reconstruct a minimal FootprintPass + Resolved from the cached JSON. let pkg_name = fp_json
src/dashcli.rsadded+322@@ -0,0 +1,322 @@+//! CLI verbs for the dashboard: serve / show / ls / ui / settings / shutdown.+//! Every verb that changes server state carries the ai-thread name as+//! `aiThread` in the JSON it POSTs (app-creator-ai-thread-name).++use crate::io::{err, hint, note, ok};+use crate::server::{self, ServeOpts, APP, DEFAULT_PORT, VERSION, WEBVIEW_TAB};+use serde_json::{json, Value};+use std::time::{Duration, Instant};++static TARGET: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);+pub fn set_target(t: Option<String>) {+ *TARGET.lock().unwrap() = t;+}++pub fn parse_port(p: &str) -> u16 {+ if p.eq_ignore_ascii_case("auto") {+ server::free_port()+ } else {+ p.parse().unwrap_or(DEFAULT_PORT)+ }+}++pub fn require_thread(t: Option<String>, verb: &str) -> Result<String, i32> {+ match t {+ Some(t) if !t.trim().is_empty() => Ok(t.trim().to_string()),+ _ => {+ err("caller_identity_required: this app requires every AI caller to give its ai-thread name.");+ hint(format!(+ "adom-ds2sf --ai-thread \"<name>\" {verb} (a short name a HUMAN recognizes for THIS conversation, like 'ds2sf' or 'stm32 board review'; reuse it on every Adom tool call)"+ ));+ Err(2)+ }+ }+}++fn spawn_detached(port: u16, thread: &str, keep_alive: bool, ttl: Option<f64>) -> std::io::Result<()> {+ use std::os::unix::process::CommandExt;+ let exe = std::env::current_exe()?;+ let mut cmd = std::process::Command::new(exe);+ cmd.args(["serve", "--port", &port.to_string(), "--ai-thread", thread, "--detached-child"]);+ if keep_alive {+ cmd.arg("--keep-alive");+ }+ if let Some(t) = ttl {+ cmd.args(["--ttl", &t.to_string()]);+ }+ cmd.stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .process_group(0);+ cmd.spawn().map(|_| ())+}++/// Make sure a current-version instance answers on `port`; returns Ok(port) once it does.+pub fn ensure_running(port: u16, thread: &str, keep_alive: bool, ttl: Option<f64>) -> Result<u16, String> {+ if let Some(h) = server::probe(port) {+ let v = h.get("version").and_then(|v| v.as_str()).unwrap_or("?").to_string();+ if v == VERSION {+ return Ok(port);+ }+ note(format!("an older adom-ds2sf (v{v}) owns port {port}; retiring it for v{VERSION}"));+ let _ = server::post_json(port, "/shutdown", &json!({+ "aiThread": "adom-ds2sf housekeeping",+ "reason": format!("version drift: replacing v{v} with v{VERSION} on port {port}")+ }));+ let t0 = Instant::now();+ while server::probe(port).is_some() && t0.elapsed() < Duration::from_secs(4) {+ std::thread::sleep(Duration::from_millis(200));+ }+ }+ spawn_detached(port, thread, keep_alive, ttl).map_err(|e| format!("could not spawn the server: {e}"))?;+ let t0 = Instant::now();+ while t0.elapsed() < Duration::from_secs(20) {+ std::thread::sleep(Duration::from_millis(250));+ if server::probe(port).is_some() {+ return Ok(port);+ }+ }+ Err(format!("server did not answer on port {port} within 20s"))+}++pub fn serve(ai_thread: Option<String>, port_s: &str, print_url: bool, detached_child: bool, keep_alive: bool, ttl: Option<f64>) -> i32 {+ let thread = match require_thread(ai_thread, "serve") { Ok(t) => t, Err(c) => return c };+ let port = parse_port(port_s);+ if detached_child {+ return match server::run(ServeOpts { port, ai_thread: thread, keep_alive, ttl_hours: ttl }) {+ Ok(()) => 0,+ Err(e) => { err(e); 1 }+ };+ }+ // Idempotent, version-aware (dock contract + lifecycle Rule 3).+ if let Some(h) = server::probe(port) {+ let v = h.get("version").and_then(|v| v.as_str()).unwrap_or("?");+ let owner = h.get("thread").and_then(|v| v.as_str()).unwrap_or("?");+ if v == VERSION {+ if print_url {+ println!("{}", server::direct_url(port));+ } else {+ ok(format!("already running on port {port} (v{v}, thread \"{owner}\"). Use that instance: {}", server::proxy_url_for_port(port)));+ }+ return 0;+ }+ }+ if print_url {+ return match ensure_running(port, &thread, keep_alive, ttl) {+ Ok(p) => { println!("{}", server::direct_url(p)); 0 }+ Err(e) => { err(e); hint("adom-ds2sf --ai-thread \"<name>\" serve (foreground, to see the bind error)"); 1 }+ };+ }+ match server::run(ServeOpts { port, ai_thread: thread, keep_alive, ttl_hours: ttl }) {+ Ok(()) => 0,+ Err(e) => { err(e); hint(format!("adom-ds2sf ls to see who owns port {port}, or --port auto")); 1 }+ }+}++fn bridge(thread: &str, verb: &str, body: &Value) -> Result<Value, String> {+ let mut cmd = std::process::Command::new("adom-bridge");+ cmd.args(["--ai-thread", thread]);+ if let Some(t) = TARGET.lock().unwrap().clone() {+ cmd.args(["--target", &t]);+ }+ let out = cmd.args([verb, &body.to_string()])+ .output()+ .map_err(|e| format!("could not run adom-bridge: {e}"))?;+ let text = String::from_utf8_lossy(&out.stdout).to_string();+ let v: Value = serde_json::from_str(text.trim()).unwrap_or(json!({ "raw": text }));+ if out.status.success() && v.get("ok").and_then(|o| o.as_bool()).unwrap_or(true) {+ Ok(v)+ } else {+ Err(v.get("error").and_then(|e| e.as_str()).map(String::from).unwrap_or_else(|| String::from_utf8_lossy(&out.stderr).to_string()))+ }+}++pub fn show(ai_thread: Option<String>, surface: Option<String>, port_s: &str) -> i32 {+ let thread = match require_thread(ai_thread, "show") { Ok(t) => t, Err(c) => return c };+ let port = parse_port(port_s);+ let port = match ensure_running(port, &thread, false, None) {+ Ok(p) => p,+ Err(e) => { err(e); return 1; }+ };+ let settings = server::settings();+ let surface = surface.unwrap_or_else(|| settings.get("default_surface").and_then(|s| s.as_str()).unwrap_or("wv").to_string());+ let url = server::proxy_url_for_port(port);+ match surface.as_str() {+ "wv" => {+ let name = std::env::var("ADOM_DOCK_WEBVIEW").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| WEBVIEW_TAB.to_string());+ let st = std::process::Command::new("timeout")+ .args(["20", "adom-cli", "hydrogen", "webview", "open-or-refresh", "--name", &name, "--url", &url])+ .output();+ match st {+ Ok(o) if o.status.success() => { ok(format!("dashboard open in Hydrogen webview tab \"{name}\": {url}")); 0 }+ Ok(o) => {+ err(format!("adom-cli could not open the webview: {}", String::from_utf8_lossy(&o.stderr).trim()));+ hint(format!("adom-ds2sf --ai-thread \"{thread}\" show --surface pup (or open {url} yourself)"));+ 1+ }+ Err(e) => { err(format!("adom-cli not runnable: {e}")); hint(format!("open {url} in a browser, or `show --surface pup`")); 1 }+ }+ }+ "pup" => {+ // Reuse the window when the session is already open: navigate it and flash+ // the taskbar instead of spawning a second one (app-creator-surfaces).+ if bridge(&thread, "pup_navigate", &json!({ "sessionId": "adom-ds2sf", "url": url })).is_ok() {+ let _ = bridge(&thread, "pup_alert_window", &json!({ "sessionId": "adom-ds2sf" }));+ ok(format!("dashboard refreshed in the existing pup window (session adom-ds2sf): {url}"));+ return 0;+ }+ let body = json!({ "sessionId": "adom-ds2sf", "profile": "adom-ds2sf", "url": url });+ match bridge(&thread, "pup_open_window", &body) {+ Ok(_) => {+ std::thread::sleep(Duration::from_millis(1200));+ let _ = bridge(&thread, "desktop_set_window_state", &json!({ "titleContains": "DS2SF", "state": "maximize" }));+ ok(format!("dashboard open in pup (session adom-ds2sf, background, maximized): {url}"));+ 0+ }+ Err(e) => { err(format!("pup_open_window failed: {e}")); hint("adom-bridge --ai-thread \"<name>\" pup_readiness to see whether the desktop bridge is up"); 1 }+ }+ }+ "hbw" => {+ let r = server::post_json_host("host.docker.internal", 47084, "/hdbw/open", &json!({ "url": url }));+ match r {+ Some(_) => { ok(format!("dashboard open in Hydrogen browser window: {url}")); 0 }+ None => { err("Hydrogen control port did not answer (hbw needs Adom Hydrogen)"); hint("adom-ds2sf show --surface wv"); 1 }+ }+ }+ "nb" => {+ match bridge(&thread, "nbrowser_open_tab", &json!({ "url": url, "background": settings.get("open_in_background").and_then(|b| b.as_bool()).unwrap_or(true) })) {+ Ok(_) => { ok(format!("dashboard open in your signed-in browser: {url}")); 0 }+ Err(e) => { err(format!("native browser open failed: {e}")); hint(format!("open {url} yourself, or `show --surface pup`")); 1 }+ }+ }+ other => {+ err(format!("unknown surface {other:?}"));+ hint("valid: wv (Hydrogen webview tab), pup (AI's Chrome on the desktop), hbw (Hydrogen browser window), nb (your signed-in browser)");+ 2+ }+ }+}++pub fn ls() -> i32 {+ let rows = server::list_instances();+ if rows.is_empty() {+ ok("no adom-ds2sf instances running");+ hint("adom-ds2sf --ai-thread \"<name>\" show");+ return 0;+ }+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);+ println!("{:<9}{:<7}{:<28}{:<10}{:<8}url", "pid", "port", "thread", "version", "idle");+ let mut drift = false;+ for r in &rows {+ let v = r.get("version").and_then(|x| x.as_str()).unwrap_or("?");+ let last = r.get("lastActivity").and_then(|x| x.as_u64()).unwrap_or(now);+ let idle = now.saturating_sub(last);+ let idle_s = if idle < 3600 { format!("{}m", idle / 60) } else { format!("{:.1}h", idle as f64 / 3600.0) };+ println!("{:<9}{:<7}{:<28}{:<10}{:<8}{}",+ r.get("pid").and_then(|x| x.as_u64()).unwrap_or(0),+ r.get("port").and_then(|x| x.as_u64()).unwrap_or(0),+ r.get("thread").and_then(|x| x.as_str()).unwrap_or("?"),+ v, idle_s,+ r.get("proxyUrl").and_then(|x| x.as_str()).unwrap_or(""));+ if v != VERSION {+ drift = true;+ crate::io::warn(format!("port {} runs {v}, disk has {VERSION}. Shut it down and respawn: adom-ds2sf --ai-thread \"<name>\" shutdown --port {} --reason \"stale version after update\"",+ r.get("port").and_then(|x| x.as_u64()).unwrap_or(0), r.get("port").and_then(|x| x.as_u64()).unwrap_or(0)));+ }+ }+ if drift { 1 } else { 0 }+}++fn need_server(port: u16) -> Result<(), i32> {+ if server::probe(port).is_none() {+ err(format!("no {APP} dashboard answering on port {port}"));+ hint(format!("adom-ds2sf --ai-thread \"<name>\" show (starts it and opens the tab), or `adom-ds2sf ls`"));+ return Err(1);+ }+ Ok(())+}++fn report(r: Option<Value>) -> i32 {+ match r {+ Some(v) if v.get("ok").and_then(|o| o.as_bool()).unwrap_or(true) => {+ ok(v.to_string());+ 0+ }+ Some(v) => {+ err(v.get("error").and_then(|e| e.as_str()).unwrap_or("request refused"));+ if let Some(h) = v.get("hint").and_then(|h| h.as_str()) {+ hint(h);+ }+ 1+ }+ None => { err("no response from the dashboard"); 1 }+ }+}++pub fn ui(ai_thread: Option<String>, op: crate::cli::UiOp, port_s: &str) -> i32 {+ use crate::cli::UiOp;+ let port = parse_port(port_s);+ if let Err(c) = need_server(port) { return c; }+ // Read-only verbs never need identity.+ match &op {+ UiOp::State => return report(server::get_json(port, "/state")),+ UiOp::Console => {+ return match server::get_json(port, "/console") {+ Some(v) => { for l in v.get("lines").and_then(|l| l.as_array()).cloned().unwrap_or_default() { println!("{}", l.as_str().unwrap_or("")); } 0 }+ None => { err("no response"); 1 }+ }+ }+ UiOp::Log => {+ return match server::get_json(port, "/log") {+ Some(v) => { for l in v.get("lines").and_then(|l| l.as_array()).cloned().unwrap_or_default() { println!("{}", l.as_str().unwrap_or("")); } if let Some(j) = v.get("job").filter(|j| !j.is_null()) { note(format!("running: {j}")); } 0 }+ None => { err("no response"); 1 }+ }+ }+ _ => {}+ }+ let thread = match require_thread(ai_thread, "ui <verb>") { Ok(t) => t, Err(c) => return c };+ let (path, body) = match op {+ UiOp::Toast { text, kind, sticky } => ("/ui/toast", json!({ "text": text, "kind": kind, "sticky": sticky })),+ UiOp::Click { selector, label } => ("/ui/click", json!({ "selector": selector, "label": label })),+ UiOp::Reveal { selector, label } => ("/ui/reveal", json!({ "selector": selector, "label": label })),+ UiOp::Cursor { selector, label } => ("/ui/cursor", json!({ "selector": selector, "label": label })),+ UiOp::Tab { name } => ("/ui/tab", json!({ "tab": name })),+ UiOp::Reload => ("/ui/reload", json!({})),+ UiOp::Eval { js } => ("/ui/eval", json!({ "js": js })),+ UiOp::Select { mpn } => ("/select", json!({ "mpn": mpn })),+ UiOp::Extract { mpn, force, pdf, model, symbol_only, footprint_only } => ("/extract", json!({+ "mpn": mpn, "force": force, "pdf": pdf, "model": model, "symbolOnly": symbol_only, "footprintOnly": footprint_only })),+ UiOp::State | UiOp::Console | UiOp::Log => unreachable!(),+ };+ let mut body = body;+ body["aiThread"] = json!(thread);+ report(server::post_json(port, path, &body))+}++pub fn settings(ai_thread: Option<String>, op: crate::cli::SettingsOp, port_s: &str) -> i32 {+ use crate::cli::SettingsOp;+ let port = parse_port(port_s);+ match op {+ SettingsOp::Get => {+ // Works with or without a running server (reads the same file).+ match server::get_json(port, "/settings") {+ Some(v) => { println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()); 0 }+ None => { println!("{}", serde_json::to_string_pretty(&json!({ "settings": server::settings(), "version": VERSION, "_note": "no server running; showing the on-disk file" })).unwrap_or_default()); 0 }+ }+ }+ SettingsOp::Set { key, value } => {+ let thread = match require_thread(ai_thread, "settings set <key> <value>") { Ok(t) => t, Err(c) => return c };+ let v: Value = serde_json::from_str(&value).unwrap_or(Value::String(value.clone()));+ if let Err(c) = need_server(port) { return c; }+ report(server::post_json(port, "/settings", &json!({ key: v, "aiThread": thread })))+ }+ }+}++pub fn shutdown(ai_thread: Option<String>, reason: Option<String>, port_s: &str) -> i32 {+ let thread = match require_thread(ai_thread, "shutdown") { Ok(t) => t, Err(c) => return c };+ let port = parse_port(port_s);+ if let Err(c) = need_server(port) { return c; }+ let r = server::post_json(port, "/shutdown", &json!({ "aiThread": thread, "reason": reason.unwrap_or_default() }));+ report(r)+}
src/main.rs+2@@ -1,6 +1,7 @@ use clap::Parser; mod cli;+mod dashcli; mod context; mod emit; mod extract;@@ -8,6 +9,7 @@ mod fpsvg; mod io; mod normalize; mod result;+mod server; fn main() { let cli = cli::Cli::parse();
src/normalize.rs+19−1@@ -199,10 +199,28 @@ fn parse_lqfp(upper: &str) -> Option<(u32, String)> { return None; }; let pin_count = find_after(upper, key)?;- let body = parse_body_dims(upper)?;+ // Datasheets and info.json usually say just "LQFP-64"; the JEDEC MS-026 body+ // for a 0.5 mm pitch LQFP follows from the pin count, so fall back to it.+ let body = parse_body_dims(upper).or_else(|| jedec_lqfp_body(pin_count).map(String::from))?; Some((pin_count, body)) } +fn jedec_lqfp_body(pins: u32) -> Option<&'static str> {+ Some(match pins {+ 32 => "7x7mm",+ 44 => "10x10mm",+ 48 => "7x7mm",+ 64 => "10x10mm",+ 80 => "12x12mm",+ 100 => "14x14mm",+ 128 => "14x14mm",+ 144 => "20x20mm",+ 176 => "24x24mm",+ 208 => "28x28mm",+ _ => return None,+ })+}+ fn parse_bga(upper: &str) -> Option<String> { let pin_count = find_after(upper, "BGA")?; Some(format!("BGA-{pin_count}"))
src/server.rsadded+1035@@ -0,0 +1,1035 @@+//! adom-ds2sf dashboard: the AI-drivable live app over a chip-fetcher library.+//!+//! GET / the dashboard UI+//! GET /events SSE live channel (state on connect, 15s heartbeat)+//! GET /state full dashboard state (library summary, current chip, running job)+//! GET /api/chips per-chip extraction status+//! GET /api/chip/<MPN>[/svg/<kind>|/pdf|/png]+//! POST /extract {mpn, force?, pdf?, model?, symbolOnly?, footprintOnly?, aiThread}+//! POST /select {mpn, aiThread}+//! POST /ui/toast {text, kind} POST /ui/click {selector} POST /ui/reveal {selector}+//! GET/POST /console, GET/POST /settings, GET /health, GET /api/status, POST /shutdown+//!+//! Lifecycle (app-creator-server-lifecycle): registry entry under+//! ~/.adom/instances/adom-ds2sf/<thread>.json, 24h idle reaper with a per-thread+//! snapshot, --keep-alive / --ttl overrides. Every state-changing POST needs an+//! ai-thread name (app-creator-ai-thread-name).++use serde_json::{json, Value};+use std::collections::VecDeque;+use std::io::Read;+use std::path::{Path, PathBuf};+use std::sync::mpsc::{channel, Sender};+use std::sync::Mutex;+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};+use tiny_http::{Header, Method, Request, Response, Server, StatusCode};++pub const APP: &str = "adom-ds2sf";+pub const VERSION: &str = env!("CARGO_PKG_VERSION");+pub const DEFAULT_PORT: u16 = 8791;+pub const WEBVIEW_TAB: &str = "DS2SF";+const APP_HTML: &str = include_str!("app.html");+const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#e6edf3" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 3.5h9l4 4V13"/><path d="M13 3.5v4h4"/><path d="M7 8.5h3M7 11.5h5"/><rect x="12" y="14" width="8" height="7" rx="1"/><path d="M14 14v-2M18 14v-2M14 21v1.5M18 21v1.5M12 16.5h-2M12 19h-2"/></svg>"##;++// ───────────────────────── state ─────────────────────────++#[derive(Clone, Default)]+pub struct Job {+ pub mpn: String,+ pub started: u64,+ pub stage: String,+ pub args: Vec<String>,+ pub ai_thread: String,+}++#[derive(Default)]+struct Dash {+ current: String,+ job: Option<Job>,+ last_job: Option<Value>,+ log: VecDeque<String>,+ console: Vec<String>,+ /// Threads that touched this instance, most recent first.+ threads: Vec<String>,+}++static DASH: Mutex<Option<Dash>> = Mutex::new(None);+static CLIENTS: Mutex<Vec<Sender<Vec<u8>>>> = Mutex::new(Vec::new());+static LAST_ACTIVITY: Mutex<Option<Instant>> = Mutex::new(None);+static OWNER: Mutex<Option<(String, u16)>> = Mutex::new(None);+static SETTINGS: Mutex<Option<Value>> = Mutex::new(None);+/// Recent UI directives with a sequence number, so a page that only polls+/// (the cloud proxy buffers SSE) still executes click/tab/toast/reveal.+static UI_EVENTS: Mutex<VecDeque<(u64, String, Value)>> = Mutex::new(VecDeque::new());+static UI_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);++fn dash<R>(f: impl FnOnce(&mut Dash) -> R) -> R {+ let mut g = DASH.lock().unwrap();+ if g.is_none() {+ *g = Some(Dash::default());+ }+ f(g.as_mut().unwrap())+}++fn touch() {+ *LAST_ACTIVITY.lock().unwrap() = Some(Instant::now());+}++fn now_unix() -> u64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)+}++// ───────────────────────── settings ─────────────────────────++fn settings_path() -> PathBuf {+ let home = std::env::var("HOME").unwrap_or_default();+ Path::new(&home).join(".config/adom-ds2sf/settings.json")+}++fn default_settings() -> Value {+ json!({+ "ttl_hours": 24,+ "default_surface": "wv",+ "open_in_background": true,+ "default_model": "claude-opus-4-7",+ "dev_mode": false,+ "library_root": Value::Null,+ })+}++fn settings_enums() -> Value {+ json!({+ "ttl_hours": {"type": "number", "min": 1, "max": 720},+ "default_surface": {"type": "enum", "values": ["wv", "pup", "hbw", "nb"]},+ "open_in_background": {"type": "bool"},+ "default_model": {"type": "enum", "values": ["claude-opus-4-7", "claude-sonnet-4-5", "claude-haiku-4-5"]},+ "dev_mode": {"type": "bool"},+ "library_root": {"type": "path"},+ })+}++pub fn settings() -> Value {+ let mut g = SETTINGS.lock().unwrap();+ if g.is_none() {+ let mut s = default_settings();+ if let Ok(raw) = std::fs::read_to_string(settings_path()) {+ if let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&raw) {+ for (k, v) in saved {+ s[k] = v;+ }+ }+ }+ *g = Some(s);+ }+ g.clone().unwrap()+}++fn save_settings(s: &Value) {+ if let Some(p) = settings_path().parent() {+ let _ = std::fs::create_dir_all(p);+ }+ let _ = std::fs::write(settings_path(), serde_json::to_string_pretty(s).unwrap_or_default());+ *SETTINGS.lock().unwrap() = Some(s.clone());+}++// ───────────────────────── library ─────────────────────────++pub fn library_root() -> Option<PathBuf> {+ if let Some(r) = settings().get("library_root").and_then(|v| v.as_str()) {+ if !r.is_empty() && Path::new(r).is_dir() {+ return Some(PathBuf::from(r));+ }+ }+ let home = std::env::var("HOME").unwrap_or_default();+ for c in [+ format!("{home}/project/chip-fetcher/library"),+ format!("{home}/project/adom-chip-fetcher/library"),+ "chip-fetcher/library".to_string(),+ ] {+ if Path::new(&c).is_dir() {+ return Some(PathBuf::from(c));+ }+ }+ None+}++fn read_json(p: &Path) -> Value {+ std::fs::read_to_string(p)+ .ok()+ .and_then(|s| serde_json::from_str::<Value>(&s).ok())+ .unwrap_or(Value::Null)+}++fn mtime(p: &Path) -> u64 {+ std::fs::metadata(p)+ .and_then(|m| m.modified())+ .ok()+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())+ .map(|d| d.as_secs())+ .unwrap_or(0)+}++fn pdfs_in(dir: &Path) -> Vec<String> {+ let mut v: Vec<String> = std::fs::read_dir(dir)+ .map(|rd| {+ rd.flatten()+ .filter(|e| e.path().extension().map(|x| x.eq_ignore_ascii_case("pdf")).unwrap_or(false))+ .map(|e| e.file_name().to_string_lossy().to_string())+ .collect()+ })+ .unwrap_or_default();+ v.sort();+ v+}++/// One row of the library rail: everything the UI needs without opening the big JSONs.+fn chip_summary(dir: &Path) -> Value {+ let mpn = dir.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();+ let f = |suffix: &str| dir.join(format!("{mpn}{suffix}"));+ let result = read_json(&f("-extraction.result.json"));+ let symbol = read_json(&f("-symbol.extracted.json"));+ let validation = read_json(&f("-validation-status.json"));+ let info = read_json(&dir.join("info.json"));+ let pdfs = pdfs_in(dir);+ let has_pdf = f(".pdf").is_file();+ let status = match result.get("status").and_then(|s| s.as_str()) {+ Some(s) => s.to_string(),+ None if has_pdf || !pdfs.is_empty() => "not_extracted".to_string(),+ None => "no_datasheet".to_string(),+ };+ let pins = symbol.get("pins").and_then(|p| p.as_array()).map(|a| a.len()).unwrap_or(0);+ let package = symbol.get("package").cloned()+ .or_else(|| info.get("package").cloned())+ .unwrap_or(Value::Null);+ let manufacturer = symbol.get("manufacturer").cloned()+ .or_else(|| info.get("manufacturer").cloned())+ .unwrap_or(Value::Null);+ let has_3d = f("-3d-iso-named.png").is_file() || f("-3d-iso.png").is_file();+ let running = dash(|d| d.job.as_ref().map(|j| j.mpn == mpn).unwrap_or(false));+ json!({+ "mpn": mpn,+ "status": status,+ "running": running,+ "summary": result.get("summary").cloned().unwrap_or(Value::Null),+ "review_count": result.get("review_required").and_then(|r| r.as_array()).map(|a| a.len()).unwrap_or(0),+ "hint_count": result.get("hints").and_then(|r| r.as_array()).map(|a| a.len()).unwrap_or(0),+ "extractor_version": result.get("extractor_version").cloned().unwrap_or(Value::Null),+ "model": result.get("claude_model").cloned().unwrap_or(Value::Null),+ "extracted_at": mtime(&f("-extraction.result.json")),+ "pins": pins,+ "package": package,+ "manufacturer": manufacturer,+ "concur": validation.get("concur_status").cloned().unwrap_or(Value::Null),+ "has_pdf": has_pdf,+ "pdfs": pdfs,+ "has_symbol": f("-symbol.extracted.json").is_file(),+ "has_footprint": f("-footprint.extracted.json").is_file(),+ "has_provenance": f("-extraction.provenance.json").is_file(),+ "has_3d": has_3d,+ "svgs": {+ "ds2sf": f("-footprint.ds2sf.svg").is_file(),+ "pcbnew": f("-footprint.pcbnew.svg").is_file(),+ "symbol": f("-symbol.ds2sf.svg").is_file(),+ },+ })+}++fn list_chips() -> Vec<Value> {+ let root = match library_root() {+ Some(r) => r,+ None => return vec![],+ };+ let mut dirs: Vec<PathBuf> = std::fs::read_dir(&root)+ .map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect())+ .unwrap_or_default();+ dirs.sort_by_key(|p| p.file_name().map(|s| s.to_string_lossy().to_lowercase()));+ dirs.iter().map(|d| chip_summary(d)).collect()+}++fn safe_mpn(mpn: &str) -> bool {+ !mpn.is_empty() && !mpn.contains('/') && !mpn.contains('\\') && !mpn.starts_with('.')+}++fn chip_dir(mpn: &str) -> Option<PathBuf> {+ if !safe_mpn(mpn) {+ return None;+ }+ let d = library_root()?.join(mpn);+ if d.is_dir() { Some(d) } else { None }+}++fn chip_detail(mpn: &str) -> Value {+ let dir = match chip_dir(mpn) {+ Some(d) => d,+ None => return Value::Null,+ };+ let f = |suffix: &str| dir.join(format!("{mpn}{suffix}"));+ let mut cache: Vec<String> = std::fs::read_dir(dir.join(".ds2sf-cache"))+ .map(|rd| rd.flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect())+ .unwrap_or_default();+ cache.sort();+ json!({+ "summary": chip_summary(&dir),+ "dir": dir.to_string_lossy(),+ "result": read_json(&f("-extraction.result.json")),+ "symbol": read_json(&f("-symbol.extracted.json")),+ "footprint": read_json(&f("-footprint.extracted.json")),+ "provenance": read_json(&f("-extraction.provenance.json")),+ "validation": read_json(&f("-validation-status.json")),+ "concur": read_json(&f("-concur.result.json")),+ "info": read_json(&dir.join("info.json")),+ "cache_files": cache,+ })+}++// ───────────────────────── SSE ─────────────────────────++struct ChanReader {+ rx: std::sync::mpsc::Receiver<Vec<u8>>,+ buf: Vec<u8>,+ pos: usize,+}++impl Read for ChanReader {+ fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {+ if self.pos >= self.buf.len() {+ match self.rx.recv() {+ Ok(b) => {+ self.buf = b;+ self.pos = 0;+ }+ Err(_) => return Ok(0),+ }+ }+ let n = out.len().min(self.buf.len() - self.pos);+ out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);+ self.pos += n;+ Ok(n)+ }+}++/// tiny_http sits on a 1 KB BufWriter, so every SSE frame is padded past it+/// with a comment line: a write >= the buffer size goes straight to the socket.+fn sse_frame(event: &str, data: &Value) -> Vec<u8> {+ let mut s = format!("event: {event}\ndata: {}\n\n", data);+ if s.len() < 1200 {+ let pad = 1200 - s.len();+ s.push_str(": ");+ s.push_str(&" ".repeat(pad));+ s.push_str("\n\n");+ }+ s.into_bytes()+}++pub fn broadcast(event: &str, data: Value) {+ if matches!(event, "toast" | "click" | "reveal" | "cursor" | "tab" | "reload" | "eval" | "chip") {+ let seq = UI_SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let mut q = UI_EVENTS.lock().unwrap();+ q.push_back((seq, event.to_string(), data.clone()));+ while q.len() > 50 {+ q.pop_front();+ }+ }+ let frame = sse_frame(event, &data);+ let mut clients = CLIENTS.lock().unwrap();+ clients.retain(|tx| tx.send(frame.clone()).is_ok());+}++fn broadcast_state() {+ broadcast("state", state_json());+}++fn push_log(line: String) {+ let line = crate::io::strip_ansi(&line);+ dash(|d| {+ d.log.push_back(line.clone());+ while d.log.len() > 600 {+ d.log.pop_front();+ }+ if let Some(j) = d.job.as_mut() {+ let l = line.trim();+ let stage = if l.starts_with("[1a]") {+ Some("symbol pass (Claude reading the pinout)")+ } else if l.starts_with("[1b]") {+ Some("footprint pass (Claude reading the package drawing)")+ } else if l.starts_with("[svg]") {+ Some("rendering footprint SVG")+ } else if l.starts_with("[normalize]") || l.contains("service-kicad") {+ Some("normalizing package against the KiCad stdlib")+ } else if l.starts_with("OK:") || l.starts_with("ERROR:") {+ Some("writing outputs")+ } else {+ None+ };+ if let Some(s) = stage {+ j.stage = s.to_string();+ }+ }+ });+ broadcast("log", json!({ "line": line }));+}++// ───────────────────────── extraction job ─────────────────────────++fn start_job(body: &Value, ai_thread: &str) -> Result<Value, (u16, Value)> {+ let mpn = body.get("mpn").and_then(|m| m.as_str()).unwrap_or("").to_string();+ let dir = chip_dir(&mpn).ok_or_else(|| {+ (404, json!({ "ok": false, "errorCode": "chip_not_found",+ "error": format!("no chip directory for {mpn:?} in the library"),+ "hint": "Land it first with `adom-chip-fetcher fetch <MPN>`, then extract." }))+ })?;+ if let Some(j) = dash(|d| d.job.clone()) {+ return Err((409, json!({ "ok": false, "errorCode": "job_running",+ "error": format!("an extraction is already running for {}", j.mpn),+ "hint": "Wait for it to finish (watch GET /state .job) or open the Log tab. One Claude extraction at a time keeps the datasheet reads honest." })));+ }+ let model = body.get("model").and_then(|m| m.as_str())+ .map(String::from)+ .unwrap_or_else(|| settings().get("default_model").and_then(|m| m.as_str()).unwrap_or("claude-opus-4-7").to_string());+ let mut args: Vec<String> = vec!["extract".into(), dir.to_string_lossy().to_string(), "--model".into(), model.clone()];+ if let Some(p) = body.get("pdf").and_then(|p| p.as_str()).filter(|p| !p.is_empty()) {+ let pdf = if p.contains('/') { PathBuf::from(p) } else { dir.join(p) };+ if !pdf.is_file() {+ return Err((404, json!({ "ok": false, "errorCode": "pdf_not_found",+ "error": format!("{} is not a file", pdf.display()),+ "hint": "Pick one of GET /api/chip/<MPN> .summary.pdfs, or fetch a datasheet with `adom-chip-fetcher pup-pdf-fetch <MPN> --pdf-url <url>`." })));+ }+ args.push("--pdf".into());+ args.push(pdf.to_string_lossy().to_string());+ } else if !dir.join(format!("{mpn}.pdf")).is_file() {+ let pdfs = pdfs_in(&dir);+ if let Some(first) = pdfs.first() {+ args.push("--pdf".into());+ args.push(dir.join(first).to_string_lossy().to_string());+ } else {+ return Err((422, json!({ "ok": false, "errorCode": "no_datasheet",+ "error": format!("{mpn} has no datasheet PDF in its chip directory"),+ "hint": format!("Fetch one first: `adom-chip-fetcher --ai-thread \"{ai_thread}\" pup-pdf-fetch {mpn} --pdf-url <manufacturer PDF url>`, then POST /extract again.") })));+ }+ }+ if body.get("force").and_then(|f| f.as_bool()).unwrap_or(false) {+ args.push("--force".into());+ }+ if body.get("symbolOnly").and_then(|f| f.as_bool()).unwrap_or(false) {+ args.push("--symbol-only".into());+ }+ if body.get("footprintOnly").and_then(|f| f.as_bool()).unwrap_or(false) {+ args.push("--footprint-only".into());+ }+ let job = Job { mpn: mpn.clone(), started: now_unix(), stage: "starting".into(), args: args.clone(), ai_thread: ai_thread.to_string() };+ dash(|d| {+ d.job = Some(job.clone());+ d.log.clear();+ d.current = mpn.clone();+ });+ push_log(format!("thread \"{ai_thread}\": adom-ds2sf {}", args.join(" ")));+ let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("adom-ds2sf"));+ std::thread::spawn(move || run_job(exe, args, mpn));+ broadcast_state();+ broadcast("toast", json!({ "text": format!("Extraction started for {}", job.mpn), "kind": "info" }));+ Ok(json!({ "ok": true, "job": job_json(&job) }))+}++fn run_job(exe: PathBuf, args: Vec<String>, mpn: String) {+ use std::io::BufRead;+ use std::process::{Command, Stdio};+ let child = Command::new(&exe)+ .args(&args)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn();+ let exit = match child {+ Ok(mut ch) => {+ let out = ch.stdout.take();+ let err = ch.stderr.take();+ let t1 = std::thread::spawn(move || {+ if let Some(o) = out {+ for l in std::io::BufReader::new(o).lines().flatten() {+ push_log(l);+ }+ }+ });+ let t2 = std::thread::spawn(move || {+ if let Some(e) = err {+ for l in std::io::BufReader::new(e).lines().flatten() {+ push_log(l);+ }+ }+ });+ let st = ch.wait().ok().and_then(|s| s.code()).unwrap_or(-1);+ let _ = t1.join();+ let _ = t2.join();+ st+ }+ Err(e) => {+ push_log(format!("ERROR: could not spawn {}: {e}", exe.display()));+ -1+ }+ };+ let dir = chip_dir(&mpn);+ let result = dir.map(|d| read_json(&d.join(format!("{mpn}-extraction.result.json")))).unwrap_or(Value::Null);+ let status = result.get("status").and_then(|s| s.as_str()).unwrap_or(if exit == 0 { "ok" } else { "unrecoverable" }).to_string();+ let summary = result.get("summary").and_then(|s| s.as_str()).unwrap_or("").to_string();+ dash(|d| {+ d.job = None;+ d.last_job = Some(json!({ "mpn": mpn, "exit": exit, "status": status, "summary": summary, "finished": now_unix() }));+ });+ push_log(format!("[done] exit {exit} status {status}"));+ let kind = match status.as_str() { "ok" => "success", "needs_better_pdf" => "info", _ => "error" };+ let text = match status.as_str() {+ "ok" => format!("{mpn}: extraction complete"),+ "needs_better_pdf" => format!("{mpn}: needs a better datasheet PDF"),+ _ => format!("{mpn}: extraction failed (exit {exit})"),+ };+ broadcast("toast", json!({ "text": text, "kind": kind, "sticky": kind == "error" }));+ broadcast_state();+ broadcast("chip", json!({ "mpn": mpn }));+ touch();+}++fn job_json(j: &Job) -> Value {+ json!({ "mpn": j.mpn, "started": j.started, "elapsed": now_unix().saturating_sub(j.started),+ "stage": j.stage, "args": j.args, "aiThread": j.ai_thread })+}++// ───────────────────────── state ─────────────────────────++fn state_json() -> Value {+ let chips = list_chips();+ let counts = |s: &str| chips.iter().filter(|c| c.get("status").and_then(|x| x.as_str()) == Some(s)).count();+ let (cur, job, last_job, threads) = dash(|d| (d.current.clone(), d.job.clone(), d.last_job.clone(), d.threads.clone()));+ let (thread, port) = OWNER.lock().unwrap().clone().unwrap_or_default();+ json!({+ "app": APP,+ "version": VERSION,+ "port": port,+ "thread": thread,+ "threads": threads,+ "library_root": library_root().map(|p| p.to_string_lossy().to_string()),+ "counts": {+ "total": chips.len(),+ "ok": counts("ok"),+ "needs_better_pdf": counts("needs_better_pdf"),+ "unrecoverable": counts("unrecoverable"),+ "not_extracted": counts("not_extracted"),+ "no_datasheet": counts("no_datasheet"),+ },+ "chips": chips,+ "current": cur,+ "job": job.as_ref().map(job_json),+ "last_job": last_job,+ "settings": settings(),+ "proxy_url": proxy_url_for_port(port),+ "log_len": dash(|d| d.log.len()),+ "ui": UI_EVENTS.lock().unwrap().iter().map(|(seq, ev, data)| json!({ "seq": seq, "event": ev, "data": data })).collect::<Vec<_>>(),+ "_hint": "POST /extract {mpn, force?, pdf?, model?, symbolOnly?, footprintOnly?, aiThread} runs the extractor; POST /select {mpn, aiThread} focuses a chip; POST /ui/toast {text, kind} narrates; GET /events is the SSE channel; GET /console reads the UI log.",+ })+}++// ───────────────────────── URLs, registry, lifecycle ─────────────────────────++pub fn proxy_url_for_port(port: u16) -> String {+ if let Ok(host) = std::env::var("ADOM_PROXY_HOST") {+ return format!("https://{host}/proxy/{port}/");+ }+ if let Ok(slug) = std::env::var("ADOM_CONTAINER_SLUG") {+ return format!("https://{slug}.adom.cloud/proxy/{port}/");+ }+ if let Ok(tpl) = std::env::var("VSCODE_PROXY_URI") {+ if tpl.contains("{{port}}") {+ return tpl.replace("{{port}}", &port.to_string());+ }+ }+ format!("http://127.0.0.1:{port}/")+}++pub fn direct_url(port: u16) -> String {+ format!("http://127.0.0.1:{port}/")+}++pub fn slugify(s: &str) -> String {+ let mut out = String::new();+ for c in s.chars() {+ if c.is_ascii_alphanumeric() {+ out.push(c.to_ascii_lowercase());+ } else if !out.ends_with('-') {+ out.push('-');+ }+ }+ let t = out.trim_matches('-').to_string();+ if t.is_empty() { "anonymous".into() } else { t }+}++pub fn instances_dir() -> PathBuf {+ let home = std::env::var("HOME").unwrap_or_default();+ Path::new(&home).join(".adom/instances").join(APP)+}++fn registry_path(thread: &str) -> PathBuf {+ instances_dir().join(format!("{}.json", slugify(thread)))+}++fn write_registry(thread: &str, port: u16, started: u64) {+ let _ = std::fs::create_dir_all(instances_dir());+ let entry = json!({+ "pid": std::process::id(), "port": port, "thread": thread, "app": APP,+ "version": VERSION, "startedAt": started, "lastActivity": now_unix(),+ "url": direct_url(port), "proxyUrl": proxy_url_for_port(port),+ });+ let _ = std::fs::write(registry_path(thread), serde_json::to_string_pretty(&entry).unwrap_or_default());+}++fn snapshot(thread: &str) {+ let dir = instances_dir().join("snapshots");+ let _ = std::fs::create_dir_all(&dir);+ let (cur, log) = dash(|d| (d.current.clone(), d.log.iter().cloned().collect::<Vec<_>>()));+ let snap = json!({ "thread": thread, "current": cur, "log": log, "savedAt": now_unix() });+ let _ = std::fs::write(dir.join(format!("{}.json", slugify(thread))), serde_json::to_string_pretty(&snap).unwrap_or_default());+}++fn restore_snapshot(thread: &str) -> bool {+ let p = instances_dir().join("snapshots").join(format!("{}.json", slugify(thread)));+ let v = read_json(&p);+ if v.is_null() {+ return false;+ }+ dash(|d| {+ d.current = v.get("current").and_then(|c| c.as_str()).unwrap_or("").to_string();+ if let Some(lines) = v.get("log").and_then(|l| l.as_array()) {+ d.log = lines.iter().filter_map(|l| l.as_str().map(String::from)).collect();+ }+ });+ true+}++/// Registry rows with liveness (dead pids pruned), for `adom-ds2sf ls`.+pub fn list_instances() -> Vec<Value> {+ let mut out = Vec::new();+ if let Ok(rd) = std::fs::read_dir(instances_dir()) {+ for e in rd.flatten() {+ let p = e.path();+ if p.extension().map(|x| x == "json").unwrap_or(false) {+ let v = read_json(&p);+ let pid = v.get("pid").and_then(|x| x.as_u64()).unwrap_or(0);+ let alive = pid > 0 && Path::new(&format!("/proc/{pid}")).exists();+ if alive {+ out.push(v);+ } else {+ let _ = std::fs::remove_file(&p);+ }+ }+ }+ }+ out+}++pub fn remove_webview_tab() {+ let _ = std::process::Command::new("timeout")+ .args(["10", "adom-cli", "hydrogen", "workspace", "remove-tab", "--name", WEBVIEW_TAB])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status();+}++fn shutdown_sequence(thread: &str, reason: &str) -> ! {+ eprintln!("[adom-ds2sf] shutting down ({reason})");+ snapshot(thread);+ let _ = std::fs::remove_file(registry_path(thread));+ remove_webview_tab();+ std::process::exit(0)+}++/// Probe a port: Some(version) when an adom-ds2sf answers /health there.+pub fn probe(port: u16) -> Option<Value> {+ use std::io::Write;+ use std::net::TcpStream;+ let addr = format!("127.0.0.1:{port}");+ let mut s = TcpStream::connect_timeout(&addr.parse().ok()?, Duration::from_millis(600)).ok()?;+ let _ = s.set_read_timeout(Some(Duration::from_millis(1500)));+ let _ = s.write_all(format!("GET /health HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes());+ let mut buf = String::new();+ let _ = s.read_to_string(&mut buf);+ let body = buf.split("\r\n\r\n").nth(1)?;+ let v: Value = serde_json::from_str(body.trim()).ok()?;+ if v.get("app").and_then(|a| a.as_str()) == Some(APP) { Some(v) } else { None }+}++pub fn post_json(port: u16, path: &str, body: &Value) -> Option<Value> {+ use std::io::Write;+ use std::net::TcpStream;+ let addr = format!("127.0.0.1:{port}");+ let mut s = TcpStream::connect_timeout(&addr.parse().ok()?, Duration::from_millis(800)).ok()?;+ let _ = s.set_read_timeout(Some(Duration::from_secs(10)));+ let b = body.to_string();+ let _ = s.write_all(format!("POST {path} HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", b.len(), b).as_bytes());+ let mut buf = String::new();+ let _ = s.read_to_string(&mut buf);+ let body = buf.split("\r\n\r\n").nth(1)?;+ serde_json::from_str(body.trim()).ok()+}++pub fn post_json_host(host: &str, port: u16, path: &str, body: &Value) -> Option<Value> {+ use std::io::Write;+ use std::net::{TcpStream, ToSocketAddrs};+ let addr = (host, port).to_socket_addrs().ok()?.next()?;+ let mut s = TcpStream::connect_timeout(&addr, Duration::from_millis(800)).ok()?;+ let _ = s.set_read_timeout(Some(Duration::from_secs(10)));+ let b = body.to_string();+ let _ = s.write_all(format!("POST {path} HTTP/1.1\r\nHost: {host}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", b.len(), b).as_bytes());+ let mut buf = String::new();+ let _ = s.read_to_string(&mut buf);+ let body = buf.split("\r\n\r\n").nth(1)?;+ Some(serde_json::from_str(body.trim()).unwrap_or(json!({ "raw": body })))+}++pub fn get_json(port: u16, path: &str) -> Option<Value> {+ use std::io::Write;+ use std::net::TcpStream;+ let addr = format!("127.0.0.1:{port}");+ let mut s = TcpStream::connect_timeout(&addr.parse().ok()?, Duration::from_millis(800)).ok()?;+ let _ = s.set_read_timeout(Some(Duration::from_secs(10)));+ let _ = s.write_all(format!("GET {path} HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes());+ let mut buf = String::new();+ let _ = s.read_to_string(&mut buf);+ let body = buf.split("\r\n\r\n").nth(1)?;+ serde_json::from_str(body.trim()).ok()+}++pub fn free_port() -> u16 {+ std::net::TcpListener::bind("127.0.0.1:0").ok().and_then(|l| l.local_addr().ok()).map(|a| a.port()).unwrap_or(DEFAULT_PORT)+}++// ───────────────────────── server ─────────────────────────++pub struct ServeOpts {+ pub port: u16,+ pub ai_thread: String,+ pub keep_alive: bool,+ pub ttl_hours: Option<f64>,+}++pub fn run(opts: ServeOpts) -> anyhow::Result<()> {+ let port = opts.port;+ let server = Server::http(format!("0.0.0.0:{port}")).map_err(|e| anyhow::anyhow!("bind {port}: {e}"))?;+ let started = now_unix();+ *OWNER.lock().unwrap() = Some((opts.ai_thread.clone(), port));+ touch();+ dash(|d| d.threads.insert(0, opts.ai_thread.clone()));+ if restore_snapshot(&opts.ai_thread) {+ eprintln!("[adom-ds2sf] restored snapshot for thread \"{}\"", opts.ai_thread);+ }+ write_registry(&opts.ai_thread, port, started);+ eprintln!("[adom-ds2sf] v{VERSION} serving on {} (thread \"{}\")", direct_url(port), opts.ai_thread);++ // Heartbeat + reaper + registry refresh.+ let ttl_h = opts.ttl_hours.unwrap_or_else(|| settings().get("ttl_hours").and_then(|t| t.as_f64()).unwrap_or(24.0));+ let keep_alive = opts.keep_alive;+ let thread = opts.ai_thread.clone();+ std::thread::spawn(move || {+ let mut tick = 0u64;+ loop {+ std::thread::sleep(Duration::from_secs(15));+ {+ let mut clients = CLIENTS.lock().unwrap();+ clients.retain(|tx| tx.send(b": hb\n\n".to_vec()).is_ok());+ }+ tick += 1;+ if tick % 4 == 0 {+ write_registry(&thread, port, started);+ let idle = LAST_ACTIVITY.lock().unwrap().map(|t| t.elapsed()).unwrap_or_default();+ let busy = dash(|d| d.job.is_some());+ if !keep_alive && !busy && idle > Duration::from_secs_f64(ttl_h * 3600.0) {+ shutdown_sequence(&thread, &format!("idle for {:.1}h, ttl {ttl_h}h", idle.as_secs_f64() / 3600.0));+ }+ }+ }+ });++ for req in server.incoming_requests() {+ std::thread::spawn(move || handle(req));+ }+ Ok(())+}++fn handle(mut req: Request) {+ let full = req.url().to_string();+ let url = full.split('?').next().unwrap_or("/").to_string();+ let query = full.splitn(2, '?').nth(1).unwrap_or("").to_string();+ let method = req.method().clone();+ let mut body = String::new();+ if matches!(method, Method::Post) {+ let _ = req.as_reader().read_to_string(&mut body);+ }+ if url != "/events" && url != "/state" && url != "/health" && url != "/api/status" && url != "/console" {+ touch();+ }++ if matches!(method, Method::Options) {+ let _ = req.respond(cors(Response::from_string("").with_status_code(204)));+ return;+ }++ if url == "/events" && matches!(method, Method::Get) {+ let (tx, rx) = channel::<Vec<u8>>();+ let mut first = Vec::new();+ first.extend_from_slice(format!(":{}\n\n", " ".repeat(32768)).as_bytes());+ first.extend_from_slice(&sse_frame("state", &state_json()));+ let _ = tx.send(first);+ CLIENTS.lock().unwrap().push(tx);+ let reader = ChanReader { rx, buf: Vec::new(), pos: 0 };+ let resp = Response::new(+ StatusCode(200),+ vec![+ hdr("Content-Type", "text/event-stream"),+ hdr("Cache-Control", "no-cache"),+ hdr("X-Accel-Buffering", "no"),+ hdr("Access-Control-Allow-Origin", "*"),+ ],+ reader,+ None,+ None,+ );+ let _ = req.respond(resp);+ return;+ }++ let shutting_down = url == "/shutdown" && matches!(method, Method::Post);+ let (thread_for_exit, resp) = route(&method, &url, &query, &body);+ let _ = req.respond(resp);+ if shutting_down {+ if let Some(t) = thread_for_exit {+ std::thread::sleep(Duration::from_millis(150));+ shutdown_sequence(&t, "POST /shutdown");+ }+ }+}++type Resp = Response<std::io::Cursor<Vec<u8>>>;++fn ai_thread_of(body: &Value) -> Option<String> {+ body.get("aiThread").and_then(|t| t.as_str()).map(|s| s.trim().to_string()).filter(|s| !s.is_empty())+}++fn identity_refusal(verb: &str) -> Resp {+ json_status(400, &json!({+ "ok": false,+ "errorCode": "caller_identity_required",+ "error": "This app requires every AI caller to give its ai-thread name.",+ "hint": format!("Re-run with the global flag: adom-ds2sf --ai-thread \"<name>\" {verb}, or add a top-level \"aiThread\" field if you are POSTing directly. Pick a short name a HUMAN would recognize for THIS conversation (like 'ds2sf' or 'stm32 board review'), and reuse it on every call to every Adom tool."),+ }))+}++fn note_thread(t: &str, what: &str) {+ dash(|d| {+ d.threads.retain(|x| x != t);+ d.threads.insert(0, t.to_string());+ d.threads.truncate(12);+ d.console.push(format!("[thread] \"{t}\": {what}"));+ let n = d.console.len();+ if n > 500 {+ d.console.drain(0..n - 500);+ }+ });+}++fn route(method: &Method, url: &str, query: &str, body: &str) -> (Option<String>, Resp) {+ let v: Value = serde_json::from_str(body).unwrap_or(Value::Null);+ let r = match (method, url) {+ (Method::Get, "/") | (Method::Get, "/index.html") => html(APP_HTML),+ (Method::Get, "/favicon.svg") => Response::from_string(FAVICON).with_header(hdr("Content-Type", "image/svg+xml")),+ (Method::Get, "/health") | (Method::Get, "/api/status") => {+ let (thread, port) = OWNER.lock().unwrap().clone().unwrap_or_default();+ cors(json_ok(&json!({ "ok": true, "app": APP, "version": VERSION, "port": port, "thread": thread,+ "job": dash(|d| d.job.clone()).map(|j| job_json(&j)), "chips": list_chips().len() })))+ }+ (Method::Get, "/version") => json_ok(&json!({ "app": APP, "version": VERSION })),+ (Method::Get, "/state") => cors(json_ok(&state_json())),+ (Method::Get, "/api/chips") => cors(json_ok(&json!({ "chips": list_chips(), "current": dash(|d| d.current.clone()) }))),+ (Method::Get, "/settings") => json_ok(&json!({ "settings": settings(), "enums": settings_enums(), "version": VERSION })),+ (Method::Post, "/settings") => {+ let t = match ai_thread_of(&v) { Some(t) => t, None => return (None, identity_refusal("settings set <key> <value>")) };+ let mut s = settings();+ let enums = settings_enums();+ if let Some(obj) = v.as_object() {+ for (k, val) in obj {+ if k == "aiThread" { continue; }+ let spec = match enums.get(k) {+ Some(sp) => sp,+ None => return (None, json_status(400, &json!({ "ok": false, "errorCode": "unknown_setting",+ "error": format!("no setting named {k:?}"), "hint": format!("Valid keys: {}", enums.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>().join(", ")).unwrap_or_default()) }))),+ };+ let ok = match spec.get("type").and_then(|t| t.as_str()) {+ Some("bool") => val.is_boolean(),+ Some("number") => val.as_f64().map(|n| n >= spec["min"].as_f64().unwrap_or(0.0) && n <= spec["max"].as_f64().unwrap_or(1e9)).unwrap_or(false),+ Some("enum") => val.as_str().map(|s| spec["values"].as_array().map(|a| a.iter().any(|x| x.as_str() == Some(s))).unwrap_or(false)).unwrap_or(false),+ _ => val.is_string() || val.is_null(),+ };+ if !ok {+ return (None, json_status(400, &json!({ "ok": false, "errorCode": "invalid_setting_value",+ "error": format!("{k} cannot be {val}"), "hint": format!("Allowed: {spec}") })));+ }+ s[k] = val.clone();+ }+ }+ save_settings(&s);+ note_thread(&t, "settings updated");+ broadcast_state();+ json_ok(&json!({ "ok": true, "settings": s }))+ }+ (Method::Get, "/console") => json_ok(&json!({ "lines": dash(|d| d.console.clone()) })),+ (Method::Post, "/console") => {+ let line = format!("[{}] {}", v.get("level").and_then(|l| l.as_str()).unwrap_or("log"), v.get("msg").and_then(|m| m.as_str()).unwrap_or(""));+ dash(|d| {+ d.console.push(line);+ let n = d.console.len();+ if n > 500 { d.console.drain(0..n - 500); }+ });+ json_ok(&json!({ "ok": true }))+ }+ (Method::Get, "/log") => json_ok(&json!({ "lines": dash(|d| d.log.iter().cloned().collect::<Vec<_>>()), "job": dash(|d| d.job.clone()).map(|j| job_json(&j)) })),+ (Method::Post, "/select") => {+ let t = match ai_thread_of(&v) { Some(t) => t, None => return (None, identity_refusal("select <MPN>")) };+ let mpn = v.get("mpn").and_then(|m| m.as_str()).unwrap_or("").to_string();+ if chip_dir(&mpn).is_none() {+ return (None, json_status(404, &json!({ "ok": false, "errorCode": "chip_not_found", "error": format!("{mpn:?} is not in the library"), "hint": "GET /api/chips lists what is." })));+ }+ dash(|d| d.current = mpn.clone());+ note_thread(&t, &format!("select {mpn}"));+ broadcast_state();+ json_ok(&json!({ "ok": true, "current": mpn }))+ }+ (Method::Post, "/extract") => {+ let t = match ai_thread_of(&v) { Some(t) => t, None => return (None, identity_refusal("extract <MPN>")) };+ note_thread(&t, &format!("extract {}", v.get("mpn").and_then(|m| m.as_str()).unwrap_or("?")));+ match start_job(&v, &t) {+ Ok(j) => json_ok(&j),+ Err((code, e)) => json_status(code, &e),+ }+ }+ (Method::Post, "/ui/toast") => {+ let text = v.get("text").or(v.get("message")).and_then(|x| x.as_str()).unwrap_or("").to_string();+ let kind = v.get("kind").and_then(|x| x.as_str()).unwrap_or("info").to_string();+ broadcast("toast", json!({ "text": text, "kind": kind, "sticky": v.get("sticky").and_then(|s| s.as_bool()).unwrap_or(false) }));+ json_ok(&json!({ "ok": true }))+ }+ (Method::Post, "/ui/click") | (Method::Post, "/ui/reveal") | (Method::Post, "/ui/cursor") | (Method::Post, "/ui/tab") | (Method::Post, "/ui/reload") => {+ let ev = &url[4..];+ broadcast(ev, v.clone());+ json_ok(&json!({ "ok": true, "event": ev }))+ }+ (Method::Post, "/ui/eval") => {+ if !settings().get("dev_mode").and_then(|d| d.as_bool()).unwrap_or(false) {+ return (None, json_status(403, &json!({ "ok": false, "errorCode": "dev_mode_off", "error": "eval is only available in dev mode", "hint": "adom-ds2sf --ai-thread \"<name>\" settings set dev_mode true" })));+ }+ broadcast("eval", v.clone());+ json_ok(&json!({ "ok": true }))+ }+ (Method::Post, "/shutdown") => {+ let t = match ai_thread_of(&v) { Some(t) => t, None => return (None, identity_refusal("shutdown")) };+ let reason = v.get("reason").and_then(|r| r.as_str()).unwrap_or("");+ if reason.len() < 10 {+ return (None, json_status(400, &json!({ "ok": false, "errorCode": "reason_required",+ "error": "Shutting down a dashboard other threads may be using requires a reason.",+ "hint": "Re-call with a \"reason\" field (>= 10 chars) quoting what the USER asked for, e.g. {\"reason\": \"user said close the ds2sf dashboard\"}. If nobody asked, leave it: the 24h idle reaper cleans up by itself." })));+ }+ note_thread(&t, &format!("shutdown: {reason}"));+ let owner = OWNER.lock().unwrap().clone().map(|o| o.0).unwrap_or(t);+ return (Some(owner), json_ok(&json!({ "ok": true, "shutting_down": true })));+ }+ _ if url.starts_with("/api/chip/") && matches!(method, Method::Get) => {+ let rest = &url["/api/chip/".len()..];+ let mut parts = rest.splitn(2, '/');+ let mpn = urldecode(parts.next().unwrap_or(""));+ let sub = parts.next().unwrap_or("");+ match chip_dir(&mpn) {+ None => json_status(404, &json!({ "ok": false, "error": format!("{mpn:?} not in library") })),+ Some(dir) => {+ if sub.is_empty() {+ cors(json_ok(&chip_detail(&mpn)))+ } else if let Some(kind) = sub.strip_prefix("svg/") {+ let file = match kind {+ "ds2sf" => format!("{mpn}-footprint.ds2sf.svg"),+ "pcbnew" => format!("{mpn}-footprint.pcbnew.svg"),+ "symbol" => format!("{mpn}-symbol.ds2sf.svg"),+ "authoritative" => format!("{mpn}-footprint.authoritative.svg"),+ other => format!("{mpn}-{other}.svg"),+ };+ match std::fs::read(dir.join(&file)) {+ Ok(b) => Response::from_data(b).with_header(hdr("Content-Type", "image/svg+xml")).with_header(hdr("Cache-Control", "no-cache")),+ Err(_) => not_found(),+ }+ } else if sub == "pdf" {+ let name = query.split('&').find_map(|kv| kv.strip_prefix("name=")).map(urldecode).unwrap_or_else(|| format!("{mpn}.pdf"));+ if !safe_mpn(&name) || !name.to_lowercase().ends_with(".pdf") {+ return (None, not_found());+ }+ match std::fs::read(dir.join(&name)) {+ Ok(b) => Response::from_data(b).with_header(hdr("Content-Type", "application/pdf")).with_header(hdr("Content-Disposition", &format!("inline; filename=\"{name}\""))),+ Err(_) => not_found(),+ }+ } else if sub == "png" {+ let mut found = None;+ for c in [format!("{mpn}-3d-iso-named.png"), format!("{mpn}-3d-iso.png")] {+ if let Ok(b) = std::fs::read(dir.join(&c)) { found = Some(b); break; }+ }+ match found {+ Some(b) => Response::from_data(b).with_header(hdr("Content-Type", "image/png")),+ None => not_found(),+ }+ } else if let Some(name) = sub.strip_prefix("cache/") {+ let name = urldecode(name);+ if !safe_mpn(&name) { return (None, not_found()); }+ match std::fs::read(dir.join(".ds2sf-cache").join(&name)) {+ Ok(b) => Response::from_data(b).with_header(hdr("Content-Type", "text/plain; charset=utf-8")),+ Err(_) => not_found(),+ }+ } else {+ not_found()+ }+ }+ }+ }+ _ => not_found(),+ };+ (None, r)+}++fn urldecode(s: &str) -> String {+ let b = s.as_bytes();+ let mut out = Vec::with_capacity(b.len());+ let mut i = 0;+ while i < b.len() {+ if b[i] == b'%' && i + 2 < b.len() + 0 && i + 2 <= b.len() - 1 {+ if let Ok(h) = u8::from_str_radix(&s[i + 1..i + 3], 16) {+ out.push(h);+ i += 3;+ continue;+ }+ }+ out.push(if b[i] == b'+' { b' ' } else { b[i] });+ i += 1;+ }+ String::from_utf8_lossy(&out).to_string()+}++fn hdr(k: &str, v: &str) -> Header {+ Header::from_bytes(k.as_bytes(), v.as_bytes()).unwrap()+}+fn html(s: &str) -> Resp {+ Response::from_string(s).with_header(hdr("Content-Type", "text/html; charset=utf-8"))+}+fn json_ok(v: &Value) -> Resp {+ Response::from_string(v.to_string()).with_header(hdr("Content-Type", "application/json"))+}+fn json_status(code: u16, v: &Value) -> Resp {+ Response::from_string(v.to_string()).with_status_code(code).with_header(hdr("Content-Type", "application/json"))+}+fn cors(r: Resp) -> Resp {+ r.with_header(hdr("Access-Control-Allow-Origin", "*"))+ .with_header(hdr("Access-Control-Allow-Headers", "Content-Type"))+ .with_header(hdr("Access-Control-Allow-Methods", "GET, POST, OPTIONS"))+}+fn not_found() -> Resp {+ json_status(404, &json!({ "ok": false, "error": "not found" }))+}