@geminixiang/mikan 1.0.0-beta.8 → 1.0.0-beta.9

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 (45) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/adapter.d.ts +1 -1
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapter.js.map +1 -1
  5. package/dist/adapters/github/bot.d.ts +23 -1
  6. package/dist/adapters/github/bot.d.ts.map +1 -1
  7. package/dist/adapters/github/bot.js +142 -5
  8. package/dist/adapters/github/bot.js.map +1 -1
  9. package/dist/adapters/github/client.d.ts +24 -1
  10. package/dist/adapters/github/client.d.ts.map +1 -1
  11. package/dist/adapters/github/client.js +45 -0
  12. package/dist/adapters/github/client.js.map +1 -1
  13. package/dist/adapters/github/context.d.ts.map +1 -1
  14. package/dist/adapters/github/context.js +9 -1
  15. package/dist/adapters/github/context.js.map +1 -1
  16. package/dist/adapters/github/repo.d.ts +19 -0
  17. package/dist/adapters/github/repo.d.ts.map +1 -0
  18. package/dist/adapters/github/repo.js +58 -0
  19. package/dist/adapters/github/repo.js.map +1 -0
  20. package/dist/adapters/github/types.d.ts +32 -0
  21. package/dist/adapters/github/types.d.ts.map +1 -1
  22. package/dist/adapters/github/types.js.map +1 -1
  23. package/dist/agent.d.ts +2 -2
  24. package/dist/agent.d.ts.map +1 -1
  25. package/dist/agent.js +10 -2
  26. package/dist/agent.js.map +1 -1
  27. package/dist/main.js +9 -0
  28. package/dist/main.js.map +1 -1
  29. package/dist/runtime/conversation-runtime.js +1 -1
  30. package/dist/runtime/conversation-runtime.js.map +1 -1
  31. package/dist/runtime/types.d.ts +3 -1
  32. package/dist/runtime/types.d.ts.map +1 -1
  33. package/dist/runtime/types.js.map +1 -1
  34. package/dist/tools/github-pr.d.ts +22 -0
  35. package/dist/tools/github-pr.d.ts.map +1 -0
  36. package/dist/tools/github-pr.js +53 -0
  37. package/dist/tools/github-pr.js.map +1 -0
  38. package/dist/tools/index.d.ts +2 -1
  39. package/dist/tools/index.d.ts.map +1 -1
  40. package/dist/tools/index.js +4 -0
  41. package/dist/tools/index.js.map +1 -1
  42. package/dist/types.d.ts +19 -0
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js.map +1 -1
  45. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -9,6 +9,31 @@ any release.
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [1.0.0-beta.9]
13
+
14
+ ### Added
15
+
16
+ - Clone GitHub repositories into conversation workspaces and check out pull request heads.
17
+ - Add a `github_pr` tool that pushes agent changes from `pi/*` branches and opens pull requests.
18
+
19
+ ### Changed
20
+
21
+ - Require GitHub App Contents read and write permission for repository automation.
22
+ - Post completed GitHub responses as single comments instead of streaming edits.
23
+
24
+ ### Fixed
25
+
26
+ - Keep GitHub issue context inside the history recency window.
27
+
28
+ ### Security
29
+
30
+ - Require commenters to have repository write permission or higher before triggering the agent.
31
+ - Keep installation tokens out of sandboxes and restrict agent pushes to non-force `pi/*` branches.
32
+
33
+ ### Tests
34
+
35
+ - Add coverage for GitHub repository checkout, permission gating, pull request creation, and branch restrictions.
36
+
12
37
  ## [1.0.0-beta.8]
13
38
 
14
39
  ### Added
package/dist/adapter.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export type { MessagingBot, ConversationContext, ConversationEvent, MessagingEventHandler, ChatAdapter, ConversationMessage, ConversationResponder, ChatToolResult, ConversationKind, MessagingInfo, PlatformName, PlatformNotifier, PlatformReactor, RunningSession, } from "./types.js";
1
+ export type { MessagingBot, ConversationContext, ConversationEvent, MessagingEventHandler, ChatAdapter, ConversationMessage, ConversationResponder, ChatToolResult, ConversationKind, GithubPrRequest, GithubPrResult, MessagingInfo, PlatformName, PlatformNotifier, PlatformPrCreator, PlatformReactor, RunningSession, } from "./types.js";
2
2
  //# sourceMappingURL=adapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,qBAAqB,EACrB,WAAW,EACX,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,EACd,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,cAAc,GACf,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,qBAAqB,EACrB,WAAW,EACX,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,cAAc,GACf,MAAM,YAAY,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"","sourcesContent":["export type {\n MessagingBot,\n ConversationContext,\n ConversationEvent,\n MessagingEventHandler,\n ChatAdapter,\n ConversationMessage,\n ConversationResponder,\n ChatToolResult,\n ConversationKind,\n MessagingInfo,\n PlatformName,\n PlatformNotifier,\n PlatformReactor,\n RunningSession,\n} from \"./types.js\";\n"]}
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"","sourcesContent":["export type {\n MessagingBot,\n ConversationContext,\n ConversationEvent,\n MessagingEventHandler,\n ChatAdapter,\n ConversationMessage,\n ConversationResponder,\n ChatToolResult,\n ConversationKind,\n GithubPrRequest,\n GithubPrResult,\n MessagingInfo,\n PlatformName,\n PlatformNotifier,\n PlatformPrCreator,\n PlatformReactor,\n RunningSession,\n} from \"./types.js\";\n"]}
@@ -1,4 +1,4 @@
1
- import type { ConversationEvent, MessagingBot, MessagingEventHandler, MessagingInfo } from "../../adapter.js";
1
+ import type { ConversationEvent, GithubPrRequest, GithubPrResult, MessagingBot, MessagingEventHandler, MessagingInfo } from "../../adapter.js";
2
2
  import { GithubClient } from "./client.js";
3
3
  import type { GithubBotConfig, GithubConversationRef } from "./types.js";
4
4
  /** GitHub comment bodies cap at 65536 chars; leave headroom for markup. */
@@ -9,9 +9,11 @@ export declare class GithubMessagingBot implements MessagingBot {
9
9
  private readonly handler;
10
10
  private readonly config;
11
11
  private appSlug;
12
+ private botEmail;
12
13
  private watchedRepos;
13
14
  private queues;
14
15
  private repoState;
16
+ private permissionCache;
15
17
  private pollInFlight;
16
18
  constructor(handler: MessagingEventHandler, config: GithubBotConfig, client?: GithubClient);
17
19
  start(): Promise<void>;
@@ -35,7 +37,27 @@ export declare class GithubMessagingBot implements MessagingBot {
35
37
  private isMentioned;
36
38
  private stripMention;
37
39
  private isParticipating;
40
+ /**
41
+ * True when `user` holds at least write permission on the repo. Fails
42
+ * closed: a failed lookup denies the trigger (and logs) rather than
43
+ * letting an unverified commenter drive the agent.
44
+ */
45
+ private hasTriggerPermission;
38
46
  private handleIncoming;
39
47
  private logIssueContext;
48
+ private repoDir;
49
+ /**
50
+ * Clone the conversation's repo into its dir (bind-mounted into the
51
+ * sandbox) using an ephemeral contents:read token that never leaves the
52
+ * host. Non-fatal: a failed clone degrades to the pre-clone experience.
53
+ */
54
+ private ensureRepoClone;
55
+ /**
56
+ * Backs the `github_pr` tool: push a `pi/*` branch the agent prepared in
57
+ * the conversation's clone, then open a pull request as the App. The write
58
+ * token is minted per call, scoped to this one repo, and never enters the
59
+ * sandbox.
60
+ */
61
+ pushAndCreatePr(conversationId: string, request: GithubPrRequest): Promise<GithubPrResult>;
40
62
  }
41
63
  //# sourceMappingURL=bot.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bot.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/bot.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,iBAAiB,EACjB,YAAY,EACZ,qBAAqB,EACrB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,IAAI,CAAC,CAqB1B;YAEa,QAAQ;IA4DtB,OAAO,CAAC,aAAa;IAkBrB,OAAO,CAAC,gBAAgB;IAkBxB,0EAA0E;IAC1E,OAAO,CAAC,cAAc;IAItB,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,YAAY;IAKpB,OAAO,CAAC,eAAe;IAIvB;;;;OAIG;YACW,oBAAoB;YA+BpB,cAAc;YA0Fd,eAAe;IAqC7B,OAAO,CAAC,OAAO;IAIf;;;;OAIG;YACW,eAAe;IA8B7B;;;;;OAKG;IACG,eAAe,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CA6B/F;CACF"}
@@ -10,6 +10,7 @@ import { appendBotResponseLog, appendChannelLog, MessagingEventQueue, resolveSto
10
10
  import { processMessageIntake } from "../intake.js";
11
11
  import { GithubClient, githubIsRateLimited } from "./client.js";
12
12
  import { createGithubAdapters } from "./context.js";
13
+ import { cloneRepo, GITHUB_PUSH_BRANCH_PATTERN, pushBranch } from "./repo.js";
13
14
  import { buildGithubConversationId, GITHUB_ISSUE_BODY_TS, parseGithubConversationId, } from "./ids.js";
14
15
  const SyncStateSchema = Type.Object({
15
16
  repos: Type.Record(Type.String(), Type.Object({
@@ -26,6 +27,23 @@ const SyncStateSchema = Type.Object({
26
27
  */
27
28
  const POLL_OVERLAP_MS = 5 * 60 * 1000;
28
29
  const MAX_SEEN_IDS = 5000;
30
+ /** Effective role → rank, for the trigger-permission gate. */
31
+ const PERMISSION_RANK = {
32
+ none: 0,
33
+ read: 1,
34
+ triage: 2,
35
+ write: 3,
36
+ maintain: 4,
37
+ admin: 5,
38
+ };
39
+ /**
40
+ * Commenters need write or better to trigger the agent. Fixed, not a config
41
+ * knob: it guards public repos (anyone can comment there), and the people who
42
+ * ask an agent to change code are exactly the people with push access.
43
+ */
44
+ const REQUIRED_TRIGGER_RANK = PERMISSION_RANK.write;
45
+ /** Permission lookups are cached this long per repo+user. */
46
+ const PERMISSION_CACHE_TTL_MS = 5 * 60 * 1000;
29
47
  const githubRetry = (fn) => withRetry(fn, { isRateLimited: githubIsRateLimited });
30
48
  /** GitHub comment bodies cap at 65536 chars; leave headroom for markup. */
31
49
  export const GITHUB_MAX_COMMENT_LENGTH = 60000;
@@ -79,9 +97,11 @@ function issueNumberFromUrl(issueUrl) {
79
97
  export class GithubMessagingBot {
80
98
  constructor(handler, config, client) {
81
99
  this.appSlug = null;
100
+ this.botEmail = null;
82
101
  this.watchedRepos = [];
83
102
  this.queues = new Map();
84
103
  this.repoState = new Map();
104
+ this.permissionCache = new Map();
85
105
  this.pollInFlight = false;
86
106
  this.handler = handler;
87
107
  this.config = config;
@@ -98,6 +118,16 @@ export class GithubMessagingBot {
98
118
  // ==========================================================================
99
119
  async start() {
100
120
  this.appSlug = await this.client.getAppSlug();
121
+ // Canonical noreply author email (<user-id>+<login>@users.noreply.github.com)
122
+ // so the bot's commits link to its avatar/profile; degrade to a plain
123
+ // noreply spelling when the lookup fails.
124
+ try {
125
+ const botUserId = await this.client.getUserId(`${this.appSlug}[bot]`);
126
+ this.botEmail = `${botUserId}+${this.appSlug}[bot]@users.noreply.github.com`;
127
+ }
128
+ catch {
129
+ this.botEmail = `${this.appSlug}[bot]@users.noreply.github.com`;
130
+ }
101
131
  this.watchedRepos =
102
132
  this.config.repos.length > 0
103
133
  ? parseRepoList(this.config.repos)
@@ -258,6 +288,7 @@ export class GithubMessagingBot {
258
288
  user: issue.user.login,
259
289
  text: `# ${issue.title}\n\n${issue.body ?? ""}`.trim(),
260
290
  createdAt: issue.created_at,
291
+ isPr: Boolean(issue.pull_request),
261
292
  });
262
293
  }
263
294
  const comments = (await this.client.listIssueCommentsSince(repo.owner, repo.repo, since)) ?? [];
@@ -329,6 +360,34 @@ export class GithubMessagingBot {
329
360
  isParticipating(conversationId) {
330
361
  return existsSync(join(this.config.workingDir, conversationId, "log.jsonl"));
331
362
  }
363
+ /**
364
+ * True when `user` holds at least write permission on the repo. Fails
365
+ * closed: a failed lookup denies the trigger (and logs) rather than
366
+ * letting an unverified commenter drive the agent.
367
+ */
368
+ async hasTriggerPermission(ref, user) {
369
+ const cacheKey = `${ref.owner}/${ref.repo}#${user}`;
370
+ const cached = this.permissionCache.get(cacheKey);
371
+ if (cached && Date.now() < cached.expiresAt) {
372
+ return cached.rank >= REQUIRED_TRIGGER_RANK;
373
+ }
374
+ let rank;
375
+ try {
376
+ const role = await githubRetry(() => this.client.getCollaboratorPermission(ref.owner, ref.repo, user));
377
+ // Custom role_name values are unrankable; the legacy permission field
378
+ // still carries their closest standard mapping, so take the stronger.
379
+ rank = Math.max(PERMISSION_RANK[role.role_name ?? ""] ?? 0, PERMISSION_RANK[role.permission] ?? 0);
380
+ }
381
+ catch (err) {
382
+ log.logWarning(`GitHub: permission lookup failed for ${user} on ${ref.owner}/${ref.repo}; denying trigger`, err instanceof Error ? err.message : String(err));
383
+ return false;
384
+ }
385
+ this.permissionCache.set(cacheKey, {
386
+ rank,
387
+ expiresAt: Date.now() + PERMISSION_CACHE_TTL_MS,
388
+ });
389
+ return rank >= REQUIRED_TRIGGER_RANK;
390
+ }
332
391
  async handleIncoming(item) {
333
392
  const conversationId = buildGithubConversationId(item.ref);
334
393
  const mentioned = this.isMentioned(item.text);
@@ -338,6 +397,12 @@ export class GithubMessagingBot {
338
397
  // busy repos don't grow conversation dirs for untouched issues.
339
398
  if (!mentioned && !participating)
340
399
  return;
400
+ // Permission gate: on public repos anyone can comment, so a mention from
401
+ // anyone below write permission is ignored entirely (no log, no state).
402
+ if (!(await this.hasTriggerPermission(item.ref, item.user))) {
403
+ log.logInfo(`GitHub: ignoring ${conversationId} comment from ${item.user} (below write permission)`);
404
+ return;
405
+ }
341
406
  const cleanedText = this.stripMention(item.text);
342
407
  const sessionKey = resolveChatSessionKey({
343
408
  conversationId,
@@ -364,10 +429,16 @@ export class GithubMessagingBot {
364
429
  }
365
430
  return;
366
431
  }
367
- // First contact via a comment: log the issue title/body first so the
368
- // session history starts with what the thread is about.
369
- if (!participating && item.ts !== GITHUB_ISSUE_BODY_TS) {
370
- await this.logIssueContext(item.ref, conversationId, item.createdAt);
432
+ // First contact: log the issue title/body ahead of the comment so the
433
+ // session history starts with what the thread is about, then clone the
434
+ // repo into the conversation dir so the agent has the code.
435
+ if (!participating) {
436
+ let isPr = item.isPr ?? false;
437
+ if (item.ts !== GITHUB_ISSUE_BODY_TS) {
438
+ const issue = await this.logIssueContext(item.ref, conversationId, item.createdAt);
439
+ isPr = Boolean(issue?.pull_request);
440
+ }
441
+ await this.ensureRepoClone(item.ref, conversationId, isPr);
371
442
  }
372
443
  const eventBase = {
373
444
  type: item.ts === GITHUB_ISSUE_BODY_TS ? "issue" : "message",
@@ -407,7 +478,7 @@ export class GithubMessagingBot {
407
478
  }
408
479
  catch (err) {
409
480
  log.logWarning(`GitHub: could not fetch issue context for ${conversationId}`, err instanceof Error ? err.message : String(err));
410
- return;
481
+ return null;
411
482
  }
412
483
  // Dated just before the triggering comment, NOT issue.created_at: history
413
484
  // sync date-sorts entries and drops anything older than its recency
@@ -424,6 +495,72 @@ export class GithubMessagingBot {
424
495
  attachments: [],
425
496
  isMessagingBot: false,
426
497
  });
498
+ return issue;
499
+ }
500
+ // ==========================================================================
501
+ // Repo clone + pull requests
502
+ // ==========================================================================
503
+ repoDir(conversationId) {
504
+ return join(this.config.workingDir, conversationId, "repo");
505
+ }
506
+ /**
507
+ * Clone the conversation's repo into its dir (bind-mounted into the
508
+ * sandbox) using an ephemeral contents:read token that never leaves the
509
+ * host. Non-fatal: a failed clone degrades to the pre-clone experience.
510
+ */
511
+ async ensureRepoClone(ref, conversationId, isPr) {
512
+ const dir = this.repoDir(conversationId);
513
+ if (existsSync(dir))
514
+ return;
515
+ try {
516
+ const token = await this.client.createScopedInstallationToken(ref.repo, {
517
+ contents: "read",
518
+ });
519
+ await cloneRepo({
520
+ url: `https://github.com/${ref.owner}/${ref.repo}.git`,
521
+ dir,
522
+ token,
523
+ botLogin: `${this.appSlug}[bot]`,
524
+ botEmail: this.botEmail ?? `${this.appSlug}[bot]@users.noreply.github.com`,
525
+ prNumber: isPr ? ref.number : undefined,
526
+ });
527
+ log.logInfo(`[${conversationId}] Cloned ${ref.owner}/${ref.repo}${isPr ? ` and checked out PR #${ref.number} head` : ""}`);
528
+ }
529
+ catch (err) {
530
+ log.logWarning(`GitHub: repo clone failed for ${conversationId}`, err instanceof Error ? err.message : String(err));
531
+ }
532
+ }
533
+ /**
534
+ * Backs the `github_pr` tool: push a `pi/*` branch the agent prepared in
535
+ * the conversation's clone, then open a pull request as the App. The write
536
+ * token is minted per call, scoped to this one repo, and never enters the
537
+ * sandbox.
538
+ */
539
+ async pushAndCreatePr(conversationId, request) {
540
+ const ref = parseGithubConversationId(conversationId);
541
+ const dir = this.repoDir(conversationId);
542
+ if (!existsSync(dir)) {
543
+ throw new Error("This conversation has no ./repo clone to push from.");
544
+ }
545
+ if (!GITHUB_PUSH_BRANCH_PATTERN.test(request.branch)) {
546
+ throw new Error(`Branch '${request.branch}' is not pushable: name it pi/<something> (e.g. pi/fix-${ref.number}).`);
547
+ }
548
+ const repository = await githubRetry(() => this.client.getRepository(ref.owner, ref.repo));
549
+ const base = request.base ?? repository.default_branch;
550
+ const token = await this.client.createScopedInstallationToken(ref.repo, {
551
+ contents: "write",
552
+ pull_requests: "write",
553
+ });
554
+ await pushBranch({ dir, branch: request.branch, token });
555
+ const pr = await githubRetry(() => this.client.createPullRequest(ref.owner, ref.repo, {
556
+ title: request.title,
557
+ head: request.branch,
558
+ base,
559
+ body: request.body,
560
+ draft: request.draft,
561
+ }));
562
+ log.logInfo(`[${conversationId}] Opened PR #${pr.number}: ${pr.html_url}`);
563
+ return { number: pr.number, url: pr.html_url };
427
564
  }
428
565
  }
429
566
  //# sourceMappingURL=bot.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/github/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU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AAI,EAAE,KAAK,KAAK,CAAC,KAAK,OAAO,KAAK,CAAC,IAAI,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE;YACtD,WAAW,EAAE,EAAE;YACf,cAAc,EAAE,KAAK;SACtB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { existsSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { Type } from \"@sinclair/typebox\";\nimport type {\n ConversationEvent,\n MessagingBot,\n MessagingEventHandler,\n MessagingInfo,\n} from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"../../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../../utils/fs-atomic.js\";\nimport { resolveChatSessionKey } from \"../../sessions/policy.js\";\nimport { formatNothingRunning } from \"../../platform-messages.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n MessagingEventQueue,\n resolveStopTarget,\n splitText,\n withRetry,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { GithubClient, githubIsRateLimited } from \"./client.js\";\nimport { createGithubAdapters } from \"./context.js\";\nimport {\n buildGithubConversationId,\n GITHUB_ISSUE_BODY_TS,\n parseGithubConversationId,\n} from \"./ids.js\";\nimport type {\n GithubBotConfig,\n GithubConversationRef,\n GithubEvent,\n GithubIssue,\n GithubReactionContent,\n GithubRepoRef,\n GithubSyncState,\n} from \"./types.js\";\n\nconst SyncStateSchema = Type.Object({\n repos: Type.Record(\n Type.String(),\n Type.Object({\n baseline: Type.String(),\n cursor: Type.String(),\n seenComments: Type.Array(Type.Number()),\n seenIssues: Type.Array(Type.Number()),\n }),\n ),\n});\n\n/**\n * Re-fetch this far behind the cursor each poll. Dedup is by id (the\n * watermark), so the overlap only costs bandwidth and closes the boundary\n * races of a bare `since` timestamp (DESIGN.md § Event source).\n */\nconst POLL_OVERLAP_MS = 5 * 60 * 1000;\n\nconst MAX_SEEN_IDS = 5000;\n\n/** In-memory form of one repo's persisted watermark. */\ninterface RepoWatermark {\n baseline: string;\n cursor: string;\n seenComments: Set<number>;\n seenIssues: Set<number>;\n}\n\nconst githubRetry = <T>(fn: () => Promise<T>): Promise<T> =>\n withRetry(fn, { isRateLimited: githubIsRateLimited });\n\n/** GitHub comment bodies cap at 65536 chars; leave headroom for markup. */\nexport const GITHUB_MAX_COMMENT_LENGTH = 60000;\n\nexport const formatGithubContinuation = (partNum: number): string => `*(continued ${partNum})*`;\n\n/** Slack-style emoji short names → GitHub reaction content values. */\nconst GITHUB_REACTIONS: Record<string, GithubReactionContent> = {\n \"+1\": \"+1\",\n thumbsup: \"+1\",\n \"-1\": \"-1\",\n thumbsdown: \"-1\",\n laugh: \"laugh\",\n smile: \"laugh\",\n confused: \"confused\",\n heart: \"heart\",\n hooray: \"hooray\",\n tada: \"hooray\",\n rocket: \"rocket\",\n eyes: \"eyes\",\n};\n\ninterface IncomingItem {\n ref: GithubConversationRef;\n /** Comment id, or GITHUB_ISSUE_BODY_TS for the issue/PR body itself. */\n ts: string;\n user: string;\n text: string;\n createdAt: string;\n}\n\n// Repo refs are lowercased at every entry point (env config here, the\n// installation API in start()) so conversation ids and sync-state keys never\n// depend on how a repo's name was spelled — GitHub is case-insensitive.\nfunction parseRepoList(repos: string[]): GithubRepoRef[] {\n return repos.map((entry) => {\n const [owner, repo, ...rest] = entry.split(\"/\");\n if (!owner || !repo || rest.length > 0) {\n throw new Error(`Invalid GITHUB_REPOS entry (expected owner/repo): ${entry}`);\n }\n return { owner: owner.toLowerCase(), repo: repo.toLowerCase() };\n });\n}\n\n/** Sets iterate in insertion order; drop the oldest ids once over the cap. */\nfunction pruneSeen(seen: Set<number>): void {\n if (seen.size <= MAX_SEEN_IDS) return;\n let toDrop = seen.size - MAX_SEEN_IDS / 2;\n for (const id of seen) {\n if (toDrop-- <= 0) break;\n seen.delete(id);\n }\n}\n\n/** Issue number from a comment's `issue_url` (…/repos/o/r/issues/42). */\nfunction issueNumberFromUrl(issueUrl: string): number {\n const match = /\\/issues\\/(\\d+)$/.exec(issueUrl);\n if (!match) {\n throw new Error(`Cannot parse issue number from ${issueUrl}`);\n }\n return Number(match[1]);\n}\n\nexport class GithubMessagingBot implements MessagingBot {\n private readonly client: GithubClient;\n private readonly handler: MessagingEventHandler;\n private readonly config: GithubBotConfig;\n private appSlug: string | null = null;\n private watchedRepos: GithubRepoRef[] = [];\n private queues = new Map<string, MessagingEventQueue>();\n private repoState = new Map<string, RepoWatermark>();\n private pollInFlight = false;\n\n constructor(handler: MessagingEventHandler, config: GithubBotConfig, client?: GithubClient) {\n this.handler = handler;\n this.config = config;\n this.client =\n client ??\n new GithubClient({\n appId: config.appId,\n privateKey: config.privateKey,\n installationId: config.installationId,\n });\n }\n\n // ==========================================================================\n // Public API (implements MessagingBot)\n // ==========================================================================\n\n async start(): Promise<void> {\n this.appSlug = await this.client.getAppSlug();\n this.watchedRepos =\n this.config.repos.length > 0\n ? parseRepoList(this.config.repos)\n : (await this.client.listInstallationRepositories()).map((repository) => ({\n owner: repository.owner.login.toLowerCase(),\n repo: repository.name.toLowerCase(),\n }));\n if (this.watchedRepos.length === 0) {\n log.logWarning(\"GitHub: installation has no repositories; nothing to poll\");\n }\n\n // Restore persisted watermarks; a repo watched for the first time gets a\n // baseline of \"now\" so history never triggers (DESIGN.md § Event source).\n const persisted = this.loadSyncState();\n const now = new Date().toISOString();\n for (const repo of this.watchedRepos) {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const saved = persisted?.repos[repoKey];\n this.repoState.set(\n repoKey,\n saved\n ? {\n baseline: saved.baseline,\n cursor: saved.cursor,\n seenComments: new Set(saved.seenComments),\n seenIssues: new Set(saved.seenIssues),\n }\n : { baseline: now, cursor: now, seenComments: new Set(), seenIssues: new Set() },\n );\n }\n this.persistSyncState();\n\n setInterval(() => {\n void this.poll();\n }, this.config.pollIntervalMs).unref();\n\n log.logConnected(\"GitHub\");\n log.logInfo(\n `GitHub bot started as @${this.appSlug}[bot], polling ${this.watchedRepos.length} repo(s) every ${Math.round(this.config.pollIntervalMs / 1000)}s`,\n );\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n const ref = parseGithubConversationId(channel);\n const parts = splitText(text, GITHUB_MAX_COMMENT_LENGTH, formatGithubContinuation);\n const firstId = await this.postComment(ref, parts[0]);\n for (const part of parts.slice(1)) {\n await this.postComment(ref, part);\n }\n return String(firstId);\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n await githubRetry(() => this.client.updateIssueComment(ref.owner, ref.repo, Number(ts), text));\n }\n\n async addReaction(channel: string, messageTs: string, emoji: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n const content = GITHUB_REACTIONS[emoji.replace(/^:|:$/g, \"\")];\n if (!content) {\n throw new Error(\n `GitHub does not support reaction '${emoji}' (supported: ${Object.keys(GITHUB_REACTIONS).join(\", \")})`,\n );\n }\n await githubRetry(() =>\n messageTs === GITHUB_ISSUE_BODY_TS\n ? this.client.createIssueReaction(ref.owner, ref.repo, ref.number, content)\n : this.client.createCommentReaction(ref.owner, ref.repo, Number(messageTs), content),\n );\n }\n\n enqueueEvent(event: ConversationEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(() => {\n const context = createGithubAdapters(event as GithubEvent, this);\n return this.handler.handleEvent(event, this, context);\n });\n return true;\n }\n\n getMessagingInfo(): MessagingInfo {\n return {\n name: \"github\",\n formattingGuide:\n \"## GitHub Formatting (GitHub Flavored Markdown)\\n\" +\n \"Standard Markdown plus tables, task lists, and ```suggestion blocks.\\n\" +\n \"Reference issues/PRs as #123 and users as @login.\",\n channels: [],\n users: [],\n };\n }\n\n // ==========================================================================\n // Internal helpers (used by context.ts)\n // ==========================================================================\n\n async postComment(ref: GithubConversationRef, text: string): Promise<number> {\n const comment = await githubRetry(() =>\n this.client.createIssueComment(ref.owner, ref.repo, ref.number, text),\n );\n return comment.id;\n }\n\n async deleteComment(ref: GithubConversationRef, commentId: number): Promise<void> {\n await githubRetry(() => this.client.deleteIssueComment(ref.owner, ref.repo, commentId));\n }\n\n logToFile(conversationId: string, entry: object): void {\n appendChannelLog(this.config.workingDir, conversationId, entry);\n }\n\n logBotResponse(conversationId: string, text: string, ts: string): void {\n appendBotResponseLog(this.config.workingDir, conversationId, text, ts);\n }\n\n // ==========================================================================\n // Private - polling\n // ==========================================================================\n\n private getQueue(conversationId: string): MessagingEventQueue {\n let queue = this.queues.get(conversationId);\n if (!queue) {\n queue = new MessagingEventQueue(\"GitHub\");\n this.queues.set(conversationId, queue);\n }\n return queue;\n }\n\n /** One poll tick over every watched repo. Public for tests. */\n async poll(): Promise<void> {\n if (this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n let changed = false;\n for (const repo of this.watchedRepos) {\n try {\n changed = (await this.pollRepo(repo)) || changed;\n } catch (err) {\n log.logWarning(\n `GitHub poll failed for ${repo.owner}/${repo.repo}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n if (changed) {\n this.persistSyncState();\n }\n } finally {\n this.pollInFlight = false;\n }\n }\n\n private async pollRepo(repo: GithubRepoRef): Promise<boolean> {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const state = this.repoState.get(repoKey);\n if (!state) return false;\n const since = new Date(Date.parse(state.cursor) - POLL_OVERLAP_MS).toISOString();\n let changed = false;\n\n // Comment activity also bumps the parent issue's updated_at, so the issues\n // list mostly echoes the comments list; only issues *created* since the\n // baseline are new conversations (their body is the first message).\n const issues = (await this.client.listIssuesSince(repo.owner, repo.repo, since)) ?? [];\n for (const issue of issues) {\n if (issue.updated_at > state.cursor) {\n state.cursor = issue.updated_at;\n changed = true;\n }\n // Edits re-surface old items with a fresh updated_at; the id watermark\n // plus the creation baseline decide what actually triggers.\n if (issue.created_at < state.baseline || state.seenIssues.has(issue.id)) continue;\n state.seenIssues.add(issue.id);\n changed = true;\n if (issue.user.type === \"Bot\") continue;\n await this.handleIncoming({\n ref: { ...repo, number: issue.number },\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n createdAt: issue.created_at,\n });\n }\n\n const comments = (await this.client.listIssueCommentsSince(repo.owner, repo.repo, since)) ?? [];\n for (const comment of comments) {\n if (comment.updated_at > state.cursor) {\n state.cursor = comment.updated_at;\n changed = true;\n }\n if (comment.created_at < state.baseline || state.seenComments.has(comment.id)) continue;\n state.seenComments.add(comment.id);\n changed = true;\n if (comment.user.type === \"Bot\") continue;\n await this.handleIncoming({\n ref: { ...repo, number: issueNumberFromUrl(comment.issue_url) },\n ts: String(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n });\n }\n\n pruneSeen(state.seenComments);\n pruneSeen(state.seenIssues);\n return changed;\n }\n\n // ==========================================================================\n // Private - watermark persistence\n // ==========================================================================\n\n private loadSyncState(): GithubSyncState | undefined {\n try {\n return readJsonSchemaFileIfExists(\n this.config.syncStatePath,\n SyncStateSchema,\n (detail) => `Malformed GitHub sync state at ${this.config.syncStatePath}: ${detail}`,\n );\n } catch (err) {\n // A bad state file re-baselines (history won't trigger) rather than\n // blocking startup; the next persist overwrites it.\n log.logWarning(\n \"GitHub: ignoring unreadable sync state\",\n err instanceof Error ? err.message : String(err),\n );\n return undefined;\n }\n }\n\n private persistSyncState(): void {\n const state: GithubSyncState = { repos: {} };\n for (const [repoKey, watermark] of this.repoState) {\n state.repos[repoKey] = {\n baseline: watermark.baseline,\n cursor: watermark.cursor,\n seenComments: [...watermark.seenComments],\n seenIssues: [...watermark.seenIssues],\n };\n }\n ensureDirExists(dirname(this.config.syncStatePath));\n atomicWritePrivateFile(this.config.syncStatePath, JSON.stringify(state));\n }\n\n // ==========================================================================\n // Private - triggering\n // ==========================================================================\n\n /** Fresh regex per call: the `g` flag makes `test`/`replace` stateful. */\n private mentionPattern(): RegExp | null {\n return this.appSlug ? new RegExp(`@${this.appSlug}(?![\\\\w-])`, \"gi\") : null;\n }\n\n private isMentioned(text: string): boolean {\n const pattern = this.mentionPattern();\n return pattern ? pattern.test(text) : false;\n }\n\n private stripMention(text: string): string {\n const pattern = this.mentionPattern();\n return (pattern ? text.replace(pattern, \"\") : text).trim();\n }\n\n private isParticipating(conversationId: string): boolean {\n return existsSync(join(this.config.workingDir, conversationId, \"log.jsonl\"));\n }\n\n private async handleIncoming(item: IncomingItem): Promise<void> {\n const conversationId = buildGithubConversationId(item.ref);\n const mentioned = this.isMentioned(item.text);\n const participating = this.isParticipating(conversationId);\n // Narrow trigger (DESIGN.md): only threads the bot is mentioned in or\n // already participates in. Everything else is ignored without logging so\n // busy repos don't grow conversation dirs for untouched issues.\n if (!mentioned && !participating) return;\n\n const cleanedText = this.stripMention(item.text);\n const sessionKey = resolveChatSessionKey({\n conversationId,\n conversationKind: \"shared\",\n messageId: item.ts,\n persistentTopLevel: true,\n });\n\n if (/^stop$/i.test(cleanedText)) {\n this.logToFile(conversationId, {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: cleanedText,\n attachments: [],\n isMessagingBot: false,\n });\n const stopTarget = resolveStopTarget({ handler: this.handler, conversationId, sessionKey });\n if (stopTarget) {\n await this.handler.handleStop(stopTarget, conversationId, this);\n } else if (mentioned) {\n await this.postMessage(conversationId, formatNothingRunning(\"github\"));\n }\n return;\n }\n\n // First contact via a comment: log the issue title/body first so the\n // session history starts with what the thread is about.\n if (!participating && item.ts !== GITHUB_ISSUE_BODY_TS) {\n await this.logIssueContext(item.ref, conversationId, item.createdAt);\n }\n\n const eventBase: GithubEvent = {\n type: item.ts === GITHUB_ISSUE_BODY_TS ? \"issue\" : \"message\",\n conversationId,\n conversationKind: \"shared\",\n ts: item.ts,\n sessionKey,\n user: item.user,\n userName: item.user,\n text: cleanedText,\n };\n\n await processMessageIntake({\n eventBase,\n workingDir: this.config.workingDir,\n isAutoReplyCandidate: false,\n logEntryBase: {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: cleanedText,\n isMessagingBot: false,\n },\n log: (entry) => this.logToFile(conversationId, entry),\n processAttachments: async () => [],\n queueKey: conversationId,\n enqueue: (queueKey, work) => this.getQueue(queueKey).enqueue(work),\n handler: this.handler,\n bot: this,\n createContext: (event) => createGithubAdapters(event, this),\n });\n }\n\n private async logIssueContext(\n ref: GithubConversationRef,\n conversationId: string,\n triggerCreatedAt: string,\n ): Promise<void> {\n let issue: GithubIssue;\n try {\n issue = await githubRetry(() => this.client.getIssue(ref.owner, ref.repo, ref.number));\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch issue context for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n return;\n }\n // Dated just before the triggering comment, NOT issue.created_at: history\n // sync date-sorts entries and drops anything older than its recency\n // window, so an old issue's real creation date would silently evict the\n // one message that says what the thread is about.\n const triggerMs = Date.parse(triggerCreatedAt);\n const contextDate = new Date((Number.isFinite(triggerMs) ? triggerMs : Date.now()) - 1000);\n this.logToFile(conversationId, {\n date: contextDate.toISOString(),\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n userName: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n attachments: [],\n isMessagingBot: false,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/github/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AASzC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,4BAA4B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EAAE,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;QACzD,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,CAChC,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE;YACjD,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,IAAI,EAAE,OAAO,CAAC,MAAM;YACpB,IAAI;YACJ,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,KAAK,EAAE,OAAO,CAAC,KAAK;SACrB,CAAC,CACH,CAAC;QACF,GAAG,CAAC,OAAO,CAAC,IAAI,cAAc,gBAAgB,EAAE,CAAC,MAAM,KAAK,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;QAC3E,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,QAAQ,EAAE,CAAC;IACjD,CAAC;CACF","sourcesContent":["import { existsSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { Type } from \"@sinclair/typebox\";\nimport type {\n ConversationEvent,\n GithubPrRequest,\n GithubPrResult,\n MessagingBot,\n MessagingEventHandler,\n MessagingInfo,\n} from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"../../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../../utils/fs-atomic.js\";\nimport { resolveChatSessionKey } from \"../../sessions/policy.js\";\nimport { formatNothingRunning } from \"../../platform-messages.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n MessagingEventQueue,\n resolveStopTarget,\n splitText,\n withRetry,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { GithubClient, githubIsRateLimited } from \"./client.js\";\nimport { createGithubAdapters } from \"./context.js\";\nimport { cloneRepo, GITHUB_PUSH_BRANCH_PATTERN, pushBranch } from \"./repo.js\";\nimport {\n buildGithubConversationId,\n GITHUB_ISSUE_BODY_TS,\n parseGithubConversationId,\n} from \"./ids.js\";\nimport type {\n GithubBotConfig,\n GithubConversationRef,\n GithubEvent,\n GithubIssue,\n GithubReactionContent,\n GithubRepoRef,\n GithubSyncState,\n} from \"./types.js\";\n\nconst SyncStateSchema = Type.Object({\n repos: Type.Record(\n Type.String(),\n Type.Object({\n baseline: Type.String(),\n cursor: Type.String(),\n seenComments: Type.Array(Type.Number()),\n seenIssues: Type.Array(Type.Number()),\n }),\n ),\n});\n\n/**\n * Re-fetch this far behind the cursor each poll. Dedup is by id (the\n * watermark), so the overlap only costs bandwidth and closes the boundary\n * races of a bare `since` timestamp (DESIGN.md § Event source).\n */\nconst POLL_OVERLAP_MS = 5 * 60 * 1000;\n\nconst MAX_SEEN_IDS = 5000;\n\n/** Effective role → rank, for the trigger-permission gate. */\nconst PERMISSION_RANK: Record<string, number> = {\n none: 0,\n read: 1,\n triage: 2,\n write: 3,\n maintain: 4,\n admin: 5,\n};\n\n/**\n * Commenters need write or better to trigger the agent. Fixed, not a config\n * knob: it guards public repos (anyone can comment there), and the people who\n * ask an agent to change code are exactly the people with push access.\n */\nconst REQUIRED_TRIGGER_RANK = PERMISSION_RANK.write;\n\n/** Permission lookups are cached this long per repo+user. */\nconst PERMISSION_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** In-memory form of one repo's persisted watermark. */\ninterface RepoWatermark {\n baseline: string;\n cursor: string;\n seenComments: Set<number>;\n seenIssues: Set<number>;\n}\n\nconst githubRetry = <T>(fn: () => Promise<T>): Promise<T> =>\n withRetry(fn, { isRateLimited: githubIsRateLimited });\n\n/** GitHub comment bodies cap at 65536 chars; leave headroom for markup. */\nexport const GITHUB_MAX_COMMENT_LENGTH = 60000;\n\nexport const formatGithubContinuation = (partNum: number): string => `*(continued ${partNum})*`;\n\n/** Slack-style emoji short names → GitHub reaction content values. */\nconst GITHUB_REACTIONS: Record<string, GithubReactionContent> = {\n \"+1\": \"+1\",\n thumbsup: \"+1\",\n \"-1\": \"-1\",\n thumbsdown: \"-1\",\n laugh: \"laugh\",\n smile: \"laugh\",\n confused: \"confused\",\n heart: \"heart\",\n hooray: \"hooray\",\n tada: \"hooray\",\n rocket: \"rocket\",\n eyes: \"eyes\",\n};\n\ninterface IncomingItem {\n ref: GithubConversationRef;\n /** Comment id, or GITHUB_ISSUE_BODY_TS for the issue/PR body itself. */\n ts: string;\n user: string;\n text: string;\n createdAt: string;\n /** Known only for issue-body items; comment first-contact resolves it via getIssue. */\n isPr?: boolean;\n}\n\n// Repo refs are lowercased at every entry point (env config here, the\n// installation API in start()) so conversation ids and sync-state keys never\n// depend on how a repo's name was spelled — GitHub is case-insensitive.\nfunction parseRepoList(repos: string[]): GithubRepoRef[] {\n return repos.map((entry) => {\n const [owner, repo, ...rest] = entry.split(\"/\");\n if (!owner || !repo || rest.length > 0) {\n throw new Error(`Invalid GITHUB_REPOS entry (expected owner/repo): ${entry}`);\n }\n return { owner: owner.toLowerCase(), repo: repo.toLowerCase() };\n });\n}\n\n/** Sets iterate in insertion order; drop the oldest ids once over the cap. */\nfunction pruneSeen(seen: Set<number>): void {\n if (seen.size <= MAX_SEEN_IDS) return;\n let toDrop = seen.size - MAX_SEEN_IDS / 2;\n for (const id of seen) {\n if (toDrop-- <= 0) break;\n seen.delete(id);\n }\n}\n\n/** Issue number from a comment's `issue_url` (…/repos/o/r/issues/42). */\nfunction issueNumberFromUrl(issueUrl: string): number {\n const match = /\\/issues\\/(\\d+)$/.exec(issueUrl);\n if (!match) {\n throw new Error(`Cannot parse issue number from ${issueUrl}`);\n }\n return Number(match[1]);\n}\n\nexport class GithubMessagingBot implements MessagingBot {\n private readonly client: GithubClient;\n private readonly handler: MessagingEventHandler;\n private readonly config: GithubBotConfig;\n private appSlug: string | null = null;\n private botEmail: string | null = null;\n private watchedRepos: GithubRepoRef[] = [];\n private queues = new Map<string, MessagingEventQueue>();\n private repoState = new Map<string, RepoWatermark>();\n private permissionCache = new Map<string, { rank: number; expiresAt: number }>();\n private pollInFlight = false;\n\n constructor(handler: MessagingEventHandler, config: GithubBotConfig, client?: GithubClient) {\n this.handler = handler;\n this.config = config;\n this.client =\n client ??\n new GithubClient({\n appId: config.appId,\n privateKey: config.privateKey,\n installationId: config.installationId,\n });\n }\n\n // ==========================================================================\n // Public API (implements MessagingBot)\n // ==========================================================================\n\n async start(): Promise<void> {\n this.appSlug = await this.client.getAppSlug();\n // Canonical noreply author email (<user-id>+<login>@users.noreply.github.com)\n // so the bot's commits link to its avatar/profile; degrade to a plain\n // noreply spelling when the lookup fails.\n try {\n const botUserId = await this.client.getUserId(`${this.appSlug}[bot]`);\n this.botEmail = `${botUserId}+${this.appSlug}[bot]@users.noreply.github.com`;\n } catch {\n this.botEmail = `${this.appSlug}[bot]@users.noreply.github.com`;\n }\n this.watchedRepos =\n this.config.repos.length > 0\n ? parseRepoList(this.config.repos)\n : (await this.client.listInstallationRepositories()).map((repository) => ({\n owner: repository.owner.login.toLowerCase(),\n repo: repository.name.toLowerCase(),\n }));\n if (this.watchedRepos.length === 0) {\n log.logWarning(\"GitHub: installation has no repositories; nothing to poll\");\n }\n\n // Restore persisted watermarks; a repo watched for the first time gets a\n // baseline of \"now\" so history never triggers (DESIGN.md § Event source).\n const persisted = this.loadSyncState();\n const now = new Date().toISOString();\n for (const repo of this.watchedRepos) {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const saved = persisted?.repos[repoKey];\n this.repoState.set(\n repoKey,\n saved\n ? {\n baseline: saved.baseline,\n cursor: saved.cursor,\n seenComments: new Set(saved.seenComments),\n seenIssues: new Set(saved.seenIssues),\n }\n : { baseline: now, cursor: now, seenComments: new Set(), seenIssues: new Set() },\n );\n }\n this.persistSyncState();\n\n setInterval(() => {\n void this.poll();\n }, this.config.pollIntervalMs).unref();\n\n log.logConnected(\"GitHub\");\n log.logInfo(\n `GitHub bot started as @${this.appSlug}[bot], polling ${this.watchedRepos.length} repo(s) every ${Math.round(this.config.pollIntervalMs / 1000)}s`,\n );\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n const ref = parseGithubConversationId(channel);\n const parts = splitText(text, GITHUB_MAX_COMMENT_LENGTH, formatGithubContinuation);\n const firstId = await this.postComment(ref, parts[0]);\n for (const part of parts.slice(1)) {\n await this.postComment(ref, part);\n }\n return String(firstId);\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n await githubRetry(() => this.client.updateIssueComment(ref.owner, ref.repo, Number(ts), text));\n }\n\n async addReaction(channel: string, messageTs: string, emoji: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n const content = GITHUB_REACTIONS[emoji.replace(/^:|:$/g, \"\")];\n if (!content) {\n throw new Error(\n `GitHub does not support reaction '${emoji}' (supported: ${Object.keys(GITHUB_REACTIONS).join(\", \")})`,\n );\n }\n await githubRetry(() =>\n messageTs === GITHUB_ISSUE_BODY_TS\n ? this.client.createIssueReaction(ref.owner, ref.repo, ref.number, content)\n : this.client.createCommentReaction(ref.owner, ref.repo, Number(messageTs), content),\n );\n }\n\n enqueueEvent(event: ConversationEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(() => {\n const context = createGithubAdapters(event as GithubEvent, this);\n return this.handler.handleEvent(event, this, context);\n });\n return true;\n }\n\n getMessagingInfo(): MessagingInfo {\n return {\n name: \"github\",\n formattingGuide:\n \"## GitHub Formatting (GitHub Flavored Markdown)\\n\" +\n \"Standard Markdown plus tables, task lists, and ```suggestion blocks.\\n\" +\n \"Reference issues/PRs as #123 and users as @login.\",\n channels: [],\n users: [],\n };\n }\n\n // ==========================================================================\n // Internal helpers (used by context.ts)\n // ==========================================================================\n\n async postComment(ref: GithubConversationRef, text: string): Promise<number> {\n const comment = await githubRetry(() =>\n this.client.createIssueComment(ref.owner, ref.repo, ref.number, text),\n );\n return comment.id;\n }\n\n async deleteComment(ref: GithubConversationRef, commentId: number): Promise<void> {\n await githubRetry(() => this.client.deleteIssueComment(ref.owner, ref.repo, commentId));\n }\n\n logToFile(conversationId: string, entry: object): void {\n appendChannelLog(this.config.workingDir, conversationId, entry);\n }\n\n logBotResponse(conversationId: string, text: string, ts: string): void {\n appendBotResponseLog(this.config.workingDir, conversationId, text, ts);\n }\n\n // ==========================================================================\n // Private - polling\n // ==========================================================================\n\n private getQueue(conversationId: string): MessagingEventQueue {\n let queue = this.queues.get(conversationId);\n if (!queue) {\n queue = new MessagingEventQueue(\"GitHub\");\n this.queues.set(conversationId, queue);\n }\n return queue;\n }\n\n /** One poll tick over every watched repo. Public for tests. */\n async poll(): Promise<void> {\n if (this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n let changed = false;\n for (const repo of this.watchedRepos) {\n try {\n changed = (await this.pollRepo(repo)) || changed;\n } catch (err) {\n log.logWarning(\n `GitHub poll failed for ${repo.owner}/${repo.repo}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n if (changed) {\n this.persistSyncState();\n }\n } finally {\n this.pollInFlight = false;\n }\n }\n\n private async pollRepo(repo: GithubRepoRef): Promise<boolean> {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const state = this.repoState.get(repoKey);\n if (!state) return false;\n const since = new Date(Date.parse(state.cursor) - POLL_OVERLAP_MS).toISOString();\n let changed = false;\n\n // Comment activity also bumps the parent issue's updated_at, so the issues\n // list mostly echoes the comments list; only issues *created* since the\n // baseline are new conversations (their body is the first message).\n const issues = (await this.client.listIssuesSince(repo.owner, repo.repo, since)) ?? [];\n for (const issue of issues) {\n if (issue.updated_at > state.cursor) {\n state.cursor = issue.updated_at;\n changed = true;\n }\n // Edits re-surface old items with a fresh updated_at; the id watermark\n // plus the creation baseline decide what actually triggers.\n if (issue.created_at < state.baseline || state.seenIssues.has(issue.id)) continue;\n state.seenIssues.add(issue.id);\n changed = true;\n if (issue.user.type === \"Bot\") continue;\n await this.handleIncoming({\n ref: { ...repo, number: issue.number },\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n createdAt: issue.created_at,\n isPr: Boolean(issue.pull_request),\n });\n }\n\n const comments = (await this.client.listIssueCommentsSince(repo.owner, repo.repo, since)) ?? [];\n for (const comment of comments) {\n if (comment.updated_at > state.cursor) {\n state.cursor = comment.updated_at;\n changed = true;\n }\n if (comment.created_at < state.baseline || state.seenComments.has(comment.id)) continue;\n state.seenComments.add(comment.id);\n changed = true;\n if (comment.user.type === \"Bot\") continue;\n await this.handleIncoming({\n ref: { ...repo, number: issueNumberFromUrl(comment.issue_url) },\n ts: String(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n });\n }\n\n pruneSeen(state.seenComments);\n pruneSeen(state.seenIssues);\n return changed;\n }\n\n // ==========================================================================\n // Private - watermark persistence\n // ==========================================================================\n\n private loadSyncState(): GithubSyncState | undefined {\n try {\n return readJsonSchemaFileIfExists(\n this.config.syncStatePath,\n SyncStateSchema,\n (detail) => `Malformed GitHub sync state at ${this.config.syncStatePath}: ${detail}`,\n );\n } catch (err) {\n // A bad state file re-baselines (history won't trigger) rather than\n // blocking startup; the next persist overwrites it.\n log.logWarning(\n \"GitHub: ignoring unreadable sync state\",\n err instanceof Error ? err.message : String(err),\n );\n return undefined;\n }\n }\n\n private persistSyncState(): void {\n const state: GithubSyncState = { repos: {} };\n for (const [repoKey, watermark] of this.repoState) {\n state.repos[repoKey] = {\n baseline: watermark.baseline,\n cursor: watermark.cursor,\n seenComments: [...watermark.seenComments],\n seenIssues: [...watermark.seenIssues],\n };\n }\n ensureDirExists(dirname(this.config.syncStatePath));\n atomicWritePrivateFile(this.config.syncStatePath, JSON.stringify(state));\n }\n\n // ==========================================================================\n // Private - triggering\n // ==========================================================================\n\n /** Fresh regex per call: the `g` flag makes `test`/`replace` stateful. */\n private mentionPattern(): RegExp | null {\n return this.appSlug ? new RegExp(`@${this.appSlug}(?![\\\\w-])`, \"gi\") : null;\n }\n\n private isMentioned(text: string): boolean {\n const pattern = this.mentionPattern();\n return pattern ? pattern.test(text) : false;\n }\n\n private stripMention(text: string): string {\n const pattern = this.mentionPattern();\n return (pattern ? text.replace(pattern, \"\") : text).trim();\n }\n\n private isParticipating(conversationId: string): boolean {\n return existsSync(join(this.config.workingDir, conversationId, \"log.jsonl\"));\n }\n\n /**\n * True when `user` holds at least write permission on the repo. Fails\n * closed: a failed lookup denies the trigger (and logs) rather than\n * letting an unverified commenter drive the agent.\n */\n private async hasTriggerPermission(ref: GithubConversationRef, user: string): Promise<boolean> {\n const cacheKey = `${ref.owner}/${ref.repo}#${user}`;\n const cached = this.permissionCache.get(cacheKey);\n if (cached && Date.now() < cached.expiresAt) {\n return cached.rank >= REQUIRED_TRIGGER_RANK;\n }\n let rank: number;\n try {\n const role = await githubRetry(() =>\n this.client.getCollaboratorPermission(ref.owner, ref.repo, user),\n );\n // Custom role_name values are unrankable; the legacy permission field\n // still carries their closest standard mapping, so take the stronger.\n rank = Math.max(\n PERMISSION_RANK[role.role_name ?? \"\"] ?? 0,\n PERMISSION_RANK[role.permission] ?? 0,\n );\n } catch (err) {\n log.logWarning(\n `GitHub: permission lookup failed for ${user} on ${ref.owner}/${ref.repo}; denying trigger`,\n err instanceof Error ? err.message : String(err),\n );\n return false;\n }\n this.permissionCache.set(cacheKey, {\n rank,\n expiresAt: Date.now() + PERMISSION_CACHE_TTL_MS,\n });\n return rank >= REQUIRED_TRIGGER_RANK;\n }\n\n private async handleIncoming(item: IncomingItem): Promise<void> {\n const conversationId = buildGithubConversationId(item.ref);\n const mentioned = this.isMentioned(item.text);\n const participating = this.isParticipating(conversationId);\n // Narrow trigger (DESIGN.md): only threads the bot is mentioned in or\n // already participates in. Everything else is ignored without logging so\n // busy repos don't grow conversation dirs for untouched issues.\n if (!mentioned && !participating) return;\n\n // Permission gate: on public repos anyone can comment, so a mention from\n // anyone below write permission is ignored entirely (no log, no state).\n if (!(await this.hasTriggerPermission(item.ref, item.user))) {\n log.logInfo(\n `GitHub: ignoring ${conversationId} comment from ${item.user} (below write permission)`,\n );\n return;\n }\n\n const cleanedText = this.stripMention(item.text);\n const sessionKey = resolveChatSessionKey({\n conversationId,\n conversationKind: \"shared\",\n messageId: item.ts,\n persistentTopLevel: true,\n });\n\n if (/^stop$/i.test(cleanedText)) {\n this.logToFile(conversationId, {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: cleanedText,\n attachments: [],\n isMessagingBot: false,\n });\n const stopTarget = resolveStopTarget({ handler: this.handler, conversationId, sessionKey });\n if (stopTarget) {\n await this.handler.handleStop(stopTarget, conversationId, this);\n } else if (mentioned) {\n await this.postMessage(conversationId, formatNothingRunning(\"github\"));\n }\n return;\n }\n\n // First contact: log the issue title/body ahead of the comment so the\n // session history starts with what the thread is about, then clone the\n // repo into the conversation dir so the agent has the code.\n if (!participating) {\n let isPr = item.isPr ?? false;\n if (item.ts !== GITHUB_ISSUE_BODY_TS) {\n const issue = await this.logIssueContext(item.ref, conversationId, item.createdAt);\n isPr = Boolean(issue?.pull_request);\n }\n await this.ensureRepoClone(item.ref, conversationId, isPr);\n }\n\n const eventBase: GithubEvent = {\n type: item.ts === GITHUB_ISSUE_BODY_TS ? \"issue\" : \"message\",\n conversationId,\n conversationKind: \"shared\",\n ts: item.ts,\n sessionKey,\n user: item.user,\n userName: item.user,\n text: cleanedText,\n };\n\n await processMessageIntake({\n eventBase,\n workingDir: this.config.workingDir,\n isAutoReplyCandidate: false,\n logEntryBase: {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: cleanedText,\n isMessagingBot: false,\n },\n log: (entry) => this.logToFile(conversationId, entry),\n processAttachments: async () => [],\n queueKey: conversationId,\n enqueue: (queueKey, work) => this.getQueue(queueKey).enqueue(work),\n handler: this.handler,\n bot: this,\n createContext: (event) => createGithubAdapters(event, this),\n });\n }\n\n private async logIssueContext(\n ref: GithubConversationRef,\n conversationId: string,\n triggerCreatedAt: string,\n ): Promise<GithubIssue | null> {\n let issue: GithubIssue;\n try {\n issue = await githubRetry(() => this.client.getIssue(ref.owner, ref.repo, ref.number));\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch issue context for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n return null;\n }\n // Dated just before the triggering comment, NOT issue.created_at: history\n // sync date-sorts entries and drops anything older than its recency\n // window, so an old issue's real creation date would silently evict the\n // one message that says what the thread is about.\n const triggerMs = Date.parse(triggerCreatedAt);\n const contextDate = new Date((Number.isFinite(triggerMs) ? triggerMs : Date.now()) - 1000);\n this.logToFile(conversationId, {\n date: contextDate.toISOString(),\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n userName: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n attachments: [],\n isMessagingBot: false,\n });\n return issue;\n }\n\n // ==========================================================================\n // Repo clone + pull requests\n // ==========================================================================\n\n private repoDir(conversationId: string): string {\n return join(this.config.workingDir, conversationId, \"repo\");\n }\n\n /**\n * Clone the conversation's repo into its dir (bind-mounted into the\n * sandbox) using an ephemeral contents:read token that never leaves the\n * host. Non-fatal: a failed clone degrades to the pre-clone experience.\n */\n private async ensureRepoClone(\n ref: GithubConversationRef,\n conversationId: string,\n isPr: boolean,\n ): Promise<void> {\n const dir = this.repoDir(conversationId);\n if (existsSync(dir)) return;\n try {\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"read\",\n });\n await cloneRepo({\n url: `https://github.com/${ref.owner}/${ref.repo}.git`,\n dir,\n token,\n botLogin: `${this.appSlug}[bot]`,\n botEmail: this.botEmail ?? `${this.appSlug}[bot]@users.noreply.github.com`,\n prNumber: isPr ? ref.number : undefined,\n });\n log.logInfo(\n `[${conversationId}] Cloned ${ref.owner}/${ref.repo}${isPr ? ` and checked out PR #${ref.number} head` : \"\"}`,\n );\n } catch (err) {\n log.logWarning(\n `GitHub: repo clone failed for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n\n /**\n * Backs the `github_pr` tool: push a `pi/*` branch the agent prepared in\n * the conversation's clone, then open a pull request as the App. The write\n * token is minted per call, scoped to this one repo, and never enters the\n * sandbox.\n */\n async pushAndCreatePr(conversationId: string, request: GithubPrRequest): Promise<GithubPrResult> {\n const ref = parseGithubConversationId(conversationId);\n const dir = this.repoDir(conversationId);\n if (!existsSync(dir)) {\n throw new Error(\"This conversation has no ./repo clone to push from.\");\n }\n if (!GITHUB_PUSH_BRANCH_PATTERN.test(request.branch)) {\n throw new Error(\n `Branch '${request.branch}' is not pushable: name it pi/<something> (e.g. pi/fix-${ref.number}).`,\n );\n }\n const repository = await githubRetry(() => this.client.getRepository(ref.owner, ref.repo));\n const base = request.base ?? repository.default_branch;\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"write\",\n pull_requests: \"write\",\n });\n await pushBranch({ dir, branch: request.branch, token });\n const pr = await githubRetry(() =>\n this.client.createPullRequest(ref.owner, ref.repo, {\n title: request.title,\n head: request.branch,\n base,\n body: request.body,\n draft: request.draft,\n }),\n );\n log.logInfo(`[${conversationId}] Opened PR #${pr.number}: ${pr.html_url}`);\n return { number: pr.number, url: pr.html_url };\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { GithubClientOptions, GithubIssue, GithubIssueComment, GithubReactionContent, GithubRepository } from "./types.js";
1
+ import type { GithubClientOptions, GithubCollaboratorPermission, GithubIssue, GithubIssueComment, GithubPullRequest, GithubReactionContent, GithubRepository, GithubRepositoryDetails, GithubTokenPermissions } from "./types.js";
2
2
  export declare class GithubApiError extends Error {
3
3
  readonly status: number;
4
4
  constructor(status: number, method: string, path: string, detail: string);
@@ -33,6 +33,29 @@ export declare class GithubClient {
33
33
  private request;
34
34
  /** The App's mention slug; its comments author as `<slug>[bot]`. */
35
35
  getAppSlug(): Promise<string>;
36
+ /** Database id of a user/bot login (for noreply commit-author emails). */
37
+ getUserId(login: string): Promise<number>;
38
+ /**
39
+ * Mint a one-off installation token narrowed to a single repo and an
40
+ * explicit permission subset. Used for host-side git operations so the
41
+ * broad installation identity never leaves this process.
42
+ */
43
+ createScopedInstallationToken(repoName: string, permissions: GithubTokenPermissions): Promise<string>;
44
+ getRepository(owner: string, repo: string): Promise<GithubRepositoryDetails>;
45
+ /**
46
+ * A user's effective role on a repo: granular `role_name` plus the legacy
47
+ * `permission` field (callers rank whichever is stronger, so custom roles
48
+ * still resolve via their legacy mapping). Needs only Metadata: Read — the
49
+ * mandatory App permission. Unknown users resolve to none.
50
+ */
51
+ getCollaboratorPermission(owner: string, repo: string, username: string): Promise<GithubCollaboratorPermission>;
52
+ createPullRequest(owner: string, repo: string, params: {
53
+ title: string;
54
+ head: string;
55
+ base: string;
56
+ body?: string;
57
+ draft?: boolean;
58
+ }): Promise<GithubPullRequest>;
36
59
  listInstallationRepositories(): Promise<GithubRepository[]>;
37
60
  /**
38
61
  * All issue/PR conversation comments in a repo updated at or after `since`,
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EACnB,WAAW,EACX,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAEpB,qBAAa,cAAe,SAAQ,KAAK;aAErB,MAAM,EAAE,MAAM;IADhC,YACkB,MAAM,EAAE,MAAM,EAC9B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EAIf;CACF;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,KAAK,GAAG,OAAO,CAGvD;AASD;;;;GAIG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAA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AAC,WAAW,EAAE,GAAG,IAAI,CAAC,CAM/F;IAEK,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAMhF;IAEK,kBAAkB,CACtB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,kBAAkB,CAAC,CAO7B;IAEK,kBAAkB,CACtB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,IAAI,CAAC,CAIf;IAEK,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtF;IAEK,qBAAqB,CACzB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAIf;IAEK,mBAAmB,CACvB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAIf;CACF"}
@@ -102,6 +102,51 @@ export class GithubClient {
102
102
  });
103
103
  return app.slug;
104
104
  }
105
+ /** Database id of a user/bot login (for noreply commit-author emails). */
106
+ async getUserId(login) {
107
+ const user = await this.request("GET", `/users/${encodeURIComponent(login)}`);
108
+ return user.id;
109
+ }
110
+ /**
111
+ * Mint a one-off installation token narrowed to a single repo and an
112
+ * explicit permission subset. Used for host-side git operations so the
113
+ * broad installation identity never leaves this process.
114
+ */
115
+ async createScopedInstallationToken(repoName, permissions) {
116
+ const data = await this.rawRequest("POST", `/app/installations/${this.installationId}/access_tokens`, {
117
+ auth: `Bearer ${this.appJwt()}`,
118
+ body: { repositories: [repoName], permissions },
119
+ });
120
+ return data.token;
121
+ }
122
+ async getRepository(owner, repo) {
123
+ const details = await this.request("GET", `/repos/${owner}/${repo}`);
124
+ return details;
125
+ }
126
+ /**
127
+ * A user's effective role on a repo: granular `role_name` plus the legacy
128
+ * `permission` field (callers rank whichever is stronger, so custom roles
129
+ * still resolve via their legacy mapping). Needs only Metadata: Read — the
130
+ * mandatory App permission. Unknown users resolve to none.
131
+ */
132
+ async getCollaboratorPermission(owner, repo, username) {
133
+ try {
134
+ const data = await this.request("GET", `/repos/${owner}/${repo}/collaborators/${encodeURIComponent(username)}/permission`);
135
+ return data;
136
+ }
137
+ catch (err) {
138
+ if (err instanceof GithubApiError && err.status === 404) {
139
+ return { permission: "none" };
140
+ }
141
+ throw err;
142
+ }
143
+ }
144
+ async createPullRequest(owner, repo, params) {
145
+ const pr = await this.request("POST", `/repos/${owner}/${repo}/pulls`, {
146
+ body: params,
147
+ });
148
+ return pr;
149
+ }
105
150
  async listInstallationRepositories() {
106
151
  const data = await this.request("GET", "/installation/repositories?per_page=100");
107
152
  return data.repositories;