Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ calls are synchronous. the [api guide](docs/usage.md) covers progress, cancellat
batches, editing, snapshots, and profile storage. the package never downloads a
binary or falls back to the javascript reference implementation on import.

## ai agents

The [openvector skill](skills/openvector/SKILL.md) guides AI agents through the CLI,
including batch conversion, palettes, edit plans, profiles, tracing stages, and exports.
It includes detailed references and helpers for reusable fitted geometry and SVG inspection.

Copy the complete `skills/openvector/` directory into your agent's skills directory,
or point the agent at its `SKILL.md`. Keep the references, scripts, and assets together.

## development

```sh
Expand Down
7 changes: 7 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,13 @@ other opens. Both export calls need completed fitted geometry. See the
[bitmap export](bitmap-export-contract.json) and
[vector output](vector-output-contract.json) contracts.

`vectorExportInput()` returns `{ width, height, geometry, palette, hiddenRegions }`
for the CLI's `export-*` commands. It needs completed fitted geometry and uses
the same straight-alpha colors and matching palette as `saveVector`. A
`snapshot({ fitting: true })` instead reports the engine's numerical state.
Set layout and format-specific options on the export input before writing it
as JSON. For headless EMF, supply `referenceDevice` explicitly.

### Batches

Create a batch with `session.createBatch(applicationDirectory, workingDirectory)`.
Expand Down
10 changes: 10 additions & 0 deletions npm/index.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,14 @@ export interface FittedGeometry {
}[];
}

export interface VectorExportInput {
width: number;
height: number;
geometry: FittedGeometry;
palette: number[];
hiddenRegions: number[];
}

/** Unrequested bulk sections are absent; requested unavailable sections are null. */
export interface DocumentSnapshot extends DocumentSummary {
original?: RasterImage | null;
Expand Down Expand Up @@ -429,6 +437,8 @@ export declare class ImageDocument {
exportBitmap(format: string, scale?: number, flatten?: boolean): Buffer;
/** Writes atomically only if the destination does not exist. Cancellation leaves no final file. */
saveVector(filename: string, options: ExportOptions, progress?: (percent: number) => boolean): SaveVectorResult;
/** Returns straight-alpha fitted data for CLI export stages. Throws before fitting completes. */
vectorExportInput(): VectorExportInput;
reset(): void;
}

Expand Down
2 changes: 1 addition & 1 deletion rust/crates/openvector-cli/src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ pub fn vectorize(args:&[String])->Result<()>{
let bytes=if let Some(format)=bitmap{
openvector::bitmap_export::export_bitmap(&BitmapExportInput{geometry:Some(&fitted),width:state.original.width as i64,height:state.original.height as i64,source_alpha_type:document.source_alpha_type(),background_mode:state.settings.background_mode,background_undo_count:background.undo.len(),hidden_regions:&hidden},&BitmapExportOptions{format,scale,flatten:args.flag("flatten")}).map_err(|e|match e{BitmapExportError::FlattenRequired=>"Non-PNG output may discard transparency. Use --flatten to continue, or --format png to preserve it.".into(),other=>other.to_string()})?
}else{
let mut request=json!({"width":state.original.width,"height":state.original.height,"palette":document.presentation_palette(),"hiddenRegions":hidden,"layout":export.layout.name(),"thinStroke":export.thin_stroke,"compact":export.compact,"curveMode":export.curve_mode.name()});
let mut request=json!({"width":state.original.width,"height":state.original.height,"palette":document.presentation_palette(&fitted),"hiddenRegions":hidden,"layout":export.layout.name(),"thinStroke":export.thin_stroke,"compact":export.compact,"curveMode":export.curve_mode.name()});
if format=="emf"{
let device=openvector::emf::EmfDevice::current_display().map_err(|error|error.to_string())?;
request["referenceDevice"]=json!({"pixels":device.pixels,"millimeters":device.millimeters,"micrometers":device.micrometers});
Expand Down
14 changes: 14 additions & 0 deletions rust/crates/openvector-node/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,20 @@ impl ImageDocument {
json!({"message": error.to_string(), "osError": error.raw_os_error()}))}))
}

#[napi]
pub fn vector_export_input<'env>(&self, env: Env) -> Result<Object<'env>> {
let geometry = self.inner.presentation_geometry()
.ok_or_else(|| engine_error("Document export needs completed fitted geometry."))?;
let state = self.inner.state();
let mut input = Object::new(&env)?;
input.set("width", state.original.width as u32)?;
input.set("height", state.original.height as u32)?;
input.set("geometry", snapshot::fitted_geometry(env, &geometry)?)?;
input.set("palette", self.inner.presentation_palette(&geometry))?;
input.set("hiddenRegions", snapshot::indices(&env, &self.inner.background_state().hidden_regions)?)?;
Ok(input)
}

#[napi]
pub fn reset(&mut self) { self.inner.reset(); }
}
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/openvector-node/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ fn array<'env, T, U: ToNapiValue>(env: &'env Env, values: impl ExactSizeIterator
Ok(output)
}

fn indices<'env>(env: &'env Env, values: &[usize]) -> Result<Array<'env>> {
pub(crate) fn indices<'env>(env: &'env Env, values: &[usize]) -> Result<Array<'env>> {
array(env, values.iter(), |&value| Ok(value as f64))
}

Expand All @@ -183,7 +183,7 @@ fn contours<'env>(env: Env, geometry: &openvector::contours::Geometry) -> Result
Ok(object)
}

fn fitted_geometry<'env>(env: Env, geometry: &openvector::contour_fitting::FittedGeometry) -> Result<Object<'env>> {
pub(crate) fn fitted_geometry<'env>(env: Env, geometry: &openvector::contour_fitting::FittedGeometry) -> Result<Object<'env>> {
let nodes = array(&env, geometry.nodes.iter(), |node| {
let mut object = Object::new(&env)?;
object.set("x", node.x)?; object.set("y", node.y)?;
Expand Down
5 changes: 2 additions & 3 deletions rust/crates/openvector/src/image_document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,11 @@ impl ImageDocument{
}
/// Match the output geometry's color space in serializers that name colors
/// from the palette (notably DXF layer tables).
pub fn presentation_palette(&self)->Vec<f32>{
pub fn presentation_palette(&self,geometry:&FittedGeometry)->Vec<f32>{
let palette=self.state.segmentation.as_ref().map_or(&[][..],|s|s.palette.as_slice());
if self.automatic_palettes.is_empty()&&!self.segmentation_palette_premultiplied{return palette.to_vec();}
// The mutable settings palette can differ from fitted edited regions.
// DXF layer names must correspond to the exact colors it draws.
let Some(geometry)=self.presentation_geometry() else{return palette.to_vec()};
let mut seen=std::collections::HashSet::new();
let mut output=Vec::new();
for region in &geometry.regions{
Expand Down Expand Up @@ -271,7 +270,7 @@ impl ImageDocument{
if input.reference_device.is_none()&&path.as_os_str().as_encoded_bytes().ends_with(b".emf"){
input.reference_device=Some(crate::emf::EmfDevice::current_display().map_err(|e|e.to_string())?);
}
let palette=self.presentation_palette();
let palette=self.presentation_palette(&geometry);
input.palette=&palette;
input.dxf_curve_mode=match options.curve_mode{crate::export_options::CurveMode::Splines=>crate::dxf::DxfCurveMode::Splines,crate::export_options::CurveMode::SparseLines=>crate::dxf::DxfCurveMode::SparseLines,crate::export_options::CurveMode::DenseLines=>crate::dxf::DxfCurveMode::DenseLines};
let progress=&mut self.state.progress;let cancel=&self.cancel;
Expand Down
106 changes: 106 additions & 0 deletions skills/openvector/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
---
name: openvector
description: Use the openvector raster-to-vector CLI to trace images, tune palettes and curves, edit segmentation and backgrounds, manage saved profiles and recent settings, batch-convert assets, run individual tracing stages, and export SVG, PDF, EPS, AI, DXF, EMF or rendered bitmaps. Use when a task names openvector or calls for raster tracing with this tool, including logos, icons, scans, illustrations, transparent artwork, CAD paths, print exports and reproducible conversion pipelines. Includes native Node API bridges for reusable fitted geometry and headless EMF export.
---

# openvector

## Start with the actual installation

1. Locate the installed `openvector` executable or the project's `node_modules/.bin/openvector`. In a built source checkout, use `node bin/openvector.mjs`. Treat `openvector` below as that verified command prefix.
2. Run `openvector --version`, `openvector --help`, and the relevant command's help. Read [setup and API](references/setup-and-api.md) if installation, native loading, platform support, or format selection needs attention. Do not silently download another version while discovering the existing one.
3. Use these references as the baseline for version 0.1.8, checked against [source commit 36fefd1](https://github.com/Microck/openvector/tree/36fefd1783a0d1c9300975ad33878cd3165ff48e). If installed help differs, verify the installed implementation before using version-specific options.
4. Inspect the actual source image: dimensions, alpha, palette, antialiasing, fine details, holes and intended background. Preserve its filename suffix; it affects classification and shadow processing. Inspect a visual preview when available.
5. Establish the intended deliverable: vector or raster, format, physical versus CSS dimensions, transparency, editability and any exact palette. Infer ordinary defaults from the task; ask only when the missing choice changes the result materially.

## Choose the right route

| Need | Route | Read |
|---|---|---|
| One image, automatic tracing, vector or rendered bitmap | `vectorize` | [CLI](references/cli.md) |
| Several images with common controls | `batch` with explicit format and destination | [CLI](references/cli.md) |
| Exact brand palette or fixed color count, even for one image | One-input `batch --settings ...` | [CLI](references/cli.md), [tuning](references/edits-and-tuning.md) |
| Reusable advanced processing settings | `profiles show/save`, then `--profile` and `--profiles-file` | [CLI](references/cli.md), [tuning](references/edits-and-tuning.md) |
| Replay a previous basic result | `--recent-file` and `--recent-index` | [CLI](references/cli.md) |
| Recolor, repair regions, draw, undo, remove background | `vectorize --edits plan.json` | [edits and tuning](references/edits-and-tuning.md) |
| Inspect numerical stages or control the pipeline explicitly | JSON stage commands | [stages](references/stages.md) |
| Trace once, export many vector formats or use headless EMF | `scripts/prepare_export.mjs`, then `export-*` | Reuse fitted geometry below; [stages](references/stages.md) |
| Stateful palette selection, progress/cancellation callbacks, selective snapshots | Public native Node API | [setup and API](references/setup-and-api.md) |

Do not invent flags such as `--colors`, `--preset`, `--quality`, `--recursive`, `--jobs`, `--background` or a generic `--json`. `vectorize` has no `--settings`; use the routes above.

## Convert, inspect, then tune

Start with one representative input and a new output path:

```sh
openvector vectorize logo.png --output logo-baseline.svg
```

Prefer `--output` over shell redirection for normal conversion. It checks collisions before writing. Shell `>` can truncate an existing file or the source before openvector starts. Replace a result with `--force` only when replacement is within the user's requested scope. Keep outputs, input images, edit plans, profiles and recent-settings files at distinct paths; create required destination folders first.

Evaluate the baseline before changing controls. Judge visible edges, holes, color fidelity, unwanted speckles, background and editable path complexity. Render SVG/PDF with an available renderer and compare at the intended size. For an approximate raster preview, rerun the same input and tracing controls with `--output preview.png`; this is another trace, not rendering the saved SVG. Use the actual SVG renderer when reviewing layout or thin-stroke effects.

Use a small number of labeled variants; change one control group at a time:

- Palette/category/quality: use explicit batch settings or a saved advanced profile. For exact colors, use advanced batch `paletteMode: 0` with normalized BGRA colors. A saved profile does not retain its palette array.
- Speckles and excess regions: investigate segmentation controls such as `minimumPixels`, `artifactRejection`, `complexity` and `clusterColors`.
- Edge shape and path complexity: investigate `smoothness`, `detectCorners`, `curveComplexity` and `smoothingAntiAlias`.
- Large images: use `--shrink-source` only when the detail tradeoff is acceptable. It changes processing dimensions above 1.6 megapixels; `--scale` only scales bitmap output.
- Background: distinguish preserving source alpha, flattening to a color, and hiding fitted regions. Apply region hiding after the last fit.

Use the exact enum meanings, ranges, and processing order in [edits and tuning](references/edits-and-tuning.md). Avoid promising that a larger numerical value always improves quality. Retain the successful settings, command, package version and original input name so a result can be reproduced.

## Keep these behaviors explicit

- `vectorize`: defaults to SVG on stdout and `grouped-cutouts` for vector layout. An output suffix selects the format; `--format` overrides it.
- `batch`: defaults to AI, the last input's folder, skipped existing outputs and a white background. Always set `--format` and `--output-dir`; set `backgroundMode: 0` in batch JSON when transparency must be preserved. Native batch supports SVG/EPS/PDF/AI/DXF, not EMF or raster output.
- Palettes and edit colors use normalized BGRA, not RGBA. Opaque red is `[0,0,1,1]`; palettes are flat arrays repeating four channels. Decoded BGRA pixels and fitted-region BGRA use byte values instead.
- Basic/advanced document, profile and batch settings use integer enums. The standalone numeric `settings`/stage commands use string enums. These JSON objects are not interchangeable.
- Saved profile replay skips classification and uses stored palette metadata. Palette mode 3 does not process. Profile selection writes ordering to its explicit storage file; recent recording can persist before a later export fails. Serialize operations sharing either file.
- An edit `settings` patch selects controls; it does not run them. After segmentation changes, process smoothing and fitting. After tools change pixels, explicitly `finish` before background work. A final implicit refit uses the document's last committed controls, so do not rely on an unprocessed patch.
- SVG dimensions are points: 48 pt renders as 64 CSS px at 96 DPI. Set display CSS dimensions for web use without changing its viewBox. Decide physical output dimensions explicitly for print.
- PNG bitmap output preserves alpha. Non-PNG output may need `--flatten`; this acknowledges transparency loss, not an instruction to discover or remove a background. Raster exports redraw fitted paths.
- Low-level `export-*` defaults to `stacked`, unlike high-level conversion. Set `layout` explicitly when matching an existing result. `--thin-stroke` can change fine lines and holes; inspect the rendered result.
- Headless `vectorize --format emf` cannot supply display metrics. Use `export-emf` with explicit, meaningful `referenceDevice` measurements.

## Reuse fitted geometry

Set `OPENVECTOR_SKILL_DIR` to this skill's directory. The helper needs a local package with `document.vectorExportInput()`. For a source build, pass `--module /absolute/path/to/openvector/npm/index.mjs`. OpenVector 0.1.8 supports [`saveVector`](references/setup-and-api.md#convert-once-export-several-times) but lacks this helper's API.

```sh
node "$OPENVECTOR_SKILL_DIR/scripts/prepare_export.mjs" logo.png --output fitted.json
```

Choose automatic processing by default, `--batch-settings batch.json` for explicit batch controls, or `--profile-record profile.json` for a record returned by `profiles show`. The latter two are mutually exclusive. Optional `--shrink-source` reduces input before tracing. This helper does not execute CLI edit plans or update profile/recent files.

Feed the same JSON to `export-svg`, `export-pdf`, `export-eps`, `export-ai`, `export-dxf` or `export-emf`; add format-specific JSON options from [stages](references/stages.md). All exports write raw bytes to stdout. Capture bytes before creating a new output so failures do not truncate files:

```python
from pathlib import Path
import subprocess

cli = ["openvector"] # Or ["node", "/absolute/path/bin/openvector.mjs"].
for fmt in ("svg", "pdf", "dxf"):
result = subprocess.run(cli + [f"export-{fmt}", "fitted.json"],
check=True, stdout=subprocess.PIPE)
with Path(f"logo.{fmt}").open("xb") as output:
output.write(result.stdout)
```

Keep the export palette for DXF. For EMF, add `referenceDevice` with positive-int32 `[x,y]` pairs named `pixels`, `millimeters`, and `micrometers`; obtain the intended measurements rather than inventing a display. For requested output dimensions, supply both `outputWidth` and `outputHeight` as positive int32 values.

## Validate and report the deliverable

1. Check the process exit code and stderr. Conversion/stage errors return 1. Batch cancellation returns 130; parse its summary even when it exits nonzero. Inspect per-file failures, skips and cancellation instead of assuming every input was exported.
2. Confirm output paths exist, contain bytes, and match their format. For SVG, run:

```sh
python3 "$OPENVECTOR_SKILL_DIR/scripts/inspect_svg.py" logo-baseline.svg
```

This reports XML structure, paths, image elements and point-to-CSS dimensions. It does not establish visual accuracy or valid cutting topology.
3. Render and inspect the chosen final output when the environment supports it. For SVG/PDF check holes and alpha on a contrasting background. For CAD/cutting inspect units, closed contours, duplicates and tool compatibility in the actual downstream workflow; successful export alone does not establish manufacturability.
4. Report the created files, settings that materially changed the result and any unverified part. Do not call an output visually verified when only its syntax or signature was checked.

Read only the reference needed for the current route: [CLI](references/cli.md), [edits and tuning](references/edits-and-tuning.md), [numeric stages](references/stages.md), or [setup, formats and API](references/setup-and-api.md).
14 changes: 14 additions & 0 deletions skills/openvector/agents/openai.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
interface:
display_name: openvector
short_description: Trace, tune, edit, and export with the openvector CLI
default_prompt: Use $openvector to inspect my images, choose tracing settings, and
produce verified vector exports.
icon_small: assets/icon.svg
icon_large: assets/icon.svg
policy:
products:
- chatgpt
- codex
- api
- atlas
allow_implicit_invocation: true
Loading
Loading