aboutsummaryrefslogtreecommitdiff
path: root/.pi/extensions/github-issues-autocomplete/index.ts
blob: 8106722623f68514ce18b59ad6f4d2d0d7a07b56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/**
 * `@issue:` GitHub issues and `@pr:` GitHub PRs autocomplete provider.
 *
 * On `@issue:<token>` in the input editor, suggests open issues from the current repo.
 * On `@pr:<token>` in the input editor, suggests open PRs from the current repo.
 *
 * Accepting a completion inserts the reference (e.g. `issue owner/repo#123` or `pr owner/repo#45`).
 * A `before_agent_start` nudge tells the agent how to fetch details with `gh`.
 *
 * Issues and PRs are fetched once on session start and cached in memory.
 */

import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import type {
  AutocompleteItem,
  AutocompleteProvider,
  AutocompleteSuggestions,
} from "@earendil-works/pi-tui";

// --- Constants ---

const ISSUE_PREFIX = "@issue";
const PR_PREFIX = "@pr";

/** Match `@issue`, `@issue:`, or `@issue:<token>` at end of text before cursor. */
const ISSUE_TOKEN_RE = /(?:^|\s)(@issue(?::\s*([^\s@]*))?)$/;

/** Match `@pr`, `@pr:`, or `@pr:<token>` at end of text before cursor. */
const PR_TOKEN_RE = /(?:^|\s)(@pr(?::\s*([^\s@]*))?)$/;

const MAX_SUGGESTIONS = 20;

// --- Types ---

interface RepoInfo {
  owner: string;
  repo: string;
  /** `owner/repo` string */
  fullName: string;
}

interface IssueInfo {
  number: number;
  title: string;
  labels: string;
  author: string;
  updatedAt: string;
}

interface PRInfo {
  number: number;
  title: string;
  author: string;
  headRefName: string;
  updatedAt: string;
  isDraft: boolean;
}

interface CachedData {
  repo: RepoInfo | null;
  issues: IssueInfo[];
  prs: PRInfo[];
}

function getCachePath(cwd: string): string {
  return join(cwd, ".pi", "cache", "github-refs.json");
}

async function readCache(cwd: string): Promise<CachedData> {
  try {
    const raw = await readFile(getCachePath(cwd), "utf8");
    const data = JSON.parse(raw) as CachedData;
    return {
      repo: data.repo ?? null,
      issues: Array.isArray(data.issues) ? data.issues : [],
      prs: Array.isArray(data.prs) ? data.prs : [],
    };
  } catch {
    return { repo: null, issues: [], prs: [] };
  }
}

async function writeCache(cwd: string, data: CachedData): Promise<void> {
  const cachePath = getCachePath(cwd);
  await mkdir(join(cwd, ".pi", "cache"), { recursive: true });
  await writeFile(cachePath, JSON.stringify(data, null, 2), "utf8");
}

// --- Shell helpers (use pi.exec) ---

async function fetchRepoName(
  exec: ExtensionAPI["exec"],
  cwd: string,
): Promise<RepoInfo | null> {
  const result = await exec("gh", ["repo", "view", "--json", "owner,name"], { cwd });

  if (result.code !== 0 || !result.stdout.trim()) return null;

  try {
    const data = JSON.parse(result.stdout) as {
      owner: { login: string };
      name: string;
    };
    const owner = data.owner?.login ?? "";
    const repo = data.name ?? "";
    if (!owner || !repo) return null;
    return { owner, repo, fullName: `${owner}/${repo}` };
  } catch {
    return null;
  }
}

async function fetchIssues(
  exec: ExtensionAPI["exec"],
  cwd: string,
): Promise<IssueInfo[]> {
  const result = await exec(
    "gh",
    ["issue", "list", "--json", "number,title,labels,author,updatedAt", "--limit", "50", "--state", "open"],
    { cwd },
  );

  if (result.code !== 0 || !result.stdout.trim()) return [];

  try {
    const items = JSON.parse(result.stdout) as Array<{
      number: number;
      title: string;
      labels: Array<{ name: string }>;
      author: { login: string };
      updatedAt: string;
    }>;

    return items.map((item) => ({
      number: item.number,
      title: item.title,
      labels: item.labels.map((l) => l.name).join(", "),
      author: item.author?.login ?? "",
      updatedAt: item.updatedAt,
    }));
  } catch {
    return [];
  }
}

async function fetchPRs(
  exec: ExtensionAPI["exec"],
  cwd: string,
): Promise<PRInfo[]> {
  const result = await exec(
    "gh",
    ["pr", "list", "--json", "number,title,author,headRefName,updatedAt,isDraft", "--limit", "50", "--state", "open"],
    { cwd },
  );

  if (result.code !== 0 || !result.stdout.trim()) return [];

  try {
    const items = JSON.parse(result.stdout || "[]") as Array<{
      number: number;
      title: string;
      author: { login: string };
      headRefName: string;
      updatedAt: string;
      isDraft: boolean;
    }>;

    return items.map((item) => ({
      number: item.number,
      title: item.title,
      author: item.author?.login ?? "",
      headRefName: item.headRefName,
      updatedAt: item.updatedAt,
      isDraft: item.isDraft,
    }));
  } catch {
    return [];
  }
}

/** Fetch all data needed for the session in parallel. */
async function fetchAll(
  exec: ExtensionAPI["exec"],
  cwd: string,
): Promise<CachedData> {
  const [repo, issues, prs] = await Promise.all([
    fetchRepoName(exec, cwd),
    fetchIssues(exec, cwd),
    fetchPRs(exec, cwd),
  ]);
  return { repo, issues, prs };
}

// --- Autocomplete replacement ---

function replaceAutocompletePrefix(
  lines: string[],
  cursorLine: number,
  cursorCol: number,
  prefix: string,
  value: string,
) {
  const currentLine = lines[cursorLine] ?? "";
  const beforePrefix = currentLine.slice(0, cursorCol - prefix.length);
  const afterCursor = currentLine.slice(cursorCol);
  const newLines = [...lines];
  newLines[cursorLine] = `${beforePrefix}${value}${afterCursor}`;

  return {
    lines: newLines,
    cursorLine,
    cursorCol: beforePrefix.length + value.length,
  };
}

function extractPrefixCandidate(
  textBeforeCursor: string,
  targetPrefix: string,
): string | undefined {
  const match = textBeforeCursor.match(/(^|\s)(@\S*)$/);
  const candidate = match?.[2];
  if (!candidate || !targetPrefix.startsWith(candidate)) return undefined;
  return candidate;
}

function createPrefixCompletionItem(
  value: string,
  label: string,
  description: string,
): AutocompleteItem {
  return { value, label, description };
}

// --- Provider factory ---

export function createGithubAutocompleteProvider(
  current: AutocompleteProvider,
  data: CachedData,
): AutocompleteProvider {
  return {
    async getSuggestions(
      lines: string[],
      cursorLine: number,
      cursorCol: number,
      options,
    ): Promise<AutocompleteSuggestions | null> {
      const currentLine = lines[cursorLine] ?? "";
      const textBeforeCursor = currentLine.slice(0, cursorCol);

      const issueMatch = textBeforeCursor.match(ISSUE_TOKEN_RE);
      const prMatch = textBeforeCursor.match(PR_TOKEN_RE);
      const issuePrefix = issueMatch?.[1];
      const prPrefix = prMatch?.[1];
      const issueToken = issueMatch ? issueMatch[2] ?? "" : undefined;
      const prToken = prMatch ? prMatch[2] ?? "" : undefined;

      // Neither complete prefix matched — check for partial prefix candidates first.
      // Do not await the built-in @file provider for @iss/@pr-like input: pi queues
      // autocomplete requests serially, so slow file scans can delay issue results.
      if (issueToken === undefined && prToken === undefined) {
        const prefixItems: AutocompleteItem[] = [];

        const issueCandidate = extractPrefixCandidate(textBeforeCursor, `${ISSUE_PREFIX}:`);
        if (issueCandidate !== undefined) {
          prefixItems.push(
            createPrefixCompletionItem(ISSUE_PREFIX, ISSUE_PREFIX, "GitHub issues"),
          );
        }

        const prCandidate = extractPrefixCandidate(textBeforeCursor, `${PR_PREFIX}:`);
        if (prCandidate !== undefined) {
          prefixItems.push(
            createPrefixCompletionItem(PR_PREFIX, PR_PREFIX, "GitHub pull requests"),
          );
        }

        if (prefixItems.length > 0) {
          return {
            items: prefixItems,
            prefix: issueCandidate ?? prCandidate ?? "",
          };
        }

        return current.getSuggestions(lines, cursorLine, cursorCol, options);
      }

      if (options.signal.aborted) return null;

      const repoPrefix = data.repo ? `${data.repo.fullName}#` : "#";

      // --- Issues ---
      if (issueToken !== undefined) {
        const tokenLower = issueToken.toLowerCase();
        const filtered = data.issues
          .filter(
            (i) =>
              i.title.toLowerCase().includes(tokenLower) ||
              String(i.number).includes(tokenLower),
          )
          .slice(0, MAX_SUGGESTIONS);

        if (filtered.length === 0) return null;

        const items: AutocompleteItem[] = filtered.map((i) => ({
          value: `issue ${repoPrefix}${i.number}`,
          label: `#${i.number} ${i.title}`,
          description: [i.labels, i.author].filter(Boolean).join(" · "),
        }));

        return { items, prefix: issuePrefix ?? `${ISSUE_PREFIX}:${issueToken}` };
      }

      // --- PRs ---
      if (prToken !== undefined) {
        const tokenLower = prToken.toLowerCase();
        const filtered = data.prs
          .filter(
            (p) =>
              p.title.toLowerCase().includes(tokenLower) ||
              String(p.number).includes(tokenLower) ||
              p.headRefName.toLowerCase().includes(tokenLower),
          )
          .slice(0, MAX_SUGGESTIONS);

        if (filtered.length === 0) return null;

        const items: AutocompleteItem[] = filtered.map((p) => ({
          value: `pr ${repoPrefix}${p.number}`,
          label: `#${p.number} ${p.title}`,
          description: [p.headRefName, p.author, p.isDraft ? "draft" : ""]
            .filter(Boolean)
            .join(" · "),
        }));

        return { items, prefix: prPrefix ?? `${PR_PREFIX}:${prToken}` };
      }

      return current.getSuggestions(lines, cursorLine, cursorCol, options);
    },

    applyCompletion(
      lines: string[],
      cursorLine: number,
      cursorCol: number,
      item: AutocompleteItem,
      prefix: string,
    ) {
      if (prefix.startsWith(ISSUE_PREFIX) || prefix.startsWith(PR_PREFIX)) {
        return replaceAutocompletePrefix(
          lines,
          cursorLine,
          cursorCol,
          prefix,
          item.value,
        );
      }

      // Prefix item completion (typing toward `@issue` or `@pr`)
      if (item.value === ISSUE_PREFIX || item.value === PR_PREFIX) {
        return replaceAutocompletePrefix(
          lines,
          cursorLine,
          cursorCol,
          prefix,
          item.value,
        );
      }

      return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
    },

    shouldTriggerFileCompletion(
      lines: string[],
      cursorLine: number,
      cursorCol: number,
    ) {
      const currentLine = lines[cursorLine] ?? "";
      const textBeforeCursor = currentLine.slice(0, cursorCol);
      if (
        textBeforeCursor.match(ISSUE_TOKEN_RE) ||
        textBeforeCursor.match(PR_TOKEN_RE)
      ) {
        return true;
      }
      return (
        current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ??
        true
      );
    },
  };
}

// --- Nudge on before_agent_start ---

/** Match `issue org/repo#123` or `issue #123` */
const ISSUE_REF_RE = /issue\s+(\S+?#(\d+))/g;
/** Match `pr org/repo#45` or `pr #45` */
const PR_REF_RE = /pr\s+(\S+?#(\d+))/g;

interface RefMatch {
  type: "issue" | "pr";
  /** Full reference string e.g. `owner/repo#123` */
  refs: string[];
}

function buildNudge(matches: RefMatch[]): string {
  const lines: string[] = [];

  for (const m of matches) {
    const uniqueRefs = [...new Set(m.refs)];
    if (m.type === "issue" && uniqueRefs.length > 0) {
      lines.push(
        `GitHub issues referenced: ${uniqueRefs.map((r) => `issue ${r}`).join(", ")}.`,
        `To fetch issue details, use: gh issue view <number> --json number,title,body,labels,author,assignees,comments`,
        `To list issues, use: gh issue list --json number,title,labels,author,updatedAt --state open`,
      );
    }
    if (m.type === "pr" && uniqueRefs.length > 0) {
      lines.push(
        `GitHub PRs referenced: ${uniqueRefs.map((r) => `pr ${r}`).join(", ")}.`,
        `To fetch PR details, use: gh pr view <number> --json number,title,body,headRefName,baseRefName,author,reviews,mergeable`,
        `To list PRs, use: gh pr list --json number,title,author,headRefName,updatedAt,isDraft --state open`,
      );
    }
  }

  return lines.join("\n");
}

// --- Extension entry point ---

export default async function (pi: ExtensionAPI) {
  pi.on("session_start", async (_event, ctx) => {
    const cwd = ctx.cwd;
    const data = await readCache(cwd);

    ctx.ui.addAutocompleteProvider((current) =>
      createGithubAutocompleteProvider(current, data),
    );

    void fetchAll(pi.exec, cwd).then(async (fresh) => {
      data.repo = fresh.repo;
      data.issues = fresh.issues;
      data.prs = fresh.prs;
      await writeCache(cwd, fresh);
    }).catch(() => {
      // Keep stale cache when gh is unavailable or slow.
    });
  });

  pi.on("before_agent_start", async (event) => {
    const text = event.prompt;

    const issueRefs: string[] = [];
    const prRefs: string[] = [];

    let match: RegExpExecArray | null;

    const issueRe = new RegExp(ISSUE_REF_RE.source, "g");
    match = issueRe.exec(text);
    while (match !== null) {
      if (match[1]) issueRefs.push(match[1]);
      match = issueRe.exec(text);
    }

    const prRe = new RegExp(PR_REF_RE.source, "g");
    match = prRe.exec(text);
    while (match !== null) {
      if (match[1]) prRefs.push(match[1]);
      match = prRe.exec(text);
    }

    if (issueRefs.length === 0 && prRefs.length === 0) return;

    const nudge = buildNudge([
      { type: "issue", refs: issueRefs },
      { type: "pr", refs: prRefs },
    ]);

    return {
      message: {
        customType: "github-ref:nudge",
        content: nudge,
        display: false,
      },
    } as const;
  });
}