sekura 0.4.2 → 0.5.1

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.
package/dist/catalogue.js CHANGED
@@ -54,13 +54,15 @@ export const ENDPOINT_SOURCE = fromEnv ? 'env' : fromSaved ? 'saved' : 'default'
54
54
  export const ORIGIN = new URL(ENDPOINT).origin;
55
55
  /** The server's host, where prose names it: sekura.ai, or dev.sekura.ai. */
56
56
  export const HOST = new URL(ENDPOINT).host;
57
+ export const link = (path) => `${ORIGIN}${path.startsWith('/') ? path : `/${path}`}`;
57
58
  export const SERVER_NAME = 'sekura';
58
59
  export const DOCS = `${ORIGIN}/connect/`;
59
60
  export const SETTINGS = `${ORIGIN}/app/settings`;
60
61
  export const KEYS_PAGE = `${SETTINGS} → Agents and API keys`;
62
+ export const SUPPORT = 'support@sekura.ai';
61
63
  /** One line naming the server, for a run that is not against production. */
62
64
  export const serverNote = () => ENDPOINT === PRODUCTION ? null
63
- : `Sekura server: ${ENDPOINT} (${ENDPOINT_SOURCE === 'env' ? 'from SEKURA_ENDPOINT' : 'where your saved key is from; set SEKURA_ENDPOINT to use another'})`;
65
+ : `Sekura server: ${ENDPOINT} (${ENDPOINT_SOURCE === 'env' ? 'from --endpoint or SEKURA_ENDPOINT' : 'where your saved key is from; set SEKURA_ENDPOINT to use another'})`;
64
66
  /** VS Code's user directory, where Copilot's `mcp.json` lives. */
65
67
  export function codeUserDir(h = home()) {
66
68
  switch (platform()) {
@@ -129,7 +131,7 @@ export const TOOLS = [
129
131
  id: 'tools-claude', name: 'Claude Code',
130
132
  detect: (h) => existsSync(join(h, '.claude')) || existsSync(join(h, '.claude.json')) || onPath('claude'),
131
133
  user: (h, key) => [
132
- { kind: 'command', bin: 'claude', add: ['mcp', 'add', '--transport', 'http', '-s', 'user', SERVER_NAME, ENDPOINT, ...(key ? ['--header', `Authorization: Bearer ${key}`] : [])], remove: ['mcp', 'remove', '-s', 'user', SERVER_NAME], get: ['mcp', 'get', SERVER_NAME] },
134
+ ...(key ? [] : [{ kind: 'command', bin: 'claude', add: ['mcp', 'add', '--transport', 'http', '-s', 'user', SERVER_NAME, ENDPOINT], remove: ['mcp', 'remove', '-s', 'user', SERVER_NAME], get: ['mcp', 'get', SERVER_NAME] }]),
133
135
  { kind: 'json', path: join(h, '.claude.json'), key: 'mcpServers', entry: { ...http, ...auth(key) } },
134
136
  ],
135
137
  project: (cwd) => [{ kind: 'json', path: join(cwd, '.mcp.json'), key: 'mcpServers', entry: http }],
@@ -228,7 +230,7 @@ export const TOOLS = [
228
230
  next: `start a new tabnine session.`,
229
231
  },
230
232
  {
231
- id: 'tools-devin', name: 'Devin Desktop and CLI',
233
+ id: 'tools-devin', name: 'Devin Desktop and the Devin CLI',
232
234
  detect: () => onPath('devin'),
233
235
  user: () => [{ kind: 'command', bin: 'devin', add: ['mcp', 'add', SERVER_NAME, ENDPOINT], remove: ['mcp', 'remove', SERVER_NAME], list: ['mcp', 'list'] }],
234
236
  signIn: `run devin mcp login ${SERVER_NAME}.`,
package/dist/cli.js CHANGED
@@ -10,35 +10,86 @@
10
10
  // agreed it signs in on a sekura.ai page (or with a code, where the browser
11
11
  // is on another device) and gives the resulting key to each tool, so none
12
12
  // of them asks, then helps with the Terms, the GitHub App and a repository.
13
- import { Command } from 'commander';
14
13
  import { createRequire } from 'node:module';
15
- import { initCommand } from './commands/init.js';
16
- import { statusCommand } from './commands/status.js';
17
- import { uninstallCommand } from './commands/uninstall.js';
18
- import { loginCommand, logoutCommand } from './commands/login.js';
19
- import { payCommand } from './commands/pay.js';
20
- import { billingCommand } from './commands/billing.js';
21
- import { DOCS } from './catalogue.js';
14
+ import { COMMANDS, ENDPOINT_FLAG, ENDPOINT_VAR, endpointFromArgv, parseOrigin, unknownCommand } from './origin.js';
15
+ const fail = (message, code = 1) => {
16
+ process.stderr.write(`\n ${message}\n\n`);
17
+ process.exit(code);
18
+ };
19
+ const flag = endpointFromArgv(process.argv.slice(2));
20
+ if (flag !== null) {
21
+ try {
22
+ process.env[ENDPOINT_VAR] = `${parseOrigin(flag)}/mcp`;
23
+ }
24
+ catch (e) {
25
+ fail(e.message);
26
+ }
27
+ }
28
+ else if (process.env[ENDPOINT_VAR]?.trim()) {
29
+ try {
30
+ process.env[ENDPOINT_VAR] = `${parseOrigin(process.env[ENDPOINT_VAR])}/mcp`;
31
+ }
32
+ catch (e) {
33
+ fail(`${ENDPOINT_VAR}: ${e.message}`);
34
+ }
35
+ }
36
+ const stray = unknownCommand(process.argv.slice(2));
37
+ if (stray !== null) {
38
+ fail(`Unknown command ${stray}. Commands: ${COMMANDS.filter((c) => c !== 'help').join(', ')}.\n To set up and scan from this terminal: npx sekura@latest, then npx sekura@latest scan owner/repo (quoted first, started only after you agree).`);
39
+ }
40
+ const { Command } = await import('commander');
41
+ const { initCommand } = await import('./commands/init.js');
42
+ const { statusCommand } = await import('./commands/status.js');
43
+ const { uninstallCommand } = await import('./commands/uninstall.js');
44
+ const { loginCommand, logoutCommand } = await import('./commands/login.js');
45
+ const { doctorCommand } = await import('./commands/doctor.js');
46
+ const { termsCommand } = await import('./commands/terms.js');
47
+ const { reposCommand } = await import('./commands/repos.js');
48
+ const { scanCommand } = await import('./commands/scan.js');
49
+ const { scansCommand } = await import('./commands/scans.js');
50
+ const { findingsCommand } = await import('./commands/findings.js');
51
+ const { reportCommand } = await import('./commands/report.js');
52
+ const { plansCommand, planCommand } = await import('./commands/plans.js');
53
+ const { payCommand } = await import('./commands/pay.js');
54
+ const { billingCommand } = await import('./commands/billing.js');
55
+ const { DOCS, SUPPORT } = await import('./catalogue.js');
56
+ const { Exit, exitCodeFor, messageFor } = await import('./exit.js');
57
+ const { SignedOut, ToolError } = await import('./api.js');
22
58
  const { version } = createRequire(import.meta.url)('../package.json');
23
59
  const program = new Command();
24
60
  program
25
61
  .name('sekura')
26
- .description(`Connect your coding tool to Sekura.\n\n npx sekura@latest init (a bare npx sekura@latest runs init too)\n\nDocumentation: ${DOCS}`)
62
+ .description(`Set up Sekura and scan your GitHub repositories from the terminal, and connect your coding tools.\n\n npx sekura@latest sign in, the Terms, the GitHub App, a repository and a first scan\n npx sekura@latest scan quote a scan; it starts only after you agree\n\nDocumentation: ${DOCS}\nSupport: ${SUPPORT}`)
27
63
  .version(version)
64
+ .option(`${ENDPOINT_FLAG} <url>`, `the Sekura server to use instead of https://sekura.ai, such as https://dev.sekura.ai or http://127.0.0.1:8787 (also ${ENDPOINT_VAR})`)
28
65
  .addCommand(initCommand, { isDefault: true })
29
66
  .addCommand(loginCommand)
30
- .addCommand(statusCommand)
31
- .addCommand(uninstallCommand)
32
67
  .addCommand(logoutCommand)
68
+ .addCommand(statusCommand)
69
+ .addCommand(doctorCommand)
70
+ .addCommand(termsCommand)
71
+ .addCommand(reposCommand)
72
+ .addCommand(scanCommand)
73
+ .addCommand(scansCommand)
74
+ .addCommand(findingsCommand)
75
+ .addCommand(reportCommand)
76
+ .addCommand(plansCommand)
77
+ .addCommand(planCommand)
78
+ .addCommand(billingCommand)
33
79
  .addCommand(payCommand)
34
- .addCommand(billingCommand);
80
+ .addCommand(uninstallCommand);
35
81
  try {
36
82
  await program.parseAsync(process.argv);
37
83
  }
38
84
  catch (e) {
39
- // Ctrl-C inside a prompt is an exit, not an error.
40
85
  if (e?.name === 'ExitPromptError')
41
86
  process.exit(130);
42
- process.stderr.write(`\n ${e.message}\n\n`);
43
- process.exit(1);
87
+ if (e instanceof Exit) {
88
+ if (e.message)
89
+ process.stderr.write(`\n ${e.message}\n\n`);
90
+ process.exit(e.code);
91
+ }
92
+ if (e instanceof SignedOut || e instanceof ToolError)
93
+ fail(messageFor(e), exitCodeFor(e));
94
+ fail(`${e.message}\n If this keeps happening, write to ${SUPPORT}.`);
44
95
  }
@@ -1,8 +1,33 @@
1
1
  import { Command } from 'commander';
2
2
  import { openBrowser, readKey } from '../auth.js';
3
- import { getBilling, getPlans, SignedOut } from '../api.js';
4
- import { cardLines, cardsFingerprint, paymentMethodsLink, planLines } from '../payment.js';
5
- import { cross, dot, say, tick, waitFor } from '../ui.js';
3
+ import { cliApi, getBilling, getPlans, isMissingRoute, isToolError, SignedOut } from '../api.js';
4
+ import { cardLines, cardsFingerprint, openableLink, paymentMethodsLink, planLines } from '../payment.js';
5
+ import { cross, dot, printJson, say, tick, waitFor } from '../ui.js';
6
+ const stripeLink = (raw) => (typeof raw === 'string' ? openableLink(raw)?.href ?? null : null);
7
+ export async function billingPage(key) {
8
+ const web = { link: paymentMethodsLink(), what: 'web' };
9
+ const old = (e) => isMissingRoute(e) || isToolError(e, 'cli_sign_in_required');
10
+ try {
11
+ const link = stripeLink((await cliApi(key, 'POST', '/billing/portal')).url);
12
+ if (link)
13
+ return { link, what: 'portal' };
14
+ }
15
+ catch (e) {
16
+ if (old(e))
17
+ return web;
18
+ if (!isToolError(e, 'no_customer'))
19
+ throw e;
20
+ }
21
+ try {
22
+ const link = stripeLink((await cliApi(key, 'POST', '/billing/card')).url);
23
+ return link ? { link, what: 'card' } : web;
24
+ }
25
+ catch (e) {
26
+ if (old(e))
27
+ return web;
28
+ throw e;
29
+ }
30
+ }
6
31
  function sayCards(b, heading) {
7
32
  const lines = cardLines(b);
8
33
  if (!lines.length) {
@@ -48,13 +73,33 @@ export async function runBilling(opts = {}) {
48
73
  return 1;
49
74
  }
50
75
  if (!opts.open) {
76
+ if (opts.json) {
77
+ let plans = [];
78
+ try {
79
+ plans = (await getPlans(key)).plans ?? [];
80
+ }
81
+ catch {
82
+ plans = [];
83
+ }
84
+ printJson({ cards: before.cards ?? [], plans });
85
+ return 0;
86
+ }
51
87
  sayCards(before, 'Saved cards:');
52
88
  await sayPlans(key);
53
89
  return 0;
54
90
  }
55
- const link = paymentMethodsLink();
91
+ let page;
92
+ try {
93
+ page = await billingPage(key);
94
+ }
95
+ catch (e) {
96
+ say(`${cross} ${e instanceof SignedOut ? `Your Sekura key no longer works (${e.message}); run npx sekura@latest login.` : `The card page could not be opened: ${e.message}`}`);
97
+ return 1;
98
+ }
99
+ const link = page.link;
56
100
  const opened = opts.browser === false ? false : openBrowser(link);
57
- say(opened ? `${tick} Opened your payment methods in the browser: ${link}` : `${dot} Open this link in a browser to add or change a card: ${link}`);
101
+ const where = page.what === 'card' ? 'Stripe\'s page for saving a card' : page.what === 'portal' ? 'your cards on Stripe' : 'your payment methods';
102
+ say(opened ? `${tick} Opened ${where} in the browser: ${link}` : `${dot} Open this link in a browser to add or change a card: ${link}`);
58
103
  const was = cardsFingerprint(before);
59
104
  let now = before;
60
105
  const minutes = Number(opts.timeout);
@@ -79,4 +124,5 @@ export const billingCommand = new Command('billing')
79
124
  .option('--open', 'open the page where cards are added or changed, then wait for the change')
80
125
  .option('--timeout <minutes>', 'how long to wait with --open', '5')
81
126
  .option('--no-browser', 'print the link instead of opening it')
127
+ .option('--json', 'print the saved cards and plans as JSON on stdout')
82
128
  .action(async (opts) => { process.exitCode = await runBilling(opts); });
@@ -6,16 +6,22 @@
6
6
  // they have seen what will be written. Nothing is written before the review
7
7
  // is agreed (unless --yes).
8
8
  import { Command } from 'commander';
9
- import { checkbox, confirm, select } from '@inquirer/prompts';
9
+ import { checkbox, select } from '@inquirer/prompts';
10
10
  import { realpathSync } from 'node:fs';
11
11
  import { homedir } from 'node:os';
12
12
  import { dirname, resolve } from 'node:path';
13
- import { DOCS, ENDPOINT, PENDING_KEY, TOOLS, carriesKey, home, serverNote, toolById } from '../catalogue.js';
13
+ import { DOCS, ENDPOINT, PENDING_KEY, TOOLS, carriesKey, home, link, serverNote, toolById } from '../catalogue.js';
14
14
  import { applyStep, buildPlan, describeStep, detectTools } from '../plan.js';
15
15
  import { verifyEndpoint } from '../verify.js';
16
- import { credentialsPath, readKey } from '../auth.js';
17
- import { checkAccount, existingSession, howToScan, nextSteps, pickRepository, runToolLogins, signInHere, toolLogin } from '../guide.js';
18
- import { banner, cross, dot, say, tick } from '../ui.js';
16
+ import { openLink } from '../open.js';
17
+ import { credentialsPath, readKey, readToolKey, savedCredentials } from '../auth.js';
18
+ import { tools as sekura } from '../api.js';
19
+ import { EXIT, Exit, exitCodeFor, messageFor } from '../exit.js';
20
+ import { howToScan, nextSteps } from '../guide.js';
21
+ import { currentSession, signInFresh, toolKeyFor, toolKeyName } from '../session.js';
22
+ import { ensureRepository, ensureTerms } from '../steps.js';
23
+ import { runScan } from './scan.js';
24
+ import { ask, banner, cross, dot, say, tick } from '../ui.js';
19
25
  /** The home folder (or the top of the disk) is no project: project scope
20
26
  * there would put AGENTS.md and .mcp.json in it for every tool to find. */
21
27
  export function isProjectDir(cwd) {
@@ -35,10 +41,96 @@ export function summary(o) {
35
41
  const sign = o.signIn === 'sign-in' ? ', and sign in to Sekura' : o.signIn === 'saved' ? ', with your saved Sekura key' : '';
36
42
  return `Connect ${and(o.names)} ${where}, ${o.skill ? 'with' : 'without'} the skill${sign}?`;
37
43
  }
44
+ export const toolFlags = () => TOOLS.map((t) => t.id.replace('tools-', ''));
45
+ export function unknownTools(names) {
46
+ return names.filter((n) => !toolById(`tools-${n.replace(/^tools-/, '')}`));
47
+ }
48
+ const shownKey = (session, login, signingIn) => {
49
+ if (!login)
50
+ return undefined;
51
+ if (session)
52
+ return session.kind === 'cli' ? readToolKey() ?? PENDING_KEY : session.key;
53
+ if (signingIn)
54
+ return PENDING_KEY;
55
+ const saved = readKey();
56
+ if (!saved)
57
+ return undefined;
58
+ const ownKey = !process.env.SEKURA_API_KEY?.trim() && savedCredentials()?.kind === 'cli';
59
+ return ownKey ? readToolKey() ?? PENDING_KEY : saved;
60
+ };
61
+ async function noScanYet(key) {
62
+ try {
63
+ return ((await sekura.listScans(key, { limit: 1 })).data.scans ?? []).length === 0;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ /**
70
+ * Whether this key can start the account's first scan, which the server says
71
+ * is free (freeScanAvailable). Only a key from
72
+ * the GitHub-code sign-in carries the cli scope; a key from the older browser
73
+ * sign-in is an ordinary connector key, and the server quotes it a paid $10
74
+ * scan with the account's first scan still unused (29 November 2026: dev's GitHub-code
75
+ * sign-in answered 404, the CLI fell back, and a person told "your first scan
76
+ * is free" was shown $10). So when that scan is still unused but this key cannot
77
+ * take it, the first-scan step sends the person to the website's first scan
78
+ * and never shows a price. The words come from the server's own answer, so the
79
+ * CLI still never calls a scan free on its own (guide.test.mjs).
80
+ */
81
+ async function freeScanElsewhere(key) {
82
+ try {
83
+ const a = (await sekura.getAccount(key)).data;
84
+ return a.freeScanAvailable === true && a.freeScanDoor !== 'cli';
85
+ }
86
+ catch {
87
+ return false;
88
+ }
89
+ }
90
+ async function firstScan(repo, opts, cwd, key) {
91
+ say();
92
+ if (await freeScanElsewhere(key)) {
93
+ const url = link('/app/start');
94
+ say(` Your first scan is free. Start it on the website: ${url}`);
95
+ if (await ask('Open it in your browser?', { default: true, short: 'Open it in your browser?' })) {
96
+ const o = openLink(url, { browser: opts.browser });
97
+ if (!o.opened)
98
+ say(` Open ${url} in your browser.`);
99
+ }
100
+ return undefined;
101
+ }
102
+ const go = await ask(`See the quote for a first scan of ${repo}? Nothing starts and nothing is charged unless you then agree.`, { default: true, short: 'See the quote?' });
103
+ if (!go) {
104
+ say(` No scan started. When you are ready: npx sekura@latest scan ${repo}`);
105
+ return undefined;
106
+ }
107
+ try {
108
+ await runScan(repo, { browser: opts.browser, cwd });
109
+ return undefined;
110
+ }
111
+ catch (e) {
112
+ if (e?.name === 'ExitPromptError')
113
+ throw e;
114
+ if (e instanceof Exit) {
115
+ if (e.message) {
116
+ say();
117
+ say(` ${e.message}`);
118
+ }
119
+ if (e.code === EXIT.declined) {
120
+ say(` When you are ready: npx sekura@latest scan ${repo}`);
121
+ return undefined;
122
+ }
123
+ return e.code;
124
+ }
125
+ say(`${cross} The scan could not be started: ${messageFor(e)}`);
126
+ return exitCodeFor(e);
127
+ }
128
+ }
38
129
  export async function runInit(opts) {
39
130
  const interactive = !opts.yes && !!process.stdin.isTTY && !!process.stderr.isTTY;
131
+ const unattended = !opts.yes && !interactive;
40
132
  const cwd = opts.cwd ?? process.cwd();
41
- banner();
133
+ banner({ login: opts.login });
42
134
  const note = serverNote();
43
135
  if (note) {
44
136
  say(` ${note}`);
@@ -49,12 +141,14 @@ export async function runInit(opts) {
49
141
  const detected = detectTools(cwd);
50
142
  let chosen;
51
143
  if (opts.tools) {
52
- chosen = opts.tools.split(',').map((s) => s.trim()).filter(Boolean).map((s) => (s.startsWith('tools-') ? s : `tools-${s}`));
53
- }
54
- else if (detected.length === 0) {
55
- say(' No supported coding tool was found on this machine.');
56
- say(` Sekura connects to Claude Code, Cursor, GitHub Copilot, OpenAI Codex and nearly forty other tools; the page has every one: ${DOCS}`);
57
- return { written: 0, byHand: 0, failed: 0 };
144
+ const names = opts.tools.split(',').map((s) => s.trim()).filter(Boolean);
145
+ const unknown = unknownTools(names);
146
+ if (unknown.length || !names.length) {
147
+ say(` Unknown tool ${unknown.map((n) => `'${n}'`).join(', ') || "''"}. Use one or more of: ${toolFlags().join(', ')}`);
148
+ say(' Nothing was changed.');
149
+ return { written: 0, byHand: 0, failed: 1 };
150
+ }
151
+ chosen = names.map((s) => (s.startsWith('tools-') ? s : `tools-${s}`));
58
152
  }
59
153
  else {
60
154
  chosen = detected.map((t) => t.id);
@@ -66,11 +160,20 @@ export async function runInit(opts) {
66
160
  say(' Nothing was changed.');
67
161
  return { written: 0, byHand: 0, failed: 1 };
68
162
  }
69
- let skill = opts.skill !== false;
163
+ let skill = opts.skill !== false && chosen.length > 0;
70
164
  let login = opts.login !== false;
71
165
  const hasKey = !!readKey();
166
+ if (!chosen.length) {
167
+ say(' No supported coding tool was found on this machine.');
168
+ say(` If you use one, name it: npx sekura@latest init --tools claude (or ${toolFlags().slice(1).join(', ')})`);
169
+ say(` Sekura connects to Claude Code, Cursor, GitHub Copilot, OpenAI Codex and nearly forty other tools; the page has every one: ${DOCS}`);
170
+ if (!login)
171
+ return { written: 0, byHand: 0, failed: 0 };
172
+ say(' Your Sekura account can still be set up from this terminal.');
173
+ say();
174
+ }
72
175
  // 2. One question, with Edit for the four it stands for.
73
- if (interactive) {
176
+ if (interactive && chosen.length) {
74
177
  const open = { tools: !opts.tools, scope: !opts.scope && inProject, skill: opts.skill === undefined, login: opts.login === undefined };
75
178
  if (open.tools) {
76
179
  say(` Found ${detected.length === 1 ? 'one tool' : `${detected.length} tools`}: ${detected.map((t) => t.name).join(', ')}`);
@@ -79,7 +182,7 @@ export async function runInit(opts) {
79
182
  if (open.tools || open.scope || open.skill || open.login) {
80
183
  const names = chosen.map((id) => toolById(id)?.name ?? id);
81
184
  const answer = await select({
82
- message: summary({ names, scope, skill, signIn: login && scope === 'user' ? (hasKey ? 'saved' : 'sign-in') : null }),
185
+ message: summary({ names, scope, skill, signIn: login ? (hasKey ? 'saved' : 'sign-in') : null }),
83
186
  choices: [
84
187
  { name: 'Yes', value: 'yes' },
85
188
  { name: 'Edit: choose the tools, where, the skill and the sign-in', value: 'edit' },
@@ -107,71 +210,85 @@ export async function runInit(opts) {
107
210
  ],
108
211
  });
109
212
  }
110
- // Every yes/no question stays on one line, its explanation printed
111
- // above it. A question that wraps leaves the cursor in the middle of a
112
- // word: the prompt library word-wraps the text but places the cursor
113
- // as if it were cut at the terminal's edge (29 November 2026, the
114
- // cursor sat on the "r" of "rule"). A wider terminal is not the fix;
115
- // the user's window decides that.
116
- if (open.skill) {
117
- say(' The sekura skill teaches the agent to quote every scan first.');
118
- skill = await confirm({ message: 'Install the skill?', default: true });
119
- }
120
- // Project files never carry the key (they are committed), so there
121
- // is no sign-in to ask about in project scope.
122
- if (open.login && scope === 'user') {
123
- say(hasKey
124
- ? ' Your tools can use your saved Sekura key, so they do not ask you to sign in.'
125
- : ' Sign in once, after you review the plan, and your tools will not have to.');
126
- login = await confirm({ message: hasKey ? 'Use the saved key?' : 'Sign in to Sekura?', default: true });
213
+ if (open.skill)
214
+ skill = await ask('Also install the sekura skill, which teaches the agent the quote-then-confirm rule?', { default: true, short: 'Install the skill?' });
215
+ if (open.login) {
216
+ login = await ask(hasKey
217
+ ? 'Use your saved Sekura sign-in, so your tools do not ask and your account is set up here?'
218
+ : 'Sign in to Sekura once you have reviewed the plan, so your tools do not have to and your account is set up here?', { default: true, short: hasKey ? 'Use the saved sign-in?' : 'Sign in to Sekura?' });
127
219
  }
128
220
  }
129
221
  }
130
222
  }
223
+ else if (interactive && opts.login === undefined) {
224
+ const go = await ask('Set up your Sekura account here: sign in, the Terms, the Sekura GitHub App and a first scan?', { default: true, short: 'Set up your account?' });
225
+ if (!go) {
226
+ say(' Nothing was changed.');
227
+ return { written: 0, byHand: 0, failed: 0 };
228
+ }
229
+ }
131
230
  // 3. A key already here is used as it is; a sign-in waits for the review.
132
231
  // A dry run never signs in.
133
232
  let session = null;
134
- const keyed = login && scope === 'user';
135
- if (keyed && hasKey) {
233
+ if (login && hasKey && !opts.dryRun) {
136
234
  say();
137
- session = await existingSession();
235
+ session = await currentSession();
236
+ }
237
+ const willSignIn = login && !session && interactive && !(opts.dryRun && hasKey);
238
+ const account = login && (!!session || willSignIn || (!!opts.dryRun && hasKey));
239
+ if (!chosen.length && !account) {
240
+ say(' There is no terminal to sign in from, so nothing was changed. Run npx sekura@latest in a terminal, or set SEKURA_API_KEY.');
241
+ say();
242
+ return { written: 0, byHand: 0, failed: 0 };
138
243
  }
139
- const willSignIn = keyed && !session && interactive;
140
244
  // 4. The plan, shown before anything happens, with a placeholder for the
141
245
  // key the sign-in will bring.
142
- const shown = buildPlan({ tools: chosen, scope, skill, cwd, key: session?.key ?? (willSignIn ? PENDING_KEY : undefined) });
246
+ const shown = buildPlan({ tools: chosen, scope, skill, cwd, key: shownKey(session, login, willSignIn) });
143
247
  say();
144
248
  say(opts.dryRun ? ' Dry run. This would:' : ' This will:');
145
249
  if (willSignIn)
146
- say(`${dot} sign in to Sekura in your browser (or with a code on another device) after you agree, and keep the key in ${credentialsPath()}`);
250
+ say(`${dot} sign in to Sekura with GitHub after you agree, and keep the key in ${credentialsPath()}`);
147
251
  for (const s of shown.steps)
148
252
  say(`${dot} ${describeStep(s, !!opts.dryRun)}`);
149
- if (willSignIn || session)
150
- for (const s of shown.steps) {
151
- const cmd = toolLogin(s);
152
- if (cmd && s.kind === 'tool')
153
- say(`${dot} ${s.tool.name}: ${opts.dryRun ? 'would ' : ''}run ${cmd}, approved in the browser`);
154
- }
155
253
  for (const s of shown.skipped)
156
254
  say(`${dot} ${s.tool.name}: skipped, ${s.why}`);
255
+ if (account)
256
+ say(`${dot} then set up your Sekura account here: the Terms, the Sekura GitHub App, a repository${opts.scan === false ? '' : ', and a first scan that is quoted first and starts only if you agree'}`);
157
257
  say(`${dot} touch nothing else: other servers, settings and files stay as they are`);
158
258
  say();
159
259
  if (opts.dryRun)
160
260
  return { written: 0, byHand: 0, failed: 0 };
161
- if (interactive && !(await confirm({ message: 'Apply?', default: true }))) {
261
+ if (unattended) {
262
+ say(' There is no terminal to ask in, so nothing was changed. Run the same command with --yes to apply this plan.');
263
+ say();
264
+ return { written: 0, byHand: 0, failed: 0 };
265
+ }
266
+ if (interactive && shown.steps.length && !(await ask('Apply?', { default: true, short: 'Apply?' }))) {
162
267
  say(' Nothing was changed.');
163
268
  return { written: 0, byHand: 0, failed: 0 };
164
269
  }
165
270
  // 5. Sign in, now that the plan is agreed, and put the key where the
166
- // placeholder was. Without a key the same entries are written plain, and
167
- // each tool signs in on first use, as it always could.
168
- let plan = shown;
271
+ // placeholder was.
169
272
  if (willSignIn) {
170
- session = await signInHere({ device: opts.device });
273
+ session = await signInFresh({ legacy: opts.legacyLogin, device: opts.device, browser: opts.browser });
171
274
  if (!session)
172
- say(' Applying the plan without a key instead: each tool signs in the first time it uses Sekura.');
173
- plan = buildPlan({ tools: chosen, scope, skill, cwd, key: session?.key });
275
+ throw new Exit(EXIT.notSignedIn, 'The sign-in did not finish, so nothing was changed. Run npx sekura@latest again to retry, or npx sekura@latest init --no-login to connect your tools without a key.');
276
+ }
277
+ let toolKey;
278
+ if (session && scope === 'user' && chosen.length) {
279
+ try {
280
+ const made = await toolKeyFor(session);
281
+ toolKey = made.key;
282
+ if (made.minted)
283
+ say(`${tick} Made a separate key for your coding tools ("${toolKeyName()}"); your sign-in key stays in ${credentialsPath()}`);
284
+ }
285
+ catch (e) {
286
+ if (session.kind === 'cli')
287
+ throw new Exit(EXIT.error, `Could not make a key for your coding tools, so nothing was changed: ${messageFor(e)}`);
288
+ toolKey = session.key;
289
+ }
174
290
  }
291
+ const plan = buildPlan({ tools: chosen, scope, skill, cwd, key: toolKey });
175
292
  // 6. Apply, one step at a time, saying what each did.
176
293
  say();
177
294
  let written = 0, byHand = 0, failed = 0;
@@ -206,33 +323,51 @@ export async function runInit(opts) {
206
323
  connected.push(s.tool);
207
324
  }
208
325
  }
209
- // Tools whose entry cannot carry the key sign in with their own command,
210
- // now, while the browser is signed in to sekura.ai. A sign-in agreed in
211
- // the one question covers them; a saved key asks first.
212
- if (session) {
213
- const steps = plan.steps.filter((s) => s.kind === 'tool' && signIns.has(s.tool.name));
214
- for (const name of await runToolLogins(steps, interactive, !willSignIn))
215
- signIns.set(name, null);
216
- }
217
326
  // 7. Verify the address.
327
+ let reachable = null;
218
328
  if (opts.verify !== false) {
219
- const v = await verifyEndpoint(ENDPOINT);
329
+ const v = await verifyEndpoint(ENDPOINT, undefined, session?.key);
330
+ reachable = v.ok;
220
331
  say(`${v.ok ? tick : cross} ${v.detail}`);
221
332
  }
222
333
  // 8. The account and a repository, with the key.
223
334
  let repo = null;
224
- if (session && signIns.size) {
335
+ let exit;
336
+ if (session) {
225
337
  say();
226
- await checkAccount(session, interactive, opts.wait);
227
- repo = await pickRepository(session, cwd, interactive, opts.wait);
338
+ const flags = { interactive, browser: opts.browser, wait: opts.wait, cwd, soft: true };
339
+ let terms = 'unknown';
340
+ try {
341
+ terms = await ensureTerms(session, flags);
342
+ }
343
+ catch (e) {
344
+ if (e?.name === 'ExitPromptError')
345
+ throw e;
346
+ say(`${dot} The Terms could not be checked just now: ${messageFor(e)}`);
347
+ }
348
+ try {
349
+ repo = await ensureRepository(session, flags);
350
+ }
351
+ catch (e) {
352
+ if (e?.name === 'ExitPromptError')
353
+ throw e;
354
+ say(`${cross} Could not list your repositories: ${messageFor(e)}`);
355
+ }
356
+ const unverified = session.account?.emailVerified === false;
357
+ if (unverified)
358
+ say(`${dot} Your email address is not verified yet, and a scan cannot start before that: ${session.account?.links?.dashboard ?? link('/app')}`);
359
+ const accountReady = (terms === 'current' || terms === 'accepted') && !unverified;
360
+ if (repo && accountReady && opts.scan !== false && interactive && await noScanYet(session.key))
361
+ exit = await firstScan(repo, opts, cwd, session.key);
228
362
  }
229
363
  // 9. What is left, per tool.
230
364
  say();
231
365
  if (signIns.size) {
232
366
  const ready = [...signIns].filter(([, how]) => how === null).map(([name]) => name);
233
367
  const pending = [...signIns].filter(([, how]) => how !== null);
368
+ const confirmed = !!session?.account || reachable === true;
234
369
  if (ready.length)
235
- say(`${tick} Ready, no sign-in needed: ${ready.join(', ')}`);
370
+ say(confirmed ? `${tick} Ready, no sign-in needed: ${ready.join(', ')}` : `${dot} Given your key, not yet confirmed because Sekura did not answer: ${ready.join(', ')}`);
236
371
  if (pending.length) {
237
372
  say(' Sign in once per tool:');
238
373
  for (const [name, how] of pending)
@@ -241,12 +376,16 @@ export async function runInit(opts) {
241
376
  say();
242
377
  nextSteps(connected);
243
378
  say();
244
- howToScan([...signIns.keys()], repo);
379
+ }
380
+ if (signIns.size || session) {
381
+ howToScan([...signIns.keys()], repo, session?.account);
245
382
  say();
246
383
  }
384
+ if (!session && login && signIns.size)
385
+ say(' To give your tools a key so they do not each ask you to sign in: run npx sekura@latest login');
247
386
  say(` Documentation and every other tool: ${DOCS}`);
248
387
  say();
249
- return { written, byHand, failed };
388
+ return { written, byHand, failed, ...(exit ? { exit } : {}) };
250
389
  }
251
390
  /** A --no-x flag's value only when it was typed: commander fills in true
252
391
  * otherwise, which would read as an answer to a question never asked. */
@@ -257,17 +396,20 @@ export function typedOnly(opts, cmd, names) {
257
396
  return opts;
258
397
  }
259
398
  export const initCommand = new Command('init')
260
- .description('Connect the coding tools on this machine to Sekura, and install the sekura skill. What a bare `sekura` runs.')
261
- .option('-y, --yes', 'apply without asking; every detected tool, user scope, with the skill, and the key in SEKURA_API_KEY or saved by sekura login')
399
+ .description('Set up Sekura from this terminal: connect your coding tools, sign in, accept the Terms, install the Sekura GitHub App, pick a repository and run a first scan. What a bare `sekura` runs.')
400
+ .option('-y, --yes', 'apply without asking; every detected tool, user scope, with the skill, and the key in SEKURA_API_KEY or saved by sekura login. Never accepts the Terms and never starts a scan')
262
401
  .option('--no-skill', 'the MCP server only: no skill, no guidance block')
263
402
  .option('--scope <scope>', 'user (every project) or project (this directory)', (v) => { if (v !== 'user' && v !== 'project')
264
403
  throw new Error('--scope is user or project'); return v; })
265
- .option('--tools <ids>', `only these, comma-separated: ${TOOLS.map((t) => t.id.replace('tools-', '')).join(', ')}`)
404
+ .option('--tools <ids>', `only these, comma-separated: ${toolFlags().join(', ')}`)
266
405
  .option('--dry-run', 'show the plan and change nothing; never signs in')
267
406
  .option('--no-verify', 'do not check that the Sekura server answers')
268
- .option('--no-login', 'do not sign in here; each tool signs in on first use (0.1.x behaviour)')
269
- .option('--device', 'sign in with a code on another device (the default over SSH and in containers)')
407
+ .option('--no-login', 'do not sign in here; each tool signs in on first use, and no account step runs')
408
+ .option('--legacy-login', 'sign in on a Sekura page instead of with a GitHub code')
409
+ .option('--device', 'with the Sekura-page sign-in: use a code on another device (the default over SSH and in containers)')
410
+ .option('--no-scan', 'stop after the repository: do not offer a first scan')
411
+ .option('--no-browser', 'print links instead of opening them')
270
412
  .action(async (opts, cmd) => {
271
413
  const r = await runInit(typedOnly(opts, cmd, ['skill', 'login']));
272
- process.exitCode = r.failed ? 1 : 0;
414
+ process.exitCode = r.failed ? EXIT.error : r.exit ?? EXIT.done;
273
415
  });