Repository navigation
Expand file tree
/
Copy pathload-thread.ts
More file actions
243 lines (227 loc) · 8.66 KB
/
Copy pathload-thread.ts
File metadata and controls
243 lines (227 loc) · 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import { getFullCommsURL } from '@todoist/comms-sdk'
import { z } from 'zod'
import type { CommsTool } from '../comms-tool.js'
import { formatAttachmentsLine, normalizeAttachments } from '../utils/attachments.js'
import { UNKNOWN_USER } from '../utils/constants.js'
import { resolveUsersWithLog } from '../utils/degrade.js'
import { LoadThreadOutputSchema, type OutputAttachment } from '../utils/output-schemas.js'
import { ToolNames } from '../utils/tool-names.js'
const ArgsSchema = {
threadId: z.string().describe('The thread ID to load.'),
newerThanDate: z
.string()
.optional()
.describe('Get comments newer than this date (YYYY-MM-DD format).'),
olderThanDate: z
.string()
.optional()
.describe('Get comments older than this date (YYYY-MM-DD format).'),
limit: z
.number()
.int()
.min(1)
.max(100)
.optional()
.default(50)
.describe('Maximum number of comments to return.'),
includeParticipants: z
.boolean()
.optional()
.default(true)
.describe('Include participant user IDs in the response.'),
}
type LoadThreadStructured = {
type: 'thread_data'
thread: {
id: string
title: string
content: string
channelId: string
channelName?: string
workspaceId: number
creator: number
creatorName?: string
posted: string
commentCount: number
isArchived: boolean
inInbox: boolean
isClosed: boolean
participants?: number[]
participantNames?: string[]
threadUrl: string
attachments?: OutputAttachment[]
}
comments: Array<{
id: string
content: string
creator: number
creatorName?: string
threadId: string
posted: string
commentUrl: string
attachments?: OutputAttachment[]
}>
totalComments: number
}
const loadThread = {
name: ToolNames.LOAD_THREAD,
description:
'Load a thread with its metadata and comments. Supports filtering by timestamp and pagination.',
parameters: ArgsSchema,
outputSchema: LoadThreadOutputSchema.shape,
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
async execute(args, client) {
const { threadId, newerThanDate, olderThanDate, limit, includeParticipants } = args
// Fetch thread metadata and comments in parallel
const [thread, comments] = await Promise.all([
client.threads.getThread(threadId),
client.comments.getComments({
threadId,
newerThan: newerThanDate ? new Date(newerThanDate) : undefined,
olderThan: olderThanDate ? new Date(olderThanDate) : undefined,
limit,
}),
])
// Collect all unique user IDs
const userIds = new Set<number>([thread.creator])
for (const comment of comments) {
userIds.add(comment.creator)
}
if (includeParticipants && thread.participants) {
for (const participantId of thread.participants) {
userIds.add(participantId)
}
}
// Fetch channel and all user info in parallel
const [channel, users] = await Promise.all([
client.channels.getChannel(thread.channelId),
// IDs that can't be resolved are simply absent from the lookup, so a
// single inaccessible user doesn't fail the whole thread.
resolveUsersWithLog(
client,
ToolNames.LOAD_THREAD,
'failed to resolve thread participant',
thread.workspaceId,
Array.from(userIds),
),
])
const userLookup: Record<number, string> = {}
for (const [id, user] of users) {
userLookup[id] = user.fullName
}
// Build text content
const creatorName = userLookup[thread.creator]
const lines: string[] = [
`# Thread: ${thread.title}`,
'',
`**Thread ID:** ${thread.id}`,
`**Channel:** ${channel.name}`,
`**Workspace ID:** ${thread.workspaceId}`,
`**Creator:** ${creatorName ?? UNKNOWN_USER} (${thread.creator})`,
`**Posted:** ${thread.posted.toISOString()}`,
`**Comments:** ${thread.commentCount}`,
`**Archived:** ${thread.isArchived ? 'Yes' : 'No'}`,
`**In Inbox:** ${thread.inInbox ? 'Yes' : 'No'}`,
`**Closed:** ${thread.closed ? 'Yes' : 'No'}`,
'',
'## Content',
'',
thread.content,
'',
]
// Normalised once per thread and comment, for both the text and the structured content.
const threadAttachments = normalizeAttachments(thread.attachments)
const attachmentsByComment = new Map(
comments.map((c) => [c.id, normalizeAttachments(c.attachments)]),
)
const threadAttachmentsLine = formatAttachmentsLine(threadAttachments)
if (threadAttachmentsLine) {
lines.push(threadAttachmentsLine)
lines.push('')
}
lines.push(`## Comments (${comments.length})`)
lines.push('')
for (const comment of comments) {
const commentDate = comment.posted.toISOString()
const commentCreatorName = userLookup[comment.creator]
lines.push(`### Comment ${comment.id}`)
lines.push(
`**Creator:** ${commentCreatorName ?? UNKNOWN_USER} (${comment.creator}) | **Posted:** ${commentDate}`,
)
lines.push('')
lines.push(comment.content)
const commentAttachmentsLine = formatAttachmentsLine(
attachmentsByComment.get(comment.id),
)
if (commentAttachmentsLine) {
lines.push('')
lines.push(commentAttachmentsLine)
}
lines.push('')
}
if (includeParticipants && thread.participants) {
lines.push('## Participants')
lines.push('')
const participantList = thread.participants
.map((id) => `${userLookup[id] ?? UNKNOWN_USER} (${id})`)
.join(', ')
lines.push(participantList)
}
const structuredContent: LoadThreadStructured = {
type: 'thread_data',
thread: {
id: thread.id,
title: thread.title,
content: thread.content,
channelId: thread.channelId,
channelName: channel.name,
workspaceId: thread.workspaceId,
creator: thread.creator,
creatorName,
posted: thread.posted.toISOString(),
commentCount: thread.commentCount,
isArchived: thread.isArchived,
inInbox: thread.inInbox ?? false,
isClosed: thread.closed ?? false,
participants: includeParticipants ? (thread.participants ?? undefined) : undefined,
participantNames:
includeParticipants && thread.participants
? thread.participants
.map((id) => userLookup[id])
.filter((name): name is string => name !== undefined)
: undefined,
threadUrl:
thread.url ??
getFullCommsURL({
workspaceId: thread.workspaceId,
channelId: thread.channelId,
threadId: thread.id,
}),
attachments: threadAttachments,
},
comments: comments.map((c) => ({
id: c.id,
content: c.content,
creator: c.creator,
creatorName: userLookup[c.creator],
threadId: c.threadId,
posted: c.posted.toISOString(),
commentUrl:
c.url ??
getFullCommsURL({
workspaceId: c.workspaceId,
channelId: c.channelId,
threadId: c.threadId,
commentId: c.id,
}),
attachments: attachmentsByComment.get(c.id),
})),
totalComments: thread.commentCount,
}
return {
textContent: lines.join('\n'),
structuredContent,
}
},
} satisfies CommsTool<typeof ArgsSchema, typeof LoadThreadOutputSchema.shape>
export { loadThread, type LoadThreadStructured }