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/notify.js CHANGED
@@ -1,84 +1,35 @@
1
- import { spawn } from "node:child_process";
2
- import { appendFile, mkdir } from "node:fs/promises";
1
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
3
2
  import { dirname } from "node:path";
3
+ import { readState, toDeliveryNotice } from "./state.js";
4
+ import { ownerWebhook } from "./webhooks.js";
5
+ import { postOwnerNotice, webhookPost } from "./webhook-http.js";
4
6
  export const NOTIFY_URL_ENV = "COPILOT_AGENTS_NOTIFY_URL";
5
7
  export const NOTIFY_AUTHORIZATION_ENV = "COPILOT_AGENTS_NOTIFY_AUTHORIZATION";
6
- const ENV_KEYS = ["PATH", "SystemRoot", "WINDIR", "PATHEXT", "DISPLAY", "DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR", "HOME"];
7
- const WINDOWS_SCRIPT = `
8
- $ErrorActionPreference = 'Stop'
9
- $title = $env:COPILOT_AGENTS_NOTIFY_TITLE
10
- $body = $env:COPILOT_AGENTS_NOTIFY_BODY
11
- try {
12
- $null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
13
- $null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
14
- $escapedTitle = [System.Security.SecurityElement]::Escape($title)
15
- $escapedBody = [System.Security.SecurityElement]::Escape($body)
16
- $template = "<toast><visual><binding template='ToastGeneric'><text>$escapedTitle</text><text>$escapedBody</text></binding></visual></toast>"
17
- $xml = New-Object Windows.Data.Xml.Dom.XmlDocument
18
- $xml.LoadXml($template)
19
- $toast = New-Object Windows.UI.Notifications.ToastNotification $xml
20
- [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('PowerShell').Show($toast)
21
- } catch {
22
- Add-Type -AssemblyName System.Windows.Forms
23
- Add-Type -AssemblyName System.Drawing
24
- $icon = New-Object System.Windows.Forms.NotifyIcon
25
- $icon.Icon = [System.Drawing.SystemIcons]::Information
26
- $icon.Visible = $true
27
- $icon.ShowBalloonTip(8000, $title, $body, [System.Windows.Forms.ToolTipIcon]::Info)
28
- Start-Sleep -Seconds 2
29
- $icon.Dispose()
8
+ export function activeNotificationChannels(_platform, baseEnv) {
9
+ return baseEnv[NOTIFY_URL_ENV]?.trim() ? ["webhook"] : [];
30
10
  }
31
- `.trim();
32
- export function notificationPlan(platform, title, body, baseEnv) {
33
- const env = publicEnv(baseEnv);
34
- env.COPILOT_AGENTS_NOTIFY_TITLE = title;
35
- env.COPILOT_AGENTS_NOTIFY_BODY = body;
36
- if (platform === "win32")
37
- return { command: "powershell.exe", args: ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_SCRIPT], env };
38
- if (platform === "darwin") {
39
- return {
40
- command: "osascript",
41
- args: ["-e", 'display notification (system attribute "COPILOT_AGENTS_NOTIFY_BODY") with title (system attribute "COPILOT_AGENTS_NOTIFY_TITLE")'],
42
- env,
43
- };
44
- }
45
- if (platform === "linux")
46
- return { command: "notify-send", args: ["--", title, body], env };
47
- return null;
11
+ export function notificationChannelsForTask(task, state, env = process.env) {
12
+ return ownerWebhook(state, task) ? ["webhook"] : activeNotificationChannels(process.platform, env);
48
13
  }
49
- export function noticeText(notice) {
50
- const title = `Copilot ${notice.state}`.slice(0, 80);
51
- const body = [notice.repo, notice.task_id, notice.error ?? notice.state].filter(Boolean).join("\n").slice(0, 240);
52
- return { title, body };
14
+ export async function deliverTaskNotice(task, statePath, env = process.env, fetchImpl = fetch, ownerPost = postOwnerNotice) {
15
+ const registration = ownerWebhook(await readState(statePath), task);
16
+ if (!registration)
17
+ return deliverNotice(toDeliveryNotice(task), env, fetchImpl);
18
+ try {
19
+ const authorization = await readFile(registration.keyFilePath, "utf8");
20
+ await ownerPost(registration.url, toDeliveryNotice(task), authorization, env);
21
+ return { channels: ["webhook"] };
22
+ }
23
+ catch {
24
+ await appendWatcherLog("Could not POST the owner task notification.", env);
25
+ return { channels: [] };
26
+ }
53
27
  }
54
- export async function notifySystem(notice, spawnImpl = spawn, platform = process.platform, baseEnv = process.env) {
55
- const { title, body } = noticeText(notice);
56
- const plan = notificationPlan(platform, title, body, baseEnv);
57
- if (!plan)
58
- return;
59
- await new Promise((resolve) => {
60
- let pending = true;
61
- const done = (error) => {
62
- if (!pending)
63
- return;
64
- pending = false;
65
- if (error === undefined) {
66
- resolve();
67
- return;
68
- }
69
- void appendWatcherLog(`Could not show the system notification: ${notifyFailure(plan.command, error)}`, baseEnv).finally(resolve);
70
- };
71
- let child;
72
- try {
73
- child = spawnImpl(plan.command, plan.args, { windowsHide: true, env: plan.env, stdio: "ignore" });
74
- }
75
- catch (error) {
76
- done(error);
77
- return;
78
- }
79
- child.on("error", (error) => done(error));
80
- child.on("exit", () => done());
81
- });
28
+ export function createNextStep(channels) {
29
+ if (channels.length === 0) {
30
+ return "Task queued. Do not poll. End your turn; no notification channel is configured (set COPILOT_AGENTS_NOTIFY_URL). Call get_agent_task once later.";
31
+ }
32
+ return "Task queued. Do not poll. End your turn; you will be notified via webhook when the task finishes. Call get_agent_task once later.";
82
33
  }
83
34
  export async function appendWatcherLog(line, env = process.env) {
84
35
  const logPath = env.COPILOT_AGENTS_LOG?.trim();
@@ -94,36 +45,29 @@ export async function appendWatcherLog(line, env = process.env) {
94
45
  console.error(line);
95
46
  }
96
47
  }
97
- function notifyFailure(command, error) {
98
- const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "error";
99
- return `${code} ${command}`;
100
- }
101
48
  export async function postNotice(url, notice, authorization, fetchImpl = fetch) {
102
- const headers = { "content-type": "application/json" };
103
- if (authorization)
104
- headers.authorization = authorization;
49
+ const { body, headers } = webhookPost(notice, authorization);
105
50
  const response = await fetchImpl(url, {
106
51
  method: "POST",
107
52
  headers,
108
- body: JSON.stringify(notice),
53
+ body,
109
54
  signal: AbortSignal.timeout(10_000),
110
55
  });
111
56
  if (!response.ok)
112
57
  throw new Error(`Notification POST returned HTTP ${response.status}.`);
113
58
  }
114
- export async function deliverNotice(notice, env = process.env, fetchImpl = fetch, spawnImpl = spawn, platform = process.platform) {
115
- await notifySystem(notice, spawnImpl, platform, env);
59
+ export async function deliverNotice(notice, env = process.env, fetchImpl = fetch) {
60
+ const channels = [];
116
61
  const url = env[NOTIFY_URL_ENV]?.trim();
117
- if (!url)
118
- return;
119
- await postNotice(url, notice, env[NOTIFY_AUTHORIZATION_ENV]?.trim() || undefined, fetchImpl);
120
- }
121
- function publicEnv(baseEnv) {
122
- const env = {};
123
- for (const key of ENV_KEYS) {
124
- const value = baseEnv[key];
125
- if (value)
126
- env[key] = value;
62
+ if (url) {
63
+ try {
64
+ await postNotice(url, notice, env[NOTIFY_AUTHORIZATION_ENV]?.trim() || undefined, fetchImpl);
65
+ channels.push("webhook");
66
+ }
67
+ catch (error) {
68
+ const message = error instanceof Error ? error.message : "webhook delivery failed";
69
+ await appendWatcherLog(`Could not POST the task notification: ${message}`, env);
70
+ }
127
71
  }
128
- return env;
72
+ return { channels };
129
73
  }
package/dist/selection.js CHANGED
@@ -1,115 +1,19 @@
1
- export const TOOLSETS = {
2
- copilot_tasks: { feature: null },
3
- copilot_models: { feature: null },
4
- copilot_automations: { feature: "agent_automations" },
5
- copilot_agent_merge: { feature: "agent_merge" },
6
- };
7
- export const FEATURES = ["agent_automations", "agent_merge"];
8
- export const DEFAULT_TOOLSETS = ["copilot_tasks", "copilot_models"];
1
+ export const TOOL_NAMES = [
2
+ "create_agent_task",
3
+ "get_agent_task",
4
+ "list_agent_tasks",
5
+ "steer_agent_task",
6
+ "abort_agent_task",
7
+ "list_copilot_models",
8
+ ];
9
9
  export const TOOLS = [
10
- { name: "create_agent_task", toolset: "copilot_tasks", method: "POST" },
11
- { name: "get_agent_task", toolset: "copilot_tasks", method: "GET" },
12
- { name: "steer_agent_task", toolset: "copilot_tasks", method: "POST" },
13
- { name: "abort_agent_task", toolset: "copilot_tasks", method: "POST" },
14
- { name: "get_agent_task_events", toolset: "copilot_tasks", method: "GET" },
15
- { name: "list_copilot_models", toolset: "copilot_models", method: "GET" },
10
+ { name: "create_agent_task", method: "POST" },
11
+ { name: "get_agent_task", method: "GET" },
12
+ { name: "list_agent_tasks", method: "GET" },
13
+ { name: "steer_agent_task", method: "POST" },
14
+ { name: "abort_agent_task", method: "POST" },
15
+ { name: "list_copilot_models", method: "GET" },
16
16
  ];
17
- export function selectToolNames(selection) {
18
- assertSelection(selection);
19
- const features = new Set(selection.features);
20
- const requestedToolsets = selection.toolsets ?? (selection.tools ? [] : [...DEFAULT_TOOLSETS]);
21
- const names = new Set();
22
- for (const tool of TOOLS) {
23
- if (!featureAllows(tool.toolset, features))
24
- continue;
25
- if (requestedToolsets.includes(tool.toolset))
26
- names.add(tool.name);
27
- }
28
- for (const name of selection.tools ?? []) {
29
- const tool = TOOLS.find((item) => item.name === name);
30
- if (!tool || !featureAllows(tool.toolset, features))
31
- continue;
32
- names.add(name);
33
- }
34
- for (const name of selection.exclude)
35
- names.delete(name);
36
- if (selection.readOnly) {
37
- for (const name of [...names]) {
38
- const tool = TOOLS.find((item) => item.name === name);
39
- if (tool && tool.method !== "GET")
40
- names.delete(name);
41
- }
42
- }
43
- return TOOLS.map((tool) => tool.name).filter((name) => names.has(name));
44
- }
45
- export function assertSelection(selection) {
46
- for (const feature of selection.features) {
47
- if (!FEATURES.includes(feature)) {
48
- throw new Error(`Unknown feature: ${feature}.`);
49
- }
50
- }
51
- for (const name of selection.toolsets ?? []) {
52
- if (!isToolset(name))
53
- throw new Error(`Unknown toolset: ${name}.`);
54
- const feature = TOOLSETS[name].feature;
55
- if (feature && !selection.features.includes(feature)) {
56
- throw new Error(`Toolset ${name} requires --features=${feature}.`);
57
- }
58
- }
59
- for (const name of selection.tools ?? []) {
60
- if (!TOOLS.some((tool) => tool.name === name))
61
- throw new Error(`Unknown tool: ${name}.`);
62
- }
63
- }
64
- export function selectionFromHttp(url, headers, base) {
65
- const parsed = new URL(url, "http://127.0.0.1");
66
- const path = parsed.pathname.replace(/\/+$/, "") || "/";
67
- const toolsetMatch = /^(?:\/mcp)?\/x\/([^/]+)$/.exec(path);
68
- const readOnlyPath = path === "/readonly" || path === "/mcp/readonly";
69
- const known = path === "/" || path === "/mcp" || readOnlyPath || toolsetMatch !== null;
70
- if (!known)
71
- throw new Error("Unknown path.");
72
- const selection = {
73
- exclude: [...base.exclude],
74
- readOnly: base.readOnly,
75
- features: [...base.features],
76
- };
77
- if (base.toolsets)
78
- selection.toolsets = [...base.toolsets];
79
- if (base.tools)
80
- selection.tools = [...base.tools];
81
- if (toolsetMatch?.[1])
82
- selection.toolsets = [decodeURIComponent(toolsetMatch[1])];
83
- if (readOnlyPath)
84
- selection.readOnly = true;
85
- const headerToolsets = headers.get("x-mcp-toolsets");
86
- if (headerToolsets !== null)
87
- selection.toolsets = splitList(headerToolsets);
88
- const headerTools = headers.get("x-mcp-tools");
89
- if (headerTools !== null)
90
- selection.tools = splitList(headerTools);
91
- const headerExclude = headers.get("x-mcp-exclude-tools");
92
- if (headerExclude !== null)
93
- selection.exclude = splitList(headerExclude);
94
- const headerReadOnly = headers.get("x-mcp-readonly");
95
- if (headerReadOnly !== null && /^(true|1)$/i.test(headerReadOnly.trim()))
96
- selection.readOnly = true;
97
- if (base.readOnly)
98
- selection.readOnly = true;
99
- const headerFeatures = headers.get("x-mcp-features");
100
- const queryFeatures = parsed.searchParams.get("features");
101
- const featureSource = headerFeatures ?? queryFeatures;
102
- if (featureSource !== null)
103
- selection.features = splitList(featureSource);
104
- return selection;
105
- }
106
- export function splitList(value) {
107
- return value.split(",").map((item) => item.trim()).filter(Boolean);
108
- }
109
- function isToolset(name) {
110
- return Object.prototype.hasOwnProperty.call(TOOLSETS, name);
111
- }
112
- function featureAllows(toolset, features) {
113
- const feature = TOOLSETS[toolset].feature;
114
- return feature === null || features.has(feature);
17
+ export function toolNames() {
18
+ return [...TOOL_NAMES];
115
19
  }