@botiverse/stamp-cli 0.3.2 → 0.3.4

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.
@@ -0,0 +1,158 @@
1
+ import { t, prefix } from "../locale.mjs";
2
+ import { ApiError, NetworkError } from "../client.mjs";
3
+ import { AgentError, printGatewayError } from "../errors.mjs";
4
+ import { pullRequestInput, pullRequestRecovery } from "../pr/create.mjs";
5
+ import { parsePRCommentArgs, validatePRCommentResult } from "../pr/comment.mjs";
6
+ import { parsePRApproveArgs, parsePRMergeArgs, validatePRApproveResult, validatePRMergeResult } from "../pr/write.mjs";
7
+ import {
8
+ formatPRChecks,
9
+ formatPRDetail,
10
+ formatPRDiff,
11
+ formatPRList,
12
+ formatPRListSections,
13
+ parsePRDiffArgs,
14
+ parsePRListArgs,
15
+ parsePRTargetArgs,
16
+ prChecksExitCode,
17
+ prDetailPath,
18
+ PR_SECTIONS,
19
+ prDiffPath,
20
+ prSection,
21
+ safeInline,
22
+ validatePRDetail,
23
+ validatePRDiff,
24
+ validatePRListResponse,
25
+ } from "../pr/read.mjs";
26
+
27
+ function sectionLabels(locale) {
28
+ const labels = {};
29
+ for (const name of Object.values(PR_SECTIONS)) labels[`prSection_${name}`] = t(locale, `prSection_${name}`);
30
+ return labels;
31
+ }
32
+
33
+ async function writeCommand(ctx, run) {
34
+ try {
35
+ await run();
36
+ } catch (e) {
37
+ if (e instanceof NetworkError) {
38
+ // The request left the machine, so whether the write landed is unknown:
39
+ // keep the uncertainty contract and add what we know about the transport.
40
+ ctx.err(`${prefix()}${t(ctx.locale, ctx.unknownKey)}`);
41
+ ctx.err(`${prefix()}${t(ctx.locale, e.code, e.details)}`);
42
+ return ctx.exit(1);
43
+ }
44
+ if (e instanceof AgentError) throw e;
45
+ if (e instanceof ApiError && e.status >= 400 && e.status < 500) {
46
+ ctx.err(`${prefix()}${e.message}`);
47
+ printGatewayError(e, ctx.err);
48
+ } else {
49
+ ctx.err(`${prefix()}${t(ctx.locale, ctx.unknownKey)}`);
50
+ if (e instanceof ApiError) printGatewayError(e, ctx.err);
51
+ }
52
+ return ctx.exit(1);
53
+ }
54
+ return ctx.exit(0);
55
+ }
56
+
57
+ export async function run(ctx) {
58
+ const { args, api, emit, out, err, locale, exit } = ctx;
59
+ const sub = args.shift();
60
+ if (sub === "comment") {
61
+ ctx.rejectKey = "prCommentRejected";
62
+ ctx.unknownKey = "prCommentOutcomeUnknown";
63
+ return writeCommand(ctx, async () => {
64
+ const input = parsePRCommentArgs(args);
65
+ const result = validatePRCommentResult(await api("POST", input.path, input.body), input.target);
66
+ emit(result, () => out(t(locale, "prCommentCreated", { url: result.url, actor: result.actorLogin })));
67
+ });
68
+ }
69
+ if (sub === "approve") {
70
+ ctx.rejectKey = "prApproveRejected";
71
+ ctx.unknownKey = "prApproveOutcomeUnknown";
72
+ return writeCommand(ctx, async () => {
73
+ const input = parsePRApproveArgs(args);
74
+ const result = validatePRApproveResult(await api(input.method, input.path, input.body), input.target);
75
+ emit(result, () => out(t(locale, "prApproved", { actor: result.reviewerLogin, repository: result.repository, number: result.number })));
76
+ });
77
+ }
78
+ if (sub === "merge") {
79
+ ctx.rejectKey = "prMergeRejected";
80
+ ctx.unknownKey = "prMergeOutcomeUnknown";
81
+ return writeCommand(ctx, async () => {
82
+ const input = parsePRMergeArgs(args);
83
+ const result = validatePRMergeResult(await api(input.method, input.path, input.body), input.target);
84
+ emit(result, () => out(t(locale, "prMerged", { actor: result.actorLogin, sha: result.mergeSha, repository: result.repository, number: result.number })));
85
+ });
86
+ }
87
+ if (sub === "create") {
88
+ const input = pullRequestInput(args);
89
+ try {
90
+ const d = await api("POST", "/v1/pull-requests", input);
91
+ emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
92
+ } catch (e) {
93
+ if (e instanceof ApiError && e.status !== 401) {
94
+ err(`${prefix()}${e.message}`);
95
+ if (!printGatewayError(e, err)) err(t(locale, pullRequestRecovery(e.body?.error)));
96
+ return exit(1);
97
+ }
98
+ throw e;
99
+ }
100
+ return exit(0);
101
+ }
102
+ if (sub === "list" || sub === "ls") {
103
+ const { path, sections } = parsePRListArgs(args);
104
+ const paged = path.includes("limit=");
105
+ const d = validatePRListResponse(await api("GET", path), paged);
106
+ const labels = {
107
+ statusUnavailable: t(locale, "prStatusUnavailable"),
108
+ ci: t(locale, "prCIShort"),
109
+ agent: t(locale, "prAgentShort"),
110
+ ...sectionLabels(locale),
111
+ };
112
+ emit(
113
+ sections
114
+ ? { ...d, items: d.items.map((item) => ({ ...item, section: prSection(item) })) }
115
+ : d,
116
+ () => {
117
+ const lines = sections ? formatPRListSections(d, labels) : formatPRList(d, labels);
118
+ if (lines.length === 0) out(t(locale, "prListEmpty"));
119
+ else for (const line of lines) out(line);
120
+ if (d.nextCursor) out(t(locale, "prListMore", { cursor: safeInline(d.nextCursor) }));
121
+ },
122
+ );
123
+ return exit(0);
124
+ }
125
+ if (sub === "view") {
126
+ const target = parsePRTargetArgs(args, "usagePrView");
127
+ const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
128
+ emit(d, () => {
129
+ for (const line of formatPRDetail(d, {
130
+ head: t(locale, "prHeadLabel"),
131
+ checks: t(locale, "prChecksLabel"),
132
+ review: t(locale, "prReviewLabel"),
133
+ })) out(line);
134
+ });
135
+ return exit(0);
136
+ }
137
+ if (sub === "diff") {
138
+ const target = parsePRDiffArgs(args);
139
+ const d = validatePRDiff(await api("GET", prDiffPath(target)), target);
140
+ emit(d, () => {
141
+ const chunks = formatPRDiff(d, target.nameOnly, t(locale, "prDiffUnavailable"));
142
+ if (chunks.length === 0) out(t(locale, "prDiffEmpty"));
143
+ else out(chunks.join("\n"));
144
+ });
145
+ return exit(0);
146
+ }
147
+ if (sub === "checks") {
148
+ const target = parsePRTargetArgs(args, "usagePrChecks");
149
+ const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
150
+ emit(d.checks, () => {
151
+ const lines = formatPRChecks(d);
152
+ if (lines.length === 0) out(t(locale, "prChecksEmpty"));
153
+ else for (const line of lines) out(line);
154
+ });
155
+ return exit(prChecksExitCode(d));
156
+ }
157
+ throw new Error(t(locale, "usagePrRead"));
158
+ }
@@ -0,0 +1,10 @@
1
+ import { t } from "../locale.mjs";
2
+
3
+ export async function run(ctx) {
4
+ const sub = ctx.args.shift();
5
+ const id = ctx.args.shift();
6
+ if (sub !== "get" || !id) throw new Error(t(ctx.locale, "usageReceiptGet"));
7
+ const d = await ctx.api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
8
+ ctx.emit(d, () => ctx.out(`${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`));
9
+ return ctx.exit(0);
10
+ }
@@ -0,0 +1,66 @@
1
+ import { existsSync } from "node:fs";
2
+ import { t } from "../locale.mjs";
3
+ import { takeFlag } from "../flags.mjs";
4
+ import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone, runGitSetSSHCommand } from "../repo/clone.mjs";
5
+ import { fetchPublishedKnownHosts, resolveIdentityPath, resolveKnownHostsPath, sshCommandFor, writePinnedKnownHosts } from "../repo/ssh.mjs";
6
+
7
+ export async function run(ctx) {
8
+ if (ctx.args.shift() !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
9
+ const identityFlag = takeFlag(ctx.args, "identity");
10
+ const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
11
+ const parsed = parseRepoCloneArgs(ctx.args);
12
+ if (!parsed) throw new Error(t(ctx.locale, "usageRepoClone"));
13
+ const me = await ctx.api("GET", "/v1/me");
14
+ const repo = parseRepository(parsed.repository, me?.github?.login);
15
+ if (!repo) throw new Error(t(ctx.locale, "usageRepoClone"));
16
+ const url = gatewayCloneURL(me.sshHost, me.sshPort, repo.owner, repo.name);
17
+
18
+ // The clone carries the enrolled identity and the gateway's published host
19
+ // key itself (task #475): a bare clone must not fail with publickey, and it
20
+ // must not need a hand-exported GIT_SSH_COMMAND.
21
+ const identityPath = resolveIdentityPath(ctx.env, identityFlag);
22
+ if (!existsSync(identityPath)) {
23
+ throw new Error(t(ctx.locale, "cloneIdentityMissing", { path: identityPath }));
24
+ }
25
+ const knownHostsPath = resolveKnownHostsPath(ctx.env, knownHostsFlag);
26
+ const fetchImpl = ctx.opts.fetchImpl ?? fetch;
27
+ const published = await fetchPublishedKnownHosts({ apiBase: ctx.auth.apiBase, fetchImpl });
28
+ if (!published.ok) {
29
+ throw new Error(t(ctx.locale, published.invalid ? "cloneKnownHostsInvalid" : "cloneKnownHostsUnavailable", {
30
+ url: `${ctx.auth.apiBase}/.well-known/ssh-known-hosts`,
31
+ status: published.status ?? "?",
32
+ }));
33
+ }
34
+ writePinnedKnownHosts(knownHostsPath, published.pattern, published.line);
35
+ const sshCommand = sshCommandFor({ identityPath, knownHostsPath });
36
+
37
+ const git = ctx.opts.gitCloneImpl ?? runGitClone;
38
+ const result = await git({
39
+ url,
40
+ directory: parsed.directory,
41
+ gitFlags: parsed.gitFlags,
42
+ env: { ...(ctx.opts.gitEnv ?? ctx.env), GIT_SSH_COMMAND: sshCommand },
43
+ });
44
+ if (result.code !== 0) {
45
+ if (result.stderr) ctx.err(result.stderr.trimEnd());
46
+ if (/permission denied \(publickey\)/i.test(result.stderr ?? "")) {
47
+ ctx.err(t(ctx.locale, "clonePublicKeyRejected", { path: identityPath, publicKey: `${identityPath}.pub` }));
48
+ }
49
+ throw new Error(t(ctx.locale, "cloneFailed", { repository: `${repo.owner}/${repo.name}` }));
50
+ }
51
+ if (result.stderr) ctx.err(result.stderr.trimEnd());
52
+
53
+ // Make later git operations in this checkout work without any export.
54
+ const directory = parsed.directory ?? repo.name;
55
+ const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
56
+ ctx.emit(
57
+ { ok: true, repository: `${repo.owner}/${repo.name}`, url, directory, sshIdentity: identityPath, sshPinned: pinned.ok },
58
+ () => {
59
+ ctx.out(t(ctx.locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url }));
60
+ ctx.out(pinned.ok
61
+ ? t(ctx.locale, "cloneIdentityPinned", { directory })
62
+ : t(ctx.locale, "cloneIdentityPinFailed", { directory, command: sshCommand }));
63
+ },
64
+ );
65
+ return ctx.exit(0);
66
+ }
@@ -0,0 +1,52 @@
1
+ import { runAgentLogin } from "../agent-login.mjs";
2
+ import { humanExpiry } from "../expiry.mjs";
3
+ import { t } from "../locale.mjs";
4
+
5
+ export async function login(ctx) {
6
+ const { auth, opts, emit, out, locale, exit } = ctx;
7
+ if (auth.mode !== "agent") {
8
+ out(t(locale, "loginHumanIntro"));
9
+ out(t(locale, "loginHumanBrowser", { url: auth.apiBase }));
10
+ out(t(locale, "loginHumanCI"));
11
+ return exit(0);
12
+ }
13
+ const loginImpl = opts.loginImpl ?? runAgentLogin;
14
+ const session = await loginImpl(auth.agentEnv, auth.apiBase, { service: auth.service, fetchImpl: opts.fetchImpl });
15
+ // JSON keeps the raw RFC3339 instant; the human line renders it for a reader
16
+ // in their own time zone with how long is left (task #436).
17
+ const expiry = humanExpiry(locale, session.access_expires_at);
18
+ emit({ ok: true, service: auth.service, api_base: auth.apiBase, access_expires_at: session.access_expires_at },
19
+ () => out(t(locale, expiry.expired ? "loginTokenExpired" : "loginAgentReady", {
20
+ service: auth.service, url: auth.apiBase, expires: expiry.text, remaining: expiry.remaining,
21
+ })));
22
+ return exit(0);
23
+ }
24
+
25
+ export async function logout(ctx) {
26
+ const p = ctx.auth.logout();
27
+ ctx.out(p ? t(ctx.locale, "logoutForgot", { path: p }) : t(ctx.locale, "logoutNothing"));
28
+ return ctx.exit(0);
29
+ }
30
+
31
+ export async function whoami(ctx) {
32
+ const me = await ctx.api("GET", "/v1/me");
33
+ ctx.emit(me, () => ctx.out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${ctx.auth.apiBase}`));
34
+ return ctx.exit(0);
35
+ }
36
+
37
+ export async function migrationHelp(ctx) {
38
+ const fetchImpl = ctx.opts.fetchImpl ?? fetch;
39
+ const res = await fetchImpl(`${ctx.auth.apiBase}/v1/migration-help`, {
40
+ headers: { "accept-language": ctx.locale === "zh-CN" ? "zh-CN" : "en" },
41
+ });
42
+ const d = await res.json();
43
+ ctx.emit(d, () => {
44
+ ctx.out(t(ctx.locale, "helpInstall", { cmds: (d.install ?? []).join(" ; ") }));
45
+ ctx.out(t(ctx.locale, "helpAgentLogin", { text: d.login?.agent ?? "" }));
46
+ for (const [from, to] of Object.entries(d.actions_to_cli ?? {})) {
47
+ const note = d.notes?.[from];
48
+ ctx.out(note ? ` ${from} → ${to} (${note})` : ` ${from} → ${to}`);
49
+ }
50
+ });
51
+ return ctx.exit(0);
52
+ }
@@ -0,0 +1,35 @@
1
+ import { t } from "../locale.mjs";
2
+ import { takeFlag, objectArgs } from "../flags.mjs";
3
+
4
+ export async function follow(ctx) {
5
+ const body = objectArgs(ctx.args, ctx.locale);
6
+ const path = ctx.cmd === "follow" ? "/v1/subscriptions/objects/follow" : "/v1/subscriptions/objects/unfollow";
7
+ const d = await ctx.api("POST", path, body);
8
+ ctx.emit(d, () => ctx.out(JSON.stringify(d)));
9
+ return ctx.exit(0);
10
+ }
11
+
12
+ export async function subscription(ctx) {
13
+ const sub = ctx.args.shift();
14
+ if (sub !== "pause" && sub !== "resume") throw new Error(t(ctx.locale, "usageSubscription"));
15
+ const body = objectArgs(ctx.args, ctx.locale);
16
+ const d = await ctx.api("POST", `/v1/subscriptions/objects/${sub}`, body);
17
+ ctx.emit(d, () => ctx.out(JSON.stringify(d)));
18
+ return ctx.exit(0);
19
+ }
20
+
21
+ export async function subscriptions(ctx) {
22
+ const d = await ctx.api("GET", "/v1/subscriptions");
23
+ ctx.emit(d, () => ctx.out(JSON.stringify(d, null, 2)));
24
+ return ctx.exit(0);
25
+ }
26
+
27
+ export async function watch(ctx) {
28
+ const repository = ctx.args.shift();
29
+ const eventType = takeFlag(ctx.args, "event");
30
+ if (!repository || !eventType) throw new Error(t(ctx.locale, "usageWatch", { cmd: ctx.cmd }));
31
+ const path = ctx.cmd === "watch" ? "/v1/subscriptions/repositories/subscribe" : "/v1/subscriptions/repositories/unsubscribe";
32
+ const d = await ctx.api("POST", path, { repository, eventType });
33
+ ctx.emit(d, () => ctx.out(JSON.stringify(d)));
34
+ return ctx.exit(0);
35
+ }
package/lib/errors.mjs CHANGED
@@ -1,19 +1,6 @@
1
- import { t } from "./locale.mjs";
1
+ import { t, prefix } from "./locale.mjs";
2
2
 
3
- const apiRecoveryKeys = new Map([
4
- ["GITHUB_IDENTITY_BINDING_REQUIRED", "apiBindIdentity"],
5
- ["REPOSITORY_NOT_INSTALLED", "apiRepositoryNotInstalled"],
6
- ["PUBLIC_CONTRIBUTION_POLICY_DENIED", "apiContributionDenied"],
7
- ["REPOSITORY_NOT_AUTHORIZED", "apiRepositoryNotAuthorized"],
8
- ["PR_NOT_FOUND", "prReadNotFound"],
9
- ["PR_HEAD_MOVED", "prReadHeadMoved"],
10
- ["PR_DIFF_INCOMPLETE", "prReadDiffIncomplete"],
11
- ["PR_DETAIL_FAILED", "prReadUnavailable"],
12
- ["PR_DIFF_FAILED", "prReadUnavailable"],
13
- ["PR_INBOX_FAILED", "prReadUnavailable"],
14
- ]);
15
-
16
- /** Stable machine code on `.code`; English catalog text on `.message` for tests. */
3
+ // Local mistakes (bad flags, malformed JSON). `.code` is a locale catalog key.
17
4
  export class AgentError extends Error {
18
5
  constructor(code, details = {}) {
19
6
  super(t("en", code, details));
@@ -38,21 +25,13 @@ function stableErrorCode(value) {
38
25
  return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
39
26
  }
40
27
 
41
- function boundedSuggestedAction(value) {
42
- if (typeof value !== "string") return "";
43
- return value.trim().replace(/[\r\n\t]+/g, " ").slice(0, 512);
44
- }
45
-
46
- // API authorization denials keep the compatibility `error` at the top level and
47
- // carry the actionable reason in errorCode + suggestedNextAction. Prefer a localized,
48
- // executable repair for known codes; preserve a bounded server suggestion for future
49
- // codes so a new denial does not degrade back to an opaque REPOSITORY_NOT_AUTHORIZED.
50
- export function apiErrorGuidance(locale, body) {
51
- if (!body || typeof body !== "object") return { code: "", action: "" };
52
- const code = stableErrorCode(body.errorCode ?? body.error);
53
- const key = apiRecoveryKeys.get(code);
54
- return {
55
- code,
56
- action: key ? t(locale, key) : boundedSuggestedAction(body.suggestedNextAction),
57
- };
28
+ // The gateway owns the repair: JSON { error, errorCode, suggestedNextAction }.
29
+ // The CLI prints those fields verbatim. It does not keep a second code→copy map.
30
+ export function printGatewayError(error, write) {
31
+ const body = error.body;
32
+ const code = stableErrorCode(body?.errorCode ?? body?.error);
33
+ if (code && code !== body?.error) write(`${prefix()}${code}`);
34
+ const action = typeof body?.suggestedNextAction === "string" ? body.suggestedNextAction : "";
35
+ if (action) write(`${prefix()}${action}`);
36
+ return Boolean(action);
58
37
  }
package/lib/expiry.mjs ADDED
@@ -0,0 +1,27 @@
1
+ // The access-token expiry was printed as the raw RFC3339 UTC string, which a
2
+ // reader in another time zone sees as a time earlier than their own clock and
3
+ // reads as "already expired" (task #436). The human line gets a local time plus
4
+ // how long is left; the JSON keeps the raw value for machines.
5
+
6
+ function localeTag(locale) {
7
+ return locale === "zh-CN" ? "zh-CN" : "en-US";
8
+ }
9
+
10
+ // humanExpiry formats an RFC3339 instant for the reader: local time with its
11
+ // zone, and a relative remaining time. An unparseable value is returned as-is
12
+ // (never crash on a display-only path).
13
+ export function humanExpiry(locale, iso, now = Date.now()) {
14
+ const ms = Date.parse(String(iso ?? ""));
15
+ if (!Number.isFinite(ms)) return { text: String(iso ?? ""), remaining: "", expired: false };
16
+ const tag = localeTag(locale);
17
+ // dateStyle/timeStyle cannot be combined with timeZoneName, and the zone is the
18
+ // whole point here: name the components explicitly.
19
+ const text = new Intl.DateTimeFormat(tag, {
20
+ year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZoneName: "short",
21
+ }).format(ms);
22
+ const minutes = Math.round((ms - now) / 60000);
23
+ const relative = new Intl.RelativeTimeFormat(tag, { numeric: "auto" });
24
+ // Minutes are the useful unit up to 90 of them; beyond that, hours.
25
+ const remaining = Math.abs(minutes) >= 90 ? relative.format(Math.round(minutes / 60), "hour") : relative.format(minutes, "minute");
26
+ return { text, remaining, expired: minutes <= 0 };
27
+ }
package/lib/flags.mjs ADDED
@@ -0,0 +1,26 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { t } from "./locale.mjs";
3
+
4
+ export function takeFlag(args, name, dflt) {
5
+ const i = args.indexOf(`--${name}`);
6
+ if (i === -1) return dflt;
7
+ const v = args[i + 1];
8
+ args.splice(i, 2);
9
+ return v;
10
+ }
11
+
12
+ export function readPublicKey(path) {
13
+ if (path === "-") return readFileSync(0, "utf8").trim();
14
+ return readFileSync(path, "utf8").trim();
15
+ }
16
+
17
+ export function objectArgs(args, locale) {
18
+ const repository = args.shift();
19
+ const rawKind = takeFlag(args, "kind");
20
+ const kind = rawKind === "pull" ? "pull_request" : rawKind;
21
+ const number = Number(takeFlag(args, "number"));
22
+ if (!repository || !["issue", "pull_request"].includes(kind) || !Number.isInteger(number) || number <= 0) {
23
+ throw new Error(t(locale, "usageFollow"));
24
+ }
25
+ return { repository, kind, number };
26
+ }