typeclaw 0.48.12 → 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 (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -0,0 +1,106 @@
1
+ import { z } from 'zod'
2
+
3
+ import type { RecoveryAdapterCallbacks } from '../../types'
4
+ import { recoveryMarker } from '../recovery-correlation'
5
+ import type { GithubAuthStrategy } from './auth'
6
+ import { githubJsonHeaders } from './auth-pat'
7
+
8
+ const commentSchema = z.object({
9
+ id: z.number(),
10
+ body: z.string().nullable(),
11
+ user: z.object({ id: z.number() }).nullable(),
12
+ in_reply_to_id: z.number().optional(),
13
+ })
14
+ const discussionSchema = z.object({
15
+ data: z.object({
16
+ repository: z
17
+ .object({
18
+ discussion: z
19
+ .object({
20
+ comments: z.object({
21
+ nodes: z.array(
22
+ z.object({
23
+ databaseId: z.number(),
24
+ body: z.string(),
25
+ author: z.object({ login: z.string() }).nullable(),
26
+ }),
27
+ ),
28
+ pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }),
29
+ }),
30
+ })
31
+ .nullable(),
32
+ })
33
+ .nullable(),
34
+ }),
35
+ errors: z.array(z.unknown()).optional(),
36
+ })
37
+
38
+ export function createGithubRecoveryCallbacks(
39
+ auth: GithubAuthStrategy,
40
+ fetchImpl: typeof fetch = fetch,
41
+ cachedAccountIdentity: () => string | undefined = () => undefined,
42
+ ): RecoveryAdapterCallbacks {
43
+ return {
44
+ cachedAccountIdentity,
45
+ async accountIdentity() {
46
+ return `github:${(await auth.getSelf()).id}`
47
+ },
48
+ async reconcile(record) {
49
+ const self = await auth.getSelf()
50
+ if (`github:${self.id}` !== (record.boundAccountIdentity ?? record.accountIdentity))
51
+ throw new Error('recovery-account-identity-changed')
52
+ const { workspace, chat, thread } = record.target
53
+ const match = /^(issue|pr|discussion):(\d+)$/.exec(chat)
54
+ if (!match || !/^[^/]+\/[^/]+$/.test(workspace)) throw new Error('invalid-recovery-github-target')
55
+ if (match[1] !== 'pr' && thread !== null) throw new Error('invalid-recovery-github-thread')
56
+ const headers = githubJsonHeaders(await auth.token({ repoSlug: workspace }))
57
+ const marker = recoveryMarker(record.deliveryId)
58
+ if (match[1] === 'discussion') {
59
+ const [owner, name] = workspace.split('/')
60
+ let cursor: string | null = null
61
+ const seen = new Set<string>()
62
+ do {
63
+ const response = await fetchImpl('https://api.github.com/graphql', {
64
+ method: 'POST',
65
+ headers,
66
+ body: JSON.stringify({
67
+ query:
68
+ 'query($owner:String!,$name:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$name){discussion(number:$number){comments(first:100,after:$cursor){nodes{databaseId body author{login}} pageInfo{hasNextPage endCursor}}}}}',
69
+ variables: { owner, name, number: Number(match[2]), cursor },
70
+ }),
71
+ })
72
+ if (!response.ok) throw new Error(`recovery-history-${response.status}`)
73
+ const result = discussionSchema.parse(await response.json())
74
+ if (result.errors?.length) throw new Error('recovery-history-graphql-error')
75
+ const comments = result.data.repository?.discussion?.comments
76
+ if (!comments) throw new Error('recovery-destination-unavailable')
77
+ const found = comments.nodes.find((row) => row.author?.login === self.login && row.body.includes(marker))
78
+ if (found) return { status: 'found', messageId: String(found.databaseId) }
79
+ cursor = comments.pageInfo.hasNextPage ? comments.pageInfo.endCursor : null
80
+ if (comments.pageInfo.hasNextPage && !cursor) throw new Error('recovery-history-missing-cursor')
81
+ if (cursor && seen.has(cursor)) throw new Error('recovery-history-cursor-loop')
82
+ if (cursor) seen.add(cursor)
83
+ } while (cursor)
84
+ } else {
85
+ const review = match[1] === 'pr' && !!thread
86
+ for (let page = 1; ; page++) {
87
+ const response = await fetchImpl(
88
+ `https://api.github.com/repos/${workspace}/${review ? 'pulls' : 'issues'}/${match[2]}/comments?per_page=100&page=${page}`,
89
+ { headers },
90
+ )
91
+ if (!response.ok) throw new Error(`recovery-history-${response.status}`)
92
+ const rows = z.array(commentSchema).parse(await response.json())
93
+ const found = rows.find(
94
+ (row) =>
95
+ row.user?.id === self.id &&
96
+ row.body?.includes(marker) &&
97
+ (!review || String(row.in_reply_to_id) === thread),
98
+ )
99
+ if (found) return { status: 'found', messageId: String(found.id) }
100
+ if (rows.length < 100) break
101
+ }
102
+ }
103
+ return { status: 'unknown' }
104
+ },
105
+ }
106
+ }
@@ -0,0 +1,510 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
3
+ import { dirname, join } from 'node:path'
4
+
5
+ import {
6
+ type PersistedReviewCheckLease,
7
+ REVIEW_CHECK_NAME,
8
+ type ReviewCheckFinding,
9
+ type ReviewCheckKey,
10
+ type ReviewCheckLeaseStore,
11
+ type ReviewCheckOutcome,
12
+ type ReviewCheckProgress,
13
+ type ReviewCheckPublisher,
14
+ type ReviewCheckPublishResult,
15
+ type ReviewCheckRef,
16
+ type ReviewCheckTiming,
17
+ type ReviewCheckVerdictDetails,
18
+ } from '@/channels/github-review-check'
19
+
20
+ import { describeError } from '../../describe-error'
21
+ import type { GithubAuthContext } from './auth'
22
+ import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
23
+
24
+ // After a 401/403/404 the repo is skipped for this long, so a missing
25
+ // permission costs one warning per window instead of one failed call per review.
26
+ export const REVIEW_CHECK_DENIAL_TTL_MS = 60 * 60_000
27
+
28
+ const STATUS_DESCRIPTION_MAX = 140
29
+
30
+ const GITHUB_WEB_BASE = 'https://github.com'
31
+
32
+ // Findings kept with a persisted outcome; the rest is only counted.
33
+ export const REVIEW_CHECK_MAX_FINDINGS = 20
34
+
35
+ // Progress holds the per-commit publish lock the completion needs, so a stalled
36
+ // progress request is aborted rather than left to block the verdict.
37
+ export const REVIEW_CHECK_PROGRESS_TIMEOUT_MS = 15_000
38
+ const FINDING_TITLE_MAX = 100
39
+
40
+ // The check is named after the agent's GitHub identity (an App's `slug[bot]`
41
+ // login shows as `slug`), so a PR reviewed by several agents gets one check per
42
+ // agent. Before the identity is known the generic name is used.
43
+ export function reviewCheckName(selfLogin: string | null): string {
44
+ const name = selfLogin?.replace(/\[bot\]$/i, '').trim()
45
+ return name !== undefined && name !== '' ? name : REVIEW_CHECK_NAME
46
+ }
47
+
48
+ export function createGithubReviewCheckPublisher(deps: {
49
+ token: (context?: GithubAuthContext) => Promise<string>
50
+ authType: 'pat' | 'app'
51
+ enabled: () => boolean
52
+ checkName: () => string
53
+ logger: { warn: (m: string) => void }
54
+ fetchImpl?: typeof fetch
55
+ now?: () => number
56
+ progressTimeoutMs?: number
57
+ }): ReviewCheckPublisher {
58
+ const fetchImpl = deps.fetchImpl ?? fetch
59
+ const now = deps.now ?? Date.now
60
+ const deniedUntil = new Map<string, number>()
61
+ const rateLimitedUntil = new Map<string, number>()
62
+
63
+ const isDenied = (repo: string): boolean => (deniedUntil.get(repo) ?? 0) > now()
64
+
65
+ const send = async (
66
+ key: ReviewCheckKey,
67
+ path: string,
68
+ method: string,
69
+ body: unknown,
70
+ signal?: AbortSignal,
71
+ ): Promise<SendResult> => {
72
+ if ((rateLimitedUntil.get(key.repo) ?? 0) > now()) return { kind: 'transient' }
73
+ let response: Response
74
+ try {
75
+ const token = await abortable(deps.token({ repoSlug: key.repo }), signal)
76
+ response = await fetchImpl(`${GITHUB_API_BASE}/repos/${key.repo}${path}`, {
77
+ method,
78
+ headers: githubJsonHeaders(token),
79
+ body: JSON.stringify(body),
80
+ ...(signal !== undefined ? { signal } : {}),
81
+ })
82
+ } catch (err) {
83
+ deps.logger.warn(`[github] review check ${method} ${path} failed for ${key.repo}: ${describeError(err)}`)
84
+ return { kind: 'transient' }
85
+ }
86
+ if (response.ok) return { kind: 'ok', response }
87
+ const text = await response.text().catch(() => '')
88
+ // GitHub reports primary and secondary rate limits as 403 (or 429); those
89
+ // clear on their own, so they must be retried rather than cached as denials.
90
+ if (isRateLimited(response, text)) {
91
+ const until = rateLimitResetAt(response, now())
92
+ rateLimitedUntil.set(key.repo, until)
93
+ deps.logger.warn(
94
+ `[github] review check ${method} ${path} rate-limited for ${key.repo}; retrying after ${new Date(until).toISOString()}`,
95
+ )
96
+ return { kind: 'transient' }
97
+ }
98
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
99
+ deniedUntil.set(key.repo, now() + REVIEW_CHECK_DENIAL_TTL_MS)
100
+ deps.logger.warn(
101
+ `[github] review check skipped for ${key.repo}: GitHub returned ${response.status}. ` +
102
+ `${permissionHint(deps.authType)} Reviews still post; set channels.github.review.check to false to silence this.`,
103
+ )
104
+ return { kind: 'denied' }
105
+ }
106
+ deps.logger.warn(`[github] review check ${method} ${path} failed for ${key.repo}: ${response.status} ${text}`)
107
+ return { kind: 'transient' }
108
+ }
109
+
110
+ return {
111
+ name: deps.checkName,
112
+
113
+ async start(key) {
114
+ if (!deps.enabled() || isDenied(key.repo)) return null
115
+ if (deps.authType === 'app') {
116
+ const result = await send(key, '/check-runs', 'POST', {
117
+ name: deps.checkName(),
118
+ head_sha: key.headSha,
119
+ status: 'in_progress',
120
+ started_at: new Date(now()).toISOString(),
121
+ output: renderProgress(key, { phase: 'reviewing', startedAt: now(), now: now(), activity: null }),
122
+ })
123
+ if (result.kind !== 'ok') return null
124
+ const body = (await result.response.json().catch(() => null)) as { id?: unknown } | null
125
+ return typeof body?.id === 'number' ? { mode: 'check-run', checkRunId: body.id } : null
126
+ }
127
+ const context = deps.checkName()
128
+ const result = await send(key, `/statuses/${key.headSha}`, 'POST', {
129
+ state: 'pending',
130
+ context,
131
+ description: 'TypeClaw is reviewing this commit',
132
+ })
133
+ return result.kind === 'ok' ? { mode: 'status', context } : null
134
+ },
135
+
136
+ async progress(key, ref, progress) {
137
+ if (ref.mode !== 'check-run' || !deps.enabled() || isDenied(key.repo)) return
138
+ await send(
139
+ key,
140
+ `/check-runs/${ref.checkRunId}`,
141
+ 'PATCH',
142
+ { output: renderProgress(key, progress) },
143
+ AbortSignal.timeout(deps.progressTimeoutMs ?? REVIEW_CHECK_PROGRESS_TIMEOUT_MS),
144
+ )
145
+ },
146
+
147
+ async finish(key, ref, outcome, timing) {
148
+ if (ref === null && (outcome.kind !== 'verdict' || !deps.enabled() || isDenied(key.repo))) return 'published'
149
+ const mode: ReviewCheckRef['mode'] = ref?.mode ?? (deps.authType === 'app' ? 'check-run' : 'status')
150
+ const reviewUrl = outcome.kind === 'verdict' ? reviewLink(key, outcome.details) : undefined
151
+ if (mode === 'status') {
152
+ return publishResult(
153
+ await send(key, `/statuses/${key.headSha}`, 'POST', {
154
+ state: statusState(outcome),
155
+ // A pending status is only replaced by one with the same context, so
156
+ // finish under the name it started with (leases from before
157
+ // per-agent names carry none and started as the generic name).
158
+ context: ref?.mode === 'status' ? (ref.context ?? REVIEW_CHECK_NAME) : deps.checkName(),
159
+ description: truncate(describeOutcome(outcome), STATUS_DESCRIPTION_MAX),
160
+ ...(reviewUrl !== undefined ? { target_url: reviewUrl } : {}),
161
+ }),
162
+ )
163
+ }
164
+ const completion = {
165
+ status: 'completed',
166
+ conclusion: checkRunConclusion(outcome),
167
+ completed_at: new Date(now()).toISOString(),
168
+ output: renderOutcome(key, outcome, timing),
169
+ ...(reviewUrl !== undefined ? { details_url: reviewUrl } : {}),
170
+ }
171
+ if (ref?.mode === 'check-run') {
172
+ return publishResult(await send(key, `/check-runs/${ref.checkRunId}`, 'PATCH', completion))
173
+ }
174
+ return publishResult(
175
+ await send(key, '/check-runs', 'POST', { name: deps.checkName(), head_sha: key.headSha, ...completion }),
176
+ )
177
+ },
178
+ }
179
+ }
180
+
181
+ export function reviewCheckDetails(
182
+ reviewId: number,
183
+ comments: readonly { path: string; line: number; side?: 'LEFT' | 'RIGHT'; body: string }[],
184
+ ): ReviewCheckVerdictDetails {
185
+ return {
186
+ reviewId,
187
+ findings: comments.slice(0, REVIEW_CHECK_MAX_FINDINGS).map((comment) => ({
188
+ path: comment.path,
189
+ line: comment.line,
190
+ ...(comment.side === 'LEFT' ? { side: 'LEFT' as const } : {}),
191
+ title: findingTitle(comment.body),
192
+ })),
193
+ findingCount: comments.length,
194
+ }
195
+ }
196
+
197
+ export function reviewCheckLeasePath(agentDir: string): string {
198
+ return join(agentDir, 'channels', 'github-review-checks.json')
199
+ }
200
+
201
+ export function createReviewCheckLeaseStore(agentDir: string): ReviewCheckLeaseStore {
202
+ const path = reviewCheckLeasePath(agentDir)
203
+ return {
204
+ async load() {
205
+ let raw: string
206
+ try {
207
+ raw = await readFile(path, 'utf8')
208
+ } catch (err) {
209
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []
210
+ throw err
211
+ }
212
+ const parsed = JSON.parse(raw) as { leases?: unknown }
213
+ return Array.isArray(parsed.leases) ? parsed.leases.filter(isPersistedLease) : []
214
+ },
215
+ async save(leases) {
216
+ await mkdir(dirname(path), { recursive: true })
217
+ const tmp = `${path}.tmp`
218
+ await writeFile(tmp, `${JSON.stringify({ version: 1, leases }, null, 2)}\n`)
219
+ await rename(tmp, path)
220
+ },
221
+ }
222
+ }
223
+
224
+ const DEFAULT_RATE_LIMIT_BACKOFF_MS = 60_000
225
+
226
+ function isRateLimited(response: Response, text: string): boolean {
227
+ if (response.status === 429) return true
228
+ if (response.status !== 403) return false
229
+ return (
230
+ response.headers.has('retry-after') ||
231
+ response.headers.get('x-ratelimit-remaining') === '0' ||
232
+ /rate limit/i.test(text)
233
+ )
234
+ }
235
+
236
+ function rateLimitResetAt(response: Response, now: number): number {
237
+ const retryAfter = Number(response.headers.get('retry-after'))
238
+ if (Number.isFinite(retryAfter) && retryAfter > 0) return now + retryAfter * 1000
239
+ const reset = Number(response.headers.get('x-ratelimit-reset'))
240
+ if (Number.isFinite(reset) && reset * 1000 > now) return reset * 1000
241
+ return now + DEFAULT_RATE_LIMIT_BACKOFF_MS
242
+ }
243
+
244
+ type SendResult = { kind: 'ok'; response: Response } | { kind: 'denied' } | { kind: 'transient' }
245
+
246
+ // A denial cannot be fixed by retrying, so only a transient failure keeps the
247
+ // outcome pending.
248
+ function publishResult(result: SendResult): ReviewCheckPublishResult {
249
+ return result.kind === 'transient' ? 'retry' : 'published'
250
+ }
251
+
252
+ function checkRunConclusion(outcome: ReviewCheckOutcome): 'success' | 'failure' | 'neutral' {
253
+ if (outcome.kind === 'failed') return 'failure'
254
+ if (outcome.kind === 'cancelled') return 'neutral'
255
+ if (outcome.state === 'APPROVED') return 'success'
256
+ if (outcome.state === 'CHANGES_REQUESTED') return 'failure'
257
+ return 'neutral'
258
+ }
259
+
260
+ // Commit statuses have no neutral state; a cancellation or comment-only review
261
+ // must not block a merge, so both map to success with an explicit description.
262
+ function statusState(outcome: ReviewCheckOutcome): 'success' | 'failure' {
263
+ return checkRunConclusion(outcome) === 'failure' ? 'failure' : 'success'
264
+ }
265
+
266
+ function describeOutcome(outcome: ReviewCheckOutcome): string {
267
+ if (outcome.kind === 'failed') return `Review failed: ${outcome.reason}`
268
+ if (outcome.kind === 'cancelled') return `Not reviewed: ${outcome.reason}`
269
+ if (outcome.state === 'APPROVED') return 'TypeClaw approved this commit'
270
+ if (outcome.state === 'CHANGES_REQUESTED') return 'TypeClaw requested changes'
271
+ return 'TypeClaw left review comments'
272
+ }
273
+
274
+ type CheckOutput = { title: string; summary: string }
275
+
276
+ function renderProgress(key: ReviewCheckKey, progress: ReviewCheckProgress): CheckOutput {
277
+ const elapsedMs = progress.now - progress.startedAt
278
+ const elapsed = elapsedMs >= 1000 ? ` (${formatDuration(elapsedMs)})` : ''
279
+ const commit = shortSha(key.headSha)
280
+ if (progress.phase === 'posting') {
281
+ return {
282
+ title: `Posting review…${elapsed}`,
283
+ summary: `The review of ${commit} is written and is being posted to the pull request.`,
284
+ }
285
+ }
286
+ const activity = progress.activity
287
+ if (activity === null || !activity.started) {
288
+ const intro =
289
+ elapsedMs >= 1000
290
+ ? `TypeClaw started reviewing ${commit} **${formatDuration(elapsedMs)} ago**.`
291
+ : `TypeClaw started reviewing ${commit}.`
292
+ return { title: `Reviewing…${elapsed}`, summary: `${intro}\n\n⏳ Reading the pull request` }
293
+ }
294
+ const kind = progress.reviewKind === 're-review' ? ' · re-review after new commits' : ''
295
+ const files = activity.filesRead > 0 ? ` (${plural(activity.filesRead, 'file')})` : ''
296
+ const steps: [string, string][] = [
297
+ ['✅', 'Read the pull request'],
298
+ [stepMark(activity.current === 'reading', activity.filesRead > 0), `Read the code${files}`],
299
+ [stepMark(activity.current === 'commands', activity.commandsRun > 0), 'Running commands (tests, builds)'],
300
+ [activity.current === 'writing' ? '⏳' : '⬜', 'Write up findings'],
301
+ ['⬜', 'Post review'],
302
+ ]
303
+ const lines = [
304
+ `TypeClaw is reviewing ${commit}${kind}`,
305
+ '',
306
+ '| | Step |',
307
+ '|---|---|',
308
+ ...steps.map(([mark, label]) => `| ${mark} | ${label} |`),
309
+ ]
310
+ if (activity.lastActivityAt !== null) {
311
+ lines.push('', `Last activity: ${formatAgo(progress.now - activity.lastActivityAt)}`)
312
+ }
313
+ return { title: `Reviewing…${elapsed}`, summary: lines.join('\n') }
314
+ }
315
+
316
+ function stepMark(active: boolean, done: boolean): string {
317
+ if (active) return '⏳'
318
+ return done ? '✅' : '⬜'
319
+ }
320
+
321
+ function renderOutcome(key: ReviewCheckKey, outcome: ReviewCheckOutcome, timing?: ReviewCheckTiming): CheckOutput {
322
+ const commit = shortSha(key.headSha)
323
+ const durationMs = timing !== undefined && timing.tracked ? timing.decidedAt - timing.startedAt : 0
324
+ const after = durationMs >= 1000 ? ` after a ${formatDuration(durationMs)} review` : ''
325
+ if (outcome.kind === 'failed') {
326
+ const stopped = durationMs >= 1000 ? ` stopped after ${formatDuration(durationMs)}` : ' stopped'
327
+ return {
328
+ title: "Review didn't finish",
329
+ summary: [
330
+ `The review of ${commit}${stopped} without posting a result.`,
331
+ '',
332
+ `Reason: ${sentence(outcome.reason)}`,
333
+ 'To retry, re-request a review from TypeClaw.',
334
+ ].join('\n'),
335
+ }
336
+ }
337
+ if (outcome.kind === 'cancelled') {
338
+ return {
339
+ title: 'Review skipped',
340
+ summary: [
341
+ `TypeClaw stopped reviewing ${commit} before posting a result.`,
342
+ '',
343
+ `Reason: ${sentence(outcome.reason)}`,
344
+ 'To review it later, re-request a review from TypeClaw.',
345
+ ].join('\n'),
346
+ }
347
+ }
348
+ const findings = outcome.details?.findings ?? []
349
+ const count = Math.max(outcome.details?.findingCount ?? 0, findings.length)
350
+ const reviewUrl = reviewLink(key, outcome.details)
351
+ const sections: string[] = []
352
+ let title: string
353
+ if (outcome.state === 'APPROVED') {
354
+ title = 'Approved'
355
+ sections.push(`TypeClaw approved ${commit}${after}.`)
356
+ if (count === 0) sections.push('No blocking issues found.')
357
+ } else if (outcome.state === 'CHANGES_REQUESTED') {
358
+ title = count > 0 ? `Changes requested · ${plural(count, 'finding')}` : 'Changes requested'
359
+ sections.push(`TypeClaw requested changes on ${commit}${after}.`)
360
+ } else {
361
+ title = count > 0 ? `Reviewed with comments · ${plural(count, 'note')}` : 'Reviewed with comments'
362
+ sections.push(`TypeClaw left non-blocking comments on ${commit}${after}.`)
363
+ }
364
+ if (findings.length > 0) {
365
+ const header = outcome.state === 'CHANGES_REQUESTED' ? 'Finding' : 'Note'
366
+ const rows = findings.map((finding) => `| ${findingLocation(key, finding)} | ${tableCell(finding.title)} |`)
367
+ const more = count > findings.length ? [``, `…and ${count - findings.length} more in the review.`] : []
368
+ sections.push([`| File | ${header} |`, '|---|---|', ...rows, ...more].join('\n'))
369
+ }
370
+ if (reviewUrl !== undefined) {
371
+ sections.push(`[${findings.length > 0 ? 'View the full review' : 'View the review'} →](${reviewUrl})`)
372
+ }
373
+ return { title, summary: sections.join('\n\n') }
374
+ }
375
+
376
+ function reviewLink(key: ReviewCheckKey, details: ReviewCheckVerdictDetails | undefined): string | undefined {
377
+ if (details?.reviewId === undefined) return undefined
378
+ return `${pullUrl(key)}#pullrequestreview-${details.reviewId}`
379
+ }
380
+
381
+ function pullUrl(key: ReviewCheckKey): string {
382
+ return `${GITHUB_WEB_BASE}/${key.repo}/pull/${key.pullRequest}`
383
+ }
384
+
385
+ // GitHub anchors a file in the PR diff by the SHA-256 of its path.
386
+ function findingLocation(key: ReviewCheckKey, finding: ReviewCheckFinding): string {
387
+ const anchor = createHash('sha256').update(finding.path).digest('hex')
388
+ const label = `${finding.path}:${finding.line}`.replaceAll('`', '')
389
+ const side = finding.side === 'LEFT' ? 'L' : 'R'
390
+ return `[\`${label}\`](${pullUrl(key)}/files#diff-${anchor}${side}${finding.line})`
391
+ }
392
+
393
+ // The first meaningful line of a review comment, stripped of leading Markdown
394
+ // markers so it reads as a one-line title.
395
+ function findingTitle(body: string): string {
396
+ const line =
397
+ body
398
+ .split('\n')
399
+ .map((l) => l.trim())
400
+ .find((l) => l !== '' && !l.startsWith('```')) ?? ''
401
+ const stripped = line
402
+ .replace(/^(?:(?:#+|>|[-+*](?=\s))\s*)+/, '')
403
+ .replace(/^(\*\*|__)(.+?)\1/, '$2')
404
+ .trim()
405
+ return truncate(stripped === '' ? 'See the review comment' : stripped, FINDING_TITLE_MAX)
406
+ }
407
+
408
+ function abortable<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
409
+ if (signal === undefined) return promise
410
+ signal.throwIfAborted()
411
+ return new Promise<T>((resolve, reject) => {
412
+ const onAbort = () => reject(signal.reason)
413
+ signal.addEventListener('abort', onAbort, { once: true })
414
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort))
415
+ })
416
+ }
417
+
418
+ function sentence(text: string): string {
419
+ const trimmed = text.trim()
420
+ return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`
421
+ }
422
+
423
+ function tableCell(text: string): string {
424
+ return text.replaceAll('|', '\\|').replace(/\s+/g, ' ')
425
+ }
426
+
427
+ function shortSha(sha: string): string {
428
+ return `\`${sha.slice(0, 7)}\``
429
+ }
430
+
431
+ function plural(count: number, noun: string): string {
432
+ return `${count} ${noun}${count === 1 ? '' : 's'}`
433
+ }
434
+
435
+ function formatDuration(ms: number): string {
436
+ const totalSec = Math.floor(ms / 1000)
437
+ const min = Math.floor(totalSec / 60)
438
+ const sec = totalSec % 60
439
+ if (min === 0) return `${sec}s`
440
+ return `${min}m ${String(sec).padStart(2, '0')}s`
441
+ }
442
+
443
+ function formatAgo(ms: number): string {
444
+ const sec = Math.max(0, Math.floor(ms / 1000))
445
+ if (sec < 60) return sec === 1 ? '1 second ago' : `${sec} seconds ago`
446
+ const min = Math.floor(sec / 60)
447
+ return min === 1 ? '1 minute ago' : `${min} minutes ago`
448
+ }
449
+
450
+ function permissionHint(authType: 'pat' | 'app'): string {
451
+ return authType === 'app'
452
+ ? 'Grant the GitHub App "Checks: Read and write" permission.'
453
+ : 'The token needs commit status write access (classic PAT `repo:status`, or fine-grained "Commit statuses: Read and write").'
454
+ }
455
+
456
+ function truncate(text: string, max: number): string {
457
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`
458
+ }
459
+
460
+ function isPersistedLease(value: unknown): value is PersistedReviewCheckLease {
461
+ if (typeof value !== 'object' || value === null) return false
462
+ const lease = value as Record<string, unknown>
463
+ const ref = lease.ref as Record<string, unknown> | undefined
464
+ return (
465
+ typeof lease.repo === 'string' &&
466
+ typeof lease.pullRequest === 'number' &&
467
+ typeof lease.headSha === 'string' &&
468
+ typeof lease.startedAt === 'number' &&
469
+ (lease.outcome === undefined || isOutcome(lease.outcome)) &&
470
+ (lease.outcomeAt === undefined || typeof lease.outcomeAt === 'number') &&
471
+ (lease.tracked === undefined || typeof lease.tracked === 'boolean') &&
472
+ (ref === null
473
+ ? lease.outcome !== undefined
474
+ : typeof ref === 'object' &&
475
+ ((ref.mode === 'status' && (ref.context === undefined || typeof ref.context === 'string')) ||
476
+ (ref.mode === 'check-run' && typeof ref.checkRunId === 'number')))
477
+ )
478
+ }
479
+
480
+ function isVerdictDetails(value: unknown): boolean {
481
+ if (typeof value !== 'object' || value === null) return false
482
+ const details = value as Record<string, unknown>
483
+ return (
484
+ (details.reviewId === undefined || typeof details.reviewId === 'number') &&
485
+ (details.findingCount === undefined || typeof details.findingCount === 'number') &&
486
+ (details.findings === undefined ||
487
+ (Array.isArray(details.findings) &&
488
+ details.findings.every(
489
+ (f: unknown) =>
490
+ typeof f === 'object' &&
491
+ f !== null &&
492
+ typeof (f as Record<string, unknown>).path === 'string' &&
493
+ typeof (f as Record<string, unknown>).line === 'number' &&
494
+ [undefined, 'LEFT', 'RIGHT'].includes((f as Record<string, unknown>).side as string | undefined) &&
495
+ typeof (f as Record<string, unknown>).title === 'string',
496
+ )))
497
+ )
498
+ }
499
+
500
+ function isOutcome(value: unknown): boolean {
501
+ if (typeof value !== 'object' || value === null) return false
502
+ const outcome = value as Record<string, unknown>
503
+ if (outcome.kind === 'verdict') {
504
+ return (
505
+ (outcome.state === 'APPROVED' || outcome.state === 'CHANGES_REQUESTED' || outcome.state === 'COMMENTED') &&
506
+ (outcome.details === undefined || isVerdictDetails(outcome.details))
507
+ )
508
+ }
509
+ return (outcome.kind === 'failed' || outcome.kind === 'cancelled') && typeof outcome.reason === 'string'
510
+ }