@octen.ai/cli 0.8.0 → 0.10.0

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.
Files changed (63) hide show
  1. package/README.md +272 -6
  2. package/dist/api/constants.d.ts +6 -0
  3. package/dist/api/constants.js +3 -0
  4. package/dist/api/errors.d.ts +15 -0
  5. package/dist/api/errors.js +15 -0
  6. package/dist/api/extract.d.ts +57 -0
  7. package/dist/api/extract.js +36 -1
  8. package/dist/auth/constants.d.ts +47 -0
  9. package/dist/auth/constants.js +89 -0
  10. package/dist/auth/exchange.d.ts +74 -0
  11. package/dist/auth/exchange.js +124 -0
  12. package/dist/auth/login.d.ts +64 -0
  13. package/dist/auth/login.js +163 -0
  14. package/dist/auth/loopback.d.ts +32 -0
  15. package/dist/auth/loopback.js +95 -0
  16. package/dist/auth/oauthClient.d.ts +70 -0
  17. package/dist/auth/oauthClient.js +136 -0
  18. package/dist/auth/pkce.d.ts +6 -0
  19. package/dist/auth/pkce.js +13 -0
  20. package/dist/auth/revoke.d.ts +58 -0
  21. package/dist/auth/revoke.js +91 -0
  22. package/dist/auth/store.d.ts +34 -0
  23. package/dist/auth/store.js +149 -0
  24. package/dist/cli.js +6 -0
  25. package/dist/commands/configureMcp.js +34 -18
  26. package/dist/commands/configureSkills.js +18 -4
  27. package/dist/commands/extract.js +9 -5
  28. package/dist/commands/login.d.ts +49 -0
  29. package/dist/commands/login.js +161 -0
  30. package/dist/commands/logout.d.ts +46 -0
  31. package/dist/commands/logout.js +142 -0
  32. package/dist/commands/reset.js +39 -3
  33. package/dist/commands/utils.d.ts +9 -0
  34. package/dist/commands/utils.js +16 -0
  35. package/dist/commands/whoami.d.ts +27 -0
  36. package/dist/commands/whoami.js +109 -0
  37. package/dist/config/resolve.d.ts +44 -1
  38. package/dist/config/resolve.js +80 -5
  39. package/dist/mcp/install.js +15 -2
  40. package/dist/mcp/write.js +24 -3
  41. package/dist/output/pretty/extract.d.ts +5 -1
  42. package/dist/output/pretty/extract.js +64 -4
  43. package/dist/output/pretty/whoami.d.ts +59 -0
  44. package/dist/output/pretty/whoami.js +103 -0
  45. package/dist/skills/setkey.js +5 -4
  46. package/dist/util/secretFile.d.ts +24 -0
  47. package/dist/util/secretFile.js +35 -0
  48. package/package.json +1 -1
  49. package/skills/manifest.json +5 -1
  50. package/skills/octen-design/SKILL.md +32 -9
  51. package/skills/octen-design/agents/openai.yaml +4 -0
  52. package/skills/octen-design/scripts/search.py +326 -71
  53. package/skills/octen-design/scripts/tests/test_search.py +449 -0
  54. package/skills/octen-extract/SKILL.md +178 -0
  55. package/skills/octen-extract/agents/openai.yaml +4 -0
  56. package/skills/octen-image-search/SKILL.md +125 -0
  57. package/skills/octen-image-search/agents/openai.yaml +4 -0
  58. package/skills/octen-search/SKILL.md +82 -3
  59. package/skills/octen-search/agents/openai.yaml +4 -0
  60. package/skills/octen-video-search/SKILL.md +108 -0
  61. package/skills/octen-video-search/agents/openai.yaml +4 -0
  62. package/skills/octen-web-search/SKILL.md +113 -0
  63. package/skills/octen-web-search/agents/openai.yaml +4 -0
@@ -15,18 +15,24 @@ Reads the API key from the OCTEN_API_KEY environment variable. Downloads result
15
15
  images locally, writes each design-style summary and reusable HTML/CSS snippet to
16
16
  an output directory, then prints a concise report to stdout (design refs first,
17
17
  general refs after) so the model can act on it. The merged manifest is written to
18
- results.json as `octen_refs`.
18
+ results.json as `octen_refs`, with `partial` / `topic_errors` recording any
19
+ topic-level failures.
19
20
 
20
21
  Stdlib only — no pip install required.
21
22
  """
22
23
 
23
24
  import argparse
24
25
  import base64
26
+ import hashlib
27
+ import http.client
25
28
  import json
26
29
  import mimetypes
27
30
  import os
31
+ import re
28
32
  import sys
33
+ import time
29
34
  import urllib.error
35
+ import urllib.parse
30
36
  import urllib.request
31
37
  from concurrent.futures import ThreadPoolExecutor
32
38
  from pathlib import Path
@@ -47,36 +53,71 @@ DEFAULT_TOPICS = ["design", "general"]
47
53
  ERROR_HINTS = {
48
54
  400: "Missing or malformed parameter.",
49
55
  401: "Invalid API key. Check the OCTEN_API_KEY environment variable.",
50
- 403: "Insufficient account balance.",
51
- 413: "Input too large (image > 5MB, or query too long).",
56
+ 403: "No beta access for this endpoint, or insufficient account balance "
57
+ "(the server message below says which).",
58
+ 413: "Input too large (image > 5MB base64-encoded, or query too long).",
52
59
  415: "Unsupported input media type.",
53
60
  422: "Input unreadable, invalid, or unsupported topic.",
54
61
  429: "Rate limit exceeded. Wait and retry.",
55
62
  500: "Server error. Retry later.",
56
63
  }
57
64
 
65
+ # Retry policy for transient failures: statuses retried, retries after the
66
+ # first attempt, base backoff.
67
+ RETRYABLE_STATUSES = {429, 500, 502, 503, 504}
68
+ MAX_RETRIES = 2
69
+ RETRY_BASE_DELAY = 1.0
70
+
71
+ # Cap on a single downloaded image (per download; up to DOWNLOAD_WORKERS may be
72
+ # in flight at once); guards memory against oversized files from arbitrary
73
+ # general-topic hosts.
74
+ MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024 # 20 MB
75
+
76
+ # Cap on a local reference image sent inline. The OpenAPI contract sets the
77
+ # limit on the base64-ENCODED payload ("at most 5MB after encoding"), so the
78
+ # pre-check measures encoded size; failing locally avoids burning a request.
79
+ MAX_LOCAL_IMAGE_BYTES = 5 * 1024 * 1024
80
+
81
+
82
+ class APICallError(Exception):
83
+ """One topic's API call failed definitively (retries exhausted, a
84
+ non-retryable error, or an envelope/contract mismatch); other topics may
85
+ still work."""
86
+
58
87
 
59
88
  def image_input(ref):
60
89
  """Turn a local path or URL into an inputs[] image entry."""
61
- if ref.startswith("http://") or ref.startswith("https://"):
90
+ try:
91
+ scheme = urllib.parse.urlsplit(ref).scheme.lower()
92
+ except ValueError:
93
+ scheme = "" # unparseable as a URL; treat as a local path below
94
+ if scheme in ("http", "https"):
62
95
  return {"type": "image", "url": ref}
63
96
  p = Path(ref)
64
97
  if not p.is_file():
65
98
  sys.exit(f"Image reference not found: {ref}")
99
+ size = p.stat().st_size
100
+ encoded_size = 4 * ((size + 2) // 3) # base64 output size for `size` raw bytes
101
+ if encoded_size > MAX_LOCAL_IMAGE_BYTES:
102
+ sys.exit(
103
+ f"Image {ref} is {size / 1048576:.1f}MB "
104
+ f"({encoded_size / 1048576:.1f}MB base64-encoded); the API accepts "
105
+ "at most 5MB after encoding — pass a public https URL instead."
106
+ )
66
107
  data = base64.b64encode(p.read_bytes()).decode("ascii")
67
108
  return {"type": "image", "data": data}
68
109
 
69
110
 
70
111
  def build_payload(args, topic):
71
- inputs = []
72
- if args.query:
73
- inputs.append({"type": "text", "data": args.query[:500]})
112
+ # The API accepts exactly ONE input per request (OpenAPI: "either one text
113
+ # input or one image input"; two inputs are rejected with 400).
74
114
  if args.image:
75
- inputs.append(image_input(args.image))
115
+ inputs = [image_input(args.image)]
116
+ else:
117
+ inputs = [{"type": "text", "data": args.query[:500]}]
76
118
  payload = {
77
119
  "inputs": inputs,
78
120
  "topic": topic,
79
- "output_modalities": ["image"],
80
121
  "count": args.count,
81
122
  # Only honored for topic=design; harmless for general.
82
123
  "html_snippet": {"enable": True, "max_tokens": args.max_snippet_tokens},
@@ -85,69 +126,198 @@ def build_payload(args, topic):
85
126
 
86
127
 
87
128
  def call_api(payload, api_key):
129
+ """POST to the API with retries on transient failures.
130
+
131
+ Raises APICallError on any definitive failure — HTTP error, exhausted
132
+ retries, network/read failure, or an unreadable response body — so the
133
+ caller can decide whether to continue with other topics (a 403 on one
134
+ topic must not discard results already fetched for another).
135
+ """
88
136
  body = json.dumps(payload).encode("utf-8")
89
- req = urllib.request.Request(
90
- API_URL,
91
- data=body,
92
- headers={
93
- "x-api-key": api_key,
94
- "Content-Type": "application/json",
95
- },
96
- method="POST",
97
- )
98
- try:
99
- with urllib.request.urlopen(req, timeout=60) as resp:
100
- return json.loads(resp.read().decode("utf-8"))
101
- except urllib.error.HTTPError as e:
102
- hint = ERROR_HINTS.get(e.code, "")
137
+ last_error = None
138
+ for attempt in range(MAX_RETRIES + 1):
139
+ req = urllib.request.Request(
140
+ API_URL,
141
+ data=body,
142
+ headers={
143
+ "x-api-key": api_key,
144
+ "Content-Type": "application/json",
145
+ },
146
+ method="POST",
147
+ )
148
+ server_delay = None
103
149
  try:
104
- detail = e.read().decode("utf-8")
105
- except Exception:
106
- detail = ""
107
- sys.exit(f"API error {e.code}: {hint} {detail}".strip())
108
- except urllib.error.URLError as e:
109
- sys.exit(f"Network error reaching the image search API: {e.reason}")
150
+ with urllib.request.urlopen(req, timeout=60) as resp:
151
+ raw = resp.read()
152
+ try:
153
+ return json.loads(raw.decode("utf-8"))
154
+ except (json.JSONDecodeError, UnicodeDecodeError) as e:
155
+ last_error = (
156
+ f"Unreadable (non-JSON) response body from the image "
157
+ f"search API: {e}"
158
+ )
159
+ break
160
+ except urllib.error.HTTPError as e:
161
+ hint = ERROR_HINTS.get(e.code, "")
162
+ try:
163
+ detail = e.read().decode("utf-8", "replace").strip()
164
+ except Exception:
165
+ detail = ""
166
+ # Cap the server body: it is replayed on every retry warning and
167
+ # persisted into results.json.
168
+ if len(detail) > 500:
169
+ detail = detail[:500] + "…(truncated)"
170
+ last_error = f"API error {e.code}: {hint} {detail or '(no readable response body)'}".strip()
171
+ if e.code not in RETRYABLE_STATUSES:
172
+ break
173
+ retry_after = e.headers.get("Retry-After") if e.headers else None
174
+ if retry_after:
175
+ try:
176
+ server_delay = min(float(retry_after), 30.0)
177
+ except ValueError:
178
+ pass
179
+ except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
180
+ # Read-phase failures (timeout, reset, truncated body) surface as
181
+ # raw OSError/HTTPException rather than URLError; all transient.
182
+ # Bare OSErrors stringify to "", so always include the class name.
183
+ last_error = (f"Network error reaching the image search API: "
184
+ f"{e.__class__.__name__}: {getattr(e, 'reason', e)}")
185
+ if attempt < MAX_RETRIES:
186
+ delay = max(RETRY_BASE_DELAY * (2 ** attempt), server_delay or 0)
187
+ print(
188
+ f"WARNING: image search API attempt {attempt + 1}/{MAX_RETRIES + 1} "
189
+ f"failed ({last_error}); retrying in {delay:.0f}s",
190
+ file=sys.stderr,
191
+ )
192
+ time.sleep(delay)
193
+ raise APICallError(last_error or "unknown error")
194
+
195
+
196
+ class _HttpOnlyRedirectHandler(urllib.request.HTTPRedirectHandler):
197
+ """Refuse redirects to any non-http(s) scheme (urllib itself would follow
198
+ a redirect to ftp://)."""
199
+
200
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
201
+ if urllib.parse.urlsplit(newurl).scheme.lower() not in ("http", "https"):
202
+ # The stdlib drains/closes fp only after redirect_request returns;
203
+ # raising would otherwise leak the connection.
204
+ fp.read()
205
+ fp.close()
206
+ raise urllib.error.URLError(f"redirect to non-http(s) URL blocked: {newurl}")
207
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
208
+
209
+
210
+ _DOWNLOAD_OPENER = urllib.request.build_opener(_HttpOnlyRedirectHandler)
110
211
 
111
212
 
112
213
  def download_image(url, dest_stem):
113
- """Download an image URL to dest_stem.<ext>. Returns the path or None."""
214
+ """Download an image URL to dest_stem.<ext>.
215
+
216
+ Returns (path, None) on success or (None, reason) on failure, so the
217
+ caller can record WHY an image is missing. Only http(s) URLs are fetched
218
+ — enforced across redirects too — and reads are capped at
219
+ MAX_DOWNLOAD_BYTES so an oversized file from an arbitrary host cannot
220
+ exhaust memory.
221
+ """
114
222
  if not url:
115
- return None
223
+ return None, "no image URL in the API response"
224
+ try:
225
+ scheme = urllib.parse.urlsplit(url).scheme.lower()
226
+ except ValueError as e:
227
+ return None, f"unparseable image URL: {e}"
228
+ if scheme not in ("http", "https"):
229
+ return None, f"blocked non-http(s) URL scheme: {scheme or '(none)'}"
116
230
  try:
117
231
  req = urllib.request.Request(url, headers={"User-Agent": "ui-design-search/1.0"})
118
- with urllib.request.urlopen(req, timeout=60) as resp:
119
- data = resp.read()
232
+ with _DOWNLOAD_OPENER.open(req, timeout=60) as resp:
233
+ data = resp.read(MAX_DOWNLOAD_BYTES + 1)
234
+ if len(data) > MAX_DOWNLOAD_BYTES:
235
+ return None, "image exceeds the 20MB download cap"
120
236
  ctype = resp.headers.get("Content-Type", "")
121
- ext = mimetypes.guess_extension(ctype.split(";")[0].strip()) or ".jpg"
122
- if ext == ".jpe":
123
- ext = ".jpg"
124
- path = dest_stem.with_suffix(ext)
237
+ except Exception as e:
238
+ return None, f"download failed: {e.__class__.__name__}: {e}"
239
+ ext = mimetypes.guess_extension(ctype.split(";")[0].strip()) or ".jpg"
240
+ if ext == ".jpe":
241
+ ext = ".jpg"
242
+ path = dest_stem.with_suffix(ext)
243
+ try:
125
244
  path.write_bytes(data)
126
- return str(path)
127
- except Exception:
128
- return None
245
+ except OSError as e:
246
+ return None, f"cannot write {path} locally: {e}"
247
+ return str(path), None
248
+
249
+
250
+ def safe_topic_slug(topic):
251
+ """Filesystem-safe slug for a topic used in output filenames.
252
+
253
+ --topics is user input that gets interpolated into paths; strip anything
254
+ that could escape the output directory (e.g. "../evil"). Sanitized or
255
+ non-lowercase slugs get a short hash suffix so distinct topics cannot
256
+ collide on the same output files — whether by sanitizing to the same text
257
+ ("a b" vs "a_b") or by case-folding on case-insensitive filesystems
258
+ ("Design" vs "design" on APFS/NTFS).
259
+ """
260
+ slug = re.sub(r"[^A-Za-z0-9_-]", "_", topic) or "topic"
261
+ if slug != topic or slug != slug.lower():
262
+ slug += "-" + hashlib.md5(topic.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
263
+ return slug
129
264
 
130
265
 
131
266
  def collect_topic(topic, args, api_key):
132
267
  """Query one topic and return its raw image results (list of dicts)."""
133
268
  resp = call_api(build_payload(args, topic), api_key)
134
- results = (resp.get("data") or {}).get("results") or []
269
+ # The beta envelope is loose (code/msg may be absent, data may be null on
270
+ # zero hits) — tolerate that, but a missing `data` key or wrong-typed
271
+ # data/results is a contract problem, NOT an empty result set.
272
+ if not isinstance(resp, dict) or "data" not in resp:
273
+ got = f"top-level keys {sorted(resp)}" if isinstance(resp, dict) else type(resp).__name__
274
+ raise APICallError(
275
+ f"Unexpected response envelope from the image search API (no 'data' key; got: {got})"
276
+ )
277
+ data = resp["data"] or {}
278
+ if not isinstance(data, dict):
279
+ raise APICallError(
280
+ "Unexpected response envelope from the image search API "
281
+ f"(data is {type(data).__name__}, expected an object)"
282
+ )
283
+ results = data.get("results") or []
284
+ if not isinstance(results, list):
285
+ raise APICallError(
286
+ "Unexpected response envelope from the image search API "
287
+ f"(results is {type(results).__name__}, expected an array)"
288
+ )
135
289
  # The image-search endpoint returns image hits with no `type` field; keep
136
290
  # any entry that has an image URL (do NOT filter on type == "image").
137
- return [r for r in results if r.get("url")]
291
+ return [r for r in results if isinstance(r, dict) and r.get("url")]
138
292
 
139
293
 
140
294
  def fetch_one_image(topic, i, r, out):
141
- """Download a single result's image (with thumbnail fallback). Thread-safe."""
295
+ """Download a single result's image (with thumbnail fallback). Thread-safe.
296
+
297
+ Returns (path, used_thumbnail, error); error is set only when no image
298
+ could be saved at all.
299
+ """
142
300
  # Primary image is `url` (full-res). For general, the foreign-host image
143
301
  # may be huge or hotlink-blocked, so fall back to the octen-proxied
144
302
  # `thumbnail` when the original download fails.
145
- img_path = download_image(r.get("url"), out / f"{topic}_{i}")
303
+ slug = safe_topic_slug(topic)
304
+ img_path, primary_error = download_image(r.get("url"), out / f"{slug}_{i}")
146
305
  used_thumbnail = False
147
- if img_path is None and r.get("thumbnail"):
148
- img_path = download_image(r.get("thumbnail"), out / f"{topic}_{i}")
149
- used_thumbnail = img_path is not None
150
- return img_path, used_thumbnail
306
+ error = None
307
+ if img_path is None:
308
+ if r.get("thumbnail"):
309
+ img_path, thumb_error = download_image(r.get("thumbnail"), out / f"{slug}_{i}")
310
+ used_thumbnail = img_path is not None
311
+ if img_path is None:
312
+ error = f"original: {primary_error}; thumbnail: {thumb_error}"
313
+ else:
314
+ print(f"NOTE: [{topic}:{i}] full-res download failed "
315
+ f"({primary_error}); saved the thumbnail instead", file=sys.stderr)
316
+ else:
317
+ error = primary_error
318
+ if error:
319
+ print(f"WARNING: [{topic}:{i}] image not saved — {error}", file=sys.stderr)
320
+ return img_path, used_thumbnail, error
151
321
 
152
322
 
153
323
  def process_topic(topic, results, args, out):
@@ -166,13 +336,26 @@ def process_topic(topic, results, args, out):
166
336
 
167
337
  refs = []
168
338
  for i, r in enumerate(results):
169
- img_path, used_thumbnail = images.get(i, (None, False))
339
+ img_path, used_thumbnail, image_error = images.get(i, (None, False, None))
170
340
 
171
341
  snippet = r.get("html_snippet")
172
342
  snippet_path = None
343
+ snippet_error = None
173
344
  if snippet:
174
- snippet_path = str(out / f"{topic}_snippet_{i}.html")
175
- Path(snippet_path).write_text(snippet, encoding="utf-8")
345
+ if not isinstance(snippet, str):
346
+ snippet_error = f"unexpected html_snippet type: {type(snippet).__name__}"
347
+ else:
348
+ snippet_path = str(out / f"{safe_topic_slug(topic)}_snippet_{i}.html")
349
+ try:
350
+ # errors="replace": json.loads can hand us lone surrogates
351
+ # (\ud83d-style escapes) that utf-8 cannot encode; a lossy
352
+ # write beats losing the snippet (or the whole run).
353
+ Path(snippet_path).write_text(snippet, encoding="utf-8", errors="replace")
354
+ except (OSError, ValueError) as e:
355
+ snippet_path = None
356
+ snippet_error = f"cannot write snippet locally: {e}"
357
+ if snippet_error:
358
+ print(f"WARNING: [{topic}:{i}] {snippet_error}", file=sys.stderr)
176
359
 
177
360
  refs.append({
178
361
  "topic": topic,
@@ -183,19 +366,24 @@ def process_topic(topic, results, args, out):
183
366
  "thumbnail_url": r.get("thumbnail") or None,
184
367
  "local_image": img_path,
185
368
  "local_image_is_thumbnail": used_thumbnail,
369
+ "image_error": image_error,
186
370
  "description": r.get("description"),
187
371
  "summary": r.get("summary"),
188
372
  "html_snippet_file": snippet_path,
373
+ "snippet_error": snippet_error,
189
374
  "width": r.get("width"),
190
375
  "height": r.get("height"),
191
376
  })
192
377
  return refs
193
378
 
194
379
 
195
- def print_topic_report(topic, refs, heading):
380
+ def print_topic_report(topic, refs, heading, error=None):
196
381
  print("=" * 64)
197
382
  print(heading)
198
383
  print("=" * 64)
384
+ if error:
385
+ print(f"(TOPIC FAILED: {error})")
386
+ return
199
387
  if not refs:
200
388
  print("(no results for this topic)")
201
389
  return
@@ -207,7 +395,7 @@ def print_topic_report(topic, refs, heading):
207
395
  tag = " (thumbnail)" if ref.get("local_image_is_thumbnail") else ""
208
396
  print(f" image : {ref['local_image']}{tag} <-- view this")
209
397
  else:
210
- print(f" image : (download failed) {ref.get('image_url')}")
398
+ print(f" image : (not saved: {ref.get('image_error')}) {ref.get('image_url')}")
211
399
  if ref.get("description"):
212
400
  print(f" desc : {ref['description']}")
213
401
  if ref.get("summary"):
@@ -217,6 +405,38 @@ def print_topic_report(topic, refs, heading):
217
405
  print("-" * 64)
218
406
 
219
407
 
408
+ def write_manifest(out, query, topics, octen_refs, topic_errors):
409
+ """Write results.json atomically: a crash mid-write must not leave a
410
+ truncated manifest, and a run that reaches the API but fails must not
411
+ leave a stale one."""
412
+ manifest = {
413
+ "query": query,
414
+ "topics": topics,
415
+ "partial": bool(topic_errors),
416
+ "topic_errors": topic_errors,
417
+ "octen_refs": octen_refs,
418
+ }
419
+ tmp = out / "results.json.tmp"
420
+ try:
421
+ # errors="replace": API strings may contain lone surrogates.
422
+ tmp.write_text(json.dumps(manifest, ensure_ascii=False, indent=2),
423
+ encoding="utf-8", errors="replace")
424
+ os.replace(tmp, out / "results.json")
425
+ except OSError as e:
426
+ try:
427
+ tmp.unlink()
428
+ except OSError:
429
+ pass
430
+ sys.exit(f"Cannot write the results manifest: {e}")
431
+
432
+
433
+ def count_arg(value):
434
+ n = int(value)
435
+ if not 1 <= n <= 10:
436
+ raise argparse.ArgumentTypeError("must be between 1 and 10 (the API's documented range)")
437
+ return n
438
+
439
+
220
440
  def main():
221
441
  parser = argparse.ArgumentParser(
222
442
  description="Search UI design references via the octen.ai image-search API (design + general topics)."
@@ -227,9 +447,10 @@ def main():
227
447
  )
228
448
  parser.add_argument(
229
449
  "--image",
230
- help="Reference image for image-based search: local path (sent as base64) or public URL.",
450
+ help="Reference image for image-based search: local path (sent as base64) "
451
+ "or public URL. Cannot be combined with a text query.",
231
452
  )
232
- parser.add_argument("--count", type=int, default=5, help="Number of results PER TOPIC, 1-100 (default 5).")
453
+ parser.add_argument("--count", type=count_arg, default=5, help="Number of results PER TOPIC, 1-10 (default 5).")
233
454
  parser.add_argument(
234
455
  "--topics", nargs="+", default=DEFAULT_TOPICS,
235
456
  help="Topics to query (default: design general). design = curated UI corpus; general = broad web images.",
@@ -244,8 +465,14 @@ def main():
244
465
  )
245
466
  args = parser.parse_args()
246
467
 
468
+ if args.query and args.image:
469
+ sys.exit(
470
+ "The image-search API accepts a single input per request: pass a "
471
+ "text query OR --image, not both. Run the script twice to combine "
472
+ "text and image references."
473
+ )
247
474
  if not args.query and not args.image:
248
- sys.exit("Provide a text query and/or --image.")
475
+ sys.exit("Provide a text query or --image.")
249
476
 
250
477
  api_key = os.environ.get("OCTEN_API_KEY")
251
478
  if not api_key:
@@ -257,29 +484,59 @@ def main():
257
484
  out = Path(args.out)
258
485
  out.mkdir(parents=True, exist_ok=True)
259
486
 
487
+ # Duplicate topics would query the same corpus twice and overwrite each
488
+ # other's files; keep the first occurrence of each.
489
+ topics = list(dict.fromkeys(args.topics))
490
+ if len(topics) < len(args.topics):
491
+ dropped = sorted({t for t in args.topics if args.topics.count(t) > 1})
492
+ print(f"WARNING: duplicate --topics values ignored: {', '.join(dropped)}",
493
+ file=sys.stderr)
494
+
260
495
  print(f"Query : {args.query or '[image search]'}")
261
- print(f"Topics : {', '.join(args.topics)}")
496
+ print(f"Topics : {', '.join(topics)}")
262
497
 
263
498
  octen_refs = []
264
499
  per_topic = {}
265
- for topic in args.topics:
266
- raw = collect_topic(topic, args, api_key)
500
+ topic_errors = {}
501
+ for topic in topics:
502
+ try:
503
+ raw = collect_topic(topic, args, api_key)
504
+ except APICallError as e:
505
+ # One topic failing (e.g. 403 no beta access) must not discard
506
+ # results already fetched for other topics.
507
+ topic_errors[topic] = str(e)
508
+ print(f"WARNING: topic '{topic}' failed: {e}", file=sys.stderr)
509
+ per_topic[topic] = []
510
+ continue
267
511
  refs = process_topic(topic, raw, args, out)
268
512
  per_topic[topic] = refs
269
513
  octen_refs.extend(refs)
270
514
 
271
- print(f"Results: {len(octen_refs)} total "
272
- f"({', '.join(f'{t}={len(per_topic.get(t, []))}' for t in args.topics)})")
515
+ if topic_errors and not octen_refs:
516
+ # Nothing was retrieved and at least one topic failed outright. Exit
517
+ # non-zero with the failure — NOT "no results": broadening the query
518
+ # is the wrong remedy for e.g. a 403.
519
+ write_manifest(out, args.query, topics, octen_refs, topic_errors)
520
+ details = "; ".join(f"{t}: {err}" for t, err in topic_errors.items())
521
+ sys.exit(f"No results — {len(topic_errors)} of {len(topics)} topic(s) failed. {details}")
522
+
523
+ status = ", ".join(
524
+ f"{t}=FAILED" if t in topic_errors else f"{t}={len(per_topic.get(t, []))}"
525
+ for t in topics
526
+ )
527
+ print(f"Results: {len(octen_refs)} total ({status})")
528
+ if topic_errors:
529
+ print(
530
+ f"NOTE: partial results — {len(topic_errors)} topic(s) failed: "
531
+ + "; ".join(f"{t}: {err}" for t, err in topic_errors.items())
532
+ )
273
533
 
274
534
  if not octen_refs:
275
535
  print(
276
536
  "NO RESULTS. Proceed using your own design judgment, tell the user no "
277
537
  "reference was found, and consider broadening the query."
278
538
  )
279
- (out / "results.json").write_text(
280
- json.dumps({"query": args.query, "topics": args.topics, "octen_refs": []},
281
- ensure_ascii=False, indent=2)
282
- )
539
+ write_manifest(out, args.query, topics, octen_refs, topic_errors)
283
540
  return
284
541
 
285
542
  headings = {
@@ -288,15 +545,13 @@ def main():
288
545
  }
289
546
  # design first (primary), then general (supplementary), then any other topics.
290
547
  ordered = [t for t in ("design", "general") if t in per_topic]
291
- ordered += [t for t in args.topics if t not in ordered]
548
+ ordered += [t for t in topics if t not in ordered]
292
549
  for topic in ordered:
293
550
  print_topic_report(topic, per_topic.get(topic, []),
294
- headings.get(topic, f"{topic.upper()} refs"))
551
+ headings.get(topic, f"{topic.upper()} refs"),
552
+ error=topic_errors.get(topic))
295
553
 
296
- (out / "results.json").write_text(
297
- json.dumps({"query": args.query, "topics": args.topics, "octen_refs": octen_refs},
298
- ensure_ascii=False, indent=2)
299
- )
554
+ write_manifest(out, args.query, topics, octen_refs, topic_errors)
300
555
  print(f"Manifest: {out / 'results.json'} (key: octen_refs)")
301
556
 
302
557