Skip to content

Open-source, local-first social media research agent for Instagram, TikTok, and LinkedIn. Jev routes read-only steps; socai CLI captures cited browser evidence.

Initial release

Asklva0f626ffe0bf
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..8312003
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,14 @@
+# Jev on OpenRouter. The lowercase `openrouter=` form is also accepted.
+OPENROUTER_API_KEY=
+OPENROUTER_JEV_MODEL=~typesafe/jev-latest
+
+# Optional path to a local or development socai binary.
+SOCAI_BIN=
+
+# Optional browser routing. Existing is socai's default; use a CDP endpoint
+# when connecting to a remote or tunneled DeepTensor browser.
+# SOCAI_CHROME_PROFILE=existing
+# SOCAI_CDP_WS=wss://your-browser-websocket
+
+# Optional isolated state directory. Defaults to ~/.jev-social.
+JEV_SOCIAL_HOME=
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0831a14
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+.env
+.DS_Store
+npm-debug.log*
+coverage/
+*.tgz
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..adadf1b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 jev-social contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..790bb38
--- /dev/null
+++ b/README.md
@@ -0,0 +1,179 @@
+<img src="docs/banner.png" alt="Jev Social — typed decisions and real social data" width="100%" />
+
+# Jev × socai
+
+**Jev decides the route. [socai](https://socai.io/) does the real browser work. You get searchable posts, downloaded videos, a complete table, and an evidence-led agent report in one local page.**
+
+[Visit socai.io](https://socai.io/) · [Star socai on GitHub](https://github.com/socai-io/socai) · [Meet Jev at TypeSafe](https://typesafe.ai/)
+
+## See it run
+
+![Jev × socai live social research demo](docs/jev-social.gif)
+
+Give the demo a social research goal such as “find the fastest-growing AI wearable conversations on TikTok.” Jev makes one typed choice—Instagram, TikTok, or unsupported—then the local socai CLI searches the live site. TikTok results continue into `get-videos --download-media`, so the result page can play the files socai actually captured instead of showing a fabricated preview. The new non-interactive `socai research` command then runs the real socai agent loop, streams captured evidence into the page, and writes the final Markdown report.
+
+## From half an hour to one minute
+
+A manual social scan is a chain of small tasks: choose a network, search, open posts, copy captions and engagement, download videos, normalize rows, and assemble evidence. Jev × socai turns that chain into one request.
+
+| Workflow | Manual research baseline | Jev × socai demo target | Reduction |
+| --- | ---: | ---: | ---: |
+| Search one social topic | 5–10 min | 10–20 s | up to 30× faster |
+| Open and inspect 10 posts | 10–15 min | 20–30 s | up to 45× faster |
+| Download video evidence | 5–10 min | included in the run | no separate step |
+| Build a normalized results table | 5–15 min | immediate | no copy/paste |
+| **End-to-end trend scan** | **about 30 min** | **about 50 s** | **about 36× faster** |
+
+The 30-minute baseline and 50-second target are an illustrative demo comparison, not a universal benchmark. Live duration depends on result count, video size, login state, network conditions, and platform throttling. The UI always shows the measured elapsed time for the current run.
+
+## What the demo returns
+
+The result page is designed for a screen recording and stays on one page:
+
+- live elapsed time while Jev and socai work;
+- streamed evidence cards instead of a frozen loading screen or raw CLI log;
+- a top-to-bottom TypeSafe-inspired gradient scan during capture;
+- every returned post or video as a rich evidence card;
+- local playback for videos downloaded by socai;
+- captions, authors, dates, engagement, duration, comments, and source links;
+- a complete, normalized evidence table;
+- a socai agent report with an executive summary, evidence, themes, audience signals, limits, and sources.
+
+Example table shape:
+
+| Platform | Author | Title / caption | Published | Views | Likes | Comments | Shares | Duration | Media |
+| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | --- |
+| TikTok | creator handle | Captured post caption | ISO timestamp | 128K | 9.4K | 312 | 840 | 34s | Downloaded |
+| Instagram | creator handle | Captured reel or post | ISO timestamp | — | 4.1K | 96 | — | — | Preview |
+
+The saved run still retains the structured CLI result for reproducibility, while the recording UI stays focused on posts, video, timing, the comparison table, and the final report.
+
+## One goal, one typed route, real CLI execution
+
+```text
+research goal
+ │
+ ▼
+Jev typed decision ── instagram_search ──┐
+ ├─ tiktok_search ─────┼─► socai browser workflow
+ └─ unsupported ───────┘ │
+ ├─ search results
+ ├─ post details
+ ├─ comments
+ ├─ downloaded video
+ └─ research agent
+ │
+ ▼
+ cards + table + report
+```
+
+Jev receives the complete natural-language request. socai receives the normalized literal search term expected by its adapter. The model cannot supply shell fragments, selectors, or browser actions; the Node process launches socai with an argument array.
+
+For TikTok, a successful run uses both stable CLI stages:
+
+```bash
+socai tiktok search "AI wearables" --num 10 --pretty
+socai tiktok get-videos --video <url> --download-media --pretty
+```
+
+Instagram search uses the native dev adapter:
+
+```bash
+socai instagram search "AI wearables" --num 10 --pretty
+```
+
+Both routes finish through the same non-interactive agent entrypoint:
+
+```bash
+socai research "Compare the strongest signals and cite the captured posts" \
+ --platform instagram --max-steps 6 --pretty
+```
+
+## Run the recording demo
+
+Requirements: Node.js 20+, an OpenRouter key with Jev access, and the included socai dev build.
+
+```bash
+npm install
+cp .env.example .env
+# Add OPENROUTER_API_KEY to .env.
+npm start
+```
+
+The browser opens directly at `http://127.0.0.1:8766`. The server binds only to the loopback interface, so no local API token or token-bearing URL is required. For the cleanest recording:
+
+1. Enter a goal and leave the platform on **Jev · auto**.
+2. Start the run and keep the live timer and streamed evidence cards in frame.
+3. Wait for the captured-post grid.
+4. Play a downloaded video directly in its card.
+5. Scroll through the complete table and the **socai research report**.
+
+The header includes direct links to [socai.io](https://socai.io/) and the [socai GitHub repository](https://github.com/socai-io/socai).
+
+## Configuration
+
+The app loads the first available environment source:
+
+1. `JEV_SOCIAL_ENV_FILE`, when explicitly set;
+2. this repository's `.env`;
+3. `docs/work/20260918-2/.env` in the parent socai workspace.
+
+Both `OPENROUTER_API_KEY=...` and the existing lowercase `openrouter=...` form are accepted. `SOCAI_BIN` can point to a custom build. In this workspace the default resolver discovers:
+
+```text
+docs/work/20260918/worktrees/dev-platform-validation/target/debug/socai
+```
+
+That build is based on socai dev / v0.5.6 and exposes Instagram search, TikTok search, detail reading, comments, media download, and the non-interactive research agent used by this demo.
+
+Browser selection follows socai instead of being overridden by the demo. With no override, socai uses the existing Chrome debugging session and can reuse an authenticated profile such as the validated Deeptensor Profile 5. Set `SOCAI_CHROME_PROFILE=managed` only for an isolated browser, or set `SOCAI_CDP_WS` / `SOCAI_CDP_URL` for an explicit remote browser endpoint.
+
+## CLI usage
+
+```bash
+npm start -- status
+npm start -- search "find AI wearable trends on TikTok" --platform auto --limit 10
+npm start -- search "find emerging design creators on Instagram" --platform auto --limit 10
+npm start -- serve --port 8766 --no-open
+```
+
+The `--limit` option remains available to the command-line interface. The web demo intentionally captures and displays up to four previewable records, prioritizing downloaded video, playable video URLs, posters, and thumbnails so the recording stays fast and avoids empty cards.
+
+## Why this is genuinely socai
+
+- **The server launches the configured socai executable.** It does not contain a second browser scraper.
+- **Progress is streamed from the child process.** Browser and download activity appears while the run is still active.
+- **Video playback uses a file written by socai.** Local media paths are validated under the socai run directory and exposed through short-lived loopback-only URLs with HTTP range support.
+- **The final report comes from the socai agent.** The UI renders the Markdown report emitted by `socai research`; it does not generate a browser-side summary.
+- **Failures stay visible.** Login gates, challenges, rate limits, invalid JSON, missing adapters, download failures, and timeouts are reported instead of replaced with fixtures.
+- **Credentials remain separated.** The OpenRouter key stays in the Node process and is removed from the socai child environment.
+
+## Small enough to audit
+
+| File | Responsibility |
+| --- | --- |
+| [`src/classifier.js`](src/classifier.js) | Jev route schema and OpenRouter Decisions request |
+| [`src/query.js`](src/query.js) | Natural-language goal to literal search query |
+| [`src/socai.js`](src/socai.js) | socai capability checks, search, video hydration, downloads, research, and stdout parsing |
+| [`src/app.js`](src/app.js) | Evidence capture, agent research, and result merging |
+| [`src/server.js`](src/server.js) | NDJSON streaming, loopback security, and range-based local media serving |
+| [`public/app.js`](public/app.js) | Live timer, progress stream, video cards, details, table, and final output |
+
+## Evidence and limits
+
+The local Instagram smoke test on September 19, 2026 used `typesafe/jev-1.13-20260917`; Jev selected Instagram and the real socai CLI returned live results successfully. Timing from one smoke test is evidence of execution, not a latency guarantee.
+
+Remote sites still control availability. Login state, challenges, regional behavior, rate limits, changing layouts, and expiring media URLs can affect a run. The application is read-only: it does not post, like, follow, message, or silently substitute sample data.
+
+## Development
+
+```bash
+npm test
+npm run check
+```
+
+Tests use local mock binaries and do not require live model calls. Real searches call OpenRouter and launch the configured socai browser workflow. Run records remain under `~/.jev-social/runs/`; credentials and `.env` files remain ignored.
+
+---
+
+Built with [Jev by TypeSafe](https://typesafe.ai/) and [socai](https://socai.io/). If this workflow is useful, [star socai on GitHub](https://github.com/socai-io/socai).
diff --git a/bin/jev-social.js b/bin/jev-social.js
new file mode 100755
index 0000000..a73d0a1
--- /dev/null
+++ b/bin/jev-social.js
@@ -0,0 +1,198 @@
+#!/usr/bin/env node
+
+import readline from "node:readline/promises";
+import { stdin, stdout } from "node:process";
+import { runSearch } from "../src/app.js";
+import { getConfigPath, readConfig, resolveApiKey } from "../src/config.js";
+import { loadLocalEnv } from "../src/env.js";
+import { saveOnboarding } from "../src/onboard.js";
+import { probeSocai } from "../src/socai.js";
+import { startServer } from "../src/server.js";
+
+const HELP = `jev-social — Jev-routed social research through socai CLI
+
+Usage:
+ jev-social Start local preview
+ jev-social onboard [options] Optional manual configuration
+ jev-social status Show local readiness
+ jev-social search <query> [options] Run one search
+ jev-social serve [--port 8766] [--no-open] Start local preview
+
+Search options:
+ --platform <auto|instagram|tiktok> Platform hint (default: auto)
+ --limit <1-100> Result limit (default: 10)
+
+Configuration (normally auto-loaded from .env):
+ --api-key <key> OpenRouter API key (prompt is safer)
+ --socai-bin <path> socai executable override
+ --install Install/reinstall official socai CLI
+ --skip-install Do not offer CLI installation
+ --no-verify Save API key without a network check
+`;
+
+try {
+ await loadLocalEnv();
+ const [command = "serve", ...rest] = process.argv.slice(2);
+ if (["help", "--help", "-h"].includes(command)) {
+ console.log(HELP);
+ } else if (command === "serve") {
+ const flags = parseArgs(rest);
+ await startServer({ port: flags.port || 8766, open: !flags.noOpen });
+ } else if (command === "status") {
+ const config = await readConfig();
+ console.log(
+ JSON.stringify(
+ {
+ jevConfigured: Boolean(resolveApiKey(config)),
+ jevModel: process.env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",
+ configPath: getConfigPath(),
+ socai: await probeSocai(config),
+ },
+ null,
+ 2,
+ ),
+ );
+ } else if (command === "onboard") {
+ await onboard(parseArgs(rest));
+ } else if (command === "search") {
+ const flags = parseArgs(rest);
+ const query = flags._.join(" ").trim();
+ const run = await runSearch(
+ { query, platform: flags.platform || "auto", limit: Number(flags.limit || 10) },
+ {
+ onEvent(event) {
+ if (event.message) console.error(`[${event.stage}] ${event.message}`);
+ },
+ },
+ );
+ console.log(JSON.stringify(run, null, 2));
+ } else {
+ throw new Error(`Unknown command: ${command}\n\n${HELP}`);
+ }
+} catch (error) {
+ console.error(`jev-social: ${error.message}`);
+ if (error.details) console.error(JSON.stringify(error.details, null, 2));
+ process.exitCode = 1;
+}
+
+async function onboard(flags) {
+ const current = await readConfig();
+ let apiKey;
+ let persistApiKey = false;
+ if (flags.apiKey) {
+ apiKey = flags.apiKey;
+ persistApiKey = true;
+ } else if (resolveApiKey(current)) {
+ apiKey = resolveApiKey(current);
+ }
+ if (!apiKey) {
+ apiKey = await promptSecret("OpenRouter API key: ");
+ persistApiKey = true;
+ }
+
+ const proposed = { ...current, ...(flags.socaiBin ? { socaiBin: flags.socaiBin } : {}) };
+ const before = await probeSocai(proposed);
+ let installCli = Boolean(flags.install);
+ if (!before.installed && !flags.skipInstall && !flags.install) {
+ installCli = await promptYesNo("socai CLI was not found. Install the official release now?", true);
+ }
+
+ console.log("Checking setup…");
+ const result = await saveOnboarding({
+ apiKey,
+ socaiBin: flags.socaiBin,
+ installCli,
+ verify: !flags.noVerify,
+ persistApiKey,
+ onMessage: (message) => console.log(message),
+ });
+ console.log(`Saved ${result.configPath}`);
+ console.log(`Jev API: ${flags.noVerify ? "saved (not verified)" : "verified"}`);
+ console.log(`socai CLI: ${result.socai.installed ? result.socai.bin : "not ready"}`);
+ if (result.socai.capabilities) {
+ console.log(`Capabilities: ${JSON.stringify(result.socai.capabilities)}`);
+ }
+}
+
+function parseArgs(args) {
+ const result = { _: [] };
+ const booleanFlags = new Map([
+ ["--no-open", "noOpen"],
+ ["--skip-install", "skipInstall"],
+ ["--install", "install"],
+ ["--no-verify", "noVerify"],
+ ]);
+ const valueFlags = new Map([
+ ["--platform", "platform"],
+ ["--limit", "limit"],
+ ["--port", "port"],
+ ["--api-key", "apiKey"],
+ ["--socai-bin", "socaiBin"],
+ ]);
+ for (let index = 0; index < args.length; index += 1) {
+ const token = args[index];
+ if (booleanFlags.has(token)) {
+ result[booleanFlags.get(token)] = true;
+ } else if (valueFlags.has(token)) {
+ const value = args[index + 1];
+ if (!value || value.startsWith("--")) throw new Error(`${token} requires a value.`);
+ result[valueFlags.get(token)] = value;
+ index += 1;
+ } else if (token.startsWith("--")) {
+ throw new Error(`Unknown option: ${token}`);
+ } else {
+ result._.push(token);
+ }
+ }
+ return result;
+}
+
+async function promptYesNo(question, defaultYes) {
+ if (!stdin.isTTY) return defaultYes;
+ const rl = readline.createInterface({ input: stdin, output: stdout });
+ try {
+ const answer = (await rl.question(`${question} ${defaultYes ? "[Y/n]" : "[y/N]"} `)).trim().toLowerCase();
+ if (!answer) return defaultYes;
+ return answer === "y" || answer === "yes";
+ } finally {
+ rl.close();
+ }
+}
+
+function promptSecret(label) {
+ if (!stdin.isTTY || typeof stdin.setRawMode !== "function") {
+ throw new Error("Set OPENROUTER_API_KEY when onboarding without an interactive terminal.");
+ }
+ return new Promise((resolve, reject) => {
+ let value = "";
+ stdout.write(label);
+ stdin.setRawMode(true);
+ stdin.resume();
+ stdin.setEncoding("utf8");
+ const cleanup = () => {
+ stdin.off("data", onData);
+ stdin.setRawMode(false);
+ stdin.pause();
+ };
+ const onData = (character) => {
+ if (character === "\u0003") {
+ cleanup();
+ stdout.write("\n");
+ reject(new Error("Onboarding cancelled."));
+ } else if (character === "\r" || character === "\n") {
+ cleanup();
+ stdout.write("\n");
+ resolve(value);
+ } else if (character === "\u007f" || character === "\b") {
+ if (value) {
+ value = value.slice(0, -1);
+ stdout.write("\b \b");
+ }
+ } else if (character >= " ") {
+ value += character;
+ stdout.write("•");
+ }
+ };
+ stdin.on("data", onData);
+ });
+}
diff --git a/docs/banner.png b/docs/banner.png
new file mode 100644
index 0000000..b3930c3
Binary files /dev/null and b/docs/banner.png differ
diff --git a/docs/jev-social.gif b/docs/jev-social.gif
new file mode 100644
index 0000000..5a18c4d
Binary files /dev/null and b/docs/jev-social.gif differ
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..fb51b64
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,19 @@
+{
+ "name": "jev-social",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "jev-social",
+ "version": "0.1.0",
+ "license": "MIT",
+ "bin": {
+ "jev-social": "bin/jev-social.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..9db2e0a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "jev-social",
+ "version": "0.1.0",
+ "description": "Jev-routed Instagram and TikTok research through the socai CLI",
+ "type": "module",
+ "bin": {
+ "jev-social": "./bin/jev-social.js"
+ },
+ "exports": {
+ ".": "./src/index.js"
+ },
+ "files": [
+ "bin",
+ "docs",
+ "public",
+ "src",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "start": "node ./bin/jev-social.js",
+ "dev": "node --watch ./bin/jev-social.js serve --no-open",
+ "check": "node --check ./bin/jev-social.js && node --check ./src/server.js && node --check ./public/app.js",
+ "test": "node --test"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "keywords": [
+ "jev",
+ "socai",
+ "instagram",
+ "tiktok",
+ "research"
+ ],
+ "license": "MIT"
+}
diff --git a/public/app.js b/public/app.js
new file mode 100644
index 0000000..97b17e7
--- /dev/null
+++ b/public/app.js
@@ -0,0 +1,681 @@
+const $ = (selector) => document.querySelector(selector);
+const elements = {
+ searchView: $("#search-view"),
+ resultView: $("#result-view"),
+ searchForm: $("#search-form"),
+ activity: $("#activity"),
+ activityTitle: $("#activity-title"),
+ activityMessage: $("#activity-message"),
+ error: $("#error"),
+ result: $("#result"),
+ cards: $("#cards"),
+ evidenceHeading: $("#evidence-heading"),
+ evidenceTable: $("#evidence-table"),
+ reportSection: $("#research-report-section"),
+ output: $("#socai-output"),
+ elapsed: $("#elapsed-time"),
+ dialog: $("#detail-dialog"),
+ detail: $("#detail-content"),
+};
+
+let timer;
+let startedAt = 0;
+let activeController;
+
+elements.searchForm.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ clearError();
+ resetLiveWorkspace();
+ const query = $("#query").value.trim();
+ $("#result-title").textContent = query;
+ showResultView({ push: true });
+ const button = elements.searchForm.querySelector("button[type=submit]");
+ button.disabled = true;
+ activeController?.abort();
+ activeController = new AbortController();
+ startTimer();
+ showActivity("Jev is routing the request", "Preparing a read-only social research workflow…");
+ try {
+ const run = await streamApi("/api/search-stream", {
+ query,
+ platform: $("#platform").value,
+ }, handleStreamEvent, activeController.signal);
+ renderRun(run);
+ } catch (error) {
+ if (error.name !== "AbortError") showError(error);
+ } finally {
+ activeController = undefined;
+ stopTimer();
+ button.disabled = false;
+ }
+});
+
+$("#back-to-search").addEventListener("click", () => {
+ if (location.hash === "#results") history.back();
+ else showSearchView();
+});
+$("#close-detail").addEventListener("click", () => elements.dialog.close());
+elements.dialog.addEventListener("click", (event) => {
+ if (event.target === elements.dialog) elements.dialog.close();
+});
+
+window.addEventListener("popstate", () => {
+ if (location.hash === "#results") showResultView();
+ else showSearchView();
+});
+
+void refreshStatus();
+
+function handleStreamEvent(event) {
+ if (event.stage === "result") return;
+ if (event.stage === "error") {
+ const error = new Error(event.error?.message || "The social research run failed.");
+ error.code = event.error?.code;
+ error.details = event.error?.details;
+ throw error;
+ }
+ if (event.stage === "evidence") {
+ showLiveEvidence(event.items);
+ return;
+ }
+ const titles = {
+ classifying: "Jev is routing the request",
+ executing: "socai is starting the browser",
+ searching: "socai is collecting search results",
+ downloading: "socai is reading and downloading videos",
+ researching: "socai is researching the captured evidence",
+ complete: "socai finished the run",
+ };
+ const descriptions = {
+ classifying: "Choosing the right social workflow.",
+ executing: "Opening the local browser.",
+ searching: "Collecting previewable posts.",
+ downloading: "Preparing video previews.",
+ researching: "Reading captured posts and building the report.",
+ complete: "The research report is ready.",
+ };
+ showActivity(titles[event.stage] || "socai is working", descriptions[event.stage] || "Research is in progress.");
+}
+
+function startTimer() {
+ startedAt = performance.now();
+ clearInterval(timer);
+ updateTimer();
+ timer = setInterval(updateTimer, 100);
+}
+
+function stopTimer(finalMs) {
+ clearInterval(timer);
+ timer = undefined;
+ if (Number.isFinite(finalMs)) elements.elapsed.textContent = formatDuration(finalMs);
+ else updateTimer();
+}
+
+function updateTimer() {
+ if (startedAt) elements.elapsed.textContent = `${((performance.now() - startedAt) / 1000).toFixed(1)} s`;
+}
+
+function showResultView({ push = false } = {}) {
+ elements.searchView.classList.add("hidden");
+ elements.resultView.classList.remove("hidden");
+ if (push && location.hash !== "#results") history.pushState({ view: "results" }, "", `${location.pathname}${location.search}#results`);
+}
+
+function showSearchView() {
+ activeController?.abort();
+ elements.resultView.classList.add("hidden");
+ elements.searchView.classList.remove("hidden");
+ elements.activity.classList.add("hidden");
+ elements.resultView.classList.remove("has-live-evidence", "is-running");
+ clearError();
+ $("#query").focus();
+}
+
+async function refreshStatus() {
+ try {
+ const status = await api("/api/status");
+ setStatus("jev", status.jevConfigured, status.jevConfigured ? "Jev ready" : "Jev needs a key");
+ const caps = status.socai.capabilities || {};
+ const ready = status.socai.installed && (caps.instagram || caps.tiktok);
+ setStatus("socai", ready, ready ? "socai ready" : "socai unavailable");
+ } catch (error) {
+ showError(error);
+ }
+}
+
+function setStatus(prefix, ready, label) {
+ $(`#${prefix}-dot`).classList.toggle("ready", ready);
+ $(`#${prefix}-status`).textContent = label;
+}
+
+function showActivity(title, message) {
+ const changed = elements.activityTitle.textContent !== title || elements.activityMessage.textContent !== message;
+ elements.activityTitle.textContent = title;
+ elements.activityMessage.textContent = message;
+ if (changed) {
+ elements.activityMessage.classList.remove("message-swap");
+ void elements.activityMessage.offsetWidth;
+ elements.activityMessage.classList.add("message-swap");
+ }
+ elements.activity.classList.remove("hidden");
+}
+
+function showError(error) {
+ elements.activity.classList.add("hidden");
+ elements.error.textContent = error.message;
+ elements.error.classList.remove("hidden");
+}
+
+function clearError() {
+ elements.error.classList.add("hidden");
+ elements.error.textContent = "";
+}
+
+function renderRun(run) {
+ elements.activity.classList.add("hidden");
+ elements.resultView.classList.remove("has-live-evidence", "is-running");
+ elements.reportSection.classList.remove("hidden");
+ stopTimer(run.elapsedMs);
+ $("#result-title").textContent = run.request || run.query || "Social results";
+
+ const items = findItems(run.result);
+ const hasEvidence = items.length > 0;
+ elements.evidenceHeading.classList.toggle("hidden", !hasEvidence);
+ elements.evidenceTable.classList.toggle("hidden", !hasEvidence);
+ elements.cards.classList.toggle("hidden", !hasEvidence);
+ const downloaded = items.filter((item) => Boolean(localVideoSource(item))).length;
+ $("#result-summary").textContent = `${items.length} previewable ${items.length === 1 ? "record" : "records"}`;
+ $("#media-summary").textContent = downloaded
+ ? `${downloaded} downloaded ${downloaded === 1 ? "video" : "videos"}`
+ : "read-only evidence";
+
+ elements.cards.replaceChildren();
+ if (items.length) {
+ items.forEach((item, index) => {
+ const card = renderCard(item, index);
+ if (card) {
+ card.classList.add("card-enter");
+ elements.cards.append(card);
+ }
+ });
+ }
+ renderTable(items);
+ renderMarkdown(elements.output, run.report || run.finalSocaiOutput || "socai completed without a report.");
+ revealReport(elements.output);
+ elements.result.classList.remove("hidden");
+}
+
+function resetLiveWorkspace() {
+ elements.resultView.classList.remove("has-live-evidence");
+ elements.resultView.classList.add("is-running");
+ elements.result.classList.remove("hidden");
+ elements.evidenceHeading.classList.remove("hidden");
+ elements.evidenceTable.classList.add("hidden");
+ elements.reportSection.classList.add("hidden");
+ elements.cards.classList.remove("hidden");
+ elements.cards.replaceChildren(element("div", "waiting-evidence", "Captured posts will appear here as soon as socai finds them."));
+ $("#result-summary").textContent = "Waiting for the first post";
+ $("#media-summary").textContent = "live evidence stream";
+ elements.output.replaceChildren();
+}
+
+function showLiveEvidence(items) {
+ const visible = Array.isArray(items) ? items.filter(isRecord).slice(0, 4) : [];
+ if (!visible.length) return;
+ showActivity(
+ "socai is researching the captured evidence",
+ `${visible.length} previewable ${visible.length === 1 ? "post" : "posts"} captured. Research continues.`,
+ );
+ elements.resultView.classList.add("has-live-evidence");
+ elements.result.classList.remove("hidden");
+ elements.evidenceHeading.classList.remove("hidden");
+ elements.cards.classList.remove("hidden");
+ elements.evidenceTable.classList.add("hidden");
+ elements.reportSection.classList.add("hidden");
+ renderLiveCards(visible);
+ const count = elements.cards.childElementCount;
+ $("#result-summary").textContent = `${count} captured so far`;
+ $("#media-summary").textContent = "live evidence stream";
+}
+
+function renderLiveCards(items) {
+ const current = new Map(
+ [...elements.cards.children].map((card) => [card.dataset.evidenceKey, card]),
+ );
+ const wanted = new Set();
+ items.forEach((item, index) => {
+ const key = evidenceKey(item, index);
+ const fingerprint = JSON.stringify(item);
+ wanted.add(key);
+ const existing = current.get(key);
+ if (existing?.dataset.fingerprint === fingerprint) return;
+ const card = renderCard(item, index);
+ if (!card) return;
+ card.dataset.evidenceKey = key;
+ card.dataset.fingerprint = fingerprint;
+ card.classList.add(existing ? "card-update" : "card-enter");
+ if (existing) existing.replaceWith(card);
+ else elements.cards.append(card);
+ });
+ for (const [key, card] of current) {
+ if (!wanted.has(key)) card.remove();
+ }
+}
+
+function evidenceKey(item, index) {
+ return String(item.shortcode || item.video_id || item.id || item.url || item.web_url || item.share_url || `item-${index}`);
+}
+
+function renderCard(item, index) {
+ const card = element("article", "card");
+ const frame = element("div", "media-frame");
+ const videoUrl = videoSource(item);
+ const downloaded = Boolean(localVideoSource(item));
+ const posterUrl = posterSource(item);
+ if (videoUrl) {
+ const video = document.createElement("video");
+ video.src = videoUrl;
+ if (posterUrl) video.poster = posterUrl;
+ video.controls = true;
+ video.preload = "metadata";
+ video.playsInline = true;
+ video.addEventListener("error", () => renderImagePreview(frame, item), { once: true });
+ frame.append(video, element("span", "media-badge", downloaded ? "downloaded video" : "video preview"));
+ } else if (isDisplayUrl(posterUrl)) {
+ renderImagePreview(frame, item);
+ } else {
+ renderMediaFallback(frame, item);
+ }
+ card.append(frame);
+
+ const body = element("div", "card-body");
+ const title = firstString(item, ["title", "caption", "description", "text", "name"]) || `Result ${index + 1}`;
+ const author = authorName(item);
+ body.append(element("h4", "", title));
+ if (author) body.append(element("p", "author", author.startsWith("@") ? author : `@${author}`));
+ const stats = renderStats(item);
+ if (stats) body.append(stats);
+ const actions = element("div", "card-actions");
+ const inspect = element("button", "", "View details");
+ inspect.type = "button";
+ inspect.addEventListener("click", () => showDetail(item, title));
+ actions.append(inspect);
+ const sourceUrl = firstString(item, ["url", "web_url", "share_url", "canonical_url"]);
+ if (isHttpUrl(sourceUrl)) {
+ const link = element("a", "", "Open source ↗");
+ link.href = sourceUrl;
+ link.target = "_blank";
+ link.rel = "noreferrer";
+ actions.append(link);
+ }
+ body.append(actions);
+ card.append(body);
+ return card;
+}
+
+function renderImagePreview(frame, item) {
+ const sources = posterSources(item);
+ let cursor = 0;
+ const tryNext = () => {
+ const source = sources[cursor++];
+ if (!source) {
+ renderMediaFallback(frame, item);
+ return;
+ }
+ const image = document.createElement("img");
+ image.src = source;
+ image.alt = "";
+ image.loading = "lazy";
+ image.referrerPolicy = "no-referrer";
+ image.addEventListener("error", tryNext, { once: true });
+ frame.replaceChildren(image);
+ };
+ tryNext();
+}
+
+function renderMediaFallback(frame, item) {
+ const platform = capitalize(String(item.platform || "social"));
+ const fallback = element("div", "media-fallback");
+ fallback.append(
+ element("span", "media-fallback-platform", platform),
+ element("strong", "", "Evidence captured"),
+ element("small", "", "Preview unavailable — post details are still preserved."),
+ );
+ frame.replaceChildren(fallback);
+}
+
+function posterSources(item) {
+ const media = Array.isArray(item?.media) ? item.media : [];
+ return [...new Set([
+ firstString(item?.video, ["poster_browser_url"]),
+ firstString(item?.video, ["poster_url"]),
+ firstString(item, ["cover_url", "cover", "thumbnail_url", "thumbnail", "image_url", "image"]),
+ ...media.flatMap((entry) => [entry?.poster_url, entry?.browser_url, entry?.url]),
+ ].filter(isDisplayUrl))];
+}
+
+function revealReport(container) {
+ const blocks = [...container.children];
+ blocks.forEach((block) => block.classList.add("report-reveal"));
+ requestAnimationFrame(() => {
+ blocks.forEach((block, index) => {
+ setTimeout(() => block.classList.add("is-visible"), Math.min(index * 42, 840));
+ });
+ });
+ if (!blocks.length) {
+ container.classList.add("is-visible");
+ }
+}
+
+function renderStats(item) {
+ const definitions = [
+ ["views", ["views", "view_count", "plays"]],
+ ["likes", ["likes", "like_count"]],
+ ["comments", ["comments_count", "comment_count"]],
+ ["shares", ["shares", "share_count"]],
+ ];
+ const values = definitions.map(([label, keys]) => [label, firstValue(item, keys)]).filter(([, value]) => value !== "");
+ if (!values.length) return null;
+ const container = element("div", "stats");
+ values.forEach(([label, value]) => container.append(element("span", "", `${compactNumber(value)} ${label}`)));
+ return container;
+}
+
+function renderTable(items) {
+ const columns = [
+ ["Platform", (item) => item.platform || "—"],
+ ["Author", authorName],
+ ["Title / caption", (item) => firstString(item, ["title", "caption", "description", "text", "name"]) || "—"],
+ ["Published", (item) => firstString(item, ["created_at", "published_at", "date"]) || "—"],
+ ["Views", (item) => firstValue(item, ["views", "view_count", "plays"]) || "—"],
+ ["Likes", (item) => firstValue(item, ["likes", "like_count"]) || "—"],
+ ["Comments", (item) => firstValue(item, ["comments_count", "comment_count"]) || "—"],
+ ["Shares", (item) => firstValue(item, ["shares", "share_count"]) || "—"],
+ ["Duration", (item) => item.duration_seconds === undefined ? "—" : `${item.duration_seconds}s`],
+ ["Media", (item) => localVideoSource(item) ? "Downloaded" : videoSource(item) || posterSource(item) ? "Preview" : "—"],
+ ];
+ const headRow = document.createElement("tr");
+ columns.forEach(([label]) => headRow.append(element("th", "", label)));
+ $("#table-head").replaceChildren(headRow);
+ const rows = items.map((item) => {
+ const row = document.createElement("tr");
+ columns.forEach(([, read]) => row.append(element("td", "", String(read(item)))));
+ return row;
+ });
+ $("#table-body").replaceChildren(...rows);
+}
+
+function showDetail(item, title) {
+ const media = element("div", "detail-media");
+ const videoUrl = videoSource(item);
+ const posterUrl = posterSource(item);
+ if (videoUrl) {
+ const video = document.createElement("video");
+ video.src = videoUrl;
+ if (posterUrl) video.poster = posterUrl;
+ video.controls = true;
+ video.autoplay = false;
+ video.playsInline = true;
+ media.append(video);
+ } else if (isDisplayUrl(posterUrl)) {
+ const image = document.createElement("img");
+ image.src = posterUrl;
+ image.alt = "";
+ image.referrerPolicy = "no-referrer";
+ media.append(image);
+ }
+ const copy = element("div", "detail-copy");
+ copy.append(element("h3", "", title));
+ const description = firstString(item, ["description", "caption", "text", "title"]);
+ if (description) copy.append(element("p", "", description));
+ const comments = item.top_comments || item.comments || item.socai_detail?.entity?.top_comments;
+ if (Array.isArray(comments) && comments.length) {
+ copy.append(element("p", "eyebrow", `TOP COMMENTS · ${comments.length}`));
+ for (const comment of comments) copy.append(element("p", "", `${authorName(comment) || "Comment"}: ${comment.text || ""}`));
+ }
+ const sourceUrl = firstString(item, ["url", "web_url", "share_url", "canonical_url"]);
+ if (isHttpUrl(sourceUrl)) {
+ const link = element("a", "detail-source", "Open original post ↗");
+ link.href = sourceUrl;
+ link.target = "_blank";
+ link.rel = "noreferrer";
+ copy.append(link);
+ }
+ const content = element("div", "detail-content");
+ content.append(media, copy);
+ elements.detail.replaceChildren(content);
+ elements.dialog.showModal();
+}
+
+function videoSource(item) {
+ return localVideoSource(item) || remoteVideoSource(item);
+}
+
+function localVideoSource(item) {
+ const candidate = firstString(item?.video, ["browser_url", "local_url"]) ||
+ firstString(item, ["video_browser_url", "browser_url"]);
+ return candidate.startsWith("/media/") ? candidate : "";
+}
+
+function remoteVideoSource(item) {
+ const direct = firstString(item?.video, ["url", "play_url", "play_addr", "download_url"]) ||
+ firstString(item, ["video_url", "play_url", "play_addr"]);
+ if (isDisplayUrl(direct)) return direct;
+ const media = Array.isArray(item?.media) ? item.media.find((entry) => entry?.type === "video") : null;
+ const candidate = firstString(media, ["browser_url", "url"]);
+ return isDisplayUrl(candidate) ? candidate : "";
+}
+
+function posterSource(item) {
+ return posterSources(item)[0] || "";
+}
+
+function emptyResultMessage(run) {
+ if (run.result?.status === "empty" || run.result?.search_state?.empty) {
+ return `socai completed successfully. ${capitalize(run.platform)} returned no matches for “${run.query}”.`;
+ }
+ if (run.result?.ok === false) return `socai returned ${run.result.status || run.result.reason || "an unavailable state"}. The complete output is below.`;
+ return "socai completed successfully, but returned no displayable records.";
+}
+
+function findItems(value) {
+ if (Array.isArray(value)) return value.filter(isRecord);
+ if (!isRecord(value)) return [];
+ for (const key of ["items", "results", "cards", "videos", "posts", "notes", "data"]) {
+ if (Array.isArray(value[key])) return value[key].filter(isRecord).map((item) => isRecord(item.entity) ? { ...item, ...item.entity } : item);
+ if (isRecord(value[key])) {
+ const nested = findItems(value[key]);
+ if (nested.length) return nested;
+ }
+ }
+ return [];
+}
+
+async function streamApi(url, body, onEvent, signal) {
+ const response = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(body),
+ signal,
+ });
+ if (!response.ok) return parseApiError(response);
+ if (!response.body) throw new Error("Streaming response is unavailable in this browser.");
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ let run;
+ while (true) {
+ const { value, done } = await reader.read();
+ buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
+ const lines = buffer.split("\n");
+ buffer = done ? "" : lines.pop();
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ const event = JSON.parse(line);
+ onEvent(event);
+ if (event.stage === "result") run = event.run;
+ }
+ if (done) break;
+ }
+ if (!run) throw new Error("socai stream ended before returning a result.");
+ return run;
+}
+
+async function api(url, options = {}) {
+ const response = await fetch(url, {
+ ...options,
+ headers: {
+ "Content-Type": "application/json",
+ ...(options.headers || {}),
+ },
+ });
+ if (!response.ok) return parseApiError(response);
+ return response.json();
+}
+
+async function parseApiError(response) {
+ const value = await response.json().catch(() => ({}));
+ const error = new Error(value.error?.message || `HTTP ${response.status}`);
+ error.code = value.error?.code;
+ error.details = value.error?.details;
+ throw error;
+}
+
+function element(tag, className = "", text = "") {
+ const node = document.createElement(tag);
+ if (className) node.className = className;
+ if (text !== "") node.textContent = text;
+ return node;
+}
+
+function renderMarkdown(container, markdown) {
+ container.replaceChildren();
+ const lines = String(markdown || "").replace(/\r/g, "").split("\n");
+ let list;
+ let listKind;
+ for (let index = 0; index < lines.length; index += 1) {
+ const rawLine = lines[index];
+ const line = rawLine.trim();
+ if (!line) {
+ list = undefined;
+ listKind = undefined;
+ continue;
+ }
+ if (line.startsWith("|") && /^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/.test(lines[index + 1]?.trim() || "")) {
+ list = undefined;
+ listKind = undefined;
+ const table = document.createElement("table");
+ const thead = document.createElement("thead");
+ const tbody = document.createElement("tbody");
+ thead.append(markdownTableRow(line, "th"));
+ index += 2;
+ while (index < lines.length && lines[index].trim().startsWith("|")) {
+ tbody.append(markdownTableRow(lines[index].trim(), "td"));
+ index += 1;
+ }
+ index -= 1;
+ table.append(thead, tbody);
+ const scroll = element("div", "table-scroll report-table");
+ scroll.append(table);
+ container.append(scroll);
+ continue;
+ }
+ const heading = line.match(/^(#{1,4})\s+(.+)$/);
+ if (heading) {
+ list = undefined;
+ listKind = undefined;
+ const level = Math.min(heading[1].length + 1, 5);
+ const node = element(`h${level}`);
+ appendMarkdownInline(node, heading[2]);
+ container.append(node);
+ continue;
+ }
+ const bullet = line.match(/^([-*]|\d+\.)\s+(.+)$/);
+ if (bullet) {
+ const kind = /\d/.test(bullet[1]) ? "ol" : "ul";
+ if (!list || listKind !== kind) {
+ list = document.createElement(kind);
+ listKind = kind;
+ container.append(list);
+ }
+ const item = element("li");
+ appendMarkdownInline(item, bullet[2]);
+ list.append(item);
+ continue;
+ }
+ list = undefined;
+ listKind = undefined;
+ const paragraph = element("p");
+ appendMarkdownInline(paragraph, line);
+ container.append(paragraph);
+ }
+}
+
+function markdownTableRow(line, cellTag) {
+ const row = document.createElement("tr");
+ const cells = line.replace(/^\||\|$/g, "").split("|");
+ for (const value of cells) {
+ const cell = document.createElement(cellTag);
+ appendMarkdownInline(cell, value.trim());
+ row.append(cell);
+ }
+ return row;
+}
+
+function appendMarkdownInline(container, value) {
+ const pattern = /(\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)|\*\*([^*]+)\*\*|`([^`]+)`)/g;
+ let cursor = 0;
+ for (const match of value.matchAll(pattern)) {
+ container.append(document.createTextNode(value.slice(cursor, match.index)));
+ if (match[2] && match[3]) {
+ const link = element("a", "", match[2]);
+ link.href = match[3];
+ link.target = "_blank";
+ link.rel = "noreferrer";
+ container.append(link);
+ } else if (match[4]) {
+ container.append(element("strong", "", match[4]));
+ } else {
+ container.append(element("code", "", match[5]));
+ }
+ cursor = match.index + match[0].length;
+ }
+ container.append(document.createTextNode(value.slice(cursor)));
+}
+
+function firstString(object, keys) {
+ for (const key of keys) {
+ const value = object?.[key];
+ if (typeof value === "string" && value.trim()) return value.trim();
+ }
+ return "";
+}
+
+function firstValue(object, keys) {
+ for (const key of keys) {
+ const value = object?.[key] ?? object?.engagement?.[key];
+ if ((typeof value === "string" && value.trim()) || typeof value === "number") return String(value);
+ }
+ return "";
+}
+
+function authorName(item) {
+ const value = item?.author_name ?? item?.author ?? item?.username ?? item?.nickname ?? item?.handle ?? item?.author_id;
+ if (typeof value === "string") return value;
+ if (isRecord(value)) return firstString(value, ["username", "name", "nickname", "id"]);
+ return "";
+}
+
+function compactNumber(value) {
+ const number = Number(String(value).replaceAll(",", ""));
+ if (!Number.isFinite(number)) return value;
+ return Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(number);
+}
+
+function isRecord(value) { return value && typeof value === "object" && !Array.isArray(value); }
+function isHttpUrl(value) { return typeof value === "string" && /^https?:\/\//i.test(value); }
+function isDisplayUrl(value) { return typeof value === "string" && (/^https?:\/\//i.test(value) || value.startsWith("/media/")); }
+function capitalize(value = "") { return value.charAt(0).toUpperCase() + value.slice(1); }
+function formatDuration(value) { return value < 1000 ? `${value} ms` : `${(value / 1000).toFixed(1)} s`; }
diff --git a/public/index.html b/public/index.html
new file mode 100644
index 0000000..4558dc0
--- /dev/null
+++ b/public/index.html
@@ -0,0 +1,102 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="color-scheme" content="light" />
+ <title>Jev × socai · social research</title>
+ <link rel="stylesheet" href="/styles.css" />
+ </head>
+ <body>
+ <div class="app-shell">
+ <header class="topbar">
+ <a class="brand" href="/" aria-label="Jev Social home">
+ <span class="brand-mark"><i></i></span>
+ <strong>JEV <b>×</b> SOCAI</strong>
+ </a>
+ <nav class="top-actions" aria-label="Project links">
+ <a href="https://socai.io/" target="_blank" rel="noreferrer">Visit socai.io ↗</a>
+ <a class="star-link" href="https://github.com/socai-io/socai" target="_blank" rel="noreferrer">Star on GitHub ★</a>
+ </nav>
+ </header>
+
+ <section id="error" class="error-box hidden" role="alert"></section>
+
+ <main class="app-main">
+ <section id="search-view" class="view search-view">
+ <div class="search-panel">
+ <p class="hero-lockup">JEV <span>×</span> SOCAI</p>
+ <h1>Social research<br /><em>at browser speed.</em></h1>
+ <p class="intro">Describe one Instagram or TikTok research goal. Jev routes it; the local socai CLI searches, reads, downloads, and returns the evidence.</p>
+
+ <form id="search-form" class="composer">
+ <textarea id="query" name="query" required autocomplete="off" rows="3" placeholder="Find emerging AI creators and their most engaging posts"></textarea>
+ <div class="composer-controls">
+ <label class="field-group">
+ <span>PLATFORM</span>
+ <select id="platform" name="platform">
+ <option value="auto">Jev · auto</option>
+ <option value="instagram">Instagram</option>
+ <option value="tiktok">TikTok</option>
+ </select>
+ </label>
+ <div class="readiness" aria-live="polite">
+ <span><i id="jev-dot"></i><b id="jev-status">Jev checking</b></span>
+ <span><i id="socai-dot"></i><b id="socai-status">socai checking</b></span>
+ </div>
+ <button class="button primary" type="submit">Run social research <span>↗</span></button>
+ </div>
+ </form>
+
+ <div class="pipeline" aria-label="Execution pipeline">
+ <span>one goal</span><i>→</i><span>Jev route</span><i>→</i><span>socai CLI</span><i>→</i><span>downloaded evidence</span>
+ </div>
+ </div>
+ </section>
+
+ <section id="result-view" class="view result-view hidden" aria-label="Social result workspace">
+ <div class="result-toolbar">
+ <button id="back-to-search" class="back-button" type="button">← New search</button>
+ <div class="result-heading">
+ <p class="eyebrow">SOCIAL RESULTS</p>
+ <h2 id="result-title">Research in progress</h2>
+ </div>
+ <div class="time-readout"><small>ELAPSED</small><strong id="elapsed-time">0.0 s</strong></div>
+ </div>
+
+ <section id="activity" class="activity hidden" aria-live="polite">
+ <div class="gradient-scan" aria-hidden="true"></div>
+ <div class="activity-card">
+ <div class="activity-head"><span class="spinner"></span><strong id="activity-title">Starting research</strong></div>
+ <p id="activity-message" class="activity-message">Preparing the local socai workflow…</p>
+ </div>
+ </section>
+
+ <section id="result" class="result-canvas hidden">
+ <div id="evidence-heading" class="canvas-head">
+ <div><p class="eyebrow">CAPTURED POSTS</p><h3 id="result-summary">Results</h3></div>
+ <span id="media-summary">read-only evidence</span>
+ </div>
+ <div id="cards" class="cards"></div>
+
+ <section id="evidence-table" class="data-section">
+ <div class="section-head"><p class="eyebrow">COMPLETE TABLE</p><span>All returned records</span></div>
+ <div class="table-scroll"><table><thead id="table-head"></thead><tbody id="table-body"></tbody></table></div>
+ </section>
+
+ <section id="research-report-section" class="report-section">
+ <div class="section-head"><p class="eyebrow">SOCAI RESEARCH REPORT</p><span>Agent-written from captured evidence</span></div>
+ <article id="socai-output" class="research-report"></article>
+ </section>
+ </section>
+ </section>
+ </main>
+ </div>
+
+ <dialog id="detail-dialog" class="detail-dialog">
+ <button id="close-detail" class="dialog-close" type="button" aria-label="Close">×</button>
+ <div id="detail-content"></div>
+ </dialog>
+ <script type="module" src="/app.js"></script>
+ </body>
+</html>
diff --git a/public/styles.css b/public/styles.css
new file mode 100644
index 0000000..6c5c85f
--- /dev/null
+++ b/public/styles.css
@@ -0,0 +1,188 @@
+:root {
+ --ink: #09090b;
+ --muted: #686a73;
+ --line: #cfd5dc;
+ --paper: #f8fbff;
+ --ice: #dff4ff;
+ --pink: #ff2ea6;
+ --pink-soft: #ffd3ec;
+ --green: #17a66a;
+ --mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
+ --sans: Inter, "Helvetica Neue", Arial, sans-serif;
+}
+
+* { box-sizing: border-box; }
+html, body { height: 100%; }
+body { margin: 0; overflow: hidden; color: var(--ink); background: var(--paper); font-family: var(--sans); -webkit-font-smoothing: antialiased; }
+button, input, select, textarea { color: inherit; font: inherit; }
+button { cursor: pointer; }
+.hidden { display: none !important; }
+
+.app-shell { height: 100vh; display: flex; flex-direction: column; }
+.topbar { position: relative; z-index: 20; flex: 0 0 64px; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 0 24px; border-bottom: 1px solid var(--ink); background: rgba(248, 251, 255, .94); backdrop-filter: blur(14px); }
+.brand { display: inline-flex; align-items: center; gap: 12px; color: inherit; text-decoration: none; }
+.brand strong { font: 800 18px/1 var(--mono); letter-spacing: -.055em; }
+.brand b { color: var(--pink); }
+.brand-mark { position: relative; width: 24px; height: 24px; border: 2px solid currentColor; }
+.brand-mark i { position: absolute; right: 3px; bottom: 3px; width: 9px; height: 9px; background: var(--pink); }
+.top-actions { display: flex; align-items: center; gap: 8px; }
+.top-actions a { display: inline-flex; align-items: center; min-height: 34px; padding: 0 13px; border: 1px solid var(--ink); color: var(--ink); background: #fff; font: 700 10px/1 var(--mono); text-decoration: none; text-transform: uppercase; }
+.top-actions a:hover { transform: translate(-1px, -1px); box-shadow: 2px 2px 0 var(--ink); }
+.top-actions .star-link { color: #fff; background: var(--ink); }
+
+.app-main { flex: 1; min-height: 0; position: relative; }
+.view { height: 100%; }
+.search-view { position: relative; display: grid; place-items: center; padding: 34px 24px; overflow: auto; background: linear-gradient(180deg, var(--ice), var(--paper) 64%); }
+.search-view::before, .search-view::after { content: ""; position: absolute; pointer-events: none; filter: contrast(140%); opacity: .7; }
+.search-view::before { inset: 0 0 auto; height: 210px; background: radial-gradient(ellipse at 12% -20%, var(--pink) 0 19%, transparent 48%), radial-gradient(ellipse at 88% -40%, #f3a 0 16%, transparent 44%); mask-image: repeating-linear-gradient(0deg, #000 0 2px, transparent 2px 5px); }
+.search-view::after { left: 8%; bottom: 9%; width: 90px; height: 90px; border: 2px solid var(--ink); transform: rotate(12deg); box-shadow: 12px 12px 0 var(--pink); }
+.search-panel { position: relative; z-index: 1; width: min(820px, 100%); }
+.hero-lockup { margin: 0; font: 900 clamp(22px, 3vw, 36px)/1 var(--mono); letter-spacing: -.08em; }
+.hero-lockup span { color: var(--pink); }
+.eyebrow { margin: 0; color: var(--muted); font: 700 9px/1.2 var(--mono); letter-spacing: .14em; }
+h1 { margin: 17px 0 0; font-size: clamp(54px, 8.4vw, 102px); font-weight: 790; line-height: .88; letter-spacing: -.075em; }
+h1 em { color: transparent; font-style: normal; -webkit-text-stroke: 1.5px var(--ink); }
+.intro { max-width: 650px; margin: 27px 0 24px; color: #3f434b; font-size: 15px; line-height: 1.65; }
+
+.composer { border: 1.5px solid var(--ink); background: #fff; box-shadow: 7px 7px 0 rgba(255, 46, 166, .72); }
+.composer textarea { display: block; width: 100%; min-height: 112px; resize: vertical; padding: 18px; border: 0; outline: 0; background: #fff; font-size: 16px; line-height: 1.55; }
+.composer textarea::placeholder { color: #9ba0aa; }
+.composer-controls { min-height: 64px; display: flex; align-items: end; gap: 11px; padding: 10px; border-top: 1px solid var(--line); background: #f3f8fc; }
+.field-group { display: grid; gap: 5px; }
+.field-group > span { font: 700 8px var(--mono); letter-spacing: .12em; }
+.field-group select { height: 36px; border: 1px solid var(--ink); outline: 0; background: #fff; padding: 0 30px 0 10px; font: 10px var(--mono); }
+.readiness { display: flex; align-items: center; align-self: center; gap: 12px; color: var(--muted); font: 9px/1 var(--mono); }
+.readiness span { display: inline-flex; align-items: center; gap: 5px; }
+.readiness i { width: 7px; height: 7px; border: 1px solid var(--ink); border-radius: 50%; }
+.readiness i.ready { border-color: var(--green); background: var(--green); }
+.readiness b { font-weight: 500; }
+.button { min-height: 38px; border: 1px solid var(--ink); padding: 0 16px; background: #fff; font-size: 12px; font-weight: 750; }
+.button.primary { margin-left: auto; color: #fff; background: var(--ink); }
+.button.primary:hover { color: var(--ink); background: var(--pink); }
+.button:disabled { opacity: .55; cursor: wait; }
+.pipeline { display: flex; align-items: center; justify-content: center; gap: 10px; margin-top: 21px; color: #6f7480; font: 8px var(--mono); letter-spacing: .08em; text-transform: uppercase; }
+.pipeline i { color: var(--pink); font-style: normal; }
+
+.error-box { position: fixed; z-index: 50; top: 76px; right: 14px; width: min(560px, calc(100% - 28px)); padding: 14px 16px; border: 1px solid var(--ink); background: #fff; box-shadow: 6px 6px 0 var(--pink); white-space: pre-wrap; font: 11px/1.6 var(--mono); }
+.result-view { min-height: 0; display: flex; flex-direction: column; background: #fff; }
+.result-toolbar { flex: 0 0 76px; display: grid; grid-template-columns: 180px 1fr 180px; align-items: center; gap: 20px; padding: 0 22px; border-bottom: 1px solid var(--ink); background: var(--ice); }
+.result-heading { min-width: 0; text-align: center; }
+.result-heading h2 { margin: 5px 0 0; overflow: hidden; font-size: 15px; font-weight: 700; text-overflow: ellipsis; white-space: nowrap; }
+.back-button { justify-self: start; border: 0; padding: 8px 0; background: transparent; font: 700 11px var(--mono); }
+.time-readout { justify-self: end; display: grid; text-align: right; }
+.time-readout small { color: var(--muted); font: 8px var(--mono); letter-spacing: .13em; }
+.time-readout strong { margin-top: 2px; font: 800 20px var(--mono); letter-spacing: -.06em; }
+
+.activity { position: relative; flex: 1; min-height: 0; display: grid; place-items: center; overflow: hidden; background: #f5fbff; }
+.gradient-scan { position: absolute; inset: -100% 0 auto; height: 100%; background: linear-gradient(180deg, transparent 0, rgba(222, 246, 255, .92) 26%, rgba(255, 46, 166, .32) 65%, transparent 100%); animation: scan-down 2.2s cubic-bezier(.45,0,.2,1) infinite; }
+.gradient-scan::after { content: ""; position: absolute; inset: 0; background: repeating-linear-gradient(0deg, transparent 0 4px, rgba(255,255,255,.62) 4px 7px); }
+@keyframes scan-down { from { transform: translateY(0); } to { transform: translateY(200%); } }
+.activity-card { position: relative; z-index: 2; width: min(520px, calc(100% - 32px)); padding: 24px; border: 1px solid var(--ink); background: rgba(255,255,255,.92); box-shadow: 8px 8px 0 var(--pink); }
+.activity-head { display: flex; align-items: center; gap: 12px; font-size: 14px; }
+.activity-card > p { margin: 8px 0 0 28px; color: var(--muted); font-size: 12px; line-height: 1.5; }
+.spinner { width: 16px; height: 16px; border: 2px solid #b8c2cb; border-top-color: var(--pink); border-radius: 50%; animation: spin .75s linear infinite; }
+@keyframes spin { to { transform: rotate(360deg); } }
+.activity-message.message-swap { animation: message-swap .34s ease both; }
+@keyframes message-swap { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
+
+.result-view.is-running .activity { flex: 0 0 108px; display: block; min-height: 108px; padding: 15px 24px; border-bottom: 1px solid var(--ink); }
+.result-view.is-running .activity-card { width: 100%; padding: 14px 18px; box-shadow: 4px 4px 0 var(--pink); }
+.result-view.is-running .activity-card > p { margin-top: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+
+.result-canvas { flex: 1; min-height: 0; overflow-y: auto; padding: 24px; background: #fff; }
+.canvas-head, .section-head { display: flex; align-items: end; justify-content: space-between; gap: 20px; }
+.canvas-head h3 { margin: 5px 0 0; font-size: 22px; letter-spacing: -.035em; }
+.canvas-head > span, .section-head > span { color: var(--muted); font: 8px var(--mono); letter-spacing: .08em; text-transform: uppercase; }
+.cards { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; margin-top: 16px; }
+.waiting-evidence { grid-column: 1 / -1; min-height: 120px; display: grid; place-items: center; border: 1px dashed var(--line); color: var(--muted); background: linear-gradient(180deg, var(--paper), #fff); font: 10px var(--mono); animation: waiting-pulse 1.8s ease-in-out infinite; }
+@keyframes waiting-pulse { 50% { color: var(--ink); border-color: var(--pink); } }
+.card { min-width: 0; display: flex; flex-direction: column; border: 1px solid var(--line); background: #fff; transition: transform .18s, box-shadow .18s; }
+.card:hover { transform: translateY(-3px); box-shadow: 5px 5px 0 var(--pink-soft); }
+.card-enter { animation: card-enter .5s cubic-bezier(.2,.72,.25,1) both; }
+.card-enter:nth-child(2) { animation-delay: 70ms; }
+.card-enter:nth-child(3) { animation-delay: 140ms; }
+.card-enter:nth-child(4) { animation-delay: 210ms; }
+.card-update { animation: card-update .42s ease both; }
+@keyframes card-enter { from { opacity: 0; transform: translateY(24px) scale(.975); } to { opacity: 1; transform: translateY(0) scale(1); } }
+@keyframes card-update { 0% { opacity: .45; transform: translateY(8px); } 55% { box-shadow: 0 0 0 3px var(--pink-soft); } 100% { opacity: 1; transform: translateY(0); } }
+.media-frame { position: relative; width: 100%; aspect-ratio: 9/12; overflow: hidden; background: #edf1f5; }
+.media-frame img, .media-frame video { width: 100%; height: 100%; display: block; object-fit: cover; }
+.media-frame video { background: #000; }
+.media-frame .placeholder { width: 100%; height: 100%; background: repeating-linear-gradient(135deg, var(--ice), var(--ice) 10px, #fff 10px, #fff 12px); }
+.media-fallback { width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: end; gap: 8px; padding: 20px; color: #fff; background: radial-gradient(circle at 82% 18%, var(--pink) 0 8%, transparent 9%), linear-gradient(145deg, #16181e, #33404b); }
+.media-fallback-platform { align-self: start; padding: 5px 7px; border: 1px solid rgba(255,255,255,.7); font: 700 8px var(--mono); letter-spacing: .1em; text-transform: uppercase; }
+.media-fallback strong { font-size: 18px; letter-spacing: -.03em; }
+.media-fallback small { max-width: 190px; color: #dce6ee; font: 9px/1.45 var(--mono); }
+.media-badge { position: absolute; top: 8px; left: 8px; padding: 5px 7px; color: #fff; background: var(--ink); font: 700 8px var(--mono); text-transform: uppercase; }
+.card-body { display: grid; gap: 9px; padding: 12px; }
+.card h4 { margin: 0; display: -webkit-box; overflow: hidden; font-size: 13px; line-height: 1.4; -webkit-line-clamp: 3; -webkit-box-orient: vertical; }
+.author { margin: 0; color: var(--muted); font: 10px var(--mono); }
+.stats { display: flex; flex-wrap: wrap; gap: 9px; color: #42464c; font: 9px var(--mono); }
+.card-actions { display: flex; gap: 12px; align-items: center; }
+.card-actions button, .card-actions a { border: 0; padding: 0; color: var(--ink); background: transparent; font: 700 9px var(--mono); text-decoration: underline; text-underline-offset: 3px; }
+.empty { grid-column: 1 / -1; padding: 34px; border: 1px solid var(--line); color: var(--muted); background: var(--paper); }
+
+.data-section { margin-top: 30px; }
+.table-scroll { margin-top: 11px; overflow: auto; border: 1px solid var(--line); }
+table { width: 100%; min-width: 900px; border-collapse: collapse; font-size: 11px; }
+th, td { max-width: 330px; padding: 10px 11px; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; overflow-wrap: anywhere; }
+th { position: sticky; top: 0; color: #fff; background: var(--ink); font: 700 8px var(--mono); letter-spacing: .08em; text-transform: uppercase; }
+td { line-height: 1.45; }
+tr:last-child td { border-bottom: 0; }
+.report-section { margin-top: 30px; }
+.research-report { padding: clamp(22px, 4vw, 42px); border: 1px solid var(--line); background: linear-gradient(180deg, #f7fcff 0%, #fff 34%); box-shadow: 0 14px 50px rgba(43, 69, 91, .08); }
+.research-report h2, .research-report h3, .research-report h4, .research-report h5 { margin: 1.3em 0 .55em; letter-spacing: -.025em; }
+.research-report h2:first-child, .research-report h3:first-child { margin-top: 0; }
+.research-report p, .research-report li { color: #313843; font: 14px/1.75 var(--sans); }
+.research-report ul { margin: .5em 0 1.25em; padding-left: 1.4em; }
+.research-report ol { margin: .5em 0 1.25em; padding-left: 1.4em; }
+.research-report a { color: #c90075; text-decoration-thickness: 1px; text-underline-offset: 3px; }
+.research-report code { padding: 2px 5px; background: var(--ice); font: 11px/1.5 var(--mono); }
+.report-reveal { opacity: 0; transform: translateY(10px); filter: blur(2px); transition: opacity .32s ease, transform .38s cubic-bezier(.2,.7,.2,1), filter .32s ease; }
+.report-reveal.is-visible { opacity: 1; transform: translateY(0); filter: blur(0); }
+.report-table { margin: 14px 0 24px; border: 1px solid var(--line); }
+.report-table table { width: 100%; border-collapse: collapse; min-width: 760px; }
+.report-table th, .report-table td { padding: 11px 12px; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; font-size: 12px; line-height: 1.55; }
+.report-table th { background: var(--ice); font: 800 10px/1.4 var(--mono); text-transform: uppercase; }
+.report-table tr:last-child td { border-bottom: 0; }
+.report-table th:last-child, .report-table td:last-child { border-right: 0; }
+.detail-source { display: inline-flex; margin-top: 14px; color: var(--ink); font: 700 11px var(--mono); }
+
+.detail-dialog { width: min(900px, calc(100% - 28px)); max-height: calc(100vh - 28px); padding: 0; border: 1px solid var(--ink); background: #fff; box-shadow: 10px 10px 0 var(--pink); }
+.detail-dialog::backdrop { background: rgba(8, 9, 12, .58); backdrop-filter: blur(3px); }
+.dialog-close { position: sticky; z-index: 3; top: 12px; float: right; width: 34px; height: 34px; margin: 12px; border: 1px solid var(--ink); background: #fff; font-size: 24px; line-height: 1; }
+.detail-content { display: grid; grid-template-columns: minmax(260px, .8fr) 1fr; clear: both; }
+.detail-content .detail-media { min-height: 480px; background: #000; }
+.detail-content .detail-media video, .detail-content .detail-media img { width: 100%; height: 100%; display: block; object-fit: contain; }
+.detail-copy { min-width: 0; padding: 24px; }
+.detail-copy h3 { margin: 0 0 8px; font-size: 25px; line-height: 1.15; letter-spacing: -.04em; }
+.detail-copy > p { color: #42464c; font-size: 13px; line-height: 1.65; white-space: pre-wrap; }
+.detail-copy pre { max-height: 340px; padding: 13px; overflow: auto; background: #111; color: #eee; font: 9px/1.55 var(--mono); white-space: pre-wrap; }
+
+@media (max-width: 1040px) { .cards { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
+@media (max-width: 760px) {
+ .topbar { padding: 0 13px; }
+ .brand strong { font-size: 14px; }
+ .top-actions a:first-child { display: none; }
+ .search-view { place-items: start center; padding: 42px 14px; }
+ h1 { font-size: 55px; }
+ .composer-controls { align-items: stretch; flex-wrap: wrap; }
+ .readiness { order: 3; width: 100%; }
+ .button.primary { flex: 1; }
+ .pipeline { flex-wrap: wrap; }
+ .result-toolbar { grid-template-columns: auto 1fr auto; padding: 0 13px; }
+ .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .result-canvas { padding: 16px; }
+ .detail-content { grid-template-columns: 1fr; }
+ .detail-content .detail-media { min-height: 360px; }
+}
+@media (max-width: 500px) {
+ .top-actions a { padding: 0 9px; font-size: 8px; }
+ .result-heading .eyebrow { display: none; }
+ .time-readout strong { font-size: 15px; }
+ .cards { grid-template-columns: 1fr; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .gradient-scan, .spinner, .activity-message.message-swap, .card-enter, .card-update, .waiting-evidence { animation: none; }
+ .report-reveal { opacity: 1; transform: none; filter: none; transition: none; }
+}
diff --git a/src/app.js b/src/app.js
new file mode 100644
index 0000000..df3c23f
--- /dev/null
+++ b/src/app.js
@@ -0,0 +1,379 @@
+import crypto from "node:crypto";
+import { classifySearch } from "./classifier.js";
+import { AppError } from "./errors.js";
+import { readConfig, resolveApiKey } from "./config.js";
+import { extractSearchQuery } from "./query.js";
+import { saveRun } from "./runs.js";
+import { runSocaiResearch, runSocaiSearch, runSocaiTikTokVideos } from "./socai.js";
+
+const DEMO_RESULT_LIMIT = 4;
+const SOCAI_EVENT_PREFIX = "@@SOCAI_EVENT@@";
+
+export async function runSearch(
+ { query, platform = "auto", limit = DEMO_RESULT_LIMIT },
+ { env = process.env, client, onEvent, signal } = {},
+) {
+ const normalizedQuery = query?.trim();
+ if (!normalizedQuery) {
+ throw new AppError("Search query cannot be empty.", { code: "EMPTY_QUERY" });
+ }
+ const config = await readConfig(env);
+ const apiKey = resolveApiKey(config, env);
+ if (!apiKey && !client) {
+ throw new AppError("Set OPENROUTER_API_KEY (or openrouter in the local .env) first.", {
+ code: "ONBOARDING_REQUIRED",
+ });
+ }
+
+ const startedAt = Date.now();
+ const runId = createRunId();
+ onEvent?.({ stage: "classifying", message: "Jev is choosing the social workflow…" });
+ const classification = await classifySearch({
+ goal: normalizedQuery,
+ requestedPlatform: platform,
+ apiKey,
+ model: env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",
+ client,
+ });
+ if (!classification.platform) {
+ throw new AppError("Jev classified this request as unsupported. Choose Instagram or TikTok and use a read-only search.", {
+ code: "UNSUPPORTED_TASK",
+ details: { classification },
+ });
+ }
+ if (typeof classification.confidence === "number" && classification.confidence < 0.35) {
+ throw new AppError("Jev confidence is too low to execute automatically. Select a platform explicitly.", {
+ code: "LOW_CLASSIFICATION_CONFIDENCE",
+ details: { classification },
+ });
+ }
+
+ const searchQuery = extractSearchQuery(normalizedQuery);
+
+ onEvent?.({
+ stage: "executing",
+ message: `Jev chose ${classification.platform}; running socai CLI with “${searchQuery}”…`,
+ classification,
+ });
+ const searchExecutions = [];
+ let execution;
+ let items = [];
+ let streamedItems = [];
+ const publishEvidence = (candidates, message) => {
+ const previous = JSON.stringify(streamedItems);
+ const prepared = (Array.isArray(candidates) ? candidates : [])
+ .filter(isRecord)
+ .map((item) => ({ ...item, platform: item.platform || classification.platform }))
+ .map(sanitizeEvidenceForStream);
+ streamedItems = selectPreviewableEvidence(
+ mergeEvidenceItems(streamedItems, prepared),
+ DEMO_RESULT_LIMIT,
+ );
+ if (!streamedItems.length || JSON.stringify(streamedItems) === previous) return;
+ onEvent?.({
+ stage: "evidence",
+ message: message || `Captured ${streamedItems.length} previewable ${streamedItems.length === 1 ? "post" : "posts"}.`,
+ items: streamedItems,
+ });
+ };
+ for (const candidate of buildSearchQueries(searchQuery, classification.platform)) {
+ if (searchExecutions.length) {
+ onEvent?.({ stage: "searching", message: `No posts yet; trying the related query “${candidate}”…` });
+ }
+ execution = await runSocaiSearch({
+ config,
+ env,
+ platform: classification.platform,
+ query: candidate,
+ limit,
+ onProgress: (message) => emitProgress(onEvent, "searching", message),
+ signal,
+ });
+ searchExecutions.push(execution);
+ items = extractItems(execution.data);
+ if (items.length) {
+ publishEvidence(items, `Captured ${items.length} search ${items.length === 1 ? "result" : "results"}; research is continuing.`);
+ break;
+ }
+ }
+
+ let videoExecution;
+ if (classification.platform === "tiktok") {
+ const locators = items.map(videoLocator).filter(Boolean);
+ if (locators.length) {
+ onEvent?.({
+ stage: "downloading",
+ message: `Opening ${locators.length} video${locators.length === 1 ? "" : "s"}, reading details, and downloading media…`,
+ });
+ videoExecution = await runSocaiTikTokVideos({
+ config,
+ env,
+ locators,
+ numComments: 4,
+ onProgress: (message) => emitProgress(onEvent, "downloading", message),
+ signal,
+ });
+ items = mergeTikTokItems(items, videoExecution.data);
+ publishEvidence(items, "Video details arrived; socai is continuing the evidence review.");
+ }
+ }
+
+ const result = videoExecution
+ ? { ...execution.data, items, video_details: videoExecution.data }
+ : {
+ ...execution.data,
+ query: searchQuery,
+ ...(searchExecutions.length > 1 ? { search_attempts: searchExecutions.map((item) => item.data) } : {}),
+ };
+
+ onEvent?.({
+ stage: "researching",
+ message: "socai is launching its research agent to compare evidence and write the report…",
+ });
+ const researchExecution = await runSocaiResearch({
+ config,
+ env,
+ platform: classification.platform,
+ task: buildResearchTask(normalizedQuery, classification.platform),
+ maxSteps: 4,
+ onProgress: (message) => {
+ const event = parseSocaiEvent(message);
+ if (event?.type === "evidence") {
+ publishEvidence(event.items, "New evidence captured; socai is comparing it now.");
+ return;
+ }
+ emitProgress(onEvent, "researching", message);
+ },
+ signal,
+ });
+ if (researchExecution.data?.ok === false) {
+ throw new AppError(researchExecution.data.error || "socai research did not complete.", {
+ code: "SOCAI_RESEARCH_FAILED",
+ status: 502,
+ details: { runId: researchExecution.data.run_id },
+ });
+ }
+ const evidenceItems = selectPreviewableEvidence(
+ mergeEvidenceItems(mergeEvidenceItems(items, streamedItems), researchExecution.data.evidence)
+ .map((item) => ({ ...item, platform: item.platform || classification.platform })),
+ DEMO_RESULT_LIMIT,
+ );
+
+ const run = {
+ id: runId,
+ createdAt: new Date().toISOString(),
+ request: normalizedQuery,
+ query: searchQuery,
+ requestedPlatform: platform,
+ platform: classification.platform,
+ classification,
+ command: researchExecution.command,
+ evidenceCommand: searchExecutions[0].command,
+ evidenceCommands: searchExecutions.map((item) => item.command),
+ socaiExitCode: execution.exitCode,
+ socaiElapsedMs: searchExecutions.reduce((total, item) => total + item.elapsedMs, 0) + (videoExecution?.elapsedMs || 0) + researchExecution.elapsedMs,
+ elapsedMs: Date.now() - startedAt,
+ result: { ...result, items: evidenceItems, research: researchExecution.data },
+ report: researchExecution.data.report,
+ socaiOutputs: [
+ ...searchExecutions.map((item, index) => ({ stage: `search ${index + 1}`, elapsedMs: item.elapsedMs, text: item.stdout })),
+ ...(videoExecution
+ ? [{ stage: "video details and download", elapsedMs: videoExecution.elapsedMs, text: videoExecution.stdout }]
+ : []),
+ { stage: "research report", elapsedMs: researchExecution.elapsedMs, text: researchExecution.stdout },
+ ],
+ finalSocaiOutput: researchExecution.data.report,
+ };
+ await saveRun(run, env);
+ onEvent?.({ stage: "complete", message: "Research report complete.", runId: run.id });
+ return run;
+}
+
+function buildResearchTask(request, platform) {
+ return [
+ `Research this goal on ${platform}: ${request}`,
+ "Use one or two focused search angles and prioritize current, concrete posts.",
+ "Read post details, audience comments, and replies whenever the platform tools support them.",
+ "Stop after identifying up to four strong posts or videos with a usable thumbnail, poster, or video URL; prefer directly previewable evidence.",
+ "Compare recurring themes, engagement signals, disagreements, and notable outliers.",
+ "Cite source URLs and do not invent facts that are not present in the captured evidence.",
+ ].join("\n");
+}
+
+function buildSearchQueries(query, platform) {
+ if (platform !== "instagram") return [query];
+ const normalized = query.trim();
+ const compact = normalized.replace(/[^a-z0-9_]+/gi, "");
+ const singularCompact = compact.replace(/s$/i, "");
+ return [...new Set([normalized, compact, singularCompact].filter(Boolean))].slice(0, 3);
+}
+
+function mergeEvidenceItems(initialItems, researchItems) {
+ const merged = [...initialItems];
+ for (const candidate of Array.isArray(researchItems) ? researchItems.filter(isRecord) : []) {
+ const identity = evidenceIdentity(candidate);
+ const index = identity ? merged.findIndex((item) => evidenceIdentity(item) === identity) : -1;
+ if (index >= 0) merged[index] = { ...merged[index], ...candidate };
+ else merged.push(candidate);
+ }
+ return merged;
+}
+
+function evidenceIdentity(item) {
+ const value = item?.shortcode || item?.video_id || item?.id || item?.url || item?.web_url || item?.share_url;
+ return String(value || "").trim();
+}
+
+function selectPreviewableEvidence(items, limit) {
+ return items
+ .map((item, index) => ({ item, index, score: previewScore(item) }))
+ .filter(({ score }) => score > 0)
+ .sort((left, right) => right.score - left.score || left.index - right.index)
+ .slice(0, limit)
+ .map(({ item }) => item);
+}
+
+function previewScore(item) {
+ const browserPaths = [
+ item?.video?.browser_url,
+ item?.video?.local_url,
+ item?.video_browser_url,
+ ];
+ if (browserPaths.some(nonEmptyString)) return 100;
+
+ const media = Array.isArray(item?.media) ? item.media : [];
+ if (media.some((entry) => entry?.type === "video" && [entry.url, entry.browser_url].some(nonEmptyString))) {
+ return 80;
+ }
+ if ([item?.video?.url, item?.video?.play_url, item?.video_url, item?.play_url].some(nonEmptyString)) return 75;
+
+ const posters = [
+ item?.video?.poster_url,
+ item?.video?.poster_browser_url,
+ item?.cover_url,
+ item?.cover,
+ item?.thumbnail_url,
+ item?.thumbnail,
+ item?.image_url,
+ item?.image,
+ ...media.flatMap((entry) => [entry?.poster_url, entry?.url, entry?.browser_url]),
+ ];
+ if (posters.some(nonEmptyString)) return 50;
+
+ const localPaths = [item?.video?.local_path, item?.video_local_path, ...media.map((entry) => entry?.local_path)];
+ return localPaths.some(nonEmptyString) ? 35 : 0;
+}
+
+function nonEmptyString(value) {
+ return typeof value === "string" && value.trim().length > 0;
+}
+
+function emitProgress(onEvent, stage, message) {
+ const normalized = safeProgressMessage(message);
+ if (normalized) onEvent?.({ stage, message: normalized });
+}
+
+function parseSocaiEvent(message) {
+ const normalized = String(message || "").trim();
+ if (!normalized.startsWith(SOCAI_EVENT_PREFIX)) return null;
+ try {
+ const event = JSON.parse(normalized.slice(SOCAI_EVENT_PREFIX.length));
+ return isRecord(event) ? event : null;
+ } catch {
+ return null;
+ }
+}
+
+function safeProgressMessage(message) {
+ const normalized = String(message || "").trim();
+ if (!normalized || normalized.startsWith(SOCAI_EVENT_PREFIX)) return "";
+ if (/^[{[]/.test(normalized)) return "";
+ if (/^\d{4}-\d{2}-\d{2}T\S+\s+(?:TRACE|DEBUG|INFO|WARN|ERROR)\b/.test(normalized)) return "";
+ if (/^at\s+(?:<anonymous>|[\w.]+)(?::|\s|$)/.test(normalized)) return "";
+ if (/\b(?:run_dir|report_path|local_path|output_dir|artifact_path)\b\s*[:=]/i.test(normalized)) return "";
+ if (/(?:^|\s)(?:\/Users\/|\/home\/|\/tmp\/|[A-Za-z]:\\)/.test(normalized)) return "";
+ return normalized;
+}
+
+function sanitizeEvidenceForStream(item) {
+ return sanitizeStreamValue(item);
+}
+
+function sanitizeStreamValue(value) {
+ if (Array.isArray(value)) return value.map(sanitizeStreamValue).filter((item) => item !== undefined);
+ if (!isRecord(value)) {
+ if (typeof value === "string" && /^(?:\/Users\/|\/home\/|\/tmp\/|[A-Za-z]:\\)/.test(value)) return undefined;
+ return value;
+ }
+ const clean = {};
+ for (const [key, child] of Object.entries(value)) {
+ if (/(?:^|_)(?:local_)?path$|(?:^|_)(?:run|output|artifact)_dir$/i.test(key)) continue;
+ const next = sanitizeStreamValue(child);
+ if (next !== undefined) clean[key] = next;
+ }
+ return clean;
+}
+
+function extractItems(value) {
+ if (Array.isArray(value)) return value.filter(isRecord);
+ if (!isRecord(value)) return [];
+ for (const key of ["results", "cards", "items", "videos", "posts", "data"]) {
+ if (Array.isArray(value[key])) return value[key].filter(isRecord);
+ }
+ return [];
+}
+
+function videoLocator(item) {
+ for (const key of ["url", "web_url", "share_url", "video_id", "id"]) {
+ const value = item?.[key];
+ if (typeof value === "string" && value.trim()) return value.trim();
+ }
+ return "";
+}
+
+function mergeTikTokItems(cards, details) {
+ const wrappers = Array.isArray(details?.videos) ? details.videos : [];
+ const unused = new Set(wrappers);
+ const merged = cards.map((card) => {
+ const wrapper = wrappers.find((candidate) => unused.has(candidate) && sameVideo(card, candidate?.entity, candidate?.locator));
+ if (!wrapper) return card;
+ unused.delete(wrapper);
+ const entity = isRecord(wrapper?.entity) ? wrapper.entity : {};
+ return { ...card, ...entity, socai_detail: wrapper };
+ });
+ for (const wrapper of unused) {
+ const entity = isRecord(wrapper?.entity) ? wrapper.entity : {};
+ merged.push({ ...entity, socai_detail: wrapper });
+ }
+ return merged;
+}
+
+function sameVideo(card, entity, locator) {
+ const candidates = [card?.video_id, card?.id, card?.url, card?.web_url, card?.share_url].map(videoIdentity).filter(Boolean);
+ const targets = [entity?.video_id, entity?.id, entity?.url, locator].map(videoIdentity).filter(Boolean);
+ return candidates.some((candidate) => targets.includes(candidate));
+}
+
+function videoIdentity(value) {
+ const normalized = String(value || "").trim();
+ const id = normalized.match(/(?:^|\/video\/)(\d{3,})(?:[/?#]|$)/)?.[1];
+ if (id) return `id:${id}`;
+ if (/^https?:\/\//i.test(normalized)) {
+ try {
+ const url = new URL(normalized);
+ return `url:${url.hostname.toLowerCase()}${url.pathname.replace(/\/+$/, "")}`;
+ } catch {
+ return "";
+ }
+ }
+ return normalized ? `value:${normalized}` : "";
+}
+
+function isRecord(value) {
+ return value && typeof value === "object" && !Array.isArray(value);
+}
+
+function createRunId() {
+ const timestamp = new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14);
+ return `${timestamp}-${crypto.randomBytes(3).toString("hex")}`;
+}
diff --git a/src/classifier.js b/src/classifier.js
new file mode 100644
index 0000000..1639e10
--- /dev/null
+++ b/src/classifier.js
@@ -0,0 +1,131 @@
+import { AppError } from "./errors.js";
+
+export const SUPPORTED_PLATFORMS = new Set(["instagram", "tiktok"]);
+
+export async function classifySearch({
+ goal,
+ requestedPlatform = "auto",
+ apiKey,
+ model = process.env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",
+ client,
+ fetchImpl = fetch,
+}) {
+ const normalizedPlatform = requestedPlatform.toLowerCase();
+ if (normalizedPlatform !== "auto" && !SUPPORTED_PLATFORMS.has(normalizedPlatform)) {
+ throw new AppError(`Unsupported platform: ${requestedPlatform}`, {
+ code: "INVALID_PLATFORM",
+ });
+ }
+ if (!goal?.trim()) {
+ throw new AppError("Search query cannot be empty.", { code: "EMPTY_QUERY" });
+ }
+
+ const request = {
+ model,
+ state: {
+ request: goal.trim(),
+ requested_platform: normalizedPlatform,
+ supported_workflows: [
+ "Read-only Instagram search via the socai CLI",
+ "Read-only TikTok search via the socai CLI",
+ ],
+ },
+ questions: {
+ route: {
+ type: "choice",
+ instructions: {
+ task: "Choose the one supported workflow that should execute this request.",
+ rules: [
+ "Honor an explicit requested_platform.",
+ "Choose unsupported when the request is not a read-only social search.",
+ "Do not invent another platform or an action that changes remote state.",
+ ],
+ },
+ criteria: {
+ instagram_search: "Search or research Instagram content, profiles, posts, or reels.",
+ tiktok_search: "Search or research TikTok content, creators, or videos.",
+ unsupported:
+ "Anything else, including posting, liking, following, messaging, or an ambiguous auto route.",
+ },
+ },
+ },
+ };
+ let response;
+ try {
+ response = client
+ ? await client.systemOne(request)
+ : await requestOpenRouterDecision({ apiKey, request, fetchImpl });
+ } catch (error) {
+ throw new AppError(`Jev classification failed: ${error.message}`, {
+ code: "JEV_UNAVAILABLE",
+ status: 502,
+ });
+ }
+
+ const answer = response?.answers?.route;
+ const selected = answer?.choice;
+ const platform = selected === "instagram_search" ? "instagram" : selected === "tiktok_search" ? "tiktok" : null;
+ const confidence = answer?.confidence;
+ const probabilities = answer?.probabilities;
+ const probabilitiesValid =
+ probabilities === undefined ||
+ (probabilities &&
+ typeof probabilities === "object" &&
+ !Array.isArray(probabilities) &&
+ Object.values(probabilities).every(
+ (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1,
+ ));
+ if (
+ answer?.type !== "choice" ||
+ !["instagram_search", "tiktok_search", "unsupported"].includes(selected) ||
+ typeof confidence !== "number" ||
+ !Number.isFinite(confidence) ||
+ confidence < 0 ||
+ confidence > 1 ||
+ !probabilitiesValid
+ ) {
+ throw new AppError("Jev returned an invalid route response.", {
+ code: "INVALID_JEV_RESPONSE",
+ status: 502,
+ });
+ }
+ if (normalizedPlatform !== "auto" && platform !== normalizedPlatform) {
+ throw new AppError(
+ `Jev route '${selected}' conflicts with the explicitly selected ${normalizedPlatform} platform.`,
+ {
+ code: "JEV_ROUTE_MISMATCH",
+ details: { requestedPlatform: normalizedPlatform, selectedRoute: selected },
+ },
+ );
+ }
+
+ return {
+ route: selected,
+ platform,
+ confidence,
+ probabilities,
+ model: response.model || model,
+ usage: response.usage || {},
+ };
+}
+
+async function requestOpenRouterDecision({ apiKey, request, fetchImpl }) {
+ if (!apiKey?.trim()) {
+ throw new Error("OPENROUTER_API_KEY is missing");
+ }
+ const response = await fetchImpl("https://openrouter.ai/api/alpha/decisions", {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey.trim()}`,
+ "Content-Type": "application/json",
+ "X-Title": "jev-social",
+ },
+ body: JSON.stringify(request),
+ signal: AbortSignal.timeout(15_000),
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ throw new Error(payload?.error?.message || `OpenRouter returned HTTP ${response.status}`);
+ }
+ return payload;
+}
diff --git a/src/config.js b/src/config.js
new file mode 100644
index 0000000..eec3906
--- /dev/null
+++ b/src/config.js
@@ -0,0 +1,60 @@
+import { constants } from "node:fs";
+import { access, chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { firstExecutable, localSocaiBuildCandidates } from "./env.js";
+
+export function getHomeDir(env = process.env) {
+ return path.resolve(env.JEV_SOCIAL_HOME || path.join(os.homedir(), ".jev-social"));
+}
+
+export function getConfigPath(env = process.env) {
+ return path.join(getHomeDir(env), "config.json");
+}
+
+export async function readConfig(env = process.env) {
+ try {
+ const raw = await readFile(getConfigPath(env), "utf8");
+ const config = JSON.parse(raw);
+ return config && typeof config === "object" ? config : {};
+ } catch (error) {
+ if (error?.code === "ENOENT") return {};
+ throw error;
+ }
+}
+
+export async function writeConfig(next, env = process.env) {
+ const homeDir = getHomeDir(env);
+ const configPath = getConfigPath(env);
+ const temporaryPath = `${configPath}.${process.pid}.tmp`;
+ await mkdir(homeDir, { recursive: true, mode: 0o700 });
+ await writeFile(temporaryPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
+ await chmod(temporaryPath, 0o600);
+ await rename(temporaryPath, configPath);
+ return configPath;
+}
+
+export function resolveApiKey(config, env = process.env) {
+ return (
+ env.OPENROUTER_API_KEY?.trim() ||
+ env.openrouter?.trim() ||
+ config.openrouterApiKey?.trim() ||
+ config.typesafeApiKey?.trim() ||
+ ""
+ );
+}
+
+export function configuredSocaiBin(config, env = process.env) {
+ return env.SOCAI_BIN?.trim() || config.socaiBin?.trim() || "";
+}
+
+export async function defaultInstalledSocaiBin() {
+ const filename = process.platform === "win32" ? "socai.exe" : "socai";
+ const candidate = path.join(os.homedir(), ".socai", "bin", filename);
+ try {
+ await access(candidate, process.platform === "win32" ? constants.F_OK : constants.X_OK);
+ return candidate;
+ } catch {
+ return (await firstExecutable(localSocaiBuildCandidates())) || "socai";
+ }
+}
diff --git a/src/env.js b/src/env.js
new file mode 100644
index 0000000..0b39ea9
--- /dev/null
+++ b/src/env.js
@@ -0,0 +1,77 @@
+import { constants } from "node:fs";
+import { access, readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const PROJECT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const WORKSPACE_ENV = path.resolve(PROJECT_ROOT, "../docs/work/20260918-2/.env");
+const AUTO_ENV_KEYS = new Set(["OPENROUTER_API_KEY", "OPENROUTER_JEV_MODEL", "openrouter"]);
+
+export async function loadLocalEnv(env = process.env) {
+ const explicitEnvFile = env.JEV_SOCIAL_ENV_FILE?.trim();
+ const candidates = [
+ ...(explicitEnvFile ? [{ path: explicitEnvFile, trusted: true }] : []),
+ { path: path.join(PROJECT_ROOT, ".env"), trusted: false },
+ { path: WORKSPACE_ENV, trusted: false },
+ ];
+ let envFile = null;
+ for (const candidate of candidates) {
+ try {
+ const values = parseEnv(await readFile(candidate.path, "utf8"));
+ for (const [key, value] of Object.entries(values)) {
+ if (!candidate.trusted && !AUTO_ENV_KEYS.has(key)) continue;
+ if (env[key] === undefined) env[key] = value;
+ }
+ envFile = candidate.path;
+ break;
+ } catch (error) {
+ if (error?.code !== "ENOENT") throw error;
+ }
+ }
+
+ if (!env.OPENROUTER_API_KEY?.trim() && env.openrouter?.trim()) {
+ env.OPENROUTER_API_KEY = env.openrouter.trim();
+ }
+ return { envFile };
+}
+
+export function parseEnv(source) {
+ const values = {};
+ for (const rawLine of source.split(/\r?\n/)) {
+ const line = rawLine.trim();
+ if (!line || line.startsWith("#")) continue;
+ const match = line.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
+ if (!match) continue;
+ let value = match[2].trim();
+ if (
+ value.length >= 2 &&
+ ((value.startsWith('"') && value.endsWith('"')) ||
+ (value.startsWith("'") && value.endsWith("'")))
+ ) {
+ value = value.slice(1, -1);
+ }
+ values[match[1]] = value;
+ }
+ return values;
+}
+
+export async function firstExecutable(candidates) {
+ for (const candidate of candidates) {
+ try {
+ await access(candidate, process.platform === "win32" ? constants.F_OK : constants.X_OK);
+ return candidate;
+ } catch {
+ // Try the next local build location.
+ }
+ }
+ return null;
+}
+
+export function localSocaiBuildCandidates() {
+ const filename = process.platform === "win32" ? "socai.exe" : "socai";
+ const targetRoot = path.resolve(
+ PROJECT_ROOT,
+ "../docs/work/20260918/worktrees/dev-platform-validation/target",
+ );
+ return [path.join(targetRoot, "debug", filename), path.join(targetRoot, "release", filename)];
+}
diff --git a/src/errors.js b/src/errors.js
new file mode 100644
index 0000000..0555907
--- /dev/null
+++ b/src/errors.js
@@ -0,0 +1,19 @@
+export class AppError extends Error {
+ constructor(message, { code = "APP_ERROR", status = 400, details } = {}) {
+ super(message);
+ this.name = "AppError";
+ this.code = code;
+ this.status = status;
+ this.details = details;
+ }
+}
+
+export function errorPayload(error) {
+ return {
+ error: {
+ code: error?.code || "INTERNAL_ERROR",
+ message: error instanceof Error ? error.message : String(error),
+ ...(error?.details ? { details: error.details } : {}),
+ },
+ };
+}
diff --git a/src/index.js b/src/index.js
new file mode 100644
index 0000000..3a36343
--- /dev/null
+++ b/src/index.js
@@ -0,0 +1,13 @@
+export { runSearch } from "./app.js";
+export { classifySearch } from "./classifier.js";
+export {
+ buildResearchArgs,
+ buildTikTokVideoArgs,
+ probeSocai,
+ runSocaiResearch,
+ runSocaiSearch,
+ runSocaiTikTokVideos,
+} from "./socai.js";
+export { saveOnboarding, verifyOpenRouterApiKey, verifyTypesafeApiKey } from "./onboard.js";
+export { loadLocalEnv } from "./env.js";
+export { extractSearchQuery } from "./query.js";
diff --git a/src/onboard.js b/src/onboard.js
new file mode 100644
index 0000000..74c94f1
--- /dev/null
+++ b/src/onboard.js
@@ -0,0 +1,105 @@
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { AppError } from "./errors.js";
+import { readConfig, resolveApiKey, writeConfig } from "./config.js";
+import { runProcess } from "./process.js";
+import { probeSocai } from "./socai.js";
+
+const INSTALLERS = {
+ darwin: "https://github.com/socai-io/socai/releases/latest/download/install.sh",
+ win32: "https://github.com/socai-io/socai/releases/latest/download/install.ps1",
+};
+
+export async function verifyOpenRouterApiKey(apiKey) {
+ if (!apiKey?.trim()) {
+ throw new AppError("An OpenRouter API key is required for Jev routing.", {
+ code: "OPENROUTER_KEY_REQUIRED",
+ });
+ }
+ try {
+ const response = await fetch("https://openrouter.ai/api/v1/auth/key", {
+ headers: { Authorization: `Bearer ${apiKey.trim()}` },
+ signal: AbortSignal.timeout(15_000),
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(payload?.error?.message || `HTTP ${response.status}`);
+ return payload.data || {};
+ } catch (error) {
+ throw new AppError(`OpenRouter API key validation failed: ${error.message}`, {
+ code: "OPENROUTER_KEY_INVALID",
+ status: 502,
+ });
+ }
+}
+
+export async function installSocaiCli({ onMessage } = {}) {
+ const installerUrl = INSTALLERS[process.platform];
+ if (!installerUrl) {
+ throw new AppError(
+ "The official prebuilt socai installer supports macOS and Windows. Install from source, then set SOCAI_BIN.",
+ { code: "SOCAI_INSTALL_UNSUPPORTED" },
+ );
+ }
+
+ onMessage?.(`Downloading official installer: ${installerUrl}`);
+ const response = await fetch(installerUrl, { redirect: "follow" });
+ if (!response.ok) {
+ throw new AppError(`Could not download socai installer (HTTP ${response.status}).`, {
+ code: "SOCAI_INSTALL_DOWNLOAD_FAILED",
+ status: 502,
+ });
+ }
+
+ const temporaryDirectory = await mkdtemp(path.join(os.tmpdir(), "jev-social-install-"));
+ const extension = process.platform === "win32" ? "ps1" : "sh";
+ const installerPath = path.join(temporaryDirectory, `install.${extension}`);
+ try {
+ await writeFile(installerPath, await response.text(), { mode: 0o700 });
+ const command = process.platform === "win32" ? "powershell.exe" : "sh";
+ const args =
+ process.platform === "win32"
+ ? ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", installerPath]
+ : [installerPath];
+ const result = await runProcess(command, args, { inherit: true, timeoutMs: 5 * 60_000 });
+ if (result.code !== 0) {
+ throw new AppError(`socai installer exited with code ${result.code}.`, {
+ code: "SOCAI_INSTALL_FAILED",
+ });
+ }
+ } finally {
+ await rm(temporaryDirectory, { recursive: true, force: true });
+ }
+}
+
+export async function saveOnboarding({
+ apiKey,
+ socaiBin,
+ installCli = false,
+ verify = true,
+ persistApiKey = Boolean(apiKey?.trim()),
+ env = process.env,
+ onMessage,
+}) {
+ const current = await readConfig(env);
+ const key = apiKey?.trim() || resolveApiKey(current, env);
+ if (!key) {
+ throw new AppError("An OpenRouter API key is required for Jev routing.", {
+ code: "OPENROUTER_KEY_REQUIRED",
+ });
+ }
+ const keyInfo = verify ? await verifyOpenRouterApiKey(key) : {};
+ if (installCli) await installSocaiCli({ onMessage });
+
+ const next = {
+ ...current,
+ ...(persistApiKey ? { openrouterApiKey: key } : {}),
+ ...(socaiBin?.trim() ? { socaiBin: socaiBin.trim() } : {}),
+ updatedAt: new Date().toISOString(),
+ };
+ const configPath = await writeConfig(next, env);
+ const socai = await probeSocai(next, env);
+ return { configPath, keyInfo, socai };
+}
+
+export const verifyTypesafeApiKey = verifyOpenRouterApiKey;
diff --git a/src/process.js b/src/process.js
new file mode 100644
index 0000000..1795b11
--- /dev/null
+++ b/src/process.js
@@ -0,0 +1,217 @@
+import { spawn } from "node:child_process";
+import { StringDecoder } from "node:string_decoder";
+
+const MAX_OUTPUT_BYTES = 24 * 1024 * 1024;
+const CHILD_ENV_KEYS = new Set([
+ "PATH",
+ "HOME",
+ "USER",
+ "LOGNAME",
+ "SHELL",
+ "TMPDIR",
+ "TMP",
+ "TEMP",
+ "LANG",
+ "LC_ALL",
+ "LC_CTYPE",
+ "DISPLAY",
+ "WAYLAND_DISPLAY",
+ "XDG_RUNTIME_DIR",
+ "XDG_CONFIG_HOME",
+ "USERPROFILE",
+ "LOCALAPPDATA",
+ "APPDATA",
+ "PROGRAMDATA",
+ "SystemRoot",
+ "WINDIR",
+ "COMSPEC",
+ "PATHEXT",
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "NO_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "no_proxy",
+ "SSL_CERT_FILE",
+ "SSL_CERT_DIR",
+ "NODE_EXTRA_CA_CERTS",
+ "NO_COLOR",
+ "SOCAI_CDP_URL",
+ "SOCAI_CDP_WS",
+ "SOCAI_CHROME_EXECUTABLE",
+ "SOCAI_CHROME_PROFILE",
+ "SOCAI_CHROME_USER_DATA_DIR",
+ "SOCAI_CLOUD_BASE_URL",
+ "SOCAI_DOWNLOAD_BASE_URL",
+ "SOCAI_HOME",
+ "SOCAI_INSTALL_DIR",
+ "SOCAI_LLM_PROVIDER",
+ "SOCAI_MODEL",
+ "SOCAI_MODEL_SYNC_OFFLINE",
+ "SOCAI_NO_UPDATE_CHECK",
+ "SOCAI_PRO_BASE_URL",
+ "SOCAI_RUNS_DIR",
+ "SOCAI_SESSIONS_DIR",
+ "SOCAI_SKIP_UPDATE_CHECK",
+ "SOCAI_TELEMETRY",
+ "SOCAI_TRACES_ENDPOINT",
+ "SOCAI_WHISPER_CLI",
+]);
+
+export function childEnvironment(source = process.env) {
+ return Object.fromEntries(
+ Object.entries(source).filter(
+ ([key, value]) => value !== undefined && CHILD_ENV_KEYS.has(key),
+ ),
+ );
+}
+
+export function runProcess(command, args, options = {}) {
+ const {
+ cwd,
+ env = process.env,
+ timeoutMs = 5 * 60_000,
+ onStderr,
+ inherit = false,
+ maxOutputBytes = MAX_OUTPUT_BYTES,
+ killGraceMs = 1_000,
+ signal,
+ } = options;
+
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ const error = new Error("Operation aborted.");
+ error.name = "AbortError";
+ reject(error);
+ return;
+ }
+ const child = spawn(command, args, {
+ cwd,
+ env: childEnvironment(env),
+ windowsHide: true,
+ detached: process.platform !== "win32",
+ stdio: inherit ? "inherit" : ["ignore", "pipe", "pipe"],
+ });
+
+ let forceKillTimer;
+ let aborted = false;
+ let stopRequested = false;
+ const stop = () => {
+ stopRequested = true;
+ terminateTree(child, "SIGTERM");
+ forceKillTimer ||= setTimeout(() => terminateTree(child, "SIGKILL"), killGraceMs);
+ forceKillTimer.unref?.();
+ };
+ const abort = () => {
+ aborted = true;
+ stop();
+ };
+ signal?.addEventListener("abort", abort, { once: true });
+ const cleanup = (preserveForceKill = false) => {
+ signal?.removeEventListener("abort", abort);
+ if (!preserveForceKill) clearTimeout(forceKillTimer);
+ };
+
+ if (inherit) {
+ const timer = setTimeout(stop, timeoutMs);
+ child.once("error", (error) => {
+ clearTimeout(timer);
+ cleanup();
+ reject(error);
+ });
+ child.once("close", (code, signal) => {
+ clearTimeout(timer);
+ cleanup(stopRequested);
+ resolve({ code, signal, stdout: "", stderr: "", aborted });
+ });
+ return;
+ }
+
+ const stdout = [];
+ const stderr = [];
+ const progressDecoder = new StringDecoder("utf8");
+ let progressBuffer = "";
+ let outputBytes = 0;
+ let timedOut = false;
+ let overflowed = false;
+ const append = (target, chunk) => {
+ outputBytes += chunk.length;
+ if (outputBytes > maxOutputBytes) {
+ overflowed = true;
+ stop();
+ return;
+ }
+ target.push(chunk);
+ };
+
+ child.stdout.on("data", (chunk) => append(stdout, chunk));
+ child.stderr.on("data", (chunk) => {
+ append(stderr, chunk);
+ if (!onStderr) return;
+ progressBuffer += progressDecoder.write(chunk);
+ const lines = progressBuffer.split(/\r?\n/);
+ progressBuffer = lines.pop() || "";
+ for (const line of lines) if (line) onStderr(line);
+ });
+ child.stderr.on("end", () => {
+ if (!onStderr) return;
+ progressBuffer += progressDecoder.end();
+ if (progressBuffer) onStderr(progressBuffer);
+ progressBuffer = "";
+ });
+
+ const timer = setTimeout(() => {
+ timedOut = true;
+ stop();
+ }, timeoutMs);
+
+ child.once("error", (error) => {
+ clearTimeout(timer);
+ cleanup();
+ reject(error);
+ });
+ child.once("close", (code, signal) => {
+ clearTimeout(timer);
+ cleanup(stopRequested);
+ resolve({
+ code,
+ signal,
+ stdout: Buffer.concat(stdout).toString("utf8"),
+ stderr: Buffer.concat(stderr).toString("utf8"),
+ timedOut,
+ overflowed,
+ aborted,
+ });
+ });
+ });
+}
+
+function terminateTree(child, signal) {
+ if (!child.pid) return;
+ if (process.platform === "win32") {
+ if (signal === "SIGKILL") {
+ const killer = spawn("taskkill.exe", ["/pid", String(child.pid), "/t", "/f"], {
+ windowsHide: true,
+ stdio: "ignore",
+ });
+ killer.on("error", () => {});
+ } else {
+ child.kill("SIGTERM");
+ }
+ return;
+ }
+ try {
+ process.kill(-child.pid, signal);
+ } catch (error) {
+ if (error.code !== "ESRCH") child.kill(signal);
+ }
+}
+
+export function formatCommand(command, args) {
+ const quote = (value) => {
+ const text = String(value);
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(text)) return text;
+ return `'${text.replaceAll("'", `'"'"'`)}'`;
+ };
+ return [command, ...args].map(quote).join(" ");
+}
diff --git a/src/query.js b/src/query.js
new file mode 100644
index 0000000..79a8310
--- /dev/null
+++ b/src/query.js
@@ -0,0 +1,51 @@
+const PLATFORM = "(?:instagram|tiktok)";
+const ENGLISH_ACTION = "(?:search|find|look\\s+up|research)";
+const ENGLISH_POLITE = "(?:(?:could|can|would)\\s+you\\s+)?(?:please\\s+)?";
+const TRAILING_ENGLISH_INSTRUCTION =
+ "(?:\\s+please)?(?:\\s*[,;:]?\\s*(?:(?:and|then)\\s+)?(?:return|show|give|list|get)\\b.*)?";
+const CHINESE_ACTION = "(?:搜索一下|搜一下|搜索|搜|查找|检索|调研)";
+const CHINESE_POLITE = "(?:请)?(?:帮我)?";
+const TRAILING_CHINESE_INSTRUCTION =
+ "(?:\\s*(?:[,,;;]\\s*)?(?:(?:然后|并且|并请|并)\\s*)?(?:返回|找出|给我|展示|列出).*)?";
+
+const PATTERNS = [
+ new RegExp(
+ `^\\s*${ENGLISH_POLITE}${ENGLISH_ACTION}\\s+(?:me\\s+)?(?:for\\s+)?(.+?)\\s+(?:on|in|from)\\s+${PLATFORM}${TRAILING_ENGLISH_INSTRUCTION}\\s*[.!?]*\\s*$`,
+ "i",
+ ),
+ new RegExp(
+ `^\\s*${ENGLISH_POLITE}${ENGLISH_ACTION}\\s+(?:on\\s+)?${PLATFORM}\\s+(?:for\\s+)?(.+?)${TRAILING_ENGLISH_INSTRUCTION}\\s*[.!?]*\\s*$`,
+ "i",
+ ),
+ new RegExp(
+ `^\\s*${CHINESE_POLITE}\\s*在\\s*${PLATFORM}\\s*(?:上|里|中)?\\s*${CHINESE_POLITE}\\s*${CHINESE_ACTION}\\s*(.+?)${TRAILING_CHINESE_INSTRUCTION}\\s*$`,
+ "i",
+ ),
+ new RegExp(
+ `^\\s*${CHINESE_POLITE}\\s*${CHINESE_ACTION}\\s*${PLATFORM}\\s*(?:上(?:的)?|里(?:的)?|中(?:的)?)?\\s*(.+?)${TRAILING_CHINESE_INSTRUCTION}\\s*$`,
+ "i",
+ ),
+];
+
+/**
+ * Convert a natural-language research request into the literal query expected by
+ * `socai <platform> search <query>`. Jev still receives the complete request so
+ * it can choose the correct platform.
+ */
+export function extractSearchQuery(request) {
+ const normalized = String(request || "").trim();
+ for (const pattern of PATTERNS) {
+ const match = normalized.match(pattern);
+ if (match?.[1]) return cleanTopic(match[1]) || normalized;
+ }
+ return normalized;
+}
+
+function cleanTopic(value) {
+ return value
+ .trim()
+ .replace(/^["'“‘]+|["'”’]+$/g, "")
+ .replace(/\s+please$/i, "")
+ .replace(/[。.!??]+$/g, "")
+ .trim();
+}
diff --git a/src/runs.js b/src/runs.js
new file mode 100644
index 0000000..1c446ca
--- /dev/null
+++ b/src/runs.js
@@ -0,0 +1,67 @@
+import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { getHomeDir } from "./config.js";
+
+function runsDir(env = process.env) {
+ return path.join(getHomeDir(env), "runs");
+}
+
+export async function saveRun(run, env = process.env) {
+ const directory = runsDir(env);
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ const target = path.join(directory, `${run.id}.json`);
+ const temporary = `${target}.${process.pid}.tmp`;
+ await writeFile(temporary, `${JSON.stringify(run, null, 2)}\n`, { mode: 0o600 });
+ await rename(temporary, target);
+ return target;
+}
+
+export async function listRuns(env = process.env, limit = 30) {
+ let files;
+ try {
+ files = await readdir(runsDir(env));
+ } catch (error) {
+ if (error?.code === "ENOENT") return [];
+ throw error;
+ }
+ const selected = files
+ .filter((name) => name.endsWith(".json"))
+ .sort()
+ .reverse()
+ .slice(0, limit);
+ const runs = [];
+ for (const name of selected) {
+ try {
+ const run = JSON.parse(await readFile(path.join(runsDir(env), name), "utf8"));
+ runs.push({
+ id: run.id,
+ createdAt: run.createdAt,
+ query: run.query,
+ platform: run.platform,
+ itemCount: countItems(run.result),
+ });
+ } catch {
+ // Ignore a partial or manually edited history entry.
+ }
+ }
+ return runs;
+}
+
+export async function readRun(id, env = process.env) {
+ if (!/^[A-Za-z0-9_.-]+$/.test(id)) return null;
+ try {
+ return JSON.parse(await readFile(path.join(runsDir(env), `${id}.json`), "utf8"));
+ } catch (error) {
+ if (error?.code === "ENOENT") return null;
+ throw error;
+ }
+}
+
+function countItems(value) {
+ if (Array.isArray(value)) return value.length;
+ if (!value || typeof value !== "object") return 0;
+ for (const key of ["results", "items", "videos", "posts", "data"]) {
+ if (Array.isArray(value[key])) return value[key].length;
+ }
+ return 0;
+}
diff --git a/src/server.js b/src/server.js
new file mode 100644
index 0000000..c295dcf
--- /dev/null
+++ b/src/server.js
@@ -0,0 +1,398 @@
+import { spawn } from "node:child_process";
+import crypto from "node:crypto";
+import { constants } from "node:fs";
+import { open, readFile, realpath, stat } from "node:fs/promises";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { runSearch } from "./app.js";
+import { getConfigPath, readConfig, resolveApiKey } from "./config.js";
+import { errorPayload } from "./errors.js";
+import { loadLocalEnv } from "./env.js";
+import { saveOnboarding } from "./onboard.js";
+import { listRuns, readRun } from "./runs.js";
+import { probeSocai } from "./socai.js";
+
+const PUBLIC_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../public");
+const MEDIA_TTL_MS = 60 * 60_000;
+const STATIC_FILES = {
+ "/": ["index.html", "text/html; charset=utf-8"],
+ "/app.js": ["app.js", "text/javascript; charset=utf-8"],
+ "/styles.css": ["styles.css", "text/css; charset=utf-8"],
+};
+
+export async function startServer({ port = 8766, open = true, env = process.env } = {}) {
+ await loadLocalEnv(env);
+ const numericPort = Number(port);
+ if (!Number.isInteger(numericPort) || numericPort < 0 || numericPort > 65_535) {
+ throw new Error("port must be an integer between 0 and 65535");
+ }
+
+ const mediaRegistry = new Map();
+ const server = http.createServer((request, response) => {
+ void handleRequest(request, response, env, mediaRegistry);
+ });
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(numericPort, "127.0.0.1", resolve);
+ });
+
+ const address = server.address();
+ const actualPort = typeof address === "object" && address ? address.port : numericPort;
+ const url = `http://127.0.0.1:${actualPort}`;
+ console.log(`jev-social preview: ${url}`);
+ if (open) openBrowser(url);
+ return { server, url, accessUrl: url };
+}
+
+async function handleRequest(request, response, env, mediaRegistry) {
+ try {
+ if (!validHost(request.headers.host)) {
+ return sendJson(response, 403, { error: { code: "INVALID_HOST", message: "Invalid Host header." } });
+ }
+ const url = new URL(request.url, "http://127.0.0.1");
+ const mediaMatch = request.method === "GET" && url.pathname.match(/^\/media\/([A-Za-z0-9_-]+)$/);
+ if (mediaMatch) {
+ const media = mediaFromRegistry(mediaRegistry, mediaMatch[1]);
+ return media
+ ? await serveMedia(request, response, media)
+ : sendJson(response, 404, { error: { code: "MEDIA_NOT_FOUND", message: "Media not found." } });
+ }
+ if (request.method === "GET" && STATIC_FILES[url.pathname]) {
+ const [filename, contentType] = STATIC_FILES[url.pathname];
+ const content = await readFile(path.join(PUBLIC_DIR, filename));
+ response.writeHead(200, {
+ "Content-Type": contentType,
+ "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff",
+ "Content-Security-Policy":
+ "default-src 'self'; img-src 'self' https: data:; media-src 'self' https: blob:; style-src 'self'; script-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
+ });
+ return response.end(content);
+ }
+ if (request.method === "GET" && url.pathname === "/api/status") {
+ const config = await readConfig(env);
+ const socai = await probeSocai(config, env);
+ return sendJson(response, 200, {
+ jevConfigured: Boolean(resolveApiKey(config, env)),
+ jevModel: env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",
+ configPath: getConfigPath(env),
+ socai,
+ });
+ }
+ if (request.method === "POST" && url.pathname === "/api/onboard") {
+ assertSameOrigin(request);
+ const body = await readJson(request);
+ validateOnboardBody(body);
+ const result = await saveOnboarding({
+ apiKey: body.apiKey,
+ socaiBin: body.socaiBin,
+ installCli: body.installCli ?? false,
+ verify: body.verify !== false,
+ persistApiKey: Boolean(body.apiKey?.trim()),
+ env,
+ onMessage: (message) => console.log(`[onboard] ${message}`),
+ });
+ return sendJson(response, 200, result);
+ }
+ if (request.method === "POST" && url.pathname === "/api/search") {
+ assertSameOrigin(request);
+ const body = await readJson(request);
+ validateSearchBody(body);
+ const run = await runSearch(
+ { query: body.query, platform: body.platform, limit: body.limit },
+ { env },
+ );
+ await registerRunMedia(run, mediaRegistry, env);
+ return sendJson(response, 200, run);
+ }
+ if (request.method === "POST" && url.pathname === "/api/search-stream") {
+ assertSameOrigin(request);
+ const body = await readJson(request);
+ validateSearchBody(body);
+ return streamSearch(request, response, body, env, mediaRegistry);
+ }
+ if (request.method === "GET" && url.pathname === "/api/runs") {
+ return sendJson(response, 200, { runs: await listRuns(env) });
+ }
+ const runMatch = request.method === "GET" && url.pathname.match(/^\/api\/runs\/([A-Za-z0-9_.-]+)$/);
+ if (runMatch) {
+ const run = await readRun(runMatch[1], env);
+ if (run) await registerRunMedia(run, mediaRegistry, env);
+ return run
+ ? sendJson(response, 200, run)
+ : sendJson(response, 404, { error: { code: "RUN_NOT_FOUND", message: "Run not found." } });
+ }
+ return sendJson(response, 404, { error: { code: "NOT_FOUND", message: "Not found." } });
+ } catch (error) {
+ const status = Number.isInteger(error?.status) ? error.status : 500;
+ if (status >= 500) console.error(error);
+ return sendJson(response, status, errorPayload(error));
+ }
+}
+
+async function streamSearch(request, response, body, env, mediaRegistry) {
+ response.writeHead(200, {
+ "Content-Type": "application/x-ndjson; charset=utf-8",
+ "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff",
+ "X-Accel-Buffering": "no",
+ });
+ const write = (value) => {
+ if (!response.destroyed && !response.writableEnded) response.write(`${JSON.stringify(value)}\n`);
+ };
+ const controller = new AbortController();
+ const abort = () => controller.abort();
+ const abortIfOpen = () => {
+ if (!response.writableEnded) abort();
+ };
+ request.once("aborted", abort);
+ response.once("close", abortIfOpen);
+ try {
+ const run = await runSearch(
+ { query: body.query, platform: body.platform, limit: body.limit },
+ { env, onEvent: write, signal: controller.signal },
+ );
+ await registerRunMedia(run, mediaRegistry, env);
+ write({ stage: "result", run });
+ } catch (error) {
+ write({ stage: "error", ...errorPayload(error) });
+ } finally {
+ request.removeListener("aborted", abort);
+ response.removeListener("close", abortIfOpen);
+ response.end();
+ }
+}
+
+async function registerRunMedia(run, registry, env) {
+ pruneMediaRegistry(registry);
+ const roots = await allowedMediaRoots(env);
+ const visit = async (value) => {
+ if (Array.isArray(value)) {
+ await Promise.all(value.map(visit));
+ return;
+ }
+ if (!value || typeof value !== "object") return;
+ for (const [key, child] of Object.entries(value)) {
+ if (key.endsWith("local_path") && typeof child === "string") {
+ const media = await verifiedMedia(child, roots);
+ if (media) {
+ let entry = [...registry.entries()].find(([, existing]) =>
+ existing.path === media.path && existing.dev === media.dev && existing.ino === media.ino,
+ );
+ if (!entry) {
+ const id = crypto.randomBytes(18).toString("base64url");
+ entry = [id, { ...media, expiresAt: Date.now() + MEDIA_TTL_MS }];
+ registry.set(...entry);
+ } else {
+ entry[1].expiresAt = Date.now() + MEDIA_TTL_MS;
+ }
+ const browserKey = key === "local_path" ? "browser_url" : key.replace(/_local_path$/, "_browser_url");
+ value[browserKey] = `/media/${entry[0]}`;
+ }
+ } else {
+ await visit(child);
+ }
+ }
+ };
+ await visit(run?.result);
+}
+
+async function allowedMediaRoots(env) {
+ const candidates = [
+ env.SOCAI_RUNS_DIR,
+ env.SOCAI_HOME && path.join(env.SOCAI_HOME, "runs"),
+ path.join(env.HOME || os.homedir(), ".socai", "runs"),
+ ].filter(Boolean);
+ return Promise.all(candidates.map(async (candidate) => realpath(candidate).catch(() => path.resolve(candidate))));
+}
+
+async function verifiedMedia(candidate, roots) {
+ try {
+ const resolved = await realpath(candidate);
+ if (!roots.some((root) => resolved === root || resolved.startsWith(`${root}${path.sep}`))) return null;
+ const metadata = await stat(resolved);
+ if (!metadata.isFile() || metadata.size <= 0) return null;
+ return { path: resolved, size: metadata.size, dev: metadata.dev, ino: metadata.ino, type: mediaType(resolved) };
+ } catch {
+ return null;
+ }
+}
+
+function mediaFromRegistry(registry, id) {
+ const media = registry.get(id);
+ if (!media) return null;
+ if (media.expiresAt <= Date.now()) {
+ registry.delete(id);
+ return null;
+ }
+ return media;
+}
+
+function pruneMediaRegistry(registry) {
+ const now = Date.now();
+ for (const [id, media] of registry) if (media.expiresAt <= now) registry.delete(id);
+}
+
+async function serveMedia(request, response, media) {
+ let handle;
+ try {
+ handle = await open(media.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
+ const metadata = await handle.stat();
+ if (!metadata.isFile() || metadata.dev !== media.dev || metadata.ino !== media.ino || metadata.size !== media.size) {
+ await handle.close();
+ return sendJson(response, 410, { error: { code: "MEDIA_CHANGED", message: "Media changed after capture." } });
+ }
+ } catch {
+ await handle?.close().catch(() => {});
+ return sendJson(response, 410, { error: { code: "MEDIA_UNAVAILABLE", message: "Media is no longer available." } });
+ }
+ const range = request.headers.range;
+ if (!range) {
+ response.writeHead(200, {
+ "Content-Type": media.type,
+ "Content-Length": media.size,
+ "Accept-Ranges": "bytes",
+ "Cache-Control": "private, max-age=3600",
+ "X-Content-Type-Options": "nosniff",
+ });
+ return pipeFileHandle(handle, response);
+ }
+ const match = /^bytes=(\d*)-(\d*)$/.exec(range);
+ if (!match) {
+ response.writeHead(416, { "Content-Range": `bytes */${media.size}` });
+ await handle.close();
+ return response.end();
+ }
+ const start = match[1] ? Number(match[1]) : Math.max(0, media.size - Number(match[2] || 0));
+ const end = match[2] && match[1] ? Math.min(Number(match[2]), media.size - 1) : media.size - 1;
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start > end || start >= media.size) {
+ response.writeHead(416, { "Content-Range": `bytes */${media.size}` });
+ await handle.close();
+ return response.end();
+ }
+ response.writeHead(206, {
+ "Content-Type": media.type,
+ "Content-Length": end - start + 1,
+ "Content-Range": `bytes ${start}-${end}/${media.size}`,
+ "Accept-Ranges": "bytes",
+ "Cache-Control": "private, max-age=3600",
+ "X-Content-Type-Options": "nosniff",
+ });
+ return pipeFileHandle(handle, response, { start, end });
+}
+
+function pipeFileHandle(handle, response, options = {}) {
+ const stream = handle.createReadStream({ ...options, autoClose: true });
+ stream.on("error", () => {
+ if (!response.destroyed) response.destroy();
+ });
+ response.on("close", () => stream.destroy());
+ stream.pipe(response);
+ return stream;
+}
+
+function mediaType(filename) {
+ const extension = path.extname(filename).toLowerCase();
+ return ({
+ ".mp4": "video/mp4",
+ ".webm": "video/webm",
+ ".mov": "video/quicktime",
+ ".m4a": "audio/mp4",
+ ".mp3": "audio/mpeg",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".png": "image/png",
+ ".webp": "image/webp",
+ })[extension] || "application/octet-stream";
+}
+
+function validHost(host = "") {
+ const hostname = host.split(":")[0].replace(/^\[|\]$/g, "");
+ return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "::1";
+}
+
+function assertSameOrigin(request) {
+ const origin = request.headers.origin;
+ const expected = `http://${request.headers.host}`;
+ try {
+ if (!origin || new URL(origin).origin !== expected) throw new Error("mismatch");
+ } catch {
+ throw httpError(403, "INVALID_ORIGIN", "Cross-origin request rejected.");
+ }
+}
+
+async function readJson(request) {
+ const contentType = request.headers["content-type"]?.split(";", 1)[0].trim().toLowerCase();
+ if (contentType !== "application/json") {
+ throw httpError(415, "UNSUPPORTED_MEDIA_TYPE", "Content-Type must be application/json.");
+ }
+ const chunks = [];
+ let size = 0;
+ for await (const chunk of request) {
+ size += chunk.length;
+ if (size > 1_000_000) {
+ throw httpError(413, "BODY_TOO_LARGE", "Request body is too large.");
+ }
+ chunks.push(chunk);
+ }
+ try {
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
+ } catch {
+ throw httpError(400, "INVALID_JSON", "Request body must be valid JSON.");
+ }
+}
+
+function validateOnboardBody(body) {
+ assertObject(body);
+ optionalType(body, "apiKey", "string");
+ optionalType(body, "socaiBin", "string");
+ optionalType(body, "installCli", "boolean");
+ optionalType(body, "verify", "boolean");
+}
+
+function validateSearchBody(body) {
+ assertObject(body);
+ if (typeof body.query !== "string") throw httpError(400, "INVALID_BODY", "query must be a string.");
+ optionalType(body, "platform", "string");
+ optionalType(body, "limit", "number");
+}
+
+function assertObject(body) {
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
+ throw httpError(400, "INVALID_BODY", "Request body must be a JSON object.");
+ }
+}
+
+function optionalType(body, key, type) {
+ if (body[key] !== undefined && typeof body[key] !== type) {
+ throw httpError(400, "INVALID_BODY", `${key} must be a ${type}.`);
+ }
+}
+
+function httpError(status, code, message) {
+ const error = new Error(message);
+ error.status = status;
+ error.code = code;
+ return error;
+}
+
+function sendJson(response, status, value) {
+ const body = `${JSON.stringify(value)}\n`;
+ response.writeHead(status, {
+ "Content-Type": "application/json; charset=utf-8",
+ "Content-Length": Buffer.byteLength(body),
+ "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff",
+ });
+ response.end(body);
+}
+
+function openBrowser(url) {
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
+ const child = spawn(command, args, { detached: true, stdio: "ignore", windowsHide: true });
+ child.on("error", (error) => console.warn(`Could not open browser automatically: ${error.message}`));
+ child.unref();
+}
diff --git a/src/socai.js b/src/socai.js
new file mode 100644
index 0000000..9750271
--- /dev/null
+++ b/src/socai.js
@@ -0,0 +1,274 @@
+import { AppError } from "./errors.js";
+import { configuredSocaiBin, defaultInstalledSocaiBin } from "./config.js";
+import { formatCommand, runProcess } from "./process.js";
+
+const PLATFORMS = ["instagram", "tiktok"];
+
+export async function resolveSocaiBin(config = {}, env = process.env) {
+ return configuredSocaiBin(config, env) || (await defaultInstalledSocaiBin());
+}
+
+export async function probeSocai(config = {}, env = process.env) {
+ const bin = await resolveSocaiBin(config, env);
+ try {
+ const root = await runProcess(bin, ["--help"], { timeoutMs: 15_000, env });
+ if (root.code !== 0) {
+ return { installed: false, bin, error: concise(root.stderr || root.stdout) };
+ }
+ const capabilities = {};
+ await Promise.all(
+ PLATFORMS.map(async (platform) => {
+ capabilities[platform] = await platformSupported(bin, platform, env);
+ }),
+ );
+ return { installed: true, bin, capabilities };
+ } catch (error) {
+ return { installed: false, bin, error: error.code === "ENOENT" ? "socai executable not found" : error.message };
+ }
+}
+
+export async function platformSupported(bin, platform, env = process.env, signal) {
+ try {
+ const result = await runProcess(bin, [platform, "--help"], { timeoutMs: 15_000, env, signal });
+ if (result.aborted) throw abortedError();
+ return result.code === 0 && /\bsearch\b/i.test(`${result.stdout}\n${result.stderr}`);
+ } catch (error) {
+ if (error?.code === "SOCAI_ABORTED" || error?.name === "AbortError") throw abortedError();
+ return false;
+ }
+}
+
+export function buildSearchArgs(platform, query, limit) {
+ if (!PLATFORMS.includes(platform)) {
+ throw new AppError(`Unsupported socai site: ${platform}`, { code: "INVALID_PLATFORM" });
+ }
+ const count = Number(limit);
+ if (!Number.isInteger(count) || count < 1 || count > 100) {
+ throw new AppError("limit must be an integer between 1 and 100.", { code: "INVALID_LIMIT" });
+ }
+ return [platform, "search", query, "--num", String(count), "--pretty"];
+}
+
+export function buildTikTokVideoArgs(locators, { numComments = 8 } = {}) {
+ const videos = [...new Set(locators.filter((value) => typeof value === "string" && value.trim()).map((value) => value.trim()))];
+ if (!videos.length) {
+ throw new AppError("TikTok video hydration requires at least one video URL or ID.", {
+ code: "MISSING_VIDEO_LOCATOR",
+ });
+ }
+ const comments = Number(numComments);
+ if (!Number.isInteger(comments) || comments < 0 || comments > 100) {
+ throw new AppError("numComments must be an integer between 0 and 100.", {
+ code: "INVALID_COMMENT_LIMIT",
+ });
+ }
+ return [
+ "tiktok",
+ "get-videos",
+ ...videos.flatMap((video) => ["--video", video]),
+ "--num-comments",
+ String(comments),
+ "--download-media",
+ "--pretty",
+ ];
+}
+
+export function buildResearchArgs(platform, task, { maxSteps = 12 } = {}) {
+ if (!PLATFORMS.includes(platform)) {
+ throw new AppError(`Unsupported socai site: ${platform}`, { code: "INVALID_PLATFORM" });
+ }
+ const steps = Number(maxSteps);
+ if (!Number.isInteger(steps) || steps < 1 || steps > 30) {
+ throw new AppError("maxSteps must be an integer between 1 and 30.", {
+ code: "INVALID_MAX_STEPS",
+ });
+ }
+ const goal = String(task || "").trim();
+ if (!goal) {
+ throw new AppError("Research task cannot be empty.", { code: "EMPTY_QUERY" });
+ }
+ return ["research", goal, "--platform", platform, "--max-steps", String(steps), "--pretty"];
+}
+
+export async function runSocaiSearch({
+ config = {},
+ env = process.env,
+ platform,
+ query,
+ limit = 10,
+ onProgress,
+ signal,
+}) {
+ const bin = await resolveSocaiBin(config, env);
+ if (!(await platformSupported(bin, platform, env, signal))) {
+ throw new AppError(
+ `This socai binary does not expose '${platform} search'. Install a compatible build or set SOCAI_BIN.`,
+ {
+ code: "SOCAI_CAPABILITY_MISSING",
+ details: { bin, platform },
+ },
+ );
+ }
+
+ return runSocaiJson(bin, buildSearchArgs(platform, query, limit), { env, onProgress, signal });
+}
+
+export async function runSocaiResearch({
+ config = {},
+ env = process.env,
+ platform,
+ task,
+ maxSteps = 12,
+ onProgress,
+ signal,
+}) {
+ const bin = await resolveSocaiBin(config, env);
+ const capability = await runProcess(bin, ["research", "--help"], {
+ timeoutMs: 15_000,
+ env,
+ signal,
+ }).catch((error) => {
+ if (error?.name === "AbortError") throw abortedError();
+ return null;
+ });
+ if (capability?.aborted) throw abortedError();
+ if (!capability || capability.code !== 0) {
+ throw new AppError("This socai binary does not expose 'socai research'. Build the dev-compatible CLI or set SOCAI_BIN.", {
+ code: "SOCAI_RESEARCH_CAPABILITY_MISSING",
+ details: { bin },
+ });
+ }
+ return runSocaiJson(bin, buildResearchArgs(platform, task, { maxSteps }), {
+ env,
+ onProgress,
+ signal,
+ timeoutMs: 20 * 60_000,
+ });
+}
+
+export async function runSocaiTikTokVideos({
+ config = {},
+ env = process.env,
+ locators,
+ numComments = 8,
+ onProgress,
+ signal,
+}) {
+ const bin = await resolveSocaiBin(config, env);
+ const capability = await runProcess(bin, ["tiktok", "get-videos", "--help"], {
+ timeoutMs: 15_000,
+ env,
+ signal,
+ }).catch((error) => {
+ if (error?.name === "AbortError") throw abortedError();
+ return null;
+ });
+ if (capability?.aborted) throw abortedError();
+ if (!capability || capability.code !== 0) {
+ throw new AppError("This socai binary does not expose 'tiktok get-videos'. Install the dev-compatible build or set SOCAI_BIN.", {
+ code: "SOCAI_VIDEO_CAPABILITY_MISSING",
+ details: { bin },
+ });
+ }
+ return runSocaiJson(bin, buildTikTokVideoArgs(locators, { numComments }), {
+ env,
+ onProgress,
+ signal,
+ timeoutMs: 12 * 60_000,
+ });
+}
+
+async function runSocaiJson(bin, args, { env, onProgress, signal, timeoutMs = 8 * 60_000 }) {
+ const command = formatCommand(bin, args);
+ const startedAt = Date.now();
+ let result;
+ try {
+ result = await runProcess(bin, args, {
+ timeoutMs,
+ env: { ...env, NO_COLOR: "1" },
+ onStderr: onProgress,
+ signal,
+ });
+ } catch (error) {
+ throw new AppError(`Could not start socai CLI: ${error.message}`, {
+ code: "SOCAI_NOT_FOUND",
+ details: { bin },
+ });
+ }
+
+ if (result.aborted) {
+ throw new AppError("socai CLI was cancelled because the client disconnected.", {
+ code: "SOCAI_ABORTED",
+ status: 499,
+ });
+ }
+
+ if (result.timedOut) {
+ throw new AppError(`socai CLI timed out after ${Math.round(timeoutMs / 60_000)} minutes.`, {
+ code: "SOCAI_TIMEOUT",
+ status: 504,
+ details: { command },
+ });
+ }
+ if (result.overflowed) {
+ throw new AppError("socai CLI output exceeded the 24 MB safety limit.", {
+ code: "SOCAI_OUTPUT_TOO_LARGE",
+ details: { command },
+ });
+ }
+ if (result.code !== 0) {
+ throw new AppError(`socai CLI failed: ${concise(result.stderr || result.stdout)}`, {
+ code: "SOCAI_FAILED",
+ status: 502,
+ details: { command, exitCode: result.code, ...(result.signal ? { signal: result.signal } : {}) },
+ });
+ }
+
+ return {
+ command,
+ exitCode: result.code,
+ elapsedMs: Date.now() - startedAt,
+ stdout: result.stdout,
+ stderr: result.stderr,
+ data: parseJsonOutput(result.stdout),
+ };
+}
+
+export function parseJsonOutput(output) {
+ const trimmed = output.trim();
+ if (!trimmed) {
+ throw new AppError("socai CLI returned no JSON output.", {
+ code: "EMPTY_SOCAI_OUTPUT",
+ status: 502,
+ });
+ }
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ for (let index = 0; index < trimmed.length; index += 1) {
+ if (trimmed[index] !== "{" && trimmed[index] !== "[") continue;
+ try {
+ return JSON.parse(trimmed.slice(index));
+ } catch {
+ // Keep looking for the start of a trailing JSON document.
+ }
+ }
+ }
+ throw new AppError("socai CLI output was not valid JSON.", {
+ code: "INVALID_SOCAI_OUTPUT",
+ status: 502,
+ details: { preview: concise(trimmed, 500) },
+ });
+}
+
+function concise(value, maxLength = 800) {
+ const normalized = String(value || "unknown error").replace(/\s+/g, " ").trim();
+ return normalized.length > maxLength ? `${normalized.slice(0, maxLength)}…` : normalized;
+}
+
+function abortedError() {
+ return new AppError("socai CLI was cancelled because the client disconnected.", {
+ code: "SOCAI_ABORTED",
+ status: 499,
+ });
+}
diff --git a/test/app.test.js b/test/app.test.js
new file mode 100644
index 0000000..64be59f
--- /dev/null
+++ b/test/app.test.js
@@ -0,0 +1,145 @@
+import assert from "node:assert/strict";
+import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { runSearch } from "../src/app.js";
+
+test("runSearch gives Jev the original request and socai the literal query", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-app-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "research" && args[1] === "--help") console.log("Run research");
+else if (args[0] === "research") {
+ console.error('@@SOCAI_EVENT@@' + JSON.stringify({ type: "evidence", items: [
+ { shortcode: "live-1", caption: "Live captured evidence", thumbnail_url: "https://cdn.example/live.jpg", local_path: "/tmp/private/video.mp4", url: "https://www.instagram.com/p/live-1/" }
+ ] }));
+ console.error('@@SOCAI_EVENT@@' + JSON.stringify({ type: "evidence", items: [1, 2, 3, 4].map((id) => ({
+ shortcode: "local-only-" + id,
+ caption: "Downloaded without a browser URL",
+ video: { local_path: "/tmp/private/" + id + ".mp4" },
+ url: "https://www.instagram.com/reel/local-only-" + id + "/"
+ })) }));
+ console.error("run_dir: /tmp/private/research-run");
+ console.error("2026-09-19T00:00:00Z WARN browser: internal diagnostic");
+ console.error("at <anonymous>:17:26");
+ console.log(JSON.stringify({ ok: true, report: "# Report\\nThree-angle research complete.", evidence: [
+ { shortcode: "no-preview", caption: "No preview", url: "https://www.instagram.com/p/no-preview/" },
+ { shortcode: "recovered-1", caption: "Recovered agent evidence", thumbnail_url: "https://cdn.example/1.jpg", url: "https://www.instagram.com/p/recovered-1/" },
+ { shortcode: "recovered-2", title: "Preview two", image_url: "https://cdn.example/2.jpg", url: "https://www.instagram.com/p/recovered-2/" },
+ { shortcode: "recovered-3", title: "Preview three", media: [{ type: "image", url: "https://cdn.example/3.jpg" }], url: "https://www.instagram.com/p/recovered-3/" },
+ { shortcode: "recovered-4", title: "Preview four", media: [{ type: "video", url: "https://cdn.example/4.mp4" }], url: "https://www.instagram.com/reel/recovered-4/" }
+] }));
+}
+else if (args[1] === "--help") console.log("Commands: search");
+else if (args[1] === "search") console.log(JSON.stringify({ ok: true, query: args[2], results: [] }));
+else console.log("socai mock");
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ let decisionRequest;
+ const client = {
+ async systemOne(request) {
+ decisionRequest = request;
+ return {
+ model: "typesafe/jev-test",
+ answers: {
+ route: {
+ type: "choice",
+ choice: "instagram_search",
+ confidence: 0.9,
+ probabilities: { instagram_search: 0.9, tiktok_search: 0.05, unsupported: 0.05 },
+ },
+ },
+ };
+ },
+ };
+
+ try {
+ const env = { ...process.env, JEV_SOCIAL_HOME: directory, SOCAI_BIN: mock };
+ const events = [];
+ const run = await runSearch(
+ { query: "search mr beasts on instagram", platform: "auto" },
+ { env, client, onEvent: (event) => events.push(event) },
+ );
+ assert.equal(decisionRequest.state.request, "search mr beasts on instagram");
+ assert.equal(run.request, "search mr beasts on instagram");
+ assert.equal(run.query, "mr beasts");
+ assert.equal(run.result.query, "mr beasts");
+ assert.equal(run.socaiExitCode, 0);
+ assert.match(run.evidenceCommand, /instagram search 'mr beasts' --num 4 --pretty$/);
+ assert.match(run.command, /research/);
+ assert.match(run.report, /Three-angle research complete/);
+ assert.equal(run.result.items.length, 4);
+ assert.ok(run.result.items.every((item) => item.shortcode !== "no-preview"));
+ assert.ok(run.result.items.every((item) => item.platform === "instagram"));
+ const live = events.find((event) => event.stage === "evidence" && event.items.some((item) => item.shortcode === "live-1"));
+ assert.ok(live, "research evidence should stream before the final result");
+ assert.equal(live.items[0].local_path, undefined);
+ const latestLive = events.filter((event) => event.stage === "evidence").at(-1);
+ assert.ok(latestLive.items.some((item) => item.shortcode === "live-1"), "later local-only captures must not evict a visible card");
+ assert.ok(latestLive.items.every((item) => item.thumbnail_url || item.image_url || item.video?.url));
+ assert.ok(events.every((event) => !String(event.message || "").includes("/tmp/private")));
+ assert.ok(events.every((event) => !String(event.message || "").startsWith("{")));
+ assert.ok(events.every((event) => !String(event.message || "").includes("internal diagnostic")));
+ assert.ok(events.every((event) => !String(event.message || "").startsWith("at <anonymous>")));
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("runSearch continues TikTok cards into detail reading and real media download", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-video-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "research" && args[1] === "--help") console.log("Run research");
+else if (args[0] === "research") console.log(JSON.stringify({ ok: true, report: "# Report\\nVideo research complete." }));
+else if (args.includes("--help")) console.log("Commands: search get-videos");
+else if (args[1] === "search") console.log(JSON.stringify({ ok: true, cards: [
+ { video_id: "123", url: "https://www.tiktok.com/@demo/video/123", title: "Unmatched card" },
+ { share_url: "https://www.tiktok.com/@demo/video/3123", title: "Matched card" }
+] }));
+else if (args[1] === "get-videos") {
+ if (!args.includes("--download-media")) process.exit(7);
+ console.error("downloading video media");
+ console.log(JSON.stringify({ ok: false, videos: [{ ok: true, locator: "3123", entity: { video_id: "3123", title: "Full post", author: "demo", video: { local_path: "/tmp/video.mp4" } } }] }));
+} else console.log("socai mock");
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+ const client = {
+ async systemOne() {
+ return {
+ model: "typesafe/jev-test",
+ answers: { route: { type: "choice", choice: "tiktok_search", confidence: 0.99 } },
+ };
+ },
+ };
+ const events = [];
+ try {
+ const env = { ...process.env, JEV_SOCIAL_HOME: directory, SOCAI_BIN: mock };
+ const run = await runSearch(
+ { query: "find demo videos on TikTok", platform: "auto", limit: 1 },
+ { env, client, onEvent: (event) => events.push(event) },
+ );
+ assert.equal(run.result.items.length, 1);
+ assert.equal(run.result.items[0].title, "Full post");
+ assert.equal(run.result.items[0].video.local_path, "/tmp/video.mp4");
+ assert.match(run.finalSocaiOutput, /Video research complete/);
+ assert.equal(run.socaiOutputs.length, 3);
+ assert.ok(events.some((event) => event.stage === "downloading"));
+ assert.ok(events.some((event) => event.stage === "researching"));
+ assert.ok(events.some((event) => /downloading video media/.test(event.message)));
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/classifier.test.js b/test/classifier.test.js
new file mode 100644
index 0000000..3e68e40
--- /dev/null
+++ b/test/classifier.test.js
@@ -0,0 +1,119 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { classifySearch } from "../src/classifier.js";
+
+test("classifySearch routes a search with Jev's structured answer", async () => {
+ let request;
+ const client = {
+ async systemOne(value) {
+ request = value;
+ return {
+ model: "jev-test",
+ answers: {
+ route: {
+ type: "choice",
+ choice: "tiktok_search",
+ confidence: 0.91,
+ probabilities: { instagram_search: 0.04, tiktok_search: 0.94, unsupported: 0.02 },
+ },
+ },
+ };
+ },
+ };
+
+ const result = await classifySearch({
+ goal: "find AI creators",
+ requestedPlatform: "tiktok",
+ client,
+ });
+
+ assert.equal(result.platform, "tiktok");
+ assert.equal(result.route, "tiktok_search");
+ assert.equal(request.state.requested_platform, "tiktok");
+ assert.equal(request.questions.route.type, "choice");
+});
+
+test("classifySearch calls OpenRouter's Decisions endpoint", async () => {
+ let url;
+ let options;
+ const result = await classifySearch({
+ goal: "search Instagram for design systems",
+ apiKey: "test-key",
+ fetchImpl: async (nextUrl, nextOptions) => {
+ url = nextUrl;
+ options = nextOptions;
+ return new Response(
+ JSON.stringify({
+ model: "typesafe/jev-test",
+ answers: { route: { type: "choice", choice: "instagram_search", confidence: 0.9 } },
+ usage: {},
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+ },
+ });
+ assert.equal(url, "https://openrouter.ai/api/alpha/decisions");
+ assert.match(options.headers.Authorization, /^Bearer /);
+ assert.equal(JSON.parse(options.body).model, "~typesafe/jev-latest");
+ assert.equal(result.platform, "instagram");
+});
+
+test("classifySearch rejects unknown platforms before any model call", async () => {
+ await assert.rejects(
+ classifySearch({ goal: "query", requestedPlatform: "youtube", client: {} }),
+ (error) => error.code === "INVALID_PLATFORM",
+ );
+});
+
+test("classifySearch preserves Jev unsupported decisions", async () => {
+ const client = {
+ async systemOne() {
+ return {
+ answers: {
+ route: {
+ type: "choice",
+ choice: "unsupported",
+ confidence: 0.8,
+ probabilities: { instagram_search: 0.1, tiktok_search: 0.1, unsupported: 0.8 },
+ },
+ },
+ };
+ },
+ };
+ const result = await classifySearch({ goal: "send a message", client });
+ assert.equal(result.platform, null);
+ assert.equal(result.route, "unsupported");
+});
+
+test("classifySearch never lets Jev override an explicit platform", async () => {
+ const client = {
+ async systemOne() {
+ return {
+ answers: {
+ route: {
+ type: "choice",
+ choice: "tiktok_search",
+ confidence: 0.9,
+ probabilities: { instagram_search: 0.05, tiktok_search: 0.9, unsupported: 0.05 },
+ },
+ },
+ };
+ },
+ };
+ await assert.rejects(
+ classifySearch({ goal: "find creators", requestedPlatform: "instagram", client }),
+ (error) => error.code === "JEV_ROUTE_MISMATCH",
+ );
+});
+
+test("classifySearch fails closed on a malformed Jev decision", async () => {
+ const client = {
+ async systemOne() {
+ return { answers: { route: { type: "choice", choice: "tiktok_search" } } };
+ },
+ };
+ await assert.rejects(
+ classifySearch({ goal: "find creators", client }),
+ (error) => error.code === "INVALID_JEV_RESPONSE",
+ );
+});
diff --git a/test/config.test.js b/test/config.test.js
new file mode 100644
index 0000000..fcb926d
--- /dev/null
+++ b/test/config.test.js
@@ -0,0 +1,21 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm, stat } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { getConfigPath, readConfig, writeConfig } from "../src/config.js";
+
+test("config is round-tripped with owner-only permissions", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-config-"));
+ const env = { JEV_SOCIAL_HOME: directory };
+ try {
+ await writeConfig({ openrouterApiKey: "secret" }, env);
+ assert.deepEqual(await readConfig(env), { openrouterApiKey: "secret" });
+ if (process.platform !== "win32") {
+ const mode = (await stat(getConfigPath(env))).mode & 0o777;
+ assert.equal(mode, 0o600);
+ }
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/env.test.js b/test/env.test.js
new file mode 100644
index 0000000..a3bb92b
--- /dev/null
+++ b/test/env.test.js
@@ -0,0 +1,9 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { parseEnv } from "../src/env.js";
+
+test("parseEnv reads the lowercase OpenRouter key format without evaluating shell code", () => {
+ assert.deepEqual(parseEnv("# local\nopenrouter='secret-value'\nINVALID LINE\n"), {
+ openrouter: "secret-value",
+ });
+});
diff --git a/test/onboard.test.js b/test/onboard.test.js
new file mode 100644
index 0000000..0fd8651
--- /dev/null
+++ b/test/onboard.test.js
@@ -0,0 +1,24 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { readConfig } from "../src/config.js";
+import { saveOnboarding } from "../src/onboard.js";
+
+test("environment-only OpenRouter keys are not persisted during onboarding", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-onboard-"));
+ const env = {
+ ...process.env,
+ JEV_SOCIAL_HOME: directory,
+ OPENROUTER_API_KEY: "environment-only-secret",
+ SOCAI_BIN: path.join(directory, "missing-socai"),
+ };
+ try {
+ await saveOnboarding({ verify: false, persistApiKey: false, env });
+ const config = await readConfig(env);
+ assert.equal(config.openrouterApiKey, undefined);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/process.test.js b/test/process.test.js
new file mode 100644
index 0000000..0afc768
--- /dev/null
+++ b/test/process.test.js
@@ -0,0 +1,105 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { childEnvironment, formatCommand, runProcess } from "../src/process.js";
+
+test("formatCommand shell-quotes substitutions in its display string", () => {
+ assert.equal(formatCommand("socai", ["instagram", "search", "$(echo injected)"]), "socai instagram search '$(echo injected)'");
+ assert.equal(formatCommand("socai", ["instagram", "search", "it's here"]), "socai instagram search 'it'\"'\"'s here'");
+});
+
+test("runProcess preserves signal termination without fabricating an exit code", async () => {
+ if (process.platform === "win32") return;
+ const result = await runProcess(process.execPath, ["-e", 'process.kill(process.pid, "SIGTERM")']);
+ assert.equal(result.code, null);
+ assert.equal(result.signal, "SIGTERM");
+});
+
+test("childEnvironment forwards socai/runtime settings but strips API credentials", () => {
+ const value = childEnvironment({
+ PATH: "/bin",
+ HOME: "/tmp/home",
+ SOCAI_HOME: "/tmp/socai",
+ SOCAI_API_KEY: "secret-3",
+ SOCAI_SESSION_TOKEN: "secret-4",
+ TYPESAFE_API_KEY: "secret",
+ OPENROUTER_API_KEY: "secret-2",
+ });
+ assert.deepEqual(value, { PATH: "/bin", HOME: "/tmp/home", SOCAI_HOME: "/tmp/socai" });
+});
+
+test("runProcess force-kills a child that ignores SIGTERM", async () => {
+ const startedAt = Date.now();
+ const result = await runProcess(
+ process.execPath,
+ ["-e", "process.on('SIGTERM',()=>{}); setInterval(()=>{},1000)"],
+ { timeoutMs: 80, killGraceMs: 80 },
+ );
+ assert.equal(result.timedOut, true);
+ assert.ok(Date.now() - startedAt < 3_000, "timeout should settle after the force-kill grace period");
+});
+
+test("runProcess force-kills output that exceeds the configured limit", async () => {
+ const result = await runProcess(
+ process.execPath,
+ ["-e", "process.stdout.write('x'.repeat(10000)); process.on('SIGTERM',()=>{}); setInterval(()=>{},1000)"],
+ { timeoutMs: 5_000, killGraceMs: 80, maxOutputBytes: 100 },
+ );
+ assert.equal(result.overflowed, true);
+});
+
+test("runProcess kills resistant descendants after the group leader exits", async () => {
+ const parent = `
+ const { spawn } = require("node:child_process");
+ spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>{}); console.log('ready'); setInterval(()=>{},1000)"], {
+ stdio: ["ignore", "inherit", "inherit"]
+ });
+ process.on("SIGTERM", () => process.exit(0));
+ setInterval(() => {}, 1000);
+ `;
+ const startedAt = Date.now();
+ const result = await runProcess(process.execPath, ["-e", parent], {
+ timeoutMs: 200,
+ killGraceMs: 80,
+ });
+ assert.equal(result.timedOut, true);
+ assert.match(result.stdout, /ready/);
+ assert.ok(Date.now() - startedAt < 2_000, "descendant should be killed with the original process group");
+});
+
+test("runProcess frames UTF-8 stderr progress by complete lines", async () => {
+ const progress = [];
+ const script = `
+ const value = Buffer.from("progress ✓\\nlast ✓", "utf8");
+ for (const byte of value) process.stderr.write(Buffer.from([byte]));
+ `;
+ const result = await runProcess(process.execPath, ["-e", script], {
+ onStderr: (line) => progress.push(line),
+ });
+ assert.equal(result.code, 0);
+ assert.deepEqual(progress, ["progress ✓", "last ✓"]);
+});
+
+test("runProcess terminates the process tree when aborted", async () => {
+ if (process.platform === "win32") return;
+ const controller = new AbortController();
+ const script = `
+ const { spawn } = require("node:child_process");
+ const descendant = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>{}); setInterval(()=>{},1000)"], {
+ stdio: "ignore"
+ });
+ console.log(descendant.pid);
+ process.on("SIGTERM", () => process.exit(0));
+ setInterval(() => {}, 1000);
+ `;
+ const pending = runProcess(
+ process.execPath,
+ ["-e", script],
+ { signal: controller.signal, killGraceMs: 60, timeoutMs: 5_000 },
+ );
+ setTimeout(() => controller.abort(), 180);
+ const result = await pending;
+ assert.equal(result.aborted, true);
+ const descendantPid = Number(result.stdout.trim());
+ await new Promise((resolve) => setTimeout(resolve, 140));
+ assert.throws(() => process.kill(descendantPid, 0), { code: "ESRCH" });
+});
diff --git a/test/query.test.js b/test/query.test.js
new file mode 100644
index 0000000..f8352df
--- /dev/null
+++ b/test/query.test.js
@@ -0,0 +1,35 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { extractSearchQuery } from "../src/query.js";
+
+test("extractSearchQuery removes English platform-routing language", () => {
+ assert.equal(extractSearchQuery("search mr beasts on instagram"), "mr beasts");
+ assert.equal(extractSearchQuery("Search for Mr Beast on Instagram"), "Mr Beast");
+ assert.equal(extractSearchQuery("search Instagram for AI creators"), "AI creators");
+ assert.equal(extractSearchQuery("find wearable reviews on TikTok and return 10 results"), "wearable reviews");
+ assert.equal(extractSearchQuery("Find AI creators on TikTok, then return 10 results"), "AI creators");
+ assert.equal(extractSearchQuery("Could you search Instagram for AI creators?"), "AI creators");
+ assert.equal(extractSearchQuery("Could you please search Instagram for AI creators?"), "AI creators");
+ assert.equal(extractSearchQuery("Find me AI creators on TikTok"), "AI creators");
+ assert.equal(extractSearchQuery("Search for AI creators on Instagram please"), "AI creators");
+ assert.equal(extractSearchQuery("Search Instagram for AI creators please"), "AI creators");
+ assert.equal(extractSearchQuery("look up 'new design tools' on instagram"), "new design tools");
+});
+
+test("extractSearchQuery removes Chinese platform-routing language", () => {
+ assert.equal(extractSearchQuery("在 Instagram 搜索 Mr Beast"), "Mr Beast");
+ assert.equal(
+ extractSearchQuery("在 TikTok 上搜索 AI wearable creators,返回 10 条高质量结果"),
+ "AI wearable creators",
+ );
+ assert.equal(extractSearchQuery("搜索 Instagram 上的 Mr Beast"), "Mr Beast");
+ assert.equal(extractSearchQuery("在 TikTok 上帮我搜索 AI creators,返回 10 条结果"), "AI creators");
+ assert.equal(extractSearchQuery("请帮我搜索一下 Instagram 上的 AI creators"), "AI creators");
+ assert.equal(extractSearchQuery("在 TikTok 上搜索 AI creators 返回 10 条结果"), "AI creators");
+ assert.equal(extractSearchQuery("在 TikTok 搜索 AI creators 并返回 10 条结果"), "AI creators");
+});
+
+test("extractSearchQuery preserves an already literal search term", () => {
+ assert.equal(extractSearchQuery("instagram marketing tips"), "instagram marketing tips");
+ assert.equal(extractSearchQuery("mr beast"), "mr beast");
+});
diff --git a/test/server.test.js b/test/server.test.js
new file mode 100644
index 0000000..c38add7
--- /dev/null
+++ b/test/server.test.js
@@ -0,0 +1,77 @@
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { saveRun } from "../src/runs.js";
+import { startServer } from "../src/server.js";
+
+test("local APIs require exact same-origin JSON and typed onboarding fields", async () => {
+ const { server, url } = await startServer({ port: 0, open: false });
+ try {
+ const status = await fetch(`${url}/api/status`);
+ assert.equal(status.status, 200);
+
+ const wrongOrigin = await fetch(`${url}/api/onboard`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Origin: "http://127.0.0.1:9",
+ },
+ body: "{}",
+ });
+ assert.equal(wrongOrigin.status, 403);
+
+ const wrongType = await fetch(`${url}/api/onboard`, {
+ method: "POST",
+ headers: { "Content-Type": "text/plain", Origin: url },
+ body: "{}",
+ });
+ assert.equal(wrongType.status, 415);
+
+ const coercedInstall = await fetch(`${url}/api/onboard`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Origin: url },
+ body: JSON.stringify({ installCli: "false" }),
+ });
+ assert.equal(coercedInstall.status, 400);
+ const payload = await coercedInstall.json();
+ assert.equal(payload.error.code, "INVALID_BODY");
+ } finally {
+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
+ }
+});
+
+test("saved socai media is exposed through an opaque range-capable local URL", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-media-"));
+ const socaiHome = path.join(directory, "socai");
+ const jevHome = path.join(directory, "jev");
+ const mediaPath = path.join(socaiHome, "runs", "capture", "site_media", "video.mp4");
+ await mkdir(path.dirname(mediaPath), { recursive: true });
+ await writeFile(mediaPath, "0123456789");
+ const env = { ...process.env, SOCAI_HOME: socaiHome, JEV_SOCIAL_HOME: jevHome };
+ await saveRun({ id: "media-test", result: { items: [{ video: { local_path: mediaPath } }] } }, env);
+ const { server, url } = await startServer({ port: 0, open: false, env });
+ try {
+ const runResponse = await fetch(`${url}/api/runs/media-test`);
+ assert.equal(runResponse.status, 200);
+ const run = await runResponse.json();
+ assert.match(run.result.items[0].video.browser_url, /^\/media\/[A-Za-z0-9_-]+$/);
+
+ const mediaResponse = await fetch(`${url}${run.result.items[0].video.browser_url}`, {
+ headers: { Range: "bytes=2-5" },
+ });
+ assert.equal(mediaResponse.status, 206);
+ assert.equal(mediaResponse.headers.get("content-range"), "bytes 2-5/10");
+ assert.equal(await mediaResponse.text(), "2345");
+
+ await rename(mediaPath, `${mediaPath}.original`);
+ await writeFile(mediaPath, "abcdefghij");
+ const swappedResponse = await fetch(`${url}${run.result.items[0].video.browser_url}`);
+ assert.equal(swappedResponse.status, 410);
+ assert.equal((await swappedResponse.json()).error.code, "MEDIA_CHANGED");
+ } finally {
+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/socai.test.js b/test/socai.test.js
new file mode 100644
index 0000000..eda1060
--- /dev/null
+++ b/test/socai.test.js
@@ -0,0 +1,165 @@
+import assert from "node:assert/strict";
+import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import {
+ buildResearchArgs,
+ buildSearchArgs,
+ buildTikTokVideoArgs,
+ parseJsonOutput,
+ probeSocai,
+ runSocaiResearch,
+ runSocaiSearch,
+} from "../src/socai.js";
+
+test("buildSearchArgs owns the stable socai CLI contract", () => {
+ assert.deepEqual(buildSearchArgs("tiktok", "AI creator", 12), [
+ "tiktok",
+ "search",
+ "AI creator",
+ "--num",
+ "12",
+ "--pretty",
+ ]);
+ assert.throws(() => buildSearchArgs("tiktok", "x", 0), /between 1 and 100/);
+});
+
+test("buildTikTokVideoArgs requests real media downloads for every result", () => {
+ assert.deepEqual(buildTikTokVideoArgs(["https://www.tiktok.com/@demo/video/123", "456"]), [
+ "tiktok",
+ "get-videos",
+ "--video",
+ "https://www.tiktok.com/@demo/video/123",
+ "--video",
+ "456",
+ "--num-comments",
+ "8",
+ "--download-media",
+ "--pretty",
+ ]);
+});
+
+test("buildResearchArgs owns the non-interactive agent contract", () => {
+ assert.deepEqual(buildResearchArgs("instagram", "Compare creator signals", { maxSteps: 8 }), [
+ "research",
+ "Compare creator signals",
+ "--platform",
+ "instagram",
+ "--max-steps",
+ "8",
+ "--pretty",
+ ]);
+ assert.throws(() => buildResearchArgs("instagram", "x", { maxSteps: 31 }), /between 1 and 30/);
+});
+
+test("runSocaiResearch streams progress and parses the report", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-research-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "research" && args[1] === "--help") console.log("Run research");
+else if (args[0] === "research") {
+ console.error("Research step 1");
+ console.log(JSON.stringify({ ok: true, report: "# Findings\\nEvidence-backed result." }));
+} else process.exitCode = 2;
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+ const progress = [];
+ try {
+ const result = await runSocaiResearch({
+ env: { ...process.env, SOCAI_BIN: mock },
+ platform: "instagram",
+ task: "Compare creators",
+ maxSteps: 6,
+ onProgress: (message) => progress.push(message),
+ });
+ assert.match(result.data.report, /Evidence-backed/);
+ assert.match(progress.join(""), /Research step 1/);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("parseJsonOutput accepts plain and warning-prefixed JSON", () => {
+ assert.deepEqual(parseJsonOutput('{"items":[1]}'), { items: [1] });
+ assert.deepEqual(parseJsonOutput('update available\n{\n "items": [2]\n}'), { items: [2] });
+});
+
+test("runSocaiSearch capability-checks and parses the real child process", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-test-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args.length === 1 && args[0] === "--help") {
+ console.log("socai mock");
+} else if (args[0] === "tiktok" && args[1] === "--help") {
+ console.log("Commands: search");
+} else if (args[0] === "instagram" && args[1] === "--help") {
+ process.exitCode = 2;
+} else if (args[0] === "tiktok" && args[1] === "search") {
+ console.error("reading TikTok");
+ console.log(JSON.stringify({ results: [{ title: args[2] }], received: args, leakedKey: process.env.OPENROUTER_API_KEY || null }));
+} else {
+ process.exitCode = 2;
+}
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ try {
+ const env = { ...process.env, SOCAI_BIN: mock, OPENROUTER_API_KEY: "must-not-leak" };
+ const status = await probeSocai({}, env);
+ assert.equal(status.installed, true);
+ assert.deepEqual(status.capabilities, { instagram: false, tiktok: true });
+
+ const progress = [];
+ const result = await runSocaiSearch({
+ env,
+ platform: "tiktok",
+ query: "wearable AI",
+ limit: 3,
+ onProgress: (message) => progress.push(message),
+ });
+ assert.equal(result.exitCode, 0);
+ assert.equal(result.data.results[0].title, "wearable AI");
+ assert.equal(result.data.leakedKey, null);
+ assert.match(result.command, /tiktok search/);
+ assert.match(progress.join(""), /reading TikTok/);
+
+ await assert.rejects(
+ runSocaiSearch({ env, platform: "instagram", query: "x", limit: 2 }),
+ (error) => error.code === "SOCAI_CAPABILITY_MISSING",
+ );
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("runSocaiSearch cancels an in-flight capability probe", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-abort-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(mock, "#!/usr/bin/env node\nsetInterval(() => {}, 1000);\n", { mode: 0o755 });
+ await chmod(mock, 0o755);
+ const controller = new AbortController();
+ try {
+ const pending = runSocaiSearch({
+ env: { ...process.env, SOCAI_BIN: mock },
+ platform: "tiktok",
+ query: "demo",
+ limit: 1,
+ signal: controller.signal,
+ });
+ setTimeout(() => controller.abort(), 80);
+ await assert.rejects(pending, (error) => error.code === "SOCAI_ABORTED");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});