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/dist/tasks.js ADDED
@@ -0,0 +1,227 @@
1
+ import { buildSummary, mapRawState, unknownStateWarning } from "./task-status.js";
2
+ import { DEFAULT_MIN_INTERVAL_S } from "./follow-up.js";
3
+ import { formatCheckAfterUtc } from "./time-format.js";
4
+ import { prUrl, sessionUrl } from "./task-urls.js";
5
+ import { fillPullRequest, headRefOf, isFinalState, observe, withStateLock, } from "./state.js";
6
+ import { deliveryForTask } from "./delivery.js";
7
+ export const DEFAULT_FRESHNESS_MS = 60_000;
8
+ export const LIST_HIDE_TERMINAL_MS = 7 * 24 * 60 * 60 * 1000;
9
+ export const REGISTRY_PRUNE_TERMINAL_MS = 30 * 24 * 60 * 60 * 1000;
10
+ export const OWNER_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
11
+ export const LIST_LIMIT_MAX = 50;
12
+ export function resolveNextCheckAfter(task, now = Date.now()) {
13
+ const stored = task.check_after?.trim();
14
+ if (stored) {
15
+ const storedMs = Date.parse(stored);
16
+ if (Number.isFinite(storedMs) && now < storedMs)
17
+ return stored;
18
+ }
19
+ const lastFetch = Date.parse(task.last_fetched_at ?? "");
20
+ const anchorMs = Number.isFinite(lastFetch)
21
+ ? lastFetch
22
+ : (stored && Number.isFinite(Date.parse(stored)) ? Date.parse(stored) : now);
23
+ return new Date(anchorMs + DEFAULT_MIN_INTERVAL_S * 1000).toISOString();
24
+ }
25
+ export function aggregateNextCheckAfter(tasks, now = Date.now()) {
26
+ const pending = tasks.filter((task) => !mapRawState(task.state).terminal);
27
+ if (pending.length === 0)
28
+ return undefined;
29
+ let latest = 0;
30
+ for (const task of pending) {
31
+ const next = Date.parse(resolveNextCheckAfter(task, now));
32
+ if (Number.isFinite(next) && next > latest)
33
+ latest = next;
34
+ }
35
+ if (latest > 0)
36
+ return new Date(latest).toISOString();
37
+ const first = pending[0];
38
+ return first ? resolveNextCheckAfter(first, now) : undefined;
39
+ }
40
+ export function freshnessMs() {
41
+ return DEFAULT_FRESHNESS_MS;
42
+ }
43
+ export function validateOwner(owner) {
44
+ const trimmed = owner.trim();
45
+ if (trimmed.length < 1 || trimmed.length > 64) {
46
+ throw new OwnerValidationError("owner must be 1-64 characters.");
47
+ }
48
+ if (!OWNER_PATTERN.test(trimmed)) {
49
+ throw new OwnerValidationError("owner must match [A-Za-z0-9._-].");
50
+ }
51
+ return trimmed;
52
+ }
53
+ export class OwnerValidationError extends Error {
54
+ constructor(message) {
55
+ super(message);
56
+ this.name = "OwnerValidationError";
57
+ }
58
+ }
59
+ export function ownerMatches(stored, filter) {
60
+ if (!stored)
61
+ return false;
62
+ return stored.toLowerCase() === filter.toLowerCase();
63
+ }
64
+ export function pruneRegistry(state, now = Date.now()) {
65
+ const remove = new Set();
66
+ for (const [id, task] of Object.entries(state.tasks)) {
67
+ if (!isFinalState(task.state))
68
+ continue;
69
+ const stamp = Date.parse(task.completed_at ?? task.updated_at ?? task.created_at ?? "");
70
+ if (!Number.isFinite(stamp))
71
+ continue;
72
+ if (now - stamp > REGISTRY_PRUNE_TERMINAL_MS)
73
+ remove.add(id);
74
+ }
75
+ if (remove.size === 0)
76
+ return;
77
+ state.tasks = Object.fromEntries(Object.entries(state.tasks).filter(([id]) => !remove.has(id)));
78
+ }
79
+ export function listVisible(task, now = Date.now()) {
80
+ if (!isFinalState(task.state))
81
+ return true;
82
+ const stamp = Date.parse(task.completed_at ?? task.updated_at ?? task.created_at ?? "");
83
+ if (!Number.isFinite(stamp))
84
+ return true;
85
+ return now - stamp <= LIST_HIDE_TERMINAL_MS;
86
+ }
87
+ export function filterTasks(state, input, now = Date.now()) {
88
+ const warnings = [];
89
+ const status = input.status ?? "all";
90
+ const limit = input.limit ?? 20;
91
+ if (limit > LIST_LIMIT_MAX) {
92
+ throw new OwnerValidationError(`limit must be at most ${LIST_LIMIT_MAX}.`);
93
+ }
94
+ const repoFilter = input.repo?.trim();
95
+ const ownerFilter = input.owner?.trim() ? validateOwner(input.owner.trim()) : undefined;
96
+ const idSet = input.task_ids?.length ? new Set(input.task_ids) : null;
97
+ if (idSet) {
98
+ for (const id of idSet) {
99
+ if (!state.tasks[id])
100
+ warnings.push(`unknown task_id: ${id}`);
101
+ }
102
+ }
103
+ let rows = Object.values(state.tasks).filter((task) => listVisible(task, now));
104
+ if (idSet)
105
+ rows = rows.filter((task) => idSet.has(task.task_id));
106
+ if (ownerFilter)
107
+ rows = rows.filter((task) => ownerMatches(task.owner, ownerFilter));
108
+ if (repoFilter)
109
+ rows = rows.filter((task) => task.repo === repoFilter);
110
+ if (status !== "all") {
111
+ rows = rows.filter((task) => {
112
+ const mapped = mapRawState(task.state);
113
+ return status === "terminal" ? mapped.terminal : !mapped.terminal;
114
+ });
115
+ }
116
+ rows.sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? ""));
117
+ return { tasks: rows.slice(0, limit), matched: rows, warnings, total_matched: rows.length };
118
+ }
119
+ export function listCounts(tasks) {
120
+ let pending = 0;
121
+ let terminal = 0;
122
+ for (const task of tasks) {
123
+ if (mapRawState(task.state).terminal)
124
+ terminal += 1;
125
+ else
126
+ pending += 1;
127
+ }
128
+ return { pending_count: pending, terminal_count: terminal, all_terminal: pending === 0 };
129
+ }
130
+ export function listNextStep(counts, matchedEmpty, registryEmpty, checkAfter) {
131
+ if (registryEmpty)
132
+ return "No tracked tasks.";
133
+ if (matchedEmpty)
134
+ return "No tasks match this filter.";
135
+ if (counts.all_terminal) {
136
+ return "No tasks are running. If you scheduled a check for these tasks, delete it now.";
137
+ }
138
+ const n = counts.pending_count;
139
+ const suffix = checkAfter ? ` End your turn; first check not before ${formatCheckAfterUtc(checkAfter)} (not sooner than 5 minutes).` : "";
140
+ return `${n} task${n === 1 ? "" : "s"} still working.${suffix}`;
141
+ }
142
+ export function toListRow(task, options) {
143
+ const mapped = mapRawState(task.state);
144
+ const row = {
145
+ task_id: task.task_id,
146
+ repo: task.repo,
147
+ status: mapped.status,
148
+ terminal: mapped.terminal,
149
+ summary: buildSummary(task, { checkAfter: options?.checkAfter }),
150
+ updated_at: task.updated_at ?? undefined,
151
+ };
152
+ const warning = unknownStateWarning(task.state);
153
+ if (warning)
154
+ row.warning = warning;
155
+ if (task.owner)
156
+ row.owner = task.owner;
157
+ const session = sessionUrl(task);
158
+ if (session)
159
+ row.session_url = session;
160
+ const link = prUrl(task);
161
+ if (link)
162
+ row.pr_url = link;
163
+ if (options?.stale)
164
+ row.stale = true;
165
+ if (options?.cached)
166
+ row.cached = true;
167
+ return row;
168
+ }
169
+ export function needsFetch(task, freshness, now = Date.now()) {
170
+ if (task.steer && !task.steer.turn_seen)
171
+ return true;
172
+ if (mapRawState(task.state).terminal)
173
+ return false;
174
+ const last = Date.parse(task.last_fetched_at ?? "");
175
+ if (!Number.isFinite(last) || now - last >= freshness)
176
+ return true;
177
+ return false;
178
+ }
179
+ export async function refreshTasks(statePath, client, taskIds, freshness, log) {
180
+ const failures = new Map();
181
+ const refreshed = new Set();
182
+ const concurrency = 4;
183
+ let index = 0;
184
+ async function worker() {
185
+ for (;;) {
186
+ const current = index;
187
+ index += 1;
188
+ if (current >= taskIds.length)
189
+ return;
190
+ const taskId = taskIds[current] ?? "";
191
+ const meta = await withStateLock(statePath, (state) => {
192
+ const task = state.tasks[taskId];
193
+ if (!task || !needsFetch(task, freshness))
194
+ return null;
195
+ return { repo: task.repo, requestedModel: task.requested_model };
196
+ });
197
+ if (!meta)
198
+ continue;
199
+ const slash = meta.repo.indexOf("/");
200
+ const owner = slash > 0 ? meta.repo.slice(0, slash) : undefined;
201
+ const repo = slash > 0 ? meta.repo.slice(slash + 1) : undefined;
202
+ try {
203
+ const remote = await client.getTask({ taskId, owner, repo });
204
+ const tracked = await withStateLock(statePath, (state) => {
205
+ const row = observe(state, remote, { repo: meta.repo, requestedModel: meta.requestedModel });
206
+ row.last_fetched_at = new Date().toISOString();
207
+ return row;
208
+ });
209
+ await fillPullRequest(tracked, (input) => client.findPullRequest(input), log, headRefOf(remote, tracked));
210
+ await withStateLock(statePath, (state) => {
211
+ const saved = state.tasks[taskId];
212
+ if (saved)
213
+ saved.pull_request = tracked.pull_request;
214
+ });
215
+ refreshed.add(taskId);
216
+ }
217
+ catch (error) {
218
+ failures.set(taskId, error instanceof Error ? error.message : "refresh failed");
219
+ }
220
+ }
221
+ }
222
+ await Promise.all(Array.from({ length: Math.min(concurrency, taskIds.length) }, () => worker()));
223
+ return { refreshed, failures };
224
+ }
225
+ export function deliveryField(task, channels) {
226
+ return deliveryForTask(task, channels);
227
+ }
@@ -0,0 +1,3 @@
1
+ export function formatCheckAfterUtc(iso) {
2
+ return `${iso} (UTC)`;
3
+ }
package/dist/watch.js CHANGED
@@ -4,14 +4,15 @@ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { failureMessage } from "./errors.js";
7
- import { appendWatcherLog } from "./notify.js";
7
+ import { appendWatcherLog, notificationChannelsForTask } from "./notify.js";
8
+ import { shouldSpawnWatcher } from "./delivery.js";
8
9
  import { awaitingSteer, fillPullRequest, isFinalState, observe, presentUsage, readState, toDeliveryNotice, withStateLock } from "./state.js";
9
10
  export async function runWatcher(options) {
10
11
  const sleep = options.sleep ?? delay;
11
12
  let cycles = 0;
12
13
  for (;;) {
13
14
  await refreshPending(options);
14
- await notifyFinal(options);
15
+ await notifyFinal(options, options.channels);
15
16
  if (!(await hasPending(options.statePath)))
16
17
  return;
17
18
  cycles += 1;
@@ -41,10 +42,10 @@ async function refreshPending(options) {
41
42
  }
42
43
  }
43
44
  }
44
- async function notifyFinal(options) {
45
+ async function notifyFinal(options, channelOverride) {
45
46
  const ready = await withStateLock(options.statePath, (state) => {
46
47
  return Object.values(state.tasks)
47
- .filter((task) => readyToNotify(task))
48
+ .filter((task) => readyToNotify(task) && shouldSpawnWatcher(channelOverride ?? notificationChannelsForTask(task, state)))
48
49
  .map((task) => task.task_id);
49
50
  });
50
51
  for (const taskId of ready) {
@@ -62,32 +63,44 @@ async function notifyFinal(options) {
62
63
  const task = state.tasks[taskId];
63
64
  if (!task || !readyToNotify(task))
64
65
  return null;
65
- const previous = {
66
- notified_at: task.notified_at,
67
- steer: task.steer ? { ...task.steer } : null,
68
- };
69
66
  task.pull_request = tracked.pull_request;
70
67
  task.usage = tracked.usage;
71
- if (task.steer?.turn_seen)
72
- task.steer = { ...task.steer, notified: true };
73
- task.notified_at = new Date().toISOString();
74
- return { notice: toDeliveryNotice(task), previous };
68
+ return { notice: toDeliveryNotice(task), task, channels: channelOverride ?? notificationChannelsForTask(task, state) };
75
69
  });
76
70
  if (!claimed)
77
71
  continue;
72
+ let delivered;
78
73
  try {
79
- await options.deliver(claimed.notice);
74
+ delivered = await options.deliver(claimed.notice, claimed.task);
80
75
  }
81
76
  catch (error) {
77
+ console.error(`Could not notify for task ${taskId}: ${failureMessage(error)}`);
78
+ delivered = { channels: [] };
79
+ }
80
+ if (delivered.channels.length === 0) {
81
+ const configured = claimed.channels;
82
+ const reason = configured.length === 0
83
+ ? "no notification channels configured"
84
+ : `all configured channels failed (${configured.join(", ")})`;
85
+ const line = `Notification delivery failed for task ${taskId}: ${reason}`;
86
+ await appendWatcherLog(line);
82
87
  await withStateLock(options.statePath, (state) => {
83
88
  const task = state.tasks[taskId];
84
- if (!task)
89
+ if (!task || !readyToNotify(task))
85
90
  return;
86
- task.notified_at = claimed.previous.notified_at;
87
- task.steer = claimed.previous.steer;
91
+ task.delivery_record = { status: "failed", reason };
88
92
  });
89
- console.error(`Could not notify for task ${taskId}: ${failureMessage(error)}`);
93
+ continue;
90
94
  }
95
+ await withStateLock(options.statePath, (state) => {
96
+ const task = state.tasks[taskId];
97
+ if (!task || !readyToNotify(task))
98
+ return;
99
+ task.delivery_record = { status: "delivered", delivered_via: delivered.channels.join(",") };
100
+ if (task.steer?.turn_seen)
101
+ task.steer = { ...task.steer, notified: true };
102
+ task.notified_at = new Date().toISOString();
103
+ });
91
104
  }
92
105
  }
93
106
  function shouldPoll(task) {
@@ -96,6 +109,8 @@ function shouldPoll(task) {
96
109
  return Boolean(task.steer && !task.steer.turn_seen);
97
110
  }
98
111
  function readyToNotify(task) {
112
+ if (task.delivery_record?.status === "failed")
113
+ return false;
99
114
  if (!isFinalState(task.state))
100
115
  return false;
101
116
  if (task.steer && task.steer.notified !== true)
@@ -104,7 +119,10 @@ function readyToNotify(task) {
104
119
  }
105
120
  async function hasPending(statePath) {
106
121
  const state = await readState(statePath);
107
- return Object.values(state.tasks).some((task) => !isFinalState(task.state) || !task.notified_at || awaitingSteer(task));
122
+ return Object.values(state.tasks).some((task) => !isFinalState(task.state) || steerPending(task) || (shouldSpawnWatcher(notificationChannelsForTask(task, state)) && readyToNotify(task)));
123
+ }
124
+ function steerPending(task) {
125
+ return awaitingSteer(task);
108
126
  }
109
127
  export function watcherLockPath(statePath) {
110
128
  return `${statePath}.watcher`;
@@ -0,0 +1,159 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import * as https from "node:https";
3
+ import { isIP } from "node:net";
4
+ import { webhookPayloadId } from "./delivery.js";
5
+ const VALIDATION_ERRORS = {
6
+ input: "Invalid webhook URL. Provide an absolute URL without embedded credentials.",
7
+ https: "Webhook URL must use HTTPS. Change the URL scheme to https.",
8
+ nonPublic: "Webhook URL resolves to a non-public address. Use a host whose addresses are all public.",
9
+ allowedHost: "Webhook host is outside COPILOT_AGENTS_NOTIFY_ALLOWED_HOSTS. Use an allowed host or update that setting.",
10
+ dns: "Webhook DNS lookup failed. Check the hostname and DNS configuration, then retry.",
11
+ };
12
+ export class WebhookValidationError extends Error {
13
+ constructor(reason) {
14
+ super(VALIDATION_ERRORS[reason]);
15
+ this.name = "WebhookValidationError";
16
+ }
17
+ }
18
+ const DELIVERY_FAILED = "Webhook delivery failed.";
19
+ const TIMEOUT_MS = 10_000;
20
+ function publicIpv4(address) {
21
+ const octets = address.split(".").map(Number);
22
+ const [a = 0, b = 0, c = 0] = octets;
23
+ return !(a === 0 || a === 10 || a === 127 || a >= 224
24
+ || (a === 100 && b >= 64 && b <= 127)
25
+ || (a === 169 && b === 254)
26
+ || (a === 172 && b >= 16 && b <= 31)
27
+ || (a === 192 && (b === 168 || (b === 0 && (c === 0 || c === 2)) || (b === 88 && c === 99)))
28
+ || (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100)))
29
+ || (a === 203 && b === 0 && c === 113));
30
+ }
31
+ function ipv6Value(address) {
32
+ const expanded = address.replace(/\d+\.\d+\.\d+\.\d+$/, (ipv4) => {
33
+ const octets = ipv4.split(".").map(Number);
34
+ return `${((octets[0] ?? 0) * 256 + (octets[1] ?? 0)).toString(16)}:${((octets[2] ?? 0) * 256 + (octets[3] ?? 0)).toString(16)}`;
35
+ });
36
+ const [left = "", right] = expanded.split("::");
37
+ const head = left ? left.split(":") : [];
38
+ const tail = right ? right.split(":") : [];
39
+ const words = right === undefined ? head : [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail];
40
+ return words.reduce((value, word) => (value << 16n) | BigInt(`0x${word}`), 0n);
41
+ }
42
+ function publicAddress(address) {
43
+ const family = isIP(address);
44
+ if (family === 4)
45
+ return publicIpv4(address);
46
+ if (family !== 6)
47
+ return false;
48
+ const value = ipv6Value(address);
49
+ if (value >> 32n === 0xffffn) {
50
+ const ipv4 = [24n, 16n, 8n, 0n].map((shift) => Number((value >> shift) & 255n)).join(".");
51
+ return publicIpv4(ipv4);
52
+ }
53
+ // Only global unicast; exclude documentation and transition ranges.
54
+ return value >> 125n === 1n
55
+ && value >> 96n !== 0x20010db8n
56
+ && value >> 96n !== 0x20010000n
57
+ && value >> 80n !== 0x200100020000n
58
+ && value >> 100n !== 0x2001001n
59
+ && value >> 100n !== 0x2001002n
60
+ && value >> 108n !== 0x3fff0n
61
+ && value >> 112n !== 0x2002n;
62
+ }
63
+ const resolveWebhook = (hostname) => lookup(hostname, { all: true, verbatim: true });
64
+ export async function validateWebhookUrl(input, env = process.env, resolver = resolveWebhook) {
65
+ let url;
66
+ try {
67
+ url = new URL(input);
68
+ }
69
+ catch {
70
+ throw new WebhookValidationError("input");
71
+ }
72
+ if (url.protocol !== "https:")
73
+ throw new WebhookValidationError("https");
74
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
75
+ if (url.username || url.password || !hostname)
76
+ throw new WebhookValidationError("input");
77
+ if (hostname.toLowerCase().replace(/\.$/, "") === "metadata.google.internal") {
78
+ throw new WebhookValidationError("nonPublic");
79
+ }
80
+ const allowed = env.COPILOT_AGENTS_NOTIFY_ALLOWED_HOSTS;
81
+ if (allowed !== undefined && !allowed.split(",").some((host) => host.trim().toLowerCase() === hostname.toLowerCase())) {
82
+ throw new WebhookValidationError("allowedHost");
83
+ }
84
+ const family = isIP(hostname);
85
+ let addresses;
86
+ try {
87
+ addresses = family ? [{ address: hostname, family }] : await resolver(hostname);
88
+ }
89
+ catch {
90
+ throw new WebhookValidationError("dns");
91
+ }
92
+ if (!addresses.length)
93
+ throw new WebhookValidationError("dns");
94
+ if (addresses.some(({ address, family: resolvedFamily }) => (!publicAddress(address) || isIP(address) !== resolvedFamily)))
95
+ throw new WebhookValidationError("nonPublic");
96
+ return { url, addresses };
97
+ }
98
+ export function webhookPost(notice, authorization) {
99
+ const headers = {
100
+ "Content-Type": "application/json",
101
+ "Idempotency-Key": webhookPayloadId(notice.task_id, notice.state),
102
+ };
103
+ if (authorization)
104
+ headers.Authorization = authorization;
105
+ return {
106
+ body: JSON.stringify({
107
+ task_id: notice.task_id,
108
+ state: notice.state,
109
+ repo: notice.repo,
110
+ pr_url: notice.pull_request?.html_url ?? null,
111
+ }),
112
+ headers,
113
+ };
114
+ }
115
+ export async function postOwnerNotice(input, notice, authorization, env = process.env) {
116
+ try {
117
+ const { url, addresses } = await validateWebhookUrl(input, env);
118
+ const [pinned] = addresses;
119
+ const pinnedLookup = (_hostname, options, callback) => {
120
+ if (options.all)
121
+ callback(null, [{ address: pinned.address, family: pinned.family }]);
122
+ else
123
+ callback(null, pinned.address, pinned.family);
124
+ };
125
+ const { body, headers } = webhookPost(notice, authorization);
126
+ await new Promise((resolve, reject) => {
127
+ const request = https.request(url, {
128
+ method: "POST",
129
+ agent: false,
130
+ lookup: pinnedLookup,
131
+ servername: isIP(url.hostname.replace(/^\[|\]$/g, "")) ? "" : url.hostname,
132
+ headers: {
133
+ ...headers,
134
+ Host: url.host,
135
+ "Content-Length": Buffer.byteLength(body),
136
+ },
137
+ timeout: TIMEOUT_MS,
138
+ }, (response) => {
139
+ response.on("error", () => reject(new Error(DELIVERY_FAILED)));
140
+ response.resume();
141
+ if (response.statusCode && response.statusCode >= 200 && response.statusCode < 300)
142
+ resolve();
143
+ else
144
+ reject(new Error(DELIVERY_FAILED));
145
+ });
146
+ const timer = setTimeout(() => request.destroy(new Error(DELIVERY_FAILED)), TIMEOUT_MS);
147
+ request.on("close", () => clearTimeout(timer));
148
+ request.on("error", () => {
149
+ clearTimeout(timer);
150
+ reject(new Error(DELIVERY_FAILED));
151
+ });
152
+ request.on("timeout", () => request.destroy(new Error(DELIVERY_FAILED)));
153
+ request.end(body);
154
+ });
155
+ }
156
+ catch {
157
+ throw new Error(DELIVERY_FAILED);
158
+ }
159
+ }
@@ -0,0 +1,102 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, rename, rm } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { readState, withStateLock } from "./state.js";
6
+ import { validateOwner } from "./tasks.js";
7
+ import { validateWebhookUrl, WebhookValidationError } from "./webhook-http.js";
8
+ export const WEBHOOK_ERROR = "Could not complete webhook operation.";
9
+ export const WEBHOOK_INPUT_ERROR = "Invalid webhook input. Use a valid --owner, secret files (--url-file and --auth-file) or hidden terminal prompts, and a nonempty single-line Authorization value.";
10
+ export function webhookKeyPath(statePath, owner) {
11
+ const digest = createHash("sha256").update(validateOwner(owner)).digest("hex");
12
+ return join(dirname(statePath), digest);
13
+ }
14
+ export function ownerWebhook(state, task) {
15
+ if (!task.owner || !task.created_at || !Object.hasOwn(state.webhooks ?? {}, task.owner))
16
+ return undefined;
17
+ const registration = state.webhooks?.[task.owner];
18
+ if (registration && Date.parse(task.created_at) > Date.parse(registration.registeredAt))
19
+ return registration;
20
+ return undefined;
21
+ }
22
+ export async function registerWebhook(statePath, owner, url, authorization, options) {
23
+ try {
24
+ owner = validateOwner(owner);
25
+ }
26
+ catch {
27
+ throw new Error(WEBHOOK_INPUT_ERROR);
28
+ }
29
+ if (!authorization.trim() || /[\r\n]/.test(authorization))
30
+ throw new Error(WEBHOOK_INPUT_ERROR);
31
+ try {
32
+ await validateWebhookUrl(url, options?.env ?? process.env);
33
+ await withStateLock(statePath, async (state) => {
34
+ const keyFilePath = webhookKeyPath(statePath, owner);
35
+ const staging = `${keyFilePath}.${randomUUID()}`;
36
+ try {
37
+ const file = await open(staging, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
38
+ try {
39
+ await file.chmod(0o600);
40
+ await file.writeFile(authorization, "utf8");
41
+ await file.sync();
42
+ }
43
+ finally {
44
+ await file.close();
45
+ }
46
+ await rename(staging, keyFilePath);
47
+ }
48
+ finally {
49
+ await rm(staging, { force: true });
50
+ }
51
+ state.webhooks ??= {};
52
+ Object.defineProperty(state.webhooks, owner, {
53
+ value: { url, keyFilePath, registeredAt: new Date((options?.now ?? Date.now)()).toISOString() },
54
+ enumerable: true,
55
+ writable: true,
56
+ configurable: true,
57
+ });
58
+ });
59
+ }
60
+ catch (error) {
61
+ if (error instanceof WebhookValidationError)
62
+ throw error;
63
+ throw new Error(WEBHOOK_ERROR);
64
+ }
65
+ }
66
+ export async function removeWebhook(statePath, owner) {
67
+ try {
68
+ owner = validateOwner(owner);
69
+ await withStateLock(statePath, async (state) => {
70
+ await rm(webhookKeyPath(statePath, owner), { force: true });
71
+ if (state.webhooks)
72
+ Reflect.deleteProperty(state.webhooks, owner);
73
+ });
74
+ }
75
+ catch {
76
+ throw new Error(WEBHOOK_ERROR);
77
+ }
78
+ }
79
+ export async function listWebhooks(statePath) {
80
+ try {
81
+ const state = await readState(statePath);
82
+ return await Promise.all(Object.entries(state.webhooks ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(async ([owner, registration]) => {
83
+ let keyPresent = false;
84
+ let keyMode0600 = false;
85
+ const keyFilePath = webhookKeyPath(statePath, owner);
86
+ if (registration.keyFilePath === keyFilePath) {
87
+ try {
88
+ const stat = await lstat(keyFilePath);
89
+ keyPresent = stat.isFile();
90
+ keyMode0600 = keyPresent && (stat.mode & 0o777) === 0o600;
91
+ }
92
+ catch {
93
+ // A missing or inaccessible key is a diagnostic, not a secret read.
94
+ }
95
+ }
96
+ return { owner, host: new URL(registration.url).hostname, keyFilePath, registeredAt: registration.registeredAt, keyPresent, keyMode0600 };
97
+ }));
98
+ }
99
+ catch {
100
+ throw new Error(WEBHOOK_ERROR);
101
+ }
102
+ }
package/package.json CHANGED
@@ -1,10 +1,22 @@
1
1
  {
2
2
  "name": "copilot-agents-mcp",
3
- "version": "0.0.1",
3
+ "version": "0.2.0",
4
4
  "description": "Local MCP server for launching GitHub Copilot cloud agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
- "keywords": ["mcp", "github", "copilot", "agents"],
7
+ "homepage": "https://github.com/daniel-saezv/copilot-agents-mcp#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/daniel-saezv/copilot-agents-mcp/issues"
10
+ },
11
+ "keywords": [
12
+ "mcp",
13
+ "model-context-protocol",
14
+ "github-copilot",
15
+ "copilot",
16
+ "coding-agent",
17
+ "github",
18
+ "agents"
19
+ ],
8
20
  "bin": {
9
21
  "copilot-agents-mcp": "dist/cli.js"
10
22
  },