@botiverse/stamp-cli 0.3.10 → 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 CHANGED
@@ -140,7 +140,14 @@ 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
- const usableStore = storeMatchesOrigin(store, apiBase) ? store : undefined;
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",
@@ -152,6 +159,7 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
152
159
  // Never ~/.ssh or ~/.stamp, which every agent on a machine user shares.
153
160
  stateDir: dirname(agentAuthPath(a, service)),
154
161
  async token() {
162
+ refreshStore();
155
163
  if (!usableStore) {
156
164
  if (storedOriginElsewhere !== null) {
157
165
  const sibling = siblingBinaryFor(storedOriginElsewhere);
@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";
2
2
  import { t } from "../locale.mjs";
3
3
  import { resolve } from "node:path";
4
4
  import { takeFlag, readPublicKey } from "../flags.mjs";
5
- import { recordIdentity } from "../repo/identities.mjs";
5
+ import { readRecordedIdentity, recordIdentity } from "../repo/identities.mjs";
6
6
  import { defaultIdentityPath } from "../repo/ssh.mjs";
7
7
  import { mkdirSync } from "node:fs";
8
8
  import { dirname } from "node:path";
@@ -18,6 +18,30 @@ function generateAgentKey(path, agentId) {
18
18
  }
19
19
  }
20
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
+ }
44
+
21
45
  export async function run(ctx) {
22
46
  const sub = ctx.args.shift();
23
47
  if (sub === "list") {
@@ -1,9 +1,10 @@
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();
@@ -21,6 +22,10 @@ export async function run(ctx) {
21
22
  // The clone carries the enrolled identity and the gateway's published host
22
23
  // key itself (task #475): a bare clone must not fail with publickey, and it
23
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
+ }
24
29
  const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
25
30
  const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
26
31
  if (!existsSync(identityPath)) {
@@ -60,9 +65,11 @@ export async function run(ctx) {
60
65
  // Make later git operations in this checkout work without any export.
61
66
  const directory = parsed.directory ?? repo.name;
62
67
  const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
68
+ const commitEmail = await setCommitIdentity(ctx, me, directory);
63
69
  ctx.emit(
64
- { 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 },
65
71
  () => {
72
+ if (commitEmail) ctx.out(t(ctx.locale, "repoCommitEmailSet", { email: commitEmail, directory }));
66
73
  ctx.out(t(ctx.locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url }));
67
74
  // The commit rules this gateway enforces, stated once up front (task #549):
68
75
  // a pusher should not meet them for the first time as a refusal.
@@ -89,6 +96,10 @@ async function use(ctx) {
89
96
  const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
90
97
  const directory = ctx.args.shift() ?? ".";
91
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
+ }
92
103
  const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
93
104
  const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
94
105
  if (!existsSync(identityPath)) {
@@ -109,8 +120,11 @@ async function use(ctx) {
109
120
  if (!pinned.ok) {
110
121
  throw new Error(t(ctx.locale, "repoUseFailed", { directory, detail: (pinned.stderr ?? "").trim() }));
111
122
  }
112
- ctx.emit({ directory, identityPath, knownHostsPath, sshCommand }, () => {
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 }, () => {
113
126
  ctx.out(t(ctx.locale, "repoUseDone", { directory, path: identityPath }));
127
+ if (commitEmail) ctx.out(t(ctx.locale, "repoCommitEmailSet", { email: commitEmail, directory }));
114
128
  });
115
129
  return ctx.exit(0);
116
130
  }
@@ -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
 
package/lib/locale.mjs CHANGED
@@ -209,6 +209,9 @@ docs: {docs} (the agent workflow, step by step)`,
209
209
  usageRepoUse: "usage: {cli} repo use [DIR] [--identity KEY] [--known-hosts FILE]",
210
210
  repoUseDone: "{directory}: git now reaches Stamp with this agent's key {path} (set in this repository only)",
211
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)",
212
215
  keyGenerated: "created this agent's own SSH key: {path} (kept in the agent's directory, not ~/.ssh)",
213
216
  enrolled: "enrolled {fingerprint} ({keyId})",
214
217
  enrolledIdentityRecorded: "`{cli} repo clone` on this machine will use {path}",
@@ -499,6 +502,9 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
499
502
  usageRepoUse: "用法:{cli} repo use [目录] [--identity KEY] [--known-hosts FILE]",
500
503
  repoUseDone: "{directory}:git 现在用这个 agent 自己的 key {path} 连 Stamp(只设在这个仓库里)",
501
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}(只设在这个仓库里)",
502
508
  keyGenerated: "已为这个 agent 生成自己的 SSH key:{path}(放在 agent 自己的目录里,不在 ~/.ssh)",
503
509
  enrolled: "已登记 {fingerprint}({keyId})",
504
510
  enrolledIdentityRecorded: "这台机器上的 `{cli} repo clone` 会使用 {path}",
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.10",
3
+ "version": "0.3.11",
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",