@andorra-labs/code 0.1.16 → 0.1.17
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/dist/src/acp-agent.d.ts +6 -0
- package/dist/src/acp-agent.js +15 -4
- package/dist/src/agent-execution.js +11 -8
- package/dist/src/agent-mcp-catalog.js +1 -0
- package/dist/src/agent-mcp.d.ts +3 -0
- package/dist/src/agent-mcp.js +33 -1
- package/dist/src/andorra/entry.d.ts +10 -0
- package/dist/src/andorra/entry.js +18 -4
- package/dist/src/andorra/hosted.d.ts +2 -1
- package/dist/src/andorra/hosted.js +2 -1
- package/dist/src/andorra/notices.d.ts +5 -0
- package/dist/src/andorra/notices.js +7 -0
- package/dist/src/andorra/state.d.ts +3 -2
- package/dist/src/andorra/state.js +4 -4
- package/dist/src/andorra/terminal.js +7 -2
- package/dist/src/anthropic-credentials.js +2 -0
- package/dist/src/app-server/error.d.ts +5 -0
- package/dist/src/app-server/error.js +7 -0
- package/dist/src/app-server/protocol.d.ts +19 -44
- package/dist/src/app-server/protocol.js +5 -1
- package/dist/src/app-server/workspace.d.ts +89 -0
- package/dist/src/app-server/workspace.js +457 -11
- package/dist/src/app-server.d.ts +358 -32
- package/dist/src/app-server.js +2429 -509
- package/dist/src/bridge/cloud.d.ts +27 -0
- package/dist/src/bridge/cloud.js +187 -0
- package/dist/src/bridge/command.d.ts +30 -0
- package/dist/src/bridge/command.js +347 -0
- package/dist/src/bridge/control.d.ts +68 -0
- package/dist/src/bridge/control.js +233 -0
- package/dist/src/bridge/engines.d.ts +90 -0
- package/dist/src/bridge/engines.js +601 -0
- package/dist/src/bridge/host-ops.d.ts +9 -0
- package/dist/src/bridge/host-ops.js +129 -0
- package/dist/src/bridge/host.d.ts +47 -0
- package/dist/src/bridge/host.js +540 -0
- package/dist/src/bridge/link.d.ts +38 -0
- package/dist/src/bridge/link.js +508 -0
- package/dist/src/bridge/login-link.d.ts +29 -0
- package/dist/src/bridge/login-link.js +54 -0
- package/dist/src/bridge/protocol.d.ts +136 -0
- package/dist/src/bridge/protocol.js +11 -0
- package/dist/src/bridge/store.d.ts +12 -0
- package/dist/src/bridge/store.js +61 -0
- package/dist/src/bridge/wording.d.ts +6 -0
- package/dist/src/bridge/wording.js +10 -0
- package/dist/src/browser-server.js +7 -1
- package/dist/src/browser-ui/tokens.css +1 -1
- package/dist/src/change-authors.d.ts +41 -0
- package/dist/src/change-authors.js +146 -0
- package/dist/src/cli.js +182 -32
- package/dist/src/coding-tools.js +15 -15
- package/dist/src/command-screens.d.ts +6 -0
- package/dist/src/command-screens.js +14 -11
- package/dist/src/commands.d.ts +14 -2
- package/dist/src/compaction-phrases.js +1 -1
- package/dist/src/completion.js +82 -5
- package/dist/src/config.d.ts +71 -3
- package/dist/src/config.js +202 -77
- package/dist/src/deadline.js +13 -1
- package/dist/src/decision/checks.js +1 -1
- package/dist/src/decision/requestPhrases.js +0 -1
- package/dist/src/default-graph.js +1 -1
- package/dist/src/file-diff.d.ts +4 -0
- package/dist/src/file-diff.js +2 -1
- package/dist/src/github-app/agent-writes.d.ts +102 -0
- package/dist/src/github-app/agent-writes.js +320 -0
- package/dist/src/github-app/client.d.ts +349 -0
- package/dist/src/github-app/client.js +810 -0
- package/dist/src/github-app/event-source.d.ts +208 -0
- package/dist/src/github-app/event-source.js +684 -0
- package/dist/src/github-app/metrics.d.ts +32 -0
- package/dist/src/github-app/metrics.js +49 -0
- package/dist/src/github-app/review-loop.d.ts +274 -0
- package/dist/src/github-app/review-loop.js +1177 -0
- package/dist/src/github-app/review-node.d.ts +81 -0
- package/dist/src/github-app/review-node.js +205 -0
- package/dist/src/github-app/review-post.d.ts +73 -0
- package/dist/src/github-app/review-post.js +139 -0
- package/dist/src/github-app/review-text.d.ts +107 -0
- package/dist/src/github-app/review-text.js +1133 -0
- package/dist/src/github-app/review-threads.d.ts +47 -0
- package/dist/src/github-app/review-threads.js +107 -0
- package/dist/src/github-app/reviewer.d.ts +121 -0
- package/dist/src/github-app/reviewer.js +598 -0
- package/dist/src/github-app/store.d.ts +59 -0
- package/dist/src/github-app/store.js +148 -0
- package/dist/src/github-app/triggers.d.ts +141 -0
- package/dist/src/github-app/triggers.js +441 -0
- package/dist/src/github-names.d.ts +8 -0
- package/dist/src/github-names.js +8 -0
- package/dist/src/glob-search.d.ts +61 -0
- package/dist/src/glob-search.js +180 -0
- package/dist/src/graph-health.js +6 -1
- package/dist/src/graph-manager-chat.js +1 -1
- package/dist/src/graph-preview.d.ts +46 -0
- package/dist/src/graph-preview.js +55 -0
- package/dist/src/graph-provider-portability.js +2 -1
- package/dist/src/graph-runner.js +64 -3
- package/dist/src/graph-server.js +3 -3
- package/dist/src/graph-sync.js +3 -3
- package/dist/src/graph-ui/app.js +91 -7
- package/dist/src/graph-ui/icons.js +2 -1
- package/dist/src/graph-ui/studio.js +15 -1
- package/dist/src/graph-ui/tokens.css +1 -1
- package/dist/src/graphs.d.ts +34 -1
- package/dist/src/graphs.js +158 -14
- package/dist/src/image-input.d.ts +16 -0
- package/dist/src/image-input.js +41 -0
- package/dist/src/membership.d.ts +10 -0
- package/dist/src/membership.js +19 -4
- package/dist/src/model-health-cache.js +1 -1
- package/dist/src/model-metadata.d.ts +6 -0
- package/dist/src/model-metadata.js +35 -15
- package/dist/src/model-relay/local.d.ts +116 -0
- package/dist/src/model-relay/local.js +468 -0
- package/dist/src/model-relay/remote.d.ts +129 -0
- package/dist/src/model-relay/remote.js +252 -0
- package/dist/src/model-relay/runs.d.ts +34 -0
- package/dist/src/model-relay/runs.js +146 -0
- package/dist/src/model-relay/wire.d.ts +5 -0
- package/dist/src/model-relay/wire.js +5 -0
- package/dist/src/project-registry.d.ts +21 -0
- package/dist/src/project-registry.js +74 -0
- package/dist/src/provider-import.d.ts +0 -12
- package/dist/src/provider-import.js +7 -195
- package/dist/src/providers.d.ts +23 -2
- package/dist/src/providers.js +25 -4
- package/dist/src/pull-request-logs.d.ts +12 -1
- package/dist/src/pull-request-logs.js +14 -3
- package/dist/src/pull-requests.d.ts +327 -7
- package/dist/src/pull-requests.js +429 -51
- package/dist/src/react-runtime.js +1 -1
- package/dist/src/remote/engine-pool.d.ts +88 -4
- package/dist/src/remote/engine-pool.js +366 -89
- package/dist/src/remote/roots.d.ts +19 -0
- package/dist/src/remote/roots.js +45 -7
- package/dist/src/remote/types.d.ts +0 -44
- package/dist/src/run-control.d.ts +7 -0
- package/dist/src/run-control.js +23 -0
- package/dist/src/run-records.d.ts +7 -2
- package/dist/src/run-records.js +71 -6
- package/dist/src/runtime.d.ts +5 -1
- package/dist/src/runtime.js +10 -2
- package/dist/src/session-changes.d.ts +35 -0
- package/dist/src/session-changes.js +194 -6
- package/dist/src/session-monitor.js +2 -1
- package/dist/src/session-reaper.d.ts +1 -1
- package/dist/src/session-reaper.js +6 -1
- package/dist/src/session-summary.d.ts +2 -1
- package/dist/src/session-summary.js +2 -1
- package/dist/src/sessions.d.ts +11 -1
- package/dist/src/sessions.js +17 -4
- package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
- package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
- package/dist/src/skills/bundled/provenance.json +2 -2
- package/dist/src/skills/runtime-skills.js +1 -1
- package/dist/src/telemetry/emitter.d.ts +15 -0
- package/dist/src/telemetry/emitter.js +35 -1
- package/dist/src/telemetry/schema.d.ts +25 -2
- package/dist/src/telemetry/schema.js +52 -4
- package/dist/src/telemetry/surface.d.ts +2 -1
- package/dist/src/telemetry/surface.js +4 -1
- package/dist/src/terminal-ui.d.ts +1 -0
- package/dist/src/terminal-ui.js +10 -3
- package/dist/src/test-edit-guard.d.ts +7 -0
- package/dist/src/test-edit-guard.js +49 -1
- package/dist/src/timers.d.ts +2 -0
- package/dist/src/tools.js +59 -9
- package/package.json +6 -1
- package/dist/src/remote/cert.d.ts +0 -11
- package/dist/src/remote/cert.js +0 -87
- package/dist/src/remote/client.d.ts +0 -119
- package/dist/src/remote/client.js +0 -544
- package/dist/src/remote/command.d.ts +0 -4
- package/dist/src/remote/command.js +0 -194
- package/dist/src/remote/errors.d.ts +0 -11
- package/dist/src/remote/errors.js +0 -14
- package/dist/src/remote/network.d.ts +0 -22
- package/dist/src/remote/network.js +0 -102
- package/dist/src/remote/pairing.d.ts +0 -63
- package/dist/src/remote/pairing.js +0 -299
- package/dist/src/remote/pem.d.ts +0 -2
- package/dist/src/remote/pem.js +0 -7
- package/dist/src/remote/serve.d.ts +0 -68
- package/dist/src/remote/serve.js +0 -244
- package/dist/src/remote/server.d.ts +0 -21
- package/dist/src/remote/server.js +0 -406
package/dist/src/file-diff.js
CHANGED
|
@@ -74,6 +74,7 @@ export function textDiff(oldText, newText, options = {}) {
|
|
|
74
74
|
let changes = midA.length && midB.length
|
|
75
75
|
? diffArrays(midA, midB, { timeout: MATCH_TIMEOUT_MS, maxEditLength: MATCH_EDIT_LIMIT })
|
|
76
76
|
: undefined;
|
|
77
|
+
const approximate = changes === undefined && midA.length > 0 && midB.length > 0;
|
|
77
78
|
changes ??= [
|
|
78
79
|
...(midA.length ? [{ value: midA, added: false, removed: true }] : []),
|
|
79
80
|
...(midB.length ? [{ value: midB, added: true, removed: false }] : []),
|
|
@@ -179,7 +180,7 @@ export function textDiff(oldText, newText, options = {}) {
|
|
|
179
180
|
if (lines.length)
|
|
180
181
|
hunks.push({ oldStart, oldLines, newStart, newLines, lines });
|
|
181
182
|
}
|
|
182
|
-
return { hunks, linesAdded, linesRemoved, hiddenLines: hidden };
|
|
183
|
+
return { hunks, linesAdded, linesRemoved, hiddenLines: hidden, ...(approximate ? { approximate: true } : {}) };
|
|
183
184
|
}
|
|
184
185
|
export function coarseCounts(oldText, newText) {
|
|
185
186
|
if (oldText === newText)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { GhRunner, SessionPullRequest } from '../pull-requests.js';
|
|
2
|
+
import { type BotWriteAction, type BotWriteFallback, type GitHubAppClient, type GitHubCoverage } from './client.js';
|
|
3
|
+
/**
|
|
4
|
+
* The agent's writes on its session's pull request (`design/specs/github-app.md`, "Bot replies"): a reply to a
|
|
5
|
+
* review thread, resolving or reopening one, and a comment on the PR's conversation. On a PR the GitHub App
|
|
6
|
+
* covers, with agent writes set to the bot, the account API makes the write as the App's bot; the engine never
|
|
7
|
+
* holds the installation token that does it. Otherwise, and whenever the service says it wrote nothing, the
|
|
8
|
+
* write goes through gh as the account the session's PR record names, and never as another account. A write
|
|
9
|
+
* whose fate is unknown is never repeated through gh.
|
|
10
|
+
*/
|
|
11
|
+
/** `github.app.agentWrites`: who the agent's PR writes post as. */
|
|
12
|
+
export type AgentWritesSetting = 'bot' | 'me';
|
|
13
|
+
export type AgentPullRequestWrite = {
|
|
14
|
+
action: 'reply';
|
|
15
|
+
threadId: string;
|
|
16
|
+
body: string;
|
|
17
|
+
} | {
|
|
18
|
+
action: 'resolve';
|
|
19
|
+
threadId: string;
|
|
20
|
+
resolved: boolean;
|
|
21
|
+
} | {
|
|
22
|
+
action: 'comment';
|
|
23
|
+
body: string;
|
|
24
|
+
};
|
|
25
|
+
/** A thread the agent named that is not on its session's PR: refused before anything was written. */
|
|
26
|
+
export declare class ThreadElsewhere extends Error {
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The person's own pending review on the PR: GitHub files a reply made through gh into it, where nobody sees it
|
|
30
|
+
* until the person submits the review. Refused before anything is written.
|
|
31
|
+
*/
|
|
32
|
+
export declare class PendingReview extends Error {
|
|
33
|
+
}
|
|
34
|
+
export declare const AGENT_WRITE_ACTIONS: readonly ["reply", "resolve", "comment"];
|
|
35
|
+
/** A ULID: 48 bits of milliseconds, then 80 random bits, in Crockford's base 32. */
|
|
36
|
+
export declare function newRequestId(now?: number, random?: Uint8Array): string;
|
|
37
|
+
/** The write the pull_request tool's `reply`, `resolve` or `comment` asks for, checked before anything is approved or sent. */
|
|
38
|
+
export declare function agentWriteFromArgs(args: Record<string, unknown>): AgentPullRequestWrite;
|
|
39
|
+
export declare const botAction: (write: AgentPullRequestWrite) => BotWriteAction;
|
|
40
|
+
/** Why a write went through gh without asking the service: the PR's coverage, or the person's setting. */
|
|
41
|
+
export declare function coverageReason(coverage: GitHubCoverage, pullRequest: SessionPullRequest): string;
|
|
42
|
+
/** Why the service wrote nothing, in the words the tool result uses. */
|
|
43
|
+
export declare function fallbackReason(reason: BotWriteFallback, pullRequest: SessionPullRequest): string;
|
|
44
|
+
export declare const AS_ME_REASON = "agent replies on pull requests are set to post as you";
|
|
45
|
+
export interface AgentWriteResult {
|
|
46
|
+
/** The tool result: who posted (or may have) and why. */
|
|
47
|
+
text: string;
|
|
48
|
+
/** `pending`: filed into the person's pending review, not visible yet. `unknown`: it may have been written. */
|
|
49
|
+
by: 'bot' | 'gh' | 'pending' | 'unknown';
|
|
50
|
+
as?: string;
|
|
51
|
+
url?: string;
|
|
52
|
+
/** The new comment's GraphQL node id, when GitHub's answer named it (the gh route's reply and comment). */
|
|
53
|
+
nodeId?: string;
|
|
54
|
+
/** Why it went through gh. */
|
|
55
|
+
reason?: string;
|
|
56
|
+
requestId?: string;
|
|
57
|
+
}
|
|
58
|
+
export interface AgentWriteOptions {
|
|
59
|
+
pullRequest: SessionPullRequest;
|
|
60
|
+
write: AgentPullRequestWrite;
|
|
61
|
+
setting: AgentWritesSetting;
|
|
62
|
+
/** The PR's coverage, as the event source last learned it. Only `covered` and `permissions-pending` ask the service. */
|
|
63
|
+
coverage: GitHubCoverage;
|
|
64
|
+
client: Pick<GitHubAppClient, 'write'>;
|
|
65
|
+
gh: GhRunner;
|
|
66
|
+
/**
|
|
67
|
+
* Asked once the route is known and the write passes its checks, before anything is sent anywhere, with who
|
|
68
|
+
* the write posts as (see `approvalDetail`). A fallback to gh after the bot wrote nothing is not asked again.
|
|
69
|
+
*/
|
|
70
|
+
approve(detail: string): Promise<void>;
|
|
71
|
+
/** The bot's login, for the approval (`GET /v1/github`'s `bot`); unknown, "the Andorra Code bot". */
|
|
72
|
+
botName?: string;
|
|
73
|
+
/**
|
|
74
|
+
* Reads the PR record, the setting and the coverage again once the approval is given: a write whose PR, account
|
|
75
|
+
* or route changed while the person was asked is refused, so it never goes where the approval did not say.
|
|
76
|
+
*/
|
|
77
|
+
current?(): Promise<{
|
|
78
|
+
pullRequest: SessionPullRequest;
|
|
79
|
+
setting: AgentWritesSetting;
|
|
80
|
+
coverage: GitHubCoverage;
|
|
81
|
+
} | undefined>;
|
|
82
|
+
signal?: AbortSignal;
|
|
83
|
+
requestId?: () => string;
|
|
84
|
+
}
|
|
85
|
+
export declare const CHANGED_WHILE_APPROVING = "The pull request or reply setting changed while awaiting approval; retry.";
|
|
86
|
+
/**
|
|
87
|
+
* What the approval says the write does and who it posts as: the bot first and the PR record's account if the
|
|
88
|
+
* bot cannot, or the account alone. One approval covers both, so a fallback is never asked about again.
|
|
89
|
+
*/
|
|
90
|
+
export declare function approvalDetail(write: AgentPullRequestWrite, pullRequest: SessionPullRequest, bot: boolean, botName?: string): string;
|
|
91
|
+
/**
|
|
92
|
+
* Whether an agent write goes to the service first: agent writes set to the bot, and the PR covered (or
|
|
93
|
+
* `permissions-pending`, where the service decides per action). The Auto-fix prompt uses the same rule, so
|
|
94
|
+
* the prompt and the tool agree on who the replies post as.
|
|
95
|
+
*/
|
|
96
|
+
export declare const asksBot: (setting: AgentWritesSetting, coverage: GitHubCoverage) => boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Carries out one agent write on the session's tracked PR. Throws for a write that must not fall back (the
|
|
99
|
+
* service refused it as malformed, or the thread is not on this PR), for one the person's pending review would
|
|
100
|
+
* swallow, and for a gh write that certainly failed; answers the tool result otherwise.
|
|
101
|
+
*/
|
|
102
|
+
export declare function performAgentWrite(options: AgentWriteOptions): Promise<AgentWriteResult>;
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { GITHUB_OWNER, GITHUB_REPO } from '../github-names.js';
|
|
3
|
+
import { runAsAccount } from '../pull-request-details.js';
|
|
4
|
+
import { COMMENT_BODY_LIMIT } from '../pull-request-review.js';
|
|
5
|
+
import { BOT_BODY_BYTES } from './client.js';
|
|
6
|
+
import { escapeWriteBody } from './review-text.js';
|
|
7
|
+
/** A thread the agent named that is not on its session's PR: refused before anything was written. */
|
|
8
|
+
export class ThreadElsewhere extends Error {
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The person's own pending review on the PR: GitHub files a reply made through gh into it, where nobody sees it
|
|
12
|
+
* until the person submits the review. Refused before anything is written.
|
|
13
|
+
*/
|
|
14
|
+
export class PendingReview extends Error {
|
|
15
|
+
}
|
|
16
|
+
export const AGENT_WRITE_ACTIONS = ['reply', 'resolve', 'comment'];
|
|
17
|
+
const THREAD_ID = /^PRRT_[A-Za-z0-9_-]{1,120}$/;
|
|
18
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
19
|
+
/** A ULID: 48 bits of milliseconds, then 80 random bits, in Crockford's base 32. */
|
|
20
|
+
export function newRequestId(now = Date.now(), random = randomBytes(10)) {
|
|
21
|
+
if (random.length !== 10)
|
|
22
|
+
throw new Error('a request id takes 10 random bytes');
|
|
23
|
+
const value = (BigInt(Math.max(0, Math.floor(now))) & ((1n << 48n) - 1n)) << 80n | BigInt(`0x${Buffer.from(random).toString('hex')}`);
|
|
24
|
+
let id = '';
|
|
25
|
+
for (let shift = 125n; shift >= 0n; shift -= 5n)
|
|
26
|
+
id += CROCKFORD[Number((value >> shift) & 31n)];
|
|
27
|
+
return id;
|
|
28
|
+
}
|
|
29
|
+
function threadIdOf(value) {
|
|
30
|
+
if (value === undefined)
|
|
31
|
+
throw new Error('threadId is required: the review thread\'s id (PRRT_…), from gh\'s reviewThreads query');
|
|
32
|
+
if (typeof value !== 'string' || !THREAD_ID.test(value))
|
|
33
|
+
throw new Error('threadId must be a review thread id (PRRT_…), as gh\'s reviewThreads query gives it');
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
function bodyOf(value) {
|
|
37
|
+
if (value === undefined)
|
|
38
|
+
throw new Error('body is required');
|
|
39
|
+
if (typeof value !== 'string')
|
|
40
|
+
throw new Error('body must be text');
|
|
41
|
+
if (value.trim() === '')
|
|
42
|
+
throw new Error('body is empty');
|
|
43
|
+
// No hidden HTML comment, and never the review marker's opening, which only the service writes (R16).
|
|
44
|
+
const body = escapeWriteBody(value);
|
|
45
|
+
if (body.length > COMMENT_BODY_LIMIT)
|
|
46
|
+
throw new Error(`body is longer than GitHub's ${COMMENT_BODY_LIMIT} characters`);
|
|
47
|
+
return body;
|
|
48
|
+
}
|
|
49
|
+
/** The write the pull_request tool's `reply`, `resolve` or `comment` asks for, checked before anything is approved or sent. */
|
|
50
|
+
export function agentWriteFromArgs(args) {
|
|
51
|
+
const unexpected = (names) => {
|
|
52
|
+
for (const name of names)
|
|
53
|
+
if (args[name] !== undefined)
|
|
54
|
+
throw new Error(`${name} does not apply to ${String(args.action)}`);
|
|
55
|
+
};
|
|
56
|
+
switch (args.action) {
|
|
57
|
+
case 'reply':
|
|
58
|
+
unexpected(['resolved', 'url', 'autoFix', 'mergeWhenReady', 'draft', 'review', 'reviewRounds', 'reviewInstruction', 'reviewModel', 'timeoutMinutes']);
|
|
59
|
+
return { action: 'reply', threadId: threadIdOf(args.threadId), body: bodyOf(args.body) };
|
|
60
|
+
case 'resolve':
|
|
61
|
+
unexpected(['body', 'url', 'autoFix', 'mergeWhenReady', 'draft', 'review', 'reviewRounds', 'reviewInstruction', 'reviewModel', 'timeoutMinutes']);
|
|
62
|
+
if (args.resolved !== undefined && typeof args.resolved !== 'boolean')
|
|
63
|
+
throw new Error('resolved must be a boolean');
|
|
64
|
+
return { action: 'resolve', threadId: threadIdOf(args.threadId), resolved: args.resolved !== false };
|
|
65
|
+
case 'comment':
|
|
66
|
+
unexpected(['threadId', 'resolved', 'url', 'autoFix', 'mergeWhenReady', 'draft', 'review', 'reviewRounds', 'reviewInstruction', 'reviewModel', 'timeoutMinutes']);
|
|
67
|
+
return { action: 'comment', body: bodyOf(args.body) };
|
|
68
|
+
default: throw new Error('action must be reply, resolve or comment');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export const botAction = (write) => write.action === 'resolve' ? (write.resolved ? 'resolve' : 'unresolve') : write.action;
|
|
72
|
+
const repository = (pullRequest) => `${pullRequest.owner}/${pullRequest.repo}`;
|
|
73
|
+
/** Why a write went through gh without asking the service: the PR's coverage, or the person's setting. */
|
|
74
|
+
export function coverageReason(coverage, pullRequest) {
|
|
75
|
+
switch (coverage) {
|
|
76
|
+
case 'signed-out': return 'this engine is not signed in to Andorra';
|
|
77
|
+
case 'not-connected': return 'your GitHub account is not connected to Andorra';
|
|
78
|
+
case 'suspended': return `Andorra Code's installation for ${pullRequest.owner} is suspended`;
|
|
79
|
+
case 'disabled': return 'the Andorra Code GitHub App is turned off';
|
|
80
|
+
case 'unavailable': return 'Andorra\'s service was unavailable';
|
|
81
|
+
default: return `this pull request is not covered by Andorra Code (${repository(pullRequest)})`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Why the service wrote nothing, in the words the tool result uses. */
|
|
85
|
+
export function fallbackReason(reason, pullRequest) {
|
|
86
|
+
switch (reason) {
|
|
87
|
+
case 'signed-out': return 'this engine is not signed in to Andorra';
|
|
88
|
+
case 'unauthorized': return 'Andorra\'s service did not accept this engine\'s sign-in';
|
|
89
|
+
case 'disabled': return 'the Andorra Code GitHub App is turned off on Andorra\'s service';
|
|
90
|
+
case 'not-allowed': return 'this Andorra account cannot use the Andorra Code GitHub App yet';
|
|
91
|
+
case 'not-covered': return `this pull request is not covered by Andorra Code (${repository(pullRequest)})`;
|
|
92
|
+
case 'forbidden': return 'Andorra\'s service refused the bot\'s write';
|
|
93
|
+
case 'rate-limited': return 'the bot reached its write limit for now';
|
|
94
|
+
case 'late': return 'Andorra\'s service could not start the bot\'s write in time';
|
|
95
|
+
case 'github-refused': return 'GitHub refused the bot\'s write';
|
|
96
|
+
case 'no-route': return 'Andorra\'s service does not offer bot replies here';
|
|
97
|
+
case 'unavailable': return 'Andorra\'s service was unavailable';
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export const AS_ME_REASON = 'agent replies on pull requests are set to post as you';
|
|
101
|
+
export const CHANGED_WHILE_APPROVING = 'The pull request or reply setting changed while awaiting approval; retry.';
|
|
102
|
+
/**
|
|
103
|
+
* What the approval says the write does and who it posts as: the bot first and the PR record's account if the
|
|
104
|
+
* bot cannot, or the account alone. One approval covers both, so a fallback is never asked about again.
|
|
105
|
+
*/
|
|
106
|
+
export function approvalDetail(write, pullRequest, bot, botName) {
|
|
107
|
+
const what = write.action === 'reply' ? 'Posts a reply' : write.action === 'comment' ? 'Posts a comment' : write.resolved ? 'Resolves a review thread' : 'Reopens a review thread';
|
|
108
|
+
const account = pullRequest.ghUser ?? 'your gh account';
|
|
109
|
+
const name = botName !== undefined && /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\[bot\]$/.test(botName) ? botName : 'the Andorra Code bot';
|
|
110
|
+
return bot ? `${what} on ${pullRequest.url} as ${name}; as ${account} if the bot can't.` : `${what} on ${pullRequest.url} as ${account}.`;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Whether an agent write goes to the service first: agent writes set to the bot, and the PR covered (or
|
|
114
|
+
* `permissions-pending`, where the service decides per action). The Auto-fix prompt uses the same rule, so
|
|
115
|
+
* the prompt and the tool agree on who the replies post as.
|
|
116
|
+
*/
|
|
117
|
+
export const asksBot = (setting, coverage) => setting === 'bot' && (coverage === 'covered' || coverage === 'permissions-pending');
|
|
118
|
+
const noun = (action) => action === 'comment' ? 'comment' : action === 'reply' ? 'reply' : action === 'resolve' ? 'resolve' : 'unresolve';
|
|
119
|
+
function botText(action, as, url) {
|
|
120
|
+
const verb = action === 'reply' ? 'Replied' : action === 'comment' ? 'Commented' : action === 'resolve' ? 'Resolved the thread' : 'Unresolved the thread';
|
|
121
|
+
return `${verb} as ${as}.${url === undefined ? '' : ` ${url}`}`;
|
|
122
|
+
}
|
|
123
|
+
function ghText(action, login, reason, url) {
|
|
124
|
+
const verb = action === 'resolve' ? 'Resolved the thread' : action === 'unresolve' ? 'Unresolved the thread' : 'Posted';
|
|
125
|
+
return `${verb} as ${login}: ${reason}.${url === undefined ? '' : ` ${url}`}`;
|
|
126
|
+
}
|
|
127
|
+
/** The tracked PR's owner and name are safe to put in a REST path: GitHub's name characters, and not `.` or `..`. */
|
|
128
|
+
function checkRepository(pullRequest) {
|
|
129
|
+
if (!GITHUB_OWNER.test(pullRequest.owner) || !GITHUB_REPO.test(pullRequest.repo)
|
|
130
|
+
|| !Number.isSafeInteger(pullRequest.number) || pullRequest.number < 1) {
|
|
131
|
+
throw new Error(`The tracked pull request ${pullRequest.url} does not name a GitHub repository this tool can write to; nothing was posted.`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Carries out one agent write on the session's tracked PR. Throws for a write that must not fall back (the
|
|
136
|
+
* service refused it as malformed, or the thread is not on this PR), for one the person's pending review would
|
|
137
|
+
* swallow, and for a gh write that certainly failed; answers the tool result otherwise.
|
|
138
|
+
*/
|
|
139
|
+
export async function performAgentWrite(options) {
|
|
140
|
+
const { pullRequest, write, signal } = options;
|
|
141
|
+
const action = botAction(write);
|
|
142
|
+
checkRepository(pullRequest);
|
|
143
|
+
const bot = asksBot(options.setting, options.coverage);
|
|
144
|
+
if (bot && write.action !== 'resolve' && Buffer.byteLength(write.body, 'utf8') > BOT_BODY_BYTES) {
|
|
145
|
+
throw new Error(`body is longer than the ${BOT_BODY_BYTES / 1024} KiB a bot ${noun(action)} may carry; shorten it. Nothing was posted.`);
|
|
146
|
+
}
|
|
147
|
+
// Everything the write will be refused for locally is checked: now the person is asked, before anything is sent.
|
|
148
|
+
await options.approve(approvalDetail(write, pullRequest, bot, options.botName));
|
|
149
|
+
if (options.current) {
|
|
150
|
+
// As edit_file re-reads its file: what was approved must still be what would be written.
|
|
151
|
+
const now = await options.current();
|
|
152
|
+
if (now === undefined || now.pullRequest.url !== pullRequest.url || (now.pullRequest.ghUser ?? null) !== (pullRequest.ghUser ?? null)
|
|
153
|
+
|| asksBot(now.setting, now.coverage) !== bot)
|
|
154
|
+
throw new Error(CHANGED_WHILE_APPROVING);
|
|
155
|
+
}
|
|
156
|
+
let reason = options.setting === 'me' ? AS_ME_REASON : coverageReason(options.coverage, pullRequest);
|
|
157
|
+
if (bot) {
|
|
158
|
+
const requestId = (options.requestId ?? (() => newRequestId()))();
|
|
159
|
+
const outcome = await options.client.write({
|
|
160
|
+
requestId, owner: pullRequest.owner, repo: pullRequest.repo, number: pullRequest.number, action,
|
|
161
|
+
...(write.action === 'comment' ? {} : { threadId: write.threadId }), ...(write.action === 'resolve' ? {} : { body: write.body }),
|
|
162
|
+
}, signal);
|
|
163
|
+
switch (outcome.kind) {
|
|
164
|
+
case 'written': return { text: botText(action, outcome.as, outcome.url), by: 'bot', as: outcome.as, ...(outcome.url === undefined ? {} : { url: outcome.url }), requestId };
|
|
165
|
+
case 'refused':
|
|
166
|
+
if (outcome.reason === 'not-found') {
|
|
167
|
+
throw new ThreadElsewhere(write.action === 'comment' ? `Andorra's service did not find ${pullRequest.url}; nothing was posted.` : `Thread ${write.threadId} is not on ${pullRequest.url}; nothing was posted.`);
|
|
168
|
+
}
|
|
169
|
+
throw new Error(`Andorra's service refused the ${noun(action)} as malformed (${outcome.field ?? 'request'}); nothing was posted.`);
|
|
170
|
+
case 'unknown':
|
|
171
|
+
return { text: `The bot's ${noun(action)} may not have ${write.action === 'resolve' ? 'gone through' : 'posted'}; check the PR before trying again. (${outcome.detail}.)`, by: 'unknown', requestId };
|
|
172
|
+
case 'not-written':
|
|
173
|
+
reason = fallbackReason(outcome.reason, pullRequest);
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
signal?.throwIfAborted();
|
|
178
|
+
// gh as the record's account (or, with none recorded, the account gh answers as now), never another one.
|
|
179
|
+
const login = pullRequest.ghUser ?? await viewerLogin(options.gh);
|
|
180
|
+
let outcome;
|
|
181
|
+
try {
|
|
182
|
+
outcome = await runAsAccount(options.gh, login, gh => ghWrite(gh, pullRequest, write, login));
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (error instanceof ThreadElsewhere || error instanceof PendingReview)
|
|
186
|
+
throw error;
|
|
187
|
+
throw new Error(`Could not ${write.action === 'resolve' ? (write.resolved ? 'resolve the thread' : 'reopen the thread') : 'post'} as ${login} (${reason}): ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
188
|
+
}
|
|
189
|
+
if (outcome.kind === 'unknown') {
|
|
190
|
+
return { text: `The ${noun(action)} as ${login} may have ${write.action === 'resolve' ? 'gone through' : 'posted'}; check the PR before trying again. (${outcome.detail}.)`, by: 'unknown', as: login, reason };
|
|
191
|
+
}
|
|
192
|
+
if (outcome.kind === 'pending') {
|
|
193
|
+
return {
|
|
194
|
+
text: `Filed as ${login} into ${login}'s pending review on ${pullRequest.url}, not posted: GitHub shows it to no one until they submit that review, so the thread is not answered yet. Do not resolve it; tell the user.`,
|
|
195
|
+
by: 'pending', as: login, ...(outcome.url === undefined ? {} : { url: outcome.url }), ...(outcome.nodeId === undefined ? {} : { nodeId: outcome.nodeId }), reason,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
return { text: ghText(action, login, reason, outcome.url), by: 'gh', as: login, ...(outcome.url === undefined ? {} : { url: outcome.url }), ...(outcome.nodeId === undefined ? {} : { nodeId: outcome.nodeId }), reason };
|
|
199
|
+
}
|
|
200
|
+
const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
|
|
201
|
+
const githubUrl = (value) => typeof value === 'string' && /^https:\/\/github\.com\/\S*$/.test(value) && value.length <= 2048 ? value : undefined;
|
|
202
|
+
/** A GraphQL read with its variables in a JSON body on gh's standard input, so no text passes through an argument. */
|
|
203
|
+
async function graphql(gh, query, variables) {
|
|
204
|
+
const raw = await gh(['api', 'graphql', '--hostname', 'github.com', '--input', '-'], { input: JSON.stringify({ query, variables }) });
|
|
205
|
+
const value = record(JSON.parse(raw));
|
|
206
|
+
const errors = (Array.isArray(value.errors) ? value.errors : []).map(entry => record(entry).message).filter((message) => typeof message === 'string');
|
|
207
|
+
if (errors.length > 0)
|
|
208
|
+
throw new Error(`GraphQL: ${errors.join('; ')}`);
|
|
209
|
+
return record(value.data);
|
|
210
|
+
}
|
|
211
|
+
async function viewerLogin(gh) {
|
|
212
|
+
const login = record((await graphql(gh, 'query { viewer { login } }', {})).viewer).login;
|
|
213
|
+
if (typeof login !== 'string' || !/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})$/.test(login))
|
|
214
|
+
throw new Error('gh did not say which GitHub account it uses.');
|
|
215
|
+
return login;
|
|
216
|
+
}
|
|
217
|
+
/** GraphQL error types that mean GitHub refused the operation, so nothing was written (as the service reads them). */
|
|
218
|
+
const REFUSALS = new Set(['FORBIDDEN', 'INSUFFICIENT_SCOPES', 'NOT_FOUND', 'RATE_LIMITED', 'UNPROCESSABLE']);
|
|
219
|
+
/** What gh printed for a write, read as GitHub's answer: the result when it is there, a refusal, or neither. */
|
|
220
|
+
function answerOf(raw, field) {
|
|
221
|
+
let value;
|
|
222
|
+
try {
|
|
223
|
+
value = record(JSON.parse(raw));
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return { unknown: 'gh answered something that is not JSON' };
|
|
227
|
+
}
|
|
228
|
+
if (field === undefined)
|
|
229
|
+
return githubUrl(value.html_url) === undefined ? { unknown: 'GitHub\'s answer named no comment' } : { result: value };
|
|
230
|
+
// A mutation's result that is there is the answer, errors or not: the write was made.
|
|
231
|
+
const result = record(value.data)[field];
|
|
232
|
+
if (typeof result === 'object' && result !== null)
|
|
233
|
+
return { result: record(result) };
|
|
234
|
+
const errors = Array.isArray(value.errors) ? value.errors.map(record) : [];
|
|
235
|
+
if (errors.length > 0 && errors.every(error => typeof error.type === 'string' && REFUSALS.has(error.type))) {
|
|
236
|
+
return { refused: `GraphQL: ${errors.map(error => String(error.message ?? error.type)).join('; ')}` };
|
|
237
|
+
}
|
|
238
|
+
return { unknown: errors.length > 0 ? `GitHub answered errors without the ${field} result` : `GitHub's answer had no ${field} result` };
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* One write through gh, read so that only a write GitHub certainly refused reads as failed (thrown): a result
|
|
242
|
+
* GitHub gave is a success even beside errors, and a gh stopped by its timeout, an answer that is not JSON, or
|
|
243
|
+
* one with neither a result nor a typed refusal is of unknown fate. A failure before anything was sent (the
|
|
244
|
+
* account's token lookup, gh missing, no connection) is thrown as it is.
|
|
245
|
+
*/
|
|
246
|
+
async function ghMutation(run, field) {
|
|
247
|
+
let raw;
|
|
248
|
+
try {
|
|
249
|
+
raw = await run();
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
const failure = error;
|
|
253
|
+
const text = failure instanceof Error ? failure.message : String(error);
|
|
254
|
+
if (/^gh auth |^gh user must not be empty|returned no token for|ENOENT|error connecting to|dial tcp|no such host|connection refused/i.test(text))
|
|
255
|
+
throw error;
|
|
256
|
+
if (failure.killed === true)
|
|
257
|
+
return { unknown: 'gh was stopped before GitHub\'s answer arrived' };
|
|
258
|
+
if (typeof failure.stdout === 'string') {
|
|
259
|
+
const answer = answerOf(failure.stdout, field);
|
|
260
|
+
if ('result' in answer)
|
|
261
|
+
return answer;
|
|
262
|
+
if ('refused' in answer)
|
|
263
|
+
throw new Error(answer.refused, { cause: error });
|
|
264
|
+
// A refusal gh names by its 4xx prints GitHub's error body, with no result: nothing was written.
|
|
265
|
+
if (/\bHTTP 4\d\d\b/.test(text))
|
|
266
|
+
throw error;
|
|
267
|
+
return answer;
|
|
268
|
+
}
|
|
269
|
+
if (/\bHTTP 4\d\d\b/.test(text))
|
|
270
|
+
throw error;
|
|
271
|
+
return { unknown: `gh failed without GitHub's answer (${text.replace(/\s+/g, ' ').slice(0, 200)})` };
|
|
272
|
+
}
|
|
273
|
+
const answer = answerOf(raw, field);
|
|
274
|
+
if ('refused' in answer)
|
|
275
|
+
throw new Error(answer.refused);
|
|
276
|
+
return answer;
|
|
277
|
+
}
|
|
278
|
+
const THREAD_QUERY = 'query($id: ID!, $owner: String!, $name: String!, $number: Int!) { node(id: $id) { ... on PullRequestReviewThread { pullRequest { number repository { databaseId } } comments(first: 1) { nodes { url } } } } repository(owner: $owner, name: $name) { databaseId pullRequest(number: $number) { reviews(states: [PENDING], first: 1) { totalCount } } } }';
|
|
279
|
+
const REPLY = 'mutation($thread: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $thread, body: $body }) { comment { id url state } } }';
|
|
280
|
+
const resolveMutation = (resolved) => `mutation($thread: ID!) { ${resolved ? 'resolveReviewThread' : 'unresolveReviewThread'}(input: { threadId: $thread }) { thread { id isResolved } } }`;
|
|
281
|
+
/**
|
|
282
|
+
* The write itself, through gh. A reply or resolve first reads the thread and the tracked PR in one query, and
|
|
283
|
+
* refuses a thread on another PR by repository id and number (so a renamed or transferred repository still
|
|
284
|
+
* matches), as the service does; a reply is also refused while the account has a pending review on the PR,
|
|
285
|
+
* which GitHub would file it into. Answers the new comment's URL (the thread's first comment's for a resolve).
|
|
286
|
+
*/
|
|
287
|
+
async function ghWrite(gh, pullRequest, write, login) {
|
|
288
|
+
const stdin = (input) => ({ input: JSON.stringify(input) });
|
|
289
|
+
if (write.action === 'comment') {
|
|
290
|
+
const answer = await ghMutation(() => gh(['api', '--hostname', 'github.com', '-X', 'POST', `repos/${pullRequest.owner}/${pullRequest.repo}/issues/${pullRequest.number}/comments`, '--input', '-'], stdin({ body: write.body })), undefined);
|
|
291
|
+
return 'unknown' in answer ? { kind: 'unknown', detail: answer.unknown } : { kind: 'written', ...urlOf(answer.result.html_url), ...nodeIdOf(answer.result.node_id) };
|
|
292
|
+
}
|
|
293
|
+
const data = await graphql(gh, THREAD_QUERY, { id: write.threadId, owner: pullRequest.owner, name: pullRequest.repo, number: pullRequest.number });
|
|
294
|
+
const node = record(data.node);
|
|
295
|
+
const pull = record(node.pullRequest);
|
|
296
|
+
const tracked = record(data.repository);
|
|
297
|
+
const repositoryId = tracked.databaseId;
|
|
298
|
+
if (pull.number !== pullRequest.number || typeof repositoryId !== 'number' || record(pull.repository).databaseId !== repositoryId) {
|
|
299
|
+
throw new ThreadElsewhere(`Thread ${write.threadId} is not on ${pullRequest.url}; nothing was posted.`);
|
|
300
|
+
}
|
|
301
|
+
const first = githubUrl(record((Array.isArray(record(node.comments).nodes) ? record(node.comments).nodes : [])[0]).url);
|
|
302
|
+
if (write.action === 'resolve') {
|
|
303
|
+
const field = write.resolved ? 'resolveReviewThread' : 'unresolveReviewThread';
|
|
304
|
+
const answer = await ghMutation(() => gh(['api', 'graphql', '--hostname', 'github.com', '--input', '-'], stdin({ query: resolveMutation(write.resolved), variables: { thread: write.threadId } })), field);
|
|
305
|
+
return 'unknown' in answer ? { kind: 'unknown', detail: answer.unknown } : { kind: 'written', ...urlOf(first) };
|
|
306
|
+
}
|
|
307
|
+
const pending = record(record(record(tracked.pullRequest).reviews)).totalCount;
|
|
308
|
+
if (typeof pending === 'number' && pending > 0) {
|
|
309
|
+
throw new PendingReview(`Nothing was posted: ${login} has a pending review on ${pullRequest.url}, and GitHub would file this reply into it, where nobody sees it until they submit that review. Leave the thread unresolved and tell the user, who can submit or discard that review; then reply again.`);
|
|
310
|
+
}
|
|
311
|
+
const answer = await ghMutation(() => gh(['api', 'graphql', '--hostname', 'github.com', '--input', '-'], stdin({ query: REPLY, variables: { thread: write.threadId, body: write.body } })), 'addPullRequestReviewThreadReply');
|
|
312
|
+
if ('unknown' in answer)
|
|
313
|
+
return { kind: 'unknown', detail: answer.unknown };
|
|
314
|
+
const comment = record(answer.result.comment);
|
|
315
|
+
// A pending review started between the check and the reply still takes it: say so rather than "posted".
|
|
316
|
+
return { kind: comment.state === 'PENDING' ? 'pending' : 'written', ...urlOf(comment.url), ...nodeIdOf(comment.id) };
|
|
317
|
+
}
|
|
318
|
+
const urlOf = (value) => { const url = githubUrl(value); return url === undefined ? {} : { url }; };
|
|
319
|
+
/** A comment's GraphQL node id (an issue comment's `IC_…`, a review comment's `PRRC_…`), as GitHub named it. */
|
|
320
|
+
const nodeIdOf = (value) => typeof value === 'string' && /^[A-Za-z0-9_=+/-]{4,200}$/.test(value) ? { nodeId: value } : {};
|