sekura 0.5.20 → 0.5.21

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/api.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // coding tools use. The server is stateless JSON-RPC over POST and answers
3
3
  // in plain JSON, so no session and no MCP library: one request per call.
4
4
  import { ENDPOINT, ORIGIN } from './catalogue.js';
5
- import { reach, serverTrouble } from './errors.js';
5
+ import { USER_AGENT, reach, serverTrouble } from './errors.js';
6
6
  export class SignedOut extends Error {
7
7
  constructor(detail) { super(detail); this.name = 'SignedOut'; }
8
8
  }
@@ -22,6 +22,15 @@ export class ToolError extends Error {
22
22
  this.status = o.status;
23
23
  }
24
24
  }
25
+ /**
26
+ * One form of a scan id everywhere: the bare uuid. The dashboard's links
27
+ * carry it as ss-<uuid>, so a person who copied one passed that to
28
+ * `report`, which echoed it back, while `scan show` printed the bare form:
29
+ * the same scan under two names (Varsha's 0.5.20 test, 1 December 2026,
30
+ * bug 7). Every command that takes a scan id accepts both, and every line
31
+ * that prints one prints this. The server reads both forms too.
32
+ */
33
+ export const bareScanId = (raw) => raw.trim().replace(/^ss-/i, '');
25
34
  export const isToolError = (e, code) => e instanceof ToolError && (code === undefined || e.code === code);
26
35
  let nextId = 1;
27
36
  const parsedBlock = (content) => {
@@ -46,7 +55,7 @@ const firstText = (content) => {
46
55
  export async function call(key, op, args = {}, opts = {}) {
47
56
  const r = await reach(ENDPOINT, {
48
57
  method: 'POST',
49
- headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
58
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'user-agent': USER_AGENT },
50
59
  body: JSON.stringify({ jsonrpc: '2.0', id: nextId++, method: 'tools/call', params: { name: op, arguments: args } }),
51
60
  signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
52
61
  });
@@ -72,7 +81,14 @@ export async function call(key, op, args = {}, opts = {}) {
72
81
  const result = body.result ?? {};
73
82
  const structured = result.structuredContent && typeof result.structuredContent === 'object' ? result.structuredContent : null;
74
83
  const text = firstText(result.content);
75
- if (result.isError) {
84
+ // A refusal comes in two forms. The server marks it isError for this CLI
85
+ // (it knows the user-agent), and answers other clients with ok: false and
86
+ // the code in structuredContent, without isError, so an agent shows a 409
87
+ // or the Checkout hand-off as an answer rather than a fault. Read only
88
+ // isError, a CLI whose user-agent was lost would take a refusal for a
89
+ // quote and ask "Do you agree?" over it (coordinator, 1 December 2026).
90
+ const refused = structured?.ok === false && typeof structured.code === 'string';
91
+ if (result.isError || refused) {
76
92
  const data = structured ?? parsedBlock(result.content) ?? {};
77
93
  const link = typeof data.link === 'string' ? data.link : undefined;
78
94
  const sentence = link && text.endsWith(` ${link}`) ? text.slice(0, -link.length - 1) : text;
@@ -90,7 +106,7 @@ export const CLI_API = '/api/cli/v1';
90
106
  export async function cliFetch(key, method, path, body, opts = {}) {
91
107
  return reach(`${ORIGIN}${CLI_API}${path}`, {
92
108
  method,
93
- headers: { authorization: `Bearer ${key}`, accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}) },
109
+ headers: { authorization: `Bearer ${key}`, accept: 'application/json', 'user-agent': USER_AGENT, ...(body ? { 'content-type': 'application/json' } : {}) },
94
110
  ...(body ? { body: JSON.stringify(body) } : {}),
95
111
  signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
96
112
  });
package/dist/auth.js CHANGED
@@ -20,7 +20,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, chmodSync }
20
20
  import { hostname } from 'node:os';
21
21
  import { dirname } from 'node:path';
22
22
  import { ENDPOINT, HOST, PRODUCTION, credentialsPath, usableEndpoint } from './catalogue.js';
23
- import { reach, refusal } from './errors.js';
23
+ import { reach, refusal, withAgent } from './errors.js';
24
24
  import { hasBrowser, openBrowser } from './open.js';
25
25
  import { DEVICE_GRANT, deviceSignIn, remoteSession } from './device.js';
26
26
  export const ISSUER = new URL(ENDPOINT).origin;
@@ -189,7 +189,7 @@ catch {
189
189
  export async function revokeKey(key, endpoint = ENDPOINT) {
190
190
  const origin = new URL(endpoint).origin;
191
191
  try {
192
- const m = await fetch(`${origin}/.well-known/oauth-authorization-server`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(10_000) });
192
+ const m = await fetch(`${origin}/.well-known/oauth-authorization-server`, withAgent({ headers: { accept: 'application/json' }, signal: AbortSignal.timeout(10_000) }));
193
193
  const doc = m.ok ? (await m.json().catch(() => null)) : null;
194
194
  if (typeof doc?.revocation_endpoint !== 'string')
195
195
  return 'unsupported';
@@ -202,12 +202,12 @@ export async function revokeKey(key, endpoint = ENDPOINT) {
202
202
  }
203
203
  if (at.origin !== origin)
204
204
  return 'unsupported';
205
- const r = await fetch(at.href, {
205
+ const r = await fetch(at.href, withAgent({
206
206
  method: 'POST',
207
207
  headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
208
208
  body: new URLSearchParams({ token: key, token_type_hint: 'access_token' }).toString(),
209
209
  signal: AbortSignal.timeout(10_000),
210
- });
210
+ }));
211
211
  return r.ok ? 'revoked' : 'failed';
212
212
  }
213
213
  catch {
package/dist/cli.js CHANGED
@@ -98,7 +98,13 @@ catch (e) {
98
98
  }
99
99
  process.exit(e.code);
100
100
  }
101
- if (e instanceof SignedOut || e instanceof ToolError)
101
+ // A refusal that no command turned into an Exit is still the person's to
102
+ // read, with its commands (Varsha's 0.5.20 test, 1 December 2026).
103
+ if (e instanceof ToolError) {
104
+ const { refusalText } = await import('./commands/shared.js');
105
+ fail(refusalText(e), exitCodeFor(e));
106
+ }
107
+ if (e instanceof SignedOut)
102
108
  fail(messageFor(e), exitCodeFor(e));
103
109
  fail(`${e.message}\n If this keeps happening, write to ${SUPPORT}.`);
104
110
  }
@@ -1,5 +1,5 @@
1
1
  import { Command } from 'commander';
2
- import { tools } from '../api.js';
2
+ import { bareScanId, tools } from '../api.js';
3
3
  import { Exit, EXIT } from '../exit.js';
4
4
  import { requireKey } from '../flow.js';
5
5
  import { dot, print, printJson, say, tick } from '../ui.js';
@@ -8,8 +8,9 @@ const line = (f, i) => {
8
8
  const head = `${i + 1}. [${f.severity}] ${f.title}${f.location ? ` — ${f.location}` : ''}`;
9
9
  return f.description && f.description !== f.title ? [head, ` ${f.description}`] : [head];
10
10
  };
11
- export async function runFindings(scanId, opts = {}) {
11
+ export async function runFindings(given, opts = {}) {
12
12
  const key = requireKey();
13
+ const scanId = bareScanId(given);
13
14
  const limit = opts.limit === undefined ? 20 : Number(opts.limit);
14
15
  if (!Number.isInteger(limit) || limit < 1 || limit > 50)
15
16
  throw new Exit(EXIT.error, '--limit takes a whole number from 1 to 50.');
@@ -18,17 +19,18 @@ export async function runFindings(scanId, opts = {}) {
18
19
  printJson(data);
19
20
  return;
20
21
  }
22
+ const id = bareScanId(data.scanId ?? scanId);
21
23
  if (!data.total) {
22
- say(`${tick} Scan ${data.scanId} has no findings.`);
24
+ say(`${tick} Scan ${id} has no findings.`);
23
25
  return;
24
26
  }
25
- say(`${tick} Scan ${data.scanId}: ${data.total} ${data.total === 1 ? 'finding' : 'findings'} (${severityWords(data.counts)})`);
27
+ say(`${tick} Scan ${id}: ${data.total} ${data.total === 1 ? 'finding' : 'findings'} (${severityWords(data.counts)})`);
26
28
  data.findings.forEach((f, i) => { for (const l of line(f, i))
27
29
  print(l); });
28
30
  if (data.total > data.findings.length)
29
- say(`${dot} The ${data.findings.length} most severe are shown. The report has all ${data.total}, with the proof for each: npx sekura@latest report ${data.scanId}`);
31
+ say(`${dot} The ${data.findings.length} most severe are shown. The report has all ${data.total}, with the proof for each: npx sekura@latest report ${id}`);
30
32
  else
31
- say(`${dot} The report has the proof for each: npx sekura@latest report ${data.scanId}`);
33
+ say(`${dot} The report has the proof for each: npx sekura@latest report ${id}`);
32
34
  }
33
35
  export const findingsCommand = new Command('findings')
34
36
  .description('Show a finished scan\'s findings, most severe first.')
@@ -179,6 +179,8 @@ export async function runInit(opts) {
179
179
  // are the defaults; a flag answers its own question.
180
180
  const detected = detectTools(cwd);
181
181
  let chosen;
182
+ /** The tools step 1 named one by one; step 2 does not name them again. */
183
+ const listed = new Set();
182
184
  if (opts.tools) {
183
185
  const names = opts.tools.split(',').map((s) => s.trim()).filter(Boolean);
184
186
  const unknown = unknownTools(names);
@@ -192,6 +194,11 @@ export async function runInit(opts) {
192
194
  else {
193
195
  chosen = detected.map((t) => t.id);
194
196
  step('Detect tools');
197
+ // The tools already connected, by name, and the rest in one line. All
198
+ // thirteen were listed, twelve as "needs setup", and step 2 listed the
199
+ // same names again above "Connect these 13 tools?" (Varsha's 0.5.20
200
+ // test, 1 December 2026, W1 and W2).
201
+ const others = [];
195
202
  for (const t of detected) {
196
203
  let present = false;
197
204
  try {
@@ -201,7 +208,16 @@ export async function runInit(opts) {
201
208
  catch {
202
209
  present = false;
203
210
  }
204
- say(present === true ? `${tick} ${t.name} ${c.dim('connected')}` : `${warn} ${t.name} ${c.dim('needs setup')}`);
211
+ if (present === true) {
212
+ say(`${tick} ${t.name} ${c.dim('connected')}`);
213
+ listed.add(t.id);
214
+ }
215
+ else
216
+ others.push(t.name);
217
+ }
218
+ if (others.length) {
219
+ const n = others.length;
220
+ say(`${warn} ${n}${listed.size ? ' other' : ''} ${n === 1 ? 'tool' : 'tools'} found; you choose ${n === 1 ? 'it' : 'them'} in the next step.`);
205
221
  }
206
222
  const missing = TOOLS.length - detected.length;
207
223
  if (missing > 0)
@@ -234,13 +250,16 @@ export async function runInit(opts) {
234
250
  step('Choose tools');
235
251
  const names = chosen.map((id) => toolById(id)?.name ?? id);
236
252
  const parts = summaryParts({ names, scope, skill, signIn: login ? (hasKey ? 'saved' : 'sign-in') : null });
237
- for (const l of parts.details.split('\n'))
253
+ // The names line only for tools step 1 did not name (W2).
254
+ const namedAbove = chosen.every((id) => listed.has(id));
255
+ const lines = parts.details.split('\n');
256
+ for (const l of namedAbove && lines.length > 1 ? lines.slice(1) : lines)
238
257
  say(` ${c.dim(l.trim())}`);
239
258
  const answer = await select({
240
259
  message: parts.question,
241
260
  choices: [
242
261
  { name: 'Yes', value: 'yes' },
243
- { name: 'Choose: tools, where, skill, sign-in', value: 'edit' },
262
+ { name: 'Let me choose', value: 'edit' },
244
263
  { name: 'No, change nothing', value: 'no' },
245
264
  ],
246
265
  });
@@ -269,9 +288,13 @@ export async function runInit(opts) {
269
288
  if (open.skill)
270
289
  skill = await ask('Install the skill? It teaches your agent to quote every scan first.', { default: true, short: 'Install the skill?' });
271
290
  if (open.login) {
291
+ // No here leaves login false: the tools get no key and each signs in
292
+ // on its own the first time it is used, and the Terms, GitHub App
293
+ // and repository steps are left for later. "Use your saved
294
+ // sign-in? Your tools use it too." said neither (W4).
272
295
  login = await ask(hasKey
273
- ? 'Use your saved sign-in? Your tools use it too.'
274
- : 'Sign in to Sekura after the review? Your tools use the same sign-in.', { default: true, short: hasKey ? 'Use the saved sign-in?' : 'Sign in to Sekura?' });
296
+ ? 'Give your coding tools this sign-in? (No: each tool signs in on its own, and the account steps here are skipped)'
297
+ : 'Sign in to Sekura after the review? Your tools use the same sign-in.', { default: true, short: hasKey ? 'Give your coding tools this sign-in?' : 'Sign in to Sekura?' });
275
298
  }
276
299
  }
277
300
  }
@@ -11,8 +11,8 @@ import { credentialsPath, forgetKey, hostOf, readSavedKey, savedCredentials } fr
11
11
  import { EXIT, Exit } from '../exit.js';
12
12
  import { howToScan, toolLogin } from '../guide.js';
13
13
  import { revokeSessionKey, toolKeyFor, toolKeyName } from '../session.js';
14
- import { ensureSignedIn, ensureTerms, TERMS_LATER } from '../steps.js';
15
- import { defaultRepository } from '../state.js';
14
+ import { ensureSignedIn, ensureTerms, scannableDefault, TERMS_LATER } from '../steps.js';
15
+ import { defaultRepository, setDefaultRepository } from '../state.js';
16
16
  import { cross, dot, say, tick } from '../ui.js';
17
17
  /** A tool name that names two things ("Devin Desktop and the Devin CLI")
18
18
  * takes a plural verb: "Devin Desktop and the Devin CLI keep their own
@@ -25,7 +25,7 @@ export async function runLogin(opts) {
25
25
  const note = serverNote();
26
26
  if (note)
27
27
  say(` ${note}`);
28
- const session = await ensureSignedIn({ interactive, legacy: opts.legacyLogin, device: opts.device, browser: opts.browser });
28
+ const session = await ensureSignedIn({ interactive, legacy: opts.legacyLogin, device: opts.device, browser: opts.browser, already: true });
29
29
  let toolKey = session.key;
30
30
  try {
31
31
  const t = await toolKeyFor(session);
@@ -85,7 +85,7 @@ export async function runLogin(opts) {
85
85
  }
86
86
  if (names.length) {
87
87
  say();
88
- howToScan(names, defaultRepository(), a);
88
+ howToScan(names, await scannableDefault(session.key), a);
89
89
  }
90
90
  say();
91
91
  return failed;
@@ -114,6 +114,14 @@ export async function runLogout() {
114
114
  say(r === 'revoked' ? `${tick} Revoked your sign-in key on ${hostOf(ENDPOINT)}` : `${dot} ${hostOf(ENDPOINT)} did not revoke your sign-in key from here. Revoke it at ${KEYS_PAGE}.`);
115
115
  }
116
116
  say(forgetKey() ? `${tick} Removed it from ${credentialsPath()}` : `${dot} No saved key at ${credentialsPath()}`);
117
+ // The default repository belongs to the account that chose it: kept, it
118
+ // was named to the next account that signed in here (Varsha's 0.5.20
119
+ // test, 1 December 2026, bug 17).
120
+ const repository = defaultRepository();
121
+ if (repository) {
122
+ setDefaultRepository(null);
123
+ say(`${tick} Forgot your default repository, ${repository}`);
124
+ }
117
125
  say(saved.kind === 'cli'
118
126
  ? ` The key your coding tools use was made from this sign-in, so Sekura ends it too. Run npx sekura@latest to sign in again and give them a new one.`
119
127
  : ` Tools that were given the key keep it until you run npx sekura@latest uninstall. To end it everywhere: ${KEYS_PAGE}.`);
@@ -1,11 +1,11 @@
1
1
  import { Command } from 'commander';
2
2
  import { input } from '@inquirer/prompts';
3
- import { call, getPlans, isToolError, tools } from '../api.js';
3
+ import { bareScanId, call, getPlans, isToolError, tools } from '../api.js';
4
4
  import { EXIT, Exit, messageFor } from '../exit.js';
5
5
  import { confirmQuote, requireKey, startWithPayment } from '../flow.js';
6
6
  import { monthlyName } from '../payment.js';
7
7
  import { select, cross, dot, interactive, printJson, printTable, say } from '../ui.js';
8
- import { afterStart, ready, resolveRepository, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
8
+ import { afterStart, alreadyHints, ready, resolveRepository, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
9
9
  const when = (iso) => (iso ? iso.replace('T', ' ').slice(0, 16) : '');
10
10
  const stateOf = (p) => p.status === 'pending' ? 'waiting on a payment'
11
11
  : p.status === 'canceled' ? 'ended'
@@ -19,7 +19,7 @@ const COLUMNS = [
19
19
  { header: 'SCHEDULE', value: (p) => (monthlyName(p) ? p.schedule?.description ?? '' : '') },
20
20
  { header: 'STATE', value: stateOf },
21
21
  { header: 'NEXT RUN (UTC)', value: (p) => when(p.nextRunAt) },
22
- { header: 'LAST SCAN', value: (p) => (p.lastScan ? `${p.lastScan.id} ${p.lastScan.status}` : '') },
22
+ { header: 'LAST SCAN', value: (p) => (p.lastScan ? `${bareScanId(p.lastScan.id)} ${p.lastScan.status}` : '') },
23
23
  ];
24
24
  export async function runPlans(opts = {}) {
25
25
  const key = requireKey();
@@ -186,6 +186,17 @@ export async function runPlanStart(repo, opts = {}) {
186
186
  const tier = tierOf(opts.tier);
187
187
  const command = `npx sekura@latest plan start ${repository}`;
188
188
  await ready(async () => {
189
+ // Asked first, as plan change does: the four schedule questions came
190
+ // before "already on a monthly plan" (Varsha's 0.5.20 test, 1 December
191
+ // 2026, bug 14). The plans list not answering is no reason to stop; the
192
+ // server refuses a second plan itself.
193
+ if (!opts.confirm) {
194
+ const plan = await planFor(key, repository).catch(() => undefined);
195
+ if (plan && liveMonthly(plan)) {
196
+ const sched = plan.schedule?.description ? `, scanned ${plan.schedule.description}` : '';
197
+ throw new Exit(EXIT.error, `${repository} is already on ${monthlyName(plan) === 'Your monthly plan' ? 'a monthly plan' : monthlyName(plan)}${sched}. Nothing was started or charged.\n ${alreadyHints(repository)}`, { code: 'already_always', planId: plan.id, repository });
198
+ }
199
+ }
189
200
  const agreed = await quoteSchedule(opts, async () => (opts.confirm ? { repository } : { repository, tier, schedule: await scheduleFor(tier, opts, command) }), (args) => confirmQuote({
190
201
  op: 'quoteAlways',
191
202
  args,
@@ -195,12 +206,16 @@ export async function runPlanStart(repo, opts = {}) {
195
206
  question: `Do you agree, and start ${tier === 'pro' ? 'More frequently' : 'Weekly'} for ${repository}?`,
196
207
  sayQuote: (text) => sayText(text, repository),
197
208
  }));
198
- if (agreed.kind === 'quoted')
209
+ if (agreed.kind !== 'agreed')
199
210
  return;
200
211
  const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
201
212
  await afterStart(key, outcome, { what: `The plan for ${repository}`, repository, watch: opts.watch, report: opts.report, output: opts.output, json: opts.json });
202
- });
213
+ }, { repository });
203
214
  }
215
+ /** A monthly plan that is running and not cancelled: the server's test for
216
+ * already_always (sekura-www, src/connector/always.ts). A cancelled plan
217
+ * can be started again. */
218
+ export const liveMonthly = (p) => p.status === 'active' && p.plan === 'always' && !p.canceledAt;
204
219
  async function planFor(key, repository) {
205
220
  const [owner, name] = repository.toLowerCase().split('/');
206
221
  const plans = (await getPlans(key)).plans ?? [];
@@ -227,7 +242,7 @@ export async function runPlanSchedule(repo, opts = {}) {
227
242
  question: `Change the schedule for ${repository}?`,
228
243
  sayQuote: (text) => sayText(text, repository),
229
244
  }));
230
- if (agreed.kind === 'quoted')
245
+ if (agreed.kind !== 'agreed')
231
246
  return;
232
247
  const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
233
248
  if (outcome.kind === 'started') {
@@ -238,7 +253,7 @@ export async function runPlanSchedule(repo, opts = {}) {
238
253
  return;
239
254
  }
240
255
  await afterStart(key, outcome, { what: `The new schedule for ${repository}`, repository, watch: false, json: opts.json });
241
- });
256
+ }, { repository });
242
257
  }
243
258
  /**
244
259
  * Move a repository between Weekly and More frequently (Sudhir, 29 November
@@ -276,7 +291,7 @@ export async function runPlanChange(repo, opts = {}) {
276
291
  question: `Move ${repository} to ${toName}?`,
277
292
  sayQuote: (text) => sayText(text, repository),
278
293
  }));
279
- if (agreed.kind === 'quoted')
294
+ if (agreed.kind !== 'agreed')
280
295
  return;
281
296
  const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
282
297
  if (outcome.kind === 'started') {
@@ -287,7 +302,7 @@ export async function runPlanChange(repo, opts = {}) {
287
302
  return;
288
303
  }
289
304
  await afterStart(key, outcome, { what: `The plan change for ${repository}`, repository, watch: false, json: opts.json });
290
- });
305
+ }, { repository });
291
306
  }
292
307
  export async function runPlanRun(repo, opts = {}) {
293
308
  const key = requireKey();
@@ -303,11 +318,11 @@ export async function runPlanRun(repo, opts = {}) {
303
318
  question: `Start a scan of ${repository} now?`,
304
319
  sayQuote: (text) => sayText(text, repository),
305
320
  });
306
- if (agreed.kind === 'quoted')
321
+ if (agreed.kind !== 'agreed')
307
322
  return;
308
323
  const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
309
324
  await afterStart(key, outcome, { what: `The scan of ${repository}`, repository, watch: opts.watch, report: opts.report, output: opts.output, json: opts.json });
310
- });
325
+ }, { repository });
311
326
  }
312
327
  export async function runPlanCancel(repo, opts = {}) {
313
328
  const key = requireKey();
@@ -322,15 +337,16 @@ export async function runPlanCancel(repo, opts = {}) {
322
337
  command: `npx sekura@latest plan cancel ${repository}`,
323
338
  question: `Cancel the plan for ${repository}?`,
324
339
  sayQuote: (text) => sayText(text, repository),
340
+ nothing: 'Nothing was cancelled.',
325
341
  });
326
- if (agreed.kind === 'quoted')
342
+ if (agreed.kind !== 'agreed')
327
343
  return;
328
344
  const reply = await call(key, agreed.confirmOperation, withoutConfirm(agreed.confirmArguments));
329
345
  if (opts.json)
330
346
  printJson(reply.data);
331
347
  else
332
348
  sayText(reply.text, repository);
333
- });
349
+ }, { repository });
334
350
  }
335
351
  const REPO_ARG = 'owner/repo; the default is your saved repository, then this folder\'s GitHub remote';
336
352
  const start = withFollowOptions(withScheduleOptions(withQuoteOptions(new Command('start')
@@ -1,11 +1,13 @@
1
1
  import { Command } from 'commander';
2
2
  import { requireKey } from '../flow.js';
3
+ import { bareScanId } from '../api.js';
3
4
  import { pathToFileURL } from 'node:url';
4
5
  import { NOT_OPENED, SEKURA_HOSTS, openLink, openTrusted } from '../open.js';
5
6
  import { dot, printJson, say, tick } from '../ui.js';
6
7
  import { fetchReport, ready, saySaved } from './shared.js';
7
- export async function runReport(scanId, opts = {}) {
8
+ export async function runReport(given, opts = {}) {
8
9
  const key = requireKey();
10
+ const scanId = bareScanId(given);
9
11
  const saved = await ready(() => fetchReport(key, scanId, opts.output));
10
12
  if (opts.json)
11
13
  printJson(saved);
@@ -1,9 +1,9 @@
1
1
  import { Command } from 'commander';
2
- import { call, tools } from '../api.js';
2
+ import { bareScanId, call, tools } from '../api.js';
3
3
  import { confirmQuote, requireKey, scanFinished, startWithPayment, watchScan } from '../flow.js';
4
4
  import { EXIT, Exit } from '../exit.js';
5
5
  import { dot, printJson, say } from '../ui.js';
6
- import { afterStart, merged, ready, resolveRepository, sayFindings, sayScan, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
6
+ import { afterStart, merged, ready, stoppedWatching, resolveRepository, sayFindings, sayScan, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
7
7
  export async function runScan(repo, opts = {}) {
8
8
  const key = requireKey();
9
9
  const repository = resolveRepository(repo, opts.cwd);
@@ -18,14 +18,15 @@ export async function runScan(repo, opts = {}) {
18
18
  question: `Do you agree, and start the scan of ${repository}?`,
19
19
  sayQuote: (text) => sayText(text, repository),
20
20
  });
21
- if (agreed.kind === 'quoted')
21
+ if (agreed.kind !== 'agreed')
22
22
  return;
23
23
  const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
24
24
  await afterStart(key, outcome, { what: `The scan of ${repository}`, repository, watch: opts.watch, report: opts.report, output: opts.output, json: opts.json, intervalMs: opts.intervalMs, timeoutMs: opts.timeoutMs });
25
- });
25
+ }, { repository });
26
26
  }
27
- export async function runScanShow(scanId, opts = {}) {
27
+ export async function runScanShow(given, opts = {}) {
28
28
  const key = requireKey();
29
+ const scanId = bareScanId(given);
29
30
  let detail = (await ready(() => tools.getScan(key, { scanId }))).data;
30
31
  if (opts.watch && !scanFinished(detail.scan.status)) {
31
32
  const w = await watchScan(key, scanId, {
@@ -39,7 +40,7 @@ export async function runScanShow(scanId, opts = {}) {
39
40
  if (w.result !== 'done') {
40
41
  if (opts.json)
41
42
  printJson(detail);
42
- throw new Exit(EXIT.stoppedWaiting, `${w.result === 'skipped' ? 'Stopped watching' : 'Still running after the wait'}; the scan carries on.`, { scanId, status: w.status });
43
+ throw new Exit(EXIT.stoppedWaiting, stoppedWatching(w.result, scanId), { scanId, status: w.status });
43
44
  }
44
45
  }
45
46
  if (opts.json) {
@@ -52,8 +53,9 @@ export async function runScanShow(scanId, opts = {}) {
52
53
  say(`${dot} The full report: npx sekura@latest report ${scanId}`);
53
54
  }
54
55
  }
55
- export async function runScanCancel(scanId, opts = {}) {
56
+ export async function runScanCancel(given, opts = {}) {
56
57
  const key = requireKey();
58
+ const scanId = bareScanId(given);
57
59
  const args = { scanId };
58
60
  await ready(async () => {
59
61
  const agreed = await confirmQuote({
@@ -63,9 +65,10 @@ export async function runScanCancel(scanId, opts = {}) {
63
65
  flags: opts,
64
66
  command: `npx sekura@latest scan cancel ${scanId}`,
65
67
  question: 'Cancel this scan?',
66
- sayQuote: sayText,
68
+ sayQuote: (text) => sayText(text),
69
+ nothing: 'Nothing was cancelled.',
67
70
  });
68
- if (agreed.kind === 'quoted')
71
+ if (agreed.kind !== 'agreed')
69
72
  return;
70
73
  const reply = await call(key, agreed.confirmOperation, withoutConfirm(agreed.confirmArguments));
71
74
  if (opts.json)
@@ -1,12 +1,12 @@
1
1
  import { Command } from 'commander';
2
- import { tools } from '../api.js';
2
+ import { bareScanId, tools } from '../api.js';
3
3
  import { Exit, EXIT } from '../exit.js';
4
4
  import { requireKey } from '../flow.js';
5
5
  import { dot, printTable, say } from '../ui.js';
6
6
  import { ready } from './shared.js';
7
7
  const day = (iso) => (iso ? iso.replace('T', ' ').slice(0, 16) : '');
8
8
  const COLUMNS = [
9
- { header: 'SCAN ID', value: (s) => s.id },
9
+ { header: 'SCAN ID', value: (s) => bareScanId(s.id) },
10
10
  { header: 'REPOSITORY', value: (s) => (s.target_owner && s.target_repo ? `${s.target_owner}/${s.target_repo}` : '') },
11
11
  { header: 'STATUS', value: (s) => s.status },
12
12
  { header: 'FINDINGS', value: (s) => (s.status === 'done' ? s.findings_count ?? 0 : ''), align: 'right' },
@@ -1,9 +1,9 @@
1
1
  import { writeFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
- import { CLI_API, ToolError, cliApi, cliFetch, isMissingRoute, isToolError, tools } from '../api.js';
3
+ import { CLI_API, ToolError, bareScanId, cliApi, cliFetch, isMissingRoute, isToolError, tools } from '../api.js';
4
4
  import { EXIT, Exit, exitCodeFor, messageFor } from '../exit.js';
5
5
  import { exitCodeOfStart, scanFinished, watchScan } from '../flow.js';
6
- import { scanLink } from '../payment.js';
6
+ import { openableLink, scanLink } from '../payment.js';
7
7
  import { currentGithubRepo } from '../repo.js';
8
8
  import { defaultRepository } from '../state.js';
9
9
  import { ask, c, cross, dot, interactive, say, tick } from '../ui.js';
@@ -25,17 +25,70 @@ export function merged(cmd) {
25
25
  out[k] = v;
26
26
  return out;
27
27
  }
28
- export async function ready(fn) {
28
+ /**
29
+ * Every refusal from Sekura, as the person at the terminal reads it. A
30
+ * refusal was printed as the server wrote it, for an agent: "updateSchedule
31
+ * changes when it runs; cancelPlan ends it" reached the terminal, and the
32
+ * reader was given no command to run (Varsha's 0.5.20 test, 1 December 2026,
33
+ * bugs 13 to 15). The repository is the command's own, for a refusal whose
34
+ * data does not name one.
35
+ */
36
+ export async function ready(fn, ctx = {}) {
29
37
  try {
30
38
  return await fn();
31
39
  }
32
40
  catch (e) {
33
- if (e instanceof ToolError && exitCodeFor(e) === EXIT.accountNotReady) {
34
- throw new Exit(EXIT.accountNotReady, `${messageFor(e)}\n ${DOCTOR_HINT}`, { code: e.code, ...e.data });
41
+ if (e instanceof ToolError) {
42
+ const code = exitCodeFor(e);
43
+ throw new Exit(code, `${refusalText(e, ctx.repository)}${code === EXIT.accountNotReady ? `\n ${DOCTOR_HINT}` : ''}`, { code: e.code, ...e.data });
35
44
  }
36
45
  throw e;
37
46
  }
38
47
  }
48
+ const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
49
+ /** What to run about a monthly plan that is already there. */
50
+ export const alreadyHints = (repo) => `To change when it runs: npx sekura@latest plan schedule ${repo}. To end it: npx sekura@latest plan cancel ${repo}`;
51
+ /**
52
+ * The terminal commands for a refusal, by its code. The server's sentence
53
+ * says what happened, to "you", with no tool names; the commands are the
54
+ * CLI's to add, because only the CLI knows it is in a terminal. Each line
55
+ * goes through say(), which adds --endpoint off production.
56
+ */
57
+ export function refusalHints(e, repository) {
58
+ const repo = str(e.data.repository) ?? repository ?? 'owner/repo';
59
+ switch (e.code) {
60
+ // A one-time scan after the first: Sekura sells only monthly plans then.
61
+ case 'once_not_sold': return [`Put it on a plan: npx sekura@latest plan start ${repo}`];
62
+ case 'already_always': return [alreadyHints(repo)];
63
+ // A payment is waiting. data.checkoutUrl is there while Stripe's page is
64
+ // still open; only a Stripe or Sekura link is printed to be opened.
65
+ case 'pending': {
66
+ const planId = str(e.data.planId);
67
+ const raw = str(e.data.checkoutUrl);
68
+ const url = raw ? openableLink(raw)?.href ?? null : null;
69
+ return [
70
+ ...(url ? [`To pay: open ${url}`] : []),
71
+ ...(planId ? [`To wait for it: npx sekura@latest pay --plan ${planId}`, `To cancel it: npx sekura@latest pay --plan ${planId} --abandon`] : []),
72
+ ];
73
+ }
74
+ default: return [];
75
+ }
76
+ }
77
+ /** A refusal's words for the person, then its commands. The words go
78
+ * through the same rewrites as a quote, as a safety net: a server that
79
+ * still writes for an agent ("the person", "connector", a tool name) has
80
+ * those sentences rewritten or left out. A hint the words already carry is
81
+ * not said twice. */
82
+ export function refusalText(e, repository) {
83
+ const said = personText(messageFor(e), repository);
84
+ if (!(e instanceof ToolError))
85
+ return said;
86
+ const fresh = refusalHints(e, repository).filter((h) => {
87
+ const parts = h.match(/npx sekura@latest [^.]+?(?=\.\s|\.?$)|https?:\/\/\S+/g) ?? [];
88
+ return !parts.length || !parts.every((p) => said.includes(p));
89
+ });
90
+ return [said, ...fresh].filter(Boolean).join('\n ');
91
+ }
39
92
  const REPO = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9._-]+$/;
40
93
  export function resolveRepository(given, cwd = process.cwd()) {
41
94
  if (given) {
@@ -108,7 +161,10 @@ const PERSON_REWRITES = [
108
161
  // After the first scan there is no one-time scan (Sudhir, 30 November 2026):
109
162
  // the server's refusal names the plan tool, the reader gets the command.
110
163
  [/To scan (\S+?), put it on a monthly plan: (.+?)\. Call \w+ with the repository and a schedule\./g,
111
- (_m, repo, plans) => `To scan ${repo}, put it on a monthly plan: ${plans}. Start one with: npx sekura@latest plan start ${repo}`],
164
+ // The command itself is the once_not_sold hint, on a line of its own:
165
+ // inside the sentence it ran on into "Nothing was started or charged."
166
+ // (Varsha's 0.5.20 test, 1 December 2026).
167
+ (_m, repo, plans) => `To scan ${repo}, put it on a monthly plan: ${plans}.`],
112
168
  [/this is the account's first scan\./g, 'this is your first scan.'],
113
169
  [/in the person's browser/g, 'in your browser'],
114
170
  [/the person's name/g, 'your name'],
@@ -116,7 +172,12 @@ const PERSON_REWRITES = [
116
172
  ];
117
173
  /** One sentence at a time, for the last check: a period that ends a sentence
118
174
  * is followed by a space and a capital; one inside a URL or "e.g." is not. */
119
- const sentences = (line) => line.split(/(?<=[.!?])\s+(?=[A-Z])/);
175
+ const sentences = (line) => line.split(SENTENCE_BREAK);
176
+ /** A sentence may also open with a tool name, in lower case: "… on this
177
+ * account. updateSchedule changes when it runs" was one sentence to the
178
+ * split above, and the repository's half was left out with the tool's
179
+ * (Varsha's 0.5.20 test, 1 December 2026, bug 13). */
180
+ const SENTENCE_BREAK = new RegExp(`(?<=[.!?])\\s+(?=[A-Z]|(?:${TOOL_NAMES.join('|')})\\b)`);
120
181
  /** The repository as the person typed it, where the server answered with its
121
182
  * lower-cased canonical name ("varsha311002/navidrome", Varsha's test, F10). */
122
183
  export function namedAs(text, repo) {
@@ -345,6 +406,11 @@ const REPORT_REFUSALS = {
345
406
  no_report_yet: (id, d) => `Scan ${id} has no report yet${typeof d.status === 'string' ? `: it is ${d.status}` : ''}. To wait for it: npx sekura@latest scan show ${id} --watch`,
346
407
  report_expired: (id) => `The report for scan ${id} is no longer kept, so it cannot be downloaded.`,
347
408
  };
409
+ /** What a watch that ended early says: the scan carries on, and the one
410
+ * command that saves its report once it is done. It said only "To look
411
+ * again: scan show --watch", and the report that the first-scan watch was
412
+ * to save was left behind (Varsha's 0.5.20 test, 1 December 2026, bug 6). */
413
+ export const stoppedWatching = (result, scanId) => `${result === 'skipped' ? 'Stopped watching' : 'Still running after the wait'}; the scan carries on. When it finishes, this saves the report: npx sekura@latest report ${bareScanId(scanId)}`;
348
414
  export const defaultReportPath = (scanId, cwd = process.cwd()) => resolve(cwd, `sekura-report-${scanId.replace(/[^A-Za-z0-9._-]/g, '_')}.html`);
349
415
  export async function fetchReport(key, scanId, output) {
350
416
  const path = `/scans/${encodeURIComponent(scanId)}/report`;
@@ -391,16 +457,17 @@ export function sayFindings(f, shown = f.findings.length) {
391
457
  say(` ${i + 1}. [${x.severity}] ${x.title}${x.location ? ` — ${x.location}` : ''}`);
392
458
  });
393
459
  if (f.total > shown)
394
- say(` … and ${f.total - shown} more: npx sekura@latest findings ${f.scanId}`);
460
+ say(` … and ${f.total - shown} more: npx sekura@latest findings ${bareScanId(f.scanId)}`);
395
461
  }
396
462
  export function sayScan(d) {
397
463
  const s = d.scan;
398
464
  const repo = s.target_owner && s.target_repo ? `${s.target_owner}/${s.target_repo}` : 'the repository';
399
465
  const count = typeof s.findings_count === 'number' ? `, ${s.findings_count} ${s.findings_count === 1 ? 'finding' : 'findings'}` : '';
400
- say(`${s.status === 'failed' ? cross : scanFinished(s.status) ? tick : dot} Scan ${s.id} of ${repo}: ${s.status}${s.status === 'done' ? count : ''}`);
466
+ say(`${s.status === 'failed' ? cross : scanFinished(s.status) ? tick : dot} Scan ${bareScanId(s.id)} of ${repo}: ${s.status}${s.status === 'done' ? count : ''}`);
401
467
  say(` ${d.link ?? scanLink(s.id)}`);
402
468
  }
403
- export async function followScan(key, scanId, opts = {}) {
469
+ export async function followScan(key, given, opts = {}) {
470
+ const scanId = bareScanId(given);
404
471
  const watching = opts.watch ?? (interactive() && !opts.json);
405
472
  if (!watching) {
406
473
  say(`${dot} To follow it: npx sekura@latest scan show ${scanId} --watch`);
@@ -415,7 +482,7 @@ export async function followScan(key, scanId, opts = {}) {
415
482
  say(`${dot} ${status}`); },
416
483
  });
417
484
  if (w.result !== 'done') {
418
- throw new Exit(EXIT.stoppedWaiting, `${w.result === 'skipped' ? 'Stopped watching' : 'Still running after the wait'}; the scan carries on. To look again: npx sekura@latest scan show ${scanId} --watch`, { scanId, status: w.status });
485
+ throw new Exit(EXIT.stoppedWaiting, stoppedWatching(w.result, scanId), { scanId, status: w.status });
419
486
  }
420
487
  if (w.detail)
421
488
  sayScan(w.detail);
@@ -24,16 +24,27 @@ export async function runStatus(opts) {
24
24
  const local = localConnections({ cwd, scope });
25
25
  if (!local.detected)
26
26
  say(' No supported coding tool found on this machine.');
27
+ // The tools that are connected (or cannot be checked) by name, and the
28
+ // others found here in one line. Every tool on the machine was listed,
29
+ // twelve of them "not connected" (Varsha's 0.5.20 test, 1 December 2026).
27
30
  const seen = [];
31
+ let others = 0;
28
32
  for (const row of local.rows) {
29
- if (row.kind === 'tool')
33
+ if (row.kind === 'tool') {
30
34
  seen.push(row.state);
35
+ if (row.state === false) {
36
+ others++;
37
+ continue;
38
+ }
39
+ }
31
40
  say(`${row.state === true ? tick : row.state === 'unknown' ? dot : cross} ${row.label}: ${row.word}`);
32
41
  }
33
42
  for (const s of local.skipped)
34
43
  say(`${dot} ${s.name}: ${s.why}`);
35
44
  if (seen.length && !local.skipped.length && seen.every((p) => p === false))
36
45
  say(`${dot} Nothing on this machine is connected to Sekura.`);
46
+ if (others)
47
+ say(`${dot} ${others}${seen.some((p) => p !== false) ? ' other' : ''} supported ${others === 1 ? 'tool' : 'tools'} found, not connected: npx sekura@latest init connects them`);
37
48
  let result = { readiness: null, server: null };
38
49
  if (opts.verify !== false) {
39
50
  const server = await verifyEndpoint(ENDPOINT, 8000, key);
package/dist/errors.js CHANGED
@@ -1,8 +1,28 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { HOST, SUPPORT } from './catalogue.js';
3
+ /** The CLI by name and version, on every request it sends to Sekura. The
4
+ * server marks a refusal as isError only for a client it knows is this CLI;
5
+ * without the header a 409 came back as an ordinary answer with ok: false,
6
+ * and a CLI that looked only at isError read a refusal as a quote (the
7
+ * coordinator's note on Varsha's 0.5.20 test, 1 December 2026). */
8
+ export const USER_AGENT = `sekura-cli/${createRequire(import.meta.url)('../package.json').version}`;
9
+ /** The headers of a request with the user-agent added; a plain object stays
10
+ * a plain object, so a caller that reads init.headers still can. */
11
+ export function withAgent(init) {
12
+ const h = init.headers;
13
+ if (h instanceof Headers) {
14
+ const copy = new Headers(h);
15
+ copy.set('user-agent', USER_AGENT);
16
+ return { ...init, headers: copy };
17
+ }
18
+ if (Array.isArray(h))
19
+ return { ...init, headers: [...h.filter(([k]) => k.toLowerCase() !== 'user-agent'), ['user-agent', USER_AGENT]] };
20
+ return { ...init, headers: { ...(h ?? {}), 'user-agent': USER_AGENT } };
21
+ }
2
22
  export const unreachable = () => `${HOST} could not be reached. Check your internet connection and try again.`;
3
23
  export const serverTrouble = (status) => `${HOST} had a problem answering (HTTP ${status}). Try again in a minute; if it keeps happening, write to ${SUPPORT}.`;
4
24
  export const REQUEST_TIMEOUT_MS = 25_000;
5
- export const timed = (init, timeoutMs = REQUEST_TIMEOUT_MS) => init.signal ? init : { ...init, signal: AbortSignal.timeout(timeoutMs) };
25
+ export const timed = (init, timeoutMs = REQUEST_TIMEOUT_MS) => withAgent(init.signal ? init : { ...init, signal: AbortSignal.timeout(timeoutMs) });
6
26
  export async function reach(url, init) {
7
27
  try {
8
28
  return await fetch(url, timed(init));
package/dist/flow.js CHANGED
@@ -12,6 +12,12 @@ export function requireKey() {
12
12
  throw new Exit(EXIT.notSignedIn, `Not signed in here: ${SIGN_IN_HINT} first.`);
13
13
  return key;
14
14
  }
15
+ /** True when the answer has a step to confirm. A preview of a plan already
16
+ * cancelled carries none (data.alreadyCancelled, no confirmOperation), and
17
+ * asking "Cancel the plan?" over it ended, on Yes, in "Cannot destructure
18
+ * property 'confirm' of 'args' as it is undefined" (Varsha's 0.5.20 test,
19
+ * 1 December 2026, bug 15). */
20
+ export const hasConfirmStep = (q) => !!q && typeof q.confirmOperation === 'string' && !!q.confirmOperation && !!q.confirmArguments && typeof q.confirmArguments === 'object';
15
21
  const usd = (cents) => `$${(cents / 100).toFixed(cents % 100 ? 2 : 0)}`;
16
22
  export const amountOf = (q) => typeof q.amountCents === 'number' && Number.isFinite(q.amountCents) ? q.amountCents : null;
17
23
  export const needsAgreement = (q) => !!q.disclosure || (amountOf(q) ?? 0) > 0;
@@ -76,6 +82,11 @@ export async function confirmQuote(req) {
76
82
  const flags = req.flags ?? {};
77
83
  const again = req.command ? `${req.command} --quote` : 'the same command with --quote';
78
84
  if (flags.confirm) {
85
+ // The payment is part of the quote: --card given here was ignored, and the
86
+ // confirm went to Checkout with no word (Claude's run of the customer flow,
87
+ // 1 December 2026). Refused, so the person knows where it goes.
88
+ if (flags.card)
89
+ throw new Exit(EXIT.error, `--card goes with --quote: the payment is part of the quote. Run ${again} --card ${flags.card}, then --confirm the new quote. Nothing was started.`);
79
90
  const found = findQuote(flags.confirm);
80
91
  if (found.status === 'unknown')
81
92
  throw new Exit(EXIT.error, `There is no quote ${flags.confirm} saved here. Run ${again} to get one.`);
@@ -92,6 +103,18 @@ export async function confirmQuote(req) {
92
103
  const amount = amountOf(q);
93
104
  const show = req.sayQuote ?? ((text) => { say(); for (const l of text.split('\n'))
94
105
  say(` ${l}`); say(); });
106
+ // No step to confirm: the answer is the whole of it, and there is no
107
+ // question to ask (bug 15).
108
+ if (!hasConfirmStep(q)) {
109
+ if (flags.json)
110
+ printJson(q);
111
+ else
112
+ show(q.text);
113
+ return { kind: 'answered', quote: q };
114
+ }
115
+ // A No to a cancel said "Nothing was started or charged." (Varsha's 0.5.20
116
+ // test, bug 16): the command names what it leaves as it was.
117
+ const nothing = req.nothing ?? 'Nothing was started or charged.';
95
118
  if (flags.quote) {
96
119
  const payment = paymentFromFlag(q, flags.card);
97
120
  const cached = cacheQuote(req, { ...q, confirmArguments: withPayment(q.confirmArguments, payment) });
@@ -99,7 +122,7 @@ export async function confirmQuote(req) {
99
122
  printJson({ quoteId: cached.quoteId, op: cached.op, confirmOperation: cached.confirmOperation, confirmArguments: cached.confirmArguments, amountCents: cached.amountCents, price: cached.price, expiresAt: cached.expiresAt, text: cached.text });
100
123
  else {
101
124
  show(q.text);
102
- say(`${dot} Quote ${cached.quoteId}, good until ${cached.expiresAt}. Nothing was started or charged.`);
125
+ say(`${dot} Quote ${cached.quoteId}, good until ${cached.expiresAt}. ${nothing}`);
103
126
  say(` To start exactly this: ${req.command ?? 'the same command'} --confirm ${cached.quoteId}`);
104
127
  }
105
128
  return { kind: 'quoted', cached };
@@ -120,7 +143,7 @@ export async function confirmQuote(req) {
120
143
  const payment = await askPayment(q, flags.card);
121
144
  const agreed = await ask(req.question ?? 'Do you agree?', { default: false, short: 'Do you agree?' });
122
145
  if (!agreed)
123
- throw new Exit(EXIT.declined, 'Nothing was started or charged.');
146
+ throw new Exit(EXIT.declined, nothing);
124
147
  return { kind: 'agreed', how: 'asked', confirmOperation: q.confirmOperation, confirmArguments: withPayment(q.confirmArguments, payment), amountCents: amount, quoteId: null, quote: q };
125
148
  }
126
149
  export async function planById(key, planId) {
@@ -217,7 +240,7 @@ export async function startWithPayment(key, op, args, opts = {}) {
217
240
  if (opts.quoteId)
218
241
  dropQuote(opts.quoteId);
219
242
  const { data } = reply;
220
- return { kind: 'started', text: reply.text, data, scanId: typeof data.scanId === 'string' ? data.scanId : null, planId: typeof data.planId === 'string' ? data.planId : null };
243
+ return { kind: 'started', text: reply.text, data, scanId: typeof data.scanId === 'string' ? data.scanId.replace(/^ss-/i, '') : null, planId: typeof data.planId === 'string' ? data.planId : null };
221
244
  }
222
245
  export function exitCodeOfStart(o) {
223
246
  switch (o.kind) {
@@ -230,6 +253,12 @@ export function exitCodeOfStart(o) {
230
253
  }
231
254
  export const SCAN_TERMINAL = new Set(['done', 'failed', 'cancelled', 'expired']);
232
255
  export const scanFinished = (status) => !!status && SCAN_TERMINAL.has(status);
256
+ /** How long a scan is watched. A typical scan takes 35 to 40 minutes, and a
257
+ * long one more than an hour; an hour's watch, and a stray Enter, ended the
258
+ * first-scan watch before the scan did, and the report was never saved
259
+ * (Varsha's 0.5.20 test, 1 December 2026, bug 6). Two hours covers the
260
+ * longest scan seen so far with room to spare. */
261
+ export const SCAN_WATCH_MS = 120 * 60_000;
233
262
  export async function watchScan(key, scanId, opts = {}) {
234
263
  let detail = null;
235
264
  let seen = null;
@@ -243,6 +272,6 @@ export async function watchScan(key, scanId, opts = {}) {
243
272
  opts.onStatus?.(status, detail);
244
273
  }
245
274
  return scanFinished(status);
246
- }, { timeoutMs: opts.timeoutMs ?? 60 * 60_000, intervalMs: opts.intervalMs ?? 5000 });
275
+ }, { timeoutMs: opts.timeoutMs ?? SCAN_WATCH_MS, intervalMs: opts.intervalMs ?? 5000 });
247
276
  return { result, detail: detail, status: seen };
248
277
  }
package/dist/payment.js CHANGED
@@ -18,14 +18,28 @@ export function checkoutCodeOf(data, text) {
18
18
  export const checkoutCodeLine = (c) => `Enter the code ${c.code} on the Stripe page${c.saving ? `: ${c.saving}` : ''}.`;
19
19
  export const paymentMethodsLink = () => `${SEKURA_ORIGIN}/app/payment-methods`;
20
20
  export const scanLink = (scanId) => `${SEKURA_ORIGIN}/app/scans/${encodeURIComponent(scanId.startsWith('ss-') ? scanId : `ss-${scanId}`)}`;
21
- const newScanOf = (start, now) => now.lastScan && now.lastScan.id !== start?.lastScan?.id ? now.lastScan : null;
21
+ const IN_FLIGHT = new Set(['pending_authorization', 'queued', 'running']);
22
+ /** The scan this payment started. A new scan since the wait began; or, when
23
+ * the payment had already landed before the wait began (`pay --plan` run
24
+ * after paying, the "To wait for it again" command), the scan in flight on
25
+ * it. That case read "The scan starts within a few minutes" while the scan
26
+ * was already running (Claude's run of the customer flow, 1 December 2026:
27
+ * queued 09:32:17, claimed 09:32:35, the CLI said "within a few minutes"
28
+ * at 09:32:36). */
29
+ const newScanOf = (start, now) => {
30
+ if (!now.lastScan)
31
+ return null;
32
+ if (now.lastScan.id !== start?.lastScan?.id)
33
+ return now.lastScan;
34
+ return start?.status === 'active' && IN_FLIGHT.has(now.lastScan.status) ? now.lastScan : null;
35
+ };
22
36
  export function paymentState(start, now) {
23
37
  if (!now)
24
38
  return start ? { kind: 'cancelled' } : { kind: 'waiting' };
25
39
  if (now.status === 'active') {
26
40
  const scan = newScanOf(start, now);
27
41
  if (scan)
28
- return { kind: 'started', scanId: scan.id, scanStatus: scan.status };
42
+ return { kind: 'started', scanId: scan.id.replace(/^ss-/i, ''), scanStatus: scan.status };
29
43
  const backAsItWas = start?.status === 'pending' && (start.pendingFrom === 'rerun' || start.pendingFrom === 'upgrade') && !now.nextRunAt && !now.pendingFrom;
30
44
  return backAsItWas && start.plan === now.plan ? { kind: 'cancelled' } : { kind: 'paid' };
31
45
  }
package/dist/session.js CHANGED
@@ -59,7 +59,11 @@ export async function currentSession(opts = {}) {
59
59
  const account = await getAccount(existing);
60
60
  if (!fromEnv)
61
61
  adoptSavedKey();
62
- tell(`${tick} Signed in to Sekura as ${who(account, existing)}${fromEnv ? ' (SEKURA_API_KEY)' : ''}`);
62
+ if (opts.already) {
63
+ tell(`${tick} Already signed in as ${who(account, existing)}${fromEnv ? ' (SEKURA_API_KEY)' : ''}. To use another account, ${fromEnv ? 'set SEKURA_API_KEY to its key' : 'run npx sekura@latest logout first'}.`);
64
+ }
65
+ else
66
+ tell(`${tick} Signed in to Sekura as ${who(account, existing)}${fromEnv ? ' (SEKURA_API_KEY)' : ''}`);
63
67
  return { key: existing, account, kind, fresh: false };
64
68
  }
65
69
  catch (e) {
@@ -124,7 +128,7 @@ export async function signInFresh(flags = {}) {
124
128
  }
125
129
  }
126
130
  export async function obtainSession(opts) {
127
- const s = await currentSession({ quiet: opts.quiet });
131
+ const s = await currentSession({ quiet: opts.quiet, already: opts.already });
128
132
  if (s || !opts.interactive)
129
133
  return s;
130
134
  return signInFresh(opts);
package/dist/skill.js CHANGED
@@ -11,13 +11,31 @@
11
11
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
12
12
  import { dirname, join } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { DOCS, ENDPOINT, SERVER_NAME } from './catalogue.js';
14
+ import { DOCS, ENDPOINT, PRODUCTION, SERVER_NAME } from './catalogue.js';
15
15
  const here = dirname(fileURLToPath(import.meta.url));
16
16
  /** The packaged skill: dist/ sits beside skills/ in the published package. */
17
17
  export const SKILL_SOURCE = join(here, '..', 'skills', SERVER_NAME, 'SKILL.md');
18
18
  /** LF whatever the checkout did: a Windows clone with autocrlf would otherwise
19
19
  * install a skill whose every line ends in \r, and a rerun would rewrite it. */
20
20
  export const skillText = () => readFileSync(SKILL_SOURCE, 'utf8').replace(/\r\n/g, '\n');
21
+ /**
22
+ * The skill as it is installed for one server. The packaged text names
23
+ * production; installed for dev.sekura.ai, its commands ran against
24
+ * production, and after a logout Claude Code told the person to run
25
+ * `npx sekura@latest login` with no --endpoint, for an account that lives on
26
+ * dev (Varsha's 0.5.20 test, 1 December 2026, bug 8). Off production every
27
+ * `npx sekura@latest` becomes `npx sekura@latest --endpoint <server>`, as the
28
+ * CLI's own printed commands do, and the server's address is this one.
29
+ */
30
+ export function skillTextFor(endpoint = ENDPOINT) {
31
+ const text = skillText();
32
+ const origin = new URL(endpoint).origin;
33
+ if (origin === new URL(PRODUCTION).origin)
34
+ return text;
35
+ return text
36
+ .replace(/npx sekura@latest(?! --endpoint)/g, `npx sekura@latest --endpoint ${origin}`)
37
+ .split(PRODUCTION).join(endpoint);
38
+ }
21
39
  export function skillPaths(root, claude, scope, agents = true) {
22
40
  const out = agents ? [join(root, '.agents', 'skills', SERVER_NAME, 'SKILL.md')] : [];
23
41
  if (claude || (scope === 'project' && existsSync(join(root, '.claude'))))
@@ -25,7 +43,7 @@ export function skillPaths(root, claude, scope, agents = true) {
25
43
  return out;
26
44
  }
27
45
  export function writeSkill(path) {
28
- const text = skillText();
46
+ const text = skillTextFor();
29
47
  if (existsSync(path) && readFileSync(path, 'utf8') === text)
30
48
  return { status: 'unchanged', where: path };
31
49
  mkdirSync(dirname(path), { recursive: true });
package/dist/steps.js CHANGED
@@ -43,6 +43,24 @@ export function localConnections(opts = {}) {
43
43
  });
44
44
  return { detected: detected.length, rows, skipped: plan.skipped.map((s) => ({ name: s.tool.name, why: s.why })), connected };
45
45
  }
46
+ /** The saved default repository, as the account names it, when it is one of
47
+ * the repositories the account can scan; otherwise null (bug 17). */
48
+ export const scannableOf = (saved, names) => (saved ? names.find((n) => same(n, saved)) ?? null : null);
49
+ /** The saved default, when the signed-in account can scan it. Null when it
50
+ * cannot, or when the list could not be read: a hint that names a
51
+ * repository the account cannot scan sends the person to a refusal. */
52
+ export async function scannableDefault(key) {
53
+ const saved = defaultRepository();
54
+ if (!saved)
55
+ return null;
56
+ try {
57
+ const names = repositoriesOf(await listRepositories(key)).filter((r) => !r.empty).map((r) => r.fullName);
58
+ return scannableOf(saved, names);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
46
64
  const settled = async (p) => {
47
65
  try {
48
66
  return { ok: true, value: await p };
@@ -60,7 +78,11 @@ export async function readiness(key, opts = {}) {
60
78
  detail: tools.connected.length ? `connected: ${tools.connected.join(', ')}` : tools.detected ? 'none of the tools on this machine is connected' : 'no supported coding tool found on this machine',
61
79
  ...(tools.connected.length ? {} : { fix: tools.detected ? 'npx sekura@latest init' : 'npx sekura@latest init --tools <tool>' }),
62
80
  };
63
- const base = { server: ENDPOINT, repositories: [], defaultRepository: defaultRepository(), plans: [], billing: null, tools };
81
+ // The saved default is named only once the signed-in account is known to
82
+ // scan it. After a logout and a sign-in as another account, status still
83
+ // read "default Srivarsha1031/NodeGoat", the first account's repository
84
+ // (Varsha's 0.5.20 test, 1 December 2026, bug 17).
85
+ const base = { server: ENDPOINT, repositories: [], defaultRepository: null, plans: [], billing: null, tools };
64
86
  if (!key) {
65
87
  return {
66
88
  ...base, signedIn: false, ready: false, account: null,
@@ -93,6 +115,7 @@ export async function readiness(key, opts = {}) {
93
115
  if (repos.ok) {
94
116
  const installs = repos.value.installations ?? [];
95
117
  names = installs.flatMap((i) => i.repositories).filter((r) => !r.empty).map((r) => r.fullName);
118
+ base.defaultRepository = scannableOf(defaultRepository(), names);
96
119
  const accounts = installs.map((i) => i.account).filter((a) => !!a);
97
120
  const broken = installs.filter((i) => i.error && i.error !== 'partial').map((i) => `${i.account}: ${i.error}`);
98
121
  checks.push(installs.length
@@ -143,7 +166,7 @@ export const readinessJson = (r) => ({
143
166
  tools: r.tools,
144
167
  });
145
168
  export async function ensureSignedIn(flags = {}) {
146
- const s = await obtainSession({ interactive: isInteractive(flags), legacy: flags.legacy, device: flags.device, browser: flags.browser, quiet: flags.json });
169
+ const s = await obtainSession({ interactive: isInteractive(flags), legacy: flags.legacy, device: flags.device, browser: flags.browser, quiet: flags.json, already: flags.already });
147
170
  if (!s) {
148
171
  throw new Exit(EXIT.notSignedIn, isInteractive(flags)
149
172
  ? 'Not signed in; nothing was changed. Run npx sekura@latest login to try again.'
package/dist/verify.js CHANGED
@@ -4,15 +4,15 @@
4
4
  // installer wrote will not connect, which the person should hear now rather
5
5
  // than from their tool later.
6
6
  import { ENDPOINT } from './catalogue.js';
7
- import { unreachable } from './errors.js';
7
+ import { unreachable, withAgent } from './errors.js';
8
8
  async function verifyWithKey(endpoint, key, signal) {
9
- const r = await fetch(endpoint, {
9
+ const r = await fetch(endpoint, withAgent({
10
10
  method: 'POST',
11
11
  headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
12
12
  body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' }),
13
13
  signal,
14
14
  redirect: 'manual',
15
- });
15
+ }));
16
16
  if (r.status === 200)
17
17
  return { ok: true, detail: `Connected to ${new URL(endpoint).host}` };
18
18
  if (r.status === 401)
@@ -27,7 +27,7 @@ export async function verifyEndpoint(endpoint = ENDPOINT, timeoutMs = 8000, key)
27
27
  try {
28
28
  if (key)
29
29
  return await verifyWithKey(endpoint, key, ctl.signal);
30
- const r = await fetch(endpoint, { method: 'GET', headers: { accept: 'application/json' }, signal: ctl.signal, redirect: 'manual' });
30
+ const r = await fetch(endpoint, withAgent({ method: 'GET', headers: { accept: 'application/json' }, signal: ctl.signal, redirect: 'manual' }));
31
31
  const type = r.headers.get('content-type') || '';
32
32
  if (r.status === 401 && type.includes('json'))
33
33
  return { ok: true, detail: `${endpoint} answers and asks for a key, as it should` };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sekura",
3
- "version": "0.5.20",
3
+ "version": "0.5.21",
4
4
  "description": "Set up Sekura and scan your GitHub repositories from the terminal, and connect your coding tools: npx sekura@latest",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "scripts": {
39
39
  "build": "tsc -p tsconfig.json && node -e \"require('fs').chmodSync('dist/cli.js', 0o755)\"",
40
- "test": "npm run build && node --test test/init.test.mjs test/login.test.mjs test/guide.test.mjs test/device.test.mjs test/skill.test.mjs test/pay.test.mjs test/keys.test.mjs test/commands.test.mjs test/endpoint.test.mjs test/errors.test.mjs test/exit.test.mjs test/state.test.mjs test/flow.test.mjs test/api.test.mjs test/v5-fixes.test.mjs",
40
+ "test": "npm run build && node --test test/init.test.mjs test/login.test.mjs test/guide.test.mjs test/device.test.mjs test/skill.test.mjs test/pay.test.mjs test/keys.test.mjs test/commands.test.mjs test/endpoint.test.mjs test/errors.test.mjs test/exit.test.mjs test/state.test.mjs test/flow.test.mjs test/api.test.mjs test/v5-fixes.test.mjs test/v520-fixes.test.mjs",
41
41
  "prepack": "npm run build"
42
42
  },
43
43
  "dependencies": {
@@ -37,7 +37,7 @@ the first word:
37
37
  monthly plans: Weekly (`tier` `always`, the default) and More frequently
38
38
  (`tier` `pro`). Use `pro` only when the user asks for More frequently, and
39
39
  call it More frequently, never by its schedule kind (`daily`). It needs a
40
- schedule; if the user gave none, ask before quoting, and always ask the time zone.
40
+ schedule; if the user gave none, ask before quoting. Always ask the time zone, and offer the computer's own first (run `date +%Z` or read the system's zone); never assume one, such as America/Los_Angeles.
41
41
  - Weekly: a weekday and a time (`schedule.kind` `weekly`), or on demand. At most
42
42
  one scan in seven days.
43
43
  - More frequently: every day, every second day or every third day at a time
@@ -211,13 +211,14 @@ the GitHub App), 6 that agreement is needed, 7 that a payment needs a browser.
211
211
 
212
212
  ## What to tell the user
213
213
 
214
+ - A refusal (`ok: false` with a `code`) is an expected answer, not a failure: relay its words as they are, and never show the person its code (such as `once_not_sold`) or an internal id (such as a `plan_…` id).
214
215
  - After the first scan, a repository is scanned on a monthly plan; Sekura sells no one-time scan. A new account's first scan is quoted with `quoteScan` like any scan: $10 on a Stripe Checkout page, free with the code NPMSCAN, which the user types there themselves. Say so in the quote, and after their yes give them the Checkout link; never offer a saved card for it.
215
216
  - The plans a user can buy here: a monthly plan for
216
217
  one repository, Weekly ($10 a month per repository) or More frequently ($25 a
217
218
  month per repository). The quote's price is the one that counts. There is no
218
219
  trial. Enterprise is quoted by Sekura: give no price or plan name for it.
219
220
  - When `getAccount` says the Terms are not accepted or the GitHub App is not installed, tell the user to run `npx sekura@latest` in a terminal (or `npx sekura@latest terms`, or `npx sekura@latest repos --add`), or give them the link it names; for an unverified email, give the link. A scan cannot start before that.
220
- - One Sekura account at a time. If the `sekura` server you were set up with fails (signed out, a 401, "connection is no longer valid"), stop and tell the user: their Sekura sign-in here no longer works, and `npx sekura@latest login` (with the same `--endpoint` it was set up with) signs in again. Never answer from another Sekura connection instead, such as the claude.ai connector: it can be a different account on a different server, with other scans and prices. If you use one at the user's request, first say which account and server it is (`getAccount`).
221
+ - One Sekura account at a time. If the `sekura` server you were set up with fails (signed out, a 401, "connection is no longer valid"), stop and tell the user: their Sekura sign-in here no longer works, and give the full command for the server this tool points at, as this skill writes it: `npx sekura@latest login`. A copy installed for a server other than sekura.ai already carries its `--endpoint` in every command; if the `sekura` server's address in this tool's settings is on a server other than sekura.ai and the command here has no `--endpoint`, add `--endpoint` with that server's origin (for example `--endpoint https://dev.sekura.ai`). Never answer from another Sekura connection instead, such as the claude.ai connector: it can be a different account on a different server, with other scans and prices. If you use one at the user's request, first say which account and server it is (`getAccount`).
221
222
  - A scan can take a while. Offer `getScan` to check on it rather than polling in a loop.
222
223
  - Findings carry proof. When summarising, keep the evidence the finding gives; do not soften a severity.
223
224
  - Sekura scans only repositories the user has granted through the Sekura GitHub App. To add one: `npx sekura@latest repos --add` in a terminal.