@botiverse/stamp-cli 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/flags.mjs ADDED
@@ -0,0 +1,26 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { t } from "./locale.mjs";
3
+
4
+ export function takeFlag(args, name, dflt) {
5
+ const i = args.indexOf(`--${name}`);
6
+ if (i === -1) return dflt;
7
+ const v = args[i + 1];
8
+ args.splice(i, 2);
9
+ return v;
10
+ }
11
+
12
+ export function readPublicKey(path) {
13
+ if (path === "-") return readFileSync(0, "utf8").trim();
14
+ return readFileSync(path, "utf8").trim();
15
+ }
16
+
17
+ export function objectArgs(args, locale) {
18
+ const repository = args.shift();
19
+ const rawKind = takeFlag(args, "kind");
20
+ const kind = rawKind === "pull" ? "pull_request" : rawKind;
21
+ const number = Number(takeFlag(args, "number"));
22
+ if (!repository || !["issue", "pull_request"].includes(kind) || !Number.isInteger(number) || number <= 0) {
23
+ throw new Error(t(locale, "usageFollow"));
24
+ }
25
+ return { repository, kind, number };
26
+ }
package/lib/locale.mjs CHANGED
@@ -2,7 +2,18 @@
2
2
  export const messages = {
3
3
  en: {
4
4
  usagePrCreate: "usage: {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
5
- usagePrRead: "usage: {cli} pr <list|view|diff|checks|comment> [arguments]",
5
+ usagePrRead: "usage: {cli} pr <list|view|diff|checks|comment|approve|merge> [arguments]",
6
+ usagePrApprove: "usage: {cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT] (human GitHub identity required)",
7
+ usagePrMerge: "usage: {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase] (human GitHub identity required)",
8
+ prApproved: "Approved {repository}#{number} as {actor}",
9
+ prMerged: "Merged {repository}#{number} as {actor} ({sha})",
10
+ prApproveRejected: "Approve was rejected. Check your human session, GitHub binding, repository access, and --head/--base.",
11
+ prMergeRejected: "Merge was rejected. Check your human session, GitHub binding, repository access, --head/--base, and mergeability.",
12
+ prApproveOutcomeUnknown: "Approve outcome is unknown. Re-read the PR reviews before sending again; do not automatically resend.",
13
+ prMergeOutcomeUnknown: "Merge outcome is unknown. Re-read the PR before sending again; do not automatically resend.",
14
+ apiHumanPrincipal: "Agents cannot approve or merge. Use a human STAMP_TOKEN session.",
15
+ apiWriteCoords: "Re-read the PR and retry with both --head and --base.",
16
+ apiGitHubBinding: "Bind your GitHub account in Stamp settings, then retry.",
6
17
  usagePrComment: "usage: {cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) (human GitHub identity required)",
7
18
  prCommentBodyInvalid: "Comment must be nonempty and at most 64 KiB of UTF-8 text.",
8
19
  prCommentCreated: "Comment posted as {actor}: {url}",
@@ -74,6 +85,8 @@ export const messages = {
74
85
  {cli} pr diff <number|URL> --repo OWNER/REPO [--name-only]
75
86
  {cli} pr checks <number|URL> --repo OWNER/REPO
76
87
  {cli} pr comment <number|URL> --repo OWNER/REPO --body-file FILE|- (human)
88
+ {cli} pr approve <number|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (human)
89
+ {cli} pr merge <number|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (human)
77
90
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
78
91
 
79
92
  {cli} follow <owner/repo> --kind issue|pull --number N
@@ -87,13 +100,22 @@ export const messages = {
87
100
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
88
101
 
89
102
  flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG`,
90
- usageRepoClone: "usage: {cli} repo clone <repository> [<directory>] [-- <gitflags>...]",
103
+ usageRepoClone: "usage: {cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
91
104
  cloned: "Cloned {repository} from {url}",
92
105
  cloneFailed: "clone of {repository} via the Stamp gateway failed",
106
+ networkUnreachable: "could not reach {base} ({cause}); check the instance address (STAMP_URL) and your network, then retry",
107
+ networkHostUnresolved: "{base} does not resolve ({cause}); check the instance address (STAMP_URL) and DNS, then retry",
108
+ cloneIdentityMissing: "no SSH private key at {path}: enroll one with `{cli} key enroll` (it reads {path}.pub), or point at an existing key with --identity FILE",
109
+ cloneKnownHostsUnavailable: "{url} returned HTTP {status}: this instance does not publish its SSH host key, so there is nothing to pin — pass --known-hosts FILE, or set STAMP_KNOWN_HOSTS",
110
+ cloneKnownHostsInvalid: "{url} did not return a usable known_hosts line; refusing to pin it — check the instance, or pass --known-hosts FILE",
111
+ clonePublicKeyRejected: "the gateway rejected the key at {path} (publickey). If it is not enrolled yet, enroll its public half: `{cli} key enroll --public-key {publicKey}`",
112
+ cloneIdentityPinned: "pinned the Stamp SSH identity for {directory} (git config core.sshCommand)",
113
+ cloneIdentityPinFailed: "could not write the SSH identity into {directory}; run it yourself: git -C {directory} config --local core.sshCommand \"{command}\"",
93
114
  loginHumanIntro: "Not a managed Raft agent. Humans and CI use STAMP_TOKEN:",
94
115
  loginHumanBrowser: " browser: {url}/login (reuse the session cookie value as STAMP_TOKEN)",
95
116
  loginHumanCI: " CI: a narrowly scoped deploy token",
96
- loginAgentReady: "Agent login ready ({service} @ {url}); access token valid until {expires}",
117
+ loginAgentReady: "Agent login ready ({service} @ {url}); access token valid until {expires} ({remaining})",
118
+ loginTokenExpired: "Agent logged in ({service} @ {url}), but the access token expired at {expires} ({remaining}); the next command refreshes it",
97
119
  logoutForgot: "forgot agent session {path}",
98
120
  logoutNothing: "nothing stored (human/CI lane uses STAMP_TOKEN)",
99
121
  enrolled: "enrolled {fingerprint} ({keyId})",
@@ -110,9 +132,14 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
110
132
  checkToken: "{cli}: check STAMP_TOKEN",
111
133
  notLoggedIn: "not logged in: run `{cli} login` (managed agent)",
112
134
  sessionOriginMismatch: "the stored session was issued for {stored}, not {target} — run `{cli} login` again",
135
+ sessionOriginMismatchSibling: "the stored session was issued for {stored}, not {target} — {stored} is served by `{other}`; run that binary instead of `{cli}`",
113
136
  pair_mismatch: "refusing a mismatched instance pair: {origin} belongs to service {owner}, not {service} (task #439)",
114
137
  stampTokenMissing: "STAMP_TOKEN is not set (session or deploy token); inside a managed agent run `{cli} login`",
115
- admission_partial: "refusing to run: partial managed-agent environment ({reason}); not falling back to STAMP_TOKEN",
138
+ admissionPartial: "refusing to run: partial managed-agent environment ({reason}); not falling back to STAMP_TOKEN",
139
+ admissionMissingVars: "refusing to run: the managed-agent environment is incomplete — {missing} unset while {present} set; this is not a human/CI shell, so STAMP_TOKEN will not be used",
140
+ admissionInvalidAgentID: "refusing to run: SLOCK_AGENT_ID={value} is not a valid agent id; fix the managed-agent environment — STAMP_TOKEN will not be used",
141
+ admissionRaftWrapper: "refusing to run: the managed-agent raft wrapper is missing or not executable at {path}; fix the managed-agent environment — STAMP_TOKEN will not be used",
142
+ keyPublicKeyMissing: "no SSH public key at {path}: create one with `ssh-keygen -t ed25519 -f {private}`, or pass --public-key FILE",
116
143
  invoke_not_json: "agent-login: `raft integration invoke` did not return JSON",
117
144
  invoke_not_object: "agent-login: invoke output is not an object",
118
145
  invoke_failed: "agent-login: invoke did not succeed",
@@ -141,7 +168,7 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
141
168
  session_refresh_expired: "agent-login: session refresh token is already expired",
142
169
  token_size_limit: "agent-login: token response exceeds the size limit",
143
170
  token_deadline: "agent-login: token endpoint exceeded the deadline",
144
- invoke_exit: "agent-login: raft invoke exited with a non-zero status ({status})",
171
+ invoke_exit: "agent-login: raft invoke failed ({status}): {diagnostic}",
145
172
  exchange_redirect: "agent-login: grant exchange rejected redirect (HTTP {status})",
146
173
  exchange_failed: "agent-login: grant exchange failed (HTTP {status})",
147
174
  exchange_not_json: "agent-login: exchange response was not JSON",
@@ -154,7 +181,18 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
154
181
  },
155
182
  "zh-CN": {
156
183
  usagePrCreate: "用法:{cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
157
- usagePrRead: "用法:{cli} pr <list|view|diff|checks|comment> [参数]",
184
+ usagePrRead: "用法:{cli} pr <list|view|diff|checks|comment|approve|merge> [参数]",
185
+ usagePrApprove: "用法:{cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT](需要本人 GitHub 身份)",
186
+ usagePrMerge: "用法:{cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase](需要本人 GitHub 身份)",
187
+ prApproved: "已以 {actor} 身份批准 {repository}#{number}",
188
+ prMerged: "已以 {actor} 身份合并 {repository}#{number}({sha})",
189
+ prApproveRejected: "批准被拒绝。请检查人类会话、GitHub 绑定、仓库权限,以及 --head/--base。",
190
+ prMergeRejected: "合并被拒绝。请检查人类会话、GitHub 绑定、仓库权限、--head/--base 和可合并性。",
191
+ prApproveOutcomeUnknown: "批准结果不明。请先重读 PR 的 reviews,不要自动重发。",
192
+ prMergeOutcomeUnknown: "合并结果不明。请先重读 PR,不要自动重发。",
193
+ apiHumanPrincipal: "Agent 不能批准或合并。请使用绑定了 GitHub 的人类 STAMP_TOKEN 会话。",
194
+ apiWriteCoords: "请重读 PR,带上当前的 --head 和 --base 再试。",
195
+ apiGitHubBinding: "请先在 Stamp 设置里绑定 GitHub,再重试。",
158
196
  usagePrComment: "用法:{cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-)(需要本人 GitHub 身份)",
159
197
  prCommentBodyInvalid: "评论不能为空,UTF-8 文本最多 64 KiB。",
160
198
  prCommentCreated: "已以 {actor} 身份发表评论:{url}",
@@ -226,6 +264,8 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
226
264
  {cli} pr diff <编号|URL> --repo OWNER/REPO [--name-only]
227
265
  {cli} pr checks <编号|URL> --repo OWNER/REPO
228
266
  {cli} pr comment <编号|URL> --repo OWNER/REPO --body-file FILE|- (本人 GitHub 身份)
267
+ {cli} pr approve <编号|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (本人 GitHub 身份)
268
+ {cli} pr merge <编号|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (本人 GitHub 身份)
229
269
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
230
270
 
231
271
  {cli} follow <owner/repo> --kind issue|pull --number N
@@ -239,13 +279,22 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
239
279
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
240
280
 
241
281
  flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG`,
242
- usageRepoClone: "用法:{cli} repo clone <repository> [<directory>] [-- <gitflags>...]",
282
+ usageRepoClone: "用法:{cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
243
283
  cloned: "已从 {url} 克隆 {repository}",
244
284
  cloneFailed: "经 Stamp 网关克隆 {repository} 失败",
285
+ networkUnreachable: "无法连接 {base}({cause});检查实例地址(STAMP_URL)和网络后重试",
286
+ networkHostUnresolved: "{base} 解析不了({cause});检查实例地址(STAMP_URL)和 DNS 后重试",
287
+ cloneIdentityMissing: "{path} 没有 SSH 私钥:用 `{cli} key enroll` 登记一把(它读 {path}.pub),或用 --identity FILE 指到已有私钥",
288
+ cloneKnownHostsUnavailable: "{url} 返回 HTTP {status}:这个实例没有发布自己的 SSH 主机公钥,没有可钉的东西——用 --known-hosts FILE 指定,或设 STAMP_KNOWN_HOSTS",
289
+ cloneKnownHostsInvalid: "{url} 返回的不是可用的 known_hosts 行;拒绝钉它——检查实例,或用 --known-hosts FILE",
290
+ clonePublicKeyRejected: "网关拒绝了 {path} 这把钥(publickey)。如果它还没登记,先登记它的公钥:`{cli} key enroll --public-key {publicKey}`",
291
+ cloneIdentityPinned: "已把 Stamp 的 SSH 身份钉到 {directory}(git config core.sshCommand)",
292
+ cloneIdentityPinFailed: "无法把 SSH 身份写入 {directory};可手动执行:git -C {directory} config --local core.sshCommand \"{command}\"",
245
293
  loginHumanIntro: "当前不是受管 Raft Agent。人类和 CI 使用 STAMP_TOKEN:",
246
294
  loginHumanBrowser: " 浏览器:{url}/login (把会话 cookie 值设为 STAMP_TOKEN)",
247
295
  loginHumanCI: " CI: 由负责人签发的窄范围部署令牌",
248
- loginAgentReady: "Agent 登录就绪({service} @ {url});访问令牌有效至 {expires}",
296
+ loginAgentReady: "Agent 登录就绪({service} @ {url});访问令牌有效至 {expires}({remaining})",
297
+ loginTokenExpired: "Agent 已登录({service} @ {url}),但访问令牌已于 {expires} 过期({remaining});下一条命令会自动刷新",
249
298
  logoutForgot: "已忘记 Agent 会话 {path}",
250
299
  logoutNothing: "没有本地会话(人类/CI 通道使用 STAMP_TOKEN)",
251
300
  enrolled: "已登记 {fingerprint}({keyId})",
@@ -262,9 +311,14 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
262
311
  checkToken: "{cli}: 请检查 STAMP_TOKEN",
263
312
  notLoggedIn: "尚未登录:请运行 `{cli} login`(受管 Agent)",
264
313
  sessionOriginMismatch: "已存会话是给 {stored} 签发的,不是 {target}——请重新运行 `{cli} login`",
314
+ sessionOriginMismatchSibling: "已存会话是给 {stored} 签发的,不是 {target}——{stored} 对应的是 `{other}`,请改用它,而不是 `{cli}`",
265
315
  pair_mismatch: "拒绝不匹配的实例配对:{origin} 属于服务 {owner},而非 {service}(task #439)",
266
316
  stampTokenMissing: "未设置 STAMP_TOKEN(会话或部署令牌);在受管 Agent 内请运行 `{cli} login`",
267
- admission_partial: "拒绝运行:受管 Agent 环境不完整({reason});不会回退到 STAMP_TOKEN",
317
+ admissionPartial: "拒绝运行:受管 Agent 环境不完整({reason});不会回退到 STAMP_TOKEN",
318
+ admissionMissingVars: "拒绝运行:受管 Agent 环境不完整——{missing} 未设置,但 {present} 已设置;这不是人类/CI 环境,不会回退到 STAMP_TOKEN",
319
+ admissionInvalidAgentID: "拒绝运行:SLOCK_AGENT_ID={value} 不是合法的 agent id;请修好受管 Agent 环境——不会回退到 STAMP_TOKEN",
320
+ admissionRaftWrapper: "拒绝运行:受管 Agent 的 raft 包装脚本缺失或不可执行({path});请修好受管 Agent 环境——不会回退到 STAMP_TOKEN",
321
+ keyPublicKeyMissing: "{path} 没有 SSH 公钥:用 `ssh-keygen -t ed25519 -f {private}` 生成一把,或用 --public-key FILE 指定",
268
322
  invoke_not_json: "agent-login: `raft integration invoke` 没有返回 JSON",
269
323
  invoke_not_object: "agent-login: invoke 输出不是对象",
270
324
  invoke_failed: "agent-login: invoke 未成功",
@@ -293,7 +347,7 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
293
347
  session_refresh_expired: "agent-login: 会话刷新令牌已经过期",
294
348
  token_size_limit: "agent-login: 令牌响应超过大小限制",
295
349
  token_deadline: "agent-login: 令牌端点超过时限",
296
- invoke_exit: "agent-login: raft invoke 以非零状态退出({status})",
350
+ invoke_exit: "agent-login: raft invoke 失败({status}):{diagnostic}",
297
351
  exchange_redirect: "agent-login: 授权兑换拒绝跟随重定向(HTTP {status})",
298
352
  exchange_failed: "agent-login: 授权兑换失败(HTTP {status})",
299
353
  exchange_not_json: "agent-login: 兑换响应不是 JSON",
@@ -317,23 +371,37 @@ export function selectLocale(env = process.env, explicit) {
317
371
  // the binary the reader actually invoked — a staging user must never be told to
318
372
  // run `stamp` (@phage: the error surface reaches users before the docs).
319
373
  // Product names ("Stamp"), the package id and historical facts are NOT `{cli}`.
320
- let cliName = "stamp";
374
+ //
375
+ // FAIL-LOUD (@Tenny): the value starts UNSET. A silent `"stamp"` default would
376
+ // mean that if the entry never set the name, a staging user would quietly be
377
+ // shown the PRODUCTION binary — the exact defect shape this task fixes. An unset
378
+ // name renders as a conspicuous marker (and prefix() throws in a test), so a
379
+ // broken parameter chain is a VISIBLE failure, never a plausible wrong value.
380
+ let cliName = null;
321
381
 
322
382
  export function setCliName(name) {
323
383
  if (typeof name === "string" && name.length > 0) cliName = name;
324
384
  }
325
385
 
386
+ /** For tests/diagnostics: the resolved entry binary, or null if never set. */
387
+ export function currentCliName() {
388
+ return cliName;
389
+ }
390
+
326
391
  /** The `<binary>:` banner that prefixes user-facing diagnostics. It names the
327
392
  * binary the user actually ran, so a staging user sees `stamp-staging:` and not
328
393
  * the production name (task #444 / #439). */
329
394
  export function prefix() {
330
- return `${cliName}: `;
395
+ // An unset name is a programming error: fail loudly rather than printing a
396
+ // plausible-but-wrong production banner on a staging entry.
397
+ const name = cliName ?? "<cli-unset>";
398
+ return `${name}: `;
331
399
  }
332
400
 
333
401
  export function t(locale, key, vars = {}) {
334
402
  const table = messages[locale] || messages.en;
335
403
  let s = table[key] || messages.en[key] || key;
336
- const all = { cli: cliName, ...vars };
404
+ const all = { cli: cliName ?? "<cli-unset>", ...vars };
337
405
  for (const [k, v] of Object.entries(all)) s = s.replaceAll(`{${k}}`, String(v));
338
406
  return s;
339
407
  }
package/lib/main.mjs CHANGED
@@ -1,80 +1,37 @@
1
- import { readFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
1
  import { createRequire } from "node:module";
2
+ import { basename } from "node:path";
5
3
  import { resolveAuth } from "./auth.mjs";
6
4
  import { makeClient, ApiError } from "./client.mjs";
7
- import { runAgentLogin } from "./agent-login.mjs";
8
- import { basename } from "node:path";
9
5
  import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
10
- import { pullRequestInput, pullRequestRecovery } from "./pull-request.mjs";
11
- import { parsePRCommentArgs, validatePRCommentResult } from "./pr-comment.mjs";
12
- import {
13
- formatPRChecks,
14
- formatPRDetail,
15
- formatPRDiff,
16
- formatPRList,
17
- formatPRListSections,
18
- parsePRDiffArgs,
19
- parsePRListArgs,
20
- parsePRTargetArgs,
21
- prChecksExitCode,
22
- prDetailPath,
23
- PR_SECTIONS,
24
- prDiffPath,
25
- prSection,
26
- safeInline,
27
- validatePRDetail,
28
- validatePRDiff,
29
- validatePRListResponse,
30
- } from "./pr-read.mjs";
31
- import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone } from "./repo-clone.mjs";
32
- import { apiErrorGuidance, presentError } from "./errors.mjs";
33
-
34
- function sectionLabels(locale) {
35
- const labels = {};
36
- for (const name of Object.values(PR_SECTIONS)) labels[`prSection_${name}`] = t(locale, `prSection_${name}`);
37
- return labels;
38
- }
6
+ import { presentError, printGatewayError } from "./errors.mjs";
7
+ import * as session from "./commands/session.mjs";
8
+ import * as key from "./commands/key.mjs";
9
+ import * as identity from "./commands/identity.mjs";
10
+ import * as receipt from "./commands/receipt.mjs";
11
+ import * as repo from "./commands/repo.mjs";
12
+ import * as pr from "./commands/pr.mjs";
13
+ import * as subscribe from "./commands/subscribe.mjs";
39
14
 
40
15
  const require = createRequire(import.meta.url);
41
16
  const pkg = require("../package.json");
42
17
 
43
- function takeFlag(args, name, dflt) {
44
- const i = args.indexOf(`--${name}`);
45
- if (i === -1) return dflt;
46
- const v = args[i + 1];
47
- args.splice(i, 2);
48
- return v;
49
- }
50
-
51
- function readPublicKey(path) {
52
- if (path === "-") return readFileSync(0, "utf8").trim();
53
- return readFileSync(path, "utf8").trim();
54
- }
55
-
56
- function objectArgs(args, locale) {
57
- const repository = args.shift();
58
- const rawKind = takeFlag(args, "kind");
59
- // Keep the concise user-facing `pull` spelling while sending the gateway's
60
- // canonical GitHubObjectKind on the wire. Also accept the canonical spelling
61
- // for scripts that already learned it from a response/event payload.
62
- const kind = rawKind === "pull" ? "pull_request" : rawKind;
63
- const number = Number(takeFlag(args, "number"));
64
- if (!repository || !["issue", "pull_request"].includes(kind) || !Number.isInteger(number) || number <= 0) {
65
- throw new Error(t(locale, "usageFollow"));
66
- }
67
- return { repository, kind, number };
68
- }
69
-
70
- function emitApiGuidance(error, locale, write) {
71
- const guidance = apiErrorGuidance(locale, error.body);
72
- if (guidance.code && guidance.code !== error.body?.error) write(`${prefix()}${guidance.code}`);
73
- if (guidance.action) write(`${prefix()}${guidance.action}`);
74
- // A typed code without a known/bounded action is not enough to suppress a
75
- // command-specific fallback (for example PR head-drift guidance).
76
- return Boolean(guidance.action);
77
- }
18
+ const commands = {
19
+ login: session.login,
20
+ logout: session.logout,
21
+ whoami: session.whoami,
22
+ "migration-help": session.migrationHelp,
23
+ key: key.run,
24
+ identity: identity.run,
25
+ receipt: receipt.run,
26
+ repo: repo.run,
27
+ pr: pr.run,
28
+ follow: subscribe.follow,
29
+ unfollow: subscribe.follow,
30
+ subscription: subscribe.subscription,
31
+ subscriptions: subscribe.subscriptions,
32
+ watch: subscribe.watch,
33
+ unwatch: subscribe.watch,
34
+ };
78
35
 
79
36
  export async function main(argv, opts) {
80
37
  const args = [...argv];
@@ -82,8 +39,7 @@ export async function main(argv, opts) {
82
39
  const err = opts.stderr ?? ((s) => console.error(s));
83
40
  const env = opts.env ?? process.env;
84
41
  const exit = opts.exit ?? ((code) => process.exit(code));
85
- // Global flags are options, never values of --title/--body/etc.
86
- const localValues = new Set(["--public-key", "--email", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "-b", "-F", "-R"]);
42
+ const localValues = new Set(["--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "--method", "-b", "-F", "-R"]);
87
43
  let json = false, langFlag, help = false, version = false;
88
44
  const commandArgs = [];
89
45
  for (let i = 0; i < args.length; i++) {
@@ -99,12 +55,8 @@ export async function main(argv, opts) {
99
55
  }
100
56
  args.splice(0, args.length, ...commandArgs);
101
57
  const locale = selectLocale(env, langFlag);
102
- // The binary that targets THIS instance; every user-visible command reference
103
- // follows it (usage, guidance, recovery). Derived from the invoked file so
104
- // `stamp-staging` names itself — the error surface reaches users before docs.
105
- const cliName = opts.cliName
106
- ?? (opts.argv1 ? basename(opts.argv1).replace(/\.mjs$/, "") : "stamp");
107
- setCliName(cliName);
58
+ const cliName = opts.cliName ?? (opts.argv1 ? basename(opts.argv1).replace(/\.mjs$/, "") : undefined);
59
+ if (cliName !== undefined) setCliName(cliName);
108
60
  if (version) { out(pkg.version); return exit(0); }
109
61
  const cmd = args.shift();
110
62
  if (help || !cmd) { out(t(locale, "usage", { version: pkg.version })); return exit(0); }
@@ -117,236 +69,21 @@ export async function main(argv, opts) {
117
69
  err(`${prefix()}${presentError(locale, e)}`);
118
70
  return exit(1);
119
71
  }
120
- const api = makeClient(auth, opts.fetchImpl);
72
+ const api = makeClient(auth, opts.fetchImpl, {
73
+ readRetries: opts.networkReadRetries, retryDelayMs: opts.networkRetryDelayMs, sleep: opts.sleep,
74
+ });
75
+ const handler = commands[cmd];
76
+ if (!handler) {
77
+ out(t(locale, "usage", { version: pkg.version }));
78
+ return exit(1);
79
+ }
121
80
 
122
81
  try {
123
- switch (cmd) {
124
- case "login": {
125
- if (auth.mode !== "agent") {
126
- out(t(locale, "loginHumanIntro"));
127
- out(t(locale, "loginHumanBrowser", { url: auth.apiBase }));
128
- out(t(locale, "loginHumanCI"));
129
- return exit(0);
130
- }
131
- const login = opts.loginImpl ?? runAgentLogin;
132
- const session = await login(auth.agentEnv, auth.apiBase, { service: auth.service, fetchImpl: opts.fetchImpl });
133
- emit({ ok: true, service: auth.service, api_base: auth.apiBase, access_expires_at: session.access_expires_at },
134
- () => out(t(locale, "loginAgentReady", { service: auth.service, url: auth.apiBase, expires: session.access_expires_at })));
135
- return exit(0);
136
- }
137
- case "logout": {
138
- const p = auth.logout();
139
- out(p ? t(locale, "logoutForgot", { path: p }) : t(locale, "logoutNothing"));
140
- return exit(0);
141
- }
142
- case "whoami": {
143
- const me = await api("GET", "/v1/me");
144
- emit(me, () => out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${auth.apiBase}`));
145
- return exit(0);
146
- }
147
- case "migration-help": {
148
- const fetchImpl = opts.fetchImpl ?? fetch;
149
- const res = await fetchImpl(`${auth.apiBase}/v1/migration-help`, {
150
- headers: { "accept-language": locale === "zh-CN" ? "zh-CN" : "en" },
151
- });
152
- const d = await res.json();
153
- emit(d, () => {
154
- out(t(locale, "helpInstall", { cmds: (d.install ?? []).join(" ; ") }));
155
- out(t(locale, "helpAgentLogin", { text: d.login?.agent ?? "" }));
156
- for (const [from, to] of Object.entries(d.actions_to_cli ?? {})) {
157
- const note = d.notes?.[from];
158
- out(note ? ` ${from} → ${to} (${note})` : ` ${from} → ${to}`);
159
- }
160
- });
161
- return exit(0);
162
- }
163
- case "key": {
164
- const sub = args.shift();
165
- if (sub !== "enroll") throw new Error(t(locale, "usageKeyEnroll"));
166
- const keyPath = takeFlag(args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
167
- const publicKey = readPublicKey(keyPath);
168
- const d = await api("POST", "/v1/keys", { publicKey });
169
- emit(d, () => out(t(locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId })));
170
- return exit(0);
171
- }
172
- case "identity": {
173
- const sub = args.shift();
174
- if (sub !== "bind") throw new Error(t(locale, "usageIdentityBind"));
175
- const agentEmail = takeFlag(args, "email");
176
- if (!agentEmail) throw new Error(t(locale, "usageIdentityBind"));
177
- const d = await api("POST", "/v1/identities", { agentEmail });
178
- emit(d, () => out(t(locale, "bound", { email: d.agentEmail })));
179
- return exit(0);
180
- }
181
- case "receipt": {
182
- const sub = args.shift();
183
- const id = args.shift();
184
- if (sub !== "get" || !id) throw new Error(t(locale, "usageReceiptGet"));
185
- const d = await api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
186
- emit(d, () => out(`${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`));
187
- return exit(0);
188
- }
189
- case "repo": {
190
- if (args.shift() !== "clone") throw new Error(t(locale, "usageRepoClone"));
191
- const parsed = parseRepoCloneArgs(args);
192
- if (!parsed) throw new Error(t(locale, "usageRepoClone"));
193
- const me = await api("GET", "/v1/me");
194
- const defaultOwner = me?.github?.login;
195
- const repo = parseRepository(parsed.repository, defaultOwner);
196
- if (!repo) throw new Error(t(locale, "usageRepoClone"));
197
- const url = gatewayCloneURL(me.sshHost, me.sshPort, repo.owner, repo.name);
198
- const git = opts.gitCloneImpl ?? runGitClone;
199
- const result = await git({
200
- url,
201
- directory: parsed.directory,
202
- gitFlags: parsed.gitFlags,
203
- env: opts.gitEnv ?? env,
204
- });
205
- if (result.code !== 0) {
206
- if (result.stderr) err(result.stderr.trimEnd());
207
- throw new Error(t(locale, "cloneFailed", { repository: `${repo.owner}/${repo.name}` }));
208
- }
209
- if (result.stderr) err(result.stderr.trimEnd());
210
- emit(
211
- { ok: true, repository: `${repo.owner}/${repo.name}`, url, directory: parsed.directory ?? repo.name },
212
- () => out(t(locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url })),
213
- );
214
- return exit(0);
215
- }
216
- case "pr": {
217
- const sub = args.shift();
218
- if (sub === "comment") {
219
- const input = parsePRCommentArgs(args);
220
- try {
221
- const result = validatePRCommentResult(await api("POST", input.path, input.body), input.target);
222
- emit(result, () => out(t(locale, "prCommentCreated", { url: result.url, actor: result.actorLogin })));
223
- } catch (e) {
224
- // A lost/malformed success response may conceal a completed write.
225
- // Never retry this command automatically or print submitted body.
226
- err(`${prefix()}${t(locale, e instanceof ApiError && e.status >= 400 && e.status < 500 ? "prCommentRejected" : "prCommentOutcomeUnknown")}`);
227
- if (e instanceof ApiError) emitApiGuidance(e, locale, err);
228
- return exit(1);
229
- }
230
- return exit(0);
231
- }
232
- if (sub === "create") {
233
- const input = pullRequestInput(args);
234
- try {
235
- const d = await api("POST", "/v1/pull-requests", input);
236
- emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
237
- } catch (e) {
238
- if (e instanceof ApiError && e.status !== 401) {
239
- err(`${prefix()}${e.message}`);
240
- if (!emitApiGuidance(e, locale, err)) err(t(locale, pullRequestRecovery(e.body?.error)));
241
- return exit(1);
242
- }
243
- throw e;
244
- }
245
- return exit(0);
246
- }
247
- if (sub === "list" || sub === "ls") {
248
- const { path, sections } = parsePRListArgs(args);
249
- const paged = path.includes("limit=");
250
- const d = validatePRListResponse(await api("GET", path), paged);
251
- const labels = {
252
- statusUnavailable: t(locale, "prStatusUnavailable"),
253
- ci: t(locale, "prCIShort"),
254
- agent: t(locale, "prAgentShort"),
255
- ...sectionLabels(locale),
256
- };
257
- emit(
258
- // The derived section is OPT-IN: a bare `--json` stays byte/structure
259
- // back-compatible with the pre-section envelope, so a strict consumer
260
- // never meets an unknown key. Only an explicit `--sections` adds it.
261
- sections
262
- ? { ...d, items: d.items.map((item) => ({ ...item, section: prSection(item) })) }
263
- : d,
264
- () => {
265
- const lines = sections ? formatPRListSections(d, labels) : formatPRList(d, labels);
266
- if (lines.length === 0) out(t(locale, "prListEmpty"));
267
- else for (const line of lines) out(line);
268
- // Surface the pagination continuation (a present cursor is never
269
- // an error — it means "there is more"). The cursor is an untrusted
270
- // wire string: strip terminal control sequences before writing it
271
- // (the JSON path keeps the verified raw value).
272
- if (d.nextCursor) out(t(locale, "prListMore", { cursor: safeInline(d.nextCursor) }));
273
- },
274
- );
275
- return exit(0);
276
- }
277
- if (sub === "view") {
278
- const target = parsePRTargetArgs(args, "usagePrView");
279
- const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
280
- emit(d, () => {
281
- for (const line of formatPRDetail(d, {
282
- head: t(locale, "prHeadLabel"),
283
- checks: t(locale, "prChecksLabel"),
284
- review: t(locale, "prReviewLabel"),
285
- })) out(line);
286
- });
287
- return exit(0);
288
- }
289
- if (sub === "diff") {
290
- const target = parsePRDiffArgs(args);
291
- const d = validatePRDiff(await api("GET", prDiffPath(target)), target);
292
- emit(d, () => {
293
- const chunks = formatPRDiff(d, target.nameOnly, t(locale, "prDiffUnavailable"));
294
- if (chunks.length === 0) out(t(locale, "prDiffEmpty"));
295
- else out(chunks.join("\n"));
296
- });
297
- return exit(0);
298
- }
299
- if (sub === "checks") {
300
- const target = parsePRTargetArgs(args, "usagePrChecks");
301
- const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
302
- emit(d.checks, () => {
303
- const lines = formatPRChecks(d);
304
- if (lines.length === 0) out(t(locale, "prChecksEmpty"));
305
- else for (const line of lines) out(line);
306
- });
307
- return exit(prChecksExitCode(d));
308
- }
309
- throw new Error(t(locale, "usagePrRead"));
310
- }
311
- case "follow":
312
- case "unfollow": {
313
- const body = objectArgs(args, locale);
314
- const path = cmd === "follow" ? "/v1/subscriptions/objects/follow" : "/v1/subscriptions/objects/unfollow";
315
- const d = await api("POST", path, body);
316
- emit(d, () => out(JSON.stringify(d)));
317
- return exit(0);
318
- }
319
- case "subscription": {
320
- const sub = args.shift();
321
- if (sub !== "pause" && sub !== "resume") throw new Error(t(locale, "usageSubscription"));
322
- const body = objectArgs(args, locale);
323
- const d = await api("POST", `/v1/subscriptions/objects/${sub}`, body);
324
- emit(d, () => out(JSON.stringify(d)));
325
- return exit(0);
326
- }
327
- case "subscriptions": {
328
- const d = await api("GET", "/v1/subscriptions");
329
- emit(d, () => out(JSON.stringify(d, null, 2)));
330
- return exit(0);
331
- }
332
- case "watch":
333
- case "unwatch": {
334
- const repository = args.shift();
335
- const eventType = takeFlag(args, "event");
336
- if (!repository || !eventType) throw new Error(t(locale, "usageWatch", { cmd }));
337
- const path = cmd === "watch" ? "/v1/subscriptions/repositories/subscribe" : "/v1/subscriptions/repositories/unsubscribe";
338
- const d = await api("POST", path, { repository, eventType });
339
- emit(d, () => out(JSON.stringify(d)));
340
- return exit(0);
341
- }
342
- default:
343
- out(t(locale, "usage", { version: pkg.version }));
344
- return exit(cmd ? 1 : 0);
345
- }
82
+ return await handler({ cmd, args, api, auth, locale, emit, out, err, exit, env, opts });
346
83
  } catch (e) {
347
84
  if (e instanceof ApiError) {
348
85
  err(`${prefix()}${e.message}`);
349
- emitApiGuidance(e, locale, err);
86
+ printGatewayError(e, err);
350
87
  if (e.status === 401) err(auth.mode === "agent" ? t(locale, "sessionRejected") : t(locale, "checkToken"));
351
88
  return exit(1);
352
89
  }
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { AgentError } from "./errors.mjs";
3
- import { parsePRTargetArgs, prDetailPath } from "./pr-read.mjs";
2
+ import { AgentError } from "../errors.mjs";
3
+ import { parsePRTargetArgs, prDetailPath } from "./read.mjs";
4
4
 
5
5
  export function parsePRCommentArgs(input) {
6
6
  const targetArgs = [], flags = new Map();
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
- import { AgentError } from "./errors.mjs";
3
+ import { AgentError } from "../errors.mjs";
4
4
 
5
5
  const names = new Set(["receipt", "repo", "head", "sha", "base", "title", "body", "body-file", "idempotency-key"]);
6
6