copilot-agents-mcp 0.1.0 → 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 CHANGED
@@ -50,16 +50,18 @@ Watcher poll interval and task freshness are **fixed internally** (15s poll, 60s
50
50
  <!-- START AUTOMATED TOOLS -->
51
51
  | Tool | Read-only | Description |
52
52
  | --- | --- | --- |
53
- | `create_agent_task` | no | Launch a GitHub Copilot cloud agent task. The model is sent unchanged. If the model was already rejected, the tool skips the API call and lists accepted models observed so far. Returns immediately with task_id. Pass owner=<your agent name> unless this server runs a single agent. Follow next_step. |
54
- | `get_agent_task` | yes | Read one task once. Returns status, terminal and a one-line summary. Do not call repeatedly; use list_agent_tasks for periodic checks. |
55
- | `list_agent_tasks` | yes | One call to check all tracked tasks. Use it for scheduled checks. When all_terminal is true, stop checking. Several agents may share this server; owner is a labeling convention, not a security boundary. |
56
- | `steer_agent_task` | no | [Experimental] Undocumented internal GitHub endpoint that can change without notice. Each steer consumes credits. The agent applies the instruction after its current tool call finishes. Send an instruction to a task with an open pull request. |
57
- | `abort_agent_task` | no | [Experimental] Undocumented internal GitHub endpoint that can change without notice. Send {type: "abort"} to the steer endpoint, as VS Code does in tasksClient.ts, to stop the task. This has not been verified against GitHub. |
58
- | `list_copilot_models` | yes | Read /agents/swe/models and return the ID, name, vendor, preview flag, token prices or multiplier, and promotion when present. |
53
+ | `create_agent_task` | no | Launch a GitHub Copilot cloud agent with repo, prompt, and model; use list_copilot_models to discover IDs. Returns status, delivery, follow_up, and next_step. May fail for authentication, repository access or policy, invalid input, or an unavailable model; previously rejected models skip the API and list accepted models observed so far. Returns immediately with task_id. Pass owner=<your agent name> unless this server runs a single agent. Follow next_step. |
54
+ | `get_agent_task` | yes | Read one task's result by task_id; optional repo overrides the saved repository and verbose adds details. Returns status, terminal, summary, delivery, and available PR/session links. Cached results may include stale and warnings after a refresh failure. Check authentication or task/repository access on errors. Use list_agent_tasks for scheduled checks, never call this in a loop. |
55
+ | `list_agent_tasks` | yes | Check locally tracked tasks in one scheduled call, filtered by owner, task_ids, status, or repo. Returns compact rows (limit defaults to 20, maximum 50), counts across all matches, all_terminal, next_step, and next_check_after while pending. Stop checks when all_terminal is true. Refresh failures return stale rows and warnings; pending tasks require authentication. Owner is a label, not a security boundary; this is not a GitHub-wide task search. |
56
+ | `steer_agent_task` | no | [Experimental] Undocumented internal GitHub endpoint that can change without notice. Send content to task_id when continuing or redirecting a task with an open pull request. Each call consumes credits and is not idempotent; the agent applies it after its current tool call. Returns task_id, accepted, and the pre-steer session_count, then watches the new turn when notifications are configured. Errors explain missing authentication, repository, or an absent/closed pull request. |
57
+ | `abort_agent_task` | no | [Experimental] Undocumented internal GitHub endpoint that can change without notice. Request cancellation of task_id via the internal steer endpoint; not verified against live GitHub. Use only to stop work, not to read status. Returns accepted, status, and terminal; accepted=false with reason when already finished. Acceptance does not mean cancellation has completed. Check authentication and task access on errors. |
58
+ | `list_copilot_models` | yes | Discover model IDs before create_agent_task. Reads /agents/swe/models and returns source metadata plus models with ID, name, vendor, preview, token prices or billing multiplier, and optional promotion/policy. No parameters. Availability remains subject to repository policy. Errors explain missing authentication, upstream access/network failures, or an invalid upstream response. |
59
59
  <!-- END AUTOMATED TOOLS -->
60
60
 
61
61
  After `create_agent_task`, end your turn. The server returns `follow_up` and `next_step`: either wake on a webhook or schedule `list_agent_tasks` (not before `check_after`).
62
62
 
63
+ Version **0.2.0** preserves the six tool names, inputs, and JSON text responses from 0.1.0. Every tool now advertises an output schema and returns matching `structuredContent`. See [tool contracts and error codes](docs/tools.md).
64
+
63
65
  ## Client setup
64
66
 
65
67
  Run the same stdio command everywhere:
@@ -128,10 +130,44 @@ Point stdio transport at `npx -y github:daniel-saezv/copilot-agents-mcp`. Pass a
128
130
  npx -y github:daniel-saezv/copilot-agents-mcp watch
129
131
  ```
130
132
 
131
- `create_agent_task` also starts a detached watcher when `COPILOT_AGENTS_NOTIFY_URL` is set. The watcher polls pending tasks, updates local state under a directory lock, and POSTs completion notices once per terminal state.
133
+ `create_agent_task` also starts a detached watcher when an eligible owner webhook or `COPILOT_AGENTS_NOTIFY_URL` is configured. The watcher polls pending tasks, updates local state under a directory lock, and records completion delivery.
132
134
 
133
135
  Several agents can share one server; pass a stable `owner` on create and filter with `list_agent_tasks` (labeling convention, not a security boundary).
134
136
 
137
+ ## Optional per-client webhooks
138
+
139
+ A webhook is the **RECOMMENDED** completion path. Clients that can receive webhooks should register one from the start with `webhook register`. `check_later` is the supported fallback: end the turn, schedule a check at `check_after` if possible, never poll in a loop. Webhook registration is local CLI configuration, not an MCP tool:
140
+
141
+ ```bash
142
+ copilot-agents-mcp webhook register --owner client-1
143
+ copilot-agents-mcp webhook list
144
+ copilot-agents-mcp auth status
145
+ copilot-agents-mcp webhook remove --owner client-1
146
+ ```
147
+
148
+ Registration reads the URL and complete `Authorization` header value through hidden terminal prompts. Alternatively, supply private input files with `--url-file /path/to/url-file --auth-file /path/to/auth-file`. Never put either secret in argv, environment variables for this command, or chat. Keep input files private and remove them when no longer needed.
149
+
150
+ Use the same `owner` when calling `create_agent_task`. Owners are exact, case-sensitive routing labels, **not authentication**: any local process with state access can register any owner. All clients and the watcher must share `COPILOT_AGENTS_STATE_PATH` (default `~/.copilot-agents-mcp/state.json`).
151
+
152
+ For an owner without a registration, only the creation response adds: “No webhook: using check_later. Recommended: configure one with `webhook register`.” It never blocks creation or repeats on status checks.
153
+
154
+ The registry stores the URL, registration time, and key file path in locked local state; the Authorization value lives separately in a mode `0600` file named `sha256(owner)` beside that state. `webhook list` shows only owner, URL host, key path, and registration time. `auth status` reports owner, host, and key presence/permissions, never the URL path/query or Authorization value.
155
+
156
+ Only tasks created **after** registration route to that owner. Other tasks retain the existing global `COPILOT_AGENTS_NOTIFY_URL` / `COPILOT_AGENTS_NOTIFY_AUTHORIZATION` fallback. Failed owner delivery does not forward secrets or task data to the global endpoint. Re-registration applies only to subsequent tasks.
157
+
158
+ Owner endpoints must use public HTTPS. Registration and delivery validate every resolved IP, blocking local/private, CGNAT, link-local, metadata, unspecified, multicast, and broadcast destinations, including IPv4-mapped IPv6. Delivery pins a validated address while retaining the original TLS hostname, preventing DNS rebinding; redirects fail. `COPILOT_AGENTS_NOTIFY_ALLOWED_HOSTS` optionally narrows allowed hostnames (comma-separated); it never permits blocked IPs. Unset means any public HTTPS host.
159
+
160
+ Owner and global POST bodies contain only `task_id`, `state`, `repo`, and `pr_url` (nullable), with a stable `Idempotency-Key: <task_id>:<status>` per task and terminal status. Receivers should deduplicate this key and call `get_agent_task` for details. Delivery records remain in local state; inspect `get_agent_task.delivery` and use scheduled checks if delivery fails.
161
+
162
+ If the receiver uses a private CA, set `NODE_EXTRA_CA_CERTS=/path/to/ca.pem` before starting the server/watcher process that sends webhooks. Setting it only on the receiver does not configure the sender's trust.
163
+
164
+ ### Example client: Grok Bot routine
165
+
166
+ 1. Each bot creates its own webhook-trigger routine.
167
+ 2. The owner copies that routine's URL and complete Authorization value into the hidden prompts of `copilot-agents-mcp webhook register --owner <botName>`. Never paste either into chat.
168
+ 3. Have that bot launch a tiny task with `owner: "<botName>"`, such as a one-line documentation correction.
169
+ 4. Verify end-to-end that its routine receives the terminal notice and calls `get_agent_task` once for the result. Confirm another bot's routine is not triggered. No release or merge is needed.
170
+
135
171
  ## Develop
136
172
 
137
173
  ```bash
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
3
4
  import { resolve } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -10,11 +11,16 @@ import { readSweModels } from "./swe-models.js";
10
11
  import { buildServer, defaultLaunchWatcher, packageVersion } from "./server.js";
11
12
  import { buildLocalStatusDiagnostics } from "./status-local.js";
12
13
  import { defaultStatePath } from "./state.js";
13
- import { deliverNotice } from "./notify.js";
14
+ import { deliverTaskNotice } from "./notify.js";
14
15
  import { acquireWatcher, releaseWatcher, runWatcher, watcherLockPath } from "./watch.js";
16
+ import { listWebhooks, registerWebhook, removeWebhook, WEBHOOK_ERROR, WEBHOOK_INPUT_ERROR } from "./webhooks.js";
17
+ import { validateOwner } from "./tasks.js";
18
+ import { WebhookValidationError } from "./webhook-http.js";
15
19
  export const WATCH_POLL_INTERVAL_MS = 15_000;
16
20
  export function parseArgs(argv) {
17
21
  const args = [...argv];
22
+ if (args[0] === "webhook")
23
+ return parseWebhookArgs(args.slice(1));
18
24
  if (args.includes("--version"))
19
25
  return { command: "version" };
20
26
  if (args[0] === "watch") {
@@ -43,10 +49,39 @@ export function parseArgs(argv) {
43
49
  continue;
44
50
  if (arg === "--help" || arg === "-h")
45
51
  throw new Help();
46
- throw new Error(`Unknown argument: ${arg}`);
52
+ throw new Error("Unknown argument.");
47
53
  }
48
54
  return { command: "serve" };
49
55
  }
56
+ function parseWebhookArgs(args) {
57
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h"))
58
+ throw new Help();
59
+ const action = args[0];
60
+ if ((action === "register" || action === "remove" || action === "list") && args.length === 2 && (args[1] === "--help" || args[1] === "-h")) {
61
+ throw new Help();
62
+ }
63
+ if (action === "list" && args.length === 1)
64
+ return { command: "webhook", action };
65
+ if (action !== "register" && action !== "remove")
66
+ throw new Error(WEBHOOK_INPUT_ERROR);
67
+ const values = new Map();
68
+ for (let index = 1; index < args.length; index += 2) {
69
+ const flag = args[index];
70
+ const value = args[index + 1];
71
+ if (!flag || !value || value.startsWith("-") || values.has(flag)
72
+ || (flag !== "--owner" && !(action === "register" && (flag === "--url-file" || flag === "--auth-file")))) {
73
+ throw new Error(WEBHOOK_INPUT_ERROR);
74
+ }
75
+ values.set(flag, value);
76
+ }
77
+ try {
78
+ const owner = validateOwner(values.get("--owner") ?? "");
79
+ return { command: "webhook", action, owner, urlFile: values.get("--url-file"), authFile: values.get("--auth-file") };
80
+ }
81
+ catch {
82
+ throw new Error(WEBHOOK_INPUT_ERROR);
83
+ }
84
+ }
50
85
  class Help extends Error {
51
86
  constructor() {
52
87
  super(helpText());
@@ -67,9 +102,17 @@ function helpText() {
67
102
  " Delete the keyring session.",
68
103
  "copilot-agents-mcp auth status",
69
104
  " Show which credential is active without showing the token, plus local diagnostics (state, notify env, D-Bus).",
105
+ "copilot-agents-mcp webhook register --owner <id> [--url-file <path>] [--auth-file <path>]",
106
+ " Files contain the URL and complete Authorization header value; surrounding whitespace is trimmed.",
107
+ " Missing secret files require hidden terminal prompts. Secrets are never accepted as arguments.",
108
+ "copilot-agents-mcp webhook list",
109
+ " Show owner, host, key file path, and registration time (never URL or authorization).",
110
+ "copilot-agents-mcp webhook remove --owner <id>",
111
+ " Remove the registration and key file; safe to repeat.",
70
112
  "",
71
113
  "Environment: GITHUB_PERSONAL_ACCESS_TOKEN, COPILOT_AGENTS_GITHUB_APP_CLIENT_ID,",
72
- "COPILOT_AGENTS_NOTIFY_URL, COPILOT_AGENTS_NOTIFY_AUTHORIZATION, COPILOT_AGENTS_STATE_PATH,",
114
+ "COPILOT_AGENTS_NOTIFY_URL, COPILOT_AGENTS_NOTIFY_AUTHORIZATION, COPILOT_AGENTS_NOTIFY_ALLOWED_HOSTS,",
115
+ "COPILOT_AGENTS_STATE_PATH,",
73
116
  "COPILOT_AGENTS_GITHUB_API_BASE_URL",
74
117
  ].join("\n");
75
118
  }
@@ -130,7 +173,7 @@ async function watch() {
130
173
  await runWatcher({
131
174
  client: githubClient(token, process.env, session),
132
175
  statePath,
133
- deliver: (notice) => deliverNotice(notice),
176
+ deliver: (_notice, task) => deliverTaskNotice(task, statePath),
134
177
  intervalMs: WATCH_POLL_INTERVAL_MS,
135
178
  });
136
179
  }
@@ -160,6 +203,8 @@ async function main() {
160
203
  await status();
161
204
  else if (command.command === "version")
162
205
  console.log(packageVersion());
206
+ else if (command.command === "webhook")
207
+ await webhook(command);
163
208
  else
164
209
  await serve();
165
210
  }
@@ -168,6 +213,89 @@ async function main() {
168
213
  process.exitCode = error instanceof Help ? 0 : 1;
169
214
  }
170
215
  }
216
+ async function webhook(command) {
217
+ try {
218
+ const statePath = defaultStatePath();
219
+ if (command.action === "list") {
220
+ for (const item of await listWebhooks(statePath)) {
221
+ console.log(`${item.owner}\t${item.host}\t${item.keyFilePath}\t${item.registeredAt}`);
222
+ }
223
+ }
224
+ else if (command.action === "remove") {
225
+ await removeWebhook(statePath, command.owner);
226
+ console.log("Webhook removed.");
227
+ }
228
+ else {
229
+ if ((!command.urlFile || !command.authFile) && (!process.stdin.isTTY || !process.stderr.isTTY)) {
230
+ throw new Error(WEBHOOK_INPUT_ERROR);
231
+ }
232
+ const url = command.urlFile ? await readWebhookInput(command.urlFile) : await hiddenPrompt("Webhook URL: ");
233
+ const authorization = command.authFile ? await readWebhookInput(command.authFile) : await hiddenPrompt("Authorization header value: ");
234
+ await registerWebhook(statePath, command.owner, url, authorization);
235
+ console.log("Webhook registered.");
236
+ }
237
+ }
238
+ catch (error) {
239
+ if (error instanceof WebhookValidationError)
240
+ throw error;
241
+ throw new Error(error instanceof Error && error.message === WEBHOOK_INPUT_ERROR ? WEBHOOK_INPUT_ERROR : WEBHOOK_ERROR);
242
+ }
243
+ }
244
+ async function readWebhookInput(path) {
245
+ try {
246
+ return (await readFile(path, "utf8")).trim();
247
+ }
248
+ catch {
249
+ throw new Error(WEBHOOK_INPUT_ERROR);
250
+ }
251
+ }
252
+ function hiddenPrompt(label) {
253
+ return new Promise((resolvePrompt, reject) => {
254
+ const input = process.stdin;
255
+ const wasRaw = input.isRaw;
256
+ let value = "";
257
+ const finish = (result) => {
258
+ input.off("data", onData);
259
+ input.off("end", onEnd);
260
+ input.off("error", onEnd);
261
+ try {
262
+ input.setRawMode(wasRaw);
263
+ }
264
+ catch {
265
+ result = undefined;
266
+ }
267
+ input.pause();
268
+ process.stderr.write("\n");
269
+ if (result === undefined)
270
+ reject(new Error(WEBHOOK_INPUT_ERROR));
271
+ else
272
+ resolvePrompt(result);
273
+ };
274
+ const onEnd = () => finish();
275
+ const onData = (data) => {
276
+ for (const char of data.toString("utf8")) {
277
+ if (char === "\r" || char === "\n") {
278
+ finish(value);
279
+ return;
280
+ }
281
+ if (char === "\u0003" || char === "\u0004" || char === "\u001b") {
282
+ finish();
283
+ return;
284
+ }
285
+ if (char === "\u007f" || char === "\b")
286
+ value = value.slice(0, -1);
287
+ else if (char >= " ")
288
+ value += char;
289
+ }
290
+ };
291
+ input.setRawMode(true);
292
+ input.on("data", onData);
293
+ input.once("end", onEnd);
294
+ input.once("error", onEnd);
295
+ process.stderr.write(label);
296
+ input.resume();
297
+ });
298
+ }
171
299
  function warnIgnored(env) {
172
300
  const message = ignoredTokenWarning(env);
173
301
  if (message)
package/dist/errors.js CHANGED
@@ -7,35 +7,6 @@ export function githubAppInstallUrl() {
7
7
  export function appNotInstalledMessage() {
8
8
  return `The app is not installed in any repository. Install it at ${githubAppInstallUrl()}.`;
9
9
  }
10
- export function withMissingAppInstall(message, status, path, appCredential) {
11
- if (!appCredential || status !== 404)
12
- return message;
13
- const repository = repositoryFromPath(path);
14
- if (!repository)
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
- }
20
- return `Install the app for ${repository.owner}/${repository.repo}: ${githubAppInstallUrl()}. ${message}`;
21
- }
22
- function repositoryFromPath(path) {
23
- const match = /\/repos\/([^/]+)\/([^/?]+)/.exec(path);
24
- const ownerPart = match?.[1];
25
- const repoPart = match?.[2];
26
- if (!ownerPart || !repoPart)
27
- return null;
28
- try {
29
- const owner = decodeURIComponent(ownerPart);
30
- const repo = decodeURIComponent(repoPart);
31
- if (!owner || !repo)
32
- return null;
33
- return { owner, repo };
34
- }
35
- catch {
36
- return null;
37
- }
38
- }
39
10
  export const TASK_HAS_NO_PULL_REQUEST = "task_has_no_pull_request";
40
11
  export const TASK_PULL_REQUEST_NOT_OPEN = "task_pull_request_not_open";
41
12
  export class ToolFailure extends Error {
@@ -44,18 +15,6 @@ export class ToolFailure extends Error {
44
15
  this.name = "ToolFailure";
45
16
  }
46
17
  }
47
- export class GitHubError extends Error {
48
- constructor(message) {
49
- super(message);
50
- this.name = "GitHubError";
51
- }
52
- }
53
- export class ModelsError extends Error {
54
- constructor(message) {
55
- super(message);
56
- this.name = "ModelsError";
57
- }
58
- }
59
18
  export class AuthError extends Error {
60
19
  constructor(message) {
61
20
  super(message);
@@ -94,6 +53,18 @@ export class CodedToolFailure extends ToolFailure {
94
53
  return body;
95
54
  }
96
55
  }
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";
66
+ }
67
+ }
97
68
  export function toolError(message) {
98
69
  const body = typeof message === "string" ? legacyErrorBody(message) : message;
99
70
  const text = compactStringify(body);
@@ -174,15 +145,68 @@ export function isModelUnavailable(message) {
174
145
  return MODEL_UNAVAILABLE.test(message);
175
146
  }
176
147
  export function formatApiError(status, headers, body) {
148
+ return apiFailure(status, headers, body).message;
149
+ }
150
+ export function apiFailure(status, headers, body, context) {
177
151
  const record = body && typeof body === "object" ? body : {};
178
- const message = typeof record.message === "string" && record.message.trim() ? record.message.trim() : `HTTP ${status}`;
179
- const details = flattenErrors(record.errors);
180
- let text = details ? `${message}: ${details}` : message;
152
+ const upstreamMessage = typeof body === "string" ? body : typeof record.message === "string" ? record.message : "";
181
153
  const retry = retrySeconds(headers);
182
- if (retry !== null && (status === 429 || status === 403 || /rate limit/i.test(text))) {
183
- text += `. Retry after ${retry} seconds`;
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.";
188
+ }
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.";
184
192
  }
185
- return text;
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
+ };
186
210
  }
187
211
  function flattenErrors(errors) {
188
212
  if (!Array.isArray(errors))
@@ -192,25 +216,22 @@ function flattenErrors(errors) {
192
216
  if (!item || typeof item !== "object")
193
217
  continue;
194
218
  const record = item;
195
- if (typeof record.message === "string" && record.message.trim()) {
196
- parts.push(record.message.trim());
197
- continue;
198
- }
199
219
  const field = typeof record.field === "string" ? record.field : "";
200
220
  const code = typeof record.code === "string" ? record.code : "";
201
- const text = [field, code].filter(Boolean).join(" ");
202
- if (text)
203
- parts.push(text);
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
+ }
204
225
  }
205
226
  return parts.length > 0 ? parts.join("; ") : null;
206
227
  }
207
228
  function retrySeconds(headers) {
208
229
  const retryAfter = headers.get("retry-after");
209
- if (retryAfter && /^\d+$/.test(retryAfter.trim()))
210
- return Number(retryAfter.trim());
230
+ if (retryAfter && /^\d+$/.test(retryAfter.trim()) && Number.isSafeInteger(Number(retryAfter)))
231
+ return Number(retryAfter);
211
232
  const remaining = headers.get("x-ratelimit-remaining");
212
233
  const reset = headers.get("x-ratelimit-reset");
213
- if (remaining === "0" && reset && /^\d+$/.test(reset.trim())) {
234
+ if (remaining === "0" && reset && /^\d+$/.test(reset.trim()) && Number.isSafeInteger(Number(reset))) {
214
235
  return Math.max(0, Number(reset.trim()) - Math.floor(Date.now() / 1000));
215
236
  }
216
237
  return null;
@@ -252,19 +273,21 @@ function acceptedPermissions(header) {
252
273
  const eq = trimmed.indexOf("=");
253
274
  const slug = (eq === -1 ? trimmed : trimmed.slice(0, eq)).trim().toLowerCase();
254
275
  const level = eq === -1 ? "" : trimmed.slice(eq + 1).trim().toLowerCase();
255
- if (!slug)
256
- continue;
257
276
  const name = permissionLabel(slug);
277
+ if (!name || (level && !["read", "write", "admin"].includes(level)))
278
+ continue;
258
279
  labels.push(level ? `${name}: ${level}` : name);
259
280
  }
260
281
  return labels;
261
282
  }
262
283
  function permissionLabel(slug) {
263
- const words = slug.split("_").filter(Boolean);
264
- const first = words[0];
265
- if (!first)
266
- return slug;
267
- return [first.charAt(0).toUpperCase() + first.slice(1), ...words.slice(1)].join(" ");
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;
268
291
  }
269
292
  function joinEnglish(items) {
270
293
  if (items.length <= 1)
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, formatApiError, missingPermission, redact, withMissingAppInstall } from "./errors.js";
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",
@@ -201,9 +201,9 @@ async function callGitHub(options) {
201
201
  const first = await sendGitHub(options, firstToken);
202
202
  if (first.response.status === 401 && options.tokens) {
203
203
  const nextToken = await options.tokens.refresh(firstToken);
204
- return acceptGitHub(options, await sendGitHub(options, nextToken), nextToken);
204
+ return acceptGitHub(options, await sendGitHub(options, nextToken));
205
205
  }
206
- return acceptGitHub(options, first, firstToken);
206
+ return acceptGitHub(options, first);
207
207
  }
208
208
  async function sendGitHub(options, token) {
209
209
  const profile = options.profile ?? "public";
@@ -229,10 +229,9 @@ async function sendGitHub(options, token) {
229
229
  }
230
230
  catch (error) {
231
231
  if (error instanceof Error && error.name === "TimeoutError") {
232
- throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`);
232
+ throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`, { code: "upstream_timeout", retryable: true });
233
233
  }
234
- const message = error instanceof Error ? error.message : "network error";
235
- throw new GitHubError(redact(`Could not call the GitHub API: ${message}`, token));
234
+ throw new GitHubError("Could not call the GitHub API. Check your network connection and GitHub service status.", { code: "upstream_error", retryable: true });
236
235
  }
237
236
  let text;
238
237
  try {
@@ -240,13 +239,12 @@ async function sendGitHub(options, token) {
240
239
  }
241
240
  catch (error) {
242
241
  if (error instanceof Error && error.name === "TimeoutError") {
243
- throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`);
242
+ throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`, { code: "upstream_timeout", retryable: true });
244
243
  }
245
244
  if (error instanceof DOMException && error.name === "AbortError") {
246
- throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`);
245
+ throw new GitHubError(`The GitHub API call timed out after ${timeoutMs} milliseconds.`, { code: "upstream_timeout", retryable: true });
247
246
  }
248
- const message = error instanceof Error ? error.message : "network error";
249
- throw new GitHubError(redact(`Could not read the GitHub API response: ${message}`, token));
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 });
250
248
  }
251
249
  let parsed = null;
252
250
  if (text) {
@@ -259,16 +257,15 @@ async function sendGitHub(options, token) {
259
257
  }
260
258
  return { response, parsed, text };
261
259
  }
262
- function acceptGitHub(options, sent, token) {
260
+ function acceptGitHub(options, sent) {
263
261
  const { response, parsed, text } = sent;
264
262
  if (!response.ok) {
265
- const detail = parsed === null && text
266
- ? `HTTP ${response.status}`
267
- : formatApiError(response.status, response.headers, parsed);
268
- const missing = missingPermission(response.status, response.headers, parsed ?? text, options.permission);
269
- const message = missing ? `${missing} ${detail}` : detail;
270
- const annotated = withMissingAppInstall(message, response.status, options.path, options.tokens !== undefined);
271
- 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);
272
269
  }
273
270
  if (options.acceptEmpty && response.status === 202)
274
271
  return undefined;
package/dist/notify.js CHANGED
@@ -1,12 +1,30 @@
1
- import { appendFile, mkdir } from "node:fs/promises";
1
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
2
2
  import { dirname } from "node:path";
3
- import { webhookPayloadId } from "./delivery.js";
4
- import { mapRawState } from "./task-status.js";
3
+ import { readState, toDeliveryNotice } from "./state.js";
4
+ import { ownerWebhook } from "./webhooks.js";
5
+ import { postOwnerNotice, webhookPost } from "./webhook-http.js";
5
6
  export const NOTIFY_URL_ENV = "COPILOT_AGENTS_NOTIFY_URL";
6
7
  export const NOTIFY_AUTHORIZATION_ENV = "COPILOT_AGENTS_NOTIFY_AUTHORIZATION";
7
8
  export function activeNotificationChannels(_platform, baseEnv) {
8
9
  return baseEnv[NOTIFY_URL_ENV]?.trim() ? ["webhook"] : [];
9
10
  }
11
+ export function notificationChannelsForTask(task, state, env = process.env) {
12
+ return ownerWebhook(state, task) ? ["webhook"] : activeNotificationChannels(process.platform, env);
13
+ }
14
+ export async function deliverTaskNotice(task, statePath, env = process.env, fetchImpl = fetch, ownerPost = postOwnerNotice) {
15
+ const registration = ownerWebhook(await readState(statePath), task);
16
+ if (!registration)
17
+ return deliverNotice(toDeliveryNotice(task), env, fetchImpl);
18
+ try {
19
+ const authorization = await readFile(registration.keyFilePath, "utf8");
20
+ await ownerPost(registration.url, toDeliveryNotice(task), authorization, env);
21
+ return { channels: ["webhook"] };
22
+ }
23
+ catch {
24
+ await appendWatcherLog("Could not POST the owner task notification.", env);
25
+ return { channels: [] };
26
+ }
27
+ }
10
28
  export function createNextStep(channels) {
11
29
  if (channels.length === 0) {
12
30
  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.";
@@ -28,14 +46,11 @@ export async function appendWatcherLog(line, env = process.env) {
28
46
  }
29
47
  }
30
48
  export async function postNotice(url, notice, authorization, fetchImpl = fetch) {
31
- const headers = { "content-type": "application/json" };
32
- if (authorization)
33
- headers.authorization = authorization;
34
- const mapped = mapRawState(notice.state);
49
+ const { body, headers } = webhookPost(notice, authorization);
35
50
  const response = await fetchImpl(url, {
36
51
  method: "POST",
37
52
  headers,
38
- body: JSON.stringify({ ...notice, status: mapped.status, terminal: mapped.terminal, id: webhookPayloadId(notice.task_id, notice.state) }),
53
+ body,
39
54
  signal: AbortSignal.timeout(10_000),
40
55
  });
41
56
  if (!response.ok)