typeclaw 0.43.1 → 0.45.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 (86) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +7 -6
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +25 -2
  6. package/src/agent/model-fallback.ts +59 -40
  7. package/src/agent/multimodal/look-at.ts +29 -10
  8. package/src/agent/plugin-tools.ts +9 -4
  9. package/src/agent/provider-error.ts +71 -18
  10. package/src/agent/retry-same-ref.ts +139 -0
  11. package/src/agent/session-origin.ts +1 -0
  12. package/src/agent/subagents.ts +6 -2
  13. package/src/agent/tools/channel-edit.ts +144 -0
  14. package/src/agent/tools/channel-fetch-attachment.ts +51 -8
  15. package/src/agent/tools/channel-reply.ts +41 -18
  16. package/src/agent/tools/channel-send.ts +82 -13
  17. package/src/agent/tools/curl-impersonate.ts +40 -1
  18. package/src/agent/tools/webfetch/fetch.ts +86 -3
  19. package/src/agent/tools/webfetch/tool.ts +26 -3
  20. package/src/agent/tools/webfetch/types.ts +8 -0
  21. package/src/agent/turn-runner.ts +65 -36
  22. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  23. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  24. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  25. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  26. package/src/bundled-plugins/memory/README.md +9 -9
  27. package/src/bundled-plugins/memory/index.ts +40 -9
  28. package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
  29. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  30. package/src/channels/adapters/discord-bot.ts +5 -0
  31. package/src/channels/adapters/discord-edit.ts +51 -0
  32. package/src/channels/adapters/discord.ts +4 -0
  33. package/src/channels/adapters/github/inbound.ts +20 -14
  34. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  35. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  36. package/src/channels/adapters/slack-bot.ts +18 -6
  37. package/src/channels/adapters/slack-edit.ts +47 -0
  38. package/src/channels/adapters/slack.ts +5 -0
  39. package/src/channels/adapters/teams-classify.ts +144 -0
  40. package/src/channels/adapters/teams-edit.ts +61 -0
  41. package/src/channels/adapters/teams-id-token.ts +112 -0
  42. package/src/channels/adapters/teams-key.ts +32 -0
  43. package/src/channels/adapters/teams.ts +523 -0
  44. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  45. package/src/channels/adapters/telegram-bot.ts +5 -0
  46. package/src/channels/adapters/webex-bot.ts +5 -0
  47. package/src/channels/adapters/webex-edit.ts +47 -0
  48. package/src/channels/adapters/webex.ts +5 -0
  49. package/src/channels/continuation-willingness.ts +227 -35
  50. package/src/channels/github-review-turn-ledger.ts +43 -0
  51. package/src/channels/index.ts +1 -1
  52. package/src/channels/manager.ts +54 -1
  53. package/src/channels/router.ts +482 -53
  54. package/src/channels/schema.ts +33 -0
  55. package/src/channels/types.ts +36 -0
  56. package/src/cli/channel.ts +92 -4
  57. package/src/cli/hostd.ts +41 -0
  58. package/src/cli/init.ts +58 -1
  59. package/src/config/channels-mutation.ts +9 -1
  60. package/src/cron/index.ts +16 -4
  61. package/src/cron/reloadable.ts +25 -7
  62. package/src/cron/scheduler.ts +4 -0
  63. package/src/cron/schema.ts +143 -35
  64. package/src/doctor/channel-checks.ts +27 -0
  65. package/src/hostd/daemon.ts +23 -3
  66. package/src/hostd/protocol.ts +2 -0
  67. package/src/hostd/teams-renewal-manager.ts +212 -0
  68. package/src/init/checkpoint.ts +1 -1
  69. package/src/init/index.ts +68 -1
  70. package/src/init/run-owner-claim.ts +1 -0
  71. package/src/init/teams-auth.ts +111 -0
  72. package/src/inspect/label.ts +4 -0
  73. package/src/permissions/match-rule.ts +11 -1
  74. package/src/permissions/resolve.ts +1 -0
  75. package/src/role-claim/match-rule.ts +2 -1
  76. package/src/run/index.ts +35 -8
  77. package/src/run/llm-fetch-observer.ts +27 -5
  78. package/src/sandbox/build.ts +12 -0
  79. package/src/sandbox/policy.ts +13 -0
  80. package/src/sandbox/writable-zones.ts +46 -10
  81. package/src/secrets/schema.ts +32 -0
  82. package/src/secrets/teams-renewal.ts +229 -0
  83. package/src/secrets/teams-store.ts +108 -0
  84. package/src/server/command-runner.ts +2 -1
  85. package/src/server/index.ts +2 -1
  86. package/typeclaw.schema.json +163 -3
@@ -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,61 @@
1
+ import type { TeamsClient } from 'agent-messenger/teams'
2
+
3
+ import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
+
5
+ import { decodeTeamsConversationKey } from './teams-key'
6
+
7
+ // The Teams user-account SDK only exposes an edit primitive for 1:1/group
8
+ // chats (`PUT /users/ME/conversations/{chatId}/messages/{messageId}`); there is
9
+ // no equivalent for team/channel posts. So a channel-keyed edit is genuinely
10
+ // `not-supported`, distinct from an undecodable id (soft `not-found`).
11
+ export function createTeamsEditMessageCallback(deps: {
12
+ client: Pick<TeamsClient, 'editChatMessage'>
13
+ }): EditMessageCallback {
14
+ return async (req): Promise<EditMessageResult> => {
15
+ if (req.adapter !== 'teams') {
16
+ return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
17
+ }
18
+ const decoded = decodeTeamsConversationKey(req.chat)
19
+ if (decoded === null) {
20
+ return { ok: false, error: `unsupported Teams conversation id: ${req.chat}`, code: 'not-found' }
21
+ }
22
+ if (decoded.kind !== 'chat') {
23
+ return { ok: false, error: 'Teams channel messages cannot be edited', code: 'not-supported' }
24
+ }
25
+ try {
26
+ await deps.client.editChatMessage(decoded.chatId, req.messageId, req.text)
27
+ } catch (err) {
28
+ return { ok: false, error: describe(err), code: classifyEditError(err) }
29
+ }
30
+ return { ok: true }
31
+ }
32
+ }
33
+
34
+ // TeamsError carries its identifier on `.code` (a string), not a numeric
35
+ // `.status`: the request path throws `TeamsError(msg, errorBody.code ?? http_<status>)`,
36
+ // so a forbidden edit surfaces as `http_403`/`http_401` and an auth failure as
37
+ // `token_expired`/`not_authenticated`. Everything else (e.g. `http_404` for a
38
+ // gone/foreign message) is a soft miss.
39
+ function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok: false })['code']> {
40
+ switch (errorCode(err)) {
41
+ case 'http_403':
42
+ case 'http_401':
43
+ case 'token_expired':
44
+ case 'not_authenticated':
45
+ return 'permission-denied'
46
+ default:
47
+ return 'not-found'
48
+ }
49
+ }
50
+
51
+ function errorCode(err: unknown): string | null {
52
+ if (typeof err === 'object' && err !== null && 'code' in err) {
53
+ const code = (err as { code: unknown }).code
54
+ if (typeof code === 'string') return code
55
+ }
56
+ return null
57
+ }
58
+
59
+ function describe(err: unknown): string {
60
+ return err instanceof Error ? err.message : String(err)
61
+ }
@@ -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
+ }