typeclaw 0.48.10 → 0.48.12

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 (68) hide show
  1. package/package.json +2 -2
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +86 -16
  5. package/src/agent/index.ts +11 -1
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  12. package/src/bundled-plugins/github-cli-auth/index.ts +2 -1
  13. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  14. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  15. package/src/channels/adapters/github/inbound.ts +195 -25
  16. package/src/channels/adapters/github/index.ts +16 -18
  17. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  18. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  19. package/src/channels/adapters/github/review-submitter.ts +28 -0
  20. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  21. package/src/channels/adapters/kakaotalk.ts +7 -8
  22. package/src/channels/adapters/teams-classify.ts +21 -0
  23. package/src/channels/adapters/teams-edit.ts +2 -1
  24. package/src/channels/adapters/teams-format.ts +16 -0
  25. package/src/channels/adapters/teams.ts +12 -5
  26. package/src/channels/github-repo.ts +11 -0
  27. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  28. package/src/channels/github-verdict-activity.ts +10 -6
  29. package/src/channels/manager.ts +9 -0
  30. package/src/channels/persistence.ts +28 -2
  31. package/src/channels/router.ts +284 -61
  32. package/src/channels/schema.ts +18 -0
  33. package/src/channels/types.ts +1 -0
  34. package/src/cli/compose.ts +3 -3
  35. package/src/cli/docker-preflight.ts +8 -4
  36. package/src/cli/restart.ts +89 -23
  37. package/src/cli/start.ts +68 -16
  38. package/src/cli/status.ts +38 -6
  39. package/src/cli/stop.ts +5 -2
  40. package/src/compose/stop.ts +5 -4
  41. package/src/config/config.ts +9 -1
  42. package/src/container/build-cache.ts +807 -0
  43. package/src/container/compose-project.ts +4 -0
  44. package/src/container/docker-app.ts +74 -0
  45. package/src/container/log-archive.ts +33 -5
  46. package/src/container/memory-limit.ts +80 -0
  47. package/src/container/memory-oversubscription.ts +125 -0
  48. package/src/container/restart.ts +6 -1
  49. package/src/container/shared.ts +43 -16
  50. package/src/container/start.ts +313 -77
  51. package/src/container/stop.ts +19 -13
  52. package/src/container/verify-running.ts +12 -0
  53. package/src/cron/scheduler.ts +12 -4
  54. package/src/doctor/apparmor.ts +101 -0
  55. package/src/doctor/bounded-exec.ts +14 -0
  56. package/src/doctor/checks.ts +42 -15
  57. package/src/doctor/index.ts +14 -2
  58. package/src/doctor/plugin-bridge.ts +15 -3
  59. package/src/hostd/paths.ts +4 -0
  60. package/src/init/dockerfile.ts +7 -6
  61. package/src/init/windows-dev-link.ts +34 -2
  62. package/src/run/index.ts +17 -0
  63. package/src/run/resource-sample.ts +171 -0
  64. package/src/sandbox/availability.ts +7 -5
  65. package/src/sandbox/index.ts +8 -1
  66. package/src/sandbox/session-tmp.ts +26 -1
  67. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  68. package/typeclaw.schema.json +7 -0
@@ -1,3 +1,4 @@
1
+ import { githubReviewerWorkKey } from '@/channels/github-repo'
1
2
  import type {
2
3
  ReviewFinding,
3
4
  ReviewSubmitter,
@@ -8,9 +9,21 @@ import type {
8
9
 
9
10
  import type { GithubAuthContext } from './auth'
10
11
  import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
12
+ import { createBoundedMap } from './dedup'
11
13
 
12
14
  const MAX_HEAD_STABILITY_ATTEMPTS = 3
13
15
 
16
+ // Bounded because a long-lived container accumulates one entry per drafted PR
17
+ // forever otherwise. Eviction is fail-safe: a submission that captured a bumped
18
+ // generation sees the evicted key read back as 0, mismatches, and is denied —
19
+ // eviction can only cancel a submission, never resurrect a cancelled one.
20
+ const reviewSubmissionGenerations = createBoundedMap<string, number>()
21
+
22
+ export function invalidateGithubReviewSubmission(workspace: string, prNumber: number): void {
23
+ const key = githubReviewerWorkKey(workspace, prNumber)
24
+ reviewSubmissionGenerations.set(key, currentReviewSubmissionGeneration(workspace, prNumber) + 1)
25
+ }
26
+
14
27
  export function createGithubReviewSubmitter(deps: {
15
28
  token: (context?: GithubAuthContext) => Promise<string>
16
29
  allowApprove: () => boolean
@@ -27,6 +40,7 @@ export function createGithubReviewSubmitter(deps: {
27
40
  code: 'transient',
28
41
  }
29
42
  }
43
+ const submissionGeneration = currentReviewSubmissionGeneration(req.workspace, target.prNumber)
30
44
 
31
45
  const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
32
46
  const stable = await fetchStableAnchors(fetchImpl, token, target)
@@ -35,6 +49,16 @@ export function createGithubReviewSubmitter(deps: {
35
49
  const { inline, reanchored } = partitionComments(req.comments, stable.anchors)
36
50
  const downgraded = req.event === 'APPROVE' && !deps.allowApprove()
37
51
  const event = downgraded ? 'COMMENT' : req.event
52
+ if (currentReviewSubmissionGeneration(req.workspace, target.prNumber) !== submissionGeneration) {
53
+ return {
54
+ ok: false,
55
+ error: 'PR converted to draft; review submission cancelled',
56
+ code: 'transient',
57
+ }
58
+ }
59
+ // Once this call dispatches fetch(), GitHub may already have accepted the
60
+ // review. Let posting, verification, and accounting settle after that
61
+ // boundary; cancelling mid-flight would leave duplicate/state ambiguity.
38
62
  const posted = await postReview(fetchImpl, token, target, {
39
63
  event,
40
64
  body: appendReanchored(req.body, reanchored),
@@ -54,6 +78,10 @@ export function createGithubReviewSubmitter(deps: {
54
78
  }
55
79
  }
56
80
 
81
+ function currentReviewSubmissionGeneration(workspace: string, prNumber: number): number {
82
+ return reviewSubmissionGenerations.get(githubReviewerWorkKey(workspace, prNumber)) ?? 0
83
+ }
84
+
57
85
  async function fetchStableAnchors(
58
86
  fetchImpl: typeof fetch,
59
87
  token: string,
@@ -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()
@@ -0,0 +1,11 @@
1
+ export function canonicalGithubRepo(repo: string): string {
2
+ return repo
3
+ .trim()
4
+ .replace(/\/+$/, '')
5
+ .replace(/\.git$/i, '')
6
+ .toLocaleLowerCase()
7
+ }
8
+
9
+ export function githubReviewerWorkKey(repo: string, prNumber: number): string {
10
+ return `reviewer:github:${canonicalGithubRepo(repo)}#${prNumber}`
11
+ }