@octen.ai/cli 0.9.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.
- package/README.md +22 -2
- package/dist/api/constants.d.ts +6 -0
- package/dist/api/constants.js +3 -0
- package/dist/api/extract.d.ts +57 -0
- package/dist/api/extract.js +36 -1
- package/dist/commands/extract.js +9 -5
- package/dist/commands/utils.d.ts +9 -0
- package/dist/commands/utils.js +16 -0
- package/dist/output/pretty/extract.d.ts +5 -1
- package/dist/output/pretty/extract.js +64 -4
- package/package.json +1 -1
- package/skills/manifest.json +5 -1
- package/skills/octen-design/SKILL.md +32 -9
- package/skills/octen-design/agents/openai.yaml +4 -0
- package/skills/octen-design/scripts/search.py +326 -71
- package/skills/octen-design/scripts/tests/test_search.py +449 -0
- package/skills/octen-extract/SKILL.md +178 -0
- package/skills/octen-extract/agents/openai.yaml +4 -0
- package/skills/octen-image-search/SKILL.md +125 -0
- package/skills/octen-image-search/agents/openai.yaml +4 -0
- package/skills/octen-search/SKILL.md +82 -3
- package/skills/octen-search/agents/openai.yaml +4 -0
- package/skills/octen-video-search/SKILL.md +108 -0
- package/skills/octen-video-search/agents/openai.yaml +4 -0
- package/skills/octen-web-search/SKILL.md +113 -0
- package/skills/octen-web-search/agents/openai.yaml +4 -0
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""Regression tests for skills/octen-design/scripts/search.py.
|
|
2
|
+
|
|
3
|
+
Runs the real script (imported as a module) against a local mock HTTP server.
|
|
4
|
+
No mocks of the code under test — only the remote API is simulated (plus
|
|
5
|
+
`time.sleep`, so retry backoff doesn't stall the suite). Stdlib only, no
|
|
6
|
+
external network access (the mock server binds loopback only):
|
|
7
|
+
|
|
8
|
+
python3 tests/test_search.py
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import contextlib
|
|
13
|
+
import io
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import socket
|
|
18
|
+
import sys
|
|
19
|
+
import tempfile
|
|
20
|
+
import threading
|
|
21
|
+
import types
|
|
22
|
+
import unittest
|
|
23
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
SCRIPTS = Path(__file__).resolve().parents[1]
|
|
27
|
+
sys.path.insert(0, str(SCRIPTS))
|
|
28
|
+
import search # noqa: E402
|
|
29
|
+
|
|
30
|
+
TINY_PNG = base64.b64decode(
|
|
31
|
+
b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class MockHandler(BaseHTTPRequestHandler):
|
|
36
|
+
protocol_version = "HTTP/1.0"
|
|
37
|
+
|
|
38
|
+
def log_message(self, *args):
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
def do_POST(self):
|
|
42
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
43
|
+
body = self.rfile.read(length)
|
|
44
|
+
try:
|
|
45
|
+
self.server.requests.append(json.loads(body))
|
|
46
|
+
except ValueError:
|
|
47
|
+
self.server.requests.append(body)
|
|
48
|
+
script = self.server.api_script
|
|
49
|
+
step = script.pop(0) if script else {"status": 200, "json": {"data": {"results": []}}}
|
|
50
|
+
status = step.get("status", 200)
|
|
51
|
+
payload = json.dumps(step["json"]).encode() if "json" in step else step.get("body", b"")
|
|
52
|
+
try:
|
|
53
|
+
if step.get("truncate"):
|
|
54
|
+
# Promise more bytes than we send, then drop the connection:
|
|
55
|
+
# the client's read() raises http.client.IncompleteRead.
|
|
56
|
+
self.send_response(status)
|
|
57
|
+
self.send_header("Content-Type", "application/json")
|
|
58
|
+
self.send_header("Content-Length", str(len(payload) + 90))
|
|
59
|
+
self.end_headers()
|
|
60
|
+
self.wfile.write(payload[:10] or b"0123456789")
|
|
61
|
+
self.wfile.flush()
|
|
62
|
+
self.connection.close()
|
|
63
|
+
return
|
|
64
|
+
self.send_response(status)
|
|
65
|
+
self.send_header("Content-Type", step.get("ctype", "application/json"))
|
|
66
|
+
for k, v in step.get("headers", {}).items():
|
|
67
|
+
self.send_header(k, v)
|
|
68
|
+
self.send_header("Content-Length", str(len(payload)))
|
|
69
|
+
self.end_headers()
|
|
70
|
+
self.wfile.write(payload)
|
|
71
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
def do_GET(self):
|
|
75
|
+
if self.path.startswith("/img/ok"):
|
|
76
|
+
self.send_response(200)
|
|
77
|
+
self.send_header("Content-Type", "image/png")
|
|
78
|
+
self.send_header("Content-Length", str(len(TINY_PNG)))
|
|
79
|
+
self.end_headers()
|
|
80
|
+
self.wfile.write(TINY_PNG)
|
|
81
|
+
elif self.path in self.server.redirect_targets:
|
|
82
|
+
self.send_response(302)
|
|
83
|
+
self.send_header("Location", self.server.redirect_targets[self.path])
|
|
84
|
+
self.send_header("Content-Length", "0")
|
|
85
|
+
self.end_headers()
|
|
86
|
+
else:
|
|
87
|
+
self.send_response(404)
|
|
88
|
+
self.send_header("Content-Length", "0")
|
|
89
|
+
self.end_headers()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class SearchScriptTest(unittest.TestCase):
|
|
93
|
+
def setUp(self):
|
|
94
|
+
self.server = ThreadingHTTPServer(("127.0.0.1", 0), MockHandler)
|
|
95
|
+
self.server.api_script = []
|
|
96
|
+
self.server.requests = []
|
|
97
|
+
self.server.redirect_targets = {}
|
|
98
|
+
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
99
|
+
self.base = f"http://127.0.0.1:{self.server.server_address[1]}"
|
|
100
|
+
|
|
101
|
+
self._old_api_url = search.API_URL
|
|
102
|
+
search.API_URL = f"{self.base}/api"
|
|
103
|
+
self._old_key = os.environ.get("OCTEN_API_KEY")
|
|
104
|
+
os.environ["OCTEN_API_KEY"] = "test-key"
|
|
105
|
+
|
|
106
|
+
self.sleeps = []
|
|
107
|
+
self._old_time = search.time
|
|
108
|
+
search.time = types.SimpleNamespace(sleep=self.sleeps.append)
|
|
109
|
+
|
|
110
|
+
self.out = tempfile.mkdtemp(prefix="uirefs-test-")
|
|
111
|
+
|
|
112
|
+
def tearDown(self):
|
|
113
|
+
search.API_URL = self._old_api_url
|
|
114
|
+
search.time = self._old_time
|
|
115
|
+
if self._old_key is None:
|
|
116
|
+
os.environ.pop("OCTEN_API_KEY", None)
|
|
117
|
+
else:
|
|
118
|
+
os.environ["OCTEN_API_KEY"] = self._old_key
|
|
119
|
+
self.server.shutdown()
|
|
120
|
+
self.server.server_close()
|
|
121
|
+
shutil.rmtree(self.out, ignore_errors=True)
|
|
122
|
+
|
|
123
|
+
# ---- helpers ----
|
|
124
|
+
|
|
125
|
+
def good_response(self, n=1, **extra):
|
|
126
|
+
results = []
|
|
127
|
+
for i in range(n):
|
|
128
|
+
r = {"url": f"{self.base}/img/ok.png", "title": f"hit {i}",
|
|
129
|
+
"source_page": "https://example.com", "html_snippet": "<div>x</div>"}
|
|
130
|
+
r.update(extra)
|
|
131
|
+
results.append(r)
|
|
132
|
+
return {"status": 200, "json": {"code": 0, "data": {"results": results}}}
|
|
133
|
+
|
|
134
|
+
def run_main(self, argv):
|
|
135
|
+
old_argv = sys.argv
|
|
136
|
+
sys.argv = ["search.py"] + argv + ["--out", self.out]
|
|
137
|
+
stdout, stderr = io.StringIO(), io.StringIO()
|
|
138
|
+
exc = None
|
|
139
|
+
try:
|
|
140
|
+
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
|
|
141
|
+
try:
|
|
142
|
+
search.main()
|
|
143
|
+
except SystemExit as e:
|
|
144
|
+
exc = e
|
|
145
|
+
finally:
|
|
146
|
+
sys.argv = old_argv
|
|
147
|
+
return exc, stdout.getvalue(), stderr.getvalue()
|
|
148
|
+
|
|
149
|
+
def manifest(self):
|
|
150
|
+
return json.loads((Path(self.out) / "results.json").read_text(encoding="utf-8"))
|
|
151
|
+
|
|
152
|
+
# ---- call_api robustness ----
|
|
153
|
+
|
|
154
|
+
def test_non_json_body_becomes_topic_error_not_crash(self):
|
|
155
|
+
"""200 + HTML body on one topic must not crash the run or lose the other topic."""
|
|
156
|
+
self.server.api_script = [
|
|
157
|
+
{"status": 200, "body": b"<html>gateway error</html>", "ctype": "text/html"},
|
|
158
|
+
self.good_response(2),
|
|
159
|
+
]
|
|
160
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design", "general"])
|
|
161
|
+
self.assertIsNone(exc, "run must survive a non-JSON body on one topic")
|
|
162
|
+
m = self.manifest()
|
|
163
|
+
self.assertEqual(len(m["octen_refs"]), 2)
|
|
164
|
+
self.assertIn("design", m["topic_errors"])
|
|
165
|
+
self.assertTrue(m["partial"])
|
|
166
|
+
|
|
167
|
+
def test_read_phase_failure_is_retried(self):
|
|
168
|
+
"""A truncated response body (IncompleteRead) is transient: retry, then succeed."""
|
|
169
|
+
self.server.api_script = [
|
|
170
|
+
{"status": 200, "truncate": True, "json": {"code": 0}},
|
|
171
|
+
self.good_response(1),
|
|
172
|
+
]
|
|
173
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
174
|
+
self.assertIsNone(exc)
|
|
175
|
+
m = self.manifest()
|
|
176
|
+
self.assertEqual(len(m["octen_refs"]), 1)
|
|
177
|
+
self.assertEqual(m["topic_errors"], {})
|
|
178
|
+
self.assertFalse(m["partial"])
|
|
179
|
+
self.assertEqual(len(self.server.requests), 2, "failed read must be retried")
|
|
180
|
+
|
|
181
|
+
def test_retry_attempts_are_logged(self):
|
|
182
|
+
self.server.api_script = [
|
|
183
|
+
{"status": 500, "json": {"msg": "boom"}},
|
|
184
|
+
{"status": 500, "json": {"msg": "boom"}},
|
|
185
|
+
self.good_response(1),
|
|
186
|
+
]
|
|
187
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
188
|
+
self.assertIsNone(exc)
|
|
189
|
+
self.assertEqual(len(self.server.requests), 3)
|
|
190
|
+
self.assertGreaterEqual(err.count("retrying in"), 2,
|
|
191
|
+
f"each failed attempt must be logged to stderr, got: {err!r}")
|
|
192
|
+
|
|
193
|
+
# ---- partial / total failure semantics ----
|
|
194
|
+
|
|
195
|
+
def test_all_failed_duplicate_topics_exit_nonzero(self):
|
|
196
|
+
"""--topics general general with a 403 must NOT exit 0 with 'NO RESULTS'.
|
|
197
|
+
|
|
198
|
+
Also pins topic dedupe (one API call, not two) and 4xx-not-retried.
|
|
199
|
+
"""
|
|
200
|
+
self.server.api_script = [
|
|
201
|
+
{"status": 403, "json": {"msg": "no beta access"}},
|
|
202
|
+
{"status": 403, "json": {"msg": "no beta access"}},
|
|
203
|
+
]
|
|
204
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "general", "general"])
|
|
205
|
+
self.assertIsNotNone(exc, "total failure must exit non-zero")
|
|
206
|
+
self.assertNotEqual(exc.code, 0)
|
|
207
|
+
self.assertNotIn("NO RESULTS", out,
|
|
208
|
+
"a total auth failure must not be presented as an empty query")
|
|
209
|
+
self.assertEqual(len(self.server.requests), 1,
|
|
210
|
+
"duplicate topics must be deduped and a 403 must not be retried")
|
|
211
|
+
|
|
212
|
+
def test_partial_failure_recorded_in_manifest_and_report(self):
|
|
213
|
+
self.server.api_script = [
|
|
214
|
+
{"status": 403, "json": {"msg": "no beta access"}},
|
|
215
|
+
self.good_response(1),
|
|
216
|
+
]
|
|
217
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design", "general"])
|
|
218
|
+
self.assertIsNone(exc, "partial success still exits 0")
|
|
219
|
+
m = self.manifest()
|
|
220
|
+
self.assertTrue(m["partial"])
|
|
221
|
+
self.assertIn("design", m["topic_errors"])
|
|
222
|
+
self.assertIn("403", m["topic_errors"]["design"])
|
|
223
|
+
self.assertEqual(len(m["octen_refs"]), 1)
|
|
224
|
+
self.assertIn("FAILED", out, "the report must mark the failed topic as failed, not empty")
|
|
225
|
+
|
|
226
|
+
def test_all_failed_overwrites_stale_manifest(self):
|
|
227
|
+
stale = {"query": "OLD", "topics": ["design"], "octen_refs": [{"title": "stale"}]}
|
|
228
|
+
(Path(self.out) / "results.json").write_text(json.dumps(stale), encoding="utf-8")
|
|
229
|
+
self.server.api_script = [{"status": 403, "json": {"msg": "no beta access"}}]
|
|
230
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
231
|
+
self.assertIsNotNone(exc)
|
|
232
|
+
self.assertNotEqual(exc.code, 0)
|
|
233
|
+
m = self.manifest()
|
|
234
|
+
self.assertEqual(m["query"], "dashboard", "stale manifest from a previous run must be replaced")
|
|
235
|
+
self.assertEqual(m["octen_refs"], [])
|
|
236
|
+
self.assertIn("design", m["topic_errors"])
|
|
237
|
+
|
|
238
|
+
def test_unexpected_envelope_is_a_topic_error(self):
|
|
239
|
+
"""A 200 whose body has no 'data' object is an API contract problem, not zero hits."""
|
|
240
|
+
self.server.api_script = [{"status": 200, "json": {"foo": 1}}]
|
|
241
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
242
|
+
self.assertIsNotNone(exc, "an envelope mismatch with no results at all must exit non-zero")
|
|
243
|
+
m = self.manifest()
|
|
244
|
+
self.assertIn("design", m["topic_errors"])
|
|
245
|
+
self.assertNotIn("NO RESULTS", out)
|
|
246
|
+
|
|
247
|
+
# ---- download / snippet resilience ----
|
|
248
|
+
|
|
249
|
+
def test_download_failure_reason_recorded(self):
|
|
250
|
+
# url points at a 404 and there is no thumbnail to fall back to
|
|
251
|
+
self.server.api_script = [self.good_response(1, url=f"{self.base}/img/missing.png")]
|
|
252
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
253
|
+
self.assertIsNone(exc)
|
|
254
|
+
ref = self.manifest()["octen_refs"][0]
|
|
255
|
+
self.assertIsNone(ref["local_image"])
|
|
256
|
+
self.assertTrue(ref.get("image_error"),
|
|
257
|
+
"the manifest must say WHY the image is missing")
|
|
258
|
+
self.assertIn("download", err.lower(), "download failures must be visible on stderr")
|
|
259
|
+
|
|
260
|
+
def test_bad_snippet_type_does_not_kill_the_run(self):
|
|
261
|
+
self.server.api_script = [self.good_response(1, html_snippet={"unexpected": "dict"})]
|
|
262
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
263
|
+
self.assertIsNone(exc, "a malformed html_snippet must not crash the whole run")
|
|
264
|
+
ref = self.manifest()["octen_refs"][0]
|
|
265
|
+
self.assertIsNone(ref["html_snippet_file"])
|
|
266
|
+
self.assertTrue(ref.get("snippet_error"))
|
|
267
|
+
|
|
268
|
+
def test_redirect_to_ftp_is_not_followed(self):
|
|
269
|
+
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
270
|
+
listener.bind(("127.0.0.1", 0))
|
|
271
|
+
listener.listen(1)
|
|
272
|
+
listener.settimeout(1)
|
|
273
|
+
ftp_port = listener.getsockname()[1]
|
|
274
|
+
connected = threading.Event()
|
|
275
|
+
|
|
276
|
+
def accept():
|
|
277
|
+
try:
|
|
278
|
+
conn, _ = listener.accept()
|
|
279
|
+
connected.set()
|
|
280
|
+
conn.close()
|
|
281
|
+
except socket.timeout:
|
|
282
|
+
pass
|
|
283
|
+
|
|
284
|
+
t = threading.Thread(target=accept, daemon=True)
|
|
285
|
+
t.start()
|
|
286
|
+
self.server.redirect_targets["/redir/ftp"] = f"ftp://127.0.0.1:{ftp_port}/x.png"
|
|
287
|
+
path, reason = search.download_image(f"{self.base}/redir/ftp", Path(self.out) / "x")
|
|
288
|
+
self.assertIsNone(path)
|
|
289
|
+
self.assertTrue(reason)
|
|
290
|
+
t.join(2)
|
|
291
|
+
listener.close()
|
|
292
|
+
self.assertFalse(connected.is_set(),
|
|
293
|
+
"a redirect to a non-http(s) scheme must not be followed")
|
|
294
|
+
|
|
295
|
+
# ---- input validation against the official contract ----
|
|
296
|
+
|
|
297
|
+
def test_count_out_of_range_rejected_locally(self):
|
|
298
|
+
"""OpenAPI: /image-search count is 1-10. --count 50 must fail before any API call."""
|
|
299
|
+
self.server.api_script = [self.good_response(1)]
|
|
300
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design", "--count", "50"])
|
|
301
|
+
self.assertIsNotNone(exc, "--count 50 must be rejected")
|
|
302
|
+
self.assertNotEqual(exc.code, 0)
|
|
303
|
+
self.assertEqual(len(self.server.requests), 0, "no API call may be made with an invalid count")
|
|
304
|
+
|
|
305
|
+
def test_local_image_checked_against_encoded_size(self):
|
|
306
|
+
"""OpenAPI: image data is 'at most 5MB after encoding'. A 4MB raw file encodes to ~5.3MB."""
|
|
307
|
+
f = Path(self.out) / "big.png"
|
|
308
|
+
f.write_bytes(b"\x00" * (4 * 1024 * 1024))
|
|
309
|
+
with self.assertRaises(SystemExit) as ctx:
|
|
310
|
+
search.image_input(str(f))
|
|
311
|
+
self.assertIn("base64", str(ctx.exception.code).lower())
|
|
312
|
+
|
|
313
|
+
def test_uppercase_scheme_image_url_is_a_url_not_a_path(self):
|
|
314
|
+
entry = search.image_input("HTTPS://example.com/a.png")
|
|
315
|
+
self.assertEqual(entry, {"type": "image", "url": "HTTPS://example.com/a.png"})
|
|
316
|
+
|
|
317
|
+
def test_query_plus_image_rejected_single_input_contract(self):
|
|
318
|
+
"""OpenAPI + live: /image-search accepts exactly ONE input; text+image 400s server-side."""
|
|
319
|
+
f = Path(self.out) / "small.png"
|
|
320
|
+
f.write_bytes(TINY_PNG)
|
|
321
|
+
exc, out, err = self.run_main(["dashboard", "--image", str(f), "--topics", "design"])
|
|
322
|
+
self.assertIsNotNone(exc, "query + --image must be rejected locally (API accepts one input)")
|
|
323
|
+
self.assertNotEqual(exc.code, 0)
|
|
324
|
+
self.assertEqual(len(self.server.requests), 0)
|
|
325
|
+
|
|
326
|
+
def test_image_only_sends_single_image_input(self):
|
|
327
|
+
f = Path(self.out) / "small.png"
|
|
328
|
+
f.write_bytes(TINY_PNG)
|
|
329
|
+
self.server.api_script = [self.good_response(1)]
|
|
330
|
+
exc, out, err = self.run_main(["--image", str(f), "--topics", "design"])
|
|
331
|
+
self.assertIsNone(exc)
|
|
332
|
+
inputs = self.server.requests[0]["inputs"]
|
|
333
|
+
self.assertEqual(len(inputs), 1)
|
|
334
|
+
self.assertEqual(inputs[0]["type"], "image")
|
|
335
|
+
|
|
336
|
+
# ---- success contract ----
|
|
337
|
+
|
|
338
|
+
def test_happy_path_saves_image_and_snippet(self):
|
|
339
|
+
"""The deliverable: a usable image file + snippet file + clean manifest."""
|
|
340
|
+
self.server.api_script = [self.good_response(1, summary="style: dark")]
|
|
341
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
342
|
+
self.assertIsNone(exc)
|
|
343
|
+
m = self.manifest()
|
|
344
|
+
self.assertFalse(m["partial"])
|
|
345
|
+
ref = m["octen_refs"][0]
|
|
346
|
+
self.assertIsNone(ref["image_error"])
|
|
347
|
+
self.assertIsNone(ref["snippet_error"])
|
|
348
|
+
self.assertEqual(Path(ref["local_image"]).read_bytes(), TINY_PNG)
|
|
349
|
+
self.assertEqual(Path(ref["html_snippet_file"]).read_text(encoding="utf-8"),
|
|
350
|
+
"<div>x</div>")
|
|
351
|
+
self.assertEqual(ref["summary"], "style: dark")
|
|
352
|
+
self.assertFalse((Path(self.out) / "results.json.tmp").exists(),
|
|
353
|
+
"the atomic-write tmp file must not be left behind")
|
|
354
|
+
|
|
355
|
+
def test_thumbnail_fallback_used_when_primary_fails(self):
|
|
356
|
+
self.server.api_script = [self.good_response(
|
|
357
|
+
1, url=f"{self.base}/img/missing.png", thumbnail=f"{self.base}/img/ok.png")]
|
|
358
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "general"])
|
|
359
|
+
self.assertIsNone(exc)
|
|
360
|
+
ref = self.manifest()["octen_refs"][0]
|
|
361
|
+
self.assertTrue(ref["local_image_is_thumbnail"])
|
|
362
|
+
self.assertEqual(Path(ref["local_image"]).read_bytes(), TINY_PNG)
|
|
363
|
+
self.assertIsNone(ref["image_error"], "an image WAS saved; image_error must be clean")
|
|
364
|
+
|
|
365
|
+
def test_zero_hits_exits_zero_with_manifest(self):
|
|
366
|
+
"""All topics succeed with zero hits: NO RESULTS + exit 0, not a failure."""
|
|
367
|
+
self.server.api_script = [
|
|
368
|
+
{"status": 200, "json": {"code": 0, "data": {"results": []}}},
|
|
369
|
+
{"status": 200, "json": {"code": 0, "data": {"results": []}}},
|
|
370
|
+
]
|
|
371
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design", "general"])
|
|
372
|
+
self.assertIsNone(exc)
|
|
373
|
+
self.assertIn("NO RESULTS", out)
|
|
374
|
+
m = self.manifest()
|
|
375
|
+
self.assertFalse(m["partial"])
|
|
376
|
+
self.assertEqual(m["octen_refs"], [])
|
|
377
|
+
|
|
378
|
+
def test_data_null_is_zero_hits_not_a_failure(self):
|
|
379
|
+
"""The beta envelope is loose; a 200 with data: null is zero hits, not a contract error."""
|
|
380
|
+
self.server.api_script = [{"status": 200, "json": {"code": 0, "data": None}}]
|
|
381
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
382
|
+
self.assertIsNone(exc)
|
|
383
|
+
self.assertIn("NO RESULTS", out)
|
|
384
|
+
self.assertFalse(self.manifest()["partial"])
|
|
385
|
+
|
|
386
|
+
def test_retry_after_header_is_honored(self):
|
|
387
|
+
self.server.api_script = [
|
|
388
|
+
{"status": 429, "json": {"msg": "slow down"}, "headers": {"Retry-After": "7"}},
|
|
389
|
+
self.good_response(1),
|
|
390
|
+
]
|
|
391
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
392
|
+
self.assertIsNone(exc)
|
|
393
|
+
self.assertEqual(self.sleeps, [7.0])
|
|
394
|
+
|
|
395
|
+
# ---- malformed API data must degrade, not crash ----
|
|
396
|
+
|
|
397
|
+
def test_malformed_image_url_is_recorded_not_a_crash(self):
|
|
398
|
+
self.server.api_script = [self.good_response(1, url="http://[bad-ipv6")]
|
|
399
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
400
|
+
self.assertIsNone(exc, "a malformed URL from the API must not crash the run")
|
|
401
|
+
ref = self.manifest()["octen_refs"][0]
|
|
402
|
+
self.assertIsNone(ref["local_image"])
|
|
403
|
+
self.assertTrue(ref["image_error"])
|
|
404
|
+
|
|
405
|
+
def test_lone_surrogate_snippet_survives(self):
|
|
406
|
+
"""json.loads can produce lone surrogates; writing the snippet must not crash."""
|
|
407
|
+
step = self.good_response(1)
|
|
408
|
+
step["json"]["data"]["results"][0]["html_snippet"] = "<div>\ud83d</div>"
|
|
409
|
+
self.server.api_script = [step]
|
|
410
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
411
|
+
self.assertIsNone(exc, "an unencodable html_snippet must not crash the run")
|
|
412
|
+
ref = self.manifest()["octen_refs"][0]
|
|
413
|
+
self.assertTrue(ref["html_snippet_file"], "the snippet should still be written (lossily)")
|
|
414
|
+
self.assertIn("<div>", Path(ref["html_snippet_file"]).read_text(encoding="utf-8"))
|
|
415
|
+
|
|
416
|
+
def test_results_wrong_type_is_topic_error(self):
|
|
417
|
+
self.server.api_script = [
|
|
418
|
+
{"status": 200, "json": {"code": 0, "data": {"results": "nope"}}}]
|
|
419
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
420
|
+
self.assertIsNotNone(exc, "a non-array results field is a contract error, not zero hits")
|
|
421
|
+
self.assertIn("design", self.manifest()["topic_errors"])
|
|
422
|
+
|
|
423
|
+
def test_error_detail_is_truncated(self):
|
|
424
|
+
"""A huge server error body must not be replayed into stderr and the manifest."""
|
|
425
|
+
self.server.api_script = [{"status": 403, "json": {"msg": "x" * 20000}}]
|
|
426
|
+
exc, out, err = self.run_main(["dashboard", "--topics", "design"])
|
|
427
|
+
self.assertIsNotNone(exc)
|
|
428
|
+
self.assertLess(len(self.manifest()["topic_errors"]["design"]), 800)
|
|
429
|
+
|
|
430
|
+
# ---- filename safety ----
|
|
431
|
+
|
|
432
|
+
def test_distinct_topics_do_not_collide_after_slugify(self):
|
|
433
|
+
self.assertNotEqual(search.safe_topic_slug("a b"), search.safe_topic_slug("a_b"))
|
|
434
|
+
|
|
435
|
+
def test_topic_slug_cannot_escape_out_dir(self):
|
|
436
|
+
for topic in ("../evil", "..", "a/b", ".hidden", "..\\win"):
|
|
437
|
+
slug = search.safe_topic_slug(topic)
|
|
438
|
+
self.assertNotIn("/", slug, topic)
|
|
439
|
+
self.assertNotIn("\\", slug, topic)
|
|
440
|
+
self.assertFalse(slug.startswith("."), topic)
|
|
441
|
+
|
|
442
|
+
def test_case_variant_topics_do_not_collide_on_insensitive_filesystems(self):
|
|
443
|
+
a = search.safe_topic_slug("design").lower()
|
|
444
|
+
b = search.safe_topic_slug("Design").lower()
|
|
445
|
+
self.assertNotEqual(a, b, "Design and design must not map to the same file on APFS/NTFS")
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
if __name__ == "__main__":
|
|
449
|
+
unittest.main(verbosity=2)
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: octen-extract
|
|
3
|
+
description: USE FOR extracting clean, LLM-ready content from one or more web page URLs, powered by Octen. Fetch 1-20 URLs in one call and get markdown/text content plus a page category, page-structure label, and (optionally) query-driven highlights. Use it for reading articles, scraping pages for RAG/grounding, summarization, or fact lookup from known URLs. It can also list the links on a page.
|
|
4
|
+
homepage: https://octen.ai
|
|
5
|
+
keywords: [extract, scrape, url, web page, content extraction, markdown, RAG, octen, read url, page links]
|
|
6
|
+
metadata: {"clawdbot":{"emoji":"📄","requires":{"bins":["curl"],"env":["OCTEN_API_KEY"]},"primaryEnv":"OCTEN_API_KEY"}, "homepage": "https://octen.ai", "support": "support@octen.ai"}
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Octen Extract
|
|
10
|
+
|
|
11
|
+
Turn one or more URLs into clean, LLM-ready content. Beyond the page body, each
|
|
12
|
+
result also carries a **category**, a **page-structure** label, and — when you
|
|
13
|
+
pass a `query` — **query-relevant highlights** instead of the full page.
|
|
14
|
+
|
|
15
|
+
> **Requires API Key**: Get one at https://octen.ai · Set it: `export OCTEN_API_KEY=your-api-key`
|
|
16
|
+
|
|
17
|
+
## API Key Setup
|
|
18
|
+
|
|
19
|
+
**Before extracting, ensure `OCTEN_API_KEY` is set. On `401`, stop and tell the user a key is required (https://octen.ai), help them configure it, then continue.** Configure the key for the relevant agent (same as other Octen skills):
|
|
20
|
+
|
|
21
|
+
- **Claude Code** — add `{ "env": { "OCTEN_API_KEY": "your-key" } }` to `~/.claude/settings.json`
|
|
22
|
+
- **Cursor / generic shell** — `export OCTEN_API_KEY="your-key"` in `~/.zshrc` or `~/.bashrc`
|
|
23
|
+
- **Codex** — `~/.codex/config.toml` → `[shell_environment_policy]`, `set = { OCTEN_API_KEY = "your-key" }`
|
|
24
|
+
- **OpenClaw** — add `OCTEN_API_KEY=your-key` to `~/.openclaw/.env`
|
|
25
|
+
|
|
26
|
+
## Endpoint
|
|
27
|
+
|
|
28
|
+
```http
|
|
29
|
+
POST https://api.octen.ai/extract
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Authentication**: `X-Api-Key: <API_KEY>` header · **Content-Type**: `application/json`
|
|
33
|
+
|
|
34
|
+
## Quick Start (cURL)
|
|
35
|
+
|
|
36
|
+
### Batch extract (full content)
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
curl -s -X POST "https://api.octen.ai/extract" \
|
|
40
|
+
-H "Content-Type: application/json" \
|
|
41
|
+
-H "X-Api-Key: ${OCTEN_API_KEY}" \
|
|
42
|
+
-d '{
|
|
43
|
+
"urls": ["https://example.com", "https://octen.ai"],
|
|
44
|
+
"format": "markdown"
|
|
45
|
+
}'
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Query-driven highlights (instead of full content)
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
curl -s -X POST "https://api.octen.ai/extract" \
|
|
52
|
+
-H "Content-Type: application/json" \
|
|
53
|
+
-H "X-Api-Key: ${OCTEN_API_KEY}" \
|
|
54
|
+
-d '{
|
|
55
|
+
"urls": ["https://en.wikipedia.org/wiki/Python_(programming_language)"],
|
|
56
|
+
"query": "async programming"
|
|
57
|
+
}'
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Hard site (advanced mode)
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
curl -s -X POST "https://api.octen.ai/extract" \
|
|
64
|
+
-H "Content-Type: application/json" \
|
|
65
|
+
-H "X-Api-Key: ${OCTEN_API_KEY}" \
|
|
66
|
+
-d '{
|
|
67
|
+
"urls": ["https://www.reddit.com/r/LocalLLaMA/"],
|
|
68
|
+
"mode": "advanced",
|
|
69
|
+
"timeout": 60
|
|
70
|
+
}'
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Mixed batch, difficulty unknown (auto mode)
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
curl -s -X POST "https://api.octen.ai/extract" \
|
|
77
|
+
-H "Content-Type: application/json" \
|
|
78
|
+
-H "X-Api-Key: ${OCTEN_API_KEY}" \
|
|
79
|
+
-d '{
|
|
80
|
+
"urls": ["https://example.com", "https://octen.ai", "https://news.ycombinator.com/item?id=1"],
|
|
81
|
+
"mode": "auto",
|
|
82
|
+
"timeout": 60
|
|
83
|
+
}'
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Page links (outbound references first)
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
curl -s -X POST "https://api.octen.ai/extract" \
|
|
90
|
+
-H "Content-Type: application/json" \
|
|
91
|
+
-H "X-Api-Key: ${OCTEN_API_KEY}" \
|
|
92
|
+
-d '{
|
|
93
|
+
"urls": ["https://octen.ai"],
|
|
94
|
+
"include_links": {"scope": "prefer_external", "max_links": 50}
|
|
95
|
+
}'
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Parameters
|
|
99
|
+
|
|
100
|
+
| Parameter | Type | Required | Default | Description |
|
|
101
|
+
|--|--|--|--|--|
|
|
102
|
+
| `urls` | string[] | **Yes** | - | 1–20 URLs to fetch in one batch |
|
|
103
|
+
| `mode` | string | No | `standard` (when omitted) | `standard`, `advanced`, or `auto` — see [Choosing a mode](#choosing-a-mode) |
|
|
104
|
+
| `query` | string | No | - | When set, each result returns query-relevant `highlights` and OMITS `full_content` (max 500 chars) |
|
|
105
|
+
| `max_age_seconds` | integer | No | `86400` | Accept cached results within this age (min 300); older cached versions are re-fetched |
|
|
106
|
+
| `format` | string | No | `markdown` | Content format: `markdown` or `text` |
|
|
107
|
+
| `timeout` | integer | No | `30` | Per-URL fetch budget in seconds (1–60) |
|
|
108
|
+
| `include_images` | boolean | No | `false` | Include image resources found on the page (also returns `cover_image` when the page has one) |
|
|
109
|
+
| `include_videos` | boolean | No | `false` | Include video URLs found on the page |
|
|
110
|
+
| `include_audio` | boolean | No | `false` | Include audio URLs found on the page |
|
|
111
|
+
| `include_links` | object | No | - | Use it to discover a site's pages or follow outbound references. Returns the page's links: `{scope, max_links}`. `scope`: `prefer_internal` (default; same-site links first) or `prefer_external` (other registered domains first); page order is kept within each group. `max_links`: 1–1000 (default 200; out of range → `400`, not clamped). `{}` uses both defaults |
|
|
112
|
+
|
|
113
|
+
## Choosing a mode
|
|
114
|
+
|
|
115
|
+
You pick the mode; omitting it means `standard`.
|
|
116
|
+
|
|
117
|
+
- **`standard`** (default): fastest and cheapest. Right for ordinary, well-structured pages without anti-bot protection — news, blogs, docs, product pages, static sites. On login-walled, JS-heavy, or anti-bot sites it can return empty content or just a page skeleton **while still reporting `status: "success"`**.
|
|
118
|
+
- **`advanced`**: highest success rate — renders in a real browser with stronger anti-bot handling; slower and 2.5x the price. Use it for known hard sites: anti-bot/WAF-protected sites, JS-heavy SPAs, social sites (Reddit, X, LinkedIn), academic sites (ResearchGate), dynamically loaded content.
|
|
119
|
+
- **`auto`**: decides per URL — standard where it suffices, advanced only for hard URLs; each URL is billed at the mode it actually used. Use it for a mixed batch when you can't tell which URLs are hard. If most URLs are hard, its cost approaches all-advanced.
|
|
120
|
+
|
|
121
|
+
| Scenario | `mode` |
|
|
122
|
+
|--|--|
|
|
123
|
+
| News / blogs / docs / product pages (ordinary sites) | `standard` (or omit) |
|
|
124
|
+
| Known hard sites (Reddit / X / LinkedIn / ResearchGate / anti-bot / SPA) | `advanced` |
|
|
125
|
+
| Mixed batch, unsure which are hard | `auto` |
|
|
126
|
+
| Cost-sensitive, mostly ordinary sites | `standard` |
|
|
127
|
+
| Quality first, mostly hard sites | `advanced` |
|
|
128
|
+
|
|
129
|
+
**Rule of thumb**: all ordinary sites → `standard` (or omit); known hard sites → `advanced`; mixed or unsure → `auto`.
|
|
130
|
+
|
|
131
|
+
**Recovery**: if a `standard` result failed, or came back empty/skeletal (`page_structure.primary` is `"No Main Content"`, or very short content on a page that should have a body), retry just those URLs with `"mode": "advanced"`.
|
|
132
|
+
|
|
133
|
+
**Timeout**: `advanced` and `auto` are slower — raise `timeout` (e.g. `60`).
|
|
134
|
+
|
|
135
|
+
## Response Format
|
|
136
|
+
|
|
137
|
+
| Field | Type | Description |
|
|
138
|
+
|--|--|--|
|
|
139
|
+
| `request_id` | string | Unique request identifier |
|
|
140
|
+
| `data.results[]` | array | One result per URL |
|
|
141
|
+
| `data.results[].url` | string | The URL |
|
|
142
|
+
| `data.results[].status` | string | `success` or `failed` |
|
|
143
|
+
| `data.results[].resolved_mode` | string? | `standard` or `advanced` — the mode actually used for this URL. Present on success, absent on failure. May differ from the requested mode (`auto` picks per URL; `advanced` can resolve to `standard`) |
|
|
144
|
+
| `data.results[].error_message` | string? | Why it failed (when `status` = failed) |
|
|
145
|
+
| `data.results[].title` | string? | Page title |
|
|
146
|
+
| `data.results[].full_content` | string? | Cleaned page content (when no `query`) |
|
|
147
|
+
| `data.results[].highlights` | string[]? | Query-relevant snippets (when `query` is set) |
|
|
148
|
+
| `data.results[].category` | object? | `{primary, secondary}` — what the page is about |
|
|
149
|
+
| `data.results[].page_structure` | object? | `{primary, secondary}` — what kind of page it is |
|
|
150
|
+
| `data.results[].time_published` | string? | Publish time, ISO 8601 |
|
|
151
|
+
| `data.results[].time_last_crawled` | string? | Last crawl time, ISO 8601 |
|
|
152
|
+
| `data.results[].favicon` | string? | Page favicon URL — returned by default when available |
|
|
153
|
+
| `data.results[].cover_image` | object? | `{url}` — page cover image (when `include_images` is true and the page has one) |
|
|
154
|
+
| `data.results[].images` / `videos` / `audio` | object[]? | `[{url}]` — media found on the page (when the matching `include_*` is true) |
|
|
155
|
+
| `data.results[].links` | object[]? | `[{url, anchor_text, is_external}]` — page links (on success, when `include_links` is set and links were found) |
|
|
156
|
+
| `meta.usage.total_urls` | integer | URLs requested |
|
|
157
|
+
| `meta.usage.successful_urls` | integer | URLs successfully fetched |
|
|
158
|
+
| `meta.usage.successful_by_mode` | object | `{standard_urls, advanced_urls}` — successful URLs per mode. **Actual billing is authoritative from these counts**, not from summing `resolved_mode` |
|
|
159
|
+
| `meta.warning` | string | e.g. `"1 URL(s) failed and were not billed"`; empty string when there is nothing to report |
|
|
160
|
+
|
|
161
|
+
`meta` is top-level (a sibling of `data`), not `data.meta`.
|
|
162
|
+
|
|
163
|
+
## Error Codes
|
|
164
|
+
|
|
165
|
+
| HTTP Status | Description |
|
|
166
|
+
|--|--|
|
|
167
|
+
| `400` | Missing or invalid parameter |
|
|
168
|
+
| `401` | Invalid or missing API key |
|
|
169
|
+
| `403` | Insufficient balance |
|
|
170
|
+
| `429` | Rate limited |
|
|
171
|
+
| `500` | Internal server error |
|
|
172
|
+
|
|
173
|
+
## Notes
|
|
174
|
+
|
|
175
|
+
- **Partial success is first-class**: a failed URL is returned with `status: "failed"` + an `error_message`; sibling URLs in the same batch still succeed. Always check per-result `status`.
|
|
176
|
+
- Pass `query` only when you want focused `highlights` for RAG/grounding; omit it to get the full cleaned page.
|
|
177
|
+
- **Pricing**: `standard` $1 / 1K successful URLs, `advanced` $2.5 / 1K. Failed URLs are not billed.
|
|
178
|
+
- `category` and `page_structure` let you route or filter pages (e.g., skip an index/operation page, keep a content page) without reading the whole body.
|