typeclaw 0.45.1 → 0.46.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 (142) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -1
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +151 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +198 -0
  11. package/src/agent/plugin-tools.ts +379 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1050 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +143 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +27 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/index.ts +2 -1
  32. package/src/bundled-plugins/backup/runner.ts +2 -1
  33. package/src/bundled-plugins/doc-render/render.ts +93 -12
  34. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  35. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  36. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  37. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  38. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  39. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  40. package/src/bundled-plugins/memory/README.md +23 -11
  41. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  42. package/src/bundled-plugins/memory/citations.ts +22 -9
  43. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  44. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  45. package/src/bundled-plugins/memory/index.ts +0 -4
  46. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  47. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  48. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  49. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  50. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  51. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  52. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  53. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  54. package/src/bundled-plugins/reviewer/index.ts +2 -2
  55. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  56. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  57. package/src/bundled-plugins/scout/scout.ts +8 -0
  58. package/src/bundled-plugins/security/index.ts +4 -4
  59. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  60. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  61. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  62. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  63. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  64. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  65. package/src/channels/adapters/discord-bot.ts +66 -6
  66. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  67. package/src/channels/adapters/discord-id.ts +4 -0
  68. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  69. package/src/channels/adapters/discord.ts +57 -7
  70. package/src/channels/adapters/github/auth-app.ts +41 -12
  71. package/src/channels/adapters/github/index.ts +23 -11
  72. package/src/channels/adapters/github/review-submitter.ts +302 -0
  73. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  74. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  75. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  76. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  77. package/src/channels/adapters/slack-bot.ts +19 -8
  78. package/src/channels/adapters/slack-classify.ts +21 -2
  79. package/src/channels/adapters/slack.ts +59 -7
  80. package/src/channels/adapters/telegram-bot.ts +18 -5
  81. package/src/channels/adapters/webex-bot.ts +8 -3
  82. package/src/channels/adapters/webex.ts +8 -3
  83. package/src/channels/fetch-attachment.ts +43 -0
  84. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  85. package/src/channels/github-token-bridge.ts +10 -3
  86. package/src/channels/manager.ts +9 -0
  87. package/src/channels/router.ts +248 -6
  88. package/src/channels/types.ts +28 -1
  89. package/src/cli/channel.ts +1 -1
  90. package/src/cli/init.ts +1 -1
  91. package/src/cli/model.ts +57 -7
  92. package/src/compose/stop.ts +17 -5
  93. package/src/config/config.ts +6 -6
  94. package/src/config/models-mutation.ts +13 -1
  95. package/src/config/providers.ts +176 -0
  96. package/src/container/start.ts +49 -10
  97. package/src/doctor/checks.ts +3 -1
  98. package/src/doctor/commit.ts +2 -1
  99. package/src/doctor/file-ownership.ts +52 -0
  100. package/src/dreams/git.ts +2 -1
  101. package/src/git/hookless.ts +5 -0
  102. package/src/git/reconcile-ignored.ts +18 -5
  103. package/src/git/secret-history.ts +371 -0
  104. package/src/git/system-commit.ts +12 -6
  105. package/src/init/dockerfile.ts +86 -5
  106. package/src/init/index.ts +17 -5
  107. package/src/init/models-dev.ts +4 -0
  108. package/src/init/validate-api-key.ts +2 -0
  109. package/src/mcp/tools.ts +16 -3
  110. package/src/permissions/builtins.ts +3 -1
  111. package/src/plugin/context.ts +2 -0
  112. package/src/plugin/index.ts +1 -0
  113. package/src/plugin/manager.ts +4 -0
  114. package/src/plugin/types.ts +21 -0
  115. package/src/run/index.ts +40 -0
  116. package/src/run/llm-fetch-observer.ts +41 -4
  117. package/src/sandbox/build.ts +37 -15
  118. package/src/sandbox/canonical-secrets.ts +18 -0
  119. package/src/sandbox/env-exposure.ts +80 -0
  120. package/src/sandbox/errors.ts +13 -6
  121. package/src/sandbox/hidden-paths.ts +102 -44
  122. package/src/sandbox/index.ts +22 -4
  123. package/src/sandbox/package-install.ts +3 -27
  124. package/src/sandbox/policy.ts +11 -25
  125. package/src/sandbox/privileged-runtime.ts +255 -0
  126. package/src/sandbox/session-tmp.ts +8 -2
  127. package/src/sandbox/writable-zones.ts +204 -140
  128. package/src/secrets/index.ts +8 -0
  129. package/src/secrets/refresh-provider-oauth.ts +128 -0
  130. package/src/server/command-runner.ts +48 -4
  131. package/src/server/index.ts +4 -0
  132. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  133. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  134. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  135. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  136. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  137. package/src/skills/typeclaw-config/SKILL.md +5 -5
  138. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  139. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  140. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  141. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  142. package/typeclaw.schema.json +20 -0
@@ -8,6 +8,7 @@ import {
8
8
  type SlackRTMReactionEvent,
9
9
  } from 'agent-messenger/slack'
10
10
 
11
+ import { DEFAULT_ATTACHMENT_MAX_BYTES, enforceAttachmentMetadataSize } from '@/channels/fetch-attachment'
11
12
  import {
12
13
  MEMBERSHIP_ENUMERATION_CAP,
13
14
  type MembershipResolver,
@@ -33,10 +34,11 @@ import { chunkMarkdown } from '@/markdown'
33
34
  import type { SlackAccountRecord } from '@/secrets/schema'
34
35
 
35
36
  import { describeError } from './describe-error'
37
+ import { downloadSlackAttachment, type SlackAttachmentFetch } from './slack-attachment-download'
36
38
  import { createSlackAuthorResolver } from './slack-author-resolver'
37
39
  import { slackTsToMillis } from './slack-bot-time'
38
40
  import { createSlackChannelResolver } from './slack-channel-resolver'
39
- import { classifyInbound, type InboundDropReason } from './slack-classify'
41
+ import { classifyInbound, type InboundDropReason, type SlackConversationType } from './slack-classify'
40
42
  import { createSlackUserEditMessageCallback } from './slack-edit'
41
43
  import { createSlackReactionCallback, createSlackRemoveReactionCallback } from './slack-reactions'
42
44
 
@@ -166,17 +168,31 @@ export function createSlackMembershipResolver(deps: {
166
168
  }
167
169
 
168
170
  export function createSlackFetchAttachmentCallback(deps: {
169
- client: Pick<SlackClient, 'downloadFile'>
171
+ client: Pick<SlackClient, 'getFileInfo'>
172
+ tokenRef: () => string | null
173
+ cookieRef?: () => string | null
174
+ fetchImpl?: SlackAttachmentFetch
170
175
  logger: SlackAdapterLogger
171
176
  }): FetchAttachmentCallback {
172
- return async ({ ref, filename }) => {
177
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
173
178
  try {
174
- const { buffer, file } = await deps.client.downloadFile(ref)
179
+ const metadata = await deps.client.getFileInfo(ref)
180
+ enforceAttachmentMetadataSize(metadata.size, maxBytes)
181
+ const token = deps.tokenRef()
182
+ if (token === null) throw new Error('Slack attachment credential is unavailable')
183
+ const cookie = deps.cookieRef?.() ?? undefined
184
+ const { buffer } = await downloadSlackAttachment({
185
+ metadata,
186
+ token,
187
+ ...(cookie === undefined ? {} : { cookie }),
188
+ maxBytes,
189
+ fetchImpl: deps.fetchImpl,
190
+ })
175
191
  return {
176
192
  ok: true,
177
193
  buffer,
178
- filename: filename ?? file.name ?? 'attachment',
179
- mimetype: file.mimetype,
194
+ filename: filename ?? metadata.name ?? 'attachment',
195
+ mimetype: metadata.mimetype,
180
196
  size: buffer.length,
181
197
  }
182
198
  } catch (err) {
@@ -197,10 +213,13 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
197
213
  let selfName: string | null = null
198
214
  let teamId = ''
199
215
  let teamName: string | null = null
216
+ let accountToken: string | null = null
217
+ let accountCookie: string | null = null
200
218
  let connected = false
201
219
  let started = false
202
220
  let inflightInbounds = 0
203
221
  let stopWaiters: Array<() => void> = []
222
+ const conversationTypes = new Map<string, SlackConversationType>()
204
223
 
205
224
  const channelResolver = createSlackChannelResolver({ client, teamNameRef: () => teamName })
206
225
  const authorResolver = createSlackAuthorResolver({ client })
@@ -221,11 +240,37 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
221
240
  selfUserIdRef: () => selfUserId,
222
241
  })
223
242
  const outboundCallback = createSlackOutboundCallback({ client, logger, formatChannelTag })
224
- const fetchAttachmentCallback = createSlackFetchAttachmentCallback({ client, logger })
243
+ const fetchAttachmentCallback = createSlackFetchAttachmentCallback({
244
+ client,
245
+ logger,
246
+ tokenRef: () => accountToken,
247
+ cookieRef: () => accountCookie,
248
+ })
225
249
  const reactionCallback = createSlackReactionCallback({ client })
226
250
  const removeReactionCallback = createSlackRemoveReactionCallback({ client })
227
251
  const editMessageCallback = createSlackUserEditMessageCallback({ client })
228
252
 
253
+ const resolveConversationType = async (event: SlackRTMMessageEvent): Promise<SlackConversationType | undefined> => {
254
+ if (!event.channel.startsWith('G')) return undefined
255
+ const cached = conversationTypes.get(event.channel)
256
+ if (cached !== undefined) return cached
257
+ return await client.listDMs().then(
258
+ (conversations) => {
259
+ const type: SlackConversationType = conversations.some(
260
+ (conversation) => conversation.id === event.channel && conversation.is_mpim,
261
+ )
262
+ ? 'mpim'
263
+ : 'channel'
264
+ conversationTypes.set(event.channel, type)
265
+ return type
266
+ },
267
+ (error: unknown) => {
268
+ logger.warn(`[slack] conversation metadata failed channel=${event.channel}: ${describeError(error)}`)
269
+ return 'channel'
270
+ },
271
+ )
272
+ }
273
+
229
274
  const handleMessage = async (event: SlackRTMMessageEvent): Promise<void> => {
230
275
  inflightInbounds++
231
276
  try {
@@ -237,6 +282,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
237
282
  teamId,
238
283
  selfUserId,
239
284
  selfAliases: options.selfAliasesRef?.() ?? [],
285
+ conversationType: await resolveConversationType(event),
240
286
  })
241
287
  if (verdict.kind === 'drop') {
242
288
  logger.info(`[slack] dropped id=${event.ts} reason=${verdict.reason}${dropHint(verdict.reason)}`)
@@ -271,6 +317,8 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
271
317
  throw new Error('no Slack account in secrets.json#channels.slack (run typeclaw init to authenticate)')
272
318
  }
273
319
  await client.login({ token: account.token, cookie: account.cookie })
320
+ accountToken = account.token
321
+ accountCookie = account.cookie
274
322
  const auth = await client.testAuth()
275
323
  selfUserId = auth.user_id
276
324
  selfName = auth.user ?? auth.user_id
@@ -280,6 +328,8 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
280
328
  } catch (err) {
281
329
  started = false
282
330
  selfUserId = null
331
+ accountToken = null
332
+ accountCookie = null
283
333
  teamId = ''
284
334
  logger.error(`[slack] login failed: ${describeError(err)}`)
285
335
  throw err
@@ -358,6 +408,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
358
408
  listener?.stop()
359
409
  listener = null
360
410
  selfUserId = null
411
+ accountToken = null
361
412
  connected = false
362
413
  started = false
363
414
  logger.error(`[slack] ${reason}: ${describeError(cause)}`)
@@ -376,6 +427,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
376
427
  async stop(): Promise<void> {
377
428
  if (!started) return
378
429
  started = false
430
+ accountToken = null
379
431
  options.router.unregisterOutbound('slack', outboundCallback)
380
432
  options.router.setTypingCapability('slack', false)
381
433
  options.router.unregisterChannelNameResolver('slack', channelResolver)
@@ -1,6 +1,12 @@
1
1
  import { TelegramBotClient, TelegramBotListener } from 'agent-messenger/telegrambot'
2
2
  import type { TelegramBotUser, TelegramMessage } from 'agent-messenger/telegrambot'
3
3
 
4
+ import { readResponseBodyBounded } from '@/agent/network/response-body'
5
+ import {
6
+ DEFAULT_ATTACHMENT_MAX_BYTES,
7
+ readAttachmentErrorSnippet,
8
+ readAttachmentResponse,
9
+ } from '@/channels/fetch-attachment'
4
10
  import type { MembershipResolver, MembershipResolverFailure, MembershipResolverResult } from '@/channels/membership'
5
11
  import type { ChannelRouter } from '@/channels/router'
6
12
  import type { ChannelAdapterConfig } from '@/channels/schema'
@@ -313,7 +319,7 @@ export function createFetchAttachmentCallback(deps: {
313
319
  }): FetchAttachmentCallback {
314
320
  const { token, logger } = deps
315
321
  const fetchImpl = deps.fetchImpl ?? fetch
316
- return async ({ ref, filename }) => {
322
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
317
323
  if (ref === '' || ref.includes('://')) {
318
324
  return { ok: false, error: `invalid Telegram file_id: ${ref}` }
319
325
  }
@@ -333,7 +339,8 @@ export function createFetchAttachmentCallback(deps: {
333
339
  }
334
340
  let meta: TelegramFileResponse
335
341
  try {
336
- meta = (await metaResponse.json()) as TelegramFileResponse
342
+ const bytes = await readResponseBodyBounded(metaResponse, 64 * 1024)
343
+ meta = JSON.parse(bytes.toString('utf8')) as TelegramFileResponse
337
344
  } catch (err) {
338
345
  return { ok: false, error: `getFile parse failed: ${describeError(err)}` }
339
346
  }
@@ -352,13 +359,19 @@ export function createFetchAttachmentCallback(deps: {
352
359
  return { ok: false, error: message }
353
360
  }
354
361
  if (!response.ok) {
355
- const body = await response.text().catch(() => '')
362
+ const body = await readAttachmentErrorSnippet(response)
356
363
  const message = `download ${response.status} ${response.statusText}${body !== '' ? `: ${body.slice(0, 200)}` : ''}`
357
364
  logger.error(`[telegram-bot] download failed for ${ref}: ${message}`)
358
365
  return { ok: false, error: message }
359
366
  }
360
- const arrayBuffer = await response.arrayBuffer()
361
- const buffer = Buffer.from(arrayBuffer)
367
+ let buffer: Buffer
368
+ try {
369
+ buffer = await readAttachmentResponse(response, maxBytes)
370
+ } catch (err) {
371
+ const message = describeError(err)
372
+ logger.error(`[telegram-bot] download failed for ${ref}: ${message}`)
373
+ return { ok: false, error: message }
374
+ }
362
375
  const inferredFilename = filename ?? filePath.split('/').pop() ?? 'attachment'
363
376
  const contentType = response.headers.get('content-type') ?? undefined
364
377
  logger.info(
@@ -7,6 +7,11 @@ import type {
7
7
  WebexPerson,
8
8
  } from 'agent-messenger/webexbot'
9
9
 
10
+ import {
11
+ DEFAULT_ATTACHMENT_MAX_BYTES,
12
+ readAttachmentErrorSnippet,
13
+ readAttachmentResponse,
14
+ } from '@/channels/fetch-attachment'
10
15
  import {
11
16
  MEMBERSHIP_ENUMERATION_CAP,
12
17
  type MembershipResolver,
@@ -236,7 +241,7 @@ export function createFetchAttachmentCallback(deps: {
236
241
  fetchImpl?: typeof fetch
237
242
  }): FetchAttachmentCallback {
238
243
  const fetchImpl = deps.fetchImpl ?? fetch
239
- return async ({ ref, filename }) => {
244
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
240
245
  let url: URL
241
246
  try {
242
247
  url = new URL(ref)
@@ -255,12 +260,12 @@ export function createFetchAttachmentCallback(deps: {
255
260
  try {
256
261
  const res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${deps.token}` } })
257
262
  if (!res.ok) {
258
- const body = await res.text().catch(() => '')
263
+ const body = await readAttachmentErrorSnippet(res)
259
264
  const message = `webex file fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
260
265
  deps.logger.error(`[webex-bot] fetchAttachment failed for ${url.toString()}: ${message}`)
261
266
  return { ok: false, error: message }
262
267
  }
263
- const buffer = Buffer.from(await res.arrayBuffer())
268
+ const buffer = await readAttachmentResponse(res, maxBytes)
264
269
  const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
265
270
  const contentType = res.headers.get('content-type') ?? undefined
266
271
  return {
@@ -9,6 +9,11 @@ import type {
9
9
  WebexPerson,
10
10
  } from 'agent-messenger/webex'
11
11
 
12
+ import {
13
+ DEFAULT_ATTACHMENT_MAX_BYTES,
14
+ readAttachmentErrorSnippet,
15
+ readAttachmentResponse,
16
+ } from '@/channels/fetch-attachment'
12
17
  import {
13
18
  MEMBERSHIP_ENUMERATION_CAP,
14
19
  type MembershipResolver,
@@ -285,7 +290,7 @@ export function createFetchAttachmentCallback(deps: {
285
290
  fetchImpl?: typeof fetch
286
291
  }): FetchAttachmentCallback {
287
292
  const fetchImpl = deps.fetchImpl ?? fetch
288
- return async ({ ref, filename }) => {
293
+ return async ({ ref, filename, maxBytes = DEFAULT_ATTACHMENT_MAX_BYTES }) => {
289
294
  const token = deps.tokenRef()
290
295
  if (token === null) return { ok: false, error: 'webex account token is not available' }
291
296
  let url: URL
@@ -306,12 +311,12 @@ export function createFetchAttachmentCallback(deps: {
306
311
  try {
307
312
  const res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${token}` } })
308
313
  if (!res.ok) {
309
- const body = await res.text().catch(() => '')
314
+ const body = await readAttachmentErrorSnippet(res)
310
315
  const message = `webex file fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
311
316
  deps.logger.error(`[webex] fetchAttachment failed for ${url.toString()}: ${message}`)
312
317
  return { ok: false, error: message }
313
318
  }
314
- const buffer = Buffer.from(await res.arrayBuffer())
319
+ const buffer = await readAttachmentResponse(res, maxBytes)
315
320
  const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
316
321
  const contentType = res.headers.get('content-type') ?? undefined
317
322
  return {
@@ -0,0 +1,43 @@
1
+ import { readResponseBodyBounded } from '@/agent/network/response-body'
2
+
3
+ export const DEFAULT_ATTACHMENT_MAX_BYTES = 100 * 1024 * 1024
4
+
5
+ export async function readAttachmentResponse(response: Response, maxBytes: number): Promise<Buffer> {
6
+ try {
7
+ return await readResponseBodyBounded(response, maxBytes)
8
+ } catch (error) {
9
+ if (error instanceof Error && error.message.startsWith('response is too large')) {
10
+ throw new Error(error.message.replace('response is too large', 'attachment is too large'))
11
+ }
12
+ throw error
13
+ }
14
+ }
15
+
16
+ export async function discardAttachmentResponse(response: Response): Promise<void> {
17
+ await response.body?.cancel().catch(() => undefined)
18
+ }
19
+
20
+ export async function readAttachmentErrorSnippet(response: Response): Promise<string> {
21
+ try {
22
+ const buffer = await readAttachmentResponse(response, 1024)
23
+ return buffer.toString('utf8').slice(0, 200)
24
+ } catch {
25
+ await discardAttachmentResponse(response)
26
+ return ''
27
+ }
28
+ }
29
+
30
+ export function enforceAttachmentMetadataSize(size: number | undefined, maxBytes: number): void {
31
+ if (size === undefined || !Number.isSafeInteger(size) || size < 0) {
32
+ throw new Error('attachment size is unknown; refusing an unbounded SDK download')
33
+ }
34
+ if (size > maxBytes) throw attachmentTooLarge(size, maxBytes)
35
+ }
36
+
37
+ export function enforceAttachmentBufferSize(buffer: Buffer, maxBytes: number): void {
38
+ if (buffer.byteLength > maxBytes) throw attachmentTooLarge(buffer.byteLength, maxBytes)
39
+ }
40
+
41
+ function attachmentTooLarge(size: number, maxBytes: number): Error {
42
+ return new Error(`attachment is too large (${size} bytes > ${maxBytes} byte limit)`)
43
+ }
@@ -1,4 +1,4 @@
1
- import type { ReviewVerdict } from '@/channels/github-review-turn-ledger'
1
+ import type { ReviewVerdict } from './github-review-turn-ledger'
2
2
 
3
3
  // Raw latest-decisive state. DISMISSED is kept DISTINCT from NONE on purpose: a
4
4
  // genuine dismissal means a fresh same-verdict re-review is legitimate and must
@@ -45,6 +45,28 @@ export type ReviewVerdictGuard = {
45
45
  // Back-compat alias: the guard now covers REQUEST_CHANGES too, not just APPROVE.
46
46
  export type ApproveIdempotencyGuard = ReviewVerdictGuard
47
47
 
48
+ let processEffectiveResolver: EffectiveApprovalResolver = async () => ({ ok: false })
49
+ let processHeadShaResolver: HeadShaResolver = async () => null
50
+
51
+ // Installs the auth-bearing resolvers used by every auth-neutral review surface
52
+ // in this process. The bash interceptor and post_github_review each create a
53
+ // lightweight guard facade, but all facades use these resolvers and the single
54
+ // module-level lease/landed state below.
55
+ export function configureReviewVerdictCoordinator(deps: {
56
+ resolveEffectiveApproval: EffectiveApprovalResolver
57
+ resolveHeadSha: HeadShaResolver
58
+ }): void {
59
+ processEffectiveResolver = deps.resolveEffectiveApproval
60
+ processHeadShaResolver = deps.resolveHeadSha
61
+ }
62
+
63
+ export function createSharedReviewVerdictGuard(): ReviewVerdictGuard {
64
+ return createApproveIdempotencyGuard({
65
+ resolveEffectiveApproval: (target) => processEffectiveResolver(target),
66
+ resolveHeadSha: (target) => processHeadShaResolver(target),
67
+ })
68
+ }
69
+
48
70
  function duplicateReason(verdict: ReviewVerdict): string {
49
71
  if (verdict === 'APPROVE') {
50
72
  return (
@@ -317,4 +339,6 @@ export function __resetReviewVerdictGuardForTest(): void {
317
339
  reservationByCall.clear()
318
340
  recentLandedByPr.clear()
319
341
  tokenSeq = 0
342
+ processEffectiveResolver = async () => ({ ok: false })
343
+ processHeadShaResolver = async () => null
320
344
  }
@@ -15,7 +15,8 @@ export type GithubTokenBridge = {
15
15
  // configs where the process-wide GH_TOKEN is intentionally NOT seeded, so the
16
16
  // git/gh mint paths can no longer rely on GH_TOKEN's prefix to detect App auth.
17
17
  hasAppTokenResolver: () => boolean
18
- registerResolver: (resolver: (repoSlug: string) => Promise<string>) => () => void
18
+ getAppSelfLogin: () => string | null
19
+ registerResolver: (resolver: (repoSlug: string) => Promise<string>, selfLogin?: () => string | null) => () => void
19
20
  }
20
21
 
21
22
  const NO_RESOLVER_REASON =
@@ -24,6 +25,7 @@ const NO_RESOLVER_REASON =
24
25
 
25
26
  export function createGithubTokenBridge(): GithubTokenBridge {
26
27
  let current: ((repoSlug: string) => Promise<string>) | null = null
28
+ let currentSelfLogin: (() => string | null) | null = null
27
29
 
28
30
  return {
29
31
  resolveTokenForRepo: async (repoSlug) => {
@@ -37,12 +39,17 @@ export function createGithubTokenBridge(): GithubTokenBridge {
37
39
  }
38
40
  },
39
41
  hasAppTokenResolver: () => current !== null,
40
- registerResolver: (resolver) => {
42
+ getAppSelfLogin: () => currentSelfLogin?.() ?? null,
43
+ registerResolver: (resolver, selfLogin) => {
41
44
  current = resolver
45
+ currentSelfLogin = selfLogin ?? null
42
46
  return () => {
43
47
  // Only clear if still the active resolver: a stop() racing a newer
44
48
  // start() must not wipe the newer registration.
45
- if (current === resolver) current = null
49
+ if (current === resolver) {
50
+ current = null
51
+ currentSelfLogin = null
52
+ }
46
53
  }
47
54
  },
48
55
  }
@@ -134,6 +134,10 @@ export type ChannelManagerOptions = {
134
134
  // otherwise spawn a duplicate child). Production wiring (src/run/index.ts)
135
135
  // supplies it from the LiveSubagentRegistry; tests omit it.
136
136
  newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
137
+ // Forwarded to the router so the graceful-restart handoff can name the
138
+ // background subagents a session was still awaiting. Same wiring shape as
139
+ // newestRunningChildSubagentStartedAt; tests omit it.
140
+ listRunningBackgroundSubagentNames?: (sessionId: string) => string[]
137
141
  // Persistent messenger SDKs usually reconnect themselves, but a host sleep/offline
138
142
  // cycle can leave a socket half-dead forever. The manager watches live adapters
139
143
  // and restarts one that stays disconnected past this grace period. Test seams are
@@ -200,6 +204,9 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
200
204
  ...(options.newestRunningChildSubagentStartedAt
201
205
  ? { newestRunningChildSubagentStartedAt: options.newestRunningChildSubagentStartedAt }
202
206
  : {}),
207
+ ...(options.listRunningBackgroundSubagentNames
208
+ ? { listRunningBackgroundSubagentNames: options.listRunningBackgroundSubagentNames }
209
+ : {}),
203
210
  })
204
211
  const createDiscordBot = options.createDiscordAdapter ?? createDiscordBotAdapter
205
212
  const createDiscordUser = options.createDiscordUserAdapter ?? createDiscordAdapter
@@ -260,6 +267,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
260
267
  const token = env.DISCORD_BOT_TOKEN
261
268
  if (token === undefined || token.trim() === '') return null
262
269
  return createDiscordBot({
270
+ agentDir: options.agentDir,
263
271
  router,
264
272
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
265
273
  token,
@@ -331,6 +339,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
331
339
  const credentialsStore = createContainerDiscordCredentialStore(options.agentDir, options.secretsProvider ?? null)
332
340
  if (credentialsStore === null) return null
333
341
  return createDiscordUser({
342
+ agentDir: options.agentDir,
334
343
  router,
335
344
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
336
345
  logger,