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/dist/server.js CHANGED
@@ -6,12 +6,12 @@ import { presentSweModelsResult, sweModelsResultSchema } from "./swe-models.js";
6
6
  import { TOOLS, toolNames } from "./selection.js";
7
7
  import { deliveryForTask, shouldSpawnWatcher } from "./delivery.js";
8
8
  import { createFollowUpNextStep, followUpBlock } from "./follow-up.js";
9
- import { activeNotificationChannels, appendWatcherLog } from "./notify.js";
9
+ import { activeNotificationChannels, appendWatcherLog, notificationChannelsForTask } from "./notify.js";
10
10
  import { compactGetTask } from "./task-present.js";
11
11
  import { mapRawState } from "./task-status.js";
12
12
  import { prUrl, resolveTaskPageUrl } from "./task-urls.js";
13
13
  import { aggregateNextCheckAfter, filterTasks, freshnessMs, listCounts, listNextStep, needsFetch, resolveNextCheckAfter, OwnerValidationError, pruneRegistry, refreshTasks, toListRow, validateOwner, } from "./tasks.js";
14
- import { armSteer, fillPullRequest, headRefOf, initialTask, isFinalState, normalizeModel, observe, taskSessionCount, withStateLock, } from "./state.js";
14
+ import { armSteer, fillPullRequest, headRefOf, initialTask, isFinalState, normalizeModel, observe, readState, taskSessionCount, withStateLock, } from "./state.js";
15
15
  import { startDetachedWatcher } from "./watch.js";
16
16
  export function packageVersion() {
17
17
  const parsed = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
@@ -22,21 +22,21 @@ export function packageVersion() {
22
22
  }
23
23
  const OWNER_FIELD = "Stable agent name (e.g. your bot's name). Required for multi-agent setups: pass owner=<your agent name> on every create so list_agent_tasks with that owner shows only your tasks. Not a security boundary.";
24
24
  const createInput = z.object({
25
- repo: z.string().describe("Repository in owner/name form."),
26
- prompt: z.string().describe("Instructions for the agent."),
27
- model: z.string().describe("Model sent unchanged to the API without a closed allowlist."),
28
- base_ref: z.string().optional().describe("Base branch for a new branch or pull request."),
29
- head_ref: z.string().optional().describe("Existing branch. With base_ref, the agent commits to this branch."),
30
- custom_agent: z.string().optional().describe("Custom agent name without the extension."),
31
- create_pull_request: z.boolean().optional().describe("When true, the API creates a pull request."),
25
+ repo: z.string().describe("Required repository in owner/name form, e.g. octocat/hello-world; surrounding whitespace is trimmed."),
26
+ prompt: z.string().describe("Required non-blank task instructions; surrounding whitespace is trimmed. Never include credentials."),
27
+ model: z.string().describe("Required non-blank model ID, e.g. gpt-6.1-sol; trimmed and sent unchanged without a closed allowlist. Discover IDs with list_copilot_models."),
28
+ base_ref: z.string().optional().describe("Base branch for a new branch or pull request, e.g. main. Omit to use GitHub's default."),
29
+ head_ref: z.string().optional().describe("Existing branch. With base_ref, the agent commits to this branch. Omit to let GitHub choose."),
30
+ custom_agent: z.string().optional().describe("Custom agent name without the extension. Omit to use GitHub's default agent."),
31
+ create_pull_request: z.boolean().optional().describe("When true, the API creates a pull request. Omit to use GitHub's default."),
32
32
  owner: z.string().min(1).max(64).regex(/^[A-Za-z0-9._-]+$/).optional().describe(OWNER_FIELD),
33
33
  }).strict();
34
34
  const followUpSchema = z.object({
35
- mode: z.enum(["push", "check_later"]),
36
- channels: z.array(z.enum(["webhook"])).optional(),
37
- check_after: z.string(),
38
- min_interval_s: z.number(),
39
- check_with: z.literal("list_agent_tasks"),
35
+ mode: z.enum(["push", "check_later"]).describe("Wake on a webhook, or end the turn and schedule a later check."),
36
+ channels: z.array(z.enum(["webhook"])).optional().describe("Configured notification channels, when available."),
37
+ check_after: z.string().describe("ISO 8601 timestamp; do not check before this time."),
38
+ min_interval_s: z.number().describe("Minimum seconds between subsequent checks."),
39
+ check_with: z.literal("list_agent_tasks").describe("Tool to call for a scheduled check."),
40
40
  }).strict();
41
41
  const createOutput = z.object({
42
42
  task_id: z.string(),
@@ -53,31 +53,32 @@ const createOutput = z.object({
53
53
  }).strict();
54
54
  const SERVER_INSTRUCTIONS = [
55
55
  "Copilot cloud tasks take minutes. Tools never wait.",
56
- "Always pass owner=<your agent name> to create_agent_task so list_agent_tasks with that owner shows only your tasks.",
57
- "After create_agent_task, end your turn and follow next_step; do not poll in a loop.",
58
- "First list check not before follow_up.check_after; call list_agent_tasks with your owner at most every follow_up.min_interval_s seconds until all_terminal is true.",
59
- "get_agent_task returns one task's full result (once, not in a loop).",
60
- "steer_agent_task sends a user message to a running task with an open pull request; abort_agent_task requests cancellation (experimental GitHub endpoints).",
61
- "With COPILOT_AGENTS_NOTIFY_URL set, the watcher POSTs JSON when a task reaches a terminal state—wake on that webhook and call get_agent_task once. Without it, follow the check_later schedule in next_step.",
56
+ "Pass owner=<your stable agent name> on create_agent_task and list_agent_tasks; owner is a label, not authentication.",
57
+ "A webhook is the RECOMMENDED completion path: configure `webhook register` locally before creating tasks; never pass webhook secrets through MCP.",
58
+ "An eligible owner webhook or COPILOT_AGENTS_NOTIFY_URL enables watcher notifications. Wake on the webhook and call get_agent_task once.",
59
+ "After create_agent_task, follow next_step and end your turn. check_later is the fallback: schedule list_agent_tasks at follow_up.check_after if possible, never poll in a loop.",
60
+ "Check no sooner than check_after, space later checks by at least follow_up.min_interval_s, and stop scheduled checks when all_terminal is true.",
61
+ "Use get_agent_task for one task's result, list_agent_tasks for scheduled batch checks, and list_copilot_models to discover model IDs.",
62
+ "steer_agent_task sends instructions to a task with an open pull request and consumes credits; abort_agent_task requests cancellation. Both use experimental GitHub endpoints.",
62
63
  ].join(" ");
63
64
  const CREATE_TASK_GUIDANCE = "Returns immediately with task_id. Pass owner=<your agent name> unless this server runs a single agent. Follow next_step.";
64
65
  const getInput = z.object({
65
- task_id: z.string().describe("Task identifier."),
66
+ task_id: z.string().describe("Required non-blank identifier returned by create_agent_task; surrounding whitespace is trimmed."),
66
67
  repo: z.string().optional().describe("Repository in owner/name form. If omitted, use the saved repository or user endpoint."),
67
- verbose: z.boolean().optional().describe("Include raw state, models, usage, and full error."),
68
+ verbose: z.boolean().optional().describe("Include raw state, models, usage, artifacts, and error (up to 2048 characters). Default false."),
68
69
  }).strict();
69
70
  const listInput = z.object({
70
71
  owner: z.string().optional().describe(OWNER_FIELD),
71
- task_ids: z.array(z.string()).max(50).optional(),
72
- status: z.enum(["pending", "terminal", "all"]).optional(),
73
- repo: z.string().optional(),
74
- limit: z.number().int().positive().max(50).optional(),
75
- verbose: z.boolean().optional(),
72
+ task_ids: z.array(z.string().describe("Locally tracked task identifier.")).max(50).optional().describe("Filter to at most 50 task IDs. Omit or pass [] for all tracked IDs; unknown IDs produce warnings."),
73
+ status: z.enum(["pending", "terminal", "all"]).optional().describe("Filter by lifecycle status. Default all; completed tasks are visible for seven days."),
74
+ repo: z.string().optional().describe("Exact repository filter in owner/name form. Omit for all repositories."),
75
+ limit: z.number().int().positive().max(50).optional().describe("Maximum rows returned, 1-50; default 20. Counts cover every matching task, not just returned rows."),
76
+ verbose: z.boolean().optional().describe("Compatibility flag, default false. List rows remain compact; use get_agent_task with verbose=true for details."),
76
77
  }).strict();
77
78
  const experimentalNotice = "[Experimental] Undocumented internal GitHub endpoint that can change without notice.";
78
79
  const steerInput = z.object({
79
- task_id: z.string().describe("Task identifier."),
80
- content: z.string().describe("Instructions to send to the task."),
80
+ task_id: z.string().describe("Required non-blank task identifier returned by create_agent_task."),
81
+ content: z.string().describe("Required non-blank follow-up instructions, trimmed before sending. Each call consumes credits; never include credentials."),
81
82
  }).strict();
82
83
  const steerOutput = z.object({
83
84
  task_id: z.string(),
@@ -85,7 +86,7 @@ const steerOutput = z.object({
85
86
  session_count: z.number(),
86
87
  }).strict();
87
88
  const abortInput = z.object({
88
- task_id: z.string().describe("Task identifier."),
89
+ task_id: z.string().describe("Required non-blank task identifier returned by create_agent_task."),
89
90
  }).strict();
90
91
  const abortOutput = z.object({
91
92
  task_id: z.string(),
@@ -94,6 +95,63 @@ const abortOutput = z.object({
94
95
  status: z.enum(["working", "needs_input", "completed", "failed", "cancelled"]).optional(),
95
96
  terminal: z.boolean().optional(),
96
97
  }).strict();
98
+ const taskRowFields = {
99
+ task_id: z.string(),
100
+ repo: z.string(),
101
+ owner: z.string().optional(),
102
+ status: z.enum(["working", "needs_input", "completed", "failed", "cancelled"]),
103
+ terminal: z.boolean(),
104
+ summary: z.string(),
105
+ pr_url: z.string().optional(),
106
+ session_url: z.string().optional(),
107
+ updated_at: z.string().optional(),
108
+ stale: z.boolean().optional(),
109
+ cached: z.boolean().optional(),
110
+ warning: z.string().optional(),
111
+ };
112
+ const branchFields = {
113
+ head_ref: z.string(),
114
+ base_ref: z.string(),
115
+ };
116
+ const getOutput = z.object({
117
+ ...taskRowFields,
118
+ delivery: z.enum(["not_configured", "pending", "delivered", "failed"]),
119
+ next_step: z.string().optional(),
120
+ warnings: z.array(z.string()).optional(),
121
+ completed_at: z.string().optional(),
122
+ state: z.string().optional(),
123
+ requested_model: z.string().optional(),
124
+ resolved_model: z.string().optional(),
125
+ pull_request: z.object({
126
+ id: z.number().optional(),
127
+ number: z.number().optional(),
128
+ url: z.string().optional(),
129
+ }).strict().optional(),
130
+ branch: z.object(branchFields).strict().optional(),
131
+ artifacts: z.array(z.discriminatedUnion("type", [
132
+ z.object({ type: z.literal("pull"), id: z.number() }).strict(),
133
+ z.object({ type: z.literal("branch"), ...branchFields }).strict(),
134
+ ])).optional(),
135
+ usage: z.object({
136
+ type: z.enum(["ai_credits", "premium_requests"]),
137
+ amount: z.number(),
138
+ amount_human: z.number(),
139
+ }).strict().optional(),
140
+ session_id: z.string().optional(),
141
+ created_at: z.string().optional(),
142
+ error: z.string().optional(),
143
+ delivered_via: z.string().optional(),
144
+ }).strict();
145
+ const listOutput = z.object({
146
+ tasks: z.array(z.object(taskRowFields).strict()),
147
+ pending_count: z.number().int().nonnegative(),
148
+ terminal_count: z.number().int().nonnegative(),
149
+ all_terminal: z.boolean(),
150
+ next_step: z.string(),
151
+ next_check_after: z.string().optional(),
152
+ warnings: z.array(z.string()).optional(),
153
+ stale: z.boolean().optional(),
154
+ }).strict();
97
155
  export function buildServer(deps) {
98
156
  const enabled = new Set(toolNames());
99
157
  const server = new McpServer({
@@ -105,7 +163,7 @@ export function buildServer(deps) {
105
163
  if (enabled.has("create_agent_task")) {
106
164
  server.registerTool("create_agent_task", {
107
165
  title: "Launch Copilot task",
108
- description: `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. ${CREATE_TASK_GUIDANCE}`,
166
+ description: `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. ${CREATE_TASK_GUIDANCE}`,
109
167
  inputSchema: createInput,
110
168
  outputSchema: createOutput,
111
169
  annotations: toolAnnotations("create_agent_task", "Launch Copilot task"),
@@ -114,23 +172,25 @@ export function buildServer(deps) {
114
172
  if (enabled.has("get_agent_task")) {
115
173
  server.registerTool("get_agent_task", {
116
174
  title: "Get task status",
117
- description: "Read one task once. Returns status, terminal and a one-line summary. Do not call repeatedly; use list_agent_tasks for periodic checks.",
175
+ description: "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.",
118
176
  inputSchema: getInput,
177
+ outputSchema: getOutput,
119
178
  annotations: toolAnnotations("get_agent_task", "Get task status"),
120
179
  }, async (args) => run(() => readTask(args, deps)));
121
180
  }
122
181
  if (enabled.has("list_agent_tasks")) {
123
182
  server.registerTool("list_agent_tasks", {
124
183
  title: "List tracked tasks",
125
- description: "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.",
184
+ description: "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.",
126
185
  inputSchema: listInput,
186
+ outputSchema: listOutput,
127
187
  annotations: toolAnnotations("list_agent_tasks", "List tracked tasks"),
128
188
  }, async (args) => run(() => listAgentTasks(args, deps)));
129
189
  }
130
190
  if (enabled.has("steer_agent_task")) {
131
191
  server.registerTool("steer_agent_task", {
132
192
  title: "Steer task",
133
- description: `${experimentalNotice} 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.`,
193
+ description: `${experimentalNotice} 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.`,
134
194
  inputSchema: steerInput,
135
195
  outputSchema: steerOutput,
136
196
  annotations: toolAnnotations("steer_agent_task", "Steer task"),
@@ -139,7 +199,7 @@ export function buildServer(deps) {
139
199
  if (enabled.has("abort_agent_task")) {
140
200
  server.registerTool("abort_agent_task", {
141
201
  title: "Abort task",
142
- description: `${experimentalNotice} 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.`,
202
+ description: `${experimentalNotice} 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.`,
143
203
  inputSchema: abortInput,
144
204
  outputSchema: abortOutput,
145
205
  annotations: toolAnnotations("abort_agent_task", "Abort task"),
@@ -148,7 +208,7 @@ export function buildServer(deps) {
148
208
  if (enabled.has("list_copilot_models")) {
149
209
  server.registerTool("list_copilot_models", {
150
210
  title: "List Copilot models",
151
- description: "Read /agents/swe/models and return the ID, name, vendor, preview flag, token prices or multiplier, and promotion when present.",
211
+ description: "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.",
152
212
  inputSchema: z.object({}).strict(),
153
213
  outputSchema: sweModelsResultSchema,
154
214
  annotations: toolAnnotations("list_copilot_models", "List Copilot models"),
@@ -198,8 +258,6 @@ async function createTask(args, deps) {
198
258
  const token = deps.readToken();
199
259
  if (!token)
200
260
  throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
201
- const channels = activeNotificationChannels(process.platform, process.env);
202
- const deliveryRecord = channels.length > 0 ? { status: "pending" } : null;
203
261
  const task = await deps.clientForToken(token).createTask({
204
262
  owner: parsed.owner,
205
263
  repo: parsed.repo,
@@ -210,6 +268,27 @@ async function createTask(args, deps) {
210
268
  ...(args.custom_agent !== undefined ? { custom_agent: args.custom_agent } : {}),
211
269
  ...(args.create_pull_request !== undefined ? { create_pull_request: args.create_pull_request } : {}),
212
270
  });
271
+ const localTask = initialTask({
272
+ id: task.id,
273
+ repo,
274
+ requestedModel: model,
275
+ state: task.state,
276
+ createdAt: task.created_at ?? null,
277
+ updatedAt: task.updated_at ?? null,
278
+ ...(taskOwner ? { owner: taskOwner } : {}),
279
+ htmlUrl: resolveTaskPageUrl(task) ?? null,
280
+ });
281
+ const followUpNow = Date.now();
282
+ const { channels, hasWebhookRegistration } = await withStateLock(deps.statePath, (state) => {
283
+ const configured = notificationChannelsForTask(localTask, state);
284
+ localTask.delivery_record = configured.length > 0 ? { status: "pending" } : null;
285
+ localTask.check_after = followUpBlock(configured, false, followUpNow).check_after;
286
+ state.tasks[task.id] = localTask;
287
+ return {
288
+ channels: configured,
289
+ hasWebhookRegistration: taskOwner !== undefined && Object.hasOwn(state.webhooks ?? {}, taskOwner),
290
+ };
291
+ });
213
292
  const mapped = mapRawState(task.state);
214
293
  let watcher_started = false;
215
294
  if (shouldSpawnWatcher(channels)) {
@@ -222,36 +301,14 @@ async function createTask(args, deps) {
222
301
  }
223
302
  }
224
303
  const session = resolveTaskPageUrl(task);
225
- const follow_up = followUpBlock(channels, watcher_started, Date.now());
226
- await withStateLock(deps.statePath, (state) => {
227
- state.tasks[task.id] = {
228
- ...initialTask({
229
- id: task.id,
230
- repo,
231
- requestedModel: model,
232
- state: task.state,
233
- createdAt: task.created_at ?? null,
234
- updatedAt: task.updated_at ?? null,
235
- ...(taskOwner ? { owner: taskOwner } : {}),
236
- deliveryRecord,
237
- htmlUrl: resolveTaskPageUrl(task) ?? null,
238
- }),
239
- check_after: follow_up.check_after,
240
- };
241
- });
304
+ const follow_up = followUpBlock(channels, watcher_started, followUpNow);
242
305
  const planMode = follow_up.mode;
243
- const next_step = createFollowUpNextStep(planMode, taskOwner, task.id, channels.length > 0 && !watcher_started, follow_up.check_after);
306
+ let next_step = createFollowUpNextStep(planMode, taskOwner, task.id, channels.length > 0 && !watcher_started, follow_up.check_after);
307
+ if (taskOwner && !hasWebhookRegistration) {
308
+ next_step += "\nNo webhook: using check_later. Recommended: configure one with `webhook register`.";
309
+ }
244
310
  const stored = await withStateLock(deps.statePath, (state) => state.tasks[task.id] ?? null);
245
- const delivery = deliveryForTask(stored ?? initialTask({
246
- id: task.id,
247
- repo,
248
- requestedModel: model,
249
- state: task.state,
250
- createdAt: task.created_at ?? null,
251
- updatedAt: task.updated_at ?? null,
252
- deliveryRecord,
253
- htmlUrl: session ?? null,
254
- }), channels);
311
+ const delivery = deliveryForTask(stored ?? localTask, channels);
255
312
  const body = {
256
313
  task_id: task.id,
257
314
  repo,
@@ -278,7 +335,9 @@ async function readTask(args, deps) {
278
335
  const repo = args.repo?.trim() || known?.repo || "";
279
336
  const parsed = repo ? parseRepo(repo) : null;
280
337
  const token = deps.readToken();
281
- const channels = activeNotificationChannels(process.platform, process.env);
338
+ const channels = known
339
+ ? notificationChannelsForTask(known, await readState(deps.statePath))
340
+ : activeNotificationChannels(process.platform, process.env);
282
341
  const freshness = freshnessMs();
283
342
  const now = Date.now();
284
343
  if (!token) {
@@ -482,7 +541,9 @@ async function steerTask(args, deps) {
482
541
  armSteer(task, sessionCount, steeredAt);
483
542
  state.tasks[taskId] = task;
484
543
  });
485
- if (shouldSpawnWatcher(activeNotificationChannels(process.platform, process.env))) {
544
+ const savedState = await readState(deps.statePath);
545
+ const steered = savedState.tasks[taskId];
546
+ if (steered && shouldSpawnWatcher(notificationChannelsForTask(steered, savedState))) {
486
547
  try {
487
548
  deps.launchWatcher();
488
549
  }
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
3
3
  import { dirname } from "node:path";
4
4
  import { defaultStatePath } from "./state.js";
5
5
  import { NOTIFY_AUTHORIZATION_ENV, NOTIFY_URL_ENV } from "./notify.js";
6
+ import { listWebhooks } from "./webhooks.js";
6
7
  export function stateLockDir(statePath) {
7
8
  return `${statePath}.lock`;
8
9
  }
@@ -63,5 +64,16 @@ export async function buildLocalStatusDiagnostics(env, options) {
63
64
  ...formatNotifyEnvDiagnostics(env),
64
65
  ...formatDbusDiagnostics(env, platform),
65
66
  ];
66
- return { text: lines.join("\n"), failed: state.writable === "fail" };
67
+ let webhookFailed = false;
68
+ try {
69
+ const webhooks = await listWebhooks(statePath);
70
+ for (const webhook of webhooks) {
71
+ lines.push(`Owner webhook: ${webhook.owner} — host: ${webhook.host} — key present: ${webhook.keyPresent ? "yes" : "no"} — mode0600: ${webhook.keyMode0600 ? "yes" : "no"}`);
72
+ }
73
+ }
74
+ catch {
75
+ lines.push("Owner webhooks: unavailable.");
76
+ webhookFailed = true;
77
+ }
78
+ return { text: lines.join("\n"), failed: state.writable === "fail" || webhookFailed };
67
79
  }
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { missingPermission, ModelsError, redact } from "./errors.js";
2
+ import { apiFailure, ModelsError } from "./errors.js";
3
3
  export const GRAPHQL_URL = "https://api.github.com/graphql";
4
4
  export const ENDPOINTS_QUERY = "query { viewer { copilotEndpoints { api } } }";
5
5
  export const SWE_MODELS_PATH = "/agents/swe/models";
@@ -16,9 +16,6 @@ const promoSchema = z.object({
16
16
  ends_at: z.string(),
17
17
  message: z.string(),
18
18
  }).strict();
19
- const policySchema = z.object({
20
- state: z.string().optional(),
21
- }).strict();
22
19
  const billingSchema = z.object({
23
20
  token_prices: tokenPricesSchema.optional(),
24
21
  promo: promoSchema.optional(),
@@ -29,7 +26,6 @@ const sweModelSchema = z.object({
29
26
  name: z.string(),
30
27
  vendor: z.string(),
31
28
  preview: z.boolean(),
32
- policy: policySchema.optional(),
33
29
  billing: billingSchema,
34
30
  }).strict();
35
31
  export const sweModelsResultSchema = z.object({
@@ -60,8 +56,6 @@ function presentSweModel(model) {
60
56
  preview: model.preview,
61
57
  billing,
62
58
  };
63
- if (model.policy?.state !== undefined)
64
- row.policy = { state: model.policy.state };
65
59
  return row;
66
60
  }
67
61
  export function validateSweModels(payload) {
@@ -92,7 +86,7 @@ export async function readSweModels(options) {
92
86
  }
93
87
  catch (error) {
94
88
  if (error instanceof ModelsError) {
95
- throw new ModelsError(`GET ${url} returned HTTP 200 with an invalid format: ${error.message}`);
89
+ throw new ModelsError(`The Copilot models API returned HTTP 200 with an invalid format: ${error.message}`);
96
90
  }
97
91
  throw error;
98
92
  }
@@ -114,7 +108,7 @@ async function readApiBase(fetchImpl, holder, tokens) {
114
108
  });
115
109
  const api = readApi(body);
116
110
  if (api === null) {
117
- throw new ModelsError(`POST ${GRAPHQL_URL} returned HTTP 200 with an invalid format: missing data.viewer.copilotEndpoints.api`);
111
+ throw new ModelsError("GitHub endpoint discovery returned HTTP 200 with an invalid format: missing data.viewer.copilotEndpoints.api");
118
112
  }
119
113
  return api;
120
114
  }
@@ -130,7 +124,6 @@ function readApi(body) {
130
124
  return api;
131
125
  }
132
126
  async function readJson(fetchImpl, holder, tokens, url, init, retried = false) {
133
- const method = init.method ?? "GET";
134
127
  const token = holder.token;
135
128
  const headers = new Headers(init.headers);
136
129
  headers.set("authorization", `Bearer ${token}`);
@@ -144,16 +137,20 @@ async function readJson(fetchImpl, holder, tokens, url, init, retried = false) {
144
137
  });
145
138
  }
146
139
  catch (error) {
147
- const message = error instanceof Error ? error.message : "network error";
148
- throw new ModelsError(redact(`Could not call ${method} ${url}: ${message}`, token));
140
+ throw modelsNetworkError(error);
141
+ }
142
+ let text;
143
+ try {
144
+ text = await response.text();
145
+ }
146
+ catch (error) {
147
+ throw modelsNetworkError(error);
149
148
  }
150
149
  if (response.status === 401 && tokens && !retried) {
151
- await response.text();
152
150
  holder.token = await tokens.refresh(token);
153
151
  return readJson(fetchImpl, holder, tokens, url, init, true);
154
152
  }
155
153
  if (response.status !== 200) {
156
- const text = await response.text();
157
154
  let parsed = null;
158
155
  if (text) {
159
156
  try {
@@ -163,18 +160,22 @@ async function readJson(fetchImpl, holder, tokens, url, init, retried = false) {
163
160
  parsed = null;
164
161
  }
165
162
  }
166
- const missing = missingPermission(response.status, response.headers, parsed ?? text, "Agent tasks");
167
- const base = `${method} ${url} returned HTTP ${response.status}.`;
168
- throw new ModelsError(redact(missing ? `${missing} ${base}` : base, token));
163
+ const failure = apiFailure(response.status, response.headers, parsed ?? text, { permission: "Agent tasks" });
164
+ throw new ModelsError(failure.message, failure);
169
165
  }
170
- const text = await response.text();
171
166
  try {
172
167
  return JSON.parse(text);
173
168
  }
174
169
  catch {
175
- throw new ModelsError(`${method} ${url} returned HTTP 200 with a non-JSON body.`);
170
+ throw new ModelsError("The Copilot API returned HTTP 200 with a non-JSON body.");
176
171
  }
177
172
  }
173
+ function modelsNetworkError(error) {
174
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
175
+ return new ModelsError("The Copilot API request timed out. Try listing models again.", { code: "upstream_timeout", retryable: true });
176
+ }
177
+ return new ModelsError("Could not read the Copilot API response. Check your network connection and try listing models again.", { code: "upstream_error", retryable: true });
178
+ }
178
179
  function readModel(item, index) {
179
180
  const where = `data[${index}]`;
180
181
  if (!isRecord(item))
@@ -190,9 +191,6 @@ function readModel(item, index) {
190
191
  preview: readBoolean(item, "preview", `${where}.preview`),
191
192
  billing: {},
192
193
  };
193
- const policy = readPolicy(item, `${where}.policy`);
194
- if (policy)
195
- model.policy = policy;
196
194
  if (hasMultiplier) {
197
195
  model.billing.multiplier = readNumber(item.billing, "multiplier", `${where}.billing.multiplier`);
198
196
  }
@@ -204,19 +202,6 @@ function readModel(item, index) {
204
202
  }
205
203
  return model;
206
204
  }
207
- function readPolicy(item, path) {
208
- if (!Object.prototype.hasOwnProperty.call(item, "policy") || item.policy === undefined || item.policy === null) {
209
- return undefined;
210
- }
211
- if (!isRecord(item.policy))
212
- throw new ModelsError(`${path} is not an object`);
213
- if (!Object.prototype.hasOwnProperty.call(item.policy, "state"))
214
- return undefined;
215
- const state = item.policy.state;
216
- if (state === null || state === undefined)
217
- return undefined;
218
- return { state: readString(item.policy, "state", `${path}.state`) };
219
- }
220
205
  function readPrices(value, path) {
221
206
  if (!isRecord(value))
222
207
  throw new ModelsError(`missing ${path}`);
package/dist/watch.js CHANGED
@@ -4,7 +4,7 @@ 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 { activeNotificationChannels, appendWatcherLog } from "./notify.js";
7
+ import { appendWatcherLog, notificationChannelsForTask } from "./notify.js";
8
8
  import { shouldSpawnWatcher } from "./delivery.js";
9
9
  import { awaitingSteer, fillPullRequest, isFinalState, observe, presentUsage, readState, toDeliveryNotice, withStateLock } from "./state.js";
10
10
  export async function runWatcher(options) {
@@ -45,12 +45,9 @@ async function refreshPending(options) {
45
45
  async function notifyFinal(options, channelOverride) {
46
46
  const ready = await withStateLock(options.statePath, (state) => {
47
47
  return Object.values(state.tasks)
48
- .filter((task) => readyToNotify(task))
48
+ .filter((task) => readyToNotify(task) && shouldSpawnWatcher(channelOverride ?? notificationChannelsForTask(task, state)))
49
49
  .map((task) => task.task_id);
50
50
  });
51
- const channels = channelOverride ?? activeNotificationChannels(process.platform, process.env);
52
- if (!shouldSpawnWatcher(channels))
53
- return;
54
51
  for (const taskId of ready) {
55
52
  const tracked = await withStateLock(options.statePath, (state) => {
56
53
  const task = state.tasks[taskId];
@@ -68,20 +65,20 @@ async function notifyFinal(options, channelOverride) {
68
65
  return null;
69
66
  task.pull_request = tracked.pull_request;
70
67
  task.usage = tracked.usage;
71
- return { notice: toDeliveryNotice(task) };
68
+ return { notice: toDeliveryNotice(task), task, channels: channelOverride ?? notificationChannelsForTask(task, state) };
72
69
  });
73
70
  if (!claimed)
74
71
  continue;
75
72
  let delivered;
76
73
  try {
77
- delivered = await options.deliver(claimed.notice);
74
+ delivered = await options.deliver(claimed.notice, claimed.task);
78
75
  }
79
76
  catch (error) {
80
77
  console.error(`Could not notify for task ${taskId}: ${failureMessage(error)}`);
81
78
  delivered = { channels: [] };
82
79
  }
83
80
  if (delivered.channels.length === 0) {
84
- const configured = activeNotificationChannels(process.platform, process.env);
81
+ const configured = claimed.channels;
85
82
  const reason = configured.length === 0
86
83
  ? "no notification channels configured"
87
84
  : `all configured channels failed (${configured.join(", ")})`;
@@ -122,8 +119,7 @@ function readyToNotify(task) {
122
119
  }
123
120
  async function hasPending(statePath) {
124
121
  const state = await readState(statePath);
125
- const channels = activeNotificationChannels(process.platform, process.env);
126
- return Object.values(state.tasks).some((task) => !isFinalState(task.state) || steerPending(task) || (shouldSpawnWatcher(channels) && readyToNotify(task)));
122
+ return Object.values(state.tasks).some((task) => !isFinalState(task.state) || steerPending(task) || (shouldSpawnWatcher(notificationChannelsForTask(task, state)) && readyToNotify(task)));
127
123
  }
128
124
  function steerPending(task) {
129
125
  return awaitingSteer(task);