MCPcopy Index your code
hub / github.com/slackapi/bolt-js / DefaultThreadContextStore

Class DefaultThreadContextStore

src/AssistantThreadContextStore.ts:20–90  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

18}
19
20export class DefaultThreadContextStore implements AssistantThreadContextStore {
21 private context: AssistantThreadContext = {};
22
23 public async get(args: AllAssistantMiddlewareArgs): Promise<AssistantThreadContext> {
24 const { context, client, payload, logger } = args;
25
26 logger.debug('DefaultAssistantThreadStore: get method called');
27
28 if (this.context.channel_id) {
29 return this.context;
30 }
31
32 const { channelId: channel, threadTs: thread_ts } = extractThreadInfo(payload);
33
34 // Retrieve the current thread history
35 const thread = await client.conversations.replies({
36 channel,
37 ts: thread_ts,
38 oldest: thread_ts,
39 include_all_metadata: true,
40 limit: 4,
41 });
42
43 if (!thread.messages) return {};
44
45 // Find the first message in the thread that holds the current context using metadata.
46 // See createSaveThreadContext below for a description and explanation for this approach.
47 const initialMsg = thread.messages.find((m) => !('subtype' in m) && m.user === context.botUserId);
48 const threadContext = initialMsg?.metadata ? initialMsg.metadata.event_payload : null;
49
50 return threadContext || {};
51 }
52
53 public async save(args: AllAssistantMiddlewareArgs): Promise<void> {
54 const { context, client, payload, logger } = args;
55 const { channelId: channel, threadTs: thread_ts, context: threadContext } = extractThreadInfo(payload);
56
57 logger.debug('DefaultAssistantThreadStore: save method called');
58
59 // Retrieve first several messages from the current Assistant thread
60 const thread = await client.conversations.replies({
61 channel,
62 ts: thread_ts,
63 oldest: thread_ts,
64 include_all_metadata: true,
65 limit: 4,
66 });
67
68 if (!thread.messages) return;
69
70 // Find and update the initial Assistant message with the new context to ensure the
71 // thread always contains the most recent context that user is sending messages from.
72 const initialMsg = thread.messages.find((m) => !('subtype' in m) && m.user === context.botUserId);
73 if (initialMsg?.ts) {
74 const params: ChatUpdateArguments = {
75 channel,
76 ts: initialMsg.ts,
77 text: initialMsg.text,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected