@ferronhooi/aihub 0.0.1 → 0.1.0-next.3

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.
Files changed (57) hide show
  1. package/dist/cli.js +10 -9
  2. package/dist/commands/comments.js +32 -0
  3. package/dist/commands/doctor.js +21 -0
  4. package/dist/commands/init.js +18 -0
  5. package/dist/commands/pr.js +75 -0
  6. package/dist/commands/skills.js +44 -0
  7. package/dist/lib/ado.js +158 -0
  8. package/dist/lib/auth.js +68 -0
  9. package/dist/lib/clients.js +26 -0
  10. package/dist/lib/comments.js +119 -0
  11. package/dist/lib/context.js +9 -0
  12. package/dist/lib/doctor.js +118 -0
  13. package/dist/lib/errors.js +7 -0
  14. package/dist/lib/git.js +79 -0
  15. package/dist/lib/init.js +157 -0
  16. package/dist/lib/install.js +141 -0
  17. package/dist/lib/pack.js +48 -0
  18. package/dist/lib/pr.js +131 -0
  19. package/dist/lib/schema.js +56 -0
  20. package/dist/lib/team.js +24 -0
  21. package/dist/lib/templates.js +184 -0
  22. package/dist/router.js +48 -0
  23. package/dist/tools/lintSkills.js +166 -0
  24. package/dist/tools/lintSkills.test.js +70 -0
  25. package/pack/commands/copilot/cherry-pick.prompt.md +6 -0
  26. package/pack/commands/copilot/pr-update.prompt.md +6 -0
  27. package/pack/commands/copilot/pr.prompt.md +6 -0
  28. package/pack/commands/copilot/refine.prompt.md +6 -0
  29. package/pack/commands/copilot/review.prompt.md +6 -0
  30. package/pack/commands/copilot/story.prompt.md +6 -0
  31. package/pack/commands/copilot/watch.prompt.md +6 -0
  32. package/pack/commands/opencode/cherry-pick.md +5 -0
  33. package/pack/commands/opencode/pr-update.md +5 -0
  34. package/pack/commands/opencode/pr.md +5 -0
  35. package/pack/commands/opencode/refine.md +5 -0
  36. package/pack/commands/opencode/review.md +5 -0
  37. package/pack/commands/opencode/story.md +5 -0
  38. package/pack/commands/opencode/watch.md +5 -0
  39. package/pack/skills/_shared/assets/commit-template.nl.txt +5 -0
  40. package/pack/skills/_shared/assets/commit-template.txt +5 -0
  41. package/pack/skills/_shared/assets/pull_request_template.md +16 -0
  42. package/pack/skills/_shared/assets/pull_request_template.nl.md +16 -0
  43. package/pack/skills/_shared/assets/story-template.md +12 -0
  44. package/pack/skills/_shared/assets/story-template.nl.md +12 -0
  45. package/pack/skills/_shared/references/team.schema.yaml +41 -0
  46. package/pack/skills/branch-sync/SKILL.md +31 -0
  47. package/pack/skills/implement/SKILL.md +25 -0
  48. package/pack/skills/pipeline-fix/SKILL.md +29 -0
  49. package/pack/skills/pr-create/SKILL.md +29 -0
  50. package/pack/skills/pr-update/SKILL.md +28 -0
  51. package/pack/skills/pr-watch/SKILL.md +30 -0
  52. package/pack/skills/release/SKILL.md +35 -0
  53. package/pack/skills/review-process/SKILL.md +35 -0
  54. package/pack/skills/start-here/SKILL.md +36 -0
  55. package/pack/skills/story-create/SKILL.md +28 -0
  56. package/pack/skills/story-refine/SKILL.md +28 -0
  57. package/package.json +13 -3
package/dist/cli.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
- // Entry point. Commands are added per workflow in src/commands/.
3
- const [, , ...args] = process.argv;
4
- if (args[0] === "--version") {
5
- console.log("0.0.0");
6
- }
7
- else {
8
- console.log("aihub: under construction. Commands: pr, comments, cherry-pick, branch, story, pipeline, batch, work, init, skills, doctor.");
9
- }
10
- export {};
2
+ // Entry point. Commands are registered in src/router.ts.
3
+ import { main } from "./router.js";
4
+ const code = await main(process.argv.slice(2), {
5
+ cwd: process.cwd(),
6
+ env: process.env,
7
+ fetch,
8
+ out: (l) => process.stdout.write(l + "\n"),
9
+ err: (l) => process.stderr.write(l + "\n"),
10
+ });
11
+ process.exitCode = code;
@@ -0,0 +1,32 @@
1
+ import { parseArgs } from "node:util";
2
+ import { commentsGet, commentsReply } from "../lib/comments.js";
3
+ import { AihubError } from "../lib/errors.js";
4
+ export async function run(argv, ctx) {
5
+ const [sub, ...rest] = argv;
6
+ let v;
7
+ try {
8
+ v = parseArgs({
9
+ args: rest,
10
+ options: {
11
+ pr: { type: "string" },
12
+ "include-resolved": { type: "boolean" },
13
+ "replies-file": { type: "string" },
14
+ json: { type: "boolean" },
15
+ },
16
+ }).values;
17
+ }
18
+ catch (e) {
19
+ throw new AihubError(e.message);
20
+ }
21
+ if (sub === "get") {
22
+ ctx.out(await commentsGet(ctx, { pr: v.pr, includeResolved: !!v["include-resolved"], json: !!v.json }));
23
+ return;
24
+ }
25
+ if (sub === "reply") {
26
+ if (!v["replies-file"])
27
+ throw new AihubError("aihub comments reply needs --replies-file <file.yaml>");
28
+ ctx.out(await commentsReply(ctx, { pr: v.pr, repliesFile: v["replies-file"], json: !!v.json }));
29
+ return;
30
+ }
31
+ throw new AihubError("usage: aihub comments get|reply [flags]");
32
+ }
@@ -0,0 +1,21 @@
1
+ import { parseArgs } from "node:util";
2
+ import { AihubError } from "../lib/errors.js";
3
+ import { formatChecks, runChecks } from "../lib/doctor.js";
4
+ export async function run(argv, ctx) {
5
+ let json = false;
6
+ try {
7
+ json = !!parseArgs({ args: argv, options: { json: { type: "boolean" } } }).values.json;
8
+ }
9
+ catch (e) {
10
+ throw new AihubError(e.message);
11
+ }
12
+ const checks = runChecks(ctx);
13
+ if (json) {
14
+ ctx.out(JSON.stringify({ ok: checks.every((c) => c.status === "OK"), checks }));
15
+ return;
16
+ }
17
+ for (const l of formatChecks(checks))
18
+ ctx.out(l);
19
+ const bad = checks.filter((c) => c.status === "FIX").length;
20
+ ctx.out(bad ? `${bad} check(s) need a fix` : "all checks passed");
21
+ }
@@ -0,0 +1,18 @@
1
+ import { parseArgs } from "node:util";
2
+ import { AihubError } from "../lib/errors.js";
3
+ import { reportInit, runInit } from "../lib/init.js";
4
+ export async function run(argv, ctx) {
5
+ let v;
6
+ try {
7
+ v = parseArgs({
8
+ args: argv,
9
+ options: { repo: { type: "string" }, "no-pr": { type: "boolean" }, language: { type: "string" } },
10
+ }).values;
11
+ }
12
+ catch (e) {
13
+ throw new AihubError(e.message);
14
+ }
15
+ const r = await runInit(ctx, { repo: v.repo, noPr: !!v["no-pr"], language: v.language });
16
+ for (const l of reportInit(r))
17
+ ctx.out(l);
18
+ }
@@ -0,0 +1,75 @@
1
+ import { parseArgs } from "node:util";
2
+ import { AihubError } from "../lib/errors.js";
3
+ import { createPr, updatePr } from "../lib/pr.js";
4
+ function parse(argv, options) {
5
+ try {
6
+ return parseArgs({ args: argv, options, allowPositionals: true }).values;
7
+ }
8
+ catch (e) {
9
+ throw new AihubError(`${e.message}`);
10
+ }
11
+ }
12
+ function num(v, flag) {
13
+ if (v === undefined)
14
+ return undefined;
15
+ const n = Number(String(v).replace(/^AB#/i, ""));
16
+ if (!Number.isInteger(n) || n <= 0)
17
+ throw new AihubError(`${flag} must be a number`);
18
+ return n;
19
+ }
20
+ export async function run(argv, ctx) {
21
+ const [sub, ...rest] = argv;
22
+ if (sub === "create") {
23
+ const v = parse(rest, {
24
+ title: { type: "string" },
25
+ "body-file": { type: "string" },
26
+ target: { type: "string" },
27
+ draft: { type: "boolean" },
28
+ "work-item": { type: "string" },
29
+ "dry-run": { type: "boolean" },
30
+ json: { type: "boolean" },
31
+ });
32
+ ctx.out(await createPr(ctx, {
33
+ title: v.title,
34
+ bodyFile: v["body-file"],
35
+ target: v.target,
36
+ draft: v.draft,
37
+ workItem: num(v["work-item"], "--work-item"),
38
+ dryRun: v["dry-run"],
39
+ json: v.json,
40
+ }));
41
+ return;
42
+ }
43
+ if (sub === "update") {
44
+ const v = parse(rest, {
45
+ pr: { type: "string" },
46
+ "body-file": { type: "string" },
47
+ section: { type: "string" },
48
+ "append-file": { type: "string" },
49
+ "replace-file": { type: "string" },
50
+ title: { type: "string" },
51
+ draft: { type: "string" },
52
+ target: { type: "string" },
53
+ json: { type: "boolean" },
54
+ });
55
+ let draft;
56
+ if (v.draft !== undefined) {
57
+ if (v.draft !== "true" && v.draft !== "false")
58
+ throw new AihubError("--draft must be true or false");
59
+ draft = v.draft === "true";
60
+ }
61
+ ctx.out(await updatePr(ctx, {
62
+ pr: v.pr,
63
+ bodyFile: v["body-file"],
64
+ section: v.section,
65
+ appendFile: v["append-file"],
66
+ replaceFile: v["replace-file"],
67
+ title: v.title,
68
+ draft,
69
+ target: v.target,
70
+ json: v.json,
71
+ }));
72
+ return;
73
+ }
74
+ throw new AihubError("usage: aihub pr create|update [flags] (see README)");
75
+ }
@@ -0,0 +1,44 @@
1
+ import { parseArgs } from "node:util";
2
+ import { AihubError } from "../lib/errors.js";
3
+ import { repoRoot } from "../lib/git.js";
4
+ import { installClients, parseClients, uninstallClients } from "../lib/install.js";
5
+ function report(reports, out) {
6
+ for (const r of reports) {
7
+ const count = (a) => r.results.filter((x) => x.action === a).length;
8
+ out(`${r.client}: ${r.dir}`);
9
+ out(` created ${count("created")}, updated ${count("updated")}, unchanged ${count("unchanged")}, removed ${count("removed")}, skipped ${count("skipped")}`);
10
+ for (const s of r.results.filter((x) => x.action === "skipped"))
11
+ out(` skipped ${s.path} (${s.reason})`);
12
+ }
13
+ }
14
+ export async function run(argv, ctx) {
15
+ const [sub, ...rest] = argv;
16
+ if (sub !== "install" && sub !== "uninstall")
17
+ throw new AihubError("usage: aihub skills install|uninstall [--global] [--client opencode|github-copilot|codex|all]");
18
+ let v;
19
+ try {
20
+ v = parseArgs({ args: rest, options: { global: { type: "boolean" }, client: { type: "string" } } }).values;
21
+ }
22
+ catch (e) {
23
+ throw new AihubError(e.message);
24
+ }
25
+ let clients;
26
+ try {
27
+ clients = parseClients(v.client);
28
+ }
29
+ catch (e) {
30
+ throw new AihubError(e.message);
31
+ }
32
+ const global = !!v.global;
33
+ let root;
34
+ if (!global) {
35
+ try {
36
+ root = repoRoot(ctx.cwd);
37
+ }
38
+ catch {
39
+ throw new AihubError("not inside a git repository: run in a repository for a project install, or add --global");
40
+ }
41
+ }
42
+ const opts = { global, root };
43
+ report(sub === "install" ? installClients(clients, ctx.env, opts) : uninstallClients(clients, ctx.env, opts), ctx.out);
44
+ }
@@ -0,0 +1,158 @@
1
+ import { AihubError } from "./errors.js";
2
+ export function parseRemote(url) {
3
+ const u = url.trim();
4
+ const dec = (s) => decodeURIComponent(s);
5
+ const make = (org, project, repo) => ({
6
+ org: dec(org),
7
+ project: dec(project),
8
+ repo: dec(repo),
9
+ orgUrl: `https://dev.azure.com/${encodeURIComponent(dec(org))}`,
10
+ });
11
+ let m;
12
+ // SSH: git@ssh.dev.azure.com:v3/org/project/repo | org@vs-ssh.visualstudio.com:v3/org/project/repo
13
+ if ((m = /^(?:ssh:\/\/)?[^@\s]+@(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)[:/](?:v3\/)?([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(u))) {
14
+ return make(m[1], m[2], m[3]);
15
+ }
16
+ // HTTPS dev.azure.com/org/project/_git/repo (optional user@)
17
+ if ((m = /^https?:\/\/(?:[^@/]+@)?dev\.azure\.com\/([^/]+)\/([^/]+)\/_git\/([^/?#]+?)(?:\.git)?\/?(?:[?#].*)?$/.exec(u))) {
18
+ return make(m[1], m[2], m[3]);
19
+ }
20
+ // HTTPS org.visualstudio.com/[DefaultCollection/]project/_git/repo
21
+ if ((m = /^https?:\/\/(?:[^@/]+@)?([^./]+)\.visualstudio\.com\/(?:DefaultCollection\/)?([^/]+)\/_git\/([^/?#]+?)(?:\.git)?\/?(?:[?#].*)?$/.exec(u))) {
22
+ return make(m[1], m[2], m[3]);
23
+ }
24
+ throw new AihubError(`remote '${u}' is not an Azure DevOps remote (dev.azure.com or visualstudio.com)`);
25
+ }
26
+ export const API_VERSION = "7.1";
27
+ export class AdoClient {
28
+ remote;
29
+ auth;
30
+ fetchFn;
31
+ constructor(remote, auth, fetchFn = fetch) {
32
+ this.remote = remote;
33
+ this.auth = auth;
34
+ this.fetchFn = fetchFn;
35
+ }
36
+ repoPath() {
37
+ return `git/repositories/${encodeURIComponent(this.remote.repo)}`;
38
+ }
39
+ prUrl(id) {
40
+ const r = this.remote;
41
+ return `${r.orgUrl}/${encodeURIComponent(r.project)}/_git/${encodeURIComponent(r.repo)}/pullrequest/${id}`;
42
+ }
43
+ url(path, query = {}) {
44
+ const q = new URLSearchParams();
45
+ for (const [k, v] of Object.entries(query))
46
+ if (v !== undefined)
47
+ q.set(k, String(v));
48
+ q.set("api-version", API_VERSION);
49
+ return `${this.remote.orgUrl}/${encodeURIComponent(this.remote.project)}/_apis/${path}?${q.toString()}`;
50
+ }
51
+ async request(method, path, opts = {}) {
52
+ const res = await this.fetchFn(this.url(path, opts.query), {
53
+ method,
54
+ headers: {
55
+ Authorization: await this.auth(),
56
+ Accept: opts.raw ? "text/plain" : "application/json",
57
+ ...(opts.body !== undefined ? { "Content-Type": "application/json; charset=utf-8" } : {}),
58
+ },
59
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
60
+ });
61
+ const text = await res.text();
62
+ const ctype = res.headers.get("content-type") ?? "";
63
+ // Azure DevOps answers a bad/missing credential with 203 + an HTML sign-in page.
64
+ if (res.status === 401 || res.status === 203 || (res.ok && !opts.raw && ctype.includes("text/html"))) {
65
+ throw new AihubError("not signed in to Azure DevOps: run 'az login' or set AIHUB_ADO_PAT");
66
+ }
67
+ if (!res.ok)
68
+ throw new AihubError(httpMessage(res.status, text, method, path));
69
+ if (opts.raw)
70
+ return { data: text, headers: res.headers };
71
+ return { data: (text ? JSON.parse(text) : {}), headers: res.headers };
72
+ }
73
+ get(path, query) {
74
+ return this.request("GET", path, { query }).then((r) => r.data);
75
+ }
76
+ /** GET a collection, following x-ms-continuationtoken. Returns all `value` items. */
77
+ async list(path, query = {}) {
78
+ const out = [];
79
+ let token = null;
80
+ for (let i = 0; i < 100; i++) {
81
+ const r = await this.request("GET", path, {
82
+ query: { ...query, ...(token ? { continuationToken: token } : {}) },
83
+ });
84
+ out.push(...(r.data.value ?? []));
85
+ token = r.headers.get("x-ms-continuationtoken");
86
+ if (!token)
87
+ break;
88
+ }
89
+ return out;
90
+ }
91
+ post(path, body, query) {
92
+ return this.request("POST", path, { body, query }).then((r) => r.data);
93
+ }
94
+ patch(path, body, query) {
95
+ return this.request("PATCH", path, { body, query }).then((r) => r.data);
96
+ }
97
+ getText(path, query) {
98
+ return this.request("GET", path, { query, raw: true }).then((r) => r.data);
99
+ }
100
+ }
101
+ function httpMessage(status, body, method, path) {
102
+ let detail = "";
103
+ try {
104
+ detail = JSON.parse(body).message ?? "";
105
+ }
106
+ catch {
107
+ detail = body.slice(0, 200);
108
+ }
109
+ detail = detail.replace(/\s+/g, " ").trim();
110
+ const p = path.split("?")[0];
111
+ if (status === 403)
112
+ return `Azure DevOps denied access (403): your account needs access to this repository${detail ? ` (${detail})` : ""}`;
113
+ if (status === 404)
114
+ return `Azure DevOps: not found (404) for ${method} ${p}${detail ? `: ${detail}` : ""}`;
115
+ return `Azure DevOps ${method} ${p} failed (${status})${detail ? `: ${detail}` : ""}`;
116
+ }
117
+ export const branchRef = (b) => (b.startsWith("refs/") ? b : `refs/heads/${b}`);
118
+ export const shortBranch = (r) => r.replace(/^refs\/heads\//, "");
119
+ export async function findActivePr(c, source, target) {
120
+ const prs = await c.list(`${c.repoPath()}/pullrequests`, {
121
+ "searchCriteria.sourceRefName": branchRef(source),
122
+ "searchCriteria.status": "active",
123
+ ...(target ? { "searchCriteria.targetRefName": branchRef(target) } : {}),
124
+ });
125
+ return prs[0];
126
+ }
127
+ export const getPr = (c, id) => c.get(`${c.repoPath()}/pullrequests/${id}`);
128
+ export async function repoDefaultBranch(c) {
129
+ const r = await c.get(c.repoPath());
130
+ return r.defaultBranch ? shortBranch(r.defaultBranch) : undefined;
131
+ }
132
+ export async function getWorkItemTitle(c, id) {
133
+ try {
134
+ const r = await c.get(`wit/workitems/${id}`, { fields: "System.Title" });
135
+ return r.fields?.["System.Title"];
136
+ }
137
+ catch {
138
+ return undefined;
139
+ }
140
+ }
141
+ /** PR ids linked to a work item through artifact links (vstfs:///Git/PullRequestId/<project>%2F<repo>%2F<id>). */
142
+ export async function getWorkItemPrIds(c, id) {
143
+ try {
144
+ const r = await c.get(`wit/workitems/${id}`, { $expand: "relations" });
145
+ const ids = [];
146
+ for (const rel of r.relations ?? []) {
147
+ if (rel.rel !== "ArtifactLink")
148
+ continue;
149
+ const m = /PullRequestId\/.*?(\d+)$/i.exec(decodeURIComponent(rel.url));
150
+ if (m)
151
+ ids.push(Number(m[1]));
152
+ }
153
+ return ids;
154
+ }
155
+ catch {
156
+ return [];
157
+ }
158
+ }
@@ -0,0 +1,68 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { AihubError } from "./errors.js";
6
+ export const ADO_RESOURCE = "499b84ac-1321-427f-aa17-267ca6975798";
7
+ export const defaultExec = (cmd, args, input) => {
8
+ const r = spawnSync(cmd, args, {
9
+ encoding: "utf8",
10
+ input,
11
+ shell: process.platform === "win32" && cmd === "az",
12
+ timeout: 30000,
13
+ });
14
+ if (r.error || r.status !== 0)
15
+ throw new Error(r.error?.message ?? (r.stderr || "").trim());
16
+ return r.stdout;
17
+ };
18
+ const basic = (pat) => `Basic ${Buffer.from(`:${pat}`).toString("base64")}`;
19
+ /** Order: PAT env -> az token (cached until expiry) -> git credential fill. */
20
+ export function makeAuth(deps = {}) {
21
+ const env = deps.env ?? process.env;
22
+ const exec = deps.exec ?? defaultExec;
23
+ const now = deps.now ?? Date.now;
24
+ const cacheFile = deps.cacheFile ?? join(tmpdir(), "aihub-az-token.json");
25
+ let cached;
26
+ return async () => {
27
+ if (cached)
28
+ return cached;
29
+ const pat = env.AIHUB_ADO_PAT || env.AZURE_DEVOPS_EXT_PAT;
30
+ if (pat)
31
+ return (cached = basic(pat));
32
+ try {
33
+ if (existsSync(cacheFile)) {
34
+ const c = JSON.parse(readFileSync(cacheFile, "utf8"));
35
+ if (c.token && c.expiresAt - 120_000 > now())
36
+ return (cached = `Bearer ${c.token}`);
37
+ }
38
+ }
39
+ catch {
40
+ /* ignore a broken cache */
41
+ }
42
+ try {
43
+ const out = exec("az", ["account", "get-access-token", "--resource", ADO_RESOURCE, "--output", "json"]);
44
+ const j = JSON.parse(out);
45
+ const expiresAt = j.expires_on ? Number(j.expires_on) * 1000 : Date.parse(j.expiresOn ?? "") || now() + 30 * 60_000;
46
+ try {
47
+ writeFileSync(cacheFile, JSON.stringify({ token: j.accessToken, expiresAt }), { mode: 0o600 });
48
+ }
49
+ catch {
50
+ /* cache is optional */
51
+ }
52
+ return (cached = `Bearer ${j.accessToken}`);
53
+ }
54
+ catch {
55
+ /* fall through to git credential */
56
+ }
57
+ try {
58
+ const out = exec("git", ["credential", "fill"], "protocol=https\nhost=dev.azure.com\n\n");
59
+ const pw = /^password=(.*)$/m.exec(out)?.[1]?.trim();
60
+ if (pw)
61
+ return (cached = basic(pw));
62
+ }
63
+ catch {
64
+ /* fall through */
65
+ }
66
+ throw new AihubError("not signed in to Azure DevOps: run 'az login' or set AIHUB_ADO_PAT");
67
+ };
68
+ }
@@ -0,0 +1,26 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ export const CLIENTS = ["opencode", "github-copilot", "codex"];
4
+ const home = (env) => env.HOME || env.USERPROFILE || homedir();
5
+ /** Global (per user) or project (inside `root`) locations of a client. Environment overrides come from `env`. */
6
+ export function clientDirs(client, env, opts) {
7
+ if (opts.global) {
8
+ if (client === "opencode") {
9
+ const base = env.OPENCODE_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(home(env), ".config"), "opencode");
10
+ return { skills: join(base, "skills"), commands: { dir: join(base, "command"), source: "opencode" } };
11
+ }
12
+ if (client === "codex") {
13
+ const base = env.CODEX_HOME || join(home(env), ".codex");
14
+ return { skills: join(base, "skills"), commands: { dir: join(base, "prompts"), source: "opencode" } };
15
+ }
16
+ return { skills: join(env.COPILOT_HOME || join(home(env), ".copilot"), "skills") };
17
+ }
18
+ const root = opts.root ?? ".";
19
+ if (client === "opencode") {
20
+ return { skills: join(root, ".opencode", "skills"), commands: { dir: join(root, ".opencode", "command"), source: "opencode" } };
21
+ }
22
+ if (client === "github-copilot") {
23
+ return { skills: join(root, ".github", "skills"), commands: { dir: join(root, ".github", "prompts"), source: "copilot" } };
24
+ }
25
+ return { skills: join(root, ".agents", "skills") };
26
+ }
@@ -0,0 +1,119 @@
1
+ import { parse } from "yaml";
2
+ import { repoClient } from "./context.js";
3
+ import { AihubError } from "./errors.js";
4
+ import { resolvePr } from "./pr.js";
5
+ import { readUtf8 } from "./team.js";
6
+ const OPEN = new Set(["active", "pending", ""]);
7
+ export const REPLY_STATUSES = ["fixed", "wontFix", "closed", "active"];
8
+ const CONTEXT = 2;
9
+ export async function getThreads(client, prId, sourceCommit, includeResolved) {
10
+ const threads = await client.list(`${client.repoPath()}/pullrequests/${prId}/threads`);
11
+ const files = new Map();
12
+ const out = [];
13
+ for (const t of threads) {
14
+ if (t.isDeleted)
15
+ continue;
16
+ const comments = (t.comments ?? []).filter((c) => !c.isDeleted && (c.commentType ?? "text") !== "system");
17
+ if (!comments.length)
18
+ continue;
19
+ const status = t.status ?? "active";
20
+ if (!includeResolved && !OPEN.has(status))
21
+ continue;
22
+ const file = t.threadContext?.filePath;
23
+ const line = t.threadContext?.rightFileStart?.line;
24
+ let code;
25
+ if (file && line && sourceCommit) {
26
+ if (!files.has(file))
27
+ files.set(file, await fetchLines(client, file, sourceCommit));
28
+ const lines = files.get(file);
29
+ if (lines) {
30
+ const end = t.threadContext?.rightFileEnd?.line ?? line;
31
+ code = [];
32
+ for (let n = Math.max(1, line - CONTEXT); n <= Math.min(lines.length, end + CONTEXT); n++)
33
+ code.push({ n, text: lines[n - 1] });
34
+ }
35
+ }
36
+ out.push({
37
+ threadId: t.id,
38
+ status,
39
+ file,
40
+ line,
41
+ code,
42
+ comments: comments.map((c) => ({ id: c.id, author: c.author?.displayName ?? "?", text: (c.content ?? "").trim() })),
43
+ });
44
+ }
45
+ return out;
46
+ }
47
+ async function fetchLines(client, path, commit) {
48
+ try {
49
+ const text = await client.getText(`${client.repoPath()}/items`, {
50
+ path,
51
+ "versionDescriptor.version": commit,
52
+ "versionDescriptor.versionType": "commit",
53
+ $format: "text",
54
+ });
55
+ return text.replace(/^/, "").replace(/\r\n/g, "\n").split("\n");
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
61
+ export function formatThreads(prId, threads) {
62
+ if (!threads.length)
63
+ return `!${prId}: no open comment threads`;
64
+ const lines = [`!${prId}: ${threads.length} thread${threads.length === 1 ? "" : "s"}`];
65
+ for (const t of threads) {
66
+ const where = t.file ? `${t.file}${t.line ? `:${t.line}` : ""}` : "(general)";
67
+ const [first, ...rest] = t.comments;
68
+ lines.push(`[${t.threadId}] ${where} (${t.status}) ${first.author}: ${oneLine(first.text)}`);
69
+ if (t.code)
70
+ for (const c of t.code)
71
+ lines.push(` ${c.n === t.line ? ">" : " "} ${String(c.n).padStart(4)} ${c.text}`);
72
+ for (const r of rest)
73
+ lines.push(` - ${r.author}: ${oneLine(r.text)}`);
74
+ }
75
+ return lines.join("\n");
76
+ }
77
+ const oneLine = (s) => s.replace(/\s*\n\s*/g, " / ");
78
+ export async function commentsGet(ctx, o) {
79
+ const { root, client } = repoClient(ctx);
80
+ const pr = await resolvePr(ctx, client, root, o.pr);
81
+ const threads = await getThreads(client, pr.pullRequestId, pr.lastMergeSourceCommit?.commitId, !!o.includeResolved);
82
+ return o.json ? JSON.stringify({ pr: pr.pullRequestId, threads }) : formatThreads(pr.pullRequestId, threads);
83
+ }
84
+ export function parseReplies(yamlText) {
85
+ const doc = parse(yamlText);
86
+ const list = Array.isArray(doc) ? doc : doc?.replies;
87
+ if (!Array.isArray(list))
88
+ throw new AihubError("replies file must be a yaml list of {threadId, text, status}");
89
+ return list.map((r, i) => {
90
+ const threadId = Number(r.threadId);
91
+ if (!Number.isInteger(threadId) || threadId <= 0)
92
+ throw new AihubError(`replies[${i}]: threadId is missing or not a number`);
93
+ const status = r.status === undefined || r.status === null ? undefined : String(r.status);
94
+ if (status && !REPLY_STATUSES.includes(status)) {
95
+ throw new AihubError(`replies[${i}]: status '${status}' must be one of ${REPLY_STATUSES.join("|")}`);
96
+ }
97
+ const text = r.text === undefined || r.text === null ? undefined : String(r.text).trim();
98
+ if (!text && !status)
99
+ throw new AihubError(`replies[${i}]: needs text and/or status`);
100
+ return { threadId, text: text || undefined, status: status };
101
+ });
102
+ }
103
+ export async function commentsReply(ctx, o) {
104
+ const replies = parseReplies(readUtf8(o.repliesFile));
105
+ const { root, client } = repoClient(ctx);
106
+ const pr = await resolvePr(ctx, client, root, o.pr);
107
+ const base = `${client.repoPath()}/pullrequests/${pr.pullRequestId}/threads`;
108
+ const done = [];
109
+ for (const r of replies) {
110
+ if (r.text)
111
+ await client.post(`${base}/${r.threadId}/comments`, { content: r.text, parentCommentId: 1, commentType: "text" });
112
+ if (r.status)
113
+ await client.patch(`${base}/${r.threadId}`, { status: r.status });
114
+ done.push(`${r.threadId}${r.status ? `=${r.status}` : ""}`);
115
+ }
116
+ return o.json
117
+ ? JSON.stringify({ pr: pr.pullRequestId, replied: replies.map((r) => r.threadId) })
118
+ : `!${pr.pullRequestId}: ${replies.length} repl${replies.length === 1 ? "y" : "ies"} posted (${done.join(", ")})`;
119
+ }
@@ -0,0 +1,9 @@
1
+ import { AdoClient, parseRemote } from "./ado.js";
2
+ import { makeAuth } from "./auth.js";
3
+ import { remoteUrl, repoRoot } from "./git.js";
4
+ export function repoClient(ctx) {
5
+ const root = repoRoot(ctx.cwd);
6
+ const remote = parseRemote(remoteUrl(root));
7
+ const auth = makeAuth({ env: ctx.env, exec: ctx.exec, cacheFile: ctx.tokenCache });
8
+ return { root, client: new AdoClient(remote, auth, ctx.fetch) };
9
+ }