@anmol-srv/sigil 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,202 +15,22 @@
15
15
  <div id="toasts" class="toast-stack" aria-live="polite"></div>
16
16
 
17
17
  <!-- ════════════════════════════════════════════════════════════════════
18
- ONBOARDING WIZARD (shown until SETUP_COMPLETE)
18
+ NATIVE SETUP (config-store driven; replaces the legacy wizard above)
19
+ Stepped progress bar — no terminal logs. See src/gui/web/setup.js.
19
20
  ════════════════════════════════════════════════════════════════════ -->
20
- <div class="onboarding" id="onboarding" hidden>
21
+ <div class="onboarding" id="setup" hidden>
21
22
  <aside class="onboarding-sidebar">
22
23
  <div class="brand">
23
24
  <img class="brand-mark" src="/static/design/sigil-mark.svg" alt="Sigil" width="20" height="20">
24
25
  <div class="brand-name">Sigil</div>
25
26
  <div class="brand-badge">setup</div>
26
27
  </div>
27
-
28
- <ol class="onboarding-steps" id="ob-steps">
29
- <li class="onboarding-step active" data-ob-step="connectors">
30
- <div class="num">1</div>
31
- <div>
32
- <div class="label">Connectors</div>
33
- <div class="desc">Editors &amp; tools</div>
34
- </div>
35
- </li>
36
- <li class="onboarding-step future" data-ob-step="llm">
37
- <div class="num">2</div>
38
- <div>
39
- <div class="label">Provider</div>
40
- <div class="desc">Fact extraction + reasoning</div>
41
- </div>
42
- </li>
43
- <li class="onboarding-step future" data-ob-step="embedding">
44
- <div class="num">3</div>
45
- <div>
46
- <div class="label">Embeddings</div>
47
- <div class="desc">Semantic search</div>
48
- </div>
49
- </li>
50
- <li class="onboarding-step future" data-ob-step="database">
51
- <div class="num">4</div>
52
- <div>
53
- <div class="label">Database</div>
54
- <div class="desc">Where memory lives</div>
55
- </div>
56
- </li>
57
- <li class="onboarding-step future" data-ob-step="finish">
58
- <div class="num">5</div>
59
- <div>
60
- <div class="label">All set</div>
61
- <div class="desc">Open the dashboard</div>
62
- </div>
63
- </li>
64
- </ol>
65
-
28
+ <ol class="onboarding-steps" id="setup-rail"></ol>
66
29
  <div class="spacer"></div>
67
30
  <p class="text-xs muted">Running locally on this machine. No telemetry; no cloud account.</p>
68
31
  </aside>
69
-
70
32
  <main class="onboarding-content">
71
- <!-- ── Step 1: Connectors ──────────────────────────────────────── -->
72
- <section class="wizard-step active" data-step="connectors">
73
- <h1>Connect your tools.</h1>
74
- <p class="lede">Sigil installs memory hooks into the AI coding tools you already use — one shared brain across Claude Code, Cursor, Codex, Kiro, and any MCP client. Click to connect; you can change this any time.</p>
75
-
76
- <div class="connector-grid" id="ob-connectors"><div class="muted">detecting installed tools…</div></div>
77
-
78
- <div class="wizard-actions">
79
- <div class="spacer"></div>
80
- <button class="btn ghost" data-ob-next="llm" id="ob-connectors-skip">Skip for now</button>
81
- <button class="btn primary large" data-ob-next="llm">Continue</button>
82
- </div>
83
- </section>
84
-
85
- <!-- ── Step 4: Database (linear guided flow) ───────────────────── -->
86
- <section class="wizard-step" data-step="database">
87
- <h1>Set up your database.</h1>
88
- <p class="lede">Sigil stores every fact, document, and embedding in Postgres with pgvector. Let Sigil create a local one for you, or point it at a database you control.</p>
89
-
90
- <div class="provider-card-grid" id="db-mode-cards">
91
- <label class="provider-card" data-db-mode="docker" id="ob-db-mode-docker" hidden>
92
- <input type="radio" name="db-mode" value="docker" hidden>
93
- <span class="name">Local (automatic) <span class="badge info" style="margin-left:8px;">RECOMMENDED</span></span>
94
- <span class="hint">Sigil runs a pgvector Postgres in Docker for you. Zero config.</span>
95
- </label>
96
- <label class="provider-card" data-db-mode="url">
97
- <input type="radio" name="db-mode" value="url" hidden checked>
98
- <span class="name">Connection URL</span>
99
- <span class="hint">Neon, Supabase, RDS, Render, Railway, CockroachDB.</span>
100
- </label>
101
- <label class="provider-card" data-db-mode="fields">
102
- <input type="radio" name="db-mode" value="fields" hidden>
103
- <span class="name">Local Postgres install</span>
104
- <span class="hint">Existing host + port + user + password.</span>
105
- </label>
106
- </div>
107
-
108
- <p class="muted text-sm" id="ob-db-docker-note" style="margin-top: var(--s-2);" hidden></p>
109
-
110
- <div id="ob-db-url" style="margin-top: var(--s-5);">
111
- <label class="field">
112
- <span class="label">Postgres connection URL</span>
113
- <input type="text" id="ob-db-url-input" placeholder="postgres://user:pass@host.neon.tech/db?sslmode=require" autocomplete="off">
114
- <span class="help">Paste from Neon dashboard / Supabase settings / RDS endpoint.</span>
115
- </label>
116
- </div>
117
-
118
- <div id="ob-db-fields" style="display:none; margin-top: var(--s-5);">
119
- <div class="row-2col">
120
- <label class="field"><span class="label">Host</span><input type="text" id="ob-db-host" value="localhost" autocomplete="off"></label>
121
- <label class="field"><span class="label">Port</span><input type="number" id="ob-db-port" value="5432"></label>
122
- </div>
123
- <div class="row-2col">
124
- <label class="field"><span class="label">Database</span><input type="text" id="ob-db-db" value="sigil" autocomplete="off"></label>
125
- <label class="field"><span class="label">User</span><input type="text" id="ob-db-user" value="sigil_app" autocomplete="off"></label>
126
- </div>
127
- <label class="field"><span class="label">Password</span><input type="password" id="ob-db-pass" autocomplete="off"></label>
128
- </div>
129
-
130
- <div class="flex-row" style="margin-top: var(--s-4);">
131
- <button class="btn primary" id="ob-db-setup">Set up database</button>
132
- </div>
133
-
134
- <!-- Linear flow rows (filled by JS) — replaces the old toggling buttons -->
135
- <div class="db-flow" id="ob-db-flow" hidden></div>
136
-
137
- <div class="wizard-actions">
138
- <button class="btn ghost" data-ob-back="embedding">Back</button>
139
- <div class="spacer"></div>
140
- <button class="btn primary" data-ob-next="finish" id="ob-db-next" disabled>Continue</button>
141
- </div>
142
- </section>
143
-
144
- <!-- ── Step 3: LLM provider ────────────────────────────────────── -->
145
- <section class="wizard-step" data-step="llm">
146
- <h1>Pick an LLM provider.</h1>
147
- <p class="lede">Sigil uses an LLM to extract facts from your conversations, decide whether new memory contradicts old, and synthesize search results.</p>
148
-
149
- <div class="provider-card-grid" id="ob-llm-cards"><div class="muted">loading providers…</div></div>
150
-
151
- <div id="ob-llm-fields" style="margin-top: var(--s-5);"></div>
152
-
153
- <div class="flex-row" style="margin-top: var(--s-3);">
154
- <button class="btn primary" id="ob-llm-save">Save and test</button>
155
- </div>
156
- <pre id="ob-llm-result" class="result" hidden></pre>
157
-
158
- <div class="wizard-actions">
159
- <button class="btn ghost" data-ob-back="connectors">Back</button>
160
- <div class="spacer"></div>
161
- <button class="btn primary" data-ob-next="embedding" id="ob-llm-next" disabled>Continue</button>
162
- </div>
163
- </section>
164
-
165
- <!-- ── Step 4: Embeddings ──────────────────────────────────────── -->
166
- <section class="wizard-step" data-step="embedding">
167
- <h1>Pick an embedding provider.</h1>
168
- <p class="lede">Vector embeddings power semantic search across your memory. The model choice fixes the vector shape — changing it later requires re-embedding every fact.</p>
169
-
170
- <div class="provider-card-grid" id="ob-emb-cards"><div class="muted">loading providers…</div></div>
171
- <div id="ob-emb-fields" style="margin-top: var(--s-5);"></div>
172
-
173
- <div class="flex-row" style="margin-top: var(--s-3);">
174
- <button class="btn primary" id="ob-emb-save">Save and test</button>
175
- </div>
176
- <pre id="ob-emb-result" class="result" hidden></pre>
177
-
178
- <div class="wizard-actions">
179
- <button class="btn ghost" data-ob-back="llm">Back</button>
180
- <div class="spacer"></div>
181
- <button class="btn primary" data-ob-next="database" id="ob-emb-next" disabled>Continue</button>
182
- </div>
183
- </section>
184
-
185
- <!-- ── Step 5: Finish ──────────────────────────────────────────── -->
186
- <section class="wizard-step" data-step="finish">
187
- <h1>You're set up.</h1>
188
- <p class="lede">Sigil's daemon is running on this machine. Open the dashboard to add memories, browse the knowledge base, and (later) connect more devices.</p>
189
-
190
- <div class="kv" style="margin-bottom: var(--s-5);">
191
- <div class="row"><div class="k">Daemon</div><div class="v" id="ob-finish-daemon">—</div></div>
192
- <div class="row"><div class="k">Database</div><div class="v" id="ob-finish-db">—</div></div>
193
- <div class="row"><div class="k">LLM</div><div class="v" id="ob-finish-llm">—</div></div>
194
- <div class="row"><div class="k">Embeddings</div><div class="v" id="ob-finish-emb">—</div></div>
195
- </div>
196
-
197
- <h2>Next steps</h2>
198
- <ul class="kv">
199
- <div class="row"><div class="k">CLI</div><div class="v" style="font-family: var(--font-ui);"><code>sigil remember "..."</code>, <code>sigil search "..."</code>, <code>sigil status</code></div></div>
200
- <div class="row"><div class="k">Claude Code</div><div class="v" style="font-family: var(--font-ui);">Run <code>sigil register</code> on the command line to add Sigil as an MCP server.</div></div>
201
- <div class="row"><div class="k">Other devices</div><div class="v" style="font-family: var(--font-ui);">From the Devices tab in the dashboard, create a pairing code and run <code>sigil join …</code> on the joining device.</div></div>
202
- </ul>
203
-
204
- <label class="field" style="flex-direction:row; align-items:center; gap: var(--s-2); margin-top: var(--s-5);">
205
- <input type="checkbox" id="ob-always-up" checked>
206
- <span class="label" style="text-transform:none; letter-spacing:0;">Keep Sigil always running — start on login, auto-restart on crash or reboot (recommended)</span>
207
- </label>
208
-
209
- <div class="wizard-actions">
210
- <div class="spacer"></div>
211
- <button class="btn primary large" id="ob-complete">Open the dashboard →</button>
212
- </div>
213
- </section>
33
+ <section class="wizard-step active" id="setup-main"></section>
214
34
  </main>
215
35
  </div>
216
36
 
@@ -0,0 +1,401 @@
1
+ /**
2
+ * Native first-run setup — GUI controller.
3
+ *
4
+ * Drives the daemon's setup service (setup.state / setup.detect / setup.run)
5
+ * and renders a stepped progress bar fed by live { type:'setup' } events on the
6
+ * /api/v1/events WebSocket. No terminal logs: every step shows a progress bar +
7
+ * a single error slot.
8
+ *
9
+ * Steps: Database (mode cards) → LLM provider (provider cards) → Embeddings
10
+ * (provider cards) → Your name (form). The flow advances itself as each step
11
+ * completes; the last step flips setup.complete and drops into the dashboard.
12
+ */
13
+ import { rpc } from './api.js';
14
+ import { toast } from './toast.js';
15
+
16
+ const $ = (s, r = document) => r.querySelector(s);
17
+ const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
18
+
19
+ const STEP_DESC = {
20
+ database: 'Where memory lives',
21
+ llm: 'Fact extraction + reasoning',
22
+ embedding: 'Semantic search',
23
+ identity: 'Personalize + smoke-test',
24
+ };
25
+
26
+ let state = null;
27
+ let busy = false;
28
+ let ws = null;
29
+ let viewStep = null; // the step currently shown (may be earlier than currentStep via Back)
30
+
31
+ // per-step selection scratch
32
+ let dbDetect = null;
33
+ let selectedMode = null;
34
+ let selectedExtra = {};
35
+ let providers = []; // current step's provider list
36
+ let selectedProvider = null;
37
+
38
+ export async function initSetup() {
39
+ try {
40
+ state = await rpc('setup.state', {}, { quiet: true });
41
+ } catch {
42
+ hide();
43
+ return false;
44
+ }
45
+ if (state.complete) { hide(); return false; }
46
+ show();
47
+ connectWs();
48
+ renderRail();
49
+ await enterStep(state.currentStep || 'database');
50
+ return true;
51
+ }
52
+
53
+ function show() { const el = $('#setup'); if (el) el.hidden = false; document.body.classList.add('in-setup'); }
54
+ function hide() { const el = $('#setup'); if (el) el.hidden = true; document.body.classList.remove('in-setup'); }
55
+
56
+ function connectWs() {
57
+ if (ws && (ws.readyState === ws.OPEN || ws.readyState === ws.CONNECTING)) return;
58
+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
59
+ ws = new WebSocket(`${proto}//${location.host}/api/v1/events`);
60
+ ws.addEventListener('message', (e) => {
61
+ try { const evt = JSON.parse(e.data); if (evt.type === 'setup') onSetupEvent(evt); } catch { /* */ }
62
+ });
63
+ ws.addEventListener('close', () => { if (!$('#setup')?.hidden) setTimeout(connectWs, 1500); });
64
+ }
65
+
66
+ // ── left rail ────────────────────────────────────────────────────────────────
67
+ function railClass(s) {
68
+ if (s.id === viewStep) return 'active';
69
+ if (s.status === 'done') return 'done';
70
+ return 'future';
71
+ }
72
+ function renderRail() {
73
+ const host = $('#setup-rail'); if (!host) return;
74
+ host.innerHTML = state.steps.map((s, i) => `
75
+ <li class="onboarding-step ${railClass(s)}" data-setup-step="${esc(s.id)}">
76
+ <div class="num">${s.status === 'done' ? '✓' : i + 1}</div>
77
+ <div>
78
+ <div class="label">${esc(s.title)}</div>
79
+ <div class="desc">${esc(STEP_DESC[s.id] || '')}${s.implemented ? '' : ' · soon'}</div>
80
+ </div>
81
+ </li>`).join('');
82
+ }
83
+
84
+ // ── shared scaffolding every step renders into #setup-main ───────────────────
85
+ function shell({ title, lede, body }) {
86
+ const order = (state?.steps || []).map((s) => s.id);
87
+ const idx = order.indexOf(viewStep);
88
+ const canBack = idx > 0;
89
+ $('#setup-main').innerHTML = `
90
+ <h1>${esc(title)}</h1>
91
+ <p class="lede">${lede}</p>
92
+ ${body}
93
+ <div id="setup-confirm"></div>
94
+ <div class="wizard-actions">
95
+ <button class="btn ghost" id="setup-back"${canBack ? '' : ' hidden'}>← Back</button>
96
+ <div class="spacer"></div>
97
+ <button class="btn primary large" id="setup-run" disabled>${esc(title.startsWith('What') ? 'Finish setup' : 'Continue')}</button>
98
+ </div>
99
+ <div id="setup-progress" class="setup-progress" hidden>
100
+ <div class="setup-progress-bar"><span id="setup-progress-fill"></span></div>
101
+ <div id="setup-progress-label" class="setup-progress-label"></div>
102
+ </div>
103
+ <div id="setup-error" class="result err" hidden></div>`;
104
+ if (canBack) $('#setup-back').addEventListener('click', () => { if (!busy) enterStep(order[idx - 1]); });
105
+ }
106
+
107
+ function fieldInputs(fields, sharedNote) {
108
+ const note = sharedNote ? `<p class="muted text-sm">${esc(sharedNote)}</p>` : '';
109
+ if (!fields.length) return note || '<p class="muted text-sm">No additional configuration needed.</p>';
110
+ return note + fields.map((f) => `
111
+ <label class="field">
112
+ <span class="label">${esc(f.label)}${f.optional ? ' <span class="muted text-xs">(optional)</span>' : ''}</span>
113
+ <input type="${esc(f.type)}" data-setup-field="${esc(f.name)}"${f.optional ? ' data-optional="1"' : ''} placeholder="${esc(f.placeholder || '')}" autocomplete="off">
114
+ </label>`).join('');
115
+ }
116
+
117
+ // Enable Continue only when every non-optional field has a value (so e.g. an
118
+ // OpenRouter model isn't optional). No fields → enabled (claude-cli).
119
+ function wireRequiredGate() {
120
+ const inputs = [...$$all('#setup-fields [data-setup-field]')];
121
+ const sync = () => {
122
+ const ok = inputs.every((i) => i.dataset.optional === '1' || i.value.trim());
123
+ const btn = $('#setup-run'); if (btn) btn.disabled = !ok;
124
+ };
125
+ inputs.forEach((i) => i.addEventListener('input', sync));
126
+ sync();
127
+ }
128
+
129
+ function collectFields() {
130
+ const out = {};
131
+ $$all('#setup-fields [data-setup-field]').forEach((i) => { if (i.value) out[i.dataset.setupField] = i.value; });
132
+ return out;
133
+ }
134
+ const $$all = (s, r = document) => r.querySelectorAll(s);
135
+
136
+ // ── dispatch ─────────────────────────────────────────────────────────────────
137
+ async function enterStep(stepId) {
138
+ viewStep = stepId;
139
+ renderRail();
140
+ if (stepId === 'database') return renderDatabaseStep();
141
+ if (stepId === 'llm') return renderProviderStep('llm');
142
+ if (stepId === 'embedding') return renderProviderStep('embedding');
143
+ if (stepId === 'identity') return renderIdentityStep();
144
+ renderComingSoon();
145
+ }
146
+
147
+ function renderComingSoon() {
148
+ $('#setup-main').innerHTML = `<h1>Setup complete.</h1><p class="lede">Opening the dashboard…</p>`;
149
+ }
150
+
151
+ // ── Database step (mode cards) ───────────────────────────────────────────────
152
+ async function renderDatabaseStep() {
153
+ shell({
154
+ title: 'Set up your database.',
155
+ lede: 'Sigil stores every fact and embedding in Postgres + pgvector. Connect one you run, let Sigil spin one up in Docker, or point it at a managed database.',
156
+ body: `<div id="setup-detect" class="setup-detect muted">Checking this machine…</div>
157
+ <div class="provider-card-grid" id="setup-db-modes"></div>
158
+ <div id="setup-fields" hidden></div>`,
159
+ });
160
+ $('#setup-run').addEventListener('click', runDatabase);
161
+ dbDetect = await rpc('setup.detect', { step: 'database' }, { quiet: true }).catch(() => null);
162
+ renderDbModes();
163
+ }
164
+
165
+ function renderDbModes() {
166
+ const det = dbDetect || { local: {}, docker: {} };
167
+ const s = $('#setup-detect');
168
+ if (det.local?.running) s.innerHTML = `Found Postgres on <b>localhost:${det.local.port}</b> — pgvector ${det.local.pgvectorAvailable ? '<b>available ✓</b>' : '<b>not available</b>'}.`;
169
+ else if (det.local?.installed) s.textContent = 'Postgres is installed but not running.';
170
+ else s.textContent = 'No local Postgres detected.';
171
+
172
+ const cards = [];
173
+ if (det.local?.running) cards.push(card('mode', 'local', 'Connect to local Postgres', `localhost:${det.local.port} · reuse your running server`, { action: 'connect' }));
174
+ else if (det.local?.installed) cards.push(card('mode', 'local', 'Start &amp; connect local Postgres', 'Start your installed Postgres, then set up', { action: 'start' }));
175
+ if (det.docker?.installed) {
176
+ const hint = det.docker.running
177
+ ? 'Docker — dedicated pgvector Postgres, zero setup'
178
+ : "Docker is installed but not running — we'll start it for you";
179
+ cards.push(card('mode', 'docker', 'Spin up a Sigil container', hint));
180
+ } else {
181
+ cards.push(cardDisabled('Spin up a Sigil container', det.docker?.reason || 'Docker not installed'));
182
+ }
183
+ cards.push(card('mode', 'url', 'External database', 'Managed (Neon / Supabase / RDS) or a connection string'));
184
+
185
+ $('#setup-db-modes').innerHTML = cards.join('');
186
+ $$all('#setup-db-modes [data-mode]').forEach((c) => c.addEventListener('click', () => {
187
+ selectedMode = c.dataset.mode;
188
+ selectedExtra = JSON.parse(c.dataset.extra || '{}');
189
+ $$all('#setup-db-modes [data-mode]').forEach((x) => x.classList.toggle('selected', x === c));
190
+ const fields = selectedMode === 'url' ? [{ name: 'url', label: 'Connection string', type: 'text', placeholder: 'postgres://user:pass@host:5432/dbname' }] : [];
191
+ const host = $('#setup-fields');
192
+ host.hidden = fields.length === 0;
193
+ host.innerHTML = fieldInputs(fields);
194
+ wireRequiredGate();
195
+ }));
196
+ }
197
+
198
+ async function runDatabase() {
199
+ if (busy || !selectedMode) return;
200
+ const input = { mode: selectedMode, ...selectedExtra, ...collectFields() };
201
+ if (selectedMode === 'url') {
202
+ if (!input.url) { showError('Enter a connection string.', null); return; }
203
+ if (!(await confirmExternal(input.url))) return;
204
+ } else if (selectedMode === 'local' && dbDetect?.local) {
205
+ input.host = 'localhost';
206
+ input.port = dbDetect.local.port;
207
+ input.adminUser = dbDetect.local.adminUser;
208
+ }
209
+ runStep('database', input);
210
+ }
211
+
212
+ function confirmExternal(url) {
213
+ return new Promise((resolve) => {
214
+ const host = (() => { try { return new URL(url).host; } catch { return 'that server'; } })();
215
+ const el = $('#setup-confirm');
216
+ el.innerHTML = `<div class="result conflict-card">
217
+ <strong>Create database &amp; run migrations on ${esc(host)}?</strong>
218
+ <div class="muted" style="margin:6px 0;">Sigil will create the database if missing, enable pgvector, and apply its schema.</div>
219
+ <div class="flex-row" style="margin-top:8px;">
220
+ <button type="button" class="btn primary" data-yes>Continue</button>
221
+ <button type="button" class="btn" data-no>Cancel</button>
222
+ </div></div>`;
223
+ el.querySelector('[data-yes]').addEventListener('click', () => { el.innerHTML = ''; resolve(true); });
224
+ el.querySelector('[data-no]').addEventListener('click', () => { el.innerHTML = ''; resolve(false); });
225
+ });
226
+ }
227
+
228
+ // ── LLM + Embedding steps (provider cards) ───────────────────────────────────
229
+ const PROVIDER_COPY = {
230
+ llm: { title: 'Choose your LLM provider.', lede: 'Sigil uses an LLM to classify input, extract facts, and answer searches. Pick one — Claude Code reuses your existing subscription.' },
231
+ embedding: { title: 'Choose your embedder.', lede: 'Embeddings power semantic search. Every option is pinned to 1024 dimensions, so it always matches your database.' },
232
+ };
233
+
234
+ async function renderProviderStep(stepId) {
235
+ const copy = PROVIDER_COPY[stepId];
236
+ shell({ title: copy.title, lede: copy.lede, body: `<div class="provider-card-grid" id="setup-providers"></div><div id="setup-fields"></div>` });
237
+ $('#setup-run').addEventListener('click', () => runProviderStep(stepId));
238
+ const det = await rpc('setup.detect', { step: stepId }, { quiet: true }).catch(() => ({ providers: [] }));
239
+ providers = det.providers || [];
240
+ $('#setup-providers').innerHTML = providers.map((p) => card('prov', p.id, `${esc(p.label)}${p.recommended ? ' <span class="badge info" style="margin-left:8px;">RECOMMENDED</span>' : ''}`, p.hint)).join('');
241
+ $$all('#setup-providers [data-prov]').forEach((c) => c.addEventListener('click', () => selectProvider(stepId, c.dataset.prov)));
242
+ const rec = providers.find((p) => p.recommended) || providers[0];
243
+ if (rec) selectProvider(stepId, rec.id);
244
+ }
245
+
246
+ function providerFields(stepId, p) {
247
+ if (stepId === 'llm') return { fields: p.fields || [], note: '' };
248
+ // embedding: synthesize fields from flags
249
+ const fields = [];
250
+ let note = '';
251
+ if (p.keyed && !p.sharedKeyAvailable) fields.push({ name: 'apiKey', label: `${p.label} API key`, type: 'password', placeholder: 'paste key' });
252
+ else if (p.keyed && p.sharedKeyAvailable) note = 'Reuses the API key from your LLM step.';
253
+ if (p.id === 'ollama') fields.push({ name: 'host', label: 'Ollama host', type: 'text', placeholder: 'http://localhost:11434' });
254
+ return { fields, note };
255
+ }
256
+
257
+ function selectProvider(stepId, id) {
258
+ selectedProvider = id;
259
+ $$all('#setup-providers [data-prov]').forEach((c) => c.classList.toggle('selected', c.dataset.prov === id));
260
+ const p = providers.find((x) => x.id === id);
261
+ const { fields, note } = providerFields(stepId, p);
262
+ $('#setup-fields').innerHTML = fieldInputs(fields, note);
263
+ wireRequiredGate();
264
+ // OpenRouter exposes a public model list — turn the free-text model field
265
+ // into an autocomplete picker (datalist) while still allowing a typed value.
266
+ if (stepId === 'llm' && id === 'openrouter') attachModelPicker();
267
+ }
268
+
269
+ let orModels = [];
270
+ async function attachModelPicker() {
271
+ const input = $('#setup-fields [data-setup-field="model"]');
272
+ if (!input) return;
273
+ // Fetch OpenRouter's PUBLIC model list directly from the browser (no key, no
274
+ // daemon round-trip — the endpoint sends Access-Control-Allow-Origin: *).
275
+ input.placeholder = 'loading models…';
276
+ try {
277
+ const res = await fetch('https://openrouter.ai/api/v1/models', { signal: AbortSignal.timeout(10000) });
278
+ if (!res.ok) throw new Error(`http ${res.status}`);
279
+ const data = await res.json();
280
+ orModels = (data.data || [])
281
+ .map((m) => ({ id: m.id, name: m.name || m.id }))
282
+ .filter((m) => m.id)
283
+ .sort((a, b) => a.id.localeCompare(b.id));
284
+ if (selectedProvider !== 'openrouter' || !document.body.contains(input)) return;
285
+ if (!orModels.length) { input.placeholder = 'e.g. google/gemini-flash-latest'; return; }
286
+ input.placeholder = `search ${orModels.length} models…`;
287
+ buildModelCombo(input);
288
+ } catch {
289
+ if (selectedProvider === 'openrouter') input.placeholder = 'e.g. google/gemini-flash-latest (list unavailable — type a model id)';
290
+ }
291
+ }
292
+
293
+ // A real searchable dropdown (the native <datalist> doesn't filter reliably
294
+ // and rendered badly with hundreds of options). Absolutely-positioned, scrolls,
295
+ // filters as you type, click to choose.
296
+ function buildModelCombo(input) {
297
+ const field = input.closest('.field') || input.parentElement;
298
+ field.classList.add('combo');
299
+ const list = document.createElement('ul');
300
+ list.className = 'combo-list';
301
+ list.hidden = true;
302
+ input.after(list);
303
+
304
+ let selecting = false;
305
+ const render = () => {
306
+ const q = input.value.trim().toLowerCase();
307
+ const matches = (q ? orModels.filter((m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q)) : orModels).slice(0, 100);
308
+ list.innerHTML = matches.length
309
+ ? matches.map((m) => `<li data-val="${esc(m.id)}"><span class="combo-id">${esc(m.id)}</span><span class="combo-name">${esc(m.name)}</span></li>`).join('')
310
+ : '<li class="combo-empty">no match — type a custom model id</li>';
311
+ };
312
+ const open = () => { render(); list.hidden = false; };
313
+ const close = () => { list.hidden = true; };
314
+
315
+ input.addEventListener('focus', open);
316
+ input.addEventListener('input', () => { if (!selecting) open(); });
317
+ // mousedown (not click) so it fires before the input's blur.
318
+ list.addEventListener('mousedown', (e) => {
319
+ const li = e.target.closest('li[data-val]');
320
+ if (!li) return;
321
+ e.preventDefault();
322
+ selecting = true;
323
+ input.value = li.dataset.val;
324
+ input.dispatchEvent(new Event('input', { bubbles: true })); // re-evaluates the required gate
325
+ selecting = false;
326
+ close();
327
+ });
328
+ document.addEventListener('click', (e) => { if (!field.contains(e.target)) close(); });
329
+ }
330
+
331
+ function runProviderStep(stepId) {
332
+ if (busy || !selectedProvider) return;
333
+ runStep(stepId, { provider: selectedProvider, ...collectFields() });
334
+ }
335
+
336
+ // ── Identity step (form) ─────────────────────────────────────────────────────
337
+ function renderIdentityStep() {
338
+ shell({
339
+ title: 'What should we call you?',
340
+ lede: "We'll save this as your first memory — which doubles as a live test of your whole setup.",
341
+ body: `<div id="setup-fields">${fieldInputs([{ name: 'name', label: 'Your name', type: 'text', placeholder: 'e.g. Anmol' }])}</div>`,
342
+ });
343
+ const input = $('#setup-fields [data-setup-field="name"]');
344
+ const btn = $('#setup-run');
345
+ const sync = () => { btn.disabled = !input.value.trim(); };
346
+ input.addEventListener('input', sync); sync();
347
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && input.value.trim()) runStep('identity', { name: input.value.trim() }); });
348
+ btn.addEventListener('click', () => runStep('identity', { name: input.value.trim() }));
349
+ }
350
+
351
+ // ── shared run + progress ────────────────────────────────────────────────────
352
+ async function runStep(stepId, input) {
353
+ if (busy) return;
354
+ startBusy();
355
+ try {
356
+ const res = await rpc('setup.run', { step: stepId, input }, { quiet: true });
357
+ if (res.ok) { setProgress(100, 'Done.'); await onStepDone(); }
358
+ else showError(res.error || (res.errors && Object.values(res.errors)[0]) || 'Setup failed.', res.hint);
359
+ } catch (err) {
360
+ showError(err.message, err.hint);
361
+ } finally {
362
+ endBusy();
363
+ }
364
+ }
365
+
366
+ function startBusy() { busy = true; $('#setup-run').disabled = true; $('#setup-error').hidden = true; $('#setup-progress').hidden = false; setProgress(0, 'Starting…'); }
367
+ function endBusy() { busy = false; const b = $('#setup-run'); if (b) b.disabled = false; }
368
+ function setProgress(pct, label) {
369
+ const f = $('#setup-progress-fill'); if (f) f.style.width = `${Math.max(0, Math.min(100, pct))}%`;
370
+ const l = $('#setup-progress-label'); if (l) l.textContent = label || '';
371
+ }
372
+ function showError(message, hint) {
373
+ const el = $('#setup-error'); if (!el) return;
374
+ el.hidden = false;
375
+ el.innerHTML = `✗ ${esc(message)}${hint ? `<div class="muted" style="margin-top:4px;">→ ${esc(hint)}</div>` : ''}`;
376
+ $('#setup-progress').hidden = true;
377
+ }
378
+
379
+ async function onStepDone() {
380
+ state = await rpc('setup.state', {}, { quiet: true }).catch(() => state);
381
+ renderRail();
382
+ if (state.complete) { toast({ variant: 'success', message: 'Setup complete.' }); setTimeout(() => window.location.reload(), 700); return; }
383
+ await enterStep(state.currentStep || null);
384
+ }
385
+
386
+ function onSetupEvent(evt) {
387
+ if (evt.status === 'active') setProgress(evt.pct ?? 0, evt.label || '');
388
+ else if (evt.status === 'error') showError(evt.label || 'Setup failed.', evt.hint);
389
+ }
390
+
391
+ // ── card helpers ──────────────────────────────────────────────────────────────
392
+ function card(kind, id, name, hint, extra = {}) {
393
+ return `<label class="provider-card" data-${kind}="${esc(id)}" data-extra='${esc(JSON.stringify(extra))}'>
394
+ <span class="check"></span><span class="name">${name}</span><span class="hint">${esc(hint)}</span>
395
+ </label>`;
396
+ }
397
+ function cardDisabled(name, why) {
398
+ return `<label class="provider-card disabled" title="${esc(why)}">
399
+ <span class="check"></span><span class="name">${esc(name)}</span><span class="hint">${esc(why)}</span>
400
+ </label>`;
401
+ }