@botiverse/stamp-cli 0.3.3 → 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.
- package/README.md +7 -0
- package/lib/agent-login.mjs +10 -1
- package/lib/auth.mjs +45 -2
- package/lib/client.mjs +67 -10
- package/lib/commands/identity.mjs +12 -0
- package/lib/commands/key.mjs +21 -0
- package/lib/commands/pr.mjs +158 -0
- package/lib/commands/receipt.mjs +10 -0
- package/lib/commands/repo.mjs +66 -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 +81 -13
- package/lib/main.mjs +39 -302
- package/lib/{pr-comment.mjs → pr/comment.mjs} +2 -2
- package/lib/{pull-request.mjs → pr/create.mjs} +1 -1
- package/lib/{pr-read.mjs → pr/read.mjs} +8 -4
- package/lib/pr/write.mjs +82 -0
- package/lib/{repo-clone.mjs → repo/clone.mjs} +15 -0
- package/lib/repo/ssh.mjs +96 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,6 +36,13 @@ Configuration layering is `environment > executable defaults`: `STAMP_URL` and
|
|
|
36
36
|
`STAMP_SERVICE` override either bin explicitly. There are no per-run URL or
|
|
37
37
|
service command-line flags today.
|
|
38
38
|
|
|
39
|
+
`repo clone` carries the SSH identity itself (task #475): it uses the key
|
|
40
|
+
`key enroll` uses (`~/.ssh/id_ed25519`, or `--identity FILE` / `STAMP_SSH_IDENTITY`)
|
|
41
|
+
and pins the host key the instance publishes at `/.well-known/ssh-known-hosts` into
|
|
42
|
+
`~/.stamp/known_hosts` (`--known-hosts FILE` / `STAMP_KNOWN_HOSTS`), then records
|
|
43
|
+
the same command as the clone's `core.sshCommand` so later `git push`/`git fetch`
|
|
44
|
+
inherit it. No `GIT_SSH_COMMAND` export is needed.
|
|
45
|
+
|
|
39
46
|
When `STAMP_URL` is not explicit, an existing Agent session stored against the
|
|
40
47
|
exact legacy staging origin `https://github-staging.botiverse.dev` or the
|
|
41
48
|
former CLI placeholder `https://github.botiverse.dev` is used against the new
|
package/lib/agent-login.mjs
CHANGED
|
@@ -160,7 +160,16 @@ export async function runAgentLogin(a, apiBase, opts = {}) {
|
|
|
160
160
|
const runner = opts.invoke ?? ((a2) => defaultInvoke(a.raftBin, a2));
|
|
161
161
|
const res = runner(args);
|
|
162
162
|
if (res.status !== 0) {
|
|
163
|
-
|
|
163
|
+
// Surface raft's OWN diagnostics (@Mason / @Tenny / @skyzh): raft already
|
|
164
|
+
// reports the LAYERED reason -- the error, the stable Code and the Next
|
|
165
|
+
// action -- and the next action is what the reader actually needs. Keep all
|
|
166
|
+
// of it (not just the first line): truncating to one line drops the fix.
|
|
167
|
+
const diagnostic = String(res.stderr ?? "")
|
|
168
|
+
.split("\n")
|
|
169
|
+
.map((l) => l.trimEnd())
|
|
170
|
+
.filter((l) => l.trim().length > 0)
|
|
171
|
+
.join("\n");
|
|
172
|
+
agentFail("invoke_exit", { status: res.status ?? "spawn error", diagnostic });
|
|
164
173
|
}
|
|
165
174
|
const { grant } = parseAgentLoginInvoke(res.stdout, service, now);
|
|
166
175
|
|
package/lib/auth.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { unlinkSync, existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
2
3
|
import { admitAgent, agentAuthPath } from "@botiverse/agent-session-store";
|
|
3
4
|
import { STAMP_LEGACY_DEFAULT_URL, STAMP_LEGACY_STAGING_URL, STAMP_SERVICE } from "./agent-login.mjs";
|
|
4
5
|
import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
|
|
@@ -25,6 +26,22 @@ const KNOWN_INSTANCES = new Map([
|
|
|
25
26
|
["https://stamp.build", "stamp"],
|
|
26
27
|
["https://staging.stamp.build", "raft-git-gateway-staging"],
|
|
27
28
|
]);
|
|
29
|
+
|
|
30
|
+
// origin -> the installed binary that serves that instance, for the "wrong
|
|
31
|
+
// entry point" case (task #436): a session stored for staging rejects `stamp`,
|
|
32
|
+
// and telling the reader to run `stamp login` again sends them further from the
|
|
33
|
+
// fix. Only the instances we ship a binary for are named.
|
|
34
|
+
const INSTANCE_BINARIES = new Map([
|
|
35
|
+
["https://stamp.build", "stamp"],
|
|
36
|
+
["https://staging.stamp.build", "stamp-staging"],
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
// siblingBinaryFor names the binary that serves the instance a stored session
|
|
40
|
+
// belongs to, so the refusal can point at it instead of at a re-login. Empty
|
|
41
|
+
// for an unknown/self-hosted origin: we do not guess a command that may not exist.
|
|
42
|
+
export function siblingBinaryFor(storedOrigin) {
|
|
43
|
+
return INSTANCE_BINARIES.get(storedOrigin) ?? "";
|
|
44
|
+
}
|
|
28
45
|
// storeMatchesOrigin reports whether a stored session belongs to the SAME
|
|
29
46
|
// instance as the target base. It is ONE branch-free property — the parsed
|
|
30
47
|
// origins must be strictly equal — and it must hold at EVERY actual use
|
|
@@ -59,6 +76,30 @@ export function assertCoherentPair(apiBase, service) {
|
|
|
59
76
|
}
|
|
60
77
|
}
|
|
61
78
|
|
|
79
|
+
// A partial managed-agent environment fails closed, and the message has to say
|
|
80
|
+
// WHICH variable is missing (task #480): "incomplete agent markers" makes the
|
|
81
|
+
// operator diff three variables by hand. The package reports the outcome, not
|
|
82
|
+
// the field, so the mapping is derived here from the environment and only the
|
|
83
|
+
// documented outcomes are matched; an unrecognized reason keeps the generic
|
|
84
|
+
// wording rather than guessing.
|
|
85
|
+
const AGENT_MARKERS = ["SLOCK_CLI_TRANSPORT_DIR", "SLOCK_HOME", "SLOCK_AGENT_ID"];
|
|
86
|
+
|
|
87
|
+
export function admissionFailure(admission, env = {}) {
|
|
88
|
+
if (admission?.reason === "incomplete agent markers") {
|
|
89
|
+
return new AgentError("admissionMissingVars", {
|
|
90
|
+
missing: AGENT_MARKERS.filter((name) => !env[name]).join(", "),
|
|
91
|
+
present: AGENT_MARKERS.filter((name) => env[name]).join(", ") || "none",
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
if (admission?.reason === "invalid SLOCK_AGENT_ID") {
|
|
95
|
+
return new AgentError("admissionInvalidAgentID", { value: String(env.SLOCK_AGENT_ID ?? "") });
|
|
96
|
+
}
|
|
97
|
+
if (admission?.reason === "raft wrapper missing or not executable in transport dir") {
|
|
98
|
+
return new AgentError("admissionRaftWrapper", { path: join(String(env.SLOCK_CLI_TRANSPORT_DIR ?? ""), "raft") });
|
|
99
|
+
}
|
|
100
|
+
return new AgentError("admissionPartial", { reason: String(admission?.reason ?? "unknown") });
|
|
101
|
+
}
|
|
102
|
+
|
|
62
103
|
export function resolveAuth({ urlBase, urlExplicit, env = process.env, service, locale = "en", cliName = "stamp" }) {
|
|
63
104
|
// The instance slug may be left unset (e.g. `stamp-staging` passes only its
|
|
64
105
|
// base). Derive it: an explicit STAMP_SERVICE wins, else the base's owner,
|
|
@@ -69,7 +110,7 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
|
|
|
69
110
|
}
|
|
70
111
|
const admission = admitAgent(env);
|
|
71
112
|
if (admission.kind === "fail_closed") {
|
|
72
|
-
|
|
113
|
+
throw admissionFailure(admission, env);
|
|
73
114
|
}
|
|
74
115
|
if (admission.kind === "agent") {
|
|
75
116
|
const a = admission.env;
|
|
@@ -109,10 +150,12 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
|
|
|
109
150
|
async token() {
|
|
110
151
|
if (!usableStore) {
|
|
111
152
|
if (storedOriginElsewhere !== null) {
|
|
112
|
-
|
|
153
|
+
const sibling = siblingBinaryFor(storedOriginElsewhere);
|
|
154
|
+
throw new AgentError(sibling && sibling !== cliName ? "sessionOriginMismatchSibling" : "sessionOriginMismatch", {
|
|
113
155
|
stored: storedOriginElsewhere,
|
|
114
156
|
target: originOf(apiBase) ?? apiBase,
|
|
115
157
|
cli: cliName,
|
|
158
|
+
other: sibling,
|
|
116
159
|
});
|
|
117
160
|
}
|
|
118
161
|
throw new AgentError("notLoggedIn");
|
package/lib/client.mjs
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import { AgentError } from "./errors.mjs";
|
|
2
|
+
|
|
3
|
+
// NetworkError is an AgentError about the transport, not about the request. A
|
|
4
|
+
// WRITE that fails this way has an UNKNOWN outcome (the request may have
|
|
5
|
+
// reached the gateway), so the write commands must keep their "outcome is
|
|
6
|
+
// unknown, do not resend" contract instead of inviting a retry.
|
|
7
|
+
export class NetworkError extends AgentError {}
|
|
8
|
+
|
|
1
9
|
export class ApiError extends Error {
|
|
2
10
|
constructor(status, body, text) {
|
|
3
11
|
super(`${status}: ${body?.error ?? (text ?? "").slice(0, 200)}`);
|
|
@@ -6,17 +14,66 @@ export class ApiError extends Error {
|
|
|
6
14
|
}
|
|
7
15
|
}
|
|
8
16
|
|
|
9
|
-
|
|
17
|
+
// A connection-level failure (never an HTTP status) arrives from undici as
|
|
18
|
+
// TypeError("fetch failed") with the real reason on `.cause`. The CLI used to
|
|
19
|
+
// hand that bare string to the operator; task #476 showed a first `pr list` on a
|
|
20
|
+
// cold instance failing that way while a rerun worked, because nothing retried
|
|
21
|
+
// the one attempt and nothing said what to try next. Text and JSON output share
|
|
22
|
+
// this client — the failure happens before either formatter runs — so the fix
|
|
23
|
+
// belongs here, not in one output path.
|
|
24
|
+
const RETRYABLE_NETWORK_CODES = new Set([
|
|
25
|
+
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE", "EAI_AGAIN",
|
|
26
|
+
"UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT",
|
|
27
|
+
]);
|
|
28
|
+
const DNS_NETWORK_CODES = new Set(["ENOTFOUND", "EAI_AGAIN"]);
|
|
29
|
+
|
|
30
|
+
export function networkFailureOf(error) {
|
|
31
|
+
const code = String(error?.cause?.code ?? error?.code ?? "");
|
|
32
|
+
const message = String(error?.cause?.message ?? error?.message ?? "");
|
|
33
|
+
if (DNS_NETWORK_CODES.has(code)) return { code, retryable: true };
|
|
34
|
+
if (RETRYABLE_NETWORK_CODES.has(code)) return { code, retryable: true };
|
|
35
|
+
if (code || /fetch failed/i.test(message)) {
|
|
36
|
+
// Unknown transport failure: report it, but do not spin on it.
|
|
37
|
+
return { code: code || message || "fetch failed", retryable: false };
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function networkErrorKey(failure) {
|
|
43
|
+
return DNS_NETWORK_CODES.has(failure.code) ? "networkHostUnresolved" : "networkUnreachable";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function makeClient(auth, fetchImpl = fetch, options = {}) {
|
|
47
|
+
// Reads are idempotent, so a bounded retry is safe; writes are not retried
|
|
48
|
+
// here (they carry their own idempotency key and a retry decision).
|
|
49
|
+
const readRetries = Number.isInteger(options.readRetries) ? Math.max(0, options.readRetries) : 2;
|
|
50
|
+
const retryDelayMs = Number.isInteger(options.retryDelayMs) ? Math.max(0, options.retryDelayMs) : 250;
|
|
51
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
52
|
+
|
|
10
53
|
async function once(method, path, body, token) {
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
54
|
+
const attempts = method === "GET" ? readRetries + 1 : 1;
|
|
55
|
+
for (let attempt = 1; ; attempt++) {
|
|
56
|
+
let res;
|
|
57
|
+
try {
|
|
58
|
+
res = await fetchImpl(`${auth.apiBase}${path}`, {
|
|
59
|
+
method,
|
|
60
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
|
|
61
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
62
|
+
});
|
|
63
|
+
} catch (error) {
|
|
64
|
+
const failure = networkFailureOf(error);
|
|
65
|
+
if (!failure) throw error;
|
|
66
|
+
if (failure.retryable && attempt < attempts) {
|
|
67
|
+
await sleep(retryDelayMs * attempt);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
throw new NetworkError(networkErrorKey(failure), { base: auth.apiBase, cause: failure.code });
|
|
71
|
+
}
|
|
72
|
+
const text = await res.text();
|
|
73
|
+
let json = null;
|
|
74
|
+
try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON error page */ }
|
|
75
|
+
return { res, json, text };
|
|
76
|
+
}
|
|
20
77
|
}
|
|
21
78
|
return async function api(method, path, body) {
|
|
22
79
|
const used = await auth.token();
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { t } from "../locale.mjs";
|
|
2
|
+
import { takeFlag } from "../flags.mjs";
|
|
3
|
+
|
|
4
|
+
export async function run(ctx) {
|
|
5
|
+
const sub = ctx.args.shift();
|
|
6
|
+
if (sub !== "bind") throw new Error(t(ctx.locale, "usageIdentityBind"));
|
|
7
|
+
const agentEmail = takeFlag(ctx.args, "email");
|
|
8
|
+
if (!agentEmail) throw new Error(t(ctx.locale, "usageIdentityBind"));
|
|
9
|
+
const d = await ctx.api("POST", "/v1/identities", { agentEmail });
|
|
10
|
+
ctx.emit(d, () => ctx.out(t(ctx.locale, "bound", { email: d.agentEmail })));
|
|
11
|
+
return ctx.exit(0);
|
|
12
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { t } from "../locale.mjs";
|
|
5
|
+
import { takeFlag, readPublicKey } from "../flags.mjs";
|
|
6
|
+
|
|
7
|
+
export async function run(ctx) {
|
|
8
|
+
const sub = ctx.args.shift();
|
|
9
|
+
if (sub !== "enroll") throw new Error(t(ctx.locale, "usageKeyEnroll"));
|
|
10
|
+
const keyPath = takeFlag(ctx.args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
|
|
11
|
+
if (keyPath !== "-" && !existsSync(keyPath)) {
|
|
12
|
+
// The default path is the interesting case: `key enroll` on a machine with
|
|
13
|
+
// no key reads a path the operator never typed, so name it and name the two
|
|
14
|
+
// ways out (task #480).
|
|
15
|
+
throw new Error(t(ctx.locale, "keyPublicKeyMissing", { path: keyPath, private: keyPath.replace(/\.pub$/i, "") }));
|
|
16
|
+
}
|
|
17
|
+
const publicKey = readPublicKey(keyPath);
|
|
18
|
+
const d = await ctx.api("POST", "/v1/keys", { publicKey });
|
|
19
|
+
ctx.emit(d, () => ctx.out(t(ctx.locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId })));
|
|
20
|
+
return ctx.exit(0);
|
|
21
|
+
}
|
|
@@ -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,24 +1,6 @@
|
|
|
1
|
-
import { t } from "./locale.mjs";
|
|
1
|
+
import { t, prefix } from "./locale.mjs";
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
// Cursor scope/format rejections (task #397 slice 1): the cursor is bound to
|
|
15
|
-
// (tenant, server, viewer scope, filter); a mismatched or malformed cursor is
|
|
16
|
-
// a recoverable user error, never a generic contract mismatch.
|
|
17
|
-
["PR_INBOX_CURSOR_SCOPE", "prCursorScope"],
|
|
18
|
-
["PR_INBOX_CURSOR_INVALID", "prCursorInvalid"],
|
|
19
|
-
]);
|
|
20
|
-
|
|
21
|
-
/** 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.
|
|
22
4
|
export class AgentError extends Error {
|
|
23
5
|
constructor(code, details = {}) {
|
|
24
6
|
super(t("en", code, details));
|
|
@@ -43,21 +25,13 @@ function stableErrorCode(value) {
|
|
|
43
25
|
return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
|
|
44
26
|
}
|
|
45
27
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
export function apiErrorGuidance(locale, body) {
|
|
56
|
-
if (!body || typeof body !== "object") return { code: "", action: "" };
|
|
57
|
-
const code = stableErrorCode(body.errorCode ?? body.error);
|
|
58
|
-
const key = apiRecoveryKeys.get(code);
|
|
59
|
-
return {
|
|
60
|
-
code,
|
|
61
|
-
action: key ? t(locale, key) : boundedSuggestedAction(body.suggestedNextAction),
|
|
62
|
-
};
|
|
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);
|
|
63
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
|
+
}
|