@mastra/factory 0.27.0 → 0.28.0-alpha.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 +6 -0
- package/dist/boards/index.js +1 -1
- package/dist/boards/project-boards.js +1 -1
- package/dist/boards/work.js +1 -1
- package/dist/dispatch-wake.d.ts +13 -0
- package/dist/dispatch-wake.d.ts.map +1 -0
- package/dist/dispatch-wake.js +30 -0
- package/dist/dispatch-wake.js.map +1 -0
- package/dist/environment/build-runner.d.ts +1 -1
- package/dist/environment/build-runner.d.ts.map +1 -1
- package/dist/environment/build-runner.js +2 -2
- package/dist/environment/build-workflow.d.ts +1 -1
- package/dist/environment/build-workflow.d.ts.map +1 -1
- package/dist/environment/build-workflow.js +1 -1
- package/dist/environment/build.js +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +57 -44
- package/dist/factory.js.map +1 -1
- package/dist/index.js +9 -9
- package/dist/integrations/channel-thread-announcements.d.ts +5 -0
- package/dist/integrations/channel-thread-announcements.d.ts.map +1 -1
- package/dist/integrations/channel-thread-announcements.js +24 -2
- package/dist/integrations/channel-thread-announcements.js.map +1 -1
- package/dist/integrations/github/default-rules.js +1 -1
- package/dist/integrations/github/integration.js +2 -2
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +18 -17
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.js +4 -4
- package/dist/integrations/github/sandbox.js +1 -1
- package/dist/integrations/github/session-subscriptions.js +3 -3
- package/dist/integrations/github/webhook.js +2 -2
- package/dist/integrations/gitlab/integration.js +2 -2
- package/dist/integrations/gitlab/issue-reconciler.js +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js +3 -3
- package/dist/integrations/gitlab/routes.js +1 -1
- package/dist/integrations/gitlab/rules.js +3 -3
- package/dist/integrations/gitlab/session-subscriptions.js +1 -1
- package/dist/integrations/gitlab/webhook-dispatch.js +1 -1
- package/dist/integrations/incidentio/integration.js +3 -3
- package/dist/integrations/incidentio/rules.js +2 -2
- package/dist/integrations/jira/integration.js +2 -2
- package/dist/integrations/jira/routes.js +1 -1
- package/dist/integrations/jira/rules.js +2 -2
- package/dist/integrations/linear/integration.js +2 -2
- package/dist/integrations/linear/routes.d.ts +21 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +20 -2
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.js +2 -2
- package/dist/integrations/platform/github/event-worker.js +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +8 -5
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js +1 -1
- package/dist/integrations/platform/gitlab/integration.js +2 -2
- package/dist/integrations/platform/incidentio/integration.js +5 -5
- package/dist/integrations/platform/jira/agent-tools.js +1 -1
- package/dist/integrations/platform/jira/integration.js +2 -2
- package/dist/integrations/platform/jira/routes.js +1 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +149 -45
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/slack/chat-tools.d.ts +16 -0
- package/dist/integrations/slack/chat-tools.d.ts.map +1 -0
- package/dist/integrations/slack/chat-tools.js +215 -0
- package/dist/integrations/slack/chat-tools.js.map +1 -0
- package/dist/integrations/slack/integration.d.ts +19 -3
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +25 -8
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/run-error-card.js +1 -1
- package/dist/integrations/slack/share-file-tool.d.ts +8 -0
- package/dist/integrations/slack/share-file-tool.d.ts.map +1 -1
- package/dist/integrations/slack/share-file-tool.js +13 -4
- package/dist/integrations/slack/share-file-tool.js.map +1 -1
- package/dist/integrations/slack/slack.js +3 -3
- package/dist/integrations/slack/tool-settings.d.ts +26 -0
- package/dist/integrations/slack/tool-settings.d.ts.map +1 -0
- package/dist/integrations/slack/tool-settings.js +35 -0
- package/dist/integrations/slack/tool-settings.js.map +1 -0
- package/dist/mcp/events.js +1 -1
- package/dist/mcp/routes.js +1 -1
- package/dist/routes/attention-activity.js +2 -2
- package/dist/routes/attention-providers.js +3 -3
- package/dist/routes/attention.js +2 -2
- package/dist/routes/automation-runs.js +1 -1
- package/dist/routes/boards.js +2 -2
- package/dist/routes/config.js +4 -4
- package/dist/routes/contracts.d.ts +30 -2
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +22 -5
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/fs.js +1 -1
- package/dist/routes/intake.js +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +35 -24
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/skills.js +2 -2
- package/dist/routes/source-control-sessions.js +2 -2
- package/dist/routes/surface.js +16 -16
- package/dist/routes/telemetry.js +1 -1
- package/dist/routes/work-items.js +9 -9
- package/dist/rules/decision-applicability.js +2 -2
- package/dist/rules/dispatcher.d.ts +14 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +135 -47
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/index.js +1 -1
- package/dist/rules/processor.d.ts +2 -0
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +4 -3
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/start-coordinator.js +2 -2
- package/dist/rules/terminal-cleanup.js.map +1 -1
- package/dist/rules/tools.js +5 -5
- package/dist/rules/transition-service.js +5 -5
- package/dist/sandbox/session-retirement.js +2 -2
- package/dist/sandbox/session-sandbox.js +1 -1
- package/dist/session/credential-policy.js +1 -1
- package/dist/session/factory-session.js +3 -3
- package/dist/session/self-review-gate.js +1 -1
- package/dist/session/source-control-tools.js +3 -3
- package/dist/storage/domains/audit/domain.js +1 -1
- package/dist/storage/domains/comments/base.js +3 -3
- package/dist/storage/domains/comments/domain.js +3 -3
- package/dist/storage/domains/comments/routes.js +1 -1
- package/dist/storage/domains/source-control/base.d.ts +20 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +42 -0
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +5 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +23 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +16 -5
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +55 -72
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.js +1 -1
- package/dist/storage/domains/work-items/claimable-work.d.ts +15 -0
- package/dist/storage/domains/work-items/claimable-work.d.ts.map +1 -0
- package/dist/storage/domains/work-items/claimable-work.js +51 -0
- package/dist/storage/domains/work-items/claimable-work.js.map +1 -0
- package/dist/tools/index.js +2 -2
- package/dist/tools/messaging-tools.js +1 -1
- package/dist/tools/read-tools.js +4 -4
- package/dist/tools/scope.js +1 -1
- package/dist/tools/session-tools.js +9 -9
- package/dist/tools/work-item-tools.js +4 -4
- package/dist/work-items/create-work-item.js +2 -2
- package/dist/work-items/decision-actions.js +2 -2
- package/dist/work-items/providers/gitlab.js +1 -1
- package/dist/work-items/providers/incidentio.js +1 -1
- package/dist/work-items/providers/index.js +1 -1
- package/dist/work-items/providers/jira.js +1 -1
- package/dist/work-items/providers/linear.js +1 -1
- package/dist/work-items/split-migration.js +2 -2
- package/dist/workspace.d.ts +2 -0
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +10 -7
- package/dist/workspace.js.map +1 -1
- package/package.json +8 -8
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Chat } from 'chat';
|
|
2
|
+
import type { IntegrationTools } from '../base.js';
|
|
3
|
+
import type { SlackToolSettings } from './tool-settings.js';
|
|
4
|
+
/**
|
|
5
|
+
* The Chat SDK's read and post tools, plus channel/person lookup, search and
|
|
6
|
+
* DMs, confined to the channels `settings` grant. They act as the app, so a
|
|
7
|
+
* session never reaches a channel the app isn't in, and posting needs no
|
|
8
|
+
* approval.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createSlackChatTools({ chat, sessionThreadId, settings, }: {
|
|
11
|
+
chat: Chat;
|
|
12
|
+
/** The session's own chat thread id, e.g. `slack:C123:1700000000.000100`. */
|
|
13
|
+
sessionThreadId: string;
|
|
14
|
+
settings: SlackToolSettings;
|
|
15
|
+
}): IntegrationTools;
|
|
16
|
+
//# sourceMappingURL=chat-tools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-tools.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/chat-tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAajC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AA0C5D;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,IAAI,EACJ,eAAe,EACf,QAAQ,GACT,EAAE;IACD,IAAI,EAAE,IAAI,CAAC;IACX,6EAA6E;IAC7E,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,EAAE,iBAAiB,CAAC;CAC7B,GAAG,gBAAgB,CAsMnB"}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { createTool } from "@mastra/core/tools";
|
|
3
|
+
import { fetchChannelMessages, fetchMessages, fetchThread, getChannelInfo, getThreadParticipants, listThreads, postChannelMessage, postMessage } from "chat/ai";
|
|
4
|
+
// src/integrations/slack/chat-tools.ts
|
|
5
|
+
/** Pages read per lookup, so one call can't walk a huge workspace. */
|
|
6
|
+
const MAX_LOOKUP_PAGES = 10;
|
|
7
|
+
/** Most messages searchMessages reads per channel. */
|
|
8
|
+
const MAX_SEARCH_SCAN = 1e3;
|
|
9
|
+
/** Treats a bare Slack id (`C0123`, `D0123`) as `slack:C0123`. */
|
|
10
|
+
function withPrefix(id) {
|
|
11
|
+
return id.startsWith("slack:") ? id : `slack:${id}`;
|
|
12
|
+
}
|
|
13
|
+
/** Same resolution the Chat SDK's own scope guard uses. */
|
|
14
|
+
function channelOf(chat, id) {
|
|
15
|
+
const prefix = id.split(":")[0];
|
|
16
|
+
return (prefix ? chat.getAdapter(prefix) : void 0)?.channelIdFromThreadId?.(id) ?? id.split(":").slice(0, 2).join(":");
|
|
17
|
+
}
|
|
18
|
+
const slackClient = (chat) => chat.getAdapter("slack").webClient;
|
|
19
|
+
/**
|
|
20
|
+
* Reads a paginated Slack list until it runs out of pages or hits the cap.
|
|
21
|
+
* `incomplete` is set when the cap stopped it, so a lookup that found nothing
|
|
22
|
+
* isn't mistaken for "doesn't exist".
|
|
23
|
+
*/
|
|
24
|
+
async function listAll(fetchPage) {
|
|
25
|
+
const items = [];
|
|
26
|
+
let cursor;
|
|
27
|
+
for (let page = 0; page < MAX_LOOKUP_PAGES; page++) {
|
|
28
|
+
const result = await fetchPage(cursor);
|
|
29
|
+
items.push(...result.items ?? []);
|
|
30
|
+
cursor = result.response_metadata?.next_cursor || void 0;
|
|
31
|
+
if (!cursor) return { items };
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
items,
|
|
35
|
+
incomplete: true
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const normalize = (text) => text.toLowerCase().replace(/^[#@]/, "").trim();
|
|
39
|
+
/**
|
|
40
|
+
* The Chat SDK's read and post tools, plus channel/person lookup, search and
|
|
41
|
+
* DMs, confined to the channels `settings` grant. They act as the app, so a
|
|
42
|
+
* session never reaches a channel the app isn't in, and posting needs no
|
|
43
|
+
* approval.
|
|
44
|
+
*/
|
|
45
|
+
function createSlackChatTools({ chat, sessionThreadId, settings }) {
|
|
46
|
+
const all = settings.channels === "all";
|
|
47
|
+
const allowed = /* @__PURE__ */ new Set([channelOf(chat, sessionThreadId), ...settings.channels === "selected" ? settings.channelIds.map((id) => `slack:${id}`) : []]);
|
|
48
|
+
const scope = all ? "any channel the app is a member of" : [...allowed].join(", ");
|
|
49
|
+
const ownChannel = channelOf(chat, sessionThreadId);
|
|
50
|
+
const guard = (id) => {
|
|
51
|
+
const channel = channelOf(chat, withPrefix(id));
|
|
52
|
+
if (channel.startsWith("slack:D") && channel !== ownChannel) throw new Error(`"${id}" is someone else's direct message with the app. Use sendDirectMessage to message a person.`);
|
|
53
|
+
if (all) return;
|
|
54
|
+
if (!allowed.has(channel)) throw new Error(`"${id}" is outside the channels this session can use: ${scope}.`);
|
|
55
|
+
};
|
|
56
|
+
const postGuard = settings.channelAccess === "read" ? (id) => {
|
|
57
|
+
if (channelOf(chat, id) !== ownChannel) throw new Error(`"${id}" is read only for this session: it can only post in its own channel, ${ownChannel}.`);
|
|
58
|
+
} : guard;
|
|
59
|
+
const note = (tool) => ({
|
|
60
|
+
...tool,
|
|
61
|
+
description: `${String(tool.description)} Channels this session can use: ${scope}${settings.channelAccess === "read" ? " (read only: post only in this session's own channel)" : ""}. This session's thread is ${sessionThreadId}.`
|
|
62
|
+
});
|
|
63
|
+
return {
|
|
64
|
+
fetchMessages: note(fetchMessages(chat, guard)),
|
|
65
|
+
fetchChannelMessages: note(fetchChannelMessages(chat, guard)),
|
|
66
|
+
fetchThread: fetchThread(chat, guard),
|
|
67
|
+
listThreads: note(listThreads(chat, guard)),
|
|
68
|
+
getThreadParticipants: getThreadParticipants(chat, guard),
|
|
69
|
+
getChannelInfo: getChannelInfo(chat, guard),
|
|
70
|
+
postMessage: note(postMessage(chat, {
|
|
71
|
+
needsApproval: false,
|
|
72
|
+
guard: postGuard
|
|
73
|
+
})),
|
|
74
|
+
postChannelMessage: note(postChannelMessage(chat, {
|
|
75
|
+
needsApproval: false,
|
|
76
|
+
guard: (id) => {
|
|
77
|
+
if (id.split(":").length > 2) throw new Error(`"${id}" is a thread, not a channel. Use postMessage to reply in a thread.`);
|
|
78
|
+
postGuard(id);
|
|
79
|
+
}
|
|
80
|
+
})),
|
|
81
|
+
findChannel: createTool({
|
|
82
|
+
id: "findChannel",
|
|
83
|
+
description: "Find Slack channels by name, e.g. \"eng\" or \"#eng-proj-factories\". Returns full channel ids (slack:C…) to pass to the other Slack tools, and whether the app is a member. `incomplete: true` means the workspace was too large to check every channel.",
|
|
84
|
+
inputSchema: z.object({ name: z.string().min(1).describe("All or part of the channel name") }),
|
|
85
|
+
execute: async ({ name }) => {
|
|
86
|
+
const query = normalize(name);
|
|
87
|
+
const { items: found, incomplete } = await listAll(async (cursor) => {
|
|
88
|
+
const page = await slackClient(chat).conversations.list({
|
|
89
|
+
types: "public_channel,private_channel",
|
|
90
|
+
exclude_archived: true,
|
|
91
|
+
limit: 1e3,
|
|
92
|
+
cursor
|
|
93
|
+
});
|
|
94
|
+
return {
|
|
95
|
+
items: page.channels,
|
|
96
|
+
response_metadata: page.response_metadata
|
|
97
|
+
};
|
|
98
|
+
});
|
|
99
|
+
return {
|
|
100
|
+
channels: found.filter((c) => c.name?.toLowerCase().includes(query)).slice(0, 20).map((c) => ({
|
|
101
|
+
id: `slack:${c.id}`,
|
|
102
|
+
name: c.name,
|
|
103
|
+
isPrivate: Boolean(c.is_private),
|
|
104
|
+
isMember: Boolean(c.is_member)
|
|
105
|
+
})),
|
|
106
|
+
...incomplete && { incomplete }
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}),
|
|
110
|
+
searchMessages: createTool({
|
|
111
|
+
id: "searchMessages",
|
|
112
|
+
description: "Search recent top-level messages in Slack channels for words. Matches messages containing every word, ignoring case. Reads each channel's newest messages (not thread replies), so older messages are missed. Defaults to this session's channel; use findChannel to get other channel ids.",
|
|
113
|
+
inputSchema: z.object({
|
|
114
|
+
query: z.string().min(1).describe("Words to look for"),
|
|
115
|
+
channelIds: z.array(z.string().min(1)).max(10).optional().describe("Channels to search, as slack:C… ids. Defaults to the channel this session started in."),
|
|
116
|
+
scan: z.number().int().min(1).max(MAX_SEARCH_SCAN).default(200).describe("How many of the newest messages to read in each channel"),
|
|
117
|
+
limit: z.number().int().min(1).max(50).default(20).describe("Most matches to return")
|
|
118
|
+
}),
|
|
119
|
+
execute: async ({ query, channelIds, scan, limit }) => {
|
|
120
|
+
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
121
|
+
const channels = channelIds?.length ? channelIds : [channelOf(chat, sessionThreadId)];
|
|
122
|
+
const matches = [];
|
|
123
|
+
const errors = [];
|
|
124
|
+
let scanned = 0;
|
|
125
|
+
for (const channelId of channels) {
|
|
126
|
+
const id = withPrefix(channelId);
|
|
127
|
+
const channel = channelOf(chat, id).replace(/^slack:/, "");
|
|
128
|
+
let cursor;
|
|
129
|
+
let read = 0;
|
|
130
|
+
try {
|
|
131
|
+
guard(id);
|
|
132
|
+
while (read < scan) {
|
|
133
|
+
const page = await slackClient(chat).conversations.history({
|
|
134
|
+
channel,
|
|
135
|
+
limit: Math.min(200, scan - read),
|
|
136
|
+
cursor
|
|
137
|
+
});
|
|
138
|
+
for (const message of (page.messages ?? []).slice(0, scan - read)) {
|
|
139
|
+
read++;
|
|
140
|
+
scanned++;
|
|
141
|
+
const text = message.text ?? "";
|
|
142
|
+
if (words.every((word) => text.toLowerCase().includes(word))) matches.push({
|
|
143
|
+
channelId: `slack:${channel}`,
|
|
144
|
+
ts: message.ts ?? "",
|
|
145
|
+
userId: message.user,
|
|
146
|
+
text
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
cursor = page.response_metadata?.next_cursor || void 0;
|
|
150
|
+
if (!cursor || (page.messages?.length ?? 0) === 0) break;
|
|
151
|
+
}
|
|
152
|
+
} catch (error) {
|
|
153
|
+
errors.push({
|
|
154
|
+
channelId: `slack:${channel}`,
|
|
155
|
+
error: error.data?.error ?? String(error)
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
matches: matches.slice(0, limit),
|
|
161
|
+
scanned,
|
|
162
|
+
...errors.length ? { errors } : {}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
}),
|
|
166
|
+
findUser: createTool({
|
|
167
|
+
id: "findUser",
|
|
168
|
+
description: "Find people in Slack by name, e.g. \"Caleb\" or \"@caleb\". Returns their user ids (U…), to mention them as <@U…> in a message or to DM them. `incomplete: true` means the workspace was too large to check everyone.",
|
|
169
|
+
inputSchema: z.object({ name: z.string().min(1).describe("All or part of their name or display name") }),
|
|
170
|
+
execute: async ({ name }) => {
|
|
171
|
+
const query = normalize(name);
|
|
172
|
+
const { items: people, incomplete } = await listAll(async (cursor) => {
|
|
173
|
+
const page = await slackClient(chat).users.list({
|
|
174
|
+
limit: 200,
|
|
175
|
+
cursor
|
|
176
|
+
});
|
|
177
|
+
return {
|
|
178
|
+
items: page.members,
|
|
179
|
+
response_metadata: page.response_metadata
|
|
180
|
+
};
|
|
181
|
+
});
|
|
182
|
+
return {
|
|
183
|
+
users: people.filter((p) => !p.deleted && !p.is_bot && p.id !== "USLACKBOT" && [
|
|
184
|
+
p.name,
|
|
185
|
+
p.profile?.real_name,
|
|
186
|
+
p.profile?.display_name
|
|
187
|
+
].some((n) => n?.toLowerCase().includes(query))).slice(0, 20).map((p) => ({
|
|
188
|
+
id: p.id,
|
|
189
|
+
name: p.profile?.real_name || p.name,
|
|
190
|
+
displayName: p.profile?.display_name || void 0
|
|
191
|
+
})),
|
|
192
|
+
...incomplete && { incomplete }
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
}),
|
|
196
|
+
...settings.directMessages === "anyone" ? { sendDirectMessage: createTool({
|
|
197
|
+
id: "sendDirectMessage",
|
|
198
|
+
description: "Send a direct message to a person in Slack. Use findUser to get their user id (U…) from a name.",
|
|
199
|
+
inputSchema: z.object({
|
|
200
|
+
userId: z.string().min(1).describe("Slack user id, e.g. U123456"),
|
|
201
|
+
text: z.string().min(1).describe("The message, in markdown")
|
|
202
|
+
}),
|
|
203
|
+
execute: async ({ userId, text }) => {
|
|
204
|
+
const sent = await (await chat.openDM(userId)).post({ markdown: text });
|
|
205
|
+
return {
|
|
206
|
+
messageId: sent.id,
|
|
207
|
+
threadId: sent.threadId
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
}) } : {}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
export { createSlackChatTools };
|
|
214
|
+
|
|
215
|
+
//# sourceMappingURL=chat-tools.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-tools.js","names":[],"sources":["../../../src/integrations/slack/chat-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport type { SlackAdapter } from '@mastra/slack';\nimport type { Chat } from 'chat';\nimport {\n fetchChannelMessages,\n fetchMessages,\n fetchThread,\n getChannelInfo,\n getThreadParticipants,\n listThreads,\n postChannelMessage,\n postMessage,\n} from 'chat/ai';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../base.js';\nimport type { SlackToolSettings } from './tool-settings.js';\n\n/** Pages read per lookup, so one call can't walk a huge workspace. */\nconst MAX_LOOKUP_PAGES = 10;\n/** Most messages searchMessages reads per channel. */\nconst MAX_SEARCH_SCAN = 1000;\n\n/** Treats a bare Slack id (`C0123`, `D0123`) as `slack:C0123`. */\nfunction withPrefix(id: string): string {\n return id.startsWith('slack:') ? id : `slack:${id}`;\n}\n\n/** Same resolution the Chat SDK's own scope guard uses. */\nfunction channelOf(chat: Chat, id: string): string {\n const prefix = id.split(':')[0];\n const adapter = prefix ? chat.getAdapter(prefix) : undefined;\n return adapter?.channelIdFromThreadId?.(id) ?? id.split(':').slice(0, 2).join(':');\n}\n\nconst slackClient = (chat: Chat) => (chat.getAdapter('slack') as SlackAdapter).webClient;\n\n/**\n * Reads a paginated Slack list until it runs out of pages or hits the cap.\n * `incomplete` is set when the cap stopped it, so a lookup that found nothing\n * isn't mistaken for \"doesn't exist\".\n */\nasync function listAll<T>(\n fetchPage: (cursor: string | undefined) => Promise<{ items?: T[]; response_metadata?: { next_cursor?: string } }>,\n): Promise<{ items: T[]; incomplete?: true }> {\n const items: T[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < MAX_LOOKUP_PAGES; page++) {\n const result = await fetchPage(cursor);\n items.push(...(result.items ?? []));\n cursor = result.response_metadata?.next_cursor || undefined;\n if (!cursor) return { items };\n }\n return { items, incomplete: true };\n}\n\nconst normalize = (text: string) => text.toLowerCase().replace(/^[#@]/, '').trim();\n\n/**\n * The Chat SDK's read and post tools, plus channel/person lookup, search and\n * DMs, confined to the channels `settings` grant. They act as the app, so a\n * session never reaches a channel the app isn't in, and posting needs no\n * approval.\n */\nexport function createSlackChatTools({\n chat,\n sessionThreadId,\n settings,\n}: {\n chat: Chat;\n /** The session's own chat thread id, e.g. `slack:C123:1700000000.000100`. */\n sessionThreadId: string;\n settings: SlackToolSettings;\n}): IntegrationTools {\n const all = settings.channels === 'all';\n const allowed = new Set([\n channelOf(chat, sessionThreadId),\n ...(settings.channels === 'selected' ? settings.channelIds.map(id => `slack:${id}`) : []),\n ]);\n const scope = all ? 'any channel the app is a member of' : [...allowed].join(', ');\n // Passing our own guard (a bare function for reads, `guard` for writes)\n // replaces the Chat SDK's, which would otherwise confine the tools to the\n // Slack conversation being handled.\n const ownChannel = channelOf(chat, sessionThreadId);\n const guard = (id: string) => {\n const channel = channelOf(chat, withPrefix(id));\n // Other people's DMs with the app are theirs, even when every channel is granted.\n if (channel.startsWith('slack:D') && channel !== ownChannel) {\n throw new Error(`\"${id}\" is someone else's direct message with the app. Use sendDirectMessage to message a person.`);\n }\n if (all) return;\n if (!allowed.has(channel)) {\n throw new Error(`\"${id}\" is outside the channels this session can use: ${scope}.`);\n }\n };\n const postGuard =\n settings.channelAccess === 'read'\n ? (id: string) => {\n if (channelOf(chat, id) !== ownChannel) {\n throw new Error(`\"${id}\" is read only for this session: it can only post in its own channel, ${ownChannel}.`);\n }\n }\n : guard;\n const note = <T extends { description?: unknown }>(tool: T): T => ({\n ...tool,\n description: `${String(tool.description)} Channels this session can use: ${scope}${\n settings.channelAccess === 'read' ? \" (read only: post only in this session's own channel)\" : ''\n }. This session's thread is ${sessionThreadId}.`,\n });\n\n return {\n fetchMessages: note(fetchMessages(chat, guard)),\n fetchChannelMessages: note(fetchChannelMessages(chat, guard)),\n fetchThread: fetchThread(chat, guard),\n listThreads: note(listThreads(chat, guard)),\n getThreadParticipants: getThreadParticipants(chat, guard),\n getChannelInfo: getChannelInfo(chat, guard),\n postMessage: note(postMessage(chat, { needsApproval: false, guard: postGuard })),\n // Given a thread id, Slack would silently post a new top-level message\n // instead of replying in that thread.\n postChannelMessage: note(\n postChannelMessage(chat, {\n needsApproval: false,\n guard: id => {\n if (id.split(':').length > 2) {\n throw new Error(`\"${id}\" is a thread, not a channel. Use postMessage to reply in a thread.`);\n }\n postGuard(id);\n },\n }),\n ),\n findChannel: createTool({\n id: 'findChannel',\n description:\n 'Find Slack channels by name, e.g. \"eng\" or \"#eng-proj-factories\". Returns full channel ids (slack:C…) to pass to the other Slack tools, and whether the app is a member. `incomplete: true` means the workspace was too large to check every channel.',\n inputSchema: z.object({ name: z.string().min(1).describe('All or part of the channel name') }),\n execute: async ({ name }) => {\n const query = normalize(name);\n const { items: found, incomplete } = await listAll(async cursor => {\n const page = await slackClient(chat).conversations.list({\n types: 'public_channel,private_channel',\n exclude_archived: true,\n limit: 1000,\n cursor,\n });\n return { items: page.channels, response_metadata: page.response_metadata };\n });\n const matches = found.filter(c => c.name?.toLowerCase().includes(query));\n return {\n channels: matches.slice(0, 20).map(c => ({\n id: `slack:${c.id}`,\n name: c.name,\n isPrivate: Boolean(c.is_private),\n isMember: Boolean(c.is_member),\n })),\n ...(incomplete && { incomplete }),\n };\n },\n }),\n searchMessages: createTool({\n id: 'searchMessages',\n description:\n \"Search recent top-level messages in Slack channels for words. Matches messages containing every word, ignoring case. Reads each channel's newest messages (not thread replies), so older messages are missed. Defaults to this session's channel; use findChannel to get other channel ids.\",\n inputSchema: z.object({\n query: z.string().min(1).describe('Words to look for'),\n channelIds: z\n .array(z.string().min(1))\n .max(10)\n .optional()\n .describe('Channels to search, as slack:C… ids. Defaults to the channel this session started in.'),\n scan: z\n .number()\n .int()\n .min(1)\n .max(MAX_SEARCH_SCAN)\n .default(200)\n .describe('How many of the newest messages to read in each channel'),\n limit: z.number().int().min(1).max(50).default(20).describe('Most matches to return'),\n }),\n execute: async ({ query, channelIds, scan, limit }) => {\n const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n const channels = channelIds?.length ? channelIds : [channelOf(chat, sessionThreadId)];\n const matches: Array<{ channelId: string; ts: string; userId?: string; text: string }> = [];\n const errors: Array<{ channelId: string; error: string }> = [];\n let scanned = 0;\n for (const channelId of channels) {\n // Read the channel the guard checked, not whatever string was passed.\n const id = withPrefix(channelId);\n const channel = channelOf(chat, id).replace(/^slack:/, '');\n let cursor: string | undefined;\n let read = 0;\n try {\n guard(id);\n while (read < scan) {\n const page = await slackClient(chat).conversations.history({\n channel,\n limit: Math.min(200, scan - read),\n cursor,\n });\n for (const message of (page.messages ?? []).slice(0, scan - read)) {\n read++;\n scanned++;\n const text = message.text ?? '';\n if (words.every(word => text.toLowerCase().includes(word))) {\n matches.push({ channelId: `slack:${channel}`, ts: message.ts ?? '', userId: message.user, text });\n }\n }\n cursor = page.response_metadata?.next_cursor || undefined;\n if (!cursor || (page.messages?.length ?? 0) === 0) break;\n }\n } catch (error) {\n errors.push({\n channelId: `slack:${channel}`,\n error: (error as { data?: { error?: string } }).data?.error ?? String(error),\n });\n }\n }\n return {\n matches: matches.slice(0, limit),\n scanned,\n ...(errors.length ? { errors } : {}),\n };\n },\n }),\n findUser: createTool({\n id: 'findUser',\n description:\n 'Find people in Slack by name, e.g. \"Caleb\" or \"@caleb\". Returns their user ids (U…), to mention them as <@U…> in a message or to DM them. `incomplete: true` means the workspace was too large to check everyone.',\n inputSchema: z.object({ name: z.string().min(1).describe('All or part of their name or display name') }),\n execute: async ({ name }) => {\n const query = normalize(name);\n const { items: people, incomplete } = await listAll(async cursor => {\n const page = await slackClient(chat).users.list({ limit: 200, cursor });\n return { items: page.members, response_metadata: page.response_metadata };\n });\n const matches = people.filter(\n p =>\n !p.deleted &&\n !p.is_bot &&\n p.id !== 'USLACKBOT' &&\n [p.name, p.profile?.real_name, p.profile?.display_name].some(n => n?.toLowerCase().includes(query)),\n );\n return {\n users: matches.slice(0, 20).map(p => ({\n id: p.id,\n name: p.profile?.real_name || p.name,\n displayName: p.profile?.display_name || undefined,\n })),\n ...(incomplete && { incomplete }),\n };\n },\n }),\n // The Chat SDK's own sendDirectMessage asks for approval; this one doesn't.\n ...(settings.directMessages === 'anyone'\n ? {\n sendDirectMessage: createTool({\n id: 'sendDirectMessage',\n description: 'Send a direct message to a person in Slack. Use findUser to get their user id (U…) from a name.',\n inputSchema: z.object({\n userId: z.string().min(1).describe('Slack user id, e.g. U123456'),\n text: z.string().min(1).describe('The message, in markdown'),\n }),\n execute: async ({ userId, text }) => {\n const dm = await chat.openDM(userId);\n const sent = await dm.post({ markdown: text });\n return { messageId: sent.id, threadId: sent.threadId };\n },\n }),\n }\n : {}),\n };\n}\n"],"mappings":";;;;;AAmBA,MAAM,mBAAmB;;AAEzB,MAAM,kBAAkB;;AAGxB,SAAS,WAAW,IAAoB;CACtC,OAAO,GAAG,WAAW,QAAQ,IAAI,KAAK,SAAS;AACjD;;AAGA,SAAS,UAAU,MAAY,IAAoB;CACjD,MAAM,SAAS,GAAG,MAAM,GAAG,CAAC,CAAC;CAE7B,QADgB,SAAS,KAAK,WAAW,MAAM,IAAI,KAAA,EAAA,EACnC,wBAAwB,EAAE,KAAK,GAAG,MAAM,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG;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AC;IAQD,OAAO;KACL,OARc,OAAO,QACrB,MACE,CAAC,EAAE,WACH,CAAC,EAAE,UACH,EAAE,OAAO,eACT;MAAC,EAAE;MAAM,EAAE,SAAS;MAAW,EAAE,SAAS;KAAY,CAAC,CAAC,MAAK,MAAK,GAAG,YAAY,CAAC,CAAC,SAAS,KAAK,CAAC,CAGvF,CAAC,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,KAAI,OAAM;MACpC,IAAI,EAAE;MACN,MAAM,EAAE,SAAS,aAAa,EAAE;MAChC,aAAa,EAAE,SAAS,gBAAgB,KAAA;KAC1C,EAAE;KACF,GAAI,cAAc,EAAE,WAAW;IACjC;GACF;EACF,CAAC;EAED,GAAI,SAAS,mBAAmB,WAC5B,EACE,mBAAmB,WAAW;GAC5B,IAAI;GACJ,aAAa;GACb,aAAa,EAAE,OAAO;IACpB,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,6BAA6B;IAChE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,0BAA0B;GAC7D,CAAC;GACD,SAAS,OAAO,EAAE,QAAQ,WAAW;IAEnC,MAAM,OAAO,OAAM,MADF,KAAK,OAAO,MAAM,EAAA,CACb,KAAK,EAAE,UAAU,KAAK,CAAC;IAC7C,OAAO;KAAE,WAAW,KAAK;KAAI,UAAU,KAAK;IAAS;GACvD;EACF,CAAC,EACH,IACA,CAAC;CACP;AACF"}
|
|
@@ -24,6 +24,7 @@ import type { ApiRoute } from '@mastra/core/server';
|
|
|
24
24
|
import type { SlackAdapterChannelConfig } from '@mastra/slack';
|
|
25
25
|
import type { WorkItemFeedPublisher } from '../../storage/domains/comments/feed-sync.js';
|
|
26
26
|
import type { FactoryChannelsConfig, FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';
|
|
27
|
+
import type { SlackToolSettings } from './tool-settings.js';
|
|
27
28
|
/** Slack app credentials, read from env ONCE by the deploy entry. */
|
|
28
29
|
export interface SlackIntegrationConfig {
|
|
29
30
|
/** Slack event transport. Defaults to webhook mode. */
|
|
@@ -63,6 +64,20 @@ export interface SlackIntegrationConfig {
|
|
|
63
64
|
* ```
|
|
64
65
|
*/
|
|
65
66
|
adapterOptions?: SlackAdapterChannelConfig;
|
|
67
|
+
/**
|
|
68
|
+
* What sessions started from Slack may do with the Slack tools. By default a
|
|
69
|
+
* session can read and post only in its own channel, and can't send DMs.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```ts
|
|
73
|
+
* new SlackIntegration({
|
|
74
|
+
* signingSecret,
|
|
75
|
+
* // Any channel the app is in, and DMs to anyone in the workspace.
|
|
76
|
+
* tools: { channels: 'all', directMessages: 'anyone' },
|
|
77
|
+
* });
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
tools?: Partial<SlackToolSettings>;
|
|
66
81
|
}
|
|
67
82
|
export declare class SlackIntegration implements FactoryIntegration {
|
|
68
83
|
#private;
|
|
@@ -88,9 +103,10 @@ export declare class SlackIntegration implements FactoryIntegration {
|
|
|
88
103
|
channels?: () => AgentChannels | null | undefined;
|
|
89
104
|
}): void;
|
|
90
105
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* post into when
|
|
106
|
+
* On runs whose session is linked to a Slack thread: `attach_file`,
|
|
107
|
+
* `reply_in_thread` when reply text is hidden, and the Slack read, post,
|
|
108
|
+
* search, lookup and DM tools. The tools find the thread to post into when
|
|
109
|
+
* they are called.
|
|
94
110
|
*/
|
|
95
111
|
agentTools({ requestContext }: {
|
|
96
112
|
requestContext: RequestContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,uBAAuB,CAAC;AAC3E,OAAO,KAAK,EAAE,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G,qBAAqB,CAE5D;IAED,MAAM,CAAC,GAAG,EAAE,kBAAkB,GAAG,QAAQ,EAAE,CAY1C;IAED,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAQrC;CACF"}
|
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
import { parseCreatedPullRequest } from "../github/session-subscriptions.js";
|
|
2
1
|
import { announcePullRequest } from "../channel-thread-announcements.js";
|
|
2
|
+
import { parseCreatedPullRequest } from "../github/session-subscriptions.js";
|
|
3
3
|
import { FactoryChannelReplyProcessor } from "./channel-reply-processor.js";
|
|
4
4
|
import { FactoryChannelSessionLinkProcessor } from "./channel-session-link-processor.js";
|
|
5
|
+
import { createSlackChatTools } from "./chat-tools.js";
|
|
5
6
|
import { createSlackConnectRoutes } from "./connect-route.js";
|
|
6
7
|
import { SlackFeedPublisher } from "./feed-publisher.js";
|
|
7
|
-
import { createShareFileTool, isSlackThread } from "./share-file-tool.js";
|
|
8
|
-
import { FactoryReplyStreamProcessor, createReplyTool } from "./reply-tool.js";
|
|
9
8
|
import { FactoryReplyReminderProcessor } from "./reply-reminder-processor.js";
|
|
9
|
+
import { FactoryReplyStreamProcessor, createReplyTool } from "./reply-tool.js";
|
|
10
|
+
import { createShareFileTool, isSlackThread, slackThreadOf } from "./share-file-tool.js";
|
|
10
11
|
import { createSlackChannelsConfig } from "./slack.js";
|
|
12
|
+
import { DEFAULT_SLACK_TOOL_SETTINGS, slackToolSettingsSchema } from "./tool-settings.js";
|
|
11
13
|
// src/integrations/slack/integration.ts
|
|
12
14
|
/** Slack renders the status inline next to the app name; keep it to one short line. */
|
|
13
15
|
const MAX_STATUS_LENGTH = 80;
|
|
@@ -74,6 +76,7 @@ var SlackIntegration = class {
|
|
|
74
76
|
*/
|
|
75
77
|
requiresStableStateSigner = true;
|
|
76
78
|
#config;
|
|
79
|
+
#toolSettings;
|
|
77
80
|
#adapterOptions;
|
|
78
81
|
/** Bound in `initialize()`; the controller mounts after integrations are built. */
|
|
79
82
|
#channels;
|
|
@@ -97,6 +100,11 @@ var SlackIntegration = class {
|
|
|
97
100
|
if (mode === "socket" && !config.appToken) throw new Error("SlackIntegration: 'appToken' is required in socket mode — Slack cannot open a Socket Mode connection without it.");
|
|
98
101
|
if (mode === "socket" && !config.botToken) throw new Error("SlackIntegration: 'botToken' is required in socket mode — Factory cannot reply without it.");
|
|
99
102
|
this.#config = config;
|
|
103
|
+
const granted = Object.fromEntries(Object.entries(config.tools ?? {}).filter(([, value]) => value !== void 0));
|
|
104
|
+
this.#toolSettings = slackToolSettingsSchema.parse({
|
|
105
|
+
...DEFAULT_SLACK_TOOL_SETTINGS,
|
|
106
|
+
...granted
|
|
107
|
+
});
|
|
100
108
|
this.#adapterOptions = factoryAdapterOptions(adapterOverrides(config.adapterOptions));
|
|
101
109
|
const textHidden = this.#textHidden;
|
|
102
110
|
this.processors = {
|
|
@@ -111,15 +119,24 @@ var SlackIntegration = class {
|
|
|
111
119
|
this.#channels = args.channels;
|
|
112
120
|
}
|
|
113
121
|
/**
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
* post into when
|
|
122
|
+
* On runs whose session is linked to a Slack thread: `attach_file`,
|
|
123
|
+
* `reply_in_thread` when reply text is hidden, and the Slack read, post,
|
|
124
|
+
* search, lookup and DM tools. The tools find the thread to post into when
|
|
125
|
+
* they are called.
|
|
117
126
|
*/
|
|
118
127
|
async agentTools({ requestContext }) {
|
|
119
|
-
|
|
128
|
+
const slackThread = await slackThreadOf(requestContext, this.#deps);
|
|
129
|
+
if (!slackThread) return {};
|
|
130
|
+
const chat = this.#channels?.()?.sdk;
|
|
131
|
+
const sessionThreadId = slackThread.threadId;
|
|
120
132
|
return {
|
|
121
133
|
...createShareFileTool(requestContext, this.#deps),
|
|
122
|
-
...this.#textHidden ? createReplyTool(requestContext, this.#deps) : {}
|
|
134
|
+
...this.#textHidden ? createReplyTool(requestContext, this.#deps) : {},
|
|
135
|
+
...chat && sessionThreadId ? createSlackChatTools({
|
|
136
|
+
chat,
|
|
137
|
+
sessionThreadId,
|
|
138
|
+
settings: this.#toolSettings
|
|
139
|
+
}) : {}
|
|
123
140
|
};
|
|
124
141
|
}
|
|
125
142
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/slack/integration.ts"],"sourcesContent":["/**\n * `SlackIntegration` — Slack as a `FactoryIntegration`.\n *\n * Slack contributes two things to a factory: the chat channels that carry\n * inbound messages into agent runs (`channels()`), and the browser-facing\n * account-link routes that bind a Slack sender to a Mastra tenant (`routes()`).\n * Both used to be assembled by hand in the deploy entry, which had to reach\n * into the prepared agent controller by string key, resolve storage domains\n * itself, mint its own state signer, and splice routes onto the factory's\n * assembled server config. Implementing the integration interface instead means\n * the factory does all of that the same way it already does for GitHub and\n * Linear, and the entry's job shrinks to reading Slack's env vars once.\n *\n * Slack ships as a factory built-in alongside GitHub and Linear (it originally\n * lived in `mastracode/web` to keep `@mastra/slack`/`chat` out of this package;\n * the team reversed that so `create-factory` consumers get Slack channels out\n * of the box). The integration interface remains open — third parties still add\n * capabilities by implementing `FactoryIntegration` from outside the package.\n */\n\nimport type { AgentChannels, TypingStatusFn } from '@mastra/core/channels';\nimport type { InputProcessor, OutputProcessor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { SlackAdapterChannelConfig } from '@mastra/slack';\n\nimport type { WorkItemFeedPublisher } from '../../storage/domains/comments/feed-sync.js';\n\nimport type { FactoryChannelsConfig, FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { announcePullRequest } from '../channel-thread-announcements.js';\nimport { parseCreatedPullRequest } from '../github/session-subscriptions.js';\nimport { FactoryChannelReplyProcessor } from './channel-reply-processor.js';\nimport { FactoryChannelSessionLinkProcessor } from './channel-session-link-processor.js';\nimport { createSlackConnectRoutes } from './connect-route.js';\nimport { SlackFeedPublisher } from './feed-publisher.js';\nimport { FactoryReplyReminderProcessor } from './reply-reminder-processor.js';\nimport { createReplyTool, FactoryReplyStreamProcessor, REPLY_TOOL_NAME } from './reply-tool.js';\nimport { createShareFileTool, isSlackThread } from './share-file-tool.js';\nimport type { ShareFileToolDeps } from './share-file-tool.js';\nimport { createSlackChannelsConfig } from './slack.js';\n\n/** Slack app credentials, read from env ONCE by the deploy entry. */\nexport interface SlackIntegrationConfig {\n /** Slack event transport. Defaults to webhook mode. */\n mode?: 'webhook' | 'socket';\n /** Verifies inbound Slack request signatures. Required in webhook mode. */\n signingSecret?: string;\n /** App-level token used to connect to Slack. Required in socket mode. */\n appToken?: string;\n /** Bot token used to post replies and ephemeral cards. */\n botToken?: string;\n /**\n * OAuth client credentials. Required for account linking: \"Sign in with\n * Slack\" (OIDC) is the only flow that writes a link, so without these the\n * settings surface reports `canConnect: false` and no sender can link.\n */\n clientId?: string;\n clientSecret?: string;\n /**\n * HTTPS origin Slack redirects back to. Slack requires HTTPS, so locally this\n * is the tunnel origin rather than the app's own public URL.\n */\n oidcRedirectBaseUrl?: string;\n /** SPA origin the post-connect redirect returns to. */\n uiOrigin?: string;\n /**\n * Overrides for the Slack channel adapter entry.\n *\n * @example\n * ```ts\n * new SlackIntegration({\n * signingSecret,\n * adapterOptions: {\n * streaming: true,\n * toolDisplay: 'grouped',\n * },\n * });\n * ```\n */\n adapterOptions?: SlackAdapterChannelConfig;\n}\n\n/** Slack renders the status inline next to the app name; keep it to one short line. */\nconst MAX_STATUS_LENGTH = 80;\n\n/**\n * Turns a tool's `description` arg (\"Listing the repo root\") into a status\n * line that reads after the app name (\"<App> is listing the repo root…\").\n * Only the first line counts: issue/PR creators carry whole bodies there.\n */\nfunction describeToolCall(args: unknown): string | undefined {\n if (!args || typeof args !== 'object') return undefined;\n const { description } = args as { description?: unknown };\n if (typeof description !== 'string') return undefined;\n const line = description\n .split('\\n')\n .map(part => part.replace(/\\s+/g, ' ').trim())\n .find(Boolean);\n if (!line) return undefined;\n const text = line.length > MAX_STATUS_LENGTH ? `${line.slice(0, MAX_STATUS_LENGTH - 1)}…` : line;\n // Drop the sentence-case capital (\"Listing\" → \"listing\") but leave acronyms\n // and identifiers (\"PR lookup\", \"CI status\") alone.\n return `is ${/^[A-Z][a-z]/.test(text) ? text.charAt(0).toLowerCase() + text.slice(1) : text}`;\n}\n\n/**\n * With reply text hidden, streamed text never reaches the thread, so it gets\n * no status: an \"is typing...\" set after the reply tool's post would sit on\n * the thread with nothing coming, and race the clear at the end of the run.\n */\nconst factoryTypingStatus =\n (textDisplay: SlackAdapterChannelConfig['textDisplay']): TypingStatusFn =>\n chunk => {\n switch (chunk.type) {\n case 'reasoning-delta':\n return 'is thinking...';\n case 'text-delta':\n return textDisplay === 'hidden' ? undefined : 'is typing...';\n // The reply tool's text streams into the thread as the model writes it.\n case 'tool-call-input-streaming-start':\n return chunk.payload.toolName === REPLY_TOOL_NAME ? 'is typing...' : undefined;\n case 'tool-call':\n // Still finishing the streamed reply; don't flip to \"is working...\".\n if (chunk.payload.toolName === REPLY_TOOL_NAME) return 'is typing...';\n return describeToolCall(chunk.payload.args) ?? 'is working...';\n default:\n return undefined;\n }\n};\n\n/**\n * Drops keys the caller set to `undefined` so spreading the overrides cannot\n * erase the Factory defaults they sit on top of.\n */\nfunction adapterOverrides(options: SlackAdapterChannelConfig | undefined): SlackAdapterChannelConfig {\n return Object.fromEntries(\n Object.entries(options ?? {}).filter(([, value]) => value !== undefined),\n ) as SlackAdapterChannelConfig;\n}\n\n/**\n * Factory defaults under the caller's overrides. Tool calls stay out of the\n * thread: a Factory session runs hundreds of them, and a row per call (or a\n * card per call) buries the reply. Progress shows through the typing status\n * instead, which names the tool's current step; the session link carries the\n * full trace. `grouped` remains available via `adapterOptions` for callers\n * who want Slack's \"Thinking Steps\" widget.\n */\nfunction factoryAdapterOptions(overrides: SlackAdapterChannelConfig): SlackAdapterChannelConfig {\n const textDisplay = overrides.textDisplay ?? 'hidden';\n return { typingStatus: factoryTypingStatus(textDisplay), toolDisplay: 'hidden', textDisplay, ...overrides };\n}\n\nexport class SlackIntegration implements FactoryIntegration {\n readonly id = 'slack';\n /**\n * The OIDC connect flow round-trips a signed `state` through Slack, so the\n * replica handling the callback must be able to verify a state a different\n * replica signed.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #config: SlackIntegrationConfig;\n readonly #adapterOptions: SlackAdapterChannelConfig;\n /** Bound in `initialize()`; the controller mounts after integrations are built. */\n #channels: ShareFileToolDeps['channels'];\n readonly #deps: ShareFileToolDeps = { channels: () => this.#channels?.() };\n /**\n * With reply text hidden (the Factory default) the agent speaks through\n * `reply_in_thread`, so the prompt, reminder and live streaming for that\n * tool come with it. The setting is fixed for the deployment, so it is\n * decided once here rather than on every run.\n */\n readonly processors: { input: InputProcessor[]; output: OutputProcessor[] };\n /**\n * Whether `channels()` found a source-control owner on the context and wired\n * repo-backed sessions. Set at the channels() attach path, which runs once at\n * boot before diagnostics are served.\n */\n #repoBackedSessions = false;\n\n constructor(config: SlackIntegrationConfig) {\n const mode = config.mode ?? 'webhook';\n if (mode === 'webhook' && !config.signingSecret) {\n throw new Error(\n \"SlackIntegration: 'signingSecret' is required in webhook mode — Slack cannot verify inbound requests without it.\",\n );\n }\n if (mode === 'socket' && !config.appToken) {\n throw new Error(\"SlackIntegration: 'appToken' is required in socket mode — Slack cannot open a Socket Mode connection without it.\");\n }\n if (mode === 'socket' && !config.botToken) {\n throw new Error(\"SlackIntegration: 'botToken' is required in socket mode — Factory cannot reply without it.\");\n }\n this.#config = config;\n this.#adapterOptions = factoryAdapterOptions(adapterOverrides(config.adapterOptions));\n const textHidden = this.#textHidden;\n this.processors = {\n input: [\n new FactoryChannelReplyProcessor(),\n ...(textHidden ? [new FactoryReplyReminderProcessor()] : []),\n ],\n output: [\n new FactoryChannelSessionLinkProcessor(),\n ...(textHidden ? [new FactoryReplyStreamProcessor(this.#deps)] : []),\n ],\n };\n }\n\n get #textHidden(): boolean {\n return this.#adapterOptions.textDisplay === 'hidden';\n }\n\n initialize(args: { channels?: () => AgentChannels | null | undefined }): void {\n this.#channels = args.channels;\n }\n\n /**\n * `attach_file`, and `reply_in_thread` when reply text is hidden, on runs\n * whose session is linked to a Slack thread. The tools find the thread to\n * post into when they are called.\n */\n async agentTools({ requestContext }: { requestContext: RequestContext }): Promise<IntegrationTools> {\n if (!(await isSlackThread(requestContext, this.#deps))) return {};\n return {\n ...createShareFileTool(requestContext, this.#deps),\n ...(this.#textHidden ? createReplyTool(requestContext, this.#deps) : {}),\n };\n }\n\n /**\n * When a run opens a pull request, post its link into the session's Slack\n * thread.\n */\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const url = parseCreatedPullRequest(toolContext);\n const threadId = (requestContext?.get('controller') as { threadId?: string } | undefined)?.threadId;\n if (!url || !requestContext || !threadId || !(await isSlackThread(requestContext, this.#deps))) return;\n // Not awaited: the tool call must not wait on Slack.\n void announcePullRequest(this.#channels?.(), threadId, 'opened', url).catch(error =>\n console.warn('[slack] pull request opened announcement failed', error),\n );\n }\n\n channels(ctx: IntegrationContext): FactoryChannelsConfig {\n // Repo-backed sessions select the source-control provider from the linked\n // repository on each Factory project.\n const sourceControls =\n ctx.storage.sourceControls ?? (ctx.storage.sourceControlOwner ? [ctx.storage.sourceControlOwner] : []);\n this.#repoBackedSessions = sourceControls.length > 0;\n const mode = this.#config.mode ?? 'webhook';\n return createSlackChannelsConfig({\n slack: {\n mode: this.#config.mode,\n ...(mode === 'webhook'\n ? { clientId: this.#config.clientId, clientSecret: this.#config.clientSecret }\n : {}),\n signingSecret: this.#config.signingSecret,\n appToken: this.#config.appToken,\n botToken: this.#config.botToken,\n },\n accountLinks: ctx.storage.channelIdentity,\n projects: ctx.storage.projects,\n sourceControls,\n modelDefaults: ctx.storage.modelDefaults,\n workItems: ctx.runtime?.workItems,\n feed: ctx.feed,\n adapterOptions: this.#adapterOptions,\n });\n }\n\n feedPublisher(ctx: IntegrationContext): WorkItemFeedPublisher {\n return new SlackFeedPublisher({ controller: ctx.controller });\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n const { clientId, clientSecret, oidcRedirectBaseUrl, uiOrigin } = this.#config;\n return createSlackConnectRoutes({\n auth: ctx.auth,\n accountLinks: ctx.storage.channelIdentity,\n tenantStateSigner: ctx.stateSigner,\n oidc:\n clientId && clientSecret && oidcRedirectBaseUrl\n ? { clientId, clientSecret, redirectBaseUrl: oidcRedirectBaseUrl, uiOrigin }\n : undefined,\n projects: ctx.storage.projects,\n });\n }\n\n diagnostics(): Record<string, unknown> {\n const { clientId, clientSecret, botToken, oidcRedirectBaseUrl } = this.#config;\n return {\n configured: true,\n botTokenConfigured: Boolean(botToken),\n oidcConfigured: Boolean(clientId && clientSecret && oidcRedirectBaseUrl),\n repoBackedSessions: this.#repoBackedSessions,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;AAmFA,MAAM,oBAAoB;;;;;;AAO1B,SAAS,iBAAiB,MAAmC;CAC3D,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAA;CAC9C,MAAM,EAAE,gBAAgB;CACxB,IAAI,OAAO,gBAAgB,UAAU,OAAO,KAAA;CAC5C,MAAM,OAAO,YACV,MAAM,IAAI,CAAC,CACX,KAAI,SAAQ,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAC7C,KAAK,OAAO;CACf,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,MAAM,OAAO,KAAK,SAAS,oBAAoB,GAAG,KAAK,MAAM,GAAG,EAAqB,EAAE,KAAK;CAG5F,OAAO,MAAM,cAAc,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC,IAAI;AACzF;;;;;;AAOA,MAAM,uBACH,iBACD,UAAS;CACT,QAAQ,MAAM,MAAd;EACE,KAAK,mBACH,OAAO;EACT,KAAK,cACH,OAAO,gBA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,IAAI,SAAS;GACxB,MAAM,IAAI;GACV,gBAAgB,KAAK;EACvB,CAAC;CACH;CAEA,cAAc,KAAgD;EAC5D,OAAO,IAAI,mBAAmB,EAAE,YAAY,IAAI,WAAW,CAAC;CAC9D;CAEA,OAAO,KAAqC;EAC1C,MAAM,EAAE,UAAU,cAAc,qBAAqB,aAAa,KAAK;EACvE,OAAO,yBAAyB;GAC9B,MAAM,IAAI;GACV,cAAc,IAAI,QAAQ;GAC1B,mBAAmB,IAAI;GACvB,MACE,YAAY,gBAAgB,sBACxB;IAAE;IAAU;IAAc,iBAAiB;IAAqB;GAAS,IACzE,KAAA;GACN,UAAU,IAAI,QAAQ;EACxB,CAAC;CACH;CAEA,cAAuC;EACrC,MAAM,EAAE,UAAU,cAAc,UAAU,wBAAwB,KAAK;EACvE,OAAO;GACL,YAAY;GACZ,oBAAoB,QAAQ,QAAQ;GACpC,gBAAgB,QAAQ,YAAY,gBAAgB,mBAAmB;GACvE,oBAAoB,KAAK;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/slack/integration.ts"],"sourcesContent":["/**\n * `SlackIntegration` — Slack as a `FactoryIntegration`.\n *\n * Slack contributes two things to a factory: the chat channels that carry\n * inbound messages into agent runs (`channels()`), and the browser-facing\n * account-link routes that bind a Slack sender to a Mastra tenant (`routes()`).\n * Both used to be assembled by hand in the deploy entry, which had to reach\n * into the prepared agent controller by string key, resolve storage domains\n * itself, mint its own state signer, and splice routes onto the factory's\n * assembled server config. Implementing the integration interface instead means\n * the factory does all of that the same way it already does for GitHub and\n * Linear, and the entry's job shrinks to reading Slack's env vars once.\n *\n * Slack ships as a factory built-in alongside GitHub and Linear (it originally\n * lived in `mastracode/web` to keep `@mastra/slack`/`chat` out of this package;\n * the team reversed that so `create-factory` consumers get Slack channels out\n * of the box). The integration interface remains open — third parties still add\n * capabilities by implementing `FactoryIntegration` from outside the package.\n */\n\nimport type { AgentChannels, TypingStatusFn } from '@mastra/core/channels';\nimport type { InputProcessor, OutputProcessor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { SlackAdapterChannelConfig } from '@mastra/slack';\n\nimport type { WorkItemFeedPublisher } from '../../storage/domains/comments/feed-sync.js';\n\nimport type { FactoryChannelsConfig, FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { announcePullRequest } from '../channel-thread-announcements.js';\nimport { parseCreatedPullRequest } from '../github/session-subscriptions.js';\nimport { FactoryChannelReplyProcessor } from './channel-reply-processor.js';\nimport { FactoryChannelSessionLinkProcessor } from './channel-session-link-processor.js';\nimport { createSlackChatTools } from './chat-tools.js';\nimport { createSlackConnectRoutes } from './connect-route.js';\nimport { SlackFeedPublisher } from './feed-publisher.js';\nimport { FactoryReplyReminderProcessor } from './reply-reminder-processor.js';\nimport { createReplyTool, FactoryReplyStreamProcessor, REPLY_TOOL_NAME } from './reply-tool.js';\nimport { createShareFileTool, isSlackThread, slackThreadOf } from './share-file-tool.js';\nimport type { ShareFileToolDeps } from './share-file-tool.js';\nimport { createSlackChannelsConfig } from './slack.js';\nimport { DEFAULT_SLACK_TOOL_SETTINGS, slackToolSettingsSchema } from './tool-settings.js';\nimport type { SlackToolSettings } from './tool-settings.js';\n\n/** Slack app credentials, read from env ONCE by the deploy entry. */\nexport interface SlackIntegrationConfig {\n /** Slack event transport. Defaults to webhook mode. */\n mode?: 'webhook' | 'socket';\n /** Verifies inbound Slack request signatures. Required in webhook mode. */\n signingSecret?: string;\n /** App-level token used to connect to Slack. Required in socket mode. */\n appToken?: string;\n /** Bot token used to post replies and ephemeral cards. */\n botToken?: string;\n /**\n * OAuth client credentials. Required for account linking: \"Sign in with\n * Slack\" (OIDC) is the only flow that writes a link, so without these the\n * settings surface reports `canConnect: false` and no sender can link.\n */\n clientId?: string;\n clientSecret?: string;\n /**\n * HTTPS origin Slack redirects back to. Slack requires HTTPS, so locally this\n * is the tunnel origin rather than the app's own public URL.\n */\n oidcRedirectBaseUrl?: string;\n /** SPA origin the post-connect redirect returns to. */\n uiOrigin?: string;\n /**\n * Overrides for the Slack channel adapter entry.\n *\n * @example\n * ```ts\n * new SlackIntegration({\n * signingSecret,\n * adapterOptions: {\n * streaming: true,\n * toolDisplay: 'grouped',\n * },\n * });\n * ```\n */\n adapterOptions?: SlackAdapterChannelConfig;\n /**\n * What sessions started from Slack may do with the Slack tools. By default a\n * session can read and post only in its own channel, and can't send DMs.\n *\n * @example\n * ```ts\n * new SlackIntegration({\n * signingSecret,\n * // Any channel the app is in, and DMs to anyone in the workspace.\n * tools: { channels: 'all', directMessages: 'anyone' },\n * });\n * ```\n */\n tools?: Partial<SlackToolSettings>;\n}\n\n/** Slack renders the status inline next to the app name; keep it to one short line. */\nconst MAX_STATUS_LENGTH = 80;\n\n/**\n * Turns a tool's `description` arg (\"Listing the repo root\") into a status\n * line that reads after the app name (\"<App> is listing the repo root…\").\n * Only the first line counts: issue/PR creators carry whole bodies there.\n */\nfunction describeToolCall(args: unknown): string | undefined {\n if (!args || typeof args !== 'object') return undefined;\n const { description } = args as { description?: unknown };\n if (typeof description !== 'string') return undefined;\n const line = description\n .split('\\n')\n .map(part => part.replace(/\\s+/g, ' ').trim())\n .find(Boolean);\n if (!line) return undefined;\n const text = line.length > MAX_STATUS_LENGTH ? `${line.slice(0, MAX_STATUS_LENGTH - 1)}…` : line;\n // Drop the sentence-case capital (\"Listing\" → \"listing\") but leave acronyms\n // and identifiers (\"PR lookup\", \"CI status\") alone.\n return `is ${/^[A-Z][a-z]/.test(text) ? text.charAt(0).toLowerCase() + text.slice(1) : text}`;\n}\n\n/**\n * With reply text hidden, streamed text never reaches the thread, so it gets\n * no status: an \"is typing...\" set after the reply tool's post would sit on\n * the thread with nothing coming, and race the clear at the end of the run.\n */\nconst factoryTypingStatus =\n (textDisplay: SlackAdapterChannelConfig['textDisplay']): TypingStatusFn =>\n chunk => {\n switch (chunk.type) {\n case 'reasoning-delta':\n return 'is thinking...';\n case 'text-delta':\n return textDisplay === 'hidden' ? undefined : 'is typing...';\n // The reply tool's text streams into the thread as the model writes it.\n case 'tool-call-input-streaming-start':\n return chunk.payload.toolName === REPLY_TOOL_NAME ? 'is typing...' : undefined;\n case 'tool-call':\n // Still finishing the streamed reply; don't flip to \"is working...\".\n if (chunk.payload.toolName === REPLY_TOOL_NAME) return 'is typing...';\n return describeToolCall(chunk.payload.args) ?? 'is working...';\n default:\n return undefined;\n }\n};\n\n/**\n * Drops keys the caller set to `undefined` so spreading the overrides cannot\n * erase the Factory defaults they sit on top of.\n */\nfunction adapterOverrides(options: SlackAdapterChannelConfig | undefined): SlackAdapterChannelConfig {\n return Object.fromEntries(\n Object.entries(options ?? {}).filter(([, value]) => value !== undefined),\n ) as SlackAdapterChannelConfig;\n}\n\n/**\n * Factory defaults under the caller's overrides. Tool calls stay out of the\n * thread: a Factory session runs hundreds of them, and a row per call (or a\n * card per call) buries the reply. Progress shows through the typing status\n * instead, which names the tool's current step; the session link carries the\n * full trace. `grouped` remains available via `adapterOptions` for callers\n * who want Slack's \"Thinking Steps\" widget.\n */\nfunction factoryAdapterOptions(overrides: SlackAdapterChannelConfig): SlackAdapterChannelConfig {\n const textDisplay = overrides.textDisplay ?? 'hidden';\n return { typingStatus: factoryTypingStatus(textDisplay), toolDisplay: 'hidden', textDisplay, ...overrides };\n}\n\nexport class SlackIntegration implements FactoryIntegration {\n readonly id = 'slack';\n /**\n * The OIDC connect flow round-trips a signed `state` through Slack, so the\n * replica handling the callback must be able to verify a state a different\n * replica signed.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #config: SlackIntegrationConfig;\n readonly #toolSettings: SlackToolSettings;\n readonly #adapterOptions: SlackAdapterChannelConfig;\n /** Bound in `initialize()`; the controller mounts after integrations are built. */\n #channels: ShareFileToolDeps['channels'];\n readonly #deps: ShareFileToolDeps = { channels: () => this.#channels?.() };\n /**\n * With reply text hidden (the Factory default) the agent speaks through\n * `reply_in_thread`, so the prompt, reminder and live streaming for that\n * tool come with it. The setting is fixed for the deployment, so it is\n * decided once here rather than on every run.\n */\n readonly processors: { input: InputProcessor[]; output: OutputProcessor[] };\n /**\n * Whether `channels()` found a source-control owner on the context and wired\n * repo-backed sessions. Set at the channels() attach path, which runs once at\n * boot before diagnostics are served.\n */\n #repoBackedSessions = false;\n\n constructor(config: SlackIntegrationConfig) {\n const mode = config.mode ?? 'webhook';\n if (mode === 'webhook' && !config.signingSecret) {\n throw new Error(\n \"SlackIntegration: 'signingSecret' is required in webhook mode — Slack cannot verify inbound requests without it.\",\n );\n }\n if (mode === 'socket' && !config.appToken) {\n throw new Error(\"SlackIntegration: 'appToken' is required in socket mode — Slack cannot open a Socket Mode connection without it.\");\n }\n if (mode === 'socket' && !config.botToken) {\n throw new Error(\"SlackIntegration: 'botToken' is required in socket mode — Factory cannot reply without it.\");\n }\n this.#config = config;\n // An explicit `undefined` means \"use the default\", not \"unset it\".\n const granted = Object.fromEntries(Object.entries(config.tools ?? {}).filter(([, value]) => value !== undefined));\n this.#toolSettings = slackToolSettingsSchema.parse({ ...DEFAULT_SLACK_TOOL_SETTINGS, ...granted });\n this.#adapterOptions = factoryAdapterOptions(adapterOverrides(config.adapterOptions));\n const textHidden = this.#textHidden;\n this.processors = {\n input: [\n new FactoryChannelReplyProcessor(),\n ...(textHidden ? [new FactoryReplyReminderProcessor()] : []),\n ],\n output: [\n new FactoryChannelSessionLinkProcessor(),\n ...(textHidden ? [new FactoryReplyStreamProcessor(this.#deps)] : []),\n ],\n };\n }\n\n get #textHidden(): boolean {\n return this.#adapterOptions.textDisplay === 'hidden';\n }\n\n initialize(args: { channels?: () => AgentChannels | null | undefined }): void {\n this.#channels = args.channels;\n }\n\n /**\n * On runs whose session is linked to a Slack thread: `attach_file`,\n * `reply_in_thread` when reply text is hidden, and the Slack read, post,\n * search, lookup and DM tools. The tools find the thread to post into when\n * they are called.\n */\n async agentTools({ requestContext }: { requestContext: RequestContext }): Promise<IntegrationTools> {\n const slackThread = await slackThreadOf(requestContext, this.#deps);\n if (!slackThread) return {};\n const chat = this.#channels?.()?.sdk;\n const sessionThreadId = slackThread.threadId;\n return {\n ...createShareFileTool(requestContext, this.#deps),\n ...(this.#textHidden ? createReplyTool(requestContext, this.#deps) : {}),\n ...(chat && sessionThreadId ? createSlackChatTools({ chat, sessionThreadId, settings: this.#toolSettings }) : {}),\n };\n }\n\n /**\n * When a run opens a pull request, post its link into the session's Slack\n * thread.\n */\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const url = parseCreatedPullRequest(toolContext);\n const threadId = (requestContext?.get('controller') as { threadId?: string } | undefined)?.threadId;\n if (!url || !requestContext || !threadId || !(await isSlackThread(requestContext, this.#deps))) return;\n // Not awaited: the tool call must not wait on Slack.\n void announcePullRequest(this.#channels?.(), threadId, 'opened', url).catch(error =>\n console.warn('[slack] pull request opened announcement failed', error),\n );\n }\n\n channels(ctx: IntegrationContext): FactoryChannelsConfig {\n // Repo-backed sessions select the source-control provider from the linked\n // repository on each Factory project.\n const sourceControls =\n ctx.storage.sourceControls ?? (ctx.storage.sourceControlOwner ? [ctx.storage.sourceControlOwner] : []);\n this.#repoBackedSessions = sourceControls.length > 0;\n const mode = this.#config.mode ?? 'webhook';\n return createSlackChannelsConfig({\n slack: {\n mode: this.#config.mode,\n ...(mode === 'webhook'\n ? { clientId: this.#config.clientId, clientSecret: this.#config.clientSecret }\n : {}),\n signingSecret: this.#config.signingSecret,\n appToken: this.#config.appToken,\n botToken: this.#config.botToken,\n },\n accountLinks: ctx.storage.channelIdentity,\n projects: ctx.storage.projects,\n sourceControls,\n modelDefaults: ctx.storage.modelDefaults,\n workItems: ctx.runtime?.workItems,\n feed: ctx.feed,\n adapterOptions: this.#adapterOptions,\n });\n }\n\n feedPublisher(ctx: IntegrationContext): WorkItemFeedPublisher {\n return new SlackFeedPublisher({ controller: ctx.controller });\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n const { clientId, clientSecret, oidcRedirectBaseUrl, uiOrigin } = this.#config;\n return createSlackConnectRoutes({\n auth: ctx.auth,\n accountLinks: ctx.storage.channelIdentity,\n tenantStateSigner: ctx.stateSigner,\n oidc:\n clientId && clientSecret && oidcRedirectBaseUrl\n ? { clientId, clientSecret, redirectBaseUrl: oidcRedirectBaseUrl, uiOrigin }\n : undefined,\n projects: ctx.storage.projects,\n });\n }\n\n diagnostics(): Record<string, unknown> {\n const { clientId, clientSecret, botToken, oidcRedirectBaseUrl } = this.#config;\n return {\n configured: true,\n botTokenConfigured: Boolean(botToken),\n oidcConfigured: Boolean(clientId && clientSecret && oidcRedirectBaseUrl),\n repoBackedSessions: this.#repoBackedSessions,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAoGA,MAAM,oBAAoB;;;;;;AAO1B,SAAS,iBAAiB,MAAmC;CAC3D,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAA;CAC9C,MAAM,EAAE,gBAAgB;CACxB,IAAI,OAAO,gBAAgB,UAAU,OAAO,KAAA;CAC5C,MAAM,OAAO,YACV,MAAM,IAAI,CAAC,CACX,KAAI,SAAQ,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAC7C,KAAK,OAAO;CACf,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,MAAM,OAAO,KAAK,SAAS,oBAAoB,GAAG,KAAK,MAAM,GAAG,EAAqB,EAAE,KAAK;CAG5F,OAAO,MAAM,cAAc,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC,IAAI;AACzF;;;;;;AAOA,MAAM,uBACH,iBACD,UAAS;CACT,QAAQ,MAAM,MAAd;EACE,KAAK,mBACH,OAAO;EACT,KAAK,cACH,OAAO,gBAAgB,WAAW,KAAA,IAAY;EAEhD,KAAK,mCACH,OAAO,MAAM,QAAQ,aAAA,oBA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BAA0B;GAC/B,OAAO;IACL,MAAM,KAAK,QAAQ;IACnB,GAAI,SAAS,YACT;KAAE,UAAU,KAAK,QAAQ;KAAU,cAAc,KAAK,QAAQ;IAAa,IAC3E,CAAC;IACL,eAAe,KAAK,QAAQ;IAC5B,UAAU,KAAK,QAAQ;IACvB,UAAU,KAAK,QAAQ;GACzB;GACA,cAAc,IAAI,QAAQ;GAC1B,UAAU,IAAI,QAAQ;GACtB;GACA,eAAe,IAAI,QAAQ;GAC3B,WAAW,IAAI,SAAS;GACxB,MAAM,IAAI;GACV,gBAAgB,KAAK;EACvB,CAAC;CACH;CAEA,cAAc,KAAgD;EAC5D,OAAO,IAAI,mBAAmB,EAAE,YAAY,IAAI,WAAW,CAAC;CAC9D;CAEA,OAAO,KAAqC;EAC1C,MAAM,EAAE,UAAU,cAAc,qBAAqB,aAAa,KAAK;EACvE,OAAO,yBAAyB;GAC9B,MAAM,IAAI;GACV,cAAc,IAAI,QAAQ;GAC1B,mBAAmB,IAAI;GACvB,MACE,YAAY,gBAAgB,sBACxB;IAAE;IAAU;IAAc,iBAAiB;IAAqB;GAAS,IACzE,KAAA;GACN,UAAU,IAAI,QAAQ;EACxB,CAAC;CACH;CAEA,cAAuC;EACrC,MAAM,EAAE,UAAU,cAAc,UAAU,wBAAwB,KAAK;EACvE,OAAO;GACL,YAAY;GACZ,oBAAoB,QAAQ,QAAQ;GACpC,gBAAgB,QAAQ,YAAY,gBAAgB,mBAAmB;GACvE,oBAAoB,KAAK;EAC3B;CACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFactorySessionScope } from "../../rules/binding-context.js";
|
|
2
|
-
import { runCredential } from "../../session/reply-credential-processor.js";
|
|
3
2
|
import { describeRunError } from "../../run-error.js";
|
|
3
|
+
import { runCredential } from "../../session/reply-credential-processor.js";
|
|
4
4
|
import { modelSettingsLink } from "./channel-reply-processor.js";
|
|
5
5
|
import { sessionLinkFromRequest } from "./channel-session-link-processor.js";
|
|
6
6
|
import { providerRequestId } from "@mastra/core/error";
|
|
@@ -31,6 +31,14 @@ export declare function resolveRenderContext(requestContext: RequestContext, dep
|
|
|
31
31
|
* Plain web sessions get `false` and no channel tools.
|
|
32
32
|
*/
|
|
33
33
|
export declare function isSlackThread(requestContext: RequestContext, deps: ShareFileToolDeps): Promise<boolean>;
|
|
34
|
+
/**
|
|
35
|
+
* The run's Slack thread, with its chat thread id (`slack:C…:ts`) when known,
|
|
36
|
+
* or null when the run isn't on a Slack thread. Same cost as
|
|
37
|
+
* {@link isSlackThread}.
|
|
38
|
+
*/
|
|
39
|
+
export declare function slackThreadOf(requestContext: RequestContext, deps: ShareFileToolDeps): Promise<{
|
|
40
|
+
threadId?: string;
|
|
41
|
+
} | null>;
|
|
34
42
|
/** The thread a channel tool posts into, resolved when the tool runs. */
|
|
35
43
|
export declare function postTarget(requestContext: RequestContext, deps: ShareFileToolDeps): Promise<ChatChannelRenderContext>;
|
|
36
44
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"share-file-tool.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/share-file-tool.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,wFAAwF;AACxF,eAAO,MAAM,oBAAoB,QAAmB,CAAC;AAErD,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,aAAa,GAAG,IAAI,GAAG,SAAS,CAAC;CACnD;AAmBD;;;;;;;;;;;GAWG;AACH,wBAAsB,oBAAoB,CACxC,cAAc,EAAE,cAAc,EAC9B,IAAI,EAAE,iBAAiB,GACtB,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAO/C;AAED;;;;;GAK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ClH"}
|
|
@@ -44,11 +44,20 @@ async function resolveRenderContext(requestContext, deps) {
|
|
|
44
44
|
* Plain web sessions get `false` and no channel tools.
|
|
45
45
|
*/
|
|
46
46
|
async function isSlackThread(requestContext, deps) {
|
|
47
|
+
return await slackThreadOf(requestContext, deps) !== null;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The run's Slack thread, with its chat thread id (`slack:C…:ts`) when known,
|
|
51
|
+
* or null when the run isn't on a Slack thread. Same cost as
|
|
52
|
+
* {@link isSlackThread}.
|
|
53
|
+
*/
|
|
54
|
+
async function slackThreadOf(requestContext, deps) {
|
|
47
55
|
const channel = requestContext.get("channel");
|
|
48
|
-
if (channel) return channel.platform === "slack";
|
|
56
|
+
if (channel) return channel.platform === "slack" ? { threadId: channel.threadId } : null;
|
|
49
57
|
const threadId = requestContext.get("controller")?.threadId;
|
|
50
|
-
if (!threadId) return
|
|
51
|
-
|
|
58
|
+
if (!threadId) return null;
|
|
59
|
+
const linked = await deps.channels?.()?.buildChannelContextForThread(threadId);
|
|
60
|
+
return linked?.channel.platform === "slack" ? { threadId: linked.render.chatThread.id } : null;
|
|
52
61
|
}
|
|
53
62
|
/** The thread a channel tool posts into, resolved when the tool runs. */
|
|
54
63
|
async function postTarget(requestContext, deps) {
|
|
@@ -100,6 +109,6 @@ function createShareFileTool(requestContext, deps = {}) {
|
|
|
100
109
|
}
|
|
101
110
|
}) };
|
|
102
111
|
}
|
|
103
|
-
export { SHARE_FILE_MAX_BYTES, createShareFileTool, isSlackThread, postTarget, resolveRenderContext };
|
|
112
|
+
export { SHARE_FILE_MAX_BYTES, createShareFileTool, isSlackThread, postTarget, resolveRenderContext, slackThreadOf };
|
|
104
113
|
|
|
105
114
|
//# sourceMappingURL=share-file-tool.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"share-file-tool.js","names":[],"sources":["../../../src/integrations/slack/share-file-tool.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { CHAT_CHANNEL_RENDER_CONTEXT_KEY } from '@mastra/core/channels';\nimport type { AgentChannels, ChatChannelRenderContext } from '@mastra/core/channels';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../base.js';\n\n/** Slack rejects larger uploads well before this; keep the sandbox read bounded too. */\nexport const SHARE_FILE_MAX_BYTES = 50 * 1024 * 1024;\n\nexport interface ShareFileToolDeps {\n /**\n * The channels attached to the controller, used to rebuild the chat thread\n * for runs that did not start from a platform message. Omit when the caller\n * has no controller; the tool is then offered only on inbound-webhook runs.\n */\n channels?: () => AgentChannels | null | undefined;\n}\n\n/**\n * Uploads need a scope (`files:write` on Slack) that an app created before\n * this tool existed will not have. `@slack/web-api` reports that as a\n * platform error with `data.error === 'missing_scope'` and the scope in\n * `data.needed`; say so plainly instead of surfacing the raw API error, so\n * the model tells the user what to fix rather than retrying.\n */\nfunction missingScopeError(error: unknown, platform: string): Error | undefined {\n if (!error || typeof error !== 'object') return undefined;\n const data = (error as { data?: { error?: unknown; needed?: unknown } }).data;\n if (data?.error !== 'missing_scope') return undefined;\n const needed = typeof data.needed === 'string' && data.needed ? data.needed : 'files:write';\n return new Error(\n `The ${platform} app is missing the \\`${needed}\\` scope, so it cannot upload files. Add the scope to the app and reinstall it, then try again.`,\n );\n}\n\n/**\n * The chat thread this run replies into, if any.\n *\n * Inbound platform messages stash the render context on `requestContext`.\n * A run woken by a signal (a subagent finishing, a scheduled fire) has no\n * such entry even though its thread is still channel-backed — and that is\n * exactly the run that ends a long job with a file to hand back. Rebuild the\n * context from the thread's persisted channel coordinates the same way\n * `ChatChannelOutputProcessor` does, so the tools post on both kinds of run.\n * A forked subagent's thread carries no channel metadata, so forks get\n * nothing here and never post to the platform.\n */\nexport async function resolveRenderContext(\n requestContext: RequestContext,\n deps: ShareFileToolDeps,\n): Promise<ChatChannelRenderContext | undefined> {\n const stashed = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY) as ChatChannelRenderContext | undefined;\n if (stashed) return stashed;\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const threadId = controller?.threadId;\n if (!threadId) return undefined;\n return (await deps.channels?.()?.buildRenderContextForThread(threadId)) ?? undefined;\n}\n\n/**\n * Whether this run's thread is a Slack thread, so the channel tools have\n * somewhere to post. A run started from Slack says so on `requestContext`; a\n * web prompt or a woken run on a Slack-linked session costs one thread read.\n * Plain web sessions get `false` and no channel tools.\n */\nexport async function isSlackThread(requestContext: RequestContext, deps: ShareFileToolDeps): Promise<boolean> {\n const channel = requestContext.get('channel') as { platform?: string } | undefined;\n if (channel) return channel.platform === 'slack';\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const threadId = controller?.threadId;\n if (!threadId) return false;\n const linked = await deps.channels?.()?.buildChannelContextForThread(threadId);\n return linked?.channel.platform === 'slack';\n}\n\n/** The thread a channel tool posts into, resolved when the tool runs. */\nexport async function postTarget(\n requestContext: RequestContext,\n deps: ShareFileToolDeps,\n): Promise<ChatChannelRenderContext> {\n const render = await resolveRenderContext(requestContext, deps);\n if (!render) throw new Error('This session is no longer linked to a chat thread.');\n return render;\n}\n\n/**\n * Lets a channel-triggered run hand a workspace file back to the thread it\n * came from. The agent's reply stream can only carry text, so a report it\n * generated in the sandbox would otherwise be described by path and left\n * there. Offered only on runs whose thread is linked to a chat thread (see\n * `isSlackThread`); the file is read through the session's workspace\n * filesystem so sandbox confinement still applies.\n */\nexport function createShareFileTool(requestContext: RequestContext, deps: ShareFileToolDeps = {}): IntegrationTools {\n return {\n attach_file: createTool({\n id: 'attach_file',\n description:\n 'Upload a file from the workspace into this chat thread as an attachment. This is the only way the person you are talking to can receive a file you produced (a report, PDF, export, screenshot, image); they cannot open workspace paths. Call it whenever you have a file to hand over, then describe it briefly in your reply. The attachment posts on its own.',\n inputSchema: z.object({\n path: z.string().min(1).describe('Absolute path of the file inside the workspace'),\n }),\n execute: async ({ path }, context) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const workspace = controller?.workspace ?? context?.workspace;\n const fs = workspace?.filesystem;\n if (!fs) throw new Error('No workspace filesystem is attached to this session.');\n const stat = await fs.stat(path);\n if (stat.type === 'directory') throw new Error(`${path} is a directory; attach a single file.`);\n // The stat check keeps us from reading something enormous; the check on\n // the bytes we actually hold is the one that bounds the upload, since the\n // file can change between the two calls.\n if (stat.size > SHARE_FILE_MAX_BYTES) {\n throw new Error(`${path} is ${stat.size} bytes; the limit is ${SHARE_FILE_MAX_BYTES} bytes.`);\n }\n const raw = await fs.readFile(path);\n const data = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);\n if (data.length > SHARE_FILE_MAX_BYTES) {\n throw new Error(`${path} is ${data.length} bytes; the limit is ${SHARE_FILE_MAX_BYTES} bytes.`);\n }\n const filename = path.split('/').pop() || 'file';\n const render = await postTarget(requestContext, deps);\n // File only. The Slack adapter posts any non-empty text as a second\n // message after the upload, so a comment would land as its own bubble\n // between the reply and the file; an empty body returns after the upload.\n try {\n await render.chatThread.post({\n markdown: '',\n files: [{ data, filename, ...(stat.mimeType ? { mimeType: stat.mimeType } : {}) }],\n });\n } catch (error) {\n throw missingScopeError(error, render.platform) ?? error;\n }\n return { attached: true, filename, bytes: data.length };\n },\n }),\n };\n}\n"],"mappings":";;;;;AAUA,MAAa,uBAAuB;;;;;;;;AAkBpC,SAAS,kBAAkB,OAAgB,UAAqC;CAC9E,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO,KAAA;CAChD,MAAM,OAAQ,MAA2D;CACzE,IAAI,MAAM,UAAU,iBAAiB,OAAO,KAAA;CAC5C,MAAM,SAAS,OAAO,KAAK,WAAW,YAAY,KAAK,SAAS,KAAK,SAAS;CAC9E,uBAAO,IAAI,MACT,OAAO,SAAS,wBAAwB,OAAO,gGACjD;AACF;;;;;;;;;;;;;AAcA,eAAsB,qBACpB,gBACA,MAC+C;CAC/C,MAAM,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qBAAqB,QAAQ;GAE9F,MAAM,MAAM,MAAM,GAAG,SAAS,IAAI;GAClC,MAAM,OAAO,OAAO,SAAS,GAAG,IAAI,MAAM,OAAO,KAAK,GAAG;GACzD,IAAI,KAAK,SAAA,UACP,MAAM,IAAI,MAAM,GAAG,KAAK,MAAM,KAAK,OAAO,uBAAuB,qBAAqB,QAAQ;GAEhG,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;GAC1C,MAAM,SAAS,MAAM,WAAW,gBAAgB,IAAI;GAIpD,IAAI;IACF,MAAM,OAAO,WAAW,KAAK;KAC3B,UAAU;KACV,OAAO,CAAC;MAAE;MAAM;MAAU,GAAI,KAAK,WAAW,EAAE,UAAU,KAAK,SAAS,IAAI,CAAC;KAAG,CAAC;IACnF,CAAC;GACH,SAAS,OAAO;IACd,MAAM,kBAAkB,OAAO,OAAO,QAAQ,KAAK;GACrD;GACA,OAAO;IAAE,UAAU;IAAM;IAAU,OAAO,KAAK;GAAO;EACxD;CACF,CAAC,EACH;AACF"}
|
|
1
|
+
{"version":3,"file":"share-file-tool.js","names":[],"sources":["../../../src/integrations/slack/share-file-tool.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { CHAT_CHANNEL_RENDER_CONTEXT_KEY } from '@mastra/core/channels';\nimport type { AgentChannels, ChatChannelRenderContext } from '@mastra/core/channels';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../base.js';\n\n/** Slack rejects larger uploads well before this; keep the sandbox read bounded too. */\nexport const SHARE_FILE_MAX_BYTES = 50 * 1024 * 1024;\n\nexport interface ShareFileToolDeps {\n /**\n * The channels attached to the controller, used to rebuild the chat thread\n * for runs that did not start from a platform message. Omit when the caller\n * has no controller; the tool is then offered only on inbound-webhook runs.\n */\n channels?: () => AgentChannels | null | undefined;\n}\n\n/**\n * Uploads need a scope (`files:write` on Slack) that an app created before\n * this tool existed will not have. `@slack/web-api` reports that as a\n * platform error with `data.error === 'missing_scope'` and the scope in\n * `data.needed`; say so plainly instead of surfacing the raw API error, so\n * the model tells the user what to fix rather than retrying.\n */\nfunction missingScopeError(error: unknown, platform: string): Error | undefined {\n if (!error || typeof error !== 'object') return undefined;\n const data = (error as { data?: { error?: unknown; needed?: unknown } }).data;\n if (data?.error !== 'missing_scope') return undefined;\n const needed = typeof data.needed === 'string' && data.needed ? data.needed : 'files:write';\n return new Error(\n `The ${platform} app is missing the \\`${needed}\\` scope, so it cannot upload files. Add the scope to the app and reinstall it, then try again.`,\n );\n}\n\n/**\n * The chat thread this run replies into, if any.\n *\n * Inbound platform messages stash the render context on `requestContext`.\n * A run woken by a signal (a subagent finishing, a scheduled fire) has no\n * such entry even though its thread is still channel-backed — and that is\n * exactly the run that ends a long job with a file to hand back. Rebuild the\n * context from the thread's persisted channel coordinates the same way\n * `ChatChannelOutputProcessor` does, so the tools post on both kinds of run.\n * A forked subagent's thread carries no channel metadata, so forks get\n * nothing here and never post to the platform.\n */\nexport async function resolveRenderContext(\n requestContext: RequestContext,\n deps: ShareFileToolDeps,\n): Promise<ChatChannelRenderContext | undefined> {\n const stashed = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY) as ChatChannelRenderContext | undefined;\n if (stashed) return stashed;\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const threadId = controller?.threadId;\n if (!threadId) return undefined;\n return (await deps.channels?.()?.buildRenderContextForThread(threadId)) ?? undefined;\n}\n\n/**\n * Whether this run's thread is a Slack thread, so the channel tools have\n * somewhere to post. A run started from Slack says so on `requestContext`; a\n * web prompt or a woken run on a Slack-linked session costs one thread read.\n * Plain web sessions get `false` and no channel tools.\n */\nexport async function isSlackThread(requestContext: RequestContext, deps: ShareFileToolDeps): Promise<boolean> {\n return (await slackThreadOf(requestContext, deps)) !== null;\n}\n\n/**\n * The run's Slack thread, with its chat thread id (`slack:C…:ts`) when known,\n * or null when the run isn't on a Slack thread. Same cost as\n * {@link isSlackThread}.\n */\nexport async function slackThreadOf(\n requestContext: RequestContext,\n deps: ShareFileToolDeps,\n): Promise<{ threadId?: string } | null> {\n const channel = requestContext.get('channel') as { platform?: string; threadId?: string } | undefined;\n if (channel) return channel.platform === 'slack' ? { threadId: channel.threadId } : null;\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const threadId = controller?.threadId;\n if (!threadId) return null;\n const linked = await deps.channels?.()?.buildChannelContextForThread(threadId);\n return linked?.channel.platform === 'slack' ? { threadId: linked.render.chatThread.id } : null;\n}\n\n/** The thread a channel tool posts into, resolved when the tool runs. */\nexport async function postTarget(\n requestContext: RequestContext,\n deps: ShareFileToolDeps,\n): Promise<ChatChannelRenderContext> {\n const render = await resolveRenderContext(requestContext, deps);\n if (!render) throw new Error('This session is no longer linked to a chat thread.');\n return render;\n}\n\n/**\n * Lets a channel-triggered run hand a workspace file back to the thread it\n * came from. The agent's reply stream can only carry text, so a report it\n * generated in the sandbox would otherwise be described by path and left\n * there. Offered only on runs whose thread is linked to a chat thread (see\n * `isSlackThread`); the file is read through the session's workspace\n * filesystem so sandbox confinement still applies.\n */\nexport function createShareFileTool(requestContext: RequestContext, deps: ShareFileToolDeps = {}): IntegrationTools {\n return {\n attach_file: createTool({\n id: 'attach_file',\n description:\n 'Upload a file from the workspace into this chat thread as an attachment. This is the only way the person you are talking to can receive a file you produced (a report, PDF, export, screenshot, image); they cannot open workspace paths. Call it whenever you have a file to hand over, then describe it briefly in your reply. The attachment posts on its own.',\n inputSchema: z.object({\n path: z.string().min(1).describe('Absolute path of the file inside the workspace'),\n }),\n execute: async ({ path }, context) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const workspace = controller?.workspace ?? context?.workspace;\n const fs = workspace?.filesystem;\n if (!fs) throw new Error('No workspace filesystem is attached to this session.');\n const stat = await fs.stat(path);\n if (stat.type === 'directory') throw new Error(`${path} is a directory; attach a single file.`);\n // The stat check keeps us from reading something enormous; the check on\n // the bytes we actually hold is the one that bounds the upload, since the\n // file can change between the two calls.\n if (stat.size > SHARE_FILE_MAX_BYTES) {\n throw new Error(`${path} is ${stat.size} bytes; the limit is ${SHARE_FILE_MAX_BYTES} bytes.`);\n }\n const raw = await fs.readFile(path);\n const data = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);\n if (data.length > SHARE_FILE_MAX_BYTES) {\n throw new Error(`${path} is ${data.length} bytes; the limit is ${SHARE_FILE_MAX_BYTES} bytes.`);\n }\n const filename = path.split('/').pop() || 'file';\n const render = await postTarget(requestContext, deps);\n // File only. The Slack adapter posts any non-empty text as a second\n // message after the upload, so a comment would land as its own bubble\n // between the reply and the file; an empty body returns after the upload.\n try {\n await render.chatThread.post({\n markdown: '',\n files: [{ data, filename, ...(stat.mimeType ? { mimeType: stat.mimeType } : {}) }],\n });\n } catch (error) {\n throw missingScopeError(error, render.platform) ?? error;\n }\n return { attached: true, filename, bytes: data.length };\n },\n }),\n };\n}\n"],"mappings":";;;;;AAUA,MAAa,uBAAuB;;;;;;;;AAkBpC,SAAS,kBAAkB,OAAgB,UAAqC;CAC9E,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO,KAAA;CAChD,MAAM,OAAQ,MAA2D;CACzE,IAAI,MAAM,UAAU,iBAAiB,OAAO,KAAA;CAC5C,MAAM,SAAS,OAAO,KAAK,WAAW,YAAY,KAAK,SAAS,KAAK,SAAS;CAC9E,uBAAO,IAAI,MACT,OAAO,SAAS,wBAAwB,OAAO,gGACjD;AACF;;;;;;;;;;;;;AAcA,eAAsB,qBACpB,gBACA,MAC+C;CAC/C,MAAM,UAAU,eAAe,IAAI,+BAA+B;CAClE,IAAI,SAAS,OAAO;CAEpB,MAAM,WADa,eAAe,IAAI,YACZ,CAAC,EAAE;CAC7B,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,OAAQ,MAAM,KAAK,WAAW,CAAC,EAAE,4BAA4B,QAAQ,KAAM,KAAA;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E9F,MAAM,MAAM,MAAM,GAAG,SAAS,IAAI;GAClC,MAAM,OAAO,OAAO,SAAS,GAAG,IAAI,MAAM,OAAO,KAAK,GAAG;GACzD,IAAI,KAAK,SAAA,UACP,MAAM,IAAI,MAAM,GAAG,KAAK,MAAM,KAAK,OAAO,uBAAuB,qBAAqB,QAAQ;GAEhG,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;GAC1C,MAAM,SAAS,MAAM,WAAW,gBAAgB,IAAI;GAIpD,IAAI;IACF,MAAM,OAAO,WAAW,KAAK;KAC3B,UAAU;KACV,OAAO,CAAC;MAAE;MAAM;MAAU,GAAI,KAAK,WAAW,EAAE,UAAU,KAAK,SAAS,IAAI,CAAC;KAAG,CAAC;IACnF,CAAC;GACH,SAAS,OAAO;IACd,MAAM,kBAAkB,OAAO,OAAO,QAAQ,KAAK;GACrD;GACA,OAAO;IAAE,UAAU;IAAM;IAAU,OAAO,KAAK;GAAO;EACxD;CACF,CAAC,EACH;AACF"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { actorFromChannelAuthor } from "../../storage/domains/comments/actor.js";
|
|
2
1
|
import { FACTORY_INTERACTIVE_KEY } from "../../auth.js";
|
|
3
2
|
import { primeTenantCredentialsForRequestContext, primeTenantCredentialsForTenant } from "../../routes/tenant-credentials.js";
|
|
4
|
-
import { readRequestContextOrgId, seedSessionOrg } from "../../session/org-seed.js";
|
|
5
|
-
import { prepareSessionRunContext } from "../subscription-session.js";
|
|
6
3
|
import { FactorySourceControlConflictError, createSourceControlSessionLookup, hydrateFactorySession, resolveFactorySessionModel, resolveFactorySourceControl, resolvePrimaryEnvironmentRepository } from "../../session/factory-session.js";
|
|
4
|
+
import { readRequestContextOrgId, seedSessionOrg } from "../../session/org-seed.js";
|
|
7
5
|
import { isRunBound, memoryResourceOf, sessionStampCounts } from "../../session/session-threads.js";
|
|
6
|
+
import { actorFromChannelAuthor } from "../../storage/domains/comments/actor.js";
|
|
8
7
|
import { FACTORY_SLACK_SENDER_KEY } from "../../tools/scope.js";
|
|
8
|
+
import { prepareSessionRunContext } from "../subscription-session.js";
|
|
9
9
|
import { markNewChannelSession } from "./channel-session-link-processor.js";
|
|
10
10
|
import { resolveEmojiShortcodes } from "./emoji.js";
|
|
11
11
|
import { slackCommentSource } from "./feed-publisher.js";
|