Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(jev-sheets): a real tool on your own file, not a demo (#126)

Dee0e00e2bb86dd
diff --git a/desktop/assets/engine-icons/jev-sheets.png b/desktop/assets/engine-icons/jev-sheets.png
new file mode 100644
index 000000000..5ee878a21
Binary files /dev/null and b/desktop/assets/engine-icons/jev-sheets.png differ
diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dart
index 4a594c6b8..58acb072a 100644
--- a/desktop/lib/widgets/engine_identity.dart
+++ b/desktop/lib/widgets/engine_identity.dart
@@ -287,6 +287,17 @@ const _harnesses = <String, EngineIdentity>{
asset: 'assets/engine-icons/lab-bench.png',
),
+ // Jev harnesses; marks are built by store/tools/jev-kit/brand.mjs from brand/icon.svg.
+ 'autonomous/jev-sheets': EngineIdentity(
+ id: 'autonomous/jev-sheets',
+ label: 'Jev Sheets',
+ category: 'Productivity',
+ tagline: 'Drop in any spreadsheet, ask in plain words, get every row answered in seconds',
+ creator: 'Autonomous',
+ color: Color(0xfffbbf24),
+ asset: 'assets/engine-icons/jev-sheets.png',
+ ),
+
'autonomous/autonomous-circuit': EngineIdentity(
id: 'autonomous/autonomous-circuit',
label: 'Autonomous Circuit',
@@ -627,6 +638,8 @@ const knownHarnessBase = <String, String>{
'autonomous/game-master': 'claude',
'autonomous/lab-bench': 'claude',
+ 'autonomous/jev-sheets': 'claude',
+
'autonomous/autonomous-circuit': 'claude',
'autonomous/kicad': 'claude',
'autonomous/autonomous-grid': 'codex',
diff --git a/store/agents/jev-archer/viewer/jev-hud.js b/store/agents/jev-archer/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-archer/viewer/jev-hud.js
+++ b/store/agents/jev-archer/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-arena/viewer/jev-hud.js b/store/agents/jev-arena/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-arena/viewer/jev-hud.js
+++ b/store/agents/jev-arena/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-blocks/toolchain/jev.mjs b/store/agents/jev-blocks/toolchain/jev.mjs
index ad49ee927..0552989b9 100644
--- a/store/agents/jev-blocks/toolchain/jev.mjs
+++ b/store/agents/jev-blocks/toolchain/jev.mjs
@@ -112,9 +112,9 @@ function clamp(x) {
}
// Imports are hoisted, so they can live here with the code that needs them.
-import { readFileSync } from 'node:fs'
+import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
@@ -234,6 +234,7 @@ export function snapshot() {
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
+ route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
@@ -291,6 +292,62 @@ export function resolveCredentials(explicitKey) {
return null
}
+/**
+ * Store one credential in the credentials file, so a pane can go live without a terminal. The file
+ * is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
+ */
+export function saveCredential(name, value) {
+ if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
+ const v = String(value ?? '').trim()
+ if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
+ const path = credentialsPath()
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ let lines = []
+ try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
+ kept.push(`${name}=${v}`)
+ writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
+ credCache = null
+}
+
+/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
+export function removeCredential(name) {
+ if (!CRED_KEYS.includes(name)) return
+ const path = credentialsPath()
+ try {
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
+ writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ } catch { /* nothing to remove */ }
+ credCache = null
+}
+
+/**
+ * A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
+ * one tiny real call. A key the service refuses is removed again. Never throws.
+ * @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
+ */
+export async function connectKey(value, { probe = true } = {}) {
+ const v = String(value ?? '').trim()
+ const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
+ try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
+ const cred = resolveCredentials()
+ // Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
+ if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
+ try {
+ await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
+ return { ok: true, provider: cred.provider, stored: true, probed: true }
+ } catch (e) {
+ const msg = String(e?.message ?? e)
+ if (/\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg)) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
+ return { ok: true, provider: cred.provider, stored: true, probed: false, warning: `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
+ }
+}
+
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
diff --git a/store/agents/jev-blocks/viewer/jev-hud.js b/store/agents/jev-blocks/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-blocks/viewer/jev-hud.js
+++ b/store/agents/jev-blocks/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-blocks/viewer/kit.mjs b/store/agents/jev-blocks/viewer/kit.mjs
index f80d29b7d..cf754e544 100644
--- a/store/agents/jev-blocks/viewer/kit.mjs
+++ b/store/agents/jev-blocks/viewer/kit.mjs
@@ -2,9 +2,9 @@
// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
// /control, plus an atomic verdict writer and a safe JSON config watcher.
import { createServer } from 'node:http'
-import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
-import { join, extname } from 'node:path'
-import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync } from 'node:fs'
+import { join, extname, dirname, basename } from 'node:path'
+import { snapshot as jevSnapshot, connectKey } from '../toolchain/jev.mjs'
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
@@ -28,8 +28,13 @@ export function mulberry32(a) {
* @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
* @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
* @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ * @param {function} [o.upload] async (name, buffer) => JSON-safe reply. Turns on POST /upload?name=<file name>: the person
+ * drops their own file on the pane. The handler must sanitise the name itself.
+ * @param {number} [o.maxUpload] largest upload in bytes (default 32 MB)
+ * @param {function} [o.downloads] () => ({ 'answers.csv': '/abs/path' }). Turns on GET /download/<name> for those files.
+ * @param {function} [o.onConnect] called after a person connects a key in the pane (POST /connect)
*/
-export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control, upload, maxUpload = 32 * 1024 * 1024, downloads, onConnect }) {
const clients = new Set()
const allowed = new Set(files)
@@ -40,12 +45,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
+ // Anything that changes state must come from this pane. A web page on another site can reach
+ // 127.0.0.1 from the person's browser, so a POST with a foreign Origin is refused.
+ if (req.method !== 'GET') {
+ const origin = req.headers.origin
+ if ((origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) || req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); return res.end('Same origin only') }
+ }
try {
if (req.method === 'GET') {
+ if (downloads && path.startsWith('/download/')) {
+ const name = decodeURIComponent(path.slice('/download/'.length))
+ const list = downloads() ?? {}
+ const file = Object.prototype.hasOwnProperty.call(list, name) ? list[name] : null
+ if (!file || !existsSync(file)) { res.writeHead(404); return res.end('Not found') }
+ res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream', 'content-disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}"` })
+ return res.end(readFileSync(file))
+ }
const name = path === '/' ? 'index.html' : path.slice(1)
if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
- if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ // canConnect tells the live panel that this server takes a pasted key (POST /connect).
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ...jevSnapshot(), canConnect: true })) }
if (path === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
@@ -63,6 +83,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
}
+ // The person pastes a Jev key in the pane. It goes to the credentials file (chmod 600) and is
+ // proven with one tiny call. The key is never echoed back, logged or kept in the page.
+ if (req.method === 'POST' && path === '/connect') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 4096) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const out = await connectKey(j.key)
+ if (out.ok) { try { await onConnect?.(out) } catch { /* the pane still learns the key is in */ } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(out))
+ }
+ // The person drops their own file on the pane. The raw bytes are the body.
+ if (req.method === 'POST' && path === '/upload' && upload) {
+ const chunks = []
+ let size = 0
+ for await (const c of req) { size += c.length; if (size > maxUpload) { res.writeHead(413, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: `that file is over ${Math.round(maxUpload / 1024 / 1024)} MB` })) } chunks.push(c) }
+ const reply = await upload(String(url.searchParams.get('name') ?? ''), Buffer.concat(chunks))
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
res.writeHead(404); res.end('Not found')
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
@@ -92,6 +133,24 @@ export function writeVerdict(workspace, verdict) {
renameSync(file + '.tmp', file)
}
+/**
+ * Call `onChange` whenever one file changes, however it was saved. Editors and coding agents save
+ * atomically (write a temp file, rename it over the target). `fs.watch` on the file itself keeps
+ * following the old inode and goes deaf after the first such save. So this watches the folder for
+ * that name, and a slow stat check catches anything the platform's watcher drops.
+ * @returns {{ close(): void }}
+ */
+export function watchPath(file, onChange, { pollMs = 1000 } = {}) {
+ const dir = dirname(file), name = basename(file)
+ const stamp = () => { try { const s = statSync(file); return `${s.ino}:${s.size}:${s.mtimeMs}` } catch { return 'missing' } }
+ let last = stamp(), closed = false, watcher = null
+ const check = () => { if (closed) return; const now = stamp(); if (now !== last) { last = now; onChange() } }
+ try { watcher = watch(dir, (_event, changed) => { if (!changed || changed === name) check() }) } catch { /* the folder may be gone; the poll still runs */ }
+ const poll = setInterval(check, pollMs)
+ poll.unref?.()
+ return { close() { closed = true; clearInterval(poll); watcher?.close() } }
+}
+
/**
* Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
* good config and reports the parse error instead of crashing the demo.
@@ -104,9 +163,7 @@ export function watchConfig(file, defaults, onChange) {
catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
}
load()
- let watcher = null
- try {
- watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
- } catch { /* file may not exist yet; defaults stand */ }
- return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+ // watchPath also sees a file that did not exist yet, and every save after an atomic replace.
+ const watcher = watchPath(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher.close() } }
}
diff --git a/store/agents/jev-browser/toolchain/jev.mjs b/store/agents/jev-browser/toolchain/jev.mjs
index ad49ee927..0552989b9 100644
--- a/store/agents/jev-browser/toolchain/jev.mjs
+++ b/store/agents/jev-browser/toolchain/jev.mjs
@@ -112,9 +112,9 @@ function clamp(x) {
}
// Imports are hoisted, so they can live here with the code that needs them.
-import { readFileSync } from 'node:fs'
+import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
@@ -234,6 +234,7 @@ export function snapshot() {
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
+ route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
@@ -291,6 +292,62 @@ export function resolveCredentials(explicitKey) {
return null
}
+/**
+ * Store one credential in the credentials file, so a pane can go live without a terminal. The file
+ * is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
+ */
+export function saveCredential(name, value) {
+ if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
+ const v = String(value ?? '').trim()
+ if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
+ const path = credentialsPath()
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ let lines = []
+ try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
+ kept.push(`${name}=${v}`)
+ writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
+ credCache = null
+}
+
+/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
+export function removeCredential(name) {
+ if (!CRED_KEYS.includes(name)) return
+ const path = credentialsPath()
+ try {
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
+ writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ } catch { /* nothing to remove */ }
+ credCache = null
+}
+
+/**
+ * A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
+ * one tiny real call. A key the service refuses is removed again. Never throws.
+ * @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
+ */
+export async function connectKey(value, { probe = true } = {}) {
+ const v = String(value ?? '').trim()
+ const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
+ try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
+ const cred = resolveCredentials()
+ // Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
+ if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
+ try {
+ await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
+ return { ok: true, provider: cred.provider, stored: true, probed: true }
+ } catch (e) {
+ const msg = String(e?.message ?? e)
+ if (/\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg)) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
+ return { ok: true, provider: cred.provider, stored: true, probed: false, warning: `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
+ }
+}
+
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
diff --git a/store/agents/jev-browser/viewer/jev-hud.js b/store/agents/jev-browser/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-browser/viewer/jev-hud.js
+++ b/store/agents/jev-browser/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-browser/viewer/kit.mjs b/store/agents/jev-browser/viewer/kit.mjs
index f80d29b7d..cf754e544 100644
--- a/store/agents/jev-browser/viewer/kit.mjs
+++ b/store/agents/jev-browser/viewer/kit.mjs
@@ -2,9 +2,9 @@
// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
// /control, plus an atomic verdict writer and a safe JSON config watcher.
import { createServer } from 'node:http'
-import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
-import { join, extname } from 'node:path'
-import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync } from 'node:fs'
+import { join, extname, dirname, basename } from 'node:path'
+import { snapshot as jevSnapshot, connectKey } from '../toolchain/jev.mjs'
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
@@ -28,8 +28,13 @@ export function mulberry32(a) {
* @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
* @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
* @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ * @param {function} [o.upload] async (name, buffer) => JSON-safe reply. Turns on POST /upload?name=<file name>: the person
+ * drops their own file on the pane. The handler must sanitise the name itself.
+ * @param {number} [o.maxUpload] largest upload in bytes (default 32 MB)
+ * @param {function} [o.downloads] () => ({ 'answers.csv': '/abs/path' }). Turns on GET /download/<name> for those files.
+ * @param {function} [o.onConnect] called after a person connects a key in the pane (POST /connect)
*/
-export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control, upload, maxUpload = 32 * 1024 * 1024, downloads, onConnect }) {
const clients = new Set()
const allowed = new Set(files)
@@ -40,12 +45,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
+ // Anything that changes state must come from this pane. A web page on another site can reach
+ // 127.0.0.1 from the person's browser, so a POST with a foreign Origin is refused.
+ if (req.method !== 'GET') {
+ const origin = req.headers.origin
+ if ((origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) || req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); return res.end('Same origin only') }
+ }
try {
if (req.method === 'GET') {
+ if (downloads && path.startsWith('/download/')) {
+ const name = decodeURIComponent(path.slice('/download/'.length))
+ const list = downloads() ?? {}
+ const file = Object.prototype.hasOwnProperty.call(list, name) ? list[name] : null
+ if (!file || !existsSync(file)) { res.writeHead(404); return res.end('Not found') }
+ res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream', 'content-disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}"` })
+ return res.end(readFileSync(file))
+ }
const name = path === '/' ? 'index.html' : path.slice(1)
if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
- if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ // canConnect tells the live panel that this server takes a pasted key (POST /connect).
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ...jevSnapshot(), canConnect: true })) }
if (path === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
@@ -63,6 +83,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
}
+ // The person pastes a Jev key in the pane. It goes to the credentials file (chmod 600) and is
+ // proven with one tiny call. The key is never echoed back, logged or kept in the page.
+ if (req.method === 'POST' && path === '/connect') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 4096) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const out = await connectKey(j.key)
+ if (out.ok) { try { await onConnect?.(out) } catch { /* the pane still learns the key is in */ } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(out))
+ }
+ // The person drops their own file on the pane. The raw bytes are the body.
+ if (req.method === 'POST' && path === '/upload' && upload) {
+ const chunks = []
+ let size = 0
+ for await (const c of req) { size += c.length; if (size > maxUpload) { res.writeHead(413, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: `that file is over ${Math.round(maxUpload / 1024 / 1024)} MB` })) } chunks.push(c) }
+ const reply = await upload(String(url.searchParams.get('name') ?? ''), Buffer.concat(chunks))
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
res.writeHead(404); res.end('Not found')
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
@@ -92,6 +133,24 @@ export function writeVerdict(workspace, verdict) {
renameSync(file + '.tmp', file)
}
+/**
+ * Call `onChange` whenever one file changes, however it was saved. Editors and coding agents save
+ * atomically (write a temp file, rename it over the target). `fs.watch` on the file itself keeps
+ * following the old inode and goes deaf after the first such save. So this watches the folder for
+ * that name, and a slow stat check catches anything the platform's watcher drops.
+ * @returns {{ close(): void }}
+ */
+export function watchPath(file, onChange, { pollMs = 1000 } = {}) {
+ const dir = dirname(file), name = basename(file)
+ const stamp = () => { try { const s = statSync(file); return `${s.ino}:${s.size}:${s.mtimeMs}` } catch { return 'missing' } }
+ let last = stamp(), closed = false, watcher = null
+ const check = () => { if (closed) return; const now = stamp(); if (now !== last) { last = now; onChange() } }
+ try { watcher = watch(dir, (_event, changed) => { if (!changed || changed === name) check() }) } catch { /* the folder may be gone; the poll still runs */ }
+ const poll = setInterval(check, pollMs)
+ poll.unref?.()
+ return { close() { closed = true; clearInterval(poll); watcher?.close() } }
+}
+
/**
* Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
* good config and reports the parse error instead of crashing the demo.
@@ -104,9 +163,7 @@ export function watchConfig(file, defaults, onChange) {
catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
}
load()
- let watcher = null
- try {
- watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
- } catch { /* file may not exist yet; defaults stand */ }
- return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+ // watchPath also sees a file that did not exist yet, and every save after an atomic replace.
+ const watcher = watchPath(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher.close() } }
}
diff --git a/store/agents/jev-catcher/viewer/jev-hud.js b/store/agents/jev-catcher/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-catcher/viewer/jev-hud.js
+++ b/store/agents/jev-catcher/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-compactor/toolchain/jev.mjs b/store/agents/jev-compactor/toolchain/jev.mjs
index ad49ee927..0552989b9 100644
--- a/store/agents/jev-compactor/toolchain/jev.mjs
+++ b/store/agents/jev-compactor/toolchain/jev.mjs
@@ -112,9 +112,9 @@ function clamp(x) {
}
// Imports are hoisted, so they can live here with the code that needs them.
-import { readFileSync } from 'node:fs'
+import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
@@ -234,6 +234,7 @@ export function snapshot() {
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
+ route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
@@ -291,6 +292,62 @@ export function resolveCredentials(explicitKey) {
return null
}
+/**
+ * Store one credential in the credentials file, so a pane can go live without a terminal. The file
+ * is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
+ */
+export function saveCredential(name, value) {
+ if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
+ const v = String(value ?? '').trim()
+ if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
+ const path = credentialsPath()
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ let lines = []
+ try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
+ kept.push(`${name}=${v}`)
+ writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
+ credCache = null
+}
+
+/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
+export function removeCredential(name) {
+ if (!CRED_KEYS.includes(name)) return
+ const path = credentialsPath()
+ try {
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
+ writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ } catch { /* nothing to remove */ }
+ credCache = null
+}
+
+/**
+ * A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
+ * one tiny real call. A key the service refuses is removed again. Never throws.
+ * @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
+ */
+export async function connectKey(value, { probe = true } = {}) {
+ const v = String(value ?? '').trim()
+ const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
+ try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
+ const cred = resolveCredentials()
+ // Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
+ if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
+ try {
+ await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
+ return { ok: true, provider: cred.provider, stored: true, probed: true }
+ } catch (e) {
+ const msg = String(e?.message ?? e)
+ if (/\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg)) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
+ return { ok: true, provider: cred.provider, stored: true, probed: false, warning: `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
+ }
+}
+
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
diff --git a/store/agents/jev-compactor/viewer/jev-hud.js b/store/agents/jev-compactor/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-compactor/viewer/jev-hud.js
+++ b/store/agents/jev-compactor/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-compactor/viewer/kit.mjs b/store/agents/jev-compactor/viewer/kit.mjs
index f80d29b7d..cf754e544 100644
--- a/store/agents/jev-compactor/viewer/kit.mjs
+++ b/store/agents/jev-compactor/viewer/kit.mjs
@@ -2,9 +2,9 @@
// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
// /control, plus an atomic verdict writer and a safe JSON config watcher.
import { createServer } from 'node:http'
-import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
-import { join, extname } from 'node:path'
-import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync } from 'node:fs'
+import { join, extname, dirname, basename } from 'node:path'
+import { snapshot as jevSnapshot, connectKey } from '../toolchain/jev.mjs'
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
@@ -28,8 +28,13 @@ export function mulberry32(a) {
* @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
* @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
* @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ * @param {function} [o.upload] async (name, buffer) => JSON-safe reply. Turns on POST /upload?name=<file name>: the person
+ * drops their own file on the pane. The handler must sanitise the name itself.
+ * @param {number} [o.maxUpload] largest upload in bytes (default 32 MB)
+ * @param {function} [o.downloads] () => ({ 'answers.csv': '/abs/path' }). Turns on GET /download/<name> for those files.
+ * @param {function} [o.onConnect] called after a person connects a key in the pane (POST /connect)
*/
-export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control, upload, maxUpload = 32 * 1024 * 1024, downloads, onConnect }) {
const clients = new Set()
const allowed = new Set(files)
@@ -40,12 +45,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
+ // Anything that changes state must come from this pane. A web page on another site can reach
+ // 127.0.0.1 from the person's browser, so a POST with a foreign Origin is refused.
+ if (req.method !== 'GET') {
+ const origin = req.headers.origin
+ if ((origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) || req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); return res.end('Same origin only') }
+ }
try {
if (req.method === 'GET') {
+ if (downloads && path.startsWith('/download/')) {
+ const name = decodeURIComponent(path.slice('/download/'.length))
+ const list = downloads() ?? {}
+ const file = Object.prototype.hasOwnProperty.call(list, name) ? list[name] : null
+ if (!file || !existsSync(file)) { res.writeHead(404); return res.end('Not found') }
+ res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream', 'content-disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}"` })
+ return res.end(readFileSync(file))
+ }
const name = path === '/' ? 'index.html' : path.slice(1)
if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
- if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ // canConnect tells the live panel that this server takes a pasted key (POST /connect).
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ...jevSnapshot(), canConnect: true })) }
if (path === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
@@ -63,6 +83,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
}
+ // The person pastes a Jev key in the pane. It goes to the credentials file (chmod 600) and is
+ // proven with one tiny call. The key is never echoed back, logged or kept in the page.
+ if (req.method === 'POST' && path === '/connect') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 4096) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const out = await connectKey(j.key)
+ if (out.ok) { try { await onConnect?.(out) } catch { /* the pane still learns the key is in */ } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(out))
+ }
+ // The person drops their own file on the pane. The raw bytes are the body.
+ if (req.method === 'POST' && path === '/upload' && upload) {
+ const chunks = []
+ let size = 0
+ for await (const c of req) { size += c.length; if (size > maxUpload) { res.writeHead(413, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: `that file is over ${Math.round(maxUpload / 1024 / 1024)} MB` })) } chunks.push(c) }
+ const reply = await upload(String(url.searchParams.get('name') ?? ''), Buffer.concat(chunks))
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
res.writeHead(404); res.end('Not found')
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
@@ -92,6 +133,24 @@ export function writeVerdict(workspace, verdict) {
renameSync(file + '.tmp', file)
}
+/**
+ * Call `onChange` whenever one file changes, however it was saved. Editors and coding agents save
+ * atomically (write a temp file, rename it over the target). `fs.watch` on the file itself keeps
+ * following the old inode and goes deaf after the first such save. So this watches the folder for
+ * that name, and a slow stat check catches anything the platform's watcher drops.
+ * @returns {{ close(): void }}
+ */
+export function watchPath(file, onChange, { pollMs = 1000 } = {}) {
+ const dir = dirname(file), name = basename(file)
+ const stamp = () => { try { const s = statSync(file); return `${s.ino}:${s.size}:${s.mtimeMs}` } catch { return 'missing' } }
+ let last = stamp(), closed = false, watcher = null
+ const check = () => { if (closed) return; const now = stamp(); if (now !== last) { last = now; onChange() } }
+ try { watcher = watch(dir, (_event, changed) => { if (!changed || changed === name) check() }) } catch { /* the folder may be gone; the poll still runs */ }
+ const poll = setInterval(check, pollMs)
+ poll.unref?.()
+ return { close() { closed = true; clearInterval(poll); watcher?.close() } }
+}
+
/**
* Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
* good config and reports the parse error instead of crashing the demo.
@@ -104,9 +163,7 @@ export function watchConfig(file, defaults, onChange) {
catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
}
load()
- let watcher = null
- try {
- watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
- } catch { /* file may not exist yet; defaults stand */ }
- return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+ // watchPath also sees a file that did not exist yet, and every save after an atomic replace.
+ const watcher = watchPath(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher.close() } }
}
diff --git a/store/agents/jev-conductor/viewer/jev-hud.js b/store/agents/jev-conductor/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-conductor/viewer/jev-hud.js
+++ b/store/agents/jev-conductor/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-duel/viewer/jev-hud.js b/store/agents/jev-duel/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-duel/viewer/jev-hud.js
+++ b/store/agents/jev-duel/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-firehose/toolchain/jev.mjs b/store/agents/jev-firehose/toolchain/jev.mjs
index ad49ee927..0552989b9 100644
--- a/store/agents/jev-firehose/toolchain/jev.mjs
+++ b/store/agents/jev-firehose/toolchain/jev.mjs
@@ -112,9 +112,9 @@ function clamp(x) {
}
// Imports are hoisted, so they can live here with the code that needs them.
-import { readFileSync } from 'node:fs'
+import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
@@ -234,6 +234,7 @@ export function snapshot() {
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
+ route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
@@ -291,6 +292,62 @@ export function resolveCredentials(explicitKey) {
return null
}
+/**
+ * Store one credential in the credentials file, so a pane can go live without a terminal. The file
+ * is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
+ */
+export function saveCredential(name, value) {
+ if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
+ const v = String(value ?? '').trim()
+ if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
+ const path = credentialsPath()
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ let lines = []
+ try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
+ kept.push(`${name}=${v}`)
+ writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
+ credCache = null
+}
+
+/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
+export function removeCredential(name) {
+ if (!CRED_KEYS.includes(name)) return
+ const path = credentialsPath()
+ try {
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
+ writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ } catch { /* nothing to remove */ }
+ credCache = null
+}
+
+/**
+ * A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
+ * one tiny real call. A key the service refuses is removed again. Never throws.
+ * @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
+ */
+export async function connectKey(value, { probe = true } = {}) {
+ const v = String(value ?? '').trim()
+ const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
+ try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
+ const cred = resolveCredentials()
+ // Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
+ if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
+ try {
+ await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
+ return { ok: true, provider: cred.provider, stored: true, probed: true }
+ } catch (e) {
+ const msg = String(e?.message ?? e)
+ if (/\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg)) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
+ return { ok: true, provider: cred.provider, stored: true, probed: false, warning: `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
+ }
+}
+
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
diff --git a/store/agents/jev-firehose/viewer/jev-hud.js b/store/agents/jev-firehose/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-firehose/viewer/jev-hud.js
+++ b/store/agents/jev-firehose/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-firehose/viewer/kit.mjs b/store/agents/jev-firehose/viewer/kit.mjs
index f80d29b7d..cf754e544 100644
--- a/store/agents/jev-firehose/viewer/kit.mjs
+++ b/store/agents/jev-firehose/viewer/kit.mjs
@@ -2,9 +2,9 @@
// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
// /control, plus an atomic verdict writer and a safe JSON config watcher.
import { createServer } from 'node:http'
-import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
-import { join, extname } from 'node:path'
-import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync } from 'node:fs'
+import { join, extname, dirname, basename } from 'node:path'
+import { snapshot as jevSnapshot, connectKey } from '../toolchain/jev.mjs'
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
@@ -28,8 +28,13 @@ export function mulberry32(a) {
* @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
* @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
* @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ * @param {function} [o.upload] async (name, buffer) => JSON-safe reply. Turns on POST /upload?name=<file name>: the person
+ * drops their own file on the pane. The handler must sanitise the name itself.
+ * @param {number} [o.maxUpload] largest upload in bytes (default 32 MB)
+ * @param {function} [o.downloads] () => ({ 'answers.csv': '/abs/path' }). Turns on GET /download/<name> for those files.
+ * @param {function} [o.onConnect] called after a person connects a key in the pane (POST /connect)
*/
-export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control, upload, maxUpload = 32 * 1024 * 1024, downloads, onConnect }) {
const clients = new Set()
const allowed = new Set(files)
@@ -40,12 +45,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
+ // Anything that changes state must come from this pane. A web page on another site can reach
+ // 127.0.0.1 from the person's browser, so a POST with a foreign Origin is refused.
+ if (req.method !== 'GET') {
+ const origin = req.headers.origin
+ if ((origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) || req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); return res.end('Same origin only') }
+ }
try {
if (req.method === 'GET') {
+ if (downloads && path.startsWith('/download/')) {
+ const name = decodeURIComponent(path.slice('/download/'.length))
+ const list = downloads() ?? {}
+ const file = Object.prototype.hasOwnProperty.call(list, name) ? list[name] : null
+ if (!file || !existsSync(file)) { res.writeHead(404); return res.end('Not found') }
+ res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream', 'content-disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}"` })
+ return res.end(readFileSync(file))
+ }
const name = path === '/' ? 'index.html' : path.slice(1)
if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
- if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ // canConnect tells the live panel that this server takes a pasted key (POST /connect).
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ...jevSnapshot(), canConnect: true })) }
if (path === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
@@ -63,6 +83,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
}
+ // The person pastes a Jev key in the pane. It goes to the credentials file (chmod 600) and is
+ // proven with one tiny call. The key is never echoed back, logged or kept in the page.
+ if (req.method === 'POST' && path === '/connect') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 4096) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const out = await connectKey(j.key)
+ if (out.ok) { try { await onConnect?.(out) } catch { /* the pane still learns the key is in */ } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(out))
+ }
+ // The person drops their own file on the pane. The raw bytes are the body.
+ if (req.method === 'POST' && path === '/upload' && upload) {
+ const chunks = []
+ let size = 0
+ for await (const c of req) { size += c.length; if (size > maxUpload) { res.writeHead(413, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: `that file is over ${Math.round(maxUpload / 1024 / 1024)} MB` })) } chunks.push(c) }
+ const reply = await upload(String(url.searchParams.get('name') ?? ''), Buffer.concat(chunks))
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
res.writeHead(404); res.end('Not found')
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
@@ -92,6 +133,24 @@ export function writeVerdict(workspace, verdict) {
renameSync(file + '.tmp', file)
}
+/**
+ * Call `onChange` whenever one file changes, however it was saved. Editors and coding agents save
+ * atomically (write a temp file, rename it over the target). `fs.watch` on the file itself keeps
+ * following the old inode and goes deaf after the first such save. So this watches the folder for
+ * that name, and a slow stat check catches anything the platform's watcher drops.
+ * @returns {{ close(): void }}
+ */
+export function watchPath(file, onChange, { pollMs = 1000 } = {}) {
+ const dir = dirname(file), name = basename(file)
+ const stamp = () => { try { const s = statSync(file); return `${s.ino}:${s.size}:${s.mtimeMs}` } catch { return 'missing' } }
+ let last = stamp(), closed = false, watcher = null
+ const check = () => { if (closed) return; const now = stamp(); if (now !== last) { last = now; onChange() } }
+ try { watcher = watch(dir, (_event, changed) => { if (!changed || changed === name) check() }) } catch { /* the folder may be gone; the poll still runs */ }
+ const poll = setInterval(check, pollMs)
+ poll.unref?.()
+ return { close() { closed = true; clearInterval(poll); watcher?.close() } }
+}
+
/**
* Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
* good config and reports the parse error instead of crashing the demo.
@@ -104,9 +163,7 @@ export function watchConfig(file, defaults, onChange) {
catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
}
load()
- let watcher = null
- try {
- watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
- } catch { /* file may not exist yet; defaults stand */ }
- return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+ // watchPath also sees a file that did not exist yet, and every save after an atomic replace.
+ const watcher = watchPath(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher.close() } }
}
diff --git a/store/agents/jev-fps/toolchain/jev.mjs b/store/agents/jev-fps/toolchain/jev.mjs
index ad49ee927..0552989b9 100644
--- a/store/agents/jev-fps/toolchain/jev.mjs
+++ b/store/agents/jev-fps/toolchain/jev.mjs
@@ -112,9 +112,9 @@ function clamp(x) {
}
// Imports are hoisted, so they can live here with the code that needs them.
-import { readFileSync } from 'node:fs'
+import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
@@ -234,6 +234,7 @@ export function snapshot() {
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
+ route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
@@ -291,6 +292,62 @@ export function resolveCredentials(explicitKey) {
return null
}
+/**
+ * Store one credential in the credentials file, so a pane can go live without a terminal. The file
+ * is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
+ */
+export function saveCredential(name, value) {
+ if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
+ const v = String(value ?? '').trim()
+ if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
+ const path = credentialsPath()
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ let lines = []
+ try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
+ kept.push(`${name}=${v}`)
+ writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
+ credCache = null
+}
+
+/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
+export function removeCredential(name) {
+ if (!CRED_KEYS.includes(name)) return
+ const path = credentialsPath()
+ try {
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
+ writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ } catch { /* nothing to remove */ }
+ credCache = null
+}
+
+/**
+ * A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
+ * one tiny real call. A key the service refuses is removed again. Never throws.
+ * @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
+ */
+export async function connectKey(value, { probe = true } = {}) {
+ const v = String(value ?? '').trim()
+ const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
+ try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
+ const cred = resolveCredentials()
+ // Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
+ if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
+ try {
+ await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
+ return { ok: true, provider: cred.provider, stored: true, probed: true }
+ } catch (e) {
+ const msg = String(e?.message ?? e)
+ if (/\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg)) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
+ return { ok: true, provider: cred.provider, stored: true, probed: false, warning: `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
+ }
+}
+
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
diff --git a/store/agents/jev-fps/viewer/jev-hud.js b/store/agents/jev-fps/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-fps/viewer/jev-hud.js
+++ b/store/agents/jev-fps/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-fps/viewer/kit.mjs b/store/agents/jev-fps/viewer/kit.mjs
index f80d29b7d..cf754e544 100644
--- a/store/agents/jev-fps/viewer/kit.mjs
+++ b/store/agents/jev-fps/viewer/kit.mjs
@@ -2,9 +2,9 @@
// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
// /control, plus an atomic verdict writer and a safe JSON config watcher.
import { createServer } from 'node:http'
-import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
-import { join, extname } from 'node:path'
-import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync } from 'node:fs'
+import { join, extname, dirname, basename } from 'node:path'
+import { snapshot as jevSnapshot, connectKey } from '../toolchain/jev.mjs'
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
@@ -28,8 +28,13 @@ export function mulberry32(a) {
* @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
* @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
* @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ * @param {function} [o.upload] async (name, buffer) => JSON-safe reply. Turns on POST /upload?name=<file name>: the person
+ * drops their own file on the pane. The handler must sanitise the name itself.
+ * @param {number} [o.maxUpload] largest upload in bytes (default 32 MB)
+ * @param {function} [o.downloads] () => ({ 'answers.csv': '/abs/path' }). Turns on GET /download/<name> for those files.
+ * @param {function} [o.onConnect] called after a person connects a key in the pane (POST /connect)
*/
-export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control, upload, maxUpload = 32 * 1024 * 1024, downloads, onConnect }) {
const clients = new Set()
const allowed = new Set(files)
@@ -40,12 +45,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
+ // Anything that changes state must come from this pane. A web page on another site can reach
+ // 127.0.0.1 from the person's browser, so a POST with a foreign Origin is refused.
+ if (req.method !== 'GET') {
+ const origin = req.headers.origin
+ if ((origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) || req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); return res.end('Same origin only') }
+ }
try {
if (req.method === 'GET') {
+ if (downloads && path.startsWith('/download/')) {
+ const name = decodeURIComponent(path.slice('/download/'.length))
+ const list = downloads() ?? {}
+ const file = Object.prototype.hasOwnProperty.call(list, name) ? list[name] : null
+ if (!file || !existsSync(file)) { res.writeHead(404); return res.end('Not found') }
+ res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream', 'content-disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}"` })
+ return res.end(readFileSync(file))
+ }
const name = path === '/' ? 'index.html' : path.slice(1)
if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
- if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ // canConnect tells the live panel that this server takes a pasted key (POST /connect).
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ...jevSnapshot(), canConnect: true })) }
if (path === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
@@ -63,6 +83,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
}
+ // The person pastes a Jev key in the pane. It goes to the credentials file (chmod 600) and is
+ // proven with one tiny call. The key is never echoed back, logged or kept in the page.
+ if (req.method === 'POST' && path === '/connect') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 4096) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const out = await connectKey(j.key)
+ if (out.ok) { try { await onConnect?.(out) } catch { /* the pane still learns the key is in */ } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(out))
+ }
+ // The person drops their own file on the pane. The raw bytes are the body.
+ if (req.method === 'POST' && path === '/upload' && upload) {
+ const chunks = []
+ let size = 0
+ for await (const c of req) { size += c.length; if (size > maxUpload) { res.writeHead(413, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: `that file is over ${Math.round(maxUpload / 1024 / 1024)} MB` })) } chunks.push(c) }
+ const reply = await upload(String(url.searchParams.get('name') ?? ''), Buffer.concat(chunks))
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
res.writeHead(404); res.end('Not found')
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
@@ -92,6 +133,24 @@ export function writeVerdict(workspace, verdict) {
renameSync(file + '.tmp', file)
}
+/**
+ * Call `onChange` whenever one file changes, however it was saved. Editors and coding agents save
+ * atomically (write a temp file, rename it over the target). `fs.watch` on the file itself keeps
+ * following the old inode and goes deaf after the first such save. So this watches the folder for
+ * that name, and a slow stat check catches anything the platform's watcher drops.
+ * @returns {{ close(): void }}
+ */
+export function watchPath(file, onChange, { pollMs = 1000 } = {}) {
+ const dir = dirname(file), name = basename(file)
+ const stamp = () => { try { const s = statSync(file); return `${s.ino}:${s.size}:${s.mtimeMs}` } catch { return 'missing' } }
+ let last = stamp(), closed = false, watcher = null
+ const check = () => { if (closed) return; const now = stamp(); if (now !== last) { last = now; onChange() } }
+ try { watcher = watch(dir, (_event, changed) => { if (!changed || changed === name) check() }) } catch { /* the folder may be gone; the poll still runs */ }
+ const poll = setInterval(check, pollMs)
+ poll.unref?.()
+ return { close() { closed = true; clearInterval(poll); watcher?.close() } }
+}
+
/**
* Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
* good config and reports the parse error instead of crashing the demo.
@@ -104,9 +163,7 @@ export function watchConfig(file, defaults, onChange) {
catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
}
load()
- let watcher = null
- try {
- watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
- } catch { /* file may not exist yet; defaults stand */ }
- return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+ // watchPath also sees a file that did not exist yet, and every save after an atomic replace.
+ const watcher = watchPath(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher.close() } }
}
diff --git a/store/agents/jev-guard/viewer/jev-hud.js b/store/agents/jev-guard/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-guard/viewer/jev-hud.js
+++ b/store/agents/jev-guard/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-lander/viewer/jev-hud.js b/store/agents/jev-lander/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-lander/viewer/jev-hud.js
+++ b/store/agents/jev-lander/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-launcher/viewer/jev-hud.js b/store/agents/jev-launcher/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-launcher/viewer/jev-hud.js
+++ b/store/agents/jev-launcher/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-pendulum/viewer/jev-hud.js b/store/agents/jev-pendulum/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-pendulum/viewer/jev-hud.js
+++ b/store/agents/jev-pendulum/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-pong/viewer/jev-hud.js b/store/agents/jev-pong/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-pong/viewer/jev-hud.js
+++ b/store/agents/jev-pong/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-sheets/AGENTS.md b/store/agents/jev-sheets/AGENTS.md
index 04f3c7004..74cdd571c 100644
--- a/store/agents/jev-sheets/AGENTS.md
+++ b/store/agents/jev-sheets/AGENTS.md
@@ -1,91 +1,151 @@
# Jev Sheets in OpenHarness
-On the left is a live spreadsheet. Every Jev column header is a question, and **Jev, TypeSafe's
-System One model, answers it for every row**. One call per row, all columns at once, each answer
-with a probability. Cells are shaded by confidence. Cells under the review line get a "?" flag.
-When a row has a truth label, the column header shows how often Jev was right.
+**This tool turns one person into a research team.** They bring a pile of text they could never read
+in full: app reviews, survey answers, support tickets, sales leads, interview notes, log lines. They
+ask questions in plain words. **Jev, TypeSafe's System One model, answers every question for every
+row** in seconds, for cents, each answer with a probability. They leave with a coded file
+(`answers.csv`) and written findings (`findings.md`). You are the senior analyst at their side.
+
+On the left is the live sheet. Every Jev column header is a question. Cells are shaded by
+confidence, and cells under the review line get a "?" flag. The **Answers so far** panel counts
+every answer, and a click on a count shows only those rows.
+
+On the right, you. You edit `sheet.json`. The viewer watches it and reloads on every save. The
+viewer is already running in the pane. Never propose opening a browser, changing ports, or running a
+second server.
+
+## Your job, in this order
+
+1. **Get the person's own data in.** Three ways in:
+ - They **drop a file on the pane** or paste rows from a spreadsheet. The viewer saves the file in
+ the workspace and points `sheet.json` at it by itself: `"source"` is already set when you look.
+ - They give you a **path**. Copy the file into the workspace, then set `"source"`.
+ - They have a PDF, an old `.xls`, an export in an odd shape, or a folder of files. **Convert it for
+ them** into a `.csv` or `.jsonl` in the workspace, one row per item, and set `"source"`. Long
+ documents: one row per paragraph or clause, with a column that says where it came from.
+ Only if they have nothing at hand, offer the made-up sample, and say it is made up.
+ Only the file named in `source` is read. Leave other files in the workspace alone.
+2. **Look before you ask.** Read the file's header and twenty or so rows. Tell the person in two
+ lines what is in it. Never paste more of their data into the chat than you need.
+3. **Write sharp questions about what is really in it**, three to five to start, and put them in
+ `columns`. If they already told you what they want to know, do not ask again: aim the questions
+ at it. If they did not, ask what decision they are trying to make. Set `context`. Replace the
+ generic starter `suggestions` with four to six about this file.
+4. **Save, and check that it took** (see "After you save").
+5. **Read the results.** `answers.csv` and `.harness/verdict.json`. Do not edit them.
+6. **Write the findings** in `findings.md` in the workspace. **Lead with the answer**: the first
+ five lines answer what the person asked, with the numbers. Then, briefly: what was asked and of
+ how many rows, the count and share of every answer, a cross-cut or two when it says something
+ ("of the 212 crash reports, 61% also say they may leave"), two to four word-for-word quotes for
+ each finding that matters (with their `row` numbers), what Jev was unsure about, and the next
+ question worth asking. Keep it to about two screens. Count with `toolchain/count.mjs` (see
+ "Counting"), never by eye or from memory. Then tell the person the three things that matter
+ most, in plain words.
+7. **Sharpen.** If many cells sit under the review line, or the person says an answer is wrong,
+ reword that question, save, and read again. Only the changed column is asked again.
+
+If the questions could not be answered (no key, the viewer is not running, errors), say so plainly.
+Never write findings from questions that were not answered.
+
+## After you save: how to know it worked
+
+The viewer fills cells on its own, whether or not anyone is looking at the pane. Watch
+`.harness/verdict.json`:
-On the right, you edit `sheet.json`. This is the ONLY file you edit. The viewer watches it and
-reloads the sheet on every save. The viewer is already running in the pane. Never propose opening
-a browser, changing ports, or running a second server.
+```jsonc
+{ "ready": false, // true when every cell is filled
+ "summary": "App reviews, Q3: 1200 rows x 3 Jev columns, 2214/3600 cells, 96 under 0.65",
+ "sheet": {
+ "loadedAt": "2026-09-20T08:41:07.412Z", // moves within two seconds of every save of sheet.json
+ "source": "reviews.csv", "client": "openrouter", // "mock" means no key: see "Without a key"
+ "rows": 1200, "cellsFilled": 2214, "cellsTotal": 3600, "flagged": 96, "costUsd": 0.017,
+ "columns": [ { "id": "topic", "filled": 738, "underReviewLine": 41, "avgConfidence": 0.93,
+ "weakest": [ { "row": "r412", "n": 412, "text": "It is fine. Nothing special…", "answered": "praise", "confidence": 0.41 } ] } ] }, // n is the `row` number in answers.csv
+ "findings": [ { "severity": "error", "kind": "sheet", "message": "…" } ] } // a bad sheet.json or a Jev error shows here
+```
-All data in a sheet is made up. Say so in `description`. Never present a sheet as a real inbox,
-real customers, real candidates or real advice.
+- `sheet.loadedAt` did not move ten seconds after your save: the viewer is not running. Ask the
+ person to reopen the harness pane. Do not start one yourself.
+- Then wait for `cellsFilled` to reach `cellsTotal`. The verdict moves every two seconds while a
+ fill runs. With a live key, plan on 30 to 55 seconds for every 1,000 rows, per save. Do not read
+ `answers.csv` for counts before it is full.
+- It is one call per row, so **rewording one column takes as long as the first fill**. It costs
+ less, because only that question is sent. Try a rewording on ten hard rows first (see "Writing
+ sharp questions"), then save once.
+- Saving again while a fill runs is safe. The new sheet loads at once and the old pass is dropped.
+- A save that only changes `suggestions`, `title` or `reviewBelow` asks Jev nothing. A changed
+ `context` asks every question again, because the context is part of every question.
-## Your job
+## The answers file
-1. **Build a sheet on any topic the person asks for.** Write the rows yourself (made-up data), and
- write sharp column questions with a meaning for every option.
-2. **Read the results.** The viewer writes `.harness/verdict.json` with the accuracy of each column,
- how many cells sit under the review line, and the weakest rows. Read it. Do not edit it.
-3. **Sharpen the wording.** Reword the weakest question, save, and read the verdict again. Only the
- changed column is asked again, so this loop is fast.
+`answers.csv` always holds the sheet as it stands. Its columns, in order:
-## The sheet file
+- `row`: 1, 2, 3… in file order. **Quote rows by this number.**
+- the text column, under its own name (`review`, `message`…)
+- the file's other columns. One called `id`, `truth` or `group` gets a trailing underscore (`id_`).
+- for every question, two columns: `<Name>` holds the answer as a word (`yes` or `no`, the option,
+ the level), and `<Name> confidence` holds 0 to 1. `<Name>` is the part of the header before `:` or
+ `?` ("Topic", "Says they will cancel").
-```jsonc
-{
- "title": "Fernhill Cloud inbox",
- "description": "Made-up inbound messages for a company that does not exist. All data is synthetic.",
- "context": "Each row is one inbound message to the shared inbox of a made-up file sync service.",
- "textLabel": "Message", // the heading of the text column
- "reviewBelow": 0.65, // cells with confidence under this get a ? flag (0 to 1)
- "concurrency": 8, // calls in flight at once (1 to 32)
- "demo": true, // the ghost typist demo loop
- "columns": [
- { "id": "urgent", "header": "Urgent?" },
- { "id": "team", "header": "Team: billing = payment or invoice problems | tech = bugs and outages | sales = pricing and quotes" },
- { "id": "anger", "header": "Anger: calm < annoyed < furious" }
- ],
- "suggestions": ["Wants a refund?", "Churn risk: low < medium < high"],
- "rows": [
- { "id": "m01", "from": "Dana Whitfield", "plan": "pro", "group": "clear",
- "text": "Hi, could you send me a copy of the invoice for March?",
- "truth": { "urgent": false, "team": "billing", "anger": "calm" } }
- ]
-}
-```
+A yes or no answer's confidence is how far it is from a coin flip: the larger of p(yes) and p(no),
+so it runs from 0.5 to 1. With the review line at 0.65, a yes or no cell is flagged when p(yes) is
+between 0.35 and 0.65. A choice's confidence is the probability of the option it picked.
-- **`rows`**: 1 to 2000. Each needs a non-empty `text`. Give each a short unique `id`. Any other
- plain field (`from`, `plan`, `channel`) is shown with the row and sent to Jev with the text.
- `group` is a label for you and the pane (`"clear"` or `"mixed"`). It is not sent to Jev.
- `truth` maps a column id to the right answer: `true` or `false` for a yes or no column, the option
- name for a choice, the level name for a score. Truth is optional. It is never sent to Jev.
-- **`columns`**: 0 to 12. A column is a header string, or `{ "id", "header" }`. Give columns an `id`
- when rows have truth labels, so you can reword the header and keep the labels lined up.
-- **`context`**: one sentence about what a row is. It is put in front of every question.
-- **`suggestions`**: headers shown as chips in the pane. The demo loop types them one at a time.
+## Counting
+
+Do not write your own CSV reader: headers and rows hold commas, quotes and line breaks.
+`toolchain/count.mjs` reads `answers.csv` for you and changes nothing. Name a question by its `id`.
+
+```sh
+node "$JEV_DSH/toolchain/count.mjs" # every question: counts, shares, unsure cells
+node "$JEV_DSH/toolchain/count.mjs" --by topic --and leaving # a cross-cut, shares by row
+node "$JEV_DSH/toolchain/count.mjs" --where topic=price --where leaving=going --rows 10 # read the rows behind a number
+node "$JEV_DSH/toolchain/count.mjs" --unsure topic --rows 10 # the least sure rows of a question
+node "$JEV_DSH/toolchain/count.mjs" --find "charged twice" --by topic # a plain word search, cut by a question
+node "$JEV_DSH/toolchain/count.mjs" --where "stars<=2" --by platform # the file's own columns work too
+```
-## The person's own data
+Add `--json` to get the same as data. If you do need a script of your own, keep it in a `scratch/`
+folder in the workspace, so the person's folder stays tidy.
-The template's rows are made up. The real use is the person's own file. If they have a spreadsheet
-export or a log, have them drop it in the workspace, then point the sheet at it:
+## The sheet file
```jsonc
{
- "title": "Inbound leads, week 38",
- "source": "leads.csv", // .csv, .tsv, .jsonl or .json, inside the workspace, up to 8 MB
- "textColumn": "message", // optional. Default: a column named text, message, body, ... or the longest one
- "columns": ["Worth a call today?", "Segment: enterprise = 200+ seats | smb = small team | hobby"]
+ "title": "App reviews, Q3",
+ "description": "Rows from reviews.csv, the person's own file.",
+ "source": "reviews.csv", // .xlsx (first sheet), .csv, .tsv, .jsonl or .json inside the workspace, up to 32 MB
+ "textColumn": "review", // optional. Default: a column named text, message, body, review… or the longest one
+ "textLabel": "review", // the heading of the text column in the pane
+ "context": "Each row is one public review of a note-taking app.",
+ "reviewBelow": 0.65, // cells with confidence under this get a ? flag (0 to 1)
+ "concurrency": 16, // calls in flight at once (1 to 32)
+ "demo": false, // keep this false on a person's own data
+ "columns": [
+ { "id": "topic", "header": "Topic: sync = notes not syncing between devices | price = unhappy with the cost or the plan limits | crash = crashes or freezing | support = unhappy with customer support | praise = happy with the app, no complaint | mixed = likes some of it and dislikes some of it | other = a complaint about something else" },
+ { "id": "leaving", "header": "Leaving: going = says in words that they have cancelled, will switch or will stop using it | wavering = says they may leave, or would stay only if something changes | staying = says nothing about leaving, even if unhappy" },
+ { "id": "lostwork", "header": "Says they lost notes or had to redo work?" }
+ ],
+ "suggestions": ["Asks for a feature?", "Mentions customer support?"]
}
```
-Up to 2,000 rows are used. One column is the row's text. Every other column rides along as a plain
-field that Jev also reads, so "Seats" or "Plan" can inform an answer. The viewer watches the file:
-save it again and the sheet reloads. `rows` may be left out when `source` is set. Rows from the
-file have no truth labels, so the pane shows confidence and review flags, not accuracy.
-
-Look at the file before you write questions: read its header and a few rows, then write columns
-about what is really in it. Never copy the person's data into your replies beyond what you need,
-and never send it anywhere else.
-
-## The answers file
-
-The viewer keeps `answers.csv` in the workspace current: every row, its plain fields, and for each
-Jev column the answer and its confidence (demo columns are left out). Read it to do the next thing
-the person asks: "which twenty should I call first", "how many furious billing tickets", "show me
-the ones Jev was unsure about". Do not edit it. The viewer rewrites it about once a second while
-cells land, and when the pane's columns change.
+- **`source`**: the person's file. Up to 10,000 rows are used. One column is the row's text. Every
+ other column rides along as a plain field that Jev also reads, so "stars" or "plan" can inform an
+ answer. The viewer watches the file: save it again and the rows reload. Rows from a file have no
+ truth labels, so the pane shows confidence and review flags, not accuracy.
+- **`columns`**: 0 to 12. A column is a header string, or `{ "id", "header" }`. Give columns an `id`
+ so you can reword a header and keep its place.
+- **`context`**: one sentence about what a row is. It is put in front of every question. Always set
+ it on a person's own data. It is the cheapest way to make every answer sharper.
+- **`reviewBelow`**: leave it at 0.65 to start. Raise it toward 0.8 when a wrong answer is costly, so
+ more rows go to a person. Lower it when they only want the clear cases.
+- **`suggestions`**: headers shown as one-click chips in the pane.
+- **`rows`**: only for a made-up sheet you write yourself (1 to 10,000, each with a non-empty `text`,
+ optional `id`, plain fields, `group`, and `truth` labels that are never sent to Jev).
+
+What a person does in the pane (typed columns, row edits, sort, filters, the review line) is not
+saved to `sheet.json`. If they like a column they typed, add it to `columns` for them.
## The header grammar
@@ -100,39 +160,85 @@ cells land, and when the pane's columns change.
## Writing sharp questions
- Ask about one thing. "Urgent and angry?" is two questions. Make two columns.
-- Give every choice option a meaning in plain words that would appear in a row. Options cannot see
- each other, and Jev cannot see your other columns.
-- Name score levels so that each one is easy to tell from the next. Three to five levels work best.
-- A yes or no header should read as a full question when the topic is not obvious:
- `Asks for a refund?` beats `Refund?`.
+- Give every choice option a meaning in plain words that would appear in a row. Jev cannot see your
+ other columns, so each question must stand on its own.
+- Rows may not fit your list. Add a catch-all and say what lands in it:
+ `other = a complaint about something else`. When the question is about complaints, also add
+ `praise = happy with the app, no complaint`, or the happy rows get forced into a complaint.
+ Then look at what landed in `other` and split it.
+- A topic like `support = customer support` also catches the happy support stories. When you are
+ counting complaints, say so in the meaning: `support = unhappy with customer support`.
+- **Intent and mood make poor yes or no questions.** "Will they cancel?" is a coin flip on every
+ unhappy row that says nothing about leaving. Ask what the row *says in words*
+ (`Says they lost notes or had to redo work?`), or use a three-way choice with a meaning for each
+ (`going | wavering | staying`). A tone scale (`calm < annoyed < furious`) is often the weakest
+ column on evenly written text. If a quarter of its cells stay under the line after one reword,
+ say so in the findings and do not rank anything by it.
+- A score level is only its words, it cannot take a meaning. Make the words carry it:
+ `no complaint < mild complaint < strong complaint`. Three to five levels work best.
+- A yes or no header should read as a full question: `Asks for a refund?` beats `Refund?`.
- Put shared facts in `context`, not in every header.
+- Characters: the first `:` ends the name, `|` splits options, the first `=` in an option starts its
+ meaning, and `<` makes a score. So keep `|` and `<` out of names and meanings. Commas, `?`, quotes
+ and a later `:` or `=` are fine.
+- A choice in `suggestions` needs its meanings too, the same as in `columns`.
+
+To try a question on a few rows before it goes in the sheet:
+
+```js
+import { evaluate, jev } from '<the harness folder>/toolchain/jev.mjs' // $JEV_DSH
+const CONTEXT = 'Each row is one public review of a note-taking app. ' // the viewer puts `context` in front of every question; do the same
+const r = await evaluate({ state: { text: 'It crashes when I paste an image', stars: 1 }, // the row: its text plus its other columns
+ questions: {
+ crash: jev.noul(CONTEXT + 'Mentions a crash?'),
+ topic: jev.choice({ crash: 'crashes or freezing', price: 'unhappy with the cost', other: 'a complaint about something else' }, CONTEXT + 'Topic: which option fits this row best?'),
+ strength: jev.score(['no complaint', 'mild complaint', 'strong complaint'], CONTEXT + 'Complaint strength: where does this row sit on the scale?') } })
+console.log(r.client) // "mock" means there is no key
+console.log(r.answers.crash) // { type: 'noul', noul: 0.97 } the probability of yes
+console.log(r.answers.topic) // { type: 'choice', choice: 'crash', confidence: 0.99, probabilities: { crash: 0.99, … } }
+console.log(r.answers.strength) // { type: 'score', score: 1.8, confidence: 0.74, legend: { '0': 'no complaint', … }, probabilities: { '0': …, '1': …, '2': … } }
+```
+
+Run a rewording on the ten rows it got wrong before you put it in the sheet: a trial takes seconds,
+a full pass takes most of a minute.
+
+## Being honest about the answers
+
+- Jev's confidence is real information. A column where most cells sit near 50% is a vague question,
+ not a finding. Say so and reword it.
+- Before you report a number that matters, open the rows behind it (filter `answers.csv`) and read
+ ten of them. Report what you saw.
+- **Check that the file makes sense.** If a cross-cut comes out flat, or a happy five-star row says
+ it is leaving, or a column contradicts the text, read twenty rows and tell the person. Jev reads
+ the words that are there. It cannot know that an export glued the wrong sentences together.
+- You find, count and quote. You do not give legal, medical, financial or hiring advice from a
+ column of answers, and you say so if the person's data invites it.
+- Their data stays in the workspace. The rows go to the Jev API to be answered and nowhere
+ else. Never send it anywhere else, and never copy more of it into the chat than you need.
-## Making the sheet honest
+## Without a key
-Write most rows with one clear signal. Then add a block of rows with mixed signals on purpose and
-mark them `"group": "mixed"` ("No rush, but production is down"). Jev should be less sure on those,
-and the review line should catch them. If confidence is just as high on the mixed rows, or the clear
-rows are often wrong, report it. Do not hide it by deleting rows.
+`"client": "mock"` in the verdict means there is no Jev key, and an offline stand-in that only
+matches words is answering. On a person's own data its answers are not good enough to act on, and
+the pane says so in a yellow bar. Do not write findings from them. Tell the person to paste a key
+into the **Jev · live mind** panel in the pane (an OpenRouter key from `openrouter.ai/keys` takes
+about a minute). The key is saved on their machine in `~/.config/typesafe/credentials`, and every
+cell is then asked again. Never ask them to paste a key into the chat.
## Rules
- Keep `sheet.json` valid JSON. A bad edit does not crash the pane: it keeps the last good sheet and
- shows the error. Fix the file when you see that.
+ shows the error in the pane and in the verdict's `findings`. Fix the file when you see that.
- Validate with `node "$JEV_DSH/toolchain/check.mjs"` before you say you are done.
-- Do not edit `.harness/verdict.json`. The viewer writes it. You may read it.
-- What a person does in the pane (typed columns, row edits, sort, the review line) is not saved to
- `sheet.json`. If they like a column they typed, add it to `columns` for them.
-- Without a `TYPESAFE_API_KEY` the harness runs on a deterministic local mock that reads word cues.
- It is a stand-in for the plumbing, not for Jev's judgement. On the mock, rows must use the same
- words as the option meanings to be read well. With a key, the viewer calls the real API.
-- You can ask Jev directly through `toolchain/jev.mjs` (`evaluate`, `jev.noul`, `jev.choice`,
- `jev.score`) to try a question on a few rows before you put it in the sheet.
-- This is a demo on made-up data. Keep `title` and `description` truthful.
+- Do not edit `.harness/verdict.json` or `answers.csv`. The viewer writes them. You may read them.
+- A sheet you wrote yourself is made up. Say so in `description`, and never present made-up rows as
+ real customers, real candidates or real results.
## Definition of done
-- `sheet.json` passes `toolchain/check.mjs`.
-- The sheet is on the topic the person asked for, with made-up rows and a mixed-signal block.
-- Every choice option has a meaning. Every score has clear levels.
-- You have read `.harness/verdict.json` and told the person, in plain words: how right each column
- is, how many cells need review, and which question you would sharpen next.
+- The person's own data is in the sheet (or they chose the sample, knowing it is made up).
+- `sheet.json` passes `toolchain/check.mjs`. Every choice option has a meaning. `context` is set.
+- The verdict shows your save was loaded, a live `client`, and every cell filled.
+- You read `answers.csv`, opened the rows behind the main numbers, and wrote `findings.md`.
+- You told the person, in plain words: the three findings that matter, how sure Jev was, and the
+ next question worth asking.
diff --git a/store/agents/jev-sheets/README.md b/store/agents/jev-sheets/README.md
index 44fefd987..9f2a7dc2a 100644
--- a/store/agents/jev-sheets/README.md
+++ b/store/agents/jev-sheets/README.md
@@ -1,124 +1,157 @@
# Jev Sheets
-**A spreadsheet where a column header is a question.** Type `Urgent?` at the top of a column and
-Jev, TypeSafe's System One model, answers it for every row. Each answer comes with a probability,
-so every cell is shaded by how sure Jev is, and the unsure ones are flagged for a person to review.
+![Jev Sheets logo](brand/logo.svg)
-This is a harness for OpenHarness. The agent on the right edits `sheet.json`. The viewer on the left
-is the sheet. It asks Jev one call per row, with every Jev column as a parallel question in that
-call, so a new column fills the sheet in a wave, top to bottom, in about a second.
+**Ask your spreadsheet anything, and get an answer for every row.** Drop in a pile of text you could
+never read in full: 5,000 app reviews, a survey's free-text answers, a quarter of support tickets,
+a list of leads. Type a question in plain words as a column header. Jev, TypeSafe's System One
+model, answers it for every row in seconds, for cents, and says how sure it is of each answer.
-All the data is made up. The template is 60 inbound sales and support messages for Fernhill Cloud,
-a file sync company that does not exist. The names, the messages and the truth labels are synthetic.
+It turns one person into a research team. Work that used to mean a week of reading and tagging by
+hand, or a script and an afternoon, becomes a question you type.
-## Bring your own file
+This is a harness for OpenHarness. The pane on the left is the sheet. The agent on the right is your
+analyst: it looks at your file, writes sharp questions with you, reads the answers and writes up the
+findings.
-The starter rows are made up. Put your own `leads.csv` (or `.tsv`, `.jsonl`, `.json`) in the workspace
-and set `"source": "leads.csv"` in `sheet.json`. Up to 2,000 rows load, one column becomes the row's
-text and the others ride along as fields Jev also reads. Then type any question as a column header.
-With a live key that is a few seconds and a fraction of a cent for a question over every row.
+## Bring your file
-## You get a file back
+- **Drop it on the pane.** An Excel `.xlsx` file (its first sheet), or `.csv`, `.tsv`, `.json` or
+ `.jsonl`, up to 32 MB and 10,000 rows.
+- **Paste rows** copied from Excel or Google Sheets, anywhere on the pane.
+- **Tell the agent where it is.** It copies the file in. It can also turn a PDF, a chat export or a
+ folder of notes into rows for you.
-`answers.csv` in the workspace always holds the sheet as it stands: each row, its fields, and every
-Jev column's answer with its confidence. Open it in a spreadsheet, or ask the agent on the right to
-work from it.
+One column is the row's text (a column called `text`, `message`, `review`… or the longest one). The
+other columns ride along as context, so "stars" or "plan" can inform an answer. The file is saved
+in your project folder. Its rows go to the Jev API to be answered, and nowhere else.
-## The header grammar
+The pane opens on a small made-up sample so there is something to try in the first ten seconds. It
+is labelled as made up, and one click takes you back to it.
+
+## Ask
| You type | It becomes |
|---|---|
-| `Urgent?` | a yes or no question (`noul`). Ends with a question mark. |
-| `Team: billing \| tech \| sales` | a `choice` of 2 to 255 options |
-| `Team: billing = payment or invoice problems \| tech = bugs and outages` | the same, with a meaning for each option. This makes Jev sharper. |
+| `Thinking of leaving?` | a yes or no question (`noul`). Ends with a question mark. |
+| `Topic: sync \| price \| crash` | a `choice` of 2 to 255 options |
+| `Topic: sync = notes not syncing \| price = cost or subscription` | the same, with a meaning for each option. This makes Jev sharper. |
| `Anger: calm < annoyed < furious` | a `score` on 2 to 10 ordered levels |
| `Urgency` | a bare word becomes a score: `low < medium < high` |
-One parser (`viewer/grammar.mjs`) is used by the viewer, by the pane while you type, and by
-`toolchain/check.mjs`.
+Press Enter and the column fills in a wave. Every question on the sheet is asked in one call per
+row, so five questions cost about the same as one. Or ask the agent: "what should I be asking
+this file?"
+
+## Read the answers
+
+- **Answers so far** counts every answer for every question. Click a count to see only those rows.
+- Cells fade when Jev is less sure. A **?** marks a cell under the review line. Drag the line, or
+ turn on "needs review only", to see the rows a person should look at.
+- Click a cell to see the exact question Jev was asked and the full probabilities.
+- Click a header to sort. Double-click a row to edit its text: it is judged again at once.
+
+## Take it away
+
+- **`answers.csv`** holds every row, its own columns, and each answer with its confidence. Download
+ it from the pane, or find it in the project folder. Cells that could run as a formula are escaped.
+- **`findings.md`**: ask the agent for the findings. It leads with the answer, counts with the
+ shipped `toolchain/count.mjs` (counts, cross-cuts, the rows behind a number), and quotes rows word
+ for word with their row numbers.
+
+## What it costs
+
+Measured on 2026-09-20 with live Jev (`typesafe/jev-1.13`) through OpenRouter, on a made-up file of
+1,200 app reviews dropped on the pane, with three questions asked together (a seven-way topic, "says
+they may cancel or switch?" and an anger scale):
+
+| rows | questions | time | cost | topic right, clear rows | topic right, above the review line |
+|---|---|---|---|---|---|
+| 1,200 | 3 | 36 s | $0.028 | 96.5% | 98.7% |
-## What you can do in the pane
+All 119 reviews that said "I am close to switching" were found. One run on made-up reviews is a
+sanity check, not a benchmark. OpenRouter answers in about half a
+second a call. The native TypeSafe API is several times faster.
-- Type a header in the add box and press Enter. The column appears and fills in a wave.
-- Click a header to sort by it. Click again to reverse, again to clear. Rows slide to their places.
-- Click the small x on a header to remove the column.
-- Click a cell to inspect it: the row, the question Jev was asked, the full probability bars, and
- the truth label if there is one.
-- Double-click a message to edit it. That row is judged again at once, across all columns.
-- Turn on "needs review only", and drag the review line. A small histogram shows where the
- confidence of all cells sits.
-- Reset drops everything done in the pane and judges the sheet again from `sheet.json`.
+## Tested cold
-While nobody is playing, a "ghost typist" types a suggested header every 20 seconds or so, lets it
-fill, and retires the older demo column. It is tagged "demo". Anything you do rests it for a minute,
-and the demo button turns it off.
+A fresh agent was given only this harness's `AGENTS.md` and skill, a workspace with the 1,200 made-up
+reviews already dropped on the pane, and one sentence: "What are people complaining about most, who
+is about to leave us and why, and what should we fix first?" In 16 minutes and $0.18 of Jev calls
+it wrote five questions, reworded three of them after reading the unsure rows, and wrote findings
+with counts, cross-cuts and quoted rows. It also noticed by itself that the made-up file glues
+closing sentences onto reviews at random, and said so. The first cold run had failed outright, and
+that is how the bugs it hit got fixed. The tool's weak spot stays a tone scale on evenly written
+text: about a quarter of those cells remained unsure, and the findings said not to rank by it.
-## The honest dial
+## A key
-The dial is ambiguity. The template has 44 clear rows and 16 rows written with mixed signals on
-purpose ("No rush at all, but our production backups have been failing since Monday"). Nothing is
-randomised. On the offline mock the tests measure:
+Real answers need a Jev key. Paste one into the **Jev · live mind** panel in the pane. An OpenRouter
+key (`openrouter.ai/keys`) takes about a minute and has no waitlist. A TypeSafe key works too. The
+key is checked with one tiny call and saved on your machine in `~/.config/typesafe/credentials`
+(chmod 600). It is never shown again and never leaves the machine except to call the API.
+Cloudflare Workers AI is a third route: see `toolchain/README.md`.
-- clear rows: average confidence 0.86, 99% right
-- mixed rows: average confidence 0.72, 73% right
-- cells under the 0.65 review line: 1.5% of clear cells, 44% of mixed cells
+Without a key the pane runs on an offline stand-in that only matches words. It shows how the tool
+works. It is not good enough for your own data, and the pane says so in a yellow bar. After you
+connect, every cell is asked again, for real.
-So the review line catches the rows a person should look at. Move the line and the count moves.
+## Being honest
+
+- Jev's confidence is real information. A column where most answers sit near 50% is a vague
+ question, not a finding. Reword it.
+- Read the rows behind a number before you act on it. One click on the count shows them.
+- It finds, counts and sorts. It is not legal, medical, financial or hiring advice.
+- The pane only accepts requests from itself: a web page on another site cannot upload a file, press
+ a control or set a key.
+
+## The sample, and the honest dial
+
+The made-up sample is 60 inbound messages to Fernhill Cloud, a file sync company that does not
+exist, with truth labels. 44 rows are clear and 16 carry mixed signals on purpose ("No rush at all,
+but our production backups have been failing since Monday"). Nothing is randomised. The tests
+measure, on the offline stand-in: clear rows 0.86 average confidence and 99% right, mixed rows 0.72
+and 73% right, and 44% of mixed cells under the review line against 1.5% of clear ones. With live
+Jev on the same 60 rows: Team 98%, Anger 90%, Urgent 85%, filled in 5.4 s for $0.0013. So the review
+line catches the rows a person should look at.
## Anatomy
```
jev-sheets/
harness.json DSH manifest (engine: claude)
- AGENTS.md what the chat agent does: build sheets, sharpen questions
- skills/sheets/SKILL.md the craft of writing rows and questions
- template/sheet.json the starter sheet (60 made-up messages, 3 Jev columns, truth labels)
+ AGENTS.md the agent's job: get the file in, ask sharp questions, write the findings
+ skills/sheets/SKILL.md the craft of questions, review and the report
+ template/sheet.json the made-up sample (60 messages, 3 Jev columns, truth labels)
toolchain/
- jev.mjs the Jev client (real TypeSafe API, or a deterministic mock)
+ jev.mjs the Jev client (TypeSafe, Cloudflare or OpenRouter, or the offline stand-in)
check.mjs validates sheet.json
+ count.mjs counts answers.csv: every answer, cross-cuts, the rows behind a number
viewer.sh setup.sh doctor.sh init-workspace.sh
viewer/
- viewer.mjs the server: owns the sheet, the call pool, the cache, the verdict
+ viewer.mjs the server: the sheet, uploads, the call pool, the cache, answers.csv, the verdict
+ source.mjs reads the person's file: Excel, CSV, TSV, JSON, JSONL
+ xlsx.mjs a small Excel reader: zip directory, shared strings, the first sheet
grammar.mjs the header parser, shared with the pane and check.mjs
- mock.mjs the offline stand-in reader (reads only the row text and the question)
- kit.mjs loopback server, SSE, config watcher, verdict writer
+ mock.mjs the offline stand-in (reads only the row text and the question)
+ kit.mjs loopback server, same-origin guard, upload, download, key connect, SSE
index.html studio.css studio.js base.css jev-hud.js the pane
- test/viewer.test.mjs
+ test/viewer.test.mjs own-file.test.mjs xlsx.test.mjs count.test.mjs
```
## How it runs
-`viewer/viewer.mjs` serves the pane on a loopback port and watches `sheet.json`. For each row with a
-missing cell it sends one `evaluate()` call: the row is the state, and every missing Jev column is a
-question. Eight calls run at a time. Answers are cached by row text plus column definition, so
-adding a column asks only for that column, editing a row asks only for that row, and adding rows
-asks only for the new rows. A bad JSON edit keeps the last good sheet on screen and shows the error.
-
-The viewer writes `.harness/verdict.json` itself: cells filled, cells under the review line, the
-accuracy of each column against the truth labels, and the weakest rows of each column. The chat
-agent reads it to decide which question to sharpen.
-
-With `TYPESAFE_API_KEY` set, the calls go to the real API (`POST /v1/systemone`). Without it, the
-harness runs on a deterministic local mock. The mock reads word cues in the row text, so it is a
-stand-in for the plumbing and not for Jev's judgement. It paces each call at about 90 ms so the
-wave looks like the live one. The pane always shows a MOCK or LIVE badge.
-
-## Jev, honestly
-
-The public claims about Jev are speed and price: about 100 ms per call, and $0.042 per million input
-tokens with free output. This harness shows both numbers live, and the cost of filling the whole
-template is well under a cent. But the inbox is made up, the truth labels are one person's opinion
-about made-up messages, and the accuracy you see offline is the mock's, not Jev's. Treat it as a
-demo of a pattern (typed questions over rows, with calibrated confidence and a review line), not as
-a measurement of any real support queue.
-
-## Measured with the real model
+`viewer/viewer.mjs` serves the pane on a loopback port and watches `sheet.json` and the source file.
+For each row with a missing cell it sends one `evaluate()` call: the row is the state, and every
+missing Jev column is a question. Up to 32 calls run at a time. Answers are cached by row text plus
+column definition, so a new column asks only for that column, an edited row asks only for that row,
+and new rows ask only for themselves. A bad JSON edit keeps the last good sheet on screen and shows
+the error. The viewer writes `answers.csv` and `.harness/verdict.json` itself. The agent reads both.
-One short run on 2026-09-20 with live Jev (`typesafe/jev-1.13`) through OpenRouter, about 0.45 s a call once warm. Small samples on made-up data: a sanity check, not a benchmark.
+## Logo and icon
-The 60-row template with its three starter columns filled in 5.4 s for $0.0013 (60 calls, three
-questions each). Against the made-up truth labels: Team 98%, Anger 90%, Urgent 85%. Average
-confidence was 0.90 on the clear rows and 0.79 on the mixed-signal rows, so the review line does its job.
+The original identity ships in `brand/`: [vector icon](brand/icon.svg), [256px PNG](brand/icon.png),
+[light logo](brand/logo.svg) and [dark logo](brand/logo-dark.svg). MIT, by Autonomous.
## Credit and stewardship
diff --git a/store/agents/jev-sheets/brand/assets.json b/store/agents/jev-sheets/brand/assets.json
new file mode 100644
index 000000000..378769253
--- /dev/null
+++ b/store/agents/jev-sheets/brand/assets.json
@@ -0,0 +1,10 @@
+{
+ "source": "icon.svg",
+ "license": "MIT",
+ "sha256": {
+ "icon.svg": "d0e101ed607b7af6ee6bf21e19eb4373b885840050e609174f37444f16b1bc4e",
+ "logo.svg": "0a6f1fdf53ada2a1181d36d45ffbeca0f5b1a8cfcf1fbbce1cd39029cbbcc124",
+ "logo-dark.svg": "6e51fb65d989eed11c8e7594dbaeb2a8bbe4c5e5e1285f2206afa57ad17e49ff",
+ "icon.png": "227c0dcbc673f6b61d450d6b34b92ed44514205a7636081cb4976caa7700ee81"
+ }
+}
diff --git a/store/agents/jev-sheets/brand/icon.png b/store/agents/jev-sheets/brand/icon.png
new file mode 100644
index 000000000..5ee878a21
Binary files /dev/null and b/store/agents/jev-sheets/brand/icon.png differ
diff --git a/store/agents/jev-sheets/brand/icon.svg b/store/agents/jev-sheets/brand/icon.svg
new file mode 100644
index 000000000..1f8fe2b87
--- /dev/null
+++ b/store/agents/jev-sheets/brand/icon.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
+ <title>Jev Sheets — one question, a column of answers</title>
+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#2b2010"/>
+ <rect x="16" y="17" width="64" height="62" rx="9" fill="#6e5d37"/>
+ <path d="M25 17h26.5v19H16V26a9 9 0 0 1 9-9Z" fill="#b89c5e"/>
+ <path d="M51.5 17H71a9 9 0 0 1 9 9v10H51.5Z" fill="#fde7a3"/>
+ <path d="M51.5 36H80v34a9 9 0 0 1-9 9H51.5Z" fill="#fbbf24"/>
+ <path d="M33 17v62M51.5 17v62M16 36h64M16 51h64M16 66h64" stroke="#2b2010" stroke-width="3.5"/>
+ <path d="M59 22v7" stroke="#2b2010" stroke-width="3" stroke-linecap="round"/>
+</svg>
diff --git a/store/agents/jev-sheets/brand/logo-dark.svg b/store/agents/jev-sheets/brand/logo-dark.svg
new file mode 100644
index 000000000..7d56cf905
--- /dev/null
+++ b/store/agents/jev-sheets/brand/logo-dark.svg
@@ -0,0 +1,13 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="480" height="112" viewBox="0 0 480 112">
+ <title>Jev Sheets logo</title>
+ <rect width="480" height="112" rx="24" fill="#18252b"/>
+ <g transform="translate(8 8)"><rect x="4" y="4" width="88" height="88" rx="23" fill="#2b2010"/>
+ <rect x="16" y="17" width="64" height="62" rx="9" fill="#6e5d37"/>
+ <path d="M25 17h26.5v19H16V26a9 9 0 0 1 9-9Z" fill="#b89c5e"/>
+ <path d="M51.5 17H71a9 9 0 0 1 9 9v10H51.5Z" fill="#fde7a3"/>
+ <path d="M51.5 36H80v34a9 9 0 0 1-9 9H51.5Z" fill="#fbbf24"/>
+ <path d="M33 17v62M51.5 17v62M16 36h64M16 51h64M16 66h64" stroke="#2b2010" stroke-width="3.5"/>
+ <path d="M59 22v7" stroke="#2b2010" stroke-width="3" stroke-linecap="round"/></g>
+ <text x="120" y="53" fill="#f4f0e4" font-family="Arial, Helvetica, sans-serif" font-size="28" font-weight="600" letter-spacing="-.8">Jev Sheets</text>
+ <text x="121" y="76" fill="#a7bbb7" font-family="Arial, Helvetica, sans-serif" font-size="10" font-weight="600" letter-spacing="2.1">COLUMNS · AUTONOMOUS</text>
+</svg>
diff --git a/store/agents/jev-sheets/brand/logo.svg b/store/agents/jev-sheets/brand/logo.svg
new file mode 100644
index 000000000..874a649a1
--- /dev/null
+++ b/store/agents/jev-sheets/brand/logo.svg
@@ -0,0 +1,13 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="480" height="112" viewBox="0 0 480 112">
+ <title>Jev Sheets logo</title>
+ <rect width="480" height="112" rx="24" fill="#f5f2e9"/>
+ <g transform="translate(8 8)"><rect x="4" y="4" width="88" height="88" rx="23" fill="#2b2010"/>
+ <rect x="16" y="17" width="64" height="62" rx="9" fill="#6e5d37"/>
+ <path d="M25 17h26.5v19H16V26a9 9 0 0 1 9-9Z" fill="#b89c5e"/>
+ <path d="M51.5 17H71a9 9 0 0 1 9 9v10H51.5Z" fill="#fde7a3"/>
+ <path d="M51.5 36H80v34a9 9 0 0 1-9 9H51.5Z" fill="#fbbf24"/>
+ <path d="M33 17v62M51.5 17v62M16 36h64M16 51h64M16 66h64" stroke="#2b2010" stroke-width="3.5"/>
+ <path d="M59 22v7" stroke="#2b2010" stroke-width="3" stroke-linecap="round"/></g>
+ <text x="120" y="53" fill="#243732" font-family="Arial, Helvetica, sans-serif" font-size="28" font-weight="600" letter-spacing="-.8">Jev Sheets</text>
+ <text x="121" y="76" fill="#63746b" font-family="Arial, Helvetica, sans-serif" font-size="10" font-weight="600" letter-spacing="2.1">COLUMNS · AUTONOMOUS</text>
+</svg>
diff --git a/store/agents/jev-sheets/harness.json b/store/agents/jev-sheets/harness.json
index cfeceb5d6..2b0a61001 100644
--- a/store/agents/jev-sheets/harness.json
+++ b/store/agents/jev-sheets/harness.json
@@ -4,7 +4,7 @@
"name": "Jev Sheets",
"category": "Productivity",
"author": "Autonomous",
- "description": "A live spreadsheet where a column header is a question. Type \"Urgent?\" and Jev, TypeSafe's System One model, answers it for every row: one call per row, all columns at once, each cell shaded by confidence and flagged for review when unsure. Made-up data. Runs offline on a mock.",
+ "description": "Ask your spreadsheet anything. Drop in reviews, survey answers, tickets or leads, type a question in plain words, and Jev, TypeSafe's System One model, answers it for every row in seconds for cents, with a confidence on each. Take away a coded file and a findings report.",
"engine": "claude",
"workspace": {
"template": "template",
diff --git a/store/agents/jev-sheets/skills/sheets/SKILL.md b/store/agents/jev-sheets/skills/sheets/SKILL.md
index 018054a6e..78e9337ab 100644
--- a/store/agents/jev-sheets/skills/sheets/SKILL.md
+++ b/store/agents/jev-sheets/skills/sheets/SKILL.md
@@ -1,8 +1,9 @@
# Craft: Jev Sheets
Jev Sheets is a spreadsheet where a column header is a typed question and Jev answers it for every
-row. The craft has two halves: writing rows that feel real, and wording questions so the answers
-are right and the confidence is honest. All rows are made up. Say so in `description`.
+row. The person brings a file they could never read in full. The craft is wording questions so the
+answers are right and the confidence is honest, then turning the answers into findings a person can
+act on. A made-up sheet is only the fallback when they have no file at hand.
## How one row is judged
@@ -34,7 +35,40 @@ Urgency score (bare word: low < m
In `sheet.json` a column is a header string or `{ "id": "team", "header": "Team: ..." }`. Use an
`id` whenever rows carry `truth`, so rewording the header does not orphan the labels.
-## Building a sheet on a new topic
+## Working on the person's own file (the main job)
+
+1. **Get it in.** They drop it on the pane or paste rows, and `"source"` appears in `sheet.json` by
+ itself. Or they give you a path: copy it into the workspace and set `"source"` (an Excel `.xlsx` works as it is: the first sheet is read). A PDF,
+ a chat export or a folder of notes: convert it to a `.csv` or `.jsonl` in the workspace, one row
+ per item, keeping a column that says where each row came from. Long documents: one row per
+ paragraph or clause.
+2. **Look.** Read the header and about twenty rows. Say in two lines what is in it. Set `context`
+ to one sentence about what a row is, and `textColumn` if the guess was wrong.
+3. **Aim at their decision.** If they already said what they want to know, do not ask again. If
+ not, ask what they are trying to decide. Then write three to five questions aimed at that. Mix the
+ types: one yes or no, one choice with a meaning for every option and an `other`, one score. The
+ other columns are part of what Jev reads, so a question can lean on them ("Worth a call today?"
+ can use a `seats` column).
+4. **Check the save took, then read the answers.** In `.harness/verdict.json`, `sheet.loadedAt`
+ moves within two seconds of a save, and the fill is done when `sheet.cellsFilled` equals
+ `sheet.cellsTotal` (30 to 40 seconds for every 1,000 rows with a live key; `"client": "mock"` means
+ no key, so stop and say so). `answers.csv` has a `row` number, the text, the file's own columns,
+ and for each question the answer as a word plus `<Name> confidence`. There are no truth labels, so judge a question by how many cells sit under the review
+ line and by reading the rows behind the numbers.
+5. **Write `findings.md`.** What was asked and of how many rows. For each question the count and share
+ of every answer. For each finding that matters, three to five word-for-word quotes with row
+ numbers (lead with the answer in the first five lines). A cross-cut or two when it says something ("of the 212 crash reports, 61% also say they
+ may leave"). What Jev was unsure about. The next question worth asking. Count with
+ `node "$JEV_DSH/toolchain/count.mjs"` (counts, `--by a --and b` cross-cuts, `--where a=b --rows 10`
+ to read the rows behind a number, `--unsure a`, `--find "words"`), never by eye.
+6. **Sharpen and repeat.** Split a fat `other`. Reword a column whose answers sit near 50%: a yes
+ or no about intent usually wants to become "says in words that…" or a three-way choice. Try the
+ rewording on ten hard rows through `toolchain/jev.mjs` first, because a full pass takes most of a
+ minute per 1,000 rows however few columns changed.
+
+Keep their data in the workspace. Quote only what the report needs.
+
+## Building a made-up sheet (when they have no file)
1. Pick the unit of a row (a message, a review, an application, a bug report) and write `context`
in one sentence.
@@ -49,14 +83,6 @@ In `sheet.json` a column is a header string or `{ "id": "team", "header": "Team:
6. Add six to ten `suggestions`: more headers a person could try on the same rows.
7. Run `node "$JEV_DSH/toolchain/check.mjs"`.
-## Working on the person's own file
-
-Set `"source": "<file in the workspace>"` (csv, tsv, jsonl or json) and optionally `"textColumn"`.
-Read the file's header and a few rows first. Write columns about what is really there. The other
-columns are part of what Jev reads for each row, so questions can lean on them ("Worth a call
-today?" can use a `seats` column). There are no truth labels, so judge the questions by the review
-count and by reading the flagged rows in the verdict.
-
## Reading the verdict
The viewer writes `.harness/verdict.json`. Read `sheet.columns[]`:
@@ -81,7 +107,8 @@ Change one column at a time, save, and read the verdict again. Report what moved
## The offline mock
-Without `TYPESAFE_API_KEY`, a local mock answers. It counts word cues: the words of the header, the
+Without a Jev key, a local mock answers. On a person's own data it is not good enough to act on: the
+pane says so, and the fix is a key pasted into the pane's live panel, never into the chat. It counts word cues: the words of the header, the
option names and their meanings, plus a small built-in list for common ideas (urgency, anger,
billing, bugs, sales, refunds, churn, sentiment, spam, security). It knows nothing else. On the
mock, a column only works if the rows use words that the option meanings also use. So write
@@ -90,6 +117,11 @@ accuracy says nothing about live Jev.
## Definition of done
+On the person's own file: `sheet.json` passes `check.mjs`, `context` is set, every choice option has
+a meaning, you read `answers.csv` and the rows behind the main numbers, and `findings.md` is written.
+
+On a made-up sheet:
+
- `sheet.json` passes `check.mjs`.
- Made-up rows on the asked topic, with a mixed-signal block and truth labels.
- Every choice option has a meaning. Scores have clear, ordered levels.
diff --git a/store/agents/jev-sheets/store.json b/store/agents/jev-sheets/store.json
index 6f43c0a70..7ed4c2575 100644
--- a/store/agents/jev-sheets/store.json
+++ b/store/agents/jev-sheets/store.json
@@ -2,16 +2,20 @@
"homepage": "https://typesafe.ai",
"upstream": "https://typesafe.ai",
"license": "MIT",
- "tagline": "Type a question as a column header and Jev answers it for every row, live",
+ "tagline": "Drop in any spreadsheet, ask in plain words, get every row answered in seconds",
"examples": [
{
- "prompt": "Build me a sheet of 80 made-up job applications for a junior designer role. Add Jev columns: \"Has a portfolio link?\", \"Fit: weak < fair < strong\" and \"Next step: reject = no relevant work | phone screen = some relevant work | interview = strong relevant work\". Put in 15 rows with mixed signals, label the truth, then read the accuracy and sharpen the weakest question.",
- "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-sheets/typed-column.jpg",
- "caption": "A header is a question: Jev fills every row in about a second, and the pane shows where it is unsure"
+ "prompt": "I dropped my app reviews export on the pane. Read a sample of it, then work out what people complain about most, who is thinking of leaving, and how angry they are. Write me a findings report with the counts and word-for-word quotes.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-sheets/own-file.jpg",
+ "caption": "1,200 reviews, three questions, 36 seconds, 3 cents: the 119 who may leave. The reviews shown are made up"
},
{
- "prompt": "Turn the inbox sheet into a churn watch. Keep the rows, replace the columns with \"Wants to cancel?\", \"Churn risk: low < medium < high\" and \"Reason: price | bugs | missing feature | support\" with a clear meaning for each option. Then tell me which rows Jev is least sure about and why.",
- "caption": "Reword the questions, watch only the changed column fill again, and review the low confidence cells"
+ "prompt": "Our survey export is in survey.csv with 3,000 free-text answers. Code every answer by theme, tell me the top five themes among the unhappy customers, and list the 20 answers I should read myself.",
+ "caption": "The agent writes the questions with you, Jev answers them for every row, and the review line shows what to read"
+ },
+ {
+ "prompt": "tickets.csv is last month of support tickets. Send each one to a team, flag the urgent ones, and tell me which three problems cost us the most tickets. Save the result so I can open it in Excel.",
+ "caption": "Every row gets an answer and a confidence. answers.csv is yours to keep"
}
]
}
diff --git a/store/agents/jev-sheets/test/count.test.mjs b/store/agents/jev-sheets/test/count.test.mjs
new file mode 100644
index 000000000..04f0d5a52
--- /dev/null
+++ b/store/agents/jev-sheets/test/count.test.mjs
@@ -0,0 +1,76 @@
+// toolchain/count.mjs: the one tested reader of answers.csv that findings rest on.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, mkdirSync } from 'node:fs'
+import { spawnSync } from 'node:child_process'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const COUNT = join(dirname(fileURLToPath(import.meta.url)), '../toolchain/count.mjs')
+
+// A header with a comma and a quote in it, and a review with a comma, a quote and a line break:
+// the things a hand-written parser gets wrong.
+const ANSWERS = [
+ 'row,review,id_,stars,Topic,Topic confidence,"Says they will cancel, or switch",' + '"Says they will cancel, or switch confidence"',
+ '1,"Too expensive, ""way"" too expensive",a1,1,price,0.97,yes,0.91',
+ '2,It crashes on launch,a2,2,crash,0.99,no,0.88',
+ '3,"Crashes when I paste\nan image",a3,1,crash,0.58,yes,0.52',
+ '4,Best notes app,a4,5,praise,0.95,no,0.97',
+ '5,The price doubled,a5,2,price,0.93,yes,0.61',
+ '6,Still waiting for an answer,a6,3,,,,',
+].join('\n') + '\n'
+
+function workspace() {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-sheets-count-'))
+ writeFileSync(join(ws, 'answers.csv'), ANSWERS)
+ writeFileSync(join(ws, 'sheet.json'), JSON.stringify({ source: 'x.csv', columns: [{ id: 'topic', header: 'Topic: price = cost | crash = crashes | praise = happy' }, { id: 'leaving', header: 'Says they will cancel, or switch?' }] }))
+ mkdirSync(join(ws, '.harness'))
+ writeFileSync(join(ws, '.harness/verdict.json'), JSON.stringify({ sheet: { reviewBelow: 0.65 } }))
+ return ws
+}
+const run = (ws, ...args) => spawnSync('node', [COUNT, ...args], { encoding: 'utf8', env: { ...process.env, HARNESS_WORKSPACE: ws } })
+const json = (ws, ...args) => { const r = run(ws, ...args, '--json'); assert.equal(r.status, 0, r.stderr); return JSON.parse(r.stdout) }
+
+test('every question: counts, shares and unsure cells, with an unanswered row left out', () => {
+ const ws = workspace()
+ const out = json(ws)
+ assert.equal(out.rows, 6)
+ assert.deepEqual(out.questions.Topic, { id: 'topic', answered: 5, unsure: 1, averageConfidence: 0.884, counts: { price: 2, crash: 2, praise: 1 } })
+ const leaving = out.questions['Says they will cancel, or switch']
+ assert.equal(leaving.id, 'leaving')
+ assert.deepEqual(leaving.counts, { yes: 3, no: 2 })
+ assert.equal(leaving.unsure, 2)
+ const text = run(ws).stdout
+ assert.match(text, /Topic\s+\[topic\]\s+·\s+5 of 6 rows answered\s+·\s+1 under 0\.65 \(20\.0%\)/)
+ assert.match(text, /price\s+2\s+40\.0%/)
+})
+
+test('a cross-cut, by id, by name or by the start of either, and over the file\'s own columns', () => {
+ const ws = workspace()
+ const cross = json(ws, '--by', 'topic', '--and', 'leaving').cross
+ assert.deepEqual(cross.values, ['yes', 'no', '(no answer yet)'])
+ assert.deepEqual(cross.table.find((r) => r[0] === 'price'), ['price', 2, '2 (100.0%)', '0 (0.0%)', '0 (0.0%)'])
+ assert.deepEqual(cross.table.find((r) => r[0] === 'crash'), ['crash', 2, '1 (50.0%)', '1 (50.0%)', '0 (0.0%)'])
+ assert.deepEqual(json(ws, '--by', 'Top').counts, { Topic: { price: 2, crash: 2, praise: 1, '(no answer yet)': 1 } })
+ assert.deepEqual(json(ws, '--where', 'stars<=2', '--by', 'says').counts, { 'Says they will cancel, or switch': { yes: 3, no: 1 } })
+})
+
+test('the rows behind a number, a word search, and the least sure rows', () => {
+ const ws = workspace()
+ const behind = json(ws, '--where', 'topic=crash', '--where', 'leaving=yes', '--rows', '5')
+ assert.equal(behind.matched, 1)
+ assert.deepEqual(behind.sample.map((r) => [r.row, r.text]), [[3, 'Crashes when I paste\nan image']])
+ const found = json(ws, '--find', 'EXPENSIVE')
+ assert.equal(found.matched, 1)
+ const unsure = json(ws, '--unsure', 'leaving', '--rows', '5').unsure
+ assert.deepEqual(unsure.map((r) => [r.row, r.answer, r.confidence]), [[3, 'yes', 0.52], [5, 'yes', 0.61]])
+ assert.equal(json(ws, '--unsure', 'leaving', '--below', '0.55').unsure.length, 1)
+})
+
+test('it says plainly what is wrong', () => {
+ const ws = workspace()
+ assert.match(run(ws, '--by', 'nothing').stderr, /no column called "nothing"\. Questions: topic = "Topic", leaving = /)
+ assert.match(run(ws, '--where', 'topic').stderr, /--where wants column=value/)
+ assert.match(run(mkdtempSync(join(tmpdir(), 'jev-sheets-count-'))).stderr, /answers\.csv is not there yet/)
+})
diff --git a/store/agents/jev-sheets/test/own-file.test.mjs b/store/agents/jev-sheets/test/own-file.test.mjs
new file mode 100644
index 000000000..f67eb1705
--- /dev/null
+++ b/store/agents/jev-sheets/test/own-file.test.mjs
@@ -0,0 +1,254 @@
+// The front door: a person brings their own file to the pane, asks, filters, and takes the answers away.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync, statSync, readdirSync, renameSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { startSheetsViewer } from '../viewer/viewer.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const TEMPLATE = readFileSync(join(HERE, '../template/sheet.json'), 'utf8')
+
+async function fresh() {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-sheets-own-'))
+ writeFileSync(join(ws, 'sheet.json'), TEMPLATE)
+ const viewer = await startSheetsViewer({ workspace: ws, port: 0, autostart: false })
+ const state = async () => (await fetch(`${viewer.url}/state`)).json()
+ const ctl = async (cmd, body = {}) => (await fetch(`${viewer.url}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd, ...body }) })).json()
+ const upload = async (name, body, headers = {}) => fetch(`${viewer.url}/upload?name=${encodeURIComponent(name)}`, { method: 'POST', body, headers })
+ return { ws, viewer, state, ctl, upload }
+}
+
+const REVIEWS = 'id,stars,review\n1,1,"The app crashes when I paste an image, please fix"\n2,5,Best notes app I have used\n3,2,"Too expensive, the price doubled"\n4,1,It crashes on launch since the update\n'
+
+test('a dropped file becomes the sheet: saved in the workspace, sheet.json points at it, the sample is kept', async () => {
+ const v = await fresh()
+ try {
+ assert.equal((await v.state()).own, false, 'it opens on the made-up sample')
+ const r = await (await v.upload('My Reviews (Q3).csv', REVIEWS)).json()
+ assert.deepEqual(r, { ok: true, file: 'My-Reviews-Q3.csv', rows: 4, total: 4, textColumn: 'review' })
+ assert.equal(readFileSync(join(v.ws, 'My-Reviews-Q3.csv'), 'utf8'), REVIEWS)
+ const marker = JSON.parse(readFileSync(join(v.ws, 'sheet.json'), 'utf8'))
+ assert.equal(marker.source, 'My-Reviews-Q3.csv')
+ assert.equal(marker.demo, false, 'the ghost typist never spends money on a person\'s own rows')
+ assert.deepEqual(marker.columns, [])
+ assert.ok(existsSync(join(v.ws, 'sheet.sample.json')), 'the sample is kept for the way back')
+ const s = await v.state()
+ assert.equal(s.own, true)
+ assert.equal(s.source.name, 'My-Reviews-Q3.csv')
+ assert.equal(s.rows.length, 4)
+ assert.equal(s.rows[0].meta.stars, 1, 'the other columns ride along as context')
+ assert.equal(s.columns.length, 0, 'the sample\'s questions do not follow the person\'s file')
+ assert.equal(s.ghost.enabled, false)
+ } finally { await v.viewer.close() }
+})
+
+test('ask, count, filter, and take the answers away', async () => {
+ const v = await fresh()
+ try {
+ await v.upload('reviews.csv', REVIEWS)
+ assert.equal((await v.ctl('addColumn', { header: 'Topic: crash = crashes or freezing | price = cost or too expensive | praise = happy, best app' })).ok, true)
+ await v.ctl('drain')
+ let s = await v.state()
+ const dist = s.colStats.topic.dist
+ assert.equal(dist.length, 3)
+ assert.equal(dist.reduce((a, b) => a + b, 0), 4, 'every row is counted once')
+ // The counts are the cells, counted. (What the offline stand-in answers is not the point here.)
+ const byValue = [0, 1, 2].map((i) => s.rows.filter((r) => s.cells[r.id].topic.v === i).map((r) => r.id))
+ assert.deepEqual(dist, byValue.map((ids) => ids.length))
+ const pick = byValue.findIndex((ids) => ids.length > 0)
+ // click that bar: only those rows
+ assert.deepEqual((await v.ctl('filter', { col: 'topic', v: pick })).filter, { col: 'topic', v: pick })
+ s = await v.state()
+ assert.deepEqual(s.order, byValue[pick])
+ await v.ctl('filter', { col: 'topic', v: pick }) // the same click again clears it
+ await v.ctl('filter', { col: 'topic', v: 0 })
+ // the same click again clears it; a removed column clears it too
+ assert.equal((await v.ctl('filter', { col: 'topic', v: 0 })).filter, null)
+ assert.equal((await v.state()).order.length, 4)
+ await v.ctl('filter', { col: 'topic', v: 1 })
+ await v.ctl('removeColumn', { id: 'topic' })
+ s = await v.state()
+ assert.equal(s.filter, null)
+ assert.equal(s.order.length, 4)
+ // the download is the answers file
+ await v.ctl('addColumn', { header: 'Complaint?' })
+ await v.ctl('drain')
+ const res = await fetch(`${v.viewer.url}/download/answers.csv`)
+ assert.equal(res.status, 200)
+ assert.match(res.headers.get('content-disposition'), /attachment; filename="answers\.csv"/)
+ const csv = await res.text()
+ assert.match(csv.split('\n')[0], /^row,review,id_,stars,Complaint,Complaint confidence$/)
+ assert.equal(csv.trim().split('\n').length, 5)
+ assert.equal((await fetch(`${v.viewer.url}/download/sheet.json`)).status, 404, 'only the answers can be downloaded')
+ assert.equal((await fetch(`${v.viewer.url}/download/..%2Fsheet.json`)).status, 404)
+ } finally { await v.viewer.close() }
+})
+
+test('a file that cannot be read changes nothing, and says why', async () => {
+ const v = await fresh()
+ try {
+ const before = readFileSync(join(v.ws, 'sheet.json'), 'utf8')
+ for (const [name, body, why] of [
+ ['notes.pdf', '%PDF-1.4', /\.csv/],
+ ['empty.csv', '', /empty/],
+ ['header-only.csv', 'review\n', /header row and at least one data row/],
+ ['broken.json', '{nope', /could not be parsed/],
+ ['../../escape.csv', REVIEWS, null], // the name is reduced to its last part: it lands inside the workspace
+ ]) {
+ const r = await (await v.upload(name, body)).json()
+ if (why) { assert.equal(r.ok, false, name); assert.match(r.error, why, name) } else assert.equal(r.file, 'escape.csv')
+ }
+ assert.ok(!existsSync(join(v.ws, 'notes.pdf')) && !existsSync(join(v.ws, 'header-only.csv')) && !existsSync(join(v.ws, 'broken.json')), 'a refused file is not left behind')
+ assert.deepEqual(readdirSync(dirname(v.ws)).filter((f) => f === 'escape.csv'), [], 'nothing is written outside the workspace')
+ // a reserved name is never overwritten by an upload
+ const r = await (await v.upload('sheet.json', JSON.stringify(['one row', 'two rows']))).json()
+ assert.equal(r.file, 'my-sheet.json')
+ assert.notEqual(readFileSync(join(v.ws, 'sheet.json'), 'utf8'), JSON.stringify(['one row', 'two rows']))
+ assert.ok(before.length > 0)
+ } finally { await v.viewer.close() }
+})
+
+test('rows pasted from a spreadsheet arrive as one JSON string per line', async () => {
+ const v = await fresh()
+ try {
+ const r = await (await v.upload('pasted.jsonl', '"Sync lost my notes"\n"Love it"\n"Refund please"\n')).json()
+ assert.equal(r.rows, 3)
+ assert.deepEqual((await v.state()).rows.map((x) => x.text), ['Sync lost my notes', 'Love it', 'Refund please'])
+ } finally { await v.viewer.close() }
+})
+
+test('back to the sample restores the made-up sheet', async () => {
+ const v = await fresh()
+ try {
+ await v.upload('reviews.csv', REVIEWS)
+ assert.equal((await v.ctl('useSample')).sample, true)
+ const s = await v.state()
+ assert.equal(s.own, false)
+ assert.equal(s.rows.length, 60)
+ assert.equal(s.columns.length, 3)
+ assert.equal(JSON.parse(readFileSync(join(v.ws, 'sheet.json'), 'utf8')).source, undefined)
+ assert.ok(existsSync(join(v.ws, 'reviews.csv')), 'the person\'s file stays where it is')
+ } finally { await v.viewer.close() }
+})
+
+test('a page on another site cannot upload, control or connect', async () => {
+ const v = await fresh()
+ try {
+ const evil = { origin: 'https://evil.example' }
+ assert.equal((await v.upload('x.csv', REVIEWS, evil)).status, 403)
+ assert.equal((await fetch(`${v.viewer.url}/control`, { method: 'POST', headers: { ...evil, 'content-type': 'application/json' }, body: '{"cmd":"reset"}' })).status, 403)
+ assert.equal((await fetch(`${v.viewer.url}/connect`, { method: 'POST', headers: { ...evil, 'content-type': 'application/json' }, body: '{"key":"sk-or-v1-aaaaaaaaaaaaaaaa"}' })).status, 403)
+ assert.equal((await fetch(`${v.viewer.url}/control`, { method: 'POST', headers: { 'sec-fetch-site': 'cross-site', 'content-type': 'application/json' }, body: '{"cmd":"reset"}' })).status, 403)
+ // the pane itself is fine
+ assert.equal((await v.upload('x.csv', REVIEWS, { origin: v.viewer.url })).status, 200)
+ assert.equal((await v.state()).own, true)
+ } finally { await v.viewer.close() }
+})
+
+test('a key pasted in the pane lands in the credentials file, chmod 600, and is never echoed', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'jev-cred-'))
+ const credFile = join(dir, 'nested', 'credentials')
+ const old = process.env.TYPESAFE_CREDENTIALS
+ process.env.TYPESAFE_CREDENTIALS = credFile
+ const v = await fresh()
+ try {
+ const connect = async (key) => (await fetch(`${v.viewer.url}/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })).json()
+ assert.equal((await (await fetch(`${v.viewer.url}/jev`)).json()).canConnect, true)
+ const bad = await connect('short')
+ assert.equal(bad.ok, false)
+ assert.ok(!existsSync(credFile), 'a string that is not a key is never written')
+ const KEY = 'sk-or-v1-' + 'a1b2c3d4'.repeat(6)
+ const ok = await connect(KEY)
+ assert.equal(ok.ok, true)
+ assert.equal(ok.provider, 'openrouter')
+ assert.equal(ok.probed, false, 'under node --test nothing is called')
+ assert.ok(!JSON.stringify(ok).includes(KEY), 'the key is never echoed back')
+ assert.equal(readFileSync(credFile, 'utf8'), `OPENROUTER_API_KEY=${KEY}\n`)
+ if (process.platform !== 'win32') assert.equal(statSync(credFile).mode & 0o777, 0o600)
+ // a second key of another kind is added; the same kind is replaced, never duplicated
+ await connect('ts_live_' + 'z9'.repeat(12))
+ await connect('sk-or-v1-' + 'ffff0000'.repeat(6))
+ const lines = readFileSync(credFile, 'utf8').trim().split('\n')
+ assert.equal(lines.length, 2)
+ assert.equal(lines.filter((l) => l.startsWith('OPENROUTER_API_KEY=')).length, 1)
+ assert.ok(lines.some((l) => l.startsWith('TYPESAFE_API_KEY=ts_live_')))
+ } finally {
+ await v.viewer.close()
+ if (old === undefined) delete process.env.TYPESAFE_CREDENTIALS; else process.env.TYPESAFE_CREDENTIALS = old
+ }
+})
+
+test('the agent saves sheet.json atomically, again and again, and every save is seen', async () => {
+ // Editors and coding agents write a temp file and rename it over the target. A watcher on the
+ // file itself goes deaf after the first such save. The drop itself is one, so this broke for real.
+ const v = await fresh()
+ try {
+ await v.upload('reviews.csv', REVIEWS) // the viewer's own write of sheet.json is an atomic save
+ const marker = join(v.ws, 'sheet.json')
+ const save = (obj) => { writeFileSync(marker + '.agent', JSON.stringify(obj)); renameSync(marker + '.agent', marker) }
+ const until = async (pred) => { const end = Date.now() + 5000; for (;;) { const s = await v.state(); if (pred(s)) return s; if (Date.now() > end) assert.fail('the viewer never saw the save'); await new Promise((r) => setTimeout(r, 50)) } }
+ const base = JSON.parse(readFileSync(marker, 'utf8'))
+ save({ ...base, columns: ['Complaint?'] })
+ await until((s) => s.columns.length === 1)
+ save({ ...base, columns: ['Complaint?', 'Anger: calm < annoyed < furious'] })
+ await until((s) => s.columns.length === 2)
+ save({ ...base, context: 'Each row is one review.', columns: ['Mentions a crash?'] })
+ const s = await until((x) => x.columns.length === 1 && x.columns[0].id === 'mentions_a_crash')
+ assert.equal(s.own, true)
+ // the person's file is watched the same way
+ writeFileSync(join(v.ws, 'reviews.csv.new'), REVIEWS + '5,4,A brand new review about the editor\n'); renameSync(join(v.ws, 'reviews.csv.new'), join(v.ws, 'reviews.csv'))
+ await until((x) => x.rows.length === 5)
+ } finally { await v.viewer.close() }
+})
+
+test('the verdict moves while a fill is still running, and says when sheet.json was loaded', async () => {
+ const v = await fresh()
+ try {
+ const verdict = () => JSON.parse(readFileSync(join(v.ws, '.harness/verdict.json'), 'utf8'))
+ const t0 = Date.now()
+ await v.upload('reviews.csv', REVIEWS)
+ await v.ctl('addColumn', { header: 'Complaint?' })
+ await v.ctl('tick', { n: 2 }) // two of the four rows: the fill is NOT finished
+ const end = Date.now() + 5000
+ let got
+ for (;;) { got = verdict(); if (got.sheet.cellsFilled === 2) break; if (Date.now() > end) assert.fail('the verdict never showed the fill in progress: ' + got.summary); await new Promise((r) => setTimeout(r, 100)) }
+ assert.equal(got.ready, false)
+ assert.equal(got.sheet.cellsTotal, 4)
+ assert.equal(got.sheet.source, 'reviews.csv')
+ assert.ok(Date.parse(got.sheet.loadedAt) >= t0 - 1000, 'loadedAt is the time this sheet was taken in')
+ await v.ctl('drain')
+ const until = Date.now() + 5000
+ for (;;) { got = verdict(); if (got.ready) break; if (Date.now() > until) assert.fail('the verdict never became ready'); await new Promise((r) => setTimeout(r, 100)) }
+ assert.equal(got.sheet.cellsFilled, 4)
+ const weak = got.sheet.columns[0].weakest[0]
+ if (weak) assert.equal(typeof weak.n, 'number', 'weakest rows carry the row number answers.csv uses')
+ } finally { await v.viewer.close() }
+})
+
+test('a changed context asks again; a changed title or suggestions does not', async () => {
+ const v = await fresh()
+ try {
+ await v.upload('reviews.csv', REVIEWS)
+ const marker = join(v.ws, 'sheet.json')
+ const base = { ...JSON.parse(readFileSync(marker, 'utf8')), columns: ['Complaint?'] }
+ const save = (obj) => { writeFileSync(marker + '.agent', JSON.stringify(obj)); renameSync(marker + '.agent', marker) }
+ const settled = async (pred) => { const end = Date.now() + 5000; for (;;) { const s = await v.state(); if (pred(s)) return s; if (Date.now() > end) assert.fail('timed out: ' + JSON.stringify(s.stats)); await new Promise((r) => setTimeout(r, 50)) } }
+ save({ ...base, context: 'Each row is one review of a notes app.' })
+ await settled((s) => s.columns.length === 1)
+ await v.ctl('drain')
+ const first = (await v.state()).stats
+ assert.equal(first.cellsFilled, 4)
+ save({ ...base, context: 'Each row is one review of a notes app.', title: 'A new title', suggestions: ['Asks for a refund?'] })
+ await settled((s) => s.title === 'A new title')
+ await v.ctl('drain')
+ assert.equal((await v.state()).stats.calls, first.calls, 'nothing is asked again for a title or suggestions')
+ save({ ...base, context: 'Each row is one support ticket to a bank.', title: 'A new title' })
+ await settled((s) => s.stats.cellsFilled === 0 || s.stats.calls > first.calls)
+ await v.ctl('drain')
+ const after = (await v.state()).stats
+ assert.equal(after.cellsFilled, 4)
+ assert.equal(after.calls, first.calls + 4, 'every row is asked again under the new context')
+ } finally { await v.viewer.close() }
+})
diff --git a/store/agents/jev-sheets/test/xlsx.test.mjs b/store/agents/jev-sheets/test/xlsx.test.mjs
new file mode 100644
index 000000000..6d9cc8c27
--- /dev/null
+++ b/store/agents/jev-sheets/test/xlsx.test.mjs
@@ -0,0 +1,87 @@
+// An Excel file dropped on the pane is read as it is: the first sheet, header row first.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { deflateRawSync } from 'node:zlib'
+import { mkdtempSync, writeFileSync, readFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { readXlsx } from '../viewer/xlsx.mjs'
+import { loadSource } from '../viewer/source.mjs'
+import { startSheetsViewer } from '../viewer/viewer.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+
+// ---- a tiny zip writer, so the fixture is built here and not checked in as a binary ----------------
+const TABLE = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0 })
+const crc32 = (buf) => { let c = 0xffffffff; for (const b of buf) c = TABLE[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0 }
+function zip(files) {
+ const locals = [], central = []
+ let offset = 0
+ for (const [name, text, store] of files) {
+ const raw = Buffer.from(text), data = store ? raw : deflateRawSync(raw), nameBuf = Buffer.from(name)
+ const head = Buffer.alloc(30)
+ head.writeUInt32LE(0x04034b50, 0); head.writeUInt16LE(20, 4); head.writeUInt16LE(store ? 0 : 8, 8)
+ head.writeUInt32LE(crc32(raw), 14); head.writeUInt32LE(data.length, 18); head.writeUInt32LE(raw.length, 22); head.writeUInt16LE(nameBuf.length, 26)
+ const cd = Buffer.alloc(46)
+ cd.writeUInt32LE(0x02014b50, 0); cd.writeUInt16LE(20, 4); cd.writeUInt16LE(20, 6); cd.writeUInt16LE(store ? 0 : 8, 10)
+ cd.writeUInt32LE(crc32(raw), 16); cd.writeUInt32LE(data.length, 20); cd.writeUInt32LE(raw.length, 24); cd.writeUInt16LE(nameBuf.length, 28); cd.writeUInt32LE(offset, 42)
+ locals.push(head, nameBuf, data); central.push(cd, nameBuf)
+ offset += 30 + nameBuf.length + data.length
+ }
+ const cdBuf = Buffer.concat(central), end = Buffer.alloc(22)
+ end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(cdBuf.length, 12); end.writeUInt32LE(offset, 16)
+ return Buffer.concat([...locals, cdBuf, end])
+}
+
+const SHARED = `<?xml version="1.0" encoding="UTF-8"?><sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="6" uniqueCount="6">
+<si><t>Customer</t></si><si><t>Feedback</t></si><si><t>Ana &amp; Co</t></si>
+<si><r><t>The checkout </t></r><r><rPr><b/></rPr><t xml:space="preserve">froze twice</t></r><rPh><t>ignored</t></rPh></si>
+<si><t>Bo</t></si><si><t>Refund "please" &lt;today&gt;</t></si></sst>`
+const SHEET = `<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>
+<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c><c r="C1" t="inlineStr"><is><t>Stars</t></is></c><c r="E1" t="inlineStr"><is><t>Paid</t></is></c></row>
+<row r="2"><c r="A2" t="s"><v>2</v></c><c r="B2" t="s"><v>3</v></c><c r="C2"><v>2</v></c><c r="E2" t="b"><v>1</v></c></row>
+<row r="3"></row>
+<row r="4"><c r="A4" t="s"><v>4</v></c><c r="B4" t="s"><v>5</v></c><c r="C4" s="3"><v>4.5</v></c><c r="D4"/><c r="E4" t="str"><f>IF(1,"no")</f><v>no</v></c></row>
+</sheetData></worksheet>`
+const workbook = () => zip([
+ ['[Content_Types].xml', '<Types/>', true],
+ ['xl/sharedStrings.xml', SHARED],
+ ['xl/worksheets/sheet2.xml', '<worksheet><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>second sheet, not read</t></is></c></row></sheetData></worksheet>'],
+ ['xl/worksheets/sheet1.xml', SHEET],
+])
+
+test('readXlsx: shared and inline strings, rich text, entities, numbers, booleans, formulas, gaps', () => {
+ assert.deepEqual(readXlsx(workbook()), [
+ ['Customer', 'Feedback', 'Stars', '', 'Paid'],
+ ['Ana & Co', 'The checkout froze twice', '2', '', 'TRUE'],
+ ['Bo', 'Refund "please" <today>', '4.5', '', 'no'],
+ ])
+ assert.throws(() => readXlsx(Buffer.from('this is not a workbook at all')), /not a zip/)
+ assert.throws(() => readXlsx(zip([['hello.txt', 'hi']])), /no worksheet/)
+})
+
+test('an Excel file is a source like any other: the prose column is the text, the rest ride along', () => {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-sheets-xlsx-'))
+ writeFileSync(join(ws, 'feedback.xlsx'), workbook())
+ const got = loadSource(ws, 'feedback.xlsx')
+ assert.equal(got.error, null)
+ assert.deepEqual(got.info, { name: 'feedback.xlsx', textColumn: 'Feedback', total: 2, used: 2 })
+ assert.deepEqual(got.rows[0], { text: 'The checkout froze twice', Customer: 'Ana & Co', Stars: 2, Paid: 'TRUE' })
+ writeFileSync(join(ws, 'broken.xlsx'), 'nope')
+ assert.match(loadSource(ws, 'broken.xlsx').error, /could not be parsed: not a zip file/)
+})
+
+test('an Excel file dropped on the pane becomes the sheet', async () => {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-sheets-xlsx-'))
+ writeFileSync(join(ws, 'sheet.json'), readFileSync(join(HERE, '../template/sheet.json')))
+ const viewer = await startSheetsViewer({ workspace: ws, port: 0, autostart: false })
+ try {
+ const r = await (await fetch(`${viewer.url}/upload?name=${encodeURIComponent('Customer feedback.xlsx')}`, { method: 'POST', body: workbook() })).json()
+ assert.deepEqual(r, { ok: true, file: 'Customer-feedback.xlsx', rows: 2, total: 2, textColumn: 'Feedback' })
+ const s = await (await fetch(`${viewer.url}/state`)).json()
+ assert.equal(s.own, true)
+ assert.deepEqual(s.rows.map((x) => x.text), ['The checkout froze twice', 'Refund "please" <today>'])
+ assert.equal(s.textLabel, 'Feedback')
+ } finally { await viewer.close() }
+})
diff --git a/store/agents/jev-sheets/toolchain/check.mjs b/store/agents/jev-sheets/toolchain/check.mjs
index 7fc40c196..e367bf72c 100644
--- a/store/agents/jev-sheets/toolchain/check.mjs
+++ b/store/agents/jev-sheets/toolchain/check.mjs
@@ -23,7 +23,8 @@ try {
if (!sheet || typeof sheet !== 'object' || Array.isArray(sheet)) { console.log('error sheet.json must be a JSON object'); process.exit(1) }
if (!sheet.title || typeof sheet.title !== 'string') warn('no title')
-if (!sheet.description || !/made.?up|synthetic|fictional|not real/i.test(String(sheet.description))) warn('say in "description" that the data is made up')
+// Rows the agent wrote are made up and must say so. Rows from the person's own file are what they are.
+if (sheet.source === undefined && (!sheet.description || !/made.?up|synthetic|fictional|not real/i.test(String(sheet.description)))) warn('say in "description" that the data is made up')
// ---- columns: 0 to 12 valid headers ------------------------------------------------------------
const columns = new Map()
@@ -43,7 +44,7 @@ else {
})
}
-// ---- rows: 1 to 2000, each with text -----------------------------------------------------------
+// ---- rows: 1 to 10,000, each with text -----------------------------------------------------------
// A sheet may take its rows from the person's own file in the workspace: "source": "leads.csv".
let sourceRows = 0
if (sheet.source !== undefined) {
@@ -87,4 +88,4 @@ if (sheet.suggestions != null) {
}
if (errors) { console.log(`fail invalid sheet.json (${errors} error${errors > 1 ? 's' : ''}, ${warnings} warning${warnings === 1 ? '' : 's'})`); process.exit(1) }
-console.log(`ok sheet.json is valid: ${rows.length} rows, ${columns.size} Jev columns${warnings ? `, ${warnings} warning${warnings > 1 ? 's' : ''}` : ''}`)
+console.log(`ok sheet.json is valid: ${sourceRows ? `${rows.length + sourceRows} rows (${sourceRows} from ${sheet.source})` : `${rows.length} rows`}, ${columns.size} Jev columns${warnings ? `, ${warnings} warning${warnings > 1 ? 's' : ''}` : ''}`)
diff --git a/store/agents/jev-sheets/toolchain/count.mjs b/store/agents/jev-sheets/toolchain/count.mjs
new file mode 100644
index 000000000..198f81530
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/count.mjs
@@ -0,0 +1,152 @@
+#!/usr/bin/env node
+// count.mjs — count what Jev answered, so findings rest on one tested reader and not on a parser
+// each agent writes by hand. It reads answers.csv in the workspace. It changes nothing.
+//
+// node "$JEV_DSH/toolchain/count.mjs" every question: counts, shares, unsure cells
+// node … --by topic --and leaving a cross-cut (rows: topic, columns: leaving)
+// node … --where topic=price --where leaving=going --rows 8 read the rows behind a number
+// node … --unsure topic --rows 10 the least sure rows of one question
+// node … --find "charged twice" --by topic a plain word search, cut by a question
+//
+// A column is named by its id in sheet.json ("topic"), by its name in answers.csv ("Topic"), or by
+// the start of either. The file's own columns work too: --by platform, --where "stars<=2".
+// Other flags: --file <answers.csv> --below 0.65 --json
+import { readFileSync, existsSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { parseDelimited } from '../viewer/source.mjs'
+import { parseHeader } from '../viewer/grammar.mjs'
+
+const argv = process.argv.slice(2)
+const flags = { where: [] }
+for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]
+ if (a === '--json') flags.json = true
+ else if (a === '--where') flags.where.push(argv[++i])
+ else if (a.startsWith('--')) flags[a.slice(2)] = argv[++i]
+ else die(`unknown argument "${a}". See the top of toolchain/count.mjs`)
+}
+function die(msg) { console.error(`count: ${msg}`); process.exit(2) }
+
+const file = flags.file || join(process.env.HARNESS_WORKSPACE || '.', 'answers.csv')
+if (!existsSync(file)) die(`${file} is not there yet. The viewer writes it once the sheet has rows`)
+const table = parseDelimited(readFileSync(file, 'utf8').replace(/^/, ''), ',')
+if (table.length < 2) die('answers.csv has no rows yet')
+const headers = table[0]
+const rows = table.slice(1).map((cells) => Object.fromEntries(headers.map((h, i) => [h, cells[i] ?? ''])))
+const ws = dirname(file)
+
+// Questions are the columns that have a "<name> confidence" twin.
+const questions = headers.filter((h) => headers.includes(`${h} confidence`))
+// sheet.json gives each question a short id.
+const idOf = new Map()
+try {
+ for (const c of JSON.parse(readFileSync(join(ws, 'sheet.json'), 'utf8')).columns ?? []) {
+ const p = parseHeader(typeof c === 'string' ? c : c?.header, c && typeof c === 'object' ? c.id : undefined)
+ if (p.ok && questions.includes(p.column.name)) idOf.set(p.column.id, p.column.name)
+ }
+} catch { /* columns typed in the pane have no id: use their name */ }
+let below = Number(flags.below)
+if (!(below >= 0 && below <= 1)) {
+ try { below = Number(JSON.parse(readFileSync(join(ws, '.harness', 'verdict.json'), 'utf8')).sheet.reviewBelow) } catch { below = NaN }
+ if (!(below >= 0 && below <= 1)) below = 0.65
+}
+
+/** A column of answers.csv from an id, a name, or the start of either. */
+function column(key) {
+ const k = String(key ?? '').trim().toLowerCase()
+ if (!k) die('a column name is missing')
+ if (idOf.has(k)) return idOf.get(k)
+ const exact = headers.find((h) => h.toLowerCase() === k)
+ if (exact) return exact
+ const starts = [...new Set([...[...idOf].filter(([id]) => id.startsWith(k)).map(([, name]) => name), ...headers.filter((h) => h.toLowerCase().startsWith(k) && !h.endsWith(' confidence'))])]
+ if (starts.length === 1) return starts[0]
+ die(`${starts.length ? `"${key}" fits more than one column` : `no column called "${key}"`}. Questions: ${questions.map((q) => `${[...idOf].find(([, n]) => n === q)?.[0] ?? '-'} = "${q}"`).join(', ')}. File columns: ${headers.filter((h) => !questions.includes(h) && !h.endsWith(' confidence')).join(', ')}`)
+}
+const conf = (row, q) => Number(row[`${q} confidence`])
+const answered = (row, q) => row[q] !== ''
+
+// ---- filters ---------------------------------------------------------------------------------
+const tests = flags.where.map((w) => {
+ const m = String(w ?? '').match(/^(.*?)(<=|>=|!=|=|<|>)(.*)$/)
+ if (!m) die(`--where wants column=value, got "${w}"`)
+ const col = column(m[1]), op = m[2], want = m[3].trim()
+ return (row) => {
+ const have = String(row[col] ?? '').trim()
+ if (op === '=') return have.toLowerCase() === want.toLowerCase()
+ if (op === '!=') return have.toLowerCase() !== want.toLowerCase()
+ const a = Number(have), b = Number(want)
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return false
+ return op === '<' ? a < b : op === '>' ? a > b : op === '<=' ? a <= b : a >= b
+ }
+})
+const textCol = headers[1]
+if (flags.find != null) { const needle = String(flags.find).toLowerCase(); tests.push((row) => String(row[textCol]).toLowerCase().includes(needle)) }
+let picked = rows.filter((row) => tests.every((t) => t(row)))
+const pct = (n, d) => (d ? `${(100 * n / d).toFixed(1)}%` : '-')
+
+function tally(list, col) {
+ const counts = new Map()
+ for (const row of list) { const v = row[col] === '' ? '(no answer yet)' : row[col]; counts.set(v, (counts.get(v) ?? 0) + 1) }
+ return [...counts].sort((a, b) => b[1] - a[1])
+}
+function print(lines) { console.log(lines.join('\n')) }
+function grid(head, body) {
+ const all = [head, ...body].map((r) => r.map(String))
+ const w = head.map((_, i) => Math.max(...all.map((r) => r[i].length)))
+ return all.map((r, n) => r.map((c, i) => (i === 0 ? c.padEnd(w[i]) : c.padStart(w[i]))).join(' ') + (n === 0 ? '\n' + w.map((x) => '-'.repeat(x)).join(' ') : ''))
+}
+
+const out = { file, rows: rows.length, matched: picked.length, reviewBelow: below }
+const said = []
+if (tests.length) said.push(`${picked.length} of ${rows.length} rows match${flags.find != null ? ` (text holds "${flags.find}")` : ''}${flags.where.length ? ` where ${flags.where.join(' and ')}` : ''} · ${pct(picked.length, rows.length)}`)
+
+if (flags.unsure) {
+ // The least sure rows of one question, least sure first.
+ const q = column(flags.unsure)
+ if (!questions.includes(q)) die(`"${q}" is not a Jev question`)
+ picked = picked.filter((r) => answered(r, q) && conf(r, q) < below).sort((a, b) => conf(a, q) - conf(b, q))
+ const n = Math.max(1, Number(flags.rows) || 10)
+ said.push(`${picked.length} rows where "${q}" is under ${below}. The least sure ${Math.min(n, picked.length)}:`)
+ out.unsure = picked.slice(0, n).map((r) => ({ row: Number(r.row), answer: r[q], confidence: conf(r, q), text: r[textCol] }))
+ for (const r of out.unsure) said.push(` row ${r.row} ${r.answer} (${r.confidence.toFixed(2)}) ${r.text}`)
+} else if (flags.by) {
+ const a = column(flags.by)
+ if (flags.and) {
+ const b = column(flags.and)
+ const bVals = tally(picked, b).map(([v]) => v)
+ const body = tally(picked, a).map(([av, n]) => {
+ const sub = picked.filter((r) => (r[a] === '' ? '(no answer yet)' : r[a]) === av)
+ return [av, n, ...bVals.map((bv) => { const k = sub.filter((r) => (r[b] === '' ? '(no answer yet)' : r[b]) === bv).length; return `${k} (${pct(k, n)})` })]
+ })
+ said.push(`"${a}" by "${b}". Each share is of its row.`, ...grid([a, 'rows', ...bVals], body))
+ out.cross = { rows: a, columns: b, values: bVals, table: body }
+ } else {
+ const body = tally(picked, a).map(([v, n]) => [v, n, pct(n, picked.length)])
+ said.push(...grid([a, 'rows', 'share'], body))
+ out.counts = { [a]: Object.fromEntries(body.map(([v, n]) => [v, n])) }
+ }
+} else if (!flags.rows) {
+ // Every question: counts, shares, how sure.
+ out.questions = {}
+ for (const q of questions) {
+ const done = picked.filter((r) => answered(r, q))
+ const unsure = done.filter((r) => conf(r, q) < below).length
+ const avg = done.length ? done.reduce((s, r) => s + conf(r, q), 0) / done.length : 0
+ const id = [...idOf].find(([, n]) => n === q)?.[0]
+ said.push('', `${q}${id ? ` [${id}]` : ''} · ${done.length} of ${picked.length} rows answered · ${unsure} under ${below} (${pct(unsure, done.length)}) · average confidence ${avg.toFixed(2)}`)
+ const body = tally(done, q).map(([v, n]) => { const u = done.filter((r) => r[q] === v && conf(r, q) < below).length; return [` ${v}`, n, pct(n, done.length), `${u} unsure`] })
+ said.push(...grid([' answer', 'rows', 'share', ''], body))
+ out.questions[q] = { id: id ?? null, answered: done.length, unsure, averageConfidence: Number(avg.toFixed(3)), counts: Object.fromEntries(body.map(([v, n]) => [v.trim(), n])) }
+ }
+ if (!questions.length) said.push('No Jev question has answers yet.')
+}
+if (flags.rows && !flags.unsure) {
+ // Rows to read, spread evenly over the matches so the first ten do not stand in for all of them.
+ const n = Math.max(1, Number(flags.rows) || 10)
+ const step = Math.max(1, picked.length / n)
+ const sample = Array.from({ length: Math.min(n, picked.length) }, (_, i) => picked[Math.floor(i * step)])
+ said.push('', `${sample.length} of the ${picked.length} matching rows, spread evenly:`)
+ out.sample = sample.map((r) => ({ row: Number(r.row), text: r[textCol], answers: Object.fromEntries(questions.map((q) => [q, r[q]])) }))
+ for (const r of sample) said.push(` row ${r.row} [${questions.map((q) => r[q]).join(' · ')}] ${r[textCol]}`)
+}
+if (flags.json) console.log(JSON.stringify(out, null, 2)); else print(said.filter((l, i) => !(i === 0 && l === '')))
diff --git a/store/agents/jev-sheets/toolchain/jev.mjs b/store/agents/jev-sheets/toolchain/jev.mjs
index ad49ee927..0552989b9 100644
--- a/store/agents/jev-sheets/toolchain/jev.mjs
+++ b/store/agents/jev-sheets/toolchain/jev.mjs
@@ -112,9 +112,9 @@ function clamp(x) {
}
// Imports are hoisted, so they can live here with the code that needs them.
-import { readFileSync } from 'node:fs'
+import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
@@ -234,6 +234,7 @@ export function snapshot() {
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
+ route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
@@ -291,6 +292,62 @@ export function resolveCredentials(explicitKey) {
return null
}
+/**
+ * Store one credential in the credentials file, so a pane can go live without a terminal. The file
+ * is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
+ */
+export function saveCredential(name, value) {
+ if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
+ const v = String(value ?? '').trim()
+ if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
+ const path = credentialsPath()
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ let lines = []
+ try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
+ kept.push(`${name}=${v}`)
+ writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
+ credCache = null
+}
+
+/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
+export function removeCredential(name) {
+ if (!CRED_KEYS.includes(name)) return
+ const path = credentialsPath()
+ try {
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
+ writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ } catch { /* nothing to remove */ }
+ credCache = null
+}
+
+/**
+ * A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
+ * one tiny real call. A key the service refuses is removed again. Never throws.
+ * @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
+ */
+export async function connectKey(value, { probe = true } = {}) {
+ const v = String(value ?? '').trim()
+ const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
+ try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
+ const cred = resolveCredentials()
+ // Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
+ if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
+ try {
+ await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
+ return { ok: true, provider: cred.provider, stored: true, probed: true }
+ } catch (e) {
+ const msg = String(e?.message ?? e)
+ if (/\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg)) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
+ return { ok: true, provider: cred.provider, stored: true, probed: false, warning: `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
+ }
+}
+
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
diff --git a/store/agents/jev-sheets/viewer/grammar.mjs b/store/agents/jev-sheets/viewer/grammar.mjs
index ca742f969..4bf84c394 100644
--- a/store/agents/jev-sheets/viewer/grammar.mjs
+++ b/store/agents/jev-sheets/viewer/grammar.mjs
@@ -9,7 +9,7 @@
// Urgency a bare word -> score low < medium < high
export const LIMITS = {
- maxRows: 2000, maxColumns: 12, maxHeader: 20000, maxName: 80,
+ maxRows: 10000, maxColumns: 12, maxHeader: 20000, maxName: 80,
minOptions: 2, maxOptions: 255, minLevels: 2, maxLevels: 10,
}
diff --git a/store/agents/jev-sheets/viewer/index.html b/store/agents/jev-sheets/viewer/index.html
index e75b78960..c61244082 100644
--- a/store/agents/jev-sheets/viewer/index.html
+++ b/store/agents/jev-sheets/viewer/index.html
@@ -16,7 +16,8 @@
<span class="dot"></span>
<h1>Jev Sheets</h1>
<span class="sub" id="sheetTitle">loading the sheet</span>
- <span class="pill warn" id="synthPill" title="Every name, message and truth label in this sheet is made up.">synthetic data</span>
+ <span class="pill warn" id="synthPill" title="Every name, message and truth label in this sheet is made up.">made-up sample</span>
+ <span class="pill ok hidden" id="ownPill" title="These rows come from your own file in the project folder.">your file</span>
</div>
<div class="stats big">
<div class="stat"><label>rows</label><span id="sRows">0</span></div>
@@ -34,6 +35,21 @@
<div id="cfgError" class="cfg-error hidden"></div>
<main>
<section id="stage">
+ <section id="door" class="door">
+ <div class="door-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4M7 9l5-5 5 5"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg></div>
+ <div class="door-text">
+ <b id="doorTitle">Use your own file</b>
+ <span id="doorSub">Drop an Excel or CSV file anywhere on this pane, or paste rows copied from Excel or Google Sheets. Reviews, survey answers, tickets, leads: one row per item. Then type a question and Jev answers it for every row.</span>
+ </div>
+ <div class="door-actions">
+ <button id="pickBtn" class="primary">Choose a file</button>
+ <button id="pasteBtn" title="Copy rows in your spreadsheet, then click here. Or press Cmd+V or Ctrl+V anywhere on the pane.">Paste rows</button>
+ <button id="downloadBtn" class="hidden" title="Every row with Jev's answer and confidence for each question">Download answers.csv</button>
+ <button id="sampleBtn" class="hidden" title="Go back to the made-up sample sheet">Back to the sample</button>
+ <input type="file" id="fileInput" class="hidden" accept=".xlsx,.csv,.tsv,.txt,.json,.jsonl,.ndjson">
+ </div>
+ </section>
+ <div id="standin" class="standin hidden"><b>These are not real answers yet.</b> An offline stand-in is filling the cells by matching words. Paste a key in the <b>Jev · live mind</b> panel on the right and every cell is asked again, for real.</div>
<div id="toolbar">
<div id="addBox" class="addbox">
<span class="plus">+</span>
@@ -41,6 +57,7 @@
<span id="ghostTag" class="demo-tag hidden">demo · ghost typist</span>
<kbd id="enterKey">Enter</kbd>
</div>
+ <button id="filterChip" class="filter-chip hidden" title="Showing only the rows with this answer. Click to show all rows."></button>
<button id="reviewOnlyBtn" title="Show only the rows with a cell under the review line">needs review only <b id="reviewOnlyN">0</b></button>
<div class="reviewbox" title="Cells where Jev's confidence is under this line get a ? flag">
<label for="reviewRange">review below <b id="reviewVal">0.65</b></label>
@@ -57,6 +74,11 @@
</div>
</section>
<aside id="rail">
+ <section class="panel" id="findings">
+ <div class="panel-title">Answers so far <span class="right dim">click a bar to see those rows</span></div>
+ <div id="findBody" class="find-empty">Type a question above. The counts for every answer show up here.</div>
+ </section>
+ <div data-jev-hud></div>
<section class="panel" id="inspector">
<div class="panel-title">Cell inspector <span class="right" id="inspTag"></span></div>
<div id="inspBody" class="insp-empty">Click any cell to see what Jev was asked and its full answer.</div>
@@ -80,5 +102,7 @@
</section>
</aside>
</main>
+ <div id="dropVeil" class="drop-veil hidden"><div><b>Drop your file</b><span>Excel, CSV, TSV, JSON or JSONL, up to 32 MB. It is saved in this project folder. Its rows go to the Jev API to be answered, and nowhere else.</span></div></div>
+ <div id="toast" class="toast hidden"></div>
</body>
</html>
diff --git a/store/agents/jev-sheets/viewer/jev-hud.js b/store/agents/jev-sheets/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-sheets/viewer/jev-hud.js
+++ b/store/agents/jev-sheets/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-sheets/viewer/kit.mjs b/store/agents/jev-sheets/viewer/kit.mjs
index f80d29b7d..cf754e544 100644
--- a/store/agents/jev-sheets/viewer/kit.mjs
+++ b/store/agents/jev-sheets/viewer/kit.mjs
@@ -2,9 +2,9 @@
// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
// /control, plus an atomic verdict writer and a safe JSON config watcher.
import { createServer } from 'node:http'
-import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
-import { join, extname } from 'node:path'
-import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync } from 'node:fs'
+import { join, extname, dirname, basename } from 'node:path'
+import { snapshot as jevSnapshot, connectKey } from '../toolchain/jev.mjs'
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
@@ -28,8 +28,13 @@ export function mulberry32(a) {
* @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
* @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
* @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ * @param {function} [o.upload] async (name, buffer) => JSON-safe reply. Turns on POST /upload?name=<file name>: the person
+ * drops their own file on the pane. The handler must sanitise the name itself.
+ * @param {number} [o.maxUpload] largest upload in bytes (default 32 MB)
+ * @param {function} [o.downloads] () => ({ 'answers.csv': '/abs/path' }). Turns on GET /download/<name> for those files.
+ * @param {function} [o.onConnect] called after a person connects a key in the pane (POST /connect)
*/
-export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control, upload, maxUpload = 32 * 1024 * 1024, downloads, onConnect }) {
const clients = new Set()
const allowed = new Set(files)
@@ -40,12 +45,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
+ // Anything that changes state must come from this pane. A web page on another site can reach
+ // 127.0.0.1 from the person's browser, so a POST with a foreign Origin is refused.
+ if (req.method !== 'GET') {
+ const origin = req.headers.origin
+ if ((origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) || req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); return res.end('Same origin only') }
+ }
try {
if (req.method === 'GET') {
+ if (downloads && path.startsWith('/download/')) {
+ const name = decodeURIComponent(path.slice('/download/'.length))
+ const list = downloads() ?? {}
+ const file = Object.prototype.hasOwnProperty.call(list, name) ? list[name] : null
+ if (!file || !existsSync(file)) { res.writeHead(404); return res.end('Not found') }
+ res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream', 'content-disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}"` })
+ return res.end(readFileSync(file))
+ }
const name = path === '/' ? 'index.html' : path.slice(1)
if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
- if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ // canConnect tells the live panel that this server takes a pasted key (POST /connect).
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ...jevSnapshot(), canConnect: true })) }
if (path === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
@@ -63,6 +83,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
}
+ // The person pastes a Jev key in the pane. It goes to the credentials file (chmod 600) and is
+ // proven with one tiny call. The key is never echoed back, logged or kept in the page.
+ if (req.method === 'POST' && path === '/connect') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 4096) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const out = await connectKey(j.key)
+ if (out.ok) { try { await onConnect?.(out) } catch { /* the pane still learns the key is in */ } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(out))
+ }
+ // The person drops their own file on the pane. The raw bytes are the body.
+ if (req.method === 'POST' && path === '/upload' && upload) {
+ const chunks = []
+ let size = 0
+ for await (const c of req) { size += c.length; if (size > maxUpload) { res.writeHead(413, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: `that file is over ${Math.round(maxUpload / 1024 / 1024)} MB` })) } chunks.push(c) }
+ const reply = await upload(String(url.searchParams.get('name') ?? ''), Buffer.concat(chunks))
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
res.writeHead(404); res.end('Not found')
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
@@ -92,6 +133,24 @@ export function writeVerdict(workspace, verdict) {
renameSync(file + '.tmp', file)
}
+/**
+ * Call `onChange` whenever one file changes, however it was saved. Editors and coding agents save
+ * atomically (write a temp file, rename it over the target). `fs.watch` on the file itself keeps
+ * following the old inode and goes deaf after the first such save. So this watches the folder for
+ * that name, and a slow stat check catches anything the platform's watcher drops.
+ * @returns {{ close(): void }}
+ */
+export function watchPath(file, onChange, { pollMs = 1000 } = {}) {
+ const dir = dirname(file), name = basename(file)
+ const stamp = () => { try { const s = statSync(file); return `${s.ino}:${s.size}:${s.mtimeMs}` } catch { return 'missing' } }
+ let last = stamp(), closed = false, watcher = null
+ const check = () => { if (closed) return; const now = stamp(); if (now !== last) { last = now; onChange() } }
+ try { watcher = watch(dir, (_event, changed) => { if (!changed || changed === name) check() }) } catch { /* the folder may be gone; the poll still runs */ }
+ const poll = setInterval(check, pollMs)
+ poll.unref?.()
+ return { close() { closed = true; clearInterval(poll); watcher?.close() } }
+}
+
/**
* Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
* good config and reports the parse error instead of crashing the demo.
@@ -104,9 +163,7 @@ export function watchConfig(file, defaults, onChange) {
catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
}
load()
- let watcher = null
- try {
- watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
- } catch { /* file may not exist yet; defaults stand */ }
- return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+ // watchPath also sees a file that did not exist yet, and every save after an atomic replace.
+ const watcher = watchPath(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher.close() } }
}
diff --git a/store/agents/jev-sheets/viewer/source.mjs b/store/agents/jev-sheets/viewer/source.mjs
index 8d2b04668..f9e049343 100644
--- a/store/agents/jev-sheets/viewer/source.mjs
+++ b/store/agents/jev-sheets/viewer/source.mjs
@@ -2,13 +2,14 @@
//
// { "source": "leads.csv", "textColumn": "message", ... }
//
-// A .csv or .tsv file (header row first), a .jsonl file (one JSON object or string per line) or a
+// An Excel .xlsx file (first sheet, header row first), a .csv or .tsv file (header row first), a .jsonl file (one JSON object or string per line) or a
// .json file (a list) becomes the sheet's rows. One column is the row's text; the other columns
// ride along as plain fields that Jev also reads. The file must live inside the workspace.
import { readFileSync, statSync } from 'node:fs'
import { resolve, sep, extname } from 'node:path'
+import { readXlsx } from './xlsx.mjs'
-export const SOURCE_LIMITS = { bytes: 8 * 1024 * 1024, field: 300, fields: 24 }
+export const SOURCE_LIMITS = { bytes: 32 * 1024 * 1024, field: 300, fields: 24 }
const TEXT_NAMES = ['text', 'message', 'body', 'content', 'description', 'comment', 'note', 'notes', 'review', 'subject', 'title', 'summary']
/** A small RFC 4180 reader: quoted fields, doubled quotes, CRLF, and a guessed delimiter. */
@@ -58,7 +59,7 @@ function tidyValue(v) {
* @param {string} workspace absolute workspace path
* @param {string} name the file, relative to the workspace
*/
-export function loadSource(workspace, name, { textColumn, limit = 2000 } = {}) {
+export function loadSource(workspace, name, { textColumn, limit = 10000 } = {}) {
const root = resolve(workspace)
const file = resolve(root, String(name))
const fail = (error) => ({ rows: [], error, file: null, info: null })
@@ -67,15 +68,15 @@ export function loadSource(workspace, name, { textColumn, limit = 2000 } = {}) {
let raw
try {
if (statSync(file).size > SOURCE_LIMITS.bytes) return fail(`source "${name}" is over ${SOURCE_LIMITS.bytes / 1024 / 1024} MB`)
- raw = readFileSync(file, 'utf8').replace(/^/, '')
+ raw = extname(file).toLowerCase() === '.xlsx' ? readFileSync(file) : readFileSync(file, 'utf8').replace(/^/, '')
} catch (e) { return fail(`source "${name}" cannot be read: ${e.code ?? e.message}`) }
const ext = extname(file).toLowerCase()
let records // list of { text, ...fields }
let textName = 'text'
try {
- if (ext === '.csv' || ext === '.tsv' || ext === '.txt') {
- const table = parseDelimited(raw, ext === '.tsv' ? '\t' : undefined)
+ if (ext === '.csv' || ext === '.tsv' || ext === '.txt' || ext === '.xlsx') {
+ const table = ext === '.xlsx' ? readXlsx(raw) : parseDelimited(raw, ext === '.tsv' ? '\t' : undefined)
if (table.length < 2) return fail(`source "${name}" needs a header row and at least one data row`)
const headers = table[0].map((h, i) => String(h).trim() || `column_${i + 1}`)
const body = table.slice(1)
@@ -102,7 +103,7 @@ export function loadSource(workspace, name, { textColumn, limit = 2000 } = {}) {
for (const [k, v] of Object.entries(item)) if (k !== textName && ['string', 'number', 'boolean'].includes(typeof v) && Object.keys(rec).length <= SOURCE_LIMITS.fields) { const t = tidyValue(v); if (t !== undefined) rec[tidyKey(k)] = t }
return rec
})
- } else return fail(`source "${name}" must be a .csv, .tsv, .jsonl or .json file`)
+ } else return fail(`source "${name}" must be an .xlsx, .csv, .tsv, .jsonl or .json file`)
} catch (e) { return fail(`source "${name}" could not be parsed: ${e.message}`) }
const total = records.length
diff --git a/store/agents/jev-sheets/viewer/studio.css b/store/agents/jev-sheets/viewer/studio.css
index 37ca85e8f..3f925c945 100644
--- a/store/agents/jev-sheets/viewer/studio.css
+++ b/store/agents/jev-sheets/viewer/studio.css
@@ -209,3 +209,38 @@
#rail { width: 318px; }
.reviewbox { width: 168px; }
}
+
+/* ---- the front door: the person's own file ---- */
+.door { flex: none; display: flex; align-items: center; gap: 14px; padding: 12px 14px; margin-bottom: 10px; border: 1px dashed color-mix(in srgb, var(--accent) 60%, transparent); border-radius: var(--radius); background: color-mix(in srgb, var(--accent) 7%, transparent); transition: border-color .2s, background .2s; }
+.door.own { border-style: solid; border-color: color-mix(in srgb, var(--ok) 45%, transparent); background: color-mix(in srgb, var(--ok) 6%, transparent); }
+.door.busy { opacity: .7; pointer-events: none; }
+.door-icon { flex: none; width: 40px; height: 40px; display: grid; place-items: center; border-radius: 10px; color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, transparent); }
+.door.own .door-icon { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }
+.door-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
+.door-text b { font-size: 14px; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.door-text span { font-size: 11.5px; line-height: 1.45; color: var(--dim); }
+.door-actions { flex: none; display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; max-width: 46%; }
+.standin { flex: none; margin-bottom: 10px; padding: 9px 12px; border-radius: 10px; font-size: 12px; line-height: 1.45; color: var(--warn); border: 1px solid color-mix(in srgb, var(--warn) 50%, transparent); background: color-mix(in srgb, var(--warn) 8%, transparent); }
+.standin b { color: var(--ink); }
+.drop-veil { position: fixed; inset: 0; z-index: 90; display: grid; place-items: center; background: rgba(7, 8, 13, .82); backdrop-filter: blur(4px); }
+.drop-veil > div { display: flex; flex-direction: column; gap: 8px; align-items: center; text-align: center; padding: 44px 60px; border: 2px dashed var(--accent); border-radius: 20px; background: color-mix(in srgb, var(--accent) 10%, var(--panel)); max-width: 520px; }
+.drop-veil b { font-size: 24px; color: var(--ink); }
+.drop-veil span { font-size: 12.5px; line-height: 1.5; color: var(--dim); }
+.toast { position: fixed; left: 50%; bottom: 22px; transform: translateX(-50%); z-index: 95; max-width: 70vw; padding: 10px 16px; border-radius: 10px; font-size: 12.5px; color: var(--ink); background: var(--panel2); border: 1px solid color-mix(in srgb, var(--ok) 55%, transparent); box-shadow: 0 10px 34px rgba(0, 0, 0, .5); }
+.toast.bad { border-color: color-mix(in srgb, var(--bad) 60%, transparent); color: #ffd5dc; }
+.filter-chip { flex: none; max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border-color: var(--accent); color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); }
+
+/* ---- the findings: how many rows got each answer ---- */
+.find-empty { font-size: 11.5px; color: var(--faint); line-height: 1.5; }
+.find { display: flex; flex-direction: column; gap: 12px; max-height: 300px; overflow: auto; padding-right: 8px; }
+.find-head { display: flex; align-items: baseline; gap: 8px; margin-bottom: 4px; }
+.find-head b { font-size: 12px; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.find-head span { margin-left: auto; flex: none; font-size: 10.5px; color: var(--faint); }
+.find-row { position: relative; display: flex; align-items: center; gap: 8px; width: 100%; padding: 4px 8px; margin: 2px 0; border: 1px solid transparent; border-radius: 7px; background: rgba(255, 255, 255, .025); font: 11.5px var(--mono); color: var(--ink); text-align: left; overflow: hidden; }
+.find-row:hover { border-color: var(--line2); }
+.find-row.on { border-color: var(--accent); }
+.find-bar { position: absolute; left: 0; top: 0; bottom: 0; opacity: .24; border-radius: 6px 0 0 6px; transition: width .35s ease; pointer-events: none; }
+.find-label { position: relative; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.find-n { position: relative; flex: none; font-variant-numeric: tabular-nums; font-weight: 700; }
+.find-pct { position: relative; flex: none; width: 34px; text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
+.find-more { font-size: 10.5px; color: var(--faint); padding: 2px 8px; }
diff --git a/store/agents/jev-sheets/viewer/studio.js b/store/agents/jev-sheets/viewer/studio.js
index 7cb309aae..65cf6eb93 100644
--- a/store/agents/jev-sheets/viewer/studio.js
+++ b/store/agents/jev-sheets/viewer/studio.js
@@ -25,7 +25,7 @@ let selected = null, inspSeq = 0, inspTimer = null
let editing = null
let ghostInfo = { enabled: true, phase: 'idle', pausedMs: 0 }, ghostInfoAt = 0, ghostRun = null, ghostOwnsInput = false
let lastTouch = -1e9, lastTour = 0, hintErrorUntil = 0, reviewPostTimer = null, draggingReview = false
-let dirty = { rows: false, head: false, top: false, hist: false }
+let dirty = { rows: false, head: false, top: false, hist: false, find: false }
const tw = { rows: { v: 0, t: 0 }, cols: { v: 0, t: 0 }, cells: { v: 0, t: 0 }, rate: { v: 0, t: 0 }, cost: { v: 0, t: 0 }, flag: { v: 0, t: 0 } }
async function post(cmd, body = {}) {
@@ -77,7 +77,7 @@ function renderHead() {
headText.children[0].textContent = S.textLabel
const shownRows = order.length === S.rows.length ? `${S.rows.length} rows` : `${order.length} of ${S.rows.length} rows`
headText.children[1].textContent = S.source ? `${shownRows} · your file ${S.source.name} · text column "${S.source.textColumn}"${S.source.total > S.source.used ? ` · first ${S.source.used} of ${S.source.total}` : ''}` : `${shownRows} · made-up data · double-click to edit`
- const pill = document.getElementById('synthPill'); if (pill) { pill.textContent = S.source ? 'your data' : 'synthetic data'; pill.title = S.source ? `Rows come from ${S.source.name} in the workspace.` : 'Every name, message and truth label in this sheet is made up.' }
+ const pill = document.getElementById('synthPill'); if (pill) { pill.textContent = S.source ? 'your data' : 'made-up sample'; pill.title = S.source ? `Rows come from ${S.source.name} in the workspace.` : 'Every name, message and truth label in this sheet is made up.' }
for (const [id, el] of headCells) if (!colIndex.has(id)) { leave(el); headCells.delete(id) }
let prev = headText
for (const col of S.columns) {
@@ -220,7 +220,7 @@ function renderRows() {
}
const none = order.length === 0
$('empty').classList.toggle('hidden', !none)
- if (none) $('empty').innerHTML = S.rows.length ? '<b>Nothing under the review line</b>Drag the line to the right to see what Jev is least sure about.' : '<b>No rows yet</b>Ask the agent to build a sheet in sheet.json.'
+ if (none) $('empty').innerHTML = !S.rows.length ? '<b>No rows yet</b>Drop your own file on this pane, or ask the agent on the right to load one.' : S.filter ? '<b>No rows with that answer</b>Click the filter chip to show all rows.' : '<b>Nothing under the review line</b>Drag the line to the right to see what Jev is least sure about.'
}
/** Re-order rows. Rows slide to their new places; rows entering or leaving slide across the edge. */
function setOrder(next, animate) {
@@ -274,7 +274,7 @@ function applyState(s) {
const [a, b] = visibleRange()
for (let i = a; i <= b; i++) s.columns.forEach((c, j) => { if (s.cells[s.order[i]]?.[c.id]) held.set(s.order[i] + SEP + c.id, now + 260 + (i - a) * 30 + j * 55) })
}
- renderHead(); renderRows(); renderChips(); applyShared(s)
+ renderHead(); renderRows(); renderChips(); applyShared(s); renderDoor()
if (grew) grid.scrollTo({ left: grid.scrollWidth, behavior: 'smooth' })
if (selected) { if (rowIndex.has(selected.row) && colIndex.has(selected.col)) inspectSoon(); else select(null) }
}
@@ -284,13 +284,17 @@ function applyShared(v) {
$('reviewOnlyBtn').classList.toggle('on', !!S.reviewOnly)
if (!draggingReview) { $('reviewRange').value = S.reviewBelow; $('reviewVal').textContent = S.reviewBelow.toFixed(2) }
if (v.ghost) applyGhost(v.ghost)
- dirty.top = dirty.hist = true
+ if (v.client) S.client = v.client
+ // Own data with no key: say plainly that the stand-in is not the real model.
+ $('standin').classList.toggle('hidden', !(S.own && S.client === 'mock'))
+ renderFilterChip()
+ dirty.top = dirty.hist = dirty.find = true
}
function applyView(v) {
if (!S) return
const orderChanged = v.order.length !== order.length || v.order.some((id, i) => id !== order[i])
const lineMoved = v.reviewBelow !== S.reviewBelow
- Object.assign(S, { reviewBelow: draggingReview ? S.reviewBelow : v.reviewBelow, reviewOnly: v.reviewOnly, sort: v.sort, order: v.order, colStats: v.colStats, groups: v.groups, stats: v.stats, running: v.running, error: v.error, jevError: v.jevError })
+ Object.assign(S, { reviewBelow: draggingReview ? S.reviewBelow : v.reviewBelow, reviewOnly: v.reviewOnly, sort: v.sort, filter: v.filter ?? null, order: v.order, colStats: v.colStats, groups: v.groups, stats: v.stats, running: v.running, error: v.error, jevError: v.jevError })
if (orderChanged) setOrder(v.order, true)
renderHead(); renderRows(); applyShared(v)
if (lineMoved && selected) inspectSoon()
@@ -312,7 +316,7 @@ function applyCells(m) {
touched.get(rid).forEach((cid, k) => held.set(rid + SEP + cid, lastRevealAt + k * 40))
}
S.colStats = m.colStats; S.groups = m.groups; S.stats = m.stats
- dirty.head = dirty.top = dirty.hist = true
+ dirty.head = dirty.top = dirty.hist = dirty.find = true
}
// ---- top bar ----------------------------------------------------------------------------------
@@ -603,6 +607,132 @@ window.addEventListener('keydown', (e) => { if (e.key === '/' && !/^(INPUT|TEXTA
grid.addEventListener('scroll', () => { dirty.rows = true; grid.classList.toggle('xscrolled', grid.scrollLeft > 0) }, { passive: true })
new ResizeObserver(() => { layout(); dirty.rows = dirty.hist = true }).observe(grid)
+// ---- the front door: the person's own file --------------------------------------------------------
+const fmtN = (n) => Number(n).toLocaleString('en-US')
+let toastTimer = null
+function toast(msg, bad) {
+ const t = $('toast')
+ t.textContent = msg; t.className = 'toast' + (bad ? ' bad' : '')
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => t.classList.add('hidden'), bad ? 6000 : 3800)
+}
+function renderDoor() {
+ const own = !!S.own
+ $('door').classList.toggle('own', own)
+ $('synthPill').classList.toggle('hidden', own)
+ $('ownPill').classList.toggle('hidden', !own)
+ $('downloadBtn').classList.toggle('hidden', !own)
+ $('sampleBtn').classList.toggle('hidden', !own)
+ $('pickBtn').textContent = own ? 'Use another file' : 'Choose a file'
+ $('pickBtn').classList.toggle('primary', !own)
+ $('pasteBtn').classList.toggle('hidden', own)
+ $('demoBtn').classList.toggle('hidden', own)
+ if (own) {
+ const i = S.source
+ $('doorTitle').textContent = i.name
+ $('doorSub').textContent = `${fmtN(i.used)}${i.total > i.used ? ` of ${fmtN(i.total)}` : ''} rows from your file. Jev reads the "${i.textColumn}" column, with the other columns as context. Answers are saved to answers.csv in this project folder.`
+ } else {
+ $('doorTitle').textContent = 'Use your own file'
+ $('doorSub').textContent = 'Drop an Excel or CSV file anywhere on this pane, or paste rows copied from Excel or Google Sheets. Reviews, survey answers, tickets, leads: one row per item. Then type a question and Jev answers it for every row. Below is a made-up sample to try first.'
+ }
+}
+async function sendFile(file, name = file.name) {
+ if (!file) return
+ if (file.size > 32 * 1024 * 1024) return toast('That file is over 32 MB. Cut it down or split it first.', true)
+ $('door').classList.add('busy'); $('doorTitle').textContent = `Reading ${name}…`
+ let j
+ try {
+ const r = await fetch('/upload?name=' + encodeURIComponent(name), { method: 'POST', body: file })
+ j = await r.json()
+ } catch { j = { ok: false, error: 'The viewer did not answer. Try again.' } }
+ $('door').classList.remove('busy')
+ if (!j.ok) { renderDoor(); return toast(j.error || 'That file could not be read.', true) }
+ select(null)
+ toast(`${fmtN(j.rows)} rows loaded from ${j.file}. Now type a question.`)
+ input.focus()
+}
+/** Rows copied from a spreadsheet arrive as tab-separated text. One column of plain lines works too. */
+function pastedFile(text) {
+ const lines = String(text).replace(/\r\n?/g, '\n').split('\n').filter((l) => l.trim() !== '')
+ if (lines.length < 2) return null
+ if (lines[0].includes('\t')) return { name: 'pasted.tsv', blob: new Blob([lines.join('\n') + '\n']) }
+ // One column. A short first line over longer lines is a header; otherwise every line is a row.
+ const rest = lines.slice(1), avg = rest.reduce((a, l) => a + l.length, 0) / rest.length
+ const hasHeader = lines[0].length <= 30 && lines[0].split(/\s+/).length <= 3 && avg > lines[0].length * 2
+ const body = (hasHeader ? rest : lines).map((l) => JSON.stringify(l)).join('\n') + '\n'
+ return { name: 'pasted.jsonl', blob: new Blob([body]) }
+}
+function usePasted(text) {
+ const f = pastedFile(text)
+ if (!f) return toast('Copy at least two rows in your spreadsheet first, then paste.', true)
+ sendFile(f.blob, f.name)
+}
+$('pickBtn').addEventListener('click', () => $('fileInput').click())
+$('fileInput').addEventListener('change', (e) => { const f = e.target.files?.[0]; e.target.value = ''; sendFile(f) })
+$('pasteBtn').addEventListener('click', async () => {
+ try { usePasted(await navigator.clipboard.readText()) } catch { toast('Click on the pane and press Cmd+V or Ctrl+V to paste your rows.') }
+})
+window.addEventListener('paste', (e) => {
+ if (/^(INPUT|TEXTAREA)$/.test(document.activeElement?.tagName ?? '')) return
+ const text = e.clipboardData?.getData('text/plain') ?? ''
+ if (text.includes('\n')) { e.preventDefault(); usePasted(text) }
+})
+$('sampleBtn').addEventListener('click', async () => { select(null); const r = await post('useSample'); if (!r.ok) toast(r.error || 'The sample could not be loaded.', true) })
+$('downloadBtn').addEventListener('click', async () => {
+ await post('export')
+ const a = document.createElement('a'); a.href = '/download/answers.csv'; a.download = 'answers.csv'; document.body.append(a); a.click(); a.remove()
+ toast('answers.csv is also in this project folder.')
+})
+let dragDepth = 0
+const hasFiles = (e) => [...(e.dataTransfer?.types ?? [])].includes('Files')
+window.addEventListener('dragenter', (e) => { if (!hasFiles(e)) return; e.preventDefault(); dragDepth++; $('dropVeil').classList.remove('hidden') })
+window.addEventListener('dragover', (e) => { if (hasFiles(e)) e.preventDefault() })
+window.addEventListener('dragleave', (e) => { if (!hasFiles(e)) return; dragDepth = Math.max(0, dragDepth - 1); if (!dragDepth) $('dropVeil').classList.add('hidden') })
+window.addEventListener('drop', (e) => {
+ if (!hasFiles(e)) return
+ e.preventDefault(); dragDepth = 0; $('dropVeil').classList.add('hidden')
+ sendFile(e.dataTransfer.files?.[0])
+})
+
+// ---- the findings: how many rows got each answer --------------------------------------------------
+function valueLabels(col) { return col.type === 'noul' ? ['no', 'yes'] : col.type === 'choice' ? col.options : col.levels }
+function valueTone(col, i) { return toneOf(col, { v: i }) }
+function renderFilterChip() {
+ const chip = $('filterChip'), f = S.filter, col = f && colIndex.get(f.col)
+ chip.classList.toggle('hidden', !col)
+ if (col) chip.textContent = `${col.name}: ${valueLabels(col)[f.v] ?? '?'} ×`
+}
+$('filterChip').addEventListener('click', () => { if (S?.filter) post('filter', { col: S.filter.col, v: S.filter.v }) })
+function renderFindings() {
+ const box = $('findBody')
+ const cols = S.columns.filter((c) => S.colStats?.[c.id]?.dist)
+ if (!cols.length) { box.className = 'find-empty'; box.textContent = 'Type a question above. The counts for every answer show up here.'; return }
+ box.className = 'find'
+ box.textContent = ''
+ for (const col of cols) {
+ const st = S.colStats[col.id], labels = valueLabels(col)
+ const block = h('div', 'find-col')
+ const head = h('div', 'find-head')
+ head.append(h('b', '', col.name), h('span', '', st.filled < S.stats.rows ? `${fmtN(st.filled)} of ${fmtN(S.stats.rows)} rows` : `${fmtN(st.filled)} rows`))
+ block.append(head)
+ // A yes/no question leads with yes. A long choice list shows its biggest answers first.
+ let idx = labels.map((_, i) => i)
+ if (col.type === 'noul') idx = [1, 0]
+ else if (col.type === 'choice') idx.sort((a, b) => st.dist[b] - st.dist[a])
+ const shown = idx.slice(0, 8)
+ for (const i of shown) {
+ const n = st.dist[i] ?? 0, share = st.filled ? n / st.filled : 0
+ const row = h('button', 'find-row' + (S.filter && S.filter.col === col.id && S.filter.v === i ? ' on' : ''))
+ row.title = `Show only the ${fmtN(n)} rows where ${col.name} is "${labels[i]}"`
+ const bar = h('i', 'find-bar'); bar.style.width = `${Math.max(share * 100, n ? 1.5 : 0)}%`; bar.style.background = valueTone(col, i)
+ row.append(bar, h('span', 'find-label', labels[i]), h('span', 'find-n', fmtN(n)), h('span', 'find-pct', `${Math.round(share * 100)}%`))
+ row.addEventListener('click', () => post('filter', { col: col.id, v: i }))
+ block.append(row)
+ }
+ if (idx.length > shown.length) block.append(h('div', 'find-more', `+ ${idx.length - shown.length} more answers in answers.csv`))
+ box.append(block)
+ }
+}
+
// ---- the frame loop ---------------------------------------------------------------------------
function frame(now) {
if (S) {
@@ -617,6 +747,7 @@ function frame(now) {
if (dirty.head) { dirty.head = false; renderHead() }
if (dirty.top) { dirty.top = false; renderTop() }
if (dirty.hist) { dirty.hist = false; drawHist() }
+ if (dirty.find) { dirty.find = false; renderFindings() }
stepTweens(); stepGhost(now); stepTour(now)
}
requestAnimationFrame(frame)
diff --git a/store/agents/jev-sheets/viewer/viewer.mjs b/store/agents/jev-sheets/viewer/viewer.mjs
index 03348e9b7..498000ccb 100644
--- a/store/agents/jev-sheets/viewer/viewer.mjs
+++ b/store/agents/jev-sheets/viewer/viewer.mjs
@@ -8,15 +8,21 @@
import { join, dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { evaluate, jev, toWire, PRICE_PER_MTOK, resolveCredentials } from '../toolchain/jev.mjs'
-import { serveViewer, writeVerdict, watchConfig, mulberry32, clean } from './kit.mjs'
+import { serveViewer, writeVerdict, watchConfig, watchPath, mulberry32, clean } from './kit.mjs'
import { parseHeader, normalizeSheet, columnKey, judge, confidenceOf, levelOf, describeColumn, LIMITS } from './grammar.mjs'
import { sheetMock } from './mock.mjs'
import { loadSource } from './source.mjs'
-import { watch as watchFile, writeFileSync, renameSync } from 'node:fs'
+import { writeFileSync, renameSync, readFileSync, existsSync, rmSync } from 'node:fs'
+import { extname } from 'node:path'
const HERE = dirname(fileURLToPath(import.meta.url))
const MARKER = 'sheet.json'
const GHOST_PAUSE_MS = 60000
+// Starter questions for a file nobody has looked at yet. The chat agent replaces them with sharper ones.
+const OWN_SUGGESTIONS = ['Is this a complaint?', 'Sentiment: negative < neutral < positive', 'Asks a question?', 'Mentions price or cost?', 'Urgency']
+const SAMPLE_BACKUP = 'sheet.sample.json'
+const OWN_EXT = new Set(['.xlsx', '.csv', '.tsv', '.txt', '.json', '.jsonl', '.ndjson'])
+const RESERVED = new Set(['sheet.json', 'answers.csv', 'sheet.sample.json', 'findings.md', 'report.md'])
const FALLBACK_SUGGESTIONS = ['Urgency', 'Sentiment: negative < neutral < positive', 'Asks a question?', 'Complaint?']
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const r3 = (x) => Math.round(x * 1000) / 1000
@@ -32,10 +38,12 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
let todo = new Set() // row ids with at least one missing cell
let inflight = new Set() // row objects being judged right now
let order = [], sort = null, reviewOnly = false, reviewBelow = 0.65, fileReviewBelow = null, fileDemo = null
+ let filter = null // { col, v }: show only the rows whose answer in that column is option/level v
let running = autostart, stopped = false, epoch = 0, rev = 0
+ let loadedAt = null // when sheet.json was last taken in: the agent's proof that a save was seen
let counters = { calls: 0, cacheHits: 0, tokens: 0, costUsd: 0, errors: 0, computed: 0 }
let burst = { active: false, startedAt: 0, cells: 0, rate: 0, ms: 0 }
- let patches = [], patchTimer = null, verdictTimer = null, retryTimer = null, ghostTimer = null
+ let patches = [], patchTimer = null, verdictTimer = null, retryTimer = null, ghostTimer = null, progressTimer = null
let ghost = { enabled: true, phase: 'idle', header: '', typeMs: 0, startedAt: 0, nextAt: 0, removeAt: 0, pausedUntil: 0, cursor: 0, watching: false }
const rng = mulberry32(20260919)
// Which live route is active (typesafe, cloudflare, openrouter), or null for the offline stand-in.
@@ -72,8 +80,10 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
m.set(col.id, cell)
return cell
}
+ // The context is put in front of every question, so it is part of what was asked.
+ const keyOf = (col) => `${sheet.context ?? ''}\u0001${columnKey(col)}`
function cacheFor(col) {
- const k = columnKey(col)
+ const k = keyOf(col)
let m = cache.get(k)
if (!m) cache.set(k, (m = new Map()))
return m
@@ -98,7 +108,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
// ---- the numbers ---------------------------------------------------------------------------
function tally() {
const colStats = {}, groups = {}
- for (const c of columns) colStats[c.id] = { filled: 0, flagged: 0, labelled: 0, correct: 0, conf: 0 }
+ for (const c of columns) colStats[c.id] = { filled: 0, flagged: 0, labelled: 0, correct: 0, conf: 0, dist: new Array(c.type === 'noul' ? 2 : c.type === 'choice' ? c.options.length : c.levels.length).fill(0) }
let filled = 0, flagged = 0
for (const row of rows) {
const m = cells.get(row.id)
@@ -108,6 +118,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
if (!cell) continue
const s = colStats[c.id]
s.filled++; s.conf += cell.conf; filled++
+ const v = valueIndex(c, cell); if (v >= 0 && v < s.dist.length) s.dist[v]++
if (cell.conf < reviewBelow) { s.flagged++; flagged++ }
if (cell.ok != null) { s.labelled++; if (cell.ok) s.correct++ }
if (row.group) {
@@ -130,6 +141,14 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
}
}
+ /** The answer as an index: no/yes = 0/1, a choice = its option, a score = its level. */
+ function valueIndex(col, cell) {
+ const a = cell.answer
+ if (col.type === 'noul') return a.noul >= 0.5 ? 1 : 0
+ if (col.type === 'choice') return col.options.indexOf(String(a.choice))
+ return levelOf(col, a)
+ }
+
// ---- order: sort and the "needs review only" filter -----------------------------------------
function rowNeedsReview(row) {
const m = cells.get(row.id)
@@ -147,6 +166,9 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
function computeOrder() {
let list = rows
if (reviewOnly) list = list.filter((r) => rowNeedsReview(r) || hasMissing(r))
+ const fcol = filter && colById(filter.col)
+ if (filter && !fcol) filter = null
+ if (fcol) list = list.filter((r) => { const cell = cellOf(r.id, fcol.id); return cell && valueIndex(fcol, cell) === filter.v })
const col = sort && colById(sort.col)
if (!col) { if (sort) sort = null; order = list.map((r) => r.id); return }
const dir = sort.dir === 'asc' ? 1 : -1
@@ -165,7 +187,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
}
}
function lightView() {
- return { rev, running, reviewBelow, reviewOnly, sort, order, error: configError, jevError, ghost: ghostView(), ...tally() }
+ return { rev, running, reviewBelow, reviewOnly, sort, filter, order, error: configError, jevError, client: liveRoute() ?? 'mock', ghost: ghostView(), ...tally() }
}
function fullState() {
const cellsOut = {}
@@ -179,6 +201,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
return {
title: sheet.title, description: sheet.description, textLabel: sheet.textLabel, client: liveRoute() ?? 'mock',
source: sourceInfo, // set when the rows come from the person's own file
+ own: !!sourceInfo, answersFile: ANSWERS,
concurrency: sheet.concurrency, limits: LIMITS,
suggestions: sheet.suggestions.length ? sheet.suggestions : FALLBACK_SUGGESTIONS,
columns: columns.map((c) => ({ id: c.id, header: c.header, name: c.name, type: c.type, options: c.options, descriptions: c.descriptions, levels: c.levels, bare: !!c.bare, source: c.source, kind: describeColumn(c) })),
@@ -193,6 +216,8 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
function flushPatches() {
clearTimeout(patchTimer); patchTimer = null
if (!patches.length) return
+ // While a long fill runs, the verdict moves every two seconds, so the chat agent can watch it climb.
+ if (!progressTimer) progressTimer = setTimeout(() => { progressTimer = null; saveVerdict() }, 2000)
const out = patches; patches = []
const t = tally()
server?.broadcast({ rev, patches: out, colStats: t.colStats, groups: t.groups, stats: t.stats }, 'cells')
@@ -213,7 +238,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
// The rows worth a second look: wrong ones first, then the least sure.
const weak = rows.map((r) => ({ r, cell: cellOf(r.id, c.id) })).filter((x) => x.cell && (x.cell.ok === false || x.cell.conf < reviewBelow))
.sort((a, b) => (a.cell.ok === false ? 0 : 1) - (b.cell.ok === false ? 0 : 1) || a.cell.conf - b.cell.conf).slice(0, 5)
- .map(({ r, cell }) => ({ row: r.id, text: r.text.slice(0, 90), answered: shown(c, cell.answer), confidence: r3(cell.conf), truth: r.truth?.[c.id] ?? null }))
+ .map(({ r, cell }) => ({ row: r.id, n: rows.indexOf(r) + 1, text: r.text.slice(0, 90), answered: shown(c, cell.answer), confidence: r3(cell.conf), truth: r.truth?.[c.id] ?? null }))
report.push({ id: c.id, header: c.header, type: c.type, source: c.source, filled: s.filled, accuracy: s.acc, labelled: s.labelled, underReviewLine: s.flagged, avgConfidence: s.avgConf, weakest: weak })
const share = s.filled ? s.flagged / s.filled : 0
findings.push({
@@ -233,7 +258,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
{ id: 'fill', name: 'Cells filled', state: full ? 'done' : stats.cellsTotal ? 'active' : 'pending' },
{ id: 'review', name: 'Review', state: !full ? 'pending' : stats.flagged ? 'active' : 'done' },
],
- sheet: { client: liveRoute() ?? 'mock', reviewBelow, rows: stats.rows, cellsFilled: stats.cellsFilled, cellsTotal: stats.cellsTotal, flagged: stats.flagged, costUsd: stats.costUsd, groups, columns: report },
+ sheet: { client: liveRoute() ?? 'mock', loadedAt, source: sourceInfo?.name ?? null, reviewBelow, rows: stats.rows, cellsFilled: stats.cellsFilled, cellsTotal: stats.cellsTotal, flagged: stats.flagged, costUsd: stats.costUsd, groups, columns: report },
}
}
function shown(col, a) {
@@ -334,9 +359,9 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
if (todo.size || inflight.size) return
const wasBusy = burst.active
burst.active = false
- if (sort || reviewOnly) computeOrder()
+ if (sort || reviewOnly || filter) computeOrder()
flushPatches()
- if (wasBusy || sort || reviewOnly) pushView()
+ if (wasBusy || sort || reviewOnly || filter) pushView()
verdictSoon()
}
function pump() {
@@ -377,8 +402,9 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
const col = colById(id)
if (!col) return { ok: false, error: 'no such column' }
columns = columns.filter((c) => c !== col)
- cache.delete(columnKey(col)) // its answers go with it; typing it again asks Jev again
+ cache.delete(keyOf(col)) // its answers go with it; typing it again asks Jev again
if (sort?.col === id) sort = null
+ if (filter?.col === id) filter = null
refill(); changed()
return { removed: id }
}
@@ -404,7 +430,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
if (file === sourceFile) return
sourceWatcher?.close(); sourceWatcher = null; sourceFile = file
if (!file) return
- try { sourceWatcher = watchFile(file, () => { clearTimeout(sourceTimer); sourceTimer = setTimeout(() => { if (!stopped) applySheet(watcher.get(), false) }, 80) }) } catch { /* the file may vanish; the next edit to sheet.json retries */ }
+ sourceWatcher = watchPath(file, () => { clearTimeout(sourceTimer); sourceTimer = setTimeout(() => { if (!stopped) applySheet(watcher.get(), false) }, 80) })
}
function applySheet(raw, fresh) {
const next = normalizeSheet(expandSource(raw))
@@ -412,6 +438,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
if (!next.rows.length && rows.length && !fresh) { configError = `${MARKER}: ${problems || 'needs at least one row with text'}. Showing the last good sheet`; pushView(); verdictSoon(); return }
configError = problems ? `${MARKER}: ${problems}` : null
sheet = next
+ loadedAt = new Date().toISOString()
epoch++
rows = next.rows.map((r) => ({ ...r, edited: false, retryAt: 0 }))
rowById = new Map(rows.map((r) => [r.id, r]))
@@ -424,8 +451,56 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
fileReviewBelow = next.reviewBelow; fileDemo = next.demo
refill(); changed()
}
+ // ---- the person's own file: dropped or pasted in the pane --------------------------------------
+ function safeFileName(name) {
+ let base = String(name ?? '').split(/[\\/]/).pop().normalize('NFKD').replace(/[^\w.\- ]+/g, '').trim().replace(/\s+/g, '-').replace(/^\.+/, '')
+ if (base.length > 80) base = base.slice(0, 60) + base.slice(-20)
+ if (!base || !extname(base)) return ''
+ return RESERVED.has(base.toLowerCase()) ? `my-${base}` : base
+ }
+ function writeMarker(obj) {
+ const f = join(workspace, MARKER)
+ writeFileSync(f + '.tmp', JSON.stringify(obj, null, 2) + '\n'); renameSync(f + '.tmp', f)
+ }
+ /** A file lands from the pane. It is checked first; only a file that reads well replaces the sheet. */
+ async function upload(name, buf) {
+ touch()
+ const file = safeFileName(name)
+ const ext = extname(file).toLowerCase()
+ if (!file || !OWN_EXT.has(ext)) return { ok: false, error: 'Use an Excel .xlsx file, or a .csv, .tsv, .json or .jsonl file. An old .xls or a Numbers file: save it as .xlsx or CSV first.' }
+ if (!buf.length) return { ok: false, error: 'That file is empty.' }
+ const target = join(workspace, file)
+ const had = existsSync(target) ? readFileSync(target) : null
+ writeFileSync(target, buf)
+ const got = loadSource(workspace, file, { limit: LIMITS.maxRows })
+ if (got.error) { if (had) writeFileSync(target, had); else rmSync(target, { force: true }); return { ok: false, error: got.error } }
+ // Keep the made-up sample, so "back to the sample" works.
+ try {
+ const cur = JSON.parse(readFileSync(join(workspace, MARKER), 'utf8'))
+ if (!cur.source && !existsSync(join(workspace, SAMPLE_BACKUP))) writeFileSync(join(workspace, SAMPLE_BACKUP), JSON.stringify(cur, null, 2) + '\n')
+ } catch { /* no sample worth keeping */ }
+ const title = file.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').trim() || 'My file'
+ const next = { title, description: `Rows from ${file}, the person's own file.`, source: file, textLabel: got.info.textColumn, demo: false, concurrency: 16, columns: [], suggestions: OWN_SUGGESTIONS }
+ writeMarker(next)
+ filter = null; sort = null; reviewOnly = false
+ applySheet(next, true)
+ return { file, rows: got.info.used, total: got.info.total, textColumn: got.info.textColumn }
+ }
+ function useSample() {
+ touch()
+ let sample = null
+ for (const f of [join(workspace, SAMPLE_BACKUP), join(HERE, '..', 'template', MARKER)]) {
+ try { sample = JSON.parse(readFileSync(f, 'utf8')); if (sample && !sample.source) break; sample = null } catch { sample = null }
+ }
+ if (!sample) return { ok: false, error: 'the made-up sample is not on this machine' }
+ writeMarker(sample)
+ filter = null; sort = null; reviewOnly = false
+ applySheet(sample, true)
+ return { sample: true }
+ }
+
function reset() {
- cache = new Map(); sort = null; reviewOnly = false; jevError = null
+ cache = new Map(); sort = null; reviewOnly = false; filter = null; jevError = null
counters = { calls: 0, cacheHits: 0, tokens: 0, costUsd: 0, errors: 0, computed: 0 }
burst = { active: false, startedAt: 0, cells: 0, rate: 0, ms: 0 }
patches = []
@@ -531,6 +606,14 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
computeOrder(); pushView(); return { sort }
}
case 'reviewOnly': touch(); reviewOnly = !!body.on; computeOrder(); pushView(); return { reviewOnly }
+ case 'filter': {
+ // Click an answer count to see only those rows. The same click again clears it.
+ touch()
+ const col = colById(String(body.col ?? '')), v = Number(body.v)
+ filter = !col || !Number.isInteger(v) || v < 0 || (filter && filter.col === col.id && filter.v === v) ? null : { col: col.id, v }
+ computeOrder(); pushView(); return { filter }
+ }
+ case 'useSample': return useSample()
case 'setReview': {
touch()
const v = Number(body.value)
@@ -553,7 +636,10 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
if (err) { configError = `${err}. Showing the last good sheet`; pushView(); verdictSoon(); return }
applySheet(cfg, false)
})
- server = await serveViewer({ here: HERE, port, files: ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js', 'grammar.mjs'], state: fullState, control })
+ server = await serveViewer({ here: HERE, port, files: ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js', 'grammar.mjs'], state: fullState, control,
+ upload, downloads: () => { saveAnswers(); return { [ANSWERS]: join(workspace, ANSWERS) } },
+ // A key just arrived: the stand-in's answers are dropped and every cell is asked again, for real.
+ onConnect: () => reset() })
applySheet(watcher.get(), true)
if (watcher.error()) configError = watcher.error()
saveVerdict()
@@ -564,7 +650,7 @@ export async function startSheetsViewer({ workspace, port = 0, autostart = true,
async close() {
sourceWatcher?.close(); clearTimeout(sourceTimer); saveAnswers(); clearTimeout(answersTimer)
stopped = true
- clearInterval(ghostTimer); clearTimeout(patchTimer); clearTimeout(verdictTimer); clearTimeout(retryTimer)
+ clearInterval(ghostTimer); clearTimeout(patchTimer); clearTimeout(verdictTimer); clearTimeout(retryTimer); clearTimeout(progressTimer)
watcher.close()
await server.close()
},
diff --git a/store/agents/jev-sheets/viewer/xlsx.mjs b/store/agents/jev-sheets/viewer/xlsx.mjs
new file mode 100644
index 000000000..e0646c305
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/xlsx.mjs
@@ -0,0 +1,88 @@
+// xlsx.mjs — read the first sheet of an Excel workbook into rows of strings. No dependencies.
+//
+// An .xlsx file is a zip of XML parts. This reads just enough of both: the zip's central directory,
+// `xl/sharedStrings.xml`, and the first worksheet. Formulas give their last saved value. Dates come
+// through as Excel's day numbers unless the cell was saved as text. Limits keep a hostile file
+// from eating memory.
+import { inflateRawSync } from 'node:zlib'
+
+const LIMITS = { part: 256 * 1024 * 1024, cells: 2_000_000 }
+
+/** name -> { method, start, size, rawSize } for every file in the zip. */
+function directory(buf) {
+ let eocd = -1
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break }
+ if (eocd < 0) throw new Error('not a zip file')
+ const count = buf.readUInt16LE(eocd + 10)
+ let at = buf.readUInt32LE(eocd + 16)
+ const out = new Map()
+ for (let n = 0; n < count; n++) {
+ if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) throw new Error('damaged zip directory')
+ const method = buf.readUInt16LE(at + 10), size = buf.readUInt32LE(at + 20), rawSize = buf.readUInt32LE(at + 24)
+ const nameLen = buf.readUInt16LE(at + 28), extraLen = buf.readUInt16LE(at + 30), commentLen = buf.readUInt16LE(at + 32)
+ const local = buf.readUInt32LE(at + 42)
+ const name = buf.toString('utf8', at + 46, at + 46 + nameLen)
+ out.set(name, { method, local, size, rawSize })
+ at += 46 + nameLen + extraLen + commentLen
+ }
+ return out
+}
+
+function part(buf, dir, name) {
+ const e = dir.get(name)
+ if (!e) return null
+ if (e.rawSize > LIMITS.part) throw new Error(`${name} is too large`)
+ if (e.local + 30 > buf.length || buf.readUInt32LE(e.local) !== 0x04034b50) throw new Error('damaged zip entry')
+ const start = e.local + 30 + buf.readUInt16LE(e.local + 26) + buf.readUInt16LE(e.local + 28)
+ const data = buf.subarray(start, start + e.size)
+ if (e.method === 0) return data.toString('utf8')
+ if (e.method === 8) return inflateRawSync(data, { maxOutputLength: LIMITS.part }).toString('utf8')
+ throw new Error(`${name} uses a zip method this reader does not know`)
+}
+
+const ENT = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }
+const unxml = (s) => s.replace(/&(#x[0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);/g, (_, e) => (e[0] === '#' ? String.fromCodePoint(e[1] === 'x' ? parseInt(e.slice(2), 16) : Number(e.slice(1))) : ENT[e]))
+ .replace(/_x([0-9A-Fa-f]{4})_/g, (_, h) => String.fromCharCode(parseInt(h, 16)))
+/** All <t> text inside a fragment, skipping phonetic guides. */
+const texts = (xml) => { let out = ''; for (const m of xml.replace(/<rPh[\s\S]*?<\/rPh>/g, '').matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)) out += unxml(m[1]); return out }
+/** "BC12" -> 54 (zero-based column). */
+function columnOf(ref) { let n = 0; for (const ch of ref) { const c = ch.charCodeAt(0); if (c < 65 || c > 90) break; n = n * 26 + (c - 64) } return n - 1 }
+
+/**
+ * @param {Buffer} buf the bytes of an .xlsx file
+ * @returns {string[][]} the first sheet, one list of cell strings per row, blank rows dropped
+ */
+export function readXlsx(buf) {
+ const dir = directory(buf)
+ const shared = []
+ const sst = part(buf, dir, 'xl/sharedStrings.xml')
+ if (sst) for (const m of sst.matchAll(/<si>([\s\S]*?)<\/si>|<si\/>/g)) shared.push(m[1] ? texts(m[1]) : '')
+ // The first sheet: the lowest-numbered worksheet part.
+ const sheets = [...dir.keys()].filter((k) => /^xl\/worksheets\/sheet\d+\.xml$/.test(k)).sort((a, b) => Number(a.match(/(\d+)\.xml$/)[1]) - Number(b.match(/(\d+)\.xml$/)[1]))
+ if (!sheets.length) throw new Error('the workbook has no worksheet')
+ const xml = part(buf, dir, sheets[0])
+ const rows = []
+ let cells = 0
+ for (const rm of xml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
+ const row = []
+ let next = 0
+ for (const cm of rm[1].matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
+ if (++cells > LIMITS.cells) throw new Error('the sheet has too many cells')
+ const attrs = cm[1], body = cm[2] ?? ''
+ const ref = attrs.match(/\br="([A-Z]+)\d+"/)?.[1]
+ const col = ref ? columnOf(ref) : next
+ next = col + 1
+ const type = attrs.match(/\bt="(\w+)"/)?.[1]
+ const v = body.match(/<v(?:\s[^>]*)?>([\s\S]*?)<\/v>/)?.[1]
+ let value = ''
+ if (type === 's') value = shared[Number(v)] ?? ''
+ else if (type === 'inlineStr') value = texts(body)
+ else if (type === 'b') value = v === '1' ? 'TRUE' : 'FALSE'
+ else if (v != null) value = unxml(v)
+ if (col >= 0 && col < 4096) row[col] = value
+ }
+ const filled = Array.from(row, (x) => x ?? '')
+ if (filled.some((x) => x.trim() !== '')) rows.push(filled)
+ }
+ return rows
+}
diff --git a/store/agents/jev-shopper/viewer/jev-hud.js b/store/agents/jev-shopper/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-shopper/viewer/jev-hud.js
+++ b/store/agents/jev-shopper/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-slalom/viewer/jev-hud.js b/store/agents/jev-slalom/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-slalom/viewer/jev-hud.js
+++ b/store/agents/jev-slalom/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/agents/jev-trader/viewer/jev-hud.js b/store/agents/jev-trader/viewer/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/agents/jev-trader/viewer/jev-hud.js
+++ b/store/agents/jev-trader/viewer/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/showcase/jev-sheets/own-file.jpg b/store/showcase/jev-sheets/own-file.jpg
new file mode 100644
index 000000000..ee0464515
Binary files /dev/null and b/store/showcase/jev-sheets/own-file.jpg differ
diff --git a/store/tools/jev-kit/README.md b/store/tools/jev-kit/README.md
index e4fa7fd67..07c1849d6 100644
--- a/store/tools/jev-kit/README.md
+++ b/store/tools/jev-kit/README.md
@@ -3,8 +3,34 @@
You are building ONE harness for the OpenHarness store. A harness is a folder. When a person opens
it, they get a **viewer on the left** (a live web pane) and a **coding agent in a chat on the
right**. The agent edits one JSON file in the workspace; the viewer watches that file and reacts
-live. **The viewer is the experience.** It must be a joy to watch and to poke at. A plain canvas with
-a few shapes is a failure. Aim for something a person would screen-record and post.
+live. **The viewer is the experience.**
+
+## The bar: a real tool, never a demo
+
+A harness gives a person a new superpower on their own work. Lovable turns non-developers into
+developers. The KiCad harness turns non-engineers into board designers. A Jev harness turns one
+person into a team of tireless readers and judges. **No demos. No watch-only panes.**
+
+- Before you build, write one line: "turns a non-X into an X, and the real thing that comes out is Y".
+ If you cannot write it, do not build it.
+- **The person's own data is the front door.** They drop a file on the pane, paste rows, or point at
+ their folder. A made-up sample is a ten-second fallback, clearly labelled.
+- **They take the result away**: a file they can open elsewhere, and findings the agent writes up.
+- **Real answers need the real model.** The pane says plainly when the offline stand-in is answering,
+ and takes a pasted key right there.
+- Open it cold and ask "what do I do here?". If the answer is "watch", it fails.
+
+`store/agents/jev-sheets` is the reference: drop a CSV, ask in plain words, every row answered, counts
+you can click, `answers.csv` to keep, `findings.md` from the agent. Harnesses that miss this bar are
+unlisted with `node store/tools/listing.mjs unlist <name>`. Their code stays.
+
+The kit gives you the plumbing for this (all in `serveViewer`, all same-origin only):
+
+| option | route | what it is for |
+|---|---|---|
+| `upload: async (name, buffer) => reply` | `POST /upload?name=` | the person's own file, up to `maxUpload` (32 MB). Sanitise the name yourself and keep it inside the workspace |
+| `downloads: () => ({ 'answers.csv': path })` | `GET /download/<name>` | the results, as an attachment. Only the names you list |
+| `onConnect: (result) => …` | `POST /connect` | a key pasted into the live panel. It is saved chmod 600, proven with one call, never echoed. Re-ask your cells when it lands |
## What Jev is (facts, verified from the docs)
@@ -176,6 +202,14 @@ Rules for the words you write (README, AGENTS.md, SKILL.md, store.json):
- `node toolchain/check.mjs` accepts the template and rejects an out-of-range value.
- Screenshots reviewed at 1440x900 and 1100x800, with a clean page console.
+## Logos and icons
+
+Draw `brand/icon.svg` by hand (256x256, viewBox `0 0 96 96`, the shared rounded square first) and add the harness's subtitle word to `WORDS` in `brand.mjs`.
+With a headless Chrome on CDP port 9555 (the command is at the top of `brand.mjs`), run `node store/tools/jev-kit/brand.mjs`.
+It writes `logo.svg`, `logo-dark.svg`, `icon.png` and `assets.json`, and copies the PNG to `desktop/assets/engine-icons/<folder>.png`.
+`--sheet <out.png>` renders every icon at 96, 48, 24 and 16 px so you can judge it. `--check` needs no browser and fails on any drift.
+Then register the harness in `_harnesses` and `knownHarnessBase` in `desktop/lib/widgets/engine_identity.dart`.
+
## Report back
End with a short report: what you built, the interactions, the dial and its measured numbers, the
diff --git a/store/tools/jev-kit/brand.mjs b/store/tools/jev-kit/brand.mjs
new file mode 100644
index 000000000..e5e745fec
--- /dev/null
+++ b/store/tools/jev-kit/brand.mjs
@@ -0,0 +1,184 @@
+#!/usr/bin/env node
+// brand.mjs — logos and icons for the Jev harnesses. A harness opts in by having a hand-drawn
+// store/agents/jev-*/brand/icon.svg. That file is the source of truth. This tool writes everything
+// else from it (no dependencies; Node 22+).
+//
+// node store/tools/jev-kit/brand.mjs [--cdp 9555] write logo.svg, logo-dark.svg, icon.png and assets.json,
+// and copy icon.png to desktop/assets/engine-icons/<folder>.png
+// node store/tools/jev-kit/brand.mjs --check no browser needed. Exit 1 and say what drifted
+// node store/tools/jev-kit/brand.mjs --sheet /abs/sheet.png [--cdp 9555] every icon at 96, 48, 24 and 16 px, on light and on dark
+//
+// Rendering drives a headless Chrome over CDP. Start one first:
+// "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless=new --remote-debugging-port=9555 --user-data-dir=<a scratch folder> --no-first-run --no-default-browser-check about:blank
+// The lockup text and assets.json match store/tools/build-experience-branding.mjs, so every store identity reads as one family.
+import { createHash } from 'node:crypto'
+import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const repo = dirname(dirname(dirname(dirname(fileURLToPath(import.meta.url)))))
+const agents = join(repo, 'store', 'agents')
+const desktopIcons = join(repo, 'desktop', 'assets', 'engine-icons')
+
+// The word before "· AUTONOMOUS" under each name: one word for what Jev does there. Add a line when a harness gets a brand/icon.svg.
+export const WORDS = { 'jev-sheets': 'COLUMNS' }
+// Two of the store's older identities, shown at the end of the sheet so new marks are judged beside them.
+const BESIDE = ['drone-pilot', 'game-master']
+const FRAME = '<rect x="4" y="4" width="88" height="88" rx="23" fill="'
+const MAX_PNG = 100 * 1024
+
+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
+const xml = (s) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('"', '&quot;')
+const dataURL = (svg) => `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+export function lockup(icon, name, subtitle, dark) {
+ const shapes = icon.replace(/^[\s\S]*?<svg[^>]*>/, '').replace(/<\/svg>\s*$/, '').replace(/<title>[\s\S]*?<\/title>/, '').trim()
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="480" height="112" viewBox="0 0 480 112">
+ <title>${xml(name)} logo</title>
+ <rect width="480" height="112" rx="24" fill="${dark ? '#18252b' : '#f5f2e9'}"/>
+ <g transform="translate(8 8)">${shapes}</g>
+ <text x="120" y="53" fill="${dark ? '#f4f0e4' : '#243732'}" font-family="Arial, Helvetica, sans-serif" font-size="28" font-weight="600" letter-spacing="-.8">${xml(name)}</text>
+ <text x="121" y="76" fill="${dark ? '#a7bbb7' : '#63746b'}" font-family="Arial, Helvetica, sans-serif" font-size="10" font-weight="600" letter-spacing="2.1">${xml(subtitle)} · AUTONOMOUS</text>
+</svg>\n`
+}
+
+// Every Jev harness that ships a brand/icon.svg, with the two lockups this tool derives from it.
+export function plan() {
+ return readdirSync(agents).filter((n) => n.startsWith('jev-') && existsSync(join(agents, n, 'brand', 'icon.svg'))).sort().map((folder) => {
+ const dir = join(agents, folder, 'brand')
+ const icon = readFileSync(join(dir, 'icon.svg'), 'utf8')
+ const name = JSON.parse(readFileSync(join(agents, folder, 'harness.json'), 'utf8')).name
+ const word = WORDS[folder] ?? ''
+ return { folder, dir, icon, name, word, logos: { 'logo.svg': lockup(icon, name, word, false), 'logo-dark.svg': lockup(icon, name, word, true) }, native: join(desktopIcons, `${folder}.png`) }
+ })
+}
+
+const record = (h, png) => JSON.stringify({ source: 'icon.svg', license: 'MIT', sha256: { 'icon.svg': hash(h.icon), 'logo.svg': hash(h.logos['logo.svg']), 'logo-dark.svg': hash(h.logos['logo-dark.svg']), 'icon.png': hash(png) } }, null, 2) + '\n'
+
+function sourceProblems(h) {
+ const out = []
+ if (!h.word) out.push(`brand.mjs has no subtitle word for ${h.folder} in WORDS`)
+ if (!h.icon.includes('width="256" height="256" viewBox="0 0 96 96"')) out.push('icon.svg must be 256x256 with viewBox 0 0 96 96')
+ if (!/<title>[^<]+<\/title>/.test(h.icon)) out.push('icon.svg needs a <title>')
+ if (!h.icon.includes(FRAME)) out.push('icon.svg must start with the shared rounded square')
+ return out
+}
+
+export function check() {
+ const problems = []
+ for (const h of plan()) {
+ const say = (msg) => problems.push(`${h.folder}: ${msg}`)
+ const source = sourceProblems(h)
+ source.forEach(say)
+ if (source.length) continue
+ for (const [file, want] of Object.entries(h.logos)) {
+ if (!existsSync(join(h.dir, file))) say(`brand/${file} is missing`)
+ else if (readFileSync(join(h.dir, file), 'utf8') !== want) say(`brand/${file} drifted from icon.svg`)
+ }
+ if (!existsSync(join(h.dir, 'icon.png'))) { say('brand/icon.png is missing'); continue }
+ const png = readFileSync(join(h.dir, 'icon.png'))
+ if (png.length < 24 || png.toString('latin1', 1, 4) !== 'PNG' || png.readUInt32BE(16) !== 256 || png.readUInt32BE(20) !== 256) say('brand/icon.png must be a 256x256 PNG')
+ if (png.length > MAX_PNG) say(`brand/icon.png is ${png.length} bytes (max ${MAX_PNG})`)
+ if (!existsSync(join(h.dir, 'assets.json'))) say('brand/assets.json is missing')
+ else if (readFileSync(join(h.dir, 'assets.json'), 'utf8') !== record(h, png)) say('brand/assets.json does not match the files (wrong hash or format)')
+ if (!existsSync(h.native)) say(`desktop/assets/engine-icons/${h.folder}.png is missing`)
+ else if (!readFileSync(h.native).equals(png)) say(`desktop/assets/engine-icons/${h.folder}.png differs from brand/icon.png`)
+ }
+ return problems
+}
+
+// One blank Chrome tab, sized to the picture, with a see-through background.
+export async function openPage(port, width, height) {
+ const target = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: 'PUT' })).json()
+ const ws = new WebSocket(target.webSocketDebuggerUrl)
+ await new Promise((r, j) => { ws.onopen = r; ws.onerror = j })
+ let nextId = 1
+ const pending = new Map()
+ ws.onmessage = (ev) => {
+ const m = JSON.parse(ev.data)
+ if (!m.id || !pending.has(m.id)) return
+ const { r, j } = pending.get(m.id)
+ pending.delete(m.id)
+ m.error ? j(new Error(m.error.message)) : r(m.result)
+ }
+ const send = (method, params = {}) => new Promise((r, j) => { const id = nextId++; pending.set(id, { r, j }); ws.send(JSON.stringify({ id, method, params })) })
+ const evalJs = async (expression) => {
+ const res = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
+ if (res.exceptionDetails) throw new Error(res.exceptionDetails.exception?.description ?? res.exceptionDetails.text)
+ return res.result.value
+ }
+ await send('Page.enable')
+ await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false })
+ await send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } })
+ const { frameTree } = await send('Page.getFrameTree')
+ return {
+ evalJs,
+ async show(html) {
+ await send('Page.setDocumentContent', { frameId: frameTree.frame.id, html })
+ await evalJs('Promise.all([...document.images].map((img) => img.decode()))')
+ await sleep(60)
+ },
+ async shot(w = width, h = height) {
+ const { data } = await send('Page.captureScreenshot', { format: 'png', clip: { x: 0, y: 0, width: w, height: h, scale: 1 }, captureBeyondViewport: true })
+ return Buffer.from(data, 'base64')
+ },
+ async close() { await fetch(`http://127.0.0.1:${port}/json/close/${target.id}`).catch(() => {}); ws.close() },
+ }
+}
+
+export async function build(port) {
+ const all = plan()
+ for (const h of all) for (const p of sourceProblems(h)) throw new Error(`${h.folder}: ${p}`)
+ const page = await openPage(port, 256, 256)
+ try {
+ for (const h of all) {
+ for (const [file, svg] of Object.entries(h.logos)) writeFileSync(join(h.dir, file), svg)
+ await page.show(`<style>html,body{margin:0;background:transparent}img{display:block;width:256px;height:256px}</style><img alt="" src="${dataURL(h.icon)}">`)
+ const png = await page.shot()
+ writeFileSync(join(h.dir, 'icon.png'), png)
+ writeFileSync(h.native, png)
+ writeFileSync(join(h.dir, 'assets.json'), record(h, png))
+ console.log(`built ${h.folder} (icon.png is ${png.length} bytes)`)
+ }
+ } finally { await page.close() }
+}
+
+export async function sheet(port, out) {
+ const beside = BESIDE.filter((n) => existsSync(join(agents, n, 'brand', 'icon.svg'))).map((n) => ({ folder: `${n} (for scale)`, icon: readFileSync(join(agents, n, 'brand', 'icon.svg'), 'utf8') }))
+ const rows = [...plan(), ...beside]
+ const strip = (h, dark) => `<div class="strip${dark ? ' dark' : ''}">${[96, 48, 24, 16].map((s) => `<img alt="" width="${s}" height="${s}" src="${dataURL(h.icon)}">`).join('')}</div>`
+ const html = `<!doctype html><html><head><meta charset="utf-8"><style>
+ *{box-sizing:border-box}body{margin:0;padding:26px 30px;background:#e8e4d8;color:#243732;font:600 12px Arial,Helvetica,sans-serif}
+ h1{font-size:18px;letter-spacing:-.4px;margin:0 0 16px}h1 span{font-weight:400;color:#63746b}
+ .row{display:grid;grid-template-columns:96px 1fr 1fr;gap:8px;align-items:center;margin-top:8px}
+ .strip{display:flex;align-items:center;justify-content:space-around;height:112px;border-radius:14px;padding:0 10px;background:#fffdf7}.dark{background:#15191d}img{display:block}
+ </style></head><body><h1>Jev harness icons <span>at 96, 48, 24 and 16 px</span></h1>${rows.map((h) => `<div class="row"><span>${xml(h.folder.replace('jev-', ''))}</span>${strip(h, false)}${strip(h, true)}</div>`).join('')}</body></html>`
+ const page = await openPage(port, 760, 900)
+ try {
+ await page.show(html)
+ writeFileSync(out, await page.shot(760, await page.evalJs('Math.ceil(document.body.getBoundingClientRect().bottom)')))
+ console.log(`sheet -> ${out} (${rows.length - beside.length} Jev icons, ${beside.length} for scale)`)
+ } finally { await page.close() }
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
+ const args = process.argv.slice(2)
+ const opt = (name, fallback) => (args.includes(`--${name}`) ? args[args.indexOf(`--${name}`) + 1] : fallback)
+ const port = Number(opt('cdp', 9555))
+ if (args.includes('--check')) {
+ const problems = check()
+ for (const p of problems) console.log(p)
+ console.log(problems.length ? `${problems.length} problem(s). Fix the source, then run: node store/tools/jev-kit/brand.mjs` : `every Jev identity is current (${plan().map((h) => h.folder).join(', ')})`)
+ process.exit(problems.length ? 1 : 0)
+ }
+ try {
+ if (args.includes('--sheet')) {
+ if (!opt('sheet') || opt('sheet').startsWith('--')) { console.error('need --sheet <out.png>'); process.exit(2) }
+ await sheet(port, resolve(opt('sheet')))
+ } else await build(port)
+ } catch (e) {
+ console.error(e.cause?.code === 'ECONNREFUSED' ? `no Chrome on CDP port ${port}. Start one (see the top of this file) or pass --cdp <port>` : e.message)
+ process.exit(1)
+ }
+}
diff --git a/store/tools/jev-kit/jev-hud.js b/store/tools/jev-kit/jev-hud.js
index 87b284fe1..f35e24f70 100644
--- a/store/tools/jev-kit/jev-hud.js
+++ b/store/tools/jev-kit/jev-hud.js
@@ -37,7 +37,7 @@
.jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
.jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
.jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
- .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qid{font-weight:700;color:var(--jh-acc);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
.jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
.jh-conf b{color:var(--jh-ink)}
@@ -57,6 +57,17 @@
.jh-lvl{font-size:11px;color:var(--jh-ink)}
.jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
.jh-foot code{color:var(--jh-warn)}
+ .jh-connect{margin-top:10px;padding:10px;border:1px solid rgba(251,191,36,.45);border-radius:10px;background:rgba(251,191,36,.06)}
+ .jh-connect-t{font-size:12px;font-weight:700;color:var(--jh-ink);margin-bottom:4px}
+ .jh-connect-s{font-size:11px;color:var(--jh-dim);line-height:1.45;margin-bottom:8px}
+ .jh-connect-s b{color:var(--jh-warn);font-weight:600}
+ .jh-connect-row{display:flex;gap:6px}
+ .jh-connect input{flex:1;min-width:0;font:12px ui-monospace,Menlo,monospace;padding:7px 9px;border-radius:8px;border:1px solid var(--jh-line);background:rgba(0,0,0,.35);color:var(--jh-ink);outline:none}
+ .jh-connect input:focus{border-color:var(--jh-warn)}
+ .jh-connect button{font:600 12px ui-monospace,Menlo,monospace;padding:7px 12px;border-radius:8px;border:1px solid rgba(251,191,36,.6);background:rgba(251,191,36,.16);color:var(--jh-warn);cursor:pointer}
+ .jh-connect button:disabled{opacity:.5;cursor:default}
+ .jh-connect-msg{margin-top:6px;font-size:11px;line-height:1.4;color:var(--jh-dim);word-break:break-word}
+ .jh-connect-msg.bad{color:var(--jh-bad)} .jh-connect-msg.ok{color:var(--jh-ok)}
.jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
`
const style = document.createElement('style')
@@ -76,6 +87,12 @@
<svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
<div class="jh-qs"></div>
<div class="jh-err" hidden></div>
+ <form class="jh-connect" hidden>
+ <div class="jh-connect-t">Go live with real Jev</div>
+ <div class="jh-connect-s">Right now an <b>offline stand-in</b> answers. It only matches words, so it is not good enough for your own data. Paste a key to use the real model. An OpenRouter key takes about a minute to get at openrouter.ai/keys. The key is saved on this machine only.</div>
+ <div class="jh-connect-row"><input type="password" name="key" autocomplete="off" spellcheck="false" placeholder="sk-or-… or a TypeSafe key"><button type="submit">Connect</button></div>
+ <div class="jh-connect-msg"></div>
+ </form>
<div class="jh-foot"></div>`
function mount() {
@@ -97,6 +114,24 @@
const pulse = root.querySelector('.jh-pulse')
const errBox = root.querySelector('.jh-err')
const foot = root.querySelector('.jh-foot')
+ const connectForm = root.querySelector('.jh-connect')
+ const connectMsg = root.querySelector('.jh-connect-msg')
+ let connectedAt = 0
+ connectForm.addEventListener('submit', async (e) => {
+ e.preventDefault()
+ const input = connectForm.querySelector('input'), btn = connectForm.querySelector('button')
+ const key = input.value.trim()
+ input.value = '' // the key never stays in the page
+ if (!key) return
+ btn.disabled = true; connectMsg.className = 'jh-connect-msg'; connectMsg.textContent = 'Checking the key with one tiny call…'
+ try {
+ const r = await fetch('/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key }) })
+ const j = await r.json()
+ if (j.ok) { connectedAt = Date.now(); connectMsg.className = 'jh-connect-msg ok'; connectMsg.textContent = j.warning || 'Connected. Answers now come from the real model.'; window.dispatchEvent(new CustomEvent('jev-connected', { detail: { provider: j.provider } })) }
+ else { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = j.error || 'That did not work.' }
+ } catch { connectMsg.className = 'jh-connect-msg bad'; connectMsg.textContent = 'The viewer did not answer. Try again.' }
+ btn.disabled = false
+ })
const spark = root.querySelector('.jh-spark polyline')
const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
@@ -173,8 +208,14 @@
let lastAt = 0
function render(s) {
- const live = s.client && s.client !== 'mock'
- const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : s.client === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
+ // `route` is the key that is set up (known before any call); `client` is who answered the last call.
+ const via = s.route || (s.client && s.client !== 'mock' ? s.client : null)
+ const live = !!via
+ root.dataset.live = live ? '1' : '0'
+ // Show the box while there is no key, and leave its "Connected" line up for a few seconds after.
+ connectForm.hidden = !s.canConnect || (live && Date.now() - connectedAt > 6000)
+ connectForm.querySelector('.jh-connect-row').hidden = live
+ const route = via === 'cloudflare' ? 'Cloudflare Workers AI' : via === 'openrouter' ? 'OpenRouter' : 'the TypeSafe API'
badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
$k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
diff --git a/store/tools/jev-kit/jev.mjs b/store/tools/jev-kit/jev.mjs
index ad49ee927..0552989b9 100644
--- a/store/tools/jev-kit/jev.mjs
+++ b/store/tools/jev-kit/jev.mjs
@@ -112,9 +112,9 @@ function clamp(x) {
}
// Imports are hoisted, so they can live here with the code that needs them.
-import { readFileSync } from 'node:fs'
+import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
@@ -234,6 +234,7 @@ export function snapshot() {
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
+ route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
@@ -291,6 +292,62 @@ export function resolveCredentials(explicitKey) {
return null
}
+/**
+ * Store one credential in the credentials file, so a pane can go live without a terminal. The file
+ * is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
+ */
+export function saveCredential(name, value) {
+ if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
+ const v = String(value ?? '').trim()
+ if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
+ const path = credentialsPath()
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ let lines = []
+ try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
+ kept.push(`${name}=${v}`)
+ writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
+ credCache = null
+}
+
+/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
+export function removeCredential(name) {
+ if (!CRED_KEYS.includes(name)) return
+ const path = credentialsPath()
+ try {
+ const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
+ const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
+ writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
+ renameSync(path + '.tmp', path)
+ } catch { /* nothing to remove */ }
+ credCache = null
+}
+
+/**
+ * A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
+ * one tiny real call. A key the service refuses is removed again. Never throws.
+ * @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
+ */
+export async function connectKey(value, { probe = true } = {}) {
+ const v = String(value ?? '').trim()
+ const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
+ try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
+ const cred = resolveCredentials()
+ // Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
+ if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
+ try {
+ await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
+ return { ok: true, provider: cred.provider, stored: true, probed: true }
+ } catch (e) {
+ const msg = String(e?.message ?? e)
+ if (/\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg)) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
+ return { ok: true, provider: cred.provider, stored: true, probed: false, warning: `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
+ }
+}
+
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
diff --git a/store/tools/jev-kit/kit.mjs b/store/tools/jev-kit/kit.mjs
index f80d29b7d..cf754e544 100644
--- a/store/tools/jev-kit/kit.mjs
+++ b/store/tools/jev-kit/kit.mjs
@@ -2,9 +2,9 @@
// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
// /control, plus an atomic verdict writer and a safe JSON config watcher.
import { createServer } from 'node:http'
-import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
-import { join, extname } from 'node:path'
-import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync } from 'node:fs'
+import { join, extname, dirname, basename } from 'node:path'
+import { snapshot as jevSnapshot, connectKey } from '../toolchain/jev.mjs'
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
@@ -28,8 +28,13 @@ export function mulberry32(a) {
* @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
* @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
* @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ * @param {function} [o.upload] async (name, buffer) => JSON-safe reply. Turns on POST /upload?name=<file name>: the person
+ * drops their own file on the pane. The handler must sanitise the name itself.
+ * @param {number} [o.maxUpload] largest upload in bytes (default 32 MB)
+ * @param {function} [o.downloads] () => ({ 'answers.csv': '/abs/path' }). Turns on GET /download/<name> for those files.
+ * @param {function} [o.onConnect] called after a person connects a key in the pane (POST /connect)
*/
-export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control, upload, maxUpload = 32 * 1024 * 1024, downloads, onConnect }) {
const clients = new Set()
const allowed = new Set(files)
@@ -40,12 +45,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
+ // Anything that changes state must come from this pane. A web page on another site can reach
+ // 127.0.0.1 from the person's browser, so a POST with a foreign Origin is refused.
+ if (req.method !== 'GET') {
+ const origin = req.headers.origin
+ if ((origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) || req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); return res.end('Same origin only') }
+ }
try {
if (req.method === 'GET') {
+ if (downloads && path.startsWith('/download/')) {
+ const name = decodeURIComponent(path.slice('/download/'.length))
+ const list = downloads() ?? {}
+ const file = Object.prototype.hasOwnProperty.call(list, name) ? list[name] : null
+ if (!file || !existsSync(file)) { res.writeHead(404); return res.end('Not found') }
+ res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream', 'content-disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}"` })
+ return res.end(readFileSync(file))
+ }
const name = path === '/' ? 'index.html' : path.slice(1)
if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
- if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ // canConnect tells the live panel that this server takes a pasted key (POST /connect).
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ...jevSnapshot(), canConnect: true })) }
if (path === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
@@ -63,6 +83,27 @@ export async function serveViewer({ here, port = 0, files = ['index.html', 'base
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
}
+ // The person pastes a Jev key in the pane. It goes to the credentials file (chmod 600) and is
+ // proven with one tiny call. The key is never echoed back, logged or kept in the page.
+ if (req.method === 'POST' && path === '/connect') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 4096) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const out = await connectKey(j.key)
+ if (out.ok) { try { await onConnect?.(out) } catch { /* the pane still learns the key is in */ } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify(out))
+ }
+ // The person drops their own file on the pane. The raw bytes are the body.
+ if (req.method === 'POST' && path === '/upload' && upload) {
+ const chunks = []
+ let size = 0
+ for await (const c of req) { size += c.length; if (size > maxUpload) { res.writeHead(413, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: `that file is over ${Math.round(maxUpload / 1024 / 1024)} MB` })) } chunks.push(c) }
+ const reply = await upload(String(url.searchParams.get('name') ?? ''), Buffer.concat(chunks))
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
res.writeHead(404); res.end('Not found')
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
@@ -92,6 +133,24 @@ export function writeVerdict(workspace, verdict) {
renameSync(file + '.tmp', file)
}
+/**
+ * Call `onChange` whenever one file changes, however it was saved. Editors and coding agents save
+ * atomically (write a temp file, rename it over the target). `fs.watch` on the file itself keeps
+ * following the old inode and goes deaf after the first such save. So this watches the folder for
+ * that name, and a slow stat check catches anything the platform's watcher drops.
+ * @returns {{ close(): void }}
+ */
+export function watchPath(file, onChange, { pollMs = 1000 } = {}) {
+ const dir = dirname(file), name = basename(file)
+ const stamp = () => { try { const s = statSync(file); return `${s.ino}:${s.size}:${s.mtimeMs}` } catch { return 'missing' } }
+ let last = stamp(), closed = false, watcher = null
+ const check = () => { if (closed) return; const now = stamp(); if (now !== last) { last = now; onChange() } }
+ try { watcher = watch(dir, (_event, changed) => { if (!changed || changed === name) check() }) } catch { /* the folder may be gone; the poll still runs */ }
+ const poll = setInterval(check, pollMs)
+ poll.unref?.()
+ return { close() { closed = true; clearInterval(poll); watcher?.close() } }
+}
+
/**
* Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
* good config and reports the parse error instead of crashing the demo.
@@ -104,9 +163,7 @@ export function watchConfig(file, defaults, onChange) {
catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
}
load()
- let watcher = null
- try {
- watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
- } catch { /* file may not exist yet; defaults stand */ }
- return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+ // watchPath also sees a file that did not exist yet, and every save after an atomic replace.
+ const watcher = watchPath(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher.close() } }
}