copilot-agents-mcp 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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, notificationChannelsForTask } 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, readState, 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,61 +20,65 @@ 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
- repo: z.string().describe("Repository in owner/name form."),
19
- prompt: z.string().describe("Instructions for the agent."),
20
- model: z.string().describe("Model sent unchanged to the API without a closed allowlist."),
21
- base_ref: z.string().optional().describe("Base branch for a new branch or pull request."),
22
- head_ref: z.string().optional().describe("Existing branch. With base_ref, the agent commits to this branch."),
23
- custom_agent: z.string().optional().describe("Custom agent name without the extension."),
24
- 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
+ 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"]).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."),
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
+ "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.",
63
+ ].join(" ");
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."),
68
+ verbose: z.boolean().optional().describe("Include raw state, models, usage, artifacts, and error (up to 2048 characters). Default false."),
69
+ }).strict();
70
+ const listInput = z.object({
71
+ owner: z.string().optional().describe(OWNER_FIELD),
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."),
67
77
  }).strict();
68
78
  const experimentalNotice = "[Experimental] Undocumented internal GitHub endpoint that can change without notice.";
69
79
  const steerInput = z.object({
70
- task_id: z.string().describe("Task identifier."),
71
- 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."),
72
82
  }).strict();
73
83
  const steerOutput = z.object({
74
84
  task_id: z.string(),
@@ -76,99 +86,145 @@ const steerOutput = z.object({
76
86
  session_count: z.number(),
77
87
  }).strict();
78
88
  const abortInput = z.object({
79
- task_id: z.string().describe("Task identifier."),
89
+ task_id: z.string().describe("Required non-blank task identifier returned by create_agent_task."),
80
90
  }).strict();
81
91
  const abortOutput = z.object({
82
92
  task_id: z.string(),
83
93
  accepted: z.boolean(),
94
+ reason: z.string().optional(),
95
+ status: z.enum(["working", "needs_input", "completed", "failed", "cancelled"]).optional(),
96
+ terminal: z.boolean().optional(),
84
97
  }).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
+ const taskRowFields = {
98
99
  task_id: z.string(),
99
- page: z.number(),
100
- per_page: z.number(),
101
- total: z.number(),
102
- events: z.array(eventOutput),
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(),
103
144
  }).strict();
104
- export function buildServer(selection, deps) {
105
- const enabled = new Set(selectToolNames(selection));
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();
155
+ export function buildServer(deps) {
156
+ const enabled = new Set(toolNames());
106
157
  const server = new McpServer({
107
158
  name: "copilot-agents-mcp",
108
159
  version: packageVersion(),
160
+ }, {
161
+ instructions: SERVER_INSTRUCTIONS,
109
162
  });
110
163
  if (enabled.has("create_agent_task")) {
111
164
  server.registerTool("create_agent_task", {
112
165
  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.",
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}`,
114
167
  inputSchema: createInput,
115
168
  outputSchema: createOutput,
116
- annotations: annotations("POST", "Launch Copilot task"),
169
+ annotations: toolAnnotations("create_agent_task", "Launch Copilot task"),
117
170
  }, async (args) => run(() => createTask(args, deps)));
118
171
  }
119
172
  if (enabled.has("get_agent_task")) {
120
173
  server.registerTool("get_agent_task", {
121
174
  title: "Get task status",
122
- description: "Read a GitHub Copilot agent task once.",
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.",
123
176
  inputSchema: getInput,
124
- outputSchema: statusOutput,
125
- annotations: annotations("GET", "Get task status"),
177
+ outputSchema: getOutput,
178
+ annotations: toolAnnotations("get_agent_task", "Get task status"),
126
179
  }, async (args) => run(() => readTask(args, deps)));
127
180
  }
181
+ if (enabled.has("list_agent_tasks")) {
182
+ server.registerTool("list_agent_tasks", {
183
+ title: "List tracked tasks",
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.",
185
+ inputSchema: listInput,
186
+ outputSchema: listOutput,
187
+ annotations: toolAnnotations("list_agent_tasks", "List tracked tasks"),
188
+ }, async (args) => run(() => listAgentTasks(args, deps)));
189
+ }
128
190
  if (enabled.has("steer_agent_task")) {
129
191
  server.registerTool("steer_agent_task", {
130
192
  title: "Steer task",
131
- 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.`,
132
194
  inputSchema: steerInput,
133
195
  outputSchema: steerOutput,
134
- annotations: annotations("POST", "Steer task"),
196
+ annotations: toolAnnotations("steer_agent_task", "Steer task"),
135
197
  }, async (args) => run(() => steerTask(args, deps)));
136
198
  }
137
199
  if (enabled.has("abort_agent_task")) {
138
200
  server.registerTool("abort_agent_task", {
139
201
  title: "Abort task",
140
- 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.`,
141
203
  inputSchema: abortInput,
142
204
  outputSchema: abortOutput,
143
- annotations: annotations("POST", "Abort task"),
205
+ annotations: toolAnnotations("abort_agent_task", "Abort task"),
144
206
  }, async (args) => run(() => abortTask(args, deps)));
145
207
  }
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
208
  if (enabled.has("list_copilot_models")) {
156
209
  server.registerTool("list_copilot_models", {
157
210
  title: "List Copilot models",
158
- 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.",
159
212
  inputSchema: z.object({}).strict(),
160
213
  outputSchema: sweModelsResultSchema,
161
- annotations: annotations("GET", "List Copilot models"),
162
- }, async () => run(() => deps.readModels()));
214
+ annotations: toolAnnotations("list_copilot_models", "List Copilot models"),
215
+ }, async () => run(async () => presentSweModelsResult(await deps.readModels())));
163
216
  }
164
217
  return server;
165
218
  }
166
- function annotations(method, title) {
219
+ function toolAnnotations(name, title) {
220
+ const readOnly = name === "get_agent_task" || name === "list_agent_tasks" || name === "list_copilot_models";
221
+ const destructive = name === "abort_agent_task";
222
+ const idempotent = readOnly || name === "abort_agent_task";
167
223
  return {
168
224
  title,
169
- readOnlyHint: method === "GET",
170
- destructiveHint: false,
171
- idempotentHint: method === "GET",
225
+ readOnlyHint: readOnly,
226
+ destructiveHint: destructive,
227
+ idempotentHint: idempotent,
172
228
  openWorldHint: true,
173
229
  };
174
230
  }
@@ -177,13 +233,19 @@ async function run(action) {
177
233
  return toolJson(await action());
178
234
  }
179
235
  catch (error) {
180
- return toolError(failureMessage(error));
236
+ if (error instanceof OwnerValidationError) {
237
+ return toolError(new CodedToolFailure("invalid_argument", error.message).toBody());
238
+ }
239
+ if (error instanceof CodedToolFailure)
240
+ return toolError(error.toBody());
241
+ return toolError(failureToError(error));
181
242
  }
182
243
  }
183
244
  async function createTask(args, deps) {
184
245
  const repo = required(args.repo, "repo");
185
246
  const prompt = required(args.prompt, "prompt");
186
247
  const model = required(args.model, "model");
248
+ const taskOwner = args.owner !== undefined ? validateOwner(args.owner) : undefined;
187
249
  const parsed = parseRepo(repo);
188
250
  const blocked = await withStateLock(deps.statePath, (state) => {
189
251
  const key = normalizeModel(model);
@@ -192,10 +254,10 @@ async function createTask(args, deps) {
192
254
  return modelUnavailableMessage(model, state.models.accepted);
193
255
  });
194
256
  if (blocked)
195
- throw new ToolFailure(blocked);
257
+ throw new CodedToolFailure("model_unavailable", blocked);
196
258
  const token = deps.readToken();
197
259
  if (!token)
198
- throw new ToolFailure(NO_SESSION_MESSAGE);
260
+ throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
199
261
  const task = await deps.clientForToken(token).createTask({
200
262
  owner: parsed.owner,
201
263
  repo: parsed.repo,
@@ -206,57 +268,237 @@ async function createTask(args, deps) {
206
268
  ...(args.custom_agent !== undefined ? { custom_agent: args.custom_agent } : {}),
207
269
  ...(args.create_pull_request !== undefined ? { create_pull_request: args.create_pull_request } : {}),
208
270
  });
209
- 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
- });
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,
218
280
  });
219
- try {
220
- deps.launchWatcher();
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
+ });
292
+ const mapped = mapRawState(task.state);
293
+ let watcher_started = false;
294
+ if (shouldSpawnWatcher(channels)) {
295
+ try {
296
+ deps.launchWatcher();
297
+ watcher_started = true;
298
+ }
299
+ catch (error) {
300
+ console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
301
+ }
221
302
  }
222
- catch (error) {
223
- console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
303
+ const session = resolveTaskPageUrl(task);
304
+ const follow_up = followUpBlock(channels, watcher_started, followUpNow);
305
+ const planMode = follow_up.mode;
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`.";
224
309
  }
225
- return {
310
+ const stored = await withStateLock(deps.statePath, (state) => state.tasks[task.id] ?? null);
311
+ const delivery = deliveryForTask(stored ?? localTask, channels);
312
+ const body = {
226
313
  task_id: task.id,
227
314
  repo,
228
- state: task.state,
315
+ status: mapped.status,
316
+ terminal: mapped.terminal,
229
317
  requested_model: model,
230
- created_at: task.created_at ?? null,
231
- html_url: task.html_url ?? null,
318
+ delivery,
319
+ follow_up,
320
+ next_step,
232
321
  };
322
+ if (taskOwner)
323
+ body.owner = taskOwner;
324
+ if (session)
325
+ body.session_url = session;
326
+ const createdPr = stored ? prUrl(stored) : undefined;
327
+ if (createdPr)
328
+ body.pr_url = createdPr;
329
+ return body;
233
330
  }
234
331
  async function readTask(args, deps) {
235
332
  const taskId = required(args.task_id, "task_id");
333
+ const verbose = args.verbose === true;
236
334
  const known = await withStateLock(deps.statePath, (state) => state.tasks[taskId] ?? null);
237
335
  const repo = args.repo?.trim() || known?.repo || "";
238
336
  const parsed = repo ? parseRepo(repo) : null;
239
337
  const token = deps.readToken();
240
- if (!token)
241
- throw new ToolFailure(NO_SESSION_MESSAGE);
338
+ const channels = known
339
+ ? notificationChannelsForTask(known, await readState(deps.statePath))
340
+ : activeNotificationChannels(process.platform, process.env);
341
+ const freshness = freshnessMs();
342
+ const now = Date.now();
343
+ if (!token) {
344
+ if (known && mapRawState(known.state).terminal) {
345
+ const checkAfter = resolveNextCheckAfter(known, now);
346
+ return {
347
+ ...compactGetTask(known, channels, { verbose, checkAfter, cached: true }),
348
+ stale: true,
349
+ warnings: [NO_SESSION_STALE_WARNING],
350
+ };
351
+ }
352
+ throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
353
+ }
242
354
  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));
355
+ let tracked;
356
+ let cached = false;
357
+ if (known && !needsFetch(known, freshness)) {
358
+ tracked = known;
359
+ cached = true;
360
+ if (mapRawState(tracked.state).terminal && tracked.pull_request && tracked.pull_request.number === null && parsed) {
361
+ let headRef = tracked.branch?.head_ref;
362
+ if (!headRef) {
363
+ const remote = await client.getTask({
364
+ taskId,
365
+ owner: parsed.owner,
366
+ repo: parsed.repo,
367
+ });
368
+ headRef = headRefOf(remote, tracked);
369
+ }
370
+ await fillPullRequest(tracked, (input) => client.findPullRequest(input), (line) => appendWatcherLog(line), headRef);
371
+ await withStateLock(deps.statePath, (state) => {
372
+ const saved = state.tasks[tracked.task_id];
373
+ if (saved) {
374
+ saved.pull_request = tracked.pull_request;
375
+ saved.pr_title = tracked.pr_title ?? null;
376
+ }
377
+ });
378
+ }
379
+ }
380
+ else {
381
+ try {
382
+ const remote = await client.getTask({
383
+ taskId,
384
+ ...(parsed ? { owner: parsed.owner, repo: parsed.repo } : {}),
385
+ });
386
+ tracked = await withStateLock(deps.statePath, (state) => {
387
+ const row = observe(state, remote, {
388
+ repo: repo || state.tasks[taskId]?.repo || "",
389
+ requestedModel: state.tasks[taskId]?.requested_model ?? known?.requested_model ?? null,
390
+ });
391
+ row.last_fetched_at = new Date().toISOString();
392
+ return row;
393
+ });
394
+ if (mapRawState(tracked.state).terminal) {
395
+ await fillPullRequest(tracked, (input) => client.findPullRequest(input), (line) => appendWatcherLog(line), headRefOf(remote, tracked));
396
+ await withStateLock(deps.statePath, (state) => {
397
+ const saved = state.tasks[tracked.task_id];
398
+ if (saved) {
399
+ saved.pull_request = tracked.pull_request;
400
+ saved.pr_title = tracked.pr_title ?? null;
401
+ }
402
+ });
403
+ }
404
+ }
405
+ catch (error) {
406
+ if (known) {
407
+ tracked = known;
408
+ const checkAfter = resolveNextCheckAfter(tracked, now);
409
+ return {
410
+ ...compactGetTask(tracked, channels, { verbose, checkAfter, cached: true }),
411
+ stale: true,
412
+ warnings: [`could not refresh 1 task: ${failureMessage(error)}`],
413
+ };
414
+ }
415
+ const message = failureMessage(error);
416
+ if (/HTTP 404|not found/i.test(message)) {
417
+ throw new CodedToolFailure("not_found", `Task ${taskId} was not found.`);
418
+ }
419
+ throw error;
420
+ }
421
+ }
422
+ const checkAfter = resolveNextCheckAfter(tracked, now);
423
+ return compactGetTask(tracked, channels, { verbose, checkAfter, cached });
424
+ }
425
+ async function listAgentTasks(args, deps) {
426
+ const token = deps.readToken();
427
+ const freshness = freshnessMs();
428
+ const now = Date.now();
429
+ const input = {
430
+ ...(args.owner !== undefined ? { owner: args.owner } : {}),
431
+ ...(args.task_ids ? { task_ids: args.task_ids } : {}),
432
+ ...(args.status ? { status: args.status } : {}),
433
+ ...(args.repo ? { repo: args.repo } : {}),
434
+ ...(args.limit !== undefined ? { limit: args.limit } : {}),
435
+ verbose: args.verbose,
436
+ };
437
+ let registryEmpty = false;
438
+ let matchedEmpty = false;
439
+ let warnings = [];
440
+ let matched = [];
441
+ let page = [];
254
442
  await withStateLock(deps.statePath, (state) => {
255
- const saved = state.tasks[tracked.task_id];
256
- if (saved)
257
- saved.pull_request = tracked.pull_request;
443
+ pruneRegistry(state, now);
444
+ registryEmpty = Object.keys(state.tasks).length === 0;
445
+ const result = filterTasks(state, input, now);
446
+ matched = result.matched;
447
+ page = result.tasks;
448
+ warnings = result.warnings;
449
+ matchedEmpty = !registryEmpty && result.total_matched === 0;
450
+ });
451
+ const staleOnly = !token;
452
+ if (staleOnly) {
453
+ const hasPending = matched.some((task) => !mapRawState(task.state).terminal);
454
+ if (hasPending)
455
+ throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
456
+ const counts = listCounts(matched);
457
+ const checkAfter = aggregateNextCheckAfter(matched, now);
458
+ const rows = page.map((task) => toListRow(task, { checkAfter: resolveNextCheckAfter(task, now) }));
459
+ const staleWarnings = [...warnings, NO_SESSION_STALE_WARNING];
460
+ return {
461
+ tasks: rows,
462
+ pending_count: counts.pending_count,
463
+ terminal_count: counts.terminal_count,
464
+ all_terminal: counts.all_terminal,
465
+ next_step: listNextStep(counts, matchedEmpty, registryEmpty, checkAfter),
466
+ warnings: staleWarnings,
467
+ stale: true,
468
+ };
469
+ }
470
+ const client = deps.clientForToken(token);
471
+ const staleIds = new Set();
472
+ const toRefresh = matched.filter((task) => needsFetch(task, freshness, now)).map((task) => task.task_id);
473
+ if (toRefresh.length > 0) {
474
+ const { failures } = await refreshTasks(deps.statePath, client, toRefresh, freshness, (line) => appendWatcherLog(line));
475
+ for (const [id, reason] of failures) {
476
+ staleIds.add(id);
477
+ warnings.push(`could not refresh 1 task: ${reason}`);
478
+ }
479
+ }
480
+ const updated = await withStateLock(deps.statePath, (state) => {
481
+ const result = filterTasks(state, input, now);
482
+ return { page: result.tasks, matched: result.matched };
258
483
  });
259
- return toNotice(tracked);
484
+ const counts = listCounts(updated.matched);
485
+ const checkAfter = aggregateNextCheckAfter(updated.matched, now);
486
+ const rows = updated.page.map((task) => toListRow(task, {
487
+ stale: staleIds.has(task.task_id) ? true : undefined,
488
+ checkAfter: resolveNextCheckAfter(task, now),
489
+ }));
490
+ const body = {
491
+ tasks: rows,
492
+ pending_count: counts.pending_count,
493
+ terminal_count: counts.terminal_count,
494
+ all_terminal: counts.all_terminal,
495
+ next_step: listNextStep(counts, matchedEmpty, registryEmpty, checkAfter),
496
+ };
497
+ if (!counts.all_terminal && counts.pending_count > 0)
498
+ body.next_check_after = checkAfter;
499
+ if (warnings.length > 0)
500
+ body.warnings = warnings;
501
+ return body;
260
502
  }
261
503
  async function steerTask(args, deps) {
262
504
  const taskId = required(args.task_id, "task_id");
@@ -299,43 +541,83 @@ async function steerTask(args, deps) {
299
541
  armSteer(task, sessionCount, steeredAt);
300
542
  state.tasks[taskId] = task;
301
543
  });
302
- try {
303
- deps.launchWatcher();
304
- }
305
- catch (error) {
306
- console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
544
+ const savedState = await readState(deps.statePath);
545
+ const steered = savedState.tasks[taskId];
546
+ if (steered && shouldSpawnWatcher(notificationChannelsForTask(steered, savedState))) {
547
+ try {
548
+ deps.launchWatcher();
549
+ }
550
+ catch (error) {
551
+ console.error(`Could not start the watcher: ${error instanceof Error ? error.message : "error"}.`);
552
+ }
307
553
  }
308
554
  return { task_id: taskId, accepted: true, session_count: sessionCount };
309
555
  }
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 };
556
+ function isAbortNoSessionError(message) {
557
+ return /cannot abort/i.test(message) && /no active session/i.test(message);
317
558
  }
318
- async function readEvents(args, deps) {
559
+ async function abortTask(args, deps) {
319
560
  const taskId = required(args.task_id, "task_id");
320
561
  const token = deps.readToken();
321
562
  if (!token)
322
- throw new ToolFailure(NO_SESSION_MESSAGE);
323
- const page = await deps.clientForToken(token).getTaskEvents(taskId, args.page, args.per_page);
563
+ throw new CodedToolFailure("not_authenticated", NO_SESSION_MESSAGE);
564
+ const known = await withStateLock(deps.statePath, (state) => state.tasks[taskId] ?? null);
565
+ if (known && isFinalState(known.state)) {
566
+ const mapped = mapRawState(known.state);
567
+ return {
568
+ task_id: taskId,
569
+ accepted: false,
570
+ reason: "already finished",
571
+ status: mapped.status,
572
+ terminal: true,
573
+ };
574
+ }
575
+ const client = deps.clientForToken(token);
576
+ try {
577
+ await client.abortTask(taskId);
578
+ }
579
+ catch (error) {
580
+ const message = failureMessage(error);
581
+ if (isAbortNoSessionError(message) && known?.repo) {
582
+ const parsed = parseRepo(known.repo);
583
+ const remote = await client.getTask({
584
+ taskId,
585
+ owner: parsed.owner,
586
+ repo: parsed.repo,
587
+ });
588
+ const tracked = await withStateLock(deps.statePath, (state) => {
589
+ const row = observe(state, remote, {
590
+ repo: known.repo,
591
+ requestedModel: state.tasks[taskId]?.requested_model ?? known.requested_model ?? null,
592
+ });
593
+ row.last_fetched_at = new Date().toISOString();
594
+ return row;
595
+ });
596
+ if (isFinalState(tracked.state)) {
597
+ const mapped = mapRawState(tracked.state);
598
+ return {
599
+ task_id: taskId,
600
+ accepted: false,
601
+ reason: "already finished",
602
+ status: mapped.status,
603
+ terminal: true,
604
+ };
605
+ }
606
+ }
607
+ throw error;
608
+ }
609
+ await withStateLock(deps.statePath, (state) => {
610
+ const task = state.tasks[taskId];
611
+ if (task)
612
+ task.last_fetched_at = null;
613
+ });
614
+ const current = await withStateLock(deps.statePath, (state) => state.tasks[taskId] ?? null);
615
+ const mapped = mapRawState(current?.state ?? "in_progress");
324
616
  return {
325
617
  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,
618
+ accepted: true,
619
+ status: mapped.status,
620
+ terminal: mapped.terminal,
339
621
  };
340
622
  }
341
623
  function pullArtifact(task) {
@@ -374,13 +656,13 @@ function repoFromTaskUrl(url) {
374
656
  }
375
657
  function required(value, name) {
376
658
  if (!value.trim())
377
- throw new ToolFailure(`missing required parameter: ${name}`);
659
+ throw new CodedToolFailure("invalid_argument", `missing required parameter: ${name}`);
378
660
  return value.trim();
379
661
  }
380
662
  export function parseRepo(repo) {
381
663
  const match = /^([^/\s]+)\/([^/\s]+)$/.exec(repo);
382
664
  if (!match?.[1] || !match[2])
383
- throw new ToolFailure("repo must use the owner/name form.");
665
+ throw new CodedToolFailure("invalid_argument", "repo must use the owner/name form.");
384
666
  return { owner: match[1], repo: match[2] };
385
667
  }
386
668
  export function defaultLaunchWatcher() {