typeclaw 0.43.1 → 0.44.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 (56) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +14 -2
  6. package/src/agent/multimodal/look-at.ts +27 -9
  7. package/src/agent/plugin-tools.ts +9 -4
  8. package/src/agent/session-origin.ts +1 -0
  9. package/src/agent/tools/channel-fetch-attachment.ts +45 -3
  10. package/src/agent/tools/channel-reply.ts +41 -18
  11. package/src/agent/tools/channel-send.ts +82 -13
  12. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  13. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  14. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  15. package/src/bundled-plugins/memory/README.md +9 -9
  16. package/src/bundled-plugins/memory/index.ts +40 -9
  17. package/src/channels/adapters/github/inbound.ts +20 -14
  18. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  19. package/src/channels/adapters/teams-classify.ts +144 -0
  20. package/src/channels/adapters/teams-id-token.ts +112 -0
  21. package/src/channels/adapters/teams-key.ts +32 -0
  22. package/src/channels/adapters/teams.ts +519 -0
  23. package/src/channels/github-review-turn-ledger.ts +43 -0
  24. package/src/channels/index.ts +1 -1
  25. package/src/channels/manager.ts +54 -1
  26. package/src/channels/router.ts +302 -39
  27. package/src/channels/schema.ts +9 -0
  28. package/src/cli/channel.ts +92 -4
  29. package/src/cli/hostd.ts +41 -0
  30. package/src/cli/init.ts +58 -1
  31. package/src/config/channels-mutation.ts +9 -1
  32. package/src/cron/index.ts +16 -4
  33. package/src/cron/reloadable.ts +25 -7
  34. package/src/cron/scheduler.ts +4 -0
  35. package/src/cron/schema.ts +143 -35
  36. package/src/doctor/channel-checks.ts +27 -0
  37. package/src/hostd/daemon.ts +23 -3
  38. package/src/hostd/protocol.ts +2 -0
  39. package/src/hostd/teams-renewal-manager.ts +212 -0
  40. package/src/init/checkpoint.ts +1 -1
  41. package/src/init/index.ts +68 -1
  42. package/src/init/run-owner-claim.ts +1 -0
  43. package/src/init/teams-auth.ts +111 -0
  44. package/src/inspect/label.ts +4 -0
  45. package/src/permissions/match-rule.ts +11 -1
  46. package/src/permissions/resolve.ts +1 -0
  47. package/src/role-claim/match-rule.ts +2 -1
  48. package/src/run/index.ts +35 -8
  49. package/src/run/llm-fetch-observer.ts +27 -5
  50. package/src/sandbox/build.ts +12 -0
  51. package/src/sandbox/policy.ts +13 -0
  52. package/src/sandbox/writable-zones.ts +46 -10
  53. package/src/secrets/schema.ts +32 -0
  54. package/src/secrets/teams-renewal.ts +229 -0
  55. package/src/secrets/teams-store.ts +108 -0
  56. package/typeclaw.schema.json +163 -3
package/README.md CHANGED
@@ -26,7 +26,7 @@
26
26
 
27
27
  ## Channels — one agent, many inboxes
28
28
 
29
- - 📨 **Supported channels** — Slack, Discord, Telegram, Webex, Instagram, LINE, KakaoTalk, GitHub, and a websocket TUI, driven by the same agent
29
+ - 📨 **Supported channels** — Slack, Discord, Telegram, Webex, Teams, Instagram, LINE, KakaoTalk, GitHub, and a websocket TUI, driven by the same agent
30
30
  - 🔎 **Cross-channel reading** — beyond the conversation it's in, it can read another channel's history, pull a single message by id, or list a workspace's channels on demand, so "check what's going on in #general" or "what do you make of this message?" just works
31
31
  - ✅ **Pull-request review** — treats a GitHub PR as a conversation, reviewing as a participant, with guards against claiming a verdict it didn't actually post and against leaving a PR stranded
32
32
 
package/auth.schema.json CHANGED
@@ -716,6 +716,98 @@
716
716
  "accounts"
717
717
  ]
718
718
  },
719
+ "teams": {
720
+ "type": "object",
721
+ "properties": {
722
+ "currentAccount": {
723
+ "anyOf": [
724
+ {
725
+ "type": "string"
726
+ },
727
+ {
728
+ "type": "null"
729
+ }
730
+ ]
731
+ },
732
+ "accounts": {
733
+ "type": "object",
734
+ "propertyNames": {
735
+ "type": "string"
736
+ },
737
+ "additionalProperties": {
738
+ "type": "object",
739
+ "properties": {
740
+ "account_id": {
741
+ "type": "string"
742
+ },
743
+ "access_token": {
744
+ "type": "string"
745
+ },
746
+ "token_expires_at": {
747
+ "type": "string"
748
+ },
749
+ "account_type": {
750
+ "anyOf": [
751
+ {
752
+ "type": "string",
753
+ "const": "work"
754
+ },
755
+ {
756
+ "type": "string",
757
+ "const": "personal"
758
+ }
759
+ ]
760
+ },
761
+ "region": {
762
+ "anyOf": [
763
+ {
764
+ "type": "string",
765
+ "const": "amer"
766
+ },
767
+ {
768
+ "type": "string",
769
+ "const": "emea"
770
+ },
771
+ {
772
+ "type": "string",
773
+ "const": "apac"
774
+ }
775
+ ]
776
+ },
777
+ "user_name": {
778
+ "type": "string"
779
+ },
780
+ "aad_refresh_token": {
781
+ "type": "string"
782
+ },
783
+ "aad_client_id": {
784
+ "type": "string"
785
+ },
786
+ "aad_tenant_id": {
787
+ "type": "string"
788
+ },
789
+ "created_at": {
790
+ "type": "string"
791
+ },
792
+ "updated_at": {
793
+ "type": "string"
794
+ }
795
+ },
796
+ "required": [
797
+ "account_id",
798
+ "access_token",
799
+ "account_type",
800
+ "created_at",
801
+ "updated_at"
802
+ ]
803
+ }
804
+ }
805
+ },
806
+ "required": [
807
+ "currentAccount",
808
+ "accounts"
809
+ ]
810
+ },
719
811
  "slack": {
720
812
  "type": "object",
721
813
  "properties": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.43.1",
3
+ "version": "0.44.0",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -50,7 +50,7 @@
50
50
  "@mariozechner/pi-tui": "^0.73.1",
51
51
  "@modelcontextprotocol/sdk": "^1.29.0",
52
52
  "@mozilla/readability": "^0.6.0",
53
- "agent-messenger": "^2.29.0",
53
+ "agent-messenger": "^2.29.1",
54
54
  "cheerio": "^1.2.0",
55
55
  "citty": "^0.2.2",
56
56
  "cron-parser": "^5.5.0",
@@ -716,6 +716,98 @@
716
716
  "accounts"
717
717
  ]
718
718
  },
719
+ "teams": {
720
+ "type": "object",
721
+ "properties": {
722
+ "currentAccount": {
723
+ "anyOf": [
724
+ {
725
+ "type": "string"
726
+ },
727
+ {
728
+ "type": "null"
729
+ }
730
+ ]
731
+ },
732
+ "accounts": {
733
+ "type": "object",
734
+ "propertyNames": {
735
+ "type": "string"
736
+ },
737
+ "additionalProperties": {
738
+ "type": "object",
739
+ "properties": {
740
+ "account_id": {
741
+ "type": "string"
742
+ },
743
+ "access_token": {
744
+ "type": "string"
745
+ },
746
+ "token_expires_at": {
747
+ "type": "string"
748
+ },
749
+ "account_type": {
750
+ "anyOf": [
751
+ {
752
+ "type": "string",
753
+ "const": "work"
754
+ },
755
+ {
756
+ "type": "string",
757
+ "const": "personal"
758
+ }
759
+ ]
760
+ },
761
+ "region": {
762
+ "anyOf": [
763
+ {
764
+ "type": "string",
765
+ "const": "amer"
766
+ },
767
+ {
768
+ "type": "string",
769
+ "const": "emea"
770
+ },
771
+ {
772
+ "type": "string",
773
+ "const": "apac"
774
+ }
775
+ ]
776
+ },
777
+ "user_name": {
778
+ "type": "string"
779
+ },
780
+ "aad_refresh_token": {
781
+ "type": "string"
782
+ },
783
+ "aad_client_id": {
784
+ "type": "string"
785
+ },
786
+ "aad_tenant_id": {
787
+ "type": "string"
788
+ },
789
+ "created_at": {
790
+ "type": "string"
791
+ },
792
+ "updated_at": {
793
+ "type": "string"
794
+ }
795
+ },
796
+ "required": [
797
+ "account_id",
798
+ "access_token",
799
+ "account_type",
800
+ "created_at",
801
+ "updated_at"
802
+ ]
803
+ }
804
+ }
805
+ },
806
+ "required": [
807
+ "currentAccount",
808
+ "accounts"
809
+ ]
810
+ },
719
811
  "slack": {
720
812
  "type": "object",
721
813
  "properties": {
@@ -72,7 +72,7 @@ import {
72
72
  import { attachToolNotFoundNudge } from './tool-not-found-nudge'
73
73
  import { createBudgetState, type ToolResultBudget, wrapToolDefinitionWithBudget } from './tool-result-budget'
74
74
  import { createChannelDisengageTool } from './tools/channel-disengage'
75
- import { createChannelFetchAttachmentTool } from './tools/channel-fetch-attachment'
75
+ import { createChannelFetchAttachmentTool, resolveInboxBaseDir } from './tools/channel-fetch-attachment'
76
76
  import { createChannelHistoryTool } from './tools/channel-history'
77
77
  import { createChannelReactTool } from './tools/channel-react'
78
78
  import { createChannelReadTool } from './tools/channel-read'
@@ -390,7 +390,14 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
390
390
  ...(options.mcpManager ? buildMcpDispatcherToolDefinitions(options.mcpManager) : []),
391
391
  ...(options.reloadRegistry ? [createReloadTool({ registry: options.reloadRegistry })] : []),
392
392
  ...(options.stream ? [createStreamSnapshotTool({ stream: options.stream })] : []),
393
- ...buildChannelTools(options.channelRouter, options.origin, sessionManager.getSessionId(), getOrigin),
393
+ ...buildChannelTools(
394
+ options.channelRouter,
395
+ options.origin,
396
+ sessionManager.getSessionId(),
397
+ getOrigin,
398
+ options.permissions,
399
+ options.plugins?.agentDir,
400
+ ),
394
401
  ...(options.containerName
395
402
  ? [
396
403
  createRestartTool({
@@ -669,6 +676,8 @@ export function buildChannelTools(
669
676
  origin: SessionOrigin | undefined,
670
677
  sessionId?: string,
671
678
  getOrigin?: () => SessionOrigin | undefined,
679
+ permissions?: PermissionService,
680
+ agentDir?: string,
672
681
  ): ToolDefinition[] {
673
682
  if (!channelRouter) return []
674
683
  const tools: ToolDefinition[] = []
@@ -713,6 +722,9 @@ export function buildChannelTools(
713
722
  createChannelFetchAttachmentTool({
714
723
  router: channelRouter,
715
724
  origin: channelOrigin,
725
+ ...(permissions !== undefined && agentDir !== undefined
726
+ ? { resolveBaseDir: () => resolveInboxBaseDir(permissions, getOrigin?.() ?? origin, agentDir) }
727
+ : {}),
716
728
  }),
717
729
  )
718
730
  tools.push(createChannelLookAtTool(channelRouter, channelOrigin))
@@ -9,6 +9,7 @@ import type { ChannelRouter } from '@/channels/router'
9
9
  import type { AdapterId } from '@/channels/schema'
10
10
  import { getConfig, resolveModel, resolveProfile } from '@/config'
11
11
  import { providerForModelRef } from '@/config/providers'
12
+ import { LLM_FETCH_OBSERVER_TIMEOUTS, type LlmFetchObservedRequestInit } from '@/run/llm-fetch-observer'
12
13
  import { SecretsBackend } from '@/secrets'
13
14
 
14
15
  import { buildMultimodalLookerSystemPrompt, resolveImage, type ImageInput } from './looker'
@@ -207,6 +208,21 @@ const GLM_VISION_MODEL = 'glm-4.6v'
207
208
  const GLM_VISION_ENDPOINT = 'https://api.z.ai/api/coding/paas/v4/chat/completions'
208
209
  const GLM_VISION_MAX_TOKENS = 32768
209
210
 
211
+ // Vision requests carry a base64 image body the server must decode before it can
212
+ // send response headers, so the observer's 15s default TTFB (tuned for ~1s text
213
+ // completions) is too tight and flakes on cold connections. 45s is 3x the
214
+ // observed-under-load window; env-overridable for operators who need more.
215
+ export const GLM_VISION_TTFB_MS = 45_000
216
+ const ENV_GLM_VISION_TTFB_MS = 'TYPECLAW_GLM_VISION_TTFB_MS'
217
+
218
+ export function resolveGlmVisionTtfbMs(env: NodeJS.ProcessEnv = process.env): number {
219
+ const raw = env[ENV_GLM_VISION_TTFB_MS]
220
+ if (raw === undefined || raw === '') return GLM_VISION_TTFB_MS
221
+ const parsed = Number.parseInt(raw, 10)
222
+ if (!Number.isFinite(parsed) || parsed < 0) return GLM_VISION_TTFB_MS
223
+ return parsed
224
+ }
225
+
210
226
  function shouldUseGlmCodingPlanVision(): boolean {
211
227
  const ref = resolveProfile(getConfig().models, 'vision').ref
212
228
  return providerForModelRef(ref) === GLM_VISION_PROVIDER && !resolveModel(ref).input.includes('image')
@@ -219,17 +235,19 @@ async function analyzeWithGlmCodingPlanVision(imageContents: ImageContent[], pro
219
235
  return errorResult('GLM Coding Plan vision unavailable: no zai-coding API key', details)
220
236
  }
221
237
 
238
+ const requestInit: LlmFetchObservedRequestInit = {
239
+ method: 'POST',
240
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
241
+ body: JSON.stringify({
242
+ model: GLM_VISION_MODEL,
243
+ max_tokens: GLM_VISION_MAX_TOKENS,
244
+ messages: buildGlmVisionMessages(imageContents, prompt),
245
+ }),
246
+ [LLM_FETCH_OBSERVER_TIMEOUTS]: { ttfbMs: resolveGlmVisionTtfbMs() },
247
+ }
222
248
  let response: Response
223
249
  try {
224
- response = await fetch(GLM_VISION_ENDPOINT, {
225
- method: 'POST',
226
- headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
227
- body: JSON.stringify({
228
- model: GLM_VISION_MODEL,
229
- max_tokens: GLM_VISION_MAX_TOKENS,
230
- messages: buildGlmVisionMessages(imageContents, prompt),
231
- }),
232
- })
250
+ response = await fetch(GLM_VISION_ENDPOINT, requestInit)
233
251
  } catch (error) {
234
252
  return errorResult(`GLM vision request failed: ${error instanceof Error ? error.message : String(error)}`, details)
235
253
  }
@@ -619,7 +619,12 @@ async function applyBashSandbox(
619
619
  { type: 'bind', source: sessionTmp, dest: '/tmp' },
620
620
  ],
621
621
  ...(packageInstall !== undefined
622
- ? { writableRoot: { dir: packageInstall.root }, masks: maskTargets, protected: packageInstall.protected }
622
+ ? {
623
+ writableRoot: { dir: packageInstall.root },
624
+ masks: maskTargets,
625
+ protected: packageInstall.protected,
626
+ blockedCreation: { files: packageInstall.blockedCreation },
627
+ }
623
628
  : { masks: maskTargets, writable, protected: protectedZones }),
624
629
  symlinks,
625
630
  network: 'inherit',
@@ -652,11 +657,11 @@ function buildRoleScopedConfigEnv(
652
657
  }
653
658
 
654
659
  function subtractMaskedProtected(
655
- zones: { root: string; protected: { dirs: string[]; files: string[] } },
660
+ zones: { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] },
656
661
  masked: { dirs: string[]; files: string[] },
657
- ): { root: string; protected: { dirs: string[]; files: string[] } } {
662
+ ): { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] } {
658
663
  const filtered = subtractMasked(zones.protected, masked)
659
- return { root: zones.root, protected: filtered }
664
+ return { root: zones.root, protected: filtered, blockedCreation: zones.blockedCreation }
660
665
  }
661
666
 
662
667
  // Picks the /proc strategy for a sandboxed bash call. The branch order is:
@@ -162,6 +162,7 @@ const PLATFORM_INFO: Record<AdapterId, PlatformInfo> = {
162
162
  },
163
163
  webex: { displayName: 'Webex', mentionMode: 'angle-id', supportsReactions: false, supportsAttachments: true },
164
164
  'webex-bot': { displayName: 'Webex', mentionMode: 'angle-id', supportsReactions: false, supportsAttachments: false },
165
+ teams: { displayName: 'Teams', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
165
166
  line: { displayName: 'LINE', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
166
167
  kakaotalk: { displayName: 'KakaoTalk', mentionMode: 'alias', supportsReactions: false, supportsAttachments: true },
167
168
  }
@@ -1,11 +1,14 @@
1
1
  import { mkdir, writeFile } from 'node:fs/promises'
2
- import { join } from 'node:path'
2
+ import { join, sep } from 'node:path'
3
3
 
4
4
  import { Type } from '@mariozechner/pi-ai'
5
5
  import { defineTool } from '@mariozechner/pi-coding-agent'
6
6
 
7
+ import type { SessionOrigin } from '@/agent/session-origin'
7
8
  import type { ChannelRouter } from '@/channels/router'
8
9
  import type { AdapterId } from '@/channels/schema'
10
+ import type { PermissionService } from '@/permissions'
11
+ import { resolveHiddenPaths } from '@/sandbox'
9
12
 
10
13
  import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
11
14
 
@@ -20,24 +23,37 @@ export type CreateChannelFetchAttachmentToolOptions = {
20
23
  router: ChannelRouter
21
24
  origin: ChannelFetchAttachmentOrigin
22
25
  inboxDir?: string
26
+ // Resolved at execute time (role is a property of the live origin, not of
27
+ // construction), and wins over inboxDir/DEFAULT_INBOX_DIR. Lets the save
28
+ // location follow the caller's role so a role hidden from workspace/ never
29
+ // gets a file it can write but not read back (privateSurfaceRead would block
30
+ // its follow-up look_at/read). See buildChannelTools for the decision.
31
+ resolveBaseDir?: () => string
23
32
  logger?: ChannelToolLogger
24
33
  }
25
34
 
35
+ // workspace/ is private-surface: readable only by roles with fs.see.private.
26
36
  export const DEFAULT_INBOX_DIR = '/agent/workspace/inbox'
37
+ // public/ is the guest-visible counterpart, so a redirected file stays readable
38
+ // back through look_at/read by the same role that fetched it.
39
+ export const PUBLIC_INBOX_DIR = '/agent/public/inbox'
27
40
 
28
41
  export function createChannelFetchAttachmentTool({
29
42
  router,
30
43
  origin,
31
44
  inboxDir,
45
+ resolveBaseDir,
32
46
  logger = consoleChannelLogger,
33
47
  }: CreateChannelFetchAttachmentToolOptions) {
34
- const baseDir = inboxDir ?? DEFAULT_INBOX_DIR
48
+ const fallbackBaseDir = inboxDir ?? DEFAULT_INBOX_DIR
35
49
  const adapter = origin.adapter
36
50
  return defineTool({
37
51
  name: 'channel_fetch_attachment',
38
52
  label: 'Channel Fetch Attachment',
39
53
  description:
40
- 'Download a file attached to a channel message and save it to disk. Inbound channel ' +
54
+ 'Download a file attached to a channel message and save it to disk. Use this only when you need the ' +
55
+ 'file ON DISK (to edit it, re-upload it, or run a tool over it); to simply VIEW an image, use ' +
56
+ '`look_at_channel_attachment` instead — it returns a description without a disk write. Inbound channel ' +
41
57
  'messages with attachments show `[<Platform> attachment #N: <kind> <metadata>]` in the text. Pass `N` as ' +
42
58
  '`attachment_id`; do not invent ids that are not present in the message. The router resolves the private ' +
43
59
  'platform ref itself. Attachments on the CURRENT inbound message resolve directly; for one from an EARLIER ' +
@@ -102,6 +118,7 @@ export function createChannelFetchAttachmentTool({
102
118
 
103
119
  const safeFilename = sanitizeFilename(result.filename)
104
120
  const refSlug = sanitizeRefSlug(ref)
121
+ const baseDir = resolveBaseDir?.() ?? fallbackBaseDir
105
122
  const targetDir = join(baseDir, adapter, refSlug)
106
123
  const targetPath = join(targetDir, safeFilename)
107
124
  try {
@@ -128,6 +145,31 @@ export function createChannelFetchAttachmentTool({
128
145
  })
129
146
  }
130
147
 
148
+ // Picks the inbox root for the caller's live role. Reuses the guard's own
149
+ // deny-list resolution (resolveHiddenPaths) as the single source of truth, so
150
+ // the save location can never drift out of sync with what privateSurfaceRead
151
+ // will let the same role read back: if workspace/inbox lands under a hidden dir
152
+ // the file goes to the guest-visible public/ inbox instead.
153
+ //
154
+ // The hidden-check joins with the OS-native separator to stay byte-identical to
155
+ // resolveHiddenPaths' own dirs, but the RETURNED path is normalized to POSIX:
156
+ // this value names a location inside the Linux container (agentDir is /agent),
157
+ // so a win32 CI host must not leak backslashes into it.
158
+ export function resolveInboxBaseDir(
159
+ permissions: PermissionService,
160
+ origin: SessionOrigin | undefined,
161
+ agentDir: string,
162
+ ): string {
163
+ const privateInbox = join(agentDir, 'workspace', 'inbox')
164
+ const { dirs } = resolveHiddenPaths(permissions, origin, agentDir)
165
+ const hidden = dirs.some((dir) => privateInbox === dir || privateInbox.startsWith(`${dir}${sep}`))
166
+ return toPosix(hidden ? join(agentDir, 'public', 'inbox') : privateInbox)
167
+ }
168
+
169
+ function toPosix(p: string): string {
170
+ return p.split(sep).join('/')
171
+ }
172
+
131
173
  function errorResult(message: string) {
132
174
  const details = { ok: false, error: message }
133
175
  return { content: [{ type: 'text' as const, text: `channel_fetch_attachment error: ${message}` }], details }
@@ -210,15 +210,22 @@ export function createChannelReplyTool({
210
210
  // flag fixes). Resolve-failure blocks the reply so the agent never posts
211
211
  // a "looks resolved" ack next to a still-open thread; the router enforces
212
212
  // that only the bot's own threads can be resolved.
213
+ let resolveMissNotice: string | null = null
213
214
  if (params.resolve_review_thread === true) {
214
- const resolveError = await resolveReviewThreadBeforeReply(router, origin)
215
- if (resolveError !== null) {
216
- logger.warn(formatChannelToolFailure('channel_reply', resolveError))
215
+ const resolve = await resolveReviewThreadBeforeReply(router, origin)
216
+ if (resolve.kind === 'block') {
217
+ logger.warn(formatChannelToolFailure('channel_reply', resolve.error))
217
218
  return {
218
- content: [{ type: 'text' as const, text: `channel_reply denied: ${resolveError}` }],
219
- details: { ok: false, error: resolveError },
219
+ content: [{ type: 'text' as const, text: `channel_reply denied: ${resolve.error}` }],
220
+ details: { ok: false, error: resolve.error },
220
221
  }
221
222
  }
223
+ // `no-match` stays non-blocking (the thread may be genuinely gone) but
224
+ // the resolve did NOT run, so tell the model instead of posting a clean
225
+ // receipt that hides the miss. Mirrors channel_send.
226
+ if (resolve.kind === 'no-match') {
227
+ resolveMissNotice = resolveMissHint(origin.thread)
228
+ }
222
229
  }
223
230
 
224
231
  const result = await router.send({
@@ -287,8 +294,9 @@ export function createChannelReplyTool({
287
294
  // intentionally weaker and is safe ONLY because denials carry no echoed
288
295
  // prose; the success result does, and the weak prefix let Kimi loop.
289
296
  const warnNote = falseReceiptNotice !== null ? fenceRuntimeNotice(falseReceiptNotice) : ''
297
+ const missNote = resolveMissNotice ?? ''
290
298
  return {
291
- content: [{ type: 'text' as const, text: `${fenceToolResult(receipt)}${hint}${warnNote}` }],
299
+ content: [{ type: 'text' as const, text: `${fenceToolResult(receipt)}${hint}${warnNote}${missNote}` }],
292
300
  details,
293
301
  }
294
302
  }
@@ -324,21 +332,25 @@ function missingReviewThreadResolveChoiceError(input: {
324
332
  )
325
333
  }
326
334
 
327
- // Returns an error string when the resolve should block the reply, or null
328
- // when it's safe to proceed. Only `no-match` (the thread is already gone, so
329
- // there's nothing to close) joins success as non-blocking; every hard failure
330
- // — wrong author, permission denial, HTTP 404 on a misdirected lookup,
331
- // transient API error — blocks, so the agent never claims a thread is settled
332
- // when the resolve did not actually run.
335
+ // `block` when the resolve should stop the reply, `no-match` when the thread is
336
+ // gone (non-blocking — the reply posts but the caller warns), `resolved` on
337
+ // success. Every hard failure — wrong author, permission denial, HTTP 404 on a
338
+ // misdirected lookup, transient API error — blocks, so the agent never claims a
339
+ // thread is settled when the resolve did not actually run.
340
+ type ResolveOutcome = { kind: 'resolved' } | { kind: 'no-match' } | { kind: 'block'; error: string }
341
+
333
342
  async function resolveReviewThreadBeforeReply(
334
343
  router: ChannelRouter,
335
344
  origin: ChannelReplyOrigin,
336
- ): Promise<string | null> {
345
+ ): Promise<ResolveOutcome> {
337
346
  if (origin.adapter !== 'github') {
338
- return 'resolve_review_thread is only supported on github sessions.'
347
+ return { kind: 'block', error: 'resolve_review_thread is only supported on github sessions.' }
339
348
  }
340
349
  if (origin.thread === null) {
341
- return 'resolve_review_thread requires replying inside a review thread (no thread on this origin).'
350
+ return {
351
+ kind: 'block',
352
+ error: 'resolve_review_thread requires replying inside a review thread (no thread on this origin).',
353
+ }
342
354
  }
343
355
  const result = await router.resolveReviewThread({
344
356
  adapter: origin.adapter,
@@ -346,9 +358,20 @@ async function resolveReviewThreadBeforeReply(
346
358
  chat: origin.chat,
347
359
  rootCommentId: origin.thread,
348
360
  })
349
- if (result.ok) return null
350
- if (result.code === 'no-match') return null
351
- return `could not resolve review thread: ${result.error}`
361
+ if (result.ok) return { kind: 'resolved' }
362
+ if (result.code === 'no-match') return { kind: 'no-match' }
363
+ return { kind: 'block', error: `could not resolve review thread: ${result.error}` }
364
+ }
365
+
366
+ // The model asked to resolve but no thread was rooted at this comment. Fenced
367
+ // as a runtime notice (not chat prose) so a persona-rich model reads it as
368
+ // tool feedback and re-targets, rather than replying to it in-character.
369
+ function resolveMissHint(thread: string | null): string {
370
+ return fenceRuntimeNotice(
371
+ `you set resolve_review_thread but no unresolved review thread is rooted at comment ${JSON.stringify(thread)} — ` +
372
+ `your reply posted, but that thread was not resolved (it may be already gone, or the thread id is stale). ` +
373
+ `If a thread should still close, resolve it on the correct thread.`,
374
+ )
352
375
  }
353
376
 
354
377
  // Tool results reach the model as USER-role messages (OpenAI / Anthropic