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/state.js CHANGED
@@ -2,8 +2,9 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
2
  import { dirname, join } from "node:path";
3
3
  import { homedir } from "node:os";
4
4
  import { failureMessage, isModelUnavailable, modelUnavailableMessage } from "./errors.js";
5
+ import { resolveTaskPageUrl } from "./task-urls.js";
6
+ import { mapRawState } from "./task-status.js";
5
7
  export const MODEL_PREFIX = "sweagent-capi:";
6
- export const FINAL_STATES = new Set(["completed", "failed", "timed_out", "cancelled", "idle"]);
7
8
  export function emptyState() {
8
9
  return { tasks: {}, models: { accepted: [], rejected: [] } };
9
10
  }
@@ -14,7 +15,7 @@ export function normalizeModel(model) {
14
15
  return model.startsWith(MODEL_PREFIX) ? model.slice(MODEL_PREFIX.length) : model;
15
16
  }
16
17
  export function isFinalState(state) {
17
- return FINAL_STATES.has(state);
18
+ return mapRawState(state).terminal;
18
19
  }
19
20
  export function taskSessionCount(task, fallback = 0) {
20
21
  if (typeof task.session_count === "number" && Number.isFinite(task.session_count))
@@ -24,6 +25,9 @@ export function taskSessionCount(task, fallback = 0) {
24
25
  return fallback;
25
26
  }
26
27
  export function armSteer(task, sessionCount, at) {
28
+ task.delivery_record = { status: "pending" };
29
+ task.notified_at = null;
30
+ task.last_fetched_at = null;
27
31
  task.steer = { at, session_count: sessionCount, turn_seen: false, notified: false };
28
32
  }
29
33
  export function noteSteerTurn(steer, task) {
@@ -34,6 +38,8 @@ export function noteSteerTurn(steer, task) {
34
38
  steer.turn_seen = true;
35
39
  }
36
40
  export function awaitingSteer(task) {
41
+ if (task.delivery_record?.status === "failed")
42
+ return false;
37
43
  return Boolean(task.steer && task.steer.notified !== true);
38
44
  }
39
45
  export function toNotice(task) {
@@ -52,6 +58,7 @@ export function toNotice(task) {
52
58
  updated_at: task.updated_at,
53
59
  completed_at: task.completed_at,
54
60
  session_id: task.session_id ?? null,
61
+ notified: Boolean(task.notified_at),
55
62
  };
56
63
  }
57
64
  export function toDeliveryNotice(task) {
@@ -117,6 +124,12 @@ export function observe(state, task, context) {
117
124
  updated_at: task.updated_at ?? null,
118
125
  completed_at: completed?.completed_at ?? null,
119
126
  notified_at: existing?.notified_at ?? null,
127
+ owner: existing?.owner,
128
+ delivery_record: existing?.delivery_record ?? null,
129
+ last_fetched_at: existing?.last_fetched_at ?? null,
130
+ check_after: existing?.check_after ?? null,
131
+ pr_title: existing?.pr_title ?? null,
132
+ html_url: resolveTaskPageUrl(task) ?? existing?.html_url ?? null,
120
133
  session_id: latestSessionId(sessions) ?? existing?.session_id ?? null,
121
134
  steer,
122
135
  };
@@ -161,6 +174,8 @@ export async function fillPullRequest(task, lookup, log, headRef = task.branch?.
161
174
  }
162
175
  pull.number = found.number;
163
176
  pull.html_url = found.html_url;
177
+ if (found.title)
178
+ task.pr_title = found.title;
164
179
  }
165
180
  catch (error) {
166
181
  await log(`Could not resolve pull request ${pull.id} for ${task.task_id}: ${failureMessage(error)}`);
@@ -205,6 +220,7 @@ export function initialTask(input) {
205
220
  return {
206
221
  task_id: input.id,
207
222
  repo: input.repo,
223
+ ...(input.owner ? { owner: input.owner } : {}),
208
224
  requested_model: input.requestedModel,
209
225
  state: input.state,
210
226
  resolved_model: null,
@@ -217,6 +233,8 @@ export function initialTask(input) {
217
233
  updated_at: input.updatedAt,
218
234
  completed_at: null,
219
235
  notified_at: null,
236
+ delivery_record: input.deliveryRecord ?? null,
237
+ html_url: input.htmlUrl ?? null,
220
238
  };
221
239
  }
222
240
  export async function withDirectoryLock(lock, fn, options) {
@@ -0,0 +1,67 @@
1
+ import { access, mkdir, rm, writeFile } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { defaultStatePath } from "./state.js";
5
+ import { NOTIFY_AUTHORIZATION_ENV, NOTIFY_URL_ENV } from "./notify.js";
6
+ export function stateLockDir(statePath) {
7
+ return `${statePath}.lock`;
8
+ }
9
+ export function envFlagSet(env, name) {
10
+ return name in env && env[name] !== "";
11
+ }
12
+ export function formatNotifyEnvDiagnostics(env) {
13
+ const urlSet = envFlagSet(env, NOTIFY_URL_ENV);
14
+ const authSet = envFlagSet(env, NOTIFY_AUTHORIZATION_ENV);
15
+ if (!urlSet && !authSet) {
16
+ return [" Info: webhook: not configured (optional)"];
17
+ }
18
+ const lines = [
19
+ `${NOTIFY_URL_ENV}: ${urlSet ? "yes" : "no"}`,
20
+ `${NOTIFY_AUTHORIZATION_ENV}: ${authSet ? "yes" : "no"}`,
21
+ ];
22
+ if (urlSet !== authSet) {
23
+ const present = urlSet ? NOTIFY_URL_ENV : NOTIFY_AUTHORIZATION_ENV;
24
+ const missing = urlSet ? NOTIFY_AUTHORIZATION_ENV : NOTIFY_URL_ENV;
25
+ lines.push(` Warning: ${present} is set but ${missing} is not; configure both or neither.`);
26
+ }
27
+ return lines;
28
+ }
29
+ export function formatDbusDiagnostics(env, platform = process.platform) {
30
+ const set = envFlagSet(env, "DBUS_SESSION_BUS_ADDRESS");
31
+ const lines = [`DBUS_SESSION_BUS_ADDRESS: ${set ? "yes" : "no"}`];
32
+ if (!set && platform === "linux") {
33
+ lines.push(" Info: Without a session D-Bus, GitHub App login may fail; set DBUS_SESSION_BUS_ADDRESS or use GITHUB_PERSONAL_ACCESS_TOKEN.");
34
+ }
35
+ return lines;
36
+ }
37
+ export async function probeStateWritable(statePath) {
38
+ const lockDir = stateLockDir(statePath);
39
+ const parent = dirname(statePath);
40
+ const fileProbe = `${statePath}.auth-status-probe`;
41
+ const lockProbe = `${lockDir}.auth-status-probe`;
42
+ try {
43
+ await mkdir(parent, { recursive: true });
44
+ await access(parent, constants.W_OK);
45
+ await writeFile(fileProbe, "", { flag: "w" });
46
+ await rm(fileProbe, { force: true });
47
+ await mkdir(lockProbe);
48
+ await rm(lockProbe, { recursive: true, force: true });
49
+ return { statePath, lockDir, writable: "ok" };
50
+ }
51
+ catch {
52
+ return { statePath, lockDir, writable: "fail" };
53
+ }
54
+ }
55
+ export async function buildLocalStatusDiagnostics(env, options) {
56
+ const statePath = defaultStatePath(env, options?.home);
57
+ const state = await probeStateWritable(statePath);
58
+ const platform = options?.platform ?? process.platform;
59
+ const lines = [
60
+ "Local diagnostics:",
61
+ `State file: ${state.statePath} — writable: ${state.writable}`,
62
+ `State lock dir: ${state.lockDir} — writable: ${state.writable}`,
63
+ ...formatNotifyEnvDiagnostics(env),
64
+ ...formatDbusDiagnostics(env, platform),
65
+ ];
66
+ return { text: lines.join("\n"), failed: state.writable === "fail" };
67
+ }
@@ -16,17 +16,21 @@ 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
+ const billingSchema = z.object({
23
+ token_prices: tokenPricesSchema.optional(),
24
+ promo: promoSchema.optional(),
25
+ multiplier: z.number().optional(),
26
+ }).strict();
19
27
  const sweModelSchema = z.object({
20
28
  id: z.string(),
21
29
  name: z.string(),
22
30
  vendor: z.string(),
23
31
  preview: z.boolean(),
24
- policy: z.object({ state: z.string().nullable() }).strict(),
25
- billing: z.object({
26
- token_prices: tokenPricesSchema.optional(),
27
- promo: promoSchema.optional(),
28
- multiplier: z.number().optional(),
29
- }).strict(),
32
+ policy: policySchema.optional(),
33
+ billing: billingSchema,
30
34
  }).strict();
31
35
  export const sweModelsResultSchema = z.object({
32
36
  source: z.object({
@@ -35,6 +39,31 @@ export const sweModelsResultSchema = z.object({
35
39
  }).strict(),
36
40
  models: z.array(sweModelSchema),
37
41
  }).strict();
42
+ export function presentSweModelsResult(result) {
43
+ return {
44
+ source: result.source,
45
+ models: result.models.map(presentSweModel),
46
+ };
47
+ }
48
+ function presentSweModel(model) {
49
+ const billing = {};
50
+ if (model.billing.token_prices)
51
+ billing.token_prices = model.billing.token_prices;
52
+ if (model.billing.promo)
53
+ billing.promo = model.billing.promo;
54
+ if (model.billing.multiplier !== undefined)
55
+ billing.multiplier = model.billing.multiplier;
56
+ const row = {
57
+ id: model.id,
58
+ name: model.name,
59
+ vendor: model.vendor,
60
+ preview: model.preview,
61
+ billing,
62
+ };
63
+ if (model.policy?.state !== undefined)
64
+ row.policy = { state: model.policy.state };
65
+ return row;
66
+ }
38
67
  export function validateSweModels(payload) {
39
68
  if (!isRecord(payload) || !Object.prototype.hasOwnProperty.call(payload, "data") || !Array.isArray(payload.data)) {
40
69
  throw new ModelsError("missing data");
@@ -159,9 +188,11 @@ function readModel(item, index) {
159
188
  name: readString(item, "name", `${where}.name`),
160
189
  vendor: readString(item, "vendor", `${where}.vendor`),
161
190
  preview: readBoolean(item, "preview", `${where}.preview`),
162
- policy: readPolicy(item, `${where}.policy`),
163
191
  billing: {},
164
192
  };
193
+ const policy = readPolicy(item, `${where}.policy`);
194
+ if (policy)
195
+ model.policy = policy;
165
196
  if (hasMultiplier) {
166
197
  model.billing.multiplier = readNumber(item.billing, "multiplier", `${where}.billing.multiplier`);
167
198
  }
@@ -175,10 +206,15 @@ function readModel(item, index) {
175
206
  }
176
207
  function readPolicy(item, path) {
177
208
  if (!Object.prototype.hasOwnProperty.call(item, "policy") || item.policy === undefined || item.policy === null) {
178
- return { state: null };
209
+ return undefined;
179
210
  }
180
211
  if (!isRecord(item.policy))
181
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;
182
218
  return { state: readString(item.policy, "state", `${path}.state`) };
183
219
  }
184
220
  function readPrices(value, path) {
@@ -0,0 +1,78 @@
1
+ import { deliveryForTask } from "./delivery.js";
2
+ import { buildSummary, durationLabel, mapRawState, pullRequestView, unknownStateWarning } from "./task-status.js";
3
+ import { formatCheckAfterUtc } from "./time-format.js";
4
+ import { prUrl, sessionUrl } from "./task-urls.js";
5
+ const ERROR_VERBOSE_MAX = 2048;
6
+ export function truncateError(error) {
7
+ if (!error)
8
+ return undefined;
9
+ if (error.length <= ERROR_VERBOSE_MAX)
10
+ return error;
11
+ return `${error.slice(0, ERROR_VERBOSE_MAX - 1)}…`;
12
+ }
13
+ export function compactGetTask(task, channels, options) {
14
+ const mapped = mapRawState(task.state);
15
+ const delivery = deliveryForTask(task, channels);
16
+ const summary = buildSummary(task, { checkAfter: options?.checkAfter });
17
+ const body = {
18
+ task_id: task.task_id,
19
+ repo: task.repo,
20
+ status: mapped.status,
21
+ terminal: mapped.terminal,
22
+ summary,
23
+ delivery,
24
+ };
25
+ const warning = unknownStateWarning(task.state);
26
+ if (warning)
27
+ body.warning = warning;
28
+ if (task.owner)
29
+ body.owner = task.owner;
30
+ const session = sessionUrl(task);
31
+ if (session)
32
+ body.session_url = session;
33
+ const prLink = prUrl(task);
34
+ if (prLink)
35
+ body.pr_url = prLink;
36
+ const pr = pullRequestView(task);
37
+ if (pr && options?.verbose)
38
+ body.pull_request = pr;
39
+ if (task.completed_at)
40
+ body.completed_at = task.completed_at;
41
+ if (!mapped.terminal && options?.checkAfter) {
42
+ const dur = durationLabel(task);
43
+ body.next_step = `Still working (${dur}). End your turn; first check not before ${formatCheckAfterUtc(options.checkAfter)}.`;
44
+ }
45
+ else if (mapped.terminal && mapped.status === "completed" && task.pull_request?.number) {
46
+ body.next_step = `PR #${task.pull_request.number} is open for review.`;
47
+ }
48
+ if (options?.cached)
49
+ body.cached = true;
50
+ if (options?.verbose) {
51
+ body.state = task.state;
52
+ if (task.requested_model)
53
+ body.requested_model = task.requested_model;
54
+ if (task.resolved_model)
55
+ body.resolved_model = task.resolved_model;
56
+ if (task.branch)
57
+ body.branch = task.branch;
58
+ if (task.artifacts.length > 0)
59
+ body.artifacts = task.artifacts;
60
+ if (task.usage)
61
+ body.usage = task.usage;
62
+ if (task.session_id)
63
+ body.session_id = task.session_id;
64
+ if (task.created_at)
65
+ body.created_at = task.created_at;
66
+ if (task.updated_at)
67
+ body.updated_at = task.updated_at;
68
+ const err = truncateError(task.error);
69
+ if (err)
70
+ body.error = err;
71
+ if (task.delivery_record?.delivered_via)
72
+ body.delivered_via = task.delivery_record.delivered_via;
73
+ }
74
+ return body;
75
+ }
76
+ export function usageOrUndefined(usage) {
77
+ return usage ?? undefined;
78
+ }
@@ -0,0 +1,124 @@
1
+ import { formatCheckAfterUtc } from "./time-format.js";
2
+ import { githubPageUrl } from "./task-urls.js";
3
+ export const DOCUMENTED_TASK_STATES = [
4
+ "queued",
5
+ "in_progress",
6
+ "completed",
7
+ "failed",
8
+ "idle",
9
+ "waiting_for_user",
10
+ "timed_out",
11
+ "cancelled",
12
+ ];
13
+ const RAW_TO_STATUS = {
14
+ queued: { status: "working", terminal: false },
15
+ in_progress: { status: "working", terminal: false },
16
+ completed: { status: "completed", terminal: true },
17
+ failed: { status: "failed", terminal: true },
18
+ idle: { status: "completed", terminal: true },
19
+ waiting_for_user: { status: "needs_input", terminal: false },
20
+ timed_out: { status: "failed", terminal: true },
21
+ cancelled: { status: "cancelled", terminal: true },
22
+ };
23
+ export function isKnownRawState(rawState) {
24
+ const normalized = rawState.trim().toLowerCase();
25
+ return Object.prototype.hasOwnProperty.call(RAW_TO_STATUS, normalized);
26
+ }
27
+ export function mapRawState(rawState) {
28
+ const normalized = rawState.trim().toLowerCase();
29
+ if (Object.prototype.hasOwnProperty.call(RAW_TO_STATUS, normalized)) {
30
+ return RAW_TO_STATUS[normalized];
31
+ }
32
+ return { status: "failed", terminal: true };
33
+ }
34
+ export function unknownStateWarning(rawState) {
35
+ if (isKnownRawState(rawState))
36
+ return undefined;
37
+ return `Unknown GitHub task state "${sanitizeLine(rawState, 80)}"; treated as failed.`;
38
+ }
39
+ export function isMappedTerminal(status) {
40
+ return status === "completed" || status === "failed" || status === "cancelled";
41
+ }
42
+ export function sanitizeLine(text, maxLen) {
43
+ const stripped = text.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
44
+ if (stripped.length <= maxLen)
45
+ return stripped;
46
+ return `${stripped.slice(0, maxLen - 1)}…`;
47
+ }
48
+ export function durationStartMs(task) {
49
+ if (task.steer?.at) {
50
+ const steerAt = Date.parse(task.steer.at);
51
+ if (Number.isFinite(steerAt))
52
+ return steerAt;
53
+ }
54
+ const created = Date.parse(task.created_at ?? "");
55
+ if (Number.isFinite(created))
56
+ return created;
57
+ return null;
58
+ }
59
+ export function durationLabel(task, now = Date.now()) {
60
+ const startMs = durationStartMs(task) ?? now;
61
+ const mapped = mapRawState(task.state);
62
+ const endRaw = mapped.terminal
63
+ ? Date.parse(task.completed_at ?? task.updated_at ?? "")
64
+ : now;
65
+ const endMs = Number.isFinite(endRaw) ? endRaw : now;
66
+ const diffMs = Math.max(0, endMs - startMs);
67
+ if (diffMs < 60_000)
68
+ return "<1m";
69
+ const minutes = Math.round(diffMs / 60_000);
70
+ return `${minutes}m`;
71
+ }
72
+ export function buildSummary(task, context = {}) {
73
+ const mapped = mapRawState(task.state);
74
+ const dur = durationLabel(task, context.now);
75
+ if (mapped.status === "working") {
76
+ if (context.checkAfter)
77
+ return `Working for ${dur}. First check not before ${formatCheckAfterUtc(context.checkAfter)}.`;
78
+ return `Working for ${dur}.`;
79
+ }
80
+ if (mapped.status === "needs_input") {
81
+ const line = task.error ? sanitizeLine(task.error, 120) : "agent";
82
+ return `Waiting for input: ${line}.`;
83
+ }
84
+ if (mapped.status === "completed") {
85
+ const pr = task.pull_request;
86
+ if (pr?.number !== null && pr?.number !== undefined) {
87
+ const prTitle = resolvePullTitle(task);
88
+ if (prTitle)
89
+ return `Completed in ${dur}: opened PR #${pr.number} '${sanitizeLine(prTitle, 60)}'.`;
90
+ return `Completed in ${dur}: opened PR #${pr.number}.`;
91
+ }
92
+ if (pr && pr.number === null) {
93
+ return `Completed in ${dur}: opened a pull request (number not resolved yet).`;
94
+ }
95
+ const head = task.branch?.head_ref;
96
+ if (head)
97
+ return `Completed in ${dur} on branch ${sanitizeLine(head, 40)}.`;
98
+ return `Completed in ${dur}; no changes.`;
99
+ }
100
+ if (mapped.status === "failed") {
101
+ if (!isKnownRawState(task.state)) {
102
+ return `Failed: unknown state ${sanitizeLine(task.state, 80)}.`;
103
+ }
104
+ if (task.state === "timed_out")
105
+ return `Failed: timed out after ${dur}.`;
106
+ const line = task.error ? sanitizeLine(task.error, 100) : "unknown error";
107
+ return `Failed after ${dur}: ${line}.`;
108
+ }
109
+ return `Cancelled after ${dur}.`;
110
+ }
111
+ function resolvePullTitle(task) {
112
+ return task.pr_title ?? null;
113
+ }
114
+ export function pullRequestView(task) {
115
+ const pr = task.pull_request;
116
+ if (!pr)
117
+ return undefined;
118
+ const page = pr.html_url ? githubPageUrl(pr.html_url) : undefined;
119
+ if (pr.number !== null && page)
120
+ return { number: pr.number, url: page };
121
+ if (pr.number !== null)
122
+ return { number: pr.number };
123
+ return { id: pr.id };
124
+ }
@@ -0,0 +1,24 @@
1
+ import { githubPageUrl } from "./github-hosts.js";
2
+ export { githubApiBase, githubPageUrl, githubWebHost } from "./github-hosts.js";
3
+ export function resolveTaskPageUrl(input) {
4
+ return githubPageUrl(input.html_url) ?? githubPageUrl(input.url);
5
+ }
6
+ export function sessionUrl(task) {
7
+ return githubPageUrl(task.html_url);
8
+ }
9
+ export function prUrl(task) {
10
+ const url = task.pull_request?.html_url;
11
+ return githubPageUrl(url);
12
+ }
13
+ export function appendUrlHints(summary, session, pr) {
14
+ const hints = [];
15
+ if (session)
16
+ hints.push(`Session: ${session}`);
17
+ if (pr)
18
+ hints.push(`PR: ${pr}`);
19
+ if (hints.length === 0)
20
+ return summary;
21
+ const suffix = ` ${hints.join(" ")}`;
22
+ const next = `${summary.replace(/\.\s*$/, "")}.${suffix}`;
23
+ return next.length <= 160 ? next : summary;
24
+ }