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/README.md +88 -152
- package/dist/cli.js +166 -98
- package/dist/compact.js +23 -0
- package/dist/delivery.js +17 -0
- package/dist/errors.js +163 -63
- package/dist/follow-up.js +47 -0
- package/dist/github-hosts.js +61 -0
- package/dist/github.js +39 -59
- package/dist/notify.js +40 -96
- package/dist/selection.js +16 -112
- package/dist/server.js +442 -160
- package/dist/state.js +20 -2
- package/dist/status-local.js +79 -0
- package/dist/swe-models.js +49 -28
- package/dist/task-present.js +78 -0
- package/dist/task-status.js +124 -0
- package/dist/task-urls.js +24 -0
- package/dist/tasks.js +227 -0
- package/dist/time-format.js +3 -0
- package/dist/watch.js +36 -18
- package/dist/webhook-http.js +159 -0
- package/dist/webhooks.js +102 -0
- package/package.json +14 -2
- package/dist/http.js +0 -77
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
|
|
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,79 @@
|
|
|
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
|
+
import { listWebhooks } from "./webhooks.js";
|
|
7
|
+
export function stateLockDir(statePath) {
|
|
8
|
+
return `${statePath}.lock`;
|
|
9
|
+
}
|
|
10
|
+
export function envFlagSet(env, name) {
|
|
11
|
+
return name in env && env[name] !== "";
|
|
12
|
+
}
|
|
13
|
+
export function formatNotifyEnvDiagnostics(env) {
|
|
14
|
+
const urlSet = envFlagSet(env, NOTIFY_URL_ENV);
|
|
15
|
+
const authSet = envFlagSet(env, NOTIFY_AUTHORIZATION_ENV);
|
|
16
|
+
if (!urlSet && !authSet) {
|
|
17
|
+
return [" Info: webhook: not configured (optional)"];
|
|
18
|
+
}
|
|
19
|
+
const lines = [
|
|
20
|
+
`${NOTIFY_URL_ENV}: ${urlSet ? "yes" : "no"}`,
|
|
21
|
+
`${NOTIFY_AUTHORIZATION_ENV}: ${authSet ? "yes" : "no"}`,
|
|
22
|
+
];
|
|
23
|
+
if (urlSet !== authSet) {
|
|
24
|
+
const present = urlSet ? NOTIFY_URL_ENV : NOTIFY_AUTHORIZATION_ENV;
|
|
25
|
+
const missing = urlSet ? NOTIFY_AUTHORIZATION_ENV : NOTIFY_URL_ENV;
|
|
26
|
+
lines.push(` Warning: ${present} is set but ${missing} is not; configure both or neither.`);
|
|
27
|
+
}
|
|
28
|
+
return lines;
|
|
29
|
+
}
|
|
30
|
+
export function formatDbusDiagnostics(env, platform = process.platform) {
|
|
31
|
+
const set = envFlagSet(env, "DBUS_SESSION_BUS_ADDRESS");
|
|
32
|
+
const lines = [`DBUS_SESSION_BUS_ADDRESS: ${set ? "yes" : "no"}`];
|
|
33
|
+
if (!set && platform === "linux") {
|
|
34
|
+
lines.push(" Info: Without a session D-Bus, GitHub App login may fail; set DBUS_SESSION_BUS_ADDRESS or use GITHUB_PERSONAL_ACCESS_TOKEN.");
|
|
35
|
+
}
|
|
36
|
+
return lines;
|
|
37
|
+
}
|
|
38
|
+
export async function probeStateWritable(statePath) {
|
|
39
|
+
const lockDir = stateLockDir(statePath);
|
|
40
|
+
const parent = dirname(statePath);
|
|
41
|
+
const fileProbe = `${statePath}.auth-status-probe`;
|
|
42
|
+
const lockProbe = `${lockDir}.auth-status-probe`;
|
|
43
|
+
try {
|
|
44
|
+
await mkdir(parent, { recursive: true });
|
|
45
|
+
await access(parent, constants.W_OK);
|
|
46
|
+
await writeFile(fileProbe, "", { flag: "w" });
|
|
47
|
+
await rm(fileProbe, { force: true });
|
|
48
|
+
await mkdir(lockProbe);
|
|
49
|
+
await rm(lockProbe, { recursive: true, force: true });
|
|
50
|
+
return { statePath, lockDir, writable: "ok" };
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return { statePath, lockDir, writable: "fail" };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export async function buildLocalStatusDiagnostics(env, options) {
|
|
57
|
+
const statePath = defaultStatePath(env, options?.home);
|
|
58
|
+
const state = await probeStateWritable(statePath);
|
|
59
|
+
const platform = options?.platform ?? process.platform;
|
|
60
|
+
const lines = [
|
|
61
|
+
"Local diagnostics:",
|
|
62
|
+
`State file: ${state.statePath} — writable: ${state.writable}`,
|
|
63
|
+
`State lock dir: ${state.lockDir} — writable: ${state.writable}`,
|
|
64
|
+
...formatNotifyEnvDiagnostics(env),
|
|
65
|
+
...formatDbusDiagnostics(env, platform),
|
|
66
|
+
];
|
|
67
|
+
let webhookFailed = false;
|
|
68
|
+
try {
|
|
69
|
+
const webhooks = await listWebhooks(statePath);
|
|
70
|
+
for (const webhook of webhooks) {
|
|
71
|
+
lines.push(`Owner webhook: ${webhook.owner} — host: ${webhook.host} — key present: ${webhook.keyPresent ? "yes" : "no"} — mode0600: ${webhook.keyMode0600 ? "yes" : "no"}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
lines.push("Owner webhooks: unavailable.");
|
|
76
|
+
webhookFailed = true;
|
|
77
|
+
}
|
|
78
|
+
return { text: lines.join("\n"), failed: state.writable === "fail" || webhookFailed };
|
|
79
|
+
}
|
package/dist/swe-models.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import {
|
|
2
|
+
import { apiFailure, ModelsError } from "./errors.js";
|
|
3
3
|
export const GRAPHQL_URL = "https://api.github.com/graphql";
|
|
4
4
|
export const ENDPOINTS_QUERY = "query { viewer { copilotEndpoints { api } } }";
|
|
5
5
|
export const SWE_MODELS_PATH = "/agents/swe/models";
|
|
@@ -16,17 +16,17 @@ const promoSchema = z.object({
|
|
|
16
16
|
ends_at: z.string(),
|
|
17
17
|
message: z.string(),
|
|
18
18
|
}).strict();
|
|
19
|
+
const billingSchema = z.object({
|
|
20
|
+
token_prices: tokenPricesSchema.optional(),
|
|
21
|
+
promo: promoSchema.optional(),
|
|
22
|
+
multiplier: z.number().optional(),
|
|
23
|
+
}).strict();
|
|
19
24
|
const sweModelSchema = z.object({
|
|
20
25
|
id: z.string(),
|
|
21
26
|
name: z.string(),
|
|
22
27
|
vendor: z.string(),
|
|
23
28
|
preview: z.boolean(),
|
|
24
|
-
|
|
25
|
-
billing: z.object({
|
|
26
|
-
token_prices: tokenPricesSchema.optional(),
|
|
27
|
-
promo: promoSchema.optional(),
|
|
28
|
-
multiplier: z.number().optional(),
|
|
29
|
-
}).strict(),
|
|
29
|
+
billing: billingSchema,
|
|
30
30
|
}).strict();
|
|
31
31
|
export const sweModelsResultSchema = z.object({
|
|
32
32
|
source: z.object({
|
|
@@ -35,6 +35,29 @@ export const sweModelsResultSchema = z.object({
|
|
|
35
35
|
}).strict(),
|
|
36
36
|
models: z.array(sweModelSchema),
|
|
37
37
|
}).strict();
|
|
38
|
+
export function presentSweModelsResult(result) {
|
|
39
|
+
return {
|
|
40
|
+
source: result.source,
|
|
41
|
+
models: result.models.map(presentSweModel),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function presentSweModel(model) {
|
|
45
|
+
const billing = {};
|
|
46
|
+
if (model.billing.token_prices)
|
|
47
|
+
billing.token_prices = model.billing.token_prices;
|
|
48
|
+
if (model.billing.promo)
|
|
49
|
+
billing.promo = model.billing.promo;
|
|
50
|
+
if (model.billing.multiplier !== undefined)
|
|
51
|
+
billing.multiplier = model.billing.multiplier;
|
|
52
|
+
const row = {
|
|
53
|
+
id: model.id,
|
|
54
|
+
name: model.name,
|
|
55
|
+
vendor: model.vendor,
|
|
56
|
+
preview: model.preview,
|
|
57
|
+
billing,
|
|
58
|
+
};
|
|
59
|
+
return row;
|
|
60
|
+
}
|
|
38
61
|
export function validateSweModels(payload) {
|
|
39
62
|
if (!isRecord(payload) || !Object.prototype.hasOwnProperty.call(payload, "data") || !Array.isArray(payload.data)) {
|
|
40
63
|
throw new ModelsError("missing data");
|
|
@@ -63,7 +86,7 @@ export async function readSweModels(options) {
|
|
|
63
86
|
}
|
|
64
87
|
catch (error) {
|
|
65
88
|
if (error instanceof ModelsError) {
|
|
66
|
-
throw new ModelsError(`
|
|
89
|
+
throw new ModelsError(`The Copilot models API returned HTTP 200 with an invalid format: ${error.message}`);
|
|
67
90
|
}
|
|
68
91
|
throw error;
|
|
69
92
|
}
|
|
@@ -85,7 +108,7 @@ async function readApiBase(fetchImpl, holder, tokens) {
|
|
|
85
108
|
});
|
|
86
109
|
const api = readApi(body);
|
|
87
110
|
if (api === null) {
|
|
88
|
-
throw new ModelsError(
|
|
111
|
+
throw new ModelsError("GitHub endpoint discovery returned HTTP 200 with an invalid format: missing data.viewer.copilotEndpoints.api");
|
|
89
112
|
}
|
|
90
113
|
return api;
|
|
91
114
|
}
|
|
@@ -101,7 +124,6 @@ function readApi(body) {
|
|
|
101
124
|
return api;
|
|
102
125
|
}
|
|
103
126
|
async function readJson(fetchImpl, holder, tokens, url, init, retried = false) {
|
|
104
|
-
const method = init.method ?? "GET";
|
|
105
127
|
const token = holder.token;
|
|
106
128
|
const headers = new Headers(init.headers);
|
|
107
129
|
headers.set("authorization", `Bearer ${token}`);
|
|
@@ -115,16 +137,20 @@ async function readJson(fetchImpl, holder, tokens, url, init, retried = false) {
|
|
|
115
137
|
});
|
|
116
138
|
}
|
|
117
139
|
catch (error) {
|
|
118
|
-
|
|
119
|
-
|
|
140
|
+
throw modelsNetworkError(error);
|
|
141
|
+
}
|
|
142
|
+
let text;
|
|
143
|
+
try {
|
|
144
|
+
text = await response.text();
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
throw modelsNetworkError(error);
|
|
120
148
|
}
|
|
121
149
|
if (response.status === 401 && tokens && !retried) {
|
|
122
|
-
await response.text();
|
|
123
150
|
holder.token = await tokens.refresh(token);
|
|
124
151
|
return readJson(fetchImpl, holder, tokens, url, init, true);
|
|
125
152
|
}
|
|
126
153
|
if (response.status !== 200) {
|
|
127
|
-
const text = await response.text();
|
|
128
154
|
let parsed = null;
|
|
129
155
|
if (text) {
|
|
130
156
|
try {
|
|
@@ -134,18 +160,22 @@ async function readJson(fetchImpl, holder, tokens, url, init, retried = false) {
|
|
|
134
160
|
parsed = null;
|
|
135
161
|
}
|
|
136
162
|
}
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
throw new ModelsError(redact(missing ? `${missing} ${base}` : base, token));
|
|
163
|
+
const failure = apiFailure(response.status, response.headers, parsed ?? text, { permission: "Agent tasks" });
|
|
164
|
+
throw new ModelsError(failure.message, failure);
|
|
140
165
|
}
|
|
141
|
-
const text = await response.text();
|
|
142
166
|
try {
|
|
143
167
|
return JSON.parse(text);
|
|
144
168
|
}
|
|
145
169
|
catch {
|
|
146
|
-
throw new ModelsError(
|
|
170
|
+
throw new ModelsError("The Copilot API returned HTTP 200 with a non-JSON body.");
|
|
147
171
|
}
|
|
148
172
|
}
|
|
173
|
+
function modelsNetworkError(error) {
|
|
174
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
|
175
|
+
return new ModelsError("The Copilot API request timed out. Try listing models again.", { code: "upstream_timeout", retryable: true });
|
|
176
|
+
}
|
|
177
|
+
return new ModelsError("Could not read the Copilot API response. Check your network connection and try listing models again.", { code: "upstream_error", retryable: true });
|
|
178
|
+
}
|
|
149
179
|
function readModel(item, index) {
|
|
150
180
|
const where = `data[${index}]`;
|
|
151
181
|
if (!isRecord(item))
|
|
@@ -159,7 +189,6 @@ function readModel(item, index) {
|
|
|
159
189
|
name: readString(item, "name", `${where}.name`),
|
|
160
190
|
vendor: readString(item, "vendor", `${where}.vendor`),
|
|
161
191
|
preview: readBoolean(item, "preview", `${where}.preview`),
|
|
162
|
-
policy: readPolicy(item, `${where}.policy`),
|
|
163
192
|
billing: {},
|
|
164
193
|
};
|
|
165
194
|
if (hasMultiplier) {
|
|
@@ -173,14 +202,6 @@ function readModel(item, index) {
|
|
|
173
202
|
}
|
|
174
203
|
return model;
|
|
175
204
|
}
|
|
176
|
-
function readPolicy(item, path) {
|
|
177
|
-
if (!Object.prototype.hasOwnProperty.call(item, "policy") || item.policy === undefined || item.policy === null) {
|
|
178
|
-
return { state: null };
|
|
179
|
-
}
|
|
180
|
-
if (!isRecord(item.policy))
|
|
181
|
-
throw new ModelsError(`${path} is not an object`);
|
|
182
|
-
return { state: readString(item.policy, "state", `${path}.state`) };
|
|
183
|
-
}
|
|
184
205
|
function readPrices(value, path) {
|
|
185
206
|
if (!isRecord(value))
|
|
186
207
|
throw new ModelsError(`missing ${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
|
+
}
|