typeclaw 0.48.11 → 0.48.13

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 (94) hide show
  1. package/package.json +7 -4
  2. package/src/agent/attention-escalation.ts +8 -5
  3. package/src/agent/auth-reloadable.ts +2 -3
  4. package/src/agent/auth.ts +59 -79
  5. package/src/agent/compaction.ts +2 -2
  6. package/src/agent/index.ts +42 -16
  7. package/src/agent/llm-replay-sanitizer.ts +1 -1
  8. package/src/agent/model-overrides.ts +1 -1
  9. package/src/agent/multimodal/look-at.ts +3 -3
  10. package/src/agent/multimodal/read-redirect.ts +1 -1
  11. package/src/agent/plugin-tools.ts +26 -31
  12. package/src/agent/reload-tool.ts +1 -1
  13. package/src/agent/subagents.ts +1 -1
  14. package/src/agent/tool-error-remediation.ts +1 -1
  15. package/src/agent/tool-result-budget.ts +2 -2
  16. package/src/agent/tools/channel-disengage.ts +2 -2
  17. package/src/agent/tools/channel-edit.ts +2 -2
  18. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  19. package/src/agent/tools/channel-history.ts +2 -2
  20. package/src/agent/tools/channel-react.ts +2 -2
  21. package/src/agent/tools/channel-read.ts +2 -2
  22. package/src/agent/tools/channel-reply.ts +2 -2
  23. package/src/agent/tools/channel-send.ts +2 -2
  24. package/src/agent/tools/grant-role.ts +2 -2
  25. package/src/agent/tools/post-github-review.ts +2 -2
  26. package/src/agent/tools/restart.ts +2 -2
  27. package/src/agent/tools/skip-response.ts +2 -2
  28. package/src/agent/tools/spawn-subagent.ts +2 -2
  29. package/src/agent/tools/stream-snapshot.ts +2 -2
  30. package/src/agent/tools/subagent-cancel.ts +2 -2
  31. package/src/agent/tools/subagent-output.ts +2 -2
  32. package/src/agent/tools/todo/index.ts +2 -2
  33. package/src/agent/tools/webfetch/tool.ts +2 -2
  34. package/src/agent/tools/websearch.ts +2 -2
  35. package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  36. package/src/bundled-plugins/github-cli-auth/index.ts +1 -1
  37. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  38. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  39. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  40. package/src/channels/adapters/kakaotalk.ts +7 -8
  41. package/src/channels/adapters/teams-classify.ts +21 -0
  42. package/src/channels/adapters/teams-edit.ts +2 -1
  43. package/src/channels/adapters/teams-format.ts +16 -0
  44. package/src/channels/adapters/teams.ts +12 -5
  45. package/src/channels/github-review-verdict-coordinator.ts +26 -3
  46. package/src/channels/router.ts +50 -25
  47. package/src/cli/compose.ts +3 -3
  48. package/src/cli/docker-preflight.ts +8 -4
  49. package/src/cli/model.ts +7 -5
  50. package/src/cli/oauth-callbacks.ts +38 -23
  51. package/src/cli/restart.ts +89 -23
  52. package/src/cli/start.ts +68 -16
  53. package/src/cli/status.ts +38 -6
  54. package/src/cli/stop.ts +5 -2
  55. package/src/compose/stop.ts +5 -4
  56. package/src/config/config.ts +62 -25
  57. package/src/config/providers.ts +272 -47
  58. package/src/container/build-cache.ts +807 -0
  59. package/src/container/compose-project.ts +4 -0
  60. package/src/container/docker-app.ts +74 -0
  61. package/src/container/log-archive.ts +33 -5
  62. package/src/container/memory-limit.ts +80 -0
  63. package/src/container/memory-oversubscription.ts +125 -0
  64. package/src/container/restart.ts +6 -1
  65. package/src/container/shared.ts +43 -16
  66. package/src/container/start.ts +280 -53
  67. package/src/container/stop.ts +19 -13
  68. package/src/container/verify-running.ts +12 -0
  69. package/src/cron/scheduler.ts +12 -4
  70. package/src/doctor/bounded-exec.ts +14 -0
  71. package/src/doctor/checks.ts +40 -15
  72. package/src/doctor/index.ts +14 -2
  73. package/src/doctor/plugin-bridge.ts +15 -3
  74. package/src/hostd/paths.ts +4 -0
  75. package/src/init/index.ts +4 -4
  76. package/src/init/oauth-login.ts +57 -17
  77. package/src/inspect/transcript-view.ts +6 -3
  78. package/src/run/channel-session-factory.ts +5 -4
  79. package/src/run/index.ts +27 -11
  80. package/src/run/resource-sample.ts +171 -0
  81. package/src/sandbox/index.ts +8 -1
  82. package/src/sandbox/session-tmp.ts +26 -1
  83. package/src/secrets/refresh-provider-oauth.ts +30 -76
  84. package/src/secrets/schema.ts +3 -4
  85. package/src/secrets/storage.ts +133 -234
  86. package/src/server/index.ts +1 -1
  87. package/src/sessions/index.ts +1 -1
  88. package/src/skills/typeclaw-config/SKILL.md +4 -4
  89. package/src/skills/typeclaw-plugins/SKILL.md +5 -5
  90. package/src/tui/index.ts +5 -3
  91. package/src/tui/theme.ts +1 -1
  92. package/typeclaw.schema.json +32 -1
  93. package/src/agent/adaptive-thinking-compat.ts +0 -79
  94. package/src/secrets/oauth-xai.ts +0 -348
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { checkCompletionClaim } from '@/channels/completion-claim'
5
5
  import { checkFalseReceipt } from '@/channels/github-false-receipt'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { checkFalseReceipt } from '@/channels/github-false-receipt'
5
5
  import { evaluateRereviewGuard } from '@/channels/github-rereview-guard'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { MEMBERSHIP_FRESHNESS_MS, type MembershipCount } from '@/channels/membership'
5
5
  import {
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { recordReview, recordReviewOutput, type ReviewVerdict } from '@/channels/github-review-turn-ledger'
5
5
  import { createSharedReviewVerdictGuard, type ReviewVerdictGuard } from '@/channels/github-review-verdict-coordinator'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { requestContainerRestart } from '@/agent/restart'
5
5
  import type { RestartHandoffOrigin } from '@/agent/restart-handoff'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { ChannelRouter } from '@/channels/router'
5
5
 
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
 
3
- import { Type } from '@mariozechner/pi-ai'
4
- import { defineTool } from '@mariozechner/pi-coding-agent'
3
+ import { Type } from '@earendil-works/pi-ai'
4
+ import { defineTool } from '@earendil-works/pi-coding-agent'
5
5
 
6
6
  import { githubReviewerWorkKey } from '@/channels/github-repo'
7
7
  import type { PermissionService } from '@/permissions'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { formatLocalDateTime } from '@/shared'
5
5
  import type { ScanFilter, Stream, StreamMessage, TargetFilter } from '@/stream'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { PermissionService } from '@/permissions'
5
5
 
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { PermissionService } from '@/permissions'
5
5
 
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { SessionOrigin } from '@/agent/session-origin'
5
5
  import { resolveTodoScope, type TodoScope } from '@/agent/todo/scope'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { extractAdaptiveHtml, validateAdaptiveHtmlComplexity } from './adaptive-html'
5
5
  import { fetchWithLimits, normalizeUrl, parseMimeType, WebFetchError } from './fetch'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import { CurlImpersonateError, isCurlExitTimeout } from './curl-impersonate'
5
5
  import { ddgSearch, DdgCaptchaError, type DdgResult } from './ddg'
@@ -11,6 +11,7 @@ export type GhBlockCode =
11
11
  | 'repo-selector-conflict'
12
12
  | 'credential-display'
13
13
  | 'credential-exposure'
14
+ | 'pathname-expansion'
14
15
 
15
16
  export type GhCommandDecision =
16
17
  | { kind: 'pass-through' }
@@ -59,6 +60,11 @@ const CREDENTIAL_DISPLAY_REASON =
59
60
  'In particular, `gh auth token` and `gh auth status --show-token` would print the command-scoped credential. ' +
60
61
  'Use host-side authentication setup or a redacted diagnostic instead.'
61
62
 
63
+ const PATHNAME_EXPANSION_REASON =
64
+ 'An unquoted `*`, `?`, or `[` in a gh command is a shell pathname pattern: the shell could expand it into ' +
65
+ 'different arguments than the ones TypeClaw authorized, so no credential is minted for it. ' +
66
+ "Quote the argument that contains it, e.g. `gh api '/repos/owner/repo/contents/path?ref=<sha>'`."
67
+
62
68
  const CREDENTIAL_EXPOSURE_REASON =
63
69
  'This gh command is not in TypeClaw’s credential-safe allowlist. Model-driven gh receives a command-scoped credential only for operations whose argv cannot read arbitrary files, render process environment values, upload arbitrary files, select another host, or start extensions. Use a supported direct gh operation, a first-class TypeClaw tool, or run this command host-side.'
64
70
 
@@ -194,7 +200,7 @@ export function analyzeGhCommand(command: string, fallbackRepo?: string): GhComm
194
200
  const ghStarts = findGhInvocations(tokens)
195
201
  if (ghStarts.length === 0) return { kind: 'pass-through' }
196
202
  if (containsUnquotedPathnameExpansion(command)) {
197
- return { kind: 'block', code: 'credential-exposure', reason: CREDENTIAL_EXPOSURE_REASON }
203
+ return { kind: 'block', code: 'pathname-expansion', reason: PATHNAME_EXPANSION_REASON }
198
204
  }
199
205
 
200
206
  for (let i = 0; i < ghStarts.length; i++) {
@@ -311,7 +311,7 @@ export default definePlugin({
311
311
  return {
312
312
  block: true,
313
313
  reason:
314
- decision.code === 'credential-display'
314
+ decision.code === 'credential-display' || decision.code === 'pathname-expansion'
315
315
  ? decision.reason
316
316
  : decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo, command),
317
317
  }
@@ -80,7 +80,15 @@ export async function prepareReviewerCheckout(options: {
80
80
  ],
81
81
  { env: baseEnv },
82
82
  )
83
- return { path: checkout, repoSlug: options.repoSlug, headSha: options.headSha.toLocaleLowerCase() }
83
+ // The checkout lives in the session's `/tmp` backing dir, but the model only
84
+ // ever sees that dir AS `/tmp` (bwrap binds it there; file tools re-map
85
+ // `/tmp/*` into it). Returning the backing path would be re-mapped a second
86
+ // time and never resolve, so hand back the model-facing path.
87
+ return {
88
+ path: path.posix.join('/tmp', path.basename(checkout)),
89
+ repoSlug: options.repoSlug,
90
+ headSha: options.headSha.toLocaleLowerCase(),
91
+ }
84
92
  } catch (error) {
85
93
  await rm(checkout, { recursive: true, force: true }).catch(() => {})
86
94
  throw error
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises'
4
- import { basename, join } from 'node:path'
4
+ import { basename, dirname, join } from 'node:path'
5
5
 
6
6
  import { z } from 'zod'
7
7
 
@@ -33,6 +33,7 @@ import { loadAllReferences, type Reference } from './references/load-references'
33
33
  import { captureShardSnapshot, restoreShardSnapshot } from './shard-snapshot'
34
34
  import type { StreamEvent } from './stream-events'
35
35
  import { readEvents, writeEventsAtomic } from './stream-io'
36
+ import { VECTOR_INDEX_REL_PATH } from './vector/doctor'
36
37
  import { embed, EMBEDDING_MODEL_ID } from './vector/embedder'
37
38
  import type { EmbedFn } from './vector/hybrid'
38
39
  import { topicPassage } from './vector/passages'
@@ -734,7 +735,17 @@ function isEnoent(err: unknown): boolean {
734
735
  return typeof err === 'object' && err !== null && 'code' in err && err.code === 'ENOENT'
735
736
  }
736
737
 
737
- const SNAPSHOT_PATHS = ['memory/'] as const
738
+ // The vector index is generated, rebuildable cache state, not durable memory.
739
+ // Keep force-adding the broad memory/ root so new durable artifact types are
740
+ // snapshotted automatically, while Git's exclusion pathspec keeps the SQLite
741
+ // DB and its WAL/SHM sidecars out of history.
742
+ const EXCLUDE_PATHSPEC_PREFIX = ':(exclude)'
743
+ const VECTOR_INDEX_DIRECTORY_REL_PATH = dirname(VECTOR_INDEX_REL_PATH)
744
+ const SNAPSHOT_PATHS = ['memory/', `${EXCLUDE_PATHSPEC_PREFIX}${VECTOR_INDEX_DIRECTORY_REL_PATH}/`] as const
745
+
746
+ function isSnapshotExclusionPathspec(pathspec: string): boolean {
747
+ return pathspec.startsWith(EXCLUDE_PATHSPEC_PREFIX)
748
+ }
738
749
 
739
750
  async function ensureMemoryFiles(agentDir: string): Promise<void> {
740
751
  const memoryDir = join(agentDir, 'memory')
@@ -767,10 +778,14 @@ async function commitMemorySnapshotUnlocked(cwd: string): Promise<void> {
767
778
 
768
779
  await clearSkipWorktree(bun, cwd, repo)
769
780
 
770
- // `git add -- foo bar/` fails with exit 128 if any pathspec matches no
771
- // path on disk. Filter to existing paths before passing them in.
772
- const presentPaths = SNAPSHOT_PATHS.filter((p) => existsSync(join(cwd, p)))
773
- if (presentPaths.length === 0) {
781
+ // `git add -- foo bar/` fails with exit 128 if any ordinary pathspec matches
782
+ // no path on disk. Keep exclusion pathspecs: they are Git syntax rather than
783
+ // filesystem paths, and must accompany the broad memory/ root everywhere it
784
+ // flows. Still return early when no ordinary root is present, so an exclusion
785
+ // by itself never reaches `git add`.
786
+ const presentPaths = SNAPSHOT_PATHS.filter((p) => isSnapshotExclusionPathspec(p) || existsSync(join(cwd, p)))
787
+ const hasPresentSnapshotRoot = presentPaths.some((p) => !isSnapshotExclusionPathspec(p))
788
+ if (!hasPresentSnapshotRoot) {
774
789
  await applySkipWorktree(bun, cwd, repo)
775
790
  return
776
791
  }
@@ -1,4 +1,10 @@
1
- import { classifyKakaoChat, type KakaoChat, type KakaoChatKind, type KakaoTalkClient } from 'agent-messenger/kakaotalk'
1
+ import {
2
+ classifyKakaoChat,
3
+ type KakaoChat,
4
+ type KakaoChatKind,
5
+ type KakaoMember,
6
+ type KakaoTalkClient,
7
+ } from 'agent-messenger/kakaotalk'
2
8
 
3
9
  import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
4
10
 
@@ -17,16 +23,51 @@ export function kakaoWorkspaceForType(kind: KakaoChatKind): KakaoWorkspace {
17
23
  export type KakaoChatLookupValue = {
18
24
  workspace: KakaoWorkspace
19
25
  isDm: boolean
20
- // True while the entry is a placeholder from `ingestProvisional` (a chat seen
21
- // on an inbound push but not yet surfaced by getChats). Its `workspace` is a
22
- // strict-bucket guess (@kakao-group), NOT the authoritative kind. Callers that
26
+ // True while the entry is a strict fallback guess (@kakao-group) — the chat
27
+ // is absent from getChats and its member roster proved nothing. Callers that
23
28
  // must know the real type decide per-feature: typing sends for provisional
24
29
  // entries (the @kakao-group guess is never @kakao-open, and a mis-guessed
25
30
  // OpenChat's linkless ACTION fails soft), while allow-rule enforcement keeps
26
- // treating the strict bucket as authoritative until a real refresh upgrades it.
31
+ // treating the strict bucket as authoritative until a real refresh upgrades
32
+ // it.
27
33
  provisional: boolean
28
34
  }
29
35
 
36
+ // What a member roster PROVES about a chat — never what it merely suggests.
37
+ //
38
+ // A roster read is only ever a SUBSET of the true membership: `getMembers`
39
+ // merges GETMEM with a CHATONROOM fallback whose failure it swallows, and that
40
+ // fallback can itself yield just `displayMembers`. So only conclusions that
41
+ // survive adding unseen members are sound:
42
+ //
43
+ // - an open marker present proves OpenChat — a subset cannot invent one
44
+ // (`open_token` / `open_profile_link_id` / `open_permission` are
45
+ // SDK-populated for OpenChat rooms only)
46
+ // - two or more counterparts proves not-a-DM — adding members keeps it true
47
+ //
48
+ // "Exactly one counterpart" proves NOTHING, because the remainder may simply be
49
+ // unobserved. So a DM is never inferred here; callers keep the strict bucket.
50
+ // Do NOT "restore" a `others.length <= 1 -> dm` branch: a truncated roster for a
51
+ // large room would then be cached as an authoritative DM, relaxing both the
52
+ // engagement ladder and `kakao:dm/*` allow-rule matching.
53
+ export function provenKindFromMembers(
54
+ members: readonly KakaoChatMemberSignal[],
55
+ selfUserId: string | null,
56
+ ): Extract<KakaoChatKind, 'open' | 'group'> | null {
57
+ if (members.some(isOpenChatMember)) return 'open'
58
+ const others = members.filter((member) => member.user_id !== selfUserId)
59
+ return others.length >= 2 ? 'group' : null
60
+ }
61
+
62
+ export type KakaoChatMemberSignal = Pick<
63
+ KakaoMember,
64
+ 'user_id' | 'open_token' | 'open_profile_link_id' | 'open_permission'
65
+ >
66
+
67
+ function isOpenChatMember(member: KakaoChatMemberSignal): boolean {
68
+ return member.open_token !== null || member.open_profile_link_id !== null || member.open_permission !== null
69
+ }
70
+
30
71
  export type KakaoChannelResolver = {
31
72
  resolve: ChannelNameResolver
32
73
  lookupChat: (chatId: string) => KakaoChatLookupValue | null
@@ -34,18 +75,20 @@ export type KakaoChannelResolver = {
34
75
  // Register a chat we learned about from an inbound push event, used as a
35
76
  // fallback when `refresh()` did not surface it (e.g. memo chats, certain
36
77
  // open chats, or chats whose membership has not yet propagated to
37
- // getChats({all:true})). Provisional entries default to @kakao-group —
38
- // the strictest bucket, matching the history callback's existing fallback
39
- // — so allow-rule enforcement stays strict. A subsequent real refresh
40
- // upgrades the entry to its authoritative kind.
41
- ingestProvisional: (chatId: string) => void
78
+ // getChats({all:true})). Upgrades the entry only to what a per-chat member
79
+ // read PROVES, and otherwise falls back to @kakao-group — the strictest
80
+ // bucket, matching the history callback's existing fallback — so allow-rule
81
+ // enforcement stays strict on chats the roster could not establish.
82
+ // Returns the bucket it settled on so callers can log the real outcome.
83
+ ingestProvisional: (chatId: string) => Promise<KakaoWorkspace>
42
84
  }
43
85
 
44
86
  export type KakaoChannelResolverOptions = {
45
- client: Pick<KakaoTalkClient, 'getChats'>
87
+ client: Pick<KakaoTalkClient, 'getChats' | 'getMembers'>
46
88
  now?: () => number
47
89
  ttlMs?: number
48
90
  logger?: { warn: (msg: string) => void }
91
+ selfUserId?: () => string | null
49
92
  }
50
93
 
51
94
  type Entry = {
@@ -117,16 +160,43 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
117
160
  return { workspace: entry.workspace, isDm: entry.isDm, provisional: entry.provisional }
118
161
  }
119
162
 
120
- const ingestProvisional = (chatId: string): void => {
121
- const existing = cache.get(chatId)
122
- if (existing !== undefined && existing.expiresAt > now()) return
163
+ const liveEntry = (chatId: string): Entry | null => {
164
+ const entry = cache.get(chatId)
165
+ return entry !== undefined && entry.expiresAt > now() ? entry : null
166
+ }
167
+
168
+ const provenKindFor = async (chatId: string): Promise<'open' | 'group' | null> => {
169
+ try {
170
+ const members = await options.client.getMembers(chatId)
171
+ return provenKindFromMembers(members, options.selfUserId?.() ?? null)
172
+ } catch (err) {
173
+ options.logger?.warn(`[kakaotalk] provisional member lookup failed chat=${chatId}: ${describeError(err)}`)
174
+ return null
175
+ }
176
+ }
177
+
178
+ const ingestProvisional = async (chatId: string): Promise<KakaoWorkspace> => {
179
+ const cached = liveEntry(chatId)
180
+ if (cached !== null) return cached.workspace
181
+
182
+ const kind = await provenKindFor(chatId)
183
+
184
+ // The member read was awaited, so a concurrent `refresh()` may have landed
185
+ // a getChats-authoritative entry meanwhile. Re-check instead of writing
186
+ // blind: clobbering it would replace a real classification with a weaker
187
+ // member-derived one — or with the strict fallback — for a whole TTL.
188
+ const current = liveEntry(chatId)
189
+ if (current !== null && !current.provisional) return current.workspace
190
+
191
+ const workspace = kind === null ? '@kakao-group' : kakaoWorkspaceForType(kind)
123
192
  cache.set(chatId, {
124
- workspace: '@kakao-group',
193
+ workspace,
125
194
  isDm: false,
126
195
  chatName: null,
127
196
  expiresAt: now() + ttlMs,
128
- provisional: true,
197
+ provisional: kind === null,
129
198
  })
199
+ return workspace
130
200
  }
131
201
 
132
202
  return { resolve, lookupChat, refresh, ingestProvisional }
@@ -378,7 +378,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
378
378
  recoveryEpisode = null
379
379
  }
380
380
 
381
- const channelResolver = createKakaoChannelResolver({ client, logger })
381
+ const channelResolver = createKakaoChannelResolver({ client, logger, selfUserId: () => selfUserId })
382
382
  const authorResolver = createKakaoAuthorResolver({ client, logger })
383
383
  const membershipResolver = createKakaoMembershipResolver({
384
384
  client,
@@ -443,14 +443,13 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
443
443
  // The push event itself proves the chat exists, even when
444
444
  // getChats({all:true}) does not surface it (e.g. memo chats,
445
445
  // certain open chats, recently-joined groups that haven't
446
- // propagated). Register a provisional @kakao-group entry (the
447
- // strictest workspace bucket — narrowest engagement assumptions)
448
- // so the message is no longer silently dropped as unknown_chat.
449
- // The next real refresh upgrades the entry if the chat is
450
- // actually a DM or open chat.
451
- channelResolver.ingestProvisional(event.chat_id)
446
+ // propagated). Resolve the real kind from a per-chat member read
447
+ // so the message is no longer silently dropped as unknown_chat,
448
+ // falling back to the strictest @kakao-group bucket when that read
449
+ // yields nothing. The next real refresh re-confirms the entry.
450
+ const bucket = await channelResolver.ingestProvisional(event.chat_id)
452
451
  logger.warn(
453
- `[kakaotalk] provisional chat=${event.chat_id} log_id=${event.log_id} bucket=@kakao-group reason=not_in_getchats`,
452
+ `[kakaotalk] provisional chat=${event.chat_id} log_id=${event.log_id} bucket=${bucket} reason=not_in_getchats`,
454
453
  )
455
454
  }
456
455
  }
@@ -142,3 +142,24 @@ function isAddressedToBot(event: TeamsInboundEvent, self: TeamsUser, selfAliases
142
142
  export function normalizeTeamsText(text: string): string {
143
143
  return text.replace(/\s+/g, ' ').trim()
144
144
  }
145
+
146
+ // Teams is the only adapter whose classifier never returns `self_author` — the
147
+ // user SDK reports `'ME'` for every author, so the send/echo fingerprint is the
148
+ // ONLY thing standing between the agent and answering its own message. That
149
+ // makes the comparison worth hardening: we fingerprint what we handed the SDK,
150
+ // but Teams stores messages as HTML, so the text comes back escaped-then-decoded
151
+ // and the two sides are not the same string. The decode is also lossy in one
152
+ // direction — it expands `&amp;` before `&lt;`, so a literal `&lt;` we wrote
153
+ // returns as `<` — which without this would miss its own reservation and route
154
+ // the agent's message back in as inbound. Decoding both sides identically makes
155
+ // the comparison survive the round trip; on text holding no entities it is a
156
+ // no-op. Order mirrors the SDK's decoder, and must keep mirroring it.
157
+ export function teamsEchoTextKey(text: string): string {
158
+ const decoded = text
159
+ .replace(/&amp;/g, '&')
160
+ .replace(/&lt;/g, '<')
161
+ .replace(/&gt;/g, '>')
162
+ .replace(/&quot;/g, '"')
163
+ .replace(/&#39;/g, "'")
164
+ return normalizeTeamsText(decoded)
165
+ }
@@ -3,6 +3,7 @@ import type { TeamsClient } from 'agent-messenger/teams'
3
3
  import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
4
 
5
5
  import { describeError } from '../describe-error'
6
+ import { TEAMS_OUTBOUND_FORMAT } from './teams-format'
6
7
  import { decodeTeamsConversationKey } from './teams-key'
7
8
 
8
9
  // The Teams user-account SDK only exposes an edit primitive for 1:1/group
@@ -24,7 +25,7 @@ export function createTeamsEditMessageCallback(deps: {
24
25
  return { ok: false, error: 'Teams channel messages cannot be edited', code: 'not-supported' }
25
26
  }
26
27
  try {
27
- await deps.client.editChatMessage(decoded.chatId, req.messageId, req.text)
28
+ await deps.client.editChatMessage(decoded.chatId, req.messageId, req.text, TEAMS_OUTBOUND_FORMAT)
28
29
  } catch (err) {
29
30
  return { ok: false, error: describeError(err), code: classifyEditError(err) }
30
31
  }
@@ -0,0 +1,16 @@
1
+ import type { TeamsMessageFormat } from 'agent-messenger/teams'
2
+
3
+ // Teams posts every outbound as `RichText/Html`, so the SDK has to decide how
4
+ // our string becomes markup. TypeClaw's contract is PLAIN TEXT — `OutboundMessage`
5
+ // carries no format metadata and no tool or skill can ask for another rendering,
6
+ // so `text` (HTML-escape) is the only mode that shows what the agent wrote;
7
+ // `html`/`markdown` would promote arbitrary prose, which routinely relays text
8
+ // authored by untrusted channel users, into live markup. Native Teams mentions,
9
+ // if ever needed, belong in a structured mention field the adapter converts —
10
+ // not in a blanket format switch.
11
+ //
12
+ // Passed EXPLICITLY at every call site, never left to the SDK default: 2.35.0
13
+ // escaped the chat path but posted the team/channel path raw, and 2.37.2
14
+ // defaulted both to `text`. Naming it pins what lands in users' chats against a
15
+ // future upstream flip.
16
+ export const TEAMS_OUTBOUND_FORMAT: TeamsMessageFormat = 'text'
@@ -19,11 +19,12 @@ import { describeError } from '../describe-error'
19
19
  import {
20
20
  classifyChannelInbound,
21
21
  classifyChatInbound,
22
- normalizeTeamsText,
22
+ teamsEchoTextKey,
23
23
  type InboundDropReason,
24
24
  type TeamsInboundEvent,
25
25
  } from './teams-classify'
26
26
  import { createTeamsEditMessageCallback } from './teams-edit'
27
+ import { TEAMS_OUTBOUND_FORMAT } from './teams-format'
27
28
  import { ContainerTeamsClient } from './teams-id-token'
28
29
  import { decodeTeamsConversationKey } from './teams-key'
29
30
 
@@ -110,8 +111,14 @@ export function createOutboundCallback(deps: {
110
111
  try {
111
112
  const sent =
112
113
  decoded.kind === 'chat'
113
- ? await client.sendChatMessage(decoded.chatId, text)
114
- : await client.sendMessage(decoded.teamId, decoded.channelId, text, msg.thread ?? undefined)
114
+ ? await client.sendChatMessage(decoded.chatId, text, TEAMS_OUTBOUND_FORMAT)
115
+ : await client.sendMessage(
116
+ decoded.teamId,
117
+ decoded.channelId,
118
+ text,
119
+ msg.thread ?? undefined,
120
+ TEAMS_OUTBOUND_FORMAT,
121
+ )
115
122
  logger.info(`[teams] sent id=${sent.id} ${decoded.kind}=${conversationId}`)
116
123
  return { ok: true, messageId: sent.id, messageIds: [sent.id] }
117
124
  } catch (err) {
@@ -168,7 +175,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
168
175
  self !== null ? { id: self.id, username: self.userPrincipalName ?? self.email ?? self.displayName } : null
169
176
 
170
177
  const reserveEcho = (chatId: string, text: string): (() => void) => {
171
- const echo: SentEcho = { chatId, textKey: normalizeTeamsText(text), sentAt: now(), consumed: false }
178
+ const echo: SentEcho = { chatId, textKey: teamsEchoTextKey(text), sentAt: now(), consumed: false }
172
179
  sentEchoes.push(echo)
173
180
  if (sentEchoes.length > MAX_SENT_ECHOES) sentEchoes = sentEchoes.slice(-MAX_SENT_ECHOES)
174
181
  return () => {
@@ -179,7 +186,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
179
186
 
180
187
  const isSelfEcho = (event: TeamsInboundEvent): boolean => {
181
188
  const conversationId = echoConversationId(event)
182
- const textKey = normalizeTeamsText(event.content)
189
+ const textKey = teamsEchoTextKey(event.content)
183
190
  const authorName = event.author.displayName.trim().toLocaleLowerCase()
184
191
  const selfName = (self?.displayName ?? '').trim().toLocaleLowerCase()
185
192
  const nowMs = now()
@@ -119,6 +119,16 @@ const ROUND_INELIGIBLE_REASON =
119
119
  'This review follow-up round assigned the formal verdict to another sibling thread session. ' +
120
120
  'Do not submit a formal verdict from this session; wait for the designated sibling verdict activity, then close out only this thread.'
121
121
 
122
+ const ROUND_HEAD_UNVERIFIED_REASON =
123
+ "Could not verify this pull request's current head commit on GitHub, so the review round's verdict was not submitted. " +
124
+ 'You are still the designated carrier for this round. Retry the same verdict once shortly. ' +
125
+ 'If it fails again, stop retrying: the head read may be failing persistently (missing credentials or a denied or malformed GitHub API response), ' +
126
+ 'so report that the PR head could not be verified and ask the operator to check GitHub credentials and API access.'
127
+
128
+ const ROUND_HEAD_MOVED_REASON =
129
+ 'The pull request head moved past the commit this review round covers, so a verdict from this round would describe stale code. ' +
130
+ 'Do not submit it; the new push starts its own review round.'
131
+
122
132
  // The standing verdict a fresh attempt would duplicate. APPROVE duplicates a
123
133
  // standing APPROVED; REQUEST_CHANGES duplicates a standing CHANGES_REQUESTED.
124
134
  function duplicatesStanding(verdict: ReviewVerdict, effective: EffectiveVerdict): boolean {
@@ -594,7 +604,7 @@ export function createApproveIdempotencyGuard(deps: {
594
604
  if (args.verdict !== 'APPROVE' && args.verdict !== 'REQUEST_CHANGES') return null
595
605
  expireRecentLanded(now)
596
606
  expirePendingPublications(now, logger)
597
- const blocked = await evaluateRoundEligibility(args, deps.resolveHeadSha ?? processHeadShaResolver, now)
607
+ const blocked = await evaluateRoundEligibility(args, deps.resolveHeadSha ?? processHeadShaResolver, now, logger)
598
608
  if (blocked !== null) return blocked
599
609
  const key = prKey(args.workspace, args.prNumber)
600
610
 
@@ -766,6 +776,7 @@ async function evaluateRoundEligibility(
766
776
  },
767
777
  resolveHeadSha: HeadShaResolver,
768
778
  now: () => number = Date.now,
779
+ logger: ReviewVerdictCoordinatorLogger = processLogger,
769
780
  ): Promise<ApproveBlock | null> {
770
781
  expireReviewRounds(now)
771
782
  const pendingRoundForPr = Array.from(reviewRounds.values()).find(
@@ -800,8 +811,20 @@ async function evaluateRoundEligibility(
800
811
  workspace: activeRound.workspace,
801
812
  prNumber: activeRound.prNumber,
802
813
  })
803
- if (currentRoundHead === null || currentRoundHead !== activeRound.headSha) {
804
- return { block: true, kind: 'round-ineligible', reason: ROUND_INELIGIBLE_REASON }
814
+ // This session IS the carrier here, so the sibling-carrier reason would be a
815
+ // lie that tells the model to stand down and strands the round. Name the
816
+ // actual cause instead: an unverified head (one retry, then diagnostics) or a moved head.
817
+ if (currentRoundHead === null) {
818
+ logger.warn(
819
+ `[github] review round head read failed pr=${activeRound.workspace}#${activeRound.prNumber} round=${activeRound.roundId} carrier=${activeRound.carrierThread ?? 'root'}`,
820
+ )
821
+ return { block: true, kind: 'round-ineligible', reason: ROUND_HEAD_UNVERIFIED_REASON }
822
+ }
823
+ if (currentRoundHead !== activeRound.headSha) {
824
+ logger.warn(
825
+ `[github] review round head moved pr=${activeRound.workspace}#${activeRound.prNumber} round=${activeRound.roundId} round_head=${activeRound.headSha} current_head=${currentRoundHead}`,
826
+ )
827
+ return { block: true, kind: 'round-ineligible', reason: ROUND_HEAD_MOVED_REASON }
805
828
  }
806
829
  registerGithubReviewRound(activeRound, now())
807
830
  return null