typeclaw 0.43.1 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +14 -2
  6. package/src/agent/multimodal/look-at.ts +27 -9
  7. package/src/agent/plugin-tools.ts +9 -4
  8. package/src/agent/session-origin.ts +1 -0
  9. package/src/agent/tools/channel-fetch-attachment.ts +45 -3
  10. package/src/agent/tools/channel-reply.ts +41 -18
  11. package/src/agent/tools/channel-send.ts +82 -13
  12. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  13. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  14. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  15. package/src/bundled-plugins/memory/README.md +9 -9
  16. package/src/bundled-plugins/memory/index.ts +40 -9
  17. package/src/channels/adapters/github/inbound.ts +20 -14
  18. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  19. package/src/channels/adapters/teams-classify.ts +144 -0
  20. package/src/channels/adapters/teams-id-token.ts +112 -0
  21. package/src/channels/adapters/teams-key.ts +32 -0
  22. package/src/channels/adapters/teams.ts +519 -0
  23. package/src/channels/github-review-turn-ledger.ts +43 -0
  24. package/src/channels/index.ts +1 -1
  25. package/src/channels/manager.ts +54 -1
  26. package/src/channels/router.ts +302 -39
  27. package/src/channels/schema.ts +9 -0
  28. package/src/cli/channel.ts +92 -4
  29. package/src/cli/hostd.ts +41 -0
  30. package/src/cli/init.ts +58 -1
  31. package/src/config/channels-mutation.ts +9 -1
  32. package/src/cron/index.ts +16 -4
  33. package/src/cron/reloadable.ts +25 -7
  34. package/src/cron/scheduler.ts +4 -0
  35. package/src/cron/schema.ts +143 -35
  36. package/src/doctor/channel-checks.ts +27 -0
  37. package/src/hostd/daemon.ts +23 -3
  38. package/src/hostd/protocol.ts +2 -0
  39. package/src/hostd/teams-renewal-manager.ts +212 -0
  40. package/src/init/checkpoint.ts +1 -1
  41. package/src/init/index.ts +68 -1
  42. package/src/init/run-owner-claim.ts +1 -0
  43. package/src/init/teams-auth.ts +111 -0
  44. package/src/inspect/label.ts +4 -0
  45. package/src/permissions/match-rule.ts +11 -1
  46. package/src/permissions/resolve.ts +1 -0
  47. package/src/role-claim/match-rule.ts +2 -1
  48. package/src/run/index.ts +35 -8
  49. package/src/run/llm-fetch-observer.ts +27 -5
  50. package/src/sandbox/build.ts +12 -0
  51. package/src/sandbox/policy.ts +13 -0
  52. package/src/sandbox/writable-zones.ts +46 -10
  53. package/src/secrets/schema.ts +32 -0
  54. package/src/secrets/teams-renewal.ts +229 -0
  55. package/src/secrets/teams-store.ts +108 -0
  56. package/typeclaw.schema.json +163 -3
@@ -9,7 +9,7 @@ const GRAPHQL_ENDPOINT = `${GITHUB_API_BASE}/graphql`
9
9
  // carry more, so the resolver paginates until it matches the root comment id
10
10
  // or exhausts the pages — stopping early on a 404-equivalent (thread absent)
11
11
  // rather than fabricating a node id.
12
- const THREADS_QUERY = `query($owner:String!,$name:String!,$number:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved comments(first:1){nodes{databaseId author{__typename login}}}}}}}}`
12
+ const THREADS_QUERY = `query($owner:String!,$name:String!,$number:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved path line comments(first:1){nodes{databaseId body author{__typename login}}}}}}}}`
13
13
 
14
14
  const RESOLVE_MUTATION = `mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{id isResolved}}}`
15
15
 
@@ -19,6 +19,9 @@ type ReviewThreadNode = {
19
19
  rootCommentId: number | null
20
20
  rootAuthorLogin: string | null
21
21
  rootAuthorIsBot: boolean
22
+ path: string | null
23
+ line: number | null
24
+ rootBody: string | null
22
25
  }
23
26
 
24
27
  type ThreadLookup =
@@ -147,7 +150,25 @@ async function findThread(fetchImpl: typeof fetch, token: string, target: Resolv
147
150
  return lookup
148
151
  }
149
152
 
150
- export type UnresolvedSelfReviewThread = { threadId: string; rootCommentId: number }
153
+ export type UnresolvedSelfReviewThread = {
154
+ threadId: string
155
+ rootCommentId: number
156
+ path: string | null
157
+ line: number | null
158
+ snippet: string | null
159
+ }
160
+
161
+ // One line of the root comment, capped, so the follow-up prompt can name each
162
+ // thread by its concern instead of a bare id — without dumping a multi-paragraph
163
+ // review comment into the system-facing instruction.
164
+ const SNIPPET_MAX_CHARS = 140
165
+
166
+ function firstLineSnippet(body: string | null): string | null {
167
+ if (body === null) return null
168
+ const firstLine = body.split('\n', 1)[0]?.trim() ?? ''
169
+ if (firstLine === '') return null
170
+ return firstLine.length > SNIPPET_MAX_CHARS ? `${firstLine.slice(0, SNIPPET_MAX_CHARS)}…` : firstLine
171
+ }
151
172
 
152
173
  export type ListUnresolvedSelfReviewThreadsResult =
153
174
  | { ok: true; threads: UnresolvedSelfReviewThread[] }
@@ -174,7 +195,13 @@ export async function listUnresolvedSelfReviewThreads(deps: {
174
195
  for (const node of nodes) {
175
196
  if (node.isResolved || node.rootCommentId === null) continue
176
197
  if (!isSelfAuthor(node, deps.selfLogin)) continue
177
- threads.push({ threadId: node.id, rootCommentId: node.rootCommentId })
198
+ threads.push({
199
+ threadId: node.id,
200
+ rootCommentId: node.rootCommentId,
201
+ path: node.path,
202
+ line: node.line,
203
+ snippet: firstLineSnippet(node.rootBody),
204
+ })
178
205
  }
179
206
  return 'continue'
180
207
  },
@@ -260,6 +287,9 @@ async function parseThreadsPage(response: Response): Promise<ThreadsPage> {
260
287
  rootCommentId: root?.databaseId ?? null,
261
288
  rootAuthorLogin: root?.author?.login ?? null,
262
289
  rootAuthorIsBot: root?.author?.__typename === 'Bot',
290
+ path: n.path ?? null,
291
+ line: n.line ?? null,
292
+ rootBody: root?.body ?? null,
263
293
  }
264
294
  })
265
295
  return { kind: 'ok', nodes, hasNextPage: connection.pageInfo.hasNextPage, endCursor: connection.pageInfo.endCursor }
@@ -316,7 +346,11 @@ type GraphqlThreadsResponse = {
316
346
  nodes: Array<{
317
347
  id: string
318
348
  isResolved: boolean
319
- comments: { nodes: Array<{ databaseId?: number; author?: { __typename?: string; login?: string } }> }
349
+ path?: string | null
350
+ line?: number | null
351
+ comments: {
352
+ nodes: Array<{ databaseId?: number; body?: string; author?: { __typename?: string; login?: string } }>
353
+ }
320
354
  }>
321
355
  }
322
356
  }
@@ -0,0 +1,144 @@
1
+ import type { TeamsRealtimeMessage, TeamsUser } from 'agent-messenger/teams'
2
+
3
+ import { matchesAnyAlias } from '@/channels/engagement'
4
+ import type { ChannelAdapterConfig } from '@/channels/schema'
5
+ import type { InboundMessage } from '@/channels/types'
6
+
7
+ import type { TeamsChatInfo } from './teams'
8
+ import { encodeTeamsChannelKey, encodeTeamsChatKey } from './teams-key'
9
+
10
+ export type TeamsInboundEvent = TeamsRealtimeMessage
11
+
12
+ export type InboundDropReason = 'self_author' | 'empty_content' | 'pre_connect' | 'unknown_chat' | 'unknown_channel'
13
+
14
+ export type InboundClassification =
15
+ | { kind: 'drop'; reason: InboundDropReason }
16
+ | { kind: 'route'; payload: InboundMessage }
17
+
18
+ // Resolved (teamId, channelId) for a channel realtime event. The SDK only
19
+ // emits `conversationType: 'channel'` once it has mapped the thread to a team,
20
+ // so both ids are guaranteed present by the time the adapter builds this.
21
+ export type TeamsChannelInfo = { teamId: string; channelId: string }
22
+
23
+ // A message the agent's own account sent is delivered back over the socket.
24
+ // Chat vs channel routing keys differ, but every routed inbound shares the
25
+ // engagement contract below. Chat DMs engage via the `dm` trigger; group chats
26
+ // and channels engage ONLY when the bot is explicitly addressed — by a
27
+ // structured mention whose display name matches, or by the bot's alias in the
28
+ // (mention-stripped) text — and otherwise fail closed via
29
+ // `suppressSticky`/`mentionsOthers` so the agent never barges into a
30
+ // conversation it was not named in.
31
+ export function classifyChatInbound(
32
+ event: TeamsInboundEvent,
33
+ _config: ChannelAdapterConfig,
34
+ self: TeamsUser | null,
35
+ chat: TeamsChatInfo | undefined,
36
+ selfAliases: readonly string[] = [],
37
+ ): InboundClassification {
38
+ if (self === null) return { kind: 'drop', reason: 'pre_connect' }
39
+ if (chat === undefined) return { kind: 'drop', reason: 'unknown_chat' }
40
+
41
+ const text = event.content.trim()
42
+ if (text === '') return { kind: 'drop', reason: 'empty_content' }
43
+
44
+ const isDm = chat.type === 'oneOnOne' || chat.type === 'self'
45
+ const addressed = isAddressedToBot(event, self, selfAliases)
46
+
47
+ return {
48
+ kind: 'route',
49
+ payload: buildPayload({
50
+ event,
51
+ chat: encodeTeamsChatKey(event.chatId),
52
+ isDm,
53
+ addressed,
54
+ text,
55
+ }),
56
+ }
57
+ }
58
+
59
+ export function classifyChannelInbound(
60
+ event: TeamsInboundEvent,
61
+ _config: ChannelAdapterConfig,
62
+ self: TeamsUser | null,
63
+ channel: TeamsChannelInfo,
64
+ selfAliases: readonly string[] = [],
65
+ ): InboundClassification {
66
+ if (self === null) return { kind: 'drop', reason: 'pre_connect' }
67
+
68
+ const text = event.content.trim()
69
+ if (text === '') return { kind: 'drop', reason: 'empty_content' }
70
+
71
+ const addressed = isAddressedToBot(event, self, selfAliases)
72
+
73
+ return {
74
+ kind: 'route',
75
+ payload: buildPayload({
76
+ event,
77
+ chat: encodeTeamsChannelKey(channel.teamId, channel.channelId),
78
+ isDm: false,
79
+ addressed,
80
+ text,
81
+ }),
82
+ }
83
+ }
84
+
85
+ function buildPayload(args: {
86
+ event: TeamsInboundEvent
87
+ chat: string
88
+ isDm: boolean
89
+ addressed: boolean
90
+ text: string
91
+ }): InboundMessage {
92
+ const { event, chat, isDm, addressed, text } = args
93
+ const ts = Date.parse(event.timestamp)
94
+ return {
95
+ adapter: 'teams',
96
+ workspace: 'teams',
97
+ chat,
98
+ thread: null,
99
+ text,
100
+ externalMessageId: event.id,
101
+ authorId: event.author.id,
102
+ authorName: event.author.displayName,
103
+ authorIsBot: false,
104
+ isBotMention: addressed,
105
+ // Teams sends expose no parent id on the realtime event, so a reply can
106
+ // never be attributed to a specific prior message.
107
+ replyToBotMessageId: null,
108
+ // Non-DM traffic (group chat + channel) fails closed: an unaddressed
109
+ // message is marked `mentionsOthers` (suppresses the solo-human fallback)
110
+ // and `suppressSticky` (stops a prior addressed turn from keeping the agent
111
+ // engaged on later unaddressed messages). Neither fires in a DM.
112
+ suppressSticky: !isDm && !addressed,
113
+ mentionsOthers: !isDm && !addressed,
114
+ replyToOtherMessageId: null,
115
+ isDm,
116
+ ts: Number.isFinite(ts) ? ts : 0,
117
+ }
118
+ }
119
+
120
+ // The realtime `content` has had its `<at>` mention HTML stripped by the SDK,
121
+ // but the structured `mentions[]` array survives — match the bot by a mention
122
+ // whose display name is the bot's name or a configured alias. `mentions[].mri`
123
+ // is NOT used for self-matching: `testAuth()` returns the placeholder id `'ME'`,
124
+ // so the adapter cannot know its own MRI to compare against. Alias text
125
+ // matching stays as a fallback for when a user types the bot's name without a
126
+ // real @mention (in which case `mentions[]` is empty).
127
+ function isAddressedToBot(event: TeamsInboundEvent, self: TeamsUser, selfAliases: readonly string[]): boolean {
128
+ const selfNames = [self.displayName, ...selfAliases].map((name) => name.trim().toLocaleLowerCase())
129
+ // A structured mention names one specific person, so it must match a self
130
+ // name EXACTLY — substring matching would wrongly treat a mention of
131
+ // "Build Bot" as addressing a bot named "Bot". The plain-text fallback below
132
+ // stays a substring match (matchesAnyAlias lowercases only the haystack, so
133
+ // its needles must be pre-lowercased), because free text has no such
134
+ // one-name-per-token guarantee.
135
+ const structuredSelfMention = event.mentions.some((mention) =>
136
+ selfNames.includes(mention.displayName.trim().toLocaleLowerCase()),
137
+ )
138
+ if (structuredSelfMention) return true
139
+ return matchesAnyAlias(event.content, selfNames)
140
+ }
141
+
142
+ export function normalizeTeamsText(text: string): string {
143
+ return text.replace(/\s+/g, ' ').trim()
144
+ }
@@ -0,0 +1,112 @@
1
+ import { TeamsClient } from 'agent-messenger/teams'
2
+
3
+ import type { TeamsAccountRecord } from '@/secrets/schema'
4
+
5
+ // The Teams realtime trouter WebSocket authenticates every connect (and every
6
+ // reconnect) with an `Authorization: Bearer <idToken>` header. The upstream
7
+ // agent-messenger SDK only knows how to obtain that token by scraping the
8
+ // `authtoken` cookie out of the Teams desktop app's on-disk SQLite database (or
9
+ // a local Chromium profile) — see agent-messenger/.../teams/token-extractor.ts.
10
+ // TypeClaw runs headless in a container where neither exists, so the scrape
11
+ // always returns null and the SDK throws `no_id_token` on start and in a
12
+ // reconnect loop.
13
+ //
14
+ // The token the trouter wants is an ordinary AAD OAuth bearer for the Teams /
15
+ // Skype "spaces" resource — the SAME resource family that our stored
16
+ // `aad_refresh_token` was minted against by the device-code login
17
+ // (agent-messenger/.../teams/device-login.ts stores `skypeScoped.refreshToken`).
18
+ // So instead of scraping, we mint the bearer in-container with a standard AAD
19
+ // `refresh_token` grant, exactly as the SDK's own `exchangeForSkypeScope` does.
20
+ // Those helpers are not exported from `agent-messenger/teams`, so the minimal
21
+ // grant is reproduced here; the scope/authority constants are mirrored from the
22
+ // SDK's `app-config.ts` and traced back to it in the comments below.
23
+
24
+ // From agent-messenger/.../teams/app-config.ts:
25
+ // DEVICE_CODE_SCOPE_SKYPE (personal / MSA)
26
+ // WORK_DEVICE_CODE_SCOPE_SKYPE (work / AAD)
27
+ const SKYPE_SCOPE_PERSONAL = 'service::api.fl.spaces.skype.com::MBI_SSL openid profile offline_access'
28
+ const SKYPE_SCOPE_WORK = 'https://api.spaces.skype.com/.default openid profile offline_access'
29
+
30
+ // From agent-messenger/.../teams/app-config.ts: CONSUMER_TENANT_ID / WORK_TENANT_ID
31
+ const CONSUMER_TENANT_ID = '9188040d-6c67-4c5b-b112-36a304b66dad'
32
+ const WORK_TENANT_AUTHORITY = 'organizations'
33
+
34
+ // From agent-messenger/.../teams/app-config.ts: TEAMS_WEB_CLIENT_ID / TEAMS_DESKTOP_CLIENT_ID.
35
+ // Only used when the stored account never captured its own aad_client_id.
36
+ const TEAMS_WEB_CLIENT_ID = '5e3ce6c0-2b1f-4285-8d4b-75ee78787346'
37
+ const TEAMS_DESKTOP_CLIENT_ID = '1fec8e78-bce4-4aaf-ab1b-5451cc387264'
38
+
39
+ export type FetchLike = (url: string, init: RequestInit) => Promise<Response>
40
+
41
+ export type MintTeamsIdTokenDeps = {
42
+ fetch?: FetchLike
43
+ }
44
+
45
+ // Returns a freshly minted skype/spaces-scoped AAD access token to use as the
46
+ // trouter bearer, or null when the account lacks the AAD refresh trio needed to
47
+ // mint one (a legacy extracted-token account) — the caller degrades to REST-only
48
+ // in that case. Throws only on an unexpected transport failure; an AAD error
49
+ // response resolves to null so the caller degrades rather than crash-loops.
50
+ export async function mintTeamsIdToken(
51
+ account: TeamsAccountRecord,
52
+ deps: MintTeamsIdTokenDeps = {},
53
+ ): Promise<string | null> {
54
+ const refreshToken = account.aad_refresh_token
55
+ if (refreshToken === undefined || refreshToken === '') return null
56
+
57
+ const doFetch = deps.fetch ?? ((url, init) => fetch(url, init))
58
+ const clientId = account.aad_client_id ?? defaultClientId(account.account_type)
59
+ const scope = account.account_type === 'personal' ? SKYPE_SCOPE_PERSONAL : SKYPE_SCOPE_WORK
60
+
61
+ let response: Response
62
+ try {
63
+ response = await doFetch(tokenUrl(account), {
64
+ method: 'POST',
65
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
66
+ body: new URLSearchParams({
67
+ client_id: clientId,
68
+ grant_type: 'refresh_token',
69
+ refresh_token: refreshToken,
70
+ scope,
71
+ }),
72
+ })
73
+ } catch {
74
+ return null
75
+ }
76
+
77
+ if (!response.ok) return null
78
+ const body = (await response.json().catch(() => ({}))) as { access_token?: unknown }
79
+ return typeof body.access_token === 'string' && body.access_token !== '' ? body.access_token : null
80
+ }
81
+
82
+ export type TeamsIdTokenMinter = (account: TeamsAccountRecord) => Promise<string | null>
83
+
84
+ // A TeamsClient whose realtime `getIdToken()` mints the trouter bearer from the
85
+ // account's AAD refresh token instead of scraping a desktop/browser cookie.
86
+ // `TeamsListener` re-calls this on every (re)connect, so it re-mints each time —
87
+ // matching the SDK's own "re-extract on every attempt" contract. Returning null
88
+ // (legacy account without the AAD trio, or an expired refresh token) makes the
89
+ // SDK throw `no_id_token`, which the adapter catches to degrade to REST-only.
90
+ export class ContainerTeamsClient extends TeamsClient {
91
+ constructor(
92
+ private readonly idTokenAccount: () => TeamsAccountRecord | null,
93
+ private readonly mint: TeamsIdTokenMinter = mintTeamsIdToken,
94
+ ) {
95
+ super()
96
+ }
97
+
98
+ override async getIdToken(): Promise<string | null> {
99
+ const account = this.idTokenAccount()
100
+ return account === null ? null : this.mint(account)
101
+ }
102
+ }
103
+
104
+ function tokenUrl(account: TeamsAccountRecord): string {
105
+ const tenant =
106
+ account.account_type === 'personal' ? CONSUMER_TENANT_ID : (account.aad_tenant_id ?? WORK_TENANT_AUTHORITY)
107
+ return `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`
108
+ }
109
+
110
+ function defaultClientId(accountType: TeamsAccountRecord['account_type']): string {
111
+ return accountType === 'work' ? TEAMS_DESKTOP_CLIENT_ID : TEAMS_WEB_CLIENT_ID
112
+ }
@@ -0,0 +1,32 @@
1
+ export type TeamsConversationKey =
2
+ | { kind: 'chat'; chatId: string }
3
+ | { kind: 'channel'; teamId: string; channelId: string }
4
+
5
+ const CHAT_PREFIX = 'chat:'
6
+ const CHANNEL_PREFIX = 'channel:'
7
+
8
+ export function encodeTeamsChatKey(chatId: string): string {
9
+ return `${CHAT_PREFIX}${chatId}`
10
+ }
11
+
12
+ // teamId is a GUID (no colons); channelId is a `19:...@thread.tacv2` value that
13
+ // DOES contain colons. Splitting the post-prefix remainder on its FIRST colon
14
+ // is therefore unambiguous: everything before it is the teamId, everything
15
+ // after is the channelId (colons and all).
16
+ export function encodeTeamsChannelKey(teamId: string, channelId: string): string {
17
+ return `${CHANNEL_PREFIX}${teamId}:${channelId}`
18
+ }
19
+
20
+ export function decodeTeamsConversationKey(key: string): TeamsConversationKey | null {
21
+ if (key.startsWith(CHAT_PREFIX)) {
22
+ const chatId = key.slice(CHAT_PREFIX.length)
23
+ return chatId === '' ? null : { kind: 'chat', chatId }
24
+ }
25
+ if (key.startsWith(CHANNEL_PREFIX)) {
26
+ const rest = key.slice(CHANNEL_PREFIX.length)
27
+ const sep = rest.indexOf(':')
28
+ if (sep <= 0 || sep === rest.length - 1) return null
29
+ return { kind: 'channel', teamId: rest.slice(0, sep), channelId: rest.slice(sep + 1) }
30
+ }
31
+ return null
32
+ }