copilot-agents-mcp 0.0.1 → 0.1.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 +58 -158
- package/dist/cli.js +38 -98
- package/dist/compact.js +23 -0
- package/dist/delivery.js +17 -0
- package/dist/errors.js +81 -4
- package/dist/follow-up.js +47 -0
- package/dist/github-hosts.js +61 -0
- package/dist/github.js +29 -46
- package/dist/notify.js +22 -93
- package/dist/selection.js +16 -112
- package/dist/server.js +370 -149
- package/dist/state.js +20 -2
- package/dist/status-local.js +67 -0
- package/dist/swe-models.js +44 -8
- 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 +39 -17
- 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() {
|
|
@@ -12,6 +13,10 @@ export function withMissingAppInstall(message, status, path, appCredential) {
|
|
|
12
13
|
const repository = repositoryFromPath(path);
|
|
13
14
|
if (!repository)
|
|
14
15
|
return message;
|
|
16
|
+
const trimmed = message.trim();
|
|
17
|
+
if (/^not found\.?$/i.test(trimmed) || /^task .+ was not found\.?$/i.test(trimmed)) {
|
|
18
|
+
return `Repository ${repository.owner}/${repository.repo} was not found or is not accessible.`;
|
|
19
|
+
}
|
|
15
20
|
return `Install the app for ${repository.owner}/${repository.repo}: ${githubAppInstallUrl()}. ${message}`;
|
|
16
21
|
}
|
|
17
22
|
function repositoryFromPath(path) {
|
|
@@ -63,19 +68,91 @@ export class KeyringError extends Error {
|
|
|
63
68
|
this.name = "KeyringError";
|
|
64
69
|
}
|
|
65
70
|
}
|
|
66
|
-
export const NO_SESSION_MESSAGE = "No GitHub session is available. Set GITHUB_PERSONAL_ACCESS_TOKEN or run `npx copilot-agents-mcp login
|
|
71
|
+
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.";
|
|
72
|
+
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`.";
|
|
73
|
+
export class CodedToolFailure extends ToolFailure {
|
|
74
|
+
code;
|
|
75
|
+
retryable;
|
|
76
|
+
retry_after_s;
|
|
77
|
+
constructor(code, message, options) {
|
|
78
|
+
super(message);
|
|
79
|
+
this.name = "CodedToolFailure";
|
|
80
|
+
this.code = code;
|
|
81
|
+
this.retryable = options?.retryable ?? false;
|
|
82
|
+
this.retry_after_s = options?.retry_after_s;
|
|
83
|
+
}
|
|
84
|
+
toBody() {
|
|
85
|
+
const body = {
|
|
86
|
+
error: {
|
|
87
|
+
code: this.code,
|
|
88
|
+
message: this.message,
|
|
89
|
+
retryable: this.retryable,
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
if (this.retry_after_s !== undefined)
|
|
93
|
+
body.error.retry_after_s = this.retry_after_s;
|
|
94
|
+
return body;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
67
97
|
export function toolError(message) {
|
|
98
|
+
const body = typeof message === "string" ? legacyErrorBody(message) : message;
|
|
99
|
+
const text = compactStringify(body);
|
|
68
100
|
return {
|
|
69
101
|
isError: true,
|
|
70
|
-
content: [{ type: "text", text
|
|
102
|
+
content: [{ type: "text", text }],
|
|
71
103
|
};
|
|
72
104
|
}
|
|
73
105
|
export function toolJson(value) {
|
|
106
|
+
const compact = compactValue(value);
|
|
74
107
|
return {
|
|
75
|
-
content: [{ type: "text", text:
|
|
76
|
-
structuredContent:
|
|
108
|
+
content: [{ type: "text", text: compactStringify(compact) }],
|
|
109
|
+
structuredContent: compact,
|
|
77
110
|
};
|
|
78
111
|
}
|
|
112
|
+
function legacyErrorBody(message) {
|
|
113
|
+
return {
|
|
114
|
+
error: {
|
|
115
|
+
code: classifyMessage(message),
|
|
116
|
+
message,
|
|
117
|
+
retryable: /retry after \d+ seconds/i.test(message) || message.includes("rate limit"),
|
|
118
|
+
...(retryAfterFromMessage(message) !== undefined ? { retry_after_s: retryAfterFromMessage(message) } : {}),
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function classifyMessage(message) {
|
|
123
|
+
if (message === NO_SESSION_MESSAGE)
|
|
124
|
+
return "not_authenticated";
|
|
125
|
+
if (/missing required parameter/i.test(message))
|
|
126
|
+
return "invalid_argument";
|
|
127
|
+
if (/^repo must use/i.test(message))
|
|
128
|
+
return "invalid_argument";
|
|
129
|
+
if (/is not available\. Accepted models/i.test(message))
|
|
130
|
+
return "model_unavailable";
|
|
131
|
+
if (/HTTP 404/.test(message) || /not found/i.test(message))
|
|
132
|
+
return "not_found";
|
|
133
|
+
if (/HTTP 403/.test(message) || /Missing .* permission/i.test(message))
|
|
134
|
+
return "forbidden";
|
|
135
|
+
if (/HTTP 429/.test(message) || /rate limit/i.test(message))
|
|
136
|
+
return "rate_limited";
|
|
137
|
+
if (/HTTP 504|timeout/i.test(message))
|
|
138
|
+
return "upstream_timeout";
|
|
139
|
+
if (/HTTP \d+/.test(message))
|
|
140
|
+
return "upstream_error";
|
|
141
|
+
return "invalid_argument";
|
|
142
|
+
}
|
|
143
|
+
function retryAfterFromMessage(message) {
|
|
144
|
+
const match = /retry after (\d+) seconds/i.exec(message);
|
|
145
|
+
if (!match?.[1])
|
|
146
|
+
return undefined;
|
|
147
|
+
const value = Number(match[1]);
|
|
148
|
+
return Number.isFinite(value) ? value : undefined;
|
|
149
|
+
}
|
|
150
|
+
export function failureToError(error) {
|
|
151
|
+
if (error instanceof CodedToolFailure)
|
|
152
|
+
return error.toBody();
|
|
153
|
+
const message = failureMessage(error);
|
|
154
|
+
return legacyErrorBody(message);
|
|
155
|
+
}
|
|
79
156
|
export function failureMessage(error) {
|
|
80
157
|
if (error instanceof ToolFailure
|
|
81
158
|
|| error instanceof GitHubError
|
|
@@ -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
|
@@ -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) {
|
|
@@ -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,30 @@ 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) {
|
|
231
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
232
|
+
throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`);
|
|
233
|
+
}
|
|
238
234
|
const message = error instanceof Error ? error.message : "network error";
|
|
239
235
|
throw new GitHubError(redact(`Could not call the GitHub API: ${message}`, token));
|
|
240
236
|
}
|
|
241
|
-
|
|
237
|
+
let text;
|
|
238
|
+
try {
|
|
239
|
+
text = await response.text();
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
243
|
+
throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`);
|
|
244
|
+
}
|
|
245
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
246
|
+
throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`);
|
|
247
|
+
}
|
|
248
|
+
const message = error instanceof Error ? error.message : "network error";
|
|
249
|
+
throw new GitHubError(redact(`Could not read the GitHub API response: ${message}`, token));
|
|
250
|
+
}
|
|
242
251
|
let parsed = null;
|
|
243
252
|
if (text) {
|
|
244
253
|
try {
|
|
@@ -276,33 +285,6 @@ function readPullState(parsed, number) {
|
|
|
276
285
|
}
|
|
277
286
|
return { number, state: record.state };
|
|
278
287
|
}
|
|
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
288
|
function matchPull(parsed, id) {
|
|
307
289
|
if (!Array.isArray(parsed))
|
|
308
290
|
throw new GitHubError("The pull requests response is not a list.");
|
|
@@ -315,7 +297,8 @@ function matchPull(parsed, id) {
|
|
|
315
297
|
if (typeof record.number !== "number" || typeof record.html_url !== "string" || !record.html_url) {
|
|
316
298
|
throw new GitHubError(`Pull request ${id} has no number and html_url.`);
|
|
317
299
|
}
|
|
318
|
-
|
|
300
|
+
const title = typeof record.title === "string" && record.title.trim() ? record.title : undefined;
|
|
301
|
+
return { number: record.number, html_url: record.html_url, ...(title ? { title } : {}) };
|
|
319
302
|
}
|
|
320
303
|
return null;
|
|
321
304
|
}
|
package/dist/notify.js
CHANGED
|
@@ -1,84 +1,17 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
1
|
import { appendFile, mkdir } from "node:fs/promises";
|
|
3
2
|
import { dirname } from "node:path";
|
|
3
|
+
import { webhookPayloadId } from "./delivery.js";
|
|
4
|
+
import { mapRawState } from "./task-status.js";
|
|
4
5
|
export const NOTIFY_URL_ENV = "COPILOT_AGENTS_NOTIFY_URL";
|
|
5
6
|
export const NOTIFY_AUTHORIZATION_ENV = "COPILOT_AGENTS_NOTIFY_AUTHORIZATION";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
$ErrorActionPreference = 'Stop'
|
|
9
|
-
$title = $env:COPILOT_AGENTS_NOTIFY_TITLE
|
|
10
|
-
$body = $env:COPILOT_AGENTS_NOTIFY_BODY
|
|
11
|
-
try {
|
|
12
|
-
$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
|
|
13
|
-
$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
|
|
14
|
-
$escapedTitle = [System.Security.SecurityElement]::Escape($title)
|
|
15
|
-
$escapedBody = [System.Security.SecurityElement]::Escape($body)
|
|
16
|
-
$template = "<toast><visual><binding template='ToastGeneric'><text>$escapedTitle</text><text>$escapedBody</text></binding></visual></toast>"
|
|
17
|
-
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
|
|
18
|
-
$xml.LoadXml($template)
|
|
19
|
-
$toast = New-Object Windows.UI.Notifications.ToastNotification $xml
|
|
20
|
-
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('PowerShell').Show($toast)
|
|
21
|
-
} catch {
|
|
22
|
-
Add-Type -AssemblyName System.Windows.Forms
|
|
23
|
-
Add-Type -AssemblyName System.Drawing
|
|
24
|
-
$icon = New-Object System.Windows.Forms.NotifyIcon
|
|
25
|
-
$icon.Icon = [System.Drawing.SystemIcons]::Information
|
|
26
|
-
$icon.Visible = $true
|
|
27
|
-
$icon.ShowBalloonTip(8000, $title, $body, [System.Windows.Forms.ToolTipIcon]::Info)
|
|
28
|
-
Start-Sleep -Seconds 2
|
|
29
|
-
$icon.Dispose()
|
|
7
|
+
export function activeNotificationChannels(_platform, baseEnv) {
|
|
8
|
+
return baseEnv[NOTIFY_URL_ENV]?.trim() ? ["webhook"] : [];
|
|
30
9
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
env.COPILOT_AGENTS_NOTIFY_TITLE = title;
|
|
35
|
-
env.COPILOT_AGENTS_NOTIFY_BODY = body;
|
|
36
|
-
if (platform === "win32")
|
|
37
|
-
return { command: "powershell.exe", args: ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_SCRIPT], env };
|
|
38
|
-
if (platform === "darwin") {
|
|
39
|
-
return {
|
|
40
|
-
command: "osascript",
|
|
41
|
-
args: ["-e", 'display notification (system attribute "COPILOT_AGENTS_NOTIFY_BODY") with title (system attribute "COPILOT_AGENTS_NOTIFY_TITLE")'],
|
|
42
|
-
env,
|
|
43
|
-
};
|
|
10
|
+
export function createNextStep(channels) {
|
|
11
|
+
if (channels.length === 0) {
|
|
12
|
+
return "Task queued. Do not poll. End your turn; no notification channel is configured (set COPILOT_AGENTS_NOTIFY_URL). Call get_agent_task once later.";
|
|
44
13
|
}
|
|
45
|
-
|
|
46
|
-
return { command: "notify-send", args: ["--", title, body], env };
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
49
|
-
export function noticeText(notice) {
|
|
50
|
-
const title = `Copilot ${notice.state}`.slice(0, 80);
|
|
51
|
-
const body = [notice.repo, notice.task_id, notice.error ?? notice.state].filter(Boolean).join("\n").slice(0, 240);
|
|
52
|
-
return { title, body };
|
|
53
|
-
}
|
|
54
|
-
export async function notifySystem(notice, spawnImpl = spawn, platform = process.platform, baseEnv = process.env) {
|
|
55
|
-
const { title, body } = noticeText(notice);
|
|
56
|
-
const plan = notificationPlan(platform, title, body, baseEnv);
|
|
57
|
-
if (!plan)
|
|
58
|
-
return;
|
|
59
|
-
await new Promise((resolve) => {
|
|
60
|
-
let pending = true;
|
|
61
|
-
const done = (error) => {
|
|
62
|
-
if (!pending)
|
|
63
|
-
return;
|
|
64
|
-
pending = false;
|
|
65
|
-
if (error === undefined) {
|
|
66
|
-
resolve();
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
void appendWatcherLog(`Could not show the system notification: ${notifyFailure(plan.command, error)}`, baseEnv).finally(resolve);
|
|
70
|
-
};
|
|
71
|
-
let child;
|
|
72
|
-
try {
|
|
73
|
-
child = spawnImpl(plan.command, plan.args, { windowsHide: true, env: plan.env, stdio: "ignore" });
|
|
74
|
-
}
|
|
75
|
-
catch (error) {
|
|
76
|
-
done(error);
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
child.on("error", (error) => done(error));
|
|
80
|
-
child.on("exit", () => done());
|
|
81
|
-
});
|
|
14
|
+
return "Task queued. Do not poll. End your turn; you will be notified via webhook when the task finishes. Call get_agent_task once later.";
|
|
82
15
|
}
|
|
83
16
|
export async function appendWatcherLog(line, env = process.env) {
|
|
84
17
|
const logPath = env.COPILOT_AGENTS_LOG?.trim();
|
|
@@ -94,36 +27,32 @@ export async function appendWatcherLog(line, env = process.env) {
|
|
|
94
27
|
console.error(line);
|
|
95
28
|
}
|
|
96
29
|
}
|
|
97
|
-
function notifyFailure(command, error) {
|
|
98
|
-
const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "error";
|
|
99
|
-
return `${code} ${command}`;
|
|
100
|
-
}
|
|
101
30
|
export async function postNotice(url, notice, authorization, fetchImpl = fetch) {
|
|
102
31
|
const headers = { "content-type": "application/json" };
|
|
103
32
|
if (authorization)
|
|
104
33
|
headers.authorization = authorization;
|
|
34
|
+
const mapped = mapRawState(notice.state);
|
|
105
35
|
const response = await fetchImpl(url, {
|
|
106
36
|
method: "POST",
|
|
107
37
|
headers,
|
|
108
|
-
body: JSON.stringify(notice),
|
|
38
|
+
body: JSON.stringify({ ...notice, status: mapped.status, terminal: mapped.terminal, id: webhookPayloadId(notice.task_id, notice.state) }),
|
|
109
39
|
signal: AbortSignal.timeout(10_000),
|
|
110
40
|
});
|
|
111
41
|
if (!response.ok)
|
|
112
42
|
throw new Error(`Notification POST returned HTTP ${response.status}.`);
|
|
113
43
|
}
|
|
114
|
-
export async function deliverNotice(notice, env = process.env, fetchImpl = fetch
|
|
115
|
-
|
|
44
|
+
export async function deliverNotice(notice, env = process.env, fetchImpl = fetch) {
|
|
45
|
+
const channels = [];
|
|
116
46
|
const url = env[NOTIFY_URL_ENV]?.trim();
|
|
117
|
-
if (
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
env[key] = value;
|
|
47
|
+
if (url) {
|
|
48
|
+
try {
|
|
49
|
+
await postNotice(url, notice, env[NOTIFY_AUTHORIZATION_ENV]?.trim() || undefined, fetchImpl);
|
|
50
|
+
channels.push("webhook");
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
const message = error instanceof Error ? error.message : "webhook delivery failed";
|
|
54
|
+
await appendWatcherLog(`Could not POST the task notification: ${message}`, env);
|
|
55
|
+
}
|
|
127
56
|
}
|
|
128
|
-
return
|
|
57
|
+
return { channels };
|
|
129
58
|
}
|
package/dist/selection.js
CHANGED
|
@@ -1,115 +1,19 @@
|
|
|
1
|
-
export const
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
export const TOOL_NAMES = [
|
|
2
|
+
"create_agent_task",
|
|
3
|
+
"get_agent_task",
|
|
4
|
+
"list_agent_tasks",
|
|
5
|
+
"steer_agent_task",
|
|
6
|
+
"abort_agent_task",
|
|
7
|
+
"list_copilot_models",
|
|
8
|
+
];
|
|
9
9
|
export const TOOLS = [
|
|
10
|
-
{ name: "create_agent_task",
|
|
11
|
-
{ name: "get_agent_task",
|
|
12
|
-
{ name: "
|
|
13
|
-
{ name: "
|
|
14
|
-
{ name: "
|
|
15
|
-
{ name: "list_copilot_models",
|
|
10
|
+
{ name: "create_agent_task", method: "POST" },
|
|
11
|
+
{ name: "get_agent_task", method: "GET" },
|
|
12
|
+
{ name: "list_agent_tasks", method: "GET" },
|
|
13
|
+
{ name: "steer_agent_task", method: "POST" },
|
|
14
|
+
{ name: "abort_agent_task", method: "POST" },
|
|
15
|
+
{ name: "list_copilot_models", method: "GET" },
|
|
16
16
|
];
|
|
17
|
-
export function
|
|
18
|
-
|
|
19
|
-
const features = new Set(selection.features);
|
|
20
|
-
const requestedToolsets = selection.toolsets ?? (selection.tools ? [] : [...DEFAULT_TOOLSETS]);
|
|
21
|
-
const names = new Set();
|
|
22
|
-
for (const tool of TOOLS) {
|
|
23
|
-
if (!featureAllows(tool.toolset, features))
|
|
24
|
-
continue;
|
|
25
|
-
if (requestedToolsets.includes(tool.toolset))
|
|
26
|
-
names.add(tool.name);
|
|
27
|
-
}
|
|
28
|
-
for (const name of selection.tools ?? []) {
|
|
29
|
-
const tool = TOOLS.find((item) => item.name === name);
|
|
30
|
-
if (!tool || !featureAllows(tool.toolset, features))
|
|
31
|
-
continue;
|
|
32
|
-
names.add(name);
|
|
33
|
-
}
|
|
34
|
-
for (const name of selection.exclude)
|
|
35
|
-
names.delete(name);
|
|
36
|
-
if (selection.readOnly) {
|
|
37
|
-
for (const name of [...names]) {
|
|
38
|
-
const tool = TOOLS.find((item) => item.name === name);
|
|
39
|
-
if (tool && tool.method !== "GET")
|
|
40
|
-
names.delete(name);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return TOOLS.map((tool) => tool.name).filter((name) => names.has(name));
|
|
44
|
-
}
|
|
45
|
-
export function assertSelection(selection) {
|
|
46
|
-
for (const feature of selection.features) {
|
|
47
|
-
if (!FEATURES.includes(feature)) {
|
|
48
|
-
throw new Error(`Unknown feature: ${feature}.`);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
for (const name of selection.toolsets ?? []) {
|
|
52
|
-
if (!isToolset(name))
|
|
53
|
-
throw new Error(`Unknown toolset: ${name}.`);
|
|
54
|
-
const feature = TOOLSETS[name].feature;
|
|
55
|
-
if (feature && !selection.features.includes(feature)) {
|
|
56
|
-
throw new Error(`Toolset ${name} requires --features=${feature}.`);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
for (const name of selection.tools ?? []) {
|
|
60
|
-
if (!TOOLS.some((tool) => tool.name === name))
|
|
61
|
-
throw new Error(`Unknown tool: ${name}.`);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
export function selectionFromHttp(url, headers, base) {
|
|
65
|
-
const parsed = new URL(url, "http://127.0.0.1");
|
|
66
|
-
const path = parsed.pathname.replace(/\/+$/, "") || "/";
|
|
67
|
-
const toolsetMatch = /^(?:\/mcp)?\/x\/([^/]+)$/.exec(path);
|
|
68
|
-
const readOnlyPath = path === "/readonly" || path === "/mcp/readonly";
|
|
69
|
-
const known = path === "/" || path === "/mcp" || readOnlyPath || toolsetMatch !== null;
|
|
70
|
-
if (!known)
|
|
71
|
-
throw new Error("Unknown path.");
|
|
72
|
-
const selection = {
|
|
73
|
-
exclude: [...base.exclude],
|
|
74
|
-
readOnly: base.readOnly,
|
|
75
|
-
features: [...base.features],
|
|
76
|
-
};
|
|
77
|
-
if (base.toolsets)
|
|
78
|
-
selection.toolsets = [...base.toolsets];
|
|
79
|
-
if (base.tools)
|
|
80
|
-
selection.tools = [...base.tools];
|
|
81
|
-
if (toolsetMatch?.[1])
|
|
82
|
-
selection.toolsets = [decodeURIComponent(toolsetMatch[1])];
|
|
83
|
-
if (readOnlyPath)
|
|
84
|
-
selection.readOnly = true;
|
|
85
|
-
const headerToolsets = headers.get("x-mcp-toolsets");
|
|
86
|
-
if (headerToolsets !== null)
|
|
87
|
-
selection.toolsets = splitList(headerToolsets);
|
|
88
|
-
const headerTools = headers.get("x-mcp-tools");
|
|
89
|
-
if (headerTools !== null)
|
|
90
|
-
selection.tools = splitList(headerTools);
|
|
91
|
-
const headerExclude = headers.get("x-mcp-exclude-tools");
|
|
92
|
-
if (headerExclude !== null)
|
|
93
|
-
selection.exclude = splitList(headerExclude);
|
|
94
|
-
const headerReadOnly = headers.get("x-mcp-readonly");
|
|
95
|
-
if (headerReadOnly !== null && /^(true|1)$/i.test(headerReadOnly.trim()))
|
|
96
|
-
selection.readOnly = true;
|
|
97
|
-
if (base.readOnly)
|
|
98
|
-
selection.readOnly = true;
|
|
99
|
-
const headerFeatures = headers.get("x-mcp-features");
|
|
100
|
-
const queryFeatures = parsed.searchParams.get("features");
|
|
101
|
-
const featureSource = headerFeatures ?? queryFeatures;
|
|
102
|
-
if (featureSource !== null)
|
|
103
|
-
selection.features = splitList(featureSource);
|
|
104
|
-
return selection;
|
|
105
|
-
}
|
|
106
|
-
export function splitList(value) {
|
|
107
|
-
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
108
|
-
}
|
|
109
|
-
function isToolset(name) {
|
|
110
|
-
return Object.prototype.hasOwnProperty.call(TOOLSETS, name);
|
|
111
|
-
}
|
|
112
|
-
function featureAllows(toolset, features) {
|
|
113
|
-
const feature = TOOLSETS[toolset].feature;
|
|
114
|
-
return feature === null || features.has(feature);
|
|
17
|
+
export function toolNames() {
|
|
18
|
+
return [...TOOL_NAMES];
|
|
115
19
|
}
|