@ysgao/web-cli 0.0.0-stage → 0.1.2

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 CHANGED
@@ -1,3 +1,561 @@
1
- # Temporary Holding Version
1
+ # Web-CLI: Self-Discovering Medical Knowledge Browser
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Status**: AI-agent-facing CLI, supporting macOS and Linux (including a Termux:X11 proot-distro
4
+ Debian on Android — see **Linux / Termux:X11 setup** below).
5
+
6
+ ## What is This?
7
+
8
+ Web-CLI is a JSON-in/JSON-out CLI that searches and retrieves content from subscription
9
+ medical-knowledge sites:
10
+
11
+ - **UpToDate** - Clinical decision support (requires login)
12
+ - **ClinicalKey** - Medical knowledge platform (requires login)
13
+ - **Google Medical Search** - Custom medical search (no login needed)
14
+
15
+ It works by **discovering REST API endpoints at runtime**, watching real network traffic from a
16
+ persistent, dedicated Chrome profile signed into the user's own account, rather than hardcoding
17
+ per-site endpoint knowledge. Every command prints one JSON document to stdout on success, or
18
+ `{"error": "...", "code": "..."}` to stderr on failure.
19
+
20
+ ## Features
21
+
22
+ - **Three-Tier Execution** - Replay a cached endpoint (fast) → auto-discover via browser → manual
23
+ `observe` fallback
24
+ - **No Hardcoded APIs** - Learns endpoints by watching network traffic
25
+ - **Automatic Login Recovery** - An expired session opens one login window, imports the cookies, and
26
+ the search continues on its own; no separate `login` run and no lost results
27
+ - **Sessions Outlive the Browser** - Auth sessions are session cookies that Chrome deletes on exit,
28
+ so the captured jar is stored separately (macOS Keychain, else a `0600` file) and reused
29
+ - **Leaves Your Browser Alone** - Automation runs in its own Chrome instance and profile; you are
30
+ never asked to quit your own Chrome, and no blank windows appear in it
31
+ - **Full JSON I/O** - All results are machine-readable JSON; `--markdown` optionally *also* writes a
32
+ human-readable report
33
+ - **Concurrent Safe** - In-process and cross-process locking prevent Chrome-profile race conditions
34
+
35
+ ## Quick Start
36
+
37
+ ```bash
38
+ npm install
39
+ npm run build
40
+
41
+ # Check authentication
42
+ node dist/index.js auth status
43
+
44
+ # Log in to a site (opens the dedicated automation Chrome profile)
45
+ node dist/index.js login uptodate
46
+
47
+ # Search medical sites
48
+ node dist/index.js search "fever treatment"
49
+
50
+ # Get help
51
+ node dist/index.js --help
52
+ ```
53
+
54
+ Optionally, `npm link` after building to get a global `web-cli` command that live-updates on
55
+ rebuild (see **Publishing** below).
56
+
57
+ ## Commands
58
+
59
+ ```bash
60
+ node dist/index.js login <site> [--durationSeconds 90] [--save-credentials] [--forget-credentials]
61
+ node dist/index.js search "<query>" [--site <site>]... [--allow-visible-login] [--disable-login-recovery] [--loginTimeoutSeconds 240] [--markdown [path]] [--out [path]] [--json] [--pretty]
62
+ # always searches uptodate, clinicalkey, and googlemedsearch (the login-gated/medically-scoped
63
+ # subscription sites this CLI targets); --site adds more. For anything outside medicine/anatomy/
64
+ # substances/organisms, use `websearch` instead (general/open-web search, not restricted to a
65
+ # fixed site list) — there is no more general-purpose default site for `search` itself.
66
+ # By default, an expired session recovers via a saved credential's SILENT refresh only — a
67
+ # visible sign-in window never opens unless you pass --allow-visible-login. --disable-login-recovery
68
+ # is a strict, rarely-needed escape hatch that disables recovery entirely (zero browser launches).
69
+ # --out [path] writes the complete JSON result straight to disk via fs, as its own standalone,
70
+ # standard .json file — independent of --json/--markdown, and immune to anything a caller's own
71
+ # stdout-capturing wraps around the terminal output (a trailing "exit code" marker, a log prefix
72
+ # on every line, stdout/stderr merged together) — the file at "outPath" is always pure, plain
73
+ # JSON.parse-able JSON with nothing else in it. See "Writing a report/JSON result to disk" below.
74
+ node dist/index.js get <site> <idOrUrl> [--allow-visible-login] [--disable-login-recovery] [--loginTimeoutSeconds 240]
75
+ node dist/index.js websearch "<query>" [--engine google|bing|gemini] [--model <model>] [--maxResults <n>] [--fallbackWaitSeconds <n>]
76
+ # general open-web search (NOT restricted to a fixed domain list, unlike the default `search`).
77
+ # Three engines CHAINED together — no single one is a hard dependency for this to return something:
78
+ # google (default) -> bing -> gemini | bing -> gemini | gemini (no further fallback)
79
+ # --engine google (default): drives web-cli's own automation Chrome against www.google.com/search
80
+ # directly — no API key/billing, genuinely relevant real results (see src/search/googleSearch.ts),
81
+ # falling back to a REAL VISIBLE window (for you to resolve a consent/CAPTCHA interstitial by hand,
82
+ # --fallbackWaitSeconds long, default 90) if headless alone returns nothing, then on to bing if that
83
+ # still fails too. --debugHtmlPath <path> saves a successful attempt's raw HTML for capturing a real
84
+ # test fixture — never used by the search itself.
85
+ # --engine bing: no API key/billing at all — scrapes Bing's HTML results page for a {query, hits} list
86
+ # instead (see src/search/bingSearch.ts for real fragility/ToS/geo-bias caveats), then on to gemini
87
+ # if that fails too.
88
+ # --engine gemini: Gemini's own Google Search grounding tool, one synthesized {query, answer}; needs
89
+ # GEMINI_API_KEY or GOOGLE_API_KEY (see "API keys" below), subject to that key's own quota/billing —
90
+ # sits at the END of the chain since it's the only one of the three needing a key/billing at all.
91
+ # The result's own "engine"/"fallback" fields report which engine actually answered and what failed.
92
+ # NOT for weather — use `weather <location>` below instead; none of the three engines actually
93
+ # answer a weather question well (see that command's own description).
94
+ node dist/index.js weather <location>
95
+ # current conditions + a 3-day forecast via wttr.in — no API key/billing at all. USE THIS, not
96
+ # `websearch`, for any weather query: wttr.in actually geocodes `location` and returns real
97
+ # current conditions/forecast data, where neither websearch engine does (gemini is subject to
98
+ # its own quota/billing; bing returns generic weather-website search results, geo-biased toward
99
+ # the request's own origin rather than the place actually named in the query — confirmed live,
100
+ # see src/weather/wttr.ts). `location` is a place name only, never a relative date phrase like
101
+ # "this weekend" — compare the returned forecast[].date entries against whatever specific date
102
+ # was actually asked about, and say so plainly if it falls outside the 3 days returned.
103
+ node dist/index.js auth status [--site <site>]
104
+ node dist/index.js observe --site <site> --intent <search|getArticle> --param "<value>" [--durationSeconds 120]
105
+ node dist/index.js learned [--site <site>]
106
+ node dist/index.js finalize [--markdown [path]] [--json] [--pretty] # reads {query, finalAnswer, summary?, keyReferences, answers} as JSON on stdin
107
+ node dist/index.js render-markdown [--from <path>] [--markdown [path]] [--json] # renders a Markdown report from an ALREADY-RETRIEVED search result -- zero network calls
108
+ node dist/index.js install-skill [--agent claude|codex|agents|all] [--project] [--force]
109
+ node dist/index.js uninstall-skill [--agent claude|codex|agents|all] [--project] [--force]
110
+ ```
111
+
112
+ (Replace `node dist/index.js` with `web-cli` if you've run `npm link`.)
113
+
114
+ ### `install-skill`'s three targets
115
+
116
+ `--agent` accepts `claude`, `codex`, `agents`, or `all` — omit it and `install-skill` registers
117
+ whichever of these are actually present on your machine (falling back to `claude` if none are).
118
+ `claude`/`codex` register with Claude Code (`~/.claude/skills`) and Codex (`~/.codex/prompts`)
119
+ respectively. **`agents`** registers with `~/.agents/skills` (or `$DSH_AGENTS_HOME/skills`) —
120
+ DeepSeek Harness's own bundled skill provider scans this location (and `~/.dsh/skills`) directly
121
+ for its `skill` tool's catalog, and never looks at `~/.claude`/`~/.codex` at all. If you're driving
122
+ this CLI from a DSH-based agent and it reports the `web-cli` skill as "unknown or no longer
123
+ available" even though `install-skill` has already run, this is almost always why — re-run with
124
+ `--agent agents` (or `--agent all`) to also cover it.
125
+
126
+ **On a brand-new machine (e.g. a fresh Termux:X11 proot-distro Debian install), a plain
127
+ `install-skill` with no `--agent` flag can silently skip the `agents` target entirely** — its
128
+ auto-detection (`detectAgents` in `src/skillInstall.ts`) only targets an agent whose home directory
129
+ *already exists*, and `~/.agents` (or `$DSH_AGENTS_HOME`) won't exist yet if DSH itself, or some
130
+ other tool that creates it, hasn't run there before. The command still reports success (typically
131
+ `{"agent":"claude","status":"installed",...}`), which reads as "the skill is installed" — but
132
+ nothing was ever written to `~/.agents/skills`, so DSH's `skill` tool still can't find it. Confirm
133
+ which targets actually ran by checking the `results[].agent` list in the command's own JSON output,
134
+ or just always pass `--agent all` explicitly when you specifically want DSH coverage rather than
135
+ relying on auto-detection. After registering (or re-registering) the `agents` target, **start a new
136
+ DSH session/chat** — the skill catalog a running agent sees is loaded once, at session start, so an
137
+ already-open session won't pick up a skill installed mid-conversation.
138
+
139
+ ### `search`/`finalize`: JSON or a human-readable report, auto-detected from whether stdout is a terminal
140
+
141
+ Every other command here always prints one JSON document to stdout on success — that part of this
142
+ CLI's JSON-in/JSON-out contract is unconditional. `search` and `finalize` are the deliberate
143
+ exception: they can ALSO print a human-readable report instead of the JSON envelope, and **which
144
+ one they print by default is decided automatically, per invocation, from `process.stdout.isTTY`**:
145
+
146
+ ```bash
147
+ web-cli search "myocardial infarction" # a real terminal -> human-readable report
148
+ web-cli search "myocardial infarction" | cat # piped (not a terminal) -> the JSON envelope, automatically
149
+ ```
150
+
151
+ A real, interactive terminal (you, typing the command directly) gets the readable report — a raw
152
+ JSON document dumped into a terminal is unreadable for a person watching it run. Anything else — an
153
+ AI agent's own command-execution mechanism, a shell redirect, a pipe — gets the JSON envelope
154
+ automatically, **with no flag needed**: `agentTask`, `keyReferences[].article.text`, `summary`, and
155
+ everything `finalize` returns only exist in that JSON, and an agent almost always wants it.
156
+
157
+ `--json`/`--pretty` are explicit overrides for the two cases auto-detection can't resolve on its
158
+ own — forcing JSON onto a real terminal, or forcing the readable report onto a non-terminal stdout
159
+ (e.g. piping to a pager like `less`). Passing one when the other is also present is a usage error
160
+ (`INVALID_ARGUMENT`) — pass at most one.
161
+
162
+ ### Session handling (what happens when a login expires)
163
+
164
+ **By default, if a site rejects the stored session, `search`/`get` try a quick, SILENT,
165
+ credential-based refresh — never a visible window.** If a credential was saved for the site (see
166
+ "Credential-based auto-fill login" below), this typically recovers in a few seconds with no human
167
+ involved and nothing shown on screen; with nothing saved, this is a cheap no-op (no browser launched
168
+ at all) and the command reports `SESSION_EXPIRED` right away. This CLI is built to be driven by an
169
+ AI agent more often than typed into directly, so a window popping up that nobody can answer is a
170
+ worse default than an honest `SESSION_EXPIRED` — see "Credential-based auto-fill login" for how to
171
+ make the silent path actually work for a given site.
172
+
173
+ - **`--allow-visible-login`** — opts IN to the older, human-friendly convenience: if the silent
174
+ refresh above doesn't recover the session, open **one** real, visible browser window, wait for you
175
+ to sign in, capture the session, and continue the original command automatically — nothing needs
176
+ re-running. The window always opens on the real site (never blank), your own Chrome is untouched,
177
+ and the wait is bounded by `--loginTimeoutSeconds` (default 240). Pass this when a human is
178
+ actually available and wants that convenience back.
179
+ - **`--disable-login-recovery`** — the strict, rarely-needed escape hatch: disables session
180
+ recovery entirely, with **zero browser launches of any kind** (not even headless) and an
181
+ immediate `SESSION_EXPIRED`. Use this only when the environment genuinely cannot tolerate ANY
182
+ browser automation attempt at all (a sandbox that denies launching even a headless Chrome
183
+ process, say) — most unattended callers want the default (silent refresh still tried) instead.
184
+
185
+ If both are passed, `--disable-login-recovery` wins (it's the strict superset).
186
+
187
+ Because a site's auth session is usually made of **session cookies** — which Chrome deletes when it
188
+ exits — the captured jar is stored outside the browser profile: the macOS Keychain, else a `0600`
189
+ file under `~/.web-cli/sessions/`, else (new: automatic, no configuration needed) a `0600` file
190
+ under `<cwd>/.web-cli/sessions/` in whatever directory you ran `web-cli` from. That third tier
191
+ exists specifically for sandboxed agent shells that deny writes to both of the tiers above — set
192
+ `WEB_CLI_SESSIONS_DIR`/`WEB_CLI_WORKSPACE_SESSIONS_DIR` to relocate either file tier if the default
193
+ locations aren't writable or aren't where you want them.
194
+
195
+ ### Credential-based auto-fill login (for sites with no SSO to silently re-authenticate)
196
+
197
+ Session persistence alone doesn't help if a site's session goes stale server-side in minutes (seen
198
+ on ClinicalKey) and your account has no institutional SSO for the automatic silent-refresh phase to
199
+ replay — you'd otherwise retype a password every time that happens. Run this **once**, interactively:
200
+
201
+ ```bash
202
+ web-cli login clinicalkey --save-credentials
203
+ ```
204
+
205
+ It prompts for your username and password at the terminal (the password isn't echoed), stores them
206
+ securely (same Keychain/file-tier precedence as the session store above, under its own, separate
207
+ Keychain entry), and immediately uses them to fill in and submit this run's login page. Every later
208
+ `search`/`get` whose session has expired then signs back in **automatically, with no visible
209
+ window at all, by default** — using those stored credentials, no flag needed. Only
210
+ `--disable-login-recovery`'s strict, zero-browser guarantee disables this too. `web-cli login
211
+ <site> --forget-credentials` removes a
212
+ stored credential (no prompt, nothing
213
+ auto-filled that run).
214
+
215
+ ### Markdown reports
216
+
217
+ `--markdown` *additionally* writes a human-readable report to a file (independent of whether you
218
+ also passed `--json` — the two are unrelated). Without `--json`, the default report already
219
+ mentions on-screen whether `--markdown` saved a file and where (or that you can pass it to get
220
+ one); with `--json`, that same information comes back in a `markdownPath` field instead.
221
+
222
+ ```bash
223
+ web-cli search "myocardial infarction" --markdown # into the current directory
224
+ web-cli search "myocardial infarction" --markdown report.md # a specific file
225
+ web-cli search "myocardial infarction" --markdown ./reports # a directory (created if missing)
226
+ ```
227
+
228
+ It is off unless asked for, and a problem writing it never fails the search — reported as
229
+ `markdownError` (`--json`) or a stderr note (without it) instead. This report is a **citation
230
+ index**, not a full-text dump — each key reference gets a title/url/snippet and a status line,
231
+ never the article text itself (a single real reference's full text has run to several thousand
232
+ report lines by itself). Full text belongs in the JSON's `keyReferences[].article.text` (so pass
233
+ `--json` to reach it), for the AI agent driving this CLI to actually read — see `agentTask` below,
234
+ and `finalize` next for turning that reading into its own report.
235
+
236
+ ### A standalone JSON file (`--out`) — for automation that captures stdout unreliably
237
+
238
+ `--markdown` above is for a *person*; `--out` is the equivalent for a *machine* parsing this
239
+ command's output. It writes the exact same object `--json` prints — the complete result, including
240
+ every site's raw/parsed hits and every `keyReferences[].article.text` — directly to disk via this
241
+ process's own `fs.writeFileSync`, as a standalone `.json` file with nothing else in it:
242
+
243
+ ```bash
244
+ web-cli search "myocardial infarction" --out # into the current directory
245
+ web-cli search "myocardial infarction" --out result.json # a specific file
246
+ web-cli search "myocardial infarction" --out ./reports # a directory (created if missing)
247
+ ```
248
+
249
+ Same conventions as `--markdown` throughout: off unless asked for, independent of `--json`/
250
+ `--markdown` (freely combine all three), never fails the search over a bad destination
251
+ (`outError`/a stderr note instead), and the path comes back as `outPath`.
252
+
253
+ **Why this exists, concretely**: this CLI's own stdout contract is already exactly one JSON
254
+ document (see CLAUDE.md) — but whatever is capturing that stdout (a shell redirect, a wrapper
255
+ script, an agent harness's own "run a command and show me the output" tool) is free to add its own
256
+ framing around whatever it captured: a command echo, a per-line log prefix, a trailing "exit code"
257
+ marker appended after the process exits (e.g. `EXIT:0`), or this CLI's own stderr progress notices
258
+ (`web-cli: searching 3 sites ...`) merged ahead of the real JSON if stdout/stderr get combined.
259
+ None of that is reproducible or hand-parseable in general — an agent is left re-deriving where the
260
+ real JSON starts and ends by inspecting the captured text's own head/tail, which is exactly the
261
+ extra, bespoke scripting this flag exists to make unnecessary. A file written by `--out` is
262
+ produced by this process's own `fs` call, so nothing outside this process ever gets a chance to
263
+ wrap it in anything — it is pure, standard JSON by construction, safe to feed straight into
264
+ `JSON.parse`/`jq`/any standard JSON tool with no pre-processing, regardless of how noisy the same
265
+ command's captured terminal output turns out to be. Prefer `--out` over redirecting stdout to a
266
+ file yourself whenever the caller doing the capturing is not fully under your control.
267
+
268
+ ### A report from a result you already have — `web-cli render-markdown` (zero network calls)
269
+
270
+ `search --markdown` renders its report inline, as part of a live search. `render-markdown` is the
271
+ standalone counterpart: hand it a `search` result you already retrieved — the exact JSON
272
+ `search --json` printed, or a file written via `search --out` — and it renders the identical report
273
+ with **no network call and no re-querying any site**:
274
+
275
+ ```bash
276
+ web-cli search "aspirin" --json --out result.json # retrieve once, save the JSON
277
+ web-cli render-markdown --from result.json # render a report from it, any time later, for free
278
+ web-cli render-markdown < result.json # or pipe it in on stdin (the default input)
279
+ ```
280
+
281
+ Useful whenever you want a readable report from a JSON blob that's already sitting on disk, without
282
+ paying for another search (possibly minutes, possibly another interactive sign-in) just to get one.
283
+ Unlike `search`/`finalize`, this command's own default output is **always** the rendered Markdown
284
+ text itself — not isatty-gated — since that text is the one thing this command exists to produce,
285
+ not a UX layer over some other JSON. Pass `--json` to get
286
+ `{query, markdown, markdownPath?, markdownError?}` instead (useful for confirming a `--markdown`
287
+ write succeeded without reading stderr, or for embedding the text in a larger pipeline);
288
+ `--markdown [path]` additionally writes a copy to disk, same conventions as `search --markdown`
289
+ (off by default, never fails, a write problem reported as `markdownError` rather than thrown).
290
+
291
+ ### `search` has no LLM — `agentTask` tells the agent what to do next
292
+
293
+ `web-cli` only retrieves; it cannot read the full text it just fetched and answer your actual
294
+ question — that's a step the AI agent driving it has to do. Every `search --json` result therefore
295
+ carries a top-level `agentTask` field (only in the `--json` output — see above) reprinting the
296
+ exact query plus an instruction: read each `keyReferences` entry's full text, cite the ones that
297
+ help answer the question, and treat the rest as irrelevant *to this question* (never deleted —
298
+ `keyReferences` itself is always returned complete and untouched; `agentTask` only ever says what
299
+ to do with it).
300
+
301
+ ### Curated final reports: `web-cli finalize`
302
+
303
+ Once an agent has read the full text and decided what actually answers the question, it can hand
304
+ that judgment back and get a report organized around the *answer* — not around everything that
305
+ happened to get fetched:
306
+
307
+ ```bash
308
+ echo '{
309
+ "query": "is finger the same as digit of the hand",
310
+ "finalAnswer": "Yes -- FMA lists Finger as the preferred name with Digit of hand as a synonym.",
311
+ "summary": { /* optional: pass through the search results own "summary" field for a coverage recap */ },
312
+ "keyReferences": [ /* the exact keyReferences array from a search result */ ],
313
+ "answers": [
314
+ {
315
+ "url": "https://...",
316
+ "quote": "a verbatim excerpt from the retrieved text for that reference",
317
+ "summary": "What this source concludes, described by the agent."
318
+ }
319
+ ]
320
+ }' | web-cli finalize --json --markdown
321
+ ```
322
+
323
+ `finalAnswer` is required and rendered first, ahead of any per-source detail. Every reference
324
+ named in `answers` (by exact `url`) gets its own section with its `quote` and `summary`; every
325
+ other fetched reference is left out of that section but still listed, unused, at the end — nothing
326
+ fetched is ever silently discarded, it's just organized around what actually answered the
327
+ question. **`quote` is required and mechanically verified** — `web-cli` checks it's an actual
328
+ substring of that reference's own retrieved text (whitespace-normalized, no LLM needed) and flags
329
+ one that isn't, both inline in the report and, with `--json`, in the result's `unverifiedQuotes`
330
+ field, so a summary can't just be taken on faith. `--markdown` follows the same convention as
331
+ `search --markdown` and is independent of `--json`; without `--json` the printed report already
332
+ says where it was saved, and with `--json` the result also carries `usedCount`/`notUsedCount` and
333
+ the full rendered report in a `report` field.
334
+
335
+ ### Manual discovery with `observe` (Tier 3 fallback)
336
+
337
+ Tier 2 (automatic discovery) drives a search box using a generic heuristic
338
+ (`src/discovery/heuristics.ts`) that doesn't fit every site's markup. When it can't find or
339
+ successfully use one, `search`/`get` fail with `DISCOVERY_FAILED` and name the exact `observe`
340
+ command to run instead — e.g.:
341
+
342
+ ```
343
+ web-cli: clinicalkey failed — DISCOVERY_FAILED: Could not automatically discover the "search"
344
+ endpoint for "clinicalkey" (observed 54 network events, search box found: false). Try:
345
+ web-cli observe --site clinicalkey --intent search --param "finger"
346
+ ```
347
+
348
+ Run it:
349
+
350
+ ```bash
351
+ web-cli observe --site clinicalkey --intent search --param "finger"
352
+ ```
353
+
354
+ This opens a **visible**, already-signed-in Chrome window and watches network traffic for up to
355
+ `--durationSeconds` (default 120). In that window, perform the action yourself — type `finger` into
356
+ the site's own search box and press Enter, exactly like a normal visitor would. `web-cli` is
357
+ watching, live, for a real API response that actually contains `finger`.
358
+
359
+ On success, it learns and caches the endpoint — so ordinary `search`/`get` no longer need `observe`
360
+ for this `(site, intent)` — and hands back what it captured, including the real response, right
361
+ away:
362
+
363
+ ```json
364
+ {
365
+ "site": "clinicalkey",
366
+ "intent": "search",
367
+ "learned": true,
368
+ "template": {
369
+ "method": "GET",
370
+ "urlTemplate": "https://www.clinicalkey.com/service/search/federated?...&query={{param}}&...",
371
+ "headers": { "Accept": "application/json, text/plain, */*", "...": "..." },
372
+ "learnedAt": 1789066283917
373
+ },
374
+ "data": { "...": "the real, live search response for \"finger\"" }
375
+ }
376
+ ```
377
+
378
+ If nothing matching shows up before the window closes, it says so plainly rather than guessing, with
379
+ enough detail to diagnose why:
380
+
381
+ ```json
382
+ {
383
+ "site": "clinicalkey",
384
+ "intent": "search",
385
+ "learned": false,
386
+ "observedCount": 54,
387
+ "triggerFound": true,
388
+ "hint": "No response containing param was found. Perform the action manually in the opened Chrome window before it closes, or re-run with a longer --durationSeconds."
389
+ }
390
+ ```
391
+
392
+ The same command works for `--intent getArticle`: pass a specific article's id/URL as `--param` and
393
+ open/click into that one article instead of searching. If the page itself is just slow to finish
394
+ loading (confirmed live against ClinicalKey — some sites don't reliably fire a clean browser "load"
395
+ event), the window stays open and usable regardless; you'll see a note on stderr rather than the
396
+ command aborting.
397
+
398
+ ## Files in This Workspace
399
+
400
+ ### Source Code
401
+
402
+ - `src/` - TypeScript source code
403
+ - `dist/index.js` - Built bundled CLI (esbuild output)
404
+ - `test/` - Vitest test suite
405
+ - `skills/` - Shipped Claude Code / Codex / DSH usage-guidance skill (see `install-skill`)
406
+
407
+ ### Documentation
408
+
409
+ - `README.md` - This file
410
+ - `CLAUDE.md` - Detailed architecture documentation (three-tier model, discovery engine, auth, etc.)
411
+ - `KNOWN_ISSUES.md` - Platform-specific issues
412
+
413
+ ## Key Paths
414
+
415
+ | Path | Purpose |
416
+ |------|---------|
417
+ | `dist/index.js` | Built CLI entry point |
418
+ | `src/` | TypeScript source |
419
+ | `CLAUDE.md` | Architecture deep dive |
420
+ | `~/.web-cli/chrome-profile/` | Persistent Chrome automation profile (auto-created) |
421
+ | `~/.web-cli/learned/` | Cached endpoint templates (auto-created) |
422
+ | `~/.web-cli/sessions/` | Stored session cookies, `0600` — only used when the macOS Keychain isn't available; override with `WEB_CLI_SESSIONS_DIR` |
423
+ | `<cwd>/.web-cli/sessions/` | Workspace-tier fallback for session cookies, `0600` — only used when BOTH the Keychain and `~/.web-cli/sessions/` refuse (e.g. a sandboxed agent shell); override with `WEB_CLI_WORKSPACE_SESSIONS_DIR`. Gitignored; never commit it |
424
+ | `~/.web-cli/credentials/` | Stored username/password from `--save-credentials`, `0600` — only used when the macOS Keychain isn't available; override with `WEB_CLI_CREDENTIALS_DIR` |
425
+ | `<cwd>/.web-cli/credentials/` | Workspace-tier fallback for stored credentials, same conditions as the session-cookie fallback above; override with `WEB_CLI_WORKSPACE_CREDENTIALS_DIR`. Gitignored; never commit it |
426
+ | `~/.web-cli/chrome-launcher/` | Generated per-launch macOS wrapper `.app` bundles (auto-created, auto-removed) |
427
+ | `~/.web-cli/chrome-profile.lock` | Cross-process lock file (auto-created) |
428
+ | `~/.web-cli/.env` | Local secrets such as `GEMINI_API_KEY` — see [API keys](#api-keys) below |
429
+
430
+ ## API keys
431
+
432
+ Some functionality (currently: the `websearch` command, backed by `src/gemini/groundedSearch.ts`'s
433
+ Gemini Google Search grounding) needs an API key. It's read from `process.env`, so it must be set through one of these — **never**
434
+ hardcode a key in source:
435
+
436
+ 1. **A normal shell environment variable** — `export GEMINI_API_KEY=...` in your shell profile, or
437
+ set it however your process manager/CI already injects secrets. Always wins over either file
438
+ below.
439
+ 2. **`~/.web-cli/.env`** (recommended for local/personal use) — a plain `KEY=value` file outside
440
+ this repo entirely, loaded automatically on every `web-cli` invocation regardless of which
441
+ directory it's run from. Since it lives outside the git checkout, there is no file to
442
+ `.gitignore` and no way to `git add` it by accident:
443
+ ```bash
444
+ mkdir -p ~/.web-cli
445
+ echo "GEMINI_API_KEY=your-key-here" >> ~/.web-cli/.env
446
+ ```
447
+ 3. **A repo-local `.env`** — convenient when hacking on this checkout directly. Copy
448
+ `.env.example` to `.env` (already gitignored — see `.gitignore`) and fill in the value. Only
449
+ takes effect when `web-cli`/`node dist/index.js` is actually run from this directory (or a
450
+ descendant of it), unlike option 2 above.
451
+
452
+ If the same key is set in more than one place, the first one found wins, in the order listed
453
+ above.
454
+
455
+ ## Development
456
+
457
+ ```bash
458
+ npm install
459
+ npm run build # esbuild bundle of src/index.ts -> dist/index.js
460
+ npm run watch # esbuild --watch
461
+ npm test # vitest run
462
+ npm run test:watch # vitest (watch mode)
463
+ npm run typecheck # tsc --noEmit -p tsconfig.test.json (includes test/**)
464
+ ```
465
+
466
+ Run a single test file: `npx vitest run test/endpointLearner.test.ts`
467
+
468
+ ## Three-Tier Execution Model
469
+
470
+ 1. **Replay** (~100-500ms) - Uses a cached endpoint template, direct HTTP call with the live cookie
471
+ jar. No browser overhead.
472
+ 2. **Discover** (~10-30s, first time only) - Launches the dedicated automation Chrome, drives it to
473
+ perform the action, and captures the real REST call from network traffic. The learned template
474
+ is persisted to `~/.web-cli/learned/<site>.json` for future Tier 1 replays.
475
+ 3. **Observe** (fallback, manual) - `web-cli observe` opens the automation Chrome for a human to
476
+ drive directly, for sites/pages the automated heuristic can't handle.
477
+
478
+ After first discovery for a given `(site, intent)`, operations are fast (Tier 1). See `CLAUDE.md`
479
+ for full details, including the preseed mechanism for sandboxed environments that can't launch
480
+ Chrome.
481
+
482
+ ## Linux / Termux:X11 setup
483
+
484
+ On Linux, `login`/`observe` (and any first-time discovery for a new `(site, intent)`) drive a
485
+ Chromium/Chrome binary directly rather than macOS's `open -a` — see `CLAUDE.md`'s auth/discovery
486
+ sections for the mechanics. Prerequisites, on Debian/Termux-proot:
487
+
488
+ ```bash
489
+ apt install chromium sqlite3 xvfb # chromium: the automation browser itself
490
+ # sqlite3: the CLI cookieCapture.ts shells out to
491
+ # xvfb: gives tier-2's unattended discovery its own private,
492
+ # invisible display — see chromeLauncher.ts's
493
+ # LINUX_PRIVATE_XVFB_BASE_DISPLAY_NUMBER doc comment
494
+ ```
495
+
496
+ For `login`/`observe` (which show a real window for you to interact with), web-cli auto-starts
497
+ **both halves** of Termux:X11's GUI stack itself if `DISPLAY` isn't already set and nothing is
498
+ already serving it: its own backend (`termux-x11 :1`) and the Termux:X11 **app** — you no longer
499
+ need to run `termux-x11 :1 &` from Termux, nor open the app by hand first.
500
+
501
+ The app-launch step needs one one-time Android permission grant: **Settings → Apps → Termux →
502
+ "Draw over other apps"** (`SYSTEM_ALERT_WINDOW`). Without it, Android's Background Activity Start
503
+ restriction silently blocks the window from appearing even though the underlying `am start` call
504
+ itself reports success — confirmed live, cold-state, end-to-end (app closed, backend killed) on a
505
+ real device: it fails silently without the permission, and reliably brings both the app and backend
506
+ back with zero manual interaction once granted. If your device has no such toggle, or the app still
507
+ doesn't reopen, just open the Termux:X11 app yourself once as before — everything else still works
508
+ unchanged.
509
+
510
+ Log in once with `web-cli login <site>`; cookies are read from that same automation profile, and — since Chrome
511
+ discards session cookies on exit — the captured session is also stored under
512
+ `~/.web-cli/sessions/` (`0600`, since a Termux proot has no keyring) so it survives into later
513
+ commands. That file is no weaker than Chrome's own `--password-store=basic` database sitting beside
514
+ it.
515
+
516
+ ## Supported Sites
517
+
518
+ - **UpToDate** (`www.uptodate.com`) - Login-gated. On an institutional IP, access is granted by the
519
+ network itself (measured identical responses with the cookie jar removed entirely). Off that
520
+ network, it requires a real signed-in session — including genuine session cookies, not just
521
+ persistent ones — and an unentitled request doesn't fail outright: it comes back as an ordinary
522
+ `HTTP 200` whose body is a truncated "you must sign in" stub. `search`/`get` detect this
523
+ content-based paywall and open a login window the same as any other expired session.
524
+ - **ClinicalKey** (`www.clinicalkey.com`) - Requires login. Note it issues an *anonymous* session on
525
+ page load that satisfies search while refusing full text, so "search works" does not mean
526
+ "signed in"
527
+ - **Google Medical Search** (`cse.google.com`) - No login needed (marked `requiresLogin: false`, so
528
+ a failure there is only ever a stale token to rediscover)
529
+
530
+ Known sites are registered in `src/sites/index.ts`.
531
+
532
+ ## Troubleshooting
533
+
534
+ | Issue | Solution |
535
+ |-------|----------|
536
+ | Session expired | By default, nothing to do if a credential was saved (`web-cli login clinicalkey --save-credentials`) — it recovers silently. Otherwise pass `--allow-visible-login` to let a window open, or sign in ahead of time: `web-cli login clinicalkey` |
537
+ | `SESSION_EXPIRED` returned | No credential was stored for the site, or the silent refresh didn't recover it (no visible window opens unless you passed `--allow-visible-login`, in which case it timed out). With `--disable-login-recovery`: recovery is fully disabled, by design |
538
+ | Full text missing on a hit | Check `keyReferences[].fetchError`. `SESSION_EXPIRED` there means signed in but not entitled to that item; `DISCOVERY_FAILED` means the article endpoint needs re-learning |
539
+ | Your own Chrome is open | Not a problem, and never was worth quitting it for — automation uses its own instance (see `src/discovery/chromeWrapperApp.ts`, and its regression tests in `test/chromeWrapperApp.test.ts`) |
540
+ | Discovery failed | Run: `node dist/index.js observe --site uptodate --intent search --param "test"` — see **Manual discovery with `observe`** above for a full walkthrough |
541
+ | Build out of date | Run: `npm install && npm run build` |
542
+ | Platform-specific issues | See `KNOWN_ISSUES.md` |
543
+
544
+ ## Publishing
545
+
546
+ This package is **not published to npm** (see `CLAUDE.md` for why). For local use:
547
+
548
+ ```bash
549
+ npm run build
550
+ npm link # symlinks the `web-cli` command globally to this checkout's dist/index.js
551
+ ```
552
+
553
+ After `npm link`, editing code + `npm run build` alone is enough for the global `web-cli` command
554
+ to pick up the change. Undo with `npm unlink -g @ysgao/web-cli`.
555
+
556
+ ## Support
557
+
558
+ For questions:
559
+ 1. Review `KNOWN_ISSUES.md` for platform-specific issues
560
+ 2. Read `CLAUDE.md` for architecture details
561
+ 3. Review source in `src/`