typeclaw 0.50.0 → 0.52.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 (258) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +17 -0
  2. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  3. package/dist/types/agent/bash-sandbox.d.ts +98 -0
  4. package/dist/types/agent/compaction.d.ts +4 -4
  5. package/dist/types/agent/idle-compaction.d.ts +1 -0
  6. package/dist/types/agent/index.d.ts +10 -17
  7. package/dist/types/agent/multimodal/look-at.d.ts +1 -1
  8. package/dist/types/agent/output-allowance.d.ts +4 -0
  9. package/dist/types/agent/plugin-tools.d.ts +8 -75
  10. package/dist/types/agent/prompt-cache-key.d.ts +1 -0
  11. package/dist/types/agent/session-tail.d.ts +12 -0
  12. package/dist/types/agent/subagents.d.ts +5 -0
  13. package/dist/types/agent/system-prompt-composition.d.ts +18 -0
  14. package/dist/types/agent/system-prompt.d.ts +2 -0
  15. package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
  16. package/dist/types/agent/tools/channel-edit.d.ts +1 -1
  17. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
  18. package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
  19. package/dist/types/agent/tools/channel-history.d.ts +1 -1
  20. package/dist/types/agent/tools/channel-react.d.ts +1 -1
  21. package/dist/types/agent/tools/channel-read.d.ts +10 -2
  22. package/dist/types/agent/tools/channel-reply.d.ts +1 -1
  23. package/dist/types/agent/tools/channel-send.d.ts +1 -1
  24. package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
  25. package/dist/types/agent/tools/ddg.d.ts +9 -0
  26. package/dist/types/agent/tools/grant-role.d.ts +1 -1
  27. package/dist/types/agent/tools/post-github-review.d.ts +1 -1
  28. package/dist/types/agent/tools/restart.d.ts +1 -1
  29. package/dist/types/agent/tools/skip-response.d.ts +1 -1
  30. package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
  31. package/dist/types/agent/tools/stream-snapshot.d.ts +2 -2
  32. package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
  33. package/dist/types/agent/tools/subagent-output.d.ts +1 -1
  34. package/dist/types/agent/tools/todo/index.d.ts +1 -1
  35. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
  36. package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
  37. package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
  38. package/dist/types/agent/tools/websearch.d.ts +1 -1
  39. package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
  40. package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
  41. package/dist/types/channels/adapters/github/auth.d.ts +24 -0
  42. package/dist/types/channels/github-review-check.d.ts +1 -1
  43. package/dist/types/channels/github-token-bridge.d.ts +4 -0
  44. package/dist/types/channels/lost-background-context.d.ts +2 -0
  45. package/dist/types/channels/persistence.d.ts +1 -0
  46. package/dist/types/channels/router.d.ts +16 -50
  47. package/dist/types/channels/types.d.ts +1 -0
  48. package/dist/types/coding-agent/tool.d.ts +1 -1
  49. package/dist/types/config/config.d.ts +22 -0
  50. package/dist/types/config/providers.d.ts +50 -1
  51. package/dist/types/container/start.d.ts +1 -0
  52. package/dist/types/eval/cell.d.ts +26 -0
  53. package/dist/types/eval/config.d.ts +19 -0
  54. package/dist/types/eval/dispatch.d.ts +7 -0
  55. package/dist/types/eval/kernel.d.ts +28 -0
  56. package/dist/types/eval/process.d.ts +23 -0
  57. package/dist/types/eval/protocol.d.ts +34 -0
  58. package/dist/types/eval/sandbox.d.ts +12 -0
  59. package/dist/types/eval/tool.d.ts +17 -0
  60. package/dist/types/eval/wire.d.ts +33 -0
  61. package/dist/types/git/resolve-identity.d.ts +2 -0
  62. package/dist/types/init/dockerfile.d.ts +1 -0
  63. package/dist/types/init/gitignore.d.ts +1 -1
  64. package/dist/types/permissions/builtins.d.ts +1 -0
  65. package/dist/types/plugin/types.d.ts +3 -0
  66. package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
  67. package/dist/types/sandbox/coding-agent.d.ts +1 -1
  68. package/dist/types/sandbox/dependency-bins.d.ts +1 -0
  69. package/dist/types/sandbox/dev-source.d.ts +2 -2
  70. package/dist/types/sandbox/env-exposure.d.ts +2 -0
  71. package/dist/types/sandbox/hidden-paths.d.ts +1 -0
  72. package/dist/types/sandbox/index.d.ts +1 -1
  73. package/dist/types/sandbox/policy.d.ts +3 -0
  74. package/dist/types/typevault/cli-path.d.ts +2 -0
  75. package/dist/types/typevault/envelope-store.d.ts +11 -0
  76. package/dist/types/typevault/lifecycle.d.ts +13 -0
  77. package/dist/types/typevault/vault.d.ts +27 -0
  78. package/package.json +8 -7
  79. package/scripts/test.ts +252 -0
  80. package/src/agent/bash-sandbox-env.ts +136 -0
  81. package/src/agent/bash-sandbox-proc.ts +70 -0
  82. package/src/agent/bash-sandbox.ts +239 -0
  83. package/src/agent/compaction.ts +22 -10
  84. package/src/agent/idle-compaction.ts +7 -3
  85. package/src/agent/index.ts +185 -187
  86. package/src/agent/multimodal/look-at.ts +1 -1
  87. package/src/agent/output-allowance.ts +7 -0
  88. package/src/agent/plugin-tools.ts +64 -380
  89. package/src/agent/prompt-cache-key.ts +26 -3
  90. package/src/agent/session-origin.ts +41 -19
  91. package/src/agent/session-tail.ts +28 -0
  92. package/src/agent/subagent-completion-reminder.ts +2 -2
  93. package/src/agent/subagents.ts +21 -2
  94. package/src/agent/system-prompt-composition.ts +159 -0
  95. package/src/agent/system-prompt.ts +43 -5
  96. package/src/agent/todo/scope.ts +1 -1
  97. package/src/agent/tool-error-remediation.ts +18 -3
  98. package/src/agent/tools/channel-disengage.ts +1 -1
  99. package/src/agent/tools/channel-edit.ts +1 -1
  100. package/src/agent/tools/channel-fetch-attachment.ts +1 -1
  101. package/src/agent/tools/channel-handoff.ts +3 -2
  102. package/src/agent/tools/channel-history.ts +2 -1
  103. package/src/agent/tools/channel-react.ts +1 -1
  104. package/src/agent/tools/channel-read.ts +36 -3
  105. package/src/agent/tools/channel-reply.ts +1 -1
  106. package/src/agent/tools/channel-send.ts +4 -3
  107. package/src/agent/tools/channel-session-search.ts +13 -4
  108. package/src/agent/tools/ddg.ts +71 -11
  109. package/src/agent/tools/grant-role.ts +1 -1
  110. package/src/agent/tools/post-github-review.ts +1 -1
  111. package/src/agent/tools/restart.ts +1 -1
  112. package/src/agent/tools/skip-response.ts +1 -1
  113. package/src/agent/tools/spawn-subagent.ts +15 -1
  114. package/src/agent/tools/stream-snapshot.ts +1 -1
  115. package/src/agent/tools/subagent-cancel.ts +1 -1
  116. package/src/agent/tools/subagent-output.ts +1 -1
  117. package/src/agent/tools/todo/index.ts +1 -1
  118. package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
  119. package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
  120. package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
  121. package/src/agent/tools/webfetch/tool.ts +6 -5
  122. package/src/agent/tools/websearch.ts +1 -1
  123. package/src/agent/tools-without-local-file-operands.ts +4 -0
  124. package/src/browser/dockerfile.ts +1 -1
  125. package/src/browser/fill-secret.ts +364 -0
  126. package/src/browser/registry.ts +6 -6
  127. package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
  128. package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
  129. package/src/bundled-plugins/backup/index.ts +17 -2
  130. package/src/bundled-plugins/backup/runner.ts +37 -2
  131. package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
  132. package/src/bundled-plugins/browser-agent/index.ts +12 -5
  133. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  134. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  135. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  136. package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
  137. package/src/bundled-plugins/managed-browser/index.ts +130 -2
  138. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
  139. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
  140. package/src/bundled-plugins/memory/README.md +23 -2
  141. package/src/bundled-plugins/memory/append-fragment.ts +133 -0
  142. package/src/bundled-plugins/memory/append-tool.ts +80 -149
  143. package/src/bundled-plugins/memory/dreaming.ts +6 -1
  144. package/src/bundled-plugins/memory/index.ts +33 -6
  145. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  146. package/src/bundled-plugins/memory/memory-logger.ts +200 -6
  147. package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
  148. package/src/bundled-plugins/memory/remember-tool.ts +81 -0
  149. package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
  150. package/src/bundled-plugins/memory/search-tool.ts +58 -12
  151. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  152. package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
  153. package/src/bundled-plugins/memory/transcript-preload.ts +208 -0
  154. package/src/bundled-plugins/memory/transcript-view.ts +36 -0
  155. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  156. package/src/bundled-plugins/memory/watermark.ts +19 -10
  157. package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
  158. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
  159. package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
  160. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  161. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
  162. package/src/bundled-plugins/typevault/grants.ts +119 -0
  163. package/src/bundled-plugins/typevault/index.ts +152 -0
  164. package/src/bundled-plugins/typevault/request.ts +87 -0
  165. package/src/bundled-plugins/typevault/runtime.ts +45 -0
  166. package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
  167. package/src/channels/adapter-halt.ts +17 -0
  168. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  169. package/src/channels/adapters/discord-bot.ts +1 -0
  170. package/src/channels/adapters/discord-classify.ts +8 -3
  171. package/src/channels/adapters/discord.ts +29 -0
  172. package/src/channels/adapters/github/history.ts +23 -2
  173. package/src/channels/adapters/github/inbound.ts +60 -1
  174. package/src/channels/adapters/github/index.ts +27 -5
  175. package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
  176. package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
  177. package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
  178. package/src/channels/adapters/kakaotalk-classify.ts +7 -9
  179. package/src/channels/adapters/kakaotalk-list.ts +62 -0
  180. package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
  181. package/src/channels/adapters/kakaotalk-membership.ts +27 -10
  182. package/src/channels/adapters/kakaotalk-mention.ts +61 -0
  183. package/src/channels/adapters/kakaotalk.ts +159 -125
  184. package/src/channels/adapters/teams-classify.ts +18 -8
  185. package/src/channels/github-review-check.ts +5 -1
  186. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  187. package/src/channels/github-token-bridge.ts +13 -0
  188. package/src/channels/lost-background-context.ts +46 -0
  189. package/src/channels/manager.ts +52 -3
  190. package/src/channels/persistence.ts +5 -0
  191. package/src/channels/router.ts +208 -128
  192. package/src/channels/schema.ts +1 -1
  193. package/src/channels/subagent-completion-bridge.ts +3 -2
  194. package/src/channels/types.ts +3 -0
  195. package/src/cli/hostd.ts +3 -0
  196. package/src/coding-agent/tool.ts +1 -1
  197. package/src/config/config.ts +35 -1
  198. package/src/config/providers.ts +75 -4
  199. package/src/container/start.ts +52 -3
  200. package/src/doctor/channel-checks.ts +33 -0
  201. package/src/doctor/checks.ts +37 -18
  202. package/src/doctor/index.ts +48 -12
  203. package/src/doctor/operational-incidents.ts +16 -1
  204. package/src/doctor/plugin-bridge.ts +14 -1
  205. package/src/doctor/stage.ts +14 -0
  206. package/src/doctor/types.ts +6 -0
  207. package/src/eval/cell.ts +93 -0
  208. package/src/eval/config.ts +32 -0
  209. package/src/eval/dispatch.ts +67 -0
  210. package/src/eval/entry.ts +261 -0
  211. package/src/eval/kernel.ts +154 -0
  212. package/src/eval/process.ts +113 -0
  213. package/src/eval/protocol.ts +26 -0
  214. package/src/eval/redeclare.ts +174 -0
  215. package/src/eval/sandbox.ts +117 -0
  216. package/src/eval/tool.ts +99 -0
  217. package/src/eval/wire.ts +93 -0
  218. package/src/git/resolve-identity.ts +67 -2
  219. package/src/git/system-commit.ts +7 -0
  220. package/src/init/dockerfile.ts +5 -1
  221. package/src/init/gitignore.ts +3 -3
  222. package/src/init/index.ts +1 -0
  223. package/src/init/models-dev.ts +2 -0
  224. package/src/init/validate-api-key.ts +5 -0
  225. package/src/migrations/secrets-v1-to-v2.ts +2 -0
  226. package/src/operations/classify-tool-outcome.ts +1 -1
  227. package/src/permissions/builtins.ts +8 -0
  228. package/src/plugin/core-tool-names.ts +6 -1
  229. package/src/plugin/types.ts +6 -0
  230. package/src/run/bundled-plugins.ts +12 -0
  231. package/src/run/channel-session-factory.ts +3 -0
  232. package/src/run/index.ts +13 -2
  233. package/src/sandbox/build.ts +1 -0
  234. package/src/sandbox/canonical-secrets.ts +6 -0
  235. package/src/sandbox/dependency-bins.ts +13 -1
  236. package/src/sandbox/dev-source.ts +21 -12
  237. package/src/sandbox/env-exposure.ts +20 -0
  238. package/src/sandbox/hidden-paths.ts +1 -1
  239. package/src/sandbox/index.ts +1 -0
  240. package/src/sandbox/policy.ts +5 -0
  241. package/src/secrets/hydrate.ts +4 -1
  242. package/src/secrets/storage.ts +10 -1
  243. package/src/server/command-runner.ts +4 -0
  244. package/src/server/index.ts +54 -12
  245. package/src/skills/typeclaw-config/SKILL.md +36 -2
  246. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  247. package/src/skills/typeclaw-permissions/SKILL.md +8 -8
  248. package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
  249. package/src/tunnels/active.ts +14 -0
  250. package/src/typevault/bash-cli.ts +18 -0
  251. package/src/typevault/cli-path.ts +11 -0
  252. package/src/typevault/envelope-helper.ts +17 -0
  253. package/src/typevault/envelope-store.ts +98 -0
  254. package/src/typevault/lifecycle.ts +132 -0
  255. package/src/typevault/prompt-tunnel.ts +33 -0
  256. package/src/typevault/redaction.ts +37 -0
  257. package/src/typevault/vault.ts +283 -0
  258. package/typeclaw.schema.json +92 -10
@@ -7,8 +7,9 @@ import {
7
7
  type AttachmentInput,
8
8
  type KakaoChat,
9
9
  type KakaoMarkReadResult,
10
- type KakaoMember,
10
+ type KakaoMemberSnapshot,
11
11
  type KakaoMessage,
12
+ type KakaoPartialMemberSnapshot,
12
13
  type KakaoProfile,
13
14
  type KakaoReplyTarget,
14
15
  type KakaoSendResult,
@@ -17,7 +18,12 @@ import {
17
18
  type KakaoTalkPushMessageEvent,
18
19
  type KakaoTypingResult,
19
20
  } from 'agent-messenger/kakaotalk'
20
- import type { KakaoAccountCredentials, KakaoConfig, PendingLoginState } from 'agent-messenger/kakaotalk'
21
+ import type {
22
+ KakaoAccountCredentials,
23
+ KakaoConfig,
24
+ KakaoMentionInput,
25
+ PendingLoginState,
26
+ } from 'agent-messenger/kakaotalk'
21
27
 
22
28
  import { prependQuoteAnchor, type ChannelRouter } from '@/channels/router'
23
29
  import type { ChannelAdapterConfig } from '@/channels/schema'
@@ -35,6 +41,7 @@ import type {
35
41
  InboundAttachment,
36
42
  } from '@/channels/types'
37
43
 
44
+ import { ChannelAdapterHaltedError } from '../adapter-halt'
38
45
  import { describeError } from '../describe-error'
39
46
  import {
40
47
  emoticonEventToMessageEvent,
@@ -47,7 +54,10 @@ import { createKakaoChannelResolver, type KakaoChannelResolver } from './kakaota
47
54
  import { classifyInbound, type InboundDropReason } from './kakaotalk-classify'
48
55
  import { createFetchAttachmentCallback } from './kakaotalk-fetch-attachment'
49
56
  import { toKakaoPlainText } from './kakaotalk-format'
57
+ import { createKakaoListCallback } from './kakaotalk-list'
58
+ import { createKakaoMemberSnapshotCache } from './kakaotalk-member-cache'
50
59
  import { createKakaoMembershipResolver } from './kakaotalk-membership'
60
+ import { resolveKakaoMentions } from './kakaotalk-mention'
51
61
  import { createKakaoTypingCallback, kakaoTypingClassFromLookup, KAKAO_TYPING_HEARTBEAT_MS } from './kakaotalk-typing'
52
62
  import { withOutboundAccount } from './outbound-account'
53
63
 
@@ -62,9 +72,13 @@ export interface KakaoTalkClient {
62
72
  credentials?: { oauthToken: string; userId: string; deviceUuid?: string; deviceType?: 'pc' | 'tablet' },
63
73
  accountId?: string,
64
74
  ): Promise<this>
65
- getChats(options?: { all?: boolean; search?: string }): Promise<KakaoChat[]>
75
+ getChats(options?: { all?: boolean; search?: string; resolveTitles?: boolean }): Promise<KakaoChat[]>
66
76
  getMessages(chatId: string, options?: { count?: number; from?: string }): Promise<KakaoMessage[]>
67
- sendMessage(chatId: string, text: string, options?: { replyTo?: KakaoReplyTarget }): Promise<KakaoSendResult>
77
+ sendMessage(
78
+ chatId: string,
79
+ text: string,
80
+ options?: { replyTo?: KakaoReplyTarget; mentions?: KakaoMentionInput[] },
81
+ ): Promise<KakaoSendResult>
68
82
  sendAttachment(
69
83
  chatId: string,
70
84
  data: Uint8Array | Buffer,
@@ -75,7 +89,13 @@ export interface KakaoTalkClient {
75
89
  markRead(chatId: string, logId: string, opts?: { linkId?: string }): Promise<KakaoMarkReadResult>
76
90
  sendTyping(chatId: string, opts?: { linkId?: string }): Promise<KakaoTypingResult>
77
91
  getProfile(): Promise<KakaoProfile>
78
- getMembers(chatId: string): Promise<KakaoMember[]>
92
+ // Always called with `allowPartial: true`: the strict default throws on every
93
+ // read in open chats whose GETMEM roster is capped below the active member
94
+ // count, which would leave those rooms with no roster at all.
95
+ getMemberSnapshot(
96
+ chatId: string,
97
+ options: { allowPartial: true },
98
+ ): Promise<KakaoMemberSnapshot | KakaoPartialMemberSnapshot>
79
99
  lookupAuthorName(chatId: string, authorId: number): string | null
80
100
  close(): void
81
101
  }
@@ -132,42 +152,22 @@ export type KakaotalkAdapterOptions = {
132
152
  credentialsDir?: string
133
153
  client?: KakaoTalkClient
134
154
  listenerFactory?: (client: KakaoTalkClient) => KakaoTalkListener
135
- // Test seam for KICKOUT auto-recovery. Production uses Date.now and
136
- // setTimeout. Tests inject deterministic clocks/schedulers so they can
137
- // assert the recovery semantics without real-time waits.
138
- now?: () => number
139
- scheduleRecovery?: (fn: () => void, delayMs: number) => void
140
155
  }
141
156
 
142
- // LOCO emits KICKOUT when the same device_uuid logs in elsewhere. Three
143
- // shapes converge on this one signal:
144
- // 1. Init handoff — `typeclaw init` left a brief session that the
145
- // container's re-login kicks. One delayed reconnect resolves it.
146
- // 2. Ghost session — a previous run's LOCO connection is still
147
- // half-alive server-side and ping-pongs with our reconnect for
148
- // ~1-2 minutes until it times out. Old one-shot recovery
149
- // reconnected once, got kicked again, and died — the bug this
150
- // state machine exists to fix.
151
- // 3. Real conflict — another device or process holds the same
152
- // device_uuid. Our retries can't win this fight; we should give up
153
- // cleanly so the user notices and intervenes.
154
- // One signal, three shapes: we always try to recover, but with a
155
- // strictly bounded budget. Within an episode we allow KICKOUT_RECOVERY_
156
- // _DELAYS_MS.length retries spaced by the listed delays; an episode is
157
- // declared successful only after the reconnect stays connected for
158
- // SUCCESS_MS (bare `connected` is too weak — ghost ping-pong reconnects
159
- // for seconds before getting kicked again). Past the budget or the
160
- // MAX_ELAPSED cap we let the session die. After a successful episode
161
- // the state resets, so a fresh KICKOUT hours later gets a fresh
162
- // episode rather than being permanently locked out.
163
- const KICKOUT_RECOVERY_SUCCESS_MS = 60_000
164
- const KICKOUT_RECOVERY_MAX_ELAPSED_MS = 5 * 60_000
165
- const KICKOUT_RECOVERY_DELAYS_MS: readonly number[] = [2_000, 10_000, 60_000]
157
+ // LOCO emits KICKOUT when the server ends this session: another login with
158
+ // the same device_uuid, or KakaoTalk acting on the account itself. We never
159
+ // log in again on our own after one. A kick that turns out to be an account
160
+ // action makes every reconnect a rejected login, and repeated rejected logins
161
+ // can escalate a temporary KakaoTalk restriction into a permanent one. The
162
+ // adapter halts and waits for an operator.
166
163
 
167
164
  export type KakaotalkAdapter = {
168
165
  start: () => Promise<void>
169
166
  stop: () => Promise<void>
170
167
  isConnected: () => boolean
168
+ // Non-null once the adapter gave up on its session for a reason a retry with
169
+ // the same credentials cannot fix. The manager stops supervising restarts.
170
+ haltReason?: () => string | null
171
171
  }
172
172
 
173
173
  export const KAKAO_HISTORY_LIMIT_MAX = 200
@@ -188,12 +188,14 @@ async function readAttachmentBuffer(path: string): Promise<Buffer> {
188
188
  }
189
189
 
190
190
  export function createOutboundCallback(deps: {
191
- client: Pick<KakaoTalkClient, 'sendMessage' | 'sendAttachment' | 'getMessages'>
191
+ client: Pick<KakaoTalkClient, 'sendMessage' | 'sendAttachment' | 'getMessages' | 'getMemberSnapshot'>
192
192
  logger: KakaotalkAdapterLogger
193
193
  formatChannelTag: (workspace: string, chat: string) => Promise<string>
194
194
  readFile?: (path: string) => Promise<Buffer>
195
+ roster?: Pick<KakaoTalkClient, 'getMemberSnapshot'>
195
196
  }): OutboundCallback {
196
197
  const { client, logger, formatChannelTag } = deps
198
+ const roster = deps.roster ?? client
197
199
  const readFile = deps.readFile ?? readAttachmentBuffer
198
200
  return async (msg: OutboundMessage): Promise<SendResult> => {
199
201
  if (msg.adapter !== 'kakaotalk') {
@@ -256,12 +258,12 @@ export function createOutboundCallback(deps: {
256
258
  outboundText = prependQuoteAnchor(text, msg.replyTo.source)
257
259
  }
258
260
  }
261
+ const mentions = await resolveOutboundMentions(roster, msg.chat, outboundText, logger)
259
262
  try {
260
- const result = await client.sendMessage(
261
- msg.chat,
262
- outboundText,
263
- replyTarget !== undefined ? { replyTo: replyTarget } : undefined,
264
- )
263
+ const result = await client.sendMessage(msg.chat, outboundText, {
264
+ ...(replyTarget !== undefined ? { replyTo: replyTarget } : {}),
265
+ ...(mentions.length > 0 ? { mentions } : {}),
266
+ })
265
267
  if (!result.success) {
266
268
  logger.error(`[kakaotalk] sendMessage status_code=${result.status_code} ${tag}`)
267
269
  return { ok: false, error: `kakaotalk send failed with status ${result.status_code}` }
@@ -283,6 +285,30 @@ export function createOutboundCallback(deps: {
283
285
  }
284
286
  }
285
287
 
288
+ // A failed member lookup only costs the native tags: the text still carries
289
+ // the `@name` the agent wrote, so the send goes out untagged.
290
+ async function resolveOutboundMentions(
291
+ client: Pick<KakaoTalkClient, 'getMemberSnapshot'>,
292
+ chatId: string,
293
+ text: string,
294
+ logger: KakaotalkAdapterLogger,
295
+ ): Promise<KakaoMentionInput[]> {
296
+ if (!text.includes('@')) return []
297
+ try {
298
+ const snapshot = await client.getMemberSnapshot(chatId, { allowPartial: true })
299
+ // Nickname matching is only safe against the whole roster: an omitted
300
+ // duplicate or longer nickname would tag the wrong member. Send untagged.
301
+ if (!snapshot.complete) {
302
+ logger.info(`[kakaotalk] mention roster incomplete chat=${chatId}; sending untagged`)
303
+ return []
304
+ }
305
+ return resolveKakaoMentions(text, snapshot.members)
306
+ } catch (err) {
307
+ logger.warn(`[kakaotalk] mention member lookup failed chat=${chatId}: ${describeError(err)}`)
308
+ return []
309
+ }
310
+ }
311
+
286
312
  // KakaoTalk replies need the full source message, not just its log_id. Resolve
287
313
  // it from the chat's recent history (matching the upstream CLI's approach).
288
314
  // Returns undefined when the target isn't in the fetched window or the fetch
@@ -355,37 +381,61 @@ function clampLimit(requested: number, max: number): number {
355
381
 
356
382
  export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): KakaotalkAdapter {
357
383
  const logger = options.logger ?? consoleLogger
358
- const client = options.client ?? new KakaoTalkClient()
359
- const now = options.now ?? Date.now
360
- const scheduleRecovery =
361
- options.scheduleRecovery ??
362
- ((fn: () => void, delayMs: number): void => {
363
- setTimeout(fn, delayMs)
364
- })
384
+ // The SDK reconnects lazily: any call on a dropped session (a typing pulse,
385
+ // a send, a history read) runs a fresh LOGINLIST, and its callers only log
386
+ // failures. Every call goes through this guard so the first rejected login
387
+ // halts the adapter, wherever it surfaces.
388
+ const client = guardLoginRejections(options.client ?? new KakaoTalkClient(), (err) => {
389
+ haltOnLoginRejection(err)
390
+ })
365
391
  let listener: KakaoTalkListener | null = null
366
392
  let selfUserId: string | null = null
367
393
  const selfIdentityResolver: ChannelSelfIdentityResolver = () => (selfUserId === null ? null : { id: selfUserId })
368
394
  let connected = false
369
395
  let started = false
370
- let lastConnectedAt: number | null = null
371
396
  let inflightInbounds = 0
372
397
  let stopWaiters: Array<() => void> = []
373
-
374
- type RecoveryEpisode = {
375
- startedAt: number
376
- attemptCount: number
377
- pendingStabilityCheck: boolean
398
+ let haltReason: string | null = null
399
+
400
+ // Every SDK call on a dead session opens a new LOCO login, so a halt closes
401
+ // the client at once instead of waiting for the manager's next supervision
402
+ // tick: typing heartbeats and inbound bookkeeping would otherwise keep
403
+ // logging in against an account the server already refused.
404
+ const halt = (reason: string): void => {
405
+ if (haltReason !== null) return
406
+ haltReason = reason
407
+ connected = false
408
+ logger.error(`[kakaotalk] halted: ${reason}`)
409
+ listener?.stop()
410
+ listener = null
411
+ try {
412
+ client.close()
413
+ } catch {
414
+ // The session is unusable either way; nothing to recover here.
415
+ }
378
416
  }
379
- let recoveryEpisode: RecoveryEpisode | null = null
380
417
 
381
- const resetRecoveryEpisode = (): void => {
382
- recoveryEpisode = null
418
+ const haltOnLoginRejection = (err: unknown): boolean => {
419
+ const status = kakaoLoginRejectionStatus(err)
420
+ if (status === null) return false
421
+ halt(
422
+ `KakaoTalk rejected the login (LOGINLIST status ${status}). Retrying with the same session only sends more ` +
423
+ 'rejected logins, which KakaoTalk can treat as abuse. Check the account in the KakaoTalk app, then run ' +
424
+ '`typeclaw channel reauth kakaotalk` or `typeclaw restart`.',
425
+ )
426
+ return true
383
427
  }
384
428
 
385
- const channelResolver = createKakaoChannelResolver({ client, logger, selfUserId: () => selfUserId })
386
- const authorResolver = createKakaoAuthorResolver({ client, logger })
429
+ const roster = createKakaoMemberSnapshotCache({ client })
430
+ const channelResolver = createKakaoChannelResolver({
431
+ client: { getChats: (opts) => client.getChats(opts), getMemberSnapshot: roster.getMemberSnapshot },
432
+ logger,
433
+ selfUserId: () => selfUserId,
434
+ })
435
+ const authorResolver = createKakaoAuthorResolver({ client: roster, logger })
387
436
  const membershipResolver = createKakaoMembershipResolver({
388
- client,
437
+ client: roster,
438
+ roster,
389
439
  selfUserIdRef: () => selfUserId,
390
440
  logger,
391
441
  })
@@ -403,12 +453,14 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
403
453
  authorResolver,
404
454
  selfUserIdRef: () => selfUserId,
405
455
  })
456
+ const listCallback = createKakaoListCallback({ client, logger })
406
457
 
407
458
  const outboundCallback = withOutboundAccount(
408
459
  createOutboundCallback({
409
460
  client,
410
461
  logger,
411
462
  formatChannelTag,
463
+ roster,
412
464
  }),
413
465
  (workspace) => fallbackChannelAccountIdentity('kakaotalk', workspace, selfUserId),
414
466
  )
@@ -521,8 +573,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
521
573
  async start(): Promise<void> {
522
574
  if (started) return
523
575
  started = true
524
- lastConnectedAt = null
525
- resetRecoveryEpisode()
576
+ haltReason = null
526
577
  try {
527
578
  const credentialStore =
528
579
  options.credentialsStore ??
@@ -567,7 +618,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
567
618
  'either because the agent was just initialized without stored credentials, or because the encryption key ' +
568
619
  'is missing/wrong. Run `typeclaw channel reauth kakaotalk` to mint fresh tokens, then `typeclaw reload`.'
569
620
  logger.error(`[kakaotalk] ${message}`)
570
- throw new Error(message)
621
+ throw new ChannelAdapterHaltedError(message)
571
622
  }
572
623
  logger.error(`[kakaotalk] getProfile failed: ${describeError(err)}`)
573
624
  throw err
@@ -578,30 +629,15 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
578
629
  } catch (err) {
579
630
  logger.warn(`[kakaotalk] initial chat list fetch failed: ${describeError(err)}`)
580
631
  }
632
+ if (haltReason !== null) {
633
+ started = false
634
+ throw new ChannelAdapterHaltedError(haltReason)
635
+ }
581
636
 
582
637
  listener = options.listenerFactory ? options.listenerFactory(client) : new KakaoTalkListener(client)
583
- const activeListener = listener
584
- const scheduleStabilityCheck = (): void => {
585
- if (recoveryEpisode === null) return
586
- if (recoveryEpisode.pendingStabilityCheck) return
587
- recoveryEpisode.pendingStabilityCheck = true
588
- const expectedConnectedAt = lastConnectedAt
589
- scheduleRecovery(() => {
590
- if (recoveryEpisode === null) return
591
- recoveryEpisode.pendingStabilityCheck = false
592
- if (!started || listener !== activeListener) return
593
- if (!connected || lastConnectedAt !== expectedConnectedAt) return
594
- logger.info(
595
- `[kakaotalk] KICKOUT recovery episode succeeded after ${recoveryEpisode.attemptCount} attempt(s); session is stable.`,
596
- )
597
- resetRecoveryEpisode()
598
- }, KICKOUT_RECOVERY_SUCCESS_MS)
599
- }
600
638
  listener.on('connected', (info) => {
601
639
  connected = true
602
- lastConnectedAt = now()
603
640
  logger.info(`[kakaotalk] connected (user_id=${info.userId})`)
604
- if (recoveryEpisode !== null) scheduleStabilityCheck()
605
641
  })
606
642
  listener.on('disconnected', () => {
607
643
  connected = false
@@ -609,48 +645,13 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
609
645
  })
610
646
  listener.on('error', (err) => {
611
647
  logger.error(`[kakaotalk] listener error: ${describeError(err)}`)
648
+ if (haltReason !== null || haltOnLoginRejection(err)) return
612
649
  if (!isKickoutError(err)) return
613
- // KICKOUT closes the SDK session and skips scheduleReconnect, so
614
- // without intervention the adapter goes silent. We must either
615
- // start/continue a recovery episode or surface the dead state.
616
- connected = false
617
- if (!started) return
618
- const tNow = now()
619
- if (recoveryEpisode === null) {
620
- recoveryEpisode = { startedAt: tNow, attemptCount: 0, pendingStabilityCheck: false }
621
- }
622
- const episode = recoveryEpisode
623
- const elapsedInEpisode = tNow - episode.startedAt
624
- const nextAttemptIndex = episode.attemptCount
625
- const delayMs = KICKOUT_RECOVERY_DELAYS_MS[nextAttemptIndex]
626
- if (delayMs === undefined || elapsedInEpisode + delayMs > KICKOUT_RECOVERY_MAX_ELAPSED_MS) {
627
- const reason =
628
- delayMs === undefined
629
- ? `${KICKOUT_RECOVERY_DELAYS_MS.length} attempt(s) exhausted`
630
- : `${Math.round(KICKOUT_RECOVERY_MAX_ELAPSED_MS / 1000)}s recovery budget exhausted`
631
- logger.error(
632
- `[kakaotalk] session is DEAD after KICKOUT — ${reason}. ` +
633
- 'Likely a real cross-device login is fighting our session. ' +
634
- 'Stop the other client, then run `typeclaw restart`. ' +
635
- 'If the conflict persists, run `typeclaw channel reauth kakaotalk` to mint a fresh sub-device session ' +
636
- '(the existing device_uuid is preserved by default so the new login skips phone-passcode confirmation).',
637
- )
638
- resetRecoveryEpisode()
639
- return
640
- }
641
- episode.attemptCount = nextAttemptIndex + 1
642
- logger.warn(
643
- `[kakaotalk] KICKOUT during recovery episode (attempt ${episode.attemptCount}/${KICKOUT_RECOVERY_DELAYS_MS.length}, episode_elapsed=${Math.round(elapsedInEpisode)}ms); reconnecting in ${delayMs}ms.`,
650
+ halt(
651
+ 'KakaoTalk ended this session (KICKOUT); not logging in again automatically. ' +
652
+ 'If another client uses the same device, stop it. Check the account in the KakaoTalk app, then run ' +
653
+ '`typeclaw restart`, or `typeclaw channel reauth kakaotalk` for a fresh sub-device session.',
644
654
  )
645
- scheduleRecovery(() => {
646
- if (!started || listener !== activeListener) return
647
- if (recoveryEpisode !== episode) return
648
- activeListener.start().catch((retryErr) => {
649
- logger.error(
650
- `[kakaotalk] KICKOUT auto-recovery failed: ${describeError(retryErr)}. Run \`typeclaw restart\` to retry.`,
651
- )
652
- })
653
- }, delayMs)
654
655
  })
655
656
  listener.on('message', (event) => {
656
657
  void handleMessageEvent(event)
@@ -658,10 +659,12 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
658
659
  listener.on('emoticon', (event) => {
659
660
  void handleEmoticonEvent(event)
660
661
  })
661
- listener.on('member_joined', () => {
662
+ listener.on('member_joined', (event) => {
663
+ roster.invalidate(event.chat_id)
662
664
  void channelResolver.refresh()
663
665
  })
664
- listener.on('member_left', () => {
666
+ listener.on('member_left', (event) => {
667
+ roster.invalidate(event.chat_id)
665
668
  void channelResolver.refresh()
666
669
  })
667
670
 
@@ -700,6 +703,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
700
703
  options.router.setTypingHeartbeatInterval('kakaotalk', KAKAO_TYPING_HEARTBEAT_MS)
701
704
  options.router.registerChannelNameResolver('kakaotalk', channelResolver.resolve)
702
705
  options.router.registerHistory('kakaotalk', historyCallback)
706
+ options.router.registerList('kakaotalk', listCallback)
703
707
  options.router.registerFetchAttachment('kakaotalk', fetchAttachmentCallback)
704
708
  options.router.registerMembership('kakaotalk', membershipResolver)
705
709
  },
@@ -714,6 +718,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
714
718
  typing.reset()
715
719
  options.router.unregisterChannelNameResolver('kakaotalk', channelResolver.resolve)
716
720
  options.router.unregisterHistory('kakaotalk', historyCallback)
721
+ options.router.unregisterList('kakaotalk', listCallback)
717
722
  options.router.unregisterFetchAttachment('kakaotalk', fetchAttachmentCallback)
718
723
  options.router.unregisterMembership('kakaotalk', membershipResolver)
719
724
  if (inflightInbounds > 0) {
@@ -731,13 +736,15 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
731
736
  }
732
737
  selfUserId = null
733
738
  connected = false
734
- lastConnectedAt = null
735
- resetRecoveryEpisode()
736
739
  },
737
740
 
738
741
  isConnected(): boolean {
739
742
  return connected && selfUserId !== null
740
743
  },
744
+
745
+ haltReason(): string | null {
746
+ return haltReason
747
+ },
741
748
  }
742
749
  }
743
750
 
@@ -786,6 +793,33 @@ function dropHint(reason: InboundDropReason): string {
786
793
  }
787
794
  }
788
795
 
796
+ function guardLoginRejections(client: KakaoTalkClient, onError: (err: unknown) => void): KakaoTalkClient {
797
+ return new Proxy(client, {
798
+ get(target, prop, receiver) {
799
+ const value: unknown = Reflect.get(target, prop, receiver)
800
+ if (typeof value !== 'function') return value
801
+ return (...args: unknown[]): unknown => {
802
+ const result: unknown = value.apply(target, args)
803
+ if (!(result instanceof Promise)) return result
804
+ return result.catch((err: unknown) => {
805
+ onError(err)
806
+ throw err
807
+ })
808
+ }
809
+ },
810
+ })
811
+ }
812
+
813
+ // The SDK maps every non-zero LOGINLIST status to KakaoTalkError code
814
+ // `login_rejected`, or `invalid_access_token` for -950. Transport failures
815
+ // carry other codes and stay retryable.
816
+ function kakaoLoginRejectionStatus(err: unknown): number | null {
817
+ if (!(err instanceof Error)) return null
818
+ const { code, serverStatus } = err as { code?: unknown; serverStatus?: unknown }
819
+ if (code !== 'login_rejected' && code !== 'invalid_access_token') return null
820
+ return typeof serverStatus === 'number' ? serverStatus : 0
821
+ }
822
+
789
823
  function isKickoutError(err: unknown): boolean {
790
824
  if (!(err instanceof Error)) return false
791
825
  return err.message.includes('kicked') || err.message.includes('KICKOUT')
@@ -148,18 +148,28 @@ export function normalizeTeamsText(text: string): string {
148
148
  // ONLY thing standing between the agent and answering its own message. That
149
149
  // makes the comparison worth hardening: we fingerprint what we handed the SDK,
150
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.
151
+ // and the two sides are not the same string. How many entity layers come back
152
+ // depends on the SDK and the message shape: a tag-free channel body without a
153
+ // `messagetype` returns still escaped, a typed body is decoded once, and older
154
+ // SDKs decoded lossily (`&amp;lt;` -> `<`). Any mismatch would miss the
155
+ // reservation and route the agent's message back in as inbound. Decoding both
156
+ // sides until no entity layer remains gives the same key for every one of those
157
+ // shapes; on text holding no entities it is a no-op.
157
158
  export function teamsEchoTextKey(text: string): string {
158
- const decoded = text
159
+ let decoded = text
160
+ for (;;) {
161
+ const next = decodeTeamsEntities(decoded)
162
+ if (next === decoded) break
163
+ decoded = next
164
+ }
165
+ return normalizeTeamsText(decoded)
166
+ }
167
+
168
+ function decodeTeamsEntities(text: string): string {
169
+ return text
159
170
  .replace(/&amp;/g, '&')
160
171
  .replace(/&lt;/g, '<')
161
172
  .replace(/&gt;/g, '>')
162
173
  .replace(/&quot;/g, '"')
163
174
  .replace(/&#39;/g, "'")
164
- return normalizeTeamsText(decoded)
165
175
  }
@@ -301,18 +301,22 @@ export class GithubReviewCheckTracker {
301
301
 
302
302
  // For a verdict posted without the reviewed head: only reviews that already
303
303
  // finished on this PR can be the ones it reports.
304
+ // When a reviewed head is supplied, complete only that commit's posting reviews.
304
305
  async completePostingReviews(
305
306
  repo: string,
306
307
  pullRequest: number,
307
308
  state: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED',
309
+ headSha?: string,
308
310
  ): Promise<void> {
309
311
  const canonical = canonicalGithubRepo(repo)
312
+ const normalizedHead = headSha?.toLocaleLowerCase()
310
313
  const matching = [...this.leases.values()].filter(
311
314
  (lease) =>
312
315
  lease.outcome === undefined &&
313
316
  lease.phase === 'posting' &&
314
317
  lease.key.repo === canonical &&
315
- lease.key.pullRequest === pullRequest,
318
+ lease.key.pullRequest === pullRequest &&
319
+ (normalizedHead === undefined || lease.key.headSha === normalizedHead),
316
320
  )
317
321
  await Promise.all(matching.map((lease) => this.finish(lease, { kind: 'verdict', state })))
318
322
  }