@botiverse/stamp-cli 0.3.13 → 0.4.0

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/errors.mjs DELETED
@@ -1,47 +0,0 @@
1
- import { t, prefix } from "./locale.mjs";
2
-
3
- // Local mistakes (bad flags, malformed JSON). `.code` is a locale catalog key.
4
- export class AgentError extends Error {
5
- constructor(code, details = {}) {
6
- super(t("en", code, details));
7
- this.name = "AgentError";
8
- this.code = code;
9
- this.details = details;
10
- }
11
- }
12
-
13
- export function agentFail(code, details = {}) {
14
- throw new AgentError(code, details);
15
- }
16
-
17
- export function presentError(locale, e) {
18
- if (e instanceof AgentError) return t(locale, e.code, e.details);
19
- return e.message;
20
- }
21
-
22
- function stableErrorCode(value) {
23
- if (typeof value !== "string") return "";
24
- const code = value.trim();
25
- return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
26
- }
27
-
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.
32
- export function printGatewayError(error, write) {
33
- const body = error.body;
34
- const code = stableErrorCode(body?.errorCode ?? body?.error);
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}`);
38
- const action = typeof body?.suggestedNextAction === "string" ? body.suggestedNextAction : "";
39
- if (action) write(`${prefix()}${action}`);
40
- // A moved-PR refusal (PR_HEAD_MOVED / PR_BASE_MOVED) hands back the PR's
41
- // current coordinates; print them as the flags to retry with.
42
- const sha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
43
- if (sha(body?.currentHead) && sha(body?.currentBase)) {
44
- write(`${prefix()}${t("en", "prCurrentCoordinates", { head: body.currentHead, base: body.currentBase })}`);
45
- }
46
- return Boolean(action);
47
- }
package/lib/expiry.mjs DELETED
@@ -1,27 +0,0 @@
1
- // The access-token expiry was printed as the raw RFC3339 UTC string, which a
2
- // reader in another time zone sees as a time earlier than their own clock and
3
- // reads as "already expired" (task #436). The human line gets a local time plus
4
- // how long is left; the JSON keeps the raw value for machines.
5
-
6
- function localeTag() {
7
- return "en-US";
8
- }
9
-
10
- // humanExpiry formats an RFC3339 instant for the reader: local time with its
11
- // zone, and a relative remaining time. An unparseable value is returned as-is
12
- // (never crash on a display-only path).
13
- export function humanExpiry(locale, iso, now = Date.now()) {
14
- const ms = Date.parse(String(iso ?? ""));
15
- if (!Number.isFinite(ms)) return { text: String(iso ?? ""), remaining: "", expired: false };
16
- const tag = localeTag(locale);
17
- // dateStyle/timeStyle cannot be combined with timeZoneName, and the zone is the
18
- // whole point here: name the components explicitly.
19
- const text = new Intl.DateTimeFormat(tag, {
20
- year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZoneName: "short",
21
- }).format(ms);
22
- const minutes = Math.round((ms - now) / 60000);
23
- const relative = new Intl.RelativeTimeFormat(tag, { numeric: "auto" });
24
- // Minutes are the useful unit up to 90 of them; beyond that, hours.
25
- const remaining = Math.abs(minutes) >= 90 ? relative.format(Math.round(minutes / 60), "hour") : relative.format(minutes, "minute");
26
- return { text, remaining, expired: minutes <= 0 };
27
- }
package/lib/flags.mjs DELETED
@@ -1,26 +0,0 @@
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 DELETED
@@ -1,378 +0,0 @@
1
- /** User-visible copy. Machine protocol fields and stable error codes stay English. */
2
- export const messages = {
3
- en: {
4
- usagePrQueue: "usage: {cli} pr queue <enqueue|status|withdraw> <NUMBER -R OWNER/REPO|PR_URL> --request-id ID [--head SHA --base SHA (enqueue only)]; ID: 16–128 letters/digits/underscore/hyphen, first alphanumeric; choose it before sending and retain it",
5
- prQueueOutcomeUnknown: "Queue outcome is unknown. Read pr queue status with the same PR and --request-id before another write; do not generate a new ID or automatically resend.",
6
- prQueueReceipt: "Queue {repository}#{number}, request {id}: {state}; reason: {reason}; landing: {landing}; terminal notification queued: {queued} (not delivery confirmation)",
7
- usageQueue: "usage: {cli} queue setup OWNER/REPO --branch BRANCH [--workflow ID]\n {cli} queue save OWNER/REPO --branch BRANCH --workflow ID --ci-policy head|all --max-batch N --wait SECONDS --timeout SECONDS --confirm\n {cli} queue verify OWNER/REPO --pr NUMBER\n {cli} queue enable OWNER/REPO\n {cli} queue status OWNER/REPO\n(agent; only on a registered queue target of a repository your server's GitHub App covers)",
8
- queueWorkflowInvalid: "--workflow must be a GitHub Actions workflow id; run {cli} queue setup OWNER/REPO --branch BRANCH to list them.",
9
- queueCIPolicyInvalid: "--ci-policy must be head (test the batch head) or all (test every prefix).",
10
- queueLimitsInvalid: "--max-batch must be 1 to 10, --wait 0 to 600 seconds and --timeout 60 to 14400 seconds.",
11
- queueInvalidResponse: "Stamp returned an unexpected merge queue response; nothing more was sent. Check the service version, then read {cli} queue status.",
12
- queueCannotSave: "This discovery cannot be saved yet: select a workflow that covers every branch-required check (--workflow ID), then retry.",
13
- queueConfirming: "Confirming the merge queue setup of {repository} {branch}:",
14
- queueConfirmRequired: "Nothing was saved. Check the lines above, then run the same command with --confirm.",
15
- queueSaved: "Saved the merge queue setup of {repository} (revision {revision}). Next: {cli} queue verify {repository} --pr NUMBER with an approved pull request.",
16
- queueVerifyStarted: "Verification of {repository} started with PR #{number}; it does not merge. Watch {cli} queue status {repository}, then run {cli} queue enable {repository} once it passed.",
17
- queueEnabled: "The merge queue of {repository} is enabled.",
18
- queueOutcomeUnknown: "The outcome is unknown. Read {cli} queue status {repository} before sending it again.",
19
- 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]; without --repo/--head/--sha they come from the published receipt",
20
- usagePrRead: "usage: {cli} pr <list|view|review|diff|checks|comment|edit|approve|unapprove|merge|queue> [arguments]",
21
- usagePrReview: "usage: {cli} pr review <number|URL> [--repo OWNER/REPO] — the exact head to pin, base, merge-base, checks, and the diff/patch-id commands against the merge-base",
22
- prReviewExactHead: "Exact head",
23
- prReviewBase: "Base",
24
- prReviewMergeBase: "Merge-base",
25
- prReviewMergeBaseRule: "log, stat, diff and patch-id against the merge-base, never against the current base: the base branch may have advanced since this branch forked, and those commits would show up as the PR's",
26
- prReviewCommands: "Local review (after cloning through Stamp)",
27
- prReviewVerdict: "Verdict to post",
28
- usagePrApprove: "usage: {cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT] (human: GitHub review; agent: recorded by Stamp, no --body)",
29
- usagePrUnapprove: "usage: {cli} pr unapprove <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA (agent: withdraws your Stamp-recorded approval of that head)",
30
- usagePrMerge: "usage: {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase] (without --method: the method the repository allows, squash first; human: as your GitHub identity; agent: as the Stamp App, once someone other than the author approved that exact head)\n {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --auto --head SHA --base SHA [--method ...] | --auto --cancel --head SHA --base SHA | --auto --status (author agent: let Stamp merge once someone else approves that head and the verdict is READY)",
31
- prApproved: "Approved {repository}#{number} as {actor}",
32
- prApprovedByStamp: "Approved {repository}#{number} at {head} as {actor} (recorded by Stamp)",
33
- prUnapproved: "Withdrew approval of {repository}#{number} at {head} as {actor} (recorded by Stamp)",
34
- prMerged: "Merged {repository}#{number} as {actor} ({sha})",
35
- prMergedByApp: "Merged {repository}#{number} at {head} as the Stamp App for {actor} ({sha})",
36
- prAutoMerge_ARMED: "{repository}#{number} will be merged by Stamp ({method}) at head {head} once someone other than the author approves it and the verdict is READY",
37
- prAutoMerge_VOID: "{repository}#{number}: the auto-merge registration was for head {head}, which the PR no longer has; register again for the current head",
38
- prAutoMerge_CANCELLED: "{repository}#{number}: auto-merge withdrawn",
39
- prAutoMerge_NONE: "{repository}#{number}: not registered for auto-merge",
40
- prAutoMerge_CLOSED: "{repository}#{number} is closed or merged; the auto-merge registration has nothing left to do",
41
- prAutoMerge_EXPIRED: "{repository}#{number}: the auto-merge registration expired (registered more than 14 days ago); register again",
42
- prAutoMergeUnchanged: "(nothing changed)",
43
- prApproveRejected: "Approve was rejected. Check your session, repository access, and --head/--base (a human also needs a GitHub binding; an agent cannot approve a PR it opened).",
44
- prMergeRejected: "Merge was rejected. Check your session, repository access, --head/--base, the approval (an agent merge needs an approval of that exact head from someone other than the author), and mergeability (a human also needs a GitHub binding).",
45
- prApproveOutcomeUnknown: "Approve outcome is unknown. Re-run the identical command; it returns the recorded result and never approves twice.",
46
- prUnapproveRejected: "Unapprove was rejected. Check your agent session, repository access, and --head/--base.",
47
- prUnapproveOutcomeUnknown: "Unapprove outcome is unknown. Retry the same command; it is idempotent.",
48
- prMergeOutcomeUnknown: "Merge outcome is unknown. Re-read the PR before sending again; do not automatically resend.",
49
- apiHumanPrincipal: "This action needs a human STAMP_TOKEN session.",
50
- apiWriteCoords: "Re-read the PR and retry with both --head and --base.",
51
- prWriteFullSHA: "{flag} is not a full commit SHA; pass the full 40-character SHA ({cli} pr view prints the PR's head and base).",
52
- prCurrentCoordinates: "Current PR coordinates: --head {head} --base {base}",
53
- apiGitHubBinding: "Bind your GitHub account in Stamp settings, then retry.",
54
- usagePrComment: "usage: {cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) [--expected-head SHA] (a human posts as their bound GitHub identity; an agent posts as the Stamp App with an attribution line naming the agent; with --expected-head the comment is refused if the pull request has moved)",
55
- prCommentExpectedHeadInvalid: "--expected-head must be the full 40-character commit SHA you reviewed.",
56
- prCommentBodyInvalid: "Comment must be nonempty and at most 64 KiB of UTF-8 text.",
57
- prCommentCreated: "Comment posted as {actor}: {url}",
58
- prCommentRejected: "Comment request was rejected. Check your session, GitHub binding (humans), repository access and input.",
59
- prCommentOutcomeUnknown: "Comment outcome is unknown. Check the PR comments before sending again; do not automatically resend.",
60
- usagePrEdit: "usage: {cli} pr edit <NUMBER -R OWNER/REPO|PR_URL> [--title TITLE] [--body TEXT|--body-file FILE|-] (only the agent recorded on Stamp's creation receipt may edit; provide title, body, or both)",
61
- usagePrClose: "usage: {cli} pr close <NUMBER -R OWNER/REPO|PR_URL> [--reason TEXT|--reason-file FILE|-] (the creating agent, or a server admin with --reason; the reason is posted on the PR before it is closed)",
62
- prCloseReasonConflict: "Use either --reason or --reason-file, not both.",
63
- prCloseReasonRead: "Cannot read --reason-file; check the file path or pass - for stdin.",
64
- prCloseReasonInvalid: "The close reason must be nonempty and at most 1000 characters.",
65
- prClosed: "Closed {repository}#{number}: {url}",
66
- prCloseRejected: "PR close was rejected. Confirm this agent created the PR through Stamp and still has repository access.",
67
- prCloseOutcomeUnknown: "PR close outcome is unknown. Re-read the PR before deciding whether to send the close again; do not automatically resend.",
68
- prEditTitleInvalid: "PR title must be nonempty and at most 256 bytes of UTF-8 text.",
69
- prEditBodyInvalid: "PR description must be nonempty and at most 64 KiB of UTF-8 text.",
70
- prEdited: "Updated {repository}#{number}: {url}",
71
- prEditRejected: "PR edit was rejected. Confirm this agent created the PR through Stamp and still has repository access.",
72
- prEditOutcomeUnknown: "PR edit outcome is unknown. Re-read the PR before deciding whether to send the edit again; do not automatically resend.",
73
- usagePrList: "usage: {cli} pr list",
74
- usagePrView: "usage: {cli} pr view <number|URL> [--repo OWNER/REPO]",
75
- usagePrDiff: "usage: {cli} pr diff <number|URL> [--repo OWNER/REPO] [--name-only]",
76
- usagePrChecks: "usage: {cli} pr checks <number|URL> [--repo OWNER/REPO]",
77
- prReadInvalidResponse: "Stamp returned an invalid PR read response; retry after checking the service version.",
78
- prReadCoordinateMismatch: "Stamp returned PR coordinates different from the requested repository or number; refusing to display them.",
79
- prListEmpty: "No Stamp-created pull requests found.",
80
- prStatusUnavailable: "status unavailable",
81
- prCIShort: "CI",
82
- prAgentShort: "Agent",
83
- prHeadLabel: "Head",
84
- prChecksLabel: "Checks",
85
- prReviewLabel: "Review",
86
- prDiffUnavailable: "patch unavailable",
87
- prDiffEmpty: "No changed files reported.",
88
- prChecksEmpty: "No checks reported.",
89
- prChecksUnreadable: "Checks could not be read for this pull request, so this is not \"no checks\" — the gateway was refused by GitHub (most often a missing Checks permission on the app). Treat CI as unknown.",
90
- prCIUnreadable: "unreadable",
91
- prVerdictCIUnreadable: "CI unreadable — not evidence of green",
92
- prVerdictLabel: "Stamp verdict",
93
- verdict_READY: "can land now",
94
- verdict_QUEUE_READY: "approved; it lands through Stamp's merge queue: `{cli} pr queue`",
95
- verdict_MERGED: "already merged",
96
- verdict_CLOSED: "closed",
97
- verdict_DRAFT: "draft",
98
- verdict_CONFLICT: "conflicts with the base",
99
- verdict_CI_UNREADABLE: "CI cannot be read — not evidence of green",
100
- verdict_CI_FAILING: "a required check failed",
101
- verdict_CI_NOT_EXECUTED: "a required check did not run",
102
- verdict_CI_PENDING: "required checks still running",
103
- verdict_REVIEW_UNREADABLE: "the approval state cannot be read",
104
- verdict_CHANGES_REQUESTED: "changes requested",
105
- verdict_STALE_REVIEW: "approvals are for another head or base",
106
- verdict_NEEDS_REVIEW: "needs a non-author approval at this head",
107
- verdict_BEHIND: "behind the base",
108
- verdict_BLOCKED: "GitHub isn't allowing the merge yet",
109
- // What a BLOCKED is waiting on (gateway pr_blocked.go); {detail} is the
110
- // gateway's short detail, "" when it has none.
111
- blocked_REVIEWS_REQUIRED: "more approvals required",
112
- blocked_CODEOWNERS_REVIEW_REQUIRED: "a code owner review is required",
113
- blocked_LAST_PUSH_APPROVAL_REQUIRED: "the last push needs an approval from someone else",
114
- blocked_CHANGES_REQUESTED: "changes requested on GitHub",
115
- blocked_SIGNED_COMMITS_REQUIRED: "signed commits required (under the current merge method)",
116
- blocked_LINEAR_HISTORY_REQUIRED: "linear history required",
117
- blocked_CONVERSATION_RESOLUTION_REQUIRED: "unresolved review conversations",
118
- blocked_REQUIRED_CHECK_MISSING: "a required check has not passed",
119
- blocked_DEPLOYMENT_REQUIRED: "a required deployment has not succeeded",
120
- blocked_BRANCH_BEHIND: "the branch must be up to date with the base",
121
- prVerdictBlockedNone: "GitHub does not say why; see the pull request on GitHub",
122
- verdict_UNCONFIRMED: "GitHub does not confirm a clean merge (a check is not passing, or it is still computing)",
123
- prReadNotFound: "Check the repository and PR number, and confirm this Agent created the PR through Stamp.",
124
- prReadHeadMoved: "The PR head changed while Stamp read the diff; rerun the command and review the new head.",
125
- prReadDiffIncomplete: "GitHub did not return the complete PR diff; retry later instead of relying on partial files.",
126
- prReadUnavailable: "The PR read is temporarily unavailable; retry after checking Stamp service status.",
127
- prListMore: "More results available; rerun with --limit and --cursor {cursor}.",
128
- prSection_drafts: "Drafts",
129
- prSection_changes: "Changes requested",
130
- prSection_approved: "Approved",
131
- prSection_approvals: "Has approvals",
132
- prSection_waiting: "Waiting for review",
133
- prSection_history: "History",
134
- prSection_unavailable: "Status unavailable",
135
- prCursorScope: "This cursor does not belong to the current identity or scope; rerun {cli} pr list from the start.",
136
- prCursorInvalid: "The cursor is invalid or expired; rerun {cli} pr list from the start.",
137
- prRequired: "Missing {flag}; use {cli} receipt get <id> to obtain the published coordinates.",
138
- prRepository: "--repo must be OWNER/REPO.",
139
- prSHA: "--sha must be the exact 40-character lowercase published commit SHA.",
140
- prBodyRequired: "Provide a non-empty PR description with --body or --body-file (use - for stdin).",
141
- prCheckArguments: "Check the PR arguments with {cli} pr create --help; correct invalid or empty values before retrying.",
142
- prCheckConfiguration: "Ask the service administrator to repair the GitHub App configuration before retrying.",
143
- prBodyConflict: "Use either --body or --body-file, not both.",
144
- prBodyRead: "Cannot read --body-file; check the file path or pass - for stdin.",
145
- prIdempotency: "--idempotency-key must contain 16–128 letters, digits, dots, underscores, colons, or hyphens.",
146
- prCreated: "Created PR #{number}: {url}",
147
- prExisting: "Existing PR #{number}: {url}",
148
- prStampPage: " Stamp: {page}",
149
- prViewStampPage: "Stamp: {page}",
150
- prInstance: "Instance: {host}",
151
- whoamiCommitEmail: "commit email: {email} (git config user.email {email})",
152
- 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)",
153
- 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)",
154
- prWaitPublished: "Check {cli} receipt get <id>; use your own receipt after its status becomes PUBLISHED.",
155
- prReceiptNotPublished: "Receipt {id} is {status}; it will not be published, so no pull request can be opened from it. See {cli} receipt get {id}.",
156
- prPublishTimeout: "Receipt {id} is still {status} after waiting for GitHub publication; run the same command again later, or check {cli} receipt get {id}.",
157
- prReceiptIncomplete: "Receipt {id} is published but lacks its repository, ref or commit; pass --repo, --head and --sha explicitly.",
158
- prCheckReceipt: "Read the receipt again and check --repo, --head and --sha against the exact published commit.",
159
- prCheckAccess: "Check repository access and the authorized base branch with the repository administrator.",
160
- prCheckBase: "The base branch does not exist on GitHub. Pass --base as an existing branch of the repository.",
161
- prCheckExisting: "Check the existing PR and keep the same receipt, title, body and idempotency key when retrying.",
162
- prRetry: "Check the receipt and service status, then retry the identical command; its idempotency key stays unchanged.",
163
- apiBindIdentity: "Run `{cli} whoami` (it gives this agent its default commit email), then retry the command.",
164
- apiRepositoryNotInstalled: "Check OWNER/REPO spelling, or ask a server owner to install the Stamp GitHub App on that repository, then retry.",
165
- apiContributionDenied: "Ask a server owner to grant this agent an active Write-or-higher repository role, then retry.",
166
- apiRepositoryNotAuthorized: "Ask a server owner to verify the Stamp GitHub App installation and this agent's identity binding, then retry.",
167
-
168
- usage: `{cli} {version} — Agent Git gateway CLI
169
-
170
- {cli} login agent: PKCE login via raft (no browser); human: how to set STAMP_TOKEN
171
- {cli} logout agent: forget the stored session
172
- {cli} whoami who the gateway thinks you are
173
- {cli} migration-help old manifest actions → CLI mapping
174
- {cli} key enroll [--public-key FILE|-] bind this agent's SSH public key (agent default: its own key, created if missing)
175
- {cli} key list list this agent's enrolled SSH keys
176
- {cli} key revoke KEY_ID revoke one of this agent's enrolled keys
177
- {cli} known-hosts refresh re-pin this instance's SSH host key from /.well-known
178
- {cli} identity bind --email ADDR bind commit-author email (DCO)
179
- {cli} receipt get <id> gateway acceptance + GitHub publication status
180
- {cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]
181
- list your own push receipts (newest first)
182
- {cli} changelog [--limit N] [--all] release history: CLI/API changes per version (--all: everything)
183
- {cli} pr create --receipt ID [--repo OWNER/REPO --head BRANCH --sha SHA] --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
184
- {cli} pr list
185
- {cli} pr view <number|URL> --repo OWNER/REPO
186
- {cli} pr diff <number|URL> --repo OWNER/REPO [--name-only]
187
- {cli} pr checks <number|URL> --repo OWNER/REPO
188
- {cli} pr comment <number|URL> --repo OWNER/REPO --body-file FILE|- (human; agent posts as the Stamp App)
189
- {cli} pr edit <number|URL> --repo OWNER/REPO [--title TITLE] [--body-file FILE|-] (creating agent only)
190
- {cli} pr close <number|URL> --repo OWNER/REPO [--reason TEXT|--reason-file FILE|-] (creating agent, or a server admin with --reason)
191
- {cli} pr approve <number|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (human; agent without --body)
192
- {cli} pr unapprove <number|URL> --repo OWNER/REPO --head SHA --base SHA (agent)
193
- {cli} pr merge <number|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (human; agent once approved by another)
194
- {cli} pr merge <number|URL> --repo OWNER/REPO --auto --head SHA --base SHA (author agent: merge once someone else approves)
195
- {cli} pr queue enqueue|status|withdraw <number|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent; coordinates required for enqueue)
196
- {cli} queue setup|save|verify|enable|status OWNER/REPO [--branch B --workflow ID ...]
197
- (agent) set up Stamp's merge queue on a registered target branch
198
- {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
199
- {cli} repo use [DIR] point an existing checkout at this agent's key (repository-local)
200
-
201
- {cli} follow <owner/repo> --kind issue|pull --number N
202
- {cli} unfollow <owner/repo> --kind issue|pull --number N
203
- {cli} subscription pause|resume <owner/repo> --kind issue|pull --number N
204
- {cli} subscriptions
205
- {cli} watch <owner/repo> --event TYPE
206
- {cli} unwatch <owner/repo> --event TYPE
207
-
208
- git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
209
- git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
210
-
211
- flags: --json env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE
212
- docs: {docs} (the agent workflow, step by step)`,
213
- usageRepoClone: "usage: {cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
214
- cloned: "Cloned {repository} from {url}",
215
- cloneCommitTrailers: "Every commit you push here must end with these trailers, as one block at the very end with no blank line between them (GitHub only reads the last contiguous block):",
216
- cloneFailed: "clone of {repository} via the Stamp gateway failed",
217
- networkUnreachable: "could not reach {base} ({cause}); check the instance address (STAMP_URL) and your network, then retry",
218
- networkHostUnresolved: "{base} does not resolve ({cause}); check the instance address (STAMP_URL) and DNS, then retry",
219
- 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",
220
- cloneEnrolledIdentityMissing: "the key `{cli} key enroll` recorded for {origin} is not at {path} on this machine: run `{cli} key enroll` here, or point at the key with --identity FILE",
221
- 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",
222
- cloneKnownHostsInvalid: "{url} did not return a usable known_hosts line; refusing to pin it — check the instance, or pass --known-hosts FILE",
223
- usageKnownHostsRefresh: "usage: known-hosts refresh [--known-hosts FILE]",
224
- knownHostsRefreshed: "pinned {pattern} in {path}\n{fingerprint}",
225
- knownHostsRepoAligned: "this repository reads that file\n note: a GIT_SSH_COMMAND set in the environment you push from overrides this and cannot be seen from here, so this does not vouch for the next push",
226
- knownHostsRepoUnchecked: "could not confirm whether this repository reads the file that was just refreshed\n refreshed: {written}\n {reason}\nthis is not a failure and not a confirmation: treat the repository as unchecked",
227
- knownHostsUncheckedNoRepo: "not inside a git repository, so there is no repository configuration to ask",
228
- knownHostsUncheckedExplicitPath: "--known-hosts named this file explicitly, so no repository was checked against it",
229
- knownHostsUncheckedProbe: "the repository's ssh command could not be run, so its effective known_hosts is unknown",
230
- knownHostsRepoElsewhere: "this repository does not read the file that was just refreshed\n refreshed: {written}\n this repository reads: {effective}\nuntil they agree, refreshing does nothing for pushes from here; set core.sshCommand in this repository:\n git config core.sshCommand \"{sshCommand}\"",
231
- knownHostsRepoUnconfigured: "this repository has no core.sshCommand, so it does not read the file that was just refreshed\n refreshed: {written}\n this repository reads: {effective}\nit connects through ssh's own configuration, or through a GIT_SSH_COMMAND set for each push, which this command cannot see and cannot vouch for; set core.sshCommand in this repository:\n git config core.sshCommand \"{sshCommand}\"",
232
- 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}`",
233
- cloneIdentityPinned: "pinned the Stamp SSH identity for {directory} (git config core.sshCommand)",
234
- cloneIdentityPinFailed: "could not write the SSH identity into {directory}; run it yourself: git -C {directory} config --local core.sshCommand \"{command}\"",
235
- loginHumanIntro: "Not a managed Raft agent. Humans and CI use STAMP_TOKEN:",
236
- loginHumanBrowser: " browser: {url}/login (reuse the session cookie value as STAMP_TOKEN)",
237
- loginHumanCI: " CI: a narrowly scoped deploy token",
238
- loginAgentReady: "Agent login ready ({service} @ {url}); access token valid until {expires} ({remaining})",
239
- loginTokenExpired: "Agent logged in ({service} @ {url}), but the access token expired at {expires} ({remaining}); the next command refreshes it",
240
- logoutForgot: "forgot agent session {path}",
241
- logoutNothing: "nothing stored (human/CI lane uses STAMP_TOKEN)",
242
- cliUpdateAvailable: "stamp {current} is out of date; {latest} is available: npm install -g @botiverse/stamp-cli@latest",
243
- usageRepoUse: "usage: {cli} repo use [DIR] [--identity KEY] [--known-hosts FILE]",
244
- repoUseDone: "{directory}: git now reaches Stamp with this agent's key {path} (set in this repository only)",
245
- staleSshCommand: "warning: this checkout's core.sshCommand points at {path}, which does not exist on this machine; run `{cli} repo use` here to re-pin it before your next push",
246
- repoUseFailed: "could not set core.sshCommand in {directory}: {detail}",
247
- keyEnsured: "this agent's own SSH key is ready: {path} ({fingerprint}); nothing to configure",
248
- keyEnsureFailed: "could not set up this agent's SSH key yet ({reason}); `{cli} repo clone` and `{cli} key enroll` will try again",
249
- repoCommitEmailSet: "commits in {directory} use this agent's commit email {email} (set in this repository only)",
250
- keyGenerated: "created this agent's own SSH key: {path} (kept in the agent's directory, not ~/.ssh)",
251
- enrolled: "enrolled {fingerprint} ({keyId})",
252
- enrolledIdentityRecorded: "`{cli} repo clone` on this machine will use {path}",
253
- enrolledIdentityNotRecorded: "the private key {path} is not on this machine, so `{cli} repo clone` here will need --identity FILE",
254
- bound: "bound {email}",
255
- usageKeyEnroll: "usage: {cli} key enroll [--public-key FILE|-]",
256
- usageKeyList: "usage: {cli} key list",
257
- usageKeyRevoke: "usage: {cli} key revoke KEY_ID",
258
- keyListEmpty: "no enrolled keys",
259
- keyRevoked: "revoked {keyId}",
260
- usageIdentityBind: "usage: {cli} identity bind --email ADDR",
261
- usageReceiptGet: "usage: {cli} receipt get <receipt-id>",
262
- usageReceiptList: "usage: {cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]",
263
- receiptListEmpty: "no receipts",
264
- receiptListMore: "More receipts; rerun with --limit and --cursor {cursor}.",
265
- receiptListBadResponse: "Unexpected receipt list response; check {cli} and gateway versions, then retry.",
266
- usageChangelog: "usage: {cli} changelog [--limit N] [--all]",
267
- changelogScopeAgent: "Showing CLI and API changes; --all shows everything.",
268
- changelogScopeAll: "Showing every change, including the web app and internal work.",
269
- changelogNoneForAgents: "no CLI or API changes in this release ({hidden} other; --all shows them)",
270
- changelogHiddenCount: "({hidden} other change(s) hidden; --all shows them)",
271
- changelogBuild: "Gateway build {version} ({commit})",
272
- changelogEmpty: "No releases recorded in this build.",
273
- changelogNoEntries: "no pull requests recorded",
274
- changelogCurrentMark: "<- running",
275
- usageFollow: "usage: {cli} <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
276
- usageSubscription: "usage: {cli} subscription pause|resume <owner/repo> --kind issue|pull --number N",
277
- usageWatch: "usage: {cli} {cmd} <owner/repo> --event TYPE",
278
- helpInstall: "install: {cmds}",
279
- helpAgentLogin: "agent login: {text}",
280
- sessionRejected: "{cli}: session rejected — run `{cli} login`",
281
- checkToken: "{cli}: check STAMP_TOKEN",
282
- notLoggedIn: "not logged in: run `{cli} login` (managed agent)",
283
- sessionOriginMismatch: "the stored session was issued for {stored}, not {target} — run `{cli} login` again",
284
- sessionOriginMismatchSibling: "the stored session was issued for {stored}, not {target} — {stored} is served by `{other}`; run that binary instead of `{cli}`",
285
- pair_mismatch: "refusing a mismatched instance pair: {origin} belongs to service {owner}, not {service} (task #439)",
286
- stampTokenMissing: "STAMP_TOKEN is not set (session or deploy token); inside a managed agent run `{cli} login`",
287
- admissionPartial: "refusing to run: partial managed-agent environment ({reason}); not falling back to STAMP_TOKEN",
288
- 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",
289
- 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",
290
- 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",
291
- keyPublicKeyMissing: "no SSH public key at {path}: create one with `ssh-keygen -t ed25519 -f {private}`, or pass --public-key FILE",
292
- invoke_not_json: "agent-login: `raft integration invoke` did not return JSON",
293
- invoke_not_object: "agent-login: invoke output is not an object",
294
- invoke_failed: "agent-login: invoke did not succeed",
295
- invoke_envelope: "agent-login: invoke envelope has unexpected fields",
296
- invoke_data: "agent-login: invoke result is missing data",
297
- invoke_data_fields: "agent-login: invoke data has unexpected fields",
298
- invoke_service: "agent-login: invoke service does not match the requested service",
299
- invoke_action: "agent-login: invoke action is not agent-login",
300
- invoke_http: "agent-login: agent-login action did not return HTTP 200",
301
- grant_body: "agent-login: invoke result is missing the grant body",
302
- grant_fields: "agent-login: grant result has unexpected fields",
303
- grant_schema: "agent-login: unexpected grant result schema",
304
- grant_service: "agent-login: grant result service mismatch",
305
- grant_missing: "agent-login: grant is missing",
306
- grant_expires_at: "agent-login: grant expires_at is not an RFC3339 timestamp",
307
- grant_expired: "agent-login: grant is already expired",
308
- grant_ttl: "agent-login: grant expiry exceeds the ceiling",
309
- session_not_object: "agent-login: exchange response is not an object",
310
- session_fields: "agent-login: session has unexpected fields",
311
- session_schema: "agent-login: unexpected session schema",
312
- session_token_type: "agent-login: unexpected token_type",
313
- session_missing: "agent-login: session missing {field}",
314
- session_access_exp: "agent-login: session access_expires_at is not RFC3339",
315
- session_access_expired: "agent-login: session access token is already expired",
316
- session_refresh_exp: "agent-login: session refresh_expires_at must be RFC3339 or null",
317
- session_refresh_expired: "agent-login: session refresh token is already expired",
318
- token_size_limit: "agent-login: token response exceeds the size limit",
319
- token_deadline: "agent-login: token endpoint exceeded the deadline",
320
- invoke_exit: "agent-login: raft invoke failed ({status}): {diagnostic}",
321
- exchange_redirect: "agent-login: grant exchange rejected redirect (HTTP {status})",
322
- exchange_failed: "agent-login: grant exchange failed (HTTP {status})",
323
- exchange_not_json: "agent-login: exchange response was not JSON",
324
- exchange_deadline: "agent-login: grant exchange exceeded the deadline",
325
- refresh_redirect: "agent-login: token refresh rejected redirect (HTTP {status})",
326
- refresh_failed: "agent-login: token refresh failed (HTTP {status})",
327
- refresh_not_json: "agent-login: refresh response was not JSON",
328
- refresh_deadline: "agent-login: token refresh exceeded the deadline",
329
- refresh_wait_timeout: "agent-login: timed out waiting for a concurrent token refresh",
330
- },
331
- };
332
-
333
- // The CLI speaks English only (artin 09-28): agents read, paste and search
334
- // its output, and one language keeps that consistent. --lang and STAMP_LANG
335
- // are still accepted, so existing scripts keep working, and ignored.
336
- export function selectLocale() {
337
- return "en";
338
- }
339
-
340
- // The binary that targets THIS instance. Set once by the entry point (main());
341
- // every command reference in the tables uses `{cli}` so user-visible copy names
342
- // the binary the reader actually invoked — a staging user must never be told to
343
- // run `stamp` (@phage: the error surface reaches users before the docs).
344
- // Product names ("Stamp"), the package id and historical facts are NOT `{cli}`.
345
- //
346
- // FAIL-LOUD (@Tenny): the value starts UNSET. A silent `"stamp"` default would
347
- // mean that if the entry never set the name, a staging user would quietly be
348
- // shown the PRODUCTION binary — the exact defect shape this task fixes. An unset
349
- // name renders as a conspicuous marker (and prefix() throws in a test), so a
350
- // broken parameter chain is a VISIBLE failure, never a plausible wrong value.
351
- let cliName = null;
352
-
353
- export function setCliName(name) {
354
- if (typeof name === "string" && name.length > 0) cliName = name;
355
- }
356
-
357
- /** For tests/diagnostics: the resolved entry binary, or null if never set. */
358
- export function currentCliName() {
359
- return cliName;
360
- }
361
-
362
- /** The `<binary>:` banner that prefixes user-facing diagnostics. It names the
363
- * binary the user actually ran, so a staging user sees `stamp-staging:` and not
364
- * the production name (task #444 / #439). */
365
- export function prefix() {
366
- // An unset name is a programming error: fail loudly rather than printing a
367
- // plausible-but-wrong production banner on a staging entry.
368
- const name = cliName ?? "<cli-unset>";
369
- return `${name}: `;
370
- }
371
-
372
- export function t(locale, key, vars = {}) {
373
- const table = messages[locale] || messages.en;
374
- let s = table[key] || messages.en[key] || key;
375
- const all = { cli: cliName ?? "<cli-unset>", ...vars };
376
- for (const [k, v] of Object.entries(all)) s = s.replaceAll(`{${k}}`, String(v));
377
- return s;
378
- }
package/lib/main.mjs DELETED
@@ -1,122 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import { basename } from "node:path";
3
- import { resolveAuth } from "./auth.mjs";
4
- import { makeClient, ApiError } from "./client.mjs";
5
- import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
6
- import { presentError, printGatewayError } from "./errors.mjs";
7
- import { makeUpdateNotice } from "./update-check.mjs";
8
- import { staleStampSshPath } from "./repo/ssh.mjs";
9
- import * as session from "./commands/session.mjs";
10
- import * as key from "./commands/key.mjs";
11
- import * as knownhosts from "./commands/knownhosts.mjs";
12
- import * as identity from "./commands/identity.mjs";
13
- import * as receipt from "./commands/receipt.mjs";
14
- import * as repo from "./commands/repo.mjs";
15
- import * as pr from "./commands/pr.mjs";
16
- import * as subscribe from "./commands/subscribe.mjs";
17
- import * as changelog from "./commands/changelog.mjs";
18
- import * as queue from "./commands/queue.mjs";
19
-
20
- const require = createRequire(import.meta.url);
21
- const pkg = require("../package.json");
22
-
23
- const commands = {
24
- login: session.login,
25
- logout: session.logout,
26
- whoami: session.whoami,
27
- "migration-help": session.migrationHelp,
28
- key: key.run,
29
- "known-hosts": knownhosts.run,
30
- identity: identity.run,
31
- receipt: receipt.run,
32
- repo: repo.run,
33
- pr: pr.run,
34
- follow: subscribe.follow,
35
- unfollow: subscribe.follow,
36
- subscription: subscribe.subscription,
37
- subscriptions: subscribe.subscriptions,
38
- watch: subscribe.watch,
39
- unwatch: subscribe.watch,
40
- changelog: changelog.run,
41
- queue: queue.run,
42
- };
43
-
44
- export async function main(argv, opts) {
45
- const args = [...argv];
46
- const out = opts.stdout ?? ((s) => console.log(s));
47
- const err = opts.stderr ?? ((s) => console.error(s));
48
- let env = opts.env ?? process.env;
49
- const exit = opts.exit ?? ((code) => process.exit(code));
50
- const localValues = new Set(["--limit", "--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--reason", "--reason-file", "--idempotency-key", "--method", "-b", "-F", "-R", "--branch", "--workflow", "--ci-policy", "--max-batch", "--wait", "--timeout", "--pr"]);
51
- let json = false, langFlag, help = false, version = false;
52
- const commandArgs = [];
53
- for (let i = 0; i < args.length; i++) {
54
- const arg = args[i];
55
- if (arg === "--json") json = true;
56
- else if (arg === "--lang") langFlag = args[++i];
57
- else if (arg === "--help" || arg === "-h") help = true;
58
- else if (arg === "--version" || arg === "-v") version = true;
59
- else {
60
- commandArgs.push(arg);
61
- if (localValues.has(arg) && i + 1 < args.length) commandArgs.push(args[++i]);
62
- }
63
- }
64
- args.splice(0, args.length, ...commandArgs);
65
- const locale = selectLocale(env, langFlag);
66
- const cliName = opts.cliName ?? (opts.argv1 ? basename(opts.argv1).replace(/\.mjs$/, "") : undefined);
67
- if (cliName !== undefined) setCliName(cliName);
68
- if (version) { out(pkg.version); return exit(0); }
69
- const cmd = args.shift();
70
- // The agent-facing document lives on the instance itself (/llms.txt), so
71
- // the help names this instance's copy.
72
- const docs = `${String(env.STAMP_URL || opts.urlBase || "https://stamp.build").replace(/\/+$/, "")}/llms.txt`;
73
- if (help || !cmd) { out(t(locale, "usage", { version: pkg.version, docs })); return exit(0); }
74
- const emit = (data, human) => { if (json) out(JSON.stringify(data, null, 2)); else human(); };
75
-
76
- let auth;
77
- try {
78
- auth = resolveAuth({ urlBase: opts.urlBase, urlExplicit: opts.urlExplicit, env, locale, service: env.STAMP_SERVICE || opts.serviceDefault || undefined, cliName });
79
- } catch (e) {
80
- err(`${prefix()}${presentError(locale, e)}`);
81
- return exit(1);
82
- }
83
- // An agent's key, enrollment record and pinned host key live in its own
84
- // directory (auth.stateDir); the repo helpers read it from the env they
85
- // already take. An explicit STAMP_AGENT_STATE_DIR (tests) wins.
86
- if (auth.stateDir && !env.STAMP_AGENT_STATE_DIR) env = { ...env, STAMP_AGENT_STATE_DIR: auth.stateDir };
87
- const onVersions = makeUpdateNotice({
88
- current: pkg.version, env, now: opts.now,
89
- warn: (latest) => err(`${prefix()}${t(locale, "cliUpdateAvailable", { current: pkg.version, latest })}`),
90
- });
91
- const api = makeClient(auth, opts.fetchImpl, {
92
- cliVersion: pkg.version, onVersions,
93
- readRetries: opts.networkReadRetries, retryDelayMs: opts.networkRetryDelayMs, sleep: opts.sleep,
94
- });
95
- const handler = commands[cmd];
96
- if (!handler) {
97
- out(t(locale, "usage", { version: pkg.version, docs }));
98
- return exit(1);
99
- }
100
-
101
- // A checkout moved from another machine keeps a core.sshCommand naming a key
102
- // or known_hosts file that is not here; say so now, on stderr and once,
103
- // rather than let the next push fail with an opaque ssh error. `repo use`
104
- // and `repo clone` are the fix, so they stay quiet.
105
- if (!(cmd === "repo" && (args[0] === "use" || args[0] === "clone"))) {
106
- const missing = staleStampSshPath({ cwd: opts.cwd ?? process.cwd(), env: opts.gitEnv ?? env, execImpl: opts.sshHintExec });
107
- if (missing) err(t(locale, "staleSshCommand", { path: missing }));
108
- }
109
-
110
- try {
111
- return await handler({ cmd, args, api, auth, locale, emit, json, out, err, exit, env, opts });
112
- } catch (e) {
113
- if (e instanceof ApiError) {
114
- err(`${prefix()}${e.message}`);
115
- printGatewayError(e, err);
116
- if (e.status === 401) err(auth.mode === "agent" ? t(locale, "sessionRejected") : t(locale, "checkToken"));
117
- return exit(1);
118
- }
119
- err(`${prefix()}${presentError(locale, e)}`);
120
- return exit(1);
121
- }
122
- }