cueapril 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +173 -2
- package/agents.mjs +996 -0
- package/cli.mjs +4 -0
- package/client.mjs +360 -0
- package/commands.mjs +1273 -0
- package/doctor.mjs +186 -0
- package/http.mjs +263 -0
- package/init.mjs +635 -0
- package/io.mjs +379 -0
- package/key-store.mjs +287 -0
- package/login.mjs +601 -0
- package/package.json +39 -4
- package/skill/cueapril-qa/SKILL.md +90 -0
package/init.mjs
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
// cueapril init: one command an agent can run to set CueApril up end to end.
|
|
2
|
+
//
|
|
3
|
+
// 1. Find a key (CUEAPRIL_API_KEY, TENHAW_TOKEN, the credentials file) or run
|
|
4
|
+
// the device login, which needs one approval in the browser.
|
|
5
|
+
// 2. Verify it with cueapril_check_setup and report readiness with fix links.
|
|
6
|
+
// A project that is not ready is not an init failure: init says what the
|
|
7
|
+
// person must do.
|
|
8
|
+
// 3. Add the CueApril MCP server to the detected agents at user level.
|
|
9
|
+
// 4. Install the cueapril-qa skill (user or project scope). Skills never
|
|
10
|
+
// contain a key, and no key is ever written under the current directory.
|
|
11
|
+
// Rerunning init changes nothing when everything is already in place.
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { createInterface } from 'node:readline';
|
|
14
|
+
import { parseArgs } from 'node:util';
|
|
15
|
+
import {
|
|
16
|
+
CliError,
|
|
17
|
+
EXIT,
|
|
18
|
+
atomicWriteFile,
|
|
19
|
+
currentDir,
|
|
20
|
+
defaultDeps,
|
|
21
|
+
displayPath,
|
|
22
|
+
homeDir,
|
|
23
|
+
isTTY,
|
|
24
|
+
pathFor,
|
|
25
|
+
readFileIfExists,
|
|
26
|
+
redact,
|
|
27
|
+
safeText,
|
|
28
|
+
writeLine,
|
|
29
|
+
} from './io.mjs';
|
|
30
|
+
import { createHttpClient, resolveBaseUrl } from './http.mjs';
|
|
31
|
+
import { RUN_COMMAND } from './client.mjs';
|
|
32
|
+
import { describeKeySource, maskKey, resolveApiKey } from './key-store.mjs';
|
|
33
|
+
import { importApiKey, runLogin } from './login.mjs';
|
|
34
|
+
import { AGENT_NAMES, applyAgentChanges, detectAgents, parseAgentList, planAgentChanges } from './agents.mjs';
|
|
35
|
+
|
|
36
|
+
export const CHECK_SETUP_TOOL = 'cueapril_check_setup';
|
|
37
|
+
export const SKILL_NAME = 'cueapril-qa';
|
|
38
|
+
export const NEXT_PROMPT = 'Test pull request 123 with CueApril and fix what fails.';
|
|
39
|
+
const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
|
|
40
|
+
|
|
41
|
+
export const INIT_USAGE = `Usage: cueapril init [--agents auto|none|claude,codex,gemini,cursor] [--scope user|project]
|
|
42
|
+
[--project <id>] [--dry-run] [--yes] [--no-login] [--json]
|
|
43
|
+
[--key-stdin | --no-wait]
|
|
44
|
+
[--name <label>] [--no-browser] [--timeout <minutes>]
|
|
45
|
+
|
|
46
|
+
Sets CueApril up for this computer and its coding agents:
|
|
47
|
+
- uses CUEAPRIL_API_KEY or the stored key, or asks for one approval in the browser;
|
|
48
|
+
- checks your CueApril setup and lists anything still to do, with links;
|
|
49
|
+
- adds the CueApril MCP server to Claude Code, Codex, Gemini CLI and Cursor (user level);
|
|
50
|
+
- installs the cueapril-qa skill.
|
|
51
|
+
|
|
52
|
+
--agents <list> auto (default: the agents found), none, or a comma list
|
|
53
|
+
--scope <scope> Where the skill goes: user (default) or project (this directory)
|
|
54
|
+
--project <id> Check readiness of this project only
|
|
55
|
+
--dry-run Show what would change, with the key masked; change nothing
|
|
56
|
+
--yes Do not ask for confirmation in a terminal
|
|
57
|
+
--no-login Fail instead of starting a browser approval when no key is found
|
|
58
|
+
--key-stdin Verify and store an existing agent key from a pipe; never argv or chat
|
|
59
|
+
--no-wait Return the approval link immediately (exit 4); rerun without this flag
|
|
60
|
+
--json Print one JSON object on stdout
|
|
61
|
+
--name, --no-browser, --timeout Passed to the login step (see cueapril login --help)
|
|
62
|
+
|
|
63
|
+
Rerunning init is safe. Exit codes: 0 set up (even if a project still needs
|
|
64
|
+
setup steps), 4 approval pending or timed out, 5 error.`;
|
|
65
|
+
|
|
66
|
+
export function bundledSkillPath() {
|
|
67
|
+
return fileURLToPath(new URL(`./skill/${SKILL_NAME}/SKILL.md`, import.meta.url));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function skillTargets(scope, deps = {}) {
|
|
71
|
+
const io = defaultDeps(deps);
|
|
72
|
+
const p = pathFor(io);
|
|
73
|
+
const root = scope === 'project' ? currentDir(io) : homeDir(io);
|
|
74
|
+
return [
|
|
75
|
+
p.join(root, '.claude', 'skills', SKILL_NAME, 'SKILL.md'),
|
|
76
|
+
p.join(root, '.agents', 'skills', SKILL_NAME, 'SKILL.md'),
|
|
77
|
+
];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
81
|
+
// Readiness
|
|
82
|
+
|
|
83
|
+
function isObject(value) {
|
|
84
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const PASSING = new Set(['ok', 'pass', 'passed', 'ready', 'done', 'complete', 'completed', 'success', 'succeeded', 'satisfied']);
|
|
88
|
+
|
|
89
|
+
function fixUrl(item, baseUrl) {
|
|
90
|
+
for (const field of ['fix_url', 'fixUrl', 'setup_url', 'action_url', 'url', 'href', 'link']) {
|
|
91
|
+
const value = item[field];
|
|
92
|
+
if (typeof value !== 'string' || !value.trim()) continue;
|
|
93
|
+
try {
|
|
94
|
+
const url = new URL(value.trim(), `${baseUrl}/`);
|
|
95
|
+
if (url.protocol === 'https:' || url.protocol === 'http:') return url.href;
|
|
96
|
+
} catch {
|
|
97
|
+
// ignore unusable links
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function checkPassed(item) {
|
|
104
|
+
for (const field of ['ok', 'passed', 'ready', 'done', 'satisfied']) {
|
|
105
|
+
if (typeof item[field] === 'boolean') return item[field];
|
|
106
|
+
}
|
|
107
|
+
if (typeof item.status === 'string') return PASSING.has(item.status.toLowerCase());
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function itemMessage(item) {
|
|
112
|
+
for (const field of ['message', 'detail', 'description', 'title', 'summary', 'label', 'name', 'code', 'id']) {
|
|
113
|
+
if (typeof item[field] === 'string' && item[field].trim()) return safeText(item[field], 300);
|
|
114
|
+
}
|
|
115
|
+
return '';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function collectIssues(list, { project, problemsOnly, baseUrl }, issues) {
|
|
119
|
+
if (!Array.isArray(list)) return;
|
|
120
|
+
for (const item of list.slice(0, 50)) {
|
|
121
|
+
if (typeof item === 'string') {
|
|
122
|
+
if (item.trim()) issues.push({ project, message: safeText(item, 300), fix_url: null });
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (!isObject(item)) continue;
|
|
126
|
+
const passed = checkPassed(item);
|
|
127
|
+
if (passed === true || (passed === undefined && !problemsOnly)) continue;
|
|
128
|
+
const message = itemMessage(item);
|
|
129
|
+
const url = fixUrl(item, baseUrl);
|
|
130
|
+
const owner = typeof item.owner === 'string' && item.owner.trim() ? safeText(item.owner, 20) : null;
|
|
131
|
+
if (message || url) issues.push({ project, message: message || 'Action needed', fix_url: url, ...(owner ? { owner } : {}) });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Normalises a cueapril_check_setup response into
|
|
137
|
+
* { ready, organisation, projects: [{ id, name, ready }], next_step,
|
|
138
|
+
* issues: [{ project, message, fix_url, owner? }] }.
|
|
139
|
+
* The shape the CLI's `cueapril setup` reads is
|
|
140
|
+
* { ready, project_id?, project_name?, repository?, checks: [{ code, ok, owner?, message, fix_url? }], next_step? };
|
|
141
|
+
* blockers/missing/next_steps lists and per-project lists are accepted too.
|
|
142
|
+
* Relative fix links are resolved against the base URL.
|
|
143
|
+
*/
|
|
144
|
+
export function summariseSetup(raw, baseUrl) {
|
|
145
|
+
const result = isObject(raw?.structuredContent) ? raw.structuredContent : isObject(raw?.result) ? raw.result : raw;
|
|
146
|
+
const r = isObject(result) ? result : {};
|
|
147
|
+
const issues = [];
|
|
148
|
+
const listsOf = (source, project) => {
|
|
149
|
+
collectIssues(source.checks, { project, problemsOnly: false, baseUrl }, issues);
|
|
150
|
+
for (const field of ['blockers', 'missing', 'next_steps', 'actions', 'issues', 'problems']) {
|
|
151
|
+
collectIssues(source[field], { project, problemsOnly: true, baseUrl }, issues);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
listsOf(r, safeText(r.project_name ?? r.repository ?? '', 120) || null);
|
|
155
|
+
const projects = [];
|
|
156
|
+
for (const project of Array.isArray(r.projects) ? r.projects.slice(0, 50) : []) {
|
|
157
|
+
if (!isObject(project)) continue;
|
|
158
|
+
const name = safeText(project.name ?? project.full_name ?? project.repository ?? project.id ?? '', 120);
|
|
159
|
+
const before = issues.length;
|
|
160
|
+
listsOf(project, name || null);
|
|
161
|
+
const ready = typeof project.ready === 'boolean' ? project.ready : issues.length === before;
|
|
162
|
+
projects.push({ id: safeText(project.id ?? '', 120) || null, name: name || null, ready });
|
|
163
|
+
}
|
|
164
|
+
const organisationSource = r.organisation ?? r.organization;
|
|
165
|
+
const organisation = safeText(
|
|
166
|
+
(isObject(organisationSource) ? organisationSource.name : organisationSource) ??
|
|
167
|
+
r.organisation_name ??
|
|
168
|
+
r.organization_name ??
|
|
169
|
+
'',
|
|
170
|
+
120,
|
|
171
|
+
);
|
|
172
|
+
const ready =
|
|
173
|
+
typeof r.ready === 'boolean' ? r.ready : projects.length ? projects.every((p) => p.ready) && !issues.length : !issues.length;
|
|
174
|
+
const nextStep = typeof r.next_step === 'string' ? safeText(r.next_step, 300) : '';
|
|
175
|
+
return { ready, organisation: organisation || null, projects, next_step: nextStep || null, issues: issues.slice(0, 20) };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ---------------------------------------------------------------------------
|
|
179
|
+
// Skills
|
|
180
|
+
|
|
181
|
+
async function loadSkill(io) {
|
|
182
|
+
return io.fs.readFile(bundledSkillPath(), 'utf8');
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function planSkills(io, scope, key) {
|
|
186
|
+
const content = await loadSkill(io);
|
|
187
|
+
if (key && content.includes(key)) throw new CliError('Refusing to install a skill that contains the key.');
|
|
188
|
+
const items = [];
|
|
189
|
+
for (const target of skillTargets(scope, io)) {
|
|
190
|
+
const current = await readFileIfExists(io, target);
|
|
191
|
+
items.push({
|
|
192
|
+
path: target,
|
|
193
|
+
displayPath: displayPath(io, target),
|
|
194
|
+
action: current === content ? 'unchanged' : current === null ? 'create' : 'update',
|
|
195
|
+
content,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return items;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function applySkills(io, items) {
|
|
202
|
+
const results = [];
|
|
203
|
+
for (const item of items) {
|
|
204
|
+
if (item.action === 'unchanged') {
|
|
205
|
+
results.push({ path: item.displayPath, status: 'unchanged' });
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
await atomicWriteFile(io, item.path, item.content, { mode: 0o644, dirMode: 0o755 });
|
|
210
|
+
results.push({ path: item.displayPath, status: item.action === 'create' ? 'created' : 'updated' });
|
|
211
|
+
} catch (error) {
|
|
212
|
+
results.push({ path: item.displayPath, status: 'failed', message: safeText(error.message, 300) });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return results;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ---------------------------------------------------------------------------
|
|
219
|
+
// Orchestration
|
|
220
|
+
|
|
221
|
+
function parseInitArgs(argv) {
|
|
222
|
+
const { values } = parseArgs({
|
|
223
|
+
args: argv,
|
|
224
|
+
allowPositionals: false,
|
|
225
|
+
strict: true,
|
|
226
|
+
options: {
|
|
227
|
+
agents: { type: 'string' },
|
|
228
|
+
scope: { type: 'string' },
|
|
229
|
+
project: { type: 'string' },
|
|
230
|
+
'dry-run': { type: 'boolean' },
|
|
231
|
+
yes: { type: 'boolean', short: 'y' },
|
|
232
|
+
'no-login': { type: 'boolean' },
|
|
233
|
+
'key-stdin': { type: 'boolean' },
|
|
234
|
+
'no-wait': { type: 'boolean' },
|
|
235
|
+
json: { type: 'boolean' },
|
|
236
|
+
name: { type: 'string' },
|
|
237
|
+
'no-browser': { type: 'boolean' },
|
|
238
|
+
timeout: { type: 'string' },
|
|
239
|
+
help: { type: 'boolean', short: 'h' },
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
return values;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function parseScope(raw) {
|
|
246
|
+
const scope = String(raw ?? 'user').trim().toLowerCase();
|
|
247
|
+
if (scope !== 'user' && scope !== 'project') throw new CliError('--scope must be user or project.');
|
|
248
|
+
return scope;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function confirm(io, question) {
|
|
252
|
+
if (typeof io.confirm === 'function') return io.confirm(question);
|
|
253
|
+
// The CLI passes stream-like { write, isTTY } objects for stdout and stderr,
|
|
254
|
+
// not tty.WriteStreams. readline's terminal mode needs a real one (it calls
|
|
255
|
+
// output.on('resize') and puts stdin in raw mode), so it stays off: the
|
|
256
|
+
// terminal's own line editing echoes the answer, and stdin is left as it was.
|
|
257
|
+
const rl = createInterface({ input: io.stdin, output: io.stderr, terminal: false });
|
|
258
|
+
try {
|
|
259
|
+
const answer = await new Promise((resolve) => {
|
|
260
|
+
rl.once('close', () => resolve(null));
|
|
261
|
+
rl.question(question, resolve);
|
|
262
|
+
});
|
|
263
|
+
// End of input without an answer changes nothing.
|
|
264
|
+
return answer !== null && !/^\s*n/i.test(answer);
|
|
265
|
+
} finally {
|
|
266
|
+
rl.close();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function verifyKey(io, baseUrl, key, projectId) {
|
|
271
|
+
try {
|
|
272
|
+
const client = createHttpClient(io, { baseUrl });
|
|
273
|
+
const raw = await client.callTool(CHECK_SETUP_TOOL, projectId ? { project_id: projectId } : {}, key, {
|
|
274
|
+
timeoutMs: 30_000,
|
|
275
|
+
});
|
|
276
|
+
return { raw };
|
|
277
|
+
} catch (error) {
|
|
278
|
+
return { error };
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function loginArgs(flags) {
|
|
283
|
+
const args = [];
|
|
284
|
+
if (flags.name !== undefined) args.push('--name', flags.name);
|
|
285
|
+
if (flags['no-browser']) args.push('--no-browser');
|
|
286
|
+
if (flags['no-wait']) args.push('--no-wait');
|
|
287
|
+
if (flags.timeout !== undefined) args.push('--timeout', flags.timeout);
|
|
288
|
+
return args;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// npx and uvx do not create a permanent cueapril executable. Give agents a
|
|
292
|
+
// runnable default plus the matching Python installer and installed forms.
|
|
293
|
+
function installCommands(argv) {
|
|
294
|
+
const quote = (arg) => /^[A-Za-z0-9_.,:/=-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
|
|
295
|
+
const suffix = argv.map(quote).join(' ');
|
|
296
|
+
return { npm: `${RUN_COMMAND} ${suffix}`, pypi: `uvx cueapril ${suffix}`, installed: `cueapril ${suffix}` };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function agentPlanLine(item) {
|
|
300
|
+
const where = item.displayPath ?? item.path;
|
|
301
|
+
switch (item.action) {
|
|
302
|
+
case 'unchanged':
|
|
303
|
+
return 'already configured';
|
|
304
|
+
case 'create':
|
|
305
|
+
return `create ${where}`;
|
|
306
|
+
case 'update':
|
|
307
|
+
return `update ${where}${item.backupPath ? ` (backup to ${where}.cueapril.bak)` : ''}`;
|
|
308
|
+
case 'configure':
|
|
309
|
+
return `run claude mcp add-json (user scope); the key goes in ${item.headersPath}`;
|
|
310
|
+
default:
|
|
311
|
+
return `cannot configure: ${item.message}`;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function agentResultLine(result) {
|
|
316
|
+
switch (result.status) {
|
|
317
|
+
case 'created':
|
|
318
|
+
return `created ${result.path}`;
|
|
319
|
+
case 'updated':
|
|
320
|
+
return `updated ${result.path}${result.backupPath ? ` (backup ${result.backupPath})` : ''}`;
|
|
321
|
+
case 'configured':
|
|
322
|
+
return `configured with claude mcp add-json (user scope); it reads the key from ${result.headersPath}`;
|
|
323
|
+
case 'unchanged':
|
|
324
|
+
return 'unchanged';
|
|
325
|
+
case 'skipped':
|
|
326
|
+
return `skipped: ${result.message}`;
|
|
327
|
+
default:
|
|
328
|
+
return `failed: ${result.message}`;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function pad(text, width) {
|
|
333
|
+
return text.length >= width ? `${text} ` : text + ' '.repeat(width - text.length);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function printSetup(out, setup) {
|
|
337
|
+
out('');
|
|
338
|
+
out('Setup');
|
|
339
|
+
if (!setup.checked) {
|
|
340
|
+
out(` Not checked: ${setup.reason}`);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (setup.ready) out(' Ready to test pull requests.');
|
|
344
|
+
else out(' Not ready yet. Still to do (a person usually does these in the browser):');
|
|
345
|
+
for (const issue of setup.issues) {
|
|
346
|
+
const owner = issue.owner === 'platform' ? ' (CueApril must fix this)' : '';
|
|
347
|
+
out(` - ${issue.project ? `${issue.project}: ` : ''}${issue.message}${owner}`);
|
|
348
|
+
if (issue.fix_url) out(` ${issue.fix_url}`);
|
|
349
|
+
}
|
|
350
|
+
if (setup.next_step) out(` Next step: ${setup.next_step}`);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Runs init. Returns { exitCode, summary }; with --json the summary is also
|
|
355
|
+
* printed as one JSON object. The summary never contains the key.
|
|
356
|
+
*/
|
|
357
|
+
export async function runInit(argv = [], deps = {}) {
|
|
358
|
+
const io = defaultDeps(deps);
|
|
359
|
+
let flags;
|
|
360
|
+
try {
|
|
361
|
+
flags = parseInitArgs(argv);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
writeLine(io.stderr, `${safeText(redact(error.message))}\n\n${INIT_USAGE}`);
|
|
364
|
+
return { exitCode: EXIT.error, summary: null };
|
|
365
|
+
}
|
|
366
|
+
if (flags.help) {
|
|
367
|
+
writeLine(io.stdout, INIT_USAGE);
|
|
368
|
+
return { exitCode: EXIT.ok, summary: null };
|
|
369
|
+
}
|
|
370
|
+
const json = Boolean(flags.json);
|
|
371
|
+
const dryRun = Boolean(flags['dry-run']);
|
|
372
|
+
const out = (text = '') => {
|
|
373
|
+
if (!json) writeLine(io.stdout, text);
|
|
374
|
+
};
|
|
375
|
+
const log = (text) => writeLine(io.stderr, text);
|
|
376
|
+
const summary = {
|
|
377
|
+
ok: false,
|
|
378
|
+
exit_code: EXIT.error,
|
|
379
|
+
dry_run: dryRun,
|
|
380
|
+
base_url: null,
|
|
381
|
+
credential: null,
|
|
382
|
+
login: { status: 'not_needed' },
|
|
383
|
+
setup: { checked: false, reason: 'no key' },
|
|
384
|
+
agents: [],
|
|
385
|
+
skills: [],
|
|
386
|
+
files_changed: [],
|
|
387
|
+
restart: [],
|
|
388
|
+
next_prompt: NEXT_PROMPT,
|
|
389
|
+
messages: [],
|
|
390
|
+
next_actions: [],
|
|
391
|
+
};
|
|
392
|
+
const finish = (exitCode) => {
|
|
393
|
+
summary.exit_code = exitCode;
|
|
394
|
+
summary.ok = exitCode === EXIT.ok;
|
|
395
|
+
if (json) writeLine(io.stdout, JSON.stringify(summary, null, 2));
|
|
396
|
+
return { exitCode, summary };
|
|
397
|
+
};
|
|
398
|
+
let key = null;
|
|
399
|
+
try {
|
|
400
|
+
const baseUrl = resolveBaseUrl(io.env);
|
|
401
|
+
summary.base_url = baseUrl;
|
|
402
|
+
const scope = parseScope(flags.scope);
|
|
403
|
+
const wanted = parseAgentList(flags.agents);
|
|
404
|
+
if (flags['key-stdin'] && ['no-wait', 'no-browser', 'name', 'timeout'].some((name) => flags[name] !== undefined)) {
|
|
405
|
+
throw new CliError('--key-stdin cannot be combined with browser approval options.');
|
|
406
|
+
}
|
|
407
|
+
if (flags['no-wait'] && flags['no-login']) throw new CliError('--no-wait cannot be combined with --no-login.');
|
|
408
|
+
let projectId;
|
|
409
|
+
if (flags.project !== undefined) {
|
|
410
|
+
projectId = String(flags.project).trim();
|
|
411
|
+
if (!PROJECT_ID.test(projectId)) throw new CliError('--project must be a CueApril project id.');
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// 1. Key.
|
|
415
|
+
let resolved;
|
|
416
|
+
if (flags['key-stdin']) {
|
|
417
|
+
const imported = await importApiKey(io, { dryRun });
|
|
418
|
+
resolved = { key: imported.key, source: 'stdin', path: imported.credentialsPath, saved: imported.saved };
|
|
419
|
+
summary.login = { status: dryRun ? 'verified' : 'imported' };
|
|
420
|
+
if (imported.changed) summary.files_changed.push(displayPath(io, imported.credentialsPath));
|
|
421
|
+
} else resolved = await resolveApiKey(io, { baseUrl });
|
|
422
|
+
let loggedIn = false;
|
|
423
|
+
const login = async (reason) => {
|
|
424
|
+
if (reason) log(reason);
|
|
425
|
+
loggedIn = true;
|
|
426
|
+
const result = await runLogin(loginArgs(flags), io, { embedded: true });
|
|
427
|
+
summary.login = {
|
|
428
|
+
status: result.status,
|
|
429
|
+
...(result.verificationUrl ? { verification_url: result.verificationUrl, code: result.code } : {}),
|
|
430
|
+
};
|
|
431
|
+
if (result.status !== 'approved' || !result.key) {
|
|
432
|
+
const code = result.status === 'pending' || result.exitCode === EXIT.timeout ? EXIT.timeout : EXIT.error;
|
|
433
|
+
if (result.verificationUrl) {
|
|
434
|
+
const resumeArgv = ['init', ...argv.filter((arg) => arg !== '--no-wait')];
|
|
435
|
+
const commands = installCommands(resumeArgv);
|
|
436
|
+
const resumeCommand = commands.npm;
|
|
437
|
+
summary.login.resume_command = resumeCommand;
|
|
438
|
+
summary.login.resume_commands = commands;
|
|
439
|
+
summary.next_actions = [
|
|
440
|
+
{ action: 'approve_in_browser', owner: 'administrator', verification_url: result.verificationUrl, code: result.code },
|
|
441
|
+
{ action: 'resume_init', command: resumeCommand, commands, argv: resumeArgv },
|
|
442
|
+
];
|
|
443
|
+
}
|
|
444
|
+
summary.messages.push(
|
|
445
|
+
result.status === 'pending'
|
|
446
|
+
? 'Approval is required. Open the verification link, check the code, then run resume_command; it reuses this request.'
|
|
447
|
+
: code === EXIT.timeout
|
|
448
|
+
? 'Approval was not received in time. Run `cueapril init` again to keep waiting; the link and code stay the same.'
|
|
449
|
+
: 'Login did not complete.',
|
|
450
|
+
);
|
|
451
|
+
throw Object.assign(new CliError(summary.messages.at(-1), { exitCode: code }), { reported: true });
|
|
452
|
+
}
|
|
453
|
+
if (result.credentialsPath) summary.files_changed.push(displayPath(io, result.credentialsPath));
|
|
454
|
+
return {
|
|
455
|
+
key: result.key,
|
|
456
|
+
source: 'store',
|
|
457
|
+
path: result.credentialsPath,
|
|
458
|
+
saved: result.saved,
|
|
459
|
+
};
|
|
460
|
+
};
|
|
461
|
+
if (!resolved) {
|
|
462
|
+
if (dryRun) summary.login = { status: 'skipped', reason: 'dry run: no key yet; a real run asks for approval' };
|
|
463
|
+
else if (flags['no-login']) {
|
|
464
|
+
summary.login = { status: 'auth_required' };
|
|
465
|
+
const importCommands = installCommands(['init', '--key-stdin', '--json']);
|
|
466
|
+
const approvalCommands = installCommands(['init', '--no-wait', '--no-browser', '--json']);
|
|
467
|
+
summary.next_actions = [
|
|
468
|
+
{ action: 'provide_api_key', environment_variable: 'CUEAPRIL_API_KEY', secure_input_command: importCommands.npm, commands: importCommands, argv: ['init', '--key-stdin', '--json'], message: 'Supply the key through a secret manager or local secure input, never in chat.' },
|
|
469
|
+
{ action: 'browser_approval', command: approvalCommands.npm, commands: approvalCommands, argv: ['init', '--no-wait', '--no-browser', '--json'] },
|
|
470
|
+
];
|
|
471
|
+
throw new CliError('No CueApril key found. Set CUEAPRIL_API_KEY, run `cueapril login`, or run init without --no-login.');
|
|
472
|
+
} else resolved = await login();
|
|
473
|
+
}
|
|
474
|
+
key = resolved?.key ?? null;
|
|
475
|
+
|
|
476
|
+
// 2. Verify.
|
|
477
|
+
if (key) {
|
|
478
|
+
let check = await verifyKey(io, baseUrl, key, projectId);
|
|
479
|
+
if (check.error?.status === 401 && resolved.source === 'store' && !loggedIn && !flags['no-login'] && !dryRun) {
|
|
480
|
+
resolved = await login('The stored key was not accepted (revoked or expired). Starting a new approval.');
|
|
481
|
+
key = resolved.key;
|
|
482
|
+
check = await verifyKey(io, baseUrl, key, projectId);
|
|
483
|
+
}
|
|
484
|
+
if (check.error) {
|
|
485
|
+
const error = check.error;
|
|
486
|
+
if (error.status === 401 || error.status === 403) {
|
|
487
|
+
const hint =
|
|
488
|
+
resolved.source === 'env'
|
|
489
|
+
? ` The key comes from ${resolved.envName}; replace or unset it.`
|
|
490
|
+
: ' Run `cueapril login` for a new key.';
|
|
491
|
+
throw new CliError(`${redact(error.message, [key])}${hint}`);
|
|
492
|
+
}
|
|
493
|
+
summary.setup =
|
|
494
|
+
error.code === 'not_found'
|
|
495
|
+
? { checked: false, reason: 'this CueApril server does not offer cueapril_check_setup yet' }
|
|
496
|
+
: { checked: false, reason: safeText(redact(error.message, [key]), 300) };
|
|
497
|
+
} else {
|
|
498
|
+
summary.setup = { checked: true, ...summariseSetup(check.raw, baseUrl) };
|
|
499
|
+
}
|
|
500
|
+
summary.credential = {
|
|
501
|
+
source: resolved.source,
|
|
502
|
+
masked: maskKey(key),
|
|
503
|
+
from: describeKeySource(resolved, (target) => (target ? displayPath(io, target) : 'not saved')),
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// 3. Plan agents and skills.
|
|
508
|
+
const agentIds =
|
|
509
|
+
wanted === 'auto' ? (await detectAgents(io)).filter((agent) => agent.detected).map((agent) => agent.id) : wanted;
|
|
510
|
+
const plan = agentIds.length ? await planAgentChanges({ agents: agentIds, baseUrl, key }, io) : [];
|
|
511
|
+
const skills = await planSkills(io, scope, key);
|
|
512
|
+
if (wanted === 'auto' && !agentIds.length) {
|
|
513
|
+
summary.messages.push(
|
|
514
|
+
'No supported coding agent was found (Claude Code, Codex, Gemini CLI, Cursor). The CLI works on its own: ' + `${RUN_COMMAND} assess --pr 123 --wait`,
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
const hasChanges =
|
|
518
|
+
plan.some((item) => item.action !== 'unchanged' && item.action !== 'error') ||
|
|
519
|
+
skills.some((item) => item.action !== 'unchanged');
|
|
520
|
+
|
|
521
|
+
out('CueApril init');
|
|
522
|
+
out(` Server: ${baseUrl}`);
|
|
523
|
+
out(` Key: ${summary.credential ? `${summary.credential.masked} from ${summary.credential.from}` : 'none yet'}`);
|
|
524
|
+
if (summary.setup.organisation) out(` Organisation: ${summary.setup.organisation}`);
|
|
525
|
+
if (key) printSetup(out, summary.setup);
|
|
526
|
+
|
|
527
|
+
if (dryRun) {
|
|
528
|
+
summary.agents = plan.map((item) => ({
|
|
529
|
+
agent: item.agent,
|
|
530
|
+
name: item.name,
|
|
531
|
+
action: item.action,
|
|
532
|
+
path: item.displayPath,
|
|
533
|
+
...(item.backupPath ? { backup_path: displayPath(io, item.backupPath) } : {}),
|
|
534
|
+
...(item.commands ? { commands: item.commands } : {}),
|
|
535
|
+
...(item.preview ? { preview: item.preview } : {}),
|
|
536
|
+
...(item.message ? { message: item.message } : {}),
|
|
537
|
+
}));
|
|
538
|
+
summary.skills = skills.map((item) => ({ path: item.displayPath, action: item.action }));
|
|
539
|
+
out('');
|
|
540
|
+
out('Plan (dry run: nothing was changed)');
|
|
541
|
+
for (const item of plan) {
|
|
542
|
+
out(` ${pad(item.name, 12)} ${agentPlanLine(item)}`);
|
|
543
|
+
for (const command of item.commands ?? []) out(` $ ${command}`);
|
|
544
|
+
if (item.preview && item.action !== 'unchanged' && item.action !== 'error') {
|
|
545
|
+
for (const line of item.preview.split('\n')) out(` ${line}`);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
for (const item of skills) out(` ${pad('Skill', 12)} ${item.action} ${item.displayPath}`);
|
|
549
|
+
for (const message of summary.messages) out(`\n${message}`);
|
|
550
|
+
return finish(EXIT.ok);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// 4. Confirm in an interactive terminal, then apply.
|
|
554
|
+
if (hasChanges && !flags.yes && !json && isTTY(io.stdin) && isTTY(io.stdout)) {
|
|
555
|
+
out('');
|
|
556
|
+
out('About to change:');
|
|
557
|
+
for (const item of plan) out(` ${pad(item.name, 12)} ${agentPlanLine(item)}`);
|
|
558
|
+
for (const item of skills) if (item.action !== 'unchanged') out(` ${pad('Skill', 12)} ${item.action} ${item.displayPath}`);
|
|
559
|
+
if (!(await confirm(io, 'Apply these changes? [Y/n] '))) {
|
|
560
|
+
out('Nothing was changed.');
|
|
561
|
+
summary.messages.push('Cancelled at the confirmation prompt; nothing was changed.');
|
|
562
|
+
return finish(EXIT.incomplete);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
const agentResults = await applyAgentChanges(plan, io);
|
|
566
|
+
const skillResults = await applySkills(io, skills);
|
|
567
|
+
summary.agents = agentResults.map((result) => ({
|
|
568
|
+
agent: result.agent,
|
|
569
|
+
name: result.name,
|
|
570
|
+
status: result.status,
|
|
571
|
+
path: result.path,
|
|
572
|
+
...(result.backupPath ? { backup_path: result.backupPath } : {}),
|
|
573
|
+
...(result.headersPath ? { headers_path: result.headersPath } : {}),
|
|
574
|
+
...(result.message ? { message: result.message } : {}),
|
|
575
|
+
}));
|
|
576
|
+
summary.skills = skillResults;
|
|
577
|
+
for (const result of agentResults) {
|
|
578
|
+
if (result.status === 'created' || result.status === 'updated') summary.files_changed.push(result.path);
|
|
579
|
+
if (result.backupPath) summary.files_changed.push(result.backupPath);
|
|
580
|
+
if (result.status === 'configured') summary.files_changed.push(`${result.path} (by claude mcp add-json)`);
|
|
581
|
+
if (result.headersChanged) summary.files_changed.push(result.headersPath);
|
|
582
|
+
if (['created', 'updated', 'configured'].includes(result.status)) summary.restart.push(AGENT_NAMES[result.agent]);
|
|
583
|
+
}
|
|
584
|
+
for (const result of skillResults) {
|
|
585
|
+
if (result.status === 'created' || result.status === 'updated') summary.files_changed.push(result.path);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
out('');
|
|
589
|
+
out('Agents (user-level MCP configuration)');
|
|
590
|
+
if (!agentResults.length) out(' none');
|
|
591
|
+
for (const result of agentResults) out(` ${pad(result.name, 12)} ${agentResultLine(result)}`);
|
|
592
|
+
out('');
|
|
593
|
+
out(`Skill (${scope} scope)`);
|
|
594
|
+
for (const result of skillResults) {
|
|
595
|
+
out(` ${result.path} ${result.status}${result.message ? `: ${result.message}` : ''}`);
|
|
596
|
+
}
|
|
597
|
+
out('');
|
|
598
|
+
if (summary.files_changed.length) {
|
|
599
|
+
out('Files changed');
|
|
600
|
+
for (const file of summary.files_changed) out(` ${file}`);
|
|
601
|
+
} else {
|
|
602
|
+
out('No changes: CueApril was already set up here.');
|
|
603
|
+
}
|
|
604
|
+
for (const message of summary.messages) out(`\n${message}`);
|
|
605
|
+
out('');
|
|
606
|
+
const steps = [];
|
|
607
|
+
if (summary.setup.checked && !summary.setup.ready) steps.push('finish the setup steps above');
|
|
608
|
+
if (summary.restart.length) {
|
|
609
|
+
const names = summary.restart;
|
|
610
|
+
const list = names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0];
|
|
611
|
+
steps.push(`restart ${list} so ${names.length > 1 ? 'they load' : 'it loads'} the CueApril tools`);
|
|
612
|
+
}
|
|
613
|
+
steps.push('ask your agent:');
|
|
614
|
+
out(`Next: ${steps.join(', then ')}`);
|
|
615
|
+
out(` "${NEXT_PROMPT}"`);
|
|
616
|
+
// An agent named with --agents must succeed. Agents found automatically
|
|
617
|
+
// are best effort: one that cannot be configured is reported, and init
|
|
618
|
+
// fails only if none of them could be.
|
|
619
|
+
const agentFailures = agentResults.filter((result) => result.status === 'failed');
|
|
620
|
+
const agentsOk =
|
|
621
|
+
wanted === 'auto'
|
|
622
|
+
? !agentResults.length || agentFailures.length < agentResults.length
|
|
623
|
+
: agentFailures.length === 0;
|
|
624
|
+
if (wanted === 'auto' && agentsOk) {
|
|
625
|
+
for (const result of agentFailures) summary.messages.push(`${result.name} was not configured: ${result.message}`);
|
|
626
|
+
}
|
|
627
|
+
const skillsOk = !skillResults.some((result) => result.status === 'failed');
|
|
628
|
+
return finish(agentsOk && skillsOk ? EXIT.ok : EXIT.error);
|
|
629
|
+
} catch (error) {
|
|
630
|
+
const message = safeText(redact(error.message, key ? [key] : []), 500);
|
|
631
|
+
if (!error.reported) summary.messages.push(message);
|
|
632
|
+
log(summary.login.status === 'pending' ? message : `Error: ${message}`);
|
|
633
|
+
return finish(error.exitCode ?? EXIT.error);
|
|
634
|
+
}
|
|
635
|
+
}
|