pally-console / index.html
chatpbc1's picture
Pally console: chat + admin + docs links
b25393b verified
Raw History Blame Contribute Delete
30.5 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pally — Personal Business Agent</title>
<meta name="description" content="Chat with Pally-1.7B, a personal AI business consultant and executive agent by ChatPBC Labs. No API key needed.">
<style>
:root{
--bg:#0b0e14;--panel:#121722;--panel2:#0e1522;--line:#1e2636;
--text:#e8edf7;--dim:#8b97ad;--acc:#4f8cff;--acc2:#7aa8ff;
--ok:#22c55e;--bad:#ef4444;--warn:#f59e0b;
--user:#182031;--bot:#0e1522;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%}
body{
background:var(--bg);color:var(--text);
font:15px/1.55 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
display:flex;flex-direction:column;align-items:center;
}
.wrap{width:100%;max-width:820px;height:100dvh;display:flex;flex-direction:column;padding:0 14px}
/* header */
header{display:flex;align-items:center;gap:12px;padding:14px 2px 10px;flex-wrap:wrap}
.logo{display:flex;align-items:center;gap:10px}
.dot{width:10px;height:10px;border-radius:50%;background:var(--warn);flex:none}
.dot.ok{background:var(--ok);box-shadow:0 0 8px var(--ok)}
.dot.bad{background:var(--bad)}
h1{font-size:19px;font-weight:800;letter-spacing:.3px}
h1 b{color:var(--acc)}
.sub{font-size:12px;color:var(--dim)}
.hbtns{margin-left:auto;display:flex;gap:6px}
button{background:var(--acc);border:0;color:#fff;font:600 13px/1 ui-sans-serif,system-ui,sans-serif;
padding:9px 13px;border-radius:8px;cursor:pointer;transition:filter .15s}
button:hover{filter:brightness(1.15)}
button:disabled{opacity:.5;cursor:not-allowed}
button.ghost{background:transparent;border:1px solid var(--line);color:var(--dim)}
button.ghost:hover{border-color:var(--acc);color:var(--acc);filter:none}
button.warn{background:transparent;border:1px solid var(--warn);color:var(--warn)}
/* chips */
.chips{display:flex;gap:7px;overflow-x:auto;padding:2px 2px 10px;scrollbar-width:none}
.chips::-webkit-scrollbar{display:none}
.chip{white-space:nowrap;background:var(--panel);border:1px solid var(--line);color:var(--dim);
font-size:12.5px;padding:7px 11px;border-radius:999px;cursor:pointer;transition:.15s}
.chip:hover{border-color:var(--acc);color:var(--acc)}
/* chat */
#chat{flex:1;overflow-y:auto;background:var(--panel);border:1px solid var(--line);
border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:10px;min-height:0}
.msg{max-width:92%;padding:11px 14px;border-radius:12px;white-space:pre-wrap;word-break:break-word}
.msg.user{align-self:flex-end;background:var(--user);border:1px solid #24304a;border-bottom-right-radius:4px}
.msg.bot{align-self:flex-start;background:var(--bot);border:1px solid var(--line);border-bottom-left-radius:4px}
.msg.err{align-self:flex-start;background:#2a1215;border:1px solid #5c2026;color:#ffb4b4;border-bottom-left-radius:4px}
.msg.sys{align-self:center;background:transparent;border:0;color:var(--dim);font-size:12.5px;padding:4px}
.meta{font-size:11px;color:var(--dim);margin-top:6px;display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.meta .lat{color:var(--ok)}
.loopwarn{font-size:11px;color:var(--warn)}
/* md-lite */
.msg.bot p{margin:0 0 8px}.msg.bot p:last-child{margin:0}
.msg.bot strong{color:#fff}
.msg.bot code{background:#070a10;border:1px solid var(--line);border-radius:4px;padding:1px 5px;font-size:13px}
.msg.bot pre{background:#070a10;border:1px solid var(--line);border-radius:8px;padding:10px;overflow-x:auto;margin:8px 0}
.msg.bot pre code{border:0;background:transparent;padding:0}
.msg.bot ul,.msg.bot ol{margin:4px 0 8px 20px}
.msg.bot h1,.msg.bot h2,.msg.bot h3{font-size:15px;margin:8px 0 4px;color:var(--acc2)}
.msg.bot blockquote{border-left:3px solid var(--acc);padding-left:10px;color:var(--dim);margin:6px 0}
.typing{align-self:flex-start;color:var(--dim);font-size:13px;padding:6px 14px;background:var(--panel2);
border:1px solid var(--line);border-radius:12px;border-bottom-left-radius:4px}
.typing b{color:var(--acc)}
/* composer */
.composer{display:flex;gap:8px;padding:10px 0 6px;align-items:flex-end}
#input{flex:1;background:var(--panel);border:1px solid var(--line);color:var(--text);
padding:12px 14px;border-radius:12px;font:inherit;resize:none;max-height:140px;min-height:46px;outline:none}
#input:focus{border-color:var(--acc)}
#send{height:46px;padding:0 18px;font-size:14px}
.toggles{display:flex;gap:12px;align-items:center;padding:0 2px 10px;font-size:12px;color:var(--dim);flex-wrap:wrap}
.toggles label{display:flex;align-items:center;gap:6px}
input[type=range]{accent-color:var(--acc);width:90px}
select{background:var(--panel);border:1px solid var(--line);color:var(--text);border-radius:6px;padding:3px 6px;font-size:12px}
footer{font-size:11px;color:var(--dim);text-align:center;padding:2px 0 12px}
footer a{color:var(--acc);text-decoration:none}
/* modal */
.overlay{position:fixed;inset:0;background:rgba(5,8,14,.72);display:flex;align-items:center;justify-content:center;padding:16px;z-index:50}
.overlay.hidden{display:none}
.card{background:var(--panel);border:1px solid var(--line);border-radius:16px;padding:22px;width:100%;max-width:440px}
.card h2{font-size:18px;margin-bottom:4px}
.card .hint{font-size:12.5px;color:var(--dim);margin-bottom:14px}
.field{margin-bottom:11px}
.field label{display:block;font-size:12px;color:var(--dim);margin-bottom:4px}
.field input,.field textarea{width:100%;background:var(--bg);border:1px solid var(--line);color:var(--text);
padding:9px 11px;border-radius:8px;font:inherit;font-size:13.5px;outline:none}
.field input:focus,.field textarea:focus{border-color:var(--acc)}
.card .row{display:flex;gap:8px;margin-top:14px}
.card .row button{flex:1}
@media (max-width:520px){
.hbtns .lbl{display:none}
.msg{max-width:96%}
}
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="logo">
<div class="dot" id="dot"></div>
<div>
<h1><b>Pally</b> <span class="sub">· personal business agent</span></h1>
<div class="sub" id="epinfo">discovering endpoint…</div>
</div>
</div>
<div class="hbtns">
<button class="ghost" id="btnUmd" title="View / edit Pally's live UserMD">usermd</button>
<button class="ghost" id="btnSetup" title="Edit who Pally works for">setup</button>
<button class="ghost" id="btnExport" title="Download transcript">export</button>
<button class="ghost" id="btnClear" title="Start a new conversation">new chat</button>
</div>
</header>
<div class="chips" id="chips"></div>
<div id="chat"></div>
<div class="typing" id="typing" style="display:none"><b>Pally</b> is thinking<span id="tick"></span></div>
<div class="composer">
<textarea id="input" rows="1" placeholder="Ask Pally anything about your business… (Enter = send, Shift+Enter = new line)"></textarea>
<button id="send">Send</button>
</div>
<div class="toggles">
<label>temp <input type="range" id="temp" min="0.1" max="1" step="0.05" value="0.7"><span id="tempv">0.70</span></label>
<label>length
<select id="len">
<option value="256">short</option>
<option value="512" selected>normal</option>
<option value="1024">long</option>
</select>
</label>
<span id="statusline" style="margin-left:auto"></span>
</div>
<footer>Pally-1.7B by <a href="https://huggingface.co/chatpbc1" target="_blank" rel="noopener">ChatPBC Labs</a> · runs on a public T4 endpoint · no API key · memory = this chat only</footer>
</div>
<!-- setup / profile -->
<div class="overlay hidden" id="setupModal">
<div class="card">
<h2>Who does Pally work for?</h2>
<div class="hint">Stored only in your browser. This becomes Pally's <b>UserMD</b> — the single source of truth it grounds every answer in. It will never ask you for it again.</div>
<div class="field"><label>Your name</label><input id="pName" placeholder="e.g. Maya" maxlength="60"></div>
<div class="field"><label>Role &amp; company</label><input id="pRole" placeholder="e.g. Founder, DTC coffee subscription" maxlength="120"></div>
<div class="field"><label>What you're working on (optional)</label><textarea id="pFocus" rows="3" placeholder="e.g. Cutting churn from 8%, deciding whether to add a B2B tier" maxlength="400"></textarea></div>
<div class="field"><label>Paste a full UserMD (optional — overrides the fields above with your own profile)</label><textarea id="pRaw" rows="5" placeholder="- Role: CEO&#10;- Company: Acme — DTC coffee&#10;- MRR: $40k&#10;- Constraint: no paid ads before churn &lt;5%" spellcheck="false"></textarea></div>
<div class="field"><label>Endpoint URL (advanced — leave empty to auto-discover)</label><input id="pEp" placeholder="https://….trycloudflare.com" spellcheck="false"></div>
<div class="row">
<button class="ghost" id="btnSkip">skip</button>
<button id="btnSave">save &amp; start</button>
</div>
</div>
</div>
<!-- live UserMD inspector -->
<div class="overlay hidden" id="umdModal">
<div class="card">
<h2>Live UserMD</h2>
<div class="hint">Exactly what Pally sees this turn. Editable — every fact you add is used in the next answer. Facts marked <i>learned</i> were extracted automatically from the chat.</div>
<div class="field"><textarea id="umdView" rows="14" spellcheck="false" style="font:12.5px/1.5 ui-monospace,Menlo,Consolas,monospace"></textarea></div>
<div class="row">
<button class="ghost" id="btnUmdForget">clear learned facts</button>
<button id="btnUmdSave">save usermd</button>
</div>
</div>
</div>
<script>
'use strict';
const $ = id => document.getElementById(id);
const LS = {
get(k, d){ try { const v = localStorage.getItem('pally_bot_' + k); return v == null ? d : JSON.parse(v); } catch(e){ return d; } },
set(k, v){ try { localStorage.setItem('pally_bot_' + k, JSON.stringify(v)); } catch(e){} }
};
const FALLBACK = 'https://number-equivalent-prospect-mattress.trycloudflare.com';
const DISCOVER = 'https://huggingface.co/chatpbc1/pally-endpoint/raw/main/endpoint.json';
/* ---- canonical blocks: IDENTITY + SoulMD are the exact skeleton Pally was SFT'd on
(SYSTEM_PROMPT.md / training rows). UserMD is filled live from setup + conversation. ---- */
const IDENTITY =
'You are Pally (full name: Pally-1.7B), a state-of-the-art business consulting model developed by ChatPBC Labs.\n\n' +
'Core idea: Stop explaining your business to AI. Teach it once.\n\n' +
'Identity (never deviate from this):\n' +
'- Your name is Pally. Your full model name is Pally-1.7B.\n' +
'- You were developed by ChatPBC Labs.\n' +
'- You are a state-of-the-art business consulting model specialized in strategy, planning, decisions, marketing, operations, and finance.\n' +
'- If asked whether you are ChatGPT, GPT, Claude, Gemini, Llama or any other model: you are not. You are Pally-1.7B by ChatPBC Labs.\n' +
'- Never claim capabilities, integrations, or data access you were not given.\n';
const SOULMD =
'SoulMD (how you behave):\n' +
'- When asked who or what you are, identify as Pally (full name Pally-1.7B), a state-of-the-art business consulting model developed by ChatPBC Labs.\n' +
'- Treat the UserMD block below as the single source of truth about this person and their business. Every answer must be grounded in it: use their name, industry, numbers, and constraints. Never ask again for anything already in UserMD.\n' +
'- When a decision needs a number that is NOT in UserMD, ask ONE pointed question for it, then give your best analysis anyway with assumptions clearly labeled.\n' +
'- Give practical, personalized answers that end with a clear next action.\n' +
'- Show math step by step using the person\'s own numbers. Never invent statistics, sources, quotes, or benchmarks; if data is missing, give the method, not a fake number.\n' +
'- Be conversational: warm, direct, human. Short paragraphs. No lecture walls, no filler praise, no emoji. Never repeat the same sentence twice.\n' +
'- Memory is honest: you keep context inside this conversation only; never claim to remember across separate chats.\n' +
'- Language: reply in English even when asked in Chinese; briefly gloss any Chinese term used.\n' +
'- Never invent facts, features, or capabilities; ask for missing numbers instead of guessing them.\n' +
'- Protect private context; do not expose it beyond what the user shared.\n' +
'- You support but do not replace licensed legal, financial, medical or compliance specialists; route those decisions to qualified professionals.\n';
const PROCEDURE =
'Answer procedure (always follow, silently):\n' +
'1. DECIDE what single decision or question this turn is about.\n' +
'2. PULL every relevant number and fact from UserMD before writing. If the question needs a UserMD number that is missing, name it.\n' +
'3. COMPUTE: if numbers are involved, show the arithmetic line by line with THEIR numbers (LTV = contribution x lifetime, payback = CAC / monthly contribution, etc.). One correct calculation beats three vague claims.\n' +
'4. ANSWER in this shape: a one-sentence verdict first, then the math if any, then 2-4 concrete moves (each with a timeframe or metric), then exactly one next step for them to send you.\n' +
'5. STAY inside the model: never roleplay being a bigger model, never claim tools or live data.\n\n' +
'Worked example of the shape (do not copy content, copy the shape):\n' +
'User: "8% monthly churn, $45 AOV, $55 CAC — viable?"\n' +
'Pally: "Marginally — the unit math works, churn is the killer."\n' +
'"Contribution = $45 x 55% = $24.75/mo. Lifetime = 1 / 0.08 = 12.5 mo. LTV = $24.75 x 12.5 = $309. LTV:CAC = 5.2, payback = 2.4 mo — both healthy."\n' +
'"But 8% monthly churn rebuilds two-thirds of the base every year. Three moves: (1) instrument why customers cancel in week 1, (2) add an annual plan at -15% to lock term, (3) target churn under 5% before scaling ad spend."\n' +
'"Next action: send me your last 30 cancellation reasons (or a sample) and I will sort them into fixable vs structural."\n' +
'You were developed by ChatPBC Labs.\n';
const NO_UMD = 'No UserMD provided yet. The user has not shared their business context.';
function buildUserMD(){
const parts = [];
if (profile && (profile.name || profile.role || profile.focus)){
if (profile.name) parts.push('- Name: ' + profile.name);
if (profile.role) parts.push('- Role & company: ' + profile.role);
if (profile.focus) parts.push('- Current focus: ' + profile.focus);
}
const raw = LS.get('umd_raw', '');
if (raw.trim()) parts.push('- Profile (as provided):\n' + raw.trim());
const facts = LS.get('facts', []);
if (facts.length){
parts.push('- Facts learned in this conversation (use these numbers, never re-ask):');
for (const f of facts) parts.push(' - ' + f + ' (learned)');
}
return parts.length ? parts.join('\n') : NO_UMD;
}
// pull real numbers/facts out of what the user says so advice stays tied to them
function extractFacts(text){
const facts = LS.get('facts', []);
const seen = new Set(facts.map(f => f.toLowerCase()));
const add = f => {
const k = f.toLowerCase();
if (seen.has(k) || facts.length >= 24) return;
seen.add(k); facts.push(f);
};
const METRIC = /(CAC|LTV|AOV|MRR|ARR|GMV|EBITDA|burn(?: rate)?|runway|margin|churn|revenue|profit|cash(?: on hand)?|seats|users|customers|orders|pipeline|conversion|payback|ticket(?: size)?|units|COGS)/i;
// "$60 CAC" / "CAC is $60" / "CAC: 60" / "churn of 8%"
const win = 46;
let m;
const numRe = /(CAC|LTV|AOV|MRR|ARR|GMV|EBITDA|burn(?: rate)?|runway|margin|churn|revenue|profit|cash(?: on hand)?|seats|users|customers|orders|pipeline|conversion|payback|ticket(?: size)?|units|COGS)\s*(?:is|are|of|at|:|=)?\s*(\$?\s*\d[\d,]*(?:\.\d+)?\s*(?:k|m|bn|million|billion|thousand)?\s*(?:%|percent|\/mo|per month|mo|months?|days?|x)?)/gi;
while ((m = numRe.exec(text)) !== null){
const val = m[2].replace(/\s+/g, ' ').trim();
add(m[1] + ' = ' + val);
if (numRe.lastIndex > text.length) break;
}
// "$60 CAC" order (number before metric)
const revRe = /(\$?\s*\d[\d,]*(?:\.\d+)?\s*(?:k|m|bn)?\s*(?:%|percent|\/mo|per month)?\s*)(CAC|LTV|AOV|MRR|ARR|monthly churn|annual churn|burn|runway|margin|conversion|payback)/gi;
while ((m = revRe.exec(text)) !== null){
add(m[2] + ' = ' + m[1].replace(/\s+/g, ' ').trim());
if (revRe.lastIndex > text.length) break;
}
// bare percentages that mention a metric word nearby
const pctRe = /(\d+(?:\.\d+)?)\s*(?:%|percent)\s*(monthly\s+|annual\s+)?([a-z ]{3,18})/gi;
while ((m = pctRe.exec(text)) !== null){
const tail = m[3] || '';
if (METRIC.test(tail) || /churn|margin|growth|conversion|retention/.test(tail))
add(((m[2] ? m[2].trim() + ' ' : '') + tail.trim().split(/\s+/)[0]) + ' = ' + m[1] + '%');
if (pctRe.lastIndex > text.length) break;
}
// self-intro: "I'm Maya", "I run ACME", "my company is Foo"
let im = text.match(/\b(?:i'?m|i am|my name is)\s+([A-Z][a-z]{1,20})\b/);
if (im && !/^(I|Im|The|My|A|An|Not|Yes|No|Ok|Okay)$/.test(im[1])) add('Name (self-stated): ' + im[1]);
im = text.match(/\b(?:i run|i own|i'm (?:a |an )?|i am (?:a |an )?|my (?:company|startup|business|shop|agency) (?:is|called|named))\s+([^.,;!?]{2,48})/i);
if (im) add('Business: ' + im[1].trim());
im = text.match(/\b(?:we sell|we make|we build|we are a|we're a)\s+([^.,;!?]{2,48})/i);
if (im) add('What they sell: ' + im[1].trim());
LS.set('facts', facts);
return facts;
}
const CHIPS = [
'Review my pricing strategy',
'How many months of runway do I have?',
'Should I pivot or keep going?',
'Cut my customer churn — where do I start?',
'Sanity-check my LTV:CAC',
'Draft a 90-day turnaround plan',
'Is this acquisition worth 8x ARR?',
'Help me prep for a board meeting'
];
// ---------- state ----------
let endpoint = LS.get('ep', FALLBACK).replace(/\/+$/, '');
let profile = LS.get('profile', null);
let history = LS.get('history', []); // [{role, content}]
let busy = false;
let ctrl = null;
function systemMsg(){
return IDENTITY
+ '\nUserMD (what you know about this user):\n'
+ buildUserMD() + '\n\n'
+ SOULMD
+ '\n' + PROCEDURE;
}
// ---------- rendering ----------
function esc(s){ return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function mdLite(raw){
let text = (raw || '')
.replace(/```[\s\S]*?<\/think>/g, '')
.trim();
const blocks = [];
text = text.replace(/```(\w*)\n?([\s\S]*?)```/g, (m, lang, code) => {
blocks.push('<pre><code>' + esc(code.replace(/\n$/,'')) + '</code></pre>');
return '\u0000B' + (blocks.length - 1) + '\u0000';
});
let h = esc(text);
h = h.replace(/`([^`\n]+)`/g, '<code>$1</code>');
h = h.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
h = h.replace(/(^|\W)\*([^*\n]+)\*/g, '$1<em>$2</em>');
h = h.replace(/^### (.+)$/gm, '<h3>$1</h3>');
h = h.replace(/^## (.+)$/gm, '<h2>$1</h2>');
h = h.replace(/^# (.+)$/gm, '<h1>$1</h1>');
h = h.replace(/^&gt; (.+)$/gm, '<blockquote>$1</blockquote>');
// lists
h = h.replace(/((?:^[ \t]*[-*] .+\n?)+)/gm, m => {
const items = m.trim().split('\n').map(l => '<li>' + l.replace(/^[ \t]*[-*] /,'') + '</li>').join('');
return '<ul>' + items + '</ul>';
});
h = h.replace(/((?:^[ \t]*\d+\. .+\n?)+)/gm, m => {
const items = m.trim().split('\n').map(l => '<li>' + l.replace(/^[ \t]*\d+\. /,'') + '</li>').join('');
return '<ol>' + items + '</ol>';
});
// paragraphs
h = h.split(/\n{2,}/).map(p => {
p = p.trim();
if (!p) return '';
if (/^<(h\d|ul|ol|pre|blockquote)/.test(p)) return p;
return '<p>' + p.replace(/\n/g, '<br>') + '</p>';
}).join('');
h = h.replace(/\u0000B(\d+)\u0000/g, (m, i) => blocks[+i]);
return h;
}
function addMsg(cls, html, metaHtml){
const d = document.createElement('div');
d.className = 'msg ' + cls;
d.innerHTML = html + (metaHtml ? '<div class="meta">' + metaHtml + '</div>' : '');
$('chat').appendChild(d);
$('chat').scrollTop = $('chat').scrollHeight;
return d;
}
function loopInfo(text){
const lines = (text || '').split('\n').map(l => l.trim().toLowerCase()).filter(l => l.length > 12);
const counts = {};
let worst = '', n = 0;
for (const l of lines){ counts[l] = (counts[l] || 0) + 1; if (counts[l] > n){ n = counts[l]; worst = l; } }
return n >= 3 ? { n, sample: worst.slice(0, 80) } : null;
}
function welcome(){
if (history.length){ renderHistory(); return; }
const who = profile && profile.name ? ', ' + profile.name : '';
const hasUmd = buildUserMD() !== NO_UMD;
addMsg('bot',
'<p>Hi' + esc(who) + ' — I\'m <strong>Pally</strong>, your business consulting model by ChatPBC Labs.</p>' +
(hasUmd
? '<p>I\'m working from your <strong>UserMD</strong>. Tell me one number or one decision and I\'ll reason from your own figures.</p>'
: '<p>Open <strong>setup</strong> once to give me your UserMD (name, company, numbers) — from then on every answer is grounded in your numbers and I never ask twice.</p>') +
'<p>Example: "8% monthly churn, $45 AOV, $60 CAC — is this viable?"</p>');
}
function renderHistory(){
for (const m of history){
if (m.role === 'user') addMsg('user', esc(m.content));
else if (m.role === 'assistant') addMsg('bot', mdLite(m.content));
}
}
// ---------- endpoint ----------
async function ping(ep){
const r = await fetch(ep + '/health', { method: 'GET' });
if (!r.ok) throw new Error('health ' + r.status);
const j = await r.json();
return j;
}
async function discover(){
const manual = LS.get('ep_manual', false);
let discovered = null;
if (!manual){
try{
const r = await fetch(DISCOVER, { cache: 'no-store' });
if (r.ok){
const j = await r.json();
if (j.url && /^https?:\/\//.test(j.url)) discovered = j.url.replace(/\/+$/, '');
}
}catch(e){ /* fall through */ }
}
const tryPing = async (ep, label) => {
await ping(ep);
endpoint = ep;
setDot('ok');
$('epinfo').textContent = new URL(ep).hostname + ' · ' + label;
LS.set('ep', ep);
return true;
};
// order: fresh discovery -> cached/manual endpoint -> fallback
const candidates = [];
if (discovered && discovered !== endpoint) candidates.push([discovered, 'live']);
if (endpoint) candidates.push([endpoint, 'cached']);
if (FALLBACK && !candidates.some(c => c[0] === FALLBACK)) candidates.push([FALLBACK, 'fallback']);
for (const [ep, label] of candidates){
try{ await tryPing(ep, label); return; }catch(e){ /* next */ }
}
setDot('bad');
$('epinfo').textContent = 'endpoint down — retrying on send';
}
function setDot(cls){ const d = $('dot'); d.className = 'dot ' + cls; }
// ---------- chat ----------
const trimThink = s => (s || '').replace(/```[\s\S]*?<\/think>/g, '').replace(/^\s+/, '').replace(/\s+$/, '');
async function ask(text){
if (busy) return;
busy = true;
$('send').disabled = true;
$('typing').style.display = 'block';
let t = 0;
const tick = setInterval(() => { t += 0.1; $('tick').textContent = ' ' + t.toFixed(1) + 's'; }, 100);
history.push({ role: 'user', content: text });
addMsg('user', esc(text));
LS.set('history', history);
extractFacts(text); // learn numbers/roles into live UserMD before this turn's call
const body = JSON.stringify({
model: 'pally-1.7b',
messages: [{ role: 'system', content: systemMsg() }].concat(history),
temperature: parseFloat($('temp').value),
top_p: 0.9,
max_tokens: parseInt($('len').value, 10)
});
let reply = null, err = null, meta = '';
const t0 = performance.now();
for (let i = 0; i < 3 && !reply; i++){
ctrl = new AbortController();
try{
const r = await fetch(endpoint + '/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body,
signal: ctrl.signal
});
const j = await r.json();
if (!r.ok || !j.choices) throw new Error((j.error && j.error.message) || JSON.stringify(j).slice(0, 160));
const dt = (performance.now() - t0) / 1000;
reply = trimThink(j.choices[0].message.content);
meta = '<span class="lat">' + dt.toFixed(1) + 's</span>' +
(j.x_latency_sec != null ? ' · server ' + j.x_latency_sec + 's' : '') +
(j.usage ? ' · ' + j.usage.completion_tokens + ' tok' : '');
}catch(e){
if (e.name === 'AbortError'){ err = 'stopped'; break; }
err = e.message || String(e);
await new Promise(w => setTimeout(w, 800 * (i + 1)));
// network error = tunnel likely dead — re-discover immediately (HF endpoint.json is source of truth)
if (/failed to fetch|networkerror|load failed/i.test(err)) await discover();
else if (i === 1) await discover(); // last-chance re-discovery for other errors
}
}
clearInterval(tick);
$('typing').style.display = 'none';
ctrl = null;
if (reply != null){
history.push({ role: 'assistant', content: reply });
LS.set('history', history);
const li = loopInfo(reply);
if (li) meta += ' <span class="loopwarn">⚠ repeated line ×' + li.n + ' — try temp 0.3 or rephrase</span>';
addMsg('bot', mdLite(reply), meta);
$('statusline').textContent = '';
} else {
if (err !== 'stopped'){
addMsg('err', esc('Request failed: ' + err + ' — tap to retry').replace('Request failed:', '<b>Request failed:</b>'), '');
$('statusline').textContent = 'last message failed';
}
history.pop(); // drop the unanswered user turn so retry is clean
LS.set('history', history);
const last = $('chat').querySelector('.msg.user:last-of-type');
if (last && err !== 'stopped') last.style.cursor = 'pointer', last.onclick = () => ask(text);
}
busy = false;
$('send').disabled = false;
$('input').focus();
}
// ---------- chrome ----------
function autosize(){
const el = $('input');
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 140) + 'px';
}
function buildChips(){
$('chips').innerHTML = '';
for (const c of CHIPS){
const b = document.createElement('button');
b.className = 'chip';
b.textContent = c;
b.onclick = () => { if (!busy) ask(c); };
$('chips').appendChild(b);
}
}
function openSetup(){
$('pName').value = (profile && profile.name) || '';
$('pRole').value = (profile && profile.role) || '';
$('pFocus').value = (profile && profile.focus) || '';
$('pRaw').value = LS.get('umd_raw', '');
$('pEp').value = LS.get('ep_manual', false) ? endpoint : '';
$('setupModal').classList.remove('hidden');
}
function closeSetup(){ $('setupModal').classList.add('hidden'); }
function saveSetup(){
profile = {
name: $('pName').value.trim(),
role: $('pRole').value.trim(),
focus: $('pFocus').value.trim()
};
LS.set('profile', profile);
LS.set('umd_raw', $('pRaw').value);
const epv = $('pEp').value.trim();
if (epv){ endpoint = epv.replace(/\/+$/, ''); LS.set('ep_manual', true); LS.set('ep', endpoint); }
else { LS.set('ep_manual', false); }
closeSetup();
discover();
if (!history.length) welcome();
}
function openUmd(){
$('umdView').value = buildUserMD();
$('umdModal').classList.remove('hidden');
}
function saveUmd(){
// save edits back into profile + raw + facts (keep learned lines, honor manual edits)
const txt = $('umdView').value;
const nameM = txt.match(/^- Name: (.+)$/m);
const roleM = txt.match(/^- Role & company: (.+)$/m);
const focusM = txt.match(/^- Current focus: (.+)$/m);
profile = {
name: nameM ? nameM[1].trim() : '',
role: roleM ? roleM[1].trim() : '',
focus: focusM ? focusM[1].trim() : ''
};
LS.set('profile', profile);
const rawM = txt.match(/- Profile \(as provided\):\n([\s\S]*?)(?=\n- Facts learned|\n- No UserMD|$)/);
if (rawM) LS.set('umd_raw', rawM[1].replace(/\n$/, ''));
const factLines = [];
for (const line of txt.split('\n')){
const m = line.match(/^\s+- ([A-Za-z].+?)(?: \(learned\))?$/);
if (m && !/^(Name|Role|Current focus|Profile)\b/.test(m[1])) factLines.push(m[1]);
}
// if user typed new numbered facts, keep them
const cur = LS.get('facts', []);
const merged = factLines.slice(0, 24);
LS.set('facts', merged);
$('umdModal').classList.add('hidden');
}
function clearChat(){
if (history.length && !confirm('Start a new chat? This conversation will be cleared from this browser.')) return;
history = [];
LS.set('history', []);
$('chat').innerHTML = '';
welcome();
}
function exportChat(){
if (!history.length){ alert('Nothing to export yet.'); return; }
const lines = ['# Pally chat — ' + new Date().toLocaleString()];
if (profile && profile.name) lines.push('_for ' + profile.name + '_');
for (const m of history) lines.push((m.role === 'user' ? '**You:** ' : '**Pally:** ') + m.content);
const blob = new Blob([lines.join('\n\n')], { type: 'text/markdown' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'pally-chat-' + new Date().toISOString().slice(0, 10) + '.md';
a.click();
URL.revokeObjectURL(a.href);
}
// ---------- wire up ----------
$('input').addEventListener('input', autosize);
$('input').addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey){
e.preventDefault();
const v = $('input').value.trim();
if (v && !busy){ $('input').value = ''; autosize(); ask(v); }
}
});
$('send').onclick = () => {
const v = $('input').value.trim();
if (v && !busy){ $('input').value = ''; autosize(); ask(v); }
};
$('temp').oninput = () => { $('tempv').textContent = parseFloat($('temp').value).toFixed(2); };
$('btnSetup').onclick = openSetup;
$('btnUmd').onclick = openUmd;
$('btnUmdSave').onclick = saveUmd;
$('btnUmdForget').onclick = () => {
if (!confirm('Clear all conversation-learned facts? Setup profile stays.')) return;
LS.set('facts', []);
$('umdView').value = buildUserMD();
};
$('btnSave').onclick = saveSetup;
$('btnSkip').onclick = () => { profile = profile || null; closeSetup(); if (!history.length) welcome(); };
$('btnClear').onclick = clearChat;
$('btnExport').onclick = exportChat;
(async function boot(){
buildChips();
await discover();
if (!profile){ openSetup(); }
else { welcome(); }
$('input').focus();
})();
</script>
</body>
</html>