notusci 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/package.json +20 -4
- package/src/cli.mjs +332 -0
- package/src/core.mjs +289 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nvbinh15
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "notusci",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "CI for coding agents: verify uncommitted changes with your GitHub Actions workflow and get typed JSON",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://ci.notusworks.com",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=22"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"notusci": "src/cli.mjs"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src/*.mjs",
|
|
16
|
+
"!src/*.test.mjs"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --test src/*.test.mjs",
|
|
20
|
+
"typecheck": "../api/node_modules/.bin/tsc -p tsconfig.json"
|
|
21
|
+
}
|
|
22
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { homedir, hostname } from "node:os";
|
|
7
|
+
import { delimiter, dirname, join } from "node:path";
|
|
8
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
9
|
+
import {
|
|
10
|
+
CliError, NPX, boundedWaitSeconds, buildSource, encodeSource, parseCommand, pickWorkflow, renderError,
|
|
11
|
+
repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain,
|
|
12
|
+
} from "./core.mjs";
|
|
13
|
+
|
|
14
|
+
const DEFAULT_URL = "https://notusci-api.binh-08d.workers.dev";
|
|
15
|
+
const RUN_BUDGET_MS = 85_000;
|
|
16
|
+
const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
|
|
17
|
+
|
|
18
|
+
/** @param {unknown} value */
|
|
19
|
+
const print = value => process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
20
|
+
const authPath = () => join(homedir(), ".config", "notusci", "auth.json");
|
|
21
|
+
|
|
22
|
+
/** @param {string} path @param {string} text */
|
|
23
|
+
function writePrivate(path, text) {
|
|
24
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
25
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
26
|
+
writeFileSync(temp, text, { mode: 0o600 });
|
|
27
|
+
renameSync(temp, path);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @typedef {{url: string, token?: string, state: {url?: string, token?: string, pending?: any}}} Session */
|
|
31
|
+
|
|
32
|
+
/** @returns {Session} */
|
|
33
|
+
function session() {
|
|
34
|
+
/** @type {Session["state"]} */
|
|
35
|
+
let state = {};
|
|
36
|
+
try { state = JSON.parse(readFileSync(authPath(), "utf8")); } catch {}
|
|
37
|
+
const url = new URL(process.env.NOTUSCI_URL ?? state.url ?? DEFAULT_URL);
|
|
38
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL_HOSTS.includes(url.hostname))) {
|
|
39
|
+
throw new CliError({ code: "usage", error: "NOTUSCI_URL must use https (http only for localhost)", next: "Fix NOTUSCI_URL and retry." });
|
|
40
|
+
}
|
|
41
|
+
return { url: url.href.replace(/\/$/, ""), token: process.env.NOTUSCI_TOKEN ?? state.token, state };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Save the token and pending login; a URL from NOTUSCI_URL is not persisted. @param {Session} s @param {{token?: string, pending?: any}} state */
|
|
45
|
+
function save(s, state) {
|
|
46
|
+
s.state = { url: process.env.NOTUSCI_URL ? s.state.url : s.url, ...state };
|
|
47
|
+
writePrivate(authPath(), `${JSON.stringify(s.state, null, 2)}\n`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {Session} s @param {string} path
|
|
52
|
+
* @param {{method?: string, query?: Record<string, string|number|undefined>, body?: unknown, bearer?: string, timeoutSeconds?: number, deadline?: number}} [options]
|
|
53
|
+
* @returns {Promise<any>}
|
|
54
|
+
*/
|
|
55
|
+
async function api(s, path, { method = "GET", query = {}, body, bearer = s.token, timeoutSeconds = 30, deadline = Infinity } = {}) {
|
|
56
|
+
const url = new URL(path, `${s.url}/`);
|
|
57
|
+
for (const [key, value] of Object.entries(query)) if (value !== undefined) url.searchParams.set(key, String(value));
|
|
58
|
+
/** @type {Record<string, string>} */
|
|
59
|
+
const headers = {};
|
|
60
|
+
if (bearer) headers.authorization = `Bearer ${bearer}`;
|
|
61
|
+
if (body !== undefined) headers["content-type"] = "application/json";
|
|
62
|
+
let response;
|
|
63
|
+
let text = "";
|
|
64
|
+
for (let attempt = 0; ; attempt++) {
|
|
65
|
+
const timeoutMs = Math.max(1000, Math.min(timeoutSeconds * 1000, deadline - Date.now()));
|
|
66
|
+
try {
|
|
67
|
+
response = await fetch(url, { method, headers, body: typeof body === "string" || body === undefined ? body : JSON.stringify(body),
|
|
68
|
+
signal: AbortSignal.timeout(timeoutMs) });
|
|
69
|
+
text = await response.text();
|
|
70
|
+
if (response.status < 500 || attempt === 2) break;
|
|
71
|
+
} catch {
|
|
72
|
+
if (attempt === 2 || Date.now() >= deadline) throw new CliError({ code: "network", error: `Cannot reach NotusCI at ${s.url}`, next: "Retry the same command." });
|
|
73
|
+
}
|
|
74
|
+
await sleep(100 * (attempt + 1));
|
|
75
|
+
}
|
|
76
|
+
let value;
|
|
77
|
+
try { value = text ? JSON.parse(text) : {}; } catch {}
|
|
78
|
+
if (!response.ok || value === undefined) {
|
|
79
|
+
throw new CliError({ ...value, code: value?.code ?? (response.status === 401 ? "not_logged_in" : `http_${response.status}`),
|
|
80
|
+
error: value?.error ?? `NotusCI returned HTTP ${response.status}` }, response.status);
|
|
81
|
+
}
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function gitRepo() {
|
|
86
|
+
try {
|
|
87
|
+
const git = (/** @type {string[]} */ ...args) => execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
88
|
+
return { root: git("rev-parse", "--show-toplevel"), repo: repositoryFromRemote(git("remote", "get-url", "origin")) };
|
|
89
|
+
} catch {
|
|
90
|
+
throw new CliError({ code: "not_git_repo", error: "Run this from a git repository whose origin remote is on GitHub",
|
|
91
|
+
next: "cd to the repository root and retry." });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {string | undefined} repo */
|
|
96
|
+
const repoOrOrigin = repo => repo ?? gitRepo().repo;
|
|
97
|
+
|
|
98
|
+
/** @param {string} root */
|
|
99
|
+
function workflowIn(root) {
|
|
100
|
+
/** @type {string[]} */
|
|
101
|
+
let names = [];
|
|
102
|
+
try { names = readdirSync(join(root, ".github", "workflows")); } catch {}
|
|
103
|
+
return pickWorkflow(names);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** @param {any} me @param {string} repo */
|
|
107
|
+
const listed = (me, repo) => me.repos.find((/** @type {any} */ r) => r.repo.toLowerCase() === repo.toLowerCase());
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Finish or start the browser login. Returns the new token, or prints `status` with the action and returns undefined.
|
|
111
|
+
* @param {Session} s @param {string[]} scopes @param {string | undefined} repo @param {number} deadline @param {string} status
|
|
112
|
+
*/
|
|
113
|
+
async function authorize(s, scopes, repo, deadline, status) {
|
|
114
|
+
const { pending } = s.state;
|
|
115
|
+
const usable = pending && new Date(pending.expiresAt).getTime() > Date.now() && String(pending.scopes) === String(scopes);
|
|
116
|
+
if (usable) {
|
|
117
|
+
for (;;) {
|
|
118
|
+
let poll;
|
|
119
|
+
try { poll = await api(s, `/api/logins/${encodeURIComponent(pending.loginId)}`, { bearer: pending.pollSecret, deadline }); }
|
|
120
|
+
catch (error) {
|
|
121
|
+
const code = /** @type {CliError} */ (error).status;
|
|
122
|
+
if (code && code >= 400 && code < 500 && code !== 401) break;
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
if (poll.status === "approved") {
|
|
126
|
+
save(s, { token: poll.token });
|
|
127
|
+
s.token = poll.token;
|
|
128
|
+
return poll.token;
|
|
129
|
+
}
|
|
130
|
+
if (poll.status === "denied") {
|
|
131
|
+
save(s, { token: s.state.token });
|
|
132
|
+
if (poll.code === "not_account_owner") throw new CliError({ code: poll.code, error: "Another GitHub user owns this account on NotusCI" });
|
|
133
|
+
throw new CliError({ code: "not_logged_in", error: "The login was denied in the browser" });
|
|
134
|
+
}
|
|
135
|
+
if (poll.status !== "pending") break;
|
|
136
|
+
if (Date.now() + 2000 > deadline) {
|
|
137
|
+
print({ status, action: { url: pending.url, code: pending.code } });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
await sleep(2000);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const created = await api(s, "/api/logins", { method: "POST", body: { repo, scopes, name: `cli@${hostname()}` }, deadline });
|
|
144
|
+
save(s, { token: s.state.token, pending: { ...created, scopes } });
|
|
145
|
+
print({ status: "action_required", action: { url: created.url, code: created.code } });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** @param {Session} s @param {number} [deadline] */
|
|
149
|
+
async function whoamiOrUndefined(s, deadline) {
|
|
150
|
+
try { return await api(s, "/api/whoami", { deadline }); }
|
|
151
|
+
catch (error) { if (/** @type {CliError} */ (error).status === 401) return; throw error; }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** @param {string} name */
|
|
155
|
+
const onPath = name => (process.env.PATH ?? "").split(delimiter).some(dir => dir && existsSync(join(dir, name)));
|
|
156
|
+
/** @param {string[]} args */
|
|
157
|
+
const claude = (...args) => spawnSync("claude", args, { stdio: "ignore" }).status === 0;
|
|
158
|
+
|
|
159
|
+
/** @param {string} path @param {typeof setCursorServer} set */
|
|
160
|
+
function fileClient(path, set) {
|
|
161
|
+
const read = () => existsSync(path) ? readFileSync(path, "utf8") : undefined;
|
|
162
|
+
return {
|
|
163
|
+
registered: (/** @type {string} */ url, /** @type {string} */ token) => existsSync(path) && set(read(), url, token).existed,
|
|
164
|
+
register(/** @type {string} */ url, /** @type {string} */ token) {
|
|
165
|
+
const { text, existed } = set(read(), url, token);
|
|
166
|
+
writePrivate(path, text);
|
|
167
|
+
return existed ? "updated" : "added";
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function mcpClients() {
|
|
173
|
+
const home = homedir();
|
|
174
|
+
return {
|
|
175
|
+
claudeCode: {
|
|
176
|
+
found: () => onPath("claude"),
|
|
177
|
+
registered: () => claude("mcp", "get", "notusci"),
|
|
178
|
+
register(/** @type {string} */ url, /** @type {string} */ token) {
|
|
179
|
+
// A project-local entry would shadow the user entry.
|
|
180
|
+
const local = claude("mcp", "remove", "--scope", "local", "notusci");
|
|
181
|
+
const existed = claude("mcp", "remove", "--scope", "user", "notusci") || local;
|
|
182
|
+
// The token is briefly visible in this process's argv; `claude mcp add` has no other way to take a header.
|
|
183
|
+
if (!claude("mcp", "add", "--transport", "http", "--scope", "user", "notusci", url, "--header", `Authorization: Bearer ${token}`)) return "failed";
|
|
184
|
+
return existed ? "updated" : "added";
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
cursor: { found: () => existsSync(join(home, ".cursor")) || onPath("cursor"), ...fileClient(join(home, ".cursor", "mcp.json"), setCursorServer) },
|
|
188
|
+
codex: { found: () => existsSync(join(home, ".codex")) || onPath("codex"), ...fileClient(join(home, ".codex", "config.toml"), setCodexServer) },
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** @param {Session} s @param {any} input */
|
|
193
|
+
async function init(s, input) {
|
|
194
|
+
const deadline = Date.now() + RUN_BUDGET_MS;
|
|
195
|
+
const { root, repo } = gitRepo();
|
|
196
|
+
let me = await whoamiOrUndefined(s, deadline);
|
|
197
|
+
if (!me || !input.scopes.every((/** @type {string} */ scope) => me.scopes.includes(scope))) {
|
|
198
|
+
if (!await authorize(s, input.scopes, repo, deadline, "action_required")) return;
|
|
199
|
+
me = await api(s, "/api/whoami", { deadline });
|
|
200
|
+
}
|
|
201
|
+
while (!listed(me, repo)) {
|
|
202
|
+
if (Date.now() + 3000 > deadline) {
|
|
203
|
+
throw new CliError({ code: "app_not_installed", error: `Install the NotusCI GitHub App on ${repo}: ${me.installUrl}`, installUrl: me.installUrl });
|
|
204
|
+
}
|
|
205
|
+
await sleep(3000);
|
|
206
|
+
me = await api(s, "/api/whoami", { deadline });
|
|
207
|
+
}
|
|
208
|
+
const workflow = workflowIn(root);
|
|
209
|
+
/** @type {Record<string, string> | "skipped"} */
|
|
210
|
+
let mcp = "skipped";
|
|
211
|
+
if (input.mcp) {
|
|
212
|
+
mcp = {};
|
|
213
|
+
for (const [name, client] of Object.entries(mcpClients())) {
|
|
214
|
+
try { mcp[name] = client.found() ? client.register(`${s.url}/mcp`, /** @type {string} */ (s.token)) : "not_found"; }
|
|
215
|
+
catch { mcp[name] = "failed"; }
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
print({ status: "ready", user: me.user, repo: listed(me, repo).repo, scopes: me.scopes, workflow, mcp, next: `${NPX} verify` });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** @param {Session} s */
|
|
222
|
+
async function doctor(s) {
|
|
223
|
+
/** @type {any[]} */
|
|
224
|
+
const checks = [];
|
|
225
|
+
/** @param {string} name @param {unknown} error */
|
|
226
|
+
const failed = (name, error) => {
|
|
227
|
+
const { code, next, candidates } = renderError(error instanceof CliError ? error.body : { code: "error", error: String(error) });
|
|
228
|
+
checks.push({ name, ok: false, code, next, ...(candidates && { candidates }) });
|
|
229
|
+
};
|
|
230
|
+
let git;
|
|
231
|
+
try { git = gitRepo(); checks.push({ name: "git_repo", ok: true }); } catch (error) { failed("git_repo", error); }
|
|
232
|
+
let me;
|
|
233
|
+
try { me = await api(s, "/api/whoami"); checks.push({ name: "login", ok: true }); } catch (error) { failed("login", error); }
|
|
234
|
+
const notGit = new CliError({ code: "not_git_repo", error: "", next: "cd to the repository root and retry." });
|
|
235
|
+
if (!me) failed("app_installed", new CliError({ code: "not_logged_in", error: "" }));
|
|
236
|
+
else if (!git) failed("app_installed", notGit);
|
|
237
|
+
else if (!listed(me, git.repo)) failed("app_installed", new CliError({ code: "app_not_installed", error: "" }));
|
|
238
|
+
else checks.push({ name: "app_installed", ok: true });
|
|
239
|
+
if (git) {
|
|
240
|
+
try { workflowIn(git.root); checks.push({ name: "workflow", ok: true }); } catch (error) { failed("workflow", error); }
|
|
241
|
+
} else failed("workflow", notGit);
|
|
242
|
+
const ready = checks.every(check => check.ok);
|
|
243
|
+
const missing = Object.values(mcpClients()).some(client => {
|
|
244
|
+
try { return client.found() && !client.registered(`${s.url}/mcp`, s.token ?? ""); } catch { return true; }
|
|
245
|
+
});
|
|
246
|
+
checks.push(missing ? { name: "mcp", ok: false, code: "mcp_not_registered", next: `${NPX} init` } : { name: "mcp", ok: true });
|
|
247
|
+
print({ ready, checks });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** @param {Session} s @param {any} input */
|
|
251
|
+
async function login(s, input) {
|
|
252
|
+
const deadline = Date.now() + RUN_BUDGET_MS;
|
|
253
|
+
let repo;
|
|
254
|
+
try { repo = gitRepo().repo; } catch {}
|
|
255
|
+
if (!await authorize(s, input.scopes, repo, deadline, "pending")) return;
|
|
256
|
+
const me = await api(s, "/api/whoami", { deadline });
|
|
257
|
+
print({ status: "logged_in", user: me.user, scopes: me.scopes });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** @param {Session} s */
|
|
261
|
+
async function logout(s) {
|
|
262
|
+
const me = await whoamiOrUndefined(s);
|
|
263
|
+
if (me) {
|
|
264
|
+
try { await api(s, `/api/tokens/${encodeURIComponent(me.tokenId)}`, { method: "DELETE" }); }
|
|
265
|
+
catch (error) { if (![401, 404].includes(/** @type {CliError} */ (error).status ?? 0)) throw error; }
|
|
266
|
+
}
|
|
267
|
+
rmSync(authPath(), { force: true });
|
|
268
|
+
print({ status: "logged_out" });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** @param {Session} s @param {string} path @param {string} repo */
|
|
272
|
+
async function waitUntilReady(s, path, repo, deadline = Infinity) {
|
|
273
|
+
for (;;) {
|
|
274
|
+
const timeoutSeconds = boundedWaitSeconds(Math.min(deadline - Date.now(), 25_000));
|
|
275
|
+
const result = await api(s, path, { query: { repo, timeoutSeconds }, timeoutSeconds: timeoutSeconds + 10 });
|
|
276
|
+
if (!shouldWaitAgain(result) || result.approval?.status === "pending" || deadline - Date.now() < 1000) return result;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Print a verify or ship result; one stopped by usage limits is also an error. @param {any} result */
|
|
281
|
+
function report(result) {
|
|
282
|
+
print(result);
|
|
283
|
+
if (result.errorCode) throw new CliError({ code: result.errorCode, error: result.error ?? "" });
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** @param {Session} s @param {any} input */
|
|
287
|
+
async function main(s, input) {
|
|
288
|
+
switch (input.command) {
|
|
289
|
+
case "init": return init(s, input);
|
|
290
|
+
case "doctor": return doctor(s);
|
|
291
|
+
case "login": return login(s, input);
|
|
292
|
+
case "logout": return logout(s);
|
|
293
|
+
case "token list": return print({ tokens: await api(s, "/api/tokens") });
|
|
294
|
+
case "token revoke":
|
|
295
|
+
await api(s, `/api/tokens/${encodeURIComponent(input.id)}`, { method: "DELETE" });
|
|
296
|
+
return print({ status: "revoked", id: input.id });
|
|
297
|
+
case "target set": {
|
|
298
|
+
const repo = repoOrOrigin(input.repo);
|
|
299
|
+
let config;
|
|
300
|
+
try { config = JSON.parse(readFileSync(input.file, "utf8")); }
|
|
301
|
+
catch { throw new CliError({ code: "usage", error: `${input.file} must be a readable JSON file`, next: "Fix --file and retry." }); }
|
|
302
|
+
await api(s, `/api/repos/${repo}/target`, { method: "PUT", body: { config, digitaloceanToken: process.env.DIGITALOCEAN_TOKEN } });
|
|
303
|
+
return print({ status: "saved", repo });
|
|
304
|
+
}
|
|
305
|
+
case "verify": {
|
|
306
|
+
const { root, repo } = gitRepo();
|
|
307
|
+
const workflow = input.workflow ?? workflowIn(root);
|
|
308
|
+
const source = buildSource(root);
|
|
309
|
+
const { verifyId } = await api(s, "/api/verifies", { method: "POST", body: encodeSource(source), timeoutSeconds: 300,
|
|
310
|
+
query: { repo, workflow, idempotencyKey: randomUUID(), baseSha: source.baseSha } });
|
|
311
|
+
return report(await waitUntilReady(s, `/api/verifies/${verifyId}/wait`, repo, Date.now() + input.timeoutSeconds * 1000));
|
|
312
|
+
}
|
|
313
|
+
case "ship": {
|
|
314
|
+
const repo = repoOrOrigin(input.repo);
|
|
315
|
+
const { shipId } = await api(s, "/api/ships", { method: "POST", body: { repo, pushRunId: input.runId } });
|
|
316
|
+
return report(await waitUntilReady(s, `/api/ships/${shipId}/wait`, repo));
|
|
317
|
+
}
|
|
318
|
+
case "wait": {
|
|
319
|
+
const repo = repoOrOrigin(input.repo);
|
|
320
|
+
if (input.timeoutSeconds === undefined) return print(await api(s, runPath(input.runId, "wait"), { query: { repo }, timeoutSeconds: 35 }));
|
|
321
|
+
return print(await waitUntilReady(s, runPath(input.runId, "wait"), repo, Date.now() + input.timeoutSeconds * 1000));
|
|
322
|
+
}
|
|
323
|
+
case "failures": return print(await api(s, runPath(input.runId, "failures"), { query: { repo: repoOrOrigin(input.repo) } }));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
try { await main(session(), parseCommand(process.argv.slice(2))); }
|
|
328
|
+
catch (error) {
|
|
329
|
+
const body = error instanceof CliError ? error.body : { code: "error", error: error instanceof Error ? error.message : String(error) };
|
|
330
|
+
process.stderr.write(`${JSON.stringify(renderError(body))}\n`);
|
|
331
|
+
process.exitCode = 1;
|
|
332
|
+
}
|
package/src/core.mjs
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { lstatSync, readFileSync, readlinkSync } from "node:fs";
|
|
3
|
+
import { Buffer } from "node:buffer";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
|
|
6
|
+
const repositoryPattern = /^[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+$/;
|
|
7
|
+
const MAX_WIRE_BYTES = 64 * 1024 * 1024;
|
|
8
|
+
const MAX_FILE_BYTES = 32 * 1024 * 1024;
|
|
9
|
+
const MAX_TREE_BYTES = 256 * 1024 * 1024;
|
|
10
|
+
const MAX_PATHS = 20_000;
|
|
11
|
+
const MAX_PATH_BYTES = 1_024;
|
|
12
|
+
export const NPX = "npx -y notusci@latest";
|
|
13
|
+
const SCOPES = ["read", "verify", "ship:staging", "ship:prod"];
|
|
14
|
+
const DEFAULT_SCOPES = "read,verify,ship:staging";
|
|
15
|
+
|
|
16
|
+
/** An error printed as `{ error, code, next, ... }` on stderr. */
|
|
17
|
+
export class CliError extends Error {
|
|
18
|
+
/** @param {{error: string, code: string, [key: string]: any}} body @param {number} [status] HTTP status from the server */
|
|
19
|
+
constructor(body, status) { super(body.error); this.body = body; this.status = status; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {string} error */
|
|
23
|
+
function usage(error) {
|
|
24
|
+
return new CliError({ error, code: "usage", next: "Fix the command line; see https://ci.notusworks.com/docs/agents.md" });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @type {Record<string, Record<string, {type: "string" | "boolean"}>>} */
|
|
28
|
+
const OPTIONS = {
|
|
29
|
+
init: { scope: { type: "string" }, "no-mcp": { type: "boolean" } },
|
|
30
|
+
login: { scope: { type: "string" } },
|
|
31
|
+
doctor: {}, logout: {}, token: {},
|
|
32
|
+
target: { repo: { type: "string" }, file: { type: "string" } },
|
|
33
|
+
verify: { workflow: { type: "string" }, timeout: { type: "string" } },
|
|
34
|
+
wait: { repo: { type: "string" }, timeout: { type: "string" } },
|
|
35
|
+
failures: { repo: { type: "string" } },
|
|
36
|
+
ship: { repo: { type: "string" } },
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** @param {string[]} args @returns {any} */
|
|
40
|
+
export function parseCommand(args) {
|
|
41
|
+
const [command = "", ...rest] = args;
|
|
42
|
+
if (!Object.hasOwn(OPTIONS, command)) throw usage(`unknown command: ${command || "(none)"}`);
|
|
43
|
+
/** @type {{values: Record<string, any>, positionals: string[]}} */
|
|
44
|
+
let parsed;
|
|
45
|
+
try { parsed = parseArgs({ args: rest, options: OPTIONS[command], allowPositionals: true, strict: true }); }
|
|
46
|
+
catch (error) { throw usage(/** @type {Error} */ (error).message); }
|
|
47
|
+
const { values, positionals } = parsed;
|
|
48
|
+
/** @param {string[]} shape */
|
|
49
|
+
const expect = (...shape) => {
|
|
50
|
+
if (positionals.length !== shape.length || shape.some((word, i) => word !== "*" && word !== positionals[i])) {
|
|
51
|
+
throw usage(`usage: notusci ${[command, ...shape].join(" ").replace("*", "ID")}`);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
if (values.repo !== undefined && !repositoryPattern.test(values.repo)) throw usage("--repo must be OWNER/REPO");
|
|
55
|
+
let timeoutSeconds;
|
|
56
|
+
if (values.timeout !== undefined) {
|
|
57
|
+
timeoutSeconds = Number(values.timeout);
|
|
58
|
+
if (!Number.isSafeInteger(timeoutSeconds) || timeoutSeconds < 1) throw usage("--timeout must be a positive integer");
|
|
59
|
+
}
|
|
60
|
+
if (command === "init" || command === "login") {
|
|
61
|
+
expect();
|
|
62
|
+
const scopes = [...new Set((values.scope ?? DEFAULT_SCOPES).split(","))];
|
|
63
|
+
const unknown = scopes.filter(scope => !SCOPES.includes(scope));
|
|
64
|
+
if (unknown.length) throw usage(`unknown scope ${unknown.join(",")}; scopes are ${SCOPES.join(",")}`);
|
|
65
|
+
return command === "init" ? { command, scopes, mcp: !values["no-mcp"] } : { command, scopes };
|
|
66
|
+
}
|
|
67
|
+
if (command === "doctor" || command === "logout") { expect(); return { command }; }
|
|
68
|
+
if (command === "token") {
|
|
69
|
+
if (positionals[0] === "revoke") { expect("revoke", "*"); return { command: "token revoke", id: positionals[1] }; }
|
|
70
|
+
expect("list");
|
|
71
|
+
return { command: "token list" };
|
|
72
|
+
}
|
|
73
|
+
if (command === "target") {
|
|
74
|
+
expect("set");
|
|
75
|
+
if (!values.file) throw usage("--file is required");
|
|
76
|
+
return { command: "target set", repo: values.repo, file: values.file };
|
|
77
|
+
}
|
|
78
|
+
if (command === "verify") {
|
|
79
|
+
expect();
|
|
80
|
+
if (values.workflow === "") throw usage("--workflow must not be empty");
|
|
81
|
+
return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540 };
|
|
82
|
+
}
|
|
83
|
+
expect("*");
|
|
84
|
+
const raw = positionals[0];
|
|
85
|
+
const runId = /^[1-9]\d*$/.test(raw) ? Number(raw) : raw.toLowerCase();
|
|
86
|
+
if (typeof runId === "number" ? !Number.isSafeInteger(runId) : !isPushRunId(runId)) {
|
|
87
|
+
throw usage("ID must be a positive safe integer or UUID");
|
|
88
|
+
}
|
|
89
|
+
if (command === "ship") {
|
|
90
|
+
if (typeof runId !== "string") throw usage("ship requires a NotusCI push UUID");
|
|
91
|
+
return { command, runId, repo: values.repo };
|
|
92
|
+
}
|
|
93
|
+
return { command, runId, repo: values.repo, timeoutSeconds };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @param {string} value */
|
|
97
|
+
export function isPushRunId(value) {
|
|
98
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** @param {number|string} runId @param {"wait"|"failures"} command */
|
|
102
|
+
export function runPath(runId, command) {
|
|
103
|
+
const kind = typeof runId === "string" ? "pushes" : "runs";
|
|
104
|
+
return `/api/${kind}/${encodeURIComponent(runId)}/${command}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** @param {number} now */
|
|
108
|
+
function nextMonthStart(now) {
|
|
109
|
+
const date = new Date(now);
|
|
110
|
+
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1)).toISOString().slice(0, 10);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Fill in the agent-facing message and `next` for an error code.
|
|
115
|
+
* @param {{error?: string, code: string, next?: string, [key: string]: any}} body @returns {Record<string, any>}
|
|
116
|
+
*/
|
|
117
|
+
export function renderError({ error = "", code, next, ...extra }, now = Date.now()) {
|
|
118
|
+
if (code === "cap_reached") {
|
|
119
|
+
const resetsOn = nextMonthStart(now);
|
|
120
|
+
return { error: `The monthly NotusCI limit is reached. It resets on ${resetsOn}.`, code,
|
|
121
|
+
next: `Tell the human the monthly limit is reached and resets on ${resetsOn}. Do not retry.`, ...extra, resetsOn };
|
|
122
|
+
}
|
|
123
|
+
if (code === "payment_required") {
|
|
124
|
+
return { error: "The 300-minute NotusCI trial is used up. Card setup is coming soon.", code,
|
|
125
|
+
next: "Tell the human the trial is used up and card setup is coming soon. Do not retry.", ...extra };
|
|
126
|
+
}
|
|
127
|
+
if (code === "missing_scope") return { error, code, next: `${NPX} login --scope ${String(extra.scopes)}`, ...extra };
|
|
128
|
+
/** @type {Record<string, string>} */
|
|
129
|
+
const defaults = {
|
|
130
|
+
not_logged_in: `${NPX} init`,
|
|
131
|
+
app_not_installed: `${NPX} init`,
|
|
132
|
+
not_account_owner: "Tell the human another GitHub user owns this account on NotusCI.",
|
|
133
|
+
workflow_required: `${NPX} verify --workflow PATH, with PATH one of candidates`,
|
|
134
|
+
};
|
|
135
|
+
return { error, code, next: next ?? defaults[code] ?? "Tell the human the error.", ...extra };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** @param {string[]} names files in .github/workflows */
|
|
139
|
+
export function pickWorkflow(names) {
|
|
140
|
+
const files = names.filter(name => /\.ya?ml$/.test(name)).sort();
|
|
141
|
+
if (files.includes("ci.yml")) return ".github/workflows/ci.yml";
|
|
142
|
+
if (files.length === 1) return `.github/workflows/${files[0]}`;
|
|
143
|
+
throw new CliError({ code: "workflow_required", error: files.length ? "Several workflows found; pick one" : "No workflow found in .github/workflows",
|
|
144
|
+
candidates: files.map(name => `.github/workflows/${name}`) });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** @param {string | undefined} text ~/.cursor/mcp.json @param {string} url @param {string} token */
|
|
148
|
+
export function setCursorServer(text, url, token) {
|
|
149
|
+
const config = text?.trim() ? JSON.parse(text) : {};
|
|
150
|
+
const existed = Boolean(config.mcpServers?.notusci);
|
|
151
|
+
config.mcpServers = { ...config.mcpServers, notusci: { url, headers: { Authorization: `Bearer ${token}` } } };
|
|
152
|
+
return { text: `${JSON.stringify(config, null, 2)}\n`, existed };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Replace or append only the [mcp_servers.notusci] table. @param {string | undefined} text ~/.codex/config.toml @param {string} url @param {string} token */
|
|
156
|
+
export function setCodexServer(text = "", url, token) {
|
|
157
|
+
const table = ["[mcp_servers.notusci]", `url = ${JSON.stringify(url)}`, `http_headers = { Authorization = ${JSON.stringify(`Bearer ${token}`)} }`, ""];
|
|
158
|
+
const header = /^\s*\[\[?[^\[\]]+\]\]?\s*(#.*)?$/;
|
|
159
|
+
const ours = /^\s*\[\[?\s*mcp_servers\.(?:notusci|"notusci")\s*[.\]]/;
|
|
160
|
+
/** @type {string[]} */
|
|
161
|
+
const kept = [];
|
|
162
|
+
let skipping = false;
|
|
163
|
+
let existed = false;
|
|
164
|
+
for (const line of text.split("\n")) {
|
|
165
|
+
if (header.test(line)) {
|
|
166
|
+
skipping = ours.test(line);
|
|
167
|
+
if (skipping && !existed) { existed = true; kept.push(...table); }
|
|
168
|
+
}
|
|
169
|
+
if (!skipping) kept.push(line);
|
|
170
|
+
}
|
|
171
|
+
if (!existed) {
|
|
172
|
+
while (kept.length && !kept[kept.length - 1].trim()) kept.pop();
|
|
173
|
+
if (kept.length) kept.push("");
|
|
174
|
+
kept.push(...table);
|
|
175
|
+
}
|
|
176
|
+
return { text: kept.join("\n").replace(/^\n+/, "").replace(/\n*$/, "\n"), existed };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** @param {string} remote */
|
|
180
|
+
export function repositoryFromRemote(remote) {
|
|
181
|
+
const match = remote.trim().match(/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https?:\/\/github\.com\/)([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i);
|
|
182
|
+
if (!match) throw new Error("git remote origin must be a GitHub repository");
|
|
183
|
+
const repo = `${match[1]}/${match[2]}`;
|
|
184
|
+
if (!repositoryPattern.test(repo)) throw new Error("git remote origin must identify OWNER/REPO");
|
|
185
|
+
return repo;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** @param {any} response */
|
|
189
|
+
export const shouldWaitAgain = response => response.ready === false;
|
|
190
|
+
|
|
191
|
+
/** @param {number} remainingMilliseconds */
|
|
192
|
+
export function boundedWaitSeconds(remainingMilliseconds) {
|
|
193
|
+
return Math.max(1, Math.min(25, Math.ceil(remainingMilliseconds / 1000)));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** @param {string} cwd @param {string[]} args @param {number} [maxBuffer] */
|
|
197
|
+
function git(cwd, args, maxBuffer = MAX_WIRE_BYTES) {
|
|
198
|
+
try { return execFileSync("git", args, { cwd, encoding: "buffer", maxBuffer }); }
|
|
199
|
+
catch { throw new Error(`git ${args.slice(0, 2).join(" ")} failed`); }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** @param {Buffer} output */
|
|
203
|
+
function paths(output) {
|
|
204
|
+
if (output.length === 0) return [];
|
|
205
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
206
|
+
try { return decoder.decode(output).replace(/\0$/, "").split("\0"); }
|
|
207
|
+
catch { throw new Error("Git paths must be valid UTF-8"); }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** @param {string} path */
|
|
211
|
+
function checkPath(path) {
|
|
212
|
+
if (!path || Buffer.byteLength(path) > MAX_PATH_BYTES) throw new Error(`path exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** @param {string} entry */
|
|
216
|
+
export function parseTreeEntry(entry) {
|
|
217
|
+
const tab = entry.indexOf("\t");
|
|
218
|
+
const match = entry.slice(0, tab).match(/^(\d+)\s+(\w+)\s+([0-9a-f]{40})\s+(\d+)$/);
|
|
219
|
+
if (tab < 0 || !match) throw new Error("invalid Git tree entry");
|
|
220
|
+
return { mode: match[1], type: match[2], oid: match[3], size: Number(match[4]), path: entry.slice(tab + 1) };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Build the raw Git base and final local overlay. @param {string} cwd */
|
|
224
|
+
export function buildSource(cwd) {
|
|
225
|
+
const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
|
|
226
|
+
const baseSha = git(root, ["rev-parse", "--verify", "HEAD"]).toString().trim();
|
|
227
|
+
if (!/^[0-9a-f]{40}$/.test(baseSha)) throw new Error("HEAD must resolve to a SHA-1 commit");
|
|
228
|
+
/** @type {Map<string,number>} */
|
|
229
|
+
const finalFiles = new Map();
|
|
230
|
+
for (const entry of paths(git(root, ["ls-tree", "-rlz", "--full-tree", baseSha]))) {
|
|
231
|
+
const { mode, type, oid, size, path } = parseTreeEntry(entry);
|
|
232
|
+
checkPath(path);
|
|
233
|
+
if (type !== "blob" || !["100644", "100755", "120000"].includes(mode)) throw new Error(`unsupported Git entry mode ${mode}: ${path}`);
|
|
234
|
+
if (size > MAX_FILE_BYTES) throw new Error(`Git file exceeds 32 MiB: ${path}`);
|
|
235
|
+
if (mode === "120000" && size > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
|
|
236
|
+
if (!Number.isSafeInteger(size)) throw new Error(`invalid Git tree entry: ${path}`);
|
|
237
|
+
finalFiles.set(path, size);
|
|
238
|
+
}
|
|
239
|
+
const objectIds = [baseSha, ...git(root, ["rev-list", "--objects", "--no-object-names", `${baseSha}^{tree}`]).toString().trim().split("\n").filter(Boolean)];
|
|
240
|
+
let decodedBytes = 0;
|
|
241
|
+
const objects = objectIds.map(oid => {
|
|
242
|
+
const type = git(root, ["cat-file", "-t", oid]).toString().trim();
|
|
243
|
+
if (type !== "commit" && type !== "tree" && type !== "blob") throw new Error(`unsupported Git object type ${type}`);
|
|
244
|
+
const raw = git(root, ["cat-file", type, oid], MAX_FILE_BYTES + 1);
|
|
245
|
+
if (type === "blob" && raw.length > MAX_FILE_BYTES) throw new Error(`Git blob ${oid} exceeds 32 MiB`);
|
|
246
|
+
decodedBytes += raw.length;
|
|
247
|
+
if (decodedBytes > MAX_TREE_BYTES) throw new Error("base Git objects exceed the 256 MiB decoded limit");
|
|
248
|
+
return { oid, type, data: raw.toString("base64") };
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
const changed = new Set([...paths(git(root, ["diff", "--no-renames", "--name-only", "-z", "HEAD", "--"])), ...paths(git(root, ["ls-files", "--others", "--exclude-standard", "-z"]))]);
|
|
252
|
+
/** @type {{path:string,mode:"100644"|"100755"|"120000",data:string}[]} */
|
|
253
|
+
const overlay = [];
|
|
254
|
+
/** @type {string[]} */
|
|
255
|
+
const deletions = [];
|
|
256
|
+
for (const path of [...changed].sort()) {
|
|
257
|
+
checkPath(path);
|
|
258
|
+
let stat;
|
|
259
|
+
try { stat = lstatSync(`${root}/${path}`); } catch (error) {
|
|
260
|
+
if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") { deletions.push(path); finalFiles.delete(path); continue; }
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
let mode;
|
|
264
|
+
let data;
|
|
265
|
+
if (stat.isSymbolicLink()) {
|
|
266
|
+
mode = /** @type {const} */ ("120000");
|
|
267
|
+
data = Buffer.from(readlinkSync(`${root}/${path}`));
|
|
268
|
+
if (data.length > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
|
|
269
|
+
} else if (stat.isFile()) {
|
|
270
|
+
mode = stat.mode & 0o111 ? /** @type {const} */ ("100755") : /** @type {const} */ ("100644");
|
|
271
|
+
if (stat.size > MAX_FILE_BYTES) throw new Error(`file exceeds 32 MiB: ${path}`);
|
|
272
|
+
data = readFileSync(`${root}/${path}`);
|
|
273
|
+
} else throw new Error(`unsupported changed file type: ${path}`);
|
|
274
|
+
finalFiles.set(path, data.length);
|
|
275
|
+
overlay.push({ path, mode, data: data.toString("base64") });
|
|
276
|
+
}
|
|
277
|
+
if (finalFiles.size > MAX_PATHS) throw new Error(`resolved source exceeds ${MAX_PATHS} paths`);
|
|
278
|
+
let finalBytes = 0;
|
|
279
|
+
for (const size of finalFiles.values()) finalBytes += size;
|
|
280
|
+
if (finalBytes > MAX_TREE_BYTES) throw new Error("resolved source exceeds the 256 MiB decoded limit");
|
|
281
|
+
return { schemaVersion: 1, baseSha, objects, overlay, deletions };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** @param {ReturnType<typeof buildSource>} source */
|
|
285
|
+
export function encodeSource(source) {
|
|
286
|
+
const body = JSON.stringify(source);
|
|
287
|
+
if (Buffer.byteLength(body) > MAX_WIRE_BYTES) throw new Error("verification upload exceeds the 64 MiB transport limit");
|
|
288
|
+
return body;
|
|
289
|
+
}
|
package/README.md
DELETED