@opencorelabs/lucidity 0.2.0 → 0.3.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.
Files changed (70) hide show
  1. package/README.md +29 -34
  2. package/bin/lucidity.js +2 -0
  3. package/dist/config.d.ts +2 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +1 -0
  6. package/dist/index.js +25 -8
  7. package/dist/mcp/clients.d.ts +21 -0
  8. package/dist/mcp/clients.d.ts.map +1 -0
  9. package/dist/mcp/clients.js +193 -0
  10. package/dist/mcp/config.d.ts +2 -1
  11. package/dist/mcp/config.d.ts.map +1 -1
  12. package/dist/mcp/paired.d.ts +2 -0
  13. package/dist/mcp/paired.d.ts.map +1 -0
  14. package/dist/mcp/paired.js +20 -0
  15. package/dist/mcp/pairedConfig.d.ts +3 -0
  16. package/dist/mcp/pairedConfig.d.ts.map +1 -0
  17. package/dist/mcp/pairedConfig.js +33 -0
  18. package/dist/setup/page.d.ts +3 -0
  19. package/dist/setup/page.d.ts.map +1 -0
  20. package/dist/setup/page.js +120 -0
  21. package/dist/setup/server.d.ts +26 -0
  22. package/dist/setup/server.d.ts.map +1 -0
  23. package/dist/setup/server.js +398 -0
  24. package/package.json +1 -1
  25. package/src/config.ts +3 -0
  26. package/src/index.ts +41 -24
  27. package/src/mcp/clients.ts +269 -0
  28. package/src/mcp/config.ts +2 -1
  29. package/src/mcp/paired.ts +22 -0
  30. package/src/mcp/pairedConfig.ts +44 -0
  31. package/src/setup/page.ts +122 -0
  32. package/src/setup/server.ts +483 -0
  33. package/vendor/mcp-server/README.md +125 -48
  34. package/vendor/mcp-server/dist/index.js +11 -5
  35. package/vendor/mcp-server/dist/tools/comments.d.ts.map +1 -1
  36. package/vendor/mcp-server/dist/tools/comments.js +16 -1
  37. package/vendor/mcp-server/dist/tools/memory.d.ts +2 -2
  38. package/vendor/mcp-server/dist/tools/memory.d.ts.map +1 -1
  39. package/vendor/mcp-server/dist/tools/memory.js +24 -14
  40. package/vendor/mcp-server/dist/tools/milestones.d.ts.map +1 -1
  41. package/vendor/mcp-server/dist/tools/milestones.js +30 -0
  42. package/vendor/mcp-server/dist/tools/notes.d.ts.map +1 -1
  43. package/vendor/mcp-server/dist/tools/notes.js +30 -5
  44. package/vendor/mcp-server/dist/tools/projects.d.ts.map +1 -1
  45. package/vendor/mcp-server/dist/tools/projects.js +15 -0
  46. package/vendor/mcp-server/dist/tools/queries.d.ts.map +1 -1
  47. package/vendor/mcp-server/dist/tools/queries.js +27 -2
  48. package/vendor/mcp-server/dist/tools/tasks.d.ts.map +1 -1
  49. package/vendor/mcp-server/dist/tools/tasks.js +37 -0
  50. package/vendor/mcp-server/package.json +1 -1
  51. package/vendor/mcp-server/src/index.ts +19 -6
  52. package/vendor/mcp-server/src/tools/comments.ts +19 -1
  53. package/vendor/mcp-server/src/tools/memory.ts +26 -12
  54. package/vendor/mcp-server/src/tools/milestones.ts +36 -0
  55. package/vendor/mcp-server/src/tools/notes.ts +35 -4
  56. package/vendor/mcp-server/src/tools/projects.ts +18 -0
  57. package/vendor/mcp-server/src/tools/queries.ts +30 -0
  58. package/vendor/mcp-server/src/tools/tasks.ts +44 -0
  59. package/vendor/shared/dist/brandArtwork.d.ts +4 -0
  60. package/vendor/shared/dist/brandArtwork.d.ts.map +1 -0
  61. package/vendor/shared/dist/brandArtwork.js +7 -0
  62. package/vendor/shared/dist/index.d.ts +1 -0
  63. package/vendor/shared/dist/index.d.ts.map +1 -1
  64. package/vendor/shared/dist/index.js +1 -0
  65. package/vendor/shared/dist/setupAppearance.d.ts +6 -0
  66. package/vendor/shared/dist/setupAppearance.d.ts.map +1 -0
  67. package/vendor/shared/dist/setupAppearance.js +17 -0
  68. package/vendor/shared/src/brandArtwork.ts +7 -0
  69. package/vendor/shared/src/index.ts +1 -0
  70. package/vendor/shared/src/setupAppearance.ts +32 -0
@@ -0,0 +1,120 @@
1
+ import { setupPage, setupIllustration } from '@lucidity/shared';
2
+ export const setupScript = `
3
+ let token = new URLSearchParams(location.hash.slice(1)).get('session');
4
+ if (token) { sessionStorage.setItem('luciditySetupSession', token); history.replaceState(null, '', '/'); }
5
+ token = token || sessionStorage.getItem('luciditySetupSession');
6
+ const content = document.getElementById('stage');
7
+ const error = document.getElementById('error');
8
+ let state = {}, selected = sessionStorage.getItem('luciditySetupProvider'), timer, busy = false, revision = 0;
9
+ let choices = {tasks:false, scheduledWork:false, clients:[]};
10
+ try { choices = {...choices, ...JSON.parse(sessionStorage.getItem('luciditySetupChoices') || '{}')}; } catch {}
11
+ const escape = s => String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
12
+ function showError(e) { error.textContent = e.message || 'Something went wrong. Please try again.'; error.hidden = false; }
13
+ async function request(path, body) {
14
+ const response = await fetch('/api/' + path, {method:'POST',headers:{'Content-Type':'application/json','X-Setup-Token':token || ''},body:JSON.stringify(body || {})});
15
+ const value = await response.json();
16
+ if(!response.ok) throw new Error(value.error || 'Please try again.');
17
+ return value;
18
+ }
19
+ function render(step, html) {
20
+ revision++; clearTimeout(timer); error.hidden = true;
21
+ document.querySelectorAll('.steps li').forEach((li,i) => { li.className = i === step ? 'active' : i < step ? 'done' : ''; li.toggleAttribute('aria-current', i === step); li.querySelector('b').textContent = i < step ? '✓' : String(i+1); });
22
+ content.innerHTML = '<div class="section">' + html + '</div>';
23
+ const title = content.querySelector('h1'); if(title) { title.tabIndex = -1; title.focus({preventScroll:true}); }
24
+ }
25
+ function button(id, fn) { document.getElementById(id).onclick = async () => { if(busy) return; busy = true; const b = document.getElementById(id); b.disabled = true; error.hidden = true; try { await fn(); } catch(e) { showError(e); } finally { busy = false; if(b.isConnected) b.disabled = false; } }; }
26
+ function welcome() {
27
+ render(0, '<p class="eyebrow">A good place to begin</p><h1>Your ideas.<br>A little more reach.</h1><p class="lead">Connect this computer to bring AI conversations and a helping hand to Lucidity on your phone.</p>' + document.getElementById('art').innerHTML + '<div class="actions"><button class="primary" id="begin">Let’s get connected <span aria-hidden="true">→</span></button></div><p class="fine" style="margin-top:18px">Your tasks already work on their own. This adds the AI.</p>');
28
+ button('begin', async () => { state = await request('begin'); connect(); });
29
+ }
30
+ function connect() {
31
+ render(1, '<p class="eyebrow">Connect your account</p><h1>Same you.<br>New possibilities.</h1><p class="lead">Open Lucidity in a new tab, sign in, and confirm this computer. We’ll take care of the connection.</p><div class="card"><strong>' + escape(state.name) + '</strong><p class="code">' + escape(state.code.match(/.{1,4}/g).join(' ')) + '</p></div><div class="actions"><a class="primary" href="' + escape(state.approvalUrl) + '" target="_blank" rel="noopener noreferrer">Connect my account <span aria-hidden="true">↗</span></a></div><p class="status" style="margin-top:22px" role="status"><span class="dot"></span>Waiting for your approval</p><p class="fine">Keep this window open. The request expires in 10 minutes.</p><button class="secondary" id="new">Start a new request</button>');
32
+ button('new', async () => { revision++; clearTimeout(timer); state = await request('begin', {restart:true}); connect(); });
33
+ poll();
34
+ }
35
+ async function poll() {
36
+ const expected = revision;
37
+ try {
38
+ const value = await request('poll');
39
+ if(expected !== revision) return;
40
+ if(value.status === 'approved') { state.account = value.account; return providers(); }
41
+ if(value.status === 'denied') { showError(new Error('This request was declined. Start a new request when you’re ready.')); return; }
42
+ error.hidden = true;
43
+ } catch(e) { if(expected !== revision) return; showError(e); if(/expired|already used/i.test(e.message)) return; }
44
+ timer = setTimeout(poll, 3000);
45
+ }
46
+ async function providers() {
47
+ render(2, '<p class="eyebrow">Choose your AI</p><h1>A familiar<br>helping hand.</h1><p class="lead">Use the subscription you already have. Lucid will use this provider for chat and coding.</p><p class="fine">Connected as ' + escape(state.account.email) + '</p><div id="providers"><p class="status" role="status"><span class="dot"></span>Checking this computer…</p></div><div class="actions"><button class="primary" id="continue" disabled>Continue <span aria-hidden="true">→</span></button><button class="secondary" id="refresh">Check again</button></div><p class="fine" style="margin-top:18px">Checking sign-in does not use a model or confirm remaining allowance.</p>');
48
+ button('refresh', refreshProviders);
49
+ button('continue', async () => preferences());
50
+ try { await refreshProviders(); } catch(e) { showError(e); }
51
+ }
52
+ async function refreshProviders() {
53
+ const expected = revision;
54
+ const result = await request('providers');
55
+ if(expected !== revision) return;
56
+ const box = document.getElementById('providers'); box.innerHTML = '';
57
+ for (const p of result.providers) {
58
+ const ready = p.auth === 'authenticated';
59
+ const card = document.createElement('button'); card.className = 'card choice'; card.type = 'button';
60
+ card.setAttribute('aria-pressed', String(selected === p.id));
61
+ card.innerHTML = '<span class="badge ' + (ready ? 'good' : '') + '">' + (ready ? 'Signed in' : 'Needs attention') + '</span><strong>' + escape(p.label) + '</strong><p>' + (ready ? 'Your existing login is ready to use.' : escape(p.message)) + '</p>';
62
+ card.onclick = () => { selected = p.id; sessionStorage.setItem('luciditySetupProvider', selected); box.querySelectorAll('button').forEach(b => b.setAttribute('aria-pressed','false')); card.setAttribute('aria-pressed','true'); document.getElementById('continue').disabled = !ready; };
63
+ box.append(card);
64
+ if(selected === p.id) document.getElementById('continue').disabled = !ready;
65
+ }
66
+ }
67
+ function clientResults(rows) {
68
+ return rows.map(c => '<div class="card"><span class="badge ' + (c.status === 'configured' ? 'good' : '') + '">' + (c.status === 'configured' ? 'Added' : 'Needs attention') + '</span><strong>' + escape(c.label) + '</strong><p>' + escape(c.message) + '</p></div>').join('');
69
+ }
70
+ async function clientChoices() {
71
+ const expected = revision;
72
+ const result = await request('clients');
73
+ if(expected !== revision) return;
74
+ const box = document.getElementById('clients');
75
+ box.innerHTML = '';
76
+ for(const c of result.clients) {
77
+ const available = c.status === 'available';
78
+ const card = document.createElement('label'); card.className = 'card checkrow';
79
+ card.innerHTML = '<input type="checkbox" value="' + escape(c.id) + '" ' + (!available ? 'disabled ' : '') + '><span><strong>Use Lucidity in ' + escape(c.label) + '</strong><p>' + escape(c.message) + '</p></span>';
80
+ const input = card.querySelector('input');
81
+ input.checked = c.status === 'configured' || (available && Array.isArray(choices.clients) && choices.clients.includes(c.id));
82
+ input.onchange = () => { choices.clients = selectedClients(); sessionStorage.setItem('luciditySetupChoices', JSON.stringify(choices)); };
83
+ box.append(card);
84
+ }
85
+ }
86
+ function selectedClients() { return Array.from(document.querySelectorAll('#clients input:checked:not(:disabled)')).map(input => input.value); }
87
+ const clientSection = '<h2>Bring your tasks along.</h2><p>Access your Lucidity tasks, projects and comments in your own AI conversations. We’ll add the connection for you.</p><div id="clients"><p class="status" role="status">Checking your apps…</p></div><p class="fine">Your AI app may ask you to approve its tools. Local files and memories are not shared by this connection.</p>';
88
+ async function existingClients() {
89
+ render(3, '<p class="eyebrow">Already connected</p><h1>Lucidity, wherever<br>you think.</h1><p class="lead">Add Lucidity to the AI apps you use on this computer. Your account is already connected.</p>' + clientSection + '<div class="actions"><button class="primary" id="add-clients">Connect selected apps <span aria-hidden="true">→</span></button><button class="secondary" id="refresh-clients">Check again</button></div><div id="client-results" aria-live="polite"></div>');
90
+ button('refresh-clients', clientChoices);
91
+ button('add-clients', async () => {
92
+ const selected = selectedClients();
93
+ if(!selected.length) throw new Error('Choose an available app to connect.');
94
+ const result = await request('configure-clients', {clients:selected});
95
+ document.getElementById('client-results').innerHTML = clientResults(result.clients);
96
+ await clientChoices();
97
+ });
98
+ await clientChoices();
99
+ }
100
+ async function preferences() {
101
+ render(3, '<p class="eyebrow">Make it yours</p><h1>A little help.<br>On your terms.</h1><p class="lead">Choose what Lucid can help with.</p><label class="card checkrow"><input type="checkbox" id="tasks"><span><strong>Help with my tasks</strong><p>Let Lucid read and change your tasks, projects and comments when you ask.</p></span></label><label class="card checkrow"><input type="checkbox" id="schedules"><span><strong>A daily rhythm</strong><p>Enable the 8am briefing, weekly review, journal processing and reminders. AI jobs use your provider allowance.</p></span></label><p class="fine">Local folders and repositories stay private until you grant access.</p>' + clientSection + '<div class="notice">For this preview, keep the terminal open while using AI. Closing your browser is fine. Background startup comes next.</div><div class="actions"><button class="primary" id="finish">Finish setup <span aria-hidden="true">→</span></button><button class="secondary" id="back">Back</button></div>');
102
+ for(const [id, field] of [['tasks','tasks'],['schedules','scheduledWork']]) { const input=document.getElementById(id); input.checked=choices[field] === true; input.onchange=()=>{choices[field]=input.checked;sessionStorage.setItem('luciditySetupChoices',JSON.stringify(choices));}; }
103
+ button('back', providers);
104
+ button('finish', async () => {
105
+ const result = await request('finish', {provider:selected,tasks:document.getElementById('tasks').checked,scheduledWork:document.getElementById('schedules').checked,clients:selectedClients()});
106
+ render(4, '<div class="seal" aria-hidden="true">✓</div><p class="eyebrow">Setup complete</p><h1>A clearer day<br>starts here.</h1><p class="lead">Your account and preferences are saved. Lucidity is starting on this computer.</p><div class="card"><strong>Open Lucidity on your phone</strong><p>Go to Connect a computer. Once it shows this computer as ready, send your first message.</p></div>' + clientResults(result.clients || []) + '<p class="fine">You can close this browser window. Keep the terminal open for AI to remain available.</p>');
107
+ document.getElementById('cancel').hidden = true;
108
+ });
109
+ try { await clientChoices(); } catch(e) { document.getElementById('clients').textContent = 'Could not check your apps. You can add them later with lucidity setup-mcp.'; }
110
+ }
111
+ button('cancel', async () => { revision++; clearTimeout(timer); await request('cancel'); render(0,'<h1>See you when<br>you’re ready.</h1><p class="lead">Setup has stopped. You can keep using Lucidity on your phone and connect this computer later.</p>'); document.getElementById('cancel').hidden = true; });
112
+ (async () => {
113
+ try { state = await request('state'); if(state.existing) { await existingClients(); } else if(state.code) connect(); else welcome(); }
114
+ catch(e) { showError(e); }
115
+ })();
116
+ `;
117
+ export function localSetupPage(nonce) {
118
+ const body = `<main class="frame"><aside class="rail"><span class="tiny">Your computer, connected</span><h2>More room<br>for your ideas.</h2><ol class="steps" aria-label="Setup progress"><li class="active"><b>1</b>Welcome</li><li><b>2</b>Connect account</li><li><b>3</b>Choose AI</li><li><b>4</b>Make it yours</li><li><b>5</b>Ready</li></ol><p class="rail-note">A private connection.<br>A familiar helping hand.<br>Everything in its place.</p></aside><section class="content"><div id="stage"><p class="status"><span class="dot"></span>Getting things ready…</p></div><div id="error" class="notice error" role="alert" hidden></div><div class="spacer"></div><button class="secondary" id="cancel" style="align-self:flex-start">Finish another time</button></section></main><template id="art">${setupIllustration}</template>`;
119
+ return setupPage(body, setupScript, nonce);
120
+ }
@@ -0,0 +1,26 @@
1
+ import { type IncomingMessage, type ServerResponse } from 'node:http';
2
+ import { createClientSetup } from '../mcp/clients.js';
3
+ export declare function setupApiUrl(value: string): string;
4
+ export declare function writeNewSetupConfig(dir: string, config: Record<string, unknown>): void;
5
+ export declare function checkSetupProviders(): Promise<{
6
+ id: "claude" | "codex";
7
+ label: string;
8
+ auth: string;
9
+ message: string;
10
+ }[]>;
11
+ export interface SetupOptions {
12
+ apiUrl?: string;
13
+ directory?: string;
14
+ fetch?: typeof globalThis.fetch;
15
+ providers?: typeof checkSetupProviders;
16
+ clients?: ReturnType<typeof createClientSetup>;
17
+ onFinish?: (start: boolean) => void;
18
+ }
19
+ export declare function createSetupServer(options?: SetupOptions): Promise<{
20
+ server: import("http").Server<typeof IncomingMessage, typeof ServerResponse>;
21
+ url: string;
22
+ token: string;
23
+ origin: string;
24
+ }>;
25
+ export declare function runSetup(): Promise<boolean>;
26
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/setup/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,cAAc,EACpB,MAAM,WAAW,CAAC;AAsBnB,OAAO,EACL,iBAAiB,EAGlB,MAAM,mBAAmB,CAAC;AAe3B,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,UAqBxC;AACD,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,QAahC;AA4BD,wBAAsB,mBAAmB;;;;;KA+BxC;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAChC,SAAS,CAAC,EAAE,OAAO,mBAAmB,CAAC;IACvC,OAAO,CAAC,EAAE,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC;IAC/C,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACrC;AACD,wBAAsB,iBAAiB,CAAC,OAAO,GAAE,YAAiB;;;;;GAmTjE;AAED,wBAAsB,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC,CAsBjD"}
@@ -0,0 +1,398 @@
1
+ import { createServer, } from 'node:http';
2
+ import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
3
+ import { hostname } from 'node:os';
4
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, linkSync, chmodSync, } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { spawn } from 'node:child_process';
7
+ import { z } from 'zod';
8
+ import { ClaudeAgentExecutor, CodexExecutor, providerFailure, } from '@lucidity/runtime';
9
+ import { CONFIG_DIR } from '../config.js';
10
+ import { localSetupPage } from './page.js';
11
+ import { createClientSetup, CLIENT_IDS, } from '../mcp/clients.js';
12
+ const clientChoices = z.array(z.enum(CLIENT_IDS)).max(2).default([]);
13
+ const sha = (s) => createHash('sha256').update(s).digest('hex');
14
+ const pendingSchema = z.object({
15
+ id: z.string().uuid(),
16
+ code: z.string().regex(/^[A-F0-9]{24}$/),
17
+ expiresAt: z.string().datetime(),
18
+ secret: z.string().regex(/^[a-f0-9]{64}$/),
19
+ key: z.string().regex(/^luc_pc_[a-f0-9]{64}$/),
20
+ apiUrl: z.string().url(),
21
+ name: z.string().min(1).max(120),
22
+ });
23
+ export function setupApiUrl(value) {
24
+ const url = new URL(value);
25
+ if (url.username ||
26
+ url.password ||
27
+ url.search ||
28
+ url.hash ||
29
+ (url.pathname !== '/' && url.pathname !== ''))
30
+ throw new Error('Use the API origin without a path or credentials.');
31
+ if (url.protocol !== 'https:' &&
32
+ !(url.protocol === 'http:' &&
33
+ ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)))
34
+ throw new Error('Setup requires HTTPS, except for a local development API.');
35
+ return url.origin;
36
+ }
37
+ export function writeNewSetupConfig(dir, config) {
38
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
39
+ const temporary = join(dir, `.setup-${randomBytes(8).toString('hex')}.json`);
40
+ writeFileSync(temporary, JSON.stringify(config, null, 2) + '\n', {
41
+ flag: 'wx',
42
+ mode: 0o600,
43
+ });
44
+ try {
45
+ linkSync(temporary, join(dir, 'config.json'));
46
+ }
47
+ finally {
48
+ unlinkSync(temporary);
49
+ }
50
+ }
51
+ function acquireSetupLock(dir) {
52
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
53
+ const path = join(dir, 'setup.lock');
54
+ if (existsSync(path)) {
55
+ const pid = Number(readFileSync(path, 'utf8'));
56
+ if (!Number.isInteger(pid) || pid < 1)
57
+ throw new Error('The saved setup lock is invalid. Your configuration has not been changed.');
58
+ let alive = true;
59
+ try {
60
+ process.kill(pid, 0);
61
+ }
62
+ catch (e) {
63
+ if (e.code === 'ESRCH')
64
+ alive = false;
65
+ }
66
+ if (alive)
67
+ throw new Error('Setup is already open for this computer. Return to its browser window.');
68
+ unlinkSync(path);
69
+ }
70
+ writeFileSync(path, String(process.pid), { flag: 'wx', mode: 0o600 });
71
+ return () => {
72
+ if (existsSync(path) && readFileSync(path, 'utf8') === String(process.pid))
73
+ unlinkSync(path);
74
+ };
75
+ }
76
+ export async function checkSetupProviders() {
77
+ return Promise.all(['claude', 'codex'].map(async (id) => {
78
+ const executor = id === 'claude' ? new ClaudeAgentExecutor() : new CodexExecutor();
79
+ try {
80
+ await executor.models();
81
+ return {
82
+ id,
83
+ label: id === 'claude' ? 'Claude' : 'Codex',
84
+ auth: 'authenticated',
85
+ message: '',
86
+ };
87
+ }
88
+ catch (e) {
89
+ const health = providerFailure(e);
90
+ return {
91
+ id,
92
+ label: id === 'claude' ? 'Claude' : 'Codex',
93
+ auth: health.auth === 'authenticated' ? 'unknown' : health.auth,
94
+ message: health.problem === 'login'
95
+ ? id === 'claude'
96
+ ? 'Sign in with Claude Code on this computer, then check again.'
97
+ : 'Run codex login on this computer, then check again.'
98
+ : 'Could not check this provider. Confirm it is installed and your network is available, then check again.',
99
+ };
100
+ }
101
+ finally {
102
+ await executor.dispose();
103
+ }
104
+ }));
105
+ }
106
+ export async function createSetupServer(options = {}) {
107
+ const apiUrl = setupApiUrl(options.apiUrl ?? process.env.LUCIDITY_API_URL ?? 'https://api.lucidity.my');
108
+ const dir = options.directory ?? CONFIG_DIR;
109
+ const pendingPath = join(dir, 'setup-pending.json');
110
+ const configPath = join(dir, 'config.json');
111
+ const clients = options.clients ?? createClientSetup({ configPath });
112
+ const token = randomBytes(32).toString('hex');
113
+ const nonce = randomBytes(18).toString('base64');
114
+ let pending;
115
+ let finished = false;
116
+ let mutation = false;
117
+ let providerCheck;
118
+ if (!existsSync(configPath) && existsSync(pendingPath)) {
119
+ const parsed = pendingSchema.safeParse(JSON.parse(readFileSync(pendingPath, 'utf8')));
120
+ if (!parsed.success)
121
+ throw new Error('Saved setup is invalid. Your existing configuration has not been changed.');
122
+ if (parsed.data.apiUrl !== apiUrl)
123
+ throw new Error('A connection is pending for a different Lucidity server. Finish or cancel it using that server before starting again.');
124
+ pending = parsed.data;
125
+ }
126
+ const api = async (path, body) => {
127
+ const response = await (options.fetch ?? fetch)(apiUrl + '/api/auth/computers/' + path, {
128
+ method: 'POST',
129
+ headers: { 'Content-Type': 'application/json' },
130
+ body: JSON.stringify(body),
131
+ signal: AbortSignal.timeout(15000),
132
+ redirect: 'error',
133
+ });
134
+ const value = await response.json().catch(() => ({}));
135
+ if (!response.ok)
136
+ throw new Error(response.status === 404
137
+ ? 'This Lucidity server does not support guided setup yet. Update the server before trying again.'
138
+ : typeof value.error === 'string'
139
+ ? value.error
140
+ : 'Lucidity could not be reached. Check your connection and try again.');
141
+ return value;
142
+ };
143
+ const publicState = () => pending
144
+ ? {
145
+ name: pending.name,
146
+ code: pending.code,
147
+ approvalUrl: (apiUrl === 'https://api.lucidity.my'
148
+ ? 'https://lucidity.my'
149
+ : apiUrl) +
150
+ '/connect-computer#code=' +
151
+ pending.code,
152
+ }
153
+ : {};
154
+ const removePending = () => {
155
+ if (existsSync(pendingPath))
156
+ unlinkSync(pendingPath);
157
+ pending = undefined;
158
+ };
159
+ async function body(req) {
160
+ const chunks = [];
161
+ let size = 0;
162
+ for await (const chunk of req) {
163
+ size += chunk.length;
164
+ if (size > 2048)
165
+ throw new Error('Request too large.');
166
+ chunks.push(chunk);
167
+ }
168
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
169
+ }
170
+ const send = (res, status, value) => {
171
+ res.writeHead(status, { 'Content-Type': 'application/json' });
172
+ res.end(JSON.stringify(value));
173
+ };
174
+ let origin = '';
175
+ const releaseLock = acquireSetupLock(dir);
176
+ const server = createServer(async (req, res) => {
177
+ res.setHeader('Cache-Control', 'no-store');
178
+ res.setHeader('Referrer-Policy', 'no-referrer');
179
+ res.setHeader('X-Content-Type-Options', 'nosniff');
180
+ res.setHeader('Content-Security-Policy', `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'`);
181
+ if (req.headers.host !== new URL(origin).host)
182
+ return send(res, 403, { error: 'Unrecognized setup host.' });
183
+ if (req.method === 'GET' && req.url === '/') {
184
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
185
+ res.end(localSetupPage(nonce));
186
+ return;
187
+ }
188
+ const provided = req.headers['x-setup-token'];
189
+ if (req.method !== 'POST' ||
190
+ req.headers.origin !== origin ||
191
+ req.headers['content-type'] !== 'application/json' ||
192
+ typeof provided !== 'string' ||
193
+ !/^[a-f0-9]{64}$/.test(provided) ||
194
+ !timingSafeEqual(Buffer.from(provided), Buffer.from(token)))
195
+ return send(res, 403, {
196
+ error: 'This setup session is unavailable. Run lucidity setup again.',
197
+ });
198
+ try {
199
+ const input = await body(req);
200
+ if (finished)
201
+ return send(res, 409, { error: 'Setup has finished.' });
202
+ if (req.url === '/api/state')
203
+ return send(res, 200, {
204
+ existing: existsSync(configPath),
205
+ ...publicState(),
206
+ });
207
+ if (req.url === '/api/poll') {
208
+ if (!pending)
209
+ throw new Error('Start a connection first.');
210
+ return send(res, 200, await api('poll', { id: pending.id, secret: pending.secret }));
211
+ }
212
+ if (req.url === '/api/providers') {
213
+ providerCheck ??= (options.providers ?? checkSetupProviders)().finally(() => {
214
+ providerCheck = undefined;
215
+ });
216
+ return send(res, 200, { providers: await providerCheck });
217
+ }
218
+ if (req.url === '/api/clients')
219
+ return send(res, 200, { clients: await clients.inspect() });
220
+ if (mutation)
221
+ return send(res, 409, { error: 'A setup step is already running.' });
222
+ mutation = true;
223
+ try {
224
+ if (req.url === '/api/configure-clients') {
225
+ if (!existsSync(configPath))
226
+ throw new Error('Finish connecting your account first.');
227
+ const selected = z
228
+ .object({ clients: clientChoices })
229
+ .parse(input).clients;
230
+ return send(res, 200, { clients: await clients.configure(selected) });
231
+ }
232
+ if (req.url === '/api/begin') {
233
+ if (existsSync(configPath))
234
+ throw new Error('This computer is already configured. Your settings have been kept.');
235
+ const restart = z
236
+ .object({ restart: z.boolean().optional() })
237
+ .parse(input).restart;
238
+ if (pending &&
239
+ !restart &&
240
+ new Date(pending.expiresAt).getTime() > Date.now())
241
+ return send(res, 200, publicState());
242
+ if (pending) {
243
+ await api('cancel', { id: pending.id, secret: pending.secret });
244
+ removePending();
245
+ }
246
+ const secret = randomBytes(32).toString('hex');
247
+ const key = 'luc_pc_' + randomBytes(32).toString('hex');
248
+ const name = hostname().slice(0, 120) || 'My computer';
249
+ const created = await api('begin', {
250
+ name,
251
+ secretHash: sha(secret),
252
+ keyHash: sha(key),
253
+ });
254
+ pending = pendingSchema.parse({
255
+ ...created,
256
+ secret,
257
+ key,
258
+ apiUrl,
259
+ name,
260
+ });
261
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
262
+ writeFileSync(pendingPath, JSON.stringify(pending), { mode: 0o600 });
263
+ chmodSync(pendingPath, 0o600);
264
+ return send(res, 200, publicState());
265
+ }
266
+ if (req.url === '/api/finish') {
267
+ const preferences = z
268
+ .object({
269
+ provider: z.enum(['claude', 'codex']),
270
+ tasks: z.boolean(),
271
+ scheduledWork: z.boolean(),
272
+ clients: clientChoices,
273
+ })
274
+ .parse(input);
275
+ if (!pending)
276
+ throw new Error('Connect your account first.');
277
+ const approved = await api('poll', {
278
+ id: pending.id,
279
+ secret: pending.secret,
280
+ });
281
+ if (approved.status !== 'approved')
282
+ throw new Error('Approve this computer in your Lucidity account first.');
283
+ const health = await (options.providers ?? checkSetupProviders)();
284
+ if (!health.some((p) => p.id === preferences.provider && p.auth === 'authenticated'))
285
+ throw new Error('Sign in to your selected provider and check again.');
286
+ writeNewSetupConfig(dir, {
287
+ apiKey: pending.key,
288
+ apiUrl,
289
+ machineName: pending.name,
290
+ chatProvider: preferences.provider,
291
+ codeProvider: preferences.provider,
292
+ chatModel: 'default',
293
+ codeModel: 'default',
294
+ delivery: 'stdout',
295
+ scheduledWork: preferences.scheduledWork,
296
+ reflect: false,
297
+ weeklyReview: preferences.scheduledWork,
298
+ capabilities: {
299
+ tasks: preferences.tasks,
300
+ memory: false,
301
+ connected: false,
302
+ },
303
+ repos: [],
304
+ });
305
+ removePending();
306
+ let clientResults = [];
307
+ if (preferences.clients.length) {
308
+ try {
309
+ clientResults = await clients.configure(preferences.clients);
310
+ }
311
+ catch {
312
+ // Pairing has succeeded. A client-config failure must not send the
313
+ // user back through pairing or revoke the saved credential.
314
+ clientResults = preferences.clients.map((id) => ({
315
+ id,
316
+ label: id === 'claude' ? 'Claude Code' : 'Codex',
317
+ status: 'error',
318
+ message: 'Your account is connected. Run lucidity setup-mcp to finish adding your tools.',
319
+ }));
320
+ }
321
+ }
322
+ finished = true;
323
+ send(res, 200, { ok: true, clients: clientResults });
324
+ setTimeout(() => {
325
+ server.close();
326
+ options.onFinish?.(true);
327
+ }, 500);
328
+ return;
329
+ }
330
+ if (req.url === '/api/cancel') {
331
+ if (pending)
332
+ await api('cancel', { id: pending.id, secret: pending.secret });
333
+ removePending();
334
+ finished = true;
335
+ send(res, 200, { ok: true });
336
+ setTimeout(() => {
337
+ server.close();
338
+ options.onFinish?.(false);
339
+ }, 500);
340
+ return;
341
+ }
342
+ send(res, 404, { error: 'Unknown setup action.' });
343
+ }
344
+ finally {
345
+ mutation = false;
346
+ }
347
+ }
348
+ catch (e) {
349
+ send(res, 400, {
350
+ error: e instanceof z.ZodError
351
+ ? 'Invalid setup choice.'
352
+ : e instanceof Error
353
+ ? e.message
354
+ : 'Setup could not finish.',
355
+ });
356
+ }
357
+ });
358
+ server.once('close', releaseLock);
359
+ server.once('error', releaseLock);
360
+ server.requestTimeout = 20000;
361
+ await new Promise((resolve, reject) => {
362
+ server.once('error', reject);
363
+ server.listen(0, '127.0.0.1', resolve);
364
+ });
365
+ const address = server.address();
366
+ if (!address || typeof address === 'string')
367
+ throw new Error('Could not open setup.');
368
+ origin = 'http://127.0.0.1:' + address.port;
369
+ const expires = setTimeout(() => {
370
+ server.closeAllConnections();
371
+ server.close();
372
+ options.onFinish?.(false);
373
+ }, 30 * 60 * 1000);
374
+ expires.unref();
375
+ server.on('close', () => clearTimeout(expires));
376
+ return { server, url: origin + '/#session=' + token, token, origin };
377
+ }
378
+ export async function runSetup() {
379
+ return new Promise((resolve, reject) => {
380
+ void createSetupServer({ onFinish: resolve }).then(({ url }) => {
381
+ console.error('Open this private setup link on this computer:\n' + url);
382
+ const command = process.platform === 'darwin'
383
+ ? 'open'
384
+ : process.platform === 'win32'
385
+ ? 'rundll32'
386
+ : 'xdg-open';
387
+ const args = process.platform === 'win32'
388
+ ? ['url.dll,FileProtocolHandler', url]
389
+ : [url];
390
+ const child = spawn(command, args, {
391
+ stdio: 'ignore',
392
+ windowsHide: true,
393
+ });
394
+ child.on('error', () => { });
395
+ child.unref();
396
+ }, reject);
397
+ });
398
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opencorelabs/lucidity",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Lucidity's local personal agent, command-line interface, and MCP server",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
package/src/config.ts CHANGED
@@ -66,6 +66,8 @@ export interface Capabilities {
66
66
  }
67
67
 
68
68
  export interface DaemonConfig {
69
+ /** Master switch for proactive jobs. Existing installations retain their behavior. */
70
+ scheduledWork?: boolean;
69
71
  chatProvider?: 'claude' | 'codex';
70
72
  codeProvider?: 'claude' | 'codex';
71
73
  /** Lucidity API key, `luc_…`. */
@@ -359,6 +361,7 @@ export function loadConfig(configPath: string = CONFIG_PATH): DaemonConfig {
359
361
  apiKey,
360
362
  apiUrl,
361
363
  machineName,
364
+ scheduledWork: obj['scheduledWork'] !== false,
362
365
  briefingTime,
363
366
  chatProvider,
364
367
  codeProvider,