Repository navigation
Expand file tree
/
Copy pathreply.ts
More file actions
244 lines (230 loc) · 10.4 KB
/
Copy pathreply.ts
File metadata and controls
244 lines (230 loc) · 10.4 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
244
import {
type CommsApi,
CommsRequestError,
getFullCommsURL,
NOTIFY_AUDIENCES,
type NotifyAudience,
THREAD_ACTIONS,
type ThreadAction,
} from '@todoist/comms-sdk'
import { z } from 'zod'
import type { CommsTool } from '../comms-tool.js'
import { type ReplyOutput, ReplyOutputSchema } from '../utils/output-schemas.js'
import { ReplyTargetTypeSchema } from '../utils/target-types.js'
import { ToolNames } from '../utils/tool-names.js'
const ArgsSchema = {
targetType: ReplyTargetTypeSchema.describe(
'The type of object to reply to: thread (posts a comment) or conversation (posts a message).',
),
targetId: z.string().describe('The ID of the thread or conversation to reply to.'),
content: z
.string()
.min(1)
.describe(
'The content of the reply. Markdown. Mention people with the link syntax [Name](comms-mention://USER_ID) — e.g. [Afzal](comms-mention://29367677) — never @Name or [[Name|id]], which post as literal text. Do not put "@" in the label; the client adds it. Groups use [Name](comms-group-mention://GROUP_ID), channels [#name](comms-channel://CHANNEL_ID), threads [Title](comms-thread://THREAD_ID). Resolve IDs with get-users/get-groups/list-channels first. Mentioning inline does not notify anyone. For thread replies, also pass mentioned user IDs in recipients and group IDs in groups; conversation replies notify all participants automatically and take no notification parameters.',
),
recipients: z
.array(z.number())
.optional()
.describe(
'Optional array of user IDs to notify (thread replies only; ignored for conversation replies, which notify all participants automatically). If omitted with no groups and no notifyAudience, thread replies default to notifying everyone who has interacted with the thread.',
),
groups: z
.array(z.string())
.optional()
.describe(
'Optional array of group IDs to notify (only for thread replies). Use get-groups to discover group IDs before passing them here.',
),
notifyAudience: z
.enum(NOTIFY_AUDIENCES)
.optional()
.describe(
"Optional broader audience to notify in addition to recipients and groups (only for thread replies). 'channel' notifies everyone in the channel; 'thread' notifies everyone who has interacted with the thread.",
),
threadAction: z
.enum(THREAD_ACTIONS)
.optional()
.describe(
"Thread replies only. 'close' closes the thread for everyone with this reply; it then accepts no new comments until reopened. 'reopen' reopens it. Unlike mark-done, which only archives the thread in your own inbox.",
),
}
/**
* The SDK call behind each thread action, the state the reply reports, and
* whether the action leaves the thread closed. Keyed by the SDK's
* ThreadAction, so an action the SDK adds fails to compile here instead of
* being posted as a plain comment.
*/
const THREAD_ACTION_STEPS = {
close: { method: 'closeThread', result: 'Closed', leavesThreadClosed: true },
reopen: { method: 'reopenThread', result: 'Reopened', leavesThreadClosed: false },
} as const satisfies Record<
ThreadAction,
{ method: keyof CommsApi['threads']; result: string; leavesThreadClosed: boolean }
>
/**
* Why Comms refused a thread reply, given whether the thread is closed:
* a comment on a closed thread, or an action on a thread already in the state
* the action leaves it in. Undefined when the thread's state does not explain
* the refusal.
*/
function describeRefusal(
threadId: string,
threadAction: ThreadAction | undefined,
isClosed: boolean,
): string | undefined {
if (threadAction === undefined) {
return isClosed
? `Thread ${threadId} is closed, so it does not accept new comments and the reply was not posted. Posting it means reopening the thread for everyone: only if the user wants that, send it again with threadAction: "reopen", which reopens the thread and posts the comment in one step.`
: undefined
}
if (THREAD_ACTION_STEPS[threadAction].leavesThreadClosed !== isClosed) {
return undefined
}
return isClosed
? `Thread ${threadId} is already closed, so the reply was not posted.`
: `Thread ${threadId} is already open, so the reply was not posted. To post it, send it again without threadAction.`
}
/**
* Comms refuses a comment on a closed thread, closing a closed thread and
* reopening an open one with a 403 and its generic forbidden error code, the
* same answer it gives when the channel limits who can comment. So on a 403
* this reads the thread to say which it was. Any other error, a refusal the
* thread's state does not explain, or a failed lookup keeps the original error.
*/
async function explainRefusedReply(
client: CommsApi,
threadId: string,
threadAction: ThreadAction | undefined,
error: unknown,
): Promise<unknown> {
if (!(error instanceof CommsRequestError) || error.httpStatusCode !== 403) {
return error
}
const thread = await client.threads.getThread(threadId).catch(() => undefined)
const isClosed = thread?.closed
const message =
typeof isClosed === 'boolean'
? describeRefusal(threadId, threadAction, isClosed)
: undefined
// Assigned rather than passed to the constructor: the es2021 lib has no `cause` option.
return message ? Object.assign(new Error(message), { cause: error }) : error
}
const reply = {
name: ToolNames.REPLY,
description:
'Post a reply to a thread (as a comment) or conversation (as a message). Thread replies notify everyone who has interacted with the thread by default unless specific user recipients, groups, or a notifyAudience are provided. Pass threadAction to close or reopen the thread with the reply.',
parameters: ArgsSchema,
outputSchema: ReplyOutputSchema.shape,
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
async execute(args, client) {
const { targetType, targetId, content, recipients, groups, notifyAudience, threadAction } =
args
if (targetType === 'conversation' && groups !== undefined) {
throw new Error('groups can only be used when replying to a thread.')
}
if (targetType === 'conversation' && notifyAudience !== undefined) {
throw new Error('notifyAudience can only be used when replying to a thread.')
}
if (targetType === 'conversation' && threadAction !== undefined) {
throw new Error(
'threadAction can only be used when replying to a thread; conversations cannot be closed.',
)
}
const groupsToNotify =
targetType === 'thread' && groups && groups.length > 0 ? groups : undefined
const appliedAudience: NotifyAudience | undefined =
targetType === 'thread'
? (notifyAudience ??
(recipients === undefined && !groupsToNotify ? 'thread' : undefined))
: undefined
let replyId: string
let created: Date
let replyUrl: string
if (targetType === 'thread') {
const notification = {
content,
recipients,
groups: groupsToNotify,
notifyAudience: appliedAudience,
}
const comment = await (
threadAction
? client.threads[THREAD_ACTION_STEPS[threadAction].method]({
id: targetId,
...notification,
})
: client.comments.createComment({ threadId: targetId, ...notification })
).catch(async (error: unknown) => {
throw await explainRefusedReply(client, targetId, threadAction, error)
})
replyId = comment.id
replyUrl =
comment.url ??
getFullCommsURL({
workspaceId: comment.workspaceId,
channelId: comment.channelId,
threadId: comment.threadId,
commentId: comment.id,
})
const postedValue = comment.posted
created = postedValue
? typeof postedValue === 'string'
? new Date(postedValue)
: postedValue
: new Date()
} else {
const message = await client.conversationMessages.createMessage({
conversationId: targetId,
content,
})
replyId = message.id
replyUrl =
message.url ??
getFullCommsURL({
workspaceId: message.workspaceId,
conversationId: message.conversationId,
messageId: message.id,
})
const postedValue = message.posted
created = postedValue
? typeof postedValue === 'string'
? new Date(postedValue)
: postedValue
: new Date()
}
const lines: string[] = [
`# Reply Posted`,
'',
`**Target:** ${targetType === 'thread' ? `Thread ${targetId}` : `Conversation ${targetId}`}`,
`**Reply ID:** ${replyId}`,
`**Created:** ${created.toISOString()}`,
...(threadAction
? [`**Thread state:** ${THREAD_ACTION_STEPS[threadAction].result}`]
: []),
'',
'## Content',
'',
content,
]
const structuredContent: ReplyStructured = {
type: 'reply_result',
success: true,
targetType,
targetId,
replyId,
content,
created: created.toISOString(),
replyUrl,
...(targetType === 'thread' && recipients ? { recipients } : {}),
...(groupsToNotify ? { groups: groupsToNotify } : {}),
...(appliedAudience ? { notifyAudience: appliedAudience } : {}),
...(threadAction ? { threadAction } : {}),
}
return {
textContent: lines.join('\n'),
structuredContent,
}
},
} satisfies CommsTool<typeof ArgsSchema, typeof ReplyOutputSchema.shape>
type ReplyStructured = ReplyOutput
export { reply, type ReplyStructured }