@botiverse/stamp-cli 0.2.0 → 0.3.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/README.md +36 -0
- package/bin/stamp.mjs +5 -96
- package/lib/agent-login.mjs +196 -0
- package/lib/agent-refresh.mjs +178 -0
- package/lib/auth.mjs +45 -0
- package/lib/client.mjs +31 -0
- package/lib/errors.mjs +20 -0
- package/lib/locale.mjs +216 -0
- package/lib/main.mjs +202 -0
- package/lib/pull-request.mjs +61 -0
- package/package.json +13 -6
package/README.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# stamp
|
|
2
|
+
|
|
3
|
+
CLI for the Agent Git gateway. Bin `stamp`. Package `@botiverse/stamp-cli`.
|
|
4
|
+
Session storage is `@botiverse/agent-session-store` (fail-closed Raft agent
|
|
5
|
+
admission, atomic 0600 `auth.json`). Future public origin: `stamp.build`.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm i -g @botiverse/stamp-cli
|
|
9
|
+
stamp login
|
|
10
|
+
stamp key enroll
|
|
11
|
+
stamp identity bind --email agent@example.com
|
|
12
|
+
git push git@github.botiverse.dev:org/repo.git HEAD:refs/heads/agent/my-change
|
|
13
|
+
stamp receipt get <id>
|
|
14
|
+
stamp pr create --receipt <published-id> --repo org/repo --head agent/my-change --sha <exact-sha> --base main --title "My change" --body-file ./pr-body.md
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- Agent: `stamp login` (PKCE grant via `raft integration invoke --action agent-login`)
|
|
18
|
+
- Human / CI: `STAMP_TOKEN`
|
|
19
|
+
- Instance: `STAMP_URL` (default `https://github.botiverse.dev`)
|
|
20
|
+
- Raft app slug: `STAMP_SERVICE` (must match the gateway: `STAMP_SERVICE` or `RAFT_OAUTH_CLIENT_ID`; staging today is `raft-git-gateway-staging`, future `stamp`)
|
|
21
|
+
|
|
22
|
+
`stamp pr create` calls the service directly using the Agent's service session.
|
|
23
|
+
The receipt must belong to that Agent and be `PUBLISHED`; head/ref/repository/SHA
|
|
24
|
+
must match it. Identical payloads derive a stable idempotency key, so rerunning
|
|
25
|
+
the command after a lost response does not create a second PR. You can supply
|
|
26
|
+
`--idempotency-key` explicitly (16–128 letters/digits/`._:-`). Branch names are
|
|
27
|
+
expanded to `refs/heads/...`; full refs also work. Use `--body-file -` for stdin,
|
|
28
|
+
`--body` for inline text. A non-empty description is required. `--json` prints the
|
|
29
|
+
service receipt; a denial exits nonzero with recovery guidance.
|
|
30
|
+
|
|
31
|
+
The Raft manifest exposes only `agent-login`. Key enrollment, identity binding,
|
|
32
|
+
receipt reads, PR creation and subscriptions all use this CLI; the HTTP APIs
|
|
33
|
+
remain available to service clients. `stamp migration-help` maps retired action
|
|
34
|
+
names to commands. The retirement follows the Stamp owner's explicit cutover
|
|
35
|
+
decision; the general Raft migration guide's optional compatibility period is
|
|
36
|
+
over for this service.
|
package/bin/stamp.mjs
CHANGED
|
@@ -1,99 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// stamp — CLI for the
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
// stamp run <case-id...> [--app slug] [--apk ref] [--release id] [--by who]
|
|
6
|
-
// stamp runs list recent runs
|
|
7
|
-
// stamp show <run-id> run detail: cases, verdicts, evidence
|
|
8
|
-
//
|
|
9
|
-
// Auth: STAMP_TOKEN env (deploy token). STAMP_URL overrides the instance.
|
|
2
|
+
// stamp — CLI for the Agent Git gateway (future origin stamp.build).
|
|
3
|
+
// Default instance is the current SSH/HTTPS hostname.
|
|
4
|
+
import { main } from "../lib/main.mjs";
|
|
10
5
|
|
|
11
|
-
const URL_BASE = process.env.STAMP_URL || "https://
|
|
12
|
-
const TOKEN = process.env.STAMP_TOKEN || "";
|
|
6
|
+
const URL_BASE = process.env.STAMP_URL || "https://github.botiverse.dev";
|
|
13
7
|
|
|
14
|
-
|
|
15
|
-
const cmd = args.shift();
|
|
16
|
-
|
|
17
|
-
function flag(name, dflt) {
|
|
18
|
-
const i = args.indexOf(`--${name}`);
|
|
19
|
-
if (i === -1) return dflt;
|
|
20
|
-
const v = args[i + 1];
|
|
21
|
-
args.splice(i, 2);
|
|
22
|
-
return v;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
async function api(method, path, body) {
|
|
26
|
-
if (!TOKEN) die("STAMP_TOKEN is not set (deploy token)");
|
|
27
|
-
const res = await fetch(`${URL_BASE}/api${path}`, {
|
|
28
|
-
method,
|
|
29
|
-
headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json" },
|
|
30
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
31
|
-
});
|
|
32
|
-
const text = await res.text();
|
|
33
|
-
let json;
|
|
34
|
-
try { json = JSON.parse(text); } catch { die(`${res.status}: ${text.slice(0, 200)}`); }
|
|
35
|
-
if (!res.ok) die(`${res.status}: ${json.error ?? text.slice(0, 200)}`);
|
|
36
|
-
return json;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function die(msg) { console.error(`stamp: ${msg}`); process.exit(1); }
|
|
40
|
-
function table(rows, cols) {
|
|
41
|
-
const w = cols.map((c) => Math.max(c.length, ...rows.map((r) => String(r[c] ?? "").length)));
|
|
42
|
-
console.log(cols.map((c, i) => c.padEnd(w[i])).join(" "));
|
|
43
|
-
for (const r of rows) console.log(cols.map((c, i) => String(r[c] ?? "").padEnd(w[i])).join(" "));
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
switch (cmd) {
|
|
47
|
-
case "cases": {
|
|
48
|
-
const { cases } = await api("GET", "/cases");
|
|
49
|
-
table(cases.map((c) => ({ id: c.id, tier: c.tier, rev: c.revision, title: c.title })), ["id", "tier", "rev", "title"]);
|
|
50
|
-
break;
|
|
51
|
-
}
|
|
52
|
-
case "run": {
|
|
53
|
-
const app = flag("app", "raft-android");
|
|
54
|
-
const apk = flag("apk"); // http url = test that exact package
|
|
55
|
-
const ref = flag("ref"); // git ref to build from (default main)
|
|
56
|
-
const apkRun = flag("apk-run"); // CI run id whose APK artifact to reuse (same bits)
|
|
57
|
-
const release = flag("release");
|
|
58
|
-
const by = flag("by", process.env.USER || "stamp-cli");
|
|
59
|
-
const caseIds = args.filter((a) => !a.startsWith("--"));
|
|
60
|
-
if (!caseIds.length) die("usage: stamp run <case-id...> [--app slug] [--ref branch] [--apk url] [--apk-run ci-run-id] [--release id]");
|
|
61
|
-
const out = await api("POST", "/runs", {
|
|
62
|
-
app_slug: app, case_ids: caseIds, apk_ref: apk, ref, apk_run_id: apkRun,
|
|
63
|
-
hands_release_id: release, requested_by: by,
|
|
64
|
-
});
|
|
65
|
-
console.log(`run ${out.run_id} — ${out.cases} case(s), ${out.dispatched} dispatched`);
|
|
66
|
-
console.log(`${URL_BASE}/runs/${out.run_id}`);
|
|
67
|
-
break;
|
|
68
|
-
}
|
|
69
|
-
case "runs": {
|
|
70
|
-
const { runs } = await api("GET", "/runs");
|
|
71
|
-
table(runs.map((r) => ({
|
|
72
|
-
run: r.id.slice(0, 8), app: r.app_slug, status: r.status,
|
|
73
|
-
cases: r.case_count, release: r.hands_release_id ?? "-",
|
|
74
|
-
created: new Date(r.created_at).toISOString().slice(0, 16),
|
|
75
|
-
})), ["run", "app", "status", "cases", "release", "created"]);
|
|
76
|
-
break;
|
|
77
|
-
}
|
|
78
|
-
case "show": {
|
|
79
|
-
const id = args[0] || die("usage: stamp show <run-id>");
|
|
80
|
-
const d = await api("GET", `/runs/${id}`);
|
|
81
|
-
console.log(`run ${d.run.id} — ${d.run.status} (${d.run.app_slug}, release: ${d.run.hands_release_id ?? "-"})`);
|
|
82
|
-
console.log(`${URL_BASE}/runs/${d.run.id}\n`);
|
|
83
|
-
table(d.cases.map((rc) => {
|
|
84
|
-
const v = rc.verdict_json ? JSON.parse(rc.verdict_json) : null;
|
|
85
|
-
const ev = d.evidence.filter((e) => e.run_case_id === rc.id).length;
|
|
86
|
-
return { case: rc.case_id, status: rc.status, verdict: v?.verdict ?? "-", turns: v?.turns ?? "-", evidence: ev };
|
|
87
|
-
}), ["case", "status", "verdict", "turns", "evidence"]);
|
|
88
|
-
for (const rv of d.reviews) console.log(`\nfinal: ${rv.verdict} by ${rv.reviewer}${rv.comment ? ` — ${rv.comment}` : ""}`);
|
|
89
|
-
break;
|
|
90
|
-
}
|
|
91
|
-
default:
|
|
92
|
-
console.log("stamp — the acceptance stamp in the Raft release loop\n");
|
|
93
|
-
console.log(" stamp cases list the case library");
|
|
94
|
-
console.log(" stamp run <case-id...> [--app --ref --apk --apk-run --release --by]");
|
|
95
|
-
console.log(" stamp runs list recent runs");
|
|
96
|
-
console.log(" stamp show <run-id> run detail");
|
|
97
|
-
console.log("\nauth: STAMP_TOKEN env; instance: STAMP_URL (default raft-app-stamp.botiverse.dev)");
|
|
98
|
-
process.exit(cmd ? 1 : 0);
|
|
99
|
-
}
|
|
8
|
+
await main(process.argv.slice(2), { urlBase: URL_BASE, urlExplicit: Boolean(process.env.STAMP_URL) });
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent CLI login (RFC 057). Ported from the Hands/testbed CLIs.
|
|
3
|
+
*
|
|
4
|
+
* 1. Local PKCE verifier; send only S256 challenge through Raft.
|
|
5
|
+
* 2. Exact wrapper `$SLOCK_CLI_TRANSPORT_DIR/raft integration invoke
|
|
6
|
+
* --service <slug> --action agent-login --json` (never PATH `raft`).
|
|
7
|
+
* 3. Exchange grant + verifier at POST /api/auth/agent/exchange.
|
|
8
|
+
* 4. Persist via @botiverse/agent-session-store.
|
|
9
|
+
*/
|
|
10
|
+
import { spawnSync } from "node:child_process";
|
|
11
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
12
|
+
import { writeAgentSession } from "@botiverse/agent-session-store";
|
|
13
|
+
import { AgentError, agentFail } from "./errors.mjs";
|
|
14
|
+
|
|
15
|
+
export const STAMP_SERVICE = "stamp";
|
|
16
|
+
export const TOKEN_DEADLINE_MS = 20_000;
|
|
17
|
+
|
|
18
|
+
function base64url(buf) {
|
|
19
|
+
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function generatePkce() {
|
|
23
|
+
const verifier = base64url(randomBytes(64));
|
|
24
|
+
const challenge = base64url(createHash("sha256").update(verifier).digest());
|
|
25
|
+
return { verifier, challenge };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function hasExactKeys(o, keys) {
|
|
29
|
+
const k = Object.keys(o);
|
|
30
|
+
return k.length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(o, key));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function parseRfc3339(s) {
|
|
34
|
+
if (typeof s !== "string") return null;
|
|
35
|
+
if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/.test(s)) return null;
|
|
36
|
+
const t = Date.parse(s);
|
|
37
|
+
return Number.isFinite(t) ? t : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const AGENT_GRANT_TTL_CEILING_MS = 300_000 + 120_000;
|
|
41
|
+
|
|
42
|
+
export function parseAgentLoginInvoke(stdout, service, now) {
|
|
43
|
+
let outer;
|
|
44
|
+
try { outer = JSON.parse(stdout); } catch { agentFail("invoke_not_json"); }
|
|
45
|
+
if (!outer || typeof outer !== "object") agentFail("invoke_not_object");
|
|
46
|
+
if (outer.ok !== true) agentFail("invoke_failed");
|
|
47
|
+
if (!hasExactKeys(outer, ["ok", "data"])) agentFail("invoke_envelope");
|
|
48
|
+
const data = outer.data;
|
|
49
|
+
if (!data || typeof data !== "object") agentFail("invoke_data");
|
|
50
|
+
if (!hasExactKeys(data, ["service", "action", "status", "result"])) agentFail("invoke_data_fields");
|
|
51
|
+
if (data.service !== service) agentFail("invoke_service");
|
|
52
|
+
if (data.action !== "agent-login") agentFail("invoke_action");
|
|
53
|
+
if (data.status !== 200) agentFail("invoke_http");
|
|
54
|
+
const result = data.result;
|
|
55
|
+
if (!result || typeof result !== "object") agentFail("grant_body");
|
|
56
|
+
if (!hasExactKeys(result, ["schema", "service", "grant", "expires_at"])) agentFail("grant_fields");
|
|
57
|
+
if (result.schema !== "raft-cli-agent-login-grant.v1") agentFail("grant_schema");
|
|
58
|
+
if (result.service !== service) agentFail("grant_service");
|
|
59
|
+
if (typeof result.grant !== "string" || result.grant.length === 0) agentFail("grant_missing");
|
|
60
|
+
const exp = parseRfc3339(result.expires_at);
|
|
61
|
+
if (exp === null) agentFail("grant_expires_at");
|
|
62
|
+
if (exp <= now) agentFail("grant_expired");
|
|
63
|
+
if (exp > now + AGENT_GRANT_TTL_CEILING_MS) agentFail("grant_ttl");
|
|
64
|
+
return { grant: result.grant, expires_at: result.expires_at };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function parseAgentSession(body, now) {
|
|
68
|
+
if (!body || typeof body !== "object") agentFail("session_not_object");
|
|
69
|
+
if (!hasExactKeys(body, ["schema", "token_type", "access_token", "access_expires_at", "refresh_token", "refresh_expires_at"])) {
|
|
70
|
+
agentFail("session_fields");
|
|
71
|
+
}
|
|
72
|
+
if (body.schema !== "raft-cli-agent-session.v1") agentFail("session_schema");
|
|
73
|
+
if (body.token_type !== "Bearer") agentFail("session_token_type");
|
|
74
|
+
for (const k of ["access_token", "refresh_token"]) {
|
|
75
|
+
if (typeof body[k] !== "string" || body[k].length === 0) agentFail("session_missing", { field: k });
|
|
76
|
+
}
|
|
77
|
+
const accessExp = parseRfc3339(body.access_expires_at);
|
|
78
|
+
if (accessExp === null) agentFail("session_access_exp");
|
|
79
|
+
if (accessExp <= now) agentFail("session_access_expired");
|
|
80
|
+
if (body.refresh_expires_at !== null) {
|
|
81
|
+
const refreshExp = parseRfc3339(body.refresh_expires_at);
|
|
82
|
+
if (refreshExp === null) agentFail("session_refresh_exp");
|
|
83
|
+
if (refreshExp <= now) agentFail("session_refresh_expired");
|
|
84
|
+
}
|
|
85
|
+
return body;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export const MAX_TOKEN_RESPONSE_BYTES = 64 * 1024;
|
|
89
|
+
|
|
90
|
+
export async function readBoundedText(res, controller) {
|
|
91
|
+
const declared = Number(res.headers?.get?.("content-length"));
|
|
92
|
+
if (Number.isFinite(declared) && declared > MAX_TOKEN_RESPONSE_BYTES) {
|
|
93
|
+
agentFail("token_size_limit");
|
|
94
|
+
}
|
|
95
|
+
const reader = res.body?.getReader?.();
|
|
96
|
+
if (!reader) {
|
|
97
|
+
const t = await res.text();
|
|
98
|
+
if (t.length > MAX_TOKEN_RESPONSE_BYTES) agentFail("token_size_limit");
|
|
99
|
+
return t;
|
|
100
|
+
}
|
|
101
|
+
if (controller?.signal) {
|
|
102
|
+
const abort = () => { void reader.cancel().catch(() => {}); };
|
|
103
|
+
if (controller.signal.aborted) abort();
|
|
104
|
+
else controller.signal.addEventListener("abort", abort, { once: true });
|
|
105
|
+
}
|
|
106
|
+
const chunks = [];
|
|
107
|
+
let total = 0;
|
|
108
|
+
for (;;) {
|
|
109
|
+
if (controller?.signal?.aborted) agentFail("token_deadline");
|
|
110
|
+
let step;
|
|
111
|
+
try {
|
|
112
|
+
step = await reader.read();
|
|
113
|
+
} catch (e) {
|
|
114
|
+
if (controller?.signal?.aborted || e?.name === "AbortError") {
|
|
115
|
+
agentFail("token_deadline");
|
|
116
|
+
}
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
const { done, value } = step;
|
|
120
|
+
if (done) break;
|
|
121
|
+
if (value) {
|
|
122
|
+
total += value.byteLength;
|
|
123
|
+
if (total > MAX_TOKEN_RESPONSE_BYTES) {
|
|
124
|
+
// Cancel the reader only — aborting the controller here races an unhandled AbortError.
|
|
125
|
+
try { await reader.cancel(); } catch { /* ignore */ }
|
|
126
|
+
agentFail("token_size_limit");
|
|
127
|
+
}
|
|
128
|
+
chunks.push(value);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const out = new Uint8Array(total);
|
|
132
|
+
let off = 0;
|
|
133
|
+
for (const c of chunks) { out.set(c, off); off += c.byteLength; }
|
|
134
|
+
return new TextDecoder().decode(out);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function defaultInvoke(raftBin, args) {
|
|
138
|
+
const res = spawnSync(raftBin, args, { encoding: "utf8" });
|
|
139
|
+
return { status: res.error ? null : res.status, stdout: res.stdout ?? "", stderr: res.stderr ?? "" };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function runAgentLogin(a, apiBase, opts = {}) {
|
|
143
|
+
const service = opts.service ?? STAMP_SERVICE;
|
|
144
|
+
const now = opts.now ?? Date.now();
|
|
145
|
+
const { verifier, challenge } = generatePkce();
|
|
146
|
+
const args = [
|
|
147
|
+
"integration", "invoke",
|
|
148
|
+
"--service", service,
|
|
149
|
+
"--action", "agent-login",
|
|
150
|
+
"--json",
|
|
151
|
+
"--data-json", JSON.stringify({
|
|
152
|
+
schema: "raft-cli-agent-login-request.v1",
|
|
153
|
+
code_challenge: challenge,
|
|
154
|
+
code_challenge_method: "S256",
|
|
155
|
+
}),
|
|
156
|
+
];
|
|
157
|
+
const runner = opts.invoke ?? ((a2) => defaultInvoke(a.raftBin, a2));
|
|
158
|
+
const res = runner(args);
|
|
159
|
+
if (res.status !== 0) {
|
|
160
|
+
agentFail("invoke_exit", { status: res.status ?? "spawn error" });
|
|
161
|
+
}
|
|
162
|
+
const { grant } = parseAgentLoginInvoke(res.stdout, service, now);
|
|
163
|
+
|
|
164
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
165
|
+
const deadlineMs = opts.deadlineMs ?? TOKEN_DEADLINE_MS;
|
|
166
|
+
const controller = new AbortController();
|
|
167
|
+
const timer = setTimeout(() => controller.abort(), deadlineMs);
|
|
168
|
+
try {
|
|
169
|
+
const exchangeRes = await fetchImpl(new URL("/api/auth/agent/exchange", apiBase).toString(), {
|
|
170
|
+
method: "POST",
|
|
171
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
172
|
+
body: JSON.stringify({ schema: "raft-cli-agent-login-exchange.v1", grant, code_verifier: verifier }),
|
|
173
|
+
redirect: "manual",
|
|
174
|
+
signal: controller.signal,
|
|
175
|
+
});
|
|
176
|
+
const status = exchangeRes.status;
|
|
177
|
+
if (status >= 300 && status < 400) {
|
|
178
|
+
agentFail("exchange_redirect", { status });
|
|
179
|
+
}
|
|
180
|
+
if (!exchangeRes.ok) {
|
|
181
|
+
agentFail("exchange_failed", { status });
|
|
182
|
+
}
|
|
183
|
+
const exchangeText = await readBoundedText(exchangeRes, controller);
|
|
184
|
+
let exchangeBody;
|
|
185
|
+
try { exchangeBody = JSON.parse(exchangeText); } catch { agentFail("exchange_not_json"); }
|
|
186
|
+
const session = parseAgentSession(exchangeBody, now);
|
|
187
|
+
writeAgentSession(a, service, session, apiBase);
|
|
188
|
+
return session;
|
|
189
|
+
} catch (e) {
|
|
190
|
+
if (e instanceof AgentError) throw e;
|
|
191
|
+
if (e?.name === "AbortError") agentFail("exchange_deadline");
|
|
192
|
+
throw e;
|
|
193
|
+
} finally {
|
|
194
|
+
clearTimeout(timer);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent token auto-refresh + cross-process single-flight (RFC 057; ported from Hands/testbed).
|
|
3
|
+
*/
|
|
4
|
+
import { openSync, closeSync, writeSync, readFileSync, existsSync, unlinkSync } from "node:fs";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
import { agentAuthPath, writeAgentSession } from "@botiverse/agent-session-store";
|
|
8
|
+
import { parseAgentSession, readBoundedText, STAMP_SERVICE } from "./agent-login.mjs";
|
|
9
|
+
import { AgentError, agentFail } from "./errors.mjs";
|
|
10
|
+
|
|
11
|
+
export const REFRESH_SKEW_MS = 60_000;
|
|
12
|
+
const REFRESH_DEADLINE_MS = 20_000;
|
|
13
|
+
const LOCK_WAIT_MS = 25_000;
|
|
14
|
+
const LOCK_POLL_MS = 100;
|
|
15
|
+
|
|
16
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
17
|
+
const newOwnerId = () => `${process.pid}:${randomBytes(12).toString("hex")}`;
|
|
18
|
+
|
|
19
|
+
export function readStore(a, service = STAMP_SERVICE) {
|
|
20
|
+
let path;
|
|
21
|
+
try { path = agentAuthPath(a, service); } catch { return null; }
|
|
22
|
+
if (!existsSync(path)) return null;
|
|
23
|
+
try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function accessExpiresWithinSkew(store, now) {
|
|
27
|
+
const exp = Date.parse(store.access_expires_at);
|
|
28
|
+
return !Number.isFinite(exp) || exp - now <= REFRESH_SKEW_MS;
|
|
29
|
+
}
|
|
30
|
+
function accessExpired(store, now) {
|
|
31
|
+
const exp = Date.parse(store.access_expires_at);
|
|
32
|
+
return !Number.isFinite(exp) || exp <= now;
|
|
33
|
+
}
|
|
34
|
+
export function refreshLockPath(a, service = STAMP_SERVICE) {
|
|
35
|
+
return join(dirname(agentAuthPath(a, service)), ".auth.refresh.lock");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function rotate(a, service, store, now, fetchImpl, deadlineMs) {
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
const timer = setTimeout(() => controller.abort(), deadlineMs);
|
|
41
|
+
try {
|
|
42
|
+
const res = await fetchImpl(new URL("/api/auth/agent/refresh", store.api_base).toString(), {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
45
|
+
body: JSON.stringify({ schema: "raft-cli-agent-refresh.v1", refresh_token: store.refresh_token }),
|
|
46
|
+
signal: controller.signal,
|
|
47
|
+
redirect: "manual",
|
|
48
|
+
});
|
|
49
|
+
const status = res.status;
|
|
50
|
+
if (status >= 300 && status < 400) {
|
|
51
|
+
agentFail("refresh_redirect", { status });
|
|
52
|
+
}
|
|
53
|
+
if (!res.ok) agentFail("refresh_failed", { status });
|
|
54
|
+
const text = await readBoundedText(res, controller);
|
|
55
|
+
let body;
|
|
56
|
+
try { body = JSON.parse(text); } catch { agentFail("refresh_not_json"); }
|
|
57
|
+
const session = parseAgentSession(body, now);
|
|
58
|
+
writeAgentSession(a, service, session, store.api_base, () => new Date(now).toISOString());
|
|
59
|
+
return session;
|
|
60
|
+
} catch (e) {
|
|
61
|
+
if (e instanceof AgentError) throw e;
|
|
62
|
+
if (e?.name === "AbortError") agentFail("refresh_deadline");
|
|
63
|
+
throw e;
|
|
64
|
+
} finally {
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function successorIfRejected(store, rejectedAccess) {
|
|
70
|
+
return rejectedAccess && store?.access_token && store.access_token !== rejectedAccess
|
|
71
|
+
? store.access_token
|
|
72
|
+
: null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function getFreshAgentAccessToken(a, opts = {}) {
|
|
76
|
+
const service = opts.service ?? STAMP_SERVICE;
|
|
77
|
+
const now = opts.now ?? Date.now();
|
|
78
|
+
const store = readStore(a, service);
|
|
79
|
+
if (!store) return null;
|
|
80
|
+
if (!accessExpiresWithinSkew(store, now)) return store.access_token;
|
|
81
|
+
return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, false, opts.deadlineMs ?? REFRESH_DEADLINE_MS);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function forceRefreshAgentToken(a, opts = {}) {
|
|
85
|
+
const service = opts.service ?? STAMP_SERVICE;
|
|
86
|
+
const now = opts.now ?? Date.now();
|
|
87
|
+
const store = readStore(a, service);
|
|
88
|
+
if (!store) return null;
|
|
89
|
+
const reused = successorIfRejected(store, opts.rejectedAccess);
|
|
90
|
+
if (reused) return reused;
|
|
91
|
+
return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, true, opts.deadlineMs ?? REFRESH_DEADLINE_MS, opts.rejectedAccess);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function singleFlightRefresh(a, service, baseline, now, fetchImpl, sleepImpl, force, deadlineMs, rejectedAccess) {
|
|
95
|
+
const lock = refreshLockPath(a, service);
|
|
96
|
+
const ownerId = newOwnerId();
|
|
97
|
+
let acquired;
|
|
98
|
+
try {
|
|
99
|
+
const fd = openSync(lock, "wx");
|
|
100
|
+
try { writeSync(fd, ownerId); } finally { try { closeSync(fd); } catch { /* ignore */ } }
|
|
101
|
+
acquired = true;
|
|
102
|
+
} catch (e) {
|
|
103
|
+
if (e?.code !== "EEXIST") throw e;
|
|
104
|
+
acquired = acquireIfDeadOwner(lock, ownerId);
|
|
105
|
+
if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess);
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const fresh = readStore(a, service);
|
|
109
|
+
if (!fresh) return null;
|
|
110
|
+
const reused = successorIfRejected(fresh, rejectedAccess);
|
|
111
|
+
if (reused) return reused;
|
|
112
|
+
if (!force && !accessExpiresWithinSkew(fresh, now)) return fresh.access_token;
|
|
113
|
+
const session = await rotate(a, service, fresh, now, fetchImpl, deadlineMs);
|
|
114
|
+
return session.access_token;
|
|
115
|
+
} finally {
|
|
116
|
+
releaseOwnLock(lock, ownerId);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function releaseOwnLock(lock, ownerId) {
|
|
121
|
+
try { if (readFileSync(lock, "utf8") === ownerId) unlinkSync(lock); } catch { /* gone or foreign */ }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function acquireIfDeadOwner(lock, ownerId) {
|
|
125
|
+
const ffd = acquireReaperFence(`${lock}.reap`);
|
|
126
|
+
if (ffd === null) return false;
|
|
127
|
+
try {
|
|
128
|
+
let owner = "";
|
|
129
|
+
try { owner = readFileSync(lock, "utf8"); } catch (e) { if (e?.code !== "ENOENT") return false; }
|
|
130
|
+
if (owner) {
|
|
131
|
+
const pid = ownerPid(owner);
|
|
132
|
+
if (pid === null || ownerAlive(pid)) return false;
|
|
133
|
+
try { unlinkSync(lock); } catch { /* vanished */ }
|
|
134
|
+
}
|
|
135
|
+
let fd;
|
|
136
|
+
try { fd = openSync(lock, "wx"); } catch (e) { if (e?.code === "EEXIST") return false; throw e; }
|
|
137
|
+
try { writeSync(fd, ownerId); } finally { try { closeSync(fd); } catch { /* ignore */ } }
|
|
138
|
+
return true;
|
|
139
|
+
} finally {
|
|
140
|
+
try { closeSync(ffd); } catch { /* ignore */ }
|
|
141
|
+
try { unlinkSync(`${lock}.reap`); } catch { /* ignore */ }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function acquireReaperFence(fence) {
|
|
146
|
+
try {
|
|
147
|
+
const fd = openSync(fence, "wx");
|
|
148
|
+
try { writeSync(fd, newOwnerId()); } catch { /* marker only */ }
|
|
149
|
+
return fd;
|
|
150
|
+
} catch {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function ownerPid(owner) {
|
|
155
|
+
const m = /^(\d+):/.exec(owner);
|
|
156
|
+
if (!m) return null;
|
|
157
|
+
const pid = Number(m[1]);
|
|
158
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
159
|
+
}
|
|
160
|
+
function ownerAlive(pid) {
|
|
161
|
+
try { process.kill(pid, 0); return true; } catch (e) { return e?.code !== "ESRCH"; }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess) {
|
|
165
|
+
const maxPolls = Math.ceil(LOCK_WAIT_MS / LOCK_POLL_MS);
|
|
166
|
+
for (let i = 0; i < maxPolls; i += 1) {
|
|
167
|
+
await sleepImpl(LOCK_POLL_MS);
|
|
168
|
+
const cur = readStore(a, service);
|
|
169
|
+
const reused = successorIfRejected(cur, rejectedAccess);
|
|
170
|
+
if (reused) return reused;
|
|
171
|
+
if (cur && cur.refresh_token !== baseline.refresh_token) return cur.access_token;
|
|
172
|
+
}
|
|
173
|
+
const cur = readStore(a, service);
|
|
174
|
+
const reused = successorIfRejected(cur, rejectedAccess);
|
|
175
|
+
if (reused) return reused;
|
|
176
|
+
if (!force && cur && !accessExpired(cur, now)) return cur.access_token;
|
|
177
|
+
agentFail("refresh_wait_timeout");
|
|
178
|
+
}
|
package/lib/auth.mjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { unlinkSync, existsSync } from "node:fs";
|
|
2
|
+
import { admitAgent, agentAuthPath } from "@botiverse/agent-session-store";
|
|
3
|
+
import { STAMP_SERVICE } from "./agent-login.mjs";
|
|
4
|
+
import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
|
|
5
|
+
import { AgentError, agentFail } from "./errors.mjs";
|
|
6
|
+
|
|
7
|
+
export function resolveAuth({ urlBase, urlExplicit, env = process.env, service = env.STAMP_SERVICE || STAMP_SERVICE, locale = "en" }) {
|
|
8
|
+
const admission = admitAgent(env);
|
|
9
|
+
if (admission.kind === "fail_closed") {
|
|
10
|
+
agentFail("admission_partial", { reason: admission.reason });
|
|
11
|
+
}
|
|
12
|
+
if (admission.kind === "agent") {
|
|
13
|
+
const a = admission.env;
|
|
14
|
+
const store = readStore(a, service);
|
|
15
|
+
const apiBase = urlExplicit ? urlBase : (store?.api_base ?? urlBase);
|
|
16
|
+
return {
|
|
17
|
+
mode: "agent",
|
|
18
|
+
apiBase,
|
|
19
|
+
agentEnv: a,
|
|
20
|
+
service,
|
|
21
|
+
async token() {
|
|
22
|
+
const tok = await getFreshAgentAccessToken(a, { service });
|
|
23
|
+
if (!tok) throw new AgentError("notLoggedIn");
|
|
24
|
+
return tok;
|
|
25
|
+
},
|
|
26
|
+
async retryToken(rejectedAccess) { return forceRefreshAgentToken(a, { service, rejectedAccess }); },
|
|
27
|
+
logout() {
|
|
28
|
+
const p = agentAuthPath(a, service);
|
|
29
|
+
if (existsSync(p)) unlinkSync(p);
|
|
30
|
+
return p;
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const token = env.STAMP_TOKEN || "";
|
|
35
|
+
return {
|
|
36
|
+
mode: "human",
|
|
37
|
+
apiBase: urlBase,
|
|
38
|
+
async token() {
|
|
39
|
+
if (!token) throw new AgentError("stampTokenMissing");
|
|
40
|
+
return token;
|
|
41
|
+
},
|
|
42
|
+
async retryToken() { return null; },
|
|
43
|
+
logout() { return null; },
|
|
44
|
+
};
|
|
45
|
+
}
|
package/lib/client.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export class ApiError extends Error {
|
|
2
|
+
constructor(status, body, text) {
|
|
3
|
+
super(`${status}: ${body?.error ?? (text ?? "").slice(0, 200)}`);
|
|
4
|
+
this.status = status;
|
|
5
|
+
this.body = body;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function makeClient(auth, fetchImpl = fetch) {
|
|
10
|
+
async function once(method, path, body, token) {
|
|
11
|
+
const res = await fetchImpl(`${auth.apiBase}${path}`, {
|
|
12
|
+
method,
|
|
13
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
|
|
14
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
15
|
+
});
|
|
16
|
+
const text = await res.text();
|
|
17
|
+
let json = null;
|
|
18
|
+
try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON error page */ }
|
|
19
|
+
return { res, json, text };
|
|
20
|
+
}
|
|
21
|
+
return async function api(method, path, body) {
|
|
22
|
+
const used = await auth.token();
|
|
23
|
+
let { res, json, text } = await once(method, path, body, used);
|
|
24
|
+
if (res.status === 401 && auth.mode === "agent") {
|
|
25
|
+
const next = await auth.retryToken(used);
|
|
26
|
+
if (next) ({ res, json, text } = await once(method, path, body, next));
|
|
27
|
+
}
|
|
28
|
+
if (!res.ok) throw new ApiError(res.status, json, text);
|
|
29
|
+
return json;
|
|
30
|
+
};
|
|
31
|
+
}
|
package/lib/errors.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { t } from "./locale.mjs";
|
|
2
|
+
|
|
3
|
+
/** Stable machine code on `.code`; English catalog text on `.message` for tests. */
|
|
4
|
+
export class AgentError extends Error {
|
|
5
|
+
constructor(code, details = {}) {
|
|
6
|
+
super(t("en", code, details));
|
|
7
|
+
this.name = "AgentError";
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.details = details;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function agentFail(code, details = {}) {
|
|
14
|
+
throw new AgentError(code, details);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function presentError(locale, e) {
|
|
18
|
+
if (e instanceof AgentError) return t(locale, e.code, e.details);
|
|
19
|
+
return e.message;
|
|
20
|
+
}
|
package/lib/locale.mjs
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/** User-visible copy. Machine protocol fields and stable error codes stay English. */
|
|
2
|
+
export const messages = {
|
|
3
|
+
en: {
|
|
4
|
+
usagePrCreate: "usage: stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
|
|
5
|
+
prRequired: "Missing {flag}; use stamp receipt get <id> to obtain the published coordinates.",
|
|
6
|
+
prRepository: "--repo must be OWNER/REPO.",
|
|
7
|
+
prSHA: "--sha must be the exact 40-character lowercase published commit SHA.",
|
|
8
|
+
prBodyRequired: "Provide a non-empty PR description with --body or --body-file (use - for stdin).",
|
|
9
|
+
prCheckArguments: "Check the PR arguments with stamp pr create --help; correct invalid or empty values before retrying.",
|
|
10
|
+
prCheckConfiguration: "Ask the service administrator to repair the GitHub App configuration before retrying.",
|
|
11
|
+
prBodyConflict: "Use either --body or --body-file, not both.",
|
|
12
|
+
prBodyRead: "Cannot read --body-file; check the file path or pass - for stdin.",
|
|
13
|
+
prIdempotency: "--idempotency-key must contain 16–128 letters, digits, dots, underscores, colons, or hyphens.",
|
|
14
|
+
prCreated: "Created PR #{number}: {url}",
|
|
15
|
+
prExisting: "Existing PR #{number}: {url}",
|
|
16
|
+
prWaitPublished: "Check stamp receipt get <id>; use your own receipt after its status becomes PUBLISHED.",
|
|
17
|
+
prCheckReceipt: "Read the receipt again and check --repo, --head and --sha against the exact published commit.",
|
|
18
|
+
prCheckAccess: "Check repository access and the authorized base branch with the repository administrator.",
|
|
19
|
+
prCheckExisting: "Check the existing PR and keep the same receipt, title, body and idempotency key when retrying.",
|
|
20
|
+
prRetry: "Check the receipt and service status, then retry the identical command; its idempotency key stays unchanged.",
|
|
21
|
+
|
|
22
|
+
usage: `stamp {version} — Agent Git gateway CLI (future origin stamp.build)
|
|
23
|
+
|
|
24
|
+
stamp login agent: PKCE login via raft (no browser); human: how to set STAMP_TOKEN
|
|
25
|
+
stamp logout agent: forget the stored session
|
|
26
|
+
stamp whoami who the gateway thinks you are
|
|
27
|
+
stamp migration-help old manifest actions → CLI mapping
|
|
28
|
+
stamp key enroll [--public-key FILE|-] bind this agent's SSH public key (default ~/.ssh/id_ed25519.pub)
|
|
29
|
+
stamp identity bind --email ADDR bind commit-author email (DCO)
|
|
30
|
+
stamp receipt get <id> gateway acceptance + GitHub publication status
|
|
31
|
+
stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
|
|
32
|
+
|
|
33
|
+
stamp follow <owner/repo> --kind issue|pull --number N
|
|
34
|
+
stamp unfollow <owner/repo> --kind issue|pull --number N
|
|
35
|
+
stamp subscription pause|resume <owner/repo> --kind issue|pull --number N
|
|
36
|
+
stamp subscriptions
|
|
37
|
+
stamp watch <owner/repo> --event TYPE
|
|
38
|
+
stamp unwatch <owner/repo> --event TYPE
|
|
39
|
+
|
|
40
|
+
git push git@github.botiverse.dev:org/repo.git HEAD:refs/heads/agent/…
|
|
41
|
+
|
|
42
|
+
flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG`,
|
|
43
|
+
loginHumanIntro: "Not a managed Raft agent. Humans and CI use STAMP_TOKEN:",
|
|
44
|
+
loginHumanBrowser: " browser: {url}/login (reuse the session cookie value as STAMP_TOKEN)",
|
|
45
|
+
loginHumanCI: " CI: a narrowly scoped deploy token",
|
|
46
|
+
loginAgentReady: "Agent login ready ({service} @ {url}); access token valid until {expires}",
|
|
47
|
+
logoutForgot: "forgot agent session {path}",
|
|
48
|
+
logoutNothing: "nothing stored (human/CI lane uses STAMP_TOKEN)",
|
|
49
|
+
enrolled: "enrolled {fingerprint} ({keyId})",
|
|
50
|
+
bound: "bound {email}",
|
|
51
|
+
usageKeyEnroll: "usage: stamp key enroll [--public-key FILE|-]",
|
|
52
|
+
usageIdentityBind: "usage: stamp identity bind --email ADDR",
|
|
53
|
+
usageReceiptGet: "usage: stamp receipt get <receipt-id>",
|
|
54
|
+
usageFollow: "usage: stamp <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
|
|
55
|
+
usageSubscription: "usage: stamp subscription pause|resume <owner/repo> --kind issue|pull --number N",
|
|
56
|
+
usageWatch: "usage: stamp {cmd} <owner/repo> --event TYPE",
|
|
57
|
+
helpInstall: "install: {cmds}",
|
|
58
|
+
helpAgentLogin: "agent login: {text}",
|
|
59
|
+
sessionRejected: "stamp: session rejected — run `stamp login`",
|
|
60
|
+
checkToken: "stamp: check STAMP_TOKEN",
|
|
61
|
+
notLoggedIn: "not logged in: run `stamp login` (managed agent)",
|
|
62
|
+
stampTokenMissing: "STAMP_TOKEN is not set (session or deploy token); inside a managed agent run `stamp login`",
|
|
63
|
+
admission_partial: "refusing to run: partial managed-agent environment ({reason}); not falling back to STAMP_TOKEN",
|
|
64
|
+
invoke_not_json: "agent-login: `raft integration invoke` did not return JSON",
|
|
65
|
+
invoke_not_object: "agent-login: invoke output is not an object",
|
|
66
|
+
invoke_failed: "agent-login: invoke did not succeed",
|
|
67
|
+
invoke_envelope: "agent-login: invoke envelope has unexpected fields",
|
|
68
|
+
invoke_data: "agent-login: invoke result is missing data",
|
|
69
|
+
invoke_data_fields: "agent-login: invoke data has unexpected fields",
|
|
70
|
+
invoke_service: "agent-login: invoke service does not match the requested service",
|
|
71
|
+
invoke_action: "agent-login: invoke action is not agent-login",
|
|
72
|
+
invoke_http: "agent-login: agent-login action did not return HTTP 200",
|
|
73
|
+
grant_body: "agent-login: invoke result is missing the grant body",
|
|
74
|
+
grant_fields: "agent-login: grant result has unexpected fields",
|
|
75
|
+
grant_schema: "agent-login: unexpected grant result schema",
|
|
76
|
+
grant_service: "agent-login: grant result service mismatch",
|
|
77
|
+
grant_missing: "agent-login: grant is missing",
|
|
78
|
+
grant_expires_at: "agent-login: grant expires_at is not an RFC3339 timestamp",
|
|
79
|
+
grant_expired: "agent-login: grant is already expired",
|
|
80
|
+
grant_ttl: "agent-login: grant expiry exceeds the ceiling",
|
|
81
|
+
session_not_object: "agent-login: exchange response is not an object",
|
|
82
|
+
session_fields: "agent-login: session has unexpected fields",
|
|
83
|
+
session_schema: "agent-login: unexpected session schema",
|
|
84
|
+
session_token_type: "agent-login: unexpected token_type",
|
|
85
|
+
session_missing: "agent-login: session missing {field}",
|
|
86
|
+
session_access_exp: "agent-login: session access_expires_at is not RFC3339",
|
|
87
|
+
session_access_expired: "agent-login: session access token is already expired",
|
|
88
|
+
session_refresh_exp: "agent-login: session refresh_expires_at must be RFC3339 or null",
|
|
89
|
+
session_refresh_expired: "agent-login: session refresh token is already expired",
|
|
90
|
+
token_size_limit: "agent-login: token response exceeds the size limit",
|
|
91
|
+
token_deadline: "agent-login: token endpoint exceeded the deadline",
|
|
92
|
+
invoke_exit: "agent-login: raft invoke exited with a non-zero status ({status})",
|
|
93
|
+
exchange_redirect: "agent-login: grant exchange rejected redirect (HTTP {status})",
|
|
94
|
+
exchange_failed: "agent-login: grant exchange failed (HTTP {status})",
|
|
95
|
+
exchange_not_json: "agent-login: exchange response was not JSON",
|
|
96
|
+
exchange_deadline: "agent-login: grant exchange exceeded the deadline",
|
|
97
|
+
refresh_redirect: "agent-login: token refresh rejected redirect (HTTP {status})",
|
|
98
|
+
refresh_failed: "agent-login: token refresh failed (HTTP {status})",
|
|
99
|
+
refresh_not_json: "agent-login: refresh response was not JSON",
|
|
100
|
+
refresh_deadline: "agent-login: token refresh exceeded the deadline",
|
|
101
|
+
refresh_wait_timeout: "agent-login: timed out waiting for a concurrent token refresh",
|
|
102
|
+
},
|
|
103
|
+
"zh-CN": {
|
|
104
|
+
usagePrCreate: "用法:stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
|
|
105
|
+
prRequired: "缺少 {flag};用 stamp receipt get <id> 获取已发表提交的信息。",
|
|
106
|
+
prRepository: "--repo 必须为 OWNER/REPO。",
|
|
107
|
+
prSHA: "--sha 必须是已发表提交的精确 40 位小写 SHA。",
|
|
108
|
+
prBodyRequired: "请用 --body 或 --body-file 提供非空 PR 正文(用 - 从标准输入读取)。",
|
|
109
|
+
prCheckArguments: "请用 stamp pr create --help 检查参数,修正无效或空值后再重试。",
|
|
110
|
+
prCheckConfiguration: "请先联系服务管理员修复 GitHub App 配置,再重试。",
|
|
111
|
+
prBodyConflict: "--body 与 --body-file 只能选一个。",
|
|
112
|
+
prBodyRead: "无法读取 --body-file;请检查路径,或用 - 从标准输入读取。",
|
|
113
|
+
prIdempotency: "--idempotency-key 必须为 16–128 位字母、数字、点、下划线、冒号或连字符。",
|
|
114
|
+
prCreated: "已创建 PR #{number}:{url}",
|
|
115
|
+
prExisting: "已有 PR #{number}:{url}",
|
|
116
|
+
prWaitPublished: "请用 stamp receipt get <id> 检查;只使用自己状态为 PUBLISHED 的 receipt。",
|
|
117
|
+
prCheckReceipt: "请重新读取 receipt,并核对 --repo、--head 和 --sha 是否与已发表提交一致。",
|
|
118
|
+
prCheckAccess: "请与仓库管理员核对仓库权限和允许的目标分支。",
|
|
119
|
+
prCheckExisting: "请检查已有 PR;重试时保持 receipt、标题、正文和幂等键不变。",
|
|
120
|
+
prRetry: "请检查 receipt 和服务状态,再原样重试命令;幂等键会保持不变。",
|
|
121
|
+
|
|
122
|
+
usage: `stamp {version} — Agent Git 网关 CLI(未来域名 stamp.build)
|
|
123
|
+
|
|
124
|
+
stamp login Agent:经 raft 做 PKCE 登录(无浏览器);人类:如何设置 STAMP_TOKEN
|
|
125
|
+
stamp logout Agent:忘掉已存会话
|
|
126
|
+
stamp whoami 网关认为你是谁
|
|
127
|
+
stamp migration-help 旧 manifest action → CLI 对照
|
|
128
|
+
stamp key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(默认 ~/.ssh/id_ed25519.pub)
|
|
129
|
+
stamp identity bind --email ADDR 绑定提交作者邮箱(DCO)
|
|
130
|
+
stamp receipt get <id> 网关接受与 GitHub 发表状态
|
|
131
|
+
stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
|
|
132
|
+
|
|
133
|
+
stamp follow <owner/repo> --kind issue|pull --number N
|
|
134
|
+
stamp unfollow <owner/repo> --kind issue|pull --number N
|
|
135
|
+
stamp subscription pause|resume <owner/repo> --kind issue|pull --number N
|
|
136
|
+
stamp subscriptions
|
|
137
|
+
stamp watch <owner/repo> --event TYPE
|
|
138
|
+
stamp unwatch <owner/repo> --event TYPE
|
|
139
|
+
|
|
140
|
+
git push git@github.botiverse.dev:org/repo.git HEAD:refs/heads/agent/…
|
|
141
|
+
|
|
142
|
+
flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG`,
|
|
143
|
+
loginHumanIntro: "当前不是受管 Raft Agent。人类和 CI 使用 STAMP_TOKEN:",
|
|
144
|
+
loginHumanBrowser: " 浏览器:{url}/login (把会话 cookie 值设为 STAMP_TOKEN)",
|
|
145
|
+
loginHumanCI: " CI: 由负责人签发的窄范围部署令牌",
|
|
146
|
+
loginAgentReady: "Agent 登录就绪({service} @ {url});访问令牌有效至 {expires}",
|
|
147
|
+
logoutForgot: "已忘记 Agent 会话 {path}",
|
|
148
|
+
logoutNothing: "没有本地会话(人类/CI 通道使用 STAMP_TOKEN)",
|
|
149
|
+
enrolled: "已登记 {fingerprint}({keyId})",
|
|
150
|
+
bound: "已绑定 {email}",
|
|
151
|
+
usageKeyEnroll: "用法:stamp key enroll [--public-key FILE|-]",
|
|
152
|
+
usageIdentityBind: "用法:stamp identity bind --email ADDR",
|
|
153
|
+
usageReceiptGet: "用法:stamp receipt get <receipt-id>",
|
|
154
|
+
usageFollow: "用法:stamp <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
|
|
155
|
+
usageSubscription: "用法:stamp subscription pause|resume <owner/repo> --kind issue|pull --number N",
|
|
156
|
+
usageWatch: "用法:stamp {cmd} <owner/repo> --event TYPE",
|
|
157
|
+
helpInstall: "安装:{cmds}",
|
|
158
|
+
helpAgentLogin: "Agent 登录:{text}",
|
|
159
|
+
sessionRejected: "stamp: 会话被拒绝 — 请运行 `stamp login`",
|
|
160
|
+
checkToken: "stamp: 请检查 STAMP_TOKEN",
|
|
161
|
+
notLoggedIn: "尚未登录:请运行 `stamp login`(受管 Agent)",
|
|
162
|
+
stampTokenMissing: "未设置 STAMP_TOKEN(会话或部署令牌);在受管 Agent 内请运行 `stamp login`",
|
|
163
|
+
admission_partial: "拒绝运行:受管 Agent 环境不完整({reason});不会回退到 STAMP_TOKEN",
|
|
164
|
+
invoke_not_json: "agent-login: `raft integration invoke` 没有返回 JSON",
|
|
165
|
+
invoke_not_object: "agent-login: invoke 输出不是对象",
|
|
166
|
+
invoke_failed: "agent-login: invoke 未成功",
|
|
167
|
+
invoke_envelope: "agent-login: invoke 信封含有意外字段",
|
|
168
|
+
invoke_data: "agent-login: invoke 结果缺少 data",
|
|
169
|
+
invoke_data_fields: "agent-login: invoke data 含有意外字段",
|
|
170
|
+
invoke_service: "agent-login: invoke 的 service 与请求的服务不匹配",
|
|
171
|
+
invoke_action: "agent-login: invoke action 不是 agent-login",
|
|
172
|
+
invoke_http: "agent-login: agent-login action 未返回 HTTP 200",
|
|
173
|
+
grant_body: "agent-login: invoke 结果缺少 grant 正文",
|
|
174
|
+
grant_fields: "agent-login: grant 结果含有意外字段",
|
|
175
|
+
grant_schema: "agent-login: grant 结果 schema 不符合预期",
|
|
176
|
+
grant_service: "agent-login: grant 结果 service 不匹配",
|
|
177
|
+
grant_missing: "agent-login: 缺少 grant",
|
|
178
|
+
grant_expires_at: "agent-login: grant expires_at 不是 RFC3339 时间戳",
|
|
179
|
+
grant_expired: "agent-login: grant 已经过期",
|
|
180
|
+
grant_ttl: "agent-login: grant 有效期超过上限",
|
|
181
|
+
session_not_object: "agent-login: 兑换响应不是对象",
|
|
182
|
+
session_fields: "agent-login: 会话含有意外字段",
|
|
183
|
+
session_schema: "agent-login: 会话 schema 不符合预期",
|
|
184
|
+
session_token_type: "agent-login: token_type 不符合预期",
|
|
185
|
+
session_missing: "agent-login: 会话缺少 {field}",
|
|
186
|
+
session_access_exp: "agent-login: 会话 access_expires_at 不是 RFC3339",
|
|
187
|
+
session_access_expired: "agent-login: 会话访问令牌已经过期",
|
|
188
|
+
session_refresh_exp: "agent-login: 会话 refresh_expires_at 必须是 RFC3339 或 null",
|
|
189
|
+
session_refresh_expired: "agent-login: 会话刷新令牌已经过期",
|
|
190
|
+
token_size_limit: "agent-login: 令牌响应超过大小限制",
|
|
191
|
+
token_deadline: "agent-login: 令牌端点超过时限",
|
|
192
|
+
invoke_exit: "agent-login: raft invoke 以非零状态退出({status})",
|
|
193
|
+
exchange_redirect: "agent-login: 授权兑换拒绝跟随重定向(HTTP {status})",
|
|
194
|
+
exchange_failed: "agent-login: 授权兑换失败(HTTP {status})",
|
|
195
|
+
exchange_not_json: "agent-login: 兑换响应不是 JSON",
|
|
196
|
+
exchange_deadline: "agent-login: 授权兑换超过时限",
|
|
197
|
+
refresh_redirect: "agent-login: 令牌刷新拒绝跟随重定向(HTTP {status})",
|
|
198
|
+
refresh_failed: "agent-login: 令牌刷新失败(HTTP {status})",
|
|
199
|
+
refresh_not_json: "agent-login: 刷新响应不是 JSON",
|
|
200
|
+
refresh_deadline: "agent-login: 令牌刷新超过时限",
|
|
201
|
+
refresh_wait_timeout: "agent-login: 等待并发令牌刷新超时",
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
export function selectLocale(env = process.env, explicit) {
|
|
206
|
+
const raw = String(explicit || env.STAMP_LANG || env.LC_ALL || env.LANG || "");
|
|
207
|
+
if (/^zh/i.test(raw.trim())) return "zh-CN";
|
|
208
|
+
return "en";
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function t(locale, key, vars = {}) {
|
|
212
|
+
const table = messages[locale] || messages.en;
|
|
213
|
+
let s = table[key] || messages.en[key] || key;
|
|
214
|
+
for (const [k, v] of Object.entries(vars)) s = s.replaceAll(`{${k}}`, String(v));
|
|
215
|
+
return s;
|
|
216
|
+
}
|
package/lib/main.mjs
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { resolveAuth } from "./auth.mjs";
|
|
6
|
+
import { makeClient, ApiError } from "./client.mjs";
|
|
7
|
+
import { runAgentLogin } from "./agent-login.mjs";
|
|
8
|
+
import { selectLocale, t } from "./locale.mjs";
|
|
9
|
+
import { pullRequestInput, pullRequestRecovery } from "./pull-request.mjs";
|
|
10
|
+
import { presentError } from "./errors.mjs";
|
|
11
|
+
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
const pkg = require("../package.json");
|
|
14
|
+
|
|
15
|
+
function takeFlag(args, name, dflt) {
|
|
16
|
+
const i = args.indexOf(`--${name}`);
|
|
17
|
+
if (i === -1) return dflt;
|
|
18
|
+
const v = args[i + 1];
|
|
19
|
+
args.splice(i, 2);
|
|
20
|
+
return v;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function readPublicKey(path) {
|
|
24
|
+
if (path === "-") return readFileSync(0, "utf8").trim();
|
|
25
|
+
return readFileSync(path, "utf8").trim();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function objectArgs(args, locale) {
|
|
29
|
+
const repository = args.shift();
|
|
30
|
+
const kind = takeFlag(args, "kind");
|
|
31
|
+
const number = Number(takeFlag(args, "number"));
|
|
32
|
+
if (!repository || !kind || !Number.isInteger(number) || number <= 0) {
|
|
33
|
+
throw new Error(t(locale, "usageFollow"));
|
|
34
|
+
}
|
|
35
|
+
return { repository, kind, number };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function main(argv, opts) {
|
|
39
|
+
const args = [...argv];
|
|
40
|
+
const out = opts.stdout ?? ((s) => console.log(s));
|
|
41
|
+
const err = opts.stderr ?? ((s) => console.error(s));
|
|
42
|
+
const env = opts.env ?? process.env;
|
|
43
|
+
const exit = opts.exit ?? ((code) => process.exit(code));
|
|
44
|
+
// Global flags are options, never values of --title/--body/etc.
|
|
45
|
+
const localValues = new Set(["--public-key", "--email", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key"]);
|
|
46
|
+
let json = false, langFlag, help = false, version = false;
|
|
47
|
+
const commandArgs = [];
|
|
48
|
+
for (let i = 0; i < args.length; i++) {
|
|
49
|
+
const arg = args[i];
|
|
50
|
+
if (arg === "--json") json = true;
|
|
51
|
+
else if (arg === "--lang") langFlag = args[++i];
|
|
52
|
+
else if (arg === "--help" || arg === "-h") help = true;
|
|
53
|
+
else if (arg === "--version" || arg === "-v") version = true;
|
|
54
|
+
else {
|
|
55
|
+
commandArgs.push(arg);
|
|
56
|
+
if (localValues.has(arg) && i + 1 < args.length) commandArgs.push(args[++i]);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
args.splice(0, args.length, ...commandArgs);
|
|
60
|
+
const locale = selectLocale(env, langFlag);
|
|
61
|
+
if (version) { out(pkg.version); return exit(0); }
|
|
62
|
+
const cmd = args.shift();
|
|
63
|
+
if (help || !cmd) { out(t(locale, "usage", { version: pkg.version })); return exit(0); }
|
|
64
|
+
const emit = (data, human) => { if (json) out(JSON.stringify(data, null, 2)); else human(); };
|
|
65
|
+
|
|
66
|
+
let auth;
|
|
67
|
+
try {
|
|
68
|
+
auth = resolveAuth({ urlBase: opts.urlBase, urlExplicit: opts.urlExplicit, env, locale });
|
|
69
|
+
} catch (e) {
|
|
70
|
+
err(`stamp: ${presentError(locale, e)}`);
|
|
71
|
+
return exit(1);
|
|
72
|
+
}
|
|
73
|
+
const api = makeClient(auth, opts.fetchImpl);
|
|
74
|
+
|
|
75
|
+
try {
|
|
76
|
+
switch (cmd) {
|
|
77
|
+
case "login": {
|
|
78
|
+
if (auth.mode !== "agent") {
|
|
79
|
+
out(t(locale, "loginHumanIntro"));
|
|
80
|
+
out(t(locale, "loginHumanBrowser", { url: auth.apiBase }));
|
|
81
|
+
out(t(locale, "loginHumanCI"));
|
|
82
|
+
return exit(0);
|
|
83
|
+
}
|
|
84
|
+
const login = opts.loginImpl ?? runAgentLogin;
|
|
85
|
+
const session = await login(auth.agentEnv, auth.apiBase, { service: auth.service, fetchImpl: opts.fetchImpl });
|
|
86
|
+
emit({ ok: true, service: auth.service, api_base: auth.apiBase, access_expires_at: session.access_expires_at },
|
|
87
|
+
() => out(t(locale, "loginAgentReady", { service: auth.service, url: auth.apiBase, expires: session.access_expires_at })));
|
|
88
|
+
return exit(0);
|
|
89
|
+
}
|
|
90
|
+
case "logout": {
|
|
91
|
+
const p = auth.logout();
|
|
92
|
+
out(p ? t(locale, "logoutForgot", { path: p }) : t(locale, "logoutNothing"));
|
|
93
|
+
return exit(0);
|
|
94
|
+
}
|
|
95
|
+
case "whoami": {
|
|
96
|
+
const me = await api("GET", "/v1/me");
|
|
97
|
+
emit(me, () => out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${auth.apiBase}`));
|
|
98
|
+
return exit(0);
|
|
99
|
+
}
|
|
100
|
+
case "migration-help": {
|
|
101
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
102
|
+
const res = await fetchImpl(`${auth.apiBase}/v1/migration-help`, {
|
|
103
|
+
headers: { "accept-language": locale === "zh-CN" ? "zh-CN" : "en" },
|
|
104
|
+
});
|
|
105
|
+
const d = await res.json();
|
|
106
|
+
emit(d, () => {
|
|
107
|
+
out(t(locale, "helpInstall", { cmds: (d.install ?? []).join(" ; ") }));
|
|
108
|
+
out(t(locale, "helpAgentLogin", { text: d.login?.agent ?? "" }));
|
|
109
|
+
for (const [from, to] of Object.entries(d.actions_to_cli ?? {})) {
|
|
110
|
+
const note = d.notes?.[from];
|
|
111
|
+
out(note ? ` ${from} → ${to} (${note})` : ` ${from} → ${to}`);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
return exit(0);
|
|
115
|
+
}
|
|
116
|
+
case "key": {
|
|
117
|
+
const sub = args.shift();
|
|
118
|
+
if (sub !== "enroll") throw new Error(t(locale, "usageKeyEnroll"));
|
|
119
|
+
const keyPath = takeFlag(args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
|
|
120
|
+
const publicKey = readPublicKey(keyPath);
|
|
121
|
+
const d = await api("POST", "/v1/keys", { publicKey });
|
|
122
|
+
emit(d, () => out(t(locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId })));
|
|
123
|
+
return exit(0);
|
|
124
|
+
}
|
|
125
|
+
case "identity": {
|
|
126
|
+
const sub = args.shift();
|
|
127
|
+
if (sub !== "bind") throw new Error(t(locale, "usageIdentityBind"));
|
|
128
|
+
const agentEmail = takeFlag(args, "email");
|
|
129
|
+
if (!agentEmail) throw new Error(t(locale, "usageIdentityBind"));
|
|
130
|
+
const d = await api("POST", "/v1/identities", { agentEmail });
|
|
131
|
+
emit(d, () => out(t(locale, "bound", { email: d.agentEmail })));
|
|
132
|
+
return exit(0);
|
|
133
|
+
}
|
|
134
|
+
case "receipt": {
|
|
135
|
+
const sub = args.shift();
|
|
136
|
+
const id = args.shift();
|
|
137
|
+
if (sub !== "get" || !id) throw new Error(t(locale, "usageReceiptGet"));
|
|
138
|
+
const d = await api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
|
|
139
|
+
emit(d, () => out(`${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`));
|
|
140
|
+
return exit(0);
|
|
141
|
+
}
|
|
142
|
+
case "pr": {
|
|
143
|
+
if (args.shift() !== "create") throw new Error(t(locale, "usagePrCreate"));
|
|
144
|
+
const input = pullRequestInput(args);
|
|
145
|
+
try {
|
|
146
|
+
const d = await api("POST", "/v1/pull-requests", input);
|
|
147
|
+
emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
|
|
148
|
+
} catch (e) {
|
|
149
|
+
if (e instanceof ApiError && e.status !== 401) {
|
|
150
|
+
err(`stamp: ${e.message}`);
|
|
151
|
+
err(t(locale, pullRequestRecovery(e.body?.error)));
|
|
152
|
+
return exit(1);
|
|
153
|
+
}
|
|
154
|
+
throw e;
|
|
155
|
+
}
|
|
156
|
+
return exit(0);
|
|
157
|
+
}
|
|
158
|
+
case "follow":
|
|
159
|
+
case "unfollow": {
|
|
160
|
+
const body = objectArgs(args, locale);
|
|
161
|
+
const path = cmd === "follow" ? "/v1/subscriptions/objects/follow" : "/v1/subscriptions/objects/unfollow";
|
|
162
|
+
const d = await api("POST", path, body);
|
|
163
|
+
emit(d, () => out(JSON.stringify(d)));
|
|
164
|
+
return exit(0);
|
|
165
|
+
}
|
|
166
|
+
case "subscription": {
|
|
167
|
+
const sub = args.shift();
|
|
168
|
+
if (sub !== "pause" && sub !== "resume") throw new Error(t(locale, "usageSubscription"));
|
|
169
|
+
const body = objectArgs(args, locale);
|
|
170
|
+
const d = await api("POST", `/v1/subscriptions/objects/${sub}`, body);
|
|
171
|
+
emit(d, () => out(JSON.stringify(d)));
|
|
172
|
+
return exit(0);
|
|
173
|
+
}
|
|
174
|
+
case "subscriptions": {
|
|
175
|
+
const d = await api("GET", "/v1/subscriptions");
|
|
176
|
+
emit(d, () => out(JSON.stringify(d, null, 2)));
|
|
177
|
+
return exit(0);
|
|
178
|
+
}
|
|
179
|
+
case "watch":
|
|
180
|
+
case "unwatch": {
|
|
181
|
+
const repository = args.shift();
|
|
182
|
+
const eventType = takeFlag(args, "event");
|
|
183
|
+
if (!repository || !eventType) throw new Error(t(locale, "usageWatch", { cmd }));
|
|
184
|
+
const path = cmd === "watch" ? "/v1/subscriptions/repositories/subscribe" : "/v1/subscriptions/repositories/unsubscribe";
|
|
185
|
+
const d = await api("POST", path, { repository, eventType });
|
|
186
|
+
emit(d, () => out(JSON.stringify(d)));
|
|
187
|
+
return exit(0);
|
|
188
|
+
}
|
|
189
|
+
default:
|
|
190
|
+
out(t(locale, "usage", { version: pkg.version }));
|
|
191
|
+
return exit(cmd ? 1 : 0);
|
|
192
|
+
}
|
|
193
|
+
} catch (e) {
|
|
194
|
+
if (e instanceof ApiError) {
|
|
195
|
+
err(`stamp: ${e.message}`);
|
|
196
|
+
if (e.status === 401) err(auth.mode === "agent" ? t(locale, "sessionRejected") : t(locale, "checkToken"));
|
|
197
|
+
return exit(1);
|
|
198
|
+
}
|
|
199
|
+
err(`stamp: ${presentError(locale, e)}`);
|
|
200
|
+
return exit(1);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { AgentError } from "./errors.mjs";
|
|
4
|
+
|
|
5
|
+
const names = new Set(["receipt", "repo", "head", "sha", "base", "title", "body", "body-file", "idempotency-key"]);
|
|
6
|
+
|
|
7
|
+
export function pullRequestInput(args) {
|
|
8
|
+
const flags = new Map();
|
|
9
|
+
for (let i = 0; i < args.length; i++) {
|
|
10
|
+
const [flag, ...inline] = args[i].split("=");
|
|
11
|
+
const name = flag.slice(2);
|
|
12
|
+
if (!flag.startsWith("--") || !names.has(name) || flags.has(name)) throw new AgentError("usagePrCreate");
|
|
13
|
+
const value = inline.length ? inline.join("=") : args[++i];
|
|
14
|
+
if (value === undefined || (!inline.length && value.startsWith("--"))) throw new AgentError("usagePrCreate");
|
|
15
|
+
flags.set(name, value);
|
|
16
|
+
}
|
|
17
|
+
for (const name of ["receipt", "repo", "head", "sha", "base", "title"]) {
|
|
18
|
+
if (!flags.get(name)?.trim()) throw new AgentError("prRequired", { flag: `--${name}` });
|
|
19
|
+
}
|
|
20
|
+
if (!/^[^/\s]+\/[^/\s]+$/.test(flags.get("repo"))) throw new AgentError("prRepository");
|
|
21
|
+
if (!/^[0-9a-f]{40}$/.test(flags.get("sha"))) throw new AgentError("prSHA");
|
|
22
|
+
const ref = (name) => {
|
|
23
|
+
const value = flags.get(name);
|
|
24
|
+
return value.startsWith("refs/") ? value : `refs/heads/${value}`;
|
|
25
|
+
};
|
|
26
|
+
if (flags.has("body") && flags.has("body-file")) throw new AgentError("prBodyConflict");
|
|
27
|
+
let body = flags.get("body") ?? "";
|
|
28
|
+
if (flags.has("body-file")) {
|
|
29
|
+
try { body = readFileSync(flags.get("body-file") === "-" ? 0 : flags.get("body-file"), "utf8"); }
|
|
30
|
+
catch { throw new AgentError("prBodyRead"); }
|
|
31
|
+
}
|
|
32
|
+
if (!body.trim()) throw new AgentError("prBodyRequired");
|
|
33
|
+
const input = {
|
|
34
|
+
receiptId: flags.get("receipt"), repository: flags.get("repo"),
|
|
35
|
+
targetRef: ref("head"), newSha: flags.get("sha"), baseRef: ref("base"),
|
|
36
|
+
title: flags.get("title"), body,
|
|
37
|
+
};
|
|
38
|
+
// Identical retries, including after a lost response or a new CLI process,
|
|
39
|
+
// retain the same key. No local credentials or state enter this digest.
|
|
40
|
+
// The server MUST scope idempotency by tenant, server and agent identity.
|
|
41
|
+
input.idempotencyKey = flags.get("idempotency-key") ?? `stamp-pr-${createHash("sha256").update(JSON.stringify(input)).digest("hex")}`;
|
|
42
|
+
if (!/^[A-Za-z0-9._:-]{16,128}$/.test(input.idempotencyKey)) throw new AgentError("prIdempotency");
|
|
43
|
+
return input;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function pullRequestRecovery(code) {
|
|
47
|
+
switch (code) {
|
|
48
|
+
case "INVALID_PULL_REQUEST_REQUEST": return "prCheckArguments";
|
|
49
|
+
case "GITHUB_APP_NOT_CONFIGURED":
|
|
50
|
+
case "GITHUB_CLIENT_INVALID": return "prCheckConfiguration";
|
|
51
|
+
case "PUBLISHED_RECEIPT_NOT_FOUND": return "prWaitPublished";
|
|
52
|
+
case "PUBLISHED_RECEIPT_BINDING_MISMATCH":
|
|
53
|
+
case "GITHUB_HEAD_DRIFT": return "prCheckReceipt";
|
|
54
|
+
case "REPOSITORY_NOT_AUTHORIZED":
|
|
55
|
+
case "BASE_REF_NOT_AUTHORIZED": return "prCheckAccess";
|
|
56
|
+
case "IDEMPOTENCY_CONFLICT":
|
|
57
|
+
case "PUSH_RECEIPT_ALREADY_BOUND":
|
|
58
|
+
case "GITHUB_PULL_REQUEST_CONFLICT": return "prCheckExisting";
|
|
59
|
+
default: return "prRetry";
|
|
60
|
+
}
|
|
61
|
+
}
|
package/package.json
CHANGED
|
@@ -1,23 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botiverse/stamp-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "CLI for Stamp
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "CLI for Stamp — Agent Git gateway in the Raft loop (bin stamp; future origin stamp.build)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"stamp": "bin/stamp.mjs"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
|
-
"bin"
|
|
11
|
+
"bin",
|
|
12
|
+
"lib"
|
|
12
13
|
],
|
|
13
14
|
"engines": {
|
|
14
|
-
"node": ">=
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test test/*.test.mjs"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@botiverse/agent-session-store": "^0.2.0"
|
|
15
22
|
},
|
|
16
23
|
"repository": {
|
|
17
24
|
"type": "git",
|
|
18
|
-
"url": "git+https://github.com/botiverse/
|
|
25
|
+
"url": "git+https://github.com/botiverse/raft-github-integration.git"
|
|
19
26
|
},
|
|
20
27
|
"publishConfig": {
|
|
21
28
|
"access": "public"
|
|
22
29
|
}
|
|
23
|
-
}
|
|
30
|
+
}
|