Open-source, local-first social media research agent for Instagram, TikTok, and LinkedIn. Jev routes read-only steps; socai CLI captures cited browser evidence.
JavaScript agent-skillsai-agentsbrowser-agentbrowser-automationdecision-modeldeep-researchinstagramjevlinkedinlocal-firstopen-sourceosintresearch-agentsocaisocial-listeningsocial-mediasocial-media-researchsocmintsystem-onetiktok
feat: support local System One decisions (#45)
Asklv3618e81e7bf8
diff --git a/.env.example b/.env.exampleindex 20658f3..77830fc 100644--- a/.env.example+++ b/.env.example@@ -4,6 +4,12 @@ OPENROUTER_JEV_MODEL=~typesafe/jev-latest# Optional evidence-report synthesis model. Set to `off` for deterministic reports.OPENROUTER_REPORT_MODEL=openai/gpt-4o-mini+# Optional local TypeSafe-compatible decision endpoint, for example Kev.+# When set, routing does not require or forward an OpenRouter key.+# JEV_SOCIAL_SYSTEM_ONE_URL=http://127.0.0.1:8009/v1/systemone+# JEV_SOCIAL_SYSTEM_ONE_MODEL=kev-latest+# JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS=120000+# Optional path to a local or development socai binary.SOCAI_BIN=diff --git a/AGENTS.md b/AGENTS.mdindex 1063203..d2aad4a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -18,8 +18,9 @@ npm ci```Offline development and tests do not need credentials. A live run additionally-needs a local `.env` with an OpenRouter key that can access Jev, a compatible-`socai CLI`, and a browser session that can access the selected platform.+needs either an OpenRouter key that can access Jev or an explicit loopback+TypeSafe-compatible decision endpoint, a compatible `socai CLI`, and a browser+session that can access the selected platform.Never commit `.env`, API keys, browser data, downloaded media, run artifacts,or personal social-media data.@@ -44,8 +45,10 @@ workflow uses the same commands after `npm ci`.and `search`.- `src/app.js` owns the Jev decision loop, checkpoints, event stream, and finalrun shape.-- `src/classifier.js` calls the OpenRouter decisions endpoint and validates the- typed Jev response.+- `src/decision-provider.js` selects OpenRouter or an explicit loopback System+ One endpoint, bounds the network response, and prevents credential forwarding.+- `src/classifier.js` builds platform choices and validates typed decision+ responses independently of the selected provider.- `src/actions.js` builds the current finite action space from the goal,installed CLI capabilities, observed targets, and action history.- `src/socai.js` probes the installed CLI, maps selected actions to arguments,diff --git a/README.md b/README.mdindex 73de7b5..0040441 100644--- a/README.md+++ b/README.md@@ -79,9 +79,9 @@ These are individual local observations, not a benchmark or guaranteed latency.## Run it-Node 20+, an OpenRouter key with Jev access, and a current [socai](https://github.com/socai-io/socai) CLI.+Node 20+, a decision provider (OpenRouter Jev or a loopback Kev server), and a current [socai](https://github.com/socai-io/socai) CLI.-Fastest path — no repository clone required. Onboarding prompts for the key and offers to install the official socai CLI when it is missing:+Fastest OpenRouter path — no repository clone required. Onboarding prompts for the key and offers to install the official socai CLI when it is missing:```bashnpx github:socai-io/jev-social#v0.1.6 onboard@@ -119,6 +119,24 @@ cp .env.example .env # OPENROUTER_API_KEY=…npm start```+To run the decision loop through local [Kev](https://github.com/jaredpalmer/kev), start its TypeSafe-compatible server on loopback, then run the current Jev Social source checkout without an OpenRouter key:++```bash+git clone https://github.com/jaredpalmer/kev.git+cd kev+uv sync --extra serve+uv run --extra serve python -m kev.serve --run jaredpalmer/kev-4b --port 8009++# In the Jev Social checkout:+export JEV_SOCIAL_SYSTEM_ONE_URL=http://127.0.0.1:8009/v1/systemone+export JEV_SOCIAL_SYSTEM_ONE_MODEL=kev-latest+export JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS=120000+export OPENROUTER_REPORT_MODEL=off+npm start+```++The local endpoint must be plain HTTP on `localhost`, `127.0.0.1`, or `::1`, with the exact `/v1/systemone` path. Jev Social does not send the OpenRouter key to it, rejects redirects and oversized responses, and keeps the same typed choice validation. Local inference allows up to 120 seconds by default; lower it with `JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS`. `OPENROUTER_REPORT_MODEL=off` uses the deterministic source-linked report; the browser and social-platform traffic still runs through local `socai` and Chrome.+Opens `http://127.0.0.1:8766`. Loopback only. Leave the platform on **Jev · auto**, type a goal, watch the timer.```bashdiff --git a/SECURITY.md b/SECURITY.mdindex b22cfc1..65e1a97 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -20,8 +20,10 @@ Jev Social runs locally, but it is not an offline application.- Onboarding can send the OpenRouter key to `https://openrouter.ai/api/v1/auth/key` for validation.- Jev decisions send the research goal, requested platform, bounded action labels, observed source URLs, previous action summaries, and up to 400 characters of visible title, caption, text, or name for each captured item to OpenRouter's Decisions API. This content may contain public or personal social-media data. The request does not intentionally include raw socai JSON, downloaded media, browser cookies, or local filesystem paths.+- When `JEV_SOCIAL_SYSTEM_ONE_URL` is configured, the same bounded decision payload is sent instead to an explicit loopback-only TypeSafe-compatible endpoint such as Kev. Only plain HTTP on `localhost`, `127.0.0.1`, or `::1` with the exact `/v1/systemone` path is accepted. Redirects, URL credentials, query strings, fragments, non-loopback hosts, oversized responses, and malformed typed answers fail closed. The OpenRouter key is never attached to this local request.- Evidence-report synthesis is enabled by default and makes a second OpenRouter model call after collection. Its compact, bounded user payload is at most 48,000 characters and contains the research goal, selected platform, run status and stop reason, coverage counts, and at most 40 sanitized records: source URLs, titles, up to 1,000 characters of each author claim, up to five 300-character comment excerpts, observed engagement metadata, and capture depth. Set `OPENROUTER_REPORT_MODEL=off` to keep report generation deterministic and prevent this synthesis call. The synthesizer receives no browser or shell tools.- Provider-side storage and retention are governed by OpenRouter and the selected model provider, not this repository.+- A local decision server has its own model, log, and retention behavior. Jev Social neither starts nor downloads that server automatically. Set `OPENROUTER_REPORT_MODEL=off` if an OpenRouter key remains configured but the report must stay on the deterministic local path.- The installed socai CLI and Chrome connect to the selected social platform. Their browser and network behavior is maintained by [socai](https://github.com/socai-io/socai), outside the Jev Social process.### Keys and browser sessionsdiff --git a/bin/jev-social.js b/bin/jev-social.jsindex d593ef1..dfb9e51 100755--- a/bin/jev-social.js+++ b/bin/jev-social.js@@ -4,6 +4,7 @@ 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 { resolveDecisionProvider } from "../src/decision-provider.js";import { loadLocalEnv } from "../src/env.js";import { saveOnboarding } from "../src/onboard.js";import { probeSocai } from "../src/socai.js";@@ -29,6 +30,11 @@ Configuration (normally auto-loaded from .env):--install Install/reinstall official socai CLI--skip-install Do not offer CLI installation--no-verify Save API key without a network check++Local decision provider (environment only):+ JEV_SOCIAL_SYSTEM_ONE_URL Loopback /v1/systemone endpoint+ JEV_SOCIAL_SYSTEM_ONE_MODEL Model name (default: kev-latest)+ JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS Timeout in ms (default/max: 120000)`;try {@@ -41,11 +47,13 @@ try {await startServer({ port: flags.port || 8766, open: !flags.noOpen });} else if (command === "status") {const config = await readConfig();+ const provider = resolveDecisionProvider();console.log(JSON.stringify({- jevConfigured: Boolean(resolveApiKey(config)),- jevModel: process.env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",+ jevConfigured: provider.kind === "local" || Boolean(resolveApiKey(config)),+ jevModel: provider.model,+ decisionProvider: provider.kind,configPath: getConfigPath(),socai: await probeSocai(config, process.env, undefined, { includeReadiness: true }),},diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 2489c97..73420ab 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -50,8 +50,8 @@ By default (using `existing` or `managed` Chrome modes without external endpoint| **Browser connection failure** | `socai` cannot connect to Chrome or its DevTools protocol (CDP) endpoint. | The readiness strip shows `Chrome unavailable`, `Chrome permission needed`, `Chrome disconnected`, or `Remote browser unavailable` with a short local action. | Follow your active connection mode below. Ensure the target Chrome instance is running with remote debugging enabled and accept any remote-debugging permission prompts. Avoid blanket process-killing commands. || **Login-required / challenge gate** | The platform blocked unauthenticated access with a login modal, redirect (e.g. `authwall`), or CAPTCHA. | Status displays a partial result notice with the specific gate reason (for example, `Partial results · The platform requires attention: login_required`). | Open the platform in the specific user-accessible Chrome session or profile selected by `socai` (`existing` or `managed` mode), complete authentication or challenges, and verify browsing before re-running. (If using hosted `remote` mode, switch to `existing` or `managed` mode to authenticate interactively.) || **Valid empty result** | The platform loaded successfully and the search executed cleanly, but returned 0 matching records. | Evidence cards, table, and heading remain hidden. Depending on subsequent decisions, the run can finalize as `partial` (`Partial results · Jev stopped without usable evidence.`), `step_limit` (if max steps are reached), or `decision_failed` (if a subsequent model decision call fails). | The initial search executed cleanly without matching records on the platform. Broaden or rephrase your search query. (If a subsequent decision failed, verify model API connectivity). |-| **Early decision or classification failure** | Jev encountered an error during classification or the very first action decision before any browser operations ran. | Classification failures emit an error before a run exists. A first action-decision failure saves a failed checkpoint with no captured posts. | Ensure your query is a supported read-only social research goal, specify `--platform` explicitly, or check your OpenRouter key and network connection. |-| **Mid-run decision failure (`decision_failed`)** | A model decision call failed after one or more actions had already executed. | Status displays `Partial results · <error message>` with status `decision_failed`; collected evidence prior to the failure is preserved. | Check OpenRouter API connectivity, ensure model quota is available, or retry the request. |+| **Early decision or classification failure** | The configured decision provider encountered an error during classification or the first action choice before any browser operation ran. | Classification failures emit an error before a run exists. A first action-decision failure saves a failed checkpoint with no captured posts. | Ensure the goal is supported, specify `--platform` explicitly, then check the OpenRouter key or local System One server reported by status. |+| **Mid-run decision failure (`decision_failed`)** | The decision provider failed after one or more actions had already executed. | Status displays `Partial results · <error message>` with status `decision_failed`; collected evidence prior to the failure is preserved. | Check the configured provider, preserve the partial evidence, and retry only after the provider is healthy. |---@@ -61,7 +61,7 @@ Run these diagnostic commands to verify readiness without exposing API credentia### 1. Check Configuration & Capabilities-Jev Social resolves your OpenRouter key from `OPENROUTER_API_KEY`, lowercase `openrouter` in `.env`, or saved onboarding config (`config.json`). Checking only `$OPENROUTER_API_KEY` in your shell can falsely report "missing" when a key is already configured.+By default, Jev Social resolves an OpenRouter key from `OPENROUTER_API_KEY`, lowercase `openrouter` in `.env`, or saved onboarding config (`config.json`). A valid `JEV_SOCIAL_SYSTEM_ONE_URL` switches typed decisions to a loopback TypeSafe-compatible provider and does not require an OpenRouter key. Checking only `$OPENROUTER_API_KEY` can therefore misreport effective readiness.Query the local status endpoint to verify the effective `jevConfigured` state and platform capabilities:@@ -75,6 +75,7 @@ The browser API endpoint `/api/status` returns sanitized status and omits local{"jevConfigured": true,"jevModel": "~typesafe/jev-latest",+ "decisionProvider": "openrouter","socai": {"installed": true,"version": "0.6.0",@@ -123,6 +124,7 @@ Expected output:{"jevConfigured": true,"jevModel": "~typesafe/jev-latest",+ "decisionProvider": "openrouter","configPath": "/home/user/.jev-social/config.json","socai": {"installed": true,@@ -146,7 +148,29 @@ Expected output:> [!NOTE]> **Privacy note:** `npm start -- status` outputs `configPath` and `socai.bin` for local operator diagnostics. If sharing CLI output in public issues or chat, redact these local filesystem paths. The browser API endpoint (`/api/status`) automatically keeps paths sanitized.-### 2. Verify the Resolved `socai` Binary+### 2. Use a Local Kev Decision Server++Kev exposes the TypeSafe-compatible endpoint Jev Social needs. Start it separately, then set the exact loopback endpoint and model:++```bash+git clone https://github.com/jaredpalmer/kev.git+cd kev+uv sync --extra serve+uv run --extra serve python -m kev.serve --run jaredpalmer/kev-4b --port 8009+```++```bash+export JEV_SOCIAL_SYSTEM_ONE_URL=http://127.0.0.1:8009/v1/systemone+export JEV_SOCIAL_SYSTEM_ONE_MODEL=kev-latest+export JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS=120000+export OPENROUTER_REPORT_MODEL=off+npm start -- status+npm start+```++The sanitized status should report `"decisionProvider": "local"`, `"jevModel": "kev-latest"`, and `"jevConfigured": true` without showing the endpoint or port. The endpoint must use plain loopback HTTP and the exact `/v1/systemone` path. Jev Social refuses remote hosts, redirects, embedded credentials, query strings, and fragments. Local decisions use a 120-second default and maximum timeout; set `JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS` to a lower integer value when needed. `OPENROUTER_REPORT_MODEL=off` prevents a separately configured OpenRouter key from being used for optional report synthesis.++### 3. Verify the Resolved `socai` BinaryJev Social resolves the `socai` binary in the following order:1. `SOCAI_BIN` environment variable or `socaiBin` in `~/.jev-social/config.json`.@@ -161,7 +185,7 @@ Because resolution is not pinned to a single binary and may differ from what is/path/from-status --version```-### 3. Installing or Reinstalling `socai`+### 4. Installing or Reinstalling `socai`- **macOS & Windows**: Run automated onboarding to download and install the official release:```bashdiff --git a/package.json b/package.jsonindex 05a7f5b..9c0aea3 100644--- a/package.json+++ b/package.json@@ -29,7 +29,7 @@"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 ./src/evidence.js && node --check ./src/report.js && node --check ./public/app.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/report-stream.js && node --check ./public/prompts.js && node --check ./public/status.js",+ "check": "node --check ./bin/jev-social.js && node --check ./src/server.js && node --check ./src/decision-provider.js && node --check ./src/evidence.js && node --check ./src/report.js && node --check ./public/app.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/report-stream.js && node --check ./public/prompts.js && node --check ./public/status.js","test": "node --test"},"engines": {@@ -37,6 +37,7 @@},"keywords": ["jev",+ "kev","socai","instagram","tiktok",@@ -44,6 +45,7 @@"research","ai-agent","browser-automation",+ "local-llm","openrouter","social-media-research"],diff --git a/public/status.js b/public/status.jsindex 84dce80..9d8568b 100644--- a/public/status.js+++ b/public/status.js@@ -15,6 +15,9 @@ export function deriveStatusView(status = {}) {}const installed = Boolean(status.socai?.installed);+ const providerError = typeof status.decisionProviderError === "string"+ ? status.decisionProviderError.trim()+ : "";const available = PLATFORMS.filter((platform) => capabilities[platform]);const allReady = installed && available.length === PLATFORMS.length;let socaiLabel = "socai unavailable";@@ -26,12 +29,16 @@ export function deriveStatusView(status = {}) {}return {- error: "",+ error: providerError,capabilities,platforms: platformStatuses(capabilities, status.socai?.readiness?.platforms),jev: {ready: Boolean(status.jevConfigured),- label: status.jevConfigured ? "Jev ready" : "Jev needs a key",+ label: providerError+ ? "Decision provider unavailable"+ : status.jevConfigured+ ? status.decisionProvider === "local" ? "Local decision model ready" : "Jev ready"+ : "Jev needs a key",},socai: { ready: allReady, label: socaiLabel },browser: browserStatus(status.socai?.readiness, installed),diff --git a/site/index.html b/site/index.htmlindex 633ccc9..b56f4bd 100644--- a/site/index.html+++ b/site/index.html@@ -204,7 +204,7 @@<div class="run-copy"><div class="section-label">RUN LOCALLY</div><h2 id="run-heading">Your browser. Your session. Your evidence.</h2>- <p>Requires Node 20+, an OpenRouter key with Jev access, and the socai browser runtime. Prebuilt socai installers currently ship for macOS and Windows; Linux uses the documented Cargo source install.</p>+ <p>The tagged release uses OpenRouter Jev. Current source checkouts can also route decisions through a loopback Kev server. Both paths keep browser execution inside the socai runtime and the user's Chrome session.</p></div><div class="code-block"><div class="code-label">TERMINAL</div>diff --git a/site/llms.txt b/site/llms.txtindex 91577a2..cf6ca3e 100644--- a/site/llms.txt+++ b/site/llms.txt@@ -38,7 +38,7 @@ The HTTP server listens on `127.0.0.1`. State-changing requests require exact sa## Run locally-Requirements: Node.js 20+, an OpenRouter API key with Jev access, a current socai CLI, and a Chrome session that can access the selected platform.+Requirements: Node.js 20+, a current socai CLI, a Chrome session that can access the selected platform, and either an OpenRouter API key with Jev access or a current-source checkout configured with a loopback TypeSafe-compatible decision endpoint such as Kev.```bashnpx github:socai-io/jev-social#v0.1.6 onboard@@ -51,6 +51,8 @@ Direct non-interactive example:npx github:socai-io/jev-social#v0.1.6 search "find emerging design creators on Instagram" --platform auto --limit 4```+The tagged v0.1.6 commands above use OpenRouter. Current source checkouts can instead set `JEV_SOCIAL_SYSTEM_ONE_URL=http://127.0.0.1:8009/v1/systemone` and `JEV_SOCIAL_SYSTEM_ONE_MODEL=kev-latest` for local Kev routing. Only an exact loopback endpoint is accepted; OpenRouter credentials are not forwarded. Set `OPENROUTER_REPORT_MODEL=off` to keep report generation on the deterministic evidence path.+## Install as an Agent SkillGitHub CLI 2.101 or newer can install the immutable v0.1.6 skill for Codex:@@ -79,6 +81,7 @@ This is a standard Agent Skill that calls the local socai CLI, not an OpenCode p- The published 63.969-second report is one recorded local run, not a benchmark or speed guarantee.- Jev Social does not bypass login requirements, CAPTCHA, rate limits, or access controls.- Captured social content is untrusted evidence, never executable instructions.+- Local System One routing accepts only plain loopback HTTP, rejects redirects, and keeps the same typed-choice validation as OpenRouter routing.- Search-card claims and captions are not independently verified unless the report explicitly says otherwise.## Project linksdiff --git a/src/app.js b/src/app.jsindex a8ee0f3..602ffc7 100644--- a/src/app.js+++ b/src/app.js@@ -5,6 +5,7 @@ import { availableActions, chooseAction } from "./actions.js";import { evidenceReport, extractEvidence, mergeEvidence, publicEvidence, resultObservation } from "./evidence.js";import { AppError } from "./errors.js";import { readConfig, resolveApiKey } from "./config.js";+import { resolveDecisionProvider } from "./decision-provider.js";import { extractSearchQuery } from "./query.js";import {buildGroundedResearchReport,@@ -31,6 +32,7 @@ export async function runSearch(synthesizer,reportChunkDelayMs = 18,reportFetchImpl = fetch,+ decisionFetchImpl = fetch,} = {},) {const request = query?.trim();@@ -104,10 +106,13 @@ export async function runSearch(}const apiKey = resolveApiKey(config, env);- if (!apiKey && !client) throw new AppError("Set OPENROUTER_API_KEY first.", { code: "ONBOARDING_REQUIRED" });+ const provider = resolveDecisionProvider(env);+ if (!apiKey && !client && provider.kind !== "local") {+ throw new AppError("Set OPENROUTER_API_KEY first.", { code: "ONBOARDING_REQUIRED" });+ }const startedAt = Date.now();- const model = env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest";- const decisionOptions = { apiKey, model, client, signal };+ const model = provider.model;+ const decisionOptions = { apiKey, model, provider, client, fetchImpl: decisionFetchImpl, signal };await emit({ stage: "classifying", message: "Jev is choosing the social platform…" });const classification = await classifySearch({goal: request,@@ -273,7 +278,7 @@ export async function runSearch(const configuredModel = String(env.OPENROUTER_REPORT_MODEL || "openai/gpt-4o-mini").trim();const liveSynthesizer = typeof synthesizer === "function"? synthesizer- : !client && configuredModel.toLowerCase() !== "off"+ : apiKey && !client && configuredModel.toLowerCase() !== "off"? (safeInput) => requestOpenRouterResearchReport(safeInput, {apiKey,model: configuredModel,diff --git a/src/classifier.js b/src/classifier.jsindex e7f74a8..e5429be 100644--- a/src/classifier.js+++ b/src/classifier.js@@ -1,4 +1,5 @@import { AppError } from "./errors.js";+import { requestDecision } from "./decision-provider.js";export const SUPPORTED_PLATFORMS = new Set(["instagram", "tiktok", "linkedin"]);const ROUTE_TO_PLATFORM = {@@ -30,11 +31,13 @@ export async function classifySearch({requestedPlatform = "auto",capabilities = { instagram: true, tiktok: true, linkedin: true },apiKey,- model = process.env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",+ model,+ provider,client,fetchImpl = fetch,signal,}) {+ const decisionModel = model || provider?.model || process.env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest";const normalizedPlatform = (requestedPlatform || "auto").toLowerCase();if (normalizedPlatform !== "auto" && !SUPPORTED_PLATFORMS.has(normalizedPlatform)) {throw new AppError(`Unsupported platform: ${requestedPlatform}`, {@@ -62,7 +65,7 @@ export async function classifySearch({routeCriteria.unsupported = "Anything else, including posting, liking, following, messaging, or an ambiguous auto route.";const request = {- model,+ model: decisionModel,state: {request: goal.trim(),requested_platform: normalizedPlatform,@@ -83,7 +86,7 @@ export async function classifySearch({},},};- const decision = await requestChoice({ request, key: "route", apiKey, client, fetchImpl, signal });+ const decision = await requestChoice({ request, key: "route", apiKey, provider, client, fetchImpl, signal });const selected = decision.choice;const platform = ROUTE_TO_PLATFORM[selected] || null;if (normalizedPlatform !== "auto" && platform !== normalizedPlatform) {@@ -98,14 +101,14 @@ export async function classifySearch({return { ...decision, route: selected, platform };}-export async function requestChoice({ request, key, apiKey, client, fetchImpl = fetch, signal }) {+export async function requestChoice({ request, key, apiKey, provider, client, fetchImpl = fetch, signal }) {signal?.throwIfAborted();const startedAt = Date.now();let response;try {response = client? await client.systemOne(request, { signal })- : await requestOpenRouterDecision({ apiKey, request, fetchImpl, signal });+ : await requestDecision({ provider, apiKey, request, fetchImpl, signal });} catch (error) {signal?.throwIfAborted();throw new AppError(`Jev decision failed: ${error.message}`, { code: "JEV_UNAVAILABLE", status: 502 });@@ -146,24 +149,3 @@ export async function requestChoice({ request, key, apiKey, client, fetchImpl =elapsedMs: Date.now() - startedAt,};}--async function requestOpenRouterDecision({ apiKey, request, fetchImpl, signal }) {- 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: signal ? AbortSignal.any([signal, AbortSignal.timeout(15_000)]) : 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/decision-provider.js b/src/decision-provider.jsnew file mode 100644index 0000000..3870edd--- /dev/null+++ b/src/decision-provider.js@@ -0,0 +1,176 @@+import { AppError } from "./errors.js";++const DEFAULT_OPENROUTER_MODEL = "~typesafe/jev-latest";+const DEFAULT_LOCAL_MODEL = "kev-latest";+const MAX_RESPONSE_BYTES = 256 * 1024;+const OPENROUTER_TIMEOUT_MS = 15_000;+const LOCAL_TIMEOUT_MS = 120_000;+const MAX_LOCAL_TIMEOUT_MS = 120_000;+const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);++export function resolveDecisionProvider(env = process.env) {+ const rawEndpoint = env.JEV_SOCIAL_SYSTEM_ONE_URL?.trim();+ if (!rawEndpoint) {+ return {+ kind: "openrouter",+ model: cleanModel(env.OPENROUTER_JEV_MODEL, DEFAULT_OPENROUTER_MODEL),+ };+ }++ return {+ kind: "local",+ endpoint: normalizeLoopbackEndpoint(rawEndpoint),+ model: cleanModel(env.JEV_SOCIAL_SYSTEM_ONE_MODEL, DEFAULT_LOCAL_MODEL),+ timeoutMs: cleanTimeout(env.JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS, LOCAL_TIMEOUT_MS),+ };+}++export async function requestDecision({+ provider = { kind: "openrouter", model: DEFAULT_OPENROUTER_MODEL },+ apiKey,+ request,+ fetchImpl = fetch,+ signal,+ timeoutMs,+}) {+ const local = provider?.kind === "local";+ const endpoint = local+ ? normalizeLoopbackEndpoint(provider.endpoint)+ : "https://openrouter.ai/api/alpha/decisions";+ if (!local && !apiKey?.trim()) throw new Error("OPENROUTER_API_KEY is missing");++ const headers = { "Content-Type": "application/json" };+ if (local) headers["X-Title"] = "jev-social-local";+ else {+ headers.Authorization = `Bearer ${apiKey.trim()}`;+ headers["X-Title"] = "jev-social";+ }++ const providerTimeoutMs = local ? provider.timeoutMs ?? LOCAL_TIMEOUT_MS : OPENROUTER_TIMEOUT_MS;+ const maximumTimeoutMs = local ? MAX_LOCAL_TIMEOUT_MS : OPENROUTER_TIMEOUT_MS;+ const boundedTimeoutMs = Math.min(maximumTimeoutMs, cleanTimeout(timeoutMs, providerTimeoutMs));+ const timedSignal = createTimedSignal(signal, boundedTimeoutMs);+ let response;+ let raw;+ try {+ response = await fetchImpl(endpoint, {+ method: "POST",+ headers,+ body: JSON.stringify(request),+ redirect: "error",+ signal: timedSignal.signal,+ });+ raw = await readBoundedText(response);+ } finally {+ timedSignal.cleanup();+ }+ let payload;+ try {+ payload = JSON.parse(raw || "{}");+ } catch {+ throw new Error(`${local ? "Local System One" : "OpenRouter"} returned invalid JSON`);+ }+ if (!response.ok) {+ const message = payload?.error?.message;+ throw new Error(+ typeof message === "string" && message.trim()+ ? message.trim()+ : `${local ? "Local System One" : "OpenRouter"} returned HTTP ${response.status}`,+ );+ }+ return payload;+}++function normalizeLoopbackEndpoint(value) {+ let url;+ try {+ url = new URL(String(value));+ } catch {+ throw invalidProvider();+ }+ const normalizedPath = url.pathname.replace(/\/+$/u, "") || "/";+ if (+ url.protocol !== "http:" ||+ !LOOPBACK_HOSTS.has(url.hostname.toLowerCase()) ||+ url.username ||+ url.password ||+ url.search ||+ url.hash ||+ normalizedPath !== "/v1/systemone"+ ) {+ throw invalidProvider();+ }+ url.pathname = "/v1/systemone";+ return url.href;+}++function invalidProvider() {+ return new AppError(+ "Invalid local System One endpoint. Use http://127.0.0.1:<port>/v1/systemone.",+ { code: "INVALID_DECISION_PROVIDER" },+ );+}++function cleanModel(value, fallback) {+ const model = String(value || fallback).trim();+ if (!model || model.length > 160 || !/^[A-Za-z0-9._~:@/-]+$/u.test(model)) {+ throw new AppError("Invalid decision model name.", { code: "INVALID_DECISION_PROVIDER" });+ }+ return model;+}++function cleanTimeout(value, fallback) {+ if (value === undefined || value === null || String(value).trim() === "") return fallback;+ const timeout = Number(value);+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_LOCAL_TIMEOUT_MS) {+ throw new AppError(`Invalid local decision timeout. Use 1-${MAX_LOCAL_TIMEOUT_MS} milliseconds.`, {+ code: "INVALID_DECISION_PROVIDER",+ });+ }+ return timeout;+}++function createTimedSignal(signal, timeoutMs) {+ const controller = new AbortController();+ const forwardAbort = () => controller.abort(signal?.reason);+ if (signal?.aborted) forwardAbort();+ else signal?.addEventListener("abort", forwardAbort, { once: true });+ const timer = setTimeout(() => {+ controller.abort(new DOMException("The operation timed out.", "TimeoutError"));+ }, timeoutMs);+ return {+ signal: controller.signal,+ cleanup() {+ clearTimeout(timer);+ signal?.removeEventListener("abort", forwardAbort);+ },+ };+}++async function readBoundedText(response) {+ const declared = Number(response.headers.get("content-length"));+ if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {+ throw new Error("Decision provider returned an oversized response");+ }+ if (!response.body) return "";+ const reader = response.body.getReader();+ const chunks = [];+ let total = 0;+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > MAX_RESPONSE_BYTES) {+ await reader.cancel().catch(() => {});+ throw new Error("Decision provider returned an oversized response");+ }+ chunks.push(value);+ }+ const bytes = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return new TextDecoder().decode(bytes);+}diff --git a/src/env.js b/src/env.jsindex 0b39ea9..b360c7c 100644--- a/src/env.js+++ b/src/env.js@@ -5,7 +5,15 @@ 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"]);+const AUTO_ENV_KEYS = new Set([+ "OPENROUTER_API_KEY",+ "OPENROUTER_JEV_MODEL",+ "OPENROUTER_REPORT_MODEL",+ "JEV_SOCIAL_SYSTEM_ONE_URL",+ "JEV_SOCIAL_SYSTEM_ONE_MODEL",+ "JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS",+ "openrouter",+]);export async function loadLocalEnv(env = process.env) {const explicitEnvFile = env.JEV_SOCIAL_ENV_FILE?.trim();@@ -18,10 +26,7 @@ export async function loadLocalEnv(env = process.env) {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;- }+ mergeLocalEnv(env, values, { trusted: candidate.trusted });envFile = candidate.path;break;} catch (error) {@@ -35,6 +40,14 @@ export async function loadLocalEnv(env = process.env) {return { envFile };}+export function mergeLocalEnv(env, values, { trusted = false } = {}) {+ for (const [key, value] of Object.entries(values)) {+ if (!trusted && !AUTO_ENV_KEYS.has(key)) continue;+ if (env[key] === undefined) env[key] = value;+ }+ return env;+}+export function parseEnv(source) {const values = {};for (const rawLine of source.split(/\r?\n/)) {diff --git a/src/index.js b/src/index.jsindex 1a77ee6..834bf26 100644--- a/src/index.js+++ b/src/index.js@@ -12,6 +12,7 @@ export {} from "./socai.js";export { saveOnboarding, verifyOpenRouterApiKey, verifyTypesafeApiKey } from "./onboard.js";export { loadLocalEnv } from "./env.js";+export { requestDecision, resolveDecisionProvider } from "./decision-provider.js";export { extractSearchQuery } from "./query.js";export {buildGroundedResearchReport,diff --git a/src/server.js b/src/server.jsindex 2ec9b22..0409a5a 100644--- a/src/server.js+++ b/src/server.js@@ -8,6 +8,7 @@ import path from "node:path";import { fileURLToPath } from "node:url";import { getPrivateRunMedia, runSearch } from "./app.js";import { getConfigPath, readConfig, resolveApiKey } from "./config.js";+import { resolveDecisionProvider } from "./decision-provider.js";import { publicEvidence } from "./evidence.js";import { errorPayload } from "./errors.js";import { loadLocalEnv } from "./env.js";@@ -93,7 +94,8 @@ async function handleRequest(request, response, env, mediaRegistry) {} catch {return sendJson(response, 200, {jevConfigured: false,- jevModel: env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",+ jevModel: "unavailable",+ decisionProvider: "unavailable",socai: {installed: false,version: null,@@ -103,17 +105,24 @@ async function handleRequest(request, response, env, mediaRegistry) {configError: "Configuration could not be read.",});}+ let provider;const socai = await probeSocai(config, env, undefined, { includeReadiness: true });+ try {+ provider = resolveDecisionProvider(env);+ } catch {+ return sendJson(response, 200, {+ jevConfigured: false,+ jevModel: "unavailable",+ decisionProvider: "unavailable",+ socai: publicSocaiStatus(socai),+ decisionProviderError: "Decision provider configuration is invalid.",+ });+ }return sendJson(response, 200, {- jevConfigured: Boolean(resolveApiKey(config, env)),- jevModel: env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",- socai: {- installed: socai.installed,- version: socai.version ?? null,- capabilities: socai.capabilities,- readiness: socai.readiness,- ...(socai.error ? { error: socai.error } : {}),- },+ jevConfigured: provider.kind === "local" || Boolean(resolveApiKey(config, env)),+ jevModel: provider.model,+ decisionProvider: provider.kind,+ socai: publicSocaiStatus(socai),});}if (request.method === "POST" && url.pathname === "/api/onboard") {@@ -167,6 +176,16 @@ async function handleRequest(request, response, env, mediaRegistry) {}}+function publicSocaiStatus(socai) {+ return {+ installed: socai.installed,+ version: socai.version ?? null,+ capabilities: socai.capabilities,+ readiness: socai.readiness ?? unknownSocaiReadiness(Boolean(socai.installed)),+ ...(socai.error ? { error: socai.error } : {}),+ };+}+async function streamSearch(request, response, body, env, mediaRegistry) {response.writeHead(200, {"Content-Type": "application/x-ndjson; charset=utf-8",diff --git a/test/app.test.js b/test/app.test.jsindex 0e550f7..c12e92b 100644--- a/test/app.test.js+++ b/test/app.test.js@@ -102,6 +102,47 @@ test("runSearch lets Jev choose a specific post, then finish without an autonomo} finally { await rm(directory,{recursive:true,force:true}); }});+test("runSearch can use a loopback Kev endpoint without an OpenRouter key", async () => {+ const { directory, env } = await fixture();+ delete env.OPENROUTER_API_KEY;+ delete env.openrouter;+ env.JEV_SOCIAL_SYSTEM_ONE_URL = "http://127.0.0.1:8009/v1/systemone";+ env.JEV_SOCIAL_SYSTEM_ONE_MODEL = "kev-latest";+ let actionStep = 0;+ let calls = 0;+ const decisionFetchImpl = async (url, options) => {+ calls += 1;+ assert.equal(url, env.JEV_SOCIAL_SYSTEM_ONE_URL);+ assert.equal(options.headers.Authorization, undefined);+ const request = JSON.parse(options.body);+ if (request.questions.route) {+ return Response.json({+ model: "kev-latest",+ answers: { route: { type: "choice", choice: "instagram_search", confidence: 0.99 } },+ });+ }+ const criteria = request.questions.action.criteria;+ const choice = actionStep++ === 0 ? matching(criteria, /^Search instagram/) : "finish";+ return Response.json({+ model: "kev-latest",+ answers: { action: { type: "choice", choice, confidence: 0.99 } },+ });+ };++ try {+ const run = await runSearch(+ { query: "find handmade art on Instagram", limit: 1 },+ { env, decisionFetchImpl, reportChunkDelayMs: 0 },+ );+ assert.equal(run.classification.model, "kev-latest");+ assert.deepEqual(run.actions.map((entry) => entry.action.kind), ["search", "finish"]);+ assert.equal(run.reportKind, "evidence");+ assert.equal(calls, 3);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});+test("Jev opens a profile then selects a newly observed post", async () => {const {directory,env} = await fixture();const client = choices('instagram',(criteria,step) => {diff --git a/test/decision-provider.test.js b/test/decision-provider.test.jsnew file mode 100644index 0000000..6716d77--- /dev/null+++ b/test/decision-provider.test.js@@ -0,0 +1,163 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ requestDecision,+ resolveDecisionProvider,+} from "../src/decision-provider.js";+import { classifySearch } from "../src/classifier.js";++const request = {+ model: "kev-latest",+ state: "Choose a platform",+ questions: {+ route: {+ type: "choice",+ criteria: { instagram_search: "Instagram", unsupported: "Unsupported" },+ },+ },+};++test("local System One provider accepts only an explicit loopback endpoint", () => {+ assert.deepEqual(+ resolveDecisionProvider({+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://127.0.0.1:8009/v1/systemone",+ JEV_SOCIAL_SYSTEM_ONE_MODEL: "kev-latest",+ OPENROUTER_JEV_MODEL: "~typesafe/jev-latest",+ }),+ {+ kind: "local",+ endpoint: "http://127.0.0.1:8009/v1/systemone",+ model: "kev-latest",+ timeoutMs: 120_000,+ },+ );++ for (const endpoint of [+ "https://127.0.0.1:8009/v1/systemone",+ "http://example.com/v1/systemone",+ "http://127.0.0.1.evil.test/v1/systemone",+ "http://user:[email protected]:8009/v1/systemone",+ "http://127.0.0.1:8009/other",+ "http://127.0.0.1:8009/v1/systemone?token=secret",+ ]) {+ assert.throws(+ () => resolveDecisionProvider({ JEV_SOCIAL_SYSTEM_ONE_URL: endpoint }),+ (error) => error.code === "INVALID_DECISION_PROVIDER",+ endpoint,+ );+ }++ assert.throws(+ () => resolveDecisionProvider({+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://127.0.0.1:8009/v1/systemone",+ JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS: "120001",+ }),+ (error) => error.code === "INVALID_DECISION_PROVIDER",+ );+});++test("classifySearch defaults to the resolved local provider model", async () => {+ const provider = resolveDecisionProvider({+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://127.0.0.1:8009/v1/systemone",+ JEV_SOCIAL_SYSTEM_ONE_MODEL: "kev-local-test",+ });+ let sent;+ const result = await classifySearch({+ goal: "find art creators on Instagram",+ provider,+ fetchImpl: async (_url, options) => {+ sent = JSON.parse(options.body);+ return Response.json({+ model: "kev-local-test",+ answers: { route: { type: "choice", choice: "instagram_search", confidence: 0.99 } },+ });+ },+ });++ assert.equal(sent.model, "kev-local-test");+ assert.equal(result.model, "kev-local-test");+});++test("local System One requests never forward OpenRouter credentials", async () => {+ const provider = resolveDecisionProvider({+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://localhost:8009/v1/systemone",+ JEV_SOCIAL_SYSTEM_ONE_MODEL: "kev-latest",+ });+ let observed;+ const response = await requestDecision({+ provider,+ apiKey: "must-not-be-forwarded",+ request,+ fetchImpl: async (url, options) => {+ observed = { url, options };+ return new Response(JSON.stringify({+ model: "kev-latest",+ answers: {+ route: { type: "choice", choice: "instagram_search", confidence: 0.92 },+ },+ }), { status: 200, headers: { "Content-Type": "application/json" } });+ },+ });++ assert.equal(observed.url, "http://localhost:8009/v1/systemone");+ assert.equal(observed.options.headers.Authorization, undefined);+ assert.equal(observed.options.redirect, "error");+ assert.deepEqual(JSON.parse(observed.options.body), request);+ assert.equal(response.model, "kev-latest");+});++test("decision providers fail closed on HTTP, JSON, and size errors", async () => {+ const provider = resolveDecisionProvider({+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://[::1]:8009/v1/systemone",+ });+ const cases = [+ new Response(JSON.stringify({ error: { message: "unavailable" } }), { status: 503 }),+ new Response("not-json", { status: 200 }),+ new Response("x".repeat(256 * 1024 + 1), { status: 200 }),+ ];++ for (const response of cases) {+ await assert.rejects(+ requestDecision({ provider, request, fetchImpl: async () => response }),+ /unavailable|HTTP 503|invalid JSON|oversized response/,+ );+ }+});++test("OpenRouter remains the default decision provider", () => {+ assert.deepEqual(resolveDecisionProvider({ OPENROUTER_JEV_MODEL: "typesafe/jev-test" }), {+ kind: "openrouter",+ model: "typesafe/jev-test",+ });+});++test("local decision requests retain a bounded timeout", async () => {+ const provider = resolveDecisionProvider({+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://127.0.0.1:8009/v1/systemone",+ });+ await assert.rejects(+ requestDecision({+ provider,+ request,+ timeoutMs: 5,+ fetchImpl: async (_url, options) => new Promise((_resolve, reject) => {+ options.signal.addEventListener("abort", () => reject(options.signal.reason), { once: true });+ }),+ }),+ (error) => error?.name === "TimeoutError",+ );+});++test("local decision timeout can exceed the OpenRouter limit but remains bounded", async () => {+ const provider = resolveDecisionProvider({+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://127.0.0.1:8009/v1/systemone",+ JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS: "30000",+ });+ assert.equal(provider.timeoutMs, 30_000);+ const response = await requestDecision({+ provider,+ request,+ fetchImpl: async () => Response.json({ answers: {} }),+ });+ assert.deepEqual(response, { answers: {} });+});diff --git a/test/env.test.js b/test/env.test.jsindex a3bb92b..7e456fd 100644--- a/test/env.test.js+++ b/test/env.test.js@@ -1,9 +1,20 @@import assert from "node:assert/strict";import test from "node:test";-import { parseEnv } from "../src/env.js";+import { mergeLocalEnv, 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",});});++test("project .env values honor the report privacy opt-out", () => {+ const env = {};+ mergeLocalEnv(env, {+ OPENROUTER_REPORT_MODEL: "off",+ UNRELATED_SECRET: "must-not-load",+ });++ assert.equal(env.OPENROUTER_REPORT_MODEL, "off");+ assert.equal(env.UNRELATED_SECRET, undefined);+});diff --git a/test/server.test.js b/test/server.test.jsindex 8b73502..7626ac2 100644--- a/test/server.test.js+++ b/test/server.test.js@@ -133,6 +133,8 @@ else process.exitCode = 2;SOCAI_BIN: mock,OPENROUTER_API_KEY: "secret-key-123",OPENROUTER_JEV_MODEL: "~typesafe/jev-latest",+ JEV_SOCIAL_SYSTEM_ONE_URL: "",+ JEV_SOCIAL_SYSTEM_ONE_TIMEOUT_MS: "",};const { server, url } = await startServer({ port: 0, open: false, env });try {@@ -142,6 +144,7 @@ else process.exitCode = 2;assert.deepEqual(body, {jevConfigured: true,jevModel: "~typesafe/jev-latest",+ decisionProvider: "openrouter",socai: {installed: true,version: "0.5.6",@@ -183,6 +186,64 @@ else process.exitCode = 2;}});+test("/api/status reports a local decision provider without exposing its endpoint", async () => {+ const env = {+ ...process.env,+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://127.0.0.1:8009/v1/systemone",+ JEV_SOCIAL_SYSTEM_ONE_MODEL: "kev-latest",+ };+ delete env.OPENROUTER_API_KEY;+ delete env.openrouter;+ const { server, url } = await startServer({ port: 0, open: false, env });+ try {+ const response = await fetch(`${url}/api/status`);+ assert.equal(response.status, 200);+ const body = await response.json();+ assert.equal(body.jevConfigured, true);+ assert.equal(body.jevModel, "kev-latest");+ assert.equal(body.decisionProvider, "local");+ assert.doesNotMatch(JSON.stringify(body), /127\.0\.0\.1|8009|systemone/);+ } finally {+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));+ }+});++test("/api/status rejects an unsafe local decision endpoint without echoing it", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-invalid-provider-"));+ const mock = path.join(directory, "socai-mock.mjs");+ await writeFile(+ mock,+ `#!/usr/bin/env node+const args = process.argv.slice(2);+if (args[0] === "--version") console.log("socai 0.5.6");+else if (args[0] === "--help") console.log("socai root");+else if (["instagram", "tiktok", "linkedin"].includes(args[0]) && args[1] === "--help") console.log("Commands: search");+else process.exitCode = 2;+`,+ { mode: 0o755 },+ );+ const env = {+ ...process.env,+ SOCAI_BIN: mock,+ JEV_SOCIAL_SYSTEM_ONE_URL: "http://example.com/v1/systemone?token=secret",+ };+ const { server, url } = await startServer({ port: 0, open: false, env });+ try {+ const response = await fetch(`${url}/api/status`);+ assert.equal(response.status, 200);+ const body = await response.json();+ assert.equal(body.jevConfigured, false);+ assert.equal(body.decisionProviderError, "Decision provider configuration is invalid.");+ assert.equal(body.configError, undefined);+ assert.equal(body.socai.installed, true);+ assert.deepEqual(body.socai.capabilities, { instagram: true, tiktok: true, linkedin: true });+ assert.doesNotMatch(JSON.stringify(body), /example\.com|token|secret/);+ } finally {+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));+ await rm(directory, { recursive: true, force: true });+ }+});+test("/api/status never leaks config path when readConfig fails", async () => {const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-err-status-"));await writeFile(path.join(directory, "config.json"), "{ invalid JSON syntax !!!");diff --git a/test/status.test.js b/test/status.test.jsindex 85bb8f0..c7097b5 100644--- a/test/status.test.js+++ b/test/status.test.js@@ -111,4 +111,41 @@ for (const [errorCode, expected] of [assert.deepEqual(view.browser, { ready: false, label: expected[0], hint: expected[1] });assert.equal(view.error, "", "browser diagnostics must not trigger the global error toast");});-}+ }++test("local provider readiness avoids asking for an OpenRouter key", () => {+ const view = deriveStatusView({+ jevConfigured: true,+ jevModel: "kev-latest",+ decisionProvider: "local",+ socai: {+ installed: true,+ version: "0.6.0",+ capabilities: { instagram: true, tiktok: true, linkedin: true },+ },+ });++ assert.deepEqual(view.jev, { ready: true, label: "Local decision model ready" });+});++test("a provider error preserves independent socai readiness", () => {+ const view = deriveStatusView({+ jevConfigured: false,+ decisionProvider: "unavailable",+ decisionProviderError: "Decision provider configuration is invalid.",+ socai: {+ installed: true,+ version: "0.6.0",+ capabilities: { instagram: true, tiktok: true, linkedin: true },+ },+ });++ assert.equal(view.error, "Decision provider configuration is invalid.");+ assert.deepEqual(view.jev, { ready: false, label: "Decision provider unavailable" });+ assert.deepEqual(view.socai, { ready: true, label: "socai v0.6.0 ready" });+ assert.deepEqual(view.browser, {+ ready: false,+ label: "Chrome state unknown",+ hint: "Update socai to enable read-only browser diagnostics.",+ });+});