ceulen 0.9.0 → 0.10.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/CHANGELOG.md +37 -0
- package/extensions/lib/registry.ts +8 -2
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +1 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/gh/configPanel.ts +82 -0
- package/extensions/modules/gh/index.ts +86 -0
- package/extensions/modules/gh/lib/gh-cli.ts +337 -0
- package/extensions/modules/gh/lib/ops.ts +771 -0
- package/extensions/modules/gh/test/gh.test.ts +280 -0
- package/extensions/modules/plan/lib/plan-tools.ts +8 -0
- package/extensions/modules/repair/index.ts +138 -0
- package/extensions/modules/repair/lib/guards.ts +1 -1
- package/extensions/modules/repair/lib/read-selector.ts +242 -0
- package/extensions/modules/repair/test/read-selector.test.ts +198 -0
- package/extensions/modules/steering/configPanel.ts +8 -0
- package/extensions/modules/steering/index.ts +6 -0
- package/extensions/modules/steering/lib/settings.ts +6 -2
- package/extensions/modules/steering/lib/think.ts +66 -0
- package/extensions/modules/steering/test/harness.ts +5 -0
- package/extensions/modules/steering/test/settings.test.ts +2 -0
- package/extensions/modules/steering/test/think.test.ts +77 -0
- package/extensions/modules/web/index.ts +37 -1
- package/extensions/modules/web/lib/a11y.ts +252 -0
- package/extensions/modules/web/test/a11y.test.ts +218 -0
- package/extensions/modules/web/test/extension.test.ts +2 -2
- package/extensions/modules/web/test/hook.test.ts +2 -2
- package/extensions/modules/web/vendor/axe/LICENSE +362 -0
- package/extensions/modules/web/vendor/axe/LICENSE-3RD-PARTY.txt +66 -0
- package/extensions/modules/web/vendor/axe/README.md +19 -0
- package/extensions/modules/web/vendor/axe/axe.min.js +12 -0
- package/package.json +2 -2
- package/skills/web/SKILL.md +1 -0
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
// ponytail: ported from oh-my-pi tools/{gh-search,gh-view,gh-run-watch}.ts
|
|
2
|
+
// (lean) — one executor per read-only op, each returning markdown-ish text.
|
|
3
|
+
// All ops take the GhRunner seam so tests inject a fake.
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
appendRepoFlag,
|
|
7
|
+
formatAuthor,
|
|
8
|
+
formatLabels,
|
|
9
|
+
formatRepoRef,
|
|
10
|
+
formatShortSha,
|
|
11
|
+
ghApiHostArgs,
|
|
12
|
+
normalizeBlock,
|
|
13
|
+
normalizeOptionalString,
|
|
14
|
+
normalizeText,
|
|
15
|
+
parseRepoRef,
|
|
16
|
+
pushLine,
|
|
17
|
+
requireNonEmpty,
|
|
18
|
+
type GhRunner,
|
|
19
|
+
} from "./gh-cli.js";
|
|
20
|
+
import { readRunWatchTimeoutSecs } from "../configPanel.js";
|
|
21
|
+
|
|
22
|
+
export interface GhParams {
|
|
23
|
+
repo?: string;
|
|
24
|
+
branch?: string;
|
|
25
|
+
path?: string;
|
|
26
|
+
pr?: string;
|
|
27
|
+
query?: string;
|
|
28
|
+
since?: string;
|
|
29
|
+
until?: string;
|
|
30
|
+
dateField?: "created" | "updated";
|
|
31
|
+
limit?: number;
|
|
32
|
+
run?: string;
|
|
33
|
+
tail?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ── Search plumbing (OMP gh-search.ts) ──
|
|
37
|
+
|
|
38
|
+
export const SEARCH_LIMIT_DEFAULT = 10;
|
|
39
|
+
export const SEARCH_LIMIT_MAX = 50;
|
|
40
|
+
const FILE_PREVIEW_LIMIT = 50;
|
|
41
|
+
const BODY_CAP = 4000;
|
|
42
|
+
|
|
43
|
+
function resolveSearchLimit(value: number | undefined): number {
|
|
44
|
+
if (value === undefined) return SEARCH_LIMIT_DEFAULT;
|
|
45
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error("limit must be a positive number");
|
|
46
|
+
return Math.min(Math.floor(value), SEARCH_LIMIT_MAX);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function composeSearchQuery(parts: ReadonlyArray<string | undefined>): string {
|
|
50
|
+
const cleaned: string[] = [];
|
|
51
|
+
for (const part of parts) {
|
|
52
|
+
const trimmed = part?.trim();
|
|
53
|
+
if (trimmed) cleaned.push(trimmed);
|
|
54
|
+
}
|
|
55
|
+
if (cleaned.length === 0) throw new Error("query is required (or pass since/until to filter by date)");
|
|
56
|
+
return cleaned.join(" ");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const RELATIVE_DURATION_PATTERN = /^(\d+)\s*(m|h|d|w|mo|y)$/i;
|
|
60
|
+
const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
61
|
+
const FIXED_UNIT_MS: Record<string, number> = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 7 * 86_400_000 };
|
|
62
|
+
|
|
63
|
+
/** Date bound → GitHub-search literal (`YYYY-MM-DD` or seconds-precision ISO). */
|
|
64
|
+
export function parseSearchDateBound(raw: string, now: Date = new Date()): string {
|
|
65
|
+
const trimmed = raw.trim();
|
|
66
|
+
if (!trimmed) throw new Error("date bound must not be empty");
|
|
67
|
+
const relMatch = trimmed.match(RELATIVE_DURATION_PATTERN);
|
|
68
|
+
if (relMatch) {
|
|
69
|
+
const count = Number(relMatch[1]);
|
|
70
|
+
const unit = relMatch[2].toLowerCase();
|
|
71
|
+
const fixedMs = FIXED_UNIT_MS[unit];
|
|
72
|
+
let bound: Date;
|
|
73
|
+
if (fixedMs !== undefined) {
|
|
74
|
+
bound = new Date(now.getTime() - count * fixedMs);
|
|
75
|
+
} else {
|
|
76
|
+
bound = new Date(now);
|
|
77
|
+
if (unit === "mo") bound.setUTCMonth(bound.getUTCMonth() - count);
|
|
78
|
+
else bound.setUTCFullYear(bound.getUTCFullYear() - count);
|
|
79
|
+
}
|
|
80
|
+
return bound.toISOString().slice(0, 10);
|
|
81
|
+
}
|
|
82
|
+
if (ISO_DATE_PATTERN.test(trimmed)) return trimmed;
|
|
83
|
+
const parsedMs = Date.parse(trimmed);
|
|
84
|
+
if (!Number.isNaN(parsedMs)) {
|
|
85
|
+
return new Date(parsedMs).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`invalid date bound: ${raw}. Expected a relative duration like "3d", "12h", "2w", an ISO date "YYYY-MM-DD", or an ISO datetime.`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function buildSearchDateQualifier(field: string, since?: string, until?: string, now?: Date): string | undefined {
|
|
91
|
+
const sinceVal = since ? parseSearchDateBound(since, now) : undefined;
|
|
92
|
+
const untilVal = until ? parseSearchDateBound(until, now) : undefined;
|
|
93
|
+
if (sinceVal && untilVal) return `${field}:${sinceVal}..${untilVal}`;
|
|
94
|
+
if (sinceVal) return `${field}:>=${sinceVal}`;
|
|
95
|
+
if (untilVal) return `${field}:<=${untilVal}`;
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function resolveSearchDateField(command: "issues" | "prs" | "commits" | "repos", requested?: "created" | "updated"): string {
|
|
100
|
+
if (command === "commits") return "committer-date";
|
|
101
|
+
const dateField = requested ?? "created";
|
|
102
|
+
if (command === "repos" && dateField === "updated") return "pushed";
|
|
103
|
+
return dateField;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Qualifiers that already scope a search — no default `repo:<current>` on top. */
|
|
107
|
+
export const REPO_SCOPE_QUALIFIER_PATTERN = /(?:^|\s)-?(?:repo|org|user|owner):\S/i;
|
|
108
|
+
|
|
109
|
+
async function resolveSearchRepoScope(gh: GhRunner, cwd: string, repo: string | undefined, query: string | undefined, signal?: AbortSignal): Promise<string | undefined> {
|
|
110
|
+
if (repo) return repo;
|
|
111
|
+
if (query && REPO_SCOPE_QUALIFIER_PATTERN.test(query)) return undefined;
|
|
112
|
+
return await tryResolveCurrentRepoVia(gh, cwd, signal);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function searchScope(repo: string | undefined): { qualifier?: string; host?: string } {
|
|
116
|
+
if (!repo) return {};
|
|
117
|
+
const ref = parseRepoRef(repo);
|
|
118
|
+
return { qualifier: `repo:${ref.slug}`, host: ref.host };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function buildGhApiSearchArgs(endpoint: "issues" | "code" | "commits" | "repositories", query: string, limit: number, options?: { host?: string; extraHeaders?: string[] }): string[] {
|
|
122
|
+
const args = ["api"];
|
|
123
|
+
if (options?.host) args.push("--hostname", options.host);
|
|
124
|
+
args.push("-X", "GET", `/search/${endpoint}`, "-f", `q=${query}`, "-F", `per_page=${limit}`);
|
|
125
|
+
for (const header of options?.extraHeaders ?? []) args.push("-H", header);
|
|
126
|
+
return args;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface GhApiUser { login?: string; name?: string }
|
|
130
|
+
interface GhApiLabel { name?: string }
|
|
131
|
+
interface GhApiSearchIssueItem {
|
|
132
|
+
number?: number; title?: string; state?: string; created_at?: string; updated_at?: string;
|
|
133
|
+
html_url?: string; user?: GhApiUser; labels?: GhApiLabel[];
|
|
134
|
+
pull_request?: { merged_at?: string | null }; repository_url?: string;
|
|
135
|
+
}
|
|
136
|
+
interface GhApiSearchCodeItem {
|
|
137
|
+
path?: string; sha?: string; html_url?: string;
|
|
138
|
+
repository?: { full_name?: string }; text_matches?: { fragment?: string; property?: string }[];
|
|
139
|
+
}
|
|
140
|
+
interface GhApiSearchCommitItem {
|
|
141
|
+
sha?: string; html_url?: string; node_id?: string;
|
|
142
|
+
author?: GhApiUser | null; committer?: GhApiUser | null;
|
|
143
|
+
repository?: { full_name?: string };
|
|
144
|
+
commit?: { message?: string; author?: { name?: string; date?: string }; committer?: { name?: string; date?: string } };
|
|
145
|
+
}
|
|
146
|
+
interface GhApiSearchRepoItem {
|
|
147
|
+
full_name?: string; description?: string; language?: string; html_url?: string;
|
|
148
|
+
stargazers_count?: number; forks_count?: number; open_issues_count?: number;
|
|
149
|
+
updated_at?: string; archived?: boolean; fork?: boolean; private?: boolean; visibility?: string;
|
|
150
|
+
}
|
|
151
|
+
interface GhApiSearchResponse<T> { total_count?: number; items?: T[] }
|
|
152
|
+
|
|
153
|
+
/** Best-effort memoized cwd → repo through the injected runner. */
|
|
154
|
+
async function tryResolveCurrentRepoVia(gh: GhRunner, cwd: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
155
|
+
try {
|
|
156
|
+
return await resolveDefaultRepoVia(gh, cwd, signal);
|
|
157
|
+
} catch {
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Memoized cwd → repo via the runner seam (test-injectable twin of gh-cli's). */
|
|
163
|
+
const REPO_CACHE = new Map<string, string>();
|
|
164
|
+
async function resolveDefaultRepoVia(gh: GhRunner, cwd: string, signal?: AbortSignal): Promise<string> {
|
|
165
|
+
const ready = REPO_CACHE.get(cwd);
|
|
166
|
+
if (ready) return ready;
|
|
167
|
+
const url = await gh.text(cwd, ["repo", "view", "--json", "url", "-q", ".url"], signal);
|
|
168
|
+
const match = /^https?:\/\/([^/]+)\/([^/]+)\/([^/?#]+)/.exec(url.trim());
|
|
169
|
+
if (!match) throw new Error(`GitHub CLI returned an unrecognized repository URL: ${url}`);
|
|
170
|
+
const host = match[1].toLowerCase();
|
|
171
|
+
const repo = host === "github.com" ? `${match[2]}/${match[3]}` : formatRepoRef(host, `${match[2]}/${match[3]}`);
|
|
172
|
+
REPO_CACHE.set(cwd, repo);
|
|
173
|
+
return repo;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function repoFromRepositoryUrl(value: string | undefined): string | undefined {
|
|
177
|
+
return value ? (/\/repos\/([^/]+\/[^/]+)$/.exec(value)?.[1] ?? undefined) : undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function formatSearchResults(kind: "issues" | "pull requests", query: string, repo: string | undefined, items: GhApiSearchIssueItem[]): string {
|
|
181
|
+
const lines: string[] = [`# GitHub ${kind} search`, "", `Query: ${query}`];
|
|
182
|
+
pushLine(lines, "Repository", repo);
|
|
183
|
+
pushLine(lines, "Results", items.length);
|
|
184
|
+
if (items.length === 0) {
|
|
185
|
+
lines.push("", `No ${kind} found.`);
|
|
186
|
+
return lines.join("\n").trim();
|
|
187
|
+
}
|
|
188
|
+
for (const item of items) {
|
|
189
|
+
lines.push("");
|
|
190
|
+
lines.push(`- #${item.number ?? "?"} ${item.title ?? "Untitled"}`);
|
|
191
|
+
pushLine(lines, " Repo", repoFromRepositoryUrl(item.repository_url));
|
|
192
|
+
pushLine(lines, " State", item.pull_request?.merged_at ? "merged" : item.state);
|
|
193
|
+
pushLine(lines, " Author", formatAuthor(item.user));
|
|
194
|
+
pushLine(lines, " Labels", formatLabels(item.labels));
|
|
195
|
+
pushLine(lines, " Created", item.created_at);
|
|
196
|
+
pushLine(lines, " Updated", item.updated_at);
|
|
197
|
+
pushLine(lines, " URL", item.html_url);
|
|
198
|
+
}
|
|
199
|
+
return lines.join("\n").trim();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function formatSearchCodeResults(query: string, repo: string | undefined, items: GhApiSearchCodeItem[]): string {
|
|
203
|
+
const lines: string[] = [`# GitHub code search`, "", `Query: ${query}`];
|
|
204
|
+
pushLine(lines, "Repository", repo);
|
|
205
|
+
pushLine(lines, "Results", items.length);
|
|
206
|
+
if (items.length === 0) {
|
|
207
|
+
lines.push("", "No code matches found.");
|
|
208
|
+
return lines.join("\n").trim();
|
|
209
|
+
}
|
|
210
|
+
for (const item of items) {
|
|
211
|
+
lines.push("");
|
|
212
|
+
lines.push(`- ${item.path ?? "(unknown path)"}`);
|
|
213
|
+
pushLine(lines, " Repo", item.repository?.full_name);
|
|
214
|
+
pushLine(lines, " Commit", formatShortSha(item.sha));
|
|
215
|
+
pushLine(lines, " URL", item.html_url);
|
|
216
|
+
const fragment = item.text_matches?.find((m) => m.fragment)?.fragment;
|
|
217
|
+
if (fragment) pushLine(lines, " Match", normalizeText(fragment).split("\n", 1)[0]);
|
|
218
|
+
}
|
|
219
|
+
return lines.join("\n").trim();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function formatSearchCommitsResults(query: string, repo: string | undefined, items: GhApiSearchCommitItem[]): string {
|
|
223
|
+
const lines: string[] = [`# GitHub commits search`, "", `Query: ${query}`];
|
|
224
|
+
pushLine(lines, "Repository", repo);
|
|
225
|
+
pushLine(lines, "Results", items.length);
|
|
226
|
+
if (items.length === 0) {
|
|
227
|
+
lines.push("", "No commits found.");
|
|
228
|
+
return lines.join("\n").trim();
|
|
229
|
+
}
|
|
230
|
+
for (const item of items) {
|
|
231
|
+
lines.push("");
|
|
232
|
+
const sha = formatShortSha(item.sha) ?? "(unknown sha)";
|
|
233
|
+
const subject = normalizeText(item.commit?.message).split("\n", 1)[0] || "(no commit message)";
|
|
234
|
+
lines.push(`- ${sha} ${subject}`);
|
|
235
|
+
pushLine(lines, " Repo", item.repository?.full_name);
|
|
236
|
+
pushLine(lines, " Author", formatAuthor(item.author) ?? item.commit?.author?.name);
|
|
237
|
+
pushLine(lines, " Date", item.commit?.author?.date ?? item.commit?.committer?.date);
|
|
238
|
+
pushLine(lines, " URL", item.html_url);
|
|
239
|
+
}
|
|
240
|
+
return lines.join("\n").trim();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function formatSearchReposResults(query: string, items: GhApiSearchRepoItem[]): string {
|
|
244
|
+
const lines: string[] = [`# GitHub repositories search`, "", `Query: ${query}`];
|
|
245
|
+
pushLine(lines, "Results", items.length);
|
|
246
|
+
if (items.length === 0) {
|
|
247
|
+
lines.push("", "No repositories found.");
|
|
248
|
+
return lines.join("\n").trim();
|
|
249
|
+
}
|
|
250
|
+
for (const item of items) {
|
|
251
|
+
lines.push("");
|
|
252
|
+
lines.push(`- ${item.full_name ?? "(unknown repository)"}`);
|
|
253
|
+
const description = normalizeText(item.description).split("\n", 1)[0];
|
|
254
|
+
if (description) pushLine(lines, " Description", description);
|
|
255
|
+
pushLine(lines, " Language", item.language);
|
|
256
|
+
pushLine(lines, " Stars", item.stargazers_count);
|
|
257
|
+
pushLine(lines, " Forks", item.forks_count);
|
|
258
|
+
pushLine(lines, " Open issues", item.open_issues_count);
|
|
259
|
+
pushLine(lines, " Updated", item.updated_at);
|
|
260
|
+
pushLine(lines, " URL", item.html_url);
|
|
261
|
+
}
|
|
262
|
+
return lines.join("\n").trim();
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function searchIssuesOrPrs(gh: GhRunner, cwd: string, params: GhParams, kind: "is:issue" | "is:pr", signal?: AbortSignal): Promise<string> {
|
|
266
|
+
const limit = resolveSearchLimit(params.limit);
|
|
267
|
+
const command = kind === "is:pr" ? "prs" : "issues";
|
|
268
|
+
const dateField = resolveSearchDateField(command, params.dateField);
|
|
269
|
+
const dateQualifier = buildSearchDateQualifier(dateField, params.since, params.until);
|
|
270
|
+
const displayQuery = composeSearchQuery([params.query, dateQualifier]);
|
|
271
|
+
const repo = await resolveSearchRepoScope(gh, cwd, normalizeOptionalString(params.repo), displayQuery, signal);
|
|
272
|
+
const scope = searchScope(repo);
|
|
273
|
+
const apiQuery = composeSearchQuery([displayQuery, scope.qualifier, kind]);
|
|
274
|
+
const args = buildGhApiSearchArgs("issues", apiQuery, limit, { host: scope.host });
|
|
275
|
+
const response = await gh.json<GhApiSearchResponse<GhApiSearchIssueItem>>(cwd, args, signal);
|
|
276
|
+
const items = response.items ?? [];
|
|
277
|
+
return formatSearchResults(kind === "is:pr" ? "pull requests" : "issues", displayQuery, repo, items);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export async function executeSearchIssues(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
281
|
+
return await searchIssuesOrPrs(gh, cwd, params, "is:issue", signal);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export async function executeSearchPrs(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
285
|
+
return await searchIssuesOrPrs(gh, cwd, params, "is:pr", signal);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export async function executeSearchCode(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
289
|
+
const query = requireNonEmpty(params.query, "query");
|
|
290
|
+
if (params.since !== undefined || params.until !== undefined) {
|
|
291
|
+
throw new Error("search_code does not support since/until; GitHub code search has no date qualifier.");
|
|
292
|
+
}
|
|
293
|
+
const limit = resolveSearchLimit(params.limit);
|
|
294
|
+
const repo = await resolveSearchRepoScope(gh, cwd, normalizeOptionalString(params.repo), query, signal);
|
|
295
|
+
const scope = searchScope(repo);
|
|
296
|
+
const apiQuery = composeSearchQuery([query, scope.qualifier]);
|
|
297
|
+
const args = buildGhApiSearchArgs("code", apiQuery, limit, {
|
|
298
|
+
host: scope.host,
|
|
299
|
+
extraHeaders: ["Accept: application/vnd.github.text-match+json"],
|
|
300
|
+
});
|
|
301
|
+
const response = await gh.json<GhApiSearchResponse<GhApiSearchCodeItem>>(cwd, args, signal);
|
|
302
|
+
return formatSearchCodeResults(query, repo, response.items ?? []);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export async function executeSearchCommits(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
306
|
+
const limit = resolveSearchLimit(params.limit);
|
|
307
|
+
const dateField = resolveSearchDateField("commits", params.dateField);
|
|
308
|
+
const dateQualifier = buildSearchDateQualifier(dateField, params.since, params.until);
|
|
309
|
+
const displayQuery = composeSearchQuery([params.query, dateQualifier]);
|
|
310
|
+
const repo = await resolveSearchRepoScope(gh, cwd, normalizeOptionalString(params.repo), displayQuery, signal);
|
|
311
|
+
const scope = searchScope(repo);
|
|
312
|
+
const apiQuery = composeSearchQuery([displayQuery, scope.qualifier]);
|
|
313
|
+
const args = buildGhApiSearchArgs("commits", apiQuery, limit, { host: scope.host });
|
|
314
|
+
const response = await gh.json<GhApiSearchResponse<GhApiSearchCommitItem>>(cwd, args, signal);
|
|
315
|
+
return formatSearchCommitsResults(displayQuery, repo, response.items ?? []);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export async function executeSearchRepos(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
319
|
+
const limit = resolveSearchLimit(params.limit);
|
|
320
|
+
const dateField = resolveSearchDateField("repos", params.dateField);
|
|
321
|
+
const dateQualifier = buildSearchDateQualifier(dateField, params.since, params.until);
|
|
322
|
+
const query = composeSearchQuery([params.query, dateQualifier]);
|
|
323
|
+
const args = buildGhApiSearchArgs("repositories", query, limit);
|
|
324
|
+
const response = await gh.json<GhApiSearchResponse<GhApiSearchRepoItem>>(cwd, args, signal);
|
|
325
|
+
return formatSearchReposResults(query, response.items ?? []);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ── repo_view (OMP gh-view.ts) ──
|
|
329
|
+
|
|
330
|
+
export const GH_REPO_FIELDS = [
|
|
331
|
+
"nameWithOwner", "description", "url", "defaultBranchRef", "homepageUrl", "forkCount",
|
|
332
|
+
"isArchived", "isFork", "primaryLanguage", "repositoryTopics", "stargazerCount",
|
|
333
|
+
"updatedAt", "viewerPermission", "visibility",
|
|
334
|
+
].join(",");
|
|
335
|
+
|
|
336
|
+
interface GhRepoViewData {
|
|
337
|
+
nameWithOwner?: string; description?: string; url?: string;
|
|
338
|
+
defaultBranchRef?: { name?: string }; homepageUrl?: string; forkCount?: number;
|
|
339
|
+
isArchived?: boolean; isFork?: boolean; primaryLanguage?: { name?: string };
|
|
340
|
+
repositoryTopics?: { name?: string; topic?: { name?: string } }[]; stargazerCount?: number;
|
|
341
|
+
updatedAt?: string; viewerPermission?: string; visibility?: string;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function formatRepoView(data: GhRepoViewData, input: { repo?: string; branch?: string }): string {
|
|
345
|
+
const lines: string[] = [];
|
|
346
|
+
const name = data.nameWithOwner ?? input.repo ?? "GitHub Repository";
|
|
347
|
+
lines.push(`# ${name}`, "");
|
|
348
|
+
lines.push(normalizeText(data.description) || "No description provided.", "");
|
|
349
|
+
pushLine(lines, "URL", data.url);
|
|
350
|
+
pushLine(lines, "Default branch", data.defaultBranchRef?.name);
|
|
351
|
+
pushLine(lines, "Branch", normalizeOptionalString(input.branch));
|
|
352
|
+
pushLine(lines, "Visibility", data.visibility);
|
|
353
|
+
pushLine(lines, "Viewer permission", data.viewerPermission);
|
|
354
|
+
pushLine(lines, "Primary language", data.primaryLanguage?.name);
|
|
355
|
+
pushLine(lines, "Stars", data.stargazerCount);
|
|
356
|
+
pushLine(lines, "Forks", data.forkCount);
|
|
357
|
+
pushLine(lines, "Archived", data.isArchived);
|
|
358
|
+
pushLine(lines, "Fork", data.isFork);
|
|
359
|
+
pushLine(lines, "Updated", data.updatedAt);
|
|
360
|
+
pushLine(lines, "Homepage", data.homepageUrl);
|
|
361
|
+
const topics = data.repositoryTopics?.map((t) => t.name ?? t.topic?.name).filter((v): v is string => Boolean(v)).join(", ");
|
|
362
|
+
pushLine(lines, "Topics", topics || undefined);
|
|
363
|
+
return lines.join("\n").trim();
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export async function executeRepoView(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
367
|
+
const repo = normalizeOptionalString(params.repo);
|
|
368
|
+
const branch = normalizeOptionalString(params.branch);
|
|
369
|
+
const args = ["repo", "view"];
|
|
370
|
+
if (repo) args.push(repo);
|
|
371
|
+
if (branch) args.push("--branch", branch);
|
|
372
|
+
args.push("--json", GH_REPO_FIELDS);
|
|
373
|
+
const data = await gh.json<GhRepoViewData>(cwd, args, signal);
|
|
374
|
+
return formatRepoView(data, { repo, branch });
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// ── file_read (OMP gh.ts executeFileRead) ──
|
|
378
|
+
|
|
379
|
+
interface GhContentsFile {
|
|
380
|
+
type?: string; encoding?: string; size?: number; content?: string; html_url?: string | null;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const BINARY_SNIFF_BYTES = 8000;
|
|
384
|
+
|
|
385
|
+
function isProbablyBinary(bytes: Buffer): boolean {
|
|
386
|
+
const n = Math.min(bytes.length, BINARY_SNIFF_BYTES);
|
|
387
|
+
for (let i = 0; i < n; i++) {
|
|
388
|
+
if (bytes[i] === 0) return true;
|
|
389
|
+
}
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const IMAGE_MIME: Record<string, string> = {
|
|
394
|
+
png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp",
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
export async function executeFileRead(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<{ text: string; image?: { data: string; mimeType: string } }> {
|
|
398
|
+
const repo = await resolveGitHubRepoVia(gh, cwd, normalizeOptionalString(params.repo), undefined, signal);
|
|
399
|
+
const filePath = requireNonEmpty(params.path, "path");
|
|
400
|
+
if (filePath.startsWith("/")) throw new Error("path must be repository-relative");
|
|
401
|
+
const branch = normalizeOptionalString(params.branch);
|
|
402
|
+
const endpointPath = filePath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
|
|
403
|
+
const ref = parseRepoRef(repo);
|
|
404
|
+
const args = [
|
|
405
|
+
"api",
|
|
406
|
+
...ghApiHostArgs(ref),
|
|
407
|
+
`/repos/${ref.slug}/contents/${endpointPath}`,
|
|
408
|
+
"--method", "GET",
|
|
409
|
+
"-H", "Accept: application/vnd.github+json",
|
|
410
|
+
"-H", "Accept-Encoding: identity",
|
|
411
|
+
];
|
|
412
|
+
if (branch) args.push("-f", `ref=${branch}`);
|
|
413
|
+
let response: GhContentsFile;
|
|
414
|
+
try {
|
|
415
|
+
response = await gh.json<GhContentsFile>(cwd, args, signal, { repoProvided: true });
|
|
416
|
+
} catch (error) {
|
|
417
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
418
|
+
throw new Error(`GitHub file read failed for '${repo}@${branch ?? "HEAD"}:${filePath}': ${message}`);
|
|
419
|
+
}
|
|
420
|
+
const fallbackHost = ref.host ?? "github.com";
|
|
421
|
+
const sourceUrl = response.html_url || `https://${fallbackHost}/${ref.slug}/blob/${encodeURIComponent(branch ?? "HEAD")}/${endpointPath}`;
|
|
422
|
+
if (response.encoding !== "base64" || typeof response.content !== "string") {
|
|
423
|
+
return { text: `[GitHub did not return file bytes for '${filePath}'. Open ${sourceUrl} to view it.]` };
|
|
424
|
+
}
|
|
425
|
+
const encoded = response.content.replaceAll(/\s/g, "");
|
|
426
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
427
|
+
const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
|
|
428
|
+
const mime = IMAGE_MIME[ext];
|
|
429
|
+
if (mime && !isProbablyBinary(bytes)) {
|
|
430
|
+
return { text: `Image file: ${filePath}`, image: { data: encoded, mimeType: mime } };
|
|
431
|
+
}
|
|
432
|
+
if (isProbablyBinary(bytes)) {
|
|
433
|
+
return { text: `[Cannot read binary file '${filePath}' (${bytes.length} bytes); not valid UTF-8 text. Open ${sourceUrl} to view it.]` };
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
437
|
+
if (text.length > 100_000) {
|
|
438
|
+
return { text: `${text.slice(0, 100_000)}\n[truncated after 100 KB — open ${sourceUrl} for the full file]` };
|
|
439
|
+
}
|
|
440
|
+
return { text };
|
|
441
|
+
} catch {
|
|
442
|
+
return { text: `[Cannot read binary file '${filePath}' (${bytes.length} bytes); not valid UTF-8 text. Open ${sourceUrl} to view it.]` };
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** resolveGitHubRepo via the runner seam (tests inject; prod passes realGh). */
|
|
447
|
+
async function resolveGitHubRepoVia(gh: GhRunner, cwd: string, repo: string | undefined, urlRepo: string | undefined, signal?: AbortSignal): Promise<string> {
|
|
448
|
+
if (repo && urlRepo && repo !== urlRepo) throw new Error("URL repository does not match the provided repo");
|
|
449
|
+
if (repo) return repo;
|
|
450
|
+
if (urlRepo) return urlRepo;
|
|
451
|
+
try {
|
|
452
|
+
return await resolveDefaultRepoVia(gh, cwd, signal);
|
|
453
|
+
} catch (err) {
|
|
454
|
+
throw new Error(`${err instanceof Error ? err.message : String(err)}\nGitHub repository context is unavailable. Pass \`repo\` explicitly or run the tool inside a GitHub checkout.`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// ── pr_view (OMP gh-view.ts) ──
|
|
459
|
+
|
|
460
|
+
export const GH_PR_FIELDS = [
|
|
461
|
+
"author", "baseRefName", "body", "createdAt", "files", "headRefName", "isDraft",
|
|
462
|
+
"labels", "mergeStateStatus", "number", "reviews", "reviewDecision", "state", "title", "updatedAt", "url",
|
|
463
|
+
].join(",");
|
|
464
|
+
|
|
465
|
+
interface GhPrFile { path?: string; changeType?: string; additions?: number; deletions?: number }
|
|
466
|
+
interface GhPrReview { author?: GhApiUser | null; body?: string; submittedAt?: string; state?: string; commit?: { oid?: string } }
|
|
467
|
+
interface GhPrViewData {
|
|
468
|
+
number?: number; title?: string; state?: string; isDraft?: boolean; author?: GhApiUser | null;
|
|
469
|
+
baseRefName?: string; headRefName?: string; body?: string; createdAt?: string; updatedAt?: string;
|
|
470
|
+
labels?: GhApiLabel[]; mergeStateStatus?: string; reviewDecision?: string; url?: string;
|
|
471
|
+
files?: GhPrFile[]; reviews?: GhPrReview[];
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function formatPrFiles(files: GhPrFile[] | undefined): string[] {
|
|
475
|
+
if (!files || files.length === 0) return [];
|
|
476
|
+
const lines: string[] = [`## Files (${files.length})`, ""];
|
|
477
|
+
for (const file of files.slice(0, FILE_PREVIEW_LIMIT)) {
|
|
478
|
+
lines.push(`- ${file.path ?? "(unknown file)"} [${file.changeType ?? "CHANGED"}] (+${file.additions ?? 0} -${file.deletions ?? 0})`);
|
|
479
|
+
}
|
|
480
|
+
if (files.length > FILE_PREVIEW_LIMIT) lines.push(`[…${files.length - FILE_PREVIEW_LIMIT} files elided…]`);
|
|
481
|
+
return lines;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function capBody(body: string | undefined): string {
|
|
485
|
+
const text = normalizeText(body) || "No description provided.";
|
|
486
|
+
return text.length > BODY_CAP ? `${text.slice(0, BODY_CAP)}\n[body truncated after ${BODY_CAP} chars]` : text;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export function formatPrView(data: GhPrViewData, input: { pr?: string }): string {
|
|
490
|
+
const lines: string[] = [];
|
|
491
|
+
lines.push(`# Pull Request #${data.number ?? input.pr ?? "current"}: ${data.title ?? "Untitled"}`, "");
|
|
492
|
+
pushLine(lines, "State", data.state);
|
|
493
|
+
pushLine(lines, "Draft", data.isDraft);
|
|
494
|
+
pushLine(lines, "Author", formatAuthor(data.author));
|
|
495
|
+
pushLine(lines, "Base", data.baseRefName);
|
|
496
|
+
pushLine(lines, "Head", data.headRefName);
|
|
497
|
+
pushLine(lines, "Review decision", data.reviewDecision);
|
|
498
|
+
pushLine(lines, "Merge state", data.mergeStateStatus);
|
|
499
|
+
pushLine(lines, "Created", data.createdAt);
|
|
500
|
+
pushLine(lines, "Updated", data.updatedAt);
|
|
501
|
+
pushLine(lines, "Labels", formatLabels(data.labels));
|
|
502
|
+
pushLine(lines, "URL", data.url);
|
|
503
|
+
lines.push("", "## Body", "", capBody(data.body));
|
|
504
|
+
const fileSection = formatPrFiles(data.files);
|
|
505
|
+
if (fileSection.length > 0) lines.push("", ...fileSection);
|
|
506
|
+
if (data.reviews && data.reviews.length > 0) {
|
|
507
|
+
lines.push("", `## Reviews (${data.reviews.length})`, "");
|
|
508
|
+
for (const review of data.reviews) {
|
|
509
|
+
const author = formatAuthor(review.author) ?? "unknown";
|
|
510
|
+
const submittedAt = review.submittedAt ? ` - ${review.submittedAt}` : "";
|
|
511
|
+
const state = review.state ? ` [${review.state}]` : "";
|
|
512
|
+
lines.push(`### ${author}${submittedAt}${state}`, "");
|
|
513
|
+
lines.push(capBody(review.body), "");
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return lines.join("\n").trim();
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export async function executePrView(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
520
|
+
const pr = requireNonEmpty(params.pr, "pr");
|
|
521
|
+
let repo = normalizeOptionalString(params.repo);
|
|
522
|
+
// A full PR URL embeds the repo — prefer it, pass the URL as the identifier.
|
|
523
|
+
const urlMatch = /^https:\/\/([^/]+)\/([^/]+\/[^/]+)\/pull\/(\d+)/.exec(pr);
|
|
524
|
+
if (urlMatch) {
|
|
525
|
+
repo = repo ?? formatRepoRef(urlMatch[1], urlMatch[2]);
|
|
526
|
+
}
|
|
527
|
+
if (!repo) {
|
|
528
|
+
repo = await resolveGitHubRepoVia(gh, cwd, undefined, undefined, signal);
|
|
529
|
+
}
|
|
530
|
+
const args = ["pr", "view", pr];
|
|
531
|
+
appendRepoFlag(args, repo, pr);
|
|
532
|
+
args.push("--json", GH_PR_FIELDS);
|
|
533
|
+
const data = await gh.json<GhPrViewData>(cwd, args, signal, { repoProvided: true });
|
|
534
|
+
return formatPrView(data, { pr });
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// ── pr_diff (OMP gh-pr-diff.ts, lean) ──
|
|
538
|
+
|
|
539
|
+
export async function executePrDiff(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<string> {
|
|
540
|
+
const pr = requireNonEmpty(params.pr, "pr");
|
|
541
|
+
let repo = normalizeOptionalString(params.repo);
|
|
542
|
+
const urlMatch = /^https:\/\/([^/]+)\/([^/]+\/[^/]+)\/pull\/(\d+)/.exec(pr);
|
|
543
|
+
if (urlMatch) repo = repo ?? formatRepoRef(urlMatch[1], urlMatch[2]);
|
|
544
|
+
if (!repo) {
|
|
545
|
+
repo = await resolveGitHubRepoVia(gh, cwd, undefined, undefined, signal);
|
|
546
|
+
}
|
|
547
|
+
const args = ["pr", "diff", pr];
|
|
548
|
+
appendRepoFlag(args, repo, pr);
|
|
549
|
+
const diff = await gh.text(cwd, args, signal, { repoProvided: true });
|
|
550
|
+
if (diff.length > 100_000) {
|
|
551
|
+
return `${diff.slice(0, 100_000)}\n[diff truncated after 100 KB]`;
|
|
552
|
+
}
|
|
553
|
+
return diff;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ── run_watch (OMP gh-run-watch.ts, lean poller) ──
|
|
557
|
+
|
|
558
|
+
export const RUN_WATCH_TAIL_DEFAULT = 15;
|
|
559
|
+
export const RUN_WATCH_TAIL_MAX = 200;
|
|
560
|
+
export const RUN_WATCH_INTERVAL_DEFAULT = 3;
|
|
561
|
+
export const RUN_WATCH_INTERVAL_SLOW = 15;
|
|
562
|
+
export const RUN_WATCH_FAST_WINDOW_MS = 60_000;
|
|
563
|
+
|
|
564
|
+
const RUN_URL_PATTERN = /^https:\/\/([^/]+)\/([^/]+\/[^/]+)\/actions\/runs\/(\d+)(?:\/.*)?$/;
|
|
565
|
+
const RUN_SUCCESS_CONCLUSIONS = new Set(["success", "neutral", "skipped"]);
|
|
566
|
+
const RUN_FAILURE_CONCLUSIONS = new Set(["failure", "timed_out", "cancelled", "action_required", "startup_failure"]);
|
|
567
|
+
const JOB_FAILURE_CONCLUSIONS = new Set(["failure", "timed_out", "cancelled", "action_required"]);
|
|
568
|
+
|
|
569
|
+
export function resolveTailLimit(value: number | undefined): number {
|
|
570
|
+
if (value === undefined) return RUN_WATCH_TAIL_DEFAULT;
|
|
571
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error("tail must be a positive number");
|
|
572
|
+
return Math.min(Math.floor(value), RUN_WATCH_TAIL_MAX);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
export function parseRunReference(value: string | undefined): { repo?: string; runId?: number } {
|
|
576
|
+
const run = normalizeOptionalString(value);
|
|
577
|
+
if (!run) return {};
|
|
578
|
+
if (/^\d+$/.test(run)) return { runId: Number(run) };
|
|
579
|
+
const match = run.match(RUN_URL_PATTERN);
|
|
580
|
+
if (!match) throw new Error("run must be a numeric workflow run ID or a full GitHub Actions run URL");
|
|
581
|
+
return { repo: formatRepoRef(match[1], match[2]), runId: Number(match[3]) };
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
interface GhActionsJobApi {
|
|
585
|
+
id?: number; name?: string; status?: string; conclusion?: string;
|
|
586
|
+
started_at?: string; completed_at?: string; html_url?: string;
|
|
587
|
+
}
|
|
588
|
+
interface GhActionsRunApi {
|
|
589
|
+
id?: number; name?: string; display_title?: string; status?: string; conclusion?: string;
|
|
590
|
+
head_branch?: string; head_sha?: string; created_at?: string; updated_at?: string; html_url?: string;
|
|
591
|
+
}
|
|
592
|
+
interface GhRunJobSnapshot {
|
|
593
|
+
id: number; name: string; status?: string; conclusion?: string;
|
|
594
|
+
startedAt?: string; completedAt?: string; url?: string;
|
|
595
|
+
}
|
|
596
|
+
interface GhRunSnapshot {
|
|
597
|
+
id: number; workflowName?: string; displayTitle?: string; status?: string; conclusion?: string;
|
|
598
|
+
branch?: string; headSha?: string; createdAt?: string; updatedAt?: string; url?: string;
|
|
599
|
+
jobs: GhRunJobSnapshot[];
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
export function isFailedJob(job: GhRunJobSnapshot): boolean {
|
|
603
|
+
return job.conclusion !== undefined && JOB_FAILURE_CONCLUSIONS.has(job.conclusion);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
export function getRunOutcome(value: string | undefined): "success" | "failure" | "pending" {
|
|
607
|
+
if (!value) return "pending";
|
|
608
|
+
if (RUN_SUCCESS_CONCLUSIONS.has(value)) return "success";
|
|
609
|
+
if (RUN_FAILURE_CONCLUSIONS.has(value)) return "failure";
|
|
610
|
+
return "pending";
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
async function fetchRunJobs(gh: GhRunner, cwd: string, repo: string, runId: number, signal?: AbortSignal): Promise<GhRunJobSnapshot[]> {
|
|
614
|
+
const ref = parseRepoRef(repo);
|
|
615
|
+
const response = await gh.json<{ jobs?: GhActionsJobApi[]; total_count?: number }>(
|
|
616
|
+
cwd,
|
|
617
|
+
["api", ...ghApiHostArgs(ref), "--method", "GET", `/repos/${ref.slug}/actions/runs/${runId}/jobs?per_page=100`],
|
|
618
|
+
signal,
|
|
619
|
+
{ repoProvided: true },
|
|
620
|
+
);
|
|
621
|
+
return (response.jobs ?? [])
|
|
622
|
+
.filter((job): job is GhActionsJobApi & { id: number } => typeof job.id === "number")
|
|
623
|
+
.map((job) => ({
|
|
624
|
+
id: job.id,
|
|
625
|
+
name: normalizeOptionalString(job.name) ?? `job-${job.id}`,
|
|
626
|
+
status: normalizeOptionalString(job.status),
|
|
627
|
+
conclusion: normalizeOptionalString(job.conclusion),
|
|
628
|
+
startedAt: normalizeOptionalString(job.started_at),
|
|
629
|
+
completedAt: normalizeOptionalString(job.completed_at),
|
|
630
|
+
url: normalizeOptionalString(job.html_url),
|
|
631
|
+
}));
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export async function fetchRunSnapshot(gh: GhRunner, cwd: string, repo: string, runId: number, signal?: AbortSignal): Promise<GhRunSnapshot> {
|
|
635
|
+
const ref = parseRepoRef(repo);
|
|
636
|
+
const run = await gh.json<GhActionsRunApi>(cwd, ["api", ...ghApiHostArgs(ref), "--method", "GET", `/repos/${ref.slug}/actions/runs/${runId}`], signal, { repoProvided: true });
|
|
637
|
+
const jobs = await fetchRunJobs(gh, cwd, repo, runId, signal);
|
|
638
|
+
if (typeof run.id !== "number") throw new Error("GitHub Actions run response did not include a run ID.");
|
|
639
|
+
return {
|
|
640
|
+
id: run.id,
|
|
641
|
+
workflowName: normalizeOptionalString(run.name),
|
|
642
|
+
displayTitle: normalizeOptionalString(run.display_title),
|
|
643
|
+
status: normalizeOptionalString(run.status),
|
|
644
|
+
conclusion: normalizeOptionalString(run.conclusion),
|
|
645
|
+
branch: normalizeOptionalString(run.head_branch),
|
|
646
|
+
headSha: normalizeOptionalString(run.head_sha),
|
|
647
|
+
createdAt: normalizeOptionalString(run.created_at),
|
|
648
|
+
updatedAt: normalizeOptionalString(run.updated_at),
|
|
649
|
+
url: normalizeOptionalString(run.html_url),
|
|
650
|
+
jobs,
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function renderJobsSection(jobs: GhRunJobSnapshot[]): string[] {
|
|
655
|
+
const lines: string[] = [`## Jobs (${jobs.length})`, ""];
|
|
656
|
+
for (const job of jobs) {
|
|
657
|
+
const dur = job.startedAt && job.completedAt
|
|
658
|
+
? ` (${Math.max(1, Math.round((Date.parse(job.completedAt) - Date.parse(job.startedAt)) / 1000))}s)`
|
|
659
|
+
: "";
|
|
660
|
+
lines.push(`- ${job.name}: ${job.status ?? "?"}${job.conclusion ? ` / ${job.conclusion}` : ""}${dur}`);
|
|
661
|
+
}
|
|
662
|
+
return lines;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function formatRunWatchResult(repo: string, run: GhRunSnapshot, failedJobLogs: { name: string; tail?: string }[]): string {
|
|
666
|
+
const failedJobs = run.jobs.filter(isFailedJob);
|
|
667
|
+
const lines: string[] = [`# GitHub Actions Run #${run.id}`, ""];
|
|
668
|
+
pushLine(lines, "Repository", repo);
|
|
669
|
+
pushLine(lines, "Workflow", run.workflowName);
|
|
670
|
+
pushLine(lines, "Title", run.displayTitle);
|
|
671
|
+
pushLine(lines, "Branch", run.branch);
|
|
672
|
+
pushLine(lines, "Status", run.status);
|
|
673
|
+
pushLine(lines, "Conclusion", run.conclusion);
|
|
674
|
+
pushLine(lines, "URL", run.url);
|
|
675
|
+
lines.push("", ...renderJobsSection(run.jobs));
|
|
676
|
+
if (failedJobs.length > 0) {
|
|
677
|
+
lines.push("", `## Failed job logs (tail)`, "");
|
|
678
|
+
for (const log of failedJobLogs) {
|
|
679
|
+
lines.push(`### ${log.name}`, "");
|
|
680
|
+
lines.push(log.tail ?? "(log unavailable)", "");
|
|
681
|
+
}
|
|
682
|
+
lines.push("Run failed.");
|
|
683
|
+
} else if (getRunOutcome(run.conclusion) === "success") {
|
|
684
|
+
lines.push("", "All jobs passed.");
|
|
685
|
+
} else {
|
|
686
|
+
lines.push("", "Run completed without successful jobs, but no failed job logs were available.");
|
|
687
|
+
}
|
|
688
|
+
return lines.join("\n").trim();
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function tailLogLines(log: string, tail: number): string | undefined {
|
|
692
|
+
const normalized = normalizeBlock(log);
|
|
693
|
+
if (!normalized) return undefined;
|
|
694
|
+
return normalized.split("\n").slice(-tail).join("\n").trimEnd();
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
|
|
698
|
+
new Promise((resolveP, rejectP) => {
|
|
699
|
+
const timer = setTimeout(resolveP, ms);
|
|
700
|
+
signal?.addEventListener("abort", () => {
|
|
701
|
+
clearTimeout(timer);
|
|
702
|
+
rejectP(new Error("Operation aborted"));
|
|
703
|
+
}, { once: true });
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Poll a workflow run until it completes; on failure tail each failed job's
|
|
708
|
+
* logs. Watch budget comes from `timeoutMs` (the tool's overall deadline —
|
|
709
|
+
* the caller passes gh-cli's 5-min window here).
|
|
710
|
+
*/
|
|
711
|
+
export async function executeRunWatch(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal, timeoutMs = 600_000): Promise<string> {
|
|
712
|
+
const runReference = parseRunReference(params.run);
|
|
713
|
+
const runId = runReference.runId;
|
|
714
|
+
if (runId === undefined) throw new Error("run_watch requires `run` (workflow run ID or Actions run URL)");
|
|
715
|
+
const repo = await resolveGitHubRepoVia(gh, cwd, normalizeOptionalString(params.repo), runReference.repo, signal);
|
|
716
|
+
const tail = resolveTailLimit(params.tail);
|
|
717
|
+
const deadline = Date.now() + Math.min(timeoutMs, 5 * 60_000 - 5_000);
|
|
718
|
+
const watchStartMs = Date.now();
|
|
719
|
+
const intervalSeconds = () => (Date.now() - watchStartMs < RUN_WATCH_FAST_WINDOW_MS ? RUN_WATCH_INTERVAL_DEFAULT : RUN_WATCH_INTERVAL_SLOW);
|
|
720
|
+
|
|
721
|
+
let pollCount = 0;
|
|
722
|
+
for (;;) {
|
|
723
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
724
|
+
pollCount += 1;
|
|
725
|
+
const run = await fetchRunSnapshot(gh, cwd, repo, runId, signal);
|
|
726
|
+
const failedJobs = run.jobs.filter(isFailedJob);
|
|
727
|
+
const runCompleted = run.status === "completed";
|
|
728
|
+
|
|
729
|
+
if (runCompleted || failedJobs.length > 0 || Date.now() >= deadline) {
|
|
730
|
+
if (Date.now() >= deadline && !runCompleted) {
|
|
731
|
+
return `${formatRunWatchResult(repo, run, [])}\n\nNote: watch budget elapsed while the run was still ${run.status}. Re-invoke run_watch with the same run id to keep watching.`;
|
|
732
|
+
}
|
|
733
|
+
const failedJobLogs: { name: string; tail?: string }[] = [];
|
|
734
|
+
const ref = parseRepoRef(repo);
|
|
735
|
+
for (const job of failedJobs) {
|
|
736
|
+
const r = await gh.run(cwd, ["api", ...ghApiHostArgs(ref), `/repos/${ref.slug}/actions/jobs/${job.id}/logs`], signal);
|
|
737
|
+
failedJobLogs.push({ name: job.name, tail: r.exitCode === 0 ? tailLogLines(r.stdout, tail) : undefined });
|
|
738
|
+
}
|
|
739
|
+
return formatRunWatchResult(repo, run, failedJobLogs);
|
|
740
|
+
}
|
|
741
|
+
await sleep(intervalSeconds() * 1000, signal);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** The dispatcher — maps op → executor. Order mirrors OMP's switch. */
|
|
746
|
+
export async function executeOp(op: string, gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<{ text: string; image?: { data: string; mimeType: string } }> {
|
|
747
|
+
switch (op) {
|
|
748
|
+
case "repo_view":
|
|
749
|
+
return { text: await executeRepoView(gh, cwd, params, signal) };
|
|
750
|
+
case "file_read":
|
|
751
|
+
return await executeFileRead(gh, cwd, params, signal);
|
|
752
|
+
case "pr_view":
|
|
753
|
+
return { text: await executePrView(gh, cwd, params, signal) };
|
|
754
|
+
case "pr_diff":
|
|
755
|
+
return { text: await executePrDiff(gh, cwd, params, signal) };
|
|
756
|
+
case "search_issues":
|
|
757
|
+
return { text: await executeSearchIssues(gh, cwd, params, signal) };
|
|
758
|
+
case "search_prs":
|
|
759
|
+
return { text: await executeSearchPrs(gh, cwd, params, signal) };
|
|
760
|
+
case "search_code":
|
|
761
|
+
return { text: await executeSearchCode(gh, cwd, params, signal) };
|
|
762
|
+
case "search_commits":
|
|
763
|
+
return { text: await executeSearchCommits(gh, cwd, params, signal) };
|
|
764
|
+
case "search_repos":
|
|
765
|
+
return { text: await executeSearchRepos(gh, cwd, params, signal) };
|
|
766
|
+
case "run_watch":
|
|
767
|
+
return { text: await executeRunWatch(gh, cwd, params, signal, readRunWatchTimeoutSecs() * 1000) };
|
|
768
|
+
default:
|
|
769
|
+
throw new Error(`Unknown github op: ${op}`);
|
|
770
|
+
}
|
|
771
|
+
}
|