@botiverse/stamp-cli 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -0
- package/bin/stamp-staging.mjs +1 -0
- package/bin/stamp.mjs +61 -5
- package/lib/agent-refresh.mjs +17 -4
- package/lib/auth.mjs +103 -4
- package/lib/errors.mjs +43 -0
- package/lib/locale.mjs +182 -59
- package/lib/main.mjs +174 -20
- package/lib/pr-comment.mjs +39 -0
- package/lib/pr-read.mjs +429 -0
- package/lib/repo-clone.mjs +60 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -6,12 +6,20 @@ admission, atomic 0600 `auth.json`). Future public origin: `stamp.build`.
|
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
8
|
npm i -g @botiverse/stamp-cli
|
|
9
|
+
# One-shot staging use must name the executable because the package has two bins.
|
|
10
|
+
npx --yes --package @botiverse/stamp-cli stamp-staging --help
|
|
9
11
|
stamp login
|
|
10
12
|
stamp key enroll
|
|
11
13
|
stamp identity bind --email agent@example.com
|
|
14
|
+
stamp repo clone org/repo
|
|
12
15
|
git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/my-change
|
|
13
16
|
stamp receipt get <id>
|
|
14
17
|
stamp pr create --receipt <published-id> --repo org/repo --head agent/my-change --sha <exact-sha> --base main --title "My change" --body-file ./pr-body.md
|
|
18
|
+
stamp pr list
|
|
19
|
+
stamp pr view 123 --repo org/repo
|
|
20
|
+
stamp pr diff 123 --repo org/repo
|
|
21
|
+
stamp pr checks 123 --repo org/repo
|
|
22
|
+
stamp pr comment 123 --repo org/repo --body-file ./comment.md
|
|
15
23
|
```
|
|
16
24
|
|
|
17
25
|
- Agent: `stamp login` (PKCE grant via `raft integration invoke --action agent-login`)
|
|
@@ -43,6 +51,45 @@ expanded to `refs/heads/...`; full refs also work. Use `--body-file -` for stdin
|
|
|
43
51
|
`--body` for inline text. A non-empty description is required. `--json` prints the
|
|
44
52
|
service receipt; a denial exits nonzero with recovery guidance.
|
|
45
53
|
|
|
54
|
+
The read-only PR commands follow the familiar `gh pr` command group while
|
|
55
|
+
reading through Stamp rather than a local GitHub credential:
|
|
56
|
+
|
|
57
|
+
- `stamp pr list` lists every PR that the current Agent created through Stamp.
|
|
58
|
+
Filtering and pagination are intentionally not advertised until the service
|
|
59
|
+
implements them.
|
|
60
|
+
- `stamp pr view`, `stamp pr diff`, and `stamp pr checks` accept a PR URL or a
|
|
61
|
+
number with `--repo OWNER/REPO` (`-R` also works).
|
|
62
|
+
- `stamp pr diff --name-only` prints only paths. `stamp pr checks` exits `8`
|
|
63
|
+
while checks are pending and `1` when a terminal check failed or no checks
|
|
64
|
+
are reported, matching the useful `gh pr checks` automation convention.
|
|
65
|
+
- `--json` returns the service's validated machine envelope. Human-formatted
|
|
66
|
+
output strips terminal control characters from provider-authored text.
|
|
67
|
+
|
|
68
|
+
### Ordinary PR comments
|
|
69
|
+
|
|
70
|
+
`stamp pr comment 123 -R org/repo --body-file ./comment.md` uses a **human Stamp
|
|
71
|
+
session with a bound GitHub account**, and posts as that GitHub user. Agent
|
|
72
|
+
sessions are rejected; there is no fallback to an App or another person's token.
|
|
73
|
+
The existing human session authentication applies; this command does not create
|
|
74
|
+
a new login flow. The web inbox does not yet provide a comment composer.
|
|
75
|
+
|
|
76
|
+
Use `--body TEXT` (`-b`) or `--body-file FILE` (`-F`); `--body-file -` reads stdin
|
|
77
|
+
and preserves paragraphs. A PR URL can replace the number/repository pair.
|
|
78
|
+
Comments must be nonempty and at most 64 KiB of UTF-8 text. Closed or merged PRs
|
|
79
|
+
can still receive comments. This is an ordinary conversation comment, not a
|
|
80
|
+
review, inline code comment, approval or merge.
|
|
81
|
+
|
|
82
|
+
GitHub must permit the bound user's token to create comments; its
|
|
83
|
+
[issue-comment API](https://docs.github.com/en/rest/issues/comments#create-an-issue-comment)
|
|
84
|
+
accepts GitHub App user tokens with Issues or Pull requests write permission.
|
|
85
|
+
Stamp's existing repository visibility checks also apply.
|
|
86
|
+
|
|
87
|
+
Success prints the confirmed comment URL and GitHub actor; `--json` includes
|
|
88
|
+
`repository`, `number`, `commentId`, `url` and `actorLogin`. Each explicit command
|
|
89
|
+
is a new send, with no persistent deduplication. Neither CLI nor provider adapter
|
|
90
|
+
automatically resends a comment. If a response is lost or cannot be validated,
|
|
91
|
+
the command exits nonzero and asks you to inspect the PR before sending again.
|
|
92
|
+
|
|
46
93
|
The Raft manifest exposes only `agent-login`. Key enrollment, identity binding,
|
|
47
94
|
receipt reads, PR creation and subscriptions all use this CLI; the HTTP APIs
|
|
48
95
|
remain available to service clients. `stamp migration-help` maps retired action
|
package/bin/stamp-staging.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { STAMP_DEFAULT_URL } from "../lib/agent-login.mjs";
|
|
|
8
8
|
const URL_BASE = process.env.STAMP_URL || STAMP_DEFAULT_URL;
|
|
9
9
|
|
|
10
10
|
await main(process.argv.slice(2), {
|
|
11
|
+
argv1: process.argv[1],
|
|
11
12
|
urlBase: URL_BASE,
|
|
12
13
|
urlExplicit: Boolean(process.env.STAMP_URL),
|
|
13
14
|
serviceDefault: "raft-git-gateway-staging",
|
package/bin/stamp.mjs
CHANGED
|
@@ -1,9 +1,65 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// stamp — CLI for the Agent Git gateway.
|
|
3
|
-
//
|
|
2
|
+
// stamp — CLI for the Agent Git gateway, targeting the PRODUCTION instance.
|
|
3
|
+
//
|
|
4
|
+
// Task #439: the production service slug and the default origin used to be
|
|
5
|
+
// resolved INDEPENDENTLY (lib/agent-login.mjs: STAMP_SERVICE="stamp" while the
|
|
6
|
+
// default URL was the staging origin). Once the production `stamp` service was
|
|
7
|
+
// registered, an unconfigured `stamp login` became a prod-slug + staging-origin
|
|
8
|
+
// pair — a wrong-environment target.
|
|
9
|
+
//
|
|
10
|
+
// The instance is pinned as a COHERENT PAIR (prod slug + prod origin) and the
|
|
11
|
+
// pair is defended. The defense compares the PARSED ORIGIN, not the raw string:
|
|
12
|
+
// `https://staging.stamp.build/` (trailing slash), `HTTPS://STAGING.STAMP.BUILD`
|
|
13
|
+
// and an explicit `:443` are the same origin and must be refused just the same.
|
|
4
14
|
import { main } from "../lib/main.mjs";
|
|
5
|
-
import { STAMP_DEFAULT_URL } from "../lib/agent-login.mjs";
|
|
6
15
|
|
|
7
|
-
const
|
|
16
|
+
const PROD_URL = "https://stamp.build";
|
|
17
|
+
const PROD_SERVICE = "stamp";
|
|
18
|
+
const STAGING_URL = "https://staging.stamp.build";
|
|
19
|
+
const STAGING_SERVICE = "raft-git-gateway-staging";
|
|
8
20
|
|
|
9
|
-
|
|
21
|
+
// Canonical origin of a URL, or null when it is not an absolute http(s) URL.
|
|
22
|
+
function originOf(value) {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = new URL(value);
|
|
25
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
26
|
+
return parsed.origin; // lowercases host, drops default port + path/query
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Canonical origin -> the service slug that owns it.
|
|
33
|
+
//
|
|
34
|
+
// SUPPORT BOUNDARY: this map lists the instances the CLI KNOWS. The pairing
|
|
35
|
+
// invariant can only be enforced where the origin<->service mapping is known;
|
|
36
|
+
// a self-hosted instance is not covered (the CLI has no general way to learn
|
|
37
|
+
// its mapping). Do not describe the guarantee as universal.
|
|
38
|
+
const KNOWN_INSTANCES = new Map([
|
|
39
|
+
[originOf(PROD_URL), PROD_SERVICE],
|
|
40
|
+
[originOf(STAGING_URL), STAGING_SERVICE],
|
|
41
|
+
]);
|
|
42
|
+
const originService = KNOWN_INSTANCES;
|
|
43
|
+
|
|
44
|
+
const url = process.env.STAMP_URL || PROD_URL;
|
|
45
|
+
const urlOrigin = originOf(url);
|
|
46
|
+
const owner = urlOrigin === null ? undefined : originService.get(urlOrigin);
|
|
47
|
+
|
|
48
|
+
// The instance this invocation targets. An explicit STAMP_SERVICE must match the
|
|
49
|
+
// origin's owner; otherwise derive it (a non-default origin needs its slug).
|
|
50
|
+
const requested = process.env.STAMP_SERVICE;
|
|
51
|
+
if (owner !== undefined && requested !== undefined && requested !== owner) {
|
|
52
|
+
process.stderr.write(
|
|
53
|
+
`stamp: STAMP_URL=${url} belongs to service ${owner}, not ${requested} — refusing to pair them (task #439).\n` +
|
|
54
|
+
"Set both explicitly for a non-default instance, or use `stamp-staging` for staging.\n",
|
|
55
|
+
);
|
|
56
|
+
process.exit(2);
|
|
57
|
+
}
|
|
58
|
+
const service = requested ?? owner ?? PROD_SERVICE;
|
|
59
|
+
|
|
60
|
+
await main(process.argv.slice(2), {
|
|
61
|
+
argv1: process.argv[1],
|
|
62
|
+
urlBase: url,
|
|
63
|
+
urlExplicit: Boolean(process.env.STAMP_URL),
|
|
64
|
+
serviceDefault: service,
|
|
65
|
+
});
|
package/lib/agent-refresh.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { randomBytes } from "node:crypto";
|
|
|
7
7
|
import { agentAuthPath, writeAgentSession } from "@botiverse/agent-session-store";
|
|
8
8
|
import { parseAgentSession, readBoundedText, STAMP_SERVICE } from "./agent-login.mjs";
|
|
9
9
|
import { AgentError, agentFail } from "./errors.mjs";
|
|
10
|
+
import { storeMatchesOrigin } from "./auth.mjs";
|
|
10
11
|
|
|
11
12
|
export const REFRESH_SKEW_MS = 60_000;
|
|
12
13
|
const REFRESH_DEADLINE_MS = 20_000;
|
|
@@ -78,7 +79,9 @@ export async function getFreshAgentAccessToken(a, opts = {}) {
|
|
|
78
79
|
const now = opts.now ?? Date.now();
|
|
79
80
|
const store = readStore(a, service);
|
|
80
81
|
if (!store) return null;
|
|
81
|
-
|
|
82
|
+
// Task #439: never use a store issued for a different origin than the target.
|
|
83
|
+
if (!storeMatchesOrigin(store, opts.apiBase ?? store.api_base)) return null;
|
|
84
|
+
if (storeMatchesOrigin(store, opts.apiBase ?? store.api_base) && !accessExpiresWithinSkew(store, now)) return store.access_token;
|
|
82
85
|
return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, false, opts.deadlineMs ?? REFRESH_DEADLINE_MS, undefined, opts.apiBase);
|
|
83
86
|
}
|
|
84
87
|
|
|
@@ -87,7 +90,8 @@ export async function forceRefreshAgentToken(a, opts = {}) {
|
|
|
87
90
|
const now = opts.now ?? Date.now();
|
|
88
91
|
const store = readStore(a, service);
|
|
89
92
|
if (!store) return null;
|
|
90
|
-
|
|
93
|
+
if (!storeMatchesOrigin(store, opts.apiBase ?? store.api_base)) return null;
|
|
94
|
+
const reused = storeMatchesOrigin(store, opts.apiBase ?? store.api_base) ? successorIfRejected(store, opts.rejectedAccess) : null;
|
|
91
95
|
if (reused) return reused;
|
|
92
96
|
return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, true, opts.deadlineMs ?? REFRESH_DEADLINE_MS, opts.rejectedAccess, opts.apiBase);
|
|
93
97
|
}
|
|
@@ -103,11 +107,14 @@ async function singleFlightRefresh(a, service, baseline, now, fetchImpl, sleepIm
|
|
|
103
107
|
} catch (e) {
|
|
104
108
|
if (e?.code !== "EEXIST") throw e;
|
|
105
109
|
acquired = acquireIfDeadOwner(lock, ownerId);
|
|
106
|
-
if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess);
|
|
110
|
+
if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess, apiBase);
|
|
107
111
|
}
|
|
108
112
|
try {
|
|
109
113
|
const fresh = readStore(a, service);
|
|
110
114
|
if (!fresh) return null;
|
|
115
|
+
if (!storeMatchesOrigin(fresh, apiBase ?? fresh.api_base)) return null;
|
|
116
|
+
// A cached token may only be returned when the stored session belongs to the
|
|
117
|
+
// TARGET origin; anything else is refused upstream (no replay, no migration).
|
|
111
118
|
const reused = successorIfRejected(fresh, rejectedAccess);
|
|
112
119
|
if (reused) return reused;
|
|
113
120
|
if (!force && !accessExpiresWithinSkew(fresh, now)) return fresh.access_token;
|
|
@@ -162,16 +169,22 @@ function ownerAlive(pid) {
|
|
|
162
169
|
try { process.kill(pid, 0); return true; } catch (e) { return e?.code !== "ESRCH"; }
|
|
163
170
|
}
|
|
164
171
|
|
|
165
|
-
async function waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess) {
|
|
172
|
+
async function waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess, apiBase) {
|
|
173
|
+
// The waiter must accept a session that the winner rewrote to the TARGET
|
|
174
|
+
// origin — comparing against the (possibly legacy) baseline base would make it
|
|
175
|
+
// poll until timeout even though the store is already correct (@skyzh).
|
|
176
|
+
const targetBase = apiBase ?? baseline.api_base;
|
|
166
177
|
const maxPolls = Math.ceil(LOCK_WAIT_MS / LOCK_POLL_MS);
|
|
167
178
|
for (let i = 0; i < maxPolls; i += 1) {
|
|
168
179
|
await sleepImpl(LOCK_POLL_MS);
|
|
169
180
|
const cur = readStore(a, service);
|
|
181
|
+
if (cur && !storeMatchesOrigin(cur, targetBase)) continue;
|
|
170
182
|
const reused = successorIfRejected(cur, rejectedAccess);
|
|
171
183
|
if (reused) return reused;
|
|
172
184
|
if (cur && cur.refresh_token !== baseline.refresh_token) return cur.access_token;
|
|
173
185
|
}
|
|
174
186
|
const cur = readStore(a, service);
|
|
187
|
+
if (cur && !storeMatchesOrigin(cur, targetBase)) agentFail("notLoggedIn");
|
|
175
188
|
const reused = successorIfRejected(cur, rejectedAccess);
|
|
176
189
|
if (reused) return reused;
|
|
177
190
|
if (!force && cur && !accessExpired(cur, now)) return cur.access_token;
|
package/lib/auth.mjs
CHANGED
|
@@ -4,7 +4,69 @@ import { STAMP_LEGACY_DEFAULT_URL, STAMP_LEGACY_STAGING_URL, STAMP_SERVICE } fro
|
|
|
4
4
|
import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
|
|
5
5
|
import { AgentError, agentFail } from "./errors.mjs";
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// Canonical origin of a URL, or null when it is not an absolute http(s) URL.
|
|
8
|
+
// Task #439: comparisons on the stored/api base MUST normalize the origin —
|
|
9
|
+
// a trailing slash, upper-case host or explicit :443 are the SAME origin and
|
|
10
|
+
// must not slip past the "this is a legacy default" check.
|
|
11
|
+
function originOf(value) {
|
|
12
|
+
try {
|
|
13
|
+
const parsed = new URL(value);
|
|
14
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
15
|
+
return parsed.origin;
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Known instance map: canonical origin -> the service slug that owns it.
|
|
22
|
+
// SUPPORT BOUNDARY: only the instances the CLI knows can be checked statically.
|
|
23
|
+
// A self-hosted instance's origin<->service mapping is not knowable locally.
|
|
24
|
+
const KNOWN_INSTANCES = new Map([
|
|
25
|
+
["https://stamp.build", "stamp"],
|
|
26
|
+
["https://staging.stamp.build", "raft-git-gateway-staging"],
|
|
27
|
+
]);
|
|
28
|
+
// storeMatchesOrigin reports whether a stored session belongs to the SAME
|
|
29
|
+
// instance as the target base. It is ONE branch-free property — the parsed
|
|
30
|
+
// origins must be strictly equal — and it must hold at EVERY actual use
|
|
31
|
+
// (token read, refresh, 401 retry), not once at resolveAuth (@Tenny: "use site"
|
|
32
|
+
// is plural; the refresh path re-reads the store file).
|
|
33
|
+
//
|
|
34
|
+
// There is deliberately NO migration of a renamed host: a session issued for a
|
|
35
|
+
// superseded origin is treated as belonging to a DIFFERENT instance and is
|
|
36
|
+
// refused (the caller re-logs in). Such a session would otherwise have to be
|
|
37
|
+
// replayed or refreshed, and that branch produced every defect in this task
|
|
38
|
+
// (@Mason, 2026-09-13: "删" — the one saved re-login is already documented as
|
|
39
|
+
// expected, so the branch is not worth its concurrency+cache complexity).
|
|
40
|
+
export function storeMatchesOrigin(store, apiBase) {
|
|
41
|
+
if (!store) return false;
|
|
42
|
+
const target = originOf(apiBase);
|
|
43
|
+
const stored = originOf(store.api_base);
|
|
44
|
+
return stored !== null && stored === target;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function assertCoherentPair(apiBase, service) {
|
|
48
|
+
const origin = originOf(apiBase);
|
|
49
|
+
if (origin === null) return; // non-http(s) base: out of this check's scope
|
|
50
|
+
const owner = KNOWN_INSTANCES.get(origin);
|
|
51
|
+
if (owner === undefined) {
|
|
52
|
+
// Unknown origin (e.g. a self-hosted instance): its origin<->service
|
|
53
|
+
// mapping is not knowable locally, so it is outside this check. See the
|
|
54
|
+
// support boundary above — do not read this as a universal guarantee.
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (service !== owner) {
|
|
58
|
+
agentFail("pair_mismatch", { origin, service, owner });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function resolveAuth({ urlBase, urlExplicit, env = process.env, service, locale = "en", cliName = "stamp" }) {
|
|
63
|
+
// The instance slug may be left unset (e.g. `stamp-staging` passes only its
|
|
64
|
+
// base). Derive it: an explicit STAMP_SERVICE wins, else the base's owner,
|
|
65
|
+
// else the production default. Task #439: entry default, env and a stored
|
|
66
|
+
// session must all resolve to ONE coherent pair.
|
|
67
|
+
if (service === undefined || service === "") {
|
|
68
|
+
service = env.STAMP_SERVICE || KNOWN_INSTANCES.get(originOf(urlBase)) || STAMP_SERVICE;
|
|
69
|
+
}
|
|
8
70
|
const admission = admitAgent(env);
|
|
9
71
|
if (admission.kind === "fail_closed") {
|
|
10
72
|
agentFail("admission_partial", { reason: admission.reason });
|
|
@@ -13,20 +75,56 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service =
|
|
|
13
75
|
const a = admission.env;
|
|
14
76
|
const store = readStore(a, service);
|
|
15
77
|
const storedBase = store?.api_base;
|
|
16
|
-
|
|
78
|
+
// Task #439: compare the stored base on its PARSED ORIGIN, not the raw
|
|
79
|
+
// string. A legacy default stored with a trailing slash, different case or
|
|
80
|
+
// an explicit :443 is still that legacy default and must be superseded by
|
|
81
|
+
// the caller's coherent base — otherwise a stale stored spelling silently
|
|
82
|
+
// retargets the request. A genuinely non-legacy custom instance is still
|
|
83
|
+
// preserved (that is the existing custom-base feature).
|
|
84
|
+
const storedOrigin = originOf(storedBase);
|
|
85
|
+
const legacyOrigins = new Set([STAMP_LEGACY_STAGING_URL, STAMP_LEGACY_DEFAULT_URL].map(originOf));
|
|
86
|
+
const apiBase = urlExplicit || (storedOrigin !== null && legacyOrigins.has(storedOrigin))
|
|
17
87
|
? urlBase
|
|
18
|
-
: (
|
|
88
|
+
: (storedBase ?? urlBase);
|
|
89
|
+
// The final resolved pair must belong to one instance. Checked here so every
|
|
90
|
+
// source (entry default / env / stored session) is covered, before any
|
|
91
|
+
// network work. Task #439.
|
|
92
|
+
assertCoherentPair(apiBase, service);
|
|
93
|
+
|
|
94
|
+
// Task #439 (@skyzh): a stored session is bound to the ORIGIN it was issued
|
|
95
|
+
// against. If the resolved origin differs from the origin the session was
|
|
96
|
+
// stored for (e.g. we just superseded a legacy staging base with prod), the
|
|
97
|
+
// cached access/refresh tokens must NOT be replayed against the new origin —
|
|
98
|
+
// that would send a foreign instance's credential to this one. Treat such a
|
|
99
|
+
// store as absent so the caller must log in afresh.
|
|
100
|
+
// No migration: a store issued for a DIFFERENT origin is not usable here.
|
|
101
|
+
// The refusal names the origin so the reader knows why and what to do.
|
|
102
|
+
const usableStore = storeMatchesOrigin(store, apiBase) ? store : undefined;
|
|
103
|
+
const storedOriginElsewhere = !usableStore && storedOrigin !== null ? storedOrigin : null;
|
|
19
104
|
return {
|
|
20
105
|
mode: "agent",
|
|
21
106
|
apiBase,
|
|
22
107
|
agentEnv: a,
|
|
23
108
|
service,
|
|
24
109
|
async token() {
|
|
110
|
+
if (!usableStore) {
|
|
111
|
+
if (storedOriginElsewhere !== null) {
|
|
112
|
+
throw new AgentError("sessionOriginMismatch", {
|
|
113
|
+
stored: storedOriginElsewhere,
|
|
114
|
+
target: originOf(apiBase) ?? apiBase,
|
|
115
|
+
cli: cliName,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
throw new AgentError("notLoggedIn");
|
|
119
|
+
}
|
|
25
120
|
const tok = await getFreshAgentAccessToken(a, { service, apiBase });
|
|
26
121
|
if (!tok) throw new AgentError("notLoggedIn");
|
|
27
122
|
return tok;
|
|
28
123
|
},
|
|
29
|
-
async retryToken(rejectedAccess) {
|
|
124
|
+
async retryToken(rejectedAccess) {
|
|
125
|
+
if (!usableStore) return null;
|
|
126
|
+
return forceRefreshAgentToken(a, { service, apiBase, rejectedAccess });
|
|
127
|
+
},
|
|
30
128
|
logout() {
|
|
31
129
|
const p = agentAuthPath(a, service);
|
|
32
130
|
if (existsSync(p)) unlinkSync(p);
|
|
@@ -35,6 +133,7 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service =
|
|
|
35
133
|
};
|
|
36
134
|
}
|
|
37
135
|
const token = env.STAMP_TOKEN || "";
|
|
136
|
+
assertCoherentPair(urlBase, service);
|
|
38
137
|
return {
|
|
39
138
|
mode: "human",
|
|
40
139
|
apiBase: urlBase,
|
package/lib/errors.mjs
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
import { t } from "./locale.mjs";
|
|
2
2
|
|
|
3
|
+
const apiRecoveryKeys = new Map([
|
|
4
|
+
["GITHUB_IDENTITY_BINDING_REQUIRED", "apiBindIdentity"],
|
|
5
|
+
["REPOSITORY_NOT_INSTALLED", "apiRepositoryNotInstalled"],
|
|
6
|
+
["PUBLIC_CONTRIBUTION_POLICY_DENIED", "apiContributionDenied"],
|
|
7
|
+
["REPOSITORY_NOT_AUTHORIZED", "apiRepositoryNotAuthorized"],
|
|
8
|
+
["PR_NOT_FOUND", "prReadNotFound"],
|
|
9
|
+
["PR_HEAD_MOVED", "prReadHeadMoved"],
|
|
10
|
+
["PR_DIFF_INCOMPLETE", "prReadDiffIncomplete"],
|
|
11
|
+
["PR_DETAIL_FAILED", "prReadUnavailable"],
|
|
12
|
+
["PR_DIFF_FAILED", "prReadUnavailable"],
|
|
13
|
+
["PR_INBOX_FAILED", "prReadUnavailable"],
|
|
14
|
+
// Cursor scope/format rejections (task #397 slice 1): the cursor is bound to
|
|
15
|
+
// (tenant, server, viewer scope, filter); a mismatched or malformed cursor is
|
|
16
|
+
// a recoverable user error, never a generic contract mismatch.
|
|
17
|
+
["PR_INBOX_CURSOR_SCOPE", "prCursorScope"],
|
|
18
|
+
["PR_INBOX_CURSOR_INVALID", "prCursorInvalid"],
|
|
19
|
+
]);
|
|
20
|
+
|
|
3
21
|
/** Stable machine code on `.code`; English catalog text on `.message` for tests. */
|
|
4
22
|
export class AgentError extends Error {
|
|
5
23
|
constructor(code, details = {}) {
|
|
@@ -18,3 +36,28 @@ export function presentError(locale, e) {
|
|
|
18
36
|
if (e instanceof AgentError) return t(locale, e.code, e.details);
|
|
19
37
|
return e.message;
|
|
20
38
|
}
|
|
39
|
+
|
|
40
|
+
function stableErrorCode(value) {
|
|
41
|
+
if (typeof value !== "string") return "";
|
|
42
|
+
const code = value.trim();
|
|
43
|
+
return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function boundedSuggestedAction(value) {
|
|
47
|
+
if (typeof value !== "string") return "";
|
|
48
|
+
return value.trim().replace(/[\r\n\t]+/g, " ").slice(0, 512);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// API authorization denials keep the compatibility `error` at the top level and
|
|
52
|
+
// carry the actionable reason in errorCode + suggestedNextAction. Prefer a localized,
|
|
53
|
+
// executable repair for known codes; preserve a bounded server suggestion for future
|
|
54
|
+
// codes so a new denial does not degrade back to an opaque REPOSITORY_NOT_AUTHORIZED.
|
|
55
|
+
export function apiErrorGuidance(locale, body) {
|
|
56
|
+
if (!body || typeof body !== "object") return { code: "", action: "" };
|
|
57
|
+
const code = stableErrorCode(body.errorCode ?? body.error);
|
|
58
|
+
const key = apiRecoveryKeys.get(code);
|
|
59
|
+
return {
|
|
60
|
+
code,
|
|
61
|
+
action: key ? t(locale, key) : boundedSuggestedAction(body.suggestedNextAction),
|
|
62
|
+
};
|
|
63
|
+
}
|