@botiverse/stamp-cli 0.3.9 → 0.3.10

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 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";
@@ -147,6 +147,10 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
147
147
  apiBase,
148
148
  agentEnv: a,
149
149
  service,
150
+ // The agent's own directory for Stamp state, beside its session (artin
151
+ // 09-27): its SSH key, the enrollment record and the pinned host key.
152
+ // Never ~/.ssh or ~/.stamp, which every agent on a machine user shares.
153
+ stateDir: dirname(agentAuthPath(a, service)),
150
154
  async token() {
151
155
  if (!usableStore) {
152
156
  if (storedOriginElsewhere !== null) {
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: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
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 */ }
@@ -1,10 +1,22 @@
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
5
  import { 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
+ }
8
20
 
9
21
  export async function run(ctx) {
10
22
  const sub = ctx.args.shift();
@@ -26,7 +38,16 @@ export async function run(ctx) {
26
38
  return ctx.exit(0);
27
39
  }
28
40
  if (sub !== "enroll") throw new Error(t(ctx.locale, "usageKeyEnroll"));
29
- const keyPath = takeFlag(ctx.args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
41
+ const agentDefault = `${defaultIdentityPath(ctx.env)}.pub`;
42
+ const keyPath = takeFlag(ctx.args, "public-key", agentDefault);
43
+ // An agent enrolling with no --public-key gets a key of its own, created in
44
+ // its own directory (artin 09-27: a shared ~/.ssh/id_ed25519 made another
45
+ // agent's key push for BoBo). Nothing to configure by hand.
46
+ let generated = false;
47
+ if (keyPath === agentDefault && ctx.env.STAMP_AGENT_STATE_DIR && !existsSync(keyPath)) {
48
+ await (ctx.opts.sshKeygenImpl ?? generateAgentKey)(keyPath.replace(/\.pub$/, ""), ctx.auth?.agentEnv?.agentId);
49
+ generated = true;
50
+ }
30
51
  if (keyPath !== "-" && !existsSync(keyPath)) {
31
52
  // The default path is the interesting case: `key enroll` on a machine with
32
53
  // no key reads a path the operator never typed, so name it and name the two
@@ -48,7 +69,8 @@ export async function run(ctx) {
48
69
  recordIdentity(ctx.env, ctx.auth.apiBase, identity);
49
70
  }
50
71
  }
51
- ctx.emit({ ...d, identity }, () => {
72
+ ctx.emit({ ...d, identity, generated }, () => {
73
+ if (generated) ctx.out(t(ctx.locale, "keyGenerated", { path: keyPath.replace(/\.pub$/, "") }));
52
74
  ctx.out(t(ctx.locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId }));
53
75
  ctx.out(identity
54
76
  ? t(ctx.locale, "enrolledIdentityRecorded", { path: identity.identityPath })
@@ -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
- emit(d, () => {
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"),
@@ -6,7 +6,9 @@ import { fetchPublishedKnownHosts, resolveIdentity, resolveKnownHostsPath, sshCo
6
6
  import { readRecordedIdentity } from "../repo/identities.mjs";
7
7
 
8
8
  export async function run(ctx) {
9
- if (ctx.args.shift() !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
9
+ const sub = ctx.args.shift();
10
+ if (sub === "use") return use(ctx);
11
+ if (sub !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
10
12
  const identityFlag = takeFlag(ctx.args, "identity");
11
13
  const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
12
14
  const parsed = parseRepoCloneArgs(ctx.args);
@@ -76,3 +78,39 @@ export async function run(ctx) {
76
78
  );
77
79
  return ctx.exit(0);
78
80
  }
81
+
82
+ // `stamp repo use [DIR]` gives a checkout that was not cloned through Stamp
83
+ // the same per-repository ssh settings `repo clone` writes: this agent's own
84
+ // key and the gateway's pinned host key, in the repository's local config
85
+ // only (artin 09-27: never ~/.ssh/config or a global setting, which other
86
+ // agents on the machine share).
87
+ async function use(ctx) {
88
+ const identityFlag = takeFlag(ctx.args, "identity");
89
+ const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
90
+ const directory = ctx.args.shift() ?? ".";
91
+ if (ctx.args.length !== 0) throw new Error(t(ctx.locale, "usageRepoUse"));
92
+ const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
93
+ const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
94
+ if (!existsSync(identityPath)) {
95
+ throw new Error(t(ctx.locale, source === "enrolled" ? "cloneEnrolledIdentityMissing" : "cloneIdentityMissing", { path: identityPath, origin: ctx.auth.apiBase }));
96
+ }
97
+ const knownHostsPath = resolveKnownHostsPath(ctx.env, knownHostsFlag);
98
+ const fetchImpl = ctx.opts.fetchImpl ?? fetch;
99
+ const published = await fetchPublishedKnownHosts({ apiBase: ctx.auth.apiBase, fetchImpl });
100
+ if (!published.ok) {
101
+ throw new Error(t(ctx.locale, published.invalid ? "cloneKnownHostsInvalid" : "cloneKnownHostsUnavailable", {
102
+ url: `${ctx.auth.apiBase}/.well-known/ssh-known-hosts`,
103
+ status: published.status ?? "?",
104
+ }));
105
+ }
106
+ writePinnedKnownHosts(knownHostsPath, published.pattern, published.line);
107
+ const sshCommand = sshCommandFor({ identityPath, knownHostsPath });
108
+ const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
109
+ if (!pinned.ok) {
110
+ throw new Error(t(ctx.locale, "repoUseFailed", { directory, detail: (pinned.stderr ?? "").trim() }));
111
+ }
112
+ ctx.emit({ directory, identityPath, knownHostsPath, sshCommand }, () => {
113
+ ctx.out(t(ctx.locale, "repoUseDone", { directory, path: identityPath }));
114
+ });
115
+ return ctx.exit(0);
116
+ }
@@ -30,7 +30,15 @@ export async function logout(ctx) {
30
30
 
31
31
  export async function whoami(ctx) {
32
32
  const me = await ctx.api("GET", "/v1/me");
33
- ctx.emit(me, () => ctx.out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${ctx.auth.apiBase}`));
33
+ ctx.emit(me, () => {
34
+ ctx.out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${ctx.auth.apiBase}`);
35
+ // An agent always has a commit email (artin 09-27): its own, or Stamp's
36
+ // default, which receives no mail. Say which, and how to use it.
37
+ const email = me.commitEmail;
38
+ if (email && typeof email.address === "string" && email.address !== "") {
39
+ ctx.out(t(ctx.locale, email.default ? "whoamiCommitEmailDefault" : "whoamiCommitEmail", { email: email.address }));
40
+ }
41
+ });
34
42
  return ctx.exit(0);
35
43
  }
36
44
 
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, suggestedNextAction }.
29
- // The CLI prints those fields verbatim. It does not keep a second code→copy map.
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: "Bind this agent first with `{cli} identity bind --email <agent-email>`, then retry the command.",
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 ~/.ssh/id_ed25519.pub)
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,11 @@ 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
+ keyGenerated: "created this agent's own SSH key: {path} (kept in the agent's directory, not ~/.ssh)",
203
213
  enrolled: "enrolled {fingerprint} ({keyId})",
204
214
  enrolledIdentityRecorded: "`{cli} repo clone` on this machine will use {path}",
205
215
  enrolledIdentityNotRecorded: "the private key {path} is not on this machine, so `{cli} repo clone` here will need --identity FILE",
@@ -354,6 +364,7 @@ docs: {docs} (the agent workflow, step by step)`,
354
364
  prVerdictCIUnreadable: "CI 无法读取——不能当作已通过",
355
365
  prVerdictLabel: "Stamp 判定",
356
366
  verdict_READY: "现在可以合入",
367
+ verdict_QUEUE_READY: "已批准;通过 Stamp 的合并队列合入:`{cli} pr queue`",
357
368
  verdict_MERGED: "已合入",
358
369
  verdict_CLOSED: "已关闭",
359
370
  verdict_DRAFT: "草稿",
@@ -395,6 +406,9 @@ docs: {docs} (the agent workflow, step by step)`,
395
406
  prCreated: "已创建 PR #{number}:{url}",
396
407
  prExisting: "已有 PR #{number}:{url}",
397
408
  prStampPage: " Stamp:{page}",
409
+ prViewStampPage: "Stamp:{page}",
410
+ whoamiCommitEmail: "提交邮箱:{email}(git config user.email {email})",
411
+ whoamiCommitEmailDefault: "提交邮箱:{email}(Stamp 给 agent 的默认地址,不能收信。直接用:git config user.email {email}。有自己的邮箱?{cli} identity bind --email ADDR)",
398
412
  prNextAutoMerge: " 下一步:{cli} pr merge {number} --repo {repository} --auto --head {head} --base {base}\n (他人批准这个 head 且判定为 READY 后,Stamp 自动合并)",
399
413
  prWaitPublished: "请用 {cli} receipt get <id> 检查;只使用自己状态为 PUBLISHED 的 receipt。",
400
414
  prReceiptNotPublished: "Receipt {id} 的状态是 {status},不会发表到 GitHub,无法据此创建 PR。见 {cli} receipt get {id}。",
@@ -405,7 +419,7 @@ docs: {docs} (the agent workflow, step by step)`,
405
419
  prCheckBase: "目标分支在 GitHub 上不存在;请用 --base 指定仓库里已存在的分支。",
406
420
  prCheckExisting: "请检查已有 PR;重试时保持 receipt、标题、正文和幂等键不变。",
407
421
  prRetry: "请检查 receipt 和服务状态,再原样重试命令;幂等键会保持不变。",
408
- apiBindIdentity: "请先运行 `{cli} identity bind --email <agent-email>` 绑定此 Agent,再重试命令。",
422
+ apiBindIdentity: "请先运行 `{cli} whoami`(它会给这个 Agent 分配默认提交邮箱),再重试命令。",
409
423
  apiRepositoryNotInstalled: "请检查 OWNER/REPO 拼写,或请 Server Owner 为该仓库安装 Stamp GitHub App,再重试。",
410
424
  apiContributionDenied: "请让 Server Owner 为此 Agent 授予有效的 Write 或更高仓库角色,再重试。",
411
425
  apiRepositoryNotAuthorized: "请让 Server Owner 核对 Stamp GitHub App 安装与此 Agent 的身份绑定,再重试。",
@@ -416,7 +430,7 @@ docs: {docs} (the agent workflow, step by step)`,
416
430
  {cli} logout Agent:忘掉已存会话
417
431
  {cli} whoami 网关认为你是谁
418
432
  {cli} migration-help 旧 manifest action → CLI 对照
419
- {cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(默认 ~/.ssh/id_ed25519.pub)
433
+ {cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(agent 默认用它自己的 key,没有就生成)
420
434
  {cli} key list 列出此 Agent 已登记的 SSH 公钥
421
435
  {cli} key revoke KEY_ID 撤销此 Agent 的一把已登记公钥
422
436
  {cli} known-hosts refresh 从 /.well-known 重新钉住本实例的 SSH 主机公钥
@@ -438,6 +452,7 @@ docs: {docs} (the agent workflow, step by step)`,
438
452
  {cli} pr merge <编号|URL> --repo OWNER/REPO --auto --head SHA --base SHA (作者 agent:他人批准后自动合入)
439
453
  {cli} pr queue enqueue|status|withdraw <编号|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent;入队需 head/base)
440
454
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
455
+ {cli} repo use [目录] 让已有的 checkout 用这个 agent 自己的 key(只设在该仓库)
441
456
 
442
457
  {cli} follow <owner/repo> --kind issue|pull --number N
443
458
  {cli} unfollow <owner/repo> --kind issue|pull --number N
@@ -480,6 +495,11 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
480
495
  loginTokenExpired: "Agent 已登录({service} @ {url}),但访问令牌已于 {expires} 过期({remaining});下一条命令会自动刷新",
481
496
  logoutForgot: "已忘记 Agent 会话 {path}",
482
497
  logoutNothing: "没有本地会话(人类/CI 通道使用 STAMP_TOKEN)",
498
+ cliUpdateAvailable: "stamp {current} 已过时,新版 {latest} 可用:npm install -g @botiverse/stamp-cli@latest",
499
+ usageRepoUse: "用法:{cli} repo use [目录] [--identity KEY] [--known-hosts FILE]",
500
+ repoUseDone: "{directory}:git 现在用这个 agent 自己的 key {path} 连 Stamp(只设在这个仓库里)",
501
+ repoUseFailed: "无法在 {directory} 设置 core.sshCommand:{detail}",
502
+ keyGenerated: "已为这个 agent 生成自己的 SSH key:{path}(放在 agent 自己的目录里,不在 ~/.ssh)",
483
503
  enrolled: "已登记 {fingerprint}({keyId})",
484
504
  enrolledIdentityRecorded: "这台机器上的 `{cli} repo clone` 会使用 {path}",
485
505
  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
- const env = opts.env ?? process.env;
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
- let origin = null;
140
- try {
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
- `${labels.review}: ${safeInline(detail.reviewStatus)}`,
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));
@@ -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
- return fromEnv || join(homedir(), ".stamp", "identities.json");
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
- return join(homedir(), ".ssh", "id_ed25519");
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
- return fromEnv || join(homedir(), ".stamp", "known_hosts");
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.9",
3
+ "version": "0.3.10",
4
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",