pikkolo 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: pikkolo
3
+ Version: 0.1.0
4
+ Summary: Fabricate and assemble a PCB with Pikkolo from the command line. Built for AI agents.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://www.pikkoloassembly.com
7
+ Project-URL: Instructions, https://www.pikkoloassembly.com/agent/SKILL.md
8
+ Keywords: pcb,pcba,assembly,fabrication,kicad,tscircuit,agent
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+
12
+ # pikkolo
13
+
14
+ Turn a PCB design into a [Pikkolo](https://www.pikkoloassembly.com) fabrication
15
+ and assembly project from the command line. Built for AI coding agents: a user
16
+ says "fabricate this board with Pikkolo", and the agent exports the fab files,
17
+ creates the project, gets every BOM line matched to a purchasable part, and
18
+ hands back a link where the user reviews the quote and orders.
19
+
20
+ No account or API key is needed. Nothing is ordered or charged from the command
21
+ line.
22
+
23
+ ## For agents
24
+
25
+ Read the instructions first. They cover exporting from KiCad, tscircuit and
26
+ other EDA tools, writing a clean BOM, and resolving every line:
27
+
28
+ https://www.pikkoloassembly.com/agent/SKILL.md
29
+
30
+ ## Use
31
+
32
+ ```sh
33
+ pikkolo new --gerbers gerbers.zip --bom bom.csv --placements placements.csv --qty 5
34
+ pikkolo status --wait
35
+ pikkolo search C12 "100nF 16V X7R 0402"
36
+ pikkolo assign C12 1
37
+ pikkolo url
38
+ ```
39
+
40
+ `pikkolo --help` lists every command. It needs Python 3.8 or newer and uses only
41
+ the standard library.
42
+
43
+ This package is the same single file published at
44
+ https://www.pikkoloassembly.com/agent/pikkolo.py, which is always the newest
45
+ copy.
@@ -0,0 +1,6 @@
1
+ pikkolo.py,sha256=Dr4o30bN9amVp1QOMhFBe3k3VCWV2uFJwX0jeZ20eHU,26846
2
+ pikkolo-0.1.0.dist-info/METADATA,sha256=_SdM56jOfouB6ETEqhfSIK3dYQQ2jiW7kFyD-qRvvrM,1540
3
+ pikkolo-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ pikkolo-0.1.0.dist-info/entry_points.txt,sha256=IT6IjA-m8q7og3nh7PSUSD8CwS_64GuwTDZh8JMKr8g,41
5
+ pikkolo-0.1.0.dist-info/top_level.txt,sha256=troQH3pk-4P6NG3jj7aYZ1rnKLHMbp2DYnyvQ9gXjs0,8
6
+ pikkolo-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pikkolo = pikkolo:main
@@ -0,0 +1 @@
1
+ pikkolo
pikkolo.py ADDED
@@ -0,0 +1,617 @@
1
+ #!/usr/bin/env python3
2
+ """pikkolo: turn fab files into a Pikkolo project an agent can finish.
3
+
4
+ Standard library only, Python 3.8+. It speaks the same anonymous API the quote
5
+ page does: creating a project hands back a per-project key, and that key is all
6
+ that is ever needed. Nothing here can order or pay; the customer does that in
7
+ the browser at the URL this prints.
8
+
9
+ State (project id + key) is kept in ./.pikkolo.json so later commands find the
10
+ project again. Treat that file like a password for the draft.
11
+ """
12
+
13
+ import argparse
14
+ import json
15
+ import mimetypes
16
+ import os
17
+ import sys
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ import uuid
22
+
23
+ API = os.environ.get("PIKKOLO_API", "https://api.pikkoloassembly.com/v1").rstrip("/")
24
+ SITE = os.environ.get("PIKKOLO_SITE", "https://www.pikkoloassembly.com").rstrip("/")
25
+ STATE = os.environ.get("PIKKOLO_STATE", ".pikkolo.json")
26
+ AGENT = "pikkolo-skill/0.1"
27
+ STALL_SECONDS = 100
28
+
29
+ # What a project accepts before it is submitted. Shipping address and payment
30
+ # are the customer's to enter on the page.
31
+ SETTABLE = {
32
+ "qty": ("qty_boards", int),
33
+ "layers": ("fab_layers", int),
34
+ "double_sided": ("double_sided_assembly", lambda v: v.lower() in ("1", "true", "yes")),
35
+ "stencil": ("include_stencils", lambda v: v.lower() in ("1", "true", "yes")),
36
+ "boards": ("board_source", str), # pikkolo_fab | direct_from_fab | ship_yourself
37
+ "notes": ("notes", str),
38
+ }
39
+
40
+
41
+ class ApiError(Exception):
42
+ def __init__(self, status, text):
43
+ super().__init__(f"HTTP {status}: {text.strip()[:400]}")
44
+ self.status = status
45
+
46
+
47
+ def die(msg, code=1):
48
+ print(f"error: {msg}", file=sys.stderr)
49
+ sys.exit(code)
50
+
51
+
52
+ def load_state():
53
+ if not os.path.exists(STATE):
54
+ die(f"no project here ({STATE} not found). Run `pikkolo.py new` first.")
55
+ with open(STATE) as f:
56
+ return json.load(f)
57
+
58
+
59
+ def save_state(state):
60
+ with open(STATE, "w") as f:
61
+ json.dump(state, f, indent=2)
62
+ os.chmod(STATE, 0o600)
63
+
64
+
65
+ def request(method, path, key=None, body=None, form=None, timeout=60):
66
+ headers = {"User-Agent": AGENT}
67
+ data = None
68
+ if key:
69
+ headers["X-Project-Key"] = key
70
+ if body is not None:
71
+ data = json.dumps(body).encode()
72
+ headers["Content-Type"] = "application/json"
73
+ elif form is not None:
74
+ boundary = uuid.uuid4().hex
75
+ parts = []
76
+ for name, value in form.items():
77
+ if isinstance(value, tuple):
78
+ filename, content = value
79
+ ctype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
80
+ parts.append(
81
+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; '
82
+ f'filename="{filename}"\r\nContent-Type: {ctype}\r\n\r\n'.encode()
83
+ + content
84
+ + b"\r\n"
85
+ )
86
+ else:
87
+ parts.append(
88
+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
89
+ )
90
+ data = b"".join(parts) + f"--{boundary}--\r\n".encode()
91
+ headers["Content-Type"] = f"multipart/form-data; boundary={boundary}"
92
+ req = urllib.request.Request(API + path, data=data, method=method, headers=headers)
93
+ try:
94
+ with urllib.request.urlopen(req, timeout=timeout) as res:
95
+ text = res.read().decode()
96
+ except urllib.error.HTTPError as e:
97
+ raise ApiError(e.code, e.read().decode(errors="replace"))
98
+ except urllib.error.URLError as e:
99
+ die(f"could not reach {API}: {e.reason}")
100
+ return json.loads(text) if text.strip() else None
101
+
102
+
103
+ def upload(state, kind, path):
104
+ if not os.path.isfile(path):
105
+ die(f"{kind} file not found: {path}")
106
+ with open(path, "rb") as f:
107
+ content = f.read()
108
+ request(
109
+ "POST",
110
+ f"/projects/{state['id']}/files",
111
+ key=state["key"],
112
+ form={"kind": kind, "file": (os.path.basename(path), content)},
113
+ timeout=180,
114
+ )
115
+ print(f"uploaded {kind}: {os.path.basename(path)} ({len(content)} bytes)")
116
+
117
+
118
+ def get_project(state):
119
+ return request("GET", f"/projects/{state['id']}/", key=state["key"])
120
+
121
+
122
+ def row_of(item):
123
+ row = item.get("row_json")
124
+ if isinstance(row, str):
125
+ try:
126
+ row = json.loads(row)
127
+ except ValueError:
128
+ row = {}
129
+ return row if isinstance(row, dict) else {}
130
+
131
+
132
+ def search_result_of(item):
133
+ sr = item.get("search_result")
134
+ return sr if isinstance(sr, dict) else {}
135
+
136
+
137
+ def item_done(item):
138
+ return item.get("status") in ("succeeded", "failed")
139
+
140
+
141
+ def designators(item):
142
+ """The line's reference designators, lower-cased. Read from the uploaded row
143
+ when the parser never filled `reference` in (a row it failed on)."""
144
+ text = item.get("reference") or ""
145
+ if not text:
146
+ row = row_of(item)
147
+ for header in row:
148
+ if header.strip().lower() in ("designator", "designators", "reference", "references", "ref", "refs", "refdes", "ref des", "reference designator"):
149
+ text = str(row[header])
150
+ break
151
+ return [r.strip().lower() for r in text.replace(";", ",").replace(" ", ",").split(",") if r.strip()]
152
+
153
+
154
+ def find_item(project, ref):
155
+ """A BOM line by one of its reference designators, or by item id."""
156
+ want = ref.strip().lower()
157
+ for item in project.get("bom_items") or []:
158
+ if item["id"].lower() == want:
159
+ return item
160
+ if want in designators(item):
161
+ return item
162
+ die(f"no BOM line with reference {ref!r}. `status` lists them.")
163
+
164
+
165
+ def parsed_item(project, ref):
166
+ """find_item, refusing a row Pikkolo never parsed: it has no quantity, so a
167
+ part assigned to it would be bought and quoted as a single piece."""
168
+ item = find_item(project, ref)
169
+ if item.get("quantity") is None:
170
+ die(
171
+ f"Pikkolo has not parsed the row for {ref} (status: {item.get('status')}). If `status --wait` reports it "
172
+ "PARSE_FAILED, re-send the BOM with `upload bom <file>` and wait again."
173
+ )
174
+ return item
175
+
176
+
177
+ def fetch_parts(ids, quantities=None):
178
+ """Catalog details for part ids, priced at the quantity each is needed in."""
179
+ ids = [i for i in dict.fromkeys(ids) if i]
180
+ out = {}
181
+ for start in range(0, len(ids), 100):
182
+ chunk = ids[start : start + 100]
183
+ reqs = [{"id": i, "quantity": (quantities or {}).get(i, 1)} for i in chunk]
184
+ res = request("POST", "/parts:batchGet", body={"requests": reqs}, timeout=120)
185
+ for p in (res or {}).get("parts") or []:
186
+ out[p["id"]] = p
187
+ return out
188
+
189
+
190
+ def describe_part(p):
191
+ if not p:
192
+ return "(part details unavailable)"
193
+ sel = p.get("selection") or {}
194
+ if sel.get("available"):
195
+ buy = (
196
+ f"{sel.get('vendor')} {sel.get('vendor_part_number')}, "
197
+ f"{sel.get('quantity_available')} in stock, ${sel.get('landed_unit_price', sel.get('unit_price')):.4g} ea"
198
+ )
199
+ else:
200
+ buy = f"NOT BUYABLE at this quantity ({sel.get('reason')}: {sel.get('detail')})"
201
+ return f"{p.get('manufacturer', '?')} {p.get('mpn')} | {buy} | {(p.get('description') or '')[:90]}"
202
+
203
+
204
+ def progress(project):
205
+ items = project.get("bom_items") or []
206
+ files = {f.get("Kind") for f in project.get("files") or []}
207
+ bom = project.get("bom") or {}
208
+ bom_status = bom.get("Status") or bom.get("status") or ("processing" if "bom" in files else "none")
209
+ drc = (project.get("drc") or {}).get("status") or ("pending" if "gerber" in files else "none")
210
+ area = (project.get("project") or {}).get("BoardAreaSqIn")
211
+ pending = [i for i in items if not item_done(i)]
212
+ done = (
213
+ ("gerber" not in files or area is not None)
214
+ and drc not in ("pending", "processing", "running")
215
+ and not pending
216
+ and ("bom" not in files or bool(items) or bom_status == "failed")
217
+ )
218
+ return {
219
+ "area": area,
220
+ "drc": drc,
221
+ "bom": bom_status,
222
+ "lines": len(items),
223
+ "pending": len(pending),
224
+ "done": done,
225
+ "signature": json.dumps([area, drc, bom_status, sorted((i["id"], i.get("status")) for i in items)]),
226
+ }
227
+
228
+
229
+ def cmd_new(args):
230
+ if os.path.exists(STATE) and not args.force:
231
+ die(f"{STATE} already exists; this directory already has a project. Use `status`, or `new --force` to start over.")
232
+ res = request(
233
+ "POST",
234
+ "/projects",
235
+ body={"ad_tracking": {"utm": {"source": "pikkolo-skill", "medium": "agent"}, "landing_path": "/agent"}},
236
+ )
237
+ state = {"id": res["id"], "key": res.get("access_key") or "", "api": API}
238
+ save_state(state)
239
+ print(f"created project {state['id']}")
240
+ upload(state, "gerber", args.gerbers)
241
+ upload(state, "bom", args.bom)
242
+ upload(state, "placements", args.placements)
243
+ fields = {"qty_boards": args.qty}
244
+ if not args.no_fab:
245
+ fields["board_source"] = "pikkolo_fab"
246
+ if args.layers:
247
+ fields["fab_layers"] = args.layers
248
+ if args.double_sided:
249
+ fields["double_sided_assembly"] = True
250
+ if args.notes:
251
+ fields["notes"] = args.notes
252
+ request("PUT", f"/projects/{state['id']}/", key=state["key"], body=fields)
253
+ print(
254
+ f"{args.qty} boards, {args.layers or 2} layers, "
255
+ f"{'double' if args.double_sided else 'single'}-sided assembly, "
256
+ f"{'assembly only (user supplies boards)' if args.no_fab else 'Pikkolo fabricates the boards'}"
257
+ )
258
+ ignored = os.path.exists(".gitignore") and STATE in open(".gitignore").read().split()
259
+ if not ignored and (os.path.exists(".gitignore") or os.path.isdir(".git")):
260
+ with open(".gitignore", "a") as f:
261
+ f.write(f"\n# Pikkolo draft pointer (holds an access key)\n{STATE}\n")
262
+ ignored = True
263
+ print(f"{STATE} holds this draft's access key" + (" (added to .gitignore)." if ignored else ": keep it out of version control."))
264
+ print("next: `pikkolo.py status --wait`")
265
+
266
+
267
+ def cmd_upload(args):
268
+ state = load_state()
269
+ upload(state, args.kind, args.path)
270
+
271
+
272
+ def cmd_status(args):
273
+ state = load_state()
274
+ deadline = time.time() + args.timeout
275
+ last_signature, last_change = None, time.time()
276
+ while True:
277
+ project = get_project(state)
278
+ prog = progress(project)
279
+ if prog["signature"] != last_signature:
280
+ last_signature, last_change = prog["signature"], time.time()
281
+ # A row whose parse died server-side never reaches a final status.
282
+ # Nothing moving for this long means waiting longer will not help.
283
+ prog["stalled"] = not prog["done"] and time.time() - last_change > STALL_SECONDS
284
+ if prog["done"] or prog["stalled"] or not args.wait or time.time() > deadline:
285
+ break
286
+ print(
287
+ f" processing: board {'measured' if prog['area'] else 'pending'}, "
288
+ f"design-rule check {'running' if prog['drc'] in ('pending', 'processing', 'running') else 'done'}, "
289
+ f"BOM {prog['lines'] - prog['pending']}/{prog['lines'] or '?'} lines resolved",
290
+ file=sys.stderr,
291
+ )
292
+ time.sleep(10)
293
+ report(state, project, prog, as_json=args.json, args_open=args.open)
294
+
295
+
296
+ def report(state, project, prog, as_json=False, args_open=False):
297
+ p = project.get("project") or {}
298
+ items = project.get("bom_items") or []
299
+ qty = p.get("QtyBoards") or 1
300
+ quantities, ids = {}, []
301
+ for item in items:
302
+ need = (item.get("quantity") or 1) * qty
303
+ sr = search_result_of(item)
304
+ for pid in [item.get("matched_part_id")] + (sr.get("ranked_part_ids") or [])[:6]:
305
+ if pid:
306
+ ids.append(pid)
307
+ quantities[pid] = need
308
+ parts = fetch_parts(ids, quantities)
309
+
310
+ lines = []
311
+ for item in sorted(items, key=lambda i: i.get("reference") or ""):
312
+ row = row_of(item)
313
+ sr = search_result_of(item)
314
+ matched = item.get("matched_part_id")
315
+ part = parts.get(matched) if matched else None
316
+ if item.get("exclude_from_bom"):
317
+ state_word = "excluded"
318
+ elif item.get("consigned"):
319
+ state_word = "consigned"
320
+ elif item.get("status") == "failed" or (prog.get("stalled") and not item_done(item)):
321
+ state_word = "PARSE_FAILED"
322
+ elif not item_done(item):
323
+ state_word = "pending"
324
+ elif not matched:
325
+ state_word = "UNMATCHED"
326
+ elif not ((part or {}).get("selection") or {}).get("available"):
327
+ state_word = "UNBUYABLE"
328
+ else:
329
+ state_word = "ok"
330
+ assessment = (sr.get("assessments") or {}).get(matched or "", {})
331
+ lines.append(
332
+ {
333
+ "reference": item.get("reference") or ",".join(designators(item)).upper() or None,
334
+ "quantity_per_board": item.get("quantity"),
335
+ "bom_row": row,
336
+ "state": state_word,
337
+ "matched": describe_part(part) if matched else None,
338
+ "matched_part_id": matched,
339
+ "relationship": assessment.get("relationship"),
340
+ "reason": assessment.get("reason"),
341
+ "cautions": assessment.get("cautions") or [],
342
+ "resolver_message": sr.get("message"),
343
+ "resolver_question": sr.get("question"),
344
+ "candidates": [
345
+ {
346
+ "number": number,
347
+ "part_id": pid,
348
+ "part": describe_part(parts.get(pid)),
349
+ "relationship": (sr.get("assessments") or {}).get(pid, {}).get("relationship"),
350
+ "reason": (sr.get("assessments") or {}).get(pid, {}).get("reason"),
351
+ "cautions": (sr.get("assessments") or {}).get(pid, {}).get("cautions") or [],
352
+ }
353
+ for number, pid in enumerate((sr.get("ranked_part_ids") or [])[:6], 1)
354
+ if pid != matched
355
+ ],
356
+ }
357
+ )
358
+
359
+ quote = None
360
+ try:
361
+ quote = request("GET", f"/projects/{state['id']}/price", key=state["key"])
362
+ except ApiError as e:
363
+ quote = {"error": str(e)}
364
+ drc = project.get("drc") or {}
365
+ open_lines = [l for l in lines if l["state"] in ("UNMATCHED", "UNBUYABLE", "PARSE_FAILED", "pending")]
366
+ tally = {}
367
+ for l in lines:
368
+ tally[l["state"]] = tally.get(l["state"], 0) + 1
369
+ summary = {
370
+ "project_id": state["id"],
371
+ "url": project_url(state),
372
+ "processing_done": prog["done"],
373
+ "stalled": bool(prog.get("stalled")),
374
+ "boards": qty,
375
+ "fab_layers": p.get("FabLayers"),
376
+ "board_area_sq_in": p.get("BoardAreaSqIn"),
377
+ "double_sided_assembly": p.get("DoubleSidedAssembly"),
378
+ "board_source": p.get("BoardSource"),
379
+ "files": sorted({f.get("Kind") for f in project.get("files") or [] if f.get("Kind") in ("gerber", "bom", "placements")}),
380
+ "drc": {"status": drc.get("status"), "summary": drc.get("summary"), "error": drc.get("error_message")},
381
+ "notes": p.get("Notes"),
382
+ "bom_lines": len(lines),
383
+ "bom_line_states": tally,
384
+ "bom_lines_needing_attention": len(open_lines),
385
+ "quote": quote,
386
+ "lines": lines,
387
+ }
388
+ if as_json:
389
+ print(json.dumps(summary, indent=2, default=str))
390
+ return
391
+
392
+ word = "processed" if prog["done"] else "STALLED" if prog.get("stalled") else "STILL PROCESSING"
393
+ print(f"project {state['id']} ({word})")
394
+ print(
395
+ f" {qty} boards, {p.get('FabLayers')} layers, area {p.get('BoardAreaSqIn')} sq in, "
396
+ f"double-sided assembly: {p.get('DoubleSidedAssembly')}, files: {', '.join(summary['files'])}"
397
+ )
398
+ print(f" boards from: {p.get('BoardSource') or 'NOT CHOSEN (set boards=pikkolo_fab, or the user picks on the page)'}")
399
+ print(f" notes to Pikkolo: {p.get('Notes') or '(none)'}")
400
+ stats = (drc.get("summary") or {}).get("stats") or {}
401
+ if drc.get("status") in (None, "pending", "processing", "running"):
402
+ print(f" design-rule check: {drc.get('status') or 'not run'}")
403
+ elif stats:
404
+ found = ", ".join(f"{k.replace('_', ' ')} x{v}" for k, v in sorted(stats.items()))
405
+ print(f" design-rule check against Pikkolo's fab rules: {sum(stats.values())} findings ({found}).")
406
+ print(" Counts only; locations are on the project page. Findings do not block the draft.")
407
+ else:
408
+ print(" design-rule check: no findings")
409
+ print(f"\nBOM: {len(lines)} lines: " + ", ".join(f"{n} {s}" for s, n in sorted(tally.items())))
410
+ for l in lines:
411
+ if args_open and l["state"] in ("ok", "excluded", "consigned") and l["relationship"] in (None, "exact_match"):
412
+ continue
413
+ row = l["bom_row"]
414
+ asked = " / ".join(str(v) for v in list(row.values())[:8] if str(v).strip())[:110]
415
+ print(f"\n[{l['state']}] {l['reference']} (x{l['quantity_per_board']}) BOM row: {asked}")
416
+ if l["matched"]:
417
+ rel = f" [{l['relationship']}]" if l["relationship"] else ""
418
+ print(f" -> {l['matched']}{rel}")
419
+ if l["relationship"] not in (None, "exact_match") and l["reason"]:
420
+ print(f" why this part: {l['reason']}")
421
+ for c in l["cautions"]:
422
+ print(f" caution: {c}")
423
+ if l["state"] == "PARSE_FAILED":
424
+ print(" Pikkolo could not read this row. Re-send the BOM (`upload bom <file>`) to parse it again;")
425
+ print(" do that before assigning parts, since a new BOM starts every line fresh.")
426
+ if l["state"] in ("UNMATCHED", "UNBUYABLE"):
427
+ if l["resolver_message"]:
428
+ print(f" resolver: {l['resolver_message']}")
429
+ if l["resolver_question"]:
430
+ print(f" resolver asks: {l['resolver_question']}")
431
+ for c in l["candidates"]:
432
+ print(f" candidate {c['number']}: {c['part']}")
433
+ print(f" part_id {c['part_id']} [{c['relationship']}] {c['reason'] or ''}")
434
+ for caution in c["cautions"]:
435
+ print(f" caution: {caution}")
436
+ if isinstance(quote, dict) and "total" in quote:
437
+ early = " (PRELIMINARY: unmatched lines are not priced yet)" if open_lines else ""
438
+ print(f"\nquote: ${quote['total']:.2f} total for {qty} boards{early}")
439
+ for it in quote.get("items") or []:
440
+ print(f" {it.get('label')}: ${it.get('total', 0):.2f}")
441
+ for u in quote.get("unavailableParts") or []:
442
+ print(f" not priced: part {u.get('partId')} ({u.get('reason')}: {u.get('detail')})")
443
+ if quote.get("pendingClassifications"):
444
+ print(f" {quote['pendingClassifications']} parts still being classified; the total may rise slightly")
445
+ print(f"\nurl: {summary['url']}")
446
+
447
+
448
+ def cmd_search(args):
449
+ state = load_state()
450
+ project = get_project(state)
451
+ item = parsed_item(project, args.ref)
452
+ body = {"query": args.query, "expected_matched_part_id": item.get("matched_part_id") or ""}
453
+ try:
454
+ res = request("POST", f"/projects/{state['id']}/bom-items/{item['id']}/search", key=state["key"], body=body, timeout=300)
455
+ except ApiError as e:
456
+ die(f"search failed: {e}")
457
+ sr = res.get("search_result") or {}
458
+ parts = {p["id"]: p for p in res.get("parts") or []}
459
+ missing = [pid for pid in sr.get("ranked_part_ids") or [] if pid not in parts]
460
+ if missing:
461
+ qty = (item.get("quantity") or 1) * ((project.get("project") or {}).get("QtyBoards") or 1)
462
+ parts.update(fetch_parts(missing, {pid: qty for pid in missing}))
463
+ print(f"{item.get('reference')}: {sr.get('outcome')}. {sr.get('message') or ''}")
464
+ if sr.get("question"):
465
+ print(f"resolver asks: {sr['question']}")
466
+ for n, pid in enumerate(sr.get("ranked_part_ids") or [], 1):
467
+ a = (sr.get("assessments") or {}).get(pid, {})
468
+ star = " (suggested)" if pid == sr.get("suggested_part_id") else ""
469
+ print(f"\n{n}. {describe_part(parts.get(pid))}{star}")
470
+ print(f" part_id {pid} [{a.get('relationship')}] {a.get('reason') or ''}")
471
+ for c in a.get("cautions") or []:
472
+ print(f" caution: {c}")
473
+ if not sr.get("ranked_part_ids"):
474
+ print("no candidates. Try a different query: an exact MPN, or the specs that matter.")
475
+
476
+
477
+ def cmd_assign(args):
478
+ state = load_state()
479
+ project = get_project(state)
480
+ item = parsed_item(project, args.ref)
481
+ sr = search_result_of(item)
482
+ part_id = args.part
483
+ if part_id.isdigit():
484
+ ranked = sr.get("ranked_part_ids") or []
485
+ if not 1 <= int(part_id) <= len(ranked):
486
+ die(f"{item.get('reference')} has {len(ranked)} candidates; {part_id} is out of range.")
487
+ part_id = ranked[int(part_id) - 1]
488
+ assessment = (sr.get("assessments") or {}).get(part_id)
489
+ if not assessment:
490
+ die(
491
+ f"part {part_id} has not been assessed for {item.get('reference')}. "
492
+ f"Run `search {args.ref} \"<mpn or specs>\"` and pick from its candidates."
493
+ )
494
+ if assessment.get("relationship") == "unvetted_alternative" and not args.accept_unvetted:
495
+ die(
496
+ "this candidate is an unvetted alternative: the resolver could not confirm it meets the BOM line.\n"
497
+ f" reason: {assessment.get('reason')}\n cautions: {assessment.get('cautions')}\n"
498
+ "Check it against the design, then rerun with --accept-unvetted if it really fits."
499
+ )
500
+ body = {
501
+ "part_id": part_id,
502
+ "requirements_hash": assessment.get("requirements_hash") or sr.get("requirements_hash"),
503
+ "expected_matched_part_id": item.get("matched_part_id") or "",
504
+ "acknowledge_unvetted": bool(args.accept_unvetted),
505
+ }
506
+ try:
507
+ request("POST", f"/bom-items/{item['id']}:assign-matched-part", key=state["key"], body=body)
508
+ except ApiError as e:
509
+ if e.status == 409:
510
+ die("the BOM line changed since it was searched (quantity or row). Run `search` on it again, then assign.")
511
+ die(f"assign failed: {e}")
512
+ print(f"{item.get('reference')}: assigned {part_id} [{assessment.get('relationship')}]")
513
+
514
+
515
+ def toggle(args, endpoint, field, value):
516
+ state = load_state()
517
+ item = find_item(get_project(state), args.ref)
518
+ try:
519
+ request("POST", f"/bom-items/{item['id']}:{endpoint}", key=state["key"], body={field: value})
520
+ except ApiError as e:
521
+ die(str(e))
522
+ print(f"{item.get('reference')}: {field} = {value}")
523
+
524
+
525
+ def cmd_set(args):
526
+ state = load_state()
527
+ fields = {}
528
+ for pair in args.pairs:
529
+ name, sep, value = pair.partition("=")
530
+ if not sep or name not in SETTABLE:
531
+ die(f"cannot set {pair!r}. Settable: {', '.join(sorted(SETTABLE))} (as name=value)")
532
+ api_name, convert = SETTABLE[name]
533
+ fields[api_name] = convert(value)
534
+ try:
535
+ request("PUT", f"/projects/{state['id']}/", key=state["key"], body=fields)
536
+ except ApiError as e:
537
+ die(str(e))
538
+ print("updated: " + ", ".join(f"{k}={v!r}" for k, v in fields.items()))
539
+
540
+
541
+ def project_url(state):
542
+ return f"{SITE}/p/{state['id']}?k={state['key']}"
543
+
544
+
545
+ def cmd_url(_args):
546
+ print(project_url(load_state()))
547
+
548
+
549
+ def main():
550
+ ap = argparse.ArgumentParser(prog="pikkolo.py", description=__doc__.split("\n\n")[0])
551
+ sub = ap.add_subparsers(dest="cmd", required=True)
552
+
553
+ n = sub.add_parser("new", help="create a draft project from fab files")
554
+ n.add_argument("--gerbers", required=True, help="zip of Gerber + drill files")
555
+ n.add_argument("--bom", required=True, help="BOM (.csv or .xlsx)")
556
+ n.add_argument("--placements", required=True, help="pick-and-place / centroid file (.csv)")
557
+ n.add_argument("--qty", type=int, default=5, help="boards to build (default 5)")
558
+ n.add_argument("--layers", type=int, help="copper layer count (2 or 4)")
559
+ n.add_argument("--double-sided", action="store_true", help="parts are placed on both sides")
560
+ n.add_argument("--no-fab", action="store_true", help="assembly only: the user already has bare boards")
561
+ n.add_argument("--notes", help="note to Pikkolo's operators (DNP list, substitutions, anything odd)")
562
+ n.add_argument("--force", action="store_true", help="discard this directory's existing project pointer")
563
+ n.set_defaults(fn=cmd_new)
564
+
565
+ u = sub.add_parser("upload", help="replace one of the project's files")
566
+ u.add_argument("kind", choices=["gerber", "bom", "placements"])
567
+ u.add_argument("path")
568
+ u.set_defaults(fn=cmd_upload)
569
+
570
+ s = sub.add_parser("status", help="board, DRC, every BOM line and its part, and the quote")
571
+ s.add_argument("--wait", action="store_true", help="block until processing finishes")
572
+ s.add_argument("--timeout", type=int, default=420, help="seconds to wait (default 420)")
573
+ s.add_argument("--open", action="store_true", help="list only lines that are unresolved or not an exact match")
574
+ s.add_argument("--json", action="store_true")
575
+ s.set_defaults(fn=cmd_status)
576
+
577
+ se = sub.add_parser("search", help="find parts for one BOM line")
578
+ se.add_argument("ref", help="a reference designator on the line, e.g. U3")
579
+ se.add_argument("query", help="an MPN, or the specs that matter, in plain words")
580
+ se.set_defaults(fn=cmd_search)
581
+
582
+ a = sub.add_parser("assign", help="choose a searched candidate for a BOM line")
583
+ a.add_argument("ref")
584
+ a.add_argument("part", help="candidate number from the last search/status, or a part_id")
585
+ a.add_argument("--accept-unvetted", action="store_true", help="you checked an unvetted alternative yourself")
586
+ a.set_defaults(fn=cmd_assign)
587
+
588
+ for name, endpoint, field, value, text in [
589
+ ("exclude", "toggle-exclude-from-bom", "exclude_from_bom", True, "mark a line do-not-populate"),
590
+ ("include", "toggle-exclude-from-bom", "exclude_from_bom", False, "undo exclude"),
591
+ ("consign", "toggle-consigned", "consigned", True, "customer will supply this part"),
592
+ ("unconsign", "toggle-consigned", "consigned", False, "undo consign"),
593
+ ]:
594
+ t = sub.add_parser(name, help=text)
595
+ t.add_argument("ref")
596
+ t.set_defaults(fn=lambda args, e=endpoint, f=field, v=value: toggle(args, e, f, v))
597
+
598
+ st = sub.add_parser(
599
+ "set",
600
+ help="change project options: " + ", ".join(sorted(SETTABLE)),
601
+ description="qty=<boards> layers=<2|4> double_sided=<true|false> stencil=<true|false> "
602
+ "boards=<pikkolo_fab|direct_from_fab|ship_yourself> notes=<text for Pikkolo's operators>",
603
+ )
604
+ st.add_argument("pairs", nargs="+", metavar="name=value")
605
+ st.set_defaults(fn=cmd_set)
606
+
607
+ sub.add_parser("url", help="the link the customer opens to review and order").set_defaults(fn=cmd_url)
608
+
609
+ args = ap.parse_args()
610
+ try:
611
+ args.fn(args)
612
+ except ApiError as e:
613
+ die(str(e))
614
+
615
+
616
+ if __name__ == "__main__":
617
+ main()