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
@@ -154,6 +154,22 @@ export async function processVerifiedGithubDelivery(
154
154
  ))
155
155
  }
156
156
  }
157
+ let staleRecoveredRemoval = false
158
+ // A recovered removal can arrive after a newer re-request was admitted. Applying it
159
+ // would cancel that request's check run and erase its pending replay entry.
160
+ if (input.recovered === true && eventAllowed && event === 'pull_request' && action === 'review_request_removed') {
161
+ const repository = readRepository(payload)
162
+ const prNumber = readNumber(readRecord(payload.pull_request), 'number')
163
+ if (repository !== null && prNumber !== null) {
164
+ staleRecoveredRemoval = await recoveredReviewerIsRequestedAgain(
165
+ options,
166
+ repository,
167
+ prNumber,
168
+ payload,
169
+ `${repository.owner}/${repository.name}`,
170
+ )
171
+ }
172
+ }
157
173
  const isSynchronize = event === 'pull_request' && action === 'synchronize'
158
174
  if (!isSynchronize && delivery !== '') {
159
175
  if (options.dedup.has(delivery)) {
@@ -172,7 +188,7 @@ export async function processVerifiedGithubDelivery(
172
188
  options.dedup.add(delivery)
173
189
  }
174
190
 
175
- if (!eventAllowed || staleRecoveredDraft) return
191
+ if (!eventAllowed || staleRecoveredDraft || staleRecoveredRemoval) return
176
192
 
177
193
  // This control event must run before the self-author drop: a maintainer can
178
194
  // draft the bot's PR, and the bot can draft its own PR. Either action must
@@ -230,6 +246,9 @@ export async function processVerifiedGithubDelivery(
230
246
  if (event === 'pull_request' && action === 'review_request_removed') {
231
247
  const prNumber = readNumber(readRecord(payload.pull_request), 'number')
232
248
  if (prNumber !== null) {
249
+ // Withdrawn work must not survive in the pending log, or the next boot's
250
+ // pending replay reviews a PR nobody asked for anymore.
251
+ await options.clearPendingReview?.(classified.workspace, prNumber)
233
252
  void githubReviewChecks.cancelPullRequest(classified.workspace, prNumber, 'the review request was removed')
234
253
  }
235
254
  }
@@ -386,6 +405,46 @@ async function recoveredPullRequestIsStillDraft(
386
405
  }
387
406
  }
388
407
 
408
+ async function recoveredReviewerIsRequestedAgain(
409
+ options: GithubWebhookHandlerOptions,
410
+ repository: { owner: string; name: string },
411
+ prNumber: number,
412
+ payload: Record<string, unknown>,
413
+ workspace: string,
414
+ ): Promise<boolean> {
415
+ const removedLogin = readUser(payload.requested_reviewer)?.login ?? null
416
+ const removedTeam = readReviewerTeam(payload.requested_team)?.slug ?? null
417
+ if (removedLogin === null && removedTeam === null) return false
418
+ if (options.authToken === undefined) {
419
+ throw new Error(`recovered review request removal check unavailable for ${workspace}#${prNumber}: auth unavailable`)
420
+ }
421
+ try {
422
+ const token = await options.authToken({ repoSlug: workspace })
423
+ const response = await (options.fetchImpl ?? fetch)(
424
+ `${GITHUB_API_BASE}/repos/${repository.owner}/${repository.name}/pulls/${prNumber}/requested_reviewers`,
425
+ { headers: githubJsonHeaders(token) },
426
+ )
427
+ if (!response.ok) {
428
+ throw new Error(`requested reviewers fetch returned ${response.status}`)
429
+ }
430
+ const current = readRecord(await response.json().catch(() => null))
431
+ if (!Array.isArray(current?.users) || !Array.isArray(current?.teams)) {
432
+ throw new Error('requested reviewers response missing users or teams')
433
+ }
434
+ const requestedAgain =
435
+ (removedLogin !== null && current.users.some((user) => readUser(user)?.login === removedLogin)) ||
436
+ (removedTeam !== null && current.teams.some((team) => readReviewerTeam(team)?.slug === removedTeam))
437
+ if (requestedAgain) {
438
+ options.logger.info(
439
+ `[github] recovered review request removal skipped for ${workspace}#${prNumber}: reviewer was requested again`,
440
+ )
441
+ }
442
+ return requestedAgain
443
+ } catch (err) {
444
+ throw new Error(`recovered review request removal check failed for ${workspace}#${prNumber}: ${describeError(err)}`)
445
+ }
446
+ }
447
+
389
448
  function scheduleDraftAbort(input: {
390
449
  workspace: string
391
450
  prNumber: number
@@ -22,7 +22,7 @@ import { createGithubChannelNameResolver } from './channel-resolver'
22
22
  import { createDeliveryDedup } from './dedup'
23
23
  import { findPermissionGaps } from './event-permissions'
24
24
  import { createGithubFetchAttachmentCallback } from './fetch-attachment'
25
- import { createGithubHistoryCallback } from './history'
25
+ import { createChatWorkspaceIndex, createGithubHistoryCallback } from './history'
26
26
  import { createGithubWebhookHandler, processVerifiedGithubDelivery, type GithubWebhookHandlerOptions } from './inbound'
27
27
  import { readGithubLastAlive, writeGithubLastAlive } from './last-alive'
28
28
  import { applyManagedPath, buildManagedPath, resolveAgentId } from './managed-path'
@@ -134,6 +134,16 @@ const MAX_RECOVERED_PER_SWEEP = 50
134
134
  // durable cooldown store, so a tick is cheap when nothing new needs review.
135
135
  const DEFAULT_RECONCILE_INTERVAL_MS = 30 * 60 * 1000
136
136
 
137
+ // Pending reviews admitted during this process, keyed by its router. A tunnel URL change
138
+ // rebuilds and restarts the adapter seconds after boot, but the router and the review
139
+ // turns it already admitted keep running. The boot replay exists for work an earlier
140
+ // process lost, so a later start in the same process must not admit that work again.
141
+ const pendingAdmissionsByRouter = new WeakMap<object, Set<string>>()
142
+
143
+ function pendingAdmissionKey(repo: string, prNumber: number, work: { headSha: string; kind: string }): string {
144
+ return `${canonicalGithubRepo(repo)}#${prNumber}@${work.headSha}:${work.kind}`
145
+ }
146
+
137
147
  export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapter {
138
148
  const logger = options.logger ?? consoleLogger
139
149
  const fetchImpl = options.fetchImpl ?? fetch
@@ -156,7 +166,10 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
156
166
  let stopObservingDismissals: (() => void) | null = null
157
167
  let lifecycleGeneration = 0
158
168
  let unregisterTokenBridge: (() => void) | null = null
159
- const workspaceByChat = new Map<string, string>()
169
+ let unregisterSelfBridge: (() => void) | null = null
170
+ const workspaceByChat = createChatWorkspaceIndex()
171
+ const pendingAdmissions = pendingAdmissionsByRouter.get(options.router) ?? new Set<string>()
172
+ pendingAdmissionsByRouter.set(options.router, pendingAdmissions)
160
173
  const setIntervalFn =
161
174
  options.setInterval ??
162
175
  ((handler: () => void, ms: number) => {
@@ -165,7 +178,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
165
178
  })
166
179
 
167
180
  const rememberWorkspace = (workspace: string, chat: string): void => {
168
- workspaceByChat.set(chat, workspace)
181
+ workspaceByChat.remember(workspace, chat)
169
182
  }
170
183
 
171
184
  // Repo/owner-aware token resolver. A single GitHub App can span multiple
@@ -224,7 +237,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
224
237
  const history = createGithubHistoryCallback({
225
238
  token: authToken,
226
239
  fetchImpl,
227
- workspaceForChat: (chat) => workspaceByChat.get(chat) ?? null,
240
+ workspaceForChat: workspaceByChat.resolve,
228
241
  })
229
242
  const membership = createGithubMembershipResolver({ token: authToken, fetchImpl })
230
243
  const reviewThreadResolver = createGithubReviewThreadResolver({
@@ -285,7 +298,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
285
298
  const pending = message.githubPendingReview
286
299
  const prNumber = /^pr:(\d+)$/.exec(message.chat)?.[1]
287
300
  // The webhook handler schedules this outside its acknowledgment path.
288
- return options.router.route(
301
+ const receipt = await options.router.route(
289
302
  {
290
303
  ...message,
291
304
  accountIdentity: message.accountIdentity ?? (selfId === null ? undefined : `github:${selfId}`),
@@ -305,6 +318,11 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
305
318
  })
306
319
  : undefined,
307
320
  )
321
+ // Only newly accepted work runs in this process. The router also invokes the admission
322
+ // callback for an open duplicate, such as a redelivered trigger from a process that died.
323
+ if (receipt.kind === 'accepted' && pending !== undefined && prNumber !== undefined)
324
+ pendingAdmissions.add(pendingAdmissionKey(message.workspace, Number(prNumber), pending))
325
+ return receipt
308
326
  }
309
327
  const handlerOptions: GithubWebhookHandlerOptions = {
310
328
  webhookSecret,
@@ -469,6 +487,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
469
487
  () => selfLogin,
470
488
  )
471
489
  }
490
+ unregisterSelfBridge = options.githubTokenBridge?.registerSelf(self) ?? null
472
491
  logger.info(`[github] webhook listening on port ${options.configRef().webhookPort} as @${self.login}`)
473
492
  // Attach before any webhook can start a review, and close checks a
474
493
  // previous process left in progress.
@@ -604,6 +623,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
604
623
  fetchImpl,
605
624
  pendingStore: loadedPendingReviewStore,
606
625
  replayId,
626
+ admittedThisProcess: (entry) => pendingAdmissions.has(pendingAdmissionKey(entry.repo, entry.prNumber, entry)),
607
627
  isCancelled: () => reconcileGeneration !== lifecycleGeneration,
608
628
  })
609
629
  .catch((error: unknown) => {
@@ -709,6 +729,8 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
709
729
  unregisterTokenBridge()
710
730
  unregisterTokenBridge = null
711
731
  }
732
+ unregisterSelfBridge?.()
733
+ unregisterSelfBridge = null
712
734
  await auth.dispose()
713
735
  if (options.secrets.auth.type === 'pat') delete process.env.GH_TOKEN
714
736
  server = null
@@ -102,7 +102,12 @@ const submittedReviewsSchema = z.array(
102
102
  // This path deliberately does not consult the scan age or launch cooldown. Each
103
103
  // boot needs a fresh identity: the previous admission may be the interrupted one.
104
104
  export async function replayPendingReviews(
105
- options: ReconcileOpenPrsOptions & { pendingStore: PendingReviewStore; replayId: string },
105
+ options: ReconcileOpenPrsOptions & {
106
+ pendingStore: PendingReviewStore
107
+ replayId: string
108
+ // Work this process already admitted is still live in the router; only lost work replays.
109
+ admittedThisProcess?: (entry: PendingReview) => boolean
110
+ },
106
111
  ): Promise<void> {
107
112
  if (options.reviewOn === 'off' || options.selfLogin === null) return
108
113
  const repos = new Set(options.repos.map(canonicalGithubRepo))
@@ -110,6 +115,7 @@ export async function replayPendingReviews(
110
115
  for (const entry of await options.pendingStore.list()) {
111
116
  if (options.isCancelled?.() === true) return
112
117
  if (!repos.has(canonicalGithubRepo(entry.repo))) continue
118
+ if (options.admittedThisProcess?.(entry) === true) continue
113
119
  try {
114
120
  const target = parseRepo(entry.repo)
115
121
  if (target === null) continue
@@ -8,7 +8,7 @@ export type KakaoAuthorResolver = {
8
8
  }
9
9
 
10
10
  export type KakaoAuthorResolverOptions = {
11
- client: Pick<KakaoTalkClient, 'getMembers'>
11
+ client: Pick<KakaoTalkClient, 'getMemberSnapshot'>
12
12
  now?: () => number
13
13
  ttlMs?: number
14
14
  logger?: { warn: (msg: string) => void }
@@ -40,10 +40,12 @@ export function createKakaoAuthorResolver(options: KakaoAuthorResolverOptions):
40
40
  const existing = inflight.get(chatId)
41
41
  if (existing !== undefined) return existing
42
42
  const promise = options.client
43
- .getMembers(chatId)
44
- .then((members): ChatCacheEntry => {
43
+ .getMemberSnapshot(chatId, { allowPartial: true })
44
+ .then((snapshot): ChatCacheEntry => {
45
+ // A partial roster still names most authors; misses fall back to the
46
+ // raw user_id exactly as a failed read does.
45
47
  const map = new Map<string, string>()
46
- for (const m of members) map.set(m.user_id, m.nickname)
48
+ for (const m of snapshot.members) map.set(m.user_id, m.nickname)
47
49
  const entry: ChatCacheEntry = { members: map, expiresAt: now() + ttlMs }
48
50
  cache.set(chatId, entry)
49
51
  return entry
@@ -51,7 +53,7 @@ export function createKakaoAuthorResolver(options: KakaoAuthorResolverOptions):
51
53
  .catch((err: unknown): null => {
52
54
  // Author resolution is best-effort. Failing here makes the message
53
55
  // render with the raw user_id, which is uglier but still routes.
54
- logger?.warn(`[kakaotalk] getMembers(${chatId}) failed: ${describeError(err)}`)
56
+ logger?.warn(`[kakaotalk] getMemberSnapshot(${chatId}) failed: ${describeError(err)}`)
55
57
  return null
56
58
  })
57
59
  .finally(() => {
@@ -1,16 +1,16 @@
1
- import {
2
- classifyKakaoChat,
3
- type KakaoChat,
4
- type KakaoChatKind,
5
- type KakaoMember,
6
- type KakaoTalkClient,
7
- } from 'agent-messenger/kakaotalk'
1
+ import { classifyKakaoChat, type KakaoChat, type KakaoChatKind, type KakaoMember } from 'agent-messenger/kakaotalk'
8
2
 
9
3
  import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
10
4
 
11
5
  import { describeError } from '../describe-error'
6
+ import type { KakaoTalkClient } from './kakaotalk'
12
7
 
13
- const DEFAULT_TTL_MS = 5 * 60 * 1000
8
+ // Chat names and kinds rarely change, and membership pushes trigger a refresh
9
+ // anyway, so a long TTL costs little. Every refresh is a full LCHATLIST walk,
10
+ // and the floor stops failed or unknown-chat lookups from re-walking the chat
11
+ // list on every message.
12
+ const DEFAULT_TTL_MS = 30 * 60 * 1000
13
+ const DEFAULT_MIN_REFRESH_INTERVAL_MS = 60 * 1000
14
14
 
15
15
  export type KakaoWorkspace = '@kakao-dm' | '@kakao-group' | '@kakao-open'
16
16
 
@@ -35,10 +35,9 @@ export type KakaoChatLookupValue = {
35
35
 
36
36
  // What a member roster PROVES about a chat — never what it merely suggests.
37
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:
38
+ // A roster read is only ever a SUBSET of the true membership: it is read with
39
+ // `allowPartial`, and GETMEM can return fewer records than the room has active
40
+ // members. So only conclusions that survive adding unseen members are sound:
42
41
  //
43
42
  // - an open marker present proves OpenChat — a subset cannot invent one
44
43
  // (`open_token` / `open_profile_link_id` / `open_permission` are
@@ -84,9 +83,11 @@ export type KakaoChannelResolver = {
84
83
  }
85
84
 
86
85
  export type KakaoChannelResolverOptions = {
87
- client: Pick<KakaoTalkClient, 'getChats' | 'getMembers'>
86
+ client: Pick<KakaoTalkClient, 'getChats' | 'getMemberSnapshot'>
88
87
  now?: () => number
89
88
  ttlMs?: number
89
+ minRefreshIntervalMs?: number
90
+ scheduleRefresh?: (fn: () => void, delayMs: number) => void
90
91
  logger?: { warn: (msg: string) => void }
91
92
  selfUserId?: () => string | null
92
93
  }
@@ -102,14 +103,43 @@ type Entry = {
102
103
  export function createKakaoChannelResolver(options: KakaoChannelResolverOptions): KakaoChannelResolver {
103
104
  const now = options.now ?? Date.now
104
105
  const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
106
+ const minRefreshIntervalMs = options.minRefreshIntervalMs ?? DEFAULT_MIN_REFRESH_INTERVAL_MS
105
107
  const cache = new Map<string, Entry>()
106
108
  let inflight: Promise<void> | null = null
109
+ let lastRefreshAt: number | null = null
110
+ let trailingScheduled = false
111
+ const scheduleRefresh =
112
+ options.scheduleRefresh ??
113
+ ((fn: () => void, delayMs: number): void => {
114
+ setTimeout(fn, delayMs).unref?.()
115
+ })
116
+
117
+ // A suppressed refresh still owes one: a chat first seen inside the floor
118
+ // (a new DM) is filed provisionally under the strict group bucket, and only a
119
+ // real chat-list walk can upgrade it. Coalesce every suppressed request into
120
+ // one trailing refresh when the floor expires.
121
+ const scheduleTrailingRefresh = (waitMs: number): void => {
122
+ if (trailingScheduled) return
123
+ trailingScheduled = true
124
+ scheduleRefresh(() => {
125
+ trailingScheduled = false
126
+ void refresh()
127
+ }, waitMs)
128
+ }
107
129
 
108
130
  const refresh = async (): Promise<void> => {
109
131
  if (inflight !== null) {
110
132
  await inflight
111
133
  return
112
134
  }
135
+ if (lastRefreshAt !== null) {
136
+ const waitMs = lastRefreshAt + minRefreshIntervalMs - now()
137
+ if (waitMs > 0) {
138
+ scheduleTrailingRefresh(waitMs)
139
+ return
140
+ }
141
+ }
142
+ lastRefreshAt = now()
113
143
  const promise = loadAll().finally(() => {
114
144
  inflight = null
115
145
  })
@@ -167,8 +197,8 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
167
197
 
168
198
  const provenKindFor = async (chatId: string): Promise<'open' | 'group' | null> => {
169
199
  try {
170
- const members = await options.client.getMembers(chatId)
171
- return provenKindFromMembers(members, options.selfUserId?.() ?? null)
200
+ const snapshot = await options.client.getMemberSnapshot(chatId, { allowPartial: true })
201
+ return provenKindFromMembers(snapshot.members, options.selfUserId?.() ?? null)
172
202
  } catch (err) {
173
203
  options.logger?.warn(`[kakaotalk] provisional member lookup failed chat=${chatId}: ${describeError(err)}`)
174
204
  return null
@@ -59,13 +59,11 @@ export function classifyInbound(
59
59
  return { kind: 'drop', reason: 'unknown_chat' }
60
60
  }
61
61
 
62
- // KakaoTalk has no native @-mention syntax in the LOCO protocol that the
63
- // SDK exposes (mention rendering happens client-side via display_name
64
- // matching). Mention-equivalent engagement comes solely from alias
65
- // matching, which the engagement layer treats as equivalent to a direct
66
- // mention (see engagement.ts: alias is unconditional and ranks alongside
67
- // explicit triggers). Without aliases configured, only `reply` and `dm`
68
- // triggers can fire on KakaoTalk.
62
+ // A native @-tag carries the tagged user ids in `mentions`. Alias matching
63
+ // stays alongside it because people also address the bot by name without
64
+ // tagging, which the engagement layer treats as equivalent to a mention.
65
+ const mentionedUserIds = (event.mentions ?? []).map((m) => m.user_id)
66
+ const botTagged = mentionedUserIds.includes(context.selfUserId)
69
67
  const aliasMatched = matchesAnyAlias(rawText, context.selfAliases ?? [])
70
68
 
71
69
  return {
@@ -84,9 +82,9 @@ export function classifyInbound(
84
82
  authorId: String(event.author_id),
85
83
  authorName: event.author_name ?? String(event.author_id),
86
84
  authorIsBot: false,
87
- isBotMention: aliasMatched,
85
+ isBotMention: botTagged || aliasMatched,
88
86
  replyToBotMessageId: replyContext?.target === 'bot' ? replyContext.logId : null,
89
- mentionsOthers: false,
87
+ mentionsOthers: mentionedUserIds.length > 0 && !botTagged,
90
88
  replyToOtherMessageId: replyContext?.target === 'other' ? replyContext.logId : null,
91
89
  isDm: chatInfo.isDm,
92
90
  // SDK delivers `sent_at` in Unix seconds (LOCO `sendAt`); contract
@@ -0,0 +1,62 @@
1
+ import { classifyKakaoChat, type KakaoChat } from 'agent-messenger/kakaotalk'
2
+
3
+ import type { ChannelListEntry, ListCallback, ListChannelsArgs, ListChannelsResult } from '@/channels/types'
4
+
5
+ import { describeError } from '../describe-error'
6
+ import type { KakaoTalkClient } from './kakaotalk'
7
+ import { kakaoWorkspaceForType, type KakaoWorkspace } from './kakaotalk-channel-resolver'
8
+
9
+ const KAKAO_WORKSPACES: readonly KakaoWorkspace[] = ['@kakao-dm', '@kakao-group', '@kakao-open']
10
+
11
+ // KakaoTalk has no server-side workspace: typeclaw buckets every chat into one
12
+ // of three synthetic workspaces by chat kind, and a later channel_send must
13
+ // name the same bucket. So the list is scoped to one bucket — returning every
14
+ // chat under an arbitrary workspace would hand back chat ids the agent cannot
15
+ // address. getChats has no paging, so the cursor is an offset into its result.
16
+ export function createKakaoListCallback(deps: {
17
+ client: Pick<KakaoTalkClient, 'getChats'>
18
+ logger: { warn: (msg: string) => void }
19
+ }): ListCallback {
20
+ return async (args: ListChannelsArgs): Promise<ListChannelsResult> => {
21
+ if (!isKakaoWorkspace(args.workspace)) {
22
+ return {
23
+ ok: false,
24
+ error: `unknown kakaotalk workspace "${args.workspace}"; use one of ${KAKAO_WORKSPACES.join(', ')}`,
25
+ }
26
+ }
27
+ let chats: KakaoChat[]
28
+ try {
29
+ // Without resolveTitles the SDK leaves `title` null, and a named room
30
+ // would only show its member names, so the agent couldn't find it by name.
31
+ chats = await deps.client.getChats({ all: true, resolveTitles: true })
32
+ } catch (err) {
33
+ const message = describeError(err)
34
+ deps.logger.warn(`[kakaotalk] chat list failed: ${message}`)
35
+ return { ok: false, error: message }
36
+ }
37
+ const inWorkspace = chats.filter((c) => kakaoWorkspaceForType(classifyKakaoChat(c)) === args.workspace)
38
+ const offset = parseOffset(args.cursor)
39
+ const end = offset + Math.max(1, args.limit)
40
+ const entries = inWorkspace.slice(offset, end).map(toListEntry)
41
+ return end < inWorkspace.length ? { ok: true, entries, nextCursor: String(end) } : { ok: true, entries }
42
+ }
43
+ }
44
+
45
+ function isKakaoWorkspace(workspace: string): workspace is KakaoWorkspace {
46
+ return (KAKAO_WORKSPACES as readonly string[]).includes(workspace)
47
+ }
48
+
49
+ function parseOffset(cursor: string | undefined): number {
50
+ const n = cursor === undefined ? 0 : Number.parseInt(cursor, 10)
51
+ return Number.isFinite(n) && n > 0 ? n : 0
52
+ }
53
+
54
+ function toListEntry(chat: KakaoChat): ChannelListEntry {
55
+ const kind = classifyKakaoChat(chat)
56
+ return {
57
+ chat: chat.chat_id,
58
+ name: chat.title ?? chat.display_name ?? chat.chat_id,
59
+ kind: kind === 'dm' ? 'dm' : 'group',
60
+ isMember: true,
61
+ }
62
+ }
@@ -0,0 +1,67 @@
1
+ import type { KakaoMemberSnapshot, KakaoPartialMemberSnapshot } from 'agent-messenger/kakaotalk'
2
+
3
+ import type { KakaoTalkClient } from './kakaotalk'
4
+
5
+ const DEFAULT_TTL_MS = 5 * 60 * 1000
6
+ const DEFAULT_FAILURE_TTL_MS = 60 * 1000
7
+
8
+ type Snapshot = KakaoMemberSnapshot | KakaoPartialMemberSnapshot
9
+
10
+ export type KakaoRosterRead = { snapshot: Snapshot; fetchedAt: number }
11
+
12
+ type Entry = { result: Promise<KakaoRosterRead>; expiresAt: number }
13
+
14
+ export type KakaoMemberSnapshotCache = Pick<KakaoTalkClient, 'getMemberSnapshot'> & {
15
+ // `fetchedAt` is when the server answered, never when the cache served it:
16
+ // freshness checks (grant_role's one-minute membership proof) must not be
17
+ // satisfied by an old roster replayed from cache.
18
+ readMemberSnapshot: (chatId: string) => Promise<KakaoRosterRead>
19
+ invalidate: (chatId: string) => void
20
+ }
21
+
22
+ // One GETMEM per chat per TTL, shared by every roster consumer (author names,
23
+ // membership counts, mention tags, provisional chat kinds). Each consumer used
24
+ // to read the roster on its own, so one inbound message in a group could fire
25
+ // several GETMEMs, and a failing read was retried on every message. KakaoTalk
26
+ // is a personal account: request volume like that reads as automation and
27
+ // risks an account restriction. Failures are cached for a shorter window so a
28
+ // transient error heals without hammering the server.
29
+ export function createKakaoMemberSnapshotCache(options: {
30
+ client: Pick<KakaoTalkClient, 'getMemberSnapshot'>
31
+ now?: () => number
32
+ ttlMs?: number
33
+ failureTtlMs?: number
34
+ }): KakaoMemberSnapshotCache {
35
+ const now = options.now ?? Date.now
36
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
37
+ const failureTtlMs = options.failureTtlMs ?? DEFAULT_FAILURE_TTL_MS
38
+ const cache = new Map<string, Entry>()
39
+
40
+ // Keyed by chat alone: every caller reads with `allowPartial: true`.
41
+ const read = (chatId: string, readOptions: { allowPartial: true }): Promise<KakaoRosterRead> => {
42
+ const cached = cache.get(chatId)
43
+ if (cached !== undefined && cached.expiresAt > now()) return cached.result
44
+ const entry: Entry = { result: Promise.resolve(null as never), expiresAt: Number.POSITIVE_INFINITY }
45
+ entry.result = options.client.getMemberSnapshot(chatId, readOptions).then(
46
+ (snapshot) => {
47
+ const fetchedAt = now()
48
+ entry.expiresAt = fetchedAt + ttlMs
49
+ return { snapshot, fetchedAt }
50
+ },
51
+ (err: unknown) => {
52
+ entry.expiresAt = now() + failureTtlMs
53
+ throw err
54
+ },
55
+ )
56
+ cache.set(chatId, entry)
57
+ return entry.result
58
+ }
59
+
60
+ return {
61
+ getMemberSnapshot: async (chatId, readOptions) => (await read(chatId, readOptions)).snapshot,
62
+ readMemberSnapshot: (chatId) => read(chatId, { allowPartial: true }),
63
+ invalidate: (chatId) => {
64
+ cache.delete(chatId)
65
+ },
66
+ }
67
+ }
@@ -6,10 +6,11 @@ import type {
6
6
  MembershipResolverResult,
7
7
  } from '../membership'
8
8
  import type { KakaoTalkClient } from './kakaotalk'
9
+ import type { KakaoMemberSnapshotCache } from './kakaotalk-member-cache'
9
10
 
10
11
  export type KakaoMembershipResolverOptions = {
11
- client: Pick<KakaoTalkClient, 'getMembers'>
12
- // The logged-in agent's own KakaoTalk user_id. Returned by `getMembers`
12
+ client: Pick<KakaoTalkClient, 'getMemberSnapshot'>
13
+ // The logged-in agent's own KakaoTalk user_id. Returned in the roster
13
14
  // alongside every human in the room, so it must be excluded from the
14
15
  // human count — otherwise a 1:1 chat (agent + one human) reports two
15
16
  // humans and a real group is off by one. Null before login completes,
@@ -17,6 +18,9 @@ export type KakaoMembershipResolverOptions = {
17
18
  selfUserIdRef: () => string | null
18
19
  logger: { warn: (msg: string) => void }
19
20
  now?: () => number
21
+ // Cached roster reads carry the time the server answered, which becomes
22
+ // `fetchedAt`. Without it, a direct client read is stamped `now()`.
23
+ roster?: Pick<KakaoMemberSnapshotCache, 'readMemberSnapshot'>
20
24
  }
21
25
 
22
26
  // Without a registered resolver the router's `resolveEffectiveHumans` falls
@@ -24,9 +28,13 @@ export type KakaoMembershipResolverOptions = {
24
28
  // session. On a cold-started group that is just the sender, tripping the
25
29
  // engagement layer's solo-human "answer everything" fallback so the agent
26
30
  // replies to messages aimed at others. Every other adapter registers a
27
- // resolver; KakaoTalk was the lone gap. `getMembers` returns the COMPLETE
28
- // active roster (agent-messenger merges the GETMEM subset with the CHATONROOM
29
- // full list), so unlike Telegram's opaque count we report it as non-truncated.
31
+ // resolver; KakaoTalk was the lone gap. The roster is read with `allowPartial`:
32
+ // GETMEM can return fewer records than the room's active member count (large
33
+ // open chats), where the strict read throws on every call. A complete snapshot
34
+ // is reported as non-truncated with its member ids; a partial one is reported
35
+ // as truncated without ids, counting humans from the room's active member count, so consumers that need a completeness proof fail
36
+ // closed. We never opt into `allowRoomEntry`, because CHATONROOM can advance
37
+ // the account's unread state.
30
38
  // Room rosters list only human accounts plus the agent's own; hence
31
39
  // `humans = roster excluding self` and `bots: 1` (the agent) — `bots: 0` would
32
40
  // defeat the engagement layer's peer-bot loop suppression.
@@ -42,17 +50,26 @@ export function createKakaoMembershipResolver(options: KakaoMembershipResolverOp
42
50
  return { kind: 'transient' } satisfies MembershipResolverFailure
43
51
  }
44
52
  try {
45
- const members = await options.client.getMembers(key.chat)
46
- // Dedupe by user_id — a merged GETMEM+CHATONROOM roster can list the
47
- // same member twice when both sources carry them.
53
+ const { snapshot, fetchedAt } =
54
+ options.roster !== undefined
55
+ ? await options.roster.readMemberSnapshot(key.chat)
56
+ : { snapshot: await options.client.getMemberSnapshot(key.chat, { allowPartial: true }), fetchedAt: now() }
57
+ // Dedupe by user_id defensively; a roster should not repeat a member.
48
58
  const memberIds = new Set<string>()
49
- for (const m of members) memberIds.add(m.user_id)
59
+ for (const m of snapshot.members) memberIds.add(m.user_id)
50
60
  memberIds.delete(selfUserId)
51
61
  const humanMemberIds = [...memberIds]
62
+ if (!snapshot.complete) {
63
+ // The returned records can be a tiny slice of a large room. The
64
+ // server's active count (which includes the agent) keeps the
65
+ // approximate total from collapsing to the solo-human fallback.
66
+ const humans = Math.max(humanMemberIds.length, snapshot.active_members - 1)
67
+ return { humans, bots: 1, fetchedAt, truncated: true } satisfies MembershipCount
68
+ }
52
69
  return {
53
70
  humans: humanMemberIds.length,
54
71
  bots: 1,
55
- fetchedAt: now(),
72
+ fetchedAt,
56
73
  truncated: false,
57
74
  humanMemberIds,
58
75
  } satisfies MembershipCount
@@ -0,0 +1,61 @@
1
+ import type { KakaoMember, KakaoMentionInput } from 'agent-messenger/kakaotalk'
2
+
3
+ const WORD_CONTINUATION = /[\p{Script=Latin}\p{N}_]/u
4
+
5
+ // Turns `@<nickname>` tags the agent wrote into native KakaoTalk mentions for
6
+ // the chat's members. The SDK's `buildMentions` gives each `@` to the longest
7
+ // REQUESTED name that matches there and throws when a requested name wins no
8
+ // `@`. So a target is requested only when it wins an `@` among every member
9
+ // name, and a nickname two members share is never requested (its tag cannot
10
+ // pick one). Because the SDK only sees requested names, a shorter target could
11
+ // still claim an `@` whose real winner was such an ambiguous name; any target
12
+ // that would is dropped too, leaving that text untagged rather than mis-tagged.
13
+ export function resolveKakaoMentions(text: string, members: readonly KakaoMember[]): KakaoMentionInput[] {
14
+ if (!text.includes('@')) return []
15
+ const idByName = new Map<string, string | null>()
16
+ for (const m of members) {
17
+ if (m.nickname === '') continue
18
+ idByName.set(m.nickname, idByName.has(m.nickname) ? null : m.user_id)
19
+ }
20
+ const allNames = [...idByName.keys()]
21
+ const intendedWinners = atPositions(text).map((i) => longestTagAt(text, i, allNames))
22
+ const requested = new Set(intendedWinners.filter((n): n is string => n !== undefined && idByName.get(n) !== null))
23
+
24
+ for (let changed = true; changed; ) {
25
+ changed = false
26
+ atPositions(text).forEach((i, k) => {
27
+ const sdkWinner = longestTagAt(text, i, [...requested])
28
+ if (sdkWinner !== undefined && sdkWinner !== intendedWinners[k]) {
29
+ requested.delete(sdkWinner)
30
+ changed = true
31
+ }
32
+ })
33
+ }
34
+
35
+ return [...requested].map((name) => ({ user_id: idByName.get(name)!, name }))
36
+ }
37
+
38
+ function atPositions(text: string): number[] {
39
+ const positions: number[] = []
40
+ for (let i = text.indexOf('@'); i !== -1; i = text.indexOf('@', i + 1)) positions.push(i)
41
+ return positions
42
+ }
43
+
44
+ function longestTagAt(text: string, at: number, names: readonly string[]): string | undefined {
45
+ let best: string | undefined
46
+ for (const n of names) {
47
+ if (best !== undefined && n.length <= best.length) continue
48
+ if (text.startsWith(n, at + 1) && endsTag(text, at + 1 + n.length, n)) best = n
49
+ }
50
+ return best
51
+ }
52
+
53
+ // A Latin/digit-final name followed by another Latin/digit is a longer word,
54
+ // not a tag. Anything else may follow, since Korean particles attach directly
55
+ // to a name (`@연규님`).
56
+ function endsTag(text: string, end: number, name: string): boolean {
57
+ const next = text[end]
58
+ if (next === undefined) return true
59
+ const last = [...name].at(-1) ?? ''
60
+ return !(WORD_CONTINUATION.test(last) && WORD_CONTINUATION.test(next))
61
+ }