copilot-agents-mcp 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,11 +1,17 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { z } from "zod";
4
- import { failureMessage, modelUnavailableMessage, NO_SESSION_MESSAGE, TASK_HAS_NO_PULL_REQUEST, TASK_PULL_REQUEST_NOT_OPEN, toolError, toolJson, ToolFailure } from "./errors.js";
5
- import { sweModelsResultSchema } from "./swe-models.js";
6
- import { selectToolNames, TOOLS } from "./selection.js";
7
- import { appendWatcherLog } from "./notify.js";
8
- import { armSteer, fillPullRequest, headRefOf, initialTask, normalizeModel, observe, taskSessionCount, toNotice, withStateLock } from "./state.js";
4
+ import { CodedToolFailure, failureMessage, failureToError, modelUnavailableMessage, NO_SESSION_MESSAGE, NO_SESSION_STALE_WARNING, TASK_HAS_NO_PULL_REQUEST, TASK_PULL_REQUEST_NOT_OPEN, toolError, toolJson, ToolFailure, } from "./errors.js";
5
+ import { presentSweModelsResult, sweModelsResultSchema } from "./swe-models.js";
6
+ import { TOOLS, toolNames } from "./selection.js";
7
+ import { deliveryForTask, shouldSpawnWatcher } from "./delivery.js";
8
+ import { createFollowUpNextStep, followUpBlock } from "./follow-up.js";
9
+ import { activeNotificationChannels, appendWatcherLog } from "./notify.js";
10
+ import { compactGetTask } from "./task-present.js";
11
+ import { mapRawState } from "./task-status.js";
12
+ import { prUrl, resolveTaskPageUrl } from "./task-urls.js";
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";
9
15
  import { startDetachedWatcher } from "./watch.js";
10
16
  export function packageVersion() {
11
17
  const parsed = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
@@ -14,6 +20,7 @@ export function packageVersion() {
14
20
  }
15
21
  return parsed.version;
16
22
  }
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.";
17
24
  const createInput = z.object({
18
25
  repo: z.string().describe("Repository in owner/name form."),
19
26
  prompt: z.string().describe("Instructions for the agent."),
@@ -22,48 +29,50 @@ const createInput = z.object({
22
29
  head_ref: z.string().optional().describe("Existing branch. With base_ref, the agent commits to this branch."),
23
30
  custom_agent: z.string().optional().describe("Custom agent name without the extension."),
24
31
  create_pull_request: z.boolean().optional().describe("When true, the API creates a pull request."),
32
+ owner: z.string().min(1).max(64).regex(/^[A-Za-z0-9._-]+$/).optional().describe(OWNER_FIELD),
33
+ }).strict();
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"),
25
40
  }).strict();
26
41
  const createOutput = z.object({
27
42
  task_id: z.string(),
28
43
  repo: z.string(),
29
- state: z.string(),
44
+ owner: z.string().optional(),
45
+ status: z.enum(["working", "needs_input", "completed", "failed", "cancelled"]),
46
+ terminal: z.boolean(),
30
47
  requested_model: z.string(),
31
- created_at: z.string().nullable(),
32
- html_url: z.string().nullable(),
33
- }).strict();
34
- const artifactSchema = z.discriminatedUnion("type", [
35
- z.object({ type: z.literal("pull"), id: z.number() }).strict(),
36
- z.object({ type: z.literal("branch"), head_ref: z.string(), base_ref: z.string() }).strict(),
37
- ]);
38
- const usageSchema = z.object({
39
- type: z.enum(["ai_credits", "premium_requests"]),
40
- amount: z.number().describe("Raw value from the API. ai_credits uses nano-units."),
41
- amount_human: z.number().describe("ai_credits divided by 1e9. premium_requests is unchanged."),
42
- }).strict();
43
- const pullRequestSchema = z.object({
44
- id: z.number().describe("Internal API ID, not the pull request number."),
45
- number: z.number().nullable(),
46
- html_url: z.string().nullable(),
47
- }).strict();
48
- const statusOutput = z.object({
49
- task_id: z.string(),
50
- repo: z.string(),
51
- state: z.string(),
52
- requested_model: z.string().nullable(),
53
- resolved_model: z.string().nullable().describe("sessions[].model exactly as returned by the API."),
54
- pull_request: pullRequestSchema.nullable(),
55
- branch: z.object({ head_ref: z.string(), base_ref: z.string() }).strict().nullable(),
56
- artifacts: z.array(artifactSchema),
57
- error: z.string().nullable(),
58
- usage: usageSchema.nullable(),
59
- created_at: z.string().nullable(),
60
- updated_at: z.string().nullable(),
61
- completed_at: z.string().nullable(),
62
- session_id: z.string().nullable().describe("ID of the task's latest session."),
48
+ delivery: z.enum(["not_configured", "pending", "delivered", "failed"]),
49
+ session_url: z.string().optional(),
50
+ pr_url: z.string().optional(),
51
+ follow_up: followUpSchema,
52
+ next_step: z.string(),
63
53
  }).strict();
54
+ const SERVER_INSTRUCTIONS = [
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.",
62
+ ].join(" ");
63
+ 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
64
  const getInput = z.object({
65
65
  task_id: z.string().describe("Task identifier."),
66
66
  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
+ }).strict();
69
+ const listInput = z.object({
70
+ 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(),
67
76
  }).strict();
68
77
  const experimentalNotice = "[Experimental] Undocumented internal GitHub endpoint that can change without notice.";
69
78
  const steerInput = z.object({
@@ -81,57 +90,50 @@ const abortInput = z.object({
81
90
  const abortOutput = z.object({
82
91
  task_id: z.string(),
83
92
  accepted: z.boolean(),
93
+ reason: z.string().optional(),
94
+ status: z.enum(["working", "needs_input", "completed", "failed", "cancelled"]).optional(),
95
+ terminal: z.boolean().optional(),
84
96
  }).strict();
85
- const eventsInput = z.object({
86
- task_id: z.string().describe("Task identifier."),
87
- page: z.number().int().positive().describe("Page, starting at 1."),
88
- per_page: z.number().int().positive().describe("Events per page."),
89
- }).strict();
90
- const eventOutput = z.object({
91
- id: z.string().nullable(),
92
- timestamp: z.string().nullable(),
93
- parentId: z.string().nullable(),
94
- type: z.string(),
95
- data: z.unknown(),
96
- }).strict();
97
- const eventsOutput = z.object({
98
- task_id: z.string(),
99
- page: z.number(),
100
- per_page: z.number(),
101
- total: z.number(),
102
- events: z.array(eventOutput),
103
- }).strict();
104
- export function buildServer(selection, deps) {
105
- const enabled = new Set(selectToolNames(selection));
97
+ export function buildServer(deps) {
98
+ const enabled = new Set(toolNames());
106
99
  const server = new McpServer({
107
100
  name: "copilot-agents-mcp",
108
101
  version: packageVersion(),
102
+ }, {
103
+ instructions: SERVER_INSTRUCTIONS,
109
104
  });
110
105
  if (enabled.has("create_agent_task")) {
111
106
  server.registerTool("create_agent_task", {
112
107
  title: "Launch Copilot task",
113
- 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.",
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}`,
114
109
  inputSchema: createInput,
115
110
  outputSchema: createOutput,
116
- annotations: annotations("POST", "Launch Copilot task"),
111
+ annotations: toolAnnotations("create_agent_task", "Launch Copilot task"),
117
112
  }, async (args) => run(() => createTask(args, deps)));
118
113
  }
119
114
  if (enabled.has("get_agent_task")) {
120
115
  server.registerTool("get_agent_task", {
121
116
  title: "Get task status",
122
- description: "Read a GitHub Copilot agent task once.",
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.",
123
118
  inputSchema: getInput,
124
- outputSchema: statusOutput,
125
- annotations: annotations("GET", "Get task status"),
119
+ annotations: toolAnnotations("get_agent_task", "Get task status"),
126
120
  }, async (args) => run(() => readTask(args, deps)));
127
121
  }
122
+ if (enabled.has("list_agent_tasks")) {
123
+ server.registerTool("list_agent_tasks", {
124
+ 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.",
126
+ inputSchema: listInput,
127
+ annotations: toolAnnotations("list_agent_tasks", "List tracked tasks"),
128
+ }, async (args) => run(() => listAgentTasks(args, deps)));
129
+ }
128
130
  if (enabled.has("steer_agent_task")) {
129
131
  server.registerTool("steer_agent_task", {
130
132
  title: "Steer task",
131
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.`,
132
134
  inputSchema: steerInput,
133
135
  outputSchema: steerOutput,
134
- annotations: annotations("POST", "Steer task"),
136
+ annotations: toolAnnotations("steer_agent_task", "Steer task"),
135
137
  }, async (args) => run(() => steerTask(args, deps)));
136
138
  }
137
139
  if (enabled.has("abort_agent_task")) {
@@ -140,35 +142,29 @@ export function buildServer(selection, deps) {
140
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.`,
141
143
  inputSchema: abortInput,
142
144
  outputSchema: abortOutput,
143
- annotations: annotations("POST", "Abort task"),
145
+ annotations: toolAnnotations("abort_agent_task", "Abort task"),
144
146
  }, async (args) => run(() => abortTask(args, deps)));
145
147
  }
146
- if (enabled.has("get_agent_task_events")) {
147
- server.registerTool("get_agent_task_events", {
148
- title: "Get task events",
149
- description: `${experimentalNotice} Read one page of task events (read-only).`,
150
- inputSchema: eventsInput,
151
- outputSchema: eventsOutput,
152
- annotations: annotations("GET", "Get task events"),
153
- }, async (args) => run(() => readEvents(args, deps)));
154
- }
155
148
  if (enabled.has("list_copilot_models")) {
156
149
  server.registerTool("list_copilot_models", {
157
150
  title: "List Copilot models",
158
151
  description: "Read /agents/swe/models and return the ID, name, vendor, preview flag, token prices or multiplier, and promotion when present.",
159
152
  inputSchema: z.object({}).strict(),
160
153
  outputSchema: sweModelsResultSchema,
161
- annotations: annotations("GET", "List Copilot models"),
162
- }, async () => run(() => deps.readModels()));
154
+ annotations: toolAnnotations("list_copilot_models", "List Copilot models"),
155
+ }, async () => run(async () => presentSweModelsResult(await deps.readModels())));
163
156
  }
164
157
  return server;
165
158
  }
166
- function annotations(method, title) {
159
+ function toolAnnotations(name, title) {
160
+ const readOnly = name === "get_agent_task" || name === "list_agent_tasks" || name === "list_copilot_models";
161
+ const destructive = name === "abort_agent_task";
162
+ const idempotent = readOnly || name === "abort_agent_task";
167
163
  return {
168
164
  title,
169
- readOnlyHint: method === "GET",
170
- destructiveHint: false,
171
- idempotentHint: method === "GET",
165
+ readOnlyHint: readOnly,
166
+ destructiveHint: destructive,
167
+ idempotentHint: idempotent,
172
168
  openWorldHint: true,
173
169
  };
174
170
  }
@@ -177,13 +173,19 @@ async function run(action) {
177
173
  return toolJson(await action());
178
174
  }
179
175
  catch (error) {
180
- return toolError(failureMessage(error));
176
+ if (error instanceof OwnerValidationError) {
177
+ return toolError(new CodedToolFailure("invalid_argument", error.message).toBody());
178
+ }
179
+ if (error instanceof CodedToolFailure)
180
+ return toolError(error.toBody());
181
+ return toolError(failureToError(error));
181
182
  }
182
183
  }
183
184
  async function createTask(args, deps) {
184
185
  const repo = required(args.repo, "repo");
185
186
  const prompt = required(args.prompt, "prompt");
186
187
  const model = required(args.model, "model");
188
+ const taskOwner = args.owner !== undefined ? validateOwner(args.owner) : undefined;
187
189
  const parsed = parseRepo(repo);
188
190
  const blocked = await withStateLock(deps.statePath, (state) => {
189
191
  const key = normalizeModel(model);
@@ -192,10 +194,12 @@ async function createTask(args, deps) {
192
194
  return modelUnavailableMessage(model, state.models.accepted);
193
195
  });
194
196
  if (blocked)
195
- throw new ToolFailure(blocked);
197
+ throw new CodedToolFailure("model_unavailable", blocked);
196
198
  const token = deps.readToken();
197
199
  if (!token)
198
- throw new ToolFailure(NO_SESSION_MESSAGE);
200
+ 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;
199
203
  const task = await deps.clientForToken(token).createTask({
200
204
  owner: parsed.owner,
201
205
  repo: parsed.repo,
@@ -206,57 +210,236 @@ async function createTask(args, deps) {
206
210
  ...(args.custom_agent !== undefined ? { custom_agent: args.custom_agent } : {}),
207
211
  ...(args.create_pull_request !== undefined ? { create_pull_request: args.create_pull_request } : {}),
208
212
  });
213
+ const mapped = mapRawState(task.state);
214
+ let watcher_started = false;
215
+ if (shouldSpawnWatcher(channels)) {
216
+ try {
217
+ deps.launchWatcher();
218
+ watcher_started = true;
219
+ }
220
+ catch (error) {
221
+ console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
222
+ }
223
+ }
224
+ const session = resolveTaskPageUrl(task);
225
+ const follow_up = followUpBlock(channels, watcher_started, Date.now());
209
226
  await withStateLock(deps.statePath, (state) => {
210
- state.tasks[task.id] = initialTask({
211
- id: task.id,
212
- repo,
213
- requestedModel: model,
214
- state: task.state,
215
- createdAt: task.created_at ?? null,
216
- updatedAt: task.updated_at ?? null,
217
- });
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
+ };
218
241
  });
219
- try {
220
- deps.launchWatcher();
221
- }
222
- catch (error) {
223
- console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
224
- }
225
- return {
226
- task_id: task.id,
242
+ const planMode = follow_up.mode;
243
+ const next_step = createFollowUpNextStep(planMode, taskOwner, task.id, channels.length > 0 && !watcher_started, follow_up.check_after);
244
+ const stored = await withStateLock(deps.statePath, (state) => state.tasks[task.id] ?? null);
245
+ const delivery = deliveryForTask(stored ?? initialTask({
246
+ id: task.id,
227
247
  repo,
248
+ requestedModel: model,
228
249
  state: task.state,
250
+ createdAt: task.created_at ?? null,
251
+ updatedAt: task.updated_at ?? null,
252
+ deliveryRecord,
253
+ htmlUrl: session ?? null,
254
+ }), channels);
255
+ const body = {
256
+ task_id: task.id,
257
+ repo,
258
+ status: mapped.status,
259
+ terminal: mapped.terminal,
229
260
  requested_model: model,
230
- created_at: task.created_at ?? null,
231
- html_url: task.html_url ?? null,
261
+ delivery,
262
+ follow_up,
263
+ next_step,
232
264
  };
265
+ if (taskOwner)
266
+ body.owner = taskOwner;
267
+ if (session)
268
+ body.session_url = session;
269
+ const createdPr = stored ? prUrl(stored) : undefined;
270
+ if (createdPr)
271
+ body.pr_url = createdPr;
272
+ return body;
233
273
  }
234
274
  async function readTask(args, deps) {
235
275
  const taskId = required(args.task_id, "task_id");
276
+ const verbose = args.verbose === true;
236
277
  const known = await withStateLock(deps.statePath, (state) => state.tasks[taskId] ?? null);
237
278
  const repo = args.repo?.trim() || known?.repo || "";
238
279
  const parsed = repo ? parseRepo(repo) : null;
239
280
  const token = deps.readToken();
240
- if (!token)
241
- throw new ToolFailure(NO_SESSION_MESSAGE);
281
+ const channels = activeNotificationChannels(process.platform, process.env);
282
+ const freshness = freshnessMs();
283
+ const now = Date.now();
284
+ if (!token) {
285
+ if (known && mapRawState(known.state).terminal) {
286
+ const checkAfter = resolveNextCheckAfter(known, now);
287
+ return {
288
+ ...compactGetTask(known, channels, { verbose, checkAfter, cached: true }),
289
+ stale: true,
290
+ warnings: [NO_SESSION_STALE_WARNING],
291
+ };
292
+ }
293
+ throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
294
+ }
242
295
  const client = deps.clientForToken(token);
243
- const remote = await client.getTask({
244
- taskId,
245
- ...(parsed ? { owner: parsed.owner, repo: parsed.repo } : {}),
246
- });
247
- const tracked = await withStateLock(deps.statePath, (state) => {
248
- return observe(state, remote, {
249
- repo: repo || state.tasks[taskId]?.repo || "",
250
- requestedModel: state.tasks[taskId]?.requested_model ?? known?.requested_model ?? null,
251
- });
252
- });
253
- await fillPullRequest(tracked, (input) => client.findPullRequest(input), (line) => appendWatcherLog(line), headRefOf(remote, tracked));
296
+ let tracked;
297
+ let cached = false;
298
+ if (known && !needsFetch(known, freshness)) {
299
+ tracked = known;
300
+ cached = true;
301
+ if (mapRawState(tracked.state).terminal && tracked.pull_request && tracked.pull_request.number === null && parsed) {
302
+ let headRef = tracked.branch?.head_ref;
303
+ if (!headRef) {
304
+ const remote = await client.getTask({
305
+ taskId,
306
+ owner: parsed.owner,
307
+ repo: parsed.repo,
308
+ });
309
+ headRef = headRefOf(remote, tracked);
310
+ }
311
+ await fillPullRequest(tracked, (input) => client.findPullRequest(input), (line) => appendWatcherLog(line), headRef);
312
+ await withStateLock(deps.statePath, (state) => {
313
+ const saved = state.tasks[tracked.task_id];
314
+ if (saved) {
315
+ saved.pull_request = tracked.pull_request;
316
+ saved.pr_title = tracked.pr_title ?? null;
317
+ }
318
+ });
319
+ }
320
+ }
321
+ else {
322
+ try {
323
+ const remote = await client.getTask({
324
+ taskId,
325
+ ...(parsed ? { owner: parsed.owner, repo: parsed.repo } : {}),
326
+ });
327
+ tracked = await withStateLock(deps.statePath, (state) => {
328
+ const row = observe(state, remote, {
329
+ repo: repo || state.tasks[taskId]?.repo || "",
330
+ requestedModel: state.tasks[taskId]?.requested_model ?? known?.requested_model ?? null,
331
+ });
332
+ row.last_fetched_at = new Date().toISOString();
333
+ return row;
334
+ });
335
+ if (mapRawState(tracked.state).terminal) {
336
+ await fillPullRequest(tracked, (input) => client.findPullRequest(input), (line) => appendWatcherLog(line), headRefOf(remote, tracked));
337
+ await withStateLock(deps.statePath, (state) => {
338
+ const saved = state.tasks[tracked.task_id];
339
+ if (saved) {
340
+ saved.pull_request = tracked.pull_request;
341
+ saved.pr_title = tracked.pr_title ?? null;
342
+ }
343
+ });
344
+ }
345
+ }
346
+ catch (error) {
347
+ if (known) {
348
+ tracked = known;
349
+ const checkAfter = resolveNextCheckAfter(tracked, now);
350
+ return {
351
+ ...compactGetTask(tracked, channels, { verbose, checkAfter, cached: true }),
352
+ stale: true,
353
+ warnings: [`could not refresh 1 task: ${failureMessage(error)}`],
354
+ };
355
+ }
356
+ const message = failureMessage(error);
357
+ if (/HTTP 404|not found/i.test(message)) {
358
+ throw new CodedToolFailure("not_found", `Task ${taskId} was not found.`);
359
+ }
360
+ throw error;
361
+ }
362
+ }
363
+ const checkAfter = resolveNextCheckAfter(tracked, now);
364
+ return compactGetTask(tracked, channels, { verbose, checkAfter, cached });
365
+ }
366
+ async function listAgentTasks(args, deps) {
367
+ const token = deps.readToken();
368
+ const freshness = freshnessMs();
369
+ const now = Date.now();
370
+ const input = {
371
+ ...(args.owner !== undefined ? { owner: args.owner } : {}),
372
+ ...(args.task_ids ? { task_ids: args.task_ids } : {}),
373
+ ...(args.status ? { status: args.status } : {}),
374
+ ...(args.repo ? { repo: args.repo } : {}),
375
+ ...(args.limit !== undefined ? { limit: args.limit } : {}),
376
+ verbose: args.verbose,
377
+ };
378
+ let registryEmpty = false;
379
+ let matchedEmpty = false;
380
+ let warnings = [];
381
+ let matched = [];
382
+ let page = [];
254
383
  await withStateLock(deps.statePath, (state) => {
255
- const saved = state.tasks[tracked.task_id];
256
- if (saved)
257
- saved.pull_request = tracked.pull_request;
384
+ pruneRegistry(state, now);
385
+ registryEmpty = Object.keys(state.tasks).length === 0;
386
+ const result = filterTasks(state, input, now);
387
+ matched = result.matched;
388
+ page = result.tasks;
389
+ warnings = result.warnings;
390
+ matchedEmpty = !registryEmpty && result.total_matched === 0;
258
391
  });
259
- return toNotice(tracked);
392
+ const staleOnly = !token;
393
+ if (staleOnly) {
394
+ const hasPending = matched.some((task) => !mapRawState(task.state).terminal);
395
+ if (hasPending)
396
+ throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
397
+ const counts = listCounts(matched);
398
+ const checkAfter = aggregateNextCheckAfter(matched, now);
399
+ const rows = page.map((task) => toListRow(task, { checkAfter: resolveNextCheckAfter(task, now) }));
400
+ const staleWarnings = [...warnings, NO_SESSION_STALE_WARNING];
401
+ return {
402
+ tasks: rows,
403
+ pending_count: counts.pending_count,
404
+ terminal_count: counts.terminal_count,
405
+ all_terminal: counts.all_terminal,
406
+ next_step: listNextStep(counts, matchedEmpty, registryEmpty, checkAfter),
407
+ warnings: staleWarnings,
408
+ stale: true,
409
+ };
410
+ }
411
+ const client = deps.clientForToken(token);
412
+ const staleIds = new Set();
413
+ const toRefresh = matched.filter((task) => needsFetch(task, freshness, now)).map((task) => task.task_id);
414
+ if (toRefresh.length > 0) {
415
+ const { failures } = await refreshTasks(deps.statePath, client, toRefresh, freshness, (line) => appendWatcherLog(line));
416
+ for (const [id, reason] of failures) {
417
+ staleIds.add(id);
418
+ warnings.push(`could not refresh 1 task: ${reason}`);
419
+ }
420
+ }
421
+ const updated = await withStateLock(deps.statePath, (state) => {
422
+ const result = filterTasks(state, input, now);
423
+ return { page: result.tasks, matched: result.matched };
424
+ });
425
+ const counts = listCounts(updated.matched);
426
+ const checkAfter = aggregateNextCheckAfter(updated.matched, now);
427
+ const rows = updated.page.map((task) => toListRow(task, {
428
+ stale: staleIds.has(task.task_id) ? true : undefined,
429
+ checkAfter: resolveNextCheckAfter(task, now),
430
+ }));
431
+ const body = {
432
+ tasks: rows,
433
+ pending_count: counts.pending_count,
434
+ terminal_count: counts.terminal_count,
435
+ all_terminal: counts.all_terminal,
436
+ next_step: listNextStep(counts, matchedEmpty, registryEmpty, checkAfter),
437
+ };
438
+ if (!counts.all_terminal && counts.pending_count > 0)
439
+ body.next_check_after = checkAfter;
440
+ if (warnings.length > 0)
441
+ body.warnings = warnings;
442
+ return body;
260
443
  }
261
444
  async function steerTask(args, deps) {
262
445
  const taskId = required(args.task_id, "task_id");
@@ -299,43 +482,81 @@ async function steerTask(args, deps) {
299
482
  armSteer(task, sessionCount, steeredAt);
300
483
  state.tasks[taskId] = task;
301
484
  });
302
- try {
303
- deps.launchWatcher();
304
- }
305
- catch (error) {
306
- console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
485
+ if (shouldSpawnWatcher(activeNotificationChannels(process.platform, process.env))) {
486
+ try {
487
+ deps.launchWatcher();
488
+ }
489
+ catch (error) {
490
+ console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
491
+ }
307
492
  }
308
493
  return { task_id: taskId, accepted: true, session_count: sessionCount };
309
494
  }
310
- async function abortTask(args, deps) {
311
- const taskId = required(args.task_id, "task_id");
312
- const token = deps.readToken();
313
- if (!token)
314
- throw new ToolFailure(NO_SESSION_MESSAGE);
315
- await deps.clientForToken(token).abortTask(taskId);
316
- return { task_id: taskId, accepted: true };
495
+ function isAbortNoSessionError(message) {
496
+ return /cannot abort/i.test(message) && /no active session/i.test(message);
317
497
  }
318
- async function readEvents(args, deps) {
498
+ async function abortTask(args, deps) {
319
499
  const taskId = required(args.task_id, "task_id");
320
500
  const token = deps.readToken();
321
501
  if (!token)
322
- throw new ToolFailure(NO_SESSION_MESSAGE);
323
- const page = await deps.clientForToken(token).getTaskEvents(taskId, args.page, args.per_page);
502
+ throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
503
+ const known = await withStateLock(deps.statePath, (state) => state.tasks[taskId] ?? null);
504
+ if (known && isFinalState(known.state)) {
505
+ const mapped = mapRawState(known.state);
506
+ return {
507
+ task_id: taskId,
508
+ accepted: false,
509
+ reason: "already finished",
510
+ status: mapped.status,
511
+ terminal: true,
512
+ };
513
+ }
514
+ const client = deps.clientForToken(token);
515
+ try {
516
+ await client.abortTask(taskId);
517
+ }
518
+ catch (error) {
519
+ const message = failureMessage(error);
520
+ if (isAbortNoSessionError(message) && known?.repo) {
521
+ const parsed = parseRepo(known.repo);
522
+ const remote = await client.getTask({
523
+ taskId,
524
+ owner: parsed.owner,
525
+ repo: parsed.repo,
526
+ });
527
+ const tracked = await withStateLock(deps.statePath, (state) => {
528
+ const row = observe(state, remote, {
529
+ repo: known.repo,
530
+ requestedModel: state.tasks[taskId]?.requested_model ?? known.requested_model ?? null,
531
+ });
532
+ row.last_fetched_at = new Date().toISOString();
533
+ return row;
534
+ });
535
+ if (isFinalState(tracked.state)) {
536
+ const mapped = mapRawState(tracked.state);
537
+ return {
538
+ task_id: taskId,
539
+ accepted: false,
540
+ reason: "already finished",
541
+ status: mapped.status,
542
+ terminal: true,
543
+ };
544
+ }
545
+ }
546
+ throw error;
547
+ }
548
+ await withStateLock(deps.statePath, (state) => {
549
+ const task = state.tasks[taskId];
550
+ if (task)
551
+ task.last_fetched_at = null;
552
+ });
553
+ const current = await withStateLock(deps.statePath, (state) => state.tasks[taskId] ?? null);
554
+ const mapped = mapRawState(current?.state ?? "in_progress");
324
555
  return {
325
556
  task_id: taskId,
326
- page: args.page,
327
- per_page: args.per_page,
328
- total: page.total,
329
- events: page.events.map(presentEvent),
330
- };
331
- }
332
- function presentEvent(event) {
333
- return {
334
- id: event.id ?? null,
335
- timestamp: event.timestamp ?? null,
336
- parentId: event.parentId ?? null,
337
- type: event.type,
338
- data: event.data ?? null,
557
+ accepted: true,
558
+ status: mapped.status,
559
+ terminal: mapped.terminal,
339
560
  };
340
561
  }
341
562
  function pullArtifact(task) {
@@ -374,13 +595,13 @@ function repoFromTaskUrl(url) {
374
595
  }
375
596
  function required(value, name) {
376
597
  if (!value.trim())
377
- throw new ToolFailure(`missing required parameter: ${name}`);
598
+ throw new CodedToolFailure("invalid_argument", `missing required parameter: ${name}`);
378
599
  return value.trim();
379
600
  }
380
601
  export function parseRepo(repo) {
381
602
  const match = /^([^/\s]+)\/([^/\s]+)$/.exec(repo);
382
603
  if (!match?.[1] || !match[2])
383
- throw new ToolFailure("repo must use the owner/name form.");
604
+ throw new CodedToolFailure("invalid_argument", "repo must use the owner/name form.");
384
605
  return { owner: match[1], repo: match[2] };
385
606
  }
386
607
  export function defaultLaunchWatcher() {