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
@@ -1,7 +1,13 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
- import { recordReview, recordReviewOutput, type ReviewVerdict } from '@/channels/github-review-turn-ledger'
4
+ import { githubReviewChecks } from '@/channels/github-review-check'
5
+ import {
6
+ recordReview,
7
+ recordReviewOutput,
8
+ type ReviewResultCoverage,
9
+ type ReviewVerdict,
10
+ } from '@/channels/github-review-turn-ledger'
5
11
  import { createSharedReviewVerdictGuard, type ReviewVerdictGuard } from '@/channels/github-review-verdict-coordinator'
6
12
  import type { ChannelRouter } from '@/channels/router'
7
13
  import type { ReviewFinding, SubmitReviewRequest } from '@/channels/types'
@@ -53,6 +59,13 @@ export function createPostGithubReviewTool(options: {
53
59
  { minItems: 1 },
54
60
  ),
55
61
  ),
62
+ head_sha: Type.Optional(
63
+ Type.String({
64
+ pattern: '^[0-9a-fA-F]{40}$',
65
+ description:
66
+ 'Full SHA of the commit your review covers. When set, the review is only posted if the PR head is still this commit.',
67
+ }),
68
+ ),
56
69
  }),
57
70
  async execute(toolCallId, params) {
58
71
  if (origin.adapter !== 'github') return denied(logger, 'post_github_review is only supported on github sessions.')
@@ -68,6 +81,7 @@ export function createPostGithubReviewTool(options: {
68
81
  verdict,
69
82
  ...(origin.githubReviewRound !== undefined ? { round: origin.githubReviewRound } : {}),
70
83
  thread: origin.thread,
84
+ ...(params.head_sha !== undefined ? { reviewedHeadSha: params.head_sha } : {}),
71
85
  retainDuplicateLease: params.event === 'REQUEST_CHANGES',
72
86
  })
73
87
  if (blocked !== null) {
@@ -86,6 +100,7 @@ export function createPostGithubReviewTool(options: {
86
100
  body: params.body,
87
101
  comments: (params.comments ?? []).map(toReviewFinding),
88
102
  logger,
103
+ ...(params.head_sha !== undefined ? { reviewedHeadSha: params.head_sha } : {}),
89
104
  })
90
105
  fallbackLanded = fallback.landed
91
106
  return fallback.result
@@ -112,10 +127,18 @@ export function createPostGithubReviewTool(options: {
112
127
  event: params.event,
113
128
  body: params.body,
114
129
  comments: (params.comments ?? []).map(toReviewFinding),
130
+ ...(params.head_sha !== undefined ? { expectedHeadSha: params.head_sha } : {}),
115
131
  }
116
132
  let releaseAsLanded = false
117
133
  try {
118
- const result = await router.submitReview(request)
134
+ const coverage = await captureCoverage(router, sessionId)
135
+ const result = await router.submitReview({
136
+ ...request,
137
+ sourceSessionId: sessionId,
138
+ ...(coverage.expectedAccountIdentity !== undefined
139
+ ? { expectedAccountIdentity: coverage.expectedAccountIdentity }
140
+ : {}),
141
+ })
119
142
  if (!result.ok) {
120
143
  // A POST whose verification failed may already have landed. Keep the
121
144
  // short conservative shield, but never credit an unverified ledger.
@@ -127,7 +150,14 @@ export function createPostGithubReviewTool(options: {
127
150
  if (effective === null)
128
151
  return denied(logger, `GitHub returned an unknown verified review state: ${result.state}`)
129
152
  releaseAsLanded = verdict !== null && effective === verdict
130
- creditVerifiedReview({ sessionId, workspace: origin.workspace, prNumber, effective })
153
+ await creditVerifiedReview({
154
+ sessionId,
155
+ workspace: origin.workspace,
156
+ prNumber,
157
+ effective,
158
+ ...coverage,
159
+ ...(result.commitSha !== undefined ? { commitSha: result.commitSha } : {}),
160
+ })
131
161
 
132
162
  const receipt = renderReceipt(
133
163
  result.reviewId,
@@ -163,7 +193,9 @@ async function postDuplicateRequestChangesComment(args: {
163
193
  body: string
164
194
  comments: readonly ReviewFinding[]
165
195
  logger: ChannelToolLogger
196
+ reviewedHeadSha?: string
166
197
  }) {
198
+ const coverage = await captureCoverage(args.router, args.sessionId)
167
199
  const result = await args.router.send(
168
200
  {
169
201
  adapter: 'github',
@@ -172,16 +204,30 @@ async function postDuplicateRequestChangesComment(args: {
172
204
  thread: null,
173
205
  text: renderFallbackComment(args.body, args.comments),
174
206
  },
175
- { accountingTarget: args.origin },
207
+ {
208
+ accountingTarget: args.origin,
209
+ ...(coverage.expectedAccountIdentity !== undefined
210
+ ? { expectedAccountIdentity: coverage.expectedAccountIdentity }
211
+ : {}),
212
+ },
176
213
  )
177
214
  if (!result.ok) return { landed: false, result: denied(args.logger, result.error, result.code) }
178
215
 
179
- recordReviewOutput({
216
+ await recordReviewOutput({
180
217
  sessionId: args.sessionId,
181
218
  workspace: args.origin.workspace,
182
219
  prNumber: args.prNumber,
183
220
  state: 'COMMENT',
221
+ ...coverage,
184
222
  })
223
+ // The comment republishes a verdict GitHub already holds as a standing
224
+ // CHANGES_REQUESTED, so the review check completes with that verdict.
225
+ void (args.reviewedHeadSha !== undefined
226
+ ? githubReviewChecks.reviewPosted(
227
+ { repo: args.origin.workspace, pullRequest: args.prNumber, headSha: args.reviewedHeadSha },
228
+ 'CHANGES_REQUESTED',
229
+ )
230
+ : githubReviewChecks.completePostingReviews(args.origin.workspace, args.prNumber, 'CHANGES_REQUESTED'))
185
231
 
186
232
  const details: PostGithubReviewDetails = {
187
233
  ok: true,
@@ -249,31 +295,47 @@ function effectiveReviewState(state: string): ReviewVerdict | 'COMMENT' | null {
249
295
  return null
250
296
  }
251
297
 
252
- function creditVerifiedReview(args: {
253
- sessionId: string
254
- workspace: string
255
- prNumber: number
256
- effective: ReviewVerdict | 'COMMENT'
257
- }): void {
298
+ async function creditVerifiedReview(
299
+ args: {
300
+ sessionId: string
301
+ workspace: string
302
+ prNumber: number
303
+ effective: ReviewVerdict | 'COMMENT'
304
+ commitSha?: string
305
+ } & ReviewResultCoverage,
306
+ ): Promise<void> {
258
307
  if (args.effective === 'COMMENT') {
259
- recordReviewOutput({
308
+ await recordReviewOutput({
260
309
  sessionId: args.sessionId,
261
310
  workspace: args.workspace,
262
311
  prNumber: args.prNumber,
263
312
  state: 'COMMENT',
313
+ ...(args.inboundCoverage !== undefined ? { inboundCoverage: args.inboundCoverage } : {}),
314
+ ...(args.backgroundCoverage !== undefined ? { backgroundCoverage: args.backgroundCoverage } : {}),
264
315
  })
265
316
  return
266
317
  }
267
- // recordReview also emits the review-output observer signal for decisive
268
- // states, keeping verdict and output credit atomic.
269
- recordReview({
318
+ // recordReview retains the verdict before awaiting the output owner's settlement.
319
+ await recordReview({
270
320
  sessionId: args.sessionId,
271
321
  workspace: args.workspace,
272
322
  prNumber: args.prNumber,
273
323
  verdict: args.effective,
324
+ ...(args.inboundCoverage !== undefined ? { inboundCoverage: args.inboundCoverage } : {}),
325
+ ...(args.backgroundCoverage !== undefined ? { backgroundCoverage: args.backgroundCoverage } : {}),
326
+ ...(args.commitSha !== undefined ? { commitSha: args.commitSha } : {}),
274
327
  })
275
328
  }
276
329
 
330
+ async function captureCoverage(router: ChannelRouter, sessionId: string): Promise<ReviewResultCoverage> {
331
+ const expectedAccountIdentity = await router.captureTurnAccountIdentity?.(sessionId, 'github')
332
+ return {
333
+ inboundCoverage: (await router.captureInboundResultCoverage?.(sessionId)) ?? [],
334
+ backgroundCoverage: (await router.captureBackgroundResultCoverage?.(sessionId)) ?? [],
335
+ ...(expectedAccountIdentity !== undefined ? { expectedAccountIdentity } : {}),
336
+ }
337
+ }
338
+
277
339
  function denied(logger: ChannelToolLogger, error: string, code?: string) {
278
340
  logger.warn(formatChannelToolFailure('post_github_review', error))
279
341
  const details: PostGithubReviewDetails = { ok: false, error, ...(code !== undefined ? { code } : {}) }
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { requestContainerRestart } from '@/agent/restart'
5
5
  import type { RestartHandoffOrigin } from '@/agent/restart-handoff'
@@ -1,12 +1,12 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { ChannelRouter } from '@/channels/router'
5
5
 
6
6
  import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
7
7
 
8
8
  export type CreateSkipResponseToolOptions = {
9
- router: ChannelRouter
9
+ router: Pick<ChannelRouter, 'markTurnSkipped'>
10
10
  // The channel session's id, used to locate the right LiveSession in the
11
11
  // router and stamp the skip flag with its current turnSeq. Mirrors how
12
12
  // `injectSubagentCompletionReminder` addresses live sessions by their
@@ -89,7 +89,7 @@ export function createSkipResponseTool({
89
89
  }
90
90
  }
91
91
 
92
- const result = router.markTurnSkipped({ parentSessionId: sessionId, reason })
92
+ const result = await router.markTurnSkipped({ parentSessionId: sessionId, reason })
93
93
  if (result.kind === 'recorded-after-send') {
94
94
  // Reply-first skip: an ack already landed; this just ends the turn
95
95
  // quietly. Not suppressed (the reply stands) and not an error (erroring
@@ -1,13 +1,16 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
 
3
- import { Type } from '@mariozechner/pi-ai'
4
- import { defineTool } from '@mariozechner/pi-coding-agent'
3
+ import { Type } from '@earendil-works/pi-ai'
4
+ import { defineTool } from '@earendil-works/pi-coding-agent'
5
5
 
6
6
  import { githubReviewerWorkKey } from '@/channels/github-repo'
7
+ import { githubReviewChecks, type ReviewerSettlement } from '@/channels/github-review-check'
8
+ import type { ChannelRouter } from '@/channels/router'
7
9
  import type { PermissionService } from '@/permissions'
8
10
  import type { Stream } from '@/stream'
9
11
 
10
12
  import { type LiveSubagentRegistry, type SubagentCompletion } from '../live-subagents'
13
+ import { attachReviewerActivityCapture } from '../reviewer-activity'
11
14
  import { MAX_SUBAGENT_DEPTH, type SessionOrigin, subagentDepth } from '../session-origin'
12
15
  import {
13
16
  type CreateSessionForSubagent,
@@ -53,6 +56,12 @@ export type CreateSpawnSubagentToolOptions = {
53
56
  agentDir: string
54
57
  parentSessionId: string
55
58
  getOrigin: () => SessionOrigin | undefined
59
+ getSessionFile?: () => string | undefined
60
+ router?: Pick<ChannelRouter, 'acceptBackgroundResponse' | 'suppressUnstartedBackgroundResponse'>
61
+ getAccountIdentity?: (
62
+ adapter: NonNullable<Extract<SessionOrigin, { kind: 'channel' }>['adapter']>,
63
+ workspace?: string,
64
+ ) => Promise<string | undefined>
56
65
  permissions?: PermissionService
57
66
  stream?: Stream
58
67
  generateTaskId?: () => string
@@ -138,7 +147,7 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
138
147
  ),
139
148
  }),
140
149
 
141
- async execute(_toolCallId, params): Promise<ToolReturn> {
150
+ async execute(_toolCallId, params, signal): Promise<ToolReturn> {
142
151
  const origin = getOrigin()
143
152
  const subagent = lookupPublicSubagent(registry, params.subagent_type)
144
153
  if (subagent === null) {
@@ -159,7 +168,7 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
159
168
  origin.thread !== origin.githubReviewRound.carrierThread
160
169
  ) {
161
170
  return errorResult(
162
- "reviewer spawn denied: another session of this PR is the designated carrier for this review round and will post the review; close out only this session's thread.",
171
+ "reviewer spawn denied: another session of this PR is the designated carrier for this review round and will post the review. Do not reply now: call `skip_response`. Once the verdict lands, close out only this session's thread with the technical outcome; never mention sessions, carriers, or review rounds on the PR.",
163
172
  )
164
173
  }
165
174
  // Fail closed past the chain-length ceiling. The tool is present on
@@ -227,6 +236,70 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
227
236
  const startedAt = now()
228
237
  const spawnedByRole = permissions?.resolveRole(origin)
229
238
  let capturedFinalMessage: string | undefined
239
+ const channelKey =
240
+ origin?.kind === 'channel'
241
+ ? { adapter: origin.adapter, workspace: origin.workspace, chat: origin.chat, thread: origin.thread }
242
+ : undefined
243
+ let backgroundResponse: { obligationId: string; generation: number } | undefined
244
+ if (background && origin?.kind === 'channel') {
245
+ if (options.router === undefined) {
246
+ if (pendingWorkKeyRegistration !== undefined) {
247
+ liveRegistry.abandonWorkKeyRegistration(pendingWorkKeyRegistration)
248
+ }
249
+ releaseCoalesceKey()
250
+ return errorResult('failed to persist background response: channel router unavailable')
251
+ }
252
+ try {
253
+ const { parentChat, lastInboundAuthorId } = origin
254
+ let parentSessionFile: string | undefined
255
+ try {
256
+ parentSessionFile = options.getSessionFile?.()
257
+ } catch {
258
+ // Recovery notices do not need the parent transcript to launch work.
259
+ }
260
+ let accountIdentity: string | undefined
261
+ try {
262
+ accountIdentity = await options.getAccountIdentity?.(origin.adapter, origin.workspace)
263
+ } catch {
264
+ // Recovery identity must not add a prerequisite to healthy launches.
265
+ }
266
+ backgroundResponse = await options.router.acceptBackgroundResponse({
267
+ parentSessionId,
268
+ parentSessionFile,
269
+ key: channelKey!,
270
+ taskId,
271
+ subagentName,
272
+ startedAt,
273
+ accountIdentity: accountIdentity ?? 'unbound-legacy',
274
+ ...(parentChat !== undefined ? { parentChat } : {}),
275
+ ...(lastInboundAuthorId !== undefined ? { triggeringAuthorId: lastInboundAuthorId } : {}),
276
+ })
277
+ } catch (error) {
278
+ if (pendingWorkKeyRegistration !== undefined) {
279
+ liveRegistry.abandonWorkKeyRegistration(pendingWorkKeyRegistration)
280
+ }
281
+ releaseCoalesceKey()
282
+ return errorResult(
283
+ `failed to persist background response: ${error instanceof Error ? error.message : String(error)}`,
284
+ )
285
+ }
286
+ // An aborted parent must not launch work after the durability await.
287
+ if (signal?.aborted) {
288
+ try {
289
+ await options.router.suppressUnstartedBackgroundResponse(
290
+ backgroundResponse,
291
+ 'background launch cancelled before execution',
292
+ )
293
+ } finally {
294
+ if (pendingWorkKeyRegistration !== undefined) {
295
+ liveRegistry.abandonWorkKeyRegistration(pendingWorkKeyRegistration)
296
+ }
297
+ releaseCoalesceKey()
298
+ }
299
+ return errorResult('background launch cancelled before execution')
300
+ }
301
+ }
302
+ let detachReviewerActivity: (() => void) | undefined
230
303
  const { handle, completion } = startSubagent(subagentName, {
231
304
  registry,
232
305
  createSessionForSubagent,
@@ -241,6 +314,15 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
241
314
  capturedFinalMessage = message
242
315
  liveRegistry.recordCapturedFinalMessageIfRunning(taskId, message)
243
316
  },
317
+ ...(params.review_identity !== undefined
318
+ ? {
319
+ onSession: ({ session }) => {
320
+ detachReviewerActivity = attachReviewerActivityCapture(session, (activity) =>
321
+ githubReviewChecks.reportActivity(taskId, activity),
322
+ )
323
+ },
324
+ }
325
+ : {}),
244
326
  })
245
327
 
246
328
  let resolvedHandle: { taskId: string; sessionId: string | undefined; abort: () => Promise<void> } | undefined
@@ -255,6 +337,8 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
255
337
  return errorResult(`failed to spawn ${subagentName}: ${message}`)
256
338
  }
257
339
 
340
+ // The latest abort attempt, resolving to whether the abort was accepted.
341
+ let abortAttempt: Promise<boolean> | undefined
258
342
  const live = {
259
343
  taskId,
260
344
  sessionId: resolvedHandle.sessionId ?? '<pending>',
@@ -268,13 +352,42 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
268
352
  ...(workKey !== undefined ? { workKey } : {}),
269
353
  startedAt,
270
354
  status: 'running' as const,
271
- abort: resolvedHandle.abort,
355
+ // Every cancel path (subagent_cancel, draft/work-key cancellation) goes
356
+ // through this handle, which is how the review check tells an accepted
357
+ // cancellation apart from a reviewer failure. An accepted abort settles
358
+ // the check at once: the reviewer's completion may stay wedged after it.
359
+ abort: async () => {
360
+ const attempt = resolvedHandle.abort()
361
+ abortAttempt = attempt.then(
362
+ () => true,
363
+ () => false,
364
+ )
365
+ await attempt
366
+ void githubReviewChecks.reviewerSettled(taskId, REVIEW_CANCELLED)
367
+ },
272
368
  releaseCoalesceKey,
273
369
  }
274
- const registered =
275
- pendingWorkKeyRegistration === undefined
276
- ? (liveRegistry.register(live), true)
277
- : liveRegistry.registerIfWorkKeyActive(live, pendingWorkKeyRegistration)
370
+ let registered: boolean
371
+ try {
372
+ registered =
373
+ pendingWorkKeyRegistration === undefined
374
+ ? (liveRegistry.register(live), true)
375
+ : liveRegistry.registerIfWorkKeyActive(live, pendingWorkKeyRegistration)
376
+ } catch (error) {
377
+ if (pendingWorkKeyRegistration !== undefined) {
378
+ liveRegistry.abandonWorkKeyRegistration(pendingWorkKeyRegistration)
379
+ }
380
+ try {
381
+ await resolvedHandle.abort()
382
+ } catch {
383
+ // Execution may already have started. Its response remains owed.
384
+ }
385
+ void completion.then(releaseCoalesceKey)
386
+ releaseCoalesceKey()
387
+ return errorResult(
388
+ `failed to register ${subagentName}: ${error instanceof Error ? error.message : String(error)}`,
389
+ )
390
+ }
278
391
  let delayedCancellationError: string | undefined
279
392
  if (!registered) {
280
393
  void completion.then(releaseCoalesceKey)
@@ -284,7 +397,14 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
284
397
  const message = err instanceof Error ? err.message : String(err)
285
398
  // The child is still live. Register it so later cancellation, status
286
399
  // inspection, and completion settlement can still reach it.
287
- liveRegistry.register(live)
400
+ try {
401
+ liveRegistry.register(live)
402
+ } catch (registrationError) {
403
+ releaseCoalesceKey()
404
+ return errorResult(
405
+ `failed to register ${subagentName} after cancellation failed: ${registrationError instanceof Error ? registrationError.message : String(registrationError)}`,
406
+ )
407
+ }
288
408
  delayedCancellationError = `reviewer cancellation failed before registration: ${message}`
289
409
  }
290
410
  if (delayedCancellationError === undefined) {
@@ -296,12 +416,17 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
296
416
  liveRegistry.recordCapturedFinalMessageIfRunning(taskId, capturedFinalMessage)
297
417
  }
298
418
 
299
- const channelKey =
300
- origin?.kind === 'channel'
301
- ? { adapter: origin.adapter, workspace: origin.workspace, chat: origin.chat, thread: origin.thread }
302
- : undefined
419
+ const reviewIdentity = delayedCancellationError === undefined ? params.review_identity : undefined
420
+ if (reviewIdentity !== undefined) {
421
+ void githubReviewChecks.beginReview(
422
+ { repo: reviewIdentity.repo, pullRequest: reviewIdentity.pull_request, headSha: reviewIdentity.head_sha },
423
+ taskId,
424
+ { reviewKind: reviewIdentity.review_kind },
425
+ )
426
+ }
303
427
 
304
428
  void completion.then((c) => {
429
+ detachReviewerActivity?.()
305
430
  releaseCoalesceKey()
306
431
  const durationMs = now() - startedAt
307
432
  // First-writer-wins: if the parent drain already settled this child by
@@ -309,6 +434,17 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
309
434
  // broadcast so exactly one canonical completed-event is emitted (the
310
435
  // winner's).
311
436
  const won = liveRegistry.recordCompletionIfRunning(taskId, completionToFinalShape(c, durationMs))
437
+ if (reviewIdentity !== undefined) {
438
+ // Classify only once an in-flight abort's result is known: aborting
439
+ // can resolve the completion before the abort itself settles.
440
+ void (async () => {
441
+ const cancelAccepted = abortAttempt !== undefined && (await abortAttempt)
442
+ await githubReviewChecks.reviewerSettled(
443
+ taskId,
444
+ reviewerSettlement(c, won, cancelAccepted, liveRegistry, taskId),
445
+ )
446
+ })()
447
+ }
312
448
  if (!won || !stream || !background) return
313
449
  const hasRecoverableOutput = !c.ok && c.finalMessage !== undefined
314
450
  stream.publish({
@@ -490,6 +626,21 @@ function completionToFinalShape(
490
626
  }
491
627
  }
492
628
 
629
+ const REVIEW_CANCELLED: ReviewerSettlement = { kind: 'cancelled', reason: 'the review was cancelled' }
630
+
631
+ function reviewerSettlement(
632
+ c: { ok: true } | { ok: false; error: string },
633
+ won: boolean,
634
+ cancelAccepted: boolean,
635
+ liveRegistry: LiveSubagentRegistry,
636
+ taskId: string,
637
+ ): ReviewerSettlement {
638
+ if (cancelAccepted) return REVIEW_CANCELLED
639
+ const recordedError = liveRegistry.get(taskId)?.completion?.error
640
+ if (won && c.ok) return { kind: 'ok' }
641
+ return { kind: 'failed', reason: c.ok ? 'the reviewer did not finish in time' : (recordedError ?? c.error) }
642
+ }
643
+
493
644
  type ToolReturn = {
494
645
  content: { type: 'text'; text: string }[]
495
646
  details: SpawnSubagentToolDetails
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { formatLocalDateTime } from '@/shared'
5
5
  import type { ScanFilter, Stream, StreamMessage, TargetFilter } from '@/stream'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { PermissionService } from '@/permissions'
5
5
 
@@ -1,6 +1,7 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
+ import type { ChannelRouter } from '@/channels/router'
4
5
  import type { PermissionService } from '@/permissions'
5
6
 
6
7
  import type { LiveSubagentRegistry, StatusSnapshot, SubagentProgressEvent } from '../live-subagents'
@@ -49,6 +50,7 @@ export type CreateSubagentOutputToolOptions = {
49
50
  getOrigin: () => SessionOrigin | undefined
50
51
  permissions?: PermissionService
51
52
  callerSessionId?: string
53
+ router?: Pick<ChannelRouter, 'attachBackgroundResultCoverage'>
52
54
  now?: () => number
53
55
  }
54
56
 
@@ -91,6 +93,12 @@ export function createSubagentOutputTool(options: CreateSubagentOutputToolOption
91
93
  if (snap === undefined) {
92
94
  return errorResult(`Unknown task_id: ${params.task_id}.`)
93
95
  }
96
+ if (snap.status !== 'running' && callerSessionId !== undefined) {
97
+ await options.router?.attachBackgroundResultCoverage({
98
+ parentSessionId: callerSessionId,
99
+ taskId: snap.taskId,
100
+ })
101
+ }
94
102
  return renderSnapshot(snap)
95
103
  },
96
104
  })
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { SessionOrigin } from '@/agent/session-origin'
5
5
  import { resolveTodoScope, type TodoScope } from '@/agent/todo/scope'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { extractAdaptiveHtml, validateAdaptiveHtmlComplexity } from './adaptive-html'
5
5
  import { fetchWithLimits, normalizeUrl, parseMimeType, WebFetchError } from './fetch'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { CurlImpersonateError, isCurlExitTimeout } from './curl-impersonate'
5
5
  import { ddgSearch, DdgCaptchaError, type DdgResult } from './ddg'
@@ -38,13 +38,14 @@ If a new prompt arrives while the runner is in flight, the runner finishes its c
38
38
 
39
39
  ## What it commits
40
40
 
41
- The runner stages an explicit snapshot from NUL-delimited porcelain status:
41
+ The runner builds an explicit snapshot from NUL-delimited porcelain status:
42
42
 
43
- - **Tracked changes**, including deletions and both rename/copy endpoints, are staged even when an endpoint is no longer present on disk.
43
+ - **Tracked changes**, including deletions and both rename/copy endpoints, remain selected even when an endpoint is no longer present on disk. A selected index entry absent from both HEAD and the worktree (including a removed intent-to-add) is cleared from the index instead of committed; excluded `memory/` paths are never touched.
44
44
  - **Ordinary untracked paths** are staged only while still present. If one disappears between snapshot and `git add`, the runner re-reads status and retries that same snapshot once without the vanished path; paths discovered during that re-read are never added.
45
- - **`memory/`** remains excluded. Present **`sessions/` and `todo/`** paths remain force-added; tracked deletions under those prefixes stay in the ordinary snapshot. The post-message pass re-stages only `sessions/` paths that appeared while the message was selected.
45
+ - **Untracked nested Git repositories** — an untracked non-bare repository outside `sessions/` and `todo/`, i.e. a directory with its own `.git` file or directory such as a linked worktree or a nested clone — are skipped. Staging one would record a `160000` gitlink instead of its contents.
46
+ - **`memory/`** remains excluded. Present **`sessions/` and `todo/`** paths reported by porcelain remain force-added; tracked deletions under those prefixes stay in the ordinary snapshot. The post-message pass selects only porcelain-visible late `sessions/` paths.
46
47
 
47
- Commit message comes from the `backup-message` subagent, which sees a truncated `git status` and `git diff --cached --stat` and writes a single conventional-ish commit message to a tmp file. On any failure the runner falls back to `chore: backup`.
48
+ The runner stages the selected paths in a temporary private Git index for its diffstat, without exposing backup entries in the shared index while `backup-message` selects a message. Git then commits **only** selected paths against its current HEAD; unrelated staged files and intervening commits stay intact. A post-message status drops deletion paths already committed by another writer, and an already-clean selection returns clean rather than a false failure. Discovery of force-added paths is unchanged: gitignored untracked files omitted by porcelain status are not discovered here, while explicitly staged ignored files remain eligible. The `backup-message` subagent sees a truncated status and private-index diffstat and returns a conventional-ish subject as its final response. Trusted backup code writes that response to an ephemeral tmp file for the runner to consume; the model has no file tools. On any failure the runner falls back to `chore: backup`.
48
49
 
49
50
  ## What it pushes
50
51
 
@@ -58,7 +59,7 @@ On non-fast-forward rejection (either push shape), the runner runs `git fetch` t
58
59
 
59
60
  **Credentials.** The runner spawns `git` directly (not via the `bash` tool), so the `github-cli-auth` plugin's `tool.before` credential injection does **not** fire for it. For **GitHub App auth** the backup plugin mints a per-repo installation token for `origin`'s github.com slug and injects it into the runner's git env via the same `GIT_ASKPASS` helper the bash path uses (token in `TYPECLAW_GIT_TOKEN`, never in argv/config; ssh remotes rewritten to https via `insteadOf`). Classic/fine-grained PATs, SSH-key, and credential-helper setups are left untouched — the runner uses its inherited process env. Non-github origins are never minted for.
60
61
 
61
- If any network step fails (rebase conflict, auth failure, network timeout), the runner aborts cleanly and spawns the `backup-diagnose` subagent. That subagent has `bash`, `read`, and `write` tools and writes a short human-readable report to `<agentDir>/sessions/backup-diagnostics.log`. The diagnose subagent is explicitly forbidden from force-pushing or resolving merge conflicts itself.
62
+ If any network step fails (rebase conflict, auth failure, network timeout), the runner aborts cleanly and spawns the `backup-diagnose` subagent. That subagent has `bash` and `read` tools, returns a short human-readable diagnosis, and trusted backup code appends it to `<agentDir>/sessions/backup-diagnostics.log`. The diagnose subagent is explicitly forbidden from force-pushing or resolving merge conflicts itself.
62
63
 
63
64
  ## What it maintains
64
65
 
@@ -76,16 +77,16 @@ Because the backup force-commits `sessions/` every idle window, each cycle lands
76
77
  | Kind | Name | Notes |
77
78
  | -------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
78
79
  | Subagent | `backup` | Runner orchestrator. No LLM call — `handler` directly invokes the deterministic `runBackup`. Coalesced per `agentDir`. |
79
- | Subagent | `backup-message` | Picks commit message from the diff. Has only the `write` tool. Coalesced per `agentDir`. |
80
- | Subagent | `backup-diagnose` | Diagnoses push/rebase failures. Has `bash`, `read`, `write`. Coalesced per `agentDir`. |
80
+ | Subagent | `backup-message` | Picks commit message from the diff. Has no tools; trusted code stores its final response. Coalesced per `agentDir`. |
81
+ | Subagent | `backup-diagnose` | Diagnoses push/rebase failures. Has `bash` and `read`; trusted code appends its final response to the diagnostics log. Coalesced per `agentDir`. |
81
82
  | Hook | `session.turn.start` / `.end` | Maintains the active-turn counter. Excludes self-induced turns (the three subagents above) so the backup never gates against itself. |
82
83
  | Hook | `session.idle` | Debouncer (idleMs). Resets the timer on every event. On fire, checks the active-turn counter and spawns `backup` if zero. |
83
84
  | Hook | `session.end` | Removes the session from the active-turn set on session close. Defensive: if a session ends mid-turn (network drop), `session.turn.end` may not have fired. |
84
85
 
85
86
  ## Files on disk
86
87
 
87
- - **`<agentDir>/.typeclaw/backup-message.tmp`** — ephemeral. Written by `backup-message` subagent, read and then deleted by the runner. The directory is created on demand. Not gitignored because it always cleans itself up before commit.
88
- - **`<agentDir>/sessions/backup-diagnostics.log`** — append-only log written by `backup-diagnose` when push/rebase fails. Lives under `sessions/` so it gets force-added by the next successful backup. Read this file when investigating why the backup plugin stopped working.
88
+ - **`<agentDir>/.typeclaw/backup-message.tmp`** — ephemeral. Written by trusted backup code, read and then deleted by the runner. The directory is created on demand. Not gitignored because it always cleans itself up before commit.
89
+ - **`<agentDir>/sessions/backup-diagnostics.log`** — append-only log written by trusted backup code from `backup-diagnose`'s final response when push/rebase fails. Lives under `sessions/` so it gets force-added by the next successful backup. Read this file when investigating why the backup plugin stopped working.
89
90
 
90
91
  ## Why this design
91
92