@geminixiang/mikan 1.0.0-beta.37 → 1.0.0-beta.39

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 (201) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +1 -1
  3. package/dist/adapter.js +1 -1
  4. package/dist/adapter.js.map +1 -1
  5. package/dist/adapters/discord/bot.d.ts +3 -6
  6. package/dist/adapters/discord/bot.d.ts.map +1 -1
  7. package/dist/adapters/discord/bot.js +16 -39
  8. package/dist/adapters/discord/bot.js.map +1 -1
  9. package/dist/adapters/github/bot.d.ts +2 -0
  10. package/dist/adapters/github/bot.d.ts.map +1 -1
  11. package/dist/adapters/github/bot.js +15 -11
  12. package/dist/adapters/github/bot.js.map +1 -1
  13. package/dist/adapters/github/github-ops.d.ts +1 -1
  14. package/dist/adapters/github/github-ops.d.ts.map +1 -1
  15. package/dist/adapters/github/github-ops.js +2 -1
  16. package/dist/adapters/github/github-ops.js.map +1 -1
  17. package/dist/adapters/github/repo.d.ts +2 -1
  18. package/dist/adapters/github/repo.d.ts.map +1 -1
  19. package/dist/adapters/github/repo.js +2 -3
  20. package/dist/adapters/github/repo.js.map +1 -1
  21. package/dist/adapters/github/types.d.ts +1 -1
  22. package/dist/adapters/github/types.d.ts.map +1 -1
  23. package/dist/adapters/github/types.js.map +1 -1
  24. package/dist/adapters/intake.js +1 -1
  25. package/dist/adapters/intake.js.map +1 -1
  26. package/dist/adapters/shared.d.ts +17 -5
  27. package/dist/adapters/shared.d.ts.map +1 -1
  28. package/dist/adapters/shared.js +44 -8
  29. package/dist/adapters/shared.js.map +1 -1
  30. package/dist/adapters/slack/blocks.d.ts +14 -0
  31. package/dist/adapters/slack/blocks.d.ts.map +1 -1
  32. package/dist/adapters/slack/blocks.js +34 -0
  33. package/dist/adapters/slack/blocks.js.map +1 -1
  34. package/dist/adapters/slack/bot.d.ts +19 -6
  35. package/dist/adapters/slack/bot.d.ts.map +1 -1
  36. package/dist/adapters/slack/bot.js +88 -21
  37. package/dist/adapters/slack/bot.js.map +1 -1
  38. package/dist/adapters/slack/types.d.ts +1 -1
  39. package/dist/adapters/slack/types.js.map +1 -1
  40. package/dist/adapters/telegram/bot.d.ts +5 -6
  41. package/dist/adapters/telegram/bot.d.ts.map +1 -1
  42. package/dist/adapters/telegram/bot.js +29 -51
  43. package/dist/adapters/telegram/bot.js.map +1 -1
  44. package/dist/adapters/types.d.ts +19 -1
  45. package/dist/adapters/types.d.ts.map +1 -1
  46. package/dist/adapters/types.js.map +1 -1
  47. package/dist/agent.d.ts +0 -1
  48. package/dist/agent.d.ts.map +1 -1
  49. package/dist/agent.js +79 -101
  50. package/dist/agent.js.map +1 -1
  51. package/dist/cli/ext-dev.d.ts.map +1 -1
  52. package/dist/cli/ext-dev.js +8 -8
  53. package/dist/cli/ext-dev.js.map +1 -1
  54. package/dist/cli/ext.js +3 -3
  55. package/dist/cli/ext.js.map +1 -1
  56. package/dist/cli/office.js +2 -2
  57. package/dist/cli/office.js.map +1 -1
  58. package/dist/commands/auto-reply.d.ts.map +1 -1
  59. package/dist/commands/auto-reply.js +1 -2
  60. package/dist/commands/auto-reply.js.map +1 -1
  61. package/dist/commands/login.js +1 -1
  62. package/dist/commands/login.js.map +1 -1
  63. package/dist/commands/manifest.d.ts.map +1 -1
  64. package/dist/commands/manifest.js +3 -1
  65. package/dist/commands/manifest.js.map +1 -1
  66. package/dist/commands/model.d.ts.map +1 -1
  67. package/dist/commands/model.js +3 -7
  68. package/dist/commands/model.js.map +1 -1
  69. package/dist/commands/sandbox.d.ts.map +1 -1
  70. package/dist/commands/sandbox.js +7 -7
  71. package/dist/commands/sandbox.js.map +1 -1
  72. package/dist/commands/session-view.d.ts.map +1 -1
  73. package/dist/commands/session-view.js +1 -2
  74. package/dist/commands/session-view.js.map +1 -1
  75. package/dist/commands/types.d.ts +2 -1
  76. package/dist/commands/types.d.ts.map +1 -1
  77. package/dist/commands/types.js.map +1 -1
  78. package/dist/config.d.ts +10 -18
  79. package/dist/config.d.ts.map +1 -1
  80. package/dist/config.js +16 -15
  81. package/dist/config.js.map +1 -1
  82. package/dist/execution-resolver.d.ts +4 -6
  83. package/dist/execution-resolver.d.ts.map +1 -1
  84. package/dist/execution-resolver.js +10 -19
  85. package/dist/execution-resolver.js.map +1 -1
  86. package/dist/harness/extensions/loader.js +1 -1
  87. package/dist/harness/extensions/loader.js.map +1 -1
  88. package/dist/harness/skills.d.ts +8 -0
  89. package/dist/harness/skills.d.ts.map +1 -1
  90. package/dist/harness/skills.js +46 -4
  91. package/dist/harness/skills.js.map +1 -1
  92. package/dist/harness/types.d.ts +2 -0
  93. package/dist/harness/types.d.ts.map +1 -1
  94. package/dist/harness/types.js.map +1 -1
  95. package/dist/index.d.ts +2 -0
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +1 -0
  98. package/dist/index.js.map +1 -1
  99. package/dist/main.js +16 -16
  100. package/dist/main.js.map +1 -1
  101. package/dist/{office-address.d.ts → office/address.d.ts} +13 -14
  102. package/dist/office/address.d.ts.map +1 -0
  103. package/dist/{office-address.js → office/address.js} +13 -18
  104. package/dist/office/address.js.map +1 -0
  105. package/dist/office/index.d.ts +11 -0
  106. package/dist/office/index.d.ts.map +1 -0
  107. package/dist/office/index.js +11 -0
  108. package/dist/office/index.js.map +1 -0
  109. package/dist/office/layout.d.ts +20 -0
  110. package/dist/office/layout.d.ts.map +1 -0
  111. package/dist/office/layout.js +88 -0
  112. package/dist/office/layout.js.map +1 -0
  113. package/dist/{office-migration.d.ts → office/migration.d.ts} +3 -3
  114. package/dist/office/migration.d.ts.map +1 -0
  115. package/dist/{office-migration.js → office/migration.js} +8 -12
  116. package/dist/office/migration.js.map +1 -0
  117. package/dist/{office-registry.d.ts → office/registry.d.ts} +18 -24
  118. package/dist/office/registry.d.ts.map +1 -0
  119. package/dist/{office-registry.js → office/registry.js} +22 -83
  120. package/dist/office/registry.js.map +1 -0
  121. package/dist/office/types.d.ts +71 -0
  122. package/dist/office/types.d.ts.map +1 -0
  123. package/dist/office/types.js +2 -0
  124. package/dist/office/types.js.map +1 -0
  125. package/dist/packages/admin.js +5 -5
  126. package/dist/packages/admin.js.map +1 -1
  127. package/dist/packages/inspect.d.ts.map +1 -1
  128. package/dist/packages/inspect.js +3 -8
  129. package/dist/packages/inspect.js.map +1 -1
  130. package/dist/packages/materialize.js +1 -1
  131. package/dist/packages/materialize.js.map +1 -1
  132. package/dist/packages/resolve.js +5 -8
  133. package/dist/packages/resolve.js.map +1 -1
  134. package/dist/packages/types.d.ts +2 -5
  135. package/dist/packages/types.d.ts.map +1 -1
  136. package/dist/packages/types.js.map +1 -1
  137. package/dist/runtime/conversation-runtime.d.ts.map +1 -1
  138. package/dist/runtime/conversation-runtime.js +13 -15
  139. package/dist/runtime/conversation-runtime.js.map +1 -1
  140. package/dist/runtime/session-lifecycle.js +1 -1
  141. package/dist/runtime/session-lifecycle.js.map +1 -1
  142. package/dist/runtime/types.d.ts +3 -2
  143. package/dist/runtime/types.d.ts.map +1 -1
  144. package/dist/runtime/types.js.map +1 -1
  145. package/dist/sandbox/identity.js +1 -1
  146. package/dist/sandbox/identity.js.map +1 -1
  147. package/dist/settings-mutation.d.ts +3 -2
  148. package/dist/settings-mutation.d.ts.map +1 -1
  149. package/dist/settings-mutation.js +6 -7
  150. package/dist/settings-mutation.js.map +1 -1
  151. package/dist/tools/generate-image.d.ts +8 -2
  152. package/dist/tools/generate-image.d.ts.map +1 -1
  153. package/dist/tools/generate-image.js +5 -3
  154. package/dist/tools/generate-image.js.map +1 -1
  155. package/dist/tools/index.d.ts +5 -0
  156. package/dist/tools/index.d.ts.map +1 -1
  157. package/dist/tools/index.js +3 -5
  158. package/dist/tools/index.js.map +1 -1
  159. package/dist/trigger.d.ts +1 -1
  160. package/dist/trigger.d.ts.map +1 -1
  161. package/dist/trigger.js +5 -10
  162. package/dist/trigger.js.map +1 -1
  163. package/dist/types.d.ts +3 -22
  164. package/dist/types.d.ts.map +1 -1
  165. package/dist/types.js.map +1 -1
  166. package/dist/vault/index.js +1 -1
  167. package/dist/vault/index.js.map +1 -1
  168. package/dist/vault/injection.d.ts +3 -1
  169. package/dist/vault/injection.d.ts.map +1 -1
  170. package/dist/vault/injection.js +2 -2
  171. package/dist/vault/injection.js.map +1 -1
  172. package/dist/web/admin/portal.d.ts.map +1 -1
  173. package/dist/web/admin/portal.js +67 -80
  174. package/dist/web/admin/portal.js.map +1 -1
  175. package/dist/web/admin/types.d.ts +2 -1
  176. package/dist/web/admin/types.d.ts.map +1 -1
  177. package/dist/web/admin/types.js.map +1 -1
  178. package/dist/web/server.d.ts +1 -1
  179. package/dist/web/server.d.ts.map +1 -1
  180. package/dist/web/server.js +3 -3
  181. package/dist/web/server.js.map +1 -1
  182. package/dist/web/session-view/portal.js +1 -1
  183. package/dist/web/session-view/portal.js.map +1 -1
  184. package/dist/workspace-projection/index.d.ts +2 -4
  185. package/dist/workspace-projection/index.d.ts.map +1 -1
  186. package/dist/workspace-projection/index.js +21 -56
  187. package/dist/workspace-projection/index.js.map +1 -1
  188. package/dist/workspace-projection/types.d.ts +0 -2
  189. package/dist/workspace-projection/types.d.ts.map +1 -1
  190. package/dist/workspace-projection/types.js.map +1 -1
  191. package/package.json +41 -16
  192. package/dist/office-address.d.ts.map +0 -1
  193. package/dist/office-address.js.map +0 -1
  194. package/dist/office-migration.d.ts.map +0 -1
  195. package/dist/office-migration.js.map +0 -1
  196. package/dist/office-registry.d.ts.map +0 -1
  197. package/dist/office-registry.js.map +0 -1
  198. package/dist/store.d.ts +0 -51
  199. package/dist/store.d.ts.map +0 -1
  200. package/dist/store.js +0 -185
  201. package/dist/store.js.map +0 -1
@@ -1 +1 @@
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;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G,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 \"fs\";\nimport { dirname, join } from \"path\";\nimport { Type } from \"@sinclair/typebox\";\nimport {\n createConversationEvent,\n type 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 {\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 { conversationOfficeDir, createOfficeAddress } from \"../../office-address.js\";\nimport { ensureOfficeDir } from \"../../office-registry.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: 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 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 workingDir: config.workingDir,\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]);\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.config.workingDir, createOfficeAddress(\"github\", conversationId), entry);\n }\n\n logBotResponse(conversationId: string, text: string, ts: string): void {\n appendBotResponseLog(\n this.config.workingDir,\n createOfficeAddress(\"github\", conversationId),\n text,\n ts,\n );\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 private isParticipating(conversationId: string): boolean {\n return existsSync(\n join(\n conversationOfficeDir(\n this.config.workingDir,\n createOfficeAddress(\"github\", conversationId),\n ),\n \"log.jsonl\",\n ),\n );\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 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 workingDir: this.config.workingDir,\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.config.workingDir, 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 dir = conversationRepoDir(this.config.workingDir, conversationId);\n if (existsSync(dir)) return;\n try {\n ensureOfficeDir(this.config.workingDir, createOfficeAddress(\"github\", conversationId));\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,IAAI,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EACL,uBAAuB,GAKxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,mBAAmB,EACnB,SAAS,GACV,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nimport { Type } from \"@sinclair/typebox\";\nimport {\n createConversationEvent,\n type 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 {\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: 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 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]);\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(\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 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"]}
@@ -24,7 +24,7 @@ export declare class GithubOps implements PlatformGithubOps {
24
24
  /** Cloud Build ids seen in getChecks summaries → their GCP project. */
25
25
  private buildRef;
26
26
  constructor(client: GithubClient, config: {
27
- workingDir: string;
27
+ workspace: import("../../office/types.js").Workspace;
28
28
  cloudBuild?: GithubBotConfig["cloudBuild"];
29
29
  });
30
30
  private repoDir;
@@ -1 +1 @@
1
- {"version":3,"file":"github-ops.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/github-ops.ts"],"names":[],"mappings":"AAEA,OAAO,EAAkB,YAAY,EAA0C,MAAM,aAAa,CAAC;AAUnG,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAClB,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAWpB;iEACiE;AACjE,wBAAsB,SAAS,CAC7B,MAAM,EAAE,YAAY,EACpB,GAAG,EAAE,qBAAqB,GACzB,OAAO,CAAC,OAAO,CAAC,CAOlB;AAED;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,YAAY,EACpB,GAAG,EAAE,qBAAqB,GACzB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAS7B;AAED;;;;;;GAMG;AACH,qBAAa,SAAU,YAAW,iBAAiB;IAK/C,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IALzB,uEAAuE;IACvE,OAAO,CAAC,QAAQ,CAA0C;IAE1D,YACmB,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE;QACvB,UAAU,EAAE,MAAM,CAAC;QACnB,UAAU,CAAC,EAAE,eAAe,CAAC,YAAY,CAAC,CAAC;KAC5C,EACC;IAEJ,OAAO,CAAC,OAAO;IAIf;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,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA4C9F;IAED;;;;;OAKG;IACG,WAAW,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC,CAoEtF;IAED;;;;;OAKG;IACG,mBAAmB,CACvB,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC,CA4B1B;IAED;;;;;;OAMG;IACG,SAAS,CAAC,cAAc,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAuBtE;CACF"}
@@ -4,6 +4,7 @@ import { GithubApiError, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from "./client
4
4
  import { CLOUD_BUILD_APP_SLUG, CloudBuildLogUnavailableError, fetchCloudBuildLog, isCloudBuildId, projectFromDetailsUrl, } from "./cloudbuild.js";
5
5
  import { parseGithubConversationId } from "./ids.js";
6
6
  import { conversationRepoDir, GITHUB_PUSH_BRANCH_PATTERN, pushBranch, syncRepo } from "./repo.js";
7
+ import { createOfficeAddress } from "../../office/index.js";
7
8
  /** Both CI log modes tail-truncate to this many characters. */
8
9
  const MAX_LOG_CHARS = 20000;
9
10
  function truncateLogTail(logText) {
@@ -54,7 +55,7 @@ export class GithubOps {
54
55
  this.buildRef = new Map();
55
56
  }
56
57
  repoDir(conversationId) {
57
- return conversationRepoDir(this.config.workingDir, conversationId);
58
+ return conversationRepoDir(this.config.workspace.office(createOfficeAddress("github", conversationId)));
58
59
  }
59
60
  /**
60
61
  * Backs the `github_pr` tool: push a `pi/*` branch the agent prepared in
@@ -1 +1 @@
1
- {"version":3,"file":"github-ops.js","sourceRoot":"","sources":["../../../src/adapters/github/github-ops.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EA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9F,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,cAAc,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBACxD,MAAM,IAAI,KAAK,CACb,WAAW,SAAS,2DAA2D;oBAC7E,+EAA+E,EACjF,EAAE,KAAK,EAAE,GAAG,EAAE,CACf,CAAC;YACJ,CAAC;YACD,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,SAAS,CAAC,cAAsB,EAAE,KAAa;QACnD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;YAC3C,MAAM,IAAI,KAAK,CACb,mGAAmG,CACpG,CAAC;QACJ,CAAC;QACD,MAAM,GAAG,GAAG,yBAAyB,CAAC,cAAc,CAAC,CAAC;QACtD,IAAI,OAAe,CAAC;QACpB,IAAI,CAAC;YACH,OAAO,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;QACvF,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,cAAc,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBACxD,MAAM,IAAI,KAAK,CACb,iCAAiC,KAAK,gDAAgD;oBACpF,oFAAoF;oBACpF,oFAAoF;oBACpF,iDAAiD,EACnD,EAAE,KAAK,EAAE,GAAG,EAAE,CACf,CAAC;YACJ,CAAC;YACD,MAAM,GAAG,CAAC;QACZ,CAAC;QACD,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;CACF","sourcesContent":["import { existsSync } from \"fs\";\nimport * as log from \"../../log.js\";\nimport { GithubApiError, GithubClient, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from \"./client.js\";\nimport {\n CLOUD_BUILD_APP_SLUG,\n CloudBuildLogUnavailableError,\n fetchCloudBuildLog,\n isCloudBuildId,\n projectFromDetailsUrl,\n} from \"./cloudbuild.js\";\nimport { parseGithubConversationId } from \"./ids.js\";\nimport { conversationRepoDir, GITHUB_PUSH_BRANCH_PATTERN, pushBranch, syncRepo } from \"./repo.js\";\nimport type {\n GithubBotConfig,\n GithubCheckSummary,\n GithubConversationRef,\n GithubIssueRequest,\n GithubPrRequest,\n GithubPrResult,\n GithubReadRequest,\n GithubReadResult,\n PlatformGithubOps,\n} from \"./types.js\";\n\n/** Both CI log modes tail-truncate to this many characters. */\nconst MAX_LOG_CHARS = 20000;\n\nfunction truncateLogTail(logText: string): string {\n return logText.length > MAX_LOG_CHARS\n ? `…(truncated to the last ${MAX_LOG_CHARS} chars)\\n${logText.slice(-MAX_LOG_CHARS)}`\n : logText;\n}\n\n/** Whether the conversation's issue is a PR, for callers where the triggering\n * item didn't carry that knowledge. Errs toward plain issue. */\nexport async function fetchIsPr(\n client: GithubClient,\n ref: GithubConversationRef,\n): Promise<boolean> {\n try {\n const issue = await githubRetry(() => client.getIssue(ref.owner, ref.repo, ref.number));\n return Boolean(issue.pull_request);\n } catch {\n return false;\n }\n}\n\n/**\n * The PR's head branch name when it lives in this repo — that is the name\n * the local checkout should carry, so committing on it and calling\n * github_pr pushes back to the PR itself instead of opening a new one.\n * Fork heads (unpushable with the repo-scoped token) and failed lookups\n * return undefined; callers then fall back to the synthetic pr-<n>.\n */\nexport async function fetchPrHeadBranch(\n client: GithubClient,\n ref: GithubConversationRef,\n): Promise<string | undefined> {\n try {\n const pr = await githubRetry(() => client.getPullRequest(ref.owner, ref.repo, ref.number));\n const sameRepo =\n pr.head?.repo?.full_name?.toLowerCase() === `${ref.owner}/${ref.repo}`.toLowerCase();\n return sameRepo ? pr.head?.ref : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Host-side backend of the github_* tool pack (`PlatformGithubOps`),\n * standalone from the messaging bot: it needs the API client, the\n * conversation working dir, and optional Cloud Build access — not the poll\n * loop, queues, or trigger gate. Tokens are minted per call, scoped to the\n * conversation's repo, and never enter the sandbox.\n */\nexport class GithubOps implements PlatformGithubOps {\n /** Cloud Build ids seen in getChecks summaries → their GCP project. */\n private buildRef = new Map<string, { project: string }>();\n\n constructor(\n private readonly client: GithubClient,\n private readonly config: {\n workingDir: string;\n cloudBuild?: GithubBotConfig[\"cloudBuild\"];\n },\n ) {}\n\n private repoDir(conversationId: string): string {\n return conversationRepoDir(this.config.workingDir, conversationId);\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 try {\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 } catch (err) {\n // Idempotency: pushing more commits to a branch that already has an\n // open PR updates that PR; the create call then 422s. Surface the\n // existing PR instead of failing the fix-CI-push-again loop.\n if (\n err instanceof GithubApiError &&\n err.status === 422 &&\n /already exists/i.test(err.message)\n ) {\n const existing = await this.client.findOpenPullRequestByBranch(\n ref.owner,\n ref.repo,\n request.branch,\n );\n if (existing) {\n log.logInfo(\n `[${conversationId}] Pushed to existing PR #${existing.number}: ${existing.html_url}`,\n );\n return { number: existing.number, url: existing.html_url, updatedExisting: true };\n }\n }\n throw err;\n }\n }\n\n /**\n * Backs the `github_checks` tool: CI check runs for a branch the agent\n * pushed, or for the conversation's PR head when no branch is given.\n */\n async getChecks(conversationId: string, branch?: string): Promise<GithubCheckSummary[]> {\n const ref = parseGithubConversationId(conversationId);\n let target = branch;\n if (!target) {\n let pr;\n try {\n pr = await githubRetry(() => this.client.getPullRequest(ref.owner, ref.repo, ref.number));\n } catch {\n pr = null;\n }\n if (!pr?.head) {\n throw new Error(\n \"This conversation is not a pull request — pass the branch whose checks you want.\",\n );\n }\n target = pr.head.sha;\n }\n const runs = await githubRetry(() => this.client.listCheckRuns(ref.owner, ref.repo, target));\n return runs.map((run) => {\n const externalId = run.external_id?.trim() || null;\n let buildLogAvailable = false;\n // Cloud Build runs carry their build UUID in external_id and the GCP\n // project in details_url. Remember project-by-build so getBuildLog only\n // serves builds the agent actually saw on this repo's checks.\n if (\n this.config.cloudBuild &&\n run.app?.slug === CLOUD_BUILD_APP_SLUG &&\n externalId &&\n isCloudBuildId(externalId)\n ) {\n const project =\n projectFromDetailsUrl(run.details_url) ?? this.config.cloudBuild.projectFallback;\n if (project) {\n this.rememberBuild(externalId, project);\n buildLogAvailable = true;\n }\n }\n return {\n id: run.id,\n name: run.name,\n status: run.status,\n conclusion: run.conclusion,\n url: run.html_url,\n appSlug: run.app?.slug ?? null,\n outputSummary: run.output?.summary?.trim() ? run.output.summary.slice(0, 500) : null,\n externalId,\n buildLogAvailable,\n };\n });\n }\n\n private rememberBuild(buildId: string, project: string): void {\n // Insertion-ordered Map as a small LRU: re-insert on touch, prune oldest.\n this.buildRef.delete(buildId);\n this.buildRef.set(buildId, { project });\n if (this.buildRef.size > 200) {\n const oldest = this.buildRef.keys().next().value;\n if (oldest !== undefined) this.buildRef.delete(oldest);\n }\n }\n\n /**\n * Backs the Cloud Build log mode of `github_checks`. GCP credentials stay\n * host-side (ADC via GOOGLE_APPLICATION_CREDENTIALS — e.g. a Workload\n * Identity Federation external_account file); the build must have appeared\n * in a github_checks summary first, which is also where its project is\n * learned. Unreadable logs degrade to the console url, never a dead end.\n */\n async getBuildLog(conversationId: string, buildId: string): Promise<string> {\n if (!this.config.cloudBuild) {\n throw new Error(\n \"Cloud Build log access is not configured on this host (no GCP credentials).\",\n );\n }\n const known = this.buildRef.get(buildId);\n if (!known) {\n throw new Error(\n `Unknown build id ${buildId}: run github_checks first and take a [build …] id from ` +\n `the summary.`,\n );\n }\n let logText: string;\n try {\n logText = await fetchCloudBuildLog({\n tokenProvider: this.config.cloudBuild.tokenProvider,\n project: known.project,\n buildId,\n });\n } catch (err) {\n if (err instanceof CloudBuildLogUnavailableError) {\n throw new Error(\n `${err.message}${err.consoleUrl ? ` Console: ${err.consoleUrl}` : \"\"} Use the check's ` +\n `summary/url from github_checks, or reproduce the failure locally in ./repo.`,\n { cause: err },\n );\n }\n throw err;\n }\n return truncateLogTail(logText);\n }\n\n /**\n * Backs the `github_sync` tool: refresh the conversation's ./repo clone\n * from origin with an ephemeral read token. Fetch-only when moving the\n * checkout could lose agent work; the formatted report tells the agent\n * what happened and what to do next.\n */\n async syncRepo(conversationId: string, branch?: string): Promise<string> {\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 sync.\");\n }\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"read\",\n });\n let prNumber: number | undefined;\n let prHeadBranch: string | undefined;\n let defaultBranch: string | undefined;\n if (!branch) {\n if (await fetchIsPr(this.client, ref)) {\n prNumber = ref.number;\n prHeadBranch = await fetchPrHeadBranch(this.client, ref);\n } else {\n const repository = await githubRetry(() => this.client.getRepository(ref.owner, ref.repo));\n defaultBranch = repository.default_branch;\n }\n }\n const result = await syncRepo({ dir, token, branch, prNumber, prHeadBranch, defaultBranch });\n\n if (result.updatedCheckout) {\n return `Updated ./repo: branch ${result.target} is now at ${result.fetchedSha.slice(0, 12)}.`;\n }\n const reasons: string[] = [];\n if (result.currentBranch !== result.target) {\n reasons.push(`the checkout is on '${result.currentBranch}', not '${result.target}'`);\n }\n if (result.dirty) {\n reasons.push(\"the working tree has uncommitted changes\");\n }\n if (result.localCommits > 0) {\n reasons.push(`'${result.target}' has ${result.localCommits} local commit(s) not on origin`);\n }\n return (\n `Fetched ${result.target} to FETCH_HEAD (${result.fetchedSha.slice(0, 12)}) but left the ` +\n `checkout alone: ${reasons.join(\"; \")}. Merge or rebase FETCH_HEAD yourself ` +\n `(e.g. git merge FETCH_HEAD), or commit your work to a pi/* branch first.`\n );\n }\n\n /**\n * Backs the `github_read` tool: PR/issue metadata the ./repo clone cannot\n * provide (diff stats, review state, other issues in the repo). Owner/repo\n * always come from the conversation id, so reads never leave this repo.\n */\n async readGithub(conversationId: string, request: GithubReadRequest): Promise<GithubReadResult> {\n const ref = parseGithubConversationId(conversationId);\n const number = request.number ?? ref.number;\n switch (request.action) {\n case \"pr\": {\n const pr = await githubRetry(() => this.client.getPullRequest(ref.owner, ref.repo, number));\n return { kind: \"pr\", pr };\n }\n case \"pr_files\": {\n const files = await githubRetry(() =>\n this.client.listPullRequestFiles(ref.owner, ref.repo, number),\n );\n return { kind: \"pr_files\", files };\n }\n case \"pr_reviews\": {\n const [reviews, threads] = await Promise.all([\n githubRetry(() => this.client.listPullRequestReviews(ref.owner, ref.repo, number)),\n githubRetry(() => this.client.listPullReviewComments(ref.owner, ref.repo, number)),\n ]);\n return { kind: \"pr_reviews\", reviews, threads };\n }\n case \"issue\": {\n const issue = await githubRetry(() => this.client.getIssue(ref.owner, ref.repo, number));\n return { kind: \"issue\", issue };\n }\n case \"comments\": {\n const comments = await githubRetry(() =>\n this.client.listIssueComments(ref.owner, ref.repo, number),\n );\n return { kind: \"comments\", comments };\n }\n case \"list\": {\n const issues = await githubRetry(() =>\n this.client.listIssues(ref.owner, ref.repo, {\n state: request.state,\n labels: request.labels,\n creator: request.creator,\n }),\n );\n return { kind: \"list\", issues };\n }\n default:\n throw new Error(`Unknown github_read action: ${String(request.action)}`);\n }\n }\n\n /**\n * Backs the `github_issue` tool: labels, assignees, and open/closed state\n * on any issue of this conversation's repo (triage). Same-repo by\n * construction — owner/repo come from the conversation id; the action enum\n * is closed, so lock/delete/transfer cannot be expressed at all.\n */\n async manageIssue(conversationId: string, request: GithubIssueRequest): Promise<string> {\n const ref = parseGithubConversationId(conversationId);\n const number = request.number ?? ref.number;\n try {\n switch (request.action) {\n case \"add_labels\": {\n if (!request.labels?.length) {\n throw new Error(\"add_labels requires a non-empty labels array.\");\n }\n await githubRetry(() =>\n this.client.addIssueLabels(ref.owner, ref.repo, number, request.labels!),\n );\n return `Added label(s) ${request.labels.join(\", \")} to #${number}.`;\n }\n case \"remove_label\": {\n if (!request.label) {\n throw new Error(\"remove_label requires a label name.\");\n }\n await githubRetry(() =>\n this.client.removeIssueLabel(ref.owner, ref.repo, number, request.label!),\n );\n return `Removed label ${request.label} from #${number}.`;\n }\n case \"add_assignees\": {\n if (!request.assignees?.length) {\n throw new Error(\"add_assignees requires a non-empty assignees array.\");\n }\n await githubRetry(() =>\n this.client.addIssueAssignees(ref.owner, ref.repo, number, request.assignees!),\n );\n return `Assigned ${request.assignees.map((login) => `@${login}`).join(\", \")} to #${number}.`;\n }\n case \"remove_assignees\": {\n if (!request.assignees?.length) {\n throw new Error(\"remove_assignees requires a non-empty assignees array.\");\n }\n await githubRetry(() =>\n this.client.removeIssueAssignees(ref.owner, ref.repo, number, request.assignees!),\n );\n return `Unassigned ${request.assignees.map((login) => `@${login}`).join(\", \")} from #${number}.`;\n }\n case \"close\": {\n await githubRetry(() =>\n this.client.updateIssueState(\n ref.owner,\n ref.repo,\n number,\n \"closed\",\n request.state_reason,\n ),\n );\n return `Closed #${number}${request.state_reason ? ` as ${request.state_reason}` : \"\"}.`;\n }\n case \"reopen\": {\n await githubRetry(() =>\n this.client.updateIssueState(ref.owner, ref.repo, number, \"open\"),\n );\n return `Reopened #${number}.`;\n }\n default:\n throw new Error(`Unknown github_issue action: ${String(request.action)}`);\n }\n } catch (err) {\n if (err instanceof GithubApiError && err.status === 404) {\n throw new Error(`Issue #${number} not found in ${ref.owner}/${ref.repo}.`, { cause: err });\n }\n throw err;\n }\n }\n\n /**\n * Backs the `github_review_reply` tool: answer inside one inline review\n * thread of this conversation's PR. The comment id comes from an\n * `[PR review comment rc-<id> …]` message; GitHub validates it belongs to\n * this PR (404 otherwise, translated into agent-actionable guidance).\n */\n async replyToReviewThread(\n conversationId: string,\n commentId: number,\n body: string,\n ): Promise<{ url: string }> {\n if (!Number.isInteger(commentId) || commentId <= 0) {\n throw new Error(\n \"comment_id must be the numeric id from an [PR review comment rc-<id> …] message.\",\n );\n }\n const ref = parseGithubConversationId(conversationId);\n const text =\n body.length > GITHUB_MAX_COMMENT_LENGTH\n ? `${body.slice(0, GITHUB_MAX_COMMENT_LENGTH)}\\n…(truncated)`\n : body;\n try {\n const reply = await githubRetry(() =>\n this.client.replyToReviewComment(ref.owner, ref.repo, ref.number, commentId, text),\n );\n return {\n url: `https://github.com/${ref.owner}/${ref.repo}/pull/${ref.number}#discussion_r${reply.id}`,\n };\n } catch (err) {\n if (err instanceof GithubApiError && err.status === 404) {\n throw new Error(\n `Comment ${commentId} is not a review comment on this PR. Take the id from an ` +\n `[PR review comment rc-<id> …] message in this conversation; do not guess ids.`,\n { cause: err },\n );\n }\n throw err;\n }\n }\n\n /**\n * Backs the log mode of `github_checks`: the tail of one CI job's log so\n * the agent can diagnose a failing check without sandbox credentials. Only\n * GitHub Actions checks have logs on GitHub — external CI apps (e.g. Cloud\n * Build) keep theirs on their own service, so a 404 here is translated\n * into guidance instead of a dead end.\n */\n async getJobLog(conversationId: string, jobId: number): Promise<string> {\n if (!Number.isInteger(jobId) || jobId <= 0) {\n throw new Error(\n \"job_id must be a positive Actions job id taken from a [job …] entry in the github_checks summary.\",\n );\n }\n const ref = parseGithubConversationId(conversationId);\n let logText: string;\n try {\n logText = await githubRetry(() => this.client.getJobLog(ref.owner, ref.repo, jobId));\n } catch (err) {\n if (err instanceof GithubApiError && err.status === 404) {\n throw new Error(\n `No GitHub Actions log for job ${jobId}. Logs are only available for checks reported ` +\n `by github-actions; external CI (e.g. Cloud Build) keeps logs on its own service — ` +\n `use that check's summary/url from github_checks, or reproduce the failure locally ` +\n `in ./repo instead. Do not retry with other ids.`,\n { cause: err },\n );\n }\n throw err;\n }\n return truncateLogTail(logText);\n }\n}\n"]}
1
+ {"version":3,"file":"github-ops.js","sourceRoot":"","sources":["../../../src/adapters/github/github-ops.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,cAAc,EAAgB,yBAAyB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACnG,OAAO,EACL,oBAAoB,EACpB,6BAA6B,EAC7B,kBAAkB,EAClB,cAAc,EACd,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAClG,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAa5D,+DAA+D;AAC/D,MAAM,aAAa,GAAG,KAAK,CAAC;AAE5B,SAAS,eAAe,CAAC,OAAe;IACtC,OAAO,OAAO,CAAC,MAAM,GAAG,aAAa;QACnC,CAAC,CAAC,2BAA2B,aAAa,YAAY,OAAO,CAAC,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE;QACrF,CAAC,CAAC,OAAO,CAA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QACtD,IAAI,OAAe,CAAC;QACpB,IAAI,CAAC;YACH,OAAO,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;QACvF,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,cAAc,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBACxD,MAAM,IAAI,KAAK,CACb,iCAAiC,KAAK,gDAAgD;oBACpF,oFAAoF;oBACpF,oFAAoF;oBACpF,iDAAiD,EACnD,EAAE,KAAK,EAAE,GAAG,EAAE,CACf,CAAC;YACJ,CAAC;YACD,MAAM,GAAG,CAAC;QACZ,CAAC;QACD,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;CACF","sourcesContent":["import { existsSync } from \"fs\";\nimport * as log from \"../../log.js\";\nimport { GithubApiError, GithubClient, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from \"./client.js\";\nimport {\n CLOUD_BUILD_APP_SLUG,\n CloudBuildLogUnavailableError,\n fetchCloudBuildLog,\n isCloudBuildId,\n projectFromDetailsUrl,\n} from \"./cloudbuild.js\";\nimport { parseGithubConversationId } from \"./ids.js\";\nimport { conversationRepoDir, GITHUB_PUSH_BRANCH_PATTERN, pushBranch, syncRepo } from \"./repo.js\";\nimport { createOfficeAddress } from \"../../office/index.js\";\nimport type {\n GithubBotConfig,\n GithubCheckSummary,\n GithubConversationRef,\n GithubIssueRequest,\n GithubPrRequest,\n GithubPrResult,\n GithubReadRequest,\n GithubReadResult,\n PlatformGithubOps,\n} from \"./types.js\";\n\n/** Both CI log modes tail-truncate to this many characters. */\nconst MAX_LOG_CHARS = 20000;\n\nfunction truncateLogTail(logText: string): string {\n return logText.length > MAX_LOG_CHARS\n ? `…(truncated to the last ${MAX_LOG_CHARS} chars)\\n${logText.slice(-MAX_LOG_CHARS)}`\n : logText;\n}\n\n/** Whether the conversation's issue is a PR, for callers where the triggering\n * item didn't carry that knowledge. Errs toward plain issue. */\nexport async function fetchIsPr(\n client: GithubClient,\n ref: GithubConversationRef,\n): Promise<boolean> {\n try {\n const issue = await githubRetry(() => client.getIssue(ref.owner, ref.repo, ref.number));\n return Boolean(issue.pull_request);\n } catch {\n return false;\n }\n}\n\n/**\n * The PR's head branch name when it lives in this repo — that is the name\n * the local checkout should carry, so committing on it and calling\n * github_pr pushes back to the PR itself instead of opening a new one.\n * Fork heads (unpushable with the repo-scoped token) and failed lookups\n * return undefined; callers then fall back to the synthetic pr-<n>.\n */\nexport async function fetchPrHeadBranch(\n client: GithubClient,\n ref: GithubConversationRef,\n): Promise<string | undefined> {\n try {\n const pr = await githubRetry(() => client.getPullRequest(ref.owner, ref.repo, ref.number));\n const sameRepo =\n pr.head?.repo?.full_name?.toLowerCase() === `${ref.owner}/${ref.repo}`.toLowerCase();\n return sameRepo ? pr.head?.ref : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Host-side backend of the github_* tool pack (`PlatformGithubOps`),\n * standalone from the messaging bot: it needs the API client, the\n * conversation working dir, and optional Cloud Build access — not the poll\n * loop, queues, or trigger gate. Tokens are minted per call, scoped to the\n * conversation's repo, and never enter the sandbox.\n */\nexport class GithubOps implements PlatformGithubOps {\n /** Cloud Build ids seen in getChecks summaries → their GCP project. */\n private buildRef = new Map<string, { project: string }>();\n\n constructor(\n private readonly client: GithubClient,\n private readonly config: {\n workspace: import(\"../../office/types.js\").Workspace;\n cloudBuild?: GithubBotConfig[\"cloudBuild\"];\n },\n ) {}\n\n private repoDir(conversationId: string): string {\n return conversationRepoDir(\n this.config.workspace.office(createOfficeAddress(\"github\", conversationId)),\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 try {\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 } catch (err) {\n // Idempotency: pushing more commits to a branch that already has an\n // open PR updates that PR; the create call then 422s. Surface the\n // existing PR instead of failing the fix-CI-push-again loop.\n if (\n err instanceof GithubApiError &&\n err.status === 422 &&\n /already exists/i.test(err.message)\n ) {\n const existing = await this.client.findOpenPullRequestByBranch(\n ref.owner,\n ref.repo,\n request.branch,\n );\n if (existing) {\n log.logInfo(\n `[${conversationId}] Pushed to existing PR #${existing.number}: ${existing.html_url}`,\n );\n return { number: existing.number, url: existing.html_url, updatedExisting: true };\n }\n }\n throw err;\n }\n }\n\n /**\n * Backs the `github_checks` tool: CI check runs for a branch the agent\n * pushed, or for the conversation's PR head when no branch is given.\n */\n async getChecks(conversationId: string, branch?: string): Promise<GithubCheckSummary[]> {\n const ref = parseGithubConversationId(conversationId);\n let target = branch;\n if (!target) {\n let pr;\n try {\n pr = await githubRetry(() => this.client.getPullRequest(ref.owner, ref.repo, ref.number));\n } catch {\n pr = null;\n }\n if (!pr?.head) {\n throw new Error(\n \"This conversation is not a pull request — pass the branch whose checks you want.\",\n );\n }\n target = pr.head.sha;\n }\n const runs = await githubRetry(() => this.client.listCheckRuns(ref.owner, ref.repo, target));\n return runs.map((run) => {\n const externalId = run.external_id?.trim() || null;\n let buildLogAvailable = false;\n // Cloud Build runs carry their build UUID in external_id and the GCP\n // project in details_url. Remember project-by-build so getBuildLog only\n // serves builds the agent actually saw on this repo's checks.\n if (\n this.config.cloudBuild &&\n run.app?.slug === CLOUD_BUILD_APP_SLUG &&\n externalId &&\n isCloudBuildId(externalId)\n ) {\n const project =\n projectFromDetailsUrl(run.details_url) ?? this.config.cloudBuild.projectFallback;\n if (project) {\n this.rememberBuild(externalId, project);\n buildLogAvailable = true;\n }\n }\n return {\n id: run.id,\n name: run.name,\n status: run.status,\n conclusion: run.conclusion,\n url: run.html_url,\n appSlug: run.app?.slug ?? null,\n outputSummary: run.output?.summary?.trim() ? run.output.summary.slice(0, 500) : null,\n externalId,\n buildLogAvailable,\n };\n });\n }\n\n private rememberBuild(buildId: string, project: string): void {\n // Insertion-ordered Map as a small LRU: re-insert on touch, prune oldest.\n this.buildRef.delete(buildId);\n this.buildRef.set(buildId, { project });\n if (this.buildRef.size > 200) {\n const oldest = this.buildRef.keys().next().value;\n if (oldest !== undefined) this.buildRef.delete(oldest);\n }\n }\n\n /**\n * Backs the Cloud Build log mode of `github_checks`. GCP credentials stay\n * host-side (ADC via GOOGLE_APPLICATION_CREDENTIALS — e.g. a Workload\n * Identity Federation external_account file); the build must have appeared\n * in a github_checks summary first, which is also where its project is\n * learned. Unreadable logs degrade to the console url, never a dead end.\n */\n async getBuildLog(conversationId: string, buildId: string): Promise<string> {\n if (!this.config.cloudBuild) {\n throw new Error(\n \"Cloud Build log access is not configured on this host (no GCP credentials).\",\n );\n }\n const known = this.buildRef.get(buildId);\n if (!known) {\n throw new Error(\n `Unknown build id ${buildId}: run github_checks first and take a [build …] id from ` +\n `the summary.`,\n );\n }\n let logText: string;\n try {\n logText = await fetchCloudBuildLog({\n tokenProvider: this.config.cloudBuild.tokenProvider,\n project: known.project,\n buildId,\n });\n } catch (err) {\n if (err instanceof CloudBuildLogUnavailableError) {\n throw new Error(\n `${err.message}${err.consoleUrl ? ` Console: ${err.consoleUrl}` : \"\"} Use the check's ` +\n `summary/url from github_checks, or reproduce the failure locally in ./repo.`,\n { cause: err },\n );\n }\n throw err;\n }\n return truncateLogTail(logText);\n }\n\n /**\n * Backs the `github_sync` tool: refresh the conversation's ./repo clone\n * from origin with an ephemeral read token. Fetch-only when moving the\n * checkout could lose agent work; the formatted report tells the agent\n * what happened and what to do next.\n */\n async syncRepo(conversationId: string, branch?: string): Promise<string> {\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 sync.\");\n }\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"read\",\n });\n let prNumber: number | undefined;\n let prHeadBranch: string | undefined;\n let defaultBranch: string | undefined;\n if (!branch) {\n if (await fetchIsPr(this.client, ref)) {\n prNumber = ref.number;\n prHeadBranch = await fetchPrHeadBranch(this.client, ref);\n } else {\n const repository = await githubRetry(() => this.client.getRepository(ref.owner, ref.repo));\n defaultBranch = repository.default_branch;\n }\n }\n const result = await syncRepo({ dir, token, branch, prNumber, prHeadBranch, defaultBranch });\n\n if (result.updatedCheckout) {\n return `Updated ./repo: branch ${result.target} is now at ${result.fetchedSha.slice(0, 12)}.`;\n }\n const reasons: string[] = [];\n if (result.currentBranch !== result.target) {\n reasons.push(`the checkout is on '${result.currentBranch}', not '${result.target}'`);\n }\n if (result.dirty) {\n reasons.push(\"the working tree has uncommitted changes\");\n }\n if (result.localCommits > 0) {\n reasons.push(`'${result.target}' has ${result.localCommits} local commit(s) not on origin`);\n }\n return (\n `Fetched ${result.target} to FETCH_HEAD (${result.fetchedSha.slice(0, 12)}) but left the ` +\n `checkout alone: ${reasons.join(\"; \")}. Merge or rebase FETCH_HEAD yourself ` +\n `(e.g. git merge FETCH_HEAD), or commit your work to a pi/* branch first.`\n );\n }\n\n /**\n * Backs the `github_read` tool: PR/issue metadata the ./repo clone cannot\n * provide (diff stats, review state, other issues in the repo). Owner/repo\n * always come from the conversation id, so reads never leave this repo.\n */\n async readGithub(conversationId: string, request: GithubReadRequest): Promise<GithubReadResult> {\n const ref = parseGithubConversationId(conversationId);\n const number = request.number ?? ref.number;\n switch (request.action) {\n case \"pr\": {\n const pr = await githubRetry(() => this.client.getPullRequest(ref.owner, ref.repo, number));\n return { kind: \"pr\", pr };\n }\n case \"pr_files\": {\n const files = await githubRetry(() =>\n this.client.listPullRequestFiles(ref.owner, ref.repo, number),\n );\n return { kind: \"pr_files\", files };\n }\n case \"pr_reviews\": {\n const [reviews, threads] = await Promise.all([\n githubRetry(() => this.client.listPullRequestReviews(ref.owner, ref.repo, number)),\n githubRetry(() => this.client.listPullReviewComments(ref.owner, ref.repo, number)),\n ]);\n return { kind: \"pr_reviews\", reviews, threads };\n }\n case \"issue\": {\n const issue = await githubRetry(() => this.client.getIssue(ref.owner, ref.repo, number));\n return { kind: \"issue\", issue };\n }\n case \"comments\": {\n const comments = await githubRetry(() =>\n this.client.listIssueComments(ref.owner, ref.repo, number),\n );\n return { kind: \"comments\", comments };\n }\n case \"list\": {\n const issues = await githubRetry(() =>\n this.client.listIssues(ref.owner, ref.repo, {\n state: request.state,\n labels: request.labels,\n creator: request.creator,\n }),\n );\n return { kind: \"list\", issues };\n }\n default:\n throw new Error(`Unknown github_read action: ${String(request.action)}`);\n }\n }\n\n /**\n * Backs the `github_issue` tool: labels, assignees, and open/closed state\n * on any issue of this conversation's repo (triage). Same-repo by\n * construction — owner/repo come from the conversation id; the action enum\n * is closed, so lock/delete/transfer cannot be expressed at all.\n */\n async manageIssue(conversationId: string, request: GithubIssueRequest): Promise<string> {\n const ref = parseGithubConversationId(conversationId);\n const number = request.number ?? ref.number;\n try {\n switch (request.action) {\n case \"add_labels\": {\n if (!request.labels?.length) {\n throw new Error(\"add_labels requires a non-empty labels array.\");\n }\n await githubRetry(() =>\n this.client.addIssueLabels(ref.owner, ref.repo, number, request.labels!),\n );\n return `Added label(s) ${request.labels.join(\", \")} to #${number}.`;\n }\n case \"remove_label\": {\n if (!request.label) {\n throw new Error(\"remove_label requires a label name.\");\n }\n await githubRetry(() =>\n this.client.removeIssueLabel(ref.owner, ref.repo, number, request.label!),\n );\n return `Removed label ${request.label} from #${number}.`;\n }\n case \"add_assignees\": {\n if (!request.assignees?.length) {\n throw new Error(\"add_assignees requires a non-empty assignees array.\");\n }\n await githubRetry(() =>\n this.client.addIssueAssignees(ref.owner, ref.repo, number, request.assignees!),\n );\n return `Assigned ${request.assignees.map((login) => `@${login}`).join(\", \")} to #${number}.`;\n }\n case \"remove_assignees\": {\n if (!request.assignees?.length) {\n throw new Error(\"remove_assignees requires a non-empty assignees array.\");\n }\n await githubRetry(() =>\n this.client.removeIssueAssignees(ref.owner, ref.repo, number, request.assignees!),\n );\n return `Unassigned ${request.assignees.map((login) => `@${login}`).join(\", \")} from #${number}.`;\n }\n case \"close\": {\n await githubRetry(() =>\n this.client.updateIssueState(\n ref.owner,\n ref.repo,\n number,\n \"closed\",\n request.state_reason,\n ),\n );\n return `Closed #${number}${request.state_reason ? ` as ${request.state_reason}` : \"\"}.`;\n }\n case \"reopen\": {\n await githubRetry(() =>\n this.client.updateIssueState(ref.owner, ref.repo, number, \"open\"),\n );\n return `Reopened #${number}.`;\n }\n default:\n throw new Error(`Unknown github_issue action: ${String(request.action)}`);\n }\n } catch (err) {\n if (err instanceof GithubApiError && err.status === 404) {\n throw new Error(`Issue #${number} not found in ${ref.owner}/${ref.repo}.`, { cause: err });\n }\n throw err;\n }\n }\n\n /**\n * Backs the `github_review_reply` tool: answer inside one inline review\n * thread of this conversation's PR. The comment id comes from an\n * `[PR review comment rc-<id> …]` message; GitHub validates it belongs to\n * this PR (404 otherwise, translated into agent-actionable guidance).\n */\n async replyToReviewThread(\n conversationId: string,\n commentId: number,\n body: string,\n ): Promise<{ url: string }> {\n if (!Number.isInteger(commentId) || commentId <= 0) {\n throw new Error(\n \"comment_id must be the numeric id from an [PR review comment rc-<id> …] message.\",\n );\n }\n const ref = parseGithubConversationId(conversationId);\n const text =\n body.length > GITHUB_MAX_COMMENT_LENGTH\n ? `${body.slice(0, GITHUB_MAX_COMMENT_LENGTH)}\\n…(truncated)`\n : body;\n try {\n const reply = await githubRetry(() =>\n this.client.replyToReviewComment(ref.owner, ref.repo, ref.number, commentId, text),\n );\n return {\n url: `https://github.com/${ref.owner}/${ref.repo}/pull/${ref.number}#discussion_r${reply.id}`,\n };\n } catch (err) {\n if (err instanceof GithubApiError && err.status === 404) {\n throw new Error(\n `Comment ${commentId} is not a review comment on this PR. Take the id from an ` +\n `[PR review comment rc-<id> …] message in this conversation; do not guess ids.`,\n { cause: err },\n );\n }\n throw err;\n }\n }\n\n /**\n * Backs the log mode of `github_checks`: the tail of one CI job's log so\n * the agent can diagnose a failing check without sandbox credentials. Only\n * GitHub Actions checks have logs on GitHub — external CI apps (e.g. Cloud\n * Build) keep theirs on their own service, so a 404 here is translated\n * into guidance instead of a dead end.\n */\n async getJobLog(conversationId: string, jobId: number): Promise<string> {\n if (!Number.isInteger(jobId) || jobId <= 0) {\n throw new Error(\n \"job_id must be a positive Actions job id taken from a [job …] entry in the github_checks summary.\",\n );\n }\n const ref = parseGithubConversationId(conversationId);\n let logText: string;\n try {\n logText = await githubRetry(() => this.client.getJobLog(ref.owner, ref.repo, jobId));\n } catch (err) {\n if (err instanceof GithubApiError && err.status === 404) {\n throw new Error(\n `No GitHub Actions log for job ${jobId}. Logs are only available for checks reported ` +\n `by github-actions; external CI (e.g. Cloud Build) keeps logs on its own service — ` +\n `use that check's summary/url from github_checks, or reproduce the failure locally ` +\n `in ./repo instead. Do not retry with other ids.`,\n { cause: err },\n );\n }\n throw err;\n }\n return truncateLogTail(logText);\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { Office } from "../../office/index.js";
1
2
  import type { CloneRepoOptions, PushBranchOptions, SyncRepoOptions, SyncRepoResult } from "./types.js";
2
3
  /**
3
4
  * Branches the bot may push: `pi/<name>`. Everything else — including the
@@ -6,7 +7,7 @@ import type { CloneRepoOptions, PushBranchOptions, SyncRepoOptions, SyncRepoResu
6
7
  */
7
8
  export declare const GITHUB_PUSH_BRANCH_PATTERN: RegExp;
8
9
  /** The conversation's clone location (bind-mounted into the sandbox as ./repo). */
9
- export declare function conversationRepoDir(workingDir: string, conversationId: string): string;
10
+ export declare function conversationRepoDir(office: Office): string;
10
11
  /**
11
12
  * Shallow-clone a repo into a conversation dir and preconfigure the bot's
12
13
  * commit identity. For PR conversations, additionally fetch the PR head and
@@ -1 +1 @@
1
- {"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACf,MAAM,YAAY,CAAC;AAMpB;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,QAAwC,CAAC;AAEhF,mFAAmF;AACnF,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,MAAM,CAKtF;AA0CD;;;;;;GAMG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxE;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CA8ChF;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAa1E"}
1
+ {"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEpD,OAAO,KAAK,EACV,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACf,MAAM,YAAY,CAAC;AAMpB;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,QAAwC,CAAC;AAEhF,mFAAmF;AACnF,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE1D;AA0CD;;;;;;GAMG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxE;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CA8ChF;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAa1E"}
@@ -1,6 +1,5 @@
1
1
  import { execFile } from "child_process";
2
2
  import { join } from "path";
3
- import { conversationOfficeDir, createOfficeAddress } from "../../office-address.js";
4
3
  import { promisify } from "util";
5
4
  const execFileAsync = promisify(execFile);
6
5
  const GIT_TIMEOUT_MS = 120_000;
@@ -11,8 +10,8 @@ const GIT_TIMEOUT_MS = 120_000;
11
10
  */
12
11
  export const GITHUB_PUSH_BRANCH_PATTERN = /^pi\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;
13
12
  /** The conversation's clone location (bind-mounted into the sandbox as ./repo). */
14
- export function conversationRepoDir(workingDir, conversationId) {
15
- return join(conversationOfficeDir(workingDir, createOfficeAddress("github", conversationId)), "repo");
13
+ export function conversationRepoDir(office) {
14
+ return join(office.dir, "repo");
16
15
  }
17
16
  /**
18
17
  * Pass the ephemeral token as a per-invocation header, never in the remote
@@ -1 +1 @@
1
- {"version":3,"file":"repo.js","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC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AM,CAAC,KAAK,UAAU,UAAU,CAAC,OAA0B;IACzD,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IACvC,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CACb,4BAA4B,MAAM,oDAAoD,CACvF,CAAC;IACJ,CAAC;IACD,IAAI,CAAC;QACH,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,MAAM,EAAE,CAAC,CAAC,CAAC;IACrF,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,WAAW,MAAM,sDAAsD,CAAC,CAAC;IAC3F,CAAC;IACD,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,MAAM,eAAe,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["import { execFile } from \"child_process\";\nimport { join } from \"path\";\nimport { conversationOfficeDir, createOfficeAddress } from \"../../office-address.js\";\nimport { promisify } from \"util\";\nimport type {\n CloneRepoOptions,\n PushBranchOptions,\n SyncRepoOptions,\n SyncRepoResult,\n} from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst GIT_TIMEOUT_MS = 120_000;\n\n/**\n * Branches the bot may push: `pi/<name>`. Everything else — including the\n * repo's default branch by construction — is refused, so a driven agent can\n * only ever produce reviewable branches, never touch mainline directly.\n */\nexport const GITHUB_PUSH_BRANCH_PATTERN = /^pi\\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;\n\n/** The conversation's clone location (bind-mounted into the sandbox as ./repo). */\nexport function conversationRepoDir(workingDir: string, conversationId: string): string {\n return join(\n conversationOfficeDir(workingDir, createOfficeAddress(\"github\", conversationId)),\n \"repo\",\n );\n}\n\n/**\n * Pass the ephemeral token as a per-invocation header, never in the remote\n * URL: nothing credential-shaped may end up in `.git/config`, which lives in\n * the conversation dir and is bind-mounted into the sandbox.\n */\nfunction gitAuthArgs(token: string): string[] {\n const basic = Buffer.from(`x-access-token:${token}`).toString(\"base64\");\n return [\"-c\", `http.extraheader=Authorization: basic ${basic}`];\n}\n\nasync function git(args: string[], token?: string): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", [...(token ? gitAuthArgs(token) : []), ...args], {\n timeout: GIT_TIMEOUT_MS,\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n return stdout;\n}\n\n/**\n * Git itself rejects these ref shapes; the check just keeps an API-supplied\n * branch name that would parse as a git option (leading dash) or an invalid\n * ref out of argv entirely instead of surfacing as a git error mid-clone.\n */\nfunction isSafeBranchName(name: string): boolean {\n return (\n name.length > 0 && !name.startsWith(\"-\") && !name.includes(\"..\") && !/[\\s~^:?*[\\\\]/.test(name)\n );\n}\n\n/**\n * Local checkout name for a PR conversation: the PR's real head branch when\n * known (same-repo heads only — the caller resolves that), falling back to\n * the synthetic `pr-<n>` for fork PRs, unresolvable heads, and unsafe names.\n * Using the real name is what lets the agent update the PR in place: commit\n * on a `pi/*` head and `github_pr` pushes back to the same branch.\n */\nfunction prCheckoutName(prNumber: number, prHeadBranch?: string): string {\n return prHeadBranch && isSafeBranchName(prHeadBranch) ? prHeadBranch : `pr-${prNumber}`;\n}\n\n/**\n * Shallow-clone a repo into a conversation dir and preconfigure the bot's\n * commit identity. For PR conversations, additionally fetch the PR head and\n * check it out so the agent starts on the code under review — under its real\n * branch name when the caller resolved one, which is what lets the agent push\n * fixes back to the PR itself.\n */\nexport async function cloneRepo(options: CloneRepoOptions): Promise<void> {\n await git([\"clone\", \"--depth\", \"50\", options.url, options.dir], options.token);\n await git([\"-C\", options.dir, \"config\", \"user.name\", options.botLogin]);\n await git([\"-C\", options.dir, \"config\", \"user.email\", options.botEmail]);\n if (options.prNumber !== undefined) {\n await git(\n [\"-C\", options.dir, \"fetch\", \"--depth\", \"50\", \"origin\", `pull/${options.prNumber}/head`],\n options.token,\n );\n await git([\n \"-C\",\n options.dir,\n \"checkout\",\n \"-B\",\n prCheckoutName(options.prNumber, options.prHeadBranch),\n \"FETCH_HEAD\",\n ]);\n }\n}\n\n/**\n * Refresh a conversation clone from origin. Always fetches; only moves the\n * checkout when that provably cannot lose agent work: the target branch is\n * the one checked out, the tree is clean, and it has no commits of its own\n * (`checkout -B` then handles fast-forward and force-pushed heads alike).\n * Anything else stays fetch-only — FETCH_HEAD is left for the agent, which\n * has full credential-less git inside the sandbox, to merge or rebase itself.\n */\nexport async function syncRepo(options: SyncRepoOptions): Promise<SyncRepoResult> {\n const { dir, token } = options;\n let refspec: string;\n let target: string;\n if (options.branch) {\n refspec = options.branch;\n target = options.branch;\n } else if (options.prNumber !== undefined) {\n refspec = `pull/${options.prNumber}/head`;\n target = prCheckoutName(options.prNumber, options.prHeadBranch);\n } else if (options.defaultBranch) {\n refspec = options.defaultBranch;\n target = options.defaultBranch;\n } else {\n throw new Error(\"syncRepo needs a branch, a PR number, or the default branch\");\n }\n\n await git([\"-C\", dir, \"fetch\", \"--depth\", \"50\", \"origin\", refspec], token);\n const fetchedSha = (await git([\"-C\", dir, \"rev-parse\", \"FETCH_HEAD\"])).trim();\n const dirty = (await git([\"-C\", dir, \"status\", \"--porcelain\"])).trim().length > 0;\n const currentBranch = (await git([\"-C\", dir, \"rev-parse\", \"--abbrev-ref\", \"HEAD\"])).trim();\n // Clones made before the head branch name was resolvable sit on the\n // synthetic pr-<n>; treat that as the same checkout so a clean sync\n // migrates them to the real name instead of going fetch-only forever.\n const legacyPrBranch = options.prNumber !== undefined ? `pr-${options.prNumber}` : undefined;\n const onTarget =\n currentBranch === target || (legacyPrBranch !== undefined && currentBranch === legacyPrBranch);\n let localCommits = 0;\n if (onTarget) {\n // Commits unique to HEAD split two ways: ones the agent committed here\n // (the clone's preconfigured bot identity) are its work and must survive;\n // ones committed by others were force-pushed away upstream and are safe\n // to drop. Filter by the bot committer so a rebased PR head still syncs.\n const botEmail = (await git([\"-C\", dir, \"config\", \"user.email\"])).trim();\n localCommits = Number(\n (\n await git([\"-C\", dir, \"rev-list\", \"--count\", `--committer=${botEmail}`, \"FETCH_HEAD..HEAD\"])\n ).trim(),\n );\n }\n\n const updatedCheckout = onTarget && !dirty && localCommits === 0;\n if (updatedCheckout) {\n await git([\"-C\", dir, \"checkout\", \"-B\", target, \"FETCH_HEAD\"]);\n }\n return { target, fetchedSha, updatedCheckout, dirty, currentBranch, localCommits };\n}\n\n/**\n * Push one local branch to origin. Non-force by construction (plain refspec),\n * and only `pi/*` branches are accepted.\n */\nexport async function pushBranch(options: PushBranchOptions): Promise<void> {\n const { dir, branch, token } = options;\n if (!GITHUB_PUSH_BRANCH_PATTERN.test(branch)) {\n throw new Error(\n `Refusing to push branch '${branch}': only branches matching pi/<name> may be pushed.`,\n );\n }\n try {\n await git([\"-C\", dir, \"rev-parse\", \"--verify\", \"--quiet\", `refs/heads/${branch}`]);\n } catch {\n throw new Error(`Branch '${branch}' does not exist in the conversation's ./repo clone.`);\n }\n await git([\"-C\", dir, \"push\", \"origin\", `refs/heads/${branch}:refs/heads/${branch}`], token);\n}\n"]}
1
+ {"version":3,"file":"repo.js","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAQjC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAE1C,MAAM,cAAc,GAAG,OAAO,CAAC;AAE/B;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,qCAAqC,CAAC;AAEhF,mFAAmF;AACnF,MAAM,UAAU,mBAAmB,CAAC,MAAc;IAChD,OAAO,IAAI,CAAC,MAAM,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AC;QACP,MAAM,IAAI,KAAK,CAAC,WAAW,MAAM,sDAAsD,CAAC,CAAC;IAC3F,CAAC;IACD,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,MAAM,eAAe,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["import { execFile } from \"child_process\";\nimport { join } from \"path\";\nimport type { Office } from \"../../office/index.js\";\nimport { promisify } from \"util\";\nimport type {\n CloneRepoOptions,\n PushBranchOptions,\n SyncRepoOptions,\n SyncRepoResult,\n} from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst GIT_TIMEOUT_MS = 120_000;\n\n/**\n * Branches the bot may push: `pi/<name>`. Everything else — including the\n * repo's default branch by construction — is refused, so a driven agent can\n * only ever produce reviewable branches, never touch mainline directly.\n */\nexport const GITHUB_PUSH_BRANCH_PATTERN = /^pi\\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;\n\n/** The conversation's clone location (bind-mounted into the sandbox as ./repo). */\nexport function conversationRepoDir(office: Office): string {\n return join(office.dir, \"repo\");\n}\n\n/**\n * Pass the ephemeral token as a per-invocation header, never in the remote\n * URL: nothing credential-shaped may end up in `.git/config`, which lives in\n * the conversation dir and is bind-mounted into the sandbox.\n */\nfunction gitAuthArgs(token: string): string[] {\n const basic = Buffer.from(`x-access-token:${token}`).toString(\"base64\");\n return [\"-c\", `http.extraheader=Authorization: basic ${basic}`];\n}\n\nasync function git(args: string[], token?: string): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", [...(token ? gitAuthArgs(token) : []), ...args], {\n timeout: GIT_TIMEOUT_MS,\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n return stdout;\n}\n\n/**\n * Git itself rejects these ref shapes; the check just keeps an API-supplied\n * branch name that would parse as a git option (leading dash) or an invalid\n * ref out of argv entirely instead of surfacing as a git error mid-clone.\n */\nfunction isSafeBranchName(name: string): boolean {\n return (\n name.length > 0 && !name.startsWith(\"-\") && !name.includes(\"..\") && !/[\\s~^:?*[\\\\]/.test(name)\n );\n}\n\n/**\n * Local checkout name for a PR conversation: the PR's real head branch when\n * known (same-repo heads only — the caller resolves that), falling back to\n * the synthetic `pr-<n>` for fork PRs, unresolvable heads, and unsafe names.\n * Using the real name is what lets the agent update the PR in place: commit\n * on a `pi/*` head and `github_pr` pushes back to the same branch.\n */\nfunction prCheckoutName(prNumber: number, prHeadBranch?: string): string {\n return prHeadBranch && isSafeBranchName(prHeadBranch) ? prHeadBranch : `pr-${prNumber}`;\n}\n\n/**\n * Shallow-clone a repo into a conversation dir and preconfigure the bot's\n * commit identity. For PR conversations, additionally fetch the PR head and\n * check it out so the agent starts on the code under review — under its real\n * branch name when the caller resolved one, which is what lets the agent push\n * fixes back to the PR itself.\n */\nexport async function cloneRepo(options: CloneRepoOptions): Promise<void> {\n await git([\"clone\", \"--depth\", \"50\", options.url, options.dir], options.token);\n await git([\"-C\", options.dir, \"config\", \"user.name\", options.botLogin]);\n await git([\"-C\", options.dir, \"config\", \"user.email\", options.botEmail]);\n if (options.prNumber !== undefined) {\n await git(\n [\"-C\", options.dir, \"fetch\", \"--depth\", \"50\", \"origin\", `pull/${options.prNumber}/head`],\n options.token,\n );\n await git([\n \"-C\",\n options.dir,\n \"checkout\",\n \"-B\",\n prCheckoutName(options.prNumber, options.prHeadBranch),\n \"FETCH_HEAD\",\n ]);\n }\n}\n\n/**\n * Refresh a conversation clone from origin. Always fetches; only moves the\n * checkout when that provably cannot lose agent work: the target branch is\n * the one checked out, the tree is clean, and it has no commits of its own\n * (`checkout -B` then handles fast-forward and force-pushed heads alike).\n * Anything else stays fetch-only — FETCH_HEAD is left for the agent, which\n * has full credential-less git inside the sandbox, to merge or rebase itself.\n */\nexport async function syncRepo(options: SyncRepoOptions): Promise<SyncRepoResult> {\n const { dir, token } = options;\n let refspec: string;\n let target: string;\n if (options.branch) {\n refspec = options.branch;\n target = options.branch;\n } else if (options.prNumber !== undefined) {\n refspec = `pull/${options.prNumber}/head`;\n target = prCheckoutName(options.prNumber, options.prHeadBranch);\n } else if (options.defaultBranch) {\n refspec = options.defaultBranch;\n target = options.defaultBranch;\n } else {\n throw new Error(\"syncRepo needs a branch, a PR number, or the default branch\");\n }\n\n await git([\"-C\", dir, \"fetch\", \"--depth\", \"50\", \"origin\", refspec], token);\n const fetchedSha = (await git([\"-C\", dir, \"rev-parse\", \"FETCH_HEAD\"])).trim();\n const dirty = (await git([\"-C\", dir, \"status\", \"--porcelain\"])).trim().length > 0;\n const currentBranch = (await git([\"-C\", dir, \"rev-parse\", \"--abbrev-ref\", \"HEAD\"])).trim();\n // Clones made before the head branch name was resolvable sit on the\n // synthetic pr-<n>; treat that as the same checkout so a clean sync\n // migrates them to the real name instead of going fetch-only forever.\n const legacyPrBranch = options.prNumber !== undefined ? `pr-${options.prNumber}` : undefined;\n const onTarget =\n currentBranch === target || (legacyPrBranch !== undefined && currentBranch === legacyPrBranch);\n let localCommits = 0;\n if (onTarget) {\n // Commits unique to HEAD split two ways: ones the agent committed here\n // (the clone's preconfigured bot identity) are its work and must survive;\n // ones committed by others were force-pushed away upstream and are safe\n // to drop. Filter by the bot committer so a rebased PR head still syncs.\n const botEmail = (await git([\"-C\", dir, \"config\", \"user.email\"])).trim();\n localCommits = Number(\n (\n await git([\"-C\", dir, \"rev-list\", \"--count\", `--committer=${botEmail}`, \"FETCH_HEAD..HEAD\"])\n ).trim(),\n );\n }\n\n const updatedCheckout = onTarget && !dirty && localCommits === 0;\n if (updatedCheckout) {\n await git([\"-C\", dir, \"checkout\", \"-B\", target, \"FETCH_HEAD\"]);\n }\n return { target, fetchedSha, updatedCheckout, dirty, currentBranch, localCommits };\n}\n\n/**\n * Push one local branch to origin. Non-force by construction (plain refspec),\n * and only `pi/*` branches are accepted.\n */\nexport async function pushBranch(options: PushBranchOptions): Promise<void> {\n const { dir, branch, token } = options;\n if (!GITHUB_PUSH_BRANCH_PATTERN.test(branch)) {\n throw new Error(\n `Refusing to push branch '${branch}': only branches matching pi/<name> may be pushed.`,\n );\n }\n try {\n await git([\"-C\", dir, \"rev-parse\", \"--verify\", \"--quiet\", `refs/heads/${branch}`]);\n } catch {\n throw new Error(`Branch '${branch}' does not exist in the conversation's ./repo clone.`);\n }\n await git([\"-C\", dir, \"push\", \"origin\", `refs/heads/${branch}:refs/heads/${branch}`], token);\n}\n"]}
@@ -12,7 +12,7 @@ export interface GithubBotConfig {
12
12
  /** `owner/repo` entries to watch; empty = all installation repositories. */
13
13
  repos: string[];
14
14
  pollIntervalMs: number;
15
- workingDir: string;
15
+ workspace: import("../../office/types.js").Workspace;
16
16
  /**
17
17
  * Where the poll watermark state (baseline + seen ids) is persisted. Lives
18
18
  * under the host-only state dir: the workspace dir can be mounted into