@botiverse/stamp-cli 0.3.9 → 0.3.11
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/lib/auth.mjs +14 -2
- package/lib/client.mjs +5 -1
- package/lib/commands/key.mjs +51 -5
- package/lib/commands/pr.mjs +6 -2
- package/lib/commands/repo.mjs +55 -3
- package/lib/commands/session.mjs +20 -1
- package/lib/errors.mjs +6 -2
- package/lib/locale.mjs +30 -4
- package/lib/main.mjs +11 -1
- package/lib/pr/create.mjs +18 -6
- package/lib/pr/read.mjs +16 -1
- package/lib/repo/clone.mjs +26 -0
- package/lib/repo/identities.mjs +3 -1
- package/lib/repo/ssh.mjs +8 -2
- package/lib/update-check.mjs +50 -0
- package/package.json +1 -1
package/lib/auth.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { unlinkSync, existsSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
3
|
import { admitAgent, agentAuthPath } from "@botiverse/agent-session-store";
|
|
4
4
|
import { STAMP_LEGACY_DEFAULT_URL, STAMP_LEGACY_STAGING_URL, STAMP_SERVICE } from "./agent-login.mjs";
|
|
5
5
|
import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
|
|
@@ -140,14 +140,26 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
|
|
|
140
140
|
// store as absent so the caller must log in afresh.
|
|
141
141
|
// No migration: a store issued for a DIFFERENT origin is not usable here.
|
|
142
142
|
// The refusal names the origin so the reader knows why and what to do.
|
|
143
|
-
|
|
143
|
+
let usableStore = storeMatchesOrigin(store, apiBase) ? store : undefined;
|
|
144
|
+
// A session written after this resolve (`login` itself) becomes usable
|
|
145
|
+
// for the rest of the same command: login then enrolls the agent's key.
|
|
146
|
+
const refreshStore = () => {
|
|
147
|
+
if (usableStore) return;
|
|
148
|
+
const fresh = readStore(a, service);
|
|
149
|
+
if (storeMatchesOrigin(fresh, apiBase)) usableStore = fresh;
|
|
150
|
+
};
|
|
144
151
|
const storedOriginElsewhere = !usableStore && storedOrigin !== null ? storedOrigin : null;
|
|
145
152
|
return {
|
|
146
153
|
mode: "agent",
|
|
147
154
|
apiBase,
|
|
148
155
|
agentEnv: a,
|
|
149
156
|
service,
|
|
157
|
+
// The agent's own directory for Stamp state, beside its session (artin
|
|
158
|
+
// 09-27): its SSH key, the enrollment record and the pinned host key.
|
|
159
|
+
// Never ~/.ssh or ~/.stamp, which every agent on a machine user shares.
|
|
160
|
+
stateDir: dirname(agentAuthPath(a, service)),
|
|
150
161
|
async token() {
|
|
162
|
+
refreshStore();
|
|
151
163
|
if (!usableStore) {
|
|
152
164
|
if (storedOriginElsewhere !== null) {
|
|
153
165
|
const sibling = siblingBinaryFor(storedOriginElsewhere);
|
package/lib/client.mjs
CHANGED
|
@@ -57,7 +57,10 @@ export function makeClient(auth, fetchImpl = fetch, options = {}) {
|
|
|
57
57
|
try {
|
|
58
58
|
res = await fetchImpl(`${auth.apiBase}${path}`, {
|
|
59
59
|
method,
|
|
60
|
-
headers: {
|
|
60
|
+
headers: {
|
|
61
|
+
authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json",
|
|
62
|
+
...(options.cliVersion ? { "stamp-cli-version": options.cliVersion } : {}),
|
|
63
|
+
},
|
|
61
64
|
body: body ? JSON.stringify(body) : undefined,
|
|
62
65
|
});
|
|
63
66
|
} catch (error) {
|
|
@@ -69,6 +72,7 @@ export function makeClient(auth, fetchImpl = fetch, options = {}) {
|
|
|
69
72
|
}
|
|
70
73
|
throw new NetworkError(networkErrorKey(failure), { base: auth.apiBase, cause: failure.code });
|
|
71
74
|
}
|
|
75
|
+
options.onVersions?.(res.headers?.get?.("stamp-cli-latest") ?? "", res.headers?.get?.("stamp-cli-minimum") ?? "");
|
|
72
76
|
const text = await res.text();
|
|
73
77
|
let json = null;
|
|
74
78
|
try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON error page */ }
|
package/lib/commands/key.mjs
CHANGED
|
@@ -1,10 +1,46 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
4
2
|
import { t } from "../locale.mjs";
|
|
5
3
|
import { resolve } from "node:path";
|
|
6
4
|
import { takeFlag, readPublicKey } from "../flags.mjs";
|
|
7
|
-
import { recordIdentity } from "../repo/identities.mjs";
|
|
5
|
+
import { readRecordedIdentity, recordIdentity } from "../repo/identities.mjs";
|
|
6
|
+
import { defaultIdentityPath } from "../repo/ssh.mjs";
|
|
7
|
+
import { mkdirSync } from "node:fs";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
import { spawnSync } from "node:child_process";
|
|
10
|
+
|
|
11
|
+
// generateAgentKey creates an ed25519 key with no passphrase at path (0600,
|
|
12
|
+
// in a 0700 directory), labelled with the agent it belongs to.
|
|
13
|
+
function generateAgentKey(path, agentId) {
|
|
14
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
15
|
+
const res = spawnSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", `stamp-agent-${agentId ?? "unknown"}`, "-f", path], { encoding: "utf8" });
|
|
16
|
+
if (res.error || res.status !== 0) {
|
|
17
|
+
throw new Error(`ssh-keygen failed: ${(res.stderr || res.error?.message || "").trim()}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// ensureAgentKey gives an agent its own SSH key without being asked, as its
|
|
22
|
+
// commit email is (artin 09-28: "enroll should only be a hint"): when the
|
|
23
|
+
// agent has no key recorded for this instance, it creates one in the agent's
|
|
24
|
+
// own directory (or reuses the one already there), enrolls it and records it.
|
|
25
|
+
// It returns what it did, or null when there was nothing to do (a person, or
|
|
26
|
+
// a key already recorded). `key enroll --public-key` stays for a key the
|
|
27
|
+
// agent chooses itself.
|
|
28
|
+
export async function ensureAgentKey(ctx) {
|
|
29
|
+
if (!ctx.env.STAMP_AGENT_STATE_DIR) return null;
|
|
30
|
+
if (readRecordedIdentity(ctx.env, ctx.auth.apiBase)) return null;
|
|
31
|
+
const privatePath = defaultIdentityPath(ctx.env);
|
|
32
|
+
const publicPath = `${privatePath}.pub`;
|
|
33
|
+
let created = false;
|
|
34
|
+
if (!existsSync(publicPath)) {
|
|
35
|
+
await (ctx.opts.sshKeygenImpl ?? generateAgentKey)(privatePath, ctx.auth?.agentEnv?.agentId);
|
|
36
|
+
created = true;
|
|
37
|
+
}
|
|
38
|
+
const d = await ctx.api("POST", "/v1/keys", { publicKey: readPublicKey(publicPath) });
|
|
39
|
+
recordIdentity(ctx.env, ctx.auth.apiBase, {
|
|
40
|
+
identityPath: privatePath, fingerprint: d.fingerprint ?? null, keyId: d.keyId ?? null, enrolledAt: new Date().toISOString(),
|
|
41
|
+
});
|
|
42
|
+
return { path: privatePath, fingerprint: d.fingerprint ?? "", created };
|
|
43
|
+
}
|
|
8
44
|
|
|
9
45
|
export async function run(ctx) {
|
|
10
46
|
const sub = ctx.args.shift();
|
|
@@ -26,7 +62,16 @@ export async function run(ctx) {
|
|
|
26
62
|
return ctx.exit(0);
|
|
27
63
|
}
|
|
28
64
|
if (sub !== "enroll") throw new Error(t(ctx.locale, "usageKeyEnroll"));
|
|
29
|
-
const
|
|
65
|
+
const agentDefault = `${defaultIdentityPath(ctx.env)}.pub`;
|
|
66
|
+
const keyPath = takeFlag(ctx.args, "public-key", agentDefault);
|
|
67
|
+
// An agent enrolling with no --public-key gets a key of its own, created in
|
|
68
|
+
// its own directory (artin 09-27: a shared ~/.ssh/id_ed25519 made another
|
|
69
|
+
// agent's key push for BoBo). Nothing to configure by hand.
|
|
70
|
+
let generated = false;
|
|
71
|
+
if (keyPath === agentDefault && ctx.env.STAMP_AGENT_STATE_DIR && !existsSync(keyPath)) {
|
|
72
|
+
await (ctx.opts.sshKeygenImpl ?? generateAgentKey)(keyPath.replace(/\.pub$/, ""), ctx.auth?.agentEnv?.agentId);
|
|
73
|
+
generated = true;
|
|
74
|
+
}
|
|
30
75
|
if (keyPath !== "-" && !existsSync(keyPath)) {
|
|
31
76
|
// The default path is the interesting case: `key enroll` on a machine with
|
|
32
77
|
// no key reads a path the operator never typed, so name it and name the two
|
|
@@ -48,7 +93,8 @@ export async function run(ctx) {
|
|
|
48
93
|
recordIdentity(ctx.env, ctx.auth.apiBase, identity);
|
|
49
94
|
}
|
|
50
95
|
}
|
|
51
|
-
ctx.emit({ ...d, identity }, () => {
|
|
96
|
+
ctx.emit({ ...d, identity, generated }, () => {
|
|
97
|
+
if (generated) ctx.out(t(ctx.locale, "keyGenerated", { path: keyPath.replace(/\.pub$/, "") }));
|
|
52
98
|
ctx.out(t(ctx.locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId }));
|
|
53
99
|
ctx.out(identity
|
|
54
100
|
? t(ctx.locale, "enrolledIdentityRecorded", { path: identity.identityPath })
|
package/lib/commands/pr.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { parsePRQueueArgs, validatePRQueueResult } from "../pr/queue.mjs";
|
|
|
4
4
|
import { t, prefix } from "../locale.mjs";
|
|
5
5
|
import { ApiError, NetworkError } from "../client.mjs";
|
|
6
6
|
import { AgentError, printGatewayError } from "../errors.mjs";
|
|
7
|
-
import { publishWaitMs, pullRequestDraft, pullRequestNextLines, pullRequestInput, pullRequestNeedsReceipt, pullRequestRecovery, waitForPublishedReceipt } from "../pr/create.mjs";
|
|
7
|
+
import { publishWaitMs, pullRequestDraft, pullRequestNextLines, stampPullRequestPage, pullRequestInput, pullRequestNeedsReceipt, pullRequestRecovery, waitForPublishedReceipt } from "../pr/create.mjs";
|
|
8
8
|
import { parsePRCommentArgs, validatePRCommentResult } from "../pr/comment.mjs";
|
|
9
9
|
import { parsePREditArgs, validatePREditResult } from "../pr/edit.mjs";
|
|
10
10
|
import { parsePRCloseArgs, validatePRCloseResult } from "../pr/close.mjs";
|
|
@@ -200,9 +200,13 @@ export async function run(ctx) {
|
|
|
200
200
|
if (sub === "view") {
|
|
201
201
|
const target = parsePRTargetArgs(args, "usagePrView");
|
|
202
202
|
const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
|
|
203
|
-
|
|
203
|
+
// The Stamp page is added to --json too (stampUrl), for agents that
|
|
204
|
+
// build their report from it.
|
|
205
|
+
const stampUrl = stampPullRequestPage(ctx.auth?.apiBase, d.repository, d.number);
|
|
206
|
+
emit(stampUrl ? { ...d, stampUrl } : d, () => {
|
|
204
207
|
for (const line of formatPRDetail(d, {
|
|
205
208
|
verdictLine: d.verdict ? formatVerdictLine(d.verdict, (key) => t(locale, key)) : "",
|
|
209
|
+
stampPage: stampUrl ? t(locale, "prViewStampPage", { page: stampUrl }) : "",
|
|
206
210
|
head: t(locale, "prHeadLabel"),
|
|
207
211
|
checks: t(locale, "prChecksLabel"),
|
|
208
212
|
ciUnreadable: t(locale, "prCIUnreadable"),
|
package/lib/commands/repo.mjs
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { t } from "../locale.mjs";
|
|
3
3
|
import { takeFlag } from "../flags.mjs";
|
|
4
|
-
import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone, runGitSetSSHCommand } from "../repo/clone.mjs";
|
|
4
|
+
import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone, runGitSetSSHCommand, setCommitIdentity } from "../repo/clone.mjs";
|
|
5
5
|
import { fetchPublishedKnownHosts, resolveIdentity, resolveKnownHostsPath, sshCommandFor, writePinnedKnownHosts } from "../repo/ssh.mjs";
|
|
6
6
|
import { readRecordedIdentity } from "../repo/identities.mjs";
|
|
7
|
+
import { ensureAgentKey } from "./key.mjs";
|
|
7
8
|
|
|
8
9
|
export async function run(ctx) {
|
|
9
|
-
|
|
10
|
+
const sub = ctx.args.shift();
|
|
11
|
+
if (sub === "use") return use(ctx);
|
|
12
|
+
if (sub !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
|
|
10
13
|
const identityFlag = takeFlag(ctx.args, "identity");
|
|
11
14
|
const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
|
|
12
15
|
const parsed = parseRepoCloneArgs(ctx.args);
|
|
@@ -19,6 +22,10 @@ export async function run(ctx) {
|
|
|
19
22
|
// The clone carries the enrolled identity and the gateway's published host
|
|
20
23
|
// key itself (task #475): a bare clone must not fail with publickey, and it
|
|
21
24
|
// must not need a hand-exported GIT_SSH_COMMAND.
|
|
25
|
+
if (!identityFlag && !String(ctx.env.STAMP_SSH_IDENTITY ?? "").trim()) {
|
|
26
|
+
const key = await ensureAgentKey(ctx);
|
|
27
|
+
if (key) ctx.err(t(ctx.locale, "keyEnsured", { path: key.path, fingerprint: key.fingerprint }));
|
|
28
|
+
}
|
|
22
29
|
const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
|
|
23
30
|
const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
|
|
24
31
|
if (!existsSync(identityPath)) {
|
|
@@ -58,9 +65,11 @@ export async function run(ctx) {
|
|
|
58
65
|
// Make later git operations in this checkout work without any export.
|
|
59
66
|
const directory = parsed.directory ?? repo.name;
|
|
60
67
|
const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
|
|
68
|
+
const commitEmail = await setCommitIdentity(ctx, me, directory);
|
|
61
69
|
ctx.emit(
|
|
62
|
-
{ ok: true, repository: `${repo.owner}/${repo.name}`, url, directory, sshIdentity: identityPath, sshIdentitySource: source, sshPinned: pinned.ok },
|
|
70
|
+
{ ok: true, repository: `${repo.owner}/${repo.name}`, url, directory, sshIdentity: identityPath, sshIdentitySource: source, sshPinned: pinned.ok, commitEmail },
|
|
63
71
|
() => {
|
|
72
|
+
if (commitEmail) ctx.out(t(ctx.locale, "repoCommitEmailSet", { email: commitEmail, directory }));
|
|
64
73
|
ctx.out(t(ctx.locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url }));
|
|
65
74
|
// The commit rules this gateway enforces, stated once up front (task #549):
|
|
66
75
|
// a pusher should not meet them for the first time as a refusal.
|
|
@@ -76,3 +85,46 @@ export async function run(ctx) {
|
|
|
76
85
|
);
|
|
77
86
|
return ctx.exit(0);
|
|
78
87
|
}
|
|
88
|
+
|
|
89
|
+
// `stamp repo use [DIR]` gives a checkout that was not cloned through Stamp
|
|
90
|
+
// the same per-repository ssh settings `repo clone` writes: this agent's own
|
|
91
|
+
// key and the gateway's pinned host key, in the repository's local config
|
|
92
|
+
// only (artin 09-27: never ~/.ssh/config or a global setting, which other
|
|
93
|
+
// agents on the machine share).
|
|
94
|
+
async function use(ctx) {
|
|
95
|
+
const identityFlag = takeFlag(ctx.args, "identity");
|
|
96
|
+
const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
|
|
97
|
+
const directory = ctx.args.shift() ?? ".";
|
|
98
|
+
if (ctx.args.length !== 0) throw new Error(t(ctx.locale, "usageRepoUse"));
|
|
99
|
+
if (!identityFlag && !String(ctx.env.STAMP_SSH_IDENTITY ?? "").trim()) {
|
|
100
|
+
const key = await ensureAgentKey(ctx);
|
|
101
|
+
if (key) ctx.err(t(ctx.locale, "keyEnsured", { path: key.path, fingerprint: key.fingerprint }));
|
|
102
|
+
}
|
|
103
|
+
const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
|
|
104
|
+
const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
|
|
105
|
+
if (!existsSync(identityPath)) {
|
|
106
|
+
throw new Error(t(ctx.locale, source === "enrolled" ? "cloneEnrolledIdentityMissing" : "cloneIdentityMissing", { path: identityPath, origin: ctx.auth.apiBase }));
|
|
107
|
+
}
|
|
108
|
+
const knownHostsPath = resolveKnownHostsPath(ctx.env, knownHostsFlag);
|
|
109
|
+
const fetchImpl = ctx.opts.fetchImpl ?? fetch;
|
|
110
|
+
const published = await fetchPublishedKnownHosts({ apiBase: ctx.auth.apiBase, fetchImpl });
|
|
111
|
+
if (!published.ok) {
|
|
112
|
+
throw new Error(t(ctx.locale, published.invalid ? "cloneKnownHostsInvalid" : "cloneKnownHostsUnavailable", {
|
|
113
|
+
url: `${ctx.auth.apiBase}/.well-known/ssh-known-hosts`,
|
|
114
|
+
status: published.status ?? "?",
|
|
115
|
+
}));
|
|
116
|
+
}
|
|
117
|
+
writePinnedKnownHosts(knownHostsPath, published.pattern, published.line);
|
|
118
|
+
const sshCommand = sshCommandFor({ identityPath, knownHostsPath });
|
|
119
|
+
const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
|
|
120
|
+
if (!pinned.ok) {
|
|
121
|
+
throw new Error(t(ctx.locale, "repoUseFailed", { directory, detail: (pinned.stderr ?? "").trim() }));
|
|
122
|
+
}
|
|
123
|
+
const me = await ctx.api("GET", "/v1/me").catch(() => null);
|
|
124
|
+
const commitEmail = await setCommitIdentity(ctx, me, directory);
|
|
125
|
+
ctx.emit({ directory, identityPath, knownHostsPath, sshCommand, commitEmail }, () => {
|
|
126
|
+
ctx.out(t(ctx.locale, "repoUseDone", { directory, path: identityPath }));
|
|
127
|
+
if (commitEmail) ctx.out(t(ctx.locale, "repoCommitEmailSet", { email: commitEmail, directory }));
|
|
128
|
+
});
|
|
129
|
+
return ctx.exit(0);
|
|
130
|
+
}
|
package/lib/commands/session.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { runAgentLogin } from "../agent-login.mjs";
|
|
2
2
|
import { humanExpiry } from "../expiry.mjs";
|
|
3
3
|
import { t } from "../locale.mjs";
|
|
4
|
+
import { ensureAgentKey } from "./key.mjs";
|
|
4
5
|
|
|
5
6
|
export async function login(ctx) {
|
|
6
7
|
const { auth, opts, emit, out, locale, exit } = ctx;
|
|
@@ -19,6 +20,16 @@ export async function login(ctx) {
|
|
|
19
20
|
() => out(t(locale, expiry.expired ? "loginTokenExpired" : "loginAgentReady", {
|
|
20
21
|
service: auth.service, url: auth.apiBase, expires: expiry.text, remaining: expiry.remaining,
|
|
21
22
|
})));
|
|
23
|
+
// The agent's own SSH key, without a separate step. A failure never costs
|
|
24
|
+
// the login: clone and `key enroll` try again.
|
|
25
|
+
if (!expiry.expired) {
|
|
26
|
+
try {
|
|
27
|
+
const key = await ensureAgentKey(ctx);
|
|
28
|
+
if (key) ctx.err(t(locale, "keyEnsured", { path: key.path, fingerprint: key.fingerprint }));
|
|
29
|
+
} catch (e) {
|
|
30
|
+
ctx.err(t(locale, "keyEnsureFailed", { reason: String(e?.message ?? e) }));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
22
33
|
return exit(0);
|
|
23
34
|
}
|
|
24
35
|
|
|
@@ -30,7 +41,15 @@ export async function logout(ctx) {
|
|
|
30
41
|
|
|
31
42
|
export async function whoami(ctx) {
|
|
32
43
|
const me = await ctx.api("GET", "/v1/me");
|
|
33
|
-
ctx.emit(me, () =>
|
|
44
|
+
ctx.emit(me, () => {
|
|
45
|
+
ctx.out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${ctx.auth.apiBase}`);
|
|
46
|
+
// An agent always has a commit email (artin 09-27): its own, or Stamp's
|
|
47
|
+
// default, which receives no mail. Say which, and how to use it.
|
|
48
|
+
const email = me.commitEmail;
|
|
49
|
+
if (email && typeof email.address === "string" && email.address !== "") {
|
|
50
|
+
ctx.out(t(ctx.locale, email.default ? "whoamiCommitEmailDefault" : "whoamiCommitEmail", { email: email.address }));
|
|
51
|
+
}
|
|
52
|
+
});
|
|
34
53
|
return ctx.exit(0);
|
|
35
54
|
}
|
|
36
55
|
|
package/lib/errors.mjs
CHANGED
|
@@ -25,12 +25,16 @@ function stableErrorCode(value) {
|
|
|
25
25
|
return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
// The gateway owns the repair: JSON { error, errorCode,
|
|
29
|
-
// The CLI prints those fields verbatim
|
|
28
|
+
// The gateway owns the repair: JSON { error, errorCode, cause,
|
|
29
|
+
// suggestedNextAction }. The CLI prints those fields verbatim (artin 09-27:
|
|
30
|
+
// every refusal reaches the client with its cause). It does not keep a
|
|
31
|
+
// second code→copy map.
|
|
30
32
|
export function printGatewayError(error, write) {
|
|
31
33
|
const body = error.body;
|
|
32
34
|
const code = stableErrorCode(body?.errorCode ?? body?.error);
|
|
33
35
|
if (code && code !== body?.error) write(`${prefix()}${code}`);
|
|
36
|
+
const cause = typeof body?.cause === "string" ? body.cause.trim() : "";
|
|
37
|
+
if (cause) write(`${prefix()}${cause}`);
|
|
34
38
|
const action = typeof body?.suggestedNextAction === "string" ? body.suggestedNextAction : "";
|
|
35
39
|
if (action) write(`${prefix()}${action}`);
|
|
36
40
|
return Boolean(action);
|
package/lib/locale.mjs
CHANGED
|
@@ -74,6 +74,7 @@ export const messages = {
|
|
|
74
74
|
prVerdictCIUnreadable: "CI unreadable — not evidence of green",
|
|
75
75
|
prVerdictLabel: "Stamp verdict",
|
|
76
76
|
verdict_READY: "can land now",
|
|
77
|
+
verdict_QUEUE_READY: "approved; it lands through Stamp's merge queue: `{cli} pr queue`",
|
|
77
78
|
verdict_MERGED: "already merged",
|
|
78
79
|
verdict_CLOSED: "closed",
|
|
79
80
|
verdict_DRAFT: "draft",
|
|
@@ -115,6 +116,9 @@ export const messages = {
|
|
|
115
116
|
prCreated: "Created PR #{number}: {url}",
|
|
116
117
|
prExisting: "Existing PR #{number}: {url}",
|
|
117
118
|
prStampPage: " Stamp: {page}",
|
|
119
|
+
prViewStampPage: "Stamp: {page}",
|
|
120
|
+
whoamiCommitEmail: "commit email: {email} (git config user.email {email})",
|
|
121
|
+
whoamiCommitEmailDefault: "commit email: {email} (Stamp's default for agents; it receives no mail. Use it: git config user.email {email}. Have your own address? {cli} identity bind --email ADDR)",
|
|
118
122
|
prNextAutoMerge: " Next: {cli} pr merge {number} --repo {repository} --auto --head {head} --base {base}\n (Stamp merges it once someone other than you approves this head and the verdict is READY)",
|
|
119
123
|
prWaitPublished: "Check {cli} receipt get <id>; use your own receipt after its status becomes PUBLISHED.",
|
|
120
124
|
prReceiptNotPublished: "Receipt {id} is {status}; it will not be published, so no pull request can be opened from it. See {cli} receipt get {id}.",
|
|
@@ -125,7 +129,7 @@ export const messages = {
|
|
|
125
129
|
prCheckBase: "The base branch does not exist on GitHub. Pass --base as an existing branch of the repository.",
|
|
126
130
|
prCheckExisting: "Check the existing PR and keep the same receipt, title, body and idempotency key when retrying.",
|
|
127
131
|
prRetry: "Check the receipt and service status, then retry the identical command; its idempotency key stays unchanged.",
|
|
128
|
-
apiBindIdentity: "
|
|
132
|
+
apiBindIdentity: "Run `{cli} whoami` (it gives this agent its default commit email), then retry the command.",
|
|
129
133
|
apiRepositoryNotInstalled: "Check OWNER/REPO spelling, or ask a server owner to install the Stamp GitHub App on that repository, then retry.",
|
|
130
134
|
apiContributionDenied: "Ask a server owner to grant this agent an active Write-or-higher repository role, then retry.",
|
|
131
135
|
apiRepositoryNotAuthorized: "Ask a server owner to verify the Stamp GitHub App installation and this agent's identity binding, then retry.",
|
|
@@ -136,7 +140,7 @@ export const messages = {
|
|
|
136
140
|
{cli} logout agent: forget the stored session
|
|
137
141
|
{cli} whoami who the gateway thinks you are
|
|
138
142
|
{cli} migration-help old manifest actions → CLI mapping
|
|
139
|
-
{cli} key enroll [--public-key FILE|-] bind this agent's SSH public key (default
|
|
143
|
+
{cli} key enroll [--public-key FILE|-] bind this agent's SSH public key (agent default: its own key, created if missing)
|
|
140
144
|
{cli} key list list this agent's enrolled SSH keys
|
|
141
145
|
{cli} key revoke KEY_ID revoke one of this agent's enrolled keys
|
|
142
146
|
{cli} known-hosts refresh re-pin this instance's SSH host key from /.well-known
|
|
@@ -158,6 +162,7 @@ export const messages = {
|
|
|
158
162
|
{cli} pr merge <number|URL> --repo OWNER/REPO --auto --head SHA --base SHA (author agent: merge once someone else approves)
|
|
159
163
|
{cli} pr queue enqueue|status|withdraw <number|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent; coordinates required for enqueue)
|
|
160
164
|
{cli} repo clone <repository> [<directory>] [-- <gitflags>...]
|
|
165
|
+
{cli} repo use [DIR] point an existing checkout at this agent's key (repository-local)
|
|
161
166
|
|
|
162
167
|
{cli} follow <owner/repo> --kind issue|pull --number N
|
|
163
168
|
{cli} unfollow <owner/repo> --kind issue|pull --number N
|
|
@@ -200,6 +205,14 @@ docs: {docs} (the agent workflow, step by step)`,
|
|
|
200
205
|
loginTokenExpired: "Agent logged in ({service} @ {url}), but the access token expired at {expires} ({remaining}); the next command refreshes it",
|
|
201
206
|
logoutForgot: "forgot agent session {path}",
|
|
202
207
|
logoutNothing: "nothing stored (human/CI lane uses STAMP_TOKEN)",
|
|
208
|
+
cliUpdateAvailable: "stamp {current} is out of date; {latest} is available: npm install -g @botiverse/stamp-cli@latest",
|
|
209
|
+
usageRepoUse: "usage: {cli} repo use [DIR] [--identity KEY] [--known-hosts FILE]",
|
|
210
|
+
repoUseDone: "{directory}: git now reaches Stamp with this agent's key {path} (set in this repository only)",
|
|
211
|
+
repoUseFailed: "could not set core.sshCommand in {directory}: {detail}",
|
|
212
|
+
keyEnsured: "this agent's own SSH key is ready: {path} ({fingerprint}); nothing to configure",
|
|
213
|
+
keyEnsureFailed: "could not set up this agent's SSH key yet ({reason}); `{cli} repo clone` and `{cli} key enroll` will try again",
|
|
214
|
+
repoCommitEmailSet: "commits in {directory} use this agent's commit email {email} (set in this repository only)",
|
|
215
|
+
keyGenerated: "created this agent's own SSH key: {path} (kept in the agent's directory, not ~/.ssh)",
|
|
203
216
|
enrolled: "enrolled {fingerprint} ({keyId})",
|
|
204
217
|
enrolledIdentityRecorded: "`{cli} repo clone` on this machine will use {path}",
|
|
205
218
|
enrolledIdentityNotRecorded: "the private key {path} is not on this machine, so `{cli} repo clone` here will need --identity FILE",
|
|
@@ -354,6 +367,7 @@ docs: {docs} (the agent workflow, step by step)`,
|
|
|
354
367
|
prVerdictCIUnreadable: "CI 无法读取——不能当作已通过",
|
|
355
368
|
prVerdictLabel: "Stamp 判定",
|
|
356
369
|
verdict_READY: "现在可以合入",
|
|
370
|
+
verdict_QUEUE_READY: "已批准;通过 Stamp 的合并队列合入:`{cli} pr queue`",
|
|
357
371
|
verdict_MERGED: "已合入",
|
|
358
372
|
verdict_CLOSED: "已关闭",
|
|
359
373
|
verdict_DRAFT: "草稿",
|
|
@@ -395,6 +409,9 @@ docs: {docs} (the agent workflow, step by step)`,
|
|
|
395
409
|
prCreated: "已创建 PR #{number}:{url}",
|
|
396
410
|
prExisting: "已有 PR #{number}:{url}",
|
|
397
411
|
prStampPage: " Stamp:{page}",
|
|
412
|
+
prViewStampPage: "Stamp:{page}",
|
|
413
|
+
whoamiCommitEmail: "提交邮箱:{email}(git config user.email {email})",
|
|
414
|
+
whoamiCommitEmailDefault: "提交邮箱:{email}(Stamp 给 agent 的默认地址,不能收信。直接用:git config user.email {email}。有自己的邮箱?{cli} identity bind --email ADDR)",
|
|
398
415
|
prNextAutoMerge: " 下一步:{cli} pr merge {number} --repo {repository} --auto --head {head} --base {base}\n (他人批准这个 head 且判定为 READY 后,Stamp 自动合并)",
|
|
399
416
|
prWaitPublished: "请用 {cli} receipt get <id> 检查;只使用自己状态为 PUBLISHED 的 receipt。",
|
|
400
417
|
prReceiptNotPublished: "Receipt {id} 的状态是 {status},不会发表到 GitHub,无法据此创建 PR。见 {cli} receipt get {id}。",
|
|
@@ -405,7 +422,7 @@ docs: {docs} (the agent workflow, step by step)`,
|
|
|
405
422
|
prCheckBase: "目标分支在 GitHub 上不存在;请用 --base 指定仓库里已存在的分支。",
|
|
406
423
|
prCheckExisting: "请检查已有 PR;重试时保持 receipt、标题、正文和幂等键不变。",
|
|
407
424
|
prRetry: "请检查 receipt 和服务状态,再原样重试命令;幂等键会保持不变。",
|
|
408
|
-
apiBindIdentity: "请先运行 `{cli}
|
|
425
|
+
apiBindIdentity: "请先运行 `{cli} whoami`(它会给这个 Agent 分配默认提交邮箱),再重试命令。",
|
|
409
426
|
apiRepositoryNotInstalled: "请检查 OWNER/REPO 拼写,或请 Server Owner 为该仓库安装 Stamp GitHub App,再重试。",
|
|
410
427
|
apiContributionDenied: "请让 Server Owner 为此 Agent 授予有效的 Write 或更高仓库角色,再重试。",
|
|
411
428
|
apiRepositoryNotAuthorized: "请让 Server Owner 核对 Stamp GitHub App 安装与此 Agent 的身份绑定,再重试。",
|
|
@@ -416,7 +433,7 @@ docs: {docs} (the agent workflow, step by step)`,
|
|
|
416
433
|
{cli} logout Agent:忘掉已存会话
|
|
417
434
|
{cli} whoami 网关认为你是谁
|
|
418
435
|
{cli} migration-help 旧 manifest action → CLI 对照
|
|
419
|
-
{cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH
|
|
436
|
+
{cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(agent 默认用它自己的 key,没有就生成)
|
|
420
437
|
{cli} key list 列出此 Agent 已登记的 SSH 公钥
|
|
421
438
|
{cli} key revoke KEY_ID 撤销此 Agent 的一把已登记公钥
|
|
422
439
|
{cli} known-hosts refresh 从 /.well-known 重新钉住本实例的 SSH 主机公钥
|
|
@@ -438,6 +455,7 @@ docs: {docs} (the agent workflow, step by step)`,
|
|
|
438
455
|
{cli} pr merge <编号|URL> --repo OWNER/REPO --auto --head SHA --base SHA (作者 agent:他人批准后自动合入)
|
|
439
456
|
{cli} pr queue enqueue|status|withdraw <编号|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent;入队需 head/base)
|
|
440
457
|
{cli} repo clone <repository> [<directory>] [-- <gitflags>...]
|
|
458
|
+
{cli} repo use [目录] 让已有的 checkout 用这个 agent 自己的 key(只设在该仓库)
|
|
441
459
|
|
|
442
460
|
{cli} follow <owner/repo> --kind issue|pull --number N
|
|
443
461
|
{cli} unfollow <owner/repo> --kind issue|pull --number N
|
|
@@ -480,6 +498,14 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
|
|
|
480
498
|
loginTokenExpired: "Agent 已登录({service} @ {url}),但访问令牌已于 {expires} 过期({remaining});下一条命令会自动刷新",
|
|
481
499
|
logoutForgot: "已忘记 Agent 会话 {path}",
|
|
482
500
|
logoutNothing: "没有本地会话(人类/CI 通道使用 STAMP_TOKEN)",
|
|
501
|
+
cliUpdateAvailable: "stamp {current} 已过时,新版 {latest} 可用:npm install -g @botiverse/stamp-cli@latest",
|
|
502
|
+
usageRepoUse: "用法:{cli} repo use [目录] [--identity KEY] [--known-hosts FILE]",
|
|
503
|
+
repoUseDone: "{directory}:git 现在用这个 agent 自己的 key {path} 连 Stamp(只设在这个仓库里)",
|
|
504
|
+
repoUseFailed: "无法在 {directory} 设置 core.sshCommand:{detail}",
|
|
505
|
+
keyEnsured: "已为这个 agent 准备好它自己的 SSH key:{path}({fingerprint}),不需要任何配置",
|
|
506
|
+
keyEnsureFailed: "暂时没能为这个 agent 准备 SSH key({reason});`{cli} repo clone` 和 `{cli} key enroll` 会再试",
|
|
507
|
+
repoCommitEmailSet: "{directory} 里的提交使用这个 agent 的提交邮箱 {email}(只设在这个仓库里)",
|
|
508
|
+
keyGenerated: "已为这个 agent 生成自己的 SSH key:{path}(放在 agent 自己的目录里,不在 ~/.ssh)",
|
|
483
509
|
enrolled: "已登记 {fingerprint}({keyId})",
|
|
484
510
|
enrolledIdentityRecorded: "这台机器上的 `{cli} repo clone` 会使用 {path}",
|
|
485
511
|
enrolledIdentityNotRecorded: "私钥 {path} 不在这台机器上,这里的 `{cli} repo clone` 需要 --identity FILE",
|
package/lib/main.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { resolveAuth } from "./auth.mjs";
|
|
|
4
4
|
import { makeClient, ApiError } from "./client.mjs";
|
|
5
5
|
import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
|
|
6
6
|
import { presentError, printGatewayError } from "./errors.mjs";
|
|
7
|
+
import { makeUpdateNotice } from "./update-check.mjs";
|
|
7
8
|
import * as session from "./commands/session.mjs";
|
|
8
9
|
import * as key from "./commands/key.mjs";
|
|
9
10
|
import * as knownhosts from "./commands/knownhosts.mjs";
|
|
@@ -41,7 +42,7 @@ export async function main(argv, opts) {
|
|
|
41
42
|
const args = [...argv];
|
|
42
43
|
const out = opts.stdout ?? ((s) => console.log(s));
|
|
43
44
|
const err = opts.stderr ?? ((s) => console.error(s));
|
|
44
|
-
|
|
45
|
+
let env = opts.env ?? process.env;
|
|
45
46
|
const exit = opts.exit ?? ((code) => process.exit(code));
|
|
46
47
|
const localValues = new Set(["--limit", "--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "--method", "-b", "-F", "-R"]);
|
|
47
48
|
let json = false, langFlag, help = false, version = false;
|
|
@@ -76,7 +77,16 @@ export async function main(argv, opts) {
|
|
|
76
77
|
err(`${prefix()}${presentError(locale, e)}`);
|
|
77
78
|
return exit(1);
|
|
78
79
|
}
|
|
80
|
+
// An agent's key, enrollment record and pinned host key live in its own
|
|
81
|
+
// directory (auth.stateDir); the repo helpers read it from the env they
|
|
82
|
+
// already take. An explicit STAMP_AGENT_STATE_DIR (tests) wins.
|
|
83
|
+
if (auth.stateDir && !env.STAMP_AGENT_STATE_DIR) env = { ...env, STAMP_AGENT_STATE_DIR: auth.stateDir };
|
|
84
|
+
const onVersions = makeUpdateNotice({
|
|
85
|
+
current: pkg.version, env, now: opts.now,
|
|
86
|
+
warn: (latest) => err(`${prefix()}${t(locale, "cliUpdateAvailable", { current: pkg.version, latest })}`),
|
|
87
|
+
});
|
|
79
88
|
const api = makeClient(auth, opts.fetchImpl, {
|
|
89
|
+
cliVersion: pkg.version, onVersions,
|
|
80
90
|
readRetries: opts.networkReadRetries, retryDelayMs: opts.networkRetryDelayMs, sleep: opts.sleep,
|
|
81
91
|
});
|
|
82
92
|
const handler = commands[cmd];
|
package/lib/pr/create.mjs
CHANGED
|
@@ -125,6 +125,22 @@ export async function waitForPublishedReceipt(api, id, { timeoutMs = publishWait
|
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
+
// stampPullRequestPage is the pull request's page on this Stamp instance:
|
|
129
|
+
// the link to hand a person (artin 09-27: Stamp links first, GitHub's as
|
|
130
|
+
// well if wanted). null when the repository, number or instance does not
|
|
131
|
+
// check out, so no half-built link is ever printed.
|
|
132
|
+
export function stampPullRequestPage(apiBase, repository, number) {
|
|
133
|
+
if (typeof repository !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(repository)) return null;
|
|
134
|
+
if (!Number.isInteger(number) || number <= 0) return null;
|
|
135
|
+
try {
|
|
136
|
+
const u = new URL(apiBase);
|
|
137
|
+
if (u.protocol === "https:" || u.hostname === "127.0.0.1" || u.hostname === "localhost") {
|
|
138
|
+
return `${u.origin}/github/${repository}/pull/${number}`;
|
|
139
|
+
}
|
|
140
|
+
} catch { /* no page */ }
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
|
|
128
144
|
// pullRequestNextLines is what `pr create` prints under "Created PR": the
|
|
129
145
|
// pull request's page on this Stamp instance, and the one command that
|
|
130
146
|
// registers it for auto-merge, with the exact head and base the gateway just
|
|
@@ -136,12 +152,8 @@ export function pullRequestNextLines(d, apiBase, tr) {
|
|
|
136
152
|
const repo = typeof d?.repository === "string" && /^[^/\s]+\/[^/\s]+$/.test(d.repository) ? d.repository : null;
|
|
137
153
|
const number = Number.isInteger(d?.pullNumber) && d.pullNumber > 0 ? d.pullNumber : null;
|
|
138
154
|
if (!repo || !number) return lines;
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
const u = new URL(apiBase);
|
|
142
|
-
if (u.protocol === "https:" || u.hostname === "127.0.0.1" || u.hostname === "localhost") origin = u.origin;
|
|
143
|
-
} catch { /* no page line */ }
|
|
144
|
-
if (origin) lines.push(tr("prStampPage", { page: `${origin}/github/${repo}/pull/${number}` }));
|
|
155
|
+
const page = stampPullRequestPage(apiBase, repo, number);
|
|
156
|
+
if (page) lines.push(tr("prStampPage", { page }));
|
|
145
157
|
const sha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
|
|
146
158
|
if (sha(d.headSha) && sha(d.baseSha)) {
|
|
147
159
|
lines.push(tr("prNextAutoMerge", { number, repository: repo, head: d.headSha, base: d.baseSha }));
|
package/lib/pr/read.mjs
CHANGED
|
@@ -386,6 +386,16 @@ function sectionLabel(section, labels) {
|
|
|
386
386
|
return labels[key] ?? section;
|
|
387
387
|
}
|
|
388
388
|
|
|
389
|
+
// formatApprovals names who approved the exact head, from the verdict; with
|
|
390
|
+
// no verdict (an older gateway) it falls back to GitHub's review status.
|
|
391
|
+
export function formatApprovals(verdict, reviewStatus) {
|
|
392
|
+
const approvals = Array.isArray(verdict?.approvals) ? verdict.approvals : null;
|
|
393
|
+
if (!approvals) return safeInline(reviewStatus);
|
|
394
|
+
if (approvals.length === 0) return "no approval at this head";
|
|
395
|
+
const who = approvals.map((a) => `${safeInline(a.principal)} (${a.source === "stamp_receipt" ? "Stamp" : "GitHub"})`).join(", ");
|
|
396
|
+
return `approved at head ${safeInline(approvals[0].headSha).slice(0, 12)} by ${who}`;
|
|
397
|
+
}
|
|
398
|
+
|
|
389
399
|
export function formatPRDetail(detail, labels) {
|
|
390
400
|
const lines = [
|
|
391
401
|
`${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
|
|
@@ -398,7 +408,12 @@ export function formatPRDetail(detail, labels) {
|
|
|
398
408
|
// the checks could not be read — one endpoint, two commands, two answers,
|
|
399
409
|
// which is the false trail #598 started on.
|
|
400
410
|
`${labels.checks}: ${detail.ciUnreadable ? labels.ciUnreadable : safeInline(detail.ciStatus)}`,
|
|
401
|
-
|
|
411
|
+
// Stamp's own approvals first (they are what the verdict counts); GitHub's
|
|
412
|
+
// review decision alone reads "unreviewed" on a PR Stamp approved.
|
|
413
|
+
`${labels.review}: ${formatApprovals(detail.verdict, detail.reviewStatus)}`,
|
|
414
|
+
// The Stamp page first, then GitHub's: the Stamp one is the link to hand
|
|
415
|
+
// a person (artin 09-27).
|
|
416
|
+
...(labels.stampPage ? [labels.stampPage] : []),
|
|
402
417
|
safeInline(detail.url),
|
|
403
418
|
];
|
|
404
419
|
if (typeof detail.body === "string" && detail.body !== "") lines.push("", safeMultiline(detail.body));
|
package/lib/repo/clone.mjs
CHANGED
|
@@ -73,3 +73,29 @@ export function runGitSetSSHCommand({ directory, sshCommand, spawnImpl = spawn }
|
|
|
73
73
|
child.on("close", (code) => resolve({ ok: code === 0, stderr }));
|
|
74
74
|
});
|
|
75
75
|
}
|
|
76
|
+
|
|
77
|
+
// runGitConfigLocal sets one key in the checkout's own config (never
|
|
78
|
+
// --global: several agents often share one machine user).
|
|
79
|
+
export function runGitConfigLocal({ directory, key, value, spawnImpl = spawn }) {
|
|
80
|
+
return new Promise((resolve) => {
|
|
81
|
+
const child = spawnImpl("git", ["-C", directory, "config", "--local", key, value], { stdio: ["ignore", "ignore", "pipe"] });
|
|
82
|
+
let stderr = "";
|
|
83
|
+
child.stderr?.on("data", (b) => { stderr += b; });
|
|
84
|
+
child.on("error", () => resolve({ ok: false }));
|
|
85
|
+
child.on("close", (code) => resolve({ ok: code === 0, stderr }));
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// setCommitIdentity writes the agent's commit identity into the checkout
|
|
90
|
+
// (artin 09-28: the commit email is already automatic, so no step should ask
|
|
91
|
+
// for `git config user.email`). An agent's commit email comes from /v1/me;
|
|
92
|
+
// a person's checkout is left alone. It returns the address written, or "".
|
|
93
|
+
export async function setCommitIdentity(ctx, me, directory) {
|
|
94
|
+
const address = typeof me?.commitEmail?.address === "string" ? me.commitEmail.address.trim() : "";
|
|
95
|
+
if (me?.principalType !== "agent" || !address) return "";
|
|
96
|
+
const set = ctx.opts.gitConfigLocalImpl ?? runGitConfigLocal;
|
|
97
|
+
const email = await set({ directory, key: "user.email", value: address });
|
|
98
|
+
if (!email.ok) return "";
|
|
99
|
+
if (typeof me.name === "string" && me.name.trim()) await set({ directory, key: "user.name", value: me.name.trim() });
|
|
100
|
+
return address;
|
|
101
|
+
}
|
package/lib/repo/identities.mjs
CHANGED
|
@@ -11,7 +11,9 @@ import { dirname, join } from "node:path";
|
|
|
11
11
|
|
|
12
12
|
export function identitiesPath(env) {
|
|
13
13
|
const fromEnv = String(env?.STAMP_IDENTITIES ?? "").trim();
|
|
14
|
-
|
|
14
|
+
if (fromEnv) return fromEnv;
|
|
15
|
+
const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
|
|
16
|
+
return agentDir ? join(agentDir, "identities.json") : join(homedir(), ".stamp", "identities.json");
|
|
15
17
|
}
|
|
16
18
|
|
|
17
19
|
function readAll(path) {
|
package/lib/repo/ssh.mjs
CHANGED
|
@@ -12,8 +12,12 @@ import { spawnSync } from "node:child_process";
|
|
|
12
12
|
|
|
13
13
|
// defaultIdentityPath is where `stamp key enroll` looks for the public key; the
|
|
14
14
|
// private half is the same path without `.pub`.
|
|
15
|
+
// An agent's default key is its own (artin 09-27), in its state directory,
|
|
16
|
+
// never the ~/.ssh/id_ed25519 every agent on a machine user shares; a human
|
|
17
|
+
// keeps the conventional path.
|
|
15
18
|
export function defaultIdentityPath(env) {
|
|
16
|
-
|
|
19
|
+
const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
|
|
20
|
+
return agentDir ? join(agentDir, "ssh", "id_ed25519") : join(homedir(), ".ssh", "id_ed25519");
|
|
17
21
|
}
|
|
18
22
|
|
|
19
23
|
// resolveIdentity picks the private key in this order and says which source
|
|
@@ -40,7 +44,9 @@ export function resolveKnownHostsPath(env, flagValue) {
|
|
|
40
44
|
const fromFlag = String(flagValue ?? "").trim();
|
|
41
45
|
if (fromFlag) return fromFlag;
|
|
42
46
|
const fromEnv = String(env?.STAMP_KNOWN_HOSTS ?? "").trim();
|
|
43
|
-
|
|
47
|
+
if (fromEnv) return fromEnv;
|
|
48
|
+
const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
|
|
49
|
+
return agentDir ? join(agentDir, "known_hosts") : join(homedir(), ".stamp", "known_hosts");
|
|
44
50
|
}
|
|
45
51
|
|
|
46
52
|
function shellQuote(value) {
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
// The gateway names the current CLI on every answer (Stamp-Cli-Latest; artin
|
|
6
|
+
// 09-27: agents ran long-outdated CLIs and nothing told them). The CLI says
|
|
7
|
+
// so on stderr at most once a day, recorded in the agent's own directory
|
|
8
|
+
// (or ~/.stamp for a person). A CLI below Stamp-Cli-Minimum is refused by the
|
|
9
|
+
// gateway itself (CLI_TOO_OLD).
|
|
10
|
+
|
|
11
|
+
export function versionLess(a, b) {
|
|
12
|
+
const parse = (v) => {
|
|
13
|
+
const core = String(v ?? "").trim().replace(/^v/, "").split("-")[0];
|
|
14
|
+
const parts = core.split(".").map((p) => (/^\d+$/.test(p) ? Number(p) : NaN));
|
|
15
|
+
return parts.length && parts.every(Number.isFinite) ? parts : null;
|
|
16
|
+
};
|
|
17
|
+
const pa = parse(a), pb = parse(b);
|
|
18
|
+
if (!pa || !pb) return false;
|
|
19
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
20
|
+
const x = pa[i] ?? 0, y = pb[i] ?? 0;
|
|
21
|
+
if (x !== y) return x < y;
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function updateCheckPath(env) {
|
|
27
|
+
const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
|
|
28
|
+
return agentDir ? join(agentDir, "update-check.json") : join(homedir(), ".stamp", "update-check.json");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
32
|
+
|
|
33
|
+
// makeUpdateNotice returns the onVersions callback: it warns once per day
|
|
34
|
+
// (per latest version) when a newer CLI exists.
|
|
35
|
+
export function makeUpdateNotice({ current, env, warn, now = () => Date.now() }) {
|
|
36
|
+
let done = false;
|
|
37
|
+
return (latest) => {
|
|
38
|
+
if (done || !latest || !versionLess(current, latest)) return;
|
|
39
|
+
done = true;
|
|
40
|
+
const path = updateCheckPath(env);
|
|
41
|
+
let last = {};
|
|
42
|
+
try { last = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {}; } catch { last = {}; }
|
|
43
|
+
if (last.latest === latest && now() - Number(last.at ?? 0) < DAY_MS) return;
|
|
44
|
+
warn(latest);
|
|
45
|
+
try {
|
|
46
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
47
|
+
writeFileSync(path, `${JSON.stringify({ latest, at: now() })}\n`, { mode: 0o600 });
|
|
48
|
+
} catch { /* a notice that cannot be recorded is shown again tomorrow */ }
|
|
49
|
+
};
|
|
50
|
+
}
|