copilot-agents-mcp 0.0.1 → 0.2.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/README.md +88 -152
- package/dist/cli.js +166 -98
- package/dist/compact.js +23 -0
- package/dist/delivery.js +17 -0
- package/dist/errors.js +163 -63
- package/dist/follow-up.js +47 -0
- package/dist/github-hosts.js +61 -0
- package/dist/github.js +39 -59
- package/dist/notify.js +40 -96
- package/dist/selection.js +16 -112
- package/dist/server.js +442 -160
- package/dist/state.js +20 -2
- package/dist/status-local.js +79 -0
- package/dist/swe-models.js +49 -28
- package/dist/task-present.js +78 -0
- package/dist/task-status.js +124 -0
- package/dist/task-urls.js +24 -0
- package/dist/tasks.js +227 -0
- package/dist/time-format.js +3 -0
- package/dist/watch.js +36 -18
- package/dist/webhook-http.js +159 -0
- package/dist/webhooks.js +102 -0
- package/package.json +14 -2
- package/dist/http.js +0 -77
package/dist/errors.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { compactStringify, compactValue } from "./compact.js";
|
|
1
2
|
export const API_VERSION = "2026-03-10";
|
|
2
3
|
export const GITHUB_APP_SLUG = "copilot-agents-mcp";
|
|
3
4
|
export function githubAppInstallUrl() {
|
|
@@ -6,31 +7,6 @@ export function githubAppInstallUrl() {
|
|
|
6
7
|
export function appNotInstalledMessage() {
|
|
7
8
|
return `The app is not installed in any repository. Install it at ${githubAppInstallUrl()}.`;
|
|
8
9
|
}
|
|
9
|
-
export function withMissingAppInstall(message, status, path, appCredential) {
|
|
10
|
-
if (!appCredential || status !== 404)
|
|
11
|
-
return message;
|
|
12
|
-
const repository = repositoryFromPath(path);
|
|
13
|
-
if (!repository)
|
|
14
|
-
return message;
|
|
15
|
-
return `Install the app for ${repository.owner}/${repository.repo}: ${githubAppInstallUrl()}. ${message}`;
|
|
16
|
-
}
|
|
17
|
-
function repositoryFromPath(path) {
|
|
18
|
-
const match = /\/repos\/([^/]+)\/([^/?]+)/.exec(path);
|
|
19
|
-
const ownerPart = match?.[1];
|
|
20
|
-
const repoPart = match?.[2];
|
|
21
|
-
if (!ownerPart || !repoPart)
|
|
22
|
-
return null;
|
|
23
|
-
try {
|
|
24
|
-
const owner = decodeURIComponent(ownerPart);
|
|
25
|
-
const repo = decodeURIComponent(repoPart);
|
|
26
|
-
if (!owner || !repo)
|
|
27
|
-
return null;
|
|
28
|
-
return { owner, repo };
|
|
29
|
-
}
|
|
30
|
-
catch {
|
|
31
|
-
return null;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
10
|
export const TASK_HAS_NO_PULL_REQUEST = "task_has_no_pull_request";
|
|
35
11
|
export const TASK_PULL_REQUEST_NOT_OPEN = "task_pull_request_not_open";
|
|
36
12
|
export class ToolFailure extends Error {
|
|
@@ -39,43 +15,115 @@ export class ToolFailure extends Error {
|
|
|
39
15
|
this.name = "ToolFailure";
|
|
40
16
|
}
|
|
41
17
|
}
|
|
42
|
-
export class
|
|
18
|
+
export class AuthError extends Error {
|
|
43
19
|
constructor(message) {
|
|
44
20
|
super(message);
|
|
45
|
-
this.name = "
|
|
21
|
+
this.name = "AuthError";
|
|
46
22
|
}
|
|
47
23
|
}
|
|
48
|
-
export class
|
|
24
|
+
export class KeyringError extends Error {
|
|
49
25
|
constructor(message) {
|
|
50
26
|
super(message);
|
|
51
|
-
this.name = "
|
|
27
|
+
this.name = "KeyringError";
|
|
52
28
|
}
|
|
53
29
|
}
|
|
54
|
-
export
|
|
55
|
-
|
|
30
|
+
export const NO_SESSION_MESSAGE = "No GitHub session is available. A prior `npx copilot-agents-mcp login` stores credentials in the OS keyring, which may be unreachable from this process (for example a different D-Bus session on Linux). Set GITHUB_PERSONAL_ACCESS_TOKEN in the environment or run `npx copilot-agents-mcp login` in the same session as this server.";
|
|
31
|
+
export const NO_SESSION_STALE_WARNING = "No GitHub session in this process; returning stored data only (not refreshed). Set GITHUB_PERSONAL_ACCESS_TOKEN or run `npx copilot-agents-mcp login`.";
|
|
32
|
+
export class CodedToolFailure extends ToolFailure {
|
|
33
|
+
code;
|
|
34
|
+
retryable;
|
|
35
|
+
retry_after_s;
|
|
36
|
+
constructor(code, message, options) {
|
|
56
37
|
super(message);
|
|
57
|
-
this.name = "
|
|
38
|
+
this.name = "CodedToolFailure";
|
|
39
|
+
this.code = code;
|
|
40
|
+
this.retryable = options?.retryable ?? false;
|
|
41
|
+
this.retry_after_s = options?.retry_after_s;
|
|
42
|
+
}
|
|
43
|
+
toBody() {
|
|
44
|
+
const body = {
|
|
45
|
+
error: {
|
|
46
|
+
code: this.code,
|
|
47
|
+
message: this.message,
|
|
48
|
+
retryable: this.retryable,
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
if (this.retry_after_s !== undefined)
|
|
52
|
+
body.error.retry_after_s = this.retry_after_s;
|
|
53
|
+
return body;
|
|
58
54
|
}
|
|
59
55
|
}
|
|
60
|
-
export class
|
|
61
|
-
constructor(message) {
|
|
62
|
-
super(message);
|
|
63
|
-
this.name = "
|
|
56
|
+
export class GitHubError extends CodedToolFailure {
|
|
57
|
+
constructor(message, failure) {
|
|
58
|
+
super(failure?.code ?? "upstream_error", message, failure);
|
|
59
|
+
this.name = "GitHubError";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export class ModelsError extends CodedToolFailure {
|
|
63
|
+
constructor(message, failure) {
|
|
64
|
+
super(failure?.code ?? "upstream_error", message, failure);
|
|
65
|
+
this.name = "ModelsError";
|
|
64
66
|
}
|
|
65
67
|
}
|
|
66
|
-
export const NO_SESSION_MESSAGE = "No GitHub session is available. Set GITHUB_PERSONAL_ACCESS_TOKEN or run `npx copilot-agents-mcp login`.";
|
|
67
68
|
export function toolError(message) {
|
|
69
|
+
const body = typeof message === "string" ? legacyErrorBody(message) : message;
|
|
70
|
+
const text = compactStringify(body);
|
|
68
71
|
return {
|
|
69
72
|
isError: true,
|
|
70
|
-
content: [{ type: "text", text
|
|
73
|
+
content: [{ type: "text", text }],
|
|
71
74
|
};
|
|
72
75
|
}
|
|
73
76
|
export function toolJson(value) {
|
|
77
|
+
const compact = compactValue(value);
|
|
78
|
+
return {
|
|
79
|
+
content: [{ type: "text", text: compactStringify(compact) }],
|
|
80
|
+
structuredContent: compact,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function legacyErrorBody(message) {
|
|
74
84
|
return {
|
|
75
|
-
|
|
76
|
-
|
|
85
|
+
error: {
|
|
86
|
+
code: classifyMessage(message),
|
|
87
|
+
message,
|
|
88
|
+
retryable: /retry after \d+ seconds/i.test(message) || message.includes("rate limit"),
|
|
89
|
+
...(retryAfterFromMessage(message) !== undefined ? { retry_after_s: retryAfterFromMessage(message) } : {}),
|
|
90
|
+
},
|
|
77
91
|
};
|
|
78
92
|
}
|
|
93
|
+
function classifyMessage(message) {
|
|
94
|
+
if (message === NO_SESSION_MESSAGE)
|
|
95
|
+
return "not_authenticated";
|
|
96
|
+
if (/missing required parameter/i.test(message))
|
|
97
|
+
return "invalid_argument";
|
|
98
|
+
if (/^repo must use/i.test(message))
|
|
99
|
+
return "invalid_argument";
|
|
100
|
+
if (/is not available\. Accepted models/i.test(message))
|
|
101
|
+
return "model_unavailable";
|
|
102
|
+
if (/HTTP 404/.test(message) || /not found/i.test(message))
|
|
103
|
+
return "not_found";
|
|
104
|
+
if (/HTTP 403/.test(message) || /Missing .* permission/i.test(message))
|
|
105
|
+
return "forbidden";
|
|
106
|
+
if (/HTTP 429/.test(message) || /rate limit/i.test(message))
|
|
107
|
+
return "rate_limited";
|
|
108
|
+
if (/HTTP 504|timeout/i.test(message))
|
|
109
|
+
return "upstream_timeout";
|
|
110
|
+
if (/HTTP \d+/.test(message))
|
|
111
|
+
return "upstream_error";
|
|
112
|
+
return "invalid_argument";
|
|
113
|
+
}
|
|
114
|
+
function retryAfterFromMessage(message) {
|
|
115
|
+
const match = /retry after (\d+) seconds/i.exec(message);
|
|
116
|
+
if (!match?.[1])
|
|
117
|
+
return undefined;
|
|
118
|
+
const value = Number(match[1]);
|
|
119
|
+
return Number.isFinite(value) ? value : undefined;
|
|
120
|
+
}
|
|
121
|
+
export function failureToError(error) {
|
|
122
|
+
if (error instanceof CodedToolFailure)
|
|
123
|
+
return error.toBody();
|
|
124
|
+
const message = failureMessage(error);
|
|
125
|
+
return legacyErrorBody(message);
|
|
126
|
+
}
|
|
79
127
|
export function failureMessage(error) {
|
|
80
128
|
if (error instanceof ToolFailure
|
|
81
129
|
|| error instanceof GitHubError
|
|
@@ -97,15 +145,68 @@ export function isModelUnavailable(message) {
|
|
|
97
145
|
return MODEL_UNAVAILABLE.test(message);
|
|
98
146
|
}
|
|
99
147
|
export function formatApiError(status, headers, body) {
|
|
148
|
+
return apiFailure(status, headers, body).message;
|
|
149
|
+
}
|
|
150
|
+
export function apiFailure(status, headers, body, context) {
|
|
100
151
|
const record = body && typeof body === "object" ? body : {};
|
|
101
|
-
const
|
|
102
|
-
const details = flattenErrors(record.errors);
|
|
103
|
-
let text = details ? `${message}: ${details}` : message;
|
|
152
|
+
const upstreamMessage = typeof body === "string" ? body : typeof record.message === "string" ? record.message : "";
|
|
104
153
|
const retry = retrySeconds(headers);
|
|
105
|
-
|
|
106
|
-
|
|
154
|
+
const limited = status === 429 || (status === 403 && (retry !== null || headers.get("x-ratelimit-remaining") === "0" || /rate limit/i.test(upstreamMessage)));
|
|
155
|
+
let code = "upstream_error";
|
|
156
|
+
let hint = "The upstream request failed. Check GitHub service status before trying again.";
|
|
157
|
+
if (limited) {
|
|
158
|
+
code = "rate_limited";
|
|
159
|
+
hint = "GitHub rate limit exceeded. Wait before trying again.";
|
|
160
|
+
}
|
|
161
|
+
else if (status === 401) {
|
|
162
|
+
code = "not_authenticated";
|
|
163
|
+
hint = "Authentication failed. Run `npx copilot-agents-mcp login` or check GITHUB_PERSONAL_ACCESS_TOKEN.";
|
|
164
|
+
}
|
|
165
|
+
else if (status === 403) {
|
|
166
|
+
code = "forbidden";
|
|
167
|
+
hint = "Access denied. Check repository access and credential permissions.";
|
|
168
|
+
if (context?.createTask) {
|
|
169
|
+
hint += " Copilot coding agent may not be enabled for this repository. Ask a repository or organization administrator to enable it and check the organization's model policy for agent tasks.";
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
else if (status === 404) {
|
|
173
|
+
code = "not_found";
|
|
174
|
+
hint = "Resource not found or is not accessible. Check the repository or task ID and your access.";
|
|
175
|
+
if (context?.appRepository)
|
|
176
|
+
hint += ` Install the app for the repository: ${githubAppInstallUrl()}.`;
|
|
177
|
+
}
|
|
178
|
+
else if (status === 400 || status === 422) {
|
|
179
|
+
code = "invalid_argument";
|
|
180
|
+
hint = "Validation Failed. Check the task arguments.";
|
|
181
|
+
const details = flattenErrors(record.errors);
|
|
182
|
+
if (details)
|
|
183
|
+
hint = `Validation Failed: ${details}. Check the task arguments.`;
|
|
184
|
+
}
|
|
185
|
+
else if (status === 409) {
|
|
186
|
+
code = "conflict";
|
|
187
|
+
hint = "The request conflicts with the current state. Read the task's current status before trying again.";
|
|
107
188
|
}
|
|
108
|
-
|
|
189
|
+
else if (status === 408 || status === 504) {
|
|
190
|
+
code = "upstream_timeout";
|
|
191
|
+
hint = "The upstream request timed out. Check the task's current status before trying again.";
|
|
192
|
+
}
|
|
193
|
+
if ([400, 409, 422].includes(status) && /^cannot abort:\s*no active session[.!]?$/i.test(upstreamMessage.trim())) {
|
|
194
|
+
hint = "cannot abort: no active session. Read the task's current status.";
|
|
195
|
+
}
|
|
196
|
+
if ((status === 403 || status === 422) && /model/i.test(upstreamMessage)
|
|
197
|
+
&& /not (?:allowed|available|enabled|supported)|disabled|policy|isn.?t available/i.test(upstreamMessage)) {
|
|
198
|
+
hint += " The selected model is not allowed or available for agent tasks. Use list_copilot_models and check the organization's model policy.";
|
|
199
|
+
}
|
|
200
|
+
const missing = context?.permission ? missingPermission(status, headers, body, context.permission) : null;
|
|
201
|
+
let message = `HTTP ${status}: ${missing ? `${missing} ` : ""}${hint}`;
|
|
202
|
+
if (limited && retry !== null)
|
|
203
|
+
message += ` Retry after ${retry} seconds.`;
|
|
204
|
+
return {
|
|
205
|
+
code,
|
|
206
|
+
message,
|
|
207
|
+
retryable: limited || status === 408 || status >= 500,
|
|
208
|
+
...(limited && retry !== null ? { retry_after_s: retry } : {}),
|
|
209
|
+
};
|
|
109
210
|
}
|
|
110
211
|
function flattenErrors(errors) {
|
|
111
212
|
if (!Array.isArray(errors))
|
|
@@ -115,25 +216,22 @@ function flattenErrors(errors) {
|
|
|
115
216
|
if (!item || typeof item !== "object")
|
|
116
217
|
continue;
|
|
117
218
|
const record = item;
|
|
118
|
-
if (typeof record.message === "string" && record.message.trim()) {
|
|
119
|
-
parts.push(record.message.trim());
|
|
120
|
-
continue;
|
|
121
|
-
}
|
|
122
219
|
const field = typeof record.field === "string" ? record.field : "";
|
|
123
220
|
const code = typeof record.code === "string" ? record.code : "";
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
parts.push(
|
|
221
|
+
if (["prompt", "model", "base_ref", "head_ref", "custom_agent", "create_pull_request"].includes(field)
|
|
222
|
+
&& ["missing_field", "invalid", "missing", "already_exists", "unprocessable"].includes(code)) {
|
|
223
|
+
parts.push(`${field} ${code}`);
|
|
224
|
+
}
|
|
127
225
|
}
|
|
128
226
|
return parts.length > 0 ? parts.join("; ") : null;
|
|
129
227
|
}
|
|
130
228
|
function retrySeconds(headers) {
|
|
131
229
|
const retryAfter = headers.get("retry-after");
|
|
132
|
-
if (retryAfter && /^\d+$/.test(retryAfter.trim()))
|
|
133
|
-
return Number(retryAfter
|
|
230
|
+
if (retryAfter && /^\d+$/.test(retryAfter.trim()) && Number.isSafeInteger(Number(retryAfter)))
|
|
231
|
+
return Number(retryAfter);
|
|
134
232
|
const remaining = headers.get("x-ratelimit-remaining");
|
|
135
233
|
const reset = headers.get("x-ratelimit-reset");
|
|
136
|
-
if (remaining === "0" && reset && /^\d+$/.test(reset.trim())) {
|
|
234
|
+
if (remaining === "0" && reset && /^\d+$/.test(reset.trim()) && Number.isSafeInteger(Number(reset))) {
|
|
137
235
|
return Math.max(0, Number(reset.trim()) - Math.floor(Date.now() / 1000));
|
|
138
236
|
}
|
|
139
237
|
return null;
|
|
@@ -175,19 +273,21 @@ function acceptedPermissions(header) {
|
|
|
175
273
|
const eq = trimmed.indexOf("=");
|
|
176
274
|
const slug = (eq === -1 ? trimmed : trimmed.slice(0, eq)).trim().toLowerCase();
|
|
177
275
|
const level = eq === -1 ? "" : trimmed.slice(eq + 1).trim().toLowerCase();
|
|
178
|
-
if (!slug)
|
|
179
|
-
continue;
|
|
180
276
|
const name = permissionLabel(slug);
|
|
277
|
+
if (!name || (level && !["read", "write", "admin"].includes(level)))
|
|
278
|
+
continue;
|
|
181
279
|
labels.push(level ? `${name}: ${level}` : name);
|
|
182
280
|
}
|
|
183
281
|
return labels;
|
|
184
282
|
}
|
|
185
283
|
function permissionLabel(slug) {
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
284
|
+
const labels = {
|
|
285
|
+
agent_tasks: "Agent tasks",
|
|
286
|
+
pull_requests: "Pull requests",
|
|
287
|
+
contents: "Contents",
|
|
288
|
+
metadata: "Metadata",
|
|
289
|
+
};
|
|
290
|
+
return Object.prototype.hasOwnProperty.call(labels, slug) ? labels[slug] : undefined;
|
|
191
291
|
}
|
|
192
292
|
function joinEnglish(items) {
|
|
193
293
|
if (items.length <= 1)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { formatCheckAfterUtc } from "./time-format.js";
|
|
2
|
+
export const DEFAULT_FIRST_CHECK_MS = 10 * 60 * 1000;
|
|
3
|
+
export const DEFAULT_MIN_INTERVAL_S = 300;
|
|
4
|
+
export function followUpMode(channels, watcherStarted) {
|
|
5
|
+
const webhook = channels.includes("webhook");
|
|
6
|
+
if (webhook && watcherStarted) {
|
|
7
|
+
return { mode: "push", channels: ["webhook"] };
|
|
8
|
+
}
|
|
9
|
+
if (webhook && !watcherStarted) {
|
|
10
|
+
return { mode: "check_later", channels: [], degraded: true };
|
|
11
|
+
}
|
|
12
|
+
return { mode: "check_later", channels: [] };
|
|
13
|
+
}
|
|
14
|
+
export function followUpBlock(channels, watcherStarted, now = Date.now()) {
|
|
15
|
+
const plan = followUpMode(channels, watcherStarted);
|
|
16
|
+
const block = {
|
|
17
|
+
mode: plan.mode,
|
|
18
|
+
check_after: new Date(now + DEFAULT_FIRST_CHECK_MS).toISOString(),
|
|
19
|
+
min_interval_s: DEFAULT_MIN_INTERVAL_S,
|
|
20
|
+
check_with: "list_agent_tasks",
|
|
21
|
+
};
|
|
22
|
+
if (plan.channels.length > 0)
|
|
23
|
+
block.channels = plan.channels;
|
|
24
|
+
return block;
|
|
25
|
+
}
|
|
26
|
+
export function createFollowUpNextStep(mode, owner, taskId, watcherDegraded, checkAfterIso) {
|
|
27
|
+
if (watcherDegraded && mode === "check_later") {
|
|
28
|
+
return `${checkLaterBase(owner, taskId, checkAfterIso)} The notifier could not start.`;
|
|
29
|
+
}
|
|
30
|
+
if (mode === "push") {
|
|
31
|
+
const ownerHint = owner ? "" : " Pass owner=<your agent name> so your scheduled check sees only your tasks.";
|
|
32
|
+
return `Task queued; cloud tasks usually take 5-30 minutes. End your turn now. Do not wait and do not call get_agent_task in a loop.${ownerHint} A completion notice will be POSTed to the configured endpoint. If you are woken by it, call get_agent_task once for the result.`;
|
|
33
|
+
}
|
|
34
|
+
const schedule = scheduleClause(owner, taskId, checkAfterIso);
|
|
35
|
+
const ownerHint = owner ? "" : " Pass owner=<your agent name> so your scheduled check sees only your tasks.";
|
|
36
|
+
return `Task queued; cloud tasks usually take 5-30 minutes. Nothing will notify you. End your turn now; do not wait or call tools in a loop.${ownerHint} ${schedule} Otherwise tell the user to ask you for the result later.`;
|
|
37
|
+
}
|
|
38
|
+
function scheduleClause(owner, taskId, checkAfterIso) {
|
|
39
|
+
const filter = owner
|
|
40
|
+
? `list_agent_tasks with owner="${owner}"`
|
|
41
|
+
: `list_agent_tasks with task_ids=["${taskId}"]`;
|
|
42
|
+
return `If you can schedule a later check, first check not before ${formatCheckAfterUtc(checkAfterIso)}; then call ${filter}, repeating no more often than every 5 minutes and stopping when all_terminal is true.`;
|
|
43
|
+
}
|
|
44
|
+
function checkLaterBase(owner, taskId, checkAfterIso) {
|
|
45
|
+
const schedule = scheduleClause(owner, taskId, checkAfterIso);
|
|
46
|
+
return `Task queued; cloud tasks usually take 5-30 minutes. Nothing will notify you. End your turn now; do not wait or call tools in a loop. ${schedule}`;
|
|
47
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export function githubApiBase(env) {
|
|
2
|
+
const raw = env.COPILOT_AGENTS_GITHUB_API_BASE_URL?.trim();
|
|
3
|
+
if (!raw)
|
|
4
|
+
return undefined;
|
|
5
|
+
let url;
|
|
6
|
+
try {
|
|
7
|
+
url = new URL(raw);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
throw new Error("COPILOT_AGENTS_GITHUB_API_BASE_URL is not a valid URL.");
|
|
11
|
+
}
|
|
12
|
+
const host = url.hostname;
|
|
13
|
+
const loopback = host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
|
|
14
|
+
if (url.protocol !== "https:" && !loopback) {
|
|
15
|
+
throw new Error("COPILOT_AGENTS_GITHUB_API_BASE_URL must use https unless the host is loopback.");
|
|
16
|
+
}
|
|
17
|
+
return raw.replace(/\/$/, "");
|
|
18
|
+
}
|
|
19
|
+
export function githubWebHost(env = process.env) {
|
|
20
|
+
const api = githubApiBase(env);
|
|
21
|
+
if (!api)
|
|
22
|
+
return "github.com";
|
|
23
|
+
const url = new URL(api);
|
|
24
|
+
const host = url.hostname.toLowerCase();
|
|
25
|
+
if (host === "api.github.com")
|
|
26
|
+
return "github.com";
|
|
27
|
+
if (host.startsWith("api.") && host.endsWith(".ghe.com"))
|
|
28
|
+
return host.slice("api.".length);
|
|
29
|
+
const path = url.pathname.replace(/\/$/, "");
|
|
30
|
+
if (path === "/api/v3" || path.endsWith("/api/v3"))
|
|
31
|
+
return host;
|
|
32
|
+
if (host.startsWith("api."))
|
|
33
|
+
return host.slice("api.".length);
|
|
34
|
+
return host;
|
|
35
|
+
}
|
|
36
|
+
function isApiStyleUrl(parsed) {
|
|
37
|
+
const host = parsed.hostname.toLowerCase();
|
|
38
|
+
const path = parsed.pathname.toLowerCase();
|
|
39
|
+
if (host.startsWith("api."))
|
|
40
|
+
return true;
|
|
41
|
+
if (path.startsWith("/api/") || path.startsWith("/api/v3/"))
|
|
42
|
+
return true;
|
|
43
|
+
if (path.startsWith("/repos/"))
|
|
44
|
+
return true;
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
export function githubPageUrl(url, env = process.env) {
|
|
48
|
+
if (!url?.trim())
|
|
49
|
+
return undefined;
|
|
50
|
+
try {
|
|
51
|
+
const parsed = new URL(url.trim());
|
|
52
|
+
if (parsed.hostname.toLowerCase() !== githubWebHost(env))
|
|
53
|
+
return undefined;
|
|
54
|
+
if (isApiStyleUrl(parsed))
|
|
55
|
+
return undefined;
|
|
56
|
+
return parsed.toString();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
package/dist/github.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { Ajv } from "ajv";
|
|
3
3
|
import addFormatsDefault from "ajv-formats";
|
|
4
|
-
import { GitHubError, API_VERSION,
|
|
4
|
+
import { GitHubError, API_VERSION, apiFailure } from "./errors.js";
|
|
5
5
|
const INTERNAL_AGENTS_BASE = "https://api.github.com/cmc_internal/api/agents";
|
|
6
6
|
const SCHEMA_KEYWORDS = new Set([
|
|
7
7
|
"type",
|
|
@@ -79,11 +79,13 @@ export function assertSchema(validate, value, label) {
|
|
|
79
79
|
.join("; ");
|
|
80
80
|
throw new GitHubError(`The GitHub response does not match the ${label} schema: ${details}`);
|
|
81
81
|
}
|
|
82
|
+
export const GITHUB_FETCH_TIMEOUT_MS = 30_000;
|
|
82
83
|
export function createGitHubClient(options) {
|
|
83
84
|
const fetchImpl = options.fetch ?? fetch;
|
|
84
85
|
const baseUrl = (options.baseUrl ?? "https://api.github.com").replace(/\/$/, "");
|
|
85
86
|
const internalBaseUrl = (options.internalBaseUrl ?? INTERNAL_AGENTS_BASE).replace(/\/$/, "");
|
|
86
87
|
const tokens = options.tokens;
|
|
88
|
+
const fetchTimeoutMs = options.fetchTimeoutMs ?? GITHUB_FETCH_TIMEOUT_MS;
|
|
87
89
|
return {
|
|
88
90
|
createTask(input) {
|
|
89
91
|
const body = { prompt: input.prompt, model: input.model };
|
|
@@ -106,6 +108,7 @@ export function createGitHubClient(options) {
|
|
|
106
108
|
validate: createResponse,
|
|
107
109
|
label: "create task",
|
|
108
110
|
permission: "Agent tasks",
|
|
111
|
+
fetchTimeoutMs,
|
|
109
112
|
});
|
|
110
113
|
},
|
|
111
114
|
getTask(input) {
|
|
@@ -122,6 +125,7 @@ export function createGitHubClient(options) {
|
|
|
122
125
|
validate: getResponse,
|
|
123
126
|
label: "read task",
|
|
124
127
|
permission: "Agent tasks",
|
|
128
|
+
fetchTimeoutMs,
|
|
125
129
|
});
|
|
126
130
|
},
|
|
127
131
|
async findPullRequest(input) {
|
|
@@ -138,6 +142,7 @@ export function createGitHubClient(options) {
|
|
|
138
142
|
path: `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}/pulls?${query.toString()}`,
|
|
139
143
|
method: "GET",
|
|
140
144
|
permission: "Pull requests",
|
|
145
|
+
fetchTimeoutMs,
|
|
141
146
|
});
|
|
142
147
|
return matchPull(parsed, input.id);
|
|
143
148
|
},
|
|
@@ -150,6 +155,7 @@ export function createGitHubClient(options) {
|
|
|
150
155
|
path: `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}/pulls/${encodeURIComponent(String(input.number))}`,
|
|
151
156
|
method: "GET",
|
|
152
157
|
permission: "Pull requests",
|
|
158
|
+
fetchTimeoutMs,
|
|
153
159
|
});
|
|
154
160
|
return readPullState(parsed, input.number);
|
|
155
161
|
},
|
|
@@ -165,6 +171,7 @@ export function createGitHubClient(options) {
|
|
|
165
171
|
profile: "internal",
|
|
166
172
|
acceptEmpty: true,
|
|
167
173
|
permission: "Contents: write",
|
|
174
|
+
fetchTimeoutMs,
|
|
168
175
|
});
|
|
169
176
|
},
|
|
170
177
|
async abortTask(taskId) {
|
|
@@ -179,25 +186,9 @@ export function createGitHubClient(options) {
|
|
|
179
186
|
profile: "internal",
|
|
180
187
|
acceptEmpty: true,
|
|
181
188
|
permission: "Contents: write",
|
|
189
|
+
fetchTimeoutMs,
|
|
182
190
|
});
|
|
183
191
|
},
|
|
184
|
-
async getTaskEvents(taskId, page, perPage) {
|
|
185
|
-
if (!Number.isInteger(page) || page < 1 || !Number.isInteger(perPage) || perPage < 1) {
|
|
186
|
-
throw new GitHubError("page and per_page must be positive integers.");
|
|
187
|
-
}
|
|
188
|
-
const query = new URLSearchParams({ per_page: String(perPage), page: String(page) });
|
|
189
|
-
const parsed = await callGitHub({
|
|
190
|
-
token: options.token,
|
|
191
|
-
tokens,
|
|
192
|
-
fetchImpl,
|
|
193
|
-
baseUrl: internalBaseUrl,
|
|
194
|
-
path: `/tasks/${encodeURIComponent(taskId)}/events?${query.toString()}`,
|
|
195
|
-
method: "GET",
|
|
196
|
-
profile: "internal",
|
|
197
|
-
permission: "Agent tasks",
|
|
198
|
-
});
|
|
199
|
-
return parseTaskEvents(parsed);
|
|
200
|
-
},
|
|
201
192
|
};
|
|
202
193
|
}
|
|
203
194
|
async function request(options) {
|
|
@@ -210,9 +201,9 @@ async function callGitHub(options) {
|
|
|
210
201
|
const first = await sendGitHub(options, firstToken);
|
|
211
202
|
if (first.response.status === 401 && options.tokens) {
|
|
212
203
|
const nextToken = await options.tokens.refresh(firstToken);
|
|
213
|
-
return acceptGitHub(options, await sendGitHub(options, nextToken)
|
|
204
|
+
return acceptGitHub(options, await sendGitHub(options, nextToken));
|
|
214
205
|
}
|
|
215
|
-
return acceptGitHub(options, first
|
|
206
|
+
return acceptGitHub(options, first);
|
|
216
207
|
}
|
|
217
208
|
async function sendGitHub(options, token) {
|
|
218
209
|
const profile = options.profile ?? "public";
|
|
@@ -225,6 +216,7 @@ async function sendGitHub(options, token) {
|
|
|
225
216
|
headers["x-github-api-version"] = API_VERSION;
|
|
226
217
|
if (options.body)
|
|
227
218
|
headers["content-type"] = "application/json";
|
|
219
|
+
const timeoutMs = options.fetchTimeoutMs ?? GITHUB_FETCH_TIMEOUT_MS;
|
|
228
220
|
let response;
|
|
229
221
|
try {
|
|
230
222
|
response = await options.fetchImpl(`${options.baseUrl}${options.path}`, {
|
|
@@ -232,13 +224,28 @@ async function sendGitHub(options, token) {
|
|
|
232
224
|
headers,
|
|
233
225
|
body: options.body ? JSON.stringify(options.body) : undefined,
|
|
234
226
|
redirect: "error",
|
|
227
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
235
228
|
});
|
|
236
229
|
}
|
|
237
230
|
catch (error) {
|
|
238
|
-
|
|
239
|
-
|
|
231
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
232
|
+
throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`, { code: "upstream_timeout", retryable: true });
|
|
233
|
+
}
|
|
234
|
+
throw new GitHubError("Could not call the GitHub API. Check your network connection and GitHub service status.", { code: "upstream_error", retryable: true });
|
|
235
|
+
}
|
|
236
|
+
let text;
|
|
237
|
+
try {
|
|
238
|
+
text = await response.text();
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
242
|
+
throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`, { code: "upstream_timeout", retryable: true });
|
|
243
|
+
}
|
|
244
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
245
|
+
throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`, { code: "upstream_timeout", retryable: true });
|
|
246
|
+
}
|
|
247
|
+
throw new GitHubError("Could not read the GitHub API response. Check your network connection and read the task's current status before trying again.", { code: "upstream_error", retryable: true });
|
|
240
248
|
}
|
|
241
|
-
const text = await response.text();
|
|
242
249
|
let parsed = null;
|
|
243
250
|
if (text) {
|
|
244
251
|
try {
|
|
@@ -250,16 +257,15 @@ async function sendGitHub(options, token) {
|
|
|
250
257
|
}
|
|
251
258
|
return { response, parsed, text };
|
|
252
259
|
}
|
|
253
|
-
function acceptGitHub(options, sent
|
|
260
|
+
function acceptGitHub(options, sent) {
|
|
254
261
|
const { response, parsed, text } = sent;
|
|
255
262
|
if (!response.ok) {
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
:
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
throw new GitHubError(redact(annotated, token));
|
|
263
|
+
const failure = apiFailure(response.status, response.headers, parsed ?? text, {
|
|
264
|
+
permission: options.permission,
|
|
265
|
+
createTask: options.method === "POST" && options.path.endsWith("/tasks"),
|
|
266
|
+
appRepository: options.tokens !== undefined && options.path.startsWith("/agents/repos/"),
|
|
267
|
+
});
|
|
268
|
+
throw new GitHubError(failure.message, failure);
|
|
263
269
|
}
|
|
264
270
|
if (options.acceptEmpty && response.status === 202)
|
|
265
271
|
return undefined;
|
|
@@ -276,33 +282,6 @@ function readPullState(parsed, number) {
|
|
|
276
282
|
}
|
|
277
283
|
return { number, state: record.state };
|
|
278
284
|
}
|
|
279
|
-
function parseTaskEvents(parsed) {
|
|
280
|
-
if (!parsed || typeof parsed !== "object")
|
|
281
|
-
throw new GitHubError("The events response is not an object.");
|
|
282
|
-
const record = parsed;
|
|
283
|
-
if (!Array.isArray(record.events) || typeof record.total !== "number") {
|
|
284
|
-
throw new GitHubError("The events response has no events and total.");
|
|
285
|
-
}
|
|
286
|
-
const events = [];
|
|
287
|
-
for (const item of record.events) {
|
|
288
|
-
if (!item || typeof item !== "object")
|
|
289
|
-
throw new GitHubError("An event is not an object.");
|
|
290
|
-
const event = item;
|
|
291
|
-
if (typeof event.type !== "string" || !event.type)
|
|
292
|
-
throw new GitHubError("An event has no type.");
|
|
293
|
-
const parsedEvent = { type: event.type };
|
|
294
|
-
if (typeof event.id === "string")
|
|
295
|
-
parsedEvent.id = event.id;
|
|
296
|
-
if (typeof event.timestamp === "string")
|
|
297
|
-
parsedEvent.timestamp = event.timestamp;
|
|
298
|
-
if (typeof event.parentId === "string" || event.parentId === null)
|
|
299
|
-
parsedEvent.parentId = event.parentId;
|
|
300
|
-
if ("data" in event)
|
|
301
|
-
parsedEvent.data = event.data;
|
|
302
|
-
events.push(parsedEvent);
|
|
303
|
-
}
|
|
304
|
-
return { events, total: record.total };
|
|
305
|
-
}
|
|
306
285
|
function matchPull(parsed, id) {
|
|
307
286
|
if (!Array.isArray(parsed))
|
|
308
287
|
throw new GitHubError("The pull requests response is not a list.");
|
|
@@ -315,7 +294,8 @@ function matchPull(parsed, id) {
|
|
|
315
294
|
if (typeof record.number !== "number" || typeof record.html_url !== "string" || !record.html_url) {
|
|
316
295
|
throw new GitHubError(`Pull request ${id} has no number and html_url.`);
|
|
317
296
|
}
|
|
318
|
-
|
|
297
|
+
const title = typeof record.title === "string" && record.title.trim() ? record.title : undefined;
|
|
298
|
+
return { number: record.number, html_url: record.html_url, ...(title ? { title } : {}) };
|
|
319
299
|
}
|
|
320
300
|
return null;
|
|
321
301
|
}
|