typeclaw 0.48.13 → 0.49.0

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 (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -1,12 +1,22 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ import { githubReviewChecks } from '@/channels/github-review-check'
4
+ import { observeVerifiedDismissals } from '@/channels/github-review-turn-ledger'
1
5
  import type { GithubTokenBridge } from '@/channels/github-token-bridge'
2
6
  import type { ChannelRouter } from '@/channels/router'
3
7
  import type { ChannelAdapterConfig, GithubAdapterConfig } from '@/channels/schema'
4
- import type { ChannelSelfIdentityResolver, InboundMessage } from '@/channels/types'
8
+ import type {
9
+ ChannelSelfIdentityResolver,
10
+ InboundMessage,
11
+ RecoveryAdapterCallbacks,
12
+ RouteReceipt,
13
+ } from '@/channels/types'
5
14
  import { resolveSecret } from '@/secrets/resolve'
6
15
  import type { GithubSecretsBlock } from '@/secrets/schema'
7
16
 
8
17
  import { describeError } from '../../describe-error'
9
18
  import { canonicalGithubRepo } from '../../github-repo'
19
+ import { withOutboundAccount } from '../outbound-account'
10
20
  import { buildAuthStrategy, type GithubAuthContext } from './auth'
11
21
  import { createGithubChannelNameResolver } from './channel-resolver'
12
22
  import { createDeliveryDedup } from './dedup'
@@ -14,18 +24,28 @@ import { findPermissionGaps } from './event-permissions'
14
24
  import { createGithubFetchAttachmentCallback } from './fetch-attachment'
15
25
  import { createGithubHistoryCallback } from './history'
16
26
  import { createGithubWebhookHandler, processVerifiedGithubDelivery, type GithubWebhookHandlerOptions } from './inbound'
27
+ import { readGithubLastAlive, writeGithubLastAlive } from './last-alive'
17
28
  import { applyManagedPath, buildManagedPath, resolveAgentId } from './managed-path'
18
29
  import { createGithubMembershipResolver } from './membership'
19
30
  import { createGithubOutboundCallback } from './outbound'
31
+ import { loadPendingReviewStore, type PendingReviewStore } from './pending-review-store'
20
32
  import {
21
33
  buildAppPermissionPreflightGuidance,
22
34
  buildPermissionGuidance,
23
35
  parseListHooksPermissionStatus,
24
36
  } from './permission-guidance'
25
37
  import { createGithubReactionCallback, createGithubRemoveReactionCallback } from './reactions'
38
+ import { createGithubOwnReactionCallbacks } from './reactions'
26
39
  import { loadReconcileCooldownStore, type ReconcileCooldownStore } from './reconcile-cooldown-store'
27
- import { reconcileOpenPrs } from './reconcile-open-prs'
40
+ import { completePendingReview, reconcileOpenPrs, replayPendingReviews } from './reconcile-open-prs'
28
41
  import { createRecoveredGuidLog, recoverFailedGithubDeliveries } from './recover-failed-deliveries'
42
+ import { createGithubRecoveryCallbacks } from './recovery'
43
+ import {
44
+ createGithubReviewCheckPublisher,
45
+ createReviewCheckLeaseStore,
46
+ reviewCheckDetails,
47
+ reviewCheckName,
48
+ } from './review-check'
29
49
  import { createGithubReviewStateResolver } from './review-state'
30
50
  import { createGithubReviewSubmitter } from './review-submitter'
31
51
  import { createGithubReviewThreadResolver } from './review-thread-resolver'
@@ -132,6 +152,9 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
132
152
  let deliveryRecoveryTimer: { clear: () => void } | null = null
133
153
  let reconcileTimer: { clear: () => void } | null = null
134
154
  let reconcileCooldownStore: ReconcileCooldownStore | null = null
155
+ let pendingReviewStore: PendingReviewStore | null = null
156
+ let stopObservingDismissals: (() => void) | null = null
157
+ let lifecycleGeneration = 0
135
158
  let unregisterTokenBridge: (() => void) | null = null
136
159
  const workspaceByChat = new Map<string, string>()
137
160
  const setIntervalFn =
@@ -151,10 +174,41 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
151
174
  // does NOT mutate process.env.GH_TOKEN. App credentials stay behind this
152
175
  // repo-scoped resolver instead of entering the ambient process environment.
153
176
  const authToken = (context?: GithubAuthContext) => auth.token(context)
154
- const outbound = createGithubOutboundCallback({
177
+ // The boot reconcile pass re-admits review work a restart killed, so a restart notice for an
178
+ // interrupted review would wrongly tell the author it was dropped. Only a replay the router
179
+ // newly accepted counts: a duplicate may be the very admission that was interrupted.
180
+ let firstReconcilePending = true
181
+ const reconcileReplayedPrs = new Set<string>()
182
+ const recoveryCallbacks: RecoveryAdapterCallbacks = {
183
+ ...createGithubRecoveryCallbacks(auth, fetchImpl, () => (selfId !== null ? `github:${selfId}` : undefined)),
184
+ redelivery: (record, eventKinds) => {
185
+ if (!eventKinds.every((kind) => REVIEW_TRIGGER_EVENT_KINDS.has(kind))) return 'not-redelivered'
186
+ const prNumber = /^pr:(\d+)$/.exec(record.target.chat)?.[1]
187
+ if (prNumber !== undefined && pendingReviewStore?.has(record.target.workspace, Number(prNumber)))
188
+ return 'redelivered'
189
+ // A fresh-review reconcile replay is runtime-synthesized: nobody asked, so a restart notice
190
+ // would only announce system state. The next periodic pass after the cooldown retries it.
191
+ // Held re-reviews (`pull_request:reconcile:rereview`) replay only on boot, so they keep the
192
+ // normal notice path below.
193
+ if (eventKinds.every((kind) => kind === 'pull_request:reconcile')) return 'redelivered'
194
+ if (reconcileReplayedPrs.has(prReplayKey(record.target.workspace, record.target.chat))) return 'redelivered'
195
+ return firstReconcilePending ? 'pending' : 'not-redelivered'
196
+ },
197
+ }
198
+ const outbound = withOutboundAccount(
199
+ createGithubOutboundCallback({
200
+ token: authToken,
201
+ authType: options.secrets.auth.type,
202
+ logger,
203
+ fetchImpl,
204
+ accountIdentity: recoveryCallbacks.accountIdentity,
205
+ }),
206
+ () => recoveryCallbacks.cachedAccountIdentity?.(),
207
+ )
208
+ const ownReaction = createGithubOwnReactionCallbacks({
155
209
  token: authToken,
210
+ getSelf: () => auth.getSelf(),
156
211
  authType: options.secrets.auth.type,
157
- logger,
158
212
  fetchImpl,
159
213
  })
160
214
  const reaction = createGithubReactionCallback({
@@ -184,9 +238,32 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
184
238
  approve: () => options.configRef().review.approve,
185
239
  fetchImpl,
186
240
  })
241
+ const reviewCheckPublisher = createGithubReviewCheckPublisher({
242
+ token: authToken,
243
+ authType: options.secrets.auth.type,
244
+ enabled: () => options.configRef().review.check,
245
+ checkName: () => reviewCheckName(selfLogin),
246
+ logger,
247
+ fetchImpl,
248
+ })
187
249
  const reviewSubmitter = createGithubReviewSubmitter({
188
250
  token: authToken,
189
251
  allowApprove: () => options.configRef().review.approve,
252
+ accountIdentity: recoveryCallbacks.accountIdentity,
253
+ onReviewPosted: async (posted) => {
254
+ if (pendingReviewStore !== null) {
255
+ try {
256
+ await completePendingReview(pendingReviewStore, { ...posted, submittedAt: Date.now() }, authToken, fetchImpl)
257
+ } catch (error) {
258
+ logger.warn(`[github] pending review completion persist failed: ${describeError(error)}`)
259
+ }
260
+ }
261
+ void githubReviewChecks.reviewPosted(
262
+ { repo: posted.repo, pullRequest: posted.prNumber, headSha: posted.headSha },
263
+ posted.state,
264
+ reviewCheckDetails(posted.reviewId, posted.comments),
265
+ )
266
+ },
190
267
  fetchImpl,
191
268
  })
192
269
  const channelNameResolver = createGithubChannelNameResolver({ token: authToken, fetchImpl })
@@ -202,15 +279,32 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
202
279
  // Shared inbound entry. Both the live webhook handler and the startup
203
280
  // reconciliation pass route through this so a replayed PR takes the exact
204
281
  // same path a real delivery would.
205
- const routeInbound = (message: InboundMessage): void => {
282
+ const routeInbound = async (message: InboundMessage): Promise<RouteReceipt> => {
206
283
  rememberWorkspace(message.workspace, message.chat)
207
- // Ack-first: wrap in Promise.resolve so a synchronous throw inside
208
- // router.route() cannot prevent the 200 response from being returned.
209
- void Promise.resolve()
210
- .then(() => options.router.route(message))
211
- .catch((err: unknown) => {
212
- logger.error(`[github] route failed: ${describeError(err)}`)
213
- })
284
+ const store = pendingReviewStore
285
+ const pending = message.githubPendingReview
286
+ const prNumber = /^pr:(\d+)$/.exec(message.chat)?.[1]
287
+ // The webhook handler schedules this outside its acknowledgment path.
288
+ return options.router.route(
289
+ {
290
+ ...message,
291
+ accountIdentity: message.accountIdentity ?? (selfId === null ? undefined : `github:${selfId}`),
292
+ eventKind: message.eventKind ?? 'review-followup',
293
+ revision: message.revision ?? 'original',
294
+ },
295
+ store !== null && pending !== undefined && prNumber !== undefined
296
+ ? () =>
297
+ store.record({
298
+ repo: message.workspace,
299
+ prNumber: Number(prNumber),
300
+ ...pending,
301
+ admittedAt: Date.now(),
302
+ authorId: message.authorId,
303
+ authorName: message.authorName,
304
+ authorIsBot: message.authorIsBot,
305
+ })
306
+ : undefined,
307
+ )
214
308
  }
215
309
  const handlerOptions: GithubWebhookHandlerOptions = {
216
310
  webhookSecret,
@@ -227,6 +321,12 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
227
321
  logger,
228
322
  route: routeInbound,
229
323
  abortGithubPrTurn: options.router.abortGithubPrTurn,
324
+ clearPendingReview: async (workspace, prNumber) => {
325
+ await pendingReviewStore?.clear(workspace, prNumber)
326
+ },
327
+ reviewSubmitted: async (review) => {
328
+ if (pendingReviewStore !== null) await completePendingReview(pendingReviewStore, review, authToken, fetchImpl)
329
+ },
230
330
  clearReconcileCooldown: async (workspace, prId) => {
231
331
  if (reconcileCooldownStore === null) return 'not-initialized'
232
332
  await reconcileCooldownStore.clear(workspace, prId)
@@ -238,14 +338,41 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
238
338
  return {
239
339
  async start(): Promise<void> {
240
340
  if (started) return
341
+ firstReconcilePending = true
342
+ reconcileReplayedPrs.clear()
241
343
  const self = await auth.getSelf()
242
344
  selfId = String(self.id)
243
345
  selfLogin = self.login
346
+ // Ready before binding HTTP: the first live webhook can create pending work.
347
+ const loadedPendingReviewStore = await loadPendingReviewStore(options.agentDir, logger)
348
+ pendingReviewStore = loadedPendingReviewStore
349
+ // Keep suppression through the boot even when API verification clears an
350
+ // entry as already completed or closed: there is no lost work to announce.
351
+ for (const pending of await loadedPendingReviewStore.list())
352
+ reconcileReplayedPrs.add(prReplayKey(pending.repo, `pr:${pending.prNumber}`))
353
+ stopObservingDismissals = observeVerifiedDismissals(async (dismissal) => {
354
+ if (dismissal.commitSha === undefined || dismissal.startedAt === undefined) return
355
+ const pending = (await loadedPendingReviewStore.list()).find(
356
+ (entry) =>
357
+ canonicalGithubRepo(entry.repo) === canonicalGithubRepo(dismissal.workspace) &&
358
+ entry.prNumber === dismissal.prNumber,
359
+ )
360
+ if (
361
+ pending?.kind !== 'rereview' ||
362
+ pending.headSha !== dismissal.commitSha ||
363
+ pending.admittedAt > dismissal.startedAt
364
+ )
365
+ return
366
+ await loadedPendingReviewStore.clear(pending.repo, pending.prNumber, pending)
367
+ })
244
368
  // Register all callbacks before binding the HTTP listener so the router
245
369
  // is fully wired before any webhook can arrive.
246
370
  options.router.registerOutbound('github', outbound)
371
+ options.router.registerRecoveryAdapter('github', recoveryCallbacks)
247
372
  options.router.registerReaction('github', reaction)
248
373
  options.router.registerRemoveReaction('github', removeReaction)
374
+ options.router.registerPrepareOwnReaction('github', ownReaction.prepare)
375
+ options.router.registerRemoveOwnReaction('github', ownReaction.remove)
249
376
  options.router.registerTyping('github', typing)
250
377
  options.router.registerHistory('github', history)
251
378
  options.router.registerMembership('github', membership)
@@ -258,11 +385,16 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
258
385
  try {
259
386
  server = (options.httpListenImpl ?? listenWithBun)(options.configRef().webhookPort, handler)
260
387
  } catch (err) {
388
+ stopObservingDismissals?.()
389
+ stopObservingDismissals = null
261
390
  // Listener failed — roll back all registrations so stop() is a no-op
262
391
  // and the manager can report the failure cleanly.
263
392
  options.router.unregisterOutbound('github', outbound)
393
+ options.router.unregisterRecoveryAdapter('github', recoveryCallbacks)
264
394
  options.router.unregisterReaction('github', reaction)
265
395
  options.router.unregisterRemoveReaction('github', removeReaction)
396
+ options.router.unregisterPrepareOwnReaction('github', ownReaction.prepare)
397
+ options.router.unregisterRemoveOwnReaction('github', ownReaction.remove)
266
398
  options.router.unregisterTyping('github', typing)
267
399
  options.router.unregisterHistory('github', history)
268
400
  options.router.unregisterMembership('github', membership)
@@ -304,7 +436,9 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
304
436
  // on — a cross-tenant leak under a multi-owner App. Enforced here, not in
305
437
  // the parser, because this adapter is the authority that owns repos[].
306
438
  unregisterTokenBridge = options.githubTokenBridge.registerResolver(
307
- (repoSlug) => {
439
+ async (repoSlug) => {
440
+ const capturedSelfId = selfId
441
+ if (capturedSelfId === null) throw new Error('GitHub authenticated account is unavailable')
308
442
  const allowed = new Set((options.configRef().repos ?? []).map(canonicalGithubRepo))
309
443
  if (!allowed.has(canonicalGithubRepo(repoSlug))) {
310
444
  throw new Error(
@@ -313,17 +447,31 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
313
447
  'or add it to `repos[]` if the agent is meant to operate there.',
314
448
  )
315
449
  }
316
- return auth.token({ repoSlug })
450
+ const token = await auth.token({ repoSlug })
451
+ return { token, accountIdentity: `github:${capturedSelfId}` }
317
452
  },
318
453
  () => selfLogin,
319
454
  )
320
455
  }
321
456
  logger.info(`[github] webhook listening on port ${options.configRef().webhookPort} as @${self.login}`)
457
+ // Attach before any webhook can start a review, and close checks a
458
+ // previous process left in progress.
459
+ await githubReviewChecks.attach({
460
+ publisher: reviewCheckPublisher,
461
+ store: createReviewCheckLeaseStore(options.agentDir),
462
+ logger,
463
+ })
322
464
  // Best-effort: App-only preflight that compares the installation's granted
323
465
  // permissions against the configured eventAllowlist and warns about gaps.
324
466
  // Catches the most common misconfiguration (App installed with the default
325
467
  // metadata-only permission set) before any event fires a 403.
326
- await runAppPermissionPreflight(logger, auth, options.configRef().eventAllowlist, options.configRef().repos ?? [])
468
+ await runAppPermissionPreflight(
469
+ logger,
470
+ auth,
471
+ options.configRef().eventAllowlist,
472
+ options.configRef().repos ?? [],
473
+ options.configRef().review.check,
474
+ )
327
475
  // Repository webhook registration is best-effort: failures are logged
328
476
  // per-repo, the adapter stays up. A misconfigured PAT or App that
329
477
  // can't manage hooks must not prevent the adapter from accepting
@@ -381,29 +529,80 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
381
529
  const loadedReconcileCooldownStore =
382
530
  repos.length > 0 ? await loadReconcileCooldownStore(options.agentDir, logger) : null
383
531
  reconcileCooldownStore = loadedReconcileCooldownStore
532
+ const bootAt = Date.now()
533
+ // First boot has no marker: only PRs opened from now on qualify, never the backlog.
534
+ const createdSince =
535
+ loadedReconcileCooldownStore !== null ? ((await readGithubLastAlive(options.agentDir)) ?? bootAt) : bootAt
536
+ const markAlive = (): Promise<void> =>
537
+ writeGithubLastAlive(options.agentDir, Date.now()).catch((err: unknown) => {
538
+ logger.warn(`[github] last-alive marker write failed: ${describeError(err)}`)
539
+ })
540
+ if (loadedReconcileCooldownStore !== null) await markAlive()
384
541
  // Resolve review.on per call, not from the captured startup cfg: review.on
385
542
  // is live-reloadable, so a periodic tick must honor a change to `off`
386
543
  // (reconcileOpenPrs short-circuits on `off`) instead of scanning forever.
387
- const runReconcile = (store: ReconcileCooldownStore): Promise<unknown> =>
544
+ const reconcileGeneration = lifecycleGeneration
545
+ const replayId = randomUUID()
546
+ const routeReconcileReplay = async (message: InboundMessage): Promise<RouteReceipt> => {
547
+ const receipt = await routeInbound(message)
548
+ if (receipt.kind === 'accepted' && reconcileGeneration === lifecycleGeneration)
549
+ reconcileReplayedPrs.add(prReplayKey(message.workspace, message.chat))
550
+ return receipt
551
+ }
552
+ const runReconcile = (store: ReconcileCooldownStore, includeHeldReviews: boolean): Promise<unknown> =>
388
553
  reconcileOpenPrs({
554
+ includeHeldReviews,
389
555
  repos,
390
556
  reviewOn: options.configRef().review.on,
391
557
  selfLogin,
392
558
  authType: options.secrets.auth.type,
393
559
  token: authToken,
394
- route: routeInbound,
560
+ route: routeReconcileReplay,
395
561
  logger,
396
562
  isBotInTeam,
397
563
  fetchImpl,
398
564
  cooldownStore: store,
565
+ pendingStore: loadedPendingReviewStore,
566
+ createdSince,
567
+ isCancelled: () => reconcileGeneration !== lifecycleGeneration,
399
568
  }).catch((err: unknown) => {
400
569
  logger.warn(`[github] reconcile pass failed: ${describeError(err)}`)
401
570
  })
571
+ if (loadedReconcileCooldownStore === null) firstReconcilePending = false
402
572
  if (loadedReconcileCooldownStore !== null) {
403
- await runReconcile(loadedReconcileCooldownStore)
573
+ // Detached on purpose: the pass awaits each replay's router receipt, and
574
+ // routing can depend on boot progress that itself waits for this start()
575
+ // to resolve. Awaiting it here stalled boot before tunnels started, so
576
+ // webhooks never registered and no PR was reviewed.
577
+ // Only the boot pass re-checks held CHANGES_REQUESTED reviews: a restart
578
+ // is what kills an in-flight push follow-up, and a periodic tick could
579
+ // race a live one.
580
+ void replayPendingReviews({
581
+ repos,
582
+ reviewOn: options.configRef().review.on,
583
+ selfLogin,
584
+ authType: options.secrets.auth.type,
585
+ token: authToken,
586
+ route: routeReconcileReplay,
587
+ logger,
588
+ fetchImpl,
589
+ pendingStore: loadedPendingReviewStore,
590
+ replayId,
591
+ isCancelled: () => reconcileGeneration !== lifecycleGeneration,
592
+ })
593
+ .catch((error: unknown) => {
594
+ logger.warn(`[github] pending review replay failed: ${describeError(error)}`)
595
+ })
596
+ .then(() => runReconcile(loadedReconcileCooldownStore, true))
597
+ .finally(() => {
598
+ if (reconcileGeneration === lifecycleGeneration) firstReconcilePending = false
599
+ })
404
600
  const reconcileIntervalMs = options.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS
405
601
  if (reconcileIntervalMs > 0) {
406
- reconcileTimer = setIntervalFn(() => void runReconcile(loadedReconcileCooldownStore), reconcileIntervalMs)
602
+ reconcileTimer = setIntervalFn(() => {
603
+ void markAlive()
604
+ void runReconcile(loadedReconcileCooldownStore, false)
605
+ }, reconcileIntervalMs)
407
606
  }
408
607
  }
409
608
  // Periodically recover inbound deliveries that failed at the tunnel and
@@ -438,6 +637,9 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
438
637
  async stop(): Promise<void> {
439
638
  if (!started) return
440
639
  started = false
640
+ lifecycleGeneration += 1
641
+ stopObservingDismissals?.()
642
+ stopObservingDismissals = null
441
643
  // Stop the recovery sweep first: its async work outlives the synchronous
442
644
  // unregister calls below, and a tick landing mid-teardown would query a
443
645
  // hook we're about to deregister and could route during shutdown.
@@ -449,11 +651,19 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
449
651
  reconcileTimer.clear()
450
652
  reconcileTimer = null
451
653
  }
654
+ if (reconcileCooldownStore !== null)
655
+ await writeGithubLastAlive(options.agentDir, Date.now()).catch((err: unknown) => {
656
+ logger.warn(`[github] last-alive marker write failed: ${describeError(err)}`)
657
+ })
658
+ githubReviewChecks.detach(reviewCheckPublisher)
452
659
  options.router.unregisterOutbound('github', outbound)
453
660
  options.router.unregisterReaction('github', reaction)
454
661
  options.router.unregisterRemoveReaction('github', removeReaction)
662
+ options.router.unregisterPrepareOwnReaction('github', ownReaction.prepare)
663
+ options.router.unregisterRemoveOwnReaction('github', ownReaction.remove)
455
664
  options.router.unregisterTyping('github', typing)
456
665
  options.router.unregisterHistory('github', history)
666
+ options.router.unregisterRecoveryAdapter('github', recoveryCallbacks)
457
667
  options.router.unregisterMembership('github', membership)
458
668
  options.router.unregisterChannelNameResolver('github', channelNameResolver)
459
669
  options.router.unregisterSelfIdentity('github', selfIdentityResolver)
@@ -489,6 +699,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
489
699
  selfId = null
490
700
  selfLogin = null
491
701
  reconcileCooldownStore = null
702
+ pendingReviewStore = null
492
703
  },
493
704
  isConnected(): boolean {
494
705
  return started && selfLogin !== null
@@ -578,6 +789,7 @@ async function runAppPermissionPreflight(
578
789
  auth: ReturnType<typeof buildAuthStrategy>,
579
790
  eventAllowlist: readonly string[],
580
791
  repos: readonly string[],
792
+ reviewCheck: boolean,
581
793
  ): Promise<void> {
582
794
  if (auth.getInstallationGrants === undefined) return
583
795
  const getGrants = (context: GithubAuthContext | undefined) => auth.getInstallationGrants?.(context)
@@ -604,6 +816,13 @@ async function runAppPermissionPreflight(
604
816
  if (grants === undefined) continue
605
817
  const gaps = findPermissionGaps(eventAllowlist, grants.permissions)
606
818
  if (gaps.length > 0) logger.warn(buildAppPermissionPreflightGuidance(gaps))
819
+ const checks = grants.permissions.checks
820
+ if (reviewCheck && checks !== 'write' && checks !== 'admin') {
821
+ logger.warn(
822
+ `[github] review check will be skipped for ${label}: the GitHub App lacks "Checks: Read and write". ` +
823
+ 'Grant it in the App settings to show reviews as a PR check, or set channels.github.review.check to false.',
824
+ )
825
+ }
607
826
  }
608
827
  }
609
828
 
@@ -621,3 +840,16 @@ function logDeregistrationOutcome(
621
840
  function defaultSleep(ms: number): Promise<void> {
622
841
  return new Promise((resolve) => setTimeout(resolve, ms))
623
842
  }
843
+
844
+ const REVIEW_TRIGGER_EVENT_KINDS: ReadonlySet<string> = new Set([
845
+ 'pull_request:opened',
846
+ 'pull_request:ready_for_review',
847
+ 'pull_request:review_requested',
848
+ 'pull_request:synchronize:review-followup',
849
+ 'pull_request:reconcile',
850
+ 'pull_request:reconcile:rereview',
851
+ ])
852
+
853
+ function prReplayKey(workspace: string, chat: string): string {
854
+ return `${canonicalGithubRepo(workspace)}#${chat}`
855
+ }
@@ -0,0 +1,27 @@
1
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+
4
+ // When the GitHub adapter was last known alive. Reconcile replays only PRs
5
+ // opened since then: those are the deliveries a downtime or tunnel change could
6
+ // have dropped, while anything older was either seen live or predates the repo
7
+ // being watched.
8
+
9
+ const FILE = 'github-last-alive.json'
10
+
11
+ export async function readGithubLastAlive(agentDir: string): Promise<number | null> {
12
+ try {
13
+ const parsed = JSON.parse(await readFile(join(agentDir, 'channels', FILE), 'utf8')) as { at?: unknown }
14
+ return typeof parsed.at === 'number' && Number.isFinite(parsed.at) ? parsed.at : null
15
+ } catch {
16
+ return null
17
+ }
18
+ }
19
+
20
+ export async function writeGithubLastAlive(agentDir: string, at: number): Promise<void> {
21
+ const dir = join(agentDir, 'channels')
22
+ await mkdir(dir, { recursive: true })
23
+ const path = join(dir, FILE)
24
+ const tmp = `${path}.${process.pid}.tmp`
25
+ await writeFile(tmp, JSON.stringify({ at }))
26
+ await rename(tmp, path)
27
+ }
@@ -1,6 +1,7 @@
1
1
  import type { OutboundCallback, OutboundMessage, SendResult } from '@/channels/types'
2
2
 
3
3
  import { describeError } from '../../describe-error'
4
+ import { recoveryHttpFailure, recoveryMarker } from '../recovery-correlation'
4
5
  import type { GithubAuthContext } from './auth'
5
6
  import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
6
7
  import {
@@ -17,12 +18,37 @@ export function createGithubOutboundCallback(deps: {
17
18
  authType: GithubAuthType
18
19
  logger: GithubOutboundLogger
19
20
  fetchImpl?: typeof fetch
21
+ accountIdentity?: () => Promise<string | undefined>
20
22
  }): OutboundCallback {
21
23
  const fetchImpl = deps.fetchImpl ?? fetch
22
24
  return async (msg: OutboundMessage): Promise<SendResult> => {
23
25
  if (msg.adapter !== 'github') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
24
26
  if ((msg.attachments ?? []).length > 0) return { ok: false, error: 'github-bot-does-not-support-attachments' }
25
- const body = msg.text ?? ''
27
+ const recovery = msg.sendOptions?.accounting === 'recovery' ? msg.sendOptions : undefined
28
+ if (recovery && (await deps.accountIdentity?.()) !== recovery.expectedAccountIdentity)
29
+ return {
30
+ ok: false,
31
+ error: 'recovery-account-identity-changed',
32
+ recoveryFailure: { kind: 'identity', safeReason: 'Authenticated account changed' },
33
+ }
34
+ const body = (msg.text ?? '') + (recovery ? `\n\n${recoveryMarker(recovery.deliveryId)}` : '')
35
+ let recoveryResponse: Response | undefined
36
+ const transport: typeof fetch = recovery
37
+ ? ((async (input, init) => {
38
+ const response = await fetchImpl(input, init)
39
+ recoveryResponse = response
40
+ return response
41
+ }) as typeof fetch)
42
+ : fetchImpl
43
+ const finish = (result: SendResult): SendResult =>
44
+ result.ok || !recovery
45
+ ? result
46
+ : {
47
+ ...result,
48
+ recoveryFailure: recoveryResponse
49
+ ? recoveryHttpFailure(recoveryResponse)
50
+ : { kind: 'transient', safeReason: 'Recovery transport failed' },
51
+ }
26
52
  if (body === '') return { ok: false, error: 'message has neither text nor attachments' }
27
53
 
28
54
  const repo = parseRepo(msg.workspace)
@@ -31,31 +57,41 @@ export function createGithubOutboundCallback(deps: {
31
57
  if (target === null) return { ok: false, error: `invalid GitHub chat: ${msg.chat}` }
32
58
 
33
59
  const token = () => deps.token({ repoSlug: msg.workspace })
60
+ if (recovery && target.kind !== 'pr' && msg.thread !== undefined && msg.thread !== null)
61
+ return {
62
+ ok: false,
63
+ error: 'invalid-recovery-github-thread',
64
+ recoveryFailure: { kind: 'target', safeReason: 'Unsupported original GitHub target' },
65
+ }
34
66
 
35
67
  if (target.kind === 'discussion') {
36
- return await postDiscussionComment({
37
- ...deps,
38
- token,
39
- fetchImpl,
40
- repo,
41
- discussionNumber: target.number,
42
- body,
43
- })
68
+ return finish(
69
+ await postDiscussionComment({
70
+ ...deps,
71
+ token,
72
+ fetchImpl: transport,
73
+ repo,
74
+ discussionNumber: target.number,
75
+ body,
76
+ }),
77
+ )
44
78
  }
45
79
 
46
80
  const isPrReviewReply = target.kind === 'pr' && msg.thread !== null && msg.thread !== undefined && msg.thread !== ''
47
81
  const endpoint = isPrReviewReply
48
82
  ? `${GITHUB_API_BASE}/repos/${repo.owner}/${repo.name}/pulls/${target.number}/comments/${encodeURIComponent(msg.thread ?? '')}/replies`
49
83
  : `${GITHUB_API_BASE}/repos/${repo.owner}/${repo.name}/issues/${target.number}/comments`
50
- return await postJson(
51
- fetchImpl,
52
- await token(),
53
- endpoint,
54
- { body },
55
- {
56
- authType: deps.authType,
57
- endpointKind: isPrReviewReply ? 'pr-review-reply' : 'issue-comment',
58
- },
84
+ return finish(
85
+ await postJson(
86
+ transport,
87
+ await token(),
88
+ endpoint,
89
+ { body },
90
+ {
91
+ authType: deps.authType,
92
+ endpointKind: isPrReviewReply ? 'pr-review-reply' : 'issue-comment',
93
+ },
94
+ ),
59
95
  )
60
96
  }
61
97
  }