typeclaw 0.43.0 → 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.
- package/README.md +1 -1
- package/auth.schema.json +92 -0
- package/package.json +2 -2
- package/secrets.schema.json +92 -0
- package/src/agent/index.ts +23 -4
- package/src/agent/multimodal/look-at.ts +27 -9
- package/src/agent/plugin-tools.ts +9 -4
- package/src/agent/session-origin.ts +1 -0
- package/src/agent/system-prompt.ts +36 -0
- package/src/agent/tools/channel-fetch-attachment.ts +45 -3
- package/src/agent/tools/channel-reply.ts +41 -18
- package/src/agent/tools/channel-send.ts +82 -13
- package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
- package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
- package/src/bundled-plugins/memory/README.md +9 -9
- package/src/bundled-plugins/memory/index.ts +40 -9
- package/src/channels/adapters/discord-bot.ts +76 -3
- package/src/channels/adapters/discord.ts +15 -2
- package/src/channels/adapters/github/inbound.ts +20 -14
- package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
- package/src/channels/adapters/teams-classify.ts +144 -0
- package/src/channels/adapters/teams-id-token.ts +112 -0
- package/src/channels/adapters/teams-key.ts +32 -0
- package/src/channels/adapters/teams.ts +519 -0
- package/src/channels/github-review-turn-ledger.ts +43 -0
- package/src/channels/index.ts +1 -1
- package/src/channels/manager.ts +63 -2
- package/src/channels/router.ts +664 -112
- package/src/channels/schema.ts +33 -0
- package/src/channels/types.ts +8 -5
- package/src/cli/channel.ts +131 -16
- package/src/cli/hostd.ts +41 -0
- package/src/cli/init.ts +58 -1
- package/src/config/channels-mutation.ts +9 -1
- package/src/cron/index.ts +16 -4
- package/src/cron/reloadable.ts +25 -7
- package/src/cron/scheduler.ts +4 -0
- package/src/cron/schema.ts +143 -35
- package/src/doctor/channel-checks.ts +27 -0
- package/src/hostd/daemon.ts +23 -3
- package/src/hostd/protocol.ts +2 -0
- package/src/hostd/teams-renewal-manager.ts +212 -0
- package/src/init/checkpoint.ts +1 -1
- package/src/init/index.ts +68 -1
- package/src/init/run-owner-claim.ts +1 -0
- package/src/init/teams-auth.ts +111 -0
- package/src/inspect/label.ts +4 -0
- package/src/permissions/match-rule.ts +11 -1
- package/src/permissions/resolve.ts +1 -0
- package/src/role-claim/match-rule.ts +2 -1
- package/src/run/index.ts +35 -8
- package/src/run/llm-fetch-observer.ts +27 -5
- package/src/sandbox/build.ts +12 -0
- package/src/sandbox/policy.ts +13 -0
- package/src/sandbox/writable-zones.ts +46 -10
- package/src/secrets/schema.ts +32 -0
- package/src/secrets/teams-renewal.ts +229 -0
- package/src/secrets/teams-store.ts +108 -0
- package/typeclaw.schema.json +163 -3
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
|
|
1
3
|
import { DiscordBotClient, DiscordBotListener } from 'agent-messenger/discordbot'
|
|
2
4
|
import {
|
|
3
5
|
DiscordIntent,
|
|
@@ -742,13 +744,26 @@ function clampLimit(requested: number, max: number): number {
|
|
|
742
744
|
// the upload error (the file the agent wanted to share is the load-bearing
|
|
743
745
|
// part of the message). The text post is best-effort and only attempted
|
|
744
746
|
// after every upload succeeds.
|
|
747
|
+
//
|
|
748
|
+
// Native reply on an attachment-only send: the SDK's `uploadFile` cannot carry
|
|
749
|
+
// a `message_reference`, so a reply-arrow on a pure-attachment reply is
|
|
750
|
+
// impossible through it. When `msg.replyTo` is set AND there is no text send to
|
|
751
|
+
// carry the reference, the FIRST file upload goes through a raw multipart POST
|
|
752
|
+
// with a `payload_json.message_reference` instead (uploadFirstFileWithReply) so
|
|
753
|
+
// the file message itself is the native reply. Only the first file carries it —
|
|
754
|
+
// otherwise Discord renders one reply-arrow per attachment. Remaining files, and
|
|
755
|
+
// every upload on a send that also has text (the text send carries the
|
|
756
|
+
// reference), stay on the SDK path.
|
|
745
757
|
export function createOutboundCallback(deps: {
|
|
746
758
|
client: Pick<DiscordBotClient, 'sendMessage' | 'uploadFile'>
|
|
747
759
|
logger: DiscordBotAdapterLogger
|
|
748
760
|
formatChannelTag: (workspace: string, chat: string) => Promise<string>
|
|
761
|
+
token: string
|
|
749
762
|
resolvePath?: (path: string) => string
|
|
763
|
+
fetchImpl?: typeof fetch
|
|
750
764
|
}): OutboundCallback {
|
|
751
|
-
const { client, logger, formatChannelTag, resolvePath } = deps
|
|
765
|
+
const { client, logger, formatChannelTag, token, resolvePath } = deps
|
|
766
|
+
const fetchImpl = deps.fetchImpl ?? fetch
|
|
752
767
|
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
753
768
|
if (msg.adapter !== 'discord-bot') {
|
|
754
769
|
return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
@@ -763,10 +778,25 @@ export function createOutboundCallback(deps: {
|
|
|
763
778
|
`[discord-bot] outbound ${tag} text_len=${text.length} attachments=${attachments.length}${msg.thread ? ` thread=${msg.thread}` : ''}`,
|
|
764
779
|
)
|
|
765
780
|
|
|
766
|
-
|
|
781
|
+
// Only a textless send lets a file carry the native reply: when text is
|
|
782
|
+
// present, the reference rides on the text send instead (below), so files
|
|
783
|
+
// must NOT also reference the parent or Discord shows two reply-arrows.
|
|
784
|
+
const replyOnFirstFile = text === '' ? msg.replyTo?.externalMessageId : undefined
|
|
785
|
+
|
|
786
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
767
787
|
const path = resolvePath ? resolvePath(attachment.path) : attachment.path
|
|
788
|
+
const referenceThisFile = index === 0 ? replyOnFirstFile : undefined
|
|
768
789
|
try {
|
|
769
|
-
const file =
|
|
790
|
+
const file =
|
|
791
|
+
referenceThisFile !== undefined
|
|
792
|
+
? await uploadFirstFileWithReply({
|
|
793
|
+
channelId: msg.chat,
|
|
794
|
+
path,
|
|
795
|
+
replyToId: referenceThisFile,
|
|
796
|
+
token,
|
|
797
|
+
fetchImpl,
|
|
798
|
+
})
|
|
799
|
+
: await client.uploadFile(msg.chat, path)
|
|
770
800
|
logger.info(`[discord-bot] uploaded id=${file.id} filename=${file.filename} size=${file.size} ${tag}`)
|
|
771
801
|
if (msg.thread) {
|
|
772
802
|
logger.warn(
|
|
@@ -804,6 +834,47 @@ export function createOutboundCallback(deps: {
|
|
|
804
834
|
}
|
|
805
835
|
}
|
|
806
836
|
|
|
837
|
+
type DiscordCreateMessageWithAttachments = {
|
|
838
|
+
attachments?: DiscordFile[]
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// Raw multipart create-message so a pure-attachment reply carries a native
|
|
842
|
+
// `message_reference`. Mirrors the SDK's `uploadFile` wire shape (`files[0]`)
|
|
843
|
+
// and adds a `payload_json` field — Discord merges JSON body fields from
|
|
844
|
+
// `payload_json` with the multipart file parts, which is the only documented
|
|
845
|
+
// way to attach `message_reference` to a file upload. Returns the created
|
|
846
|
+
// message's first attachment as a `DiscordFile`, matching `client.uploadFile`
|
|
847
|
+
// so the caller's logging/typing is identical on both paths.
|
|
848
|
+
async function uploadFirstFileWithReply(args: {
|
|
849
|
+
channelId: string
|
|
850
|
+
path: string
|
|
851
|
+
replyToId: string
|
|
852
|
+
token: string
|
|
853
|
+
fetchImpl: typeof fetch
|
|
854
|
+
}): Promise<DiscordFile> {
|
|
855
|
+
const fileBuffer = await readFile(args.path)
|
|
856
|
+
const filename = args.path.split('/').pop() ?? 'file'
|
|
857
|
+
const form = new FormData()
|
|
858
|
+
form.append('payload_json', JSON.stringify({ message_reference: { message_id: args.replyToId } }))
|
|
859
|
+
form.append('files[0]', new Blob([new Uint8Array(fileBuffer)]), filename)
|
|
860
|
+
|
|
861
|
+
const response = await args.fetchImpl(`${DISCORD_API_BASE}/channels/${args.channelId}/messages`, {
|
|
862
|
+
method: 'POST',
|
|
863
|
+
headers: { Authorization: `Bot ${args.token}` },
|
|
864
|
+
body: form,
|
|
865
|
+
})
|
|
866
|
+
if (!response.ok) {
|
|
867
|
+
const body = await response.text().catch(() => '')
|
|
868
|
+
throw new Error(`http ${response.status}${body ? `: ${body.slice(0, 200)}` : ''}`)
|
|
869
|
+
}
|
|
870
|
+
const message = (await response.json()) as DiscordCreateMessageWithAttachments
|
|
871
|
+
const first = message.attachments?.[0]
|
|
872
|
+
if (first === undefined) {
|
|
873
|
+
throw new Error('upload succeeded but no attachments returned')
|
|
874
|
+
}
|
|
875
|
+
return first
|
|
876
|
+
}
|
|
877
|
+
|
|
807
878
|
// Discord CDN URLs (`cdn.discordapp.com/attachments/...`) are signed and
|
|
808
879
|
// expire (~24h). Sending the bot token alongside makes no difference for
|
|
809
880
|
// public CDN URLs (Discord ignores it), but is required for the rare
|
|
@@ -999,6 +1070,8 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
999
1070
|
client,
|
|
1000
1071
|
logger,
|
|
1001
1072
|
formatChannelTag,
|
|
1073
|
+
token: options.token,
|
|
1074
|
+
fetchImpl,
|
|
1002
1075
|
})
|
|
1003
1076
|
|
|
1004
1077
|
const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger })
|
|
@@ -75,13 +75,26 @@ export function createDiscordOutboundCallback(deps: {
|
|
|
75
75
|
if (text === '' && attachments.length === 0) return { ok: false, error: 'message has neither text nor attachments' }
|
|
76
76
|
const tag = await deps.formatChannelTag(msg.chat)
|
|
77
77
|
deps.logger.info(`[discord] outbound ${tag} text_len=${text.length} attachments=${attachments.length}`)
|
|
78
|
+
|
|
79
|
+
// The native reply reference rides on exactly ONE message so Discord shows a
|
|
80
|
+
// single reply-arrow: the first text chunk when there is text, otherwise the
|
|
81
|
+
// first file upload. Every later chunk/file posts bare.
|
|
82
|
+
const replyTo = msg.replyTo?.externalMessageId
|
|
83
|
+
const replyOnFirstFile = text === '' ? replyTo : undefined
|
|
84
|
+
const replyOption = (reference: string | undefined): { reply_to: string } | undefined =>
|
|
85
|
+
reference !== undefined ? { reply_to: reference } : undefined
|
|
78
86
|
try {
|
|
79
87
|
// Attachments first, then text — Discord's upstream uploadFile takes no
|
|
80
88
|
// content body, so a failed upload must not leave a text-only message
|
|
81
89
|
// already posted (see OutboundMessage.attachments contract).
|
|
82
|
-
for (const attachment of attachments
|
|
90
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
91
|
+
await deps.client.uploadFile(msg.chat, attachment.path, replyOption(index === 0 ? replyOnFirstFile : undefined))
|
|
92
|
+
}
|
|
83
93
|
if (text !== '') {
|
|
84
|
-
|
|
94
|
+
const chunks = chunkMarkdown(text, 2_000)
|
|
95
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
96
|
+
await deps.client.sendMessage(msg.chat, chunk, replyOption(index === 0 ? replyTo : undefined))
|
|
97
|
+
}
|
|
85
98
|
}
|
|
86
99
|
return { ok: true }
|
|
87
100
|
} catch (err) {
|
|
@@ -10,7 +10,7 @@ import type { DeliveryDedup } from './dedup'
|
|
|
10
10
|
import { isGithubEventAllowed } from './event-allowlist'
|
|
11
11
|
import { encodeGithubReactionRef, type GithubReactionTarget } from './reactions'
|
|
12
12
|
import { fetchSelfReviewBlocking } from './review-state'
|
|
13
|
-
import { listUnresolvedSelfReviewThreads } from './review-thread-resolver'
|
|
13
|
+
import { listUnresolvedSelfReviewThreads, type UnresolvedSelfReviewThread } from './review-thread-resolver'
|
|
14
14
|
|
|
15
15
|
export type GithubInboundLogger = { info: (m: string) => void; warn: (m: string) => void; error: (m: string) => void }
|
|
16
16
|
|
|
@@ -280,15 +280,14 @@ function scheduleReviewFollowup(input: {
|
|
|
280
280
|
else options.logger.warn(`[github] review-state recheck failed for ${target}: ${blocking.error}`)
|
|
281
281
|
}
|
|
282
282
|
|
|
283
|
-
|
|
284
|
-
if (rootCommentIds.length === 0 && !selfBlocking) return
|
|
283
|
+
if (threads.threads.length === 0 && !selfBlocking) return
|
|
285
284
|
options.route(
|
|
286
285
|
withApprovalPolicy(
|
|
287
286
|
buildReviewFollowupInbound({
|
|
288
287
|
repository,
|
|
289
288
|
pullNumber,
|
|
290
289
|
headSha,
|
|
291
|
-
|
|
290
|
+
threads: threads.threads,
|
|
292
291
|
selfBlocking,
|
|
293
292
|
title: readString(pr, 'title'),
|
|
294
293
|
}),
|
|
@@ -307,15 +306,15 @@ function buildReviewFollowupInbound(input: {
|
|
|
307
306
|
repository: { owner: string; name: string }
|
|
308
307
|
pullNumber: number
|
|
309
308
|
headSha: string
|
|
310
|
-
|
|
309
|
+
threads: readonly UnresolvedSelfReviewThread[]
|
|
311
310
|
selfBlocking: boolean
|
|
312
311
|
title: string | null
|
|
313
312
|
}): InboundMessage {
|
|
314
|
-
const { repository, pullNumber, headSha,
|
|
313
|
+
const { repository, pullNumber, headSha, threads, selfBlocking, title } = input
|
|
315
314
|
const titleSegment = title !== null && title.trim() !== '' ? `: "${title}"` : ''
|
|
316
315
|
const text =
|
|
317
316
|
`PR #${pullNumber}${titleSegment} received new commits (now at ${headSha.slice(0, 7)}). ` +
|
|
318
|
-
followupInstruction(
|
|
317
|
+
followupInstruction(threads, selfBlocking)
|
|
319
318
|
|
|
320
319
|
return {
|
|
321
320
|
adapter: 'github',
|
|
@@ -336,14 +335,15 @@ function buildReviewFollowupInbound(input: {
|
|
|
336
335
|
}
|
|
337
336
|
}
|
|
338
337
|
|
|
339
|
-
function followupInstruction(
|
|
338
|
+
function followupInstruction(threads: readonly UnresolvedSelfReviewThread[], selfBlocking: boolean): string {
|
|
340
339
|
const threadPart =
|
|
341
|
-
|
|
342
|
-
? `You have ${
|
|
343
|
-
`
|
|
344
|
-
`
|
|
345
|
-
`acknowledgement and resolve_review_thread: true
|
|
346
|
-
`
|
|
340
|
+
threads.length > 0
|
|
341
|
+
? `You have ${threads.length} unresolved review thread(s) you authored on this PR. ` +
|
|
342
|
+
`For each, check whether the new commits addressed your concern, then act on THAT thread ` +
|
|
343
|
+
`by passing its root comment id as \`thread\` to channel_send: if addressed, reply with a short ` +
|
|
344
|
+
`acknowledgement and resolve_review_thread: true; if not, reply with resolve_review_thread: false ` +
|
|
345
|
+
`(or leave it). Use the id — not the file/line — as \`thread\`; the file/line is only to tell the ` +
|
|
346
|
+
`threads apart:\n${threads.map(renderThreadLine).join('\n')}\n`
|
|
347
347
|
: ''
|
|
348
348
|
// A held CHANGES_REQUESTED never clears itself: GitHub keeps the block until a
|
|
349
349
|
// fresh APPROVE/COMMENT/dismiss, so a blocking follow-up must always end with a
|
|
@@ -360,6 +360,12 @@ function followupInstruction(rootCommentIds: readonly number[], selfBlocking: bo
|
|
|
360
360
|
return `${threadPart}${blockingPart}${tail}`
|
|
361
361
|
}
|
|
362
362
|
|
|
363
|
+
function renderThreadLine(thread: UnresolvedSelfReviewThread): string {
|
|
364
|
+
const where = thread.path !== null ? ` on ${thread.path}${thread.line !== null ? `:${thread.line}` : ''}` : ''
|
|
365
|
+
const concern = thread.snippet !== null ? ` — "${thread.snippet}"` : ''
|
|
366
|
+
return `- thread ${thread.rootCommentId}${where}${concern}`
|
|
367
|
+
}
|
|
368
|
+
|
|
363
369
|
export async function verifySignature(body: string, secret: string, sigHeader: string): Promise<boolean> {
|
|
364
370
|
const expected = `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`
|
|
365
371
|
const a = Buffer.from(expected)
|
|
@@ -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 = {
|
|
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({
|
|
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
|
-
|
|
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
|
+
}
|