@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
package/src/index.ts CHANGED
@@ -46,6 +46,8 @@ import { listAllowlist } from './coding/discover.js';
46
46
  import { resolveRepo } from './coding/repos.js';
47
47
  import { watchBranches } from './coding/branchWatch.js';
48
48
  import { sweepStaleRequests } from './sweepStale.js';
49
+ import { runSetup } from './setup/server.js';
50
+ import { runClientSetup } from './mcp/clients.js';
49
51
 
50
52
  const KNOWN_JOBS = ['briefing', 'weekly-review', 'extraction'] as const;
51
53
 
@@ -84,6 +86,14 @@ function parseArgs(argv: string[]): CliArgs {
84
86
 
85
87
  async function main(): Promise<void> {
86
88
  const args = parseArgs(process.argv.slice(2));
89
+ if (args.command === 'setup-mcp') {
90
+ await runClientSetup(process.argv.slice(3));
91
+ return;
92
+ }
93
+ if (args.command === 'setup') {
94
+ if (!(await runSetup())) return;
95
+ args.command = undefined;
96
+ }
87
97
 
88
98
  // Service-management commands (manage the launchd agent; handled before config
89
99
  // so `status`/`uninstall` work even without a valid config).
@@ -195,15 +205,18 @@ async function main(): Promise<void> {
195
205
 
196
206
  // Default mode: run the scheduler in the foreground.
197
207
  const scheduler = new Scheduler();
198
- const briefingJob = scheduler.scheduleDaily(
199
- config.briefingTime,
200
- () =>
201
- void runJob('briefing', queue, () =>
202
- runBriefing(config, executor, deliverer, attention),
203
- ),
204
- { timezone: config.timezone },
205
- );
206
- if (config.weeklyReview) {
208
+ const briefingJob =
209
+ config.scheduledWork !== false
210
+ ? scheduler.scheduleDaily(
211
+ config.briefingTime,
212
+ () =>
213
+ void runJob('briefing', queue, () =>
214
+ runBriefing(config, executor, deliverer, attention),
215
+ ),
216
+ { timezone: config.timezone },
217
+ )
218
+ : undefined;
219
+ if (config.scheduledWork !== false && config.weeklyReview) {
207
220
  scheduler.scheduleWeekly(
208
221
  config.weeklyReviewDay,
209
222
  config.weeklyReviewTime,
@@ -219,12 +232,14 @@ async function main(): Promise<void> {
219
232
  // shouldn't wait for tomorrow's briefing to be read, and the batch is capped, so a quiet
220
233
  // week catching up costs the same as a busy one. It delivers nothing — this is the step
221
234
  // that makes the briefing and the weekly review better, not another thing to read.
222
- scheduler.scheduleEveryHours(
223
- EXTRACTION_INTERVAL_HOURS,
224
- () =>
225
- void runJob('extraction', queue, () => runExtraction(config, executor)),
226
- { timezone: config.timezone },
227
- );
235
+ if (config.scheduledWork !== false) {
236
+ scheduler.scheduleEveryHours(
237
+ EXTRACTION_INTERVAL_HOURS,
238
+ () =>
239
+ void runJob('extraction', queue, () => runExtraction(config, executor)),
240
+ { timezone: config.timezone },
241
+ );
242
+ }
228
243
 
229
244
  // Interactive chat server (lite local gateway): loopback + token auth.
230
245
  const chatServer = createChatServer({
@@ -248,13 +263,15 @@ async function main(): Promise<void> {
248
263
  // Nag about procurement requests that have stopped moving. Just after the
249
264
  // briefing rather than overnight, so the nudge lands when someone is at a desk
250
265
  // and can act on it — a 3am notification is one you scroll past at 9.
251
- scheduler.scheduleDaily(
252
- '09:30',
253
- () => void sweepStaleRequests(config.apiKey),
254
- {
255
- timezone: config.timezone,
256
- },
257
- );
266
+ if (config.scheduledWork !== false) {
267
+ scheduler.scheduleDaily(
268
+ '09:30',
269
+ () => void sweepStaleRequests(config.apiKey),
270
+ {
271
+ timezone: config.timezone,
272
+ },
273
+ );
274
+ }
258
275
 
259
276
  // Room client (free path): dial the hosted relay so the phone can reach Lucid,
260
277
  // serving ask/briefing/journal through the shared harness. Best-effort — it
@@ -393,7 +410,7 @@ async function main(): Promise<void> {
393
410
  : null;
394
411
 
395
412
  const tz = config.timezone ? ` ${config.timezone}` : '';
396
- const next = briefingJob.nextRun();
413
+ const next = briefingJob?.nextRun();
397
414
  const weekly = config.weeklyReview
398
415
  ? `; weekly review ${config.weeklyReviewTime} (day ${config.weeklyReviewDay})`
399
416
  : '';
@@ -411,7 +428,7 @@ async function main(): Promise<void> {
411
428
 
412
429
  console.error(
413
430
  `[daemon] Lucid daemon started. Briefing ${config.briefingTime}${tz} → ${deliverer.name}${weekly}. ` +
414
- `Next briefing: ${next ? next.toISOString() : 'unknown'}. Chat on 127.0.0.1:${config.chatPort}. ` +
431
+ `Scheduled work: ${config.scheduledWork !== false ? 'on' : 'off'}. Next briefing: ${next ? next.toISOString() : 'none'}. Chat on 127.0.0.1:${config.chatPort}. ` +
415
432
  `Room dialing ${config.apiUrl}. ${tools}.${shell} ${runtimeVersions}.`,
416
433
  );
417
434
 
@@ -0,0 +1,269 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { createRequire } from 'node:module';
4
+ import {
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ writeFileSync,
9
+ unlinkSync,
10
+ } from 'node:fs';
11
+ import { homedir } from 'node:os';
12
+ import { delimiter, dirname, join, resolve } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { CONFIG_PATH } from '../config.js';
15
+ import { pairedMcpEnvironment } from './pairedConfig.js';
16
+
17
+ export const CLIENT_IDS = ['claude', 'codex'] as const;
18
+ export type ClientId = (typeof CLIENT_IDS)[number];
19
+ export interface ClientStatus {
20
+ id: ClientId;
21
+ label: string;
22
+ status: 'available' | 'configured' | 'missing' | 'conflict' | 'error';
23
+ message: string;
24
+ }
25
+ export interface ClientSetupOptions {
26
+ configPath?: string;
27
+ home?: string;
28
+ env?: NodeJS.ProcessEnv;
29
+ /** Alternate executable entry for isolated installation checks. */
30
+ launcherPath?: string;
31
+ }
32
+ const labels = { claude: 'Claude Code', codex: 'Codex' };
33
+ const execute = promisify(execFile);
34
+ const require = createRequire(import.meta.url);
35
+ const runtimeRequire = createRequire(require.resolve('@lucidity/runtime'));
36
+
37
+ /** Always use the tested, bundled official CLI; no shell or npm shim execution. */
38
+ function clientCommand(id: ClientId): { command: string; prefix: string[] } {
39
+ if (id === 'codex')
40
+ return {
41
+ command: process.execPath,
42
+ prefix: [runtimeRequire.resolve('@openai/codex/bin/codex.js')],
43
+ };
44
+ const sdk = runtimeRequire.resolve('@anthropic-ai/claude-agent-sdk');
45
+ const musl =
46
+ process.platform === 'linux' &&
47
+ !(
48
+ process.report.getReport() as { header: { glibcVersionRuntime?: string } }
49
+ ).header.glibcVersionRuntime
50
+ ? '-musl'
51
+ : '';
52
+ const native = createRequire(sdk).resolve(
53
+ `@anthropic-ai/claude-agent-sdk-${process.platform}-${process.arch}${musl}/package.json`,
54
+ );
55
+ return {
56
+ command: join(
57
+ dirname(native),
58
+ process.platform === 'win32' ? 'claude.exe' : 'claude',
59
+ ),
60
+ prefix: [],
61
+ };
62
+ }
63
+
64
+ export function createClientSetup(options: ClientSetupOptions = {}) {
65
+ const home = options.home ?? homedir();
66
+ const env = options.env ?? process.env;
67
+ const configPath = resolve(options.configPath ?? CONFIG_PATH);
68
+ const claudeConfig = env.CLAUDE_CONFIG_DIR
69
+ ? join(resolve(env.CLAUDE_CONFIG_DIR), '.claude.json')
70
+ : join(home, '.claude.json');
71
+ const codexHome = resolve(env.CODEX_HOME ?? join(home, '.codex'));
72
+ const launcher =
73
+ options.launcherPath ??
74
+ fileURLToPath(new URL('../../dist/mcp/paired.js', import.meta.url));
75
+ const args = [launcher, '--config', configPath];
76
+ const detected = (id: ClientId) =>
77
+ existsSync(id === 'claude' ? claudeConfig : codexHome) ||
78
+ (env.PATH ?? env.Path ?? '')
79
+ .split(delimiter)
80
+ .filter(Boolean)
81
+ .some((dir) =>
82
+ (process.platform === 'win32'
83
+ ? ['.exe', '.cmd', '.bat', '']
84
+ : ['']
85
+ ).some((ext) => existsSync(join(dir, id + ext))),
86
+ );
87
+ const run = async (id: ClientId, argv: string[]) => {
88
+ const { command, prefix } = clientCommand(id);
89
+ const childEnv = { ...env, DISABLE_AUTOUPDATER: '1' };
90
+ const { stdout } = await execute(command, [...prefix, ...argv], {
91
+ cwd: home,
92
+ env: childEnv,
93
+ timeout: 15000,
94
+ maxBuffer: 1024 * 1024,
95
+ windowsHide: true,
96
+ });
97
+ return stdout;
98
+ };
99
+ const result = (
100
+ id: ClientId,
101
+ status: ClientStatus['status'],
102
+ message: string,
103
+ ): ClientStatus => ({ id, label: labels[id], status, message });
104
+ const matches = (entry: Record<string, unknown>) =>
105
+ entry.command === process.execPath &&
106
+ JSON.stringify(entry.args) === JSON.stringify(args) &&
107
+ (!entry.env || Object.keys(entry.env).length === 0) &&
108
+ (!entry.env_vars ||
109
+ (Array.isArray(entry.env_vars) && entry.env_vars.length === 0)) &&
110
+ (!entry.type || entry.type === 'stdio');
111
+
112
+ async function inspectOne(id: ClientId): Promise<ClientStatus> {
113
+ if (!detected(id))
114
+ return result(
115
+ id,
116
+ 'missing',
117
+ `Open ${labels[id]} once after installing it, then check again.`,
118
+ );
119
+ try {
120
+ let entry: Record<string, unknown> | undefined;
121
+ let present = false;
122
+ let enabled = true;
123
+ if (id === 'claude') {
124
+ const config = existsSync(claudeConfig)
125
+ ? JSON.parse(readFileSync(claudeConfig, 'utf8'))
126
+ : {};
127
+ if (
128
+ !config ||
129
+ typeof config !== 'object' ||
130
+ Array.isArray(config) ||
131
+ (config.mcpServers !== undefined &&
132
+ (!config.mcpServers ||
133
+ typeof config.mcpServers !== 'object' ||
134
+ Array.isArray(config.mcpServers)))
135
+ )
136
+ throw new Error('Invalid config');
137
+ present = Object.hasOwn(config.mcpServers ?? {}, 'lucidity');
138
+ if (present) entry = config.mcpServers.lucidity;
139
+ } else {
140
+ const list: unknown = JSON.parse(
141
+ await run(id, ['mcp', 'list', '--json']),
142
+ );
143
+ if (!Array.isArray(list)) throw new Error('Invalid list');
144
+ const existing = list.find((e) => e?.name === 'lucidity');
145
+ if (existing) {
146
+ present = true;
147
+ entry = existing.transport;
148
+ enabled = existing.enabled !== false;
149
+ }
150
+ }
151
+ if (!present)
152
+ return result(
153
+ id,
154
+ 'available',
155
+ 'Add your Lucidity tasks, projects and comments.',
156
+ );
157
+ if (entry && typeof entry === 'object' && matches(entry) && enabled)
158
+ return result(
159
+ id,
160
+ 'configured',
161
+ 'Settings saved. Open a new session to use Lucidity.',
162
+ );
163
+ return result(
164
+ id,
165
+ 'conflict',
166
+ 'A different or disabled Lucidity connection already exists. Your settings have been kept.',
167
+ );
168
+ } catch {
169
+ // Native CLI errors can quote config values. Never return their stdout/stderr.
170
+ return result(
171
+ id,
172
+ 'error',
173
+ `Could not read ${labels[id]} settings. Check its MCP settings, then try again.`,
174
+ );
175
+ }
176
+ }
177
+
178
+ async function inspect(): Promise<ClientStatus[]> {
179
+ return Promise.all(CLIENT_IDS.map(inspectOne));
180
+ }
181
+ async function configure(ids: ClientId[]): Promise<ClientStatus[]> {
182
+ pairedMcpEnvironment(configPath);
183
+ if (!existsSync(launcher))
184
+ throw new Error(
185
+ 'Build or reinstall Lucidity before connecting your AI apps.',
186
+ );
187
+ const lock = join(dirname(configPath), 'mcp-setup.lock');
188
+ mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
189
+ if (existsSync(lock)) {
190
+ const pid = Number(readFileSync(lock, 'utf8'));
191
+ if (Number.isInteger(pid) && pid > 0) {
192
+ try {
193
+ process.kill(pid, 0);
194
+ } catch (error) {
195
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH')
196
+ unlinkSync(lock);
197
+ }
198
+ }
199
+ }
200
+ try {
201
+ writeFileSync(lock, String(process.pid), { flag: 'wx', mode: 0o600 });
202
+ } catch {
203
+ throw new Error(
204
+ 'MCP setup is already running. Wait for it to finish, then try again.',
205
+ );
206
+ }
207
+ try {
208
+ const results: ClientStatus[] = [];
209
+ for (const id of [...new Set(ids)]) {
210
+ const before = await inspectOne(id);
211
+ if (before.status !== 'available') {
212
+ results.push(before);
213
+ continue;
214
+ }
215
+ try {
216
+ await run(id, [
217
+ 'mcp',
218
+ 'add',
219
+ ...(id === 'claude' ? ['--scope', 'user'] : []),
220
+ 'lucidity',
221
+ '--',
222
+ process.execPath,
223
+ ...args,
224
+ ]);
225
+ const after = await inspectOne(id);
226
+ results.push(
227
+ after.status === 'configured'
228
+ ? after
229
+ : result(
230
+ id,
231
+ 'error',
232
+ `Could not confirm ${labels[id]} settings. Check again before retrying.`,
233
+ ),
234
+ );
235
+ } catch {
236
+ results.push(
237
+ result(
238
+ id,
239
+ 'error',
240
+ `Could not save ${labels[id]} settings. Check its MCP settings, then run lucidity setup-mcp ${id}.`,
241
+ ),
242
+ );
243
+ }
244
+ }
245
+ return results;
246
+ } finally {
247
+ unlinkSync(lock);
248
+ }
249
+ }
250
+ return { inspect, configure };
251
+ }
252
+
253
+ export async function runClientSetup(argv: string[]) {
254
+ if (argv.some((id) => !CLIENT_IDS.includes(id as ClientId)))
255
+ throw new Error('Usage: lucidity setup-mcp [claude] [codex]');
256
+ const setup = createClientSetup();
257
+ const selected = argv.length
258
+ ? (argv as ClientId[])
259
+ : (await setup.inspect())
260
+ .filter((c) => c.status !== 'missing')
261
+ .map((c) => c.id);
262
+ if (!selected.length)
263
+ throw new Error(
264
+ 'Install and open Claude Code or Codex first, then run lucidity setup-mcp again.',
265
+ );
266
+ const results = await setup.configure(selected);
267
+ for (const row of results) console.error(`${row.label}: ${row.message}`);
268
+ if (results.some((row) => row.status !== 'configured')) process.exitCode = 1;
269
+ }
package/src/mcp/config.ts CHANGED
@@ -5,7 +5,8 @@ import { CONFIG_DIR, type DaemonConfig } from '../config.js';
5
5
 
6
6
  const require = createRequire(import.meta.url);
7
7
 
8
- /** The scoped-MCP wiring passed to the executor for a chat/ask turn. */
8
+ /** Scoped MCP wiring for the daemon's Claude/Codex chat turns.
9
+ * Client registration is handled separately by guided setup. */
9
10
  export interface McpWiring {
10
11
  /** Path to the hermetic MCP config JSON (`--mcp-config`). */
11
12
  configPath: string;
@@ -0,0 +1,22 @@
1
+ import { pairedMcpEnvironment } from './pairedConfig.js';
2
+
3
+ // A dedicated stdio entry, independent of the running daemon and AI subscription.
4
+ // Both arguments and client config contain only the path to the saved connection.
5
+ try {
6
+ const [flag, configPath, ...extra] = process.argv.slice(2);
7
+ if (flag !== '--config' || !configPath || extra.length) {
8
+ throw new Error('Run lucidity setup-mcp to configure this MCP connection.');
9
+ }
10
+ Object.assign(process.env, pairedMcpEnvironment(configPath));
11
+ // Connecting task tools does not also grant access to local notes or memory.
12
+ delete process.env.LUCIDITY_NOTES_PATH;
13
+ delete process.env.LUCIDITY_VAULT_PATH;
14
+ } catch (error) {
15
+ console.error(
16
+ error instanceof Error
17
+ ? error.message
18
+ : 'Lucidity connection is unavailable.',
19
+ );
20
+ process.exit(1);
21
+ }
22
+ await import('@lucidity/mcp-server');
@@ -0,0 +1,44 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ /** Read at server startup so client settings never contain a credential. */
4
+ export function pairedMcpEnvironment(
5
+ configPath: string,
6
+ ): Record<string, string> {
7
+ let config;
8
+ try {
9
+ config = JSON.parse(readFileSync(configPath, 'utf8'));
10
+ } catch {
11
+ throw new Error('Run lucidity setup to connect your account first.');
12
+ }
13
+ if (
14
+ typeof config?.apiKey !== 'string' ||
15
+ !/^luc_[a-zA-Z0-9_]+$/.test(config.apiKey)
16
+ ) {
17
+ throw new Error('Your Lucidity connection is missing. Run lucidity setup.');
18
+ }
19
+ let url: URL;
20
+ try {
21
+ url = new URL(config.apiUrl ?? 'https://api.lucidity.my');
22
+ } catch {
23
+ throw new Error(
24
+ 'Your Lucidity API address is invalid. Check its settings.',
25
+ );
26
+ }
27
+ if (
28
+ url.username ||
29
+ url.password ||
30
+ url.pathname !== '/' ||
31
+ url.search ||
32
+ url.hash ||
33
+ (url.protocol !== 'https:' &&
34
+ !(
35
+ url.protocol === 'http:' &&
36
+ ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
37
+ ))
38
+ ) {
39
+ throw new Error(
40
+ 'Lucidity requires an HTTPS API address or a local development server.',
41
+ );
42
+ }
43
+ return { LUCIDITY_API_KEY: config.apiKey, LUCIDITY_API_URL: url.origin };
44
+ }
@@ -0,0 +1,122 @@
1
+ import { setupPage, setupIllustration } from '@lucidity/shared';
2
+
3
+ export const setupScript = `
4
+ let token = new URLSearchParams(location.hash.slice(1)).get('session');
5
+ if (token) { sessionStorage.setItem('luciditySetupSession', token); history.replaceState(null, '', '/'); }
6
+ token = token || sessionStorage.getItem('luciditySetupSession');
7
+ const content = document.getElementById('stage');
8
+ const error = document.getElementById('error');
9
+ let state = {}, selected = sessionStorage.getItem('luciditySetupProvider'), timer, busy = false, revision = 0;
10
+ let choices = {tasks:false, scheduledWork:false, clients:[]};
11
+ try { choices = {...choices, ...JSON.parse(sessionStorage.getItem('luciditySetupChoices') || '{}')}; } catch {}
12
+ const escape = s => String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
13
+ function showError(e) { error.textContent = e.message || 'Something went wrong. Please try again.'; error.hidden = false; }
14
+ async function request(path, body) {
15
+ const response = await fetch('/api/' + path, {method:'POST',headers:{'Content-Type':'application/json','X-Setup-Token':token || ''},body:JSON.stringify(body || {})});
16
+ const value = await response.json();
17
+ if(!response.ok) throw new Error(value.error || 'Please try again.');
18
+ return value;
19
+ }
20
+ function render(step, html) {
21
+ revision++; clearTimeout(timer); error.hidden = true;
22
+ 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); });
23
+ content.innerHTML = '<div class="section">' + html + '</div>';
24
+ const title = content.querySelector('h1'); if(title) { title.tabIndex = -1; title.focus({preventScroll:true}); }
25
+ }
26
+ 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; } }; }
27
+ function welcome() {
28
+ 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>');
29
+ button('begin', async () => { state = await request('begin'); connect(); });
30
+ }
31
+ function connect() {
32
+ 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>');
33
+ button('new', async () => { revision++; clearTimeout(timer); state = await request('begin', {restart:true}); connect(); });
34
+ poll();
35
+ }
36
+ async function poll() {
37
+ const expected = revision;
38
+ try {
39
+ const value = await request('poll');
40
+ if(expected !== revision) return;
41
+ if(value.status === 'approved') { state.account = value.account; return providers(); }
42
+ if(value.status === 'denied') { showError(new Error('This request was declined. Start a new request when you’re ready.')); return; }
43
+ error.hidden = true;
44
+ } catch(e) { if(expected !== revision) return; showError(e); if(/expired|already used/i.test(e.message)) return; }
45
+ timer = setTimeout(poll, 3000);
46
+ }
47
+ async function providers() {
48
+ 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>');
49
+ button('refresh', refreshProviders);
50
+ button('continue', async () => preferences());
51
+ try { await refreshProviders(); } catch(e) { showError(e); }
52
+ }
53
+ async function refreshProviders() {
54
+ const expected = revision;
55
+ const result = await request('providers');
56
+ if(expected !== revision) return;
57
+ const box = document.getElementById('providers'); box.innerHTML = '';
58
+ for (const p of result.providers) {
59
+ const ready = p.auth === 'authenticated';
60
+ const card = document.createElement('button'); card.className = 'card choice'; card.type = 'button';
61
+ card.setAttribute('aria-pressed', String(selected === p.id));
62
+ 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>';
63
+ 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; };
64
+ box.append(card);
65
+ if(selected === p.id) document.getElementById('continue').disabled = !ready;
66
+ }
67
+ }
68
+ function clientResults(rows) {
69
+ 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('');
70
+ }
71
+ async function clientChoices() {
72
+ const expected = revision;
73
+ const result = await request('clients');
74
+ if(expected !== revision) return;
75
+ const box = document.getElementById('clients');
76
+ box.innerHTML = '';
77
+ for(const c of result.clients) {
78
+ const available = c.status === 'available';
79
+ const card = document.createElement('label'); card.className = 'card checkrow';
80
+ 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>';
81
+ const input = card.querySelector('input');
82
+ input.checked = c.status === 'configured' || (available && Array.isArray(choices.clients) && choices.clients.includes(c.id));
83
+ input.onchange = () => { choices.clients = selectedClients(); sessionStorage.setItem('luciditySetupChoices', JSON.stringify(choices)); };
84
+ box.append(card);
85
+ }
86
+ }
87
+ function selectedClients() { return Array.from(document.querySelectorAll('#clients input:checked:not(:disabled)')).map(input => input.value); }
88
+ 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>';
89
+ async function existingClients() {
90
+ 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>');
91
+ button('refresh-clients', clientChoices);
92
+ button('add-clients', async () => {
93
+ const selected = selectedClients();
94
+ if(!selected.length) throw new Error('Choose an available app to connect.');
95
+ const result = await request('configure-clients', {clients:selected});
96
+ document.getElementById('client-results').innerHTML = clientResults(result.clients);
97
+ await clientChoices();
98
+ });
99
+ await clientChoices();
100
+ }
101
+ async function preferences() {
102
+ 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>');
103
+ 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));}; }
104
+ button('back', providers);
105
+ button('finish', async () => {
106
+ const result = await request('finish', {provider:selected,tasks:document.getElementById('tasks').checked,scheduledWork:document.getElementById('schedules').checked,clients:selectedClients()});
107
+ 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>');
108
+ document.getElementById('cancel').hidden = true;
109
+ });
110
+ try { await clientChoices(); } catch(e) { document.getElementById('clients').textContent = 'Could not check your apps. You can add them later with lucidity setup-mcp.'; }
111
+ }
112
+ 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; });
113
+ (async () => {
114
+ try { state = await request('state'); if(state.existing) { await existingClients(); } else if(state.code) connect(); else welcome(); }
115
+ catch(e) { showError(e); }
116
+ })();
117
+ `;
118
+
119
+ export function localSetupPage(nonce: string) {
120
+ 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>`;
121
+ return setupPage(body, setupScript, nonce);
122
+ }