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/doctor.mjs ADDED
@@ -0,0 +1,186 @@
1
+ // cueapril doctor: checks the local setup an agent depends on and says how to
2
+ // fix each problem. Exit 0 when nothing fails, 5 otherwise. Readiness steps a
3
+ // person still has to take (for example installing the GitHub App) are
4
+ // warnings, not failures, matching init.
5
+ import { parseArgs } from 'node:util';
6
+ import { RUN_COMMAND } from './client.mjs';
7
+ import { EXIT, defaultDeps, displayPath, readFileIfExists, redact, safeText, writeLine } from './io.mjs';
8
+ import { baseUrlSource, createHttpClient, resolveBaseUrl } from './http.mjs';
9
+ import { describeKeySource, maskKey, resolveApiKey } from './key-store.mjs';
10
+ import { inspectAgents } from './agents.mjs';
11
+ import { CHECK_SETUP_TOOL, bundledSkillPath, skillTargets, summariseSetup } from './init.mjs';
12
+
13
+ export const DOCTOR_USAGE = `Usage: cueapril doctor [--project <id>] [--json]
14
+
15
+ Checks the CueApril server URL, your key (masked), the API health, whether the
16
+ key is accepted, which coding agents have a CueApril MCP entry and whether the
17
+ cueapril-qa skill is installed. Use --project when the key covers several
18
+ projects. Exit 0 when nothing fails, 5 otherwise.`;
19
+
20
+ const INIT_COMMAND = `${RUN_COMMAND} init`;
21
+ const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
22
+ const LABELS = {
23
+ server: 'Server',
24
+ key: 'Key',
25
+ health: 'API health',
26
+ key_valid: 'Key valid',
27
+ readiness: 'Readiness',
28
+ mcp: 'Agent MCP',
29
+ skill: 'Skill',
30
+ };
31
+
32
+ function line(check) {
33
+ const marker = { ok: '[ok] ', warn: '[warn]', fail: '[fail]', skip: '[skip]' }[check.status];
34
+ const label = check.label ?? LABELS[check.id] ?? check.id;
35
+ const padded = label.length >= 13 ? `${label} ` : label + ' '.repeat(13 - label.length);
36
+ return `${marker} ${padded}${check.message}${check.fix ? `\n${' '.repeat(21)}Fix: ${check.fix}` : ''}`;
37
+ }
38
+
39
+ /** Runs the checks. Returns { exitCode, report }; --json prints the report as one object. */
40
+ export async function runDoctor(argv = [], deps = {}) {
41
+ const io = defaultDeps(deps);
42
+ let flags;
43
+ let projectId;
44
+ try {
45
+ ({ values: flags } = parseArgs({
46
+ args: argv,
47
+ allowPositionals: false,
48
+ strict: true,
49
+ options: { json: { type: 'boolean' }, project: { type: 'string' }, help: { type: 'boolean', short: 'h' } },
50
+ }));
51
+ if (flags.project !== undefined) {
52
+ projectId = String(flags.project).trim();
53
+ if (!PROJECT_ID.test(projectId)) throw new Error('--project must be a CueApril project id.');
54
+ }
55
+ } catch (error) {
56
+ writeLine(io.stderr, `${safeText(redact(error.message))}\n\n${DOCTOR_USAGE}`);
57
+ return { exitCode: EXIT.error, report: null };
58
+ }
59
+ if (flags.help) {
60
+ writeLine(io.stdout, DOCTOR_USAGE);
61
+ return { exitCode: EXIT.ok, report: null };
62
+ }
63
+ const checks = [];
64
+ const add = (id, status, message, extra = {}) => {
65
+ checks.push({ id, status, message: safeText(message, 400), ...extra });
66
+ };
67
+ const report = { ok: false, exit_code: EXIT.error, base_url: null, checks, agents: [] };
68
+ const finish = () => {
69
+ const failed = checks.some((check) => check.status === 'fail');
70
+ report.exit_code = failed ? EXIT.error : EXIT.ok;
71
+ report.ok = !failed;
72
+ if (flags.json) {
73
+ writeLine(io.stdout, JSON.stringify(report, null, 2));
74
+ } else {
75
+ for (const check of checks) writeLine(io.stdout, line(check));
76
+ const warnings = checks.filter((check) => check.status === 'warn').length;
77
+ writeLine(
78
+ io.stdout,
79
+ failed
80
+ ? `\nCueApril is not set up correctly. Run: ${INIT_COMMAND}`
81
+ : `\nAll good${warnings ? ` (${warnings} warning${warnings === 1 ? '' : 's'})` : ''}.`,
82
+ );
83
+ }
84
+ return { exitCode: report.exit_code, report };
85
+ };
86
+
87
+ let baseUrl;
88
+ try {
89
+ baseUrl = resolveBaseUrl(io.env);
90
+ report.base_url = baseUrl;
91
+ const source = baseUrlSource(io.env);
92
+ add('server', 'ok', `${baseUrl} (${source === 'default' ? 'default' : `from ${source}`})`);
93
+ } catch (error) {
94
+ add('server', 'fail', error.message, { fix: 'Set CUEAPRIL_URL to your CueApril address, or unset it.' });
95
+ return finish();
96
+ }
97
+
98
+ let resolved = null;
99
+ try {
100
+ resolved = await resolveApiKey(io, { baseUrl });
101
+ if (resolved) {
102
+ add('key', 'ok', `${maskKey(resolved.key)} from ${describeKeySource(resolved, (target) => displayPath(io, target))}`);
103
+ } else {
104
+ add('key', 'fail', 'No CueApril key found.', { fix: INIT_COMMAND });
105
+ }
106
+ } catch (error) {
107
+ add('key', 'fail', error.message);
108
+ }
109
+ const secrets = resolved ? [resolved.key] : [];
110
+
111
+ const client = createHttpClient(io, { baseUrl });
112
+ try {
113
+ await client.health();
114
+ add('health', 'ok', `${baseUrl}/api/v1/health answered`);
115
+ } catch (error) {
116
+ add('health', 'fail', redact(error.message, secrets));
117
+ }
118
+
119
+ if (resolved) {
120
+ try {
121
+ const raw = await client.callTool(CHECK_SETUP_TOOL, projectId ? { project_id: projectId } : {}, resolved.key, { timeoutMs: 30_000 });
122
+ const setup = summariseSetup(raw, baseUrl);
123
+ add('key_valid', 'ok', `Accepted${setup.organisation ? ` for ${setup.organisation}` : ''}`);
124
+ if (setup.ready) {
125
+ add('readiness', 'ok', 'Ready to test pull requests');
126
+ } else {
127
+ const first = setup.issues[0];
128
+ add(
129
+ 'readiness',
130
+ 'warn',
131
+ first
132
+ ? `${setup.issues.length} setup step${setup.issues.length === 1 ? '' : 's'} left, first: ${first.project ? `${first.project}: ` : ''}${first.message}`
133
+ : setup.next_step
134
+ ? `Not ready yet: ${setup.next_step}`
135
+ : 'Not ready to test pull requests yet',
136
+ first?.fix_url ? { fix: first.fix_url } : { fix: 'Open CueApril in the browser to finish setup.' },
137
+ );
138
+ }
139
+ } catch (error) {
140
+ if (error.status === 401 || error.status === 403) {
141
+ add('key_valid', 'fail', redact(error.message, secrets), {
142
+ fix: resolved.source === 'env' ? `Replace or unset ${resolved.envName}.` : `${RUN_COMMAND} login`,
143
+ });
144
+ } else if (error.code === 'not_found') {
145
+ add('key_valid', 'warn', 'This CueApril server does not offer cueapril_check_setup yet, so the key was not checked.');
146
+ } else {
147
+ add('key_valid', 'fail', redact(error.message, secrets));
148
+ }
149
+ }
150
+ } else {
151
+ add('key_valid', 'skip', 'Not checked: no key');
152
+ }
153
+
154
+ const agents = await inspectAgents(io, { baseUrl, key: resolved?.key });
155
+ const detected = agents.filter((agent) => agent.detected || agent.state !== 'missing');
156
+ report.agents = detected.map(({ id, name, state, path, message }) => ({ id, name, state, path, ...(message ? { message } : {}) }));
157
+ for (const agent of detected) {
158
+ const fix = `${INIT_COMMAND} --agents ${agent.id}`;
159
+ if (agent.state === 'current') add('agent', 'ok', `CueApril MCP entry in ${agent.path}`, { label: agent.name });
160
+ else if (agent.state === 'different') {
161
+ add('agent', 'warn', `The CueApril entry in ${agent.path} uses a different key or URL`, { label: agent.name, fix });
162
+ } else if (agent.state === 'unreadable') {
163
+ add('agent', 'warn', agent.message || `Could not read ${agent.path}`, { label: agent.name });
164
+ } else add('agent', 'warn', 'No CueApril MCP entry', { label: agent.name, fix });
165
+ }
166
+ if (!detected.length) {
167
+ add('mcp', 'warn', 'No supported coding agent found (Claude Code, Codex, Gemini CLI, Cursor). The CLI works on its own.');
168
+ } else if (!detected.some((agent) => agent.state === 'current')) {
169
+ add('mcp', 'fail', 'No coding agent has a working CueApril MCP entry.', { fix: INIT_COMMAND });
170
+ }
171
+
172
+ const bundled = await io.fs.readFile(bundledSkillPath(), 'utf8').catch(() => null);
173
+ const installed = [];
174
+ for (const target of [...skillTargets('user', io), ...skillTargets('project', io)]) {
175
+ const content = await readFileIfExists(io, target).catch(() => null);
176
+ if (content !== null && !installed.some((item) => item.target === target)) installed.push({ target, content });
177
+ }
178
+ if (!installed.length) {
179
+ add('skill', 'fail', 'The cueapril-qa skill is not installed.', { fix: INIT_COMMAND });
180
+ } else {
181
+ const where = installed.map((item) => displayPath(io, item.target)).join(', ');
182
+ const stale = bundled !== null && installed.some((item) => item.content !== bundled);
183
+ add('skill', stale ? 'warn' : 'ok', stale ? `An older cueapril-qa skill is installed (${where})` : `Installed at ${where}`, stale ? { fix: INIT_COMMAND } : {});
184
+ }
185
+ return finish();
186
+ }
package/http.mjs ADDED
@@ -0,0 +1,263 @@
1
+ // Minimal, safe HTTP client for the CueApril CLI. It speaks JSON to one base
2
+ // URL, refuses redirects and plaintext HTTP except on localhost, bounds every
3
+ // response, and never puts a key into an error message.
4
+ import { defaultDeps, redact, safeText } from './io.mjs';
5
+ import {
6
+ AGENT_CLIENT_HEADER,
7
+ CLIENT_IDENTIFIER,
8
+ CLI_VERSION as CLIENT_VERSION,
9
+ DEFAULT_BASE_URL as CLIENT_DEFAULT_BASE_URL,
10
+ USER_AGENT as CLIENT_USER_AGENT,
11
+ normalizeBaseUrl,
12
+ } from './client.mjs';
13
+
14
+ // Shared with client.mjs, so every command reports one version and uses one
15
+ // base-URL rule. The npm package builder checks CLI_VERSION against package.json.
16
+ export const CLI_VERSION = CLIENT_VERSION;
17
+ export const DEFAULT_BASE_URL = CLIENT_DEFAULT_BASE_URL;
18
+ /** Matches AGENT_CLIENT_HEADER in agent-contracts.ts. */
19
+ export const CLIENT_HEADER = AGENT_CLIENT_HEADER;
20
+ export const CLIENT_ID = CLIENT_IDENTIFIER;
21
+ export const USER_AGENT = CLIENT_USER_AGENT;
22
+ export const DEFAULT_TIMEOUT_MS = 30_000;
23
+ export const MAX_RESPONSE_BYTES = 10_000_000;
24
+
25
+ const TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;
26
+ // Printable ASCII without spaces: anything else could split or forge a header.
27
+ const HEADER_TOKEN = /^[\x21-\x7e]{8,4096}$/;
28
+
29
+ export class HttpError extends Error {
30
+ constructor(message, { status = null, code = 'error', retryAfterSeconds = null, body = null } = {}) {
31
+ super(message);
32
+ this.name = 'HttpError';
33
+ this.status = status;
34
+ this.code = code;
35
+ this.retryAfterSeconds = retryAfterSeconds;
36
+ this.body = body;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Validates and canonicalises a base URL with client.mjs's rule: HTTPS, or
42
+ * HTTP on localhost; no credentials, query or fragment; no trailing slash.
43
+ * Credentials are keyed by the result, so equivalent spellings share one key.
44
+ */
45
+ export function normaliseBaseUrl(raw) {
46
+ const text = String(raw ?? '').trim();
47
+ try {
48
+ return normalizeBaseUrl(text);
49
+ } catch (error) {
50
+ throw new HttpError(`The CueApril URL "${safeText(text, 120)}" is not usable (${safeText(error.message, 200)}).`, {
51
+ code: 'invalid_url',
52
+ });
53
+ }
54
+ }
55
+
56
+ function clean(value) {
57
+ return typeof value === 'string' && value.trim() ? value.trim() : '';
58
+ }
59
+
60
+ /** Where the base URL comes from: CUEAPRIL_URL, then TENHAW_URL, then the default. */
61
+ export function baseUrlSource(env = {}) {
62
+ if (clean(env.CUEAPRIL_URL)) return 'CUEAPRIL_URL';
63
+ if (clean(env.TENHAW_URL)) return 'TENHAW_URL';
64
+ return 'default';
65
+ }
66
+
67
+ export function resolveBaseUrl(env = {}) {
68
+ return normaliseBaseUrl(clean(env.CUEAPRIL_URL) || clean(env.TENHAW_URL) || DEFAULT_BASE_URL);
69
+ }
70
+
71
+ export function isHeaderSafeToken(token) {
72
+ return typeof token === 'string' && HEADER_TOKEN.test(token);
73
+ }
74
+
75
+ async function readBounded(response, limit) {
76
+ const declared = Number(response.headers?.get?.('content-length'));
77
+ const tooLarge = () =>
78
+ new HttpError(`CueApril's response is larger than the ${limit}-byte limit.`, {
79
+ status: response.status,
80
+ code: 'response_too_large',
81
+ });
82
+ if (Number.isFinite(declared) && declared > limit) {
83
+ await response.body?.cancel?.().catch(() => {});
84
+ throw tooLarge();
85
+ }
86
+ if (!response.body || typeof response.body.getReader !== 'function') {
87
+ const text = await response.text();
88
+ if (Buffer.byteLength(text, 'utf8') > limit) throw tooLarge();
89
+ return text;
90
+ }
91
+ const reader = response.body.getReader();
92
+ const chunks = [];
93
+ let total = 0;
94
+ for (;;) {
95
+ const { done, value } = await reader.read();
96
+ if (done) break;
97
+ total += value.byteLength;
98
+ if (total > limit) {
99
+ await reader.cancel().catch(() => {});
100
+ throw tooLarge();
101
+ }
102
+ chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
103
+ }
104
+ return Buffer.concat(chunks).toString('utf8');
105
+ }
106
+
107
+ function serverMessage(body) {
108
+ if (!body || typeof body !== 'object') return '';
109
+ for (const field of ['message', 'error_description', 'detail', 'error']) {
110
+ const value = body[field];
111
+ if (typeof value === 'string' && value.trim()) return value;
112
+ if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value.join('; ');
113
+ }
114
+ return '';
115
+ }
116
+
117
+ const STATUS_CODES = new Map([
118
+ [400, 'invalid_request'],
119
+ [401, 'unauthorized'],
120
+ [403, 'forbidden'],
121
+ [404, 'not_found'],
122
+ [405, 'not_found'],
123
+ [409, 'conflict'],
124
+ [410, 'gone'],
125
+ [422, 'invalid_request'],
126
+ [429, 'rate_limited'],
127
+ ]);
128
+
129
+ function retryAfter(response) {
130
+ const raw = response.headers?.get?.('retry-after');
131
+ if (!raw) return null;
132
+ const seconds = Number(raw);
133
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds, 3600);
134
+ const date = Date.parse(raw);
135
+ if (Number.isFinite(date)) return Math.max(0, Math.min(3600, Math.ceil((date - Date.now()) / 1000)));
136
+ return null;
137
+ }
138
+
139
+ function errorFromResponse(response, body, secrets) {
140
+ const status = response.status;
141
+ const code = STATUS_CODES.get(status) ?? (status >= 500 ? 'server_error' : 'http_error');
142
+ const detail = safeText(redact(serverMessage(body), secrets), 300);
143
+ const hint =
144
+ status === 401
145
+ ? ' The API key was not accepted: it may be revoked or expired. Run `cueapril login` for a new key.'
146
+ : status === 403
147
+ ? ' The API key does not have access to this.'
148
+ : '';
149
+ const message = `CueApril answered ${status} (${code})${detail ? `: ${detail}` : '.'}${hint}`;
150
+ return new HttpError(message, {
151
+ status,
152
+ code,
153
+ retryAfterSeconds: status === 429 || status === 503 ? retryAfter(response) : null,
154
+ body: body && typeof body === 'object' ? JSON.parse(redact(JSON.stringify(body), secrets)) : null,
155
+ });
156
+ }
157
+
158
+ function networkError(error, baseUrl, timeoutMs, secrets) {
159
+ const name = error?.name;
160
+ if (name === 'TimeoutError' || name === 'AbortError') {
161
+ return new HttpError(`CueApril at ${baseUrl} did not answer within ${Math.round(timeoutMs / 1000)} s.`, {
162
+ code: 'timeout',
163
+ });
164
+ }
165
+ const cause = error?.cause;
166
+ const reason = safeText(redact(cause?.code || cause?.message || error?.message || 'unknown error', secrets), 160);
167
+ if (/redirect/i.test(`${error?.message} ${cause?.message}`)) {
168
+ return new HttpError(
169
+ `CueApril at ${baseUrl} answered with a redirect, which the CLI refuses. Check CUEAPRIL_URL.`,
170
+ { code: 'redirect' },
171
+ );
172
+ }
173
+ return new HttpError(`Could not reach CueApril at ${baseUrl} (${reason}).`, { code: 'network_error' });
174
+ }
175
+
176
+ /**
177
+ * Creates a client bound to one base URL. request() resolves to the parsed
178
+ * JSON body (null for an empty body) and throws HttpError otherwise.
179
+ */
180
+ export function createHttpClient(deps = {}, { baseUrl } = {}) {
181
+ const resolved = defaultDeps(deps);
182
+ const origin = baseUrl ? normaliseBaseUrl(baseUrl) : resolveBaseUrl(resolved.env);
183
+ async function request(
184
+ path,
185
+ { method = 'GET', body, key, timeoutMs = DEFAULT_TIMEOUT_MS, maxBytes = MAX_RESPONSE_BYTES, idempotencyKey } = {},
186
+ ) {
187
+ if (typeof path !== 'string' || !path.startsWith('/')) throw new HttpError('Request path must start with /.');
188
+ const secrets = key ? [key] : [];
189
+ const headers = {
190
+ Accept: 'application/json',
191
+ [CLIENT_HEADER]: CLIENT_ID,
192
+ 'User-Agent': USER_AGENT,
193
+ };
194
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
195
+ if (key !== undefined && key !== null) {
196
+ if (!isHeaderSafeToken(key)) {
197
+ throw new HttpError('The API key contains characters that cannot be sent in a header.', {
198
+ code: 'invalid_key',
199
+ });
200
+ }
201
+ headers.Authorization = `Bearer ${key}`;
202
+ }
203
+ if (idempotencyKey) {
204
+ if (!/^[\x21-\x7e]{1,200}$/.test(idempotencyKey)) throw new HttpError('Invalid idempotency key.');
205
+ headers['Idempotency-Key'] = idempotencyKey;
206
+ }
207
+ let response;
208
+ try {
209
+ response = await resolved.fetch(origin + path, {
210
+ method,
211
+ headers,
212
+ body: body === undefined ? undefined : JSON.stringify(body),
213
+ redirect: 'error',
214
+ signal: AbortSignal.timeout(timeoutMs),
215
+ });
216
+ } catch (error) {
217
+ throw networkError(error, origin, timeoutMs, secrets);
218
+ }
219
+ let raw;
220
+ try {
221
+ raw = await readBounded(response, maxBytes);
222
+ } catch (error) {
223
+ if (error instanceof HttpError) throw error;
224
+ throw networkError(error, origin, timeoutMs, secrets);
225
+ }
226
+ let value = null;
227
+ if (raw.trim()) {
228
+ try {
229
+ value = JSON.parse(raw);
230
+ } catch {
231
+ if (response.ok) {
232
+ throw new HttpError(`CueApril answered ${response.status} with a body that is not JSON.`, {
233
+ status: response.status,
234
+ code: 'invalid_response',
235
+ });
236
+ }
237
+ }
238
+ }
239
+ if (!response.ok) throw errorFromResponse(response, value, secrets);
240
+ return value;
241
+ }
242
+ return {
243
+ baseUrl: origin,
244
+ request,
245
+ callTool: (name, args, key, options) => callToolWith(request, name, args, key, options),
246
+ health: (options = {}) => request('/api/v1/health', { timeoutMs: 15_000, ...options }),
247
+ };
248
+ }
249
+
250
+ async function callToolWith(request, name, args = {}, key, options = {}) {
251
+ if (typeof name !== 'string' || !TOOL_NAME.test(name)) throw new HttpError('Invalid tool name.');
252
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
253
+ throw new HttpError('Tool arguments must be a JSON object.');
254
+ }
255
+ if (!key) throw new HttpError('An API key is required for agent tools.', { code: 'unauthorized' });
256
+ return request(`/api/v1/quality/agent-tools/${name}`, { ...options, method: 'POST', body: args, key });
257
+ }
258
+
259
+ /** POST /api/v1/quality/agent-tools/<name> with the key as bearer. */
260
+ export async function callTool(name, args, key, deps = {}, options = {}) {
261
+ const { baseUrl, ...requestOptions } = options;
262
+ return createHttpClient(deps, { baseUrl }).callTool(name, args, key, requestOptions);
263
+ }