@geminixiang/mikan 1.0.0-beta.42 → 1.0.0-beta.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,25 @@ any release.
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [1.0.0-beta.43]
13
+
14
+ ### Added
15
+
16
+ - Add an optional authenticated GitHub webhook endpoint that wakes polling immediately for lower-latency issue and pull-request handling.
17
+ - Add a machine-readable architecture index and generated system architecture documentation for repository-wide module boundaries and flows.
18
+
19
+ ### Changed
20
+
21
+ - Run manual and automatic Session Dreams in the background while preserving session rotation and conversation maintenance boundaries.
22
+
23
+ ### Fixed
24
+
25
+ - Wait for final Slack thread responses in isolation coverage instead of accepting provisional native-stream text.
26
+
27
+ ### Tests
28
+
29
+ - Add regression coverage for GitHub webhook authentication and dispatch, background Session Dream lifecycle behavior, and final Slack stream settlement.
30
+
12
31
  ## [1.0.0-beta.42]
13
32
 
14
33
  ### Changed
@@ -17,6 +17,8 @@ export declare class GithubMessagingBot implements MessagingBot {
17
17
  private repoState;
18
18
  private permissionCache;
19
19
  private pollInFlight;
20
+ private pollPending;
21
+ private requestPollTimer;
20
22
  constructor(handler: MessagingEventHandler, config: GithubBotConfig, client?: GithubClient);
21
23
  start(): Promise<void>;
22
24
  postMessage(channel: string, text: string): Promise<string>;
@@ -29,6 +31,12 @@ export declare class GithubMessagingBot implements MessagingBot {
29
31
  logToFile(conversationId: string, entry: object): void;
30
32
  logBotResponse(conversationId: string, text: string, ts: string): void;
31
33
  private getQueue;
34
+ /**
35
+ * Webhook poke: run a poll soon. Debounced so a burst of deliveries costs
36
+ * one tick; a poke landing mid-poll marks it pending and the tick re-runs,
37
+ * because the in-flight pass may already be past the poked repo's feeds.
38
+ */
39
+ requestPoll(debounceMs?: number): void;
32
40
  /** One poll tick over every watched repo. Public for tests. */
33
41
  poll(): Promise<void>;
34
42
  private pollRepo;
@@ -1 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;;;;;OAKG;YACW,mBAAmB;IAqBjC;;;OAGG;YACW,mBAAmB;YA+BnB,eAAe;IAqC7B;;;;OAIG;YACW,eAAe;CAiC9B"}
@@ -32,6 +32,8 @@ const SyncStateSchema = Type.Object({
32
32
  */
33
33
  const POLL_OVERLAP_MS = 5 * 60 * 1000;
34
34
  const MAX_SEEN_IDS = 5000;
35
+ /** Webhook pokes within this window collapse into one poll tick. */
36
+ const REQUEST_POLL_DEBOUNCE_MS = 1500;
35
37
  /** Effective role → rank, for the trigger-permission gate. */
36
38
  const PERMISSION_RANK = {
37
39
  none: 0,
@@ -121,6 +123,8 @@ export class GithubMessagingBot {
121
123
  this.repoState = new Map();
122
124
  this.permissionCache = new Map();
123
125
  this.pollInFlight = false;
126
+ this.pollPending = false;
127
+ this.requestPollTimer = null;
124
128
  this.handler = handler;
125
129
  this.config = config;
126
130
  this.client =
@@ -272,10 +276,30 @@ export class GithubMessagingBot {
272
276
  }
273
277
  return queue;
274
278
  }
279
+ /**
280
+ * Webhook poke: run a poll soon. Debounced so a burst of deliveries costs
281
+ * one tick; a poke landing mid-poll marks it pending and the tick re-runs,
282
+ * because the in-flight pass may already be past the poked repo's feeds.
283
+ */
284
+ requestPoll(debounceMs = REQUEST_POLL_DEBOUNCE_MS) {
285
+ if (this.pollInFlight) {
286
+ this.pollPending = true;
287
+ return;
288
+ }
289
+ if (this.requestPollTimer)
290
+ return;
291
+ this.requestPollTimer = setTimeout(() => {
292
+ this.requestPollTimer = null;
293
+ void this.poll();
294
+ }, debounceMs);
295
+ this.requestPollTimer.unref();
296
+ }
275
297
  /** One poll tick over every watched repo. Public for tests. */
276
298
  async poll() {
277
- if (this.pollInFlight)
299
+ if (this.pollInFlight) {
300
+ this.pollPending = true;
278
301
  return;
302
+ }
279
303
  this.pollInFlight = true;
280
304
  try {
281
305
  let changed = false;
@@ -293,6 +317,10 @@ export class GithubMessagingBot {
293
317
  }
294
318
  finally {
295
319
  this.pollInFlight = false;
320
+ if (this.pollPending) {
321
+ this.pollPending = false;
322
+ this.requestPoll();
323
+ }
296
324
  }
297
325
  }
298
326
  async pollRepo(repo) {
@@ -1 +1 @@
1
- {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/github/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,OAAO,EAAE,uBAAuB,EAA0B,MAAM,kBAAkB,CAAC;AACnF,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,mBAAmB,EACnB,SAAS,GACV,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,yBAAyB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAe,MAAM,uBAAuB,CAAC;AACzE,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,qBAAqB,EACrB,yBAAyB,EACzB,oBAAoB,GACrB,MAAM,UAAU,CAAC;AAWlB,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC;IAClC,KAAK,EAAE,IAAI,CAAC,MAAM,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Q,EAAE,GAAG,IAAI,CAAC,OAAO,OAAO;gBAChC,QAAQ,EAAE,IAAI,CAAC,QAAQ,IAAI,GAAG,IAAI,CAAC,OAAO,gCAAgC;gBAC1E,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;gBACvC,YAAY;aACb,CAAC,CAAC;YACH,GAAG,CAAC,OAAO,CACT,IAAI,cAAc,YAAY,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,wBAAwB,GAAG,CAAC,MAAM,YAAY,YAAY,IAAI,MAAM,GAAG,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CACvJ,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,UAAU,CACZ,iCAAiC,cAAc,EAAE,EACjD,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CACjD,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { MessagingBot, MessagingEventHandler, MessagingInfo } from \"../../adapter.js\";\nimport { createConversationEvent, type ConversationEvent } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"../../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../../utils/file-guards.js\";\nimport { resolveChatSessionKey } from \"../../sessions/session-key.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n MessagingEventQueue,\n splitText,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { GithubClient, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from \"./client.js\";\nimport { createGithubAdapters } from \"./context.js\";\nimport { fetchIsPr, fetchPrHeadBranch, GithubOps } from \"./github-ops.js\";\nimport { cloneRepo, conversationRepoDir } from \"./repo.js\";\nimport { createOfficeAddress, type Office } from \"../../office/index.js\";\nimport {\n buildGithubConversationId,\n GITHUB_ISSUE_BODY_TS,\n githubReviewCommentTs,\n parseGithubConversationId,\n parseReviewCommentTs,\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 // Optional: state files written before review-comment polling must keep\n // loading — a schema failure re-baselines and silently drops dedup state.\n seenReviewComments: Type.Optional(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 = {\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/** Rank for an arbitrary API-reported permission name; unknown names rank 0. */\nfunction rankOfPermission(name: string): number {\n return PERMISSION_RANK[name as keyof typeof PERMISSION_RANK] ?? 0;\n}\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 seenReviewComments: Set<number>;\n}\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, rc-<id> for review comments, or GITHUB_ISSUE_BODY_TS for the body. */\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 /** Present for inline PR review comments: the diff anchor to inject as context. */\n review?: {\n commentId: number;\n path: string;\n line: number | null;\n diffHunk: string;\n inReplyToId?: number;\n };\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\n/** PR number from a review comment's `pull_request_url` (…/repos/o/r/pulls/42). */\nfunction prNumberFromUrl(pullRequestUrl: string): number {\n const match = /\\/pulls\\/(\\d+)$/.exec(pullRequestUrl);\n if (!match) {\n throw new Error(`Cannot parse PR number from ${pullRequestUrl}`);\n }\n return Number(match[1]);\n}\n\n/** Keep the tail: a review comment anchors to the hunk's final lines. */\nconst MAX_DIFF_HUNK_CHARS = 1500;\nconst MAX_THREAD_TURNS = 10;\nconst MAX_THREAD_TURN_CHARS = 500;\n\nexport class GithubMessagingBot implements MessagingBot {\n private readonly client: GithubClient;\n private readonly handler: MessagingEventHandler;\n private readonly config: GithubBotConfig;\n /** Host-side backend for the github_* tool pack; standalone from polling. */\n readonly ops: GithubOps;\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 this.ops = new GithubOps(this.client, {\n workspace: config.workspace,\n cloudBuild: config.cloudBuild,\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 seenReviewComments: new Set(saved.seenReviewComments ?? []),\n }\n : {\n baseline: now,\n cursor: now,\n seenComments: new Set(),\n seenIssues: new Set(),\n seenReviewComments: new Set(),\n },\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] ?? text);\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 const reviewCommentId = parseReviewCommentTs(messageTs);\n await githubRetry(() => {\n if (messageTs === GITHUB_ISSUE_BODY_TS) {\n return this.client.createIssueReaction(ref.owner, ref.repo, ref.number, content);\n }\n if (reviewCommentId !== null) {\n return this.client.createReviewCommentReaction(\n ref.owner,\n ref.repo,\n reviewCommentId,\n content,\n );\n }\n return 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 trustModel: \"open-trigger\",\n formattingGuide:\n \"## GitHub Formatting (GitHub Flavored Markdown)\\n\" +\n \"Standard Markdown plus tables, task lists, fenced code blocks, and ```suggestion blocks.\\n\" +\n \"Reference issues/PRs as #123 and users as @login (mentions notify people — use sparingly).\",\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.office(conversationId), entry);\n }\n\n logBotResponse(conversationId: string, text: string, ts: string): void {\n appendBotResponseLog(this.office(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 changed =\n (await this.advanceFeed(state, state.seenIssues, issues, (issue) => ({\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 }))) || changed;\n\n const comments = (await this.client.listIssueCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenComments, comments, (comment) => ({\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 }))) || changed;\n\n // Inline PR review comments live in their own endpoint and id space; the\n // same watermark discipline applies. The bot's own thread replies (the\n // github_review_reply tool) re-surface here and are dropped as Bot-authored.\n const reviewComments =\n (await this.client.listPullReviewCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenReviewComments, reviewComments, (comment) => ({\n ref: { ...repo, number: prNumberFromUrl(comment.pull_request_url) },\n ts: githubReviewCommentTs(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n isPr: true,\n review: {\n commentId: comment.id,\n path: comment.path,\n line: comment.line,\n diffHunk: comment.diff_hunk,\n inReplyToId: comment.in_reply_to_id,\n },\n }))) || changed;\n\n pruneSeen(state.seenComments);\n pruneSeen(state.seenIssues);\n pruneSeen(state.seenReviewComments);\n return changed;\n }\n\n /**\n * One feed's watermark advance — the same discipline for all three feeds:\n * bump the cursor on any fresher updated_at, then let the id watermark plus\n * the creation baseline decide what actually triggers (edits re-surface old\n * items with a fresh updated_at). Bot-authored items advance the watermark\n * without triggering.\n */\n private async advanceFeed<\n T extends {\n id: number;\n created_at: string;\n updated_at: string;\n user: { login: string; type: string };\n },\n >(\n state: RepoWatermark,\n seen: Set<number>,\n items: T[],\n toIncoming: (item: T) => IncomingItem,\n ): Promise<boolean> {\n let changed = false;\n for (const item of items) {\n if (item.updated_at > state.cursor) {\n state.cursor = item.updated_at;\n changed = true;\n }\n if (item.created_at < state.baseline || seen.has(item.id)) continue;\n seen.add(item.id);\n changed = true;\n if (item.user.type === \"Bot\") continue;\n await this.handleIncoming(toIncoming(item));\n }\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 /** The persisted form of the current watermarks; the test/inspection surface. */\n syncStateSnapshot(): GithubSyncState {\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 seenReviewComments: [...watermark.seenReviewComments],\n };\n }\n return state;\n }\n\n private persistSyncState(): void {\n ensureDirExists(dirname(this.config.syncStatePath));\n atomicWritePrivateFile(this.config.syncStatePath, JSON.stringify(this.syncStateSnapshot()));\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 /** The Conversation office for a GitHub conversation id (one PR/issue). */\n private office(conversationId: string): Office {\n return this.config.workspace.office(createOfficeAddress(\"github\", conversationId));\n }\n\n private isParticipating(conversationId: string): boolean {\n return existsSync(this.office(conversationId).logPath);\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(rankOfPermission(role.role_name ?? \"\"), rankOfPermission(role.permission));\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 const messageText = item.review\n ? await this.formatReviewMessage(item, cleanedText)\n : cleanedText;\n\n const eventBase = createConversationEvent({\n platform: \"github\",\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: messageText,\n }) as GithubEvent;\n\n await processMessageIntake({\n eventBase,\n office: this.office(eventBase.conversationId),\n isAutoReplyCandidate: false,\n // Match on the user-typed text, not the review-decorated messageText.\n magicWord: { text: cleanedText, addressed: mentioned, scopeFallback: \"never\" },\n busyPolicy: \"queue\",\n logEntryBase: {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: messageText,\n isMessagingBot: false,\n },\n log: (entry) => this.logToFile(conversationId, entry),\n // GitHub has no attachments; the prep hook is used to lay down the\n // issue context and repo clone only for messages that will dispatch,\n // and before the comment itself is logged.\n processAttachments: async () => {\n await this.prepareConversation(item, conversationId, participating);\n return [];\n },\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 /**\n * First contact: log the issue title/body ahead of the comment so the\n * session history starts with what the thread is about. The clone is\n * (re)attempted on every trigger while ./repo is missing — a no-op once\n * it exists — so a failed first clone (e.g. App permissions granted\n * later) heals on the next mention instead of wedging the conversation.\n */\n private async prepareConversation(\n item: IncomingItem,\n conversationId: string,\n participating: boolean,\n ): Promise<void> {\n let isPrHint = item.isPr;\n if (!participating && item.ts !== GITHUB_ISSUE_BODY_TS) {\n const issue = await this.logIssueContext(item.ref, conversationId, item.createdAt);\n // Only comments arrive without the PR-ness hint; review comments carry\n // isPr: true (they only exist on PRs) and that knowledge is authoritative.\n if (issue && isPrHint === undefined) isPrHint = Boolean(issue.pull_request);\n }\n if (!existsSync(conversationRepoDir(this.office(conversationId)))) {\n const isPr = isPrHint ?? (await fetchIsPr(this.client, item.ref));\n await this.ensureRepoClone(item.ref, conversationId, isPr);\n }\n }\n\n /**\n * Decorates an inline review comment with its diff anchor and (for replies)\n * the thread's earlier turns, so the agent knows which code the feedback is\n * about without hunting through the PR. The rc-<id> in the header is what\n * github_review_reply takes to answer in-thread.\n */\n private async formatReviewMessage(item: IncomingItem, cleanedText: string): Promise<string> {\n const review = item.review!;\n const location = review.line !== null ? `${review.path}:${review.line}` : review.path;\n const parts = [`[PR review comment ${githubReviewCommentTs(review.commentId)} on ${location}]`];\n if (review.diffHunk) {\n const hunk =\n review.diffHunk.length > MAX_DIFF_HUNK_CHARS\n ? `…${review.diffHunk.slice(-MAX_DIFF_HUNK_CHARS)}`\n : review.diffHunk;\n parts.push(`\\`\\`\\`diff\\n${hunk}\\n\\`\\`\\``);\n }\n if (review.inReplyToId !== undefined) {\n const turns = await this.reviewThreadContext(item.ref, review.inReplyToId, review.commentId);\n if (turns.length > 0) {\n parts.push(`Thread so far:\\n${turns.join(\"\\n\")}`);\n }\n }\n parts.push(cleanedText);\n return parts.join(\"\\n\");\n }\n\n /**\n * Earlier turns of one review thread (root + replies before the trigger),\n * newest-truncated. Fail-soft: context is a nicety, the trigger is not.\n */\n private async reviewThreadContext(\n ref: GithubConversationRef,\n rootId: number,\n beforeId: number,\n ): Promise<string[]> {\n try {\n const all = await githubRetry(() =>\n this.client.listPullReviewComments(ref.owner, ref.repo, ref.number),\n );\n return all\n .filter(\n (comment) =>\n (comment.id === rootId || comment.in_reply_to_id === rootId) && comment.id < beforeId,\n )\n .slice(-MAX_THREAD_TURNS)\n .map((comment) => {\n const body =\n comment.body.length > MAX_THREAD_TURN_CHARS\n ? `${comment.body.slice(0, MAX_THREAD_TURN_CHARS)}…`\n : comment.body;\n return `@${comment.user.login}: ${body}`;\n });\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch review thread context for ${ref.owner}/${ref.repo}#${ref.number}`,\n err instanceof Error ? err.message : String(err),\n );\n return [];\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\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 office = this.office(conversationId);\n const dir = conversationRepoDir(office);\n if (existsSync(dir)) return;\n try {\n office.ensure();\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"read\",\n });\n const prHeadBranch = isPr ? await fetchPrHeadBranch(this.client, ref) : undefined;\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 prHeadBranch,\n });\n log.logInfo(\n `[${conversationId}] Cloned ${ref.owner}/${ref.repo}${isPr ? ` and checked out PR #${ref.number} head as ${prHeadBranch ?? `pr-${ref.number}`}` : \"\"}`,\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"]}
1
+ {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/github/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,OAAO,EAAE,uBAAuB,EAA0B,MAAM,kBAAkB,CAAC;AACnF,OAAO,KAAK,GAAG,M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I,CAAC,MAAM,CAAC,6BAA6B,CAAC,GAAG,CAAC,IAAI,EAAE;gBACtE,QAAQ,EAAE,MAAM;aACjB,CAAC,CAAC;YACH,MAAM,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,iBAAiB,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAClF,MAAM,SAAS,CAAC;gBACd,GAAG,EAAE,sBAAsB,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,IAAI,MAAM;gBACtD,GAAG;gBACH,KAAK;gBACL,QAAQ,EAAE,GAAG,IAAI,CAAC,OAAO,OAAO;gBAChC,QAAQ,EAAE,IAAI,CAAC,QAAQ,IAAI,GAAG,IAAI,CAAC,OAAO,gCAAgC;gBAC1E,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;gBACvC,YAAY;aACb,CAAC,CAAC;YACH,GAAG,CAAC,OAAO,CACT,IAAI,cAAc,YAAY,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,wBAAwB,GAAG,CAAC,MAAM,YAAY,YAAY,IAAI,MAAM,GAAG,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CACvJ,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,UAAU,CACZ,iCAAiC,cAAc,EAAE,EACjD,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CACjD,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { MessagingBot, MessagingEventHandler, MessagingInfo } from \"../../adapter.js\";\nimport { createConversationEvent, type ConversationEvent } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"../../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../../utils/file-guards.js\";\nimport { resolveChatSessionKey } from \"../../sessions/session-key.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n MessagingEventQueue,\n splitText,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { GithubClient, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from \"./client.js\";\nimport { createGithubAdapters } from \"./context.js\";\nimport { fetchIsPr, fetchPrHeadBranch, GithubOps } from \"./github-ops.js\";\nimport { cloneRepo, conversationRepoDir } from \"./repo.js\";\nimport { createOfficeAddress, type Office } from \"../../office/index.js\";\nimport {\n buildGithubConversationId,\n GITHUB_ISSUE_BODY_TS,\n githubReviewCommentTs,\n parseGithubConversationId,\n parseReviewCommentTs,\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 // Optional: state files written before review-comment polling must keep\n // loading — a schema failure re-baselines and silently drops dedup state.\n seenReviewComments: Type.Optional(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/** Webhook pokes within this window collapse into one poll tick. */\nconst REQUEST_POLL_DEBOUNCE_MS = 1500;\n\n/** Effective role → rank, for the trigger-permission gate. */\nconst PERMISSION_RANK = {\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/** Rank for an arbitrary API-reported permission name; unknown names rank 0. */\nfunction rankOfPermission(name: string): number {\n return PERMISSION_RANK[name as keyof typeof PERMISSION_RANK] ?? 0;\n}\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 seenReviewComments: Set<number>;\n}\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, rc-<id> for review comments, or GITHUB_ISSUE_BODY_TS for the body. */\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 /** Present for inline PR review comments: the diff anchor to inject as context. */\n review?: {\n commentId: number;\n path: string;\n line: number | null;\n diffHunk: string;\n inReplyToId?: number;\n };\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\n/** PR number from a review comment's `pull_request_url` (…/repos/o/r/pulls/42). */\nfunction prNumberFromUrl(pullRequestUrl: string): number {\n const match = /\\/pulls\\/(\\d+)$/.exec(pullRequestUrl);\n if (!match) {\n throw new Error(`Cannot parse PR number from ${pullRequestUrl}`);\n }\n return Number(match[1]);\n}\n\n/** Keep the tail: a review comment anchors to the hunk's final lines. */\nconst MAX_DIFF_HUNK_CHARS = 1500;\nconst MAX_THREAD_TURNS = 10;\nconst MAX_THREAD_TURN_CHARS = 500;\n\nexport class GithubMessagingBot implements MessagingBot {\n private readonly client: GithubClient;\n private readonly handler: MessagingEventHandler;\n private readonly config: GithubBotConfig;\n /** Host-side backend for the github_* tool pack; standalone from polling. */\n readonly ops: GithubOps;\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 private pollPending = false;\n private requestPollTimer: NodeJS.Timeout | null = null;\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 this.ops = new GithubOps(this.client, {\n workspace: config.workspace,\n cloudBuild: config.cloudBuild,\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 seenReviewComments: new Set(saved.seenReviewComments ?? []),\n }\n : {\n baseline: now,\n cursor: now,\n seenComments: new Set(),\n seenIssues: new Set(),\n seenReviewComments: new Set(),\n },\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] ?? text);\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 const reviewCommentId = parseReviewCommentTs(messageTs);\n await githubRetry(() => {\n if (messageTs === GITHUB_ISSUE_BODY_TS) {\n return this.client.createIssueReaction(ref.owner, ref.repo, ref.number, content);\n }\n if (reviewCommentId !== null) {\n return this.client.createReviewCommentReaction(\n ref.owner,\n ref.repo,\n reviewCommentId,\n content,\n );\n }\n return 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 trustModel: \"open-trigger\",\n formattingGuide:\n \"## GitHub Formatting (GitHub Flavored Markdown)\\n\" +\n \"Standard Markdown plus tables, task lists, fenced code blocks, and ```suggestion blocks.\\n\" +\n \"Reference issues/PRs as #123 and users as @login (mentions notify people — use sparingly).\",\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.office(conversationId), entry);\n }\n\n logBotResponse(conversationId: string, text: string, ts: string): void {\n appendBotResponseLog(this.office(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 /**\n * Webhook poke: run a poll soon. Debounced so a burst of deliveries costs\n * one tick; a poke landing mid-poll marks it pending and the tick re-runs,\n * because the in-flight pass may already be past the poked repo's feeds.\n */\n requestPoll(debounceMs = REQUEST_POLL_DEBOUNCE_MS): void {\n if (this.pollInFlight) {\n this.pollPending = true;\n return;\n }\n if (this.requestPollTimer) return;\n this.requestPollTimer = setTimeout(() => {\n this.requestPollTimer = null;\n void this.poll();\n }, debounceMs);\n this.requestPollTimer.unref();\n }\n\n /** One poll tick over every watched repo. Public for tests. */\n async poll(): Promise<void> {\n if (this.pollInFlight) {\n this.pollPending = true;\n return;\n }\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 if (this.pollPending) {\n this.pollPending = false;\n this.requestPoll();\n }\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 changed =\n (await this.advanceFeed(state, state.seenIssues, issues, (issue) => ({\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 }))) || changed;\n\n const comments = (await this.client.listIssueCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenComments, comments, (comment) => ({\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 }))) || changed;\n\n // Inline PR review comments live in their own endpoint and id space; the\n // same watermark discipline applies. The bot's own thread replies (the\n // github_review_reply tool) re-surface here and are dropped as Bot-authored.\n const reviewComments =\n (await this.client.listPullReviewCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenReviewComments, reviewComments, (comment) => ({\n ref: { ...repo, number: prNumberFromUrl(comment.pull_request_url) },\n ts: githubReviewCommentTs(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n isPr: true,\n review: {\n commentId: comment.id,\n path: comment.path,\n line: comment.line,\n diffHunk: comment.diff_hunk,\n inReplyToId: comment.in_reply_to_id,\n },\n }))) || changed;\n\n pruneSeen(state.seenComments);\n pruneSeen(state.seenIssues);\n pruneSeen(state.seenReviewComments);\n return changed;\n }\n\n /**\n * One feed's watermark advance — the same discipline for all three feeds:\n * bump the cursor on any fresher updated_at, then let the id watermark plus\n * the creation baseline decide what actually triggers (edits re-surface old\n * items with a fresh updated_at). Bot-authored items advance the watermark\n * without triggering.\n */\n private async advanceFeed<\n T extends {\n id: number;\n created_at: string;\n updated_at: string;\n user: { login: string; type: string };\n },\n >(\n state: RepoWatermark,\n seen: Set<number>,\n items: T[],\n toIncoming: (item: T) => IncomingItem,\n ): Promise<boolean> {\n let changed = false;\n for (const item of items) {\n if (item.updated_at > state.cursor) {\n state.cursor = item.updated_at;\n changed = true;\n }\n if (item.created_at < state.baseline || seen.has(item.id)) continue;\n seen.add(item.id);\n changed = true;\n if (item.user.type === \"Bot\") continue;\n await this.handleIncoming(toIncoming(item));\n }\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 /** The persisted form of the current watermarks; the test/inspection surface. */\n syncStateSnapshot(): GithubSyncState {\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 seenReviewComments: [...watermark.seenReviewComments],\n };\n }\n return state;\n }\n\n private persistSyncState(): void {\n ensureDirExists(dirname(this.config.syncStatePath));\n atomicWritePrivateFile(this.config.syncStatePath, JSON.stringify(this.syncStateSnapshot()));\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 /** The Conversation office for a GitHub conversation id (one PR/issue). */\n private office(conversationId: string): Office {\n return this.config.workspace.office(createOfficeAddress(\"github\", conversationId));\n }\n\n private isParticipating(conversationId: string): boolean {\n return existsSync(this.office(conversationId).logPath);\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(rankOfPermission(role.role_name ?? \"\"), rankOfPermission(role.permission));\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 const messageText = item.review\n ? await this.formatReviewMessage(item, cleanedText)\n : cleanedText;\n\n const eventBase = createConversationEvent({\n platform: \"github\",\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: messageText,\n }) as GithubEvent;\n\n await processMessageIntake({\n eventBase,\n office: this.office(eventBase.conversationId),\n isAutoReplyCandidate: false,\n // Match on the user-typed text, not the review-decorated messageText.\n magicWord: { text: cleanedText, addressed: mentioned, scopeFallback: \"never\" },\n busyPolicy: \"queue\",\n logEntryBase: {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: messageText,\n isMessagingBot: false,\n },\n log: (entry) => this.logToFile(conversationId, entry),\n // GitHub has no attachments; the prep hook is used to lay down the\n // issue context and repo clone only for messages that will dispatch,\n // and before the comment itself is logged.\n processAttachments: async () => {\n await this.prepareConversation(item, conversationId, participating);\n return [];\n },\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 /**\n * First contact: log the issue title/body ahead of the comment so the\n * session history starts with what the thread is about. The clone is\n * (re)attempted on every trigger while ./repo is missing — a no-op once\n * it exists — so a failed first clone (e.g. App permissions granted\n * later) heals on the next mention instead of wedging the conversation.\n */\n private async prepareConversation(\n item: IncomingItem,\n conversationId: string,\n participating: boolean,\n ): Promise<void> {\n let isPrHint = item.isPr;\n if (!participating && item.ts !== GITHUB_ISSUE_BODY_TS) {\n const issue = await this.logIssueContext(item.ref, conversationId, item.createdAt);\n // Only comments arrive without the PR-ness hint; review comments carry\n // isPr: true (they only exist on PRs) and that knowledge is authoritative.\n if (issue && isPrHint === undefined) isPrHint = Boolean(issue.pull_request);\n }\n if (!existsSync(conversationRepoDir(this.office(conversationId)))) {\n const isPr = isPrHint ?? (await fetchIsPr(this.client, item.ref));\n await this.ensureRepoClone(item.ref, conversationId, isPr);\n }\n }\n\n /**\n * Decorates an inline review comment with its diff anchor and (for replies)\n * the thread's earlier turns, so the agent knows which code the feedback is\n * about without hunting through the PR. The rc-<id> in the header is what\n * github_review_reply takes to answer in-thread.\n */\n private async formatReviewMessage(item: IncomingItem, cleanedText: string): Promise<string> {\n const review = item.review!;\n const location = review.line !== null ? `${review.path}:${review.line}` : review.path;\n const parts = [`[PR review comment ${githubReviewCommentTs(review.commentId)} on ${location}]`];\n if (review.diffHunk) {\n const hunk =\n review.diffHunk.length > MAX_DIFF_HUNK_CHARS\n ? `…${review.diffHunk.slice(-MAX_DIFF_HUNK_CHARS)}`\n : review.diffHunk;\n parts.push(`\\`\\`\\`diff\\n${hunk}\\n\\`\\`\\``);\n }\n if (review.inReplyToId !== undefined) {\n const turns = await this.reviewThreadContext(item.ref, review.inReplyToId, review.commentId);\n if (turns.length > 0) {\n parts.push(`Thread so far:\\n${turns.join(\"\\n\")}`);\n }\n }\n parts.push(cleanedText);\n return parts.join(\"\\n\");\n }\n\n /**\n * Earlier turns of one review thread (root + replies before the trigger),\n * newest-truncated. Fail-soft: context is a nicety, the trigger is not.\n */\n private async reviewThreadContext(\n ref: GithubConversationRef,\n rootId: number,\n beforeId: number,\n ): Promise<string[]> {\n try {\n const all = await githubRetry(() =>\n this.client.listPullReviewComments(ref.owner, ref.repo, ref.number),\n );\n return all\n .filter(\n (comment) =>\n (comment.id === rootId || comment.in_reply_to_id === rootId) && comment.id < beforeId,\n )\n .slice(-MAX_THREAD_TURNS)\n .map((comment) => {\n const body =\n comment.body.length > MAX_THREAD_TURN_CHARS\n ? `${comment.body.slice(0, MAX_THREAD_TURN_CHARS)}…`\n : comment.body;\n return `@${comment.user.login}: ${body}`;\n });\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch review thread context for ${ref.owner}/${ref.repo}#${ref.number}`,\n err instanceof Error ? err.message : String(err),\n );\n return [];\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\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 office = this.office(conversationId);\n const dir = conversationRepoDir(office);\n if (existsSync(dir)) return;\n try {\n office.ensure();\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"read\",\n });\n const prHeadBranch = isPr ? await fetchPrHeadBranch(this.client, ref) : undefined;\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 prHeadBranch,\n });\n log.logInfo(\n `[${conversationId}] Cloned ${ref.owner}/${ref.repo}${isPr ? ` and checked out PR #${ref.number} head as ${prHeadBranch ?? `pr-${ref.number}`}` : \"\"}`,\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"]}
@@ -0,0 +1,23 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ /**
3
+ * GitHub webhook receiver — a poke, not an event source. Deliveries are
4
+ * unordered, unguaranteed, and may repeat, so the payload is never parsed into
5
+ * the intake pipeline; a verified delivery only asks the bot to poll soon, and
6
+ * the poll's watermark/dedup discipline decides what actually triggers
7
+ * (DESIGN.md § Event source). Polling stays on as the missed-delivery
8
+ * backstop.
9
+ */
10
+ export declare const GITHUB_WEBHOOK_PATH = "/github/webhook";
11
+ export interface GithubWebhookOptions {
12
+ secret: string;
13
+ /** Called after signature verification for relevant events. */
14
+ onPoke: () => void;
15
+ }
16
+ /** Constant-time check of `X-Hub-Signature-256: sha256=<hex>` over the raw body. */
17
+ export declare function verifyWebhookSignature(secret: string, body: Buffer, signatureHeader: string | undefined): boolean;
18
+ /**
19
+ * Handle a request if it targets the webhook path. Returns false when the
20
+ * request is not for this route so the caller falls through.
21
+ */
22
+ export declare function handleGithubWebhookRequest(req: IncomingMessage, res: ServerResponse, url: URL, options: GithubWebhookOptions): Promise<boolean>;
23
+ //# sourceMappingURL=webhook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/webhook.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAGjE;;;;;;;GAOG;AAEH,eAAO,MAAM,mBAAmB,oBAAoB,CAAC;AAQrD,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,+DAA+D;IAC/D,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB;AAoBD,oFAAoF;AACpF,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,eAAe,EAAE,MAAM,GAAG,SAAS,GAClC,OAAO,CAMT;AAED;;;GAGG;AACH,wBAAsB,0BAA0B,CAC9C,GAAG,EAAE,eAAe,EACpB,GAAG,EAAE,cAAc,EACnB,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,OAAO,CAAC,CAoClB"}
@@ -0,0 +1,78 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import * as log from "../../log.js";
3
+ /**
4
+ * GitHub webhook receiver — a poke, not an event source. Deliveries are
5
+ * unordered, unguaranteed, and may repeat, so the payload is never parsed into
6
+ * the intake pipeline; a verified delivery only asks the bot to poll soon, and
7
+ * the poll's watermark/dedup discipline decides what actually triggers
8
+ * (DESIGN.md § Event source). Polling stays on as the missed-delivery
9
+ * backstop.
10
+ */
11
+ export const GITHUB_WEBHOOK_PATH = "/github/webhook";
12
+ /** Events that can carry a new conversation-triggering item. */
13
+ const POKE_EVENTS = new Set(["issues", "issue_comment", "pull_request_review_comment"]);
14
+ /** GitHub payloads are small; anything larger than this is not GitHub. */
15
+ const MAX_BODY_BYTES = 1024 * 1024;
16
+ function readBody(req, maxBytes) {
17
+ return new Promise((resolve, reject) => {
18
+ const chunks = [];
19
+ let size = 0;
20
+ req.on("data", (chunk) => {
21
+ size += chunk.length;
22
+ if (size > maxBytes) {
23
+ resolve(null);
24
+ req.destroy();
25
+ return;
26
+ }
27
+ chunks.push(chunk);
28
+ });
29
+ req.on("end", () => resolve(Buffer.concat(chunks)));
30
+ req.on("error", reject);
31
+ });
32
+ }
33
+ /** Constant-time check of `X-Hub-Signature-256: sha256=<hex>` over the raw body. */
34
+ export function verifyWebhookSignature(secret, body, signatureHeader) {
35
+ if (!signatureHeader?.startsWith("sha256="))
36
+ return false;
37
+ const expected = createHmac("sha256", secret).update(body).digest("hex");
38
+ const received = signatureHeader.slice("sha256=".length);
39
+ if (received.length !== expected.length)
40
+ return false;
41
+ return timingSafeEqual(Buffer.from(received, "utf-8"), Buffer.from(expected, "utf-8"));
42
+ }
43
+ /**
44
+ * Handle a request if it targets the webhook path. Returns false when the
45
+ * request is not for this route so the caller falls through.
46
+ */
47
+ export async function handleGithubWebhookRequest(req, res, url, options) {
48
+ if (url.pathname !== GITHUB_WEBHOOK_PATH)
49
+ return false;
50
+ if (req.method !== "POST") {
51
+ res.writeHead(405).end();
52
+ return true;
53
+ }
54
+ const body = await readBody(req, MAX_BODY_BYTES);
55
+ if (body === null) {
56
+ res.writeHead(413).end();
57
+ return true;
58
+ }
59
+ const signature = req.headers["x-hub-signature-256"];
60
+ if (!verifyWebhookSignature(options.secret, body, typeof signature === "string" ? signature : undefined)) {
61
+ log.logWarning("GitHub webhook: rejected delivery with bad or missing signature");
62
+ res.writeHead(401).end();
63
+ return true;
64
+ }
65
+ const event = req.headers["x-github-event"];
66
+ if (event === "ping") {
67
+ res.writeHead(200, { "Content-Type": "application/json" });
68
+ res.end(JSON.stringify({ ok: true }));
69
+ return true;
70
+ }
71
+ // Respond before the poll runs — GitHub times deliveries out at 10s.
72
+ res.writeHead(202).end();
73
+ if (typeof event === "string" && POKE_EVENTS.has(event)) {
74
+ options.onPoke();
75
+ }
76
+ return true;
77
+ }
78
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +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,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CACtD,EACD,CAAC;QACD,GAAG,CAAC,UAAU,CAAC,iEAAiE,CAAC,CAAC;QAClF,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC5C,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QACrB,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAC,CAAC;QAC3D,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,qEAAqE;IACrE,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;IACzB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QACxD,OAAO,CAAC,MAAM,EAAE,CAAC;IACnB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as log from \"../../log.js\";\n\n/**\n * GitHub webhook receiver — a poke, not an event source. Deliveries are\n * unordered, unguaranteed, and may repeat, so the payload is never parsed into\n * the intake pipeline; a verified delivery only asks the bot to poll soon, and\n * the poll's watermark/dedup discipline decides what actually triggers\n * (DESIGN.md § Event source). Polling stays on as the missed-delivery\n * backstop.\n */\n\nexport const GITHUB_WEBHOOK_PATH = \"/github/webhook\";\n\n/** Events that can carry a new conversation-triggering item. */\nconst POKE_EVENTS = new Set([\"issues\", \"issue_comment\", \"pull_request_review_comment\"]);\n\n/** GitHub payloads are small; anything larger than this is not GitHub. */\nconst MAX_BODY_BYTES = 1024 * 1024;\n\nexport interface GithubWebhookOptions {\n secret: string;\n /** Called after signature verification for relevant events. */\n onPoke: () => void;\n}\n\nfunction readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer | null> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n req.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > maxBytes) {\n resolve(null);\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => resolve(Buffer.concat(chunks)));\n req.on(\"error\", reject);\n });\n}\n\n/** Constant-time check of `X-Hub-Signature-256: sha256=<hex>` over the raw body. */\nexport function verifyWebhookSignature(\n secret: string,\n body: Buffer,\n signatureHeader: string | undefined,\n): boolean {\n if (!signatureHeader?.startsWith(\"sha256=\")) return false;\n const expected = createHmac(\"sha256\", secret).update(body).digest(\"hex\");\n const received = signatureHeader.slice(\"sha256=\".length);\n if (received.length !== expected.length) return false;\n return timingSafeEqual(Buffer.from(received, \"utf-8\"), Buffer.from(expected, \"utf-8\"));\n}\n\n/**\n * Handle a request if it targets the webhook path. Returns false when the\n * request is not for this route so the caller falls through.\n */\nexport async function handleGithubWebhookRequest(\n req: IncomingMessage,\n res: ServerResponse,\n url: URL,\n options: GithubWebhookOptions,\n): Promise<boolean> {\n if (url.pathname !== GITHUB_WEBHOOK_PATH) return false;\n if (req.method !== \"POST\") {\n res.writeHead(405).end();\n return true;\n }\n const body = await readBody(req, MAX_BODY_BYTES);\n if (body === null) {\n res.writeHead(413).end();\n return true;\n }\n const signature = req.headers[\"x-hub-signature-256\"];\n if (\n !verifyWebhookSignature(\n options.secret,\n body,\n typeof signature === \"string\" ? signature : undefined,\n )\n ) {\n log.logWarning(\"GitHub webhook: rejected delivery with bad or missing signature\");\n res.writeHead(401).end();\n return true;\n }\n\n const event = req.headers[\"x-github-event\"];\n if (event === \"ping\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true }));\n return true;\n }\n // Respond before the poll runs — GitHub times deliveries out at 10s.\n res.writeHead(202).end();\n if (typeof event === \"string\" && POKE_EVENTS.has(event)) {\n options.onPoke();\n }\n return true;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"env-manifest.d.ts","sourceRoot":"","sources":["../src/env-manifest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMxD;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAG/D;AAED,YAAY,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,eAAO,MAAM,YAAY,EAAE,SAAS,QAAQ,EA6J3C,CAAC;AAEF,KAAK,SAAS,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;AAQtD,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,SAAmB,GAAG,OAAO,CAM/E;AAED,wBAAgB,kBAAkB,CAAC,GAAG,GAAE,SAAmB,GAAG,MAAM,EAAE,CAIrE;AASD,wBAAgB,kBAAkB,IAAI,MAAM,CAK3C;AAED,0EAA0E;AAC1E,wBAAgB,eAAe,IAAI,MAAM,EAAE,CAI1C;AAED,mFAAmF;AACnF,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,EAAE,CAM7E;AAED,gFAAgF;AAChF,wBAAgB,SAAS,CAAC,GAAG,GAAE,SAAmB,GAAG,MAAM,CAuB1D"}
1
+ {"version":3,"file":"env-manifest.d.ts","sourceRoot":"","sources":["../src/env-manifest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMxD;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAG/D;AAED,YAAY,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,eAAO,MAAM,YAAY,EAAE,SAAS,QAAQ,EAkK3C,CAAC;AAEF,KAAK,SAAS,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;AAQtD,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,SAAmB,GAAG,OAAO,CAM/E;AAED,wBAAgB,kBAAkB,CAAC,GAAG,GAAE,SAAmB,GAAG,MAAM,EAAE,CAIrE;AASD,wBAAgB,kBAAkB,IAAI,MAAM,CAK3C;AAED,0EAA0E;AAC1E,wBAAgB,eAAe,IAAI,MAAM,EAAE,CAI1C;AAED,mFAAmF;AACnF,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,EAAE,CAM7E;AAED,gFAAgF;AAChF,wBAAgB,SAAS,CAAC,GAAG,GAAE,SAAmB,GAAG,MAAM,CAuB1D"}
@@ -44,7 +44,7 @@ export const ENV_MANIFEST = [
44
44
  key: "github",
45
45
  title: "GitHub",
46
46
  kind: "platform",
47
- doc: "Issue/PR conversations via a GitHub App (polling, no webhook)",
47
+ doc: "Issue/PR conversations via a GitHub App (polling; optional webhook poke)",
48
48
  vars: [
49
49
  { name: "GITHUB_APP_ID", required: true, doc: "GitHub App id" },
50
50
  { name: "GITHUB_INSTALLATION_ID", required: true, doc: "App installation id" },
@@ -63,6 +63,11 @@ export const ENV_MANIFEST = [
63
63
  doc: "Comma-separated owner/repo allowlist (default: all installed)",
64
64
  },
65
65
  { name: "GITHUB_POLL_INTERVAL", doc: "Poll interval in seconds (default 60)" },
66
+ {
67
+ name: "GITHUB_WEBHOOK_SECRET",
68
+ secret: true,
69
+ doc: "Webhook secret; when set, deliveries to /github/webhook trigger an immediate poll (needs LINK_PORT)",
70
+ },
66
71
  ],
67
72
  anyOf: ["GITHUB_APP_PRIVATE_KEY", "GITHUB_APP_PRIVATE_KEY_PATH"],
68
73
  },