@botiverse/stamp-cli 0.3.3 → 0.3.7
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 +14 -0
- package/lib/agent-login.mjs +10 -1
- package/lib/auth.mjs +45 -2
- package/lib/client.mjs +67 -10
- package/lib/commands/changelog.mjs +58 -0
- package/lib/commands/identity.mjs +12 -0
- package/lib/commands/key.mjs +58 -0
- package/lib/commands/knownhosts.mjs +144 -0
- package/lib/commands/pr.mjs +189 -0
- package/lib/commands/receipt.mjs +16 -0
- package/lib/commands/repo.mjs +78 -0
- package/lib/commands/session.mjs +52 -0
- package/lib/commands/subscribe.mjs +35 -0
- package/lib/errors.mjs +11 -37
- package/lib/expiry.mjs +27 -0
- package/lib/flags.mjs +26 -0
- package/lib/locale.mjs +167 -17
- package/lib/main.mjs +43 -302
- package/lib/{pr-comment.mjs → pr/comment.mjs} +10 -5
- package/lib/{pull-request.mjs → pr/create.mjs} +1 -1
- package/lib/{pr-read.mjs → pr/read.mjs} +29 -5
- package/lib/pr/review.mjs +81 -0
- package/lib/pr/write.mjs +82 -0
- package/lib/{repo-clone.mjs → repo/clone.mjs} +15 -0
- package/lib/repo/identities.mjs +43 -0
- package/lib/repo/ssh.mjs +227 -0
- package/package.json +1 -1
package/lib/main.mjs
CHANGED
|
@@ -1,80 +1,41 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
4
1
|
import { createRequire } from "node:module";
|
|
2
|
+
import { basename } from "node:path";
|
|
5
3
|
import { resolveAuth } from "./auth.mjs";
|
|
6
4
|
import { makeClient, ApiError } from "./client.mjs";
|
|
7
|
-
import { runAgentLogin } from "./agent-login.mjs";
|
|
8
|
-
import { basename } from "node:path";
|
|
9
5
|
import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
|
|
10
|
-
import {
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
parsePRTargetArgs,
|
|
21
|
-
prChecksExitCode,
|
|
22
|
-
prDetailPath,
|
|
23
|
-
PR_SECTIONS,
|
|
24
|
-
prDiffPath,
|
|
25
|
-
prSection,
|
|
26
|
-
safeInline,
|
|
27
|
-
validatePRDetail,
|
|
28
|
-
validatePRDiff,
|
|
29
|
-
validatePRListResponse,
|
|
30
|
-
} from "./pr-read.mjs";
|
|
31
|
-
import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone } from "./repo-clone.mjs";
|
|
32
|
-
import { apiErrorGuidance, presentError } from "./errors.mjs";
|
|
33
|
-
|
|
34
|
-
function sectionLabels(locale) {
|
|
35
|
-
const labels = {};
|
|
36
|
-
for (const name of Object.values(PR_SECTIONS)) labels[`prSection_${name}`] = t(locale, `prSection_${name}`);
|
|
37
|
-
return labels;
|
|
38
|
-
}
|
|
6
|
+
import { presentError, printGatewayError } from "./errors.mjs";
|
|
7
|
+
import * as session from "./commands/session.mjs";
|
|
8
|
+
import * as key from "./commands/key.mjs";
|
|
9
|
+
import * as knownhosts from "./commands/knownhosts.mjs";
|
|
10
|
+
import * as identity from "./commands/identity.mjs";
|
|
11
|
+
import * as receipt from "./commands/receipt.mjs";
|
|
12
|
+
import * as repo from "./commands/repo.mjs";
|
|
13
|
+
import * as pr from "./commands/pr.mjs";
|
|
14
|
+
import * as subscribe from "./commands/subscribe.mjs";
|
|
15
|
+
import * as changelog from "./commands/changelog.mjs";
|
|
39
16
|
|
|
40
17
|
const require = createRequire(import.meta.url);
|
|
41
18
|
const pkg = require("../package.json");
|
|
42
19
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const kind = rawKind === "pull" ? "pull_request" : rawKind;
|
|
63
|
-
const number = Number(takeFlag(args, "number"));
|
|
64
|
-
if (!repository || !["issue", "pull_request"].includes(kind) || !Number.isInteger(number) || number <= 0) {
|
|
65
|
-
throw new Error(t(locale, "usageFollow"));
|
|
66
|
-
}
|
|
67
|
-
return { repository, kind, number };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function emitApiGuidance(error, locale, write) {
|
|
71
|
-
const guidance = apiErrorGuidance(locale, error.body);
|
|
72
|
-
if (guidance.code && guidance.code !== error.body?.error) write(`${prefix()}${guidance.code}`);
|
|
73
|
-
if (guidance.action) write(`${prefix()}${guidance.action}`);
|
|
74
|
-
// A typed code without a known/bounded action is not enough to suppress a
|
|
75
|
-
// command-specific fallback (for example PR head-drift guidance).
|
|
76
|
-
return Boolean(guidance.action);
|
|
77
|
-
}
|
|
20
|
+
const commands = {
|
|
21
|
+
login: session.login,
|
|
22
|
+
logout: session.logout,
|
|
23
|
+
whoami: session.whoami,
|
|
24
|
+
"migration-help": session.migrationHelp,
|
|
25
|
+
key: key.run,
|
|
26
|
+
"known-hosts": knownhosts.run,
|
|
27
|
+
identity: identity.run,
|
|
28
|
+
receipt: receipt.run,
|
|
29
|
+
repo: repo.run,
|
|
30
|
+
pr: pr.run,
|
|
31
|
+
follow: subscribe.follow,
|
|
32
|
+
unfollow: subscribe.follow,
|
|
33
|
+
subscription: subscribe.subscription,
|
|
34
|
+
subscriptions: subscribe.subscriptions,
|
|
35
|
+
watch: subscribe.watch,
|
|
36
|
+
unwatch: subscribe.watch,
|
|
37
|
+
changelog: changelog.run,
|
|
38
|
+
};
|
|
78
39
|
|
|
79
40
|
export async function main(argv, opts) {
|
|
80
41
|
const args = [...argv];
|
|
@@ -82,8 +43,7 @@ export async function main(argv, opts) {
|
|
|
82
43
|
const err = opts.stderr ?? ((s) => console.error(s));
|
|
83
44
|
const env = opts.env ?? process.env;
|
|
84
45
|
const exit = opts.exit ?? ((code) => process.exit(code));
|
|
85
|
-
|
|
86
|
-
const localValues = new Set(["--public-key", "--email", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "-b", "-F", "-R"]);
|
|
46
|
+
const localValues = new Set(["--limit", "--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "--method", "-b", "-F", "-R"]);
|
|
87
47
|
let json = false, langFlag, help = false, version = false;
|
|
88
48
|
const commandArgs = [];
|
|
89
49
|
for (let i = 0; i < args.length; i++) {
|
|
@@ -99,12 +59,8 @@ export async function main(argv, opts) {
|
|
|
99
59
|
}
|
|
100
60
|
args.splice(0, args.length, ...commandArgs);
|
|
101
61
|
const locale = selectLocale(env, langFlag);
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
// `stamp-staging` names itself — the error surface reaches users before docs.
|
|
105
|
-
const cliName = opts.cliName
|
|
106
|
-
?? (opts.argv1 ? basename(opts.argv1).replace(/\.mjs$/, "") : "stamp");
|
|
107
|
-
setCliName(cliName);
|
|
62
|
+
const cliName = opts.cliName ?? (opts.argv1 ? basename(opts.argv1).replace(/\.mjs$/, "") : undefined);
|
|
63
|
+
if (cliName !== undefined) setCliName(cliName);
|
|
108
64
|
if (version) { out(pkg.version); return exit(0); }
|
|
109
65
|
const cmd = args.shift();
|
|
110
66
|
if (help || !cmd) { out(t(locale, "usage", { version: pkg.version })); return exit(0); }
|
|
@@ -117,236 +73,21 @@ export async function main(argv, opts) {
|
|
|
117
73
|
err(`${prefix()}${presentError(locale, e)}`);
|
|
118
74
|
return exit(1);
|
|
119
75
|
}
|
|
120
|
-
const api = makeClient(auth, opts.fetchImpl
|
|
76
|
+
const api = makeClient(auth, opts.fetchImpl, {
|
|
77
|
+
readRetries: opts.networkReadRetries, retryDelayMs: opts.networkRetryDelayMs, sleep: opts.sleep,
|
|
78
|
+
});
|
|
79
|
+
const handler = commands[cmd];
|
|
80
|
+
if (!handler) {
|
|
81
|
+
out(t(locale, "usage", { version: pkg.version }));
|
|
82
|
+
return exit(1);
|
|
83
|
+
}
|
|
121
84
|
|
|
122
85
|
try {
|
|
123
|
-
|
|
124
|
-
case "login": {
|
|
125
|
-
if (auth.mode !== "agent") {
|
|
126
|
-
out(t(locale, "loginHumanIntro"));
|
|
127
|
-
out(t(locale, "loginHumanBrowser", { url: auth.apiBase }));
|
|
128
|
-
out(t(locale, "loginHumanCI"));
|
|
129
|
-
return exit(0);
|
|
130
|
-
}
|
|
131
|
-
const login = opts.loginImpl ?? runAgentLogin;
|
|
132
|
-
const session = await login(auth.agentEnv, auth.apiBase, { service: auth.service, fetchImpl: opts.fetchImpl });
|
|
133
|
-
emit({ ok: true, service: auth.service, api_base: auth.apiBase, access_expires_at: session.access_expires_at },
|
|
134
|
-
() => out(t(locale, "loginAgentReady", { service: auth.service, url: auth.apiBase, expires: session.access_expires_at })));
|
|
135
|
-
return exit(0);
|
|
136
|
-
}
|
|
137
|
-
case "logout": {
|
|
138
|
-
const p = auth.logout();
|
|
139
|
-
out(p ? t(locale, "logoutForgot", { path: p }) : t(locale, "logoutNothing"));
|
|
140
|
-
return exit(0);
|
|
141
|
-
}
|
|
142
|
-
case "whoami": {
|
|
143
|
-
const me = await api("GET", "/v1/me");
|
|
144
|
-
emit(me, () => out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${auth.apiBase}`));
|
|
145
|
-
return exit(0);
|
|
146
|
-
}
|
|
147
|
-
case "migration-help": {
|
|
148
|
-
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
149
|
-
const res = await fetchImpl(`${auth.apiBase}/v1/migration-help`, {
|
|
150
|
-
headers: { "accept-language": locale === "zh-CN" ? "zh-CN" : "en" },
|
|
151
|
-
});
|
|
152
|
-
const d = await res.json();
|
|
153
|
-
emit(d, () => {
|
|
154
|
-
out(t(locale, "helpInstall", { cmds: (d.install ?? []).join(" ; ") }));
|
|
155
|
-
out(t(locale, "helpAgentLogin", { text: d.login?.agent ?? "" }));
|
|
156
|
-
for (const [from, to] of Object.entries(d.actions_to_cli ?? {})) {
|
|
157
|
-
const note = d.notes?.[from];
|
|
158
|
-
out(note ? ` ${from} → ${to} (${note})` : ` ${from} → ${to}`);
|
|
159
|
-
}
|
|
160
|
-
});
|
|
161
|
-
return exit(0);
|
|
162
|
-
}
|
|
163
|
-
case "key": {
|
|
164
|
-
const sub = args.shift();
|
|
165
|
-
if (sub !== "enroll") throw new Error(t(locale, "usageKeyEnroll"));
|
|
166
|
-
const keyPath = takeFlag(args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
|
|
167
|
-
const publicKey = readPublicKey(keyPath);
|
|
168
|
-
const d = await api("POST", "/v1/keys", { publicKey });
|
|
169
|
-
emit(d, () => out(t(locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId })));
|
|
170
|
-
return exit(0);
|
|
171
|
-
}
|
|
172
|
-
case "identity": {
|
|
173
|
-
const sub = args.shift();
|
|
174
|
-
if (sub !== "bind") throw new Error(t(locale, "usageIdentityBind"));
|
|
175
|
-
const agentEmail = takeFlag(args, "email");
|
|
176
|
-
if (!agentEmail) throw new Error(t(locale, "usageIdentityBind"));
|
|
177
|
-
const d = await api("POST", "/v1/identities", { agentEmail });
|
|
178
|
-
emit(d, () => out(t(locale, "bound", { email: d.agentEmail })));
|
|
179
|
-
return exit(0);
|
|
180
|
-
}
|
|
181
|
-
case "receipt": {
|
|
182
|
-
const sub = args.shift();
|
|
183
|
-
const id = args.shift();
|
|
184
|
-
if (sub !== "get" || !id) throw new Error(t(locale, "usageReceiptGet"));
|
|
185
|
-
const d = await api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
|
|
186
|
-
emit(d, () => out(`${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`));
|
|
187
|
-
return exit(0);
|
|
188
|
-
}
|
|
189
|
-
case "repo": {
|
|
190
|
-
if (args.shift() !== "clone") throw new Error(t(locale, "usageRepoClone"));
|
|
191
|
-
const parsed = parseRepoCloneArgs(args);
|
|
192
|
-
if (!parsed) throw new Error(t(locale, "usageRepoClone"));
|
|
193
|
-
const me = await api("GET", "/v1/me");
|
|
194
|
-
const defaultOwner = me?.github?.login;
|
|
195
|
-
const repo = parseRepository(parsed.repository, defaultOwner);
|
|
196
|
-
if (!repo) throw new Error(t(locale, "usageRepoClone"));
|
|
197
|
-
const url = gatewayCloneURL(me.sshHost, me.sshPort, repo.owner, repo.name);
|
|
198
|
-
const git = opts.gitCloneImpl ?? runGitClone;
|
|
199
|
-
const result = await git({
|
|
200
|
-
url,
|
|
201
|
-
directory: parsed.directory,
|
|
202
|
-
gitFlags: parsed.gitFlags,
|
|
203
|
-
env: opts.gitEnv ?? env,
|
|
204
|
-
});
|
|
205
|
-
if (result.code !== 0) {
|
|
206
|
-
if (result.stderr) err(result.stderr.trimEnd());
|
|
207
|
-
throw new Error(t(locale, "cloneFailed", { repository: `${repo.owner}/${repo.name}` }));
|
|
208
|
-
}
|
|
209
|
-
if (result.stderr) err(result.stderr.trimEnd());
|
|
210
|
-
emit(
|
|
211
|
-
{ ok: true, repository: `${repo.owner}/${repo.name}`, url, directory: parsed.directory ?? repo.name },
|
|
212
|
-
() => out(t(locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url })),
|
|
213
|
-
);
|
|
214
|
-
return exit(0);
|
|
215
|
-
}
|
|
216
|
-
case "pr": {
|
|
217
|
-
const sub = args.shift();
|
|
218
|
-
if (sub === "comment") {
|
|
219
|
-
const input = parsePRCommentArgs(args);
|
|
220
|
-
try {
|
|
221
|
-
const result = validatePRCommentResult(await api("POST", input.path, input.body), input.target);
|
|
222
|
-
emit(result, () => out(t(locale, "prCommentCreated", { url: result.url, actor: result.actorLogin })));
|
|
223
|
-
} catch (e) {
|
|
224
|
-
// A lost/malformed success response may conceal a completed write.
|
|
225
|
-
// Never retry this command automatically or print submitted body.
|
|
226
|
-
err(`${prefix()}${t(locale, e instanceof ApiError && e.status >= 400 && e.status < 500 ? "prCommentRejected" : "prCommentOutcomeUnknown")}`);
|
|
227
|
-
if (e instanceof ApiError) emitApiGuidance(e, locale, err);
|
|
228
|
-
return exit(1);
|
|
229
|
-
}
|
|
230
|
-
return exit(0);
|
|
231
|
-
}
|
|
232
|
-
if (sub === "create") {
|
|
233
|
-
const input = pullRequestInput(args);
|
|
234
|
-
try {
|
|
235
|
-
const d = await api("POST", "/v1/pull-requests", input);
|
|
236
|
-
emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
|
|
237
|
-
} catch (e) {
|
|
238
|
-
if (e instanceof ApiError && e.status !== 401) {
|
|
239
|
-
err(`${prefix()}${e.message}`);
|
|
240
|
-
if (!emitApiGuidance(e, locale, err)) err(t(locale, pullRequestRecovery(e.body?.error)));
|
|
241
|
-
return exit(1);
|
|
242
|
-
}
|
|
243
|
-
throw e;
|
|
244
|
-
}
|
|
245
|
-
return exit(0);
|
|
246
|
-
}
|
|
247
|
-
if (sub === "list" || sub === "ls") {
|
|
248
|
-
const { path, sections } = parsePRListArgs(args);
|
|
249
|
-
const paged = path.includes("limit=");
|
|
250
|
-
const d = validatePRListResponse(await api("GET", path), paged);
|
|
251
|
-
const labels = {
|
|
252
|
-
statusUnavailable: t(locale, "prStatusUnavailable"),
|
|
253
|
-
ci: t(locale, "prCIShort"),
|
|
254
|
-
agent: t(locale, "prAgentShort"),
|
|
255
|
-
...sectionLabels(locale),
|
|
256
|
-
};
|
|
257
|
-
emit(
|
|
258
|
-
// The derived section is OPT-IN: a bare `--json` stays byte/structure
|
|
259
|
-
// back-compatible with the pre-section envelope, so a strict consumer
|
|
260
|
-
// never meets an unknown key. Only an explicit `--sections` adds it.
|
|
261
|
-
sections
|
|
262
|
-
? { ...d, items: d.items.map((item) => ({ ...item, section: prSection(item) })) }
|
|
263
|
-
: d,
|
|
264
|
-
() => {
|
|
265
|
-
const lines = sections ? formatPRListSections(d, labels) : formatPRList(d, labels);
|
|
266
|
-
if (lines.length === 0) out(t(locale, "prListEmpty"));
|
|
267
|
-
else for (const line of lines) out(line);
|
|
268
|
-
// Surface the pagination continuation (a present cursor is never
|
|
269
|
-
// an error — it means "there is more"). The cursor is an untrusted
|
|
270
|
-
// wire string: strip terminal control sequences before writing it
|
|
271
|
-
// (the JSON path keeps the verified raw value).
|
|
272
|
-
if (d.nextCursor) out(t(locale, "prListMore", { cursor: safeInline(d.nextCursor) }));
|
|
273
|
-
},
|
|
274
|
-
);
|
|
275
|
-
return exit(0);
|
|
276
|
-
}
|
|
277
|
-
if (sub === "view") {
|
|
278
|
-
const target = parsePRTargetArgs(args, "usagePrView");
|
|
279
|
-
const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
|
|
280
|
-
emit(d, () => {
|
|
281
|
-
for (const line of formatPRDetail(d, {
|
|
282
|
-
head: t(locale, "prHeadLabel"),
|
|
283
|
-
checks: t(locale, "prChecksLabel"),
|
|
284
|
-
review: t(locale, "prReviewLabel"),
|
|
285
|
-
})) out(line);
|
|
286
|
-
});
|
|
287
|
-
return exit(0);
|
|
288
|
-
}
|
|
289
|
-
if (sub === "diff") {
|
|
290
|
-
const target = parsePRDiffArgs(args);
|
|
291
|
-
const d = validatePRDiff(await api("GET", prDiffPath(target)), target);
|
|
292
|
-
emit(d, () => {
|
|
293
|
-
const chunks = formatPRDiff(d, target.nameOnly, t(locale, "prDiffUnavailable"));
|
|
294
|
-
if (chunks.length === 0) out(t(locale, "prDiffEmpty"));
|
|
295
|
-
else out(chunks.join("\n"));
|
|
296
|
-
});
|
|
297
|
-
return exit(0);
|
|
298
|
-
}
|
|
299
|
-
if (sub === "checks") {
|
|
300
|
-
const target = parsePRTargetArgs(args, "usagePrChecks");
|
|
301
|
-
const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
|
|
302
|
-
emit(d.checks, () => {
|
|
303
|
-
const lines = formatPRChecks(d);
|
|
304
|
-
if (lines.length === 0) out(t(locale, "prChecksEmpty"));
|
|
305
|
-
else for (const line of lines) out(line);
|
|
306
|
-
});
|
|
307
|
-
return exit(prChecksExitCode(d));
|
|
308
|
-
}
|
|
309
|
-
throw new Error(t(locale, "usagePrRead"));
|
|
310
|
-
}
|
|
311
|
-
case "follow":
|
|
312
|
-
case "unfollow": {
|
|
313
|
-
const body = objectArgs(args, locale);
|
|
314
|
-
const path = cmd === "follow" ? "/v1/subscriptions/objects/follow" : "/v1/subscriptions/objects/unfollow";
|
|
315
|
-
const d = await api("POST", path, body);
|
|
316
|
-
emit(d, () => out(JSON.stringify(d)));
|
|
317
|
-
return exit(0);
|
|
318
|
-
}
|
|
319
|
-
case "subscription": {
|
|
320
|
-
const sub = args.shift();
|
|
321
|
-
if (sub !== "pause" && sub !== "resume") throw new Error(t(locale, "usageSubscription"));
|
|
322
|
-
const body = objectArgs(args, locale);
|
|
323
|
-
const d = await api("POST", `/v1/subscriptions/objects/${sub}`, body);
|
|
324
|
-
emit(d, () => out(JSON.stringify(d)));
|
|
325
|
-
return exit(0);
|
|
326
|
-
}
|
|
327
|
-
case "subscriptions": {
|
|
328
|
-
const d = await api("GET", "/v1/subscriptions");
|
|
329
|
-
emit(d, () => out(JSON.stringify(d, null, 2)));
|
|
330
|
-
return exit(0);
|
|
331
|
-
}
|
|
332
|
-
case "watch":
|
|
333
|
-
case "unwatch": {
|
|
334
|
-
const repository = args.shift();
|
|
335
|
-
const eventType = takeFlag(args, "event");
|
|
336
|
-
if (!repository || !eventType) throw new Error(t(locale, "usageWatch", { cmd }));
|
|
337
|
-
const path = cmd === "watch" ? "/v1/subscriptions/repositories/subscribe" : "/v1/subscriptions/repositories/unsubscribe";
|
|
338
|
-
const d = await api("POST", path, { repository, eventType });
|
|
339
|
-
emit(d, () => out(JSON.stringify(d)));
|
|
340
|
-
return exit(0);
|
|
341
|
-
}
|
|
342
|
-
default:
|
|
343
|
-
out(t(locale, "usage", { version: pkg.version }));
|
|
344
|
-
return exit(cmd ? 1 : 0);
|
|
345
|
-
}
|
|
86
|
+
return await handler({ cmd, args, api, auth, locale, emit, out, err, exit, env, opts });
|
|
346
87
|
} catch (e) {
|
|
347
88
|
if (e instanceof ApiError) {
|
|
348
89
|
err(`${prefix()}${e.message}`);
|
|
349
|
-
|
|
90
|
+
printGatewayError(e, err);
|
|
350
91
|
if (e.status === 401) err(auth.mode === "agent" ? t(locale, "sessionRejected") : t(locale, "checkToken"));
|
|
351
92
|
return exit(1);
|
|
352
93
|
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
|
-
import { AgentError } from "
|
|
3
|
-
import { parsePRTargetArgs, prDetailPath } from "./
|
|
2
|
+
import { AgentError } from "../errors.mjs";
|
|
3
|
+
import { parsePRTargetArgs, prDetailPath } from "./read.mjs";
|
|
4
4
|
|
|
5
5
|
export function parsePRCommentArgs(input) {
|
|
6
6
|
const targetArgs = [], flags = new Map();
|
|
7
7
|
for (let i = 0; i < input.length; i++) {
|
|
8
8
|
const arg = input[i];
|
|
9
|
-
const match = arg.match(/^(--body|--body-file)(?:=(.*))?$/s);
|
|
9
|
+
const match = arg.match(/^(--body|--body-file|--expected-head)(?:=(.*))?$/s);
|
|
10
10
|
const name = match?.[1] ?? ({ "-b": "--body", "-F": "--body-file" })[arg];
|
|
11
11
|
if (!name) { targetArgs.push(arg); continue; }
|
|
12
12
|
if (flags.has(name)) throw new AgentError("usagePrComment");
|
|
@@ -15,7 +15,10 @@ export function parsePRCommentArgs(input) {
|
|
|
15
15
|
flags.set(name, value);
|
|
16
16
|
}
|
|
17
17
|
const target = parsePRTargetArgs(targetArgs, "usagePrComment");
|
|
18
|
+
const expectedHead = flags.get("--expected-head");
|
|
19
|
+
flags.delete("--expected-head");
|
|
18
20
|
if (flags.size !== 1) throw new AgentError("usagePrComment");
|
|
21
|
+
if (expectedHead !== undefined && !/^[0-9a-fA-F]{40}$/.test(expectedHead)) throw new AgentError("prCommentExpectedHeadInvalid");
|
|
19
22
|
let body = flags.get("--body");
|
|
20
23
|
if (flags.has("--body-file")) {
|
|
21
24
|
const file = flags.get("--body-file");
|
|
@@ -23,7 +26,9 @@ export function parsePRCommentArgs(input) {
|
|
|
23
26
|
catch { throw new AgentError("prBodyRead"); }
|
|
24
27
|
}
|
|
25
28
|
if (!body?.trim() || Buffer.byteLength(body, "utf8") > 65536) throw new AgentError("prCommentBodyInvalid");
|
|
26
|
-
|
|
29
|
+
const request = { body };
|
|
30
|
+
if (expectedHead !== undefined) request.expectedHead = expectedHead.toLowerCase();
|
|
31
|
+
return { target, path: `${prDetailPath(target)}/comments`, body: request };
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
export function validatePRCommentResult(result, target) {
|
|
@@ -31,7 +36,7 @@ export function validatePRCommentResult(result, target) {
|
|
|
31
36
|
const valid = result && typeof result === "object" && !Array.isArray(result)
|
|
32
37
|
&& typeof result.repository === "string" && result.repository.toLowerCase() === expectedRepo.toLowerCase()
|
|
33
38
|
&& result.number === target.number && Number.isSafeInteger(result.commentId) && result.commentId > 0
|
|
34
|
-
&& typeof result.actorLogin === "string" && /^[A-Za-z0-9-]
|
|
39
|
+
&& typeof result.actorLogin === "string" && /^[A-Za-z0-9-]+(\[bot\])?$/.test(result.actorLogin)
|
|
35
40
|
&& typeof result.url === "string"
|
|
36
41
|
&& result.url.toLowerCase() === `https://github.com/${expectedRepo}/pull/${target.number}#issuecomment-${result.commentId}`.toLowerCase();
|
|
37
42
|
if (!valid) throw new AgentError("prCommentOutcomeUnknown");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
-
import { AgentError } from "
|
|
3
|
+
import { AgentError } from "../errors.mjs";
|
|
4
4
|
|
|
5
5
|
const names = new Set(["receipt", "repo", "head", "sha", "base", "title", "body", "body-file", "idempotency-key"]);
|
|
6
6
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AgentError } from "
|
|
1
|
+
import { AgentError } from "../errors.mjs";
|
|
2
2
|
|
|
3
3
|
const consolidatedStatuses = new Set(["OPEN", "DRAFT", "MERGING", "MERGED", "CLOSED"]);
|
|
4
4
|
const ciStatuses = new Set(["passing", "failing", "pending", "none"]);
|
|
@@ -11,7 +11,7 @@ const reviewStates = new Set([
|
|
|
11
11
|
const terminalPassConclusions = new Set(["success", "neutral", "skipped"]);
|
|
12
12
|
const pendingCheckStates = new Set(["", "expected", "in_progress", "pending", "queued", "requested", "waiting"]);
|
|
13
13
|
|
|
14
|
-
function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
|
|
14
|
+
export function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
|
|
15
15
|
const matches = [];
|
|
16
16
|
for (let i = 0; i < args.length; i++) {
|
|
17
17
|
if (args[i] === `--${long}` || (short && args[i] === `-${short}`)) {
|
|
@@ -77,7 +77,7 @@ function targetFromURL(value) {
|
|
|
77
77
|
* Parse `stamp pr list` args (task #397 slice 1 + #345 CLI lane).
|
|
78
78
|
*
|
|
79
79
|
* Optional, opt-in pagination — the wire adds `?limit=` and an OPAQUE cursor to
|
|
80
|
-
* the SAME `/v1/
|
|
80
|
+
* the SAME `/v1/inbox/pull-requests` path (never a new path):
|
|
81
81
|
* --limit <n> 1..200 page size
|
|
82
82
|
* --cursor <s> an opaque server token, passed through VERBATIM (never parsed,
|
|
83
83
|
* never cached, never reused across identities: it is bound to
|
|
@@ -108,7 +108,11 @@ export function parsePRListArgs(input) {
|
|
|
108
108
|
params.set("cursor", cursor);
|
|
109
109
|
}
|
|
110
110
|
const query = params.toString();
|
|
111
|
-
|
|
111
|
+
// task #413: the SSOT is /v1/inbox/pull-requests; the server keeps
|
|
112
|
+
// /v1/pr-inbox as a Deprecation alias for one version cycle. The CLI targets
|
|
113
|
+
// the SSOT (one build point).
|
|
114
|
+
const base = "/v1/inbox/pull-requests";
|
|
115
|
+
const path = query === "" ? base : `${base}?${query}`;
|
|
112
116
|
return { path, sections };
|
|
113
117
|
}
|
|
114
118
|
|
|
@@ -235,6 +239,12 @@ export function validatePRDetail(value, expected) {
|
|
|
235
239
|
requireString(detail.headRef);
|
|
236
240
|
requireString(detail.baseRef);
|
|
237
241
|
if (!ciStatuses.has(requireString(detail.ciStatus))) throw new AgentError("prReadInvalidResponse");
|
|
242
|
+
// Optional: absent means the CI sources were actually read. Validated rather
|
|
243
|
+
// than ignored so a malformed value is caught here instead of silently
|
|
244
|
+
// deciding an exit code further down.
|
|
245
|
+
if (detail.ciUnreadable !== undefined && typeof detail.ciUnreadable !== "boolean") {
|
|
246
|
+
throw new AgentError("prReadInvalidResponse");
|
|
247
|
+
}
|
|
238
248
|
requireString(detail.reviewStatus);
|
|
239
249
|
requireString(detail.reviewFreshness);
|
|
240
250
|
if (typeof detail.stale !== "boolean" || typeof detail.invalidated !== "boolean") throw new AgentError("prReadInvalidResponse");
|
|
@@ -378,7 +388,11 @@ export function formatPRDetail(detail, labels) {
|
|
|
378
388
|
const lines = [
|
|
379
389
|
`${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
|
|
380
390
|
`${labels.head}: ${safeInline(detail.headSha)}`,
|
|
381
|
-
|
|
391
|
+
// Forks on ciUnreadable rather than printing ciStatus straight through. Left
|
|
392
|
+
// alone, `pr view` would keep saying "none" while `pr checks` already says
|
|
393
|
+
// the checks could not be read — one endpoint, two commands, two answers,
|
|
394
|
+
// which is the false trail #598 started on.
|
|
395
|
+
`${labels.checks}: ${detail.ciUnreadable ? labels.ciUnreadable : safeInline(detail.ciStatus)}`,
|
|
382
396
|
`${labels.review}: ${safeInline(detail.reviewStatus)}`,
|
|
383
397
|
safeInline(detail.url),
|
|
384
398
|
];
|
|
@@ -400,6 +414,16 @@ export function formatPRChecks(detail) {
|
|
|
400
414
|
}
|
|
401
415
|
|
|
402
416
|
export function prChecksExitCode(detail) {
|
|
417
|
+
// "Unconfigured" and "unavailable" used to share the line below, because
|
|
418
|
+
// nothing on the wire could tell them apart — the comment there named both.
|
|
419
|
+
// `ciUnreadable` is the first thing that can, so the unreadable case gets its
|
|
420
|
+
// own branch instead of continuing to ride on "the set came back empty".
|
|
421
|
+
//
|
|
422
|
+
// This matters beyond tidiness: someone will eventually decide that a repo
|
|
423
|
+
// with genuinely no CI should not exit non-zero, and if the two cases are
|
|
424
|
+
// still merged, that change silently takes fail-closed with it while reading
|
|
425
|
+
// as a pure ergonomics fix in review.
|
|
426
|
+
if (detail.ciUnreadable) return 1;
|
|
403
427
|
// Match `gh pr checks`: an empty check set is not evidence that CI passed.
|
|
404
428
|
// Keep it non-zero so automation cannot treat an unconfigured or unavailable
|
|
405
429
|
// check suite as a green pull request.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// `stamp pr review <n>`: the reviewer's preparation, in one read (task #551,
|
|
2
|
+
// 飞牛 2026-09-18). Everything a non-author exact-head review starts from —
|
|
3
|
+
// the exact head to pin, the base, the merge-base, whether the base has moved
|
|
4
|
+
// since the branch forked (the trap: diffing against the current base then
|
|
5
|
+
// shows unrelated changes), checks, review state — and the local commands
|
|
6
|
+
// that diff and patch-id against the merge-base rather than the base.
|
|
7
|
+
import { safeInline } from "./read.mjs";
|
|
8
|
+
|
|
9
|
+
// The brief does NOT say whether the base has advanced: GitHub's `base.sha`
|
|
10
|
+
// on a pull request is the fork point and stays put while the base branch
|
|
11
|
+
// moves, so `baseSha !== mergeBaseSha` only detects a retarget or rebase and
|
|
12
|
+
// would call an advanced base "current" — the one sentence this tool exists
|
|
13
|
+
// to prevent (飞牛, review of #258). Until the detail carries the base
|
|
14
|
+
// branch's current tip, the rule is stated unconditionally.
|
|
15
|
+
export function reviewBrief(detail) {
|
|
16
|
+
const short = (sha) => sha.slice(0, 12);
|
|
17
|
+
return {
|
|
18
|
+
repository: detail.repository,
|
|
19
|
+
number: detail.number,
|
|
20
|
+
title: detail.title,
|
|
21
|
+
author: detail.author,
|
|
22
|
+
url: detail.url,
|
|
23
|
+
headSha: detail.headSha,
|
|
24
|
+
headRef: detail.headRef,
|
|
25
|
+
baseRef: detail.baseRef,
|
|
26
|
+
baseSha: detail.baseSha,
|
|
27
|
+
mergeBaseSha: detail.mergeBaseSha,
|
|
28
|
+
ciStatus: detail.ciStatus,
|
|
29
|
+
// Carried through because this brief is what a reviewer reads before
|
|
30
|
+
// pinning a verdict to an exact head. Dropping it here let `pr review`
|
|
31
|
+
// keep saying "none" after `pr view` and `pr checks` had both learned to
|
|
32
|
+
// say the checks were refused -- the same quiet falsehood, on the path
|
|
33
|
+
// where it costs the most (cross, reviewing #602).
|
|
34
|
+
ciUnreadable: detail.ciUnreadable === true,
|
|
35
|
+
reviewStatus: detail.reviewStatus,
|
|
36
|
+
reviewFreshness: detail.reviewFreshness,
|
|
37
|
+
checks: detail.checks.map((c) => ({ name: c.name, status: c.status, conclusion: c.conclusion })),
|
|
38
|
+
commands: {
|
|
39
|
+
fetch: `git fetch origin ${detail.headRef} ${detail.baseRef}`,
|
|
40
|
+
diff: `git diff ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
41
|
+
stat: `git diff --stat ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
42
|
+
log: `git log --oneline ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
43
|
+
patchId: `git diff ${short(detail.mergeBaseSha)} ${short(detail.headSha)} | git patch-id --stable`,
|
|
44
|
+
},
|
|
45
|
+
verdict: `GO|CHANGES @ exact ${detail.headSha}`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function formatPRReview(brief, t) {
|
|
50
|
+
const lines = [
|
|
51
|
+
`${safeInline(brief.repository)} #${brief.number} — ${safeInline(brief.title)} (${safeInline(brief.author)})`,
|
|
52
|
+
`${t("prReviewExactHead")}: ${safeInline(brief.headSha)} (${safeInline(brief.headRef)})`,
|
|
53
|
+
`${t("prReviewBase")}: ${safeInline(brief.baseRef)} @ ${safeInline(brief.baseSha)}`,
|
|
54
|
+
`${t("prReviewMergeBase")}: ${safeInline(brief.mergeBaseSha)}`,
|
|
55
|
+
` ${t("prReviewMergeBaseRule")}`,
|
|
56
|
+
brief.ciUnreadable
|
|
57
|
+
? `${t("prChecksLabel")}: ${t("prCIUnreadable")}`
|
|
58
|
+
: `${t("prChecksLabel")}: ${safeInline(brief.ciStatus)}${brief.checks.length ? " — " + brief.checks.map((c) => `${safeInline(c.name)}=${safeInline(c.conclusion || c.status)}`).join(" ") : ""}`,
|
|
59
|
+
`${t("prReviewLabel")}: ${safeInline(brief.reviewStatus)} (${safeInline(brief.reviewFreshness)})`,
|
|
60
|
+
safeInline(brief.url),
|
|
61
|
+
"",
|
|
62
|
+
`${t("prReviewCommands")}:`,
|
|
63
|
+
` ${brief.commands.fetch}`,
|
|
64
|
+
` ${brief.commands.log}`,
|
|
65
|
+
` ${brief.commands.stat}`,
|
|
66
|
+
` ${brief.commands.diff}`,
|
|
67
|
+
` ${brief.commands.patchId}`,
|
|
68
|
+
"",
|
|
69
|
+
// The qualifier goes ON this line, not eight lines above it. `Checks:
|
|
70
|
+
// unreadable` already appears near the top, but this is the line a reviewer
|
|
71
|
+
// copies to record a verdict, and by the time they reach it there is a whole
|
|
72
|
+
// block of commands in between. This card's entire subject is a true
|
|
73
|
+
// statement sitting somewhere other than where the decision is made; putting
|
|
74
|
+
// it only at the top would have been a milder version of the same thing
|
|
75
|
+
// (飞牛, reviewing #282).
|
|
76
|
+
brief.ciUnreadable
|
|
77
|
+
? `${t("prReviewVerdict")}: ${brief.verdict} (${t("prVerdictCIUnreadable")})`
|
|
78
|
+
: `${t("prReviewVerdict")}: ${brief.verdict}`,
|
|
79
|
+
];
|
|
80
|
+
return lines;
|
|
81
|
+
}
|