diff --git a/README.md b/README.md index b63b6ec..045480b 100644 --- a/README.md +++ b/README.md @@ -1,77 +1,118 @@ -# inventory plugin +

+ Inventory in protoAgent: the Stock tab grouped by game system, with an item's drawer open showing its price, the eBay sold comps it rests on, its bin, label and listing draft +

-The resale inventory as a **source of truth** for [protoAgent](https://github.com/protoLabsAI/protoAgent): -lots, items, listings, sales, price evidence, and an audit trail of every change — in a -SQLite file the plugin owns. Built for merchantAgent, useful for any agent that sells things. +

+ CI + Latest tag + protoAgent 0.148+ + Python 3.11+ + MIT license +

-``` -inventory_summary() - BLOODBOWL-2026-09 cost $355.00 remaining (low/target/high) $612 / $790 / $1,010 - realized net $0.00 projected net at target +$435.00 -``` +# Inventory -## What it contributes +The back office for a resale business, built as a [protoAgent](https://github.com/protoLabsAI/protoAgent) +plugin. It tracks what you bought, what each box split into, where every piece is on the shelf, what it's +worth, where it's listed and what it actually sold for. Your agent works the inventory with you in chat, and +the Inventory view in the console lets you do it by hand, on a desktop or on your phone. -| | | +It was built for tabletop games (sealed boxes broken into units and sold on eBay), but anything you buy in +lots and sell piece by piece fits. + +## What you get + +- **A work queue.** Next shows what needs you today: sales to pack and which bin they're in, listings to end, + scans that need a look, items ready to list, boxes still to split, and stock that's sat too long. A section + only appears when there's something in it. +- **Scan a box in.** Photograph a box and say what you paid. The agent identifies it in the background, lists + the pieces it splits into, and you choose Keep or Sell for each one. +- **Label first, then put it away.** Print a QR sticker for every piece, then scan a piece's label and the + bin's label with your phone camera. The piece is now in that bin and up for sale. +- **Bins and labels.** Numbered bins (B01, B02…) with printable QR labels on Avery sheets or thermal rolls. + Scanning a bin's label opens its contents. +- **Prices with their evidence.** Targets come from eBay sold listings, and every price keeps the basis it + rests on, so you can always see why something is $54. +- **Listing drafts you paste into eBay.** The agent writes the title and description from the record and the + photos. You copy them into eBay yourself, then paste the listing link back. +- **Record a sale by pasting it.** Paste an eBay order or a quick note ("sold the dice for $70 + $9 shipping") + and check what the agent read before it's recorded. If the item was still listed somewhere else, Next tells + you to end that listing. +- **What to do with stock.** Aging stock suggests an offer, a markdown, a bundle or a decision as items sit. + When you scan a box, it compares selling it sealed against splitting it, after fees. +- **Packing and shipping data.** Packed weight, box size and your own packaging presets, copied into the + listing the way eBay asks for them. +- **Check a bin.** Scan everything in a bin and see what's there, what's missing and what's in the wrong bin. +- **Copy list.** Select items and copy a for-sale post for a group chat: the game system as a header, then + `Name NoS — $20` on each line. +- **Lot P&L.** For every purchase: what it cost, what's left to sell, what's been realized, and the projected + net if the rest sells at target. + +## How it stays honest + +- **It never posts, lists or messages anyone.** Drafts and sales are written for you to check and act on. + There's no eBay write access at all. +- **A price always has a basis.** A target can't be set without saying what it rests on, and the comps are + stored with it. +- **It doesn't invent facts about items.** Model counts it can't see stay unknown, a box's contents come from + what it can confirm, and a scan it isn't sure about asks you to pick or type the name. +- **Sold means a sale was recorded.** An item becomes sold only through a sale record, with its price, fees + and postage, never by flipping a status. +- **Everything is audited.** Every change records who made it (the agent or you in the console) and what + changed. + +## Quick start + +1. **Install it** on an agent you already have: + + ```sh + python -m server plugin install https://github.com/protoLabsAI/inventory-plugin + ``` + + Or in the console: **Plugins → Install from URL**. +2. **Turn it on** in **Console → Plugins**. It ships disabled. +3. **Set the basics** in **Settings → Plugins → Inventory**: the workspace directory, and the weekly review + if you want it. Every setting is in [configuration.md](docs/configuration.md). +4. **Open Inventory** from the console's rail. Add bins under **Bins**, then **Scan a box**, or import a + spreadsheet from **More → Import CSV**. + +Pricing from sold comps uses the [ebay plugin](https://github.com/protoLabsAI/ebay-plugin). Identifying +photos needs a vision-capable model. A printed label opens its item or bin in the console on protoAgent +0.227.0 or later; on an older host it shows a page naming the bin or item. Full steps are in +[Install and setup](docs/install.md). + +## Using it + +| To | Say something like, or do | +|---|---| +| See how you're doing | "How are my lots doing?" · open **Lots** | +| Bring in a box | **Scan a box**, photograph it, enter what you paid | +| Put pieces away | **Bins → Put away → Scan with camera**: scan pieces' labels, then the bin's | +| Find something | **Scan label** on a piece or a bin · "Where's the Halfling team?" | +| Price stock | "Re-price everything older than a month from sold comps." | +| List an item | **Draft listing** in its drawer, copy into eBay, then **I listed it** | +| Record a sale | **Record a sale** on Next and paste the order · "Sold the Goblin team for $39, eBay." | +| Pack orders | Next → **To pack**, grouped by bin, then **Packed** | +| Post to a group chat | Select items in **Stock**, then **Copy list** | +| Deal with slow stock | Next → **Aging stock**: Mark down, Bundle or Snooze | + +More in [Using it](docs/usage.md). + +## Documentation + +| Doc | What's in it | |---|---| -| **Tools** | `inventory_summary` · `inventory_list` · `inventory_get` · `inventory_upsert_lot` · `inventory_upsert_item` · `inventory_delete_item` · `inventory_set_price` · `inventory_mark_sold` · `inventory_listing` · `inventory_bins` · `inventory_move_to_bin` · `inventory_packing` · `inventory_import_csv` · `inventory_export_csv` · `inventory_reprice_plan` · `inventory_stale` · `inventory_scan_photos` · `inventory_scan_propose` · `inventory_scan_fail` · `inventory_scan_pricing_done` · `inventory_draft_item` · `inventory_draft_write` · `inventory_draft_fail` · `inventory_sale_candidates` · `inventory_sale_propose` · `inventory_sale_fail` (the scan, draft and sale tools are for the turns the plugin starts) | -| **View** | a rail panel built around what you ask, not the tables. **Scan** (pinned at the bottom on a phone, in the header on desktop) walks a photo from box to binned pieces: what it is, a photo through the phone's own camera, the agent's identification (pick one of its guesses or type it when it isn't sure), Keep or Sell per piece, prices from sold comps, then a bin for each. **Next** is a work queue (to pack, grouped by bin; scans that need a look, resumable where you left off; ready to list; to split; items not in a bin; stale prices) whose sections only appear when there is something to do; **Stock** filters by lifecycle (for sale, to split, sold, all), with search and one System / Lot filter, list rows on a phone and a table from 640px; **Bins** shows each bin with its count and value, opens a bin's contents (move items in, copy its list), creates bins and prints their **labels**; **Lots** holds the P&L, with each lot's units and sales in its detail. One drawer holds everything about an item: price with its full basis, Record sale, Listing, Keep, Withdraw, Edit, Delete and its history. Multi-select with **Copy list** (also ⌘C) — a for-sale post per game system: the system as a header, then `Name NoS — $20` per line (condition inline, whole-dollar prices). More holds Add item, New lot, CSV import (file or paste, with the mapping report) and export, and a readable History | -| **API** | bearer-gated JSON under `/api/plugins/inventory` — `summary`, `lots`, `items`, `items/{id}/price`, `items/{id}/sold`, `items/{id}/listings`, `listings/{id}/end`, `listings/to-end`, `sales`, `bins` (list/create/update/delete), `bins/move`, `labels/base`, `labels/sheet`, `to-pack`, `sales/{id}/packed`, `scans` (list/create/get/discard), `scans/{id}/photos` (raw image body; GET one by id), `scans/{id}/retry`, `scans/{id}/confirm`, `scans/{id}/price`, `scans/{id}/finish`, `drafts` (each item's draft state), `drafts/bulk` (at most 10), `items/{id}/draft` (GET the draft / POST to request one), `items/{id}/draft/copied`, `items/{id}/draft/sku-updated`, `items/{id}/draft/live` (the eBay address), `items/{id}/photos.zip`, `sale-pastes` (list/create/get/discard), `sale-pastes/{id}/retry`, `sale-pastes/{id}/record`, `stale`, `audit`, `import`, `export` | -| **Automations** | `weekly_review: true` arms a plugin-owned recurring turn (`weekly_review_cron`, default Monday 09:00 in `review_timezone`) that re-prices stale evidence from eBay sold comps through the same tools, reports stale listings with a recommendation (it never changes a listing itself), and posts the per-lot P&L. Cancelled when the plugin is disabled. | -| **Events** | `inventory.item.changed`, `inventory.lot.changed`, `inventory.sale.recorded`, `inventory.imported`, `inventory.bin.changed`, `inventory.sale.packed`, `inventory.scan.changed`, `inventory.draft.changed` | -| **Skill** | `inventory-ops` — the rules (a target needs a basis; never set sold by hand; sold ≠ active ≠ retail) and the re-price / weekly-review routines | - -## The model - -- **Lot** — a purchase: cost, date, source. P&L is against the lot cost. -- **Item** — one sellable thing from a lot, optionally tagged with its game **system** (Warhammer 40K, Blood Bowl, …). Status `planned → available → listed → pending → sold`, or `kept` / `withdrawn` (`planned` = a piece that exists once a sealed box is split). - Targets low/target/high **with a `price_basis` and a date**. -- **Price observation** — the comps behind a target (source, n, p25/median/p75, query). Recorded by `inventory_set_price`. -- **Listing** — where the item is up (channel, url, price). -- **Bin** — where the item physically is (B01, B02 …). Moves are audited with where it came from. A sale waits on the **pick list** until it is packed; sales from before bins existed are recorded as already packed. -- **Bin label** — a printable US Letter sheet (3 × 4), each label a QR code, the bin id in large type and its label text. It opens in your browser and you print from there. Every QR encodes `/plugins/inventory/b/`, where `` is **Bin label address** in Settings, else the agent's public URL (a fleet member's hub address, which a paired phone on the tailnet can open), else its console. That one public route takes only a bin id and reads no data: on a protoAgent with plugin-view deep links (#4712) it hands off to the console with the bin open (a signed-in browser goes straight on; see **Scan label**); on an older one it says the console needs an update. So printed labels never go stale when the console changes how it opens a view. -- **Where a sheet opens** (0.10.1) — **in your browser**: a new tab in the web console, your default browser from the desktop app (which hands any http(s) link from a plugin to the system browser and ignores a blank window). The gated `POST /api/plugins/inventory/labels/sheet` renders the sheet and returns a `link` to it; the public `GET /plugins/inventory/sheet/` serves it. The token is 32 random bytes, lives 15 minutes (reloads and print preview are fine), and at most 50 sheets are kept; the sheet holds only what the printed labels show. An unknown or expired link answers a short page with no data. The print dialog always keeps the link too, in case nothing opened. -- **Item label** (0.10.0) — stickers for individual pieces on **Avery 5160 / 8160** (30 to a US Letter sheet: 2⅝″ × 1″, 0.5″ top/bottom and 3⁄16″ side margins, 2¾″ × 1″ pitch). Each label carries a QR, the name (two lines at most), condition · bin, and the item id, but no price, since that changes and the sticker doesn't. Print it from a Stock selection (**Print labels**), the item drawer (**Print label**), or the last step of a scan (**Print N labels**). **Start at label** reuses a partly used sheet. Print at 100% (Actual size). Every QR encodes `/plugins/inventory/i/`, which works like the bin hop: it's public, takes only an item id, reads no data, and hands off to the console with that item's drawer open (`?item=`), through the same landing page as the bin hop. Printing records `labels_printed_on` on the item, shown in the drawer. -- **Put away** (0.11.0) — label first, then bin by scanning. A scan now ends by printing labels for the pieces you're selling (no bin picker). Bins ▸ **Put away**: photograph a piece's label to add it to the tray (several pieces is fine), then photograph the bin's label and confirm, and they move into that bin in one audited move; a `planned` piece becomes `available`. The QR is read in the view from the photo (native camera sheet; the vendored jsQR 1.4.0, Apache-2.0, in `vendor/jsqr`), so nothing leaves the page; only this plugin's `/i/` and `/b/` label paths are accepted. A label that won't read: type the item or bin id. `POST /bins/move` takes `put_away: true`. -- **Live camera** (0.13.0) — Put away ▸ **Scan with camera** opens a viewfinder: point at a piece's label and it's added (a short beep, a green frame); point at the next; point at the bin's label and confirm. Reading pauses while the confirm is open, the same label is ignored for 2.5 s, and the flashlight toggle appears where the phone supports it. The camera starts only on your tap and stops on Done, when the drawer closes or the view is hidden, and after 2 minutes with nothing scanned (Resume brings it back). It works where the console and this view share an origin, as they do through a fleet hub (a same-origin frame may use the camera; no Permissions-Policy header is sent), and falls back to **Take a photo** where it can't: a refused permission says how to allow it (Settings ▸ Safari ▸ Camera), and the desktop app (a cross-origin frame with no camera permission) uses photos. Frames are decoded in the page (the centre square, at most 720 px, about 7 per second, and every third frame the whole picture at most 960 px wide, so a label whose QR is off-centre still reads); nothing is uploaded. -- **Scan** — a photo the agent identifies in the background. A **box** scan starts its lot at once with what you paid (named "Box scanned …" until confirmed) and proposes the pieces it splits into; a **piece** is scanned alone or into a box being broken down. Photos (up to 3 per scan) are stripped of metadata on upload (HEIC is converted with macOS `sips`) and kept beside the database. After a photo lands the plugin starts one agent turn with `sdk.run_in_session` in that scan's own session (`inventory-scan-`, never your chat): it may not use eBay, pricing tools or subagents and allows two web searches; it answers through `inventory_scan_propose` (or `_fail`). Confirming writes the items (Keep → `kept`, Sell → `planned`) and keeps the correction (the agent's name vs yours) on the scan. **Price the sell pile** starts a second turn that prices from eBay sold comps with `inventory_set_price` and reports what it couldn't price. Binning makes each sell piece `available`. A turn that never answers shows as failed with Retry after **Scan: give up after** (Settings). -- **Listing drafts** — **Draft listing** on an item (or **Draft N** from Next ▸ Ready to list, at most 10, one after another) starts one agent turn in the item's own session (`inventory-draft-`, never your chat). It reads the item and its scan photos and writes a title (at most 80 characters) and a plain-text description through `inventory_draft_write`, with no eBay, pricing tools or subagents. The draft's price is always the item's target, shown with its basis. Copy the title, price, description and **Custom label (SKU)** — bin first (`B03-`, capped at eBay's 50 characters), so eBay's own pick list and order search say where it lives — download the photos, list it on eBay yourself, then **I listed it** with the listing's address (`ebay.com/itm/…`, or the app's `ebay.us` share link): that records an eBay listing at the target and marks the item listed. Next asks about drafts copied a day ago but never marked live, and — once you have copied the Custom label — shows **Update the custom label on eBay** when the item moves to another bin (Copy the new label, then Done). Nothing is ever posted for you. -- **Record a sale by pasting it** — Next ▸ **Record a sale** (also More, and "Paste the order instead" in an item's Record sale dialog). Paste an eBay order email or Seller Hub row, an app's share text, or a note ("sold the dice for $70 + $9 shipping, personal connection"). The plugin starts one cheap agent turn in that paste's own session (`inventory-sale-`, never your chat; no web, no eBay browsing, no subagents) that finds the items with `inventory_sale_candidates` and proposes one line per item with `inventory_sale_propose`: price, shipping charged, fees (the stated fee, or an estimate from the ebay plugin's `ebay_net_proceeds` marked *estimated*, never invented), postage, channel and date. A bundle is split across lines and checked against its total. A weekday-without-a-year date ("Delivered Mon Dec 23") must land on that weekday, and no sale can be dated in the future. Buyer names, addresses and tracking numbers are never copied. The proposal waits under Next ▸ **Sales to check**; you can change the item or any number, remove a line, then **Record N sales** — one audited `mark_sold` per line — and the items land on To pack with their bins. Nothing is recorded until you do. The paste (text, proposal, outcome) stays in this database. A paste that repeats a sale already recorded (the candidates include items sold in the last 180 days, flagged with that sale) is not proposed again: it reads **Already recorded: sold on for $X** with a link to the item. -- **Sale** — `net = price + shipping charged − fees − shipping cost`. Selling the last unit closes a live listing **on the same channel** as sold. A live listing on **any other channel** (it sold to a personal connection while still up on eBay) is flagged `needs_end` instead, because nothing here can take it down: Next ▸ **End these listings** shows it with an Open listing link, and **I ended it** marks it ended (audited). A partial sale of a multi-quantity item flags nothing. The agent sees the same list with `inventory_listing(action="to_end")`. -- **Sealed or split** (0.14.0) — for a box scan, **Price the sell pile** also prices the box itself sealed from eBay sold comps (the same 3-comp rule) and, where the ebay plugin's `ebay_net_proceeds` is available, the fees on the sealed target and on the pieces' targets. That price is kept on the scan through `inventory_scan_sealed_price`, never as an item. The pricing step then shows **Split** (the sell pieces at target) against **Sealed**, net of fees when both fee figures are known and before fees otherwise (it says which), with the difference and a one-line verdict. Sealed has to win by at least $10 or 5% of the split total before it's suggested; an unpriced piece makes the verdict "incomplete". When sealed wins, **Sell it sealed instead…** (confirmed first) removes the planned pieces (snapshotted into the history) and puts one sealed item (NIB, `available`, the sealed price and its comps as basis and evidence) in the lot; it's refused once any piece is kept, for sale, listed or sold. Lot detail shows the same comparison while every piece is still planned. `POST /scans/{id}/sell-sealed`, `GET /lots/{id}/split-check`. -- **Aging stock** (0.14.0) — Next ▸ **Aging stock** lists unsold items (`available` or `listed`; `planned` and `pending` never age) that have sat past a tier from Settings (**Aging** 45 / 90 / 120 days by default, each 1–730), oldest first, with one suggested move per tier: an offer to watchers or a 10% drop, another drop or a bundle, then decide (clearance, bundle, or pull it). Days count from the live listing's date ("listed"), else from when the item last became listed/available in the audit trail ("not listed" if it isn't up anywhere), else from when it was added; every row says which. We have no marketplace data, so watcher counts are never shown. **Mark down…** opens the Price dialog with the target 10% lower and a stated basis ("Aging markdown, 95 days, no sale"), which you can change before saving; **Bundle…** (pick two or more) drafts a chat message asking the agent to propose a bundle and its price; **Snooze 14 days** hides the item until then (audited). `GET /aging`, `POST /items/{id}/snooze`. -- **Shipping** (0.15.0) — an item's **packed weight** (pounds + ounces in, stored as whole ounces, partial ounces rounded up the way carriers bill), its **box** (length × width × height in inches, one decimal) and its **packaging**. Packaging presets (name, size, empty weight) are yours to make from More ▸ **Packaging**; none ship with the plugin, so no box size is ever invented. Picking a preset fills the box and adds its empty weight for the packed weight (weigh the item alone); without one, weigh it as it ships. Edit it from the item drawer's **Shipping** row or **Weigh** on a piece in the Put away list (optional, never in the way). The listing draft shows **Package weight** (Copy lb, Copy oz) and **Package size** (L, W, H), the way eBay's form asks for them. Next ▸ Housekeeping counts for-sale items with **no packed weight**. Anything not measured stays blank. `GET/POST /packaging`, `PUT/DELETE /packaging/{id}`, `PUT /items/{id}/shipping`. -- **Check a bin** (0.15.0) — bin detail ▸ **Check this bin**: scan the label on every piece in it with the live camera (or photos, or a typed id). The drawer shows what's **found** (✓), what's **not scanned yet**, and what **doesn't belong**: in another bin ("In another bin: B05 → move here?"), in no bin ("Not in a bin → move here?"), or sold and packed ("Sold: should not be here"), plus any unknown label. A piece that's sold but not packed yet still counts as found: it's waiting to be picked. **Finish check** saves it in one audited transaction: strays move into the bin, the unscanned can be flagged **missing** (a flag with a date, not a status; the item stays recorded in the bin), and the bin is stamped `checked_on` (the Bins list shows "checked 3 d ago"). Next ▸ Housekeeping counts missing items; one turns up again with a later check, any move, or **Found it** in its drawer. `POST /bins/{id}/check` (`found`, `move_here`, `mark_missing`), `POST /items/{id}/found`. -- **Scan label** (0.16.0) — on an iPhone, a label scanned with the Camera app always opens in Safari: iOS never hands a link to a home-screen web app, and Safari keeps its own storage, so it isn't signed in. So the view scans its own labels. **Scan label** (header on desktop, beside **Scan a box** on the phone's bottom bar; the box-intake button was renamed from plain "Scan") opens the live camera, with the photo and typed-id fallbacks: an item's label opens its drawer, a bin's opens the bin. A decoded URL is parsed, never opened. The public label hops now answer with a small landing page instead of a bare 302. A browser already signed in to this console (the console's token in this origin's `localStorage`: `protoagent.deviceToken`, else `protoagent.authToken`) goes straight on to the item or bin. Anyone else sees the id and how to open it in the app, plus **Sign in here instead**. The page reads no data (the same for an id that exists and one that doesn't), sends nothing, never puts a token in a URL, and carries `no-store`, `no-referrer` and `noindex`. With JavaScript off, the link still works. On an older host without plugin-view deep links, it is the same "needs an update" page as before. -- **Label stock** (0.15.0) — the bin and item label dialogs pick what you print on: **Avery 5160 / 8160** (30 to a Letter sheet, 2⅝″ × 1″, the items' default), **Avery 5163 / 8163** (10 to a sheet, 4″ × 2″: 0.5″ top/bottom, 5⁄32″ sides, 3⁄16″ between columns), a **Dymo 30252** address roll (3½″ × 1⅛″), or a **2¼″ × 1¼″ thermal roll** (Dymo 30334, the same size as standard Zebra, Rollo and Brother rolls). The bins' 12-to-a-sheet large squares stay their default. A roll prints one label per page, the page being the label (`@page` sized to it, no margin), so pick your label printer and its label size in the print dialog; sheets keep **Start at label** for a partly used sheet. The QR is at least 0.8″ on every stock and never under 0.6″, below which phone photos and the live camera stop reading it reliably at a hand's distance. The last stock is remembered per kind in this browser (localStorage), not in Settings: it's about the printer beside you. `POST /labels/sheet` takes `stock`; `GET /labels/base` lists the stocks. -- **Audit** — every mutation, with the actor (`agent` or `console`) and the fields that changed. - -Money is stored as integer cents and exposed as dollars. - -## Setup - -```bash -protoagent plugin install https://github.com/protoLabsAI/inventory-plugin -``` - -```yaml -# langgraph-config.yaml -plugins: - enabled: [inventory] -inventory: - workspace_dir: /path/to/agent/workspace # relative CSV paths resolve here -``` - -The database lives in the host's instance-scoped plugin store, so each agent (and the dev -sandbox) gets its own. Seed it from a spreadsheet: `inventory_import_csv(path="inventory.csv")` -maps common headers (`inventory_id`, `item`, `lot_id`, `target_low_usd`, `target_price_usd`, -`status`, `sold_price_usd`, `price_source` …) and reports what it could not place. - -## Development - -```bash -uv venv --python 3.12 .venv && uv pip install -p .venv/bin/python -r requirements-dev.txt ruff -.venv/bin/ruff check . && .venv/bin/ruff format --check . && .venv/bin/python -m pytest -q -``` - -The suite is host-free: no protoAgent, no database beyond a temp file. +| [Install and setup](docs/install.md) | Requirements, install, the settings that matter, first steps, phones | +| [Using it](docs/usage.md) | Each tab and every flow, step by step | +| [How it works](docs/how-it-works.md) | The data model, the agent turns the plugin starts, labels, the audit trail | +| [Configuration](docs/configuration.md) | Every setting, its default, and what it does | +| [Tools](docs/tools.md) | Every agent tool | +| [HTTP API](docs/api.md) | Every route, operator and public | +| [Design decisions](docs/design-decisions.md) | Why it's built the way it is | +| [Development](docs/development.md) | Layout, tests, the view harness, releasing | +| [Upgrading](docs/upgrading.md) | Notes for versions that change behavior | + +## License + +MIT, see [LICENSE](LICENSE). The QR encoder is Project Nayuki's QR Code generator (MIT) and the label reader +is jsQR (Apache-2.0); both are vendored unmodified under `vendor/` with their licences. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..c60de75 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,19 @@ +# Documentation + +Start with the [README](../README.md) for the short version. This directory has the rest. + +| Doc | What's in it | +|---|---| +| [install.md](install.md) | Requirements, install and enable, the settings that matter, first steps, phones | +| [usage.md](usage.md) | The Inventory view tab by tab, and every flow: scanning, labels, put away, pricing, drafts, sales, packing | +| [how-it-works.md](how-it-works.md) | The data model, money in cents, the audit trail, the agent turns the plugin starts, labels and their public links | +| [configuration.md](configuration.md) | Every setting under **Settings → Plugins → Inventory**, with its default | +| [tools.md](tools.md) | Every agent tool | +| [api.md](api.md) | Every HTTP route: the bearer-gated operator surface and the public routes | +| [design-decisions.md](design-decisions.md) | The reasoning behind the main design choices | +| [development.md](development.md) | Layout, tests, the view harness, releasing | +| [upgrading.md](upgrading.md) | Version notes that change behavior | +| [design/](design/) | The Inventory view redesign spec | + +ADRs cited in these pages are protoAgent's, and live in +[protoAgent's `docs/adr/`](https://github.com/protoLabsAI/protoAgent/tree/main/docs/adr). diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..e0eb6f2 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,136 @@ +# HTTP API reference + +Every route here is real and comes from `api.py` and `view.py`. `tests/test_docs_reference.py` fails if a +route is added, removed or renamed without this page changing. Money is in dollars in requests and +responses. + +There are two surfaces with different authentication, on purpose. + +## Operator surface: bearer token + +Mounted under `/api/plugins/inventory`. The console view and anything you script use these. They need the +instance's operator bearer token, which the view gets from the console's handshake: + +```bash +curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:7870/api/plugins/inventory/summary +``` + +Through a fleet hub, prefix the path with `/agents/`. + +### Lots, items and prices + +| Method | Path | What it does | +|---|---|---| +| `GET` | `/summary` | The P&L per lot and in total: cost, remaining at low/target/high, realized gross and net, projected net | +| `GET` | `/lots` | Every lot | +| `PUT` | `/lots/{lot_id}` | Create or update a lot. Only the fields sent change | +| `DELETE` | `/lots/{lot_id}` | Delete a lot. Refused while it has items unless `cascade=true`, which snapshots each removed item into the audit trail | +| `GET` | `/lots/{lot_id}/split-check` | Sealed vs split for a lot whose pieces are all still planned | +| `GET` | `/systems` | The game systems in use, for the system picker | +| `GET` | `/conditions` | The condition suggestions plus every condition in use | +| `GET` | `/items` | Items, filtered by lot, status, category, system, bin or a text search | +| `POST` | `/items` | Create an item | +| `GET` | `/items/{item_id}` | One item with its listings, sales and price observations | +| `PUT` | `/items/{item_id}` | Update an item's fields. Setting sold here is refused: record a sale instead | +| `DELETE` | `/items/{item_id}` | Delete an item and its listings, sales and observations (snapshotted into the audit trail) | +| `POST` | `/items/{item_id}/price` | Set the price band. A `basis` is required, and the comps evidence is stored with it | +| `GET` | `/stale` | Listings live longer than `listed_days` and prices older than `price_days` (default: the Stale price setting) | +| `GET` | `/aging` | Unsold items past an aging tier, oldest first, each with the basis its days count from | +| `POST` | `/items/{item_id}/snooze` | Hide an item from Aging stock for 14 days (audited) | +| `PUT` | `/items/{item_id}/shipping` | Set packed weight, box size and packaging preset | +| `GET` | `/view-config` | The settings the view needs: the stale-price days and the aging tiers | + +### Selling + +| Method | Path | What it does | +|---|---|---| +| `POST` | `/items/{item_id}/sold` | Record a sale (the same rules as `inventory_mark_sold`) | +| `GET` | `/sales` | Sales, optionally for one lot | +| `POST` | `/items/{item_id}/listings` | Record a live listing on a channel | +| `POST` | `/listings/{listing_id}/end` | End a listing, including one flagged `needs_end` ("I ended it") | +| `GET` | `/listings/to-end` | The double-sell guard: listings still up somewhere for items that sold elsewhere | +| `GET` | `/to-pack` | Sales not yet packed, grouped by the bin to pull from | +| `POST` | `/sales/{sale_id}/packed` | Mark a sale packed. An item with no stock left leaves its bin | +| `GET` | `/sale-pastes` | Pasted sales waiting to be checked | +| `POST` | `/sale-pastes` | Paste an order or a note. Starts one agent turn that reads it | +| `GET` | `/sale-pastes/{paste_id}` | One paste with its proposal | +| `POST` | `/sale-pastes/{paste_id}/retry` | Read a failed paste again | +| `POST` | `/sale-pastes/{paste_id}/record` | Record the checked lines, one audited sale each | +| `DELETE` | `/sale-pastes/{paste_id}` | Discard a paste (it's kept, marked discarded) | + +### Listing drafts + +| Method | Path | What it does | +|---|---|---| +| `GET` | `/drafts` | Every item's draft state | +| `GET` | `/items/{item_id}/draft` | One item's draft | +| `POST` | `/items/{item_id}/draft` | Ask for a draft. Starts one agent turn | +| `POST` | `/drafts/bulk` | Draft several items, one turn after another, at most 10 per request | +| `POST` | `/items/{item_id}/draft/copied` | Note that you copied the draft | +| `POST` | `/items/{item_id}/draft/sku-updated` | Note that you updated the Custom label on eBay after a bin move | +| `POST` | `/items/{item_id}/draft/live` | "I listed it": the eBay item address records a listing and marks the item listed | +| `GET` | `/items/{item_id}/photos.zip` | The item's photos in listing order, cover first | + +### Scans + +| Method | Path | What it does | +|---|---|---| +| `GET` | `/scans` | Open scans (or all with `open=false`) | +| `POST` | `/scans` | Start a scan: a `box` (with what you paid, which starts its lot) or a `unit` | +| `GET` | `/scans/{scan_id}` | One scan with its proposal | +| `POST` | `/scans/{scan_id}/photos` | Upload a photo (the raw image as the body, 20 MB at most). Starts identification | +| `GET` | `/scans/{scan_id}/photos/{photo_id}` | One stored photo | +| `POST` | `/scans/{scan_id}/retry` | Identify again | +| `POST` | `/scans/{scan_id}/confirm` | Confirm the name and Keep or Sell for each piece; writes the items | +| `POST` | `/scans/{scan_id}/price` | Price the sell pile. Starts one agent turn | +| `POST` | `/scans/{scan_id}/sell-sealed` | Replace the planned pieces with one sealed item at the sealed price | +| `POST` | `/scans/{scan_id}/finish` | Finish the scan | +| `DELETE` | `/scans/{scan_id}` | Discard a scan, its photos and an empty lot it started | + +### Bins and labels + +| Method | Path | What it does | +|---|---|---| +| `GET` | `/bins` | Every bin with its count, unsold value and when it was last checked | +| `POST` | `/bins` | Create bins | +| `PUT` | `/bins/{bin_id}` | Change a bin's label or note | +| `DELETE` | `/bins/{bin_id}` | Delete an empty bin | +| `POST` | `/bins/move` | Move items into a bin. `put_away: true` also makes a planned piece available | +| `POST` | `/bins/{bin_id}/check` | Save a bin check: strays to move in, unscanned items to flag missing | +| `POST` | `/items/{item_id}/found` | Clear an item's missing flag | +| `GET` | `/labels/base` | Where label QR codes point, and the label stocks | +| `POST` | `/labels/sheet` | Build a label sheet for bins or items, record what was printed, and return a short-lived link to it | + +### Packaging + +| Method | Path | What it does | +|---|---|---| +| `GET` | `/packaging` | Your packaging presets | +| `POST` | `/packaging` | Add a preset: name, length/width/height in inches, empty weight | +| `PUT` | `/packaging/{packaging_id}` | Change a preset | +| `DELETE` | `/packaging/{packaging_id}` | Delete a preset | + +### Data + +| Method | Path | What it does | +|---|---|---| +| `GET` | `/audit` | The audit trail, newest first, optionally for one entity | +| `POST` | `/import` | Import CSV text (items or lots). Re-import never clobbers | +| `GET` | `/export` | Export items, lots or sales as CSV | + +## Public surface: no token + +Mounted under `/plugins/inventory`. The console frames the view with a plain navigation, and a phone opens +labels from a printed QR, so neither can carry a bearer token. None of these routes reads inventory data. +The host exempts them because the manifest lists them under `public_paths` (the view is exempt because it's +a declared view). + +| Method | Path | What it does | +|---|---|---| +| `GET` | `/view` | The console view's page. Its data comes from the operator surface | +| `GET` | `/b/{bin_id}` | A bin label's landing page. A browser signed in to this console goes straight to the bin; anyone else sees how to open it in the app. The same response for a bin that exists and one that doesn't | +| `GET` | `/i/{item_id}` | An item label's landing page, the same way | +| `GET` | `/sheet/{token}` | A label sheet by its 15-minute token, for printing in the browser. An unknown or expired token answers a short page with no data | + +The landing pages and sheets are sent with `Cache-Control: no-store`, `Referrer-Policy: no-referrer` and +`X-Robots-Tag: noindex`. diff --git a/docs/assets/hero.webp b/docs/assets/hero.webp new file mode 100644 index 0000000..4ea8fc8 Binary files /dev/null and b/docs/assets/hero.webp differ diff --git a/docs/assets/phone-next.webp b/docs/assets/phone-next.webp new file mode 100644 index 0000000..f31f45d Binary files /dev/null and b/docs/assets/phone-next.webp differ diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..a246169 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,69 @@ +# Configuration + +Most settings are in **Settings → Plugins → Inventory**. In YAML they sit under `inventory:` in your +agent's `config/langgraph-config.yaml`. One key, `db_path`, is YAML-only. The plugin has no secrets. + +`tests/test_docs_reference.py` fails if the manifest gains or drops a key without this page changing. + +```yaml +plugins: + enabled: [inventory] +inventory: + workspace_dir: /path/to/agent/workspace + weekly_review: true + review_timezone: America/Los_Angeles +``` + +## Where things live + +| Key | Default | In Settings | What it does | +|---|---|---|---| +| `db_path` | `""` | no | Where the SQLite file lives. Blank uses the host's instance-scoped plugin store, so every agent and the dev sandbox get their own database. Set it only to point at an existing file. Scan photos are kept beside the database | +| `workspace_dir` | `""` | Workspace directory | Relative paths given to `inventory_import_csv` and `inventory_export_csv` resolve here. Blank uses the process working directory. Point it at the agent workspace | + +## Weekly review + +A recurring agent turn the plugin schedules on the host. It re-prices stale evidence from eBay sold comps, +reports stale listings with a recommendation (it never changes a listing itself) and ends with the per-lot +P&L. Turning the plugin off cancels it. + +| Key | Default | In Settings | What it does | +|---|---|---|---| +| `weekly_review` | `false` | Weekly review | Arms the recurring turn | +| `weekly_review_cron` | `"0 9 * * 1"` | Weekly review cron | A 5-field cron, read in the review timezone. The default is Monday 09:00 | +| `review_timezone` | `""` | Review timezone | An IANA name such as `America/Los_Angeles`. Blank means UTC | +| `review_max_items` | `15` | Items re-priced per run | The most items one run re-prices. This paces eBay searches; the rest wait for the next run | +| `stale_listing_days` | `14` | Stale listing (days) | A live listing older than this is reported in the review | + +## Stale prices and aging stock + +| Key | Default | In Settings | What it does | +|---|---|---|---| +| `stale_price_days` | `30` | Stale price (days) | Price evidence older than this is stale. The weekly review re-checks it, the view badges it and Next ▸ Housekeeping counts it. Bounded 1 to 365 | +| `aging_days_1` | `45` | Aging: first nudge (days) | Days unsold before Next ▸ Aging stock suggests an offer to watchers or a 10% drop. Bounded 1 to 730 | +| `aging_days_2` | `90` | Aging: second nudge (days) | Days before it suggests another 10% drop or a bundle | +| `aging_days_3` | `120` | Aging: decide (days) | Days before it asks you to decide: clearance, bundle or pull it | + +The three aging tiers are sorted if you set them out of order. A missing or bad value falls back to its +default. + +## Labels + +| Key | Default | In Settings | What it does | +|---|---|---|---| +| `label_base_url` | `""` | Bin label address | The address printed in every label's QR code, up to (not including) `/plugins/inventory`, for example `https://hub.example.ts.net/agents/`. Blank works it out: the agent's public URL (a fleet member's hub address), else its console. A malformed value is refused rather than guessed around | + +Labels you've already printed keep the address they were printed with, so set this before your first +sheet. + +## Scan intake + +| Key | Default | In Settings | What it does | +|---|---|---|---| +| `scan_confidence_threshold` | `0.7` | Scan: sure enough at | 0 to 1. Below this, a scan shows "Not sure. Pick one or type it" with the agent's other guesses instead of offering Looks right | +| `scan_timeout_minutes` | `10` | Scan: give up after (minutes) | An identification that hasn't answered by then shows as failed, with Retry. Pricing gets three times as long | + +## Kept in the browser, not in Settings + +The label stock you last printed on is remembered per kind (bin or item) in the browser's `localStorage`, +because it's about the printer next to you, not the agent. diff --git a/docs/design-decisions.md b/docs/design-decisions.md new file mode 100644 index 0000000..01e1b22 --- /dev/null +++ b/docs/design-decisions.md @@ -0,0 +1,98 @@ +# Design decisions + +Why Inventory is built the way it is. What it does is in [how-it-works.md](how-it-works.md). + +## One database is the record, not a spreadsheet + +The inventory started as CSVs in an agent's workspace. They drifted: two copies of a sheet disagreed, a price +lost the reason it was set, and a sale typed into chat never reached the sheet. A record is only a record if +every change goes through one place with a history, so the plugin owns a SQLite file, every write is one +transaction, and every change is audited with who made it. Spreadsheets stay as import and export. + +## A re-import never clobbers + +Importing a sheet again fills in what's new and leaves the rest alone. A blank cell keeps the current value. A +sheet can't walk a status back from listed, pending or sold, and a sheet without ids matches rows by lot and +name. An old export dropped back in shouldn't undo a week of work. + +## Money in cents, parsed strictly + +Floats round wrong, and loose parsing reads `54%` as $54 and `2026-07` as $2,026. Amounts are stored as +integer cents, and anything that isn't clearly an amount is refused rather than guessed. + +## A price without a reason isn't a price + +The first estimates on real stock came from active asks and retail, presented as if they were sold prices. +So a target can't be set without a basis, the comps are stored with it in the same write, and a price that's +gone stale says so. When you ask why something is $54, there's an answer. + +## Sold comps from a browser, not an API + +eBay's sold-listings data (Marketplace Insights) is closed to new developers, and a seller account's own APIs +need developer keys and OAuth for every agent. The ebay plugin reads sold listings in a signed-in browser +instead. It's slower and it's paced, but it needs nothing but your own eBay login. + +## Nothing posts for you + +There's no eBay write access. A listing draft is text you paste, a pasted sale is a proposal you check, and +the weekly review reports stale listings without touching them. Listing, pricing in public and contacting +buyers stay your decisions. It also keeps a wrong guess from ever reaching a marketplace. + +## Sold only through a sale record + +An item can't be set to sold by editing its status. Recording a sale captures the price, shipping, fees and +postage that make the P&L true, closes the right listing, and puts the item on the pick list. Every way into +"sold" goes through that one path. + +## The double-sell guard flags instead of closing + +When an item sells on one channel while it's listed on another, quietly closing the other listing would leave +it live on the marketplace with nobody knowing. So the listing is flagged `needs_end` and stays on Next until +you've ended it there. + +## The plugin's turns are its own, and narrow + +Identifying a box, writing a draft and reading a pasted sale each run in a session of their own, never your +chat, so they can't clutter it or read it. Each has a short tool list and hard limits (no eBay where it isn't +needed, no subagents, a cap on web searches), because an early pricing session that leaned on general web +search ran to hundreds of tool calls and several dollars for a single lot. + +## The agent never invents item facts + +A guessed model count once made the agent doubt its own correct comps. So unknown counts stay 0, a box's +contents are what the agent can confirm, an unsure identification offers choices and a typing field, and your +correction is kept on the scan. + +## Label first, then put away + +Binning used to be the last step of a scan. In practice you sort pieces into bins after they're labelled, and +a piece already in a bin with no label is the one you can't find later. So a scan ends by printing labels, and +a piece goes into a bin by scanning its label and then the bin's. + +## The view reads its own labels, because of iOS + +iOS never hands a scanned link to a Home Screen web app: a QR read by the Camera app always opens in Safari, +which keeps its own storage and isn't signed in. So the view has **Scan label**, and the public label links +serve a page that sends a signed-in browser straight on and tells anyone else how to open it in the app. + +## Labels encode the plugin's address, not the console's + +A label's QR points at the plugin's own `/b/` or `/i/` route, which forwards to wherever the console opens +views today. Printed paper can't be updated, so only the plugin's stable address is ever printed. + +## A live camera where it's allowed, a photo everywhere + +A viewfinder that reads label after label is much faster than a photo per label, and it works where the view +shares an origin with the console. Where it doesn't, or the camera is refused, the phone's own camera and a +photo always work. QR decoding happens in the page, so photos of your shelves never leave it. + +## Copy list is the operator's own format + +The for-sale post was first built as Markdown with sections and bullets. The operator hand-edited it to what +a group chat actually wants: the game system as a plain header, then `Name NoS — $20` per line, nothing else. +That edit became the format, and a test pins it byte for byte. + +## Settings in Settings, not on the view + +Thresholds such as stale-price days, aging tiers and scan confidence are Settings, not controls on the work +view. The view stays about the work. diff --git a/docs/design/inventory-view-redesign.md b/docs/design/inventory-view-redesign.md index 96e37c8..4c78c3e 100644 --- a/docs/design/inventory-view-redesign.md +++ b/docs/design/inventory-view-redesign.md @@ -1,5 +1,15 @@ # Inventory view redesign: audit and spec +> **Status (0.16.2).** Shipped: the Next / Stock / Bins / Lots IA and the item drawer (0.5.0), bins +> and the pick list (0.6.0), bin labels (0.7.0), scan intake (0.8.0), listing drafts (0.9.0), item +> labels (0.10.0). **Superseded:** the scan flow's S6 bin picker (§3) was replaced in 0.11.0 by +> *label first*: the scan ends with Print labels and pieces are binned later with **Put away**, by +> scanning each piece's label and then the bin's. QR deep links (§4, open question 2) shipped in +> core as protoAgent #4712 (`sdk.view_url`, 0.227.0). Shipped after this spec: paste a sale and the +> double-sell guard (0.12.0), a live camera (0.13.0), aging stock and sealed vs split (0.14.0), +> shipping data, Check a bin and thermal labels (0.15.0), and in-app Scan label (0.16.0). How the +> view works today is in [usage.md](../usage.md); this page is kept as the design record. + Plugin `inventory` 0.4.2, shown as a merchantAgent rail view. Requested by Josh, 2026-11-02. Status: **approved 2026-11-02.** This repo is public, so dollar figures from the real inventory are redacted to `$NN`, and the interactive preview (built on real data) is not committed. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..f1ee116 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,90 @@ +# Development + +Contributor notes: the file layout, the tests, checking the view by hand, and releasing. + +## Layout + +| Path | What it is | +|---|---| +| `__init__.py` | `register()`: opens the store, registers the tools, the two routers, the skill and the weekly review | +| `protoagent.plugin.yaml` | The manifest: config defaults, settings, the view, public paths, events | +| `store.py` | The SQLite store: schema and migrations, every write in one transaction, the audit trail, money in cents | +| `tools.py` | The agent tools | +| `api.py` | The bearer-gated operator API under `/api/plugins/inventory` | +| `view.py` | The console view (one vanilla-JS page on the kit) and the public routes: `/view`, the label landing pages, sheets | +| `automations.py` | The weekly review job, the re-price plan, and the stale-price and aging settings | +| `scans.py` | The scan identification and pricing turns | +| `drafts.py` | The listing-draft turn | +| `sales.py` | The pasted-sale turn | +| `photos.py` | Photo intake: sniff, convert HEIC, strip metadata | +| `labels.py` | Label addresses, the landing pages, the sheets and label stocks | +| `sheetlinks.py` | Short-lived links to rendered label sheets | +| `csvio.py` | CSV import and export | +| `vendor/qrcodegen.py` | Project Nayuki's QR encoder (MIT), unmodified | +| `vendor/jsqr` | jsQR 1.4.0 (Apache-2.0), the QR decoder the view inlines | +| `skills/inventory-ops` | The agent's skill: the rules and the routines | +| `docs/` | These pages, plus `design/` (the view redesign spec) | +| `tests/` | The host-free suite | + +## Tests + +```bash +uv venv --python 3.12 .venv && uv pip install -p .venv/bin/python -r requirements-dev.txt ruff +.venv/bin/ruff check . && .venv/bin/ruff format --check . && .venv/bin/python -m pytest -q +``` + +The suite is host-free: no protoAgent, no database beyond a temp file. A stub `graph.sdk` stands in for the +host where a module needs one. CI runs the same three commands on Python 3.12. Some view tests run the page's +JavaScript under node (`node --check` plus small harnesses); they skip if node isn't installed. + +Tests worth knowing about: + +| Test | What it guards | +|---|---| +| `tests/test_view.py` | The view's four rules (one fetch shim, every call through `apiFetch`, no `--pl-*` definitions, no outside URLs), the public routes (exactly `/view`, `/b/`, `/i/` and `/sheet/`, all GET), and Copy list byte for byte | +| `tests/test_docs_reference.py` | These docs: every route, tool and setting is documented, nothing removed is, defaults match, links resolve | +| `tests/test_plugin.py` | The manifest: the version matches `pyproject.toml`, it ships disabled, the skill is found, and runtime dependencies come from the host | +| `tests/test_hardening.py` | Atomic writes, the sold guard, strict money, non-clobbering import | + +## Checking the view by hand + +The view has no build step. To see a change, mount the real routers on a copy of a database and borrow the +design kit from a running agent: + +1. Copy a database (never work on a live one), or seed an invented one. +2. Start a small FastAPI app that calls `register()` with a fake registry, includes the routers it collects, + and proxies `/_ds/*` to a running protoAgent (for example `http://127.0.0.1:7870/_ds/`). +3. Stub `graph.sdk.run_in_session` to play the agent: call the store's `propose_scan`, `write_draft` or + proposal methods after a short delay. +4. Open `http://127.0.0.1:/plugins/inventory/view` and check it at 390, 495 and 1200 px. + +### A fake camera + +To exercise the live viewfinder without a phone, feed Chromium a video of labels: + +```bash +ffmpeg -loop 1 -i label.jpg -t 4 -vf "scale=1920:1440,format=yuvj420p" -r 10 -c:v mjpeg labels.mjpeg +chromium --use-fake-device-for-media-stream --use-fake-ui-for-media-stream \ + --use-file-for-fake-video-capture=labels.mjpeg +``` + +The view only gets a live camera where it shares an origin with the console. A standalone harness page is its +own origin, so the camera works there too. + +## Releasing + +Versions are bumped in feature PRs and cut by a separate release PR, the same ritual as the other +fleet plugins. + +1. **In the PR that changes behavior**, bump `version` in `protoagent.plugin.yaml` and `pyproject.toml` + together, and add a note to [upgrading.md](upgrading.md) if existing users need to know. +2. **To cut a release**, merge a PR titled `chore: release vX.Y.Z` whose version matches the manifest. + `.github/workflows/release.yml` calls `protoLabsAI/release-tools`' reusable `plugin-release.yml`, + which tags `vX.Y.Z`, writes the release notes, creates the GitHub release and posts the fleet's + Discord embed. It skips every other push, and it's idempotent if the tag already exists. Don't + create releases by hand with `gh release create`. +3. **Agents pick it up** when the plugin is updated: `POST /api/plugins/inventory/update` on the agent + re-installs from the default branch and hot-reloads. Back up `inventory.db` first if the release + migrates the database. + +A behavior change worth a note for existing users goes in [upgrading.md](upgrading.md). diff --git a/docs/how-it-works.md b/docs/how-it-works.md new file mode 100644 index 0000000..e377146 --- /dev/null +++ b/docs/how-it-works.md @@ -0,0 +1,137 @@ +# How it works + +What the plugin stores, how it decides things, and what it asks the agent to do. The reasoning behind each +choice is in [design-decisions.md](design-decisions.md). + +## One database is the source of truth + +Everything lives in one SQLite file the plugin owns, `inventory.db`, in the host's instance-scoped plugin store +(or at `db_path`). Each agent and the dev sandbox get their own. Scan photos are kept beside it, stripped of +metadata. Spreadsheets are an import and an export, never the record. + +Every write is one transaction under a process lock, so a parallel tool call can't half-apply. + +## The data model + +| Thing | What it is | +|---|---| +| **Lot** | A purchase: what it cost, when, from where. P&L is worked out against the lot's cost | +| **Item** | One sellable thing from a lot, with its game system, condition, quantity, status, bin, price band and the basis for that band | +| **Price observation** | The comps behind a price: source, count, p25 / median / p75 and the search used. Written with the price, in the same transaction | +| **Listing** | Where an item is up for sale: channel, address, price, state | +| **Sale** | What it actually sold for, with shipping charged, fees and postage. Net = price + shipping charged − fees − shipping cost | +| **Bin** | Where items physically are (B01, B02…), with a label, a note and when it was last checked | +| **Scan** | A photographed box or piece, the agent's proposal, and your correction | +| **Draft** | An item's eBay listing draft and its state | +| **Sale paste** | A pasted order, the agent's reading of it, and what you recorded | +| **Packaging** | Your packaging presets: name, box size, empty weight | +| **Audit** | Every change, who made it (`agent` or `console`) and the fields that changed | + +### Item statuses + +| Status | Meaning | +|---|---| +| `planned` | A piece that will exist once a box is split. Its target counts toward the lot, but it isn't for sale yet. Shown as "to split" | +| `available` | For sale | +| `listed` | Live on at least one channel | +| `pending` | Sold but not settled, or on hold for a buyer | +| `sold` | Set only by recording a sale | +| `kept` | You're keeping it | +| `withdrawn` | Out of the sale pile for another reason | + +Listings are `active`, `ended`, `sold`, or `needs_end`. `needs_end` means the item sold on a different +channel while this listing was still up. Nothing here can take the listing down for you, so it stays on Next +until you end it and press **I ended it**. + +Drafts are `drafting`, `draft`, `copied`, `live` or `failed`. + +## Money + +Money is stored as integer cents and shown as dollars. Parsing is strict: `12.50`, `$1,234.56` and `12,50` +are amounts; `54%`, `2026-07` and `n/a` are not, and are refused rather than guessed. + +## Prices always carry their basis + +`inventory_set_price` refuses a price without a `basis`, such as "eBay sold comps (22 sold, incl. shipping)", +and stores the comps with it. A price older than **Stale price** (30 days by default) is badged and counted, +and the weekly review re-checks it. + +The weekly review uses at least 5 exact sold comps to set a band (p25, median, p75). Pricing from a scan uses +at least 3. With fewer, the item keeps its price and says why. + +## Turns the plugin starts + +Some work needs the model, so the plugin starts an agent turn itself with `sdk.run_in_session`. Each runs in +its own session, never your chat, and each is kept narrow so it stays cheap. + +| Turn | Session | What it may do | Rough cost in our tests | +|---|---|---|---| +| Identify a scan | `inventory-scan-` | See the photos, at most two web searches. No eBay, no pricing, no subagents | About $0.60 on a frontier model | +| Price a scan | `inventory-scan--price` | eBay sold comps for each sell piece, and the box sealed | More: one eBay search per piece | +| Write a listing draft | `inventory-draft-` | The item and its photos, at most one web search | About $0.40 | +| Read a pasted sale | `inventory-sale-` | Match items with `inventory_sale_candidates`. No web, no eBay, no subagents | About $0.55 | +| Weekly review | the plugin's scheduled job | Re-price stale evidence, report stale listings, post the P&L. Never changes a listing | Scales with `review_max_items` | + +A turn answers through its own tools (`inventory_scan_propose`, `inventory_draft_write`, +`inventory_sale_propose`, and their `_fail` partners). The view polls while one is pending. A turn that never +answers shows as failed with Retry after **Scan: give up after** (pricing gets three times as long). + +Photos reach the model through the host's multimodal tool result, so these turns need a vision-capable model. + +## Reading a pasted sale safely + +- A bundle is split across lines and checked against its total. +- A date like "Delivered Mon Dec 23" must land on that weekday, and no sale can be dated in the future. +- Fees are the stated fee, or an estimate from the ebay plugin marked *estimated*, never invented. +- Buyer names, addresses and tracking numbers are never copied. +- Items sold in the last 180 days are among the candidates, so a repeat paste reads **Already recorded**. + +## Labels and their public links + +A label's QR encodes `/plugins/inventory/b/` or `/i/`. `` is **Bin label address**, +else the agent's public URL, else its console. + +These routes are public, because a phone opening a printed QR carries no token. They take only an id, read no +data, and answer the same whether the id exists or not. Each serves a small landing page: + +- A browser already signed in to this console (the console's token in this origin's `localStorage`) goes + straight on to the bin or item. +- Anyone else sees the id, how to open it in the app, and **Sign in here instead**. +- On a host without plugin-view deep links, the page says the console needs an update. + +The label never encodes the console's own route, so a change in how the console opens views never makes +printed labels stale. + +### Label sheets + +`POST /labels/sheet` renders the sheet and returns a link to it: `/plugins/inventory/sheet/`, where +the token is 32 random bytes that live 15 minutes. At most 50 sheets are kept, in memory, so a restart +expires them. A sheet holds only what the printed labels show. + +## Reading QR codes + +The view reads labels itself, with a bundled decoder (jsQR 1.4.0, Apache-2.0, in `vendor/jsqr`). Nothing is +uploaded. It accepts only this plugin's `/i/` and `/b/` paths, from any host, and never opens a decoded +address. + +- **Live camera:** it decodes the centre of the frame about 7 times a second, and the whole frame every third + time, so an off-centre label still reads. The same label is ignored for 2.5 seconds. The camera stops on + Done, when the drawer closes, when the view is hidden, and after 2 minutes of nothing. +- **Photo:** it tries the photo at 1,600 px, full size, then 1,000 px. + +The live camera works where the view and the console share an origin, as they do through a fleet hub. Where +they don't (the desktop app), or the camera is refused, the view falls back to a photo. + +## Bins, put away and packing + +- A move is all or nothing and audited with where the item came from. A put-away move also makes a + `planned` piece `available`. +- A sale waits on **To pack** until you mark it packed. Then an item with no stock left leaves its bin. +- A bin check records `checked_on`. An unscanned item can be flagged missing, which is a date on the item, + not a status. + +## The audit trail + +Every write records the actor and the fields that changed. A deleted item or lot is snapshotted into the +trail first, with its listings, sales and observations, so nothing is lost without a record. **More → +History** shows the trail as sentences. diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 0000000..2122132 --- /dev/null +++ b/docs/install.md @@ -0,0 +1,74 @@ +# Install and setup + +Get Inventory running on a protoAgent agent. Every setting is described in +[configuration.md](configuration.md). + +## Requirements + +- **protoAgent 0.148.0 or later.** The manifest declares `min_protoagent_version: 0.148.0` (the host's + instance-scoped plugin store), and the loader refuses the plugin on older cores. Some features need a newer + host and fall back gracefully without one: + + | Feature | Needs | Without it | + |---|---|---| + | A scanned label opens the bin or item in the console | protoAgent 0.227.0 (plugin-view deep links, [#4712](https://github.com/protoLabsAI/protoAgent/pull/4712)) | The label opens a page that names the bin or item and links to the console | + | **Ask for a re-price** drafts a message in chat | protoAgent 0.206.0 (the chat-compose bridge) | Use the agent in chat yourself | + | Label sheets open in your browser from the desktop app | protoAgent desktop 0.157.0 (it hands plugin links to the system browser) | Copy the sheet link from the print dialog | + +- **A vision-capable model** for scanning a box and for listing drafts: those turns hand the agent your + photos. Everything else works on any model. +- **The [ebay plugin](https://github.com/protoLabsAI/ebay-plugin)**, for prices from eBay sold listings and + for fee estimates (`ebay_price_check`, `ebay_net_proceeds`). Without it you can still set prices by hand, + with a basis. + +## Install + +1. **Install it.** In a running protoAgent: **Console → Plugins → Install from URL**, with + `https://github.com/protoLabsAI/inventory-plugin`. Or from the shell: + + ```sh + python -m server plugin install https://github.com/protoLabsAI/inventory-plugin + ``` + +2. **Turn it on** in **Console → Plugins**. It ships disabled. In YAML: + + ```yaml + plugins: + enabled: [inventory] + ``` + +3. **Set the basics** in **Settings → Plugins → Inventory**: + - **Workspace directory**: where relative CSV paths resolve. Point it at the agent workspace. + - **Weekly review**: on, with your timezone, if you want a Monday re-price and P&L. + - **Bin label address**: leave it blank unless labels need a different address than the agent's own. Set + it before you print your first sheet. + +The database is created on first use in the host's instance-scoped plugin store, so each agent and the dev +sandbox get their own. + +## First steps + +1. **Make bins.** Open **Inventory** from the console's rail, go to **Bins** and create a few (B01, B02…). + Print their labels from **Print labels** and stick one on each box or shelf. +2. **Bring stock in.** Either **Scan a box** for a box you've bought, or **More → Import CSV** to load a + spreadsheet you already keep. The import matches common headers (`inventory_id`, `item`, `lot_id`, + `target_price_usd`, `status`, `sold_price_usd`…) and reports what it couldn't place. +3. **Label and put away.** Print item labels for the pieces, stick them on, then **Bins → Put away** and scan + each piece, then the bin. +4. **Add your packaging** under **More → Packaging** if you want packed weights and box sizes on listings. + None ship with the plugin. + +## On a phone + +Use the console from your Home Screen (the protoAgent web app) through your tailnet, the same way you reach +it in a browser. + +- **Scan inside the app.** Use **Scan label** in Inventory. On an iPhone, a QR scanned with the Camera app + always opens in Safari, never in a Home Screen web app, and Safari keeps its own sign-in. A label opened + that way shows its id and how to open it in the app. A Safari that's already signed in to the console goes + straight to the bin. +- **Live camera or a photo.** Put away, Check a bin and Scan label use a live viewfinder where the browser + allows it (through a fleet hub it does). Otherwise they use your phone's camera to take a photo. A sharp + photo reads a label from about 45 cm away. The live camera needs the label closer, because a video frame + has fewer pixels than a photo. +- **The desktop app** uses photos for scanning, because its frames can't use the camera. diff --git a/docs/tools.md b/docs/tools.md new file mode 100644 index 0000000..97cded9 --- /dev/null +++ b/docs/tools.md @@ -0,0 +1,66 @@ +# Tools + +The agent tools this plugin registers. You don't call these yourself. The agent picks them from what you +ask, and the plugin's own turns (scan identification, pricing, listing drafts, pasted sales) use the turn +tools below. Prices go in and come out in dollars; the database stores cents. + +`tests/test_docs_reference.py` fails if a tool is added or removed without this page changing. + +## Reading the inventory + +| Tool | What it does | +|---|---| +| `inventory_summary` | The P&L per lot: what it cost, what's left to sell at low/target/high, what's been realized (gross and net), and the projected net if the rest sells at target. The start for "how are we doing" | +| `inventory_list` | Items with their target, status and bin, ordered by game system, lot, then category. Filters: lot, status (comma-separated), category, system, bin (`-` for no bin) and a text search | +| `inventory_get` | One item in full: its fields, listings, sales and last 20 price observations | +| `inventory_stale` | What needs attention: listings live longer than `listed_days`, and unsold items whose price evidence is older than `price_days` or missing (`0` uses the Stale price setting) | +| `inventory_reprice_plan` | The re-price worklist: unsold items with stale or missing evidence, oldest first, capped, each with a suggested eBay search and its current band | + +## Changing the inventory + +| Tool | What it does | +|---|---| +| `inventory_upsert_lot` | Create or update a lot: a purchase that items came from, with what it cost. Only the fields you pass change | +| `inventory_upsert_item` | Create an item (a blank id mints one) or update fields on one. Only the fields you pass change. It doesn't set prices or sold status | +| `inventory_delete_item` | Remove an item and its listings, sales and observations for good. Meant for mistakes and duplicates; `withdrawn` or `kept` is the right status for things that just left the sale pile | +| `inventory_set_price` | Set an item's low/target/high **with** the evidence. `basis` is required (for example "eBay sold comps (22 sold, incl. shipping)"), and the comps are recorded as a price observation in the same write | +| `inventory_mark_sold` | Record a sale. Net = price + shipping charged − fees − shipping cost. Decrements quantity, or marks the last unit sold. A live listing on the same channel closes as sold; one on any other channel is flagged `needs_end`. Refuses an item that's already sold unless `force` | +| `inventory_listing` | Track where an item is listed. `add` records a live listing and moves an available item to listed. `end` closes one. `to_end` lists listings still up somewhere for items that sold elsewhere | +| `inventory_bins` | The physical bins (B01, B02…). `list` with counts and unsold value, `create` (the next numbers, or a named one, with a label), `update` a label or note, `delete` an empty bin | +| `inventory_move_to_bin` | Put items into a bin, or `""` to take them out. All or nothing: an unknown item or bin refuses the whole move. Every move is audited | +| `inventory_packing` | The pick list. `list` shows every sale not yet packed, grouped by the bin to pull it from. `packed` ticks one off, and an item with no stock left is taken out of its bin | +| `inventory_import_csv` | Load a spreadsheet from a path or pasted text. Common headers are matched for you. Rows are upserted by id; blank cells keep what's there; a sold row with a price also records the sale. Returns the mapping it used and per-line warnings | +| `inventory_export_csv` | Write items, lots or sales as CSV to a path in the workspace, or return the text. A spreadsheet view, not a backup | + +## Turn tools: scan identification + +The plugin starts these turns itself, in a session of their own. See [how-it-works.md](how-it-works.md). + +| Tool | What it does | +|---|---| +| `inventory_scan_photos` | See a scan's photos (up to 3) and what's already known about it | +| `inventory_scan_propose` | Record what a scan shows: the name, a 0–1 confidence that it's the exact product, up to 3 alternatives, and for a box the pieces it splits into. Unknown model counts stay 0 | +| `inventory_scan_fail` | Give up on a scan with a one-line reason you'll read, such as "the photo is too dark to read the box" | + +## Turn tools: pricing a scan + +| Tool | What it does | +|---|---| +| `inventory_scan_sealed_price` | For a box, record what it would sell for sealed (from eBay sold comps), plus the fees on the sealed price and on the pieces' total. Kept on the scan as a comparison, never as an item price | +| `inventory_scan_pricing_done` | Close the pricing turn, listing each piece it couldn't price and why (for example "only 1 sold comp") | + +## Turn tools: listing drafts + +| Tool | What it does | +|---|---| +| `inventory_draft_item` | See an item and its scan photos for writing its eBay listing | +| `inventory_draft_write` | Save the draft: a title of at most 80 characters and a plain-text description with the condition first. The price always comes from the item's target | +| `inventory_draft_fail` | Give up on a draft with a reason, such as "no photos and the name doesn't say what is in the box" | + +## Turn tools: pasted sales + +| Tool | What it does | +|---|---| +| `inventory_sale_candidates` | Find items matching what sold. Items sold in the last 180 days come back flagged with that sale, so a repeat paste is caught | +| `inventory_sale_propose` | Propose one line per item for you to check: price, shipping charged, fees (marked estimated when they are), postage, channel and date. Nothing is recorded until you press Record | +| `inventory_sale_fail` | Give up on a paste with a reason. `already_recorded` names the item when the paste repeats a recorded sale | diff --git a/docs/upgrading.md b/docs/upgrading.md new file mode 100644 index 0000000..0f2c777 --- /dev/null +++ b/docs/upgrading.md @@ -0,0 +1,89 @@ +# Upgrading + +Version notes that change behavior, newest first. Installing or updating through protoAgent runs the +database migrations for you: every one is additive, and an older database upgrades in place on first +open. Take a copy of `inventory.db` before a big jump anyway. + +## 0.16.2 + +- **Docs only.** The README and `docs/` follow the protoAgent plugin docs standard, and the agent skill + and the plugin description match what the plugin does today. No behavior change. + +## 0.16.1 + +- **One scroll area.** Only the list scrolls; the page around it no longer does. If you embed the view + somewhere unusual, it still fills its frame. +- **The More menu uses the kit's menu items**, with a hover highlight and arrow, Home, End, Enter and + Escape keys. + +## 0.16.0 + +- **Scan label** sits in the view's header (beside **Scan a box** on a phone, which was called **Scan**). + It reads an item or bin label with the camera and opens it. +- **A label link now answers with a small page, not a redirect.** A browser that is signed in to the + console goes straight to the item or bin. One that isn't (on iPhone, a label scanned with the Camera + app always opens Safari) sees the id and how to open it in the app. Printed labels keep working. + +## 0.15.0 + +- **New per-item fields:** packed weight (stored in ounces) and box size, plus packaging presets. Presets + start empty: add your own boxes and mailers under **More → Packaging**. +- **Check a bin** can flag items as missing. Missing is a flag, not a status, and clears when the item + is found, moved, or checked again. +- **Label stocks:** Avery 5160 stays the default. Avery 5163 and two thermal roll sizes are new, and the + last stock you used is remembered in your browser. + +## 0.14.0 + +- **Aging stock** tiers are settings (`aging_days_1/2/3`, defaults 45, 90 and 120 days). Days count from + the listing date when there is one, otherwise from when the item became available. +- **Sealed vs split:** a box scan's pricing turn also prices the sealed box. **Sell it sealed instead** + replaces the planned pieces with one sealed item (audited, and refused once the box is open). + +## 0.13.0 + +- **Put away can use the live camera** where the browser allows it (the console reached through the + hub). Taking a photo is still there as the fallback. +- **A repeat sale paste reads as already recorded** instead of failing as an unknown item. + +## 0.12.0 + +- **Recording a sale off-eBay no longer silently closes a live eBay listing.** The listing is marked + `needs_end` and shows under **Next → End these listings** until you end it on eBay and tap + **I ended it**. An eBay sale still closes its eBay listing. +- **Listing drafts get a Custom label (SKU)** row, bin first (`B03-`). Moving the item to + another bin later shows **Update the custom label on eBay**. + +## 0.11.0 + +- **Label first.** The last step of a box scan is **Print labels**, not a bin picker. Pieces stay out of + any bin until you **Put away**: scan pieces' labels, then the bin's. Putting away makes a planned piece + available, so binning is what puts it up for sale. + +## 0.10.0 and 0.10.1 + +- **Item labels** (Avery 5160) whose QR opens the item. +- **Label sheets open in your browser** through a short-lived link (15 minutes), in the desktop app too, + where the old blank-tab sheet did nothing. + +## 0.9.1 + +- **The stale-price threshold is the `stale_price_days` setting**, which the weekly review already used. + Its default is 30 days, so the view now badges more prices than its old hard-coded 45. +- **Edit no longer changes status.** Use the drawer's Record sale, Keep, Withdraw and Return to stock. + +## 0.7.0 and 0.7.1 + +- **Bin labels with QR codes.** The plugin declares `/plugins/inventory/b/` in `public_paths` so a label + opens without a sign-in. On a protoAgent older than 0.227.0 (no `sdk.view_url`) the link shows a page + naming the bin instead of opening it. + +## 0.6.0 + +- **Bins.** Every sale recorded before 0.6.0 is marked packed by the migration, so **To pack** starts + empty. + +## 0.5.0 + +- **The view was redesigned** around Next, Stock and Lots with one item drawer. Copy list output is + byte-for-byte what it was. diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..6dd7e56 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,184 @@ +# Using it + +Day to day you can ask the agent in chat, or work the **Inventory** view in the console's rail by hand. The +agent's tools are listed in [tools.md](tools.md). + +

+ The Inventory view on a phone: Next shows a sale to pack, items ready to list and a box to split, with Scan label and Scan a box at the bottom +

+ +## The view + +The header has **Scan label**, **Scan a box** and **More**. On a phone, the two scan buttons sit at the +bottom of the screen. + +**More** holds the occasional jobs: Record a sale, Add item by hand, New lot, New bins, Print bin labels, +Packaging, Import CSV, Export CSV and History (every change, as readable sentences). + +Everything about one item lives in its **drawer**: the price with its full basis, the listing draft, the bin, +the label, shipping, the details, and the actions (Record sale, Keep, Withdraw, Return to stock, Edit, +Delete). It opens from the side on a desktop and from the bottom on a phone. + +### Next + +A work queue. Each section only appears when it has something in it, in this order: + +| Section | What's in it | +|---|---| +| **End these listings** | Items that sold somewhere else while still listed on another channel. Open the listing, end it there, then **I ended it** | +| **Sales to check** | Pasted sales the agent has read, waiting for you to check and record | +| **To pack** | Sales not yet packed, grouped by the bin to pull from. **Packed** ticks one off | +| **Needs a look** | Scans that are unsure, failed or unfinished. Each one resumes where you left it | +| **Update the custom label on eBay** | Items that moved bins after you copied their Custom label (SKU) | +| **Copied, not live yet** | Drafts you copied a day ago or more but never marked listed | +| **Aging stock** | Unsold items past an aging tier, with one suggested move each | +| **Ready to list** | Priced, available items with no live listing, with their draft state. **Draft N** drafts several at once | +| **To split** | Lots with planned pieces still to break out | +| **Housekeeping** | Counts: labelled pieces waiting to be put away, unsold items with no bin, missing items, for-sale items with no packed weight, stale prices (with **Ask for a re-price**) | + +**Record a sale** sits at the top of Next. + +### Stock + +Everything you have, grouped by game system the same way Copy list groups it. + +- **For sale / To split / Sold / All** switches what's shown. Kept and withdrawn items are under All. +- **Search** matches the name, condition and id. **Filter** narrows by system, lot or bin, and each active + filter shows as a chip you can remove. +- **Select** rows to **Copy list**, **Move to bin…** or **Print labels**. ⌘C copies too, unless you've + selected text. + +### Bins + +One row per bin with its item count, its unsold value at target, and when it was last checked. Open a bin to +see what's in it, **Move items here**, **Check this bin**, **Copy list** or **Print labels**. **Put away**, +**Print labels** and **New bins** are at the top. + +### Lots + +The P&L. Each lot shows its date, its pieces and its projected net, with a loss marked. A lot's detail has the +four numbers that matter (lot cost, remaining at target, realized net, projected net), its pieces grouped by +state, and its sales. A totals row heads the list. + +## Scan a box in + +1. **Scan a box**, then choose **New box I bought** or **Single piece**. +2. Take a photo (it opens your phone's camera), say what you paid and, if you like, where from. The lot starts + right away, named "Box scanned…" until it's identified, so nothing is lost if you walk away. +3. The agent identifies it in the background, usually in under a minute. You don't have to wait on the + screen. + - **Sure:** the name, the game system and Looks right. + - **Not sure:** up to three guesses to pick from, and a field to type the name. + - **Couldn't tell:** Type the name or Retake photo. +4. **Keep or Sell** each piece. The agent lists the pieces it can confirm. Add more with a photo of a piece. +5. **Price the sell pile.** A second turn prices each piece from eBay sold comps. A piece without enough comps + stays unpriced, and says why. For a box, it also prices the box sealed and shows **Split** against + **Sealed**, after fees when it can work them out. If sealed clearly wins, **Sell it sealed instead…** + turns the pieces back into one sealed item. +6. **Print labels for these pieces.** The last step prints a sticker for each piece you're selling. Then put + them away. + +## Labels + +- **Bin labels:** Bins → **Print labels**. Pick all bins, a range, or only the ones without a printed label. +- **Item labels:** select items in Stock and **Print labels**, or **Print label** in an item's drawer, or the + last step of a scan. +- **Label stock:** Avery 5160 (30 to a sheet, 2⅝″ × 1″), Avery 5163 (10 to a sheet, 4″ × 2″), a Dymo 30252 + address roll (3½″ × 1⅛″), or a 2¼″ × 1¼″ thermal roll. On a sheet, **Start at label** skips labels you've + already used. +- The sheet opens in your browser: a new tab on the web, your default browser from the desktop app. Print it + at 100% (actual size). + +An item label carries its QR, the name, condition and bin, and the item id. It has no price, because the +price changes and the sticker doesn't. + +## Put away + +Label first, then bin by scanning: + +1. **Bins → Put away**, then **Scan with camera** (or **Take a photo**). +2. Point at a piece's label. It's added to the list with a short beep. Do the same for as many pieces as are + going in the same bin. +3. Point at the bin's label and confirm "Put 3 items in B01?". They move into that bin, and a planned piece + becomes available. + +A label that won't read: type the item or bin id. **Weigh** on a piece in the list records its packed weight +and box on the way. + +## Scan label + +**Scan label** reads any of your labels: an item's opens its drawer, a bin's opens the bin. It uses the live +camera, a photo, or a typed id. + +## Check a bin + +Open a bin, **Check this bin**, and scan the label on every piece in it. The list shows what's found, what's +not scanned yet, and anything that doesn't belong (in another bin, in no bin, or sold and packed). **Finish +check** moves strays in, can flag the unscanned as missing, and stamps the bin as checked. A missing item +turns up again with a later check, any move, or **Found it** in its drawer. + +## Price stock + +Ask in chat ("re-price the Blood Bowl teams from sold comps"), or use **Ask for a re-price** under +Housekeeping, which drafts the request in chat for you to send. Or **Set price** in an item's drawer: a +target always needs a basis. + +The weekly review, if it's on, re-prices the oldest evidence every Monday and reports listings that have been +up too long. + +## List on eBay + +1. **Draft listing** in an item's drawer, or **Draft N** on Next ▸ Ready to list (at most 10, one after + another). +2. Copy the **title** (80 characters at most), **price**, **description**, **Custom label (SKU)** and, if + you've recorded them, **package weight** and **size**. **Download photos** gets the photos in order. +3. List it on eBay yourself. +4. **I listed it**, and paste the listing address (`ebay.com/itm/…` or the app's share link). The item is now + listed. + +The Custom label is bin first (`B03-`), so eBay's own pick list and order search show where it is. +If the item moves bins later, Next reminds you to update it on eBay. + +## Record a sale + +- **Paste it:** **Record a sale** on Next (or More, or "Paste the order instead" in an item's Record sale + dialog). Paste an eBay order, a Seller Hub row, an app's share text or a note. The agent finds the item and + proposes the price, shipping charged, fees (marked estimated when they are), postage, channel and date. + Change anything, then **Record**. Nothing is recorded until you do. A paste that repeats a recorded sale + says **Already recorded** with a link to the item. +- **By hand:** **Record sale** in an item's drawer. +- **In chat:** "Sold the Goblin team for $39 plus $6 shipping on eBay." + +Sold items land on **To pack** with their bin. If the item was also listed on another channel, Next shows it +under **End these listings**. + +## Aging stock + +Items that haven't sold get one suggestion per tier (45, 90 and 120 days by default): an offer to watchers or +a 10% drop, then another drop or a bundle, then a decision. **Mark down…** opens the Price dialog 10% lower +with a basis filled in. **Bundle…** drafts a chat message asking the agent to propose a bundle. **Snooze 14 +days** hides an item until then. Each row says what its days count from: the listing date, or when it became +available if it isn't listed. + +## Copy list + +Select items in Stock or a bin, then **Copy list**. You get a post for a group chat: + +``` +Blood Bowl +Halfling team NIB — $41 +Goblin team NIB — $39 +``` + +The game system is a header, then one line per item with its condition and a whole-dollar price. + +## In chat + +| To | Say something like | +|---|---| +| See the P&L | "How are we doing?" · "How did the patrol box do?" | +| Find things | "What's in B02?" · "Where's the star player pair?" | +| Fix a record | "The Halfling team is NIB, not NoS." | +| Price | "Re-price everything with stale evidence." | +| Record a sale | "Sold the rulebook locally for $15." | +| Import | "Import inventory.csv from the workspace." | diff --git a/protoagent.plugin.yaml b/protoagent.plugin.yaml index 5d34c40..cbba92f 100644 --- a/protoagent.plugin.yaml +++ b/protoagent.plugin.yaml @@ -1,19 +1,19 @@ id: inventory name: Inventory (resale source of truth) -version: 0.16.1 +version: 0.16.2 description: >- - The resale inventory as a source of truth: lots (what you bought and for how much), - items (what each lot split into, its condition and status), listings (where each item is - up for sale), sales (what it actually sold for, net of fees and postage) and price - observations (the comps a target rests on) — in a SQLite file this plugin owns, with an - audit trail of every change and who made it. + Inventory for resellers who buy in lots and sell piece by piece. Tracks what you bought, what each + box split into, which bin every piece is in, what it's worth (eBay sold comps, each price with its + basis), where it's listed and what it sold for, with profit per lot and an audit trail of every + change. - Contributes agent tools for every operation (summary/P&L, list, get, upsert lot/item, - set price with evidence, mark sold, listings, CSV import/export, stale review, re-price - plan, scan intake: identify a photographed box or piece and price its sell pile), an optional weekly-review job on the host scheduler, a console rail view (a work queue, stock and lot P&L tabs, one item drawer with - price / sold / listing actions, CSV import/export and a readable history) and a bearer-gated JSON API under - /api/plugins/inventory. Money is stored as integer cents and exposed as dollars. Ships - DISABLED; enable with `plugins: { enabled: [inventory] }`. + The Inventory view gives you a work queue (to pack, listings to end, scans to check, ready to + list, aging stock), phone-first box scanning with agent identification, QR labels for bins and + items, label-first put-away with the camera, listing drafts you paste into eBay yourself, paste-a- + sale, packing data, bin checks and a Copy list for group chats. It never posts, lists or messages + anyone. Contributes agent tools for every operation, a bearer-gated JSON API under + /api/plugins/inventory, and an optional weekly review. Ships DISABLED; enable it in Console → + Plugins. enabled: false repository: https://github.com/protoLabsAI/inventory-plugin min_protoagent_version: "0.148.0" # sdk.plugin_store (the instance-scoped store) first shipped in 0.148 diff --git a/pyproject.toml b/pyproject.toml index 2299aec..ef8af31 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "inventory-plugin" -version = "0.16.1" +version = "0.16.2" description = "Resale inventory as a source of truth for protoAgent — lots, items, listings, sales, price evidence, audit" requires-python = ">=3.11" license = "MIT" diff --git a/skills/inventory-ops/SKILL.md b/skills/inventory-ops/SKILL.md index fb01344..d69ef62 100644 --- a/skills/inventory-ops/SKILL.md +++ b/skills/inventory-ops/SKILL.md @@ -23,10 +23,19 @@ not a note. If a number is not in the inventory, it has not been decided. re-price explainable. - **Listings** — where an item is up (channel, url, price). `inventory_listing add|end`. - **Sales** — what it actually sold for. `inventory_mark_sold` computes - `net = price + shipping charged − fees − shipping cost` and closes live listings. + `net = price + shipping charged − fees − shipping cost`. A live listing on the SAME channel + closes as sold; one on any other channel is flagged `needs_end` (still up on that + marketplace) and the result lists it. Tell the operator to end it there — the view shows it + under Next → End these listings until they tap **I ended it**. - **Bins** — where an item physically is (B01, B02 …). `inventory_bins` lists, creates, relabels and deletes empty bins; `inventory_move_to_bin` records a move; `inventory_list(bin_id="B03")` shows a bin's contents, `bin_id="-"` the items in no bin. + The operator normally bins in the view, **label first**: a scanned box's pieces get QR + labels, then **Put away** scans each piece's label and the bin's, which moves them and makes + a `planned` piece `available`. Answer "where is X" from `inventory_get` / `inventory_list`; + an item flagged missing by Check a bin has `missing_since` set. +- **Shipping** — packed weight (ounces) and box size per item, entered in the view. Quote + them when drafting or answering shipping questions; never guess a weight. - **Pick list** — every sale not yet packed, with the bin to pull it from. `inventory_packing list`, then `inventory_packing packed` once the operator says it is packed (a sold-out item then leaves its bin). @@ -88,7 +97,11 @@ two web searches to confirm a box's contents. `confidence` is how sure you are o product; give up to 3 alternatives when unsure. For a box, list the pieces it splits into, with `model_count` 0 for anything you cannot see or confirm. Never pad the list. In a **pricing** turn, follow "Re-pricing an item" for each item listed, set no price below 3 -relevant sold comps, and finish with `inventory_scan_pricing_done(scan_id, unpriced)`. Don't +relevant sold comps, and finish with `inventory_scan_pricing_done(scan_id, unpriced)`. When the +prompt names the box itself, also price it SEALED the same way and record that with +`inventory_scan_sealed_price` (never `inventory_set_price` — the sealed box is not an item); +pass the fees from `ebay_net_proceeds` when you have them so the view can compare net, not +gross. Don't message the operator from either turn; the view shows the result. ## Listing-draft turns @@ -102,3 +115,16 @@ on the first line, and only what the record and photos show. No eBay, pricing to subagents, and a web search only when the record lacks the basics. The price is the item's target and is never part of the draft. Nothing is posted: the operator lists it and records the URL. Don't message the operator from the turn. + +## Sale-paste turns + +**Record a sale** in the view stores the operator's pasted order or note and starts a turn in +that paste's own session. Read the text, find each item with `inventory_sale_candidates` (search +by name, part number and product type; it also returns recent SOLD matches), then call +`inventory_sale_propose(paste_id, lines, confidence, questions)` once, or `inventory_sale_fail`. +One paste can cover several items: split a bundle price the way the operator said, otherwise say +how you split it. Use the fee from the text when it's there; an estimate must be marked +`fees_estimated`. Never stamp a year onto a date like "Mon Dec 23" without checking the weekday — +ask in `questions` and default to today. If a candidate shows the same item already sold at a +similar price and date, fail with `already_recorded` instead of proposing a second sale. Nothing +is recorded until the operator taps Record. No web, eBay or subagents; don't message the operator. diff --git a/tests/test_docs_reference.py b/tests/test_docs_reference.py new file mode 100644 index 0000000..e743a12 --- /dev/null +++ b/tests/test_docs_reference.py @@ -0,0 +1,150 @@ +"""The reference docs must describe the code that exists. + +Docs drift because nothing fails when they do. These tests fail. They check COVERAGE, not prose: +every route, tool and setting the code exposes appears in its reference page, and no page names +one that no longer exists. What each one means is a human's job. (The same guard as +projectBoard-plugin's tests/test_docs_reference.py.) +""" + +from __future__ import annotations + +import ast +import pathlib +import re + +import yaml + +_ROOT = pathlib.Path(__file__).resolve().parent.parent +_DOCS = _ROOT / "docs" +_ROW = re.compile(r"^\| `(GET|POST|PUT|PATCH|DELETE)` \| `([^`]+)` \|", re.M) + + +def _decorated_routes(path: pathlib.Path, namespace: dict) -> set[tuple[str, str]]: + """(VERB, path) for every ``@r.(...)`` route in a module, read from the AST so a new + decorator can't slip past a text search. A path built from a constant (``LABEL_PREFIX + + "/{bin_id}"``) is evaluated against ``namespace``.""" + found: set[tuple[str, str]] = set() + for node in ast.walk(ast.parse(path.read_text())): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + for dec in node.decorator_list: + if not isinstance(dec, ast.Call) or not dec.args: + continue + verb = getattr(dec.func, "attr", "") + owner = getattr(getattr(dec.func, "value", None), "id", "") + if verb in ("get", "post", "put", "patch", "delete") and owner == "r": + route = eval(compile(ast.Expression(dec.args[0]), str(path), "eval"), {}, namespace) # noqa: S307 + found.add((verb.upper(), route)) + return found + + +def _operator_routes() -> set[tuple[str, str]]: + return _decorated_routes(_ROOT / "api.py", {}) + + +def _public_routes() -> set[tuple[str, str]]: + from inventory_plugin.labels import ITEM_PREFIX, LABEL_PREFIX + from inventory_plugin.sheetlinks import SHEET_PREFIX + from inventory_plugin.view import VIEW_PATH + + ns = { + "VIEW_PATH": VIEW_PATH, + "LABEL_PREFIX": LABEL_PREFIX, + "ITEM_PREFIX": ITEM_PREFIX, + "SHEET_PREFIX": SHEET_PREFIX, + } + return _decorated_routes(_ROOT / "view.py", ns) + + +def _tools() -> set[str]: + names = set() + for node in ast.walk(ast.parse((_ROOT / "tools.py").read_text())): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and any( + ast.unparse(d).split("(")[0] == "tool" for d in node.decorator_list + ): + names.add(node.name) + return names + + +def _manifest_keys() -> set[str]: + manifest = yaml.safe_load((_ROOT / "protoagent.plugin.yaml").read_text()) + keys = set(manifest.get("config") or {}) + keys |= {f["key"] for f in manifest.get("settings") or [] if isinstance(f, dict) and "key" in f} + return keys + + +def _doc_rows(page: str) -> set[tuple[str, str]]: + return set(_ROW.findall((_DOCS / page).read_text())) + + +def test_the_code_exposes_what_these_tests_think_it_does(): + # A guard that reads nothing passes everything. Pin the extractors to real numbers. + assert len(_operator_routes()) >= 60 + assert ("GET", "/b/{bin_id}") in _public_routes() + assert "inventory_mark_sold" in _tools() and len(_tools()) >= 25 + assert {"db_path", "stale_price_days", "aging_days_1"} <= _manifest_keys() + + +def test_every_route_is_in_the_api_reference_and_none_that_was_removed(): + documented = _doc_rows("api.md") + live = _operator_routes() | _public_routes() + missing = sorted(f"{v} {p}" for v, p in live if (v, p) not in documented) + stale = sorted(f"{v} {p}" for v, p in documented if (v, p) not in live) + assert not missing, f"docs/api.md is missing {missing}: add the row, with what the route is for" + assert not stale, f"docs/api.md documents routes that no longer exist: {stale}" + + +def test_every_agent_tool_is_in_the_tools_reference_and_none_that_was_removed(): + doc = (_DOCS / "tools.md").read_text() + documented = set(re.findall(r"^\| `(inventory_[a-z_]+)` \|", doc, re.M)) + missing = sorted(_tools() - documented) + stale = sorted(documented - _tools()) + assert not missing, f"docs/tools.md is missing {missing}: every agent tool needs a row" + assert not stale, f"docs/tools.md documents tools that no longer exist: {stale}" + + +def test_every_setting_is_in_the_configuration_reference_and_none_that_was_removed(): + doc = (_DOCS / "configuration.md").read_text() + documented = set(re.findall(r"^\| `([a-z_0-9]+)` \| `", doc, re.M)) + missing = sorted(_manifest_keys() - documented) + stale = sorted(documented - _manifest_keys()) + assert not missing, f"docs/configuration.md is missing {missing}: add key, default and effect" + assert not stale, f"docs/configuration.md documents keys the manifest no longer has: {stale}" + + +def test_the_configuration_defaults_match_the_manifest(): + manifest = yaml.safe_load((_ROOT / "protoagent.plugin.yaml").read_text())["config"] + doc = (_DOCS / "configuration.md").read_text() + for key, default in manifest.items(): + shown = re.search(rf"^\| `{key}` \| `([^`]*)` \|", doc, re.M).group(1) + expected = '""' if default == "" else str(default).lower() if isinstance(default, bool) else str(default) + assert shown.strip('"') == expected.strip('"'), f"{key}: docs say {shown}, manifest says {default!r}" + + +def test_the_layout_table_names_only_files_that_exist(): + body = (_DOCS / "development.md").read_text().split("## Layout", 1)[1].split("\n## ", 1)[0] + names = re.findall(r"^\| `([A-Za-z0-9_./-]+)` \|", body, re.M) + assert names, "docs/development.md lost its Layout table" + gone = [n for n in names if not (_ROOT / n).exists()] + assert not gone, f"docs/development.md's Layout table names files that don't exist: {gone}" + + +def test_every_relative_link_in_the_docs_resolves(): + pages = [_ROOT / "README.md", *sorted(_DOCS.rglob("*.md")), _ROOT / "skills" / "inventory-ops" / "SKILL.md"] + broken = [] + for page in pages: + for target in re.findall(r"\]\(([^)\s]+)\)", page.read_text()): + if re.match(r"[a-z]+:", target) or target.startswith("#"): + continue + path = (page.parent / target.split("#", 1)[0]).resolve() + if not path.exists(): + broken.append(f"{page.relative_to(_ROOT)} → {target}") + assert not broken, f"broken relative links: {broken}" + + +def test_the_install_steps_name_real_cli_subcommands(): + # A setup step that can't run is worse than a missing one. Real verbs of `python -m server + # plugin` (protoAgent docs/guides/cli.md: install, list, update, uninstall, sync). + text = (_ROOT / "README.md").read_text() + (_DOCS / "install.md").read_text() + claimed = set(re.findall(r"python -m server plugin ([a-z][a-z-]*)", text)) + assert claimed and claimed <= {"install", "list", "update", "uninstall", "sync"}, claimed