typeclaw 0.45.1 → 0.46.1

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 (163) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  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 +161 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +207 -0
  11. package/src/agent/plugin-tools.ts +377 -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 +1310 -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 +163 -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 +30 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/README.md +23 -10
  32. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  33. package/src/bundled-plugins/backup/index.ts +85 -44
  34. package/src/bundled-plugins/backup/runner.ts +85 -1
  35. package/src/bundled-plugins/doc-render/render.ts +93 -12
  36. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  37. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  38. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  39. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  40. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  41. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  42. package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
  43. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  44. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  45. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  46. package/src/bundled-plugins/memory/README.md +32 -11
  47. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  48. package/src/bundled-plugins/memory/citations.ts +22 -9
  49. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  50. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  51. package/src/bundled-plugins/memory/index.ts +0 -4
  52. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  53. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  54. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  55. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  56. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  57. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  58. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  59. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  60. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  61. package/src/bundled-plugins/researcher/write-report.ts +8 -5
  62. package/src/bundled-plugins/reviewer/index.ts +2 -2
  63. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  64. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  65. package/src/bundled-plugins/scout/scout.ts +8 -0
  66. package/src/bundled-plugins/security/index.ts +4 -4
  67. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  68. package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
  69. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  70. package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
  71. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  72. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  73. package/src/channels/adapters/discord-bot.ts +66 -6
  74. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  75. package/src/channels/adapters/discord-id.ts +4 -0
  76. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  77. package/src/channels/adapters/discord.ts +57 -7
  78. package/src/channels/adapters/github/auth-app.ts +41 -12
  79. package/src/channels/adapters/github/inbound.ts +11 -0
  80. package/src/channels/adapters/github/index.ts +71 -65
  81. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  82. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  83. package/src/channels/adapters/github/review-submitter.ts +302 -0
  84. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  85. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  86. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  87. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  88. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  89. package/src/channels/adapters/slack-bot.ts +26 -10
  90. package/src/channels/adapters/slack-classify.ts +21 -2
  91. package/src/channels/adapters/slack-format.ts +245 -0
  92. package/src/channels/adapters/slack.ts +59 -7
  93. package/src/channels/adapters/telegram-bot.ts +18 -5
  94. package/src/channels/adapters/webex-bot.ts +8 -3
  95. package/src/channels/adapters/webex.ts +8 -3
  96. package/src/channels/fetch-attachment.ts +43 -0
  97. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  98. package/src/channels/github-token-bridge.ts +12 -6
  99. package/src/channels/manager.ts +9 -0
  100. package/src/channels/router.ts +248 -6
  101. package/src/channels/types.ts +28 -1
  102. package/src/cli/channel.ts +1 -1
  103. package/src/cli/init.ts +1 -1
  104. package/src/cli/model.ts +57 -7
  105. package/src/compose/stop.ts +17 -5
  106. package/src/config/config.ts +6 -6
  107. package/src/config/models-mutation.ts +13 -1
  108. package/src/config/providers.ts +176 -0
  109. package/src/container/docker-app.ts +42 -13
  110. package/src/container/start.ts +62 -10
  111. package/src/cron/bridge.ts +9 -2
  112. package/src/doctor/checks.ts +8 -3
  113. package/src/doctor/commit.ts +2 -1
  114. package/src/doctor/file-ownership.ts +52 -0
  115. package/src/dreams/git.ts +2 -1
  116. package/src/git/bound-gc-config.ts +82 -0
  117. package/src/git/hookless.ts +5 -0
  118. package/src/git/reconcile-ignored.ts +18 -5
  119. package/src/git/system-commit.ts +12 -6
  120. package/src/hostd/spawn.ts +133 -47
  121. package/src/init/dockerfile.ts +99 -5
  122. package/src/init/index.ts +17 -5
  123. package/src/init/models-dev.ts +4 -0
  124. package/src/init/validate-api-key.ts +2 -0
  125. package/src/inspect/replay.ts +21 -9
  126. package/src/inspect/session-list.ts +71 -33
  127. package/src/mcp/tools.ts +17 -3
  128. package/src/network/internal-destinations.ts +267 -0
  129. package/src/permissions/builtins.ts +3 -1
  130. package/src/plugin/context.ts +2 -0
  131. package/src/plugin/index.ts +1 -0
  132. package/src/plugin/manager.ts +4 -0
  133. package/src/plugin/types.ts +22 -0
  134. package/src/run/index.ts +40 -0
  135. package/src/run/llm-fetch-observer.ts +41 -4
  136. package/src/sandbox/build.ts +37 -15
  137. package/src/sandbox/canonical-secrets.ts +18 -0
  138. package/src/sandbox/env-exposure.ts +83 -0
  139. package/src/sandbox/errors.ts +13 -6
  140. package/src/sandbox/hidden-paths.ts +102 -44
  141. package/src/sandbox/index.ts +22 -4
  142. package/src/sandbox/package-install.ts +3 -27
  143. package/src/sandbox/policy.ts +16 -28
  144. package/src/sandbox/privileged-runtime.ts +256 -0
  145. package/src/sandbox/session-tmp.ts +8 -2
  146. package/src/sandbox/writable-zones.ts +204 -140
  147. package/src/secrets/index.ts +8 -0
  148. package/src/secrets/refresh-provider-oauth.ts +128 -0
  149. package/src/server/command-runner.ts +48 -4
  150. package/src/server/index.ts +4 -0
  151. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  152. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  153. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  154. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  155. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  156. package/src/skills/typeclaw-config/SKILL.md +27 -11
  157. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  158. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  159. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  160. package/src/skills/typeclaw-permissions/SKILL.md +36 -19
  161. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  162. package/src/usage/scan.ts +11 -2
  163. package/typeclaw.schema.json +25 -0
@@ -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
  }
@@ -11,11 +11,11 @@ export type GithubTokenBridge = {
11
11
  resolveTokenForRepo: ResolveGithubTokenForRepo
12
12
  // True when a per-repo App-token minter is registered (only the GitHub App
13
13
  // adapter registers one). This is the non-secret "App auth with per-repo
14
- // minting is available" signal: it stays true for multi-owner / no-repos App
15
- // configs where the process-wide GH_TOKEN is intentionally NOT seeded, so the
16
- // git/gh mint paths can no longer rely on GH_TOKEN's prefix to detect App auth.
14
+ // minting is available" signal. App credentials are never seeded into the
15
+ // process-wide GH_TOKEN, so brokered gh paths cannot rely on its prefix.
17
16
  hasAppTokenResolver: () => boolean
18
- registerResolver: (resolver: (repoSlug: string) => Promise<string>) => () => void
17
+ getAppSelfLogin: () => string | null
18
+ registerResolver: (resolver: (repoSlug: string) => Promise<string>, selfLogin?: () => string | null) => () => void
19
19
  }
20
20
 
21
21
  const NO_RESOLVER_REASON =
@@ -24,6 +24,7 @@ const NO_RESOLVER_REASON =
24
24
 
25
25
  export function createGithubTokenBridge(): GithubTokenBridge {
26
26
  let current: ((repoSlug: string) => Promise<string>) | null = null
27
+ let currentSelfLogin: (() => string | null) | null = null
27
28
 
28
29
  return {
29
30
  resolveTokenForRepo: async (repoSlug) => {
@@ -37,12 +38,17 @@ export function createGithubTokenBridge(): GithubTokenBridge {
37
38
  }
38
39
  },
39
40
  hasAppTokenResolver: () => current !== null,
40
- registerResolver: (resolver) => {
41
+ getAppSelfLogin: () => currentSelfLogin?.() ?? null,
42
+ registerResolver: (resolver, selfLogin) => {
41
43
  current = resolver
44
+ currentSelfLogin = selfLogin ?? null
42
45
  return () => {
43
46
  // Only clear if still the active resolver: a stop() racing a newer
44
47
  // start() must not wipe the newer registration.
45
- if (current === resolver) current = null
48
+ if (current === resolver) {
49
+ current = null
50
+ currentSelfLogin = null
51
+ }
46
52
  }
47
53
  },
48
54
  }
@@ -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,
@@ -10,7 +10,13 @@ import { resolveFallbackChain } from '@/agent/model-fallback'
10
10
  import { applyModelRuntimeOverrides } from '@/agent/model-overrides'
11
11
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
12
12
  import { detectHardProviderError, isFailoverWorthy, subscribeProviderErrors } from '@/agent/provider-error'
13
- import type { RestartHandoff } from '@/agent/restart-handoff'
13
+ import {
14
+ acquireRestartHandoffLock,
15
+ peekRestartHandoff,
16
+ RESTART_HANDOFF_TTL_MS,
17
+ type RestartHandoff,
18
+ writeRestartHandoff,
19
+ } from '@/agent/restart-handoff'
14
20
  import type { ChannelParticipant, SessionOrigin } from '@/agent/session-origin'
15
21
  import { renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
16
22
  import {
@@ -105,6 +111,7 @@ import type {
105
111
  ReactionRequest,
106
112
  ReactionResult,
107
113
  ResolvedChannelNames,
114
+ ReviewSubmitter,
108
115
  ReviewStateRequest,
109
116
  ReviewStateResolver,
110
117
  ReviewStateResult,
@@ -113,6 +120,8 @@ import type {
113
120
  ReviewThreadResolver,
114
121
  SendErrorCode,
115
122
  SendResult,
123
+ SubmitReviewRequest,
124
+ SubmitReviewResult,
116
125
  TypingCallback,
117
126
  } from './types'
118
127
  import { channelKeyId } from './types'
@@ -212,6 +221,38 @@ export const RESTART_RESUME_WAKE_REMINDER = [
212
221
  '',
213
222
  '---',
214
223
  ].join('\n')
224
+
225
+ // The lost-work directive: names the interrupted subagents and tells the model
226
+ // to inform the thread, in the audience's language, that the result was lost —
227
+ // never to re-run it automatically (the human decides whether to re-ask). Used
228
+ // standalone when a racing inbound already provides the wake turn, and embedded
229
+ // in the fuller resume reminder when the synthetic wake fires. Rendered as plain
230
+ // text so a non-Latin subagent name survives intact.
231
+ export function buildInterruptedSubagentNotice(interruptedSubagents: readonly string[]): string {
232
+ const names = interruptedSubagents.join(', ')
233
+ return [
234
+ '---',
235
+ '**[SYSTEM MESSAGE — not from a human]**',
236
+ '',
237
+ `A background task you had promised a result for was lost when the container`,
238
+ `restarted (interrupted subagent(s): ${names}). Briefly tell the people in`,
239
+ `this conversation, in their own language, that the result was lost to a`,
240
+ `restart and they can ask again if they still want it. Do not silently`,
241
+ `re-run it. Do not acknowledge or reply to this notice itself.`,
242
+ '',
243
+ '---',
244
+ ].join('\n')
245
+ }
246
+
247
+ // The synthetic "I'm back" wake, optionally carrying the lost-work directive
248
+ // when the restart interrupted background subagents this session had promised
249
+ // results for. With none, it is the plain wake reminder unchanged.
250
+ export function buildRestartResumeWakeReminder(interruptedSubagents?: readonly string[]): string {
251
+ if (interruptedSubagents === undefined || interruptedSubagents.length === 0) {
252
+ return RESTART_RESUME_WAKE_REMINDER
253
+ }
254
+ return `${RESTART_RESUME_WAKE_REMINDER}\n\n${buildInterruptedSubagentNotice(interruptedSubagents)}`
255
+ }
215
256
  // Ceiling on tool-source channel sends that a same-turn router policy DENIED
216
257
  // without delivering — `skip-locked`, `turn-cap`, or `duplicate`. Such denials
217
258
  // return a soft error and do NOT increment `consecutiveSends`, so a model that
@@ -1269,6 +1310,9 @@ export type ChannelRouter = {
1269
1310
  registerReviewStateResolver: (adapter: ChannelKey['adapter'], resolver: ReviewStateResolver) => void
1270
1311
  unregisterReviewStateResolver: (adapter: ChannelKey['adapter'], resolver: ReviewStateResolver) => void
1271
1312
  getReviewState: (req: ReviewStateRequest) => Promise<ReviewStateResult>
1313
+ registerReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1314
+ unregisterReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1315
+ submitReview: (req: SubmitReviewRequest) => Promise<SubmitReviewResult>
1272
1316
  lookupInboundAttachment: (args: ChannelKey & { id: number }) => InboundAttachment | null
1273
1317
  listInboundAttachmentIds: (args: ChannelKey) => readonly number[]
1274
1318
  // Stash refs from a channel_history fetch so prior-turn attachments stay
@@ -1382,6 +1426,10 @@ export type ChannelRouter = {
1382
1426
  // Graceful-restart shutdown: mark + abort every live channel session so each
1383
1427
  // scope's incomplete todos auto-continue on the next boot. See the impl.
1384
1428
  markRestartAbortForAllLive: () => Promise<void>
1429
+ // Graceful-restart shutdown: persist a channel handoff naming the background
1430
+ // subagents a live session was still awaiting, so the resume greeting can tell
1431
+ // that thread the promised result was lost. Resolves true iff one was written.
1432
+ writeInterruptedSubagentHandoff: () => Promise<boolean>
1385
1433
  liveCount: () => number
1386
1434
  __testing?: {
1387
1435
  flushDebounce: (key: ChannelKey) => Promise<void>
@@ -1515,6 +1563,11 @@ export type CreateChannelRouterOptions = {
1515
1563
  // spawned child is still inside its window. Production wiring forwards the
1516
1564
  // LiveSubagentRegistry; omitted (tests, no-subagent setups) means no pin.
1517
1565
  newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
1566
+ // Names of the still-running BACKGROUND subagents for a parent session, used
1567
+ // by writeInterruptedSubagentHandoff on graceful restart to name the lost
1568
+ // work in the resume greeting. Background-only: a foreground child returns its
1569
+ // result inline, so it is not orphaned by the bounce. Omitted means none.
1570
+ listRunningBackgroundSubagentNames?: (sessionId: string) => string[]
1518
1571
  }
1519
1572
 
1520
1573
  export type RestartCommandContext = {
@@ -1609,6 +1662,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1609
1662
  const fetchAttachmentCallbacks = new Map<ChannelKey['adapter'], Set<FetchAttachmentCallback>>()
1610
1663
  const reviewThreadResolvers = new Map<ChannelKey['adapter'], ReviewThreadResolver>()
1611
1664
  const reviewStateResolvers = new Map<ChannelKey['adapter'], ReviewStateResolver>()
1665
+ const reviewSubmitters = new Map<ChannelKey['adapter'], ReviewSubmitter>()
1612
1666
  const stickyLedger = new StickyLedger()
1613
1667
  // The /help handler reads the live registry to enumerate commands, so it
1614
1668
  // forward-references `commands`. Safe at runtime — the handler only runs on
@@ -1728,6 +1782,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1728
1782
  sessionManager,
1729
1783
  origin,
1730
1784
  originRef,
1785
+ permissions,
1731
1786
  })
1732
1787
  const sessionId = sessionManager.getSessionId()
1733
1788
  void key
@@ -2031,6 +2086,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2031
2086
  chat: key.chat,
2032
2087
  ...(resolvedNames.chatName !== undefined ? { chatName: resolvedNames.chatName } : {}),
2033
2088
  thread: key.thread,
2089
+ ...(room?.parentChat !== undefined ? { parentChat: room.parentChat } : {}),
2090
+ ...(room?.parentChatName !== undefined ? { parentChatName: room.parentChatName } : {}),
2034
2091
  ...(triggeringAuthorId !== undefined ? { lastInboundAuthorId: triggeringAuthorId } : {}),
2035
2092
  participants,
2036
2093
  ...(membership !== null ? { membership } : {}),
@@ -2724,7 +2781,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2724
2781
  }
2725
2782
 
2726
2783
  const buildLiveOrigin = (live: LiveSession): SessionOrigin => {
2727
- const membership = readMembership(live.key)
2784
+ const membership = readMembership(live.key, live.room)
2728
2785
  const self = resolveSelfIdentity(live.key)
2729
2786
  return {
2730
2787
  kind: 'channel',
@@ -2734,6 +2791,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2734
2791
  chat: live.key.chat,
2735
2792
  ...(live.resolvedNames.chatName !== undefined ? { chatName: live.resolvedNames.chatName } : {}),
2736
2793
  thread: live.key.thread,
2794
+ ...(live.room?.parentChat !== undefined ? { parentChat: live.room.parentChat } : {}),
2795
+ ...(live.room?.parentChatName !== undefined ? { parentChatName: live.room.parentChatName } : {}),
2737
2796
  ...(live.currentTurnAuthorId !== null ? { lastInboundAuthorId: live.currentTurnAuthorId } : {}),
2738
2797
  ...(live.currentTurnReactionRef !== null ? { reactionRef: live.currentTurnReactionRef } : {}),
2739
2798
  participants: live.participants,
@@ -4095,6 +4154,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4095
4154
  )
4096
4155
  }
4097
4156
 
4157
+ const registerReviewSubmitter = (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter): void => {
4158
+ reviewSubmitters.set(adapter, submitter)
4159
+ }
4160
+
4161
+ const unregisterReviewSubmitter = (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter): void => {
4162
+ if (reviewSubmitters.get(adapter) === submitter) reviewSubmitters.delete(adapter)
4163
+ }
4164
+
4165
+ const submitReview = async (req: SubmitReviewRequest): Promise<SubmitReviewResult> => {
4166
+ const submitter = reviewSubmitters.get(req.adapter)
4167
+ if (submitter === undefined) {
4168
+ return { ok: false, error: `adapter "${req.adapter}" does not support review submission`, code: 'unsupported' }
4169
+ }
4170
+ return await submitter(req).catch(
4171
+ (err): SubmitReviewResult => ({ ok: false, error: describe(err), code: 'transient' }),
4172
+ )
4173
+ }
4174
+
4098
4175
  const lookupInboundAttachment = (args: ChannelKey & { id: number }): InboundAttachment | null => {
4099
4176
  const live = liveSessions.get(channelKeyId(args))
4100
4177
  if (live === undefined) return null
@@ -5176,6 +5253,73 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5176
5253
  }
5177
5254
  }
5178
5255
 
5256
+ // Graceful-restart hint: if a live channel session has background subagents
5257
+ // still running, record their names in the restart handoff so the boot resume
5258
+ // can tell that thread its promised result was lost. Only one handoff exists
5259
+ // on disk, so the FIRST session with running background children wins; the
5260
+ // rare "two threads mid-research at once" case notifies one. The fresh/stale
5261
+ // and augment-vs-fresh-write decision is documented inline below.
5262
+ //
5263
+ // Returns whether the handoff now carries interrupted names, propagated from
5264
+ // the writer's real result so a swallowed filesystem failure reports false.
5265
+ const writeInterruptedSubagentHandoff = async (): Promise<boolean> => {
5266
+ const listNames = options.listRunningBackgroundSubagentNames
5267
+ if (listNames === undefined) return false
5268
+
5269
+ // Take the same lock `/restart` holds so our peek→select→write is atomic
5270
+ // relative to its post-ACK write: either it commits first and we augment the
5271
+ // exact handoff, or we commit first and it overwrites with its own origin —
5272
+ // never an interleaved read-modify-write that drops one producer's data.
5273
+ const release = await acquireRestartHandoffLock(options.agentDir)
5274
+ try {
5275
+ // A FRESH existing handoff is authoritative: it is the accepted in-session
5276
+ // restart's, so we augment it (never clobber its origin/author with a
5277
+ // different live session's) — or, if its own session has no running
5278
+ // children, leave it untouched and record nothing. A STALE handoff is not
5279
+ // authoritative: peekRestartHandoff applies no TTL, so an unclaimed TUI
5280
+ // handoff left on disk by kind-aware consume can surface here; honoring it
5281
+ // would suppress THIS restart's note or preserve its old restartedAt so the
5282
+ // next boot discards the note as stale — so we ignore it and write fresh
5283
+ // from the current live sessions. When we augment, stamp restartedAt=now()
5284
+ // so the note survives the boot TTL.
5285
+ const existing = await peekRestartHandoff(options.agentDir)
5286
+ const existingIsFresh = existing !== null && now() - Date.parse(existing.restartedAt) <= RESTART_HANDOFF_TTL_MS
5287
+ if (existing !== null && existingIsFresh) {
5288
+ const names = listNames(existing.originatingSessionId)
5289
+ if (names.length === 0) return false
5290
+ return await writeRestartHandoff(options.agentDir, {
5291
+ ...existing,
5292
+ restartedAt: new Date(now()).toISOString(),
5293
+ interruptedSubagents: names,
5294
+ })
5295
+ }
5296
+
5297
+ for (const live of Array.from(liveSessions.values())) {
5298
+ const names = listNames(live.sessionId)
5299
+ if (names.length === 0) continue
5300
+ const sessionFile = live.getTranscriptPath?.()
5301
+ if (sessionFile === undefined) continue
5302
+ // Carry the session's author (same precedence as buildRestartCommandContext)
5303
+ // so boot re-seeds lastTurnAuthorId. Without it an author-scoped role demotes
5304
+ // on resume and the reminder-only turn can lose channel.send — i.e. fail to
5305
+ // deliver the very lost-work notice this handoff exists for.
5306
+ const triggeringAuthorId = live.currentTurnAuthorId ?? live.lastTurnAuthorId ?? undefined
5307
+ return await writeRestartHandoff(options.agentDir, {
5308
+ schemaVersion: 2,
5309
+ restartedAt: new Date(now()).toISOString(),
5310
+ originatingSessionId: live.sessionId,
5311
+ origin: { kind: 'channel', key: live.key },
5312
+ originatingSessionFile: basename(sessionFile),
5313
+ interruptedSubagents: names,
5314
+ ...(triggeringAuthorId !== undefined ? { triggeringAuthorId } : {}),
5315
+ })
5316
+ }
5317
+ return false
5318
+ } finally {
5319
+ release()
5320
+ }
5321
+ }
5322
+
5179
5323
  // Boot-time resume for a restart that originated from a channel session, in
5180
5324
  // two phases to close the race with adapters that begin receiving inbounds.
5181
5325
  //
@@ -5269,8 +5413,25 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5269
5413
  // A real inbound coalesced onto the reservation during boot: it is the
5270
5414
  // wake. Adding the synthetic "I'm back" turn on top would duplicate
5271
5415
  // work / stack a spurious turn, so skip it and let the inbound drain.
5416
+ // The interrupted-subagent directive is NOT part of that generic wake,
5417
+ // though: it is the only signal that a promised result was lost, and the
5418
+ // boot already consumed the handoff, so if we drop it here no later turn
5419
+ // re-delivers it. Queue it AND drain ourselves: `sawInbound` is set
5420
+ // before engagement is decided, so an observe-only inbound returns
5421
+ // without draining and would strand the reminder. drain() is guarded
5422
+ // (`draining || destroyed` no-ops) so if the inbound WILL engage this is
5423
+ // a harmless second call, and its loop consumes pendingSystemReminders
5424
+ // either way. Still skip the generic synthetic wake.
5272
5425
  if (reservation.sawInbound) {
5273
- logger.info(`[channels] ${keyId}: restart-resume coalesced with a real inbound; skipping synthetic wake`)
5426
+ if (handoff.interruptedSubagents !== undefined && handoff.interruptedSubagents.length > 0) {
5427
+ live.pendingSystemReminders.push(buildInterruptedSubagentNotice(handoff.interruptedSubagents))
5428
+ logger.info(
5429
+ `[channels] ${keyId}: restart-resume coalesced with a real inbound; delivering interrupted-subagent notice`,
5430
+ )
5431
+ void drain(live)
5432
+ } else {
5433
+ logger.info(`[channels] ${keyId}: restart-resume coalesced with a real inbound; skipping synthetic wake`)
5434
+ }
5274
5435
  return
5275
5436
  }
5276
5437
 
@@ -5284,7 +5445,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5284
5445
  logger.error(`[channels] ${keyId}: restart-resume clear abort suppression failed: ${describe(err)}`),
5285
5446
  )
5286
5447
 
5287
- live.pendingSystemReminders.push(RESTART_RESUME_WAKE_REMINDER)
5448
+ live.pendingSystemReminders.push(buildRestartResumeWakeReminder(handoff.interruptedSubagents))
5288
5449
  logger.info(`[channels] ${keyId}: restart-resume waking session ${live.sessionId}`)
5289
5450
  void drain(live)
5290
5451
  },
@@ -5693,6 +5854,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5693
5854
  registerReviewStateResolver,
5694
5855
  unregisterReviewStateResolver,
5695
5856
  getReviewState,
5857
+ registerReviewSubmitter,
5858
+ unregisterReviewSubmitter,
5859
+ submitReview,
5696
5860
  lookupInboundAttachment,
5697
5861
  listInboundAttachmentIds,
5698
5862
  registerHistoryAttachments,
@@ -5708,6 +5872,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5708
5872
  stop,
5709
5873
  tearDownAllLive,
5710
5874
  markRestartAbortForAllLive,
5875
+ writeInterruptedSubagentHandoff,
5711
5876
  liveCount: () => liveSessions.size,
5712
5877
  __testing: {
5713
5878
  flushDebounce: async (key: ChannelKey) => {
@@ -6896,8 +7061,9 @@ export function getPlainTextChannelToolCallKind(text: string): PlainTextChannelT
6896
7061
  // dropping the explanation. `isWholeMessageToolCall` returns the tool name
6897
7062
  // only when the entire trimmed message is the call (or a truncated one), so a
6898
7063
  // reply/send leak still recovers while a mention-with-trailing-prose falls
6899
- // through to the user.
6900
- const toolName = isWholeMessageToolCall(text)
7064
+ // through to the user. The JSON-object serialization shape (see
7065
+ // `parseWholeMessageJsonToolCall`) feeds the SAME name->kind mapping below.
7066
+ const toolName = isWholeMessageToolCall(text) ?? parseWholeMessageJsonToolCall(text)?.toolName ?? null
6901
7067
  if (toolName === null) return null
6902
7068
  if (toolName === 'channel_reply') return 'reply'
6903
7069
  if (toolName === 'channel_send') return 'send'
@@ -6953,6 +7119,74 @@ export function isWholeMessageToolCall(text: string): string | null {
6953
7119
  return null
6954
7120
  }
6955
7121
 
7122
+ export type JsonToolCallLeak = { toolName: string; params: Record<string, unknown> }
7123
+
7124
+ const JSON_TOOL_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/
7125
+
7126
+ // Detects the JSON-RPC-object serialization of a leaked tool call — the sibling
7127
+ // of `isWholeMessageToolCall`'s call-expression shape. Observed against
7128
+ // `solar-open2` (Upstage) on channel deployments: the entire assistant message
7129
+ // body is the object `{"method":"<tool>","params":{...}}`, optionally wrapped in
7130
+ // a single ```json (or bare ```) fence, so the call-expression parser (which
7131
+ // requires `identifier(`) never fires and the plumbing ships verbatim.
7132
+ //
7133
+ // The boundary is deliberately STRICT because a legitimate reply that IS this
7134
+ // exact object is byte-for-byte indistinguishable from a leak — the tightest
7135
+ // practical rule keeps that false positive to the narrowest possible shape:
7136
+ // 1. the fenced-or-bare object is the ENTIRE trimmed message (nothing before
7137
+ // or after the single optional fence), parsed by strict `JSON.parse` so
7138
+ // truncated/malformed serializations are NOT treated as leaks;
7139
+ // 2. the parsed value is a plain object whose own top-level keys are EXACTLY
7140
+ // `method` and `params` — a canonical JSON-RPC frame (`jsonrpc`/`id`) or a
7141
+ // user-requested JSON document carries extra keys and falls through;
7142
+ // 3. `method` is a non-empty identifier-shaped string (the tool grammar), and
7143
+ // `params` is a non-null, non-array object.
7144
+ // A match returns the tool name so the caller reuses the existing name->kind
7145
+ // disposition (reply/send recover, skip_response silent, else warn).
7146
+ export function parseWholeMessageJsonToolCall(text: string): JsonToolCallLeak | null {
7147
+ const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim()
7148
+ const body = stripSingleWholeMessageJsonFence(normalized)
7149
+ if (body === null) return null
7150
+
7151
+ let parsed: unknown
7152
+ try {
7153
+ parsed = JSON.parse(body)
7154
+ } catch {
7155
+ return null
7156
+ }
7157
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
7158
+
7159
+ const keys = Object.keys(parsed)
7160
+ if (keys.length !== 2 || !keys.includes('method') || !keys.includes('params')) return null
7161
+
7162
+ const record = parsed as Record<string, unknown>
7163
+ const method = record.method
7164
+ if (typeof method !== 'string' || !JSON_TOOL_NAME_RE.test(method)) return null
7165
+
7166
+ const params = record.params
7167
+ if (typeof params !== 'object' || params === null || Array.isArray(params)) return null
7168
+
7169
+ return { toolName: method, params: params as Record<string, unknown> }
7170
+ }
7171
+
7172
+ // Unwraps a single whole-message ```` ``` ```` or ```` ```json ```` fence around
7173
+ // a JSON object, returning the inner body, or the input unchanged when there is
7174
+ // no fence. Returns null when a fence opens but the message is not JUST that one
7175
+ // fenced block (leading/trailing prose, unterminated fence) so a fenced example
7176
+ // embedded in prose is never mistaken for the whole-message shape. The opener is
7177
+ // held to EXACTLY three backticks with an optional lowercase `json` info string —
7178
+ // tilde fences, longer runs, and other language tags stay out of the boundary so
7179
+ // the false-positive surface matches only the reported production shape.
7180
+ function stripSingleWholeMessageJsonFence(trimmed: string): string | null {
7181
+ if (!trimmed.startsWith('```')) return trimmed
7182
+
7183
+ const open = /^```(json)?\n/.exec(trimmed)
7184
+ if (open === null) return null
7185
+ const close = /\n```$/.exec(trimmed)
7186
+ if (close === null || close.index < open[0].length) return null
7187
+ return trimmed.slice(open[0].length, close.index)
7188
+ }
7189
+
6956
7190
  export type TrailingToolCallLeak = { text: string; toolName: string; leakedCall: string }
6957
7191
 
6958
7192
  // Catches the sibling leak that `isWholeMessageToolCall` cannot: the model wrote
@@ -7190,6 +7424,14 @@ function columnWidth(s: string): number {
7190
7424
  // model-supplied destination. Returns null when no recoverable, non-empty
7191
7425
  // `text` value is present so the caller can fall back to suppression.
7192
7426
  export function extractPlainTextChannelToolCallText(text: string): string | null {
7427
+ const jsonCall = parseWholeMessageJsonToolCall(text)
7428
+ if (jsonCall !== null) {
7429
+ if (jsonCall.toolName !== 'channel_reply' && jsonCall.toolName !== 'channel_send') return null
7430
+ if (!Object.hasOwn(jsonCall.params, 'text')) return null
7431
+ const value = jsonCall.params.text
7432
+ return typeof value === 'string' && value.trim().length > 0 ? value : null
7433
+ }
7434
+
7193
7435
  const trimmed = text.trim()
7194
7436
  if (!/^(?:channel_reply|channel_send)\s*\(/.test(trimmed)) return null
7195
7437
 
@@ -60,7 +60,7 @@ export type InboundMessage = {
60
60
  // set this explicitly. `parentChat` carries the parent channel id when the
61
61
  // adapter knows it, so membership can be scoped to the room (channel), not
62
62
  // the thread. Absent ⇒ not a thread room (or the adapter cannot tell).
63
- room?: { kind: 'thread'; parentChat?: string }
63
+ room?: { kind: 'thread'; parentChat?: string; parentChatName?: string }
64
64
  text: string
65
65
  // Prompt-only context for replied-to / quoted / linked messages. Kept out
66
66
  // of `text` so the engagement gate sees only the human-authored body.
@@ -456,6 +456,7 @@ export type ListCallback = (args: ListChannelsArgs) => Promise<ListChannelsResul
456
456
  export type FetchAttachmentArgs = {
457
457
  ref: string
458
458
  filename?: string
459
+ maxBytes?: number
459
460
  }
460
461
 
461
462
  export type FetchAttachmentResult =
@@ -542,6 +543,32 @@ export type GithubReviewDecision = 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_RE
542
543
  // answer `unsupported`.
543
544
  export type ReviewStateResolver = (req: ReviewStateRequest) => Promise<ReviewStateResult>
544
545
 
546
+ export type ReviewFinding = {
547
+ path: string
548
+ line: number
549
+ side?: 'LEFT' | 'RIGHT'
550
+ startLine?: number
551
+ startSide?: 'LEFT' | 'RIGHT'
552
+ body: string
553
+ }
554
+
555
+ export type SubmitReviewRequest = {
556
+ adapter: AdapterId
557
+ workspace: string
558
+ chat: string
559
+ event: 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT'
560
+ body: string
561
+ comments: ReviewFinding[]
562
+ }
563
+
564
+ export type SubmitReviewResult =
565
+ | { ok: true; reviewId: number; state: string; downgraded?: boolean; reanchored?: ReviewFinding[] }
566
+ | { ok: false; error: string; code: SubmitReviewErrorCode; submitted?: boolean }
567
+
568
+ export type SubmitReviewErrorCode = 'unsupported' | 'permission-denied' | 'bad-anchor' | 'not-found' | 'transient'
569
+
570
+ export type ReviewSubmitter = (req: SubmitReviewRequest) => Promise<SubmitReviewResult>
571
+
545
572
  export function channelKeyId(key: { adapter: string; workspace: string; chat: string; thread: string | null }): string {
546
573
  return `${key.adapter}:${key.workspace}:${key.chat}:${key.thread ?? ''}`
547
574
  }
@@ -1518,7 +1518,7 @@ async function promptSlackAppToken(): Promise<string> {
1518
1518
  async function promptTelegramToken(): Promise<string> {
1519
1519
  note(
1520
1520
  [
1521
- 'Open Telegram and message @BotFather.',
1521
+ 'Open Telegram and message @BotFather or visit https://t.me/BotFather.',
1522
1522
  '/newbot → pick a name and username, copy the HTTP API token',
1523
1523
  ' (looks like 1234567890:ABCdef...).',
1524
1524
  'In @BotFather: /setprivacy → Disable, so the bot can see group messages.',
package/src/cli/init.ts CHANGED
@@ -1882,7 +1882,7 @@ function validatePositiveInteger(v: string, requiredMessage: string): string | u
1882
1882
  async function runTelegramFlow(): Promise<StepResult<CollectedInputs['channelSecrets']>> {
1883
1883
  note(
1884
1884
  [
1885
- 'Open Telegram and message @BotFather.',
1885
+ 'Open Telegram and message @BotFather or visit https://t.me/BotFather.',
1886
1886
  '/newbot → pick a name and username, copy the HTTP API token',
1887
1887
  ' (looks like 1234567890:ABCdef...).',
1888
1888
  'In @BotFather: /setprivacy → Disable, so the bot can see group messages.',