notusci 0.1.10 → 0.1.14
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/package.json +1 -1
- package/src/cli.mjs +38 -4
- package/src/core.mjs +79 -5
package/package.json
CHANGED
package/src/cli.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { homedir, hostname } from "node:os";
|
|
|
7
7
|
import { delimiter, dirname, join } from "node:path";
|
|
8
8
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
9
9
|
import {
|
|
10
|
-
CliError, HELP, NPX, apiUrl, authFile, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, jsonText, parseCommand, pickWorkflow, renderError,
|
|
10
|
+
CliError, HELP, NPX, addTakeoverGuard, apiUrl, authFile, billingText, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, jsonText, parseCommand, pickWorkflow, renderError,
|
|
11
11
|
repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain, sourceBase, sourceIdentity,
|
|
12
12
|
} from "./core.mjs";
|
|
13
13
|
|
|
@@ -63,12 +63,16 @@ async function api(s, path, { method = "GET", query = {}, body, bearer = s.token
|
|
|
63
63
|
if (body !== undefined) headers["content-type"] = "application/json";
|
|
64
64
|
let response;
|
|
65
65
|
let text = "";
|
|
66
|
+
let waited = false;
|
|
66
67
|
for (let attempt = 0; ; attempt++) {
|
|
67
68
|
const timeoutMs = Math.max(1000, Math.min(timeoutSeconds * 1000, deadline - Date.now()));
|
|
68
69
|
try {
|
|
69
70
|
response = await fetch(url, { method, headers, body: typeof body === "string" || body === undefined ? body : JSON.stringify(body),
|
|
70
71
|
signal: AbortSignal.timeout(timeoutMs) });
|
|
71
72
|
text = await response.text();
|
|
73
|
+
// Rate limited: wait once as told, then report (spec 071).
|
|
74
|
+
const wait = Math.min(60, Number(response.headers.get("retry-after")) || 60) * 1000;
|
|
75
|
+
if (response.status === 429 && !waited && Date.now() + wait < deadline) { waited = true; await sleep(wait); continue; }
|
|
72
76
|
if (response.status < 500 || attempt === 2) break;
|
|
73
77
|
} catch {
|
|
74
78
|
if (attempt === 2 || Date.now() >= deadline) throw new CliError({ code: "network", error: `Cannot reach NotusCI at ${s.url}`, next: "Retry the same command." });
|
|
@@ -218,10 +222,36 @@ async function init(s, input) {
|
|
|
218
222
|
}
|
|
219
223
|
}
|
|
220
224
|
if (input.billing) return billing(s, { repo, timeoutSeconds: 90 });
|
|
221
|
-
|
|
225
|
+
const githubFirst = input.githubFirst && await githubFirstSetup(s, root, listed(me, repo).repo, workflow, input.githubFirst, deadline);
|
|
226
|
+
print({ status: "ready", user: me.user, repo: listed(me, repo).repo, scopes: me.scopes, workflow, mcp, ...(githubFirst && { githubFirst }), next: `${NPX} verify` });
|
|
222
227
|
}
|
|
223
228
|
|
|
224
|
-
/**
|
|
229
|
+
/**
|
|
230
|
+
* Spec 070: guards the workflow's job so GitHub skips it during takeover, then turns GitHub-first on.
|
|
231
|
+
* A workflow with more than one job stays on GitHub, watched only. Never commits or pushes.
|
|
232
|
+
* @param {Session} s @param {string} root @param {string} repo @param {string} workflow @param {string} plan @param {number} deadline
|
|
233
|
+
*/
|
|
234
|
+
async function githubFirstSetup(s, root, repo, workflow, plan, deadline) {
|
|
235
|
+
const path = join(root, workflow);
|
|
236
|
+
const before = readFileSync(path, "utf8");
|
|
237
|
+
const { text, jobs } = addTakeoverGuard(before);
|
|
238
|
+
const takeover = jobs === 1;
|
|
239
|
+
if (takeover && text !== before) writeFileSync(path, text);
|
|
240
|
+
const saved = await api(s, `/api/repos/${repo}/settings`, { method: "PUT", deadline,
|
|
241
|
+
body: { githubFirst: { plan }, ...(takeover && { pushWorkflow: workflow }) } });
|
|
242
|
+
const diff = execFileSync("git", ["diff", "--", workflow], { cwd: root, encoding: "utf8" });
|
|
243
|
+
return {
|
|
244
|
+
plan, takeover: takeover ? "on" : `off: ${workflow} has ${jobs} jobs and NotusCI runs one; pushes stay on GitHub, watched`,
|
|
245
|
+
...(diff && { diff }), variables: saved.variables,
|
|
246
|
+
next: [
|
|
247
|
+
...(diff ? [`Commit and push ${workflow}`] : []),
|
|
248
|
+
"Tell the human: in branch protection, require the NotusCI check instead of the GitHub job",
|
|
249
|
+
...(saved.next ? [`Tell the human: ${saved.next}`] : []),
|
|
250
|
+
],
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** @param {Session} s @param {{repo?: string, timeoutSeconds: number, interval?: "month" | "year"}} input */
|
|
225
255
|
async function billing(s, input) {
|
|
226
256
|
const repo = repoOrOrigin(input.repo);
|
|
227
257
|
const deadline = Date.now() + input.timeoutSeconds * 1000;
|
|
@@ -232,7 +262,7 @@ async function billing(s, input) {
|
|
|
232
262
|
}
|
|
233
263
|
let action = s.state.billing;
|
|
234
264
|
if (!action || action.repo.toLowerCase() !== repo.toLowerCase() || new Date(action.expiresAt).getTime() <= Date.now()) {
|
|
235
|
-
action = { ...await api(s, "/api/billing/checkouts", { method: "POST", body: { repo }, deadline }), repo };
|
|
265
|
+
action = { ...await api(s, "/api/billing/checkouts", { method: "POST", body: { repo, ...(input.interval ? { interval: input.interval } : {}) }, deadline }), repo };
|
|
236
266
|
save(s, { token: s.state.token, pending: s.state.pending, billing: action });
|
|
237
267
|
}
|
|
238
268
|
while (Date.now() + 2_000 <= deadline) {
|
|
@@ -347,6 +377,10 @@ async function main(s, input) {
|
|
|
347
377
|
case "doctor": return doctor(s);
|
|
348
378
|
case "login": return login(s, input);
|
|
349
379
|
case "billing": return billing(s, input);
|
|
380
|
+
case "billing status": {
|
|
381
|
+
const summary = await api(s, "/api/billing/summary", { query: { repo: repoOrOrigin(input.repo) } });
|
|
382
|
+
return input.json ? print(summary) : process.stdout.write(billingText(summary));
|
|
383
|
+
}
|
|
350
384
|
case "usage": {
|
|
351
385
|
const repo = repoOrOrigin(input.repo);
|
|
352
386
|
return print(input.capUsd === undefined ? await api(s, "/api/usage", { query: { repo } })
|
package/src/core.mjs
CHANGED
|
@@ -29,7 +29,7 @@ function usage(error) {
|
|
|
29
29
|
|
|
30
30
|
/** @type {Record<string, Record<string, {type: "string" | "boolean"}>>} */
|
|
31
31
|
const OPTIONS = {
|
|
32
|
-
init: { scope: { type: "string" }, "no-mcp": { type: "boolean" }, billing: { type: "boolean" } },
|
|
32
|
+
init: { scope: { type: "string" }, "no-mcp": { type: "boolean" }, billing: { type: "boolean" }, "github-first": { type: "string" } },
|
|
33
33
|
login: { scope: { type: "string" } },
|
|
34
34
|
doctor: {}, logout: {}, token: {}, whoami: {}, repos: {}, version: {}, "--version": {},
|
|
35
35
|
target: { repo: { type: "string" }, file: { type: "string" }, "auto-promote": { type: "string" }, "auto-release": { type: "string" } },
|
|
@@ -43,14 +43,14 @@ const OPTIONS = {
|
|
|
43
43
|
approve: { repo: { type: "string" } },
|
|
44
44
|
repo: { repo: { type: "string" }, settings: { type: "string" }, "push-workflow": { type: "string" }, off: { type: "boolean" }, "image-from-workspace": { type: "string" }, "image-from-dockerfile": { type: "boolean" } },
|
|
45
45
|
migrations: { repo: { type: "string" }, push: { type: "string" }, reason: { type: "string" }, "force-destructive": { type: "boolean" } },
|
|
46
|
-
billing: { repo: { type: "string" }, timeout: { type: "string" } },
|
|
46
|
+
billing: { repo: { type: "string" }, timeout: { type: "string" }, yearly: { type: "boolean" }, json: { type: "boolean" } },
|
|
47
47
|
usage: { repo: { type: "string" }, cap: { type: "string" } },
|
|
48
48
|
api: { data: { type: "string" } },
|
|
49
49
|
};
|
|
50
50
|
|
|
51
51
|
export const HELP = {
|
|
52
52
|
commands: [
|
|
53
|
-
"init [--scope SCOPES] [--no-mcp] [--billing]", "billing [--repo OWNER/REPO] [--timeout SECONDS]", "usage [--repo OWNER/REPO] [--cap USD]", "doctor",
|
|
53
|
+
"init [--scope SCOPES] [--no-mcp] [--billing] [--github-first free|pro|team|enterprise]", "billing [--repo OWNER/REPO] [--yearly] [--timeout SECONDS]", "billing status [--repo OWNER/REPO] [--json]", "usage [--repo OWNER/REPO] [--cap USD]", "doctor",
|
|
54
54
|
"login [--scope SCOPES]", "logout", "whoami", "repos", "token list", "token revoke ID",
|
|
55
55
|
"target set [--repo OWNER/REPO] [--file TARGET.json] [--auto-promote on|off] [--auto-release on|off]",
|
|
56
56
|
"secret set NAME [--repo OWNER/REPO] (value on stdin)", "secret list [--repo OWNER/REPO]", "secret rm NAME [--repo OWNER/REPO]",
|
|
@@ -114,7 +114,9 @@ export function parseCommand(args) {
|
|
|
114
114
|
const scopes = [...new Set((values.scope ?? DEFAULT_SCOPES).split(","))];
|
|
115
115
|
const unknown = scopes.filter(scope => !SCOPES.includes(scope));
|
|
116
116
|
if (unknown.length) throw usage(`unknown scope ${unknown.join(",")}; scopes are ${SCOPES.join(",")}`);
|
|
117
|
-
|
|
117
|
+
const githubFirst = values["github-first"];
|
|
118
|
+
if (githubFirst !== undefined && !["free", "pro", "team", "enterprise"].includes(githubFirst)) throw usage("--github-first takes your GitHub plan: free, pro, team or enterprise");
|
|
119
|
+
return command === "init" ? { command, scopes, mcp: !values["no-mcp"], billing: values.billing === true, ...(githubFirst && { githubFirst }) } : { command, scopes };
|
|
118
120
|
}
|
|
119
121
|
if (["doctor", "logout", "whoami", "repos"].includes(command)) { expect(); return { command }; }
|
|
120
122
|
if (command === "version" || command === "--version") { expect(); return { command: "version" }; }
|
|
@@ -179,7 +181,8 @@ export function parseCommand(args) {
|
|
|
179
181
|
if (values.workflow === "") throw usage("--workflow must not be empty");
|
|
180
182
|
return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540, ...(values["no-reuse"] ? { reuse: false } : {}) };
|
|
181
183
|
}
|
|
182
|
-
if (command === "billing") { expect(); return { command, repo: values.repo,
|
|
184
|
+
if (command === "billing" && positionals[0] === "status") { expect("status"); return { command: "billing status", repo: values.repo, json: values.json === true }; }
|
|
185
|
+
if (command === "billing") { expect(); return { command, repo: values.repo, timeoutSeconds: timeoutSeconds ?? 90, ...(values.yearly ? { interval: "year" } : {}) }; }
|
|
183
186
|
if (command === "usage") {
|
|
184
187
|
expect(); const capUsd = values.cap === undefined ? undefined : Number(values.cap);
|
|
185
188
|
if (capUsd !== undefined && !(capUsd >= 0)) throw usage("--cap must be a number of dollars, 0 or more");
|
|
@@ -231,6 +234,27 @@ function nextMonthStart(now) {
|
|
|
231
234
|
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1)).toISOString().slice(0, 10);
|
|
232
235
|
}
|
|
233
236
|
|
|
237
|
+
const PLAN_NAMES = { free: "Free", trial: "Pro trial", pro: "Pro", legacy: "Early access" };
|
|
238
|
+
|
|
239
|
+
/** `billing status` without --json: labels and numbers, one line each (077). @param {any} b @returns {string} */
|
|
240
|
+
export function billingText(b) {
|
|
241
|
+
const day = (/** @type {string} */ iso) => new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
|
|
242
|
+
const usd = (/** @type {number} */ n) => `$${n.toFixed(2)}`;
|
|
243
|
+
const row = (/** @type {string} */ label, /** @type {unknown} */ value) => value ? [`${label.padEnd(13)}${value}`] : [];
|
|
244
|
+
const p = b.period, o = p.overage;
|
|
245
|
+
const head = [`${PLAN_NAMES[/** @type {keyof typeof PLAN_NAMES} */ (b.plan)] ?? b.plan}${b.source === "comp" ? " (comp)" : ""}`,
|
|
246
|
+
b.interval && (b.interval === "year" ? "yearly" : "monthly"), !["trial", "free", "comp", "legacy"].includes(b.status) && b.status.replace("_", " ")];
|
|
247
|
+
return [head.filter(Boolean).join(" · "),
|
|
248
|
+
...row("Next charge", b.nextCharge && `${usd(b.nextCharge.amountUsd)}${b.nextCharge.estimate ? " (estimate)" : ""} · ${day(b.nextCharge.at)}`),
|
|
249
|
+
...row("Cancels", b.cancelsAt && day(b.cancelsAt)), ...row("Trial ends", b.trialEndsAt && day(b.trialEndsAt)),
|
|
250
|
+
...row("This period", `${p.usedMinutes} / ${p.includedMinutes} min · ${p.leftMinutes} min left${b.trialEndsAt ? "" : ` · resets ${day(p.resetsAt)}`}`),
|
|
251
|
+
...row("Overage", o && `${o.minutes} min · ${usd(o.usd)} of ${usd(o.capUsd)} cap`),
|
|
252
|
+
...row("Card", b.paymentMethod && `${b.paymentMethod.brand} ···· ${b.paymentMethod.last4}`),
|
|
253
|
+
...b.invoices.map((/** @type {any} */ i, /** @type {number} */ n) => `${(n ? "" : "Invoices").padEnd(13)}${day(i.at)} ${i.number ?? "-"} ${usd(i.amountUsd)} ${i.status} ${i.url ?? ""}`.trimEnd()),
|
|
254
|
+
...row("Manage", b.actions.manage), ...row("Upgrade", b.actions.upgrade),
|
|
255
|
+
].join("\n") + "\n";
|
|
256
|
+
}
|
|
257
|
+
|
|
234
258
|
/**
|
|
235
259
|
* Fill in the agent-facing message and `next` for an error code.
|
|
236
260
|
* @param {{error?: string, code: string, next?: string, [key: string]: any}} body @returns {Record<string, any>}
|
|
@@ -245,6 +269,15 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
|
|
|
245
269
|
return { error: "This account's NotusCI minutes are used up (Free: 1,000 a month; the Pro trial: 3,000). Upgrade to Pro to continue.", code,
|
|
246
270
|
next: `${NPX} billing`, ...extra };
|
|
247
271
|
}
|
|
272
|
+
if (code === "card_required") {
|
|
273
|
+
return { error: "This is the GitHub user's third or later free NotusCI account, so it has no free minutes until a card is on file.", code,
|
|
274
|
+
next: `${NPX} billing`, ...extra };
|
|
275
|
+
}
|
|
276
|
+
if (code === "account_suspended") {
|
|
277
|
+
return { error: error || "This NotusCI account is suspended for review.", code,
|
|
278
|
+
next: "Stop. Tell the human the account is suspended and to contact NotusCI at https://ci.notusworks.com/support.", ...extra };
|
|
279
|
+
}
|
|
280
|
+
if (code === "rate_limited") return { error, code, next: "Wait a minute before the next call; tell the human if it repeats.", ...extra };
|
|
248
281
|
if (code === "missing_scope") return { error, code, next: `${NPX} login --scope ${String(extra.scopes)}`, ...extra };
|
|
249
282
|
/** @type {Record<string, string>} */
|
|
250
283
|
const defaults = {
|
|
@@ -256,6 +289,47 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
|
|
|
256
289
|
return { error, code, next: next ?? defaults[code] ?? "Tell the human the error.", ...extra };
|
|
257
290
|
}
|
|
258
291
|
|
|
292
|
+
export const TAKEOVER_GUARD = "vars.NOTUSCI_TAKEOVER != 'true' || github.event.pull_request.head.repo.fork";
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Spec 070: adds the takeover guard to each job's `if:`, keeping an existing one with `&&`.
|
|
296
|
+
* Returns the new text and the job count; a guard already there leaves the text as it is.
|
|
297
|
+
* @param {string} text a workflow file @returns {{ text: string, jobs: number }}
|
|
298
|
+
*/
|
|
299
|
+
export function addTakeoverGuard(text) {
|
|
300
|
+
const lines = text.split("\n");
|
|
301
|
+
const indent = (/** @type {string} */ line) => line.length - line.trimStart().length;
|
|
302
|
+
const blank = (/** @type {string} */ line) => !line.trim() || line.trim().startsWith("#");
|
|
303
|
+
const start = lines.findIndex(line => /^jobs:\s*(#.*)?$/.test(line));
|
|
304
|
+
/** @type {number[]} */
|
|
305
|
+
const jobs = [];
|
|
306
|
+
let jobIndent = -1;
|
|
307
|
+
for (let i = start + 1; start >= 0 && i < lines.length; i++) {
|
|
308
|
+
if (blank(lines[i])) continue;
|
|
309
|
+
if (indent(lines[i]) === 0) break;
|
|
310
|
+
if (jobIndent < 0) jobIndent = indent(lines[i]);
|
|
311
|
+
if (indent(lines[i]) === jobIndent && /^\s*[A-Za-z_][\w-]*:\s*(#.*)?$/.test(lines[i])) jobs.push(i);
|
|
312
|
+
}
|
|
313
|
+
if (!jobs.length) throw new CliError({ code: "workflow_refused", error: "No block-style jobs: section found; add the if: line by hand", guard: TAKEOVER_GUARD });
|
|
314
|
+
const on = lines.findIndex(line => /^["']?on["']?:/.test(line));
|
|
315
|
+
const next = lines.findIndex((line, i) => i > on && !blank(line) && indent(line) === 0);
|
|
316
|
+
if (on < 0 || !/\b(push|pull_request)\b/.test(lines.slice(on, next < 0 ? undefined : next).join("\n"))) {
|
|
317
|
+
throw new CliError({ code: "workflow_refused", error: "GitHub-first needs the workflow to run on push or pull_request; add them to on:" });
|
|
318
|
+
}
|
|
319
|
+
if (text.includes("vars.NOTUSCI_TAKEOVER")) return { text, jobs: jobs.length };
|
|
320
|
+
for (const job of [...jobs].reverse()) {
|
|
321
|
+
let end = job + 1;
|
|
322
|
+
while (end < lines.length && (blank(lines[end]) || indent(lines[end]) > jobIndent)) end++;
|
|
323
|
+
const propIndent = lines.slice(job + 1, end).filter(line => !blank(line)).map(indent)[0] ?? jobIndent + 2;
|
|
324
|
+
const at = lines.findIndex((line, i) => i > job && i < end && indent(line) === propIndent && /^\s*if:/.test(line));
|
|
325
|
+
if (at < 0) { lines.splice(job + 1, 0, `${" ".repeat(propIndent)}if: ${TAKEOVER_GUARD}`); continue; }
|
|
326
|
+
const value = lines[at].trim().slice(3).trim().replace(/^\$\{\{\s*([\s\S]*?)\s*\}\}$/, "$1");
|
|
327
|
+
if (!value || /^["'|>]/.test(value) || value.includes("#")) throw new CliError({ code: "workflow_refused", error: `Line ${at + 1}: merge the job's if: with the guard by hand`, guard: TAKEOVER_GUARD });
|
|
328
|
+
lines[at] = `${" ".repeat(propIndent)}if: (${TAKEOVER_GUARD}) && (${value})`;
|
|
329
|
+
}
|
|
330
|
+
return { text: lines.join("\n"), jobs: jobs.length };
|
|
331
|
+
}
|
|
332
|
+
|
|
259
333
|
/** @param {string[]} names files in .github/workflows */
|
|
260
334
|
export function pickWorkflow(names) {
|
|
261
335
|
const files = names.filter(name => /\.ya?ml$/.test(name)).sort();
|