notusci 0.1.11 → 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 +32 -2
- package/src/core.mjs +70 -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
|
|
|
@@ -222,7 +222,33 @@ async function init(s, input) {
|
|
|
222
222
|
}
|
|
223
223
|
}
|
|
224
224
|
if (input.billing) return billing(s, { repo, timeoutSeconds: 90 });
|
|
225
|
-
|
|
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` });
|
|
227
|
+
}
|
|
228
|
+
|
|
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
|
+
};
|
|
226
252
|
}
|
|
227
253
|
|
|
228
254
|
/** @param {Session} s @param {{repo?: string, timeoutSeconds: number, interval?: "month" | "year"}} input */
|
|
@@ -351,6 +377,10 @@ async function main(s, input) {
|
|
|
351
377
|
case "doctor": return doctor(s);
|
|
352
378
|
case "login": return login(s, input);
|
|
353
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
|
+
}
|
|
354
384
|
case "usage": {
|
|
355
385
|
const repo = repoOrOrigin(input.repo);
|
|
356
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" }, yearly: { type: "boolean" } },
|
|
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] [--yearly] [--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,6 +181,7 @@ 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
|
}
|
|
184
|
+
if (command === "billing" && positionals[0] === "status") { expect("status"); return { command: "billing status", repo: values.repo, json: values.json === true }; }
|
|
182
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);
|
|
@@ -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>}
|
|
@@ -251,7 +275,7 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
|
|
|
251
275
|
}
|
|
252
276
|
if (code === "account_suspended") {
|
|
253
277
|
return { error: error || "This NotusCI account is suspended for review.", code,
|
|
254
|
-
next: "Stop. Tell the human the account is suspended and to
|
|
278
|
+
next: "Stop. Tell the human the account is suspended and to contact NotusCI at https://ci.notusworks.com/support.", ...extra };
|
|
255
279
|
}
|
|
256
280
|
if (code === "rate_limited") return { error, code, next: "Wait a minute before the next call; tell the human if it repeats.", ...extra };
|
|
257
281
|
if (code === "missing_scope") return { error, code, next: `${NPX} login --scope ${String(extra.scopes)}`, ...extra };
|
|
@@ -265,6 +289,47 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
|
|
|
265
289
|
return { error, code, next: next ?? defaults[code] ?? "Tell the human the error.", ...extra };
|
|
266
290
|
}
|
|
267
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
|
+
|
|
268
333
|
/** @param {string[]} names files in .github/workflows */
|
|
269
334
|
export function pickWorkflow(names) {
|
|
270
335
|
const files = names.filter(name => /\.ya?ml$/.test(name)).sort();
|