@letta-ai/letta-code 0.34.72 → 0.34.73-app-server.1
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/dist/mcp-client.js +2 -2
- package/dist/mcp-client.js.map +1 -1
- package/dist/mcp-oauth.js +2 -2
- package/dist/mcp-oauth.js.map +1 -1
- package/dist/schedules.js +19 -5
- package/dist/schedules.js.map +5 -4
- package/dist/types/agent/message.d.ts.map +1 -1
- package/dist/types/agent/modify.d.ts.map +1 -1
- package/dist/types/agent/preloaded-skills.d.ts +4 -1
- package/dist/types/agent/preloaded-skills.d.ts.map +1 -1
- package/dist/types/agent/shared-memory-skills.d.ts.map +1 -1
- package/dist/types/agent/subagents/parent-transcript.d.ts.map +1 -1
- package/dist/types/backend/api/agents.d.ts +1 -0
- package/dist/types/backend/api/agents.d.ts.map +1 -1
- package/dist/types/cli/helpers/conversation-title.d.ts.map +1 -1
- package/dist/types/constants.d.ts +5 -0
- package/dist/types/constants.d.ts.map +1 -1
- package/dist/types/cron/scheduled-task-prompt.d.ts +2 -0
- package/dist/types/cron/scheduled-task-prompt.d.ts.map +1 -1
- package/dist/types/experiments/manager.d.ts.map +1 -1
- package/dist/types/experiments/types.d.ts +2 -1
- package/dist/types/experiments/types.d.ts.map +1 -1
- package/dist/types/headless-super-run-wait.d.ts.map +1 -1
- package/dist/types/helpers/usable-directory.d.ts +2 -2
- package/dist/types/helpers/usable-directory.d.ts.map +1 -1
- package/dist/types/helpers/working-directory.d.ts +1 -0
- package/dist/types/helpers/working-directory.d.ts.map +1 -1
- package/dist/types/mods/context.d.ts +1 -0
- package/dist/types/mods/context.d.ts.map +1 -1
- package/dist/types/permissions/loader.d.ts.map +1 -1
- package/dist/types/queue/turn-queue-runtime.d.ts +0 -4
- package/dist/types/queue/turn-queue-runtime.d.ts.map +1 -1
- package/dist/types/telemetry/index.d.ts +1 -22
- package/dist/types/telemetry/index.d.ts.map +1 -1
- package/dist/types/tools/external-tool-background.d.ts.map +1 -1
- package/dist/types/tools/impl/foreground-sleep.d.ts.map +1 -1
- package/dist/types/tools/impl/kill-bash.d.ts +1 -1
- package/dist/types/tools/impl/kill-bash.d.ts.map +1 -1
- package/dist/types/tools/impl/monitor-script.d.ts +1 -0
- package/dist/types/tools/impl/monitor-script.d.ts.map +1 -1
- package/dist/types/tools/impl/monitor.d.ts +1 -0
- package/dist/types/tools/impl/monitor.d.ts.map +1 -1
- package/dist/types/tools/impl/skill.d.ts.map +1 -1
- package/dist/types/tools/impl/watch-pr-cloud.d.ts +1 -0
- package/dist/types/tools/impl/watch-pr-cloud.d.ts.map +1 -1
- package/dist/types/tools/impl/watch-pr.d.ts +1 -0
- package/dist/types/tools/impl/watch-pr.d.ts.map +1 -1
- package/dist/types/tools/manager.d.ts +3 -5
- package/dist/types/tools/manager.d.ts.map +1 -1
- package/dist/types/tools/script-tool-scope.d.ts.map +1 -1
- package/dist/types/tools/workflow/sdk-spawner.d.ts.map +1 -1
- package/dist/types/types/agent-picker.d.ts +55 -0
- package/dist/types/types/agent-picker.d.ts.map +1 -0
- package/dist/types/types/background-process-protocol.d.ts +4 -0
- package/dist/types/types/background-process-protocol.d.ts.map +1 -1
- package/dist/types/types/list-memory-command.d.ts +9 -0
- package/dist/types/types/list-memory-command.d.ts.map +1 -0
- package/dist/types/types/protocol_v2.d.ts +8 -24
- package/dist/types/types/protocol_v2.d.ts.map +1 -1
- package/dist/types/utils/task-notifications.d.ts +2 -0
- package/dist/types/utils/task-notifications.d.ts.map +1 -1
- package/dist/types/websocket/listener/background-process-snapshot.d.ts +1 -0
- package/dist/types/websocket/listener/background-process-snapshot.d.ts.map +1 -1
- package/dist/types/websocket/listener/cwd.d.ts.map +1 -1
- package/dist/types/websocket/listener/listener-constants.d.ts.map +1 -1
- package/dist/types/websocket/listener/protocol-outbound.d.ts +0 -1
- package/dist/types/websocket/listener/protocol-outbound.d.ts.map +1 -1
- package/dist/types/websocket/listener/types.d.ts +1 -0
- package/dist/types/websocket/listener/types.d.ts.map +1 -1
- package/letta.js +241422 -234880
- package/npm-shrinkwrap.json +52 -11
- package/package.json +2 -35
- package/scripts/isolated-unit-tests.json +0 -5
- package/scripts/source-file-size-baseline.json +9 -16
- package/scripts/unit-test-impact.test.cjs +2 -2
- package/dist/channels-public.js +0 -1964
- package/dist/channels-public.js.map +0 -20
- package/dist/channels-slack.js +0 -1784
- package/dist/channels-slack.js.map +0 -27
- package/dist/gateway-core.js +0 -3067
- package/dist/gateway-core.js.map +0 -19
- package/dist/types/channels/command-runtime-executor.d.ts +0 -125
- package/dist/types/channels/command-runtime-executor.d.ts.map +0 -1
- package/dist/types/channels/command-surface.d.ts +0 -42
- package/dist/types/channels/command-surface.d.ts.map +0 -1
- package/dist/types/channels/control-request-coordinator.d.ts +0 -42
- package/dist/types/channels/control-request-coordinator.d.ts.map +0 -1
- package/dist/types/channels/core-stream.d.ts +0 -35
- package/dist/types/channels/core-stream.d.ts.map +0 -1
- package/dist/types/channels/gateway-core.d.ts +0 -88
- package/dist/types/channels/gateway-core.d.ts.map +0 -1
- package/dist/types/channels/gateway-sources.d.ts +0 -6
- package/dist/types/channels/gateway-sources.d.ts.map +0 -1
- package/dist/types/channels/interactive.d.ts +0 -13
- package/dist/types/channels/interactive.d.ts.map +0 -1
- package/dist/types/channels/lifecycle-error.d.ts +0 -25
- package/dist/types/channels/lifecycle-error.d.ts.map +0 -1
- package/dist/types/channels/message-channel-executor.d.ts +0 -48
- package/dist/types/channels/message-channel-executor.d.ts.map +0 -1
- package/dist/types/channels/message-channel-formatting.d.ts +0 -6
- package/dist/types/channels/message-channel-formatting.d.ts.map +0 -1
- package/dist/types/channels/message-channel-idempotency.d.ts +0 -8
- package/dist/types/channels/message-channel-idempotency.d.ts.map +0 -1
- package/dist/types/channels/message-channel-tool-definition.d.ts +0 -37
- package/dist/types/channels/message-channel-tool-definition.d.ts.map +0 -1
- package/dist/types/channels/message-channel-types.d.ts +0 -46
- package/dist/types/channels/message-channel-types.d.ts.map +0 -1
- package/dist/types/channels/processor.d.ts +0 -27
- package/dist/types/channels/processor.d.ts.map +0 -1
- package/dist/types/channels/progress-builder.d.ts +0 -7
- package/dist/types/channels/progress-builder.d.ts.map +0 -1
- package/dist/types/channels/progress-formatting.d.ts +0 -27
- package/dist/types/channels/progress-formatting.d.ts.map +0 -1
- package/dist/types/channels/route-thread-key.d.ts +0 -4
- package/dist/types/channels/route-thread-key.d.ts.map +0 -1
- package/dist/types/channels/slack/attachment-primitives.d.ts +0 -55
- package/dist/types/channels/slack/attachment-primitives.d.ts.map +0 -1
- package/dist/types/channels/slack/bot-policy.d.ts +0 -25
- package/dist/types/channels/slack/bot-policy.d.ts.map +0 -1
- package/dist/types/channels/slack/ingress-policy.d.ts +0 -108
- package/dist/types/channels/slack/ingress-policy.d.ts.map +0 -1
- package/dist/types/channels/slack/internal-types.d.ts +0 -168
- package/dist/types/channels/slack/internal-types.d.ts.map +0 -1
- package/dist/types/channels/slack/message-action-contract.d.ts +0 -11
- package/dist/types/channels/slack/message-action-contract.d.ts.map +0 -1
- package/dist/types/channels/slack/model-picker-blocks.d.ts +0 -5
- package/dist/types/channels/slack/model-picker-blocks.d.ts.map +0 -1
- package/dist/types/channels/slack/presentation.d.ts +0 -18
- package/dist/types/channels/slack/presentation.d.ts.map +0 -1
- package/dist/types/channels/slack/progress.d.ts +0 -7
- package/dist/types/channels/slack/progress.d.ts.map +0 -1
- package/dist/types/channels/slack/public-utils.d.ts +0 -10
- package/dist/types/channels/slack/public-utils.d.ts.map +0 -1
- package/dist/types/channels/slack/sender.d.ts +0 -39
- package/dist/types/channels/slack/sender.d.ts.map +0 -1
- package/dist/types/channels/slack/status-controller.d.ts +0 -37
- package/dist/types/channels/slack/status-controller.d.ts.map +0 -1
- package/dist/types/channels/slack/user-mentions.d.ts +0 -10
- package/dist/types/channels/slack/user-mentions.d.ts.map +0 -1
- package/dist/types/channels/slack/utils.d.ts +0 -37
- package/dist/types/channels/slack/utils.d.ts.map +0 -1
- package/dist/types/channels/xml.d.ts +0 -6
- package/dist/types/channels/xml.d.ts.map +0 -1
- package/dist/types/channels-public.d.ts +0 -17
- package/dist/types/channels-public.d.ts.map +0 -1
- package/dist/types/channels-slack.d.ts +0 -17
- package/dist/types/channels-slack.d.ts.map +0 -1
- package/dist/types/gateway-core.d.ts +0 -12
- package/dist/types/gateway-core.d.ts.map +0 -1
- package/dist/types/websocket/listener/constants.d.ts +0 -26
- package/dist/types/websocket/listener/constants.d.ts.map +0 -1
package/dist/channels-slack.js
DELETED
|
@@ -1,1784 +0,0 @@
|
|
|
1
|
-
// src/channels/slack/attachment-primitives.ts
|
|
2
|
-
var MAX_SLACK_ATTACHMENTS = 8;
|
|
3
|
-
var ALLOWED_SLACK_HOST_SUFFIXES = [
|
|
4
|
-
"slack.com",
|
|
5
|
-
"slack-edge.com",
|
|
6
|
-
"slack-files.com"
|
|
7
|
-
];
|
|
8
|
-
function asRecord(value) {
|
|
9
|
-
return value && typeof value === "object" ? value : null;
|
|
10
|
-
}
|
|
11
|
-
function isNonEmptyString(value) {
|
|
12
|
-
return typeof value === "string" && value.trim().length > 0;
|
|
13
|
-
}
|
|
14
|
-
function parseSlackMessages(value) {
|
|
15
|
-
const page = asRecord(value);
|
|
16
|
-
if (!page || !Array.isArray(page.messages))
|
|
17
|
-
return [];
|
|
18
|
-
return page.messages.map((entry) => {
|
|
19
|
-
const message = asRecord(entry);
|
|
20
|
-
if (!message || !isNonEmptyString(message.ts))
|
|
21
|
-
return null;
|
|
22
|
-
return {
|
|
23
|
-
ts: message.ts,
|
|
24
|
-
files: Array.isArray(message.files) ? message.files : undefined,
|
|
25
|
-
attachments: Array.isArray(message.attachments) ? message.attachments : undefined
|
|
26
|
-
};
|
|
27
|
-
}).filter((entry) => Boolean(entry));
|
|
28
|
-
}
|
|
29
|
-
function normalizeSlackFileLike(value) {
|
|
30
|
-
const record = asRecord(value);
|
|
31
|
-
if (!record)
|
|
32
|
-
return null;
|
|
33
|
-
return {
|
|
34
|
-
id: isNonEmptyString(record.id) ? record.id : undefined,
|
|
35
|
-
name: isNonEmptyString(record.name) ? record.name : undefined,
|
|
36
|
-
mimetype: isNonEmptyString(record.mimetype) ? record.mimetype : undefined,
|
|
37
|
-
size: typeof record.size === "number" ? record.size : undefined,
|
|
38
|
-
url_private: isNonEmptyString(record.url_private) ? record.url_private : undefined,
|
|
39
|
-
url_private_download: isNonEmptyString(record.url_private_download) ? record.url_private_download : undefined
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
function normalizeSlackAttachmentLike(value) {
|
|
43
|
-
const record = asRecord(value);
|
|
44
|
-
if (!record)
|
|
45
|
-
return null;
|
|
46
|
-
const files = Array.isArray(record.files) ? record.files.map((entry) => normalizeSlackFileLike(entry)).filter((entry) => Boolean(entry)) : undefined;
|
|
47
|
-
return {
|
|
48
|
-
image_url: isNonEmptyString(record.image_url) ? record.image_url : undefined,
|
|
49
|
-
files
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
function collectSlackFiles(rawEvent) {
|
|
53
|
-
const record = asRecord(rawEvent);
|
|
54
|
-
if (!record)
|
|
55
|
-
return [];
|
|
56
|
-
const deduped = new Map;
|
|
57
|
-
const push = (file) => {
|
|
58
|
-
if (!file)
|
|
59
|
-
return;
|
|
60
|
-
const key = file.id ?? file.url_private_download ?? file.url_private ?? `${file.name ?? "attachment"}:${file.mimetype ?? ""}`;
|
|
61
|
-
deduped.set(key, file);
|
|
62
|
-
};
|
|
63
|
-
if (Array.isArray(record.files)) {
|
|
64
|
-
for (const entry of record.files)
|
|
65
|
-
push(normalizeSlackFileLike(entry));
|
|
66
|
-
}
|
|
67
|
-
if (Array.isArray(record.attachments)) {
|
|
68
|
-
record.attachments.map((entry) => normalizeSlackAttachmentLike(entry)).filter((entry) => Boolean(entry)).forEach((attachment, index) => {
|
|
69
|
-
for (const file of attachment.files ?? [])
|
|
70
|
-
push(file);
|
|
71
|
-
if (attachment.image_url) {
|
|
72
|
-
push({
|
|
73
|
-
id: `attachment-image-${index}`,
|
|
74
|
-
name: `attachment-image-${index}.png`,
|
|
75
|
-
url_private: attachment.image_url
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
return Array.from(deduped.values()).slice(0, MAX_SLACK_ATTACHMENTS);
|
|
81
|
-
}
|
|
82
|
-
async function resolveSlackMessageFiles(params) {
|
|
83
|
-
if (isNonEmptyString(params.threadTs)) {
|
|
84
|
-
const messages2 = parseSlackMessages(await params.client.conversations.replies({
|
|
85
|
-
channel: params.channelId,
|
|
86
|
-
ts: params.threadTs,
|
|
87
|
-
oldest: params.messageTs,
|
|
88
|
-
latest: params.messageTs,
|
|
89
|
-
inclusive: true,
|
|
90
|
-
limit: 2
|
|
91
|
-
}));
|
|
92
|
-
const message2 = messages2.find((entry) => entry.ts === params.messageTs);
|
|
93
|
-
return message2 ? collectSlackFiles(message2) : null;
|
|
94
|
-
}
|
|
95
|
-
const messages = parseSlackMessages(await params.client.conversations.history({
|
|
96
|
-
channel: params.channelId,
|
|
97
|
-
oldest: params.messageTs,
|
|
98
|
-
latest: params.messageTs,
|
|
99
|
-
inclusive: true,
|
|
100
|
-
limit: 1
|
|
101
|
-
}));
|
|
102
|
-
const message = messages.find((entry) => entry.ts === params.messageTs);
|
|
103
|
-
return message ? collectSlackFiles(message) : null;
|
|
104
|
-
}
|
|
105
|
-
function isAllowedSlackHostname(hostname) {
|
|
106
|
-
const normalized = hostname.trim().toLowerCase();
|
|
107
|
-
return ALLOWED_SLACK_HOST_SUFFIXES.some((suffix) => normalized === suffix || normalized.endsWith(`.${suffix}`));
|
|
108
|
-
}
|
|
109
|
-
function assertSlackFileUrl(rawUrl) {
|
|
110
|
-
const parsed = new URL(rawUrl);
|
|
111
|
-
if (parsed.protocol !== "https:") {
|
|
112
|
-
throw new Error(`Unsupported Slack file protocol: ${parsed.protocol}`);
|
|
113
|
-
}
|
|
114
|
-
if (!isAllowedSlackHostname(parsed.hostname)) {
|
|
115
|
-
throw new Error(`Refusing non-Slack attachment host: ${parsed.hostname}`);
|
|
116
|
-
}
|
|
117
|
-
return parsed;
|
|
118
|
-
}
|
|
119
|
-
function extensionForMimeType(mimeType) {
|
|
120
|
-
switch (mimeType?.toLowerCase()) {
|
|
121
|
-
case "image/png":
|
|
122
|
-
return ".png";
|
|
123
|
-
case "image/jpeg":
|
|
124
|
-
return ".jpg";
|
|
125
|
-
case "image/gif":
|
|
126
|
-
return ".gif";
|
|
127
|
-
case "image/webp":
|
|
128
|
-
return ".webp";
|
|
129
|
-
case "audio/aac":
|
|
130
|
-
return ".aac";
|
|
131
|
-
case "audio/m4a":
|
|
132
|
-
case "audio/mp4":
|
|
133
|
-
case "audio/x-m4a":
|
|
134
|
-
return ".m4a";
|
|
135
|
-
case "audio/mpeg":
|
|
136
|
-
return ".mp3";
|
|
137
|
-
case "audio/ogg":
|
|
138
|
-
return ".ogg";
|
|
139
|
-
case "audio/wav":
|
|
140
|
-
case "audio/x-wav":
|
|
141
|
-
return ".wav";
|
|
142
|
-
case "audio/webm":
|
|
143
|
-
return ".webm";
|
|
144
|
-
case "application/pdf":
|
|
145
|
-
return ".pdf";
|
|
146
|
-
case "text/plain":
|
|
147
|
-
return ".txt";
|
|
148
|
-
default:
|
|
149
|
-
return "";
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
function pathBaseName(pathname) {
|
|
153
|
-
const trimmed = pathname.replace(/\/+$/, "");
|
|
154
|
-
const separator = trimmed.lastIndexOf("/");
|
|
155
|
-
return trimmed.slice(separator + 1);
|
|
156
|
-
}
|
|
157
|
-
function extensionName(name) {
|
|
158
|
-
const base = pathBaseName(name);
|
|
159
|
-
if (base === "..")
|
|
160
|
-
return "";
|
|
161
|
-
const index = base.lastIndexOf(".");
|
|
162
|
-
return index > 0 ? base.slice(index) : "";
|
|
163
|
-
}
|
|
164
|
-
function resolveMimeType(name, fallback) {
|
|
165
|
-
if (fallback)
|
|
166
|
-
return fallback;
|
|
167
|
-
switch (extensionName(name).toLowerCase()) {
|
|
168
|
-
case ".png":
|
|
169
|
-
return "image/png";
|
|
170
|
-
case ".jpg":
|
|
171
|
-
case ".jpeg":
|
|
172
|
-
return "image/jpeg";
|
|
173
|
-
case ".gif":
|
|
174
|
-
return "image/gif";
|
|
175
|
-
case ".webp":
|
|
176
|
-
return "image/webp";
|
|
177
|
-
case ".aac":
|
|
178
|
-
return "audio/aac";
|
|
179
|
-
case ".m4a":
|
|
180
|
-
return "audio/mp4";
|
|
181
|
-
case ".mp3":
|
|
182
|
-
return "audio/mpeg";
|
|
183
|
-
case ".oga":
|
|
184
|
-
case ".ogg":
|
|
185
|
-
case ".opus":
|
|
186
|
-
return "audio/ogg";
|
|
187
|
-
case ".wav":
|
|
188
|
-
return "audio/wav";
|
|
189
|
-
case ".webm":
|
|
190
|
-
return "audio/webm";
|
|
191
|
-
case ".pdf":
|
|
192
|
-
return "application/pdf";
|
|
193
|
-
case ".txt":
|
|
194
|
-
case ".md":
|
|
195
|
-
return "text/plain";
|
|
196
|
-
default:
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
function isGenericSlackMimeType(mimeType) {
|
|
201
|
-
const normalized = mimeType?.trim().toLowerCase();
|
|
202
|
-
return normalized === "application/octet-stream" || normalized === "binary/octet-stream";
|
|
203
|
-
}
|
|
204
|
-
function resolveSlackFileName(params) {
|
|
205
|
-
const hintedName = params.file.name ?? (params.url ? pathBaseName(new URL(params.url).pathname) : undefined) ?? `${params.file.id ?? "attachment"}${extensionForMimeType(params.file.mimetype)}`;
|
|
206
|
-
return extensionName(hintedName) || !params.mimeType ? hintedName : `${hintedName}${extensionForMimeType(params.mimeType)}`;
|
|
207
|
-
}
|
|
208
|
-
function resolveSlackFileMimeType(params) {
|
|
209
|
-
const preferredMimeType = params.responseMimeType && !isGenericSlackMimeType(params.responseMimeType) ? params.responseMimeType : params.file.mimetype && !isGenericSlackMimeType(params.file.mimetype) ? params.file.mimetype : undefined;
|
|
210
|
-
return resolveMimeType(params.fileName, preferredMimeType);
|
|
211
|
-
}
|
|
212
|
-
function resolveSlackFileMetadata(params) {
|
|
213
|
-
const hintedName = resolveSlackFileName({
|
|
214
|
-
file: params.file,
|
|
215
|
-
url: params.url
|
|
216
|
-
});
|
|
217
|
-
const mimeType = resolveSlackFileMimeType({
|
|
218
|
-
file: params.file,
|
|
219
|
-
fileName: hintedName,
|
|
220
|
-
responseMimeType: params.responseMimeType
|
|
221
|
-
});
|
|
222
|
-
return {
|
|
223
|
-
fileName: resolveSlackFileName({
|
|
224
|
-
file: params.file,
|
|
225
|
-
url: params.url,
|
|
226
|
-
mimeType
|
|
227
|
-
}),
|
|
228
|
-
mimeType
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
function parseContentLength(response) {
|
|
232
|
-
const header = response.headers.get("content-length");
|
|
233
|
-
if (!header)
|
|
234
|
-
return;
|
|
235
|
-
const value = Number(header);
|
|
236
|
-
return Number.isFinite(value) ? value : undefined;
|
|
237
|
-
}
|
|
238
|
-
async function fetchSlackFile(params) {
|
|
239
|
-
const rawUrl = params.file.url_private_download ?? params.file.url_private;
|
|
240
|
-
if (!rawUrl) {
|
|
241
|
-
throw new Error("Slack attachment does not include a private download URL.");
|
|
242
|
-
}
|
|
243
|
-
const parsed = assertSlackFileUrl(rawUrl);
|
|
244
|
-
const fetcher = params.fetcher ?? globalThis.fetch;
|
|
245
|
-
const authHeaders = { Authorization: `Bearer ${params.token}` };
|
|
246
|
-
const initial = await fetcher(parsed.href, {
|
|
247
|
-
headers: authHeaders,
|
|
248
|
-
redirect: "manual",
|
|
249
|
-
...params.signal ? { signal: params.signal } : {}
|
|
250
|
-
});
|
|
251
|
-
let response = initial;
|
|
252
|
-
if (initial.status >= 300 && initial.status < 400) {
|
|
253
|
-
const location = initial.headers.get("location");
|
|
254
|
-
if (location) {
|
|
255
|
-
const resolved = new URL(location, parsed.href);
|
|
256
|
-
response = await fetcher(resolved.href, {
|
|
257
|
-
...resolved.origin === parsed.origin ? { headers: authHeaders } : {},
|
|
258
|
-
redirect: "follow",
|
|
259
|
-
...params.signal ? { signal: params.signal } : {}
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
if (!response.ok) {
|
|
264
|
-
throw new Error(`Slack attachment fetch failed with HTTP ${response.status}.`);
|
|
265
|
-
}
|
|
266
|
-
if (!response.body) {
|
|
267
|
-
throw new Error("Slack attachment response did not include a body.");
|
|
268
|
-
}
|
|
269
|
-
const responseMimeType = response.headers.get("content-type")?.split(";")[0]?.trim() || undefined;
|
|
270
|
-
const metadata = resolveSlackFileMetadata({
|
|
271
|
-
file: params.file,
|
|
272
|
-
url: rawUrl,
|
|
273
|
-
responseMimeType
|
|
274
|
-
});
|
|
275
|
-
return {
|
|
276
|
-
body: response.body,
|
|
277
|
-
...metadata,
|
|
278
|
-
contentLength: parseContentLength(response)
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
// src/channels/slack/bot-policy.ts
|
|
282
|
-
function resolveSlackAllowBotsMode(value) {
|
|
283
|
-
if (value === "mentions")
|
|
284
|
-
return "mentions";
|
|
285
|
-
return "off";
|
|
286
|
-
}
|
|
287
|
-
function isNonEmptyString2(value) {
|
|
288
|
-
return typeof value === "string" && value.length > 0;
|
|
289
|
-
}
|
|
290
|
-
function isSlackBotAuthoredInboundMessage(message) {
|
|
291
|
-
return isNonEmptyString2(message.bot_id) || message.subtype === "bot_message";
|
|
292
|
-
}
|
|
293
|
-
function isOwnSlackBotInboundMessage(params) {
|
|
294
|
-
return isNonEmptyString2(params.botUserId) && params.message.user === params.botUserId || isNonEmptyString2(params.botId) && params.message.bot_id === params.botId;
|
|
295
|
-
}
|
|
296
|
-
function shouldAcceptSlackInboundBotMessage(params) {
|
|
297
|
-
if (isOwnSlackBotInboundMessage({
|
|
298
|
-
message: params.message,
|
|
299
|
-
botUserId: params.botUserId,
|
|
300
|
-
botId: params.botId
|
|
301
|
-
})) {
|
|
302
|
-
return false;
|
|
303
|
-
}
|
|
304
|
-
if (!isSlackBotAuthoredInboundMessage(params.message)) {
|
|
305
|
-
return true;
|
|
306
|
-
}
|
|
307
|
-
const mode = resolveSlackAllowBotsMode(params.allowBots);
|
|
308
|
-
return mode === "mentions" && params.wasMentioned;
|
|
309
|
-
}
|
|
310
|
-
// src/channels/slack/public-utils.ts
|
|
311
|
-
function isNonEmptyString3(value) {
|
|
312
|
-
return typeof value === "string" && value.length > 0;
|
|
313
|
-
}
|
|
314
|
-
function firstNonEmptyString(...values) {
|
|
315
|
-
return values.find(isNonEmptyString3);
|
|
316
|
-
}
|
|
317
|
-
function resolveSlackChatType(chatId) {
|
|
318
|
-
return chatId.startsWith("D") ? "direct" : "channel";
|
|
319
|
-
}
|
|
320
|
-
function resolveSlackSourceThreadTs(source) {
|
|
321
|
-
if (source.chatType === "direct" || resolveSlackChatType(source.chatId) === "direct") {
|
|
322
|
-
return firstNonEmptyString(source.threadId);
|
|
323
|
-
}
|
|
324
|
-
return firstNonEmptyString(source.threadId, source.messageId);
|
|
325
|
-
}
|
|
326
|
-
function resolveSlackProgressThreadTs(source) {
|
|
327
|
-
if (source.chatType === "direct" || resolveSlackChatType(source.chatId) === "direct") {
|
|
328
|
-
return firstNonEmptyString(source.threadId, source.messageId);
|
|
329
|
-
}
|
|
330
|
-
return resolveSlackSourceThreadTs(source);
|
|
331
|
-
}
|
|
332
|
-
function resolveSlackOutboundThreadTs(msg) {
|
|
333
|
-
if (resolveSlackChatType(msg.chatId) === "direct") {
|
|
334
|
-
return firstNonEmptyString(msg.threadId);
|
|
335
|
-
}
|
|
336
|
-
return firstNonEmptyString(msg.threadId, msg.replyToMessageId);
|
|
337
|
-
}
|
|
338
|
-
function normalizeSlackReactionName(value) {
|
|
339
|
-
return value.trim().replace(/^:+|:+$/g, "");
|
|
340
|
-
}
|
|
341
|
-
function slackTimestampToMillis(value) {
|
|
342
|
-
return Math.round(Number.parseFloat(value) * 1000);
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
// src/channels/slack/user-mentions.ts
|
|
346
|
-
var SLACK_USER_MENTION_PATTERN = /<@([A-Z0-9]+)(?:\|[^>]*)?>/g;
|
|
347
|
-
var MAX_SLACK_DISPLAY_NAME_LENGTH = 80;
|
|
348
|
-
function escapeRegExp(text) {
|
|
349
|
-
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
350
|
-
}
|
|
351
|
-
function stripSlackBotMention(text, botUserId) {
|
|
352
|
-
if (!botUserId)
|
|
353
|
-
return text.trim();
|
|
354
|
-
const botMentionPattern = new RegExp(`^\\s*<@${escapeRegExp(botUserId)}(?:\\|[^>]*)?>`);
|
|
355
|
-
return text.replace(botMentionPattern, "").trim();
|
|
356
|
-
}
|
|
357
|
-
function sanitizeSlackUserDisplayName(value, fallbackUserId) {
|
|
358
|
-
const sanitized = (value ?? "").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, " ").replace(/\s+/gu, " ").trim().slice(0, MAX_SLACK_DISPLAY_NAME_LENGTH).trim();
|
|
359
|
-
return sanitized || fallbackUserId;
|
|
360
|
-
}
|
|
361
|
-
function extractSlackUserMentionTokens(text) {
|
|
362
|
-
if (!text?.includes("<@"))
|
|
363
|
-
return [];
|
|
364
|
-
return Array.from(text.matchAll(SLACK_USER_MENTION_PATTERN), (match) => ({
|
|
365
|
-
start: match.index,
|
|
366
|
-
end: match.index + match[0].length,
|
|
367
|
-
userId: match[1] ?? ""
|
|
368
|
-
})).filter((mention) => mention.userId.length > 0);
|
|
369
|
-
}
|
|
370
|
-
function buildChannelUserMentions(text, displayNames) {
|
|
371
|
-
const mentions = extractSlackUserMentionTokens(text).map((mention) => ({
|
|
372
|
-
...mention,
|
|
373
|
-
displayName: displayNames.get(mention.userId) ?? mention.userId
|
|
374
|
-
}));
|
|
375
|
-
return mentions.length > 0 ? mentions : undefined;
|
|
376
|
-
}
|
|
377
|
-
function collectMentionUserIds(msg) {
|
|
378
|
-
const ids = new Set;
|
|
379
|
-
const collect = (text) => {
|
|
380
|
-
for (const mention of extractSlackUserMentionTokens(text)) {
|
|
381
|
-
ids.add(mention.userId);
|
|
382
|
-
}
|
|
383
|
-
};
|
|
384
|
-
collect(msg.text);
|
|
385
|
-
collect(msg.replyContext?.text);
|
|
386
|
-
collect(msg.threadContext?.starter?.text);
|
|
387
|
-
for (const entry of msg.threadContext?.history ?? [])
|
|
388
|
-
collect(entry.text);
|
|
389
|
-
return [...ids];
|
|
390
|
-
}
|
|
391
|
-
function withResolvedReplyMentions(replyContext, displayNames) {
|
|
392
|
-
if (!replyContext)
|
|
393
|
-
return;
|
|
394
|
-
const userMentions = buildChannelUserMentions(replyContext.text, displayNames);
|
|
395
|
-
return userMentions ? { ...replyContext, userMentions } : replyContext;
|
|
396
|
-
}
|
|
397
|
-
function withResolvedEntryMentions(entry, displayNames) {
|
|
398
|
-
const userMentions = buildChannelUserMentions(entry.text, displayNames);
|
|
399
|
-
return userMentions ? { ...entry, userMentions } : entry;
|
|
400
|
-
}
|
|
401
|
-
async function resolveSlackUserMentionsInMessage(params) {
|
|
402
|
-
const { message } = params;
|
|
403
|
-
const userIds = collectMentionUserIds(message);
|
|
404
|
-
if (userIds.length === 0)
|
|
405
|
-
return message;
|
|
406
|
-
const resolvedNames = await Promise.all(userIds.map(async (userId) => {
|
|
407
|
-
try {
|
|
408
|
-
const name = await params.resolveUserName(userId);
|
|
409
|
-
return [userId, sanitizeSlackUserDisplayName(name, userId)];
|
|
410
|
-
} catch {
|
|
411
|
-
return [userId, userId];
|
|
412
|
-
}
|
|
413
|
-
}));
|
|
414
|
-
const displayNames = new Map(resolvedNames);
|
|
415
|
-
const userMentions = buildChannelUserMentions(message.text, displayNames);
|
|
416
|
-
const replyContext = withResolvedReplyMentions(message.replyContext, displayNames);
|
|
417
|
-
const starter = message.threadContext?.starter ? withResolvedEntryMentions(message.threadContext.starter, displayNames) : undefined;
|
|
418
|
-
const history = message.threadContext?.history?.map((entry) => withResolvedEntryMentions(entry, displayNames));
|
|
419
|
-
return {
|
|
420
|
-
...message,
|
|
421
|
-
...userMentions ? { userMentions } : {},
|
|
422
|
-
...replyContext ? { replyContext } : {},
|
|
423
|
-
...message.threadContext ? {
|
|
424
|
-
threadContext: {
|
|
425
|
-
...message.threadContext,
|
|
426
|
-
...starter ? { starter } : {},
|
|
427
|
-
...history ? { history } : {}
|
|
428
|
-
}
|
|
429
|
-
} : {}
|
|
430
|
-
};
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
// src/channels/slack/ingress-policy.ts
|
|
434
|
-
var IGNORED_SLACK_MESSAGE_SUBTYPES = new Set([
|
|
435
|
-
"assistant_app_thread",
|
|
436
|
-
"channel_archive",
|
|
437
|
-
"channel_convert_to_private",
|
|
438
|
-
"channel_convert_to_public",
|
|
439
|
-
"channel_join",
|
|
440
|
-
"channel_leave",
|
|
441
|
-
"channel_name",
|
|
442
|
-
"channel_posting_permissions",
|
|
443
|
-
"channel_purpose",
|
|
444
|
-
"channel_topic",
|
|
445
|
-
"channel_unarchive",
|
|
446
|
-
"document_mention",
|
|
447
|
-
"ekm_access_denied",
|
|
448
|
-
"file_comment",
|
|
449
|
-
"group_archive",
|
|
450
|
-
"group_join",
|
|
451
|
-
"group_leave",
|
|
452
|
-
"group_name",
|
|
453
|
-
"group_purpose",
|
|
454
|
-
"group_topic",
|
|
455
|
-
"group_unarchive",
|
|
456
|
-
"pinned_item",
|
|
457
|
-
"reminder_add",
|
|
458
|
-
"unpinned_item"
|
|
459
|
-
]);
|
|
460
|
-
var WRAPPER_SLACK_MESSAGE_SUBTYPES = new Set([
|
|
461
|
-
"message_changed",
|
|
462
|
-
"message_deleted",
|
|
463
|
-
"message_replied"
|
|
464
|
-
]);
|
|
465
|
-
function isSlackMentionOnlyChannel(channelId, mentionOnlyChannels) {
|
|
466
|
-
return mentionOnlyChannels?.includes(channelId) === true;
|
|
467
|
-
}
|
|
468
|
-
function hasRecordValue(value) {
|
|
469
|
-
return value !== null && typeof value === "object";
|
|
470
|
-
}
|
|
471
|
-
function hasSlackMention(text, userId) {
|
|
472
|
-
return isNonEmptyString3(text) && isNonEmptyString3(userId) && (text.includes(`<@${userId}>`) || text.includes(`<@${userId}|`));
|
|
473
|
-
}
|
|
474
|
-
function isBotAuthoredMessage(message) {
|
|
475
|
-
return isNonEmptyString3(message.bot_id) || message.subtype === "bot_message";
|
|
476
|
-
}
|
|
477
|
-
function resolveMessageSubtypeIgnoreReason(message) {
|
|
478
|
-
const subtype = isNonEmptyString3(message.subtype) ? message.subtype : null;
|
|
479
|
-
if (!subtype) {
|
|
480
|
-
return null;
|
|
481
|
-
}
|
|
482
|
-
if (IGNORED_SLACK_MESSAGE_SUBTYPES.has(subtype)) {
|
|
483
|
-
return "ignored_subtype";
|
|
484
|
-
}
|
|
485
|
-
if (WRAPPER_SLACK_MESSAGE_SUBTYPES.has(subtype) && hasRecordValue(message.message)) {
|
|
486
|
-
return "wrapper_message";
|
|
487
|
-
}
|
|
488
|
-
return null;
|
|
489
|
-
}
|
|
490
|
-
function isProcessableSlackInboundMessage(message) {
|
|
491
|
-
return resolveSlackMessageIngressPolicy({ message }).shouldRoute;
|
|
492
|
-
}
|
|
493
|
-
function shouldSkipSlackMessageByLastSeen(params) {
|
|
494
|
-
return Boolean(params.lastSeenMessageTs && params.lastSeenMessageTs >= params.messageTs);
|
|
495
|
-
}
|
|
496
|
-
function resolveSlackMessageIngressPolicy(params) {
|
|
497
|
-
const { message } = params;
|
|
498
|
-
if (!isNonEmptyString3(message.channel)) {
|
|
499
|
-
return { shouldRoute: false, reason: "missing_channel" };
|
|
500
|
-
}
|
|
501
|
-
const senderId = firstNonEmptyString(message.user, message.bot_id);
|
|
502
|
-
if (!senderId) {
|
|
503
|
-
return { shouldRoute: false, reason: "missing_sender" };
|
|
504
|
-
}
|
|
505
|
-
if (!isNonEmptyString3(message.ts)) {
|
|
506
|
-
return { shouldRoute: false, reason: "missing_timestamp" };
|
|
507
|
-
}
|
|
508
|
-
if (message.hidden === true) {
|
|
509
|
-
return { shouldRoute: false, reason: "hidden_message" };
|
|
510
|
-
}
|
|
511
|
-
const subtypeIgnoreReason = resolveMessageSubtypeIgnoreReason(message);
|
|
512
|
-
if (subtypeIgnoreReason) {
|
|
513
|
-
return { shouldRoute: false, reason: subtypeIgnoreReason };
|
|
514
|
-
}
|
|
515
|
-
const chatType = resolveSlackChatType(message.channel);
|
|
516
|
-
const threadId = chatType === "direct" ? firstNonEmptyString(message.thread_ts) ?? null : firstNonEmptyString(message.thread_ts, message.ts) ?? null;
|
|
517
|
-
if (chatType === "channel" && !isNonEmptyString3(message.thread_ts)) {
|
|
518
|
-
return { shouldRoute: false, reason: "top_level_channel_message" };
|
|
519
|
-
}
|
|
520
|
-
const rawText = isNonEmptyString3(message.text) ? message.text : "";
|
|
521
|
-
const wasMentioned = hasSlackMention(rawText, params.botUserId);
|
|
522
|
-
if (chatType === "channel" && wasMentioned && params.appMentionEventWillHandleMentions === true) {
|
|
523
|
-
return { shouldRoute: false, reason: "handled_by_app_mention" };
|
|
524
|
-
}
|
|
525
|
-
const isAgentThread = params.isAgentThread === true;
|
|
526
|
-
const effectiveMention = isBotAuthoredMessage(message) ? wasMentioned : wasMentioned || isAgentThread;
|
|
527
|
-
return {
|
|
528
|
-
shouldRoute: true,
|
|
529
|
-
channelId: message.channel,
|
|
530
|
-
senderId,
|
|
531
|
-
...isNonEmptyString3(message.user) ? { senderUserId: message.user } : {},
|
|
532
|
-
...isNonEmptyString3(message.bot_id) ? { senderBotId: message.bot_id } : {},
|
|
533
|
-
messageId: message.ts,
|
|
534
|
-
threadId,
|
|
535
|
-
chatType,
|
|
536
|
-
text: wasMentioned ? stripSlackBotMention(rawText, params.botUserId) : rawText,
|
|
537
|
-
rawText,
|
|
538
|
-
wasMentioned,
|
|
539
|
-
effectiveMention,
|
|
540
|
-
isAgentThread,
|
|
541
|
-
routedBy: wasMentioned ? "mention" : chatType === "direct" ? "dm" : "thread"
|
|
542
|
-
};
|
|
543
|
-
}
|
|
544
|
-
function resolveSlackAppMentionIngressPolicy(params) {
|
|
545
|
-
const { event } = params;
|
|
546
|
-
if (!isNonEmptyString3(event.channel)) {
|
|
547
|
-
return { shouldRoute: false, reason: "missing_channel" };
|
|
548
|
-
}
|
|
549
|
-
const senderId = firstNonEmptyString(event.user, event.bot_id);
|
|
550
|
-
if (!senderId) {
|
|
551
|
-
return { shouldRoute: false, reason: "missing_sender" };
|
|
552
|
-
}
|
|
553
|
-
if (!isNonEmptyString3(event.ts)) {
|
|
554
|
-
return { shouldRoute: false, reason: "missing_timestamp" };
|
|
555
|
-
}
|
|
556
|
-
const rawText = isNonEmptyString3(event.text) ? event.text : "";
|
|
557
|
-
return {
|
|
558
|
-
shouldRoute: true,
|
|
559
|
-
channelId: event.channel,
|
|
560
|
-
senderId,
|
|
561
|
-
...isNonEmptyString3(event.user) ? { senderUserId: event.user } : {},
|
|
562
|
-
...isNonEmptyString3(event.bot_id) ? { senderBotId: event.bot_id } : {},
|
|
563
|
-
messageId: event.ts,
|
|
564
|
-
threadId: firstNonEmptyString(event.thread_ts, event.ts) ?? event.ts,
|
|
565
|
-
chatType: "channel",
|
|
566
|
-
text: stripSlackBotMention(rawText, params.botUserId),
|
|
567
|
-
rawText,
|
|
568
|
-
wasMentioned: true,
|
|
569
|
-
effectiveMention: true,
|
|
570
|
-
isAgentThread: false,
|
|
571
|
-
routedBy: "mention"
|
|
572
|
-
};
|
|
573
|
-
}
|
|
574
|
-
function resolveSlackReactionIngressPolicy(params) {
|
|
575
|
-
const item = hasRecordValue(params.event.item) ? params.event.item : null;
|
|
576
|
-
if (item?.type !== "message") {
|
|
577
|
-
return { shouldRoute: false, reason: "invalid_reaction_item" };
|
|
578
|
-
}
|
|
579
|
-
if (!isNonEmptyString3(item.channel)) {
|
|
580
|
-
return { shouldRoute: false, reason: "missing_channel" };
|
|
581
|
-
}
|
|
582
|
-
if (!isNonEmptyString3(params.event.user)) {
|
|
583
|
-
return { shouldRoute: false, reason: "missing_sender" };
|
|
584
|
-
}
|
|
585
|
-
if (!isNonEmptyString3(item.ts)) {
|
|
586
|
-
return { shouldRoute: false, reason: "missing_timestamp" };
|
|
587
|
-
}
|
|
588
|
-
if (!isNonEmptyString3(params.event.reaction)) {
|
|
589
|
-
return { shouldRoute: false, reason: "missing_reaction" };
|
|
590
|
-
}
|
|
591
|
-
if (params.event.user === params.botUserId) {
|
|
592
|
-
return { shouldRoute: false, reason: "own_bot_reaction" };
|
|
593
|
-
}
|
|
594
|
-
const chatType = resolveSlackChatType(item.channel);
|
|
595
|
-
if (chatType === "channel" && isSlackMentionOnlyChannel(item.channel, params.mentionOnlyChannels)) {
|
|
596
|
-
return { shouldRoute: false, reason: "mention_only_channel" };
|
|
597
|
-
}
|
|
598
|
-
const targetMessageId = item.ts;
|
|
599
|
-
const threadId = params.threadId !== undefined ? params.threadId : chatType === "channel" ? targetMessageId : null;
|
|
600
|
-
const eventTimestamp = firstNonEmptyString(params.event.event_ts, targetMessageId) ?? targetMessageId;
|
|
601
|
-
const reaction = {
|
|
602
|
-
action: params.action,
|
|
603
|
-
emoji: params.event.reaction,
|
|
604
|
-
targetMessageId,
|
|
605
|
-
...isNonEmptyString3(params.event.item_user) ? { targetSenderId: params.event.item_user } : {}
|
|
606
|
-
};
|
|
607
|
-
return {
|
|
608
|
-
shouldRoute: true,
|
|
609
|
-
channelId: item.channel,
|
|
610
|
-
senderId: params.event.user,
|
|
611
|
-
messageId: eventTimestamp,
|
|
612
|
-
threadId,
|
|
613
|
-
chatType,
|
|
614
|
-
text: `Slack reaction ${params.action}: :${params.event.reaction}:`,
|
|
615
|
-
reaction
|
|
616
|
-
};
|
|
617
|
-
}
|
|
618
|
-
// src/channels/message-channel-bindings.ts
|
|
619
|
-
function formatSlackBindingNotice(info, conversationId) {
|
|
620
|
-
if (!info)
|
|
621
|
-
return "";
|
|
622
|
-
if ("unavailable" in info) {
|
|
623
|
-
return `
|
|
624
|
-
The message was delivered, but its thread binding could not be checked.`;
|
|
625
|
-
}
|
|
626
|
-
if (!info.binding)
|
|
627
|
-
return `
|
|
628
|
-
This thread has no incoming-message binding.`;
|
|
629
|
-
const binding = info.binding;
|
|
630
|
-
const state = binding.detached ? `This thread is detached (binding: ${binding.conversationId}).` : !binding.enabled ? `Incoming replies are paused for this thread (binding: ${binding.conversationId}).` : binding.conversationId === conversationId ? `Replies in this thread go to this conversation (${conversationId}).` : `Replies in this thread currently go to ${binding.conversationId}; this conversation is ${conversationId}.`;
|
|
631
|
-
if (binding.conversationId === conversationId)
|
|
632
|
-
return `
|
|
633
|
-
${state}`;
|
|
634
|
-
const action = {
|
|
635
|
-
action: "update-binding",
|
|
636
|
-
channel: info.channel,
|
|
637
|
-
accountId: info.accountId,
|
|
638
|
-
chat_id: info.chatId,
|
|
639
|
-
threadId: info.threadId,
|
|
640
|
-
conversationId,
|
|
641
|
-
expectedConversationId: binding.conversationId
|
|
642
|
-
};
|
|
643
|
-
return `
|
|
644
|
-
${state}
|
|
645
|
-
To change this thread's destination to this conversation, call MessageChannel with ${JSON.stringify(action)}. Existing pause/detach settings are preserved.`;
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
// src/channels/slack/message-action-contract.ts
|
|
649
|
-
async function sendSlackMessage(context) {
|
|
650
|
-
const { request, route, adapter, formatText } = context;
|
|
651
|
-
const text = request.message ?? "";
|
|
652
|
-
if (text.trim().length === 0 && !request.mediaPath) {
|
|
653
|
-
return "Error: Slack send requires message or media.";
|
|
654
|
-
}
|
|
655
|
-
const isDirect = route.chatType === "direct" || request.chatId.startsWith("D");
|
|
656
|
-
const formatted = formatText(text);
|
|
657
|
-
const result = await adapter.sendMessage({
|
|
658
|
-
channel: "slack",
|
|
659
|
-
accountId: route.accountId,
|
|
660
|
-
chatId: request.chatId,
|
|
661
|
-
text: formatted.text,
|
|
662
|
-
replyToMessageId: isDirect ? undefined : request.replyToMessageId,
|
|
663
|
-
threadId: isDirect ? request.threadId ?? route.threadId ?? null : request.replyToMessageId ? null : request.threadId ?? route.threadId ?? null,
|
|
664
|
-
mediaPath: request.mediaPath,
|
|
665
|
-
fileName: request.filename,
|
|
666
|
-
title: request.title,
|
|
667
|
-
parseMode: formatted.parseMode,
|
|
668
|
-
agentId: route.agentId,
|
|
669
|
-
conversationId: route.conversationId
|
|
670
|
-
});
|
|
671
|
-
const confirmation = request.mediaPath ? `Attachment sent to slack (message_id: ${result.messageId})` : `Message sent to slack (message_id: ${result.messageId})`;
|
|
672
|
-
return confirmation + formatSlackBindingNotice(result.bindingInfo, route.conversationId);
|
|
673
|
-
}
|
|
674
|
-
async function reactInSlack(context) {
|
|
675
|
-
const { request, route, adapter } = context;
|
|
676
|
-
if (!request.emoji?.trim())
|
|
677
|
-
return "Error: Slack react requires emoji.";
|
|
678
|
-
if (!request.messageId?.trim()) {
|
|
679
|
-
return "Error: Slack react requires messageId.";
|
|
680
|
-
}
|
|
681
|
-
const result = await adapter.sendMessage({
|
|
682
|
-
channel: "slack",
|
|
683
|
-
accountId: route.accountId,
|
|
684
|
-
chatId: request.chatId,
|
|
685
|
-
text: "",
|
|
686
|
-
targetMessageId: request.messageId,
|
|
687
|
-
reaction: request.emoji,
|
|
688
|
-
removeReaction: request.remove,
|
|
689
|
-
threadId: request.threadId ?? route.threadId ?? null
|
|
690
|
-
});
|
|
691
|
-
return request.remove ? `Reaction removed on slack (message_id: ${result.messageId})` : `Reaction added on slack (message_id: ${result.messageId})`;
|
|
692
|
-
}
|
|
693
|
-
async function listSlackCustomEmojis(context) {
|
|
694
|
-
const listCustomEmojis = context.adapter.listCustomEmojis;
|
|
695
|
-
if (typeof listCustomEmojis !== "function") {
|
|
696
|
-
return "Error: Running Slack adapter does not support custom emoji discovery.";
|
|
697
|
-
}
|
|
698
|
-
try {
|
|
699
|
-
const names = await listCustomEmojis.call(context.adapter);
|
|
700
|
-
if (names.length === 0) {
|
|
701
|
-
return "This Slack workspace has no custom emoji available to the app.";
|
|
702
|
-
}
|
|
703
|
-
return `Available custom Slack emoji (${names.length}): ${names.map((name) => `:${name}:`).join(", ")}`;
|
|
704
|
-
} catch (error) {
|
|
705
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
706
|
-
return `Error: Could not list custom Slack emoji. ${message}`;
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
function createSlackMessageActionAdapter(options = {}) {
|
|
710
|
-
const actions = [
|
|
711
|
-
"send",
|
|
712
|
-
...options.react ? ["react"] : [],
|
|
713
|
-
...options.listCustomEmojis ? ["list-custom-emojis"] : [],
|
|
714
|
-
...options.uploadFile ? ["upload-file"] : [],
|
|
715
|
-
...options.downloadFile ? ["download-file"] : [],
|
|
716
|
-
...options.bindings ? ["get-binding", "update-binding"] : []
|
|
717
|
-
];
|
|
718
|
-
return {
|
|
719
|
-
describeMessageTool() {
|
|
720
|
-
const properties = {};
|
|
721
|
-
if (options.bindings) {
|
|
722
|
-
properties.threadId = {
|
|
723
|
-
type: ["string", "null"],
|
|
724
|
-
description: "Thread identifier. Binding actions require an exact Slack thread timestamp, or explicit null for an unthreaded DM."
|
|
725
|
-
};
|
|
726
|
-
properties.conversationId = {
|
|
727
|
-
type: "string",
|
|
728
|
-
description: "Destination conversation for update-binding. Must belong to this agent; default selects this agent's default conversation."
|
|
729
|
-
};
|
|
730
|
-
properties.expectedConversationId = {
|
|
731
|
-
type: "string",
|
|
732
|
-
description: "Expected current destination for update-binding, from get-binding. A different current binding returns a conflict; an already-matching destination is a no-op."
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
if (options.downloadFile) {
|
|
736
|
-
properties.attachmentId = {
|
|
737
|
-
type: "string",
|
|
738
|
-
description: "Slack attachment id for action='download-file'. Copy attachment_id from the channel notification."
|
|
739
|
-
};
|
|
740
|
-
}
|
|
741
|
-
if (options.react || options.downloadFile) {
|
|
742
|
-
properties.messageId = {
|
|
743
|
-
type: "string",
|
|
744
|
-
description: options.downloadFile ? "Target Slack message id for action='react', or the source message id containing attachmentId for action='download-file'." : "Target Slack message id for action='react'."
|
|
745
|
-
};
|
|
746
|
-
}
|
|
747
|
-
return {
|
|
748
|
-
actions: [...actions],
|
|
749
|
-
...Object.keys(properties).length > 0 ? { schema: { properties } } : {}
|
|
750
|
-
};
|
|
751
|
-
},
|
|
752
|
-
...options.resolveMessageTarget ? { resolveMessageTarget: options.resolveMessageTarget } : {},
|
|
753
|
-
async handleAction(context) {
|
|
754
|
-
switch (context.request.action) {
|
|
755
|
-
case "send":
|
|
756
|
-
return await sendSlackMessage(context);
|
|
757
|
-
case "upload-file":
|
|
758
|
-
if (!options.uploadFile) {
|
|
759
|
-
return 'Error: Action "upload-file" is not supported on slack.';
|
|
760
|
-
}
|
|
761
|
-
if (!context.request.mediaPath?.trim()) {
|
|
762
|
-
return "Error: Slack upload-file requires media.";
|
|
763
|
-
}
|
|
764
|
-
return await sendSlackMessage(context);
|
|
765
|
-
case "react":
|
|
766
|
-
return options.react ? await reactInSlack(context) : 'Error: Action "react" is not supported on slack.';
|
|
767
|
-
case "list-custom-emojis":
|
|
768
|
-
return options.listCustomEmojis ? await listSlackCustomEmojis(context) : 'Error: Action "list-custom-emojis" is not supported on slack.';
|
|
769
|
-
case "download-file":
|
|
770
|
-
return options.downloadFile ? await options.downloadFile(context) : 'Error: Action "download-file" is not supported on slack.';
|
|
771
|
-
default:
|
|
772
|
-
return `Error: Action "${context.request.action}" is not supported on slack.`;
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
};
|
|
776
|
-
}
|
|
777
|
-
// src/channels/command-runtime-executor.ts
|
|
778
|
-
function getModelEntryRank(entry) {
|
|
779
|
-
if (entry.isDefault)
|
|
780
|
-
return 0;
|
|
781
|
-
if (entry.isFeatured)
|
|
782
|
-
return 1;
|
|
783
|
-
const effort = entry.updateArgs?.reasoning_effort;
|
|
784
|
-
if (effort === "medium")
|
|
785
|
-
return 2;
|
|
786
|
-
if (effort === "high")
|
|
787
|
-
return 3;
|
|
788
|
-
return 4;
|
|
789
|
-
}
|
|
790
|
-
function preferModelEntry(current, candidate) {
|
|
791
|
-
return getModelEntryRank(candidate) < getModelEntryRank(current) ? candidate : current;
|
|
792
|
-
}
|
|
793
|
-
function buildModelEntriesByHandle(entries) {
|
|
794
|
-
const byHandle = new Map;
|
|
795
|
-
for (const entry of entries) {
|
|
796
|
-
const current = byHandle.get(entry.handle);
|
|
797
|
-
byHandle.set(entry.handle, current ? preferModelEntry(current, entry) : entry);
|
|
798
|
-
}
|
|
799
|
-
return byHandle;
|
|
800
|
-
}
|
|
801
|
-
function makeUnknownModelEntry(handle) {
|
|
802
|
-
return {
|
|
803
|
-
id: handle,
|
|
804
|
-
handle,
|
|
805
|
-
label: handle,
|
|
806
|
-
description: ""
|
|
807
|
-
};
|
|
808
|
-
}
|
|
809
|
-
function resolveModelHandles(params) {
|
|
810
|
-
const { handles, byHandle, availableHandles } = params;
|
|
811
|
-
const seen = new Set;
|
|
812
|
-
const resolved = [];
|
|
813
|
-
for (const handle of handles) {
|
|
814
|
-
if (!handle || seen.has(handle))
|
|
815
|
-
continue;
|
|
816
|
-
seen.add(handle);
|
|
817
|
-
if (availableHandles && !availableHandles.has(handle))
|
|
818
|
-
continue;
|
|
819
|
-
resolved.push(byHandle.get(handle) ?? makeUnknownModelEntry(handle));
|
|
820
|
-
}
|
|
821
|
-
return resolved;
|
|
822
|
-
}
|
|
823
|
-
function getFallbackModelEntries(byHandle) {
|
|
824
|
-
const preferred = Array.from(byHandle.values()).filter((entry) => entry.isDefault || entry.isFeatured);
|
|
825
|
-
return preferred.length > 0 ? preferred : Array.from(byHandle.values());
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
// src/channels/slack/utils.ts
|
|
829
|
-
function isNonEmptyString4(value) {
|
|
830
|
-
return typeof value === "string" && value.length > 0;
|
|
831
|
-
}
|
|
832
|
-
function firstNonEmptyString2(...values) {
|
|
833
|
-
return values.find(isNonEmptyString4);
|
|
834
|
-
}
|
|
835
|
-
function asRecord2(value) {
|
|
836
|
-
return value && typeof value === "object" ? value : null;
|
|
837
|
-
}
|
|
838
|
-
var IGNORED_SLACK_MESSAGE_SUBTYPES2 = new Set([
|
|
839
|
-
"assistant_app_thread",
|
|
840
|
-
"channel_archive",
|
|
841
|
-
"channel_convert_to_private",
|
|
842
|
-
"channel_convert_to_public",
|
|
843
|
-
"channel_join",
|
|
844
|
-
"channel_leave",
|
|
845
|
-
"channel_name",
|
|
846
|
-
"channel_posting_permissions",
|
|
847
|
-
"channel_purpose",
|
|
848
|
-
"channel_topic",
|
|
849
|
-
"channel_unarchive",
|
|
850
|
-
"document_mention",
|
|
851
|
-
"ekm_access_denied",
|
|
852
|
-
"file_comment",
|
|
853
|
-
"group_archive",
|
|
854
|
-
"group_join",
|
|
855
|
-
"group_leave",
|
|
856
|
-
"group_name",
|
|
857
|
-
"group_purpose",
|
|
858
|
-
"group_topic",
|
|
859
|
-
"group_unarchive",
|
|
860
|
-
"pinned_item",
|
|
861
|
-
"reminder_add",
|
|
862
|
-
"unpinned_item"
|
|
863
|
-
]);
|
|
864
|
-
var WRAPPER_SLACK_MESSAGE_SUBTYPES2 = new Set([
|
|
865
|
-
"message_changed",
|
|
866
|
-
"message_deleted",
|
|
867
|
-
"message_replied"
|
|
868
|
-
]);
|
|
869
|
-
function getSlackActionRecord(action, body) {
|
|
870
|
-
const directAction = asRecord2(action);
|
|
871
|
-
if (directAction) {
|
|
872
|
-
return directAction;
|
|
873
|
-
}
|
|
874
|
-
const actions = asRecord2(body)?.actions;
|
|
875
|
-
return Array.isArray(actions) ? asRecord2(actions[0]) : null;
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
// src/channels/slack/model-picker-blocks.ts
|
|
879
|
-
var SLACK_MODEL_PICKER_OPTION_LIMIT = 100;
|
|
880
|
-
var SLACK_MODEL_PICKER_GROUP_LIMIT = 100;
|
|
881
|
-
var SLACK_MODEL_OPTION_TEXT_LIMIT = 75;
|
|
882
|
-
var SLACK_MODEL_OPTION_VALUE_LIMIT = 150;
|
|
883
|
-
var SLACK_MODEL_SELECT_ACTION_ID = "letta_channel_model_select";
|
|
884
|
-
function resolveSlackSelectedModel(action, body) {
|
|
885
|
-
const actionRecord = getSlackActionRecord(action, body);
|
|
886
|
-
const selectedOption = asRecord2(actionRecord?.selected_option);
|
|
887
|
-
return firstNonEmptyString2(selectedOption?.value, actionRecord?.value) ?? null;
|
|
888
|
-
}
|
|
889
|
-
function escapeSlackMrkdwn(text) {
|
|
890
|
-
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
891
|
-
}
|
|
892
|
-
function truncateSlackPlainText(text, limit) {
|
|
893
|
-
if (text.length <= limit) {
|
|
894
|
-
return text;
|
|
895
|
-
}
|
|
896
|
-
return `${text.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
|
|
897
|
-
}
|
|
898
|
-
function getSlackModelOptionValue(entry) {
|
|
899
|
-
const candidates = [entry.id, entry.handle].filter((value) => typeof value === "string" && value.length > 0);
|
|
900
|
-
return candidates.find((value) => value.length <= SLACK_MODEL_OPTION_VALUE_LIMIT) ?? null;
|
|
901
|
-
}
|
|
902
|
-
function buildSlackModelOption(entry) {
|
|
903
|
-
const value = getSlackModelOptionValue(entry);
|
|
904
|
-
if (!value) {
|
|
905
|
-
return null;
|
|
906
|
-
}
|
|
907
|
-
const labelText = entry.handle === entry.label ? entry.label : `${entry.label} - ${entry.handle}`;
|
|
908
|
-
const option = {
|
|
909
|
-
text: {
|
|
910
|
-
type: "plain_text",
|
|
911
|
-
text: truncateSlackPlainText(labelText, SLACK_MODEL_OPTION_TEXT_LIMIT),
|
|
912
|
-
emoji: true
|
|
913
|
-
},
|
|
914
|
-
value
|
|
915
|
-
};
|
|
916
|
-
if (entry.description) {
|
|
917
|
-
option.description = {
|
|
918
|
-
type: "plain_text",
|
|
919
|
-
text: truncateSlackPlainText(entry.description, SLACK_MODEL_OPTION_TEXT_LIMIT),
|
|
920
|
-
emoji: true
|
|
921
|
-
};
|
|
922
|
-
}
|
|
923
|
-
return option;
|
|
924
|
-
}
|
|
925
|
-
function buildSlackModelPickerBlocks(params) {
|
|
926
|
-
const entries = params.entries;
|
|
927
|
-
const byHandle = buildModelEntriesByHandle(entries);
|
|
928
|
-
const availableHandleList = Array.isArray(params.availableHandles) ? params.availableHandles : null;
|
|
929
|
-
const availableSet = availableHandleList ? new Set(availableHandleList) : null;
|
|
930
|
-
const recentEntries = resolveModelHandles({
|
|
931
|
-
handles: params.recentHandles ?? [],
|
|
932
|
-
byHandle,
|
|
933
|
-
availableHandles: availableSet
|
|
934
|
-
});
|
|
935
|
-
const availableEntries = availableHandleList ? resolveModelHandles({ handles: availableHandleList, byHandle }) : getFallbackModelEntries(byHandle);
|
|
936
|
-
const optionEntries = [...recentEntries, ...availableEntries];
|
|
937
|
-
const options = [];
|
|
938
|
-
const seenValues = new Set;
|
|
939
|
-
for (const entry of optionEntries) {
|
|
940
|
-
const option = buildSlackModelOption(entry);
|
|
941
|
-
if (!option || seenValues.has(option.value)) {
|
|
942
|
-
continue;
|
|
943
|
-
}
|
|
944
|
-
seenValues.add(option.value);
|
|
945
|
-
options.push(option);
|
|
946
|
-
if (options.length >= SLACK_MODEL_PICKER_OPTION_LIMIT * SLACK_MODEL_PICKER_GROUP_LIMIT) {
|
|
947
|
-
break;
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
if (options.length === 0) {
|
|
951
|
-
return;
|
|
952
|
-
}
|
|
953
|
-
const currentScope = params.current.scope === "agent" ? "agent" : "conversation";
|
|
954
|
-
const currentHandleText = params.current.modelHandle ? `
|
|
955
|
-
Handle: ${escapeSlackMrkdwn(params.current.modelHandle)}` : "";
|
|
956
|
-
const currentHandle = params.current.modelHandle;
|
|
957
|
-
const initialOption = options.find((option) => {
|
|
958
|
-
const entry = optionEntries.find((candidate) => candidate.id === option.value || candidate.handle === option.value);
|
|
959
|
-
return currentHandle ? entry?.handle === currentHandle || option.value === currentHandle : false;
|
|
960
|
-
});
|
|
961
|
-
return [
|
|
962
|
-
{
|
|
963
|
-
type: "section",
|
|
964
|
-
text: {
|
|
965
|
-
type: "mrkdwn",
|
|
966
|
-
text: `*Current ${currentScope} model:* ${escapeSlackMrkdwn(params.current.modelLabel)}${currentHandleText}`
|
|
967
|
-
}
|
|
968
|
-
},
|
|
969
|
-
{
|
|
970
|
-
type: "section",
|
|
971
|
-
text: {
|
|
972
|
-
type: "mrkdwn",
|
|
973
|
-
text: "Choose a model for this routed conversation:"
|
|
974
|
-
}
|
|
975
|
-
},
|
|
976
|
-
{
|
|
977
|
-
type: "actions",
|
|
978
|
-
elements: [
|
|
979
|
-
{
|
|
980
|
-
type: "static_select",
|
|
981
|
-
action_id: SLACK_MODEL_SELECT_ACTION_ID,
|
|
982
|
-
placeholder: {
|
|
983
|
-
type: "plain_text",
|
|
984
|
-
text: "Select a model",
|
|
985
|
-
emoji: true
|
|
986
|
-
},
|
|
987
|
-
...options.length <= SLACK_MODEL_PICKER_OPTION_LIMIT ? { options } : {
|
|
988
|
-
option_groups: Array.from({
|
|
989
|
-
length: Math.ceil(options.length / SLACK_MODEL_PICKER_OPTION_LIMIT)
|
|
990
|
-
}, (_, index) => {
|
|
991
|
-
const start = index * SLACK_MODEL_PICKER_OPTION_LIMIT;
|
|
992
|
-
const end = Math.min(start + SLACK_MODEL_PICKER_OPTION_LIMIT, options.length);
|
|
993
|
-
return {
|
|
994
|
-
label: {
|
|
995
|
-
type: "plain_text",
|
|
996
|
-
text: `Models ${start + 1}–${end}`
|
|
997
|
-
},
|
|
998
|
-
options: options.slice(start, end)
|
|
999
|
-
};
|
|
1000
|
-
})
|
|
1001
|
-
},
|
|
1002
|
-
...initialOption ? { initial_option: initialOption } : {}
|
|
1003
|
-
}
|
|
1004
|
-
]
|
|
1005
|
-
},
|
|
1006
|
-
{
|
|
1007
|
-
type: "context",
|
|
1008
|
-
elements: [
|
|
1009
|
-
{
|
|
1010
|
-
type: "mrkdwn",
|
|
1011
|
-
text: "Need another handle? Mention the app with `@agent /model <handle-or-id>`."
|
|
1012
|
-
}
|
|
1013
|
-
]
|
|
1014
|
-
}
|
|
1015
|
-
];
|
|
1016
|
-
}
|
|
1017
|
-
// src/agent/agent-id.ts
|
|
1018
|
-
function isLocalAgentId(agentId) {
|
|
1019
|
-
return agentId.startsWith("agent-local-");
|
|
1020
|
-
}
|
|
1021
|
-
|
|
1022
|
-
// src/utils/conversation-busy-error.ts
|
|
1023
|
-
var CONVERSATION_BUSY_ERROR_PATTERNS = [
|
|
1024
|
-
/another request is (?:currently )?(?:being )?processed/i,
|
|
1025
|
-
/currently being processed for this conversation/i,
|
|
1026
|
-
/busy with another active run/i,
|
|
1027
|
-
/already processing for this conversation/i,
|
|
1028
|
-
/turn still running/i
|
|
1029
|
-
];
|
|
1030
|
-
var CONVERSATION_BUSY_TITLE = "Turn still running";
|
|
1031
|
-
function isConversationBusyErrorText(errorText) {
|
|
1032
|
-
if (!errorText)
|
|
1033
|
-
return false;
|
|
1034
|
-
return CONVERSATION_BUSY_ERROR_PATTERNS.some((pattern) => pattern.test(errorText));
|
|
1035
|
-
}
|
|
1036
|
-
function buildConversationBusyErrorBody(automaticRetry) {
|
|
1037
|
-
return automaticRetry ? "Another request is already processing for this conversation. I’ll wait for it to finish and retry automatically." : "Another request is already processing for this conversation. Please wait for it to finish, then try again.";
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
// src/channels/lifecycle-error.ts
|
|
1041
|
-
var RAW_LOOP_ERROR_PATTERN = /^Unexpected stop reason:\s*error$/i;
|
|
1042
|
-
var APP_CHAT_URL_PATTERN = /https:\/\/app\.letta\.com\/chat\/\S+/i;
|
|
1043
|
-
var ESCAPE_CHARACTER = String.fromCharCode(27);
|
|
1044
|
-
var OSC8_PREFIX = `${ESCAPE_CHARACTER}]8;;`;
|
|
1045
|
-
var OSC8_TERMINATOR = `${ESCAPE_CHARACTER}\\`;
|
|
1046
|
-
var APPROVAL_PENDING_ERROR_PATTERNS = [
|
|
1047
|
-
/waiting for approval/i,
|
|
1048
|
-
/pending request before continuing/i,
|
|
1049
|
-
/approve or deny the pending request/i
|
|
1050
|
-
];
|
|
1051
|
-
var DATABASE_LOCK_TIMEOUT_PATTERN = /\bcancel(?:l)?ing statement due to lock timeout\b/i;
|
|
1052
|
-
var POSTGRES_LOCK_NOT_AVAILABLE_CODE_PATTERN = /\b55P03\b/i;
|
|
1053
|
-
var POSTGRES_LOCK_NOT_AVAILABLE_SQLSTATE_PATTERN = /\b(?:sqlstate|pgcode)\s*[:=]?\s*["']?55P03\b/i;
|
|
1054
|
-
var POSTGRES_LOCK_NOT_AVAILABLE_CONTEXT_PATTERN = /\b(?:postgres(?:ql)?|psycopg|sqlalchemy|lock[_ -]?not[_ -]?available|lock timeout)\b/i;
|
|
1055
|
-
var RUN_ID_PATTERNS = [
|
|
1056
|
-
/"run_id"\s*:\s*"([^"\\]+)"/i,
|
|
1057
|
-
/\brun[_\s-]?id\b["']?\s*[:=]\s*["']?([A-Za-z0-9_-]+)/i,
|
|
1058
|
-
/\(run:\s*([A-Za-z0-9_-]+)\)/i
|
|
1059
|
-
];
|
|
1060
|
-
var CHANNEL_LIFECYCLE_FALLBACK_ERROR_MESSAGE = "Something went wrong while processing that message. Please try again.";
|
|
1061
|
-
var CHANNEL_LIFECYCLE_APPROVAL_PENDING_MESSAGE = "The agent is still waiting on a tool approval from an earlier turn. Please approve or deny that pending request, then send your message again.";
|
|
1062
|
-
var CHANNEL_LIFECYCLE_TRANSIENT_ERROR_MESSAGE = "A temporary error interrupted this turn. Please try again.";
|
|
1063
|
-
var CHANNEL_LIFECYCLE_CONVERSATION_BUSY_TITLE = CONVERSATION_BUSY_TITLE;
|
|
1064
|
-
function stripTrailingRunIdPunctuation(runId) {
|
|
1065
|
-
return runId.replace(/[)"'.,;]+$/g, "");
|
|
1066
|
-
}
|
|
1067
|
-
function extractChannelLifecycleRunId(errorText) {
|
|
1068
|
-
if (!errorText)
|
|
1069
|
-
return;
|
|
1070
|
-
for (const pattern of RUN_ID_PATTERNS) {
|
|
1071
|
-
const match = errorText.match(pattern);
|
|
1072
|
-
const runId = match?.[1]?.trim();
|
|
1073
|
-
if (runId) {
|
|
1074
|
-
return stripTrailingRunIdPunctuation(runId);
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
return;
|
|
1078
|
-
}
|
|
1079
|
-
function stripOsc8TerminalLinks(errorText) {
|
|
1080
|
-
let output = "";
|
|
1081
|
-
let cursor = 0;
|
|
1082
|
-
while (cursor < errorText.length) {
|
|
1083
|
-
const linkStart = errorText.indexOf(OSC8_PREFIX, cursor);
|
|
1084
|
-
if (linkStart === -1) {
|
|
1085
|
-
output += errorText.slice(cursor);
|
|
1086
|
-
break;
|
|
1087
|
-
}
|
|
1088
|
-
const labelStart = errorText.indexOf(OSC8_TERMINATOR, linkStart + OSC8_PREFIX.length);
|
|
1089
|
-
if (labelStart === -1) {
|
|
1090
|
-
output += errorText.slice(cursor);
|
|
1091
|
-
break;
|
|
1092
|
-
}
|
|
1093
|
-
const closeStart = errorText.indexOf(OSC8_PREFIX, labelStart + OSC8_TERMINATOR.length);
|
|
1094
|
-
if (closeStart === -1) {
|
|
1095
|
-
output += errorText.slice(cursor);
|
|
1096
|
-
break;
|
|
1097
|
-
}
|
|
1098
|
-
const closeEnd = errorText.indexOf(OSC8_TERMINATOR, closeStart + OSC8_PREFIX.length);
|
|
1099
|
-
if (closeEnd === -1) {
|
|
1100
|
-
output += errorText.slice(cursor);
|
|
1101
|
-
break;
|
|
1102
|
-
}
|
|
1103
|
-
output += errorText.slice(cursor, linkStart);
|
|
1104
|
-
output += errorText.slice(labelStart + OSC8_TERMINATOR.length, closeStart);
|
|
1105
|
-
cursor = closeEnd + OSC8_TERMINATOR.length;
|
|
1106
|
-
}
|
|
1107
|
-
return output;
|
|
1108
|
-
}
|
|
1109
|
-
function sanitizeChannelLifecycleErrorText(errorText) {
|
|
1110
|
-
if (!errorText)
|
|
1111
|
-
return "";
|
|
1112
|
-
const withoutTerminalLinks = stripOsc8TerminalLinks(errorText);
|
|
1113
|
-
return withoutTerminalLinks.split(`
|
|
1114
|
-
`).filter((line) => {
|
|
1115
|
-
const trimmed = line.trim();
|
|
1116
|
-
if (/^View agent:/i.test(trimmed))
|
|
1117
|
-
return false;
|
|
1118
|
-
if (APP_CHAT_URL_PATTERN.test(trimmed))
|
|
1119
|
-
return false;
|
|
1120
|
-
return true;
|
|
1121
|
-
}).join(`
|
|
1122
|
-
`).replace(/[ \t]+\n/g, `
|
|
1123
|
-
`).trim();
|
|
1124
|
-
}
|
|
1125
|
-
function truncateLifecycleMessage(text, maxLength) {
|
|
1126
|
-
if (text.length <= maxLength)
|
|
1127
|
-
return text;
|
|
1128
|
-
return `${text.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
|
|
1129
|
-
}
|
|
1130
|
-
function isDatabaseLockErrorText(errorText) {
|
|
1131
|
-
return DATABASE_LOCK_TIMEOUT_PATTERN.test(errorText) || POSTGRES_LOCK_NOT_AVAILABLE_SQLSTATE_PATTERN.test(errorText) || POSTGRES_LOCK_NOT_AVAILABLE_CODE_PATTERN.test(errorText) && POSTGRES_LOCK_NOT_AVAILABLE_CONTEXT_PATTERN.test(errorText);
|
|
1132
|
-
}
|
|
1133
|
-
function getChannelLifecycleErrorDisplay(errorText, options = {}) {
|
|
1134
|
-
const normalized = sanitizeChannelLifecycleErrorText(errorText);
|
|
1135
|
-
const optionsRunId = options.runId?.trim();
|
|
1136
|
-
const runId = optionsRunId || extractChannelLifecycleRunId(errorText);
|
|
1137
|
-
if (!normalized || RAW_LOOP_ERROR_PATTERN.test(normalized)) {
|
|
1138
|
-
return {
|
|
1139
|
-
kind: "generic",
|
|
1140
|
-
title: "Turn failed",
|
|
1141
|
-
body: CHANNEL_LIFECYCLE_FALLBACK_ERROR_MESSAGE,
|
|
1142
|
-
runId
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
if (isDatabaseLockErrorText(normalized)) {
|
|
1146
|
-
return {
|
|
1147
|
-
kind: "database_lock_timeout",
|
|
1148
|
-
title: "Turn failed",
|
|
1149
|
-
body: CHANNEL_LIFECYCLE_TRANSIENT_ERROR_MESSAGE,
|
|
1150
|
-
runId
|
|
1151
|
-
};
|
|
1152
|
-
}
|
|
1153
|
-
if (isConversationBusyErrorText(normalized)) {
|
|
1154
|
-
return {
|
|
1155
|
-
kind: "conversation_busy",
|
|
1156
|
-
title: CHANNEL_LIFECYCLE_CONVERSATION_BUSY_TITLE,
|
|
1157
|
-
body: buildConversationBusyErrorBody(options.automaticRetry ?? false),
|
|
1158
|
-
runId
|
|
1159
|
-
};
|
|
1160
|
-
}
|
|
1161
|
-
if (APPROVAL_PENDING_ERROR_PATTERNS.some((pattern) => pattern.test(normalized))) {
|
|
1162
|
-
return {
|
|
1163
|
-
kind: "approval_pending",
|
|
1164
|
-
title: "Turn failed",
|
|
1165
|
-
body: CHANNEL_LIFECYCLE_APPROVAL_PENDING_MESSAGE,
|
|
1166
|
-
runId
|
|
1167
|
-
};
|
|
1168
|
-
}
|
|
1169
|
-
return {
|
|
1170
|
-
kind: "generic",
|
|
1171
|
-
title: "Turn failed",
|
|
1172
|
-
body: normalized,
|
|
1173
|
-
runId
|
|
1174
|
-
};
|
|
1175
|
-
}
|
|
1176
|
-
function formatChannelLifecycleErrorMessage(errorText, options = {}) {
|
|
1177
|
-
const display = getChannelLifecycleErrorDisplay(errorText, options);
|
|
1178
|
-
const maxLength = options.maxLength ?? Number.POSITIVE_INFINITY;
|
|
1179
|
-
const body = truncateLifecycleMessage(display.body, maxLength);
|
|
1180
|
-
if (display.kind === "conversation_busy") {
|
|
1181
|
-
const lines2 = [display.title, body];
|
|
1182
|
-
if (display.runId) {
|
|
1183
|
-
lines2.push("", `Run ID: ${display.runId}`);
|
|
1184
|
-
}
|
|
1185
|
-
return lines2.join(`
|
|
1186
|
-
`);
|
|
1187
|
-
}
|
|
1188
|
-
if (display.kind === "database_lock_timeout") {
|
|
1189
|
-
const lines2 = [`${display.title}:`, body];
|
|
1190
|
-
if (display.runId) {
|
|
1191
|
-
lines2.push("", `Run ID: ${display.runId}`);
|
|
1192
|
-
}
|
|
1193
|
-
return lines2.join(`
|
|
1194
|
-
`);
|
|
1195
|
-
}
|
|
1196
|
-
if (options.codeBlock) {
|
|
1197
|
-
const escaped = body.replace(/```/g, "```");
|
|
1198
|
-
const lines2 = [`${display.title}:`, "```", escaped, "```"];
|
|
1199
|
-
if (display.runId) {
|
|
1200
|
-
lines2.push("", `Run ID: ${display.runId}`);
|
|
1201
|
-
}
|
|
1202
|
-
return lines2.join(`
|
|
1203
|
-
`);
|
|
1204
|
-
}
|
|
1205
|
-
const lines = [`${display.title}:`, body];
|
|
1206
|
-
if (display.runId) {
|
|
1207
|
-
lines.push("", `Run ID: ${display.runId}`);
|
|
1208
|
-
}
|
|
1209
|
-
return lines.join(`
|
|
1210
|
-
`);
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
// src/channels/progress-formatting.ts
|
|
1214
|
-
var ESCAPE_CODE = String.fromCharCode(27);
|
|
1215
|
-
var ANSI_ESCAPE_RE = new RegExp(`${ESCAPE_CODE}\\[[0-9;?]*[ -/]*[@-~]`, "g");
|
|
1216
|
-
var SECRET_ASSIGNMENT_RE = /\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|API[_-]?KEY|ACCESS[_-]?KEY)[A-Z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/gi;
|
|
1217
|
-
var SECRET_JSON_RE = /(["']?(?:token|secret|password|api[_-]?key|access[_-]?key)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|\S+)/gi;
|
|
1218
|
-
function truncateChannelProgressText(value, maxLength, marker = "...") {
|
|
1219
|
-
if (value.length <= maxLength) {
|
|
1220
|
-
return value;
|
|
1221
|
-
}
|
|
1222
|
-
if (maxLength <= marker.length) {
|
|
1223
|
-
return marker.slice(0, Math.max(0, maxLength));
|
|
1224
|
-
}
|
|
1225
|
-
return `${value.slice(0, maxLength - marker.length).trimEnd()}${marker}`;
|
|
1226
|
-
}
|
|
1227
|
-
function replaceControlCharacters(value) {
|
|
1228
|
-
let result = "";
|
|
1229
|
-
for (let index = 0;index < value.length; index += 1) {
|
|
1230
|
-
const character = value[index] ?? "";
|
|
1231
|
-
const code = character.charCodeAt(0);
|
|
1232
|
-
result += code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31 || code === 127 ? " " : character;
|
|
1233
|
-
}
|
|
1234
|
-
return result;
|
|
1235
|
-
}
|
|
1236
|
-
function sanitizeChannelProgressCore(value) {
|
|
1237
|
-
const raw = typeof value === "string" ? value : String(value ?? "");
|
|
1238
|
-
const redacted = raw.replace(ANSI_ESCAPE_RE, "").replace(SECRET_ASSIGNMENT_RE, "$1=[redacted]").replace(SECRET_JSON_RE, "$1[redacted]");
|
|
1239
|
-
return replaceControlCharacters(redacted).replace(/[\r\n\t]+/g, " ").replace(/@(?=channel|here|everyone|[A-Za-z0-9._-]+)/gi, "@").replace(/\s+/g, " ").trim();
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
// src/channels/slack/progress.ts
|
|
1243
|
-
var SLACK_ASSISTANT_STARTUP_STATUS = "is thinking...";
|
|
1244
|
-
var SLACK_ASSISTANT_WORKING_STATUS = "is working...";
|
|
1245
|
-
var SLACK_LOADING_MESSAGE_MAX = 50;
|
|
1246
|
-
function sanitizeSlackStatusText(text, maxLength) {
|
|
1247
|
-
const normalized = sanitizeChannelProgressCore(text).replace(/[<>]/g, "").replace(/&/g, "and").replace(/\s+/g, " ").trim();
|
|
1248
|
-
return truncateChannelProgressText(normalized, maxLength, "...");
|
|
1249
|
-
}
|
|
1250
|
-
function formatSlackToolNameForDisplay(toolName) {
|
|
1251
|
-
if (toolName === "Task" || toolName === "task" || toolName === "Agent") {
|
|
1252
|
-
return "Subagent";
|
|
1253
|
-
}
|
|
1254
|
-
if (toolName === "Bash" || toolName === "bash" || toolName === "exec_command") {
|
|
1255
|
-
return "Bash";
|
|
1256
|
-
}
|
|
1257
|
-
return toolName;
|
|
1258
|
-
}
|
|
1259
|
-
function resolveSlackConcreteActivity(event) {
|
|
1260
|
-
if (event.kind === "command" && isNonEmptyString3(event.command)) {
|
|
1261
|
-
return sanitizeSlackStatusText(formatSlackToolNameForDisplay(event.command), SLACK_LOADING_MESSAGE_MAX);
|
|
1262
|
-
}
|
|
1263
|
-
if (event.kind !== "tool" || !isNonEmptyString3(event.toolName) || event.toolName.toLowerCase() === "messagechannel") {
|
|
1264
|
-
return null;
|
|
1265
|
-
}
|
|
1266
|
-
const descriptions = event.toolBatchTitle !== undefined ? [event.toolBatchTitle] : [event.toolTitle, event.toolDetails];
|
|
1267
|
-
for (const description of descriptions) {
|
|
1268
|
-
if (!isNonEmptyString3(description)) {
|
|
1269
|
-
continue;
|
|
1270
|
-
}
|
|
1271
|
-
const sanitized = sanitizeSlackStatusText(description, SLACK_LOADING_MESSAGE_MAX);
|
|
1272
|
-
if (sanitized) {
|
|
1273
|
-
return sanitized;
|
|
1274
|
-
}
|
|
1275
|
-
}
|
|
1276
|
-
return null;
|
|
1277
|
-
}
|
|
1278
|
-
// src/channels/slack/presentation.ts
|
|
1279
|
-
var SLACK_MARKDOWN_BLOCK_TEXT_MAX = 12000;
|
|
1280
|
-
var SLACK_LIFECYCLE_ERROR_TEXT_MAX = 3000;
|
|
1281
|
-
function buildSlackChatUrl(agentId, conversationId) {
|
|
1282
|
-
if (isLocalAgentId(agentId)) {
|
|
1283
|
-
return;
|
|
1284
|
-
}
|
|
1285
|
-
const base = `https://chat.letta.com/chat/${agentId}`;
|
|
1286
|
-
return conversationId && conversationId !== "default" ? `${base}?conversation=${conversationId}` : base;
|
|
1287
|
-
}
|
|
1288
|
-
function buildSlackChatFootnote(identity) {
|
|
1289
|
-
const chatUrl = buildSlackChatUrl(identity.agentId, identity.conversationId);
|
|
1290
|
-
return chatUrl ? `<${chatUrl}|View on web>` : "";
|
|
1291
|
-
}
|
|
1292
|
-
function buildSlackReplyBlocksWithFootnote(text, footnote) {
|
|
1293
|
-
const chunks = [];
|
|
1294
|
-
let remaining = text;
|
|
1295
|
-
while (remaining.length > 0) {
|
|
1296
|
-
if (remaining.length <= SLACK_MARKDOWN_BLOCK_TEXT_MAX) {
|
|
1297
|
-
chunks.push(remaining);
|
|
1298
|
-
break;
|
|
1299
|
-
}
|
|
1300
|
-
let cut = remaining.lastIndexOf(`
|
|
1301
|
-
`, SLACK_MARKDOWN_BLOCK_TEXT_MAX);
|
|
1302
|
-
if (cut <= 0) {
|
|
1303
|
-
cut = remaining.lastIndexOf(" ", SLACK_MARKDOWN_BLOCK_TEXT_MAX);
|
|
1304
|
-
}
|
|
1305
|
-
if (cut <= 0) {
|
|
1306
|
-
cut = SLACK_MARKDOWN_BLOCK_TEXT_MAX;
|
|
1307
|
-
}
|
|
1308
|
-
chunks.push(remaining.slice(0, cut));
|
|
1309
|
-
remaining = remaining.slice(cut);
|
|
1310
|
-
}
|
|
1311
|
-
const markdownChunks = chunks.filter((chunk) => chunk.trim().length > 0);
|
|
1312
|
-
if (markdownChunks.length === 0 || markdownChunks.length > 49) {
|
|
1313
|
-
return;
|
|
1314
|
-
}
|
|
1315
|
-
const blocks = markdownChunks.map((chunk) => ({
|
|
1316
|
-
type: "markdown",
|
|
1317
|
-
text: chunk
|
|
1318
|
-
}));
|
|
1319
|
-
blocks.push({
|
|
1320
|
-
type: "context",
|
|
1321
|
-
elements: [{ type: "mrkdwn", text: footnote }]
|
|
1322
|
-
});
|
|
1323
|
-
return blocks;
|
|
1324
|
-
}
|
|
1325
|
-
function shouldPostSlackTerminalError(stopReason) {
|
|
1326
|
-
return !["end_turn", "cancelled", "requires_approval", "tool_rule"].includes(stopReason);
|
|
1327
|
-
}
|
|
1328
|
-
function formatSlackLifecycleErrorMessage(errorText) {
|
|
1329
|
-
return formatChannelLifecycleErrorMessage(errorText, {
|
|
1330
|
-
codeBlock: true,
|
|
1331
|
-
maxLength: SLACK_LIFECYCLE_ERROR_TEXT_MAX
|
|
1332
|
-
});
|
|
1333
|
-
}
|
|
1334
|
-
// src/channels/slack/sender.ts
|
|
1335
|
-
async function sendSlackReaction(client, message) {
|
|
1336
|
-
const targetMessageId = message.targetMessageId ?? message.replyToMessageId;
|
|
1337
|
-
if (!targetMessageId) {
|
|
1338
|
-
throw new Error("Slack reactions require message_id (or reply_to_message_id) to identify the target message.");
|
|
1339
|
-
}
|
|
1340
|
-
const name = normalizeSlackReactionName(message.reaction ?? "");
|
|
1341
|
-
if (!name) {
|
|
1342
|
-
throw new Error("Slack reaction emoji cannot be empty.");
|
|
1343
|
-
}
|
|
1344
|
-
const params = {
|
|
1345
|
-
channel: message.chatId,
|
|
1346
|
-
timestamp: targetMessageId,
|
|
1347
|
-
name
|
|
1348
|
-
};
|
|
1349
|
-
if (message.removeReaction) {
|
|
1350
|
-
if (!client.removeReaction) {
|
|
1351
|
-
throw new Error("Slack sender client does not support removing reactions.");
|
|
1352
|
-
}
|
|
1353
|
-
await client.removeReaction(params);
|
|
1354
|
-
} else {
|
|
1355
|
-
if (!client.addReaction) {
|
|
1356
|
-
throw new Error("Slack sender client does not support adding reactions.");
|
|
1357
|
-
}
|
|
1358
|
-
await client.addReaction(params);
|
|
1359
|
-
}
|
|
1360
|
-
return { messageId: targetMessageId };
|
|
1361
|
-
}
|
|
1362
|
-
function buildSlackOutboundBlocks(message) {
|
|
1363
|
-
if (!message.agentId || !message.conversationId) {
|
|
1364
|
-
return;
|
|
1365
|
-
}
|
|
1366
|
-
const footnote = buildSlackChatFootnote({
|
|
1367
|
-
agentId: message.agentId,
|
|
1368
|
-
conversationId: message.conversationId
|
|
1369
|
-
});
|
|
1370
|
-
if (!footnote) {
|
|
1371
|
-
return;
|
|
1372
|
-
}
|
|
1373
|
-
return buildSlackReplyBlocksWithFootnote(message.text, footnote);
|
|
1374
|
-
}
|
|
1375
|
-
function createSlackChannelSender(params) {
|
|
1376
|
-
const { client } = params;
|
|
1377
|
-
return {
|
|
1378
|
-
async sendMessage(message) {
|
|
1379
|
-
if (message.reaction) {
|
|
1380
|
-
return await sendSlackReaction(client, message);
|
|
1381
|
-
}
|
|
1382
|
-
const threadTs = resolveSlackOutboundThreadTs({
|
|
1383
|
-
chatId: message.chatId,
|
|
1384
|
-
threadId: message.threadId,
|
|
1385
|
-
replyToMessageId: message.replyToMessageId
|
|
1386
|
-
});
|
|
1387
|
-
const blocks = buildSlackOutboundBlocks(message);
|
|
1388
|
-
return await client.postMessage({
|
|
1389
|
-
channel: message.chatId,
|
|
1390
|
-
text: message.text,
|
|
1391
|
-
...blocks ? { blocks } : {},
|
|
1392
|
-
...threadTs ? { threadTs } : {}
|
|
1393
|
-
});
|
|
1394
|
-
},
|
|
1395
|
-
async sendDirectReply(params2) {
|
|
1396
|
-
const threadTs = resolveSlackOutboundThreadTs({
|
|
1397
|
-
chatId: params2.chatId,
|
|
1398
|
-
threadId: params2.threadId,
|
|
1399
|
-
replyToMessageId: params2.replyToMessageId
|
|
1400
|
-
});
|
|
1401
|
-
await client.postMessage({
|
|
1402
|
-
channel: params2.chatId,
|
|
1403
|
-
text: params2.text,
|
|
1404
|
-
...params2.blocks ? { blocks: params2.blocks } : {},
|
|
1405
|
-
...threadTs ? { threadTs } : {}
|
|
1406
|
-
});
|
|
1407
|
-
}
|
|
1408
|
-
};
|
|
1409
|
-
}
|
|
1410
|
-
// src/channels/slack/status-controller.ts
|
|
1411
|
-
var SLACK_ASSISTANT_STATUS_KEEPALIVE_MS = 90000;
|
|
1412
|
-
function createSlackStatusController(params) {
|
|
1413
|
-
const stateByConversation = new Map;
|
|
1414
|
-
const sourceByConversation = new Map;
|
|
1415
|
-
const signatureByConversation = new Map;
|
|
1416
|
-
const revisionByConversation = new Map;
|
|
1417
|
-
const relinquishedThroughRevision = new Map;
|
|
1418
|
-
const outstandingWrites = new Map;
|
|
1419
|
-
let nextRevision = 0;
|
|
1420
|
-
function advanceRevision(key) {
|
|
1421
|
-
const revision = ++nextRevision;
|
|
1422
|
-
revisionByConversation.set(key, revision);
|
|
1423
|
-
return revision;
|
|
1424
|
-
}
|
|
1425
|
-
function currentRevision(key) {
|
|
1426
|
-
return revisionByConversation.get(key) ?? advanceRevision(key);
|
|
1427
|
-
}
|
|
1428
|
-
function ownedReplyKey(key) {
|
|
1429
|
-
const source = sourceByConversation.get(key);
|
|
1430
|
-
return source ? getLifecycleReplyKey(source) : null;
|
|
1431
|
-
}
|
|
1432
|
-
const writePromiseByConversation = new Map;
|
|
1433
|
-
const keepaliveByConversation = new Map;
|
|
1434
|
-
const clearedStaleReplyKeys = new Set;
|
|
1435
|
-
function getConversationKey(source) {
|
|
1436
|
-
return source.channel === "slack" && isNonEmptyString3(source.agentId) && isNonEmptyString3(source.conversationId) ? `${source.agentId}:${source.conversationId}` : null;
|
|
1437
|
-
}
|
|
1438
|
-
function getLifecycleReplyKey(source) {
|
|
1439
|
-
if (source.channel !== "slack" || !isNonEmptyString3(source.chatId)) {
|
|
1440
|
-
return null;
|
|
1441
|
-
}
|
|
1442
|
-
const replyToMessageId = resolveSlackProgressThreadTs(source);
|
|
1443
|
-
return isNonEmptyString3(replyToMessageId) ? `${source.chatId}:${replyToMessageId}` : null;
|
|
1444
|
-
}
|
|
1445
|
-
function getLifecycleErrorReplyKey(source) {
|
|
1446
|
-
if (source.channel !== "slack" || !isNonEmptyString3(source.chatId)) {
|
|
1447
|
-
return null;
|
|
1448
|
-
}
|
|
1449
|
-
if (source.chatType === "direct" || resolveSlackChatType(source.chatId) === "direct") {
|
|
1450
|
-
const replyToMessageId = resolveSlackSourceThreadTs(source);
|
|
1451
|
-
return isNonEmptyString3(replyToMessageId) ? `${source.chatId}:${replyToMessageId}` : `${source.chatId}:direct`;
|
|
1452
|
-
}
|
|
1453
|
-
return getLifecycleReplyKey(source);
|
|
1454
|
-
}
|
|
1455
|
-
function getUniqueSources(sources) {
|
|
1456
|
-
const seen = new Set;
|
|
1457
|
-
const unique = [];
|
|
1458
|
-
for (const source of sources) {
|
|
1459
|
-
const key = getConversationKey(source);
|
|
1460
|
-
if (!key || seen.has(key) || !getLifecycleReplyKey(source))
|
|
1461
|
-
continue;
|
|
1462
|
-
seen.add(key);
|
|
1463
|
-
unique.push(source);
|
|
1464
|
-
}
|
|
1465
|
-
return unique;
|
|
1466
|
-
}
|
|
1467
|
-
function clearKeepalive(key) {
|
|
1468
|
-
const timer = keepaliveByConversation.get(key);
|
|
1469
|
-
if (timer) {
|
|
1470
|
-
clearTimeout(timer);
|
|
1471
|
-
keepaliveByConversation.delete(key);
|
|
1472
|
-
}
|
|
1473
|
-
}
|
|
1474
|
-
async function writeStatus(source, footerText, loadingText, options = {}) {
|
|
1475
|
-
const stateKey = getConversationKey(source);
|
|
1476
|
-
const replyKey = getLifecycleReplyKey(source);
|
|
1477
|
-
const threadTs = resolveSlackProgressThreadTs(source);
|
|
1478
|
-
if (!stateKey || !replyKey || !threadTs)
|
|
1479
|
-
return false;
|
|
1480
|
-
const revision = currentRevision(stateKey);
|
|
1481
|
-
const revocationKey = JSON.stringify([stateKey, replyKey]);
|
|
1482
|
-
const canWrite = () => {
|
|
1483
|
-
const current = revisionByConversation.get(stateKey);
|
|
1484
|
-
if (current === undefined || revision <= (relinquishedThroughRevision.get(revocationKey) ?? 0))
|
|
1485
|
-
return false;
|
|
1486
|
-
const active = stateByConversation.get(stateKey)?.isThinkingActive;
|
|
1487
|
-
if (footerText) {
|
|
1488
|
-
return current === revision && Boolean(active) && ownedReplyKey(stateKey) === replyKey;
|
|
1489
|
-
}
|
|
1490
|
-
return current === revision || !active || ownedReplyKey(stateKey) !== replyKey;
|
|
1491
|
-
};
|
|
1492
|
-
const signature = `${revision}
|
|
1493
|
-
${replyKey}
|
|
1494
|
-
${footerText}
|
|
1495
|
-
${loadingText}`;
|
|
1496
|
-
if (!options.force && signatureByConversation.get(stateKey) === signature) {
|
|
1497
|
-
return true;
|
|
1498
|
-
}
|
|
1499
|
-
const writes = outstandingWrites.get(stateKey) ?? new Set;
|
|
1500
|
-
const pendingWrite = { replyKey, revision };
|
|
1501
|
-
writes.add(pendingWrite);
|
|
1502
|
-
outstandingWrites.set(stateKey, writes);
|
|
1503
|
-
try {
|
|
1504
|
-
await params.ensureApp();
|
|
1505
|
-
const slackClient = await params.ensureWriteClient();
|
|
1506
|
-
const setStatus = slackClient.assistant?.threads?.setStatus;
|
|
1507
|
-
if (!setStatus || !canWrite())
|
|
1508
|
-
return false;
|
|
1509
|
-
if (revisionByConversation.get(stateKey) === revision) {
|
|
1510
|
-
signatureByConversation.set(stateKey, signature);
|
|
1511
|
-
}
|
|
1512
|
-
const previous = writePromiseByConversation.get(stateKey) ?? Promise.resolve();
|
|
1513
|
-
const operation = previous.then(async () => {
|
|
1514
|
-
if (!canWrite()) {
|
|
1515
|
-
if (signatureByConversation.get(stateKey) === signature) {
|
|
1516
|
-
signatureByConversation.delete(stateKey);
|
|
1517
|
-
}
|
|
1518
|
-
return false;
|
|
1519
|
-
}
|
|
1520
|
-
try {
|
|
1521
|
-
await setStatus.call(slackClient.assistant?.threads, {
|
|
1522
|
-
channel_id: source.chatId,
|
|
1523
|
-
thread_ts: threadTs,
|
|
1524
|
-
status: footerText,
|
|
1525
|
-
...footerText ? { loading_messages: [loadingText] } : {}
|
|
1526
|
-
});
|
|
1527
|
-
const state = stateByConversation.get(stateKey);
|
|
1528
|
-
if (footerText && revision > (relinquishedThroughRevision.get(revocationKey) ?? 0) && state && (!state.isThinkingActive || ownedReplyKey(stateKey) !== replyKey)) {
|
|
1529
|
-
await setStatus.call(slackClient.assistant?.threads, {
|
|
1530
|
-
channel_id: source.chatId,
|
|
1531
|
-
thread_ts: threadTs,
|
|
1532
|
-
status: ""
|
|
1533
|
-
});
|
|
1534
|
-
clearedStaleReplyKeys.add(replyKey);
|
|
1535
|
-
return true;
|
|
1536
|
-
}
|
|
1537
|
-
if (footerText)
|
|
1538
|
-
clearedStaleReplyKeys.delete(replyKey);
|
|
1539
|
-
else
|
|
1540
|
-
clearedStaleReplyKeys.add(replyKey);
|
|
1541
|
-
return true;
|
|
1542
|
-
} catch (error) {
|
|
1543
|
-
if (signatureByConversation.get(stateKey) === signature) {
|
|
1544
|
-
signatureByConversation.delete(stateKey);
|
|
1545
|
-
}
|
|
1546
|
-
console.warn("[Slack] Failed to update assistant thread status:", error instanceof Error ? error.message : error);
|
|
1547
|
-
return false;
|
|
1548
|
-
}
|
|
1549
|
-
});
|
|
1550
|
-
const settled = operation.then(() => {
|
|
1551
|
-
return;
|
|
1552
|
-
});
|
|
1553
|
-
writePromiseByConversation.set(stateKey, settled);
|
|
1554
|
-
settled.then(() => {
|
|
1555
|
-
if (writePromiseByConversation.get(stateKey) === settled) {
|
|
1556
|
-
writePromiseByConversation.delete(stateKey);
|
|
1557
|
-
}
|
|
1558
|
-
});
|
|
1559
|
-
return await operation;
|
|
1560
|
-
} finally {
|
|
1561
|
-
writes.delete(pendingWrite);
|
|
1562
|
-
if (writes.size === 0 && outstandingWrites.get(stateKey) === writes)
|
|
1563
|
-
outstandingWrites.delete(stateKey);
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
function scheduleKeepalive(key) {
|
|
1567
|
-
clearKeepalive(key);
|
|
1568
|
-
const timer = setTimeout(() => {
|
|
1569
|
-
keepaliveByConversation.delete(key);
|
|
1570
|
-
(async () => {
|
|
1571
|
-
const state = stateByConversation.get(key);
|
|
1572
|
-
const source = sourceByConversation.get(key);
|
|
1573
|
-
if (!state?.isThinkingActive || !source)
|
|
1574
|
-
return;
|
|
1575
|
-
const revision = currentRevision(key);
|
|
1576
|
-
await writeStatus(source, state.typingFooterText, state.thinkingText, {
|
|
1577
|
-
force: true
|
|
1578
|
-
});
|
|
1579
|
-
if (revisionByConversation.get(key) === revision && state.isThinkingActive)
|
|
1580
|
-
scheduleKeepalive(key);
|
|
1581
|
-
})();
|
|
1582
|
-
}, SLACK_ASSISTANT_STATUS_KEEPALIVE_MS);
|
|
1583
|
-
timer.unref?.();
|
|
1584
|
-
keepaliveByConversation.set(key, timer);
|
|
1585
|
-
}
|
|
1586
|
-
async function activate(source, footerText, loadingText) {
|
|
1587
|
-
const key = getConversationKey(source);
|
|
1588
|
-
if (!key || !getLifecycleReplyKey(source))
|
|
1589
|
-
return;
|
|
1590
|
-
const state = stateByConversation.get(key) ?? {
|
|
1591
|
-
isThinkingActive: false,
|
|
1592
|
-
thinkingText: "",
|
|
1593
|
-
typingFooterText: ""
|
|
1594
|
-
};
|
|
1595
|
-
if (state.isThinkingActive && state.thinkingText === loadingText && state.typingFooterText === footerText && ownedReplyKey(key) === getLifecycleReplyKey(source)) {
|
|
1596
|
-
sourceByConversation.set(key, source);
|
|
1597
|
-
return;
|
|
1598
|
-
}
|
|
1599
|
-
const revision = advanceRevision(key);
|
|
1600
|
-
state.isThinkingActive = true;
|
|
1601
|
-
state.thinkingText = loadingText;
|
|
1602
|
-
state.typingFooterText = footerText;
|
|
1603
|
-
stateByConversation.set(key, state);
|
|
1604
|
-
sourceByConversation.set(key, source);
|
|
1605
|
-
const sent = await writeStatus(source, footerText, loadingText);
|
|
1606
|
-
if (revisionByConversation.get(key) !== revision)
|
|
1607
|
-
return;
|
|
1608
|
-
if (sent && state.isThinkingActive)
|
|
1609
|
-
scheduleKeepalive(key);
|
|
1610
|
-
else if (!sent)
|
|
1611
|
-
state.isThinkingActive = false;
|
|
1612
|
-
}
|
|
1613
|
-
function markAutoClearedByKey(key) {
|
|
1614
|
-
advanceRevision(key);
|
|
1615
|
-
clearKeepalive(key);
|
|
1616
|
-
const state = stateByConversation.get(key);
|
|
1617
|
-
if (state)
|
|
1618
|
-
state.isThinkingActive = false;
|
|
1619
|
-
signatureByConversation.delete(key);
|
|
1620
|
-
sourceByConversation.delete(key);
|
|
1621
|
-
}
|
|
1622
|
-
async function deactivate(source) {
|
|
1623
|
-
const key = getConversationKey(source);
|
|
1624
|
-
if (!key)
|
|
1625
|
-
return;
|
|
1626
|
-
if (stateByConversation.get(key)?.isThinkingActive && ownedReplyKey(key) !== getLifecycleReplyKey(source)) {
|
|
1627
|
-
await writeStatus(source, "", "", { force: true });
|
|
1628
|
-
return;
|
|
1629
|
-
}
|
|
1630
|
-
const revision = advanceRevision(key);
|
|
1631
|
-
clearKeepalive(key);
|
|
1632
|
-
const state = stateByConversation.get(key);
|
|
1633
|
-
if (state)
|
|
1634
|
-
state.isThinkingActive = false;
|
|
1635
|
-
signatureByConversation.delete(key);
|
|
1636
|
-
sourceByConversation.delete(key);
|
|
1637
|
-
await writeStatus(source, "", "", { force: true });
|
|
1638
|
-
if (revisionByConversation.get(key) !== revision)
|
|
1639
|
-
return;
|
|
1640
|
-
signatureByConversation.delete(key);
|
|
1641
|
-
stateByConversation.delete(key);
|
|
1642
|
-
}
|
|
1643
|
-
async function clearStale(source) {
|
|
1644
|
-
const key = getConversationKey(source);
|
|
1645
|
-
const replyKey = getLifecycleReplyKey(source);
|
|
1646
|
-
if (!key || !replyKey || stateByConversation.get(key)?.isThinkingActive || clearedStaleReplyKeys.has(replyKey)) {
|
|
1647
|
-
return;
|
|
1648
|
-
}
|
|
1649
|
-
const revision = currentRevision(key);
|
|
1650
|
-
await writeStatus(source, "", "", { force: true });
|
|
1651
|
-
if (revisionByConversation.get(key) === revision)
|
|
1652
|
-
signatureByConversation.delete(key);
|
|
1653
|
-
}
|
|
1654
|
-
async function refresh(source) {
|
|
1655
|
-
const key = getConversationKey(source);
|
|
1656
|
-
const state = key ? stateByConversation.get(key) : undefined;
|
|
1657
|
-
if (!key || !state?.isThinkingActive || ownedReplyKey(key) !== getLifecycleReplyKey(source))
|
|
1658
|
-
return false;
|
|
1659
|
-
const revision = currentRevision(key);
|
|
1660
|
-
await writeStatus(source, state.typingFooterText, state.thinkingText, {
|
|
1661
|
-
force: true
|
|
1662
|
-
});
|
|
1663
|
-
if (revisionByConversation.get(key) === revision && state.isThinkingActive) {
|
|
1664
|
-
scheduleKeepalive(key);
|
|
1665
|
-
}
|
|
1666
|
-
return true;
|
|
1667
|
-
}
|
|
1668
|
-
async function handleLifecycle(event) {
|
|
1669
|
-
if (event.type === "queued") {
|
|
1670
|
-
if (await refresh(event.source))
|
|
1671
|
-
return;
|
|
1672
|
-
if (event.source.showStartupStatus) {
|
|
1673
|
-
await activate(event.source, SLACK_ASSISTANT_STARTUP_STATUS, SLACK_ASSISTANT_STARTUP_STATUS);
|
|
1674
|
-
}
|
|
1675
|
-
return;
|
|
1676
|
-
}
|
|
1677
|
-
for (const source of getUniqueSources(event.sources)) {
|
|
1678
|
-
if (event.type === "processing") {
|
|
1679
|
-
await clearStale(source);
|
|
1680
|
-
} else if (event.stopReason !== "requires_approval") {
|
|
1681
|
-
const remaining = event.remainingSources?.some((other) => other.accountId === source.accountId && getConversationKey(other) === getConversationKey(source) && getLifecycleReplyKey(other) === getLifecycleReplyKey(source));
|
|
1682
|
-
if (!remaining)
|
|
1683
|
-
await deactivate(source);
|
|
1684
|
-
}
|
|
1685
|
-
}
|
|
1686
|
-
}
|
|
1687
|
-
return {
|
|
1688
|
-
handleLifecycle,
|
|
1689
|
-
getUniqueSources,
|
|
1690
|
-
getLifecycleErrorReplyKey,
|
|
1691
|
-
activate,
|
|
1692
|
-
deactivate,
|
|
1693
|
-
clearStale,
|
|
1694
|
-
relinquish(source) {
|
|
1695
|
-
const key = getConversationKey(source);
|
|
1696
|
-
const replyKey = getLifecycleReplyKey(source);
|
|
1697
|
-
if (!key || !replyKey)
|
|
1698
|
-
return;
|
|
1699
|
-
const ownsCurrent = ownedReplyKey(key) === replyKey;
|
|
1700
|
-
let cutoff = ownsCurrent ? currentRevision(key) : 0;
|
|
1701
|
-
for (const write of outstandingWrites.get(key) ?? []) {
|
|
1702
|
-
if (write.replyKey === replyKey)
|
|
1703
|
-
cutoff = Math.max(cutoff, write.revision);
|
|
1704
|
-
}
|
|
1705
|
-
if (!cutoff)
|
|
1706
|
-
return;
|
|
1707
|
-
const revocationKey = JSON.stringify([key, replyKey]);
|
|
1708
|
-
relinquishedThroughRevision.set(revocationKey, Math.max(relinquishedThroughRevision.get(revocationKey) ?? 0, cutoff));
|
|
1709
|
-
if (ownsCurrent)
|
|
1710
|
-
markAutoClearedByKey(key);
|
|
1711
|
-
},
|
|
1712
|
-
markAutoCleared(source) {
|
|
1713
|
-
const key = getConversationKey(source);
|
|
1714
|
-
if (key && ownedReplyKey(key) === getLifecycleReplyKey(source)) {
|
|
1715
|
-
markAutoClearedByKey(key);
|
|
1716
|
-
}
|
|
1717
|
-
},
|
|
1718
|
-
markAutoClearedForMessage(msg) {
|
|
1719
|
-
if (isNonEmptyString3(msg.agentId) && isNonEmptyString3(msg.conversationId)) {
|
|
1720
|
-
const key = `${msg.agentId}:${msg.conversationId}`;
|
|
1721
|
-
const anchor2 = firstNonEmptyString(msg.threadId, msg.replyToMessageId);
|
|
1722
|
-
if (anchor2 && ownedReplyKey(key) !== `${msg.chatId}:${params.resolveKnownThreadRoot(anchor2)}`)
|
|
1723
|
-
return;
|
|
1724
|
-
markAutoClearedByKey(key);
|
|
1725
|
-
return;
|
|
1726
|
-
}
|
|
1727
|
-
const anchor = firstNonEmptyString(msg.threadId, msg.replyToMessageId);
|
|
1728
|
-
if (!anchor)
|
|
1729
|
-
return;
|
|
1730
|
-
const root = params.resolveKnownThreadRoot(anchor);
|
|
1731
|
-
for (const [key, source] of sourceByConversation) {
|
|
1732
|
-
if (source.chatId === msg.chatId && resolveSlackProgressThreadTs(source) === root) {
|
|
1733
|
-
markAutoClearedByKey(key);
|
|
1734
|
-
}
|
|
1735
|
-
}
|
|
1736
|
-
},
|
|
1737
|
-
activeSources: () => Array.from(sourceByConversation.values()),
|
|
1738
|
-
clear() {
|
|
1739
|
-
for (const timer of keepaliveByConversation.values())
|
|
1740
|
-
clearTimeout(timer);
|
|
1741
|
-
stateByConversation.clear();
|
|
1742
|
-
revisionByConversation.clear();
|
|
1743
|
-
sourceByConversation.clear();
|
|
1744
|
-
signatureByConversation.clear();
|
|
1745
|
-
writePromiseByConversation.clear();
|
|
1746
|
-
keepaliveByConversation.clear();
|
|
1747
|
-
clearedStaleReplyKeys.clear();
|
|
1748
|
-
}
|
|
1749
|
-
};
|
|
1750
|
-
}
|
|
1751
|
-
export {
|
|
1752
|
-
stripSlackBotMention,
|
|
1753
|
-
slackTimestampToMillis,
|
|
1754
|
-
shouldSkipSlackMessageByLastSeen,
|
|
1755
|
-
shouldPostSlackTerminalError,
|
|
1756
|
-
shouldAcceptSlackInboundBotMessage,
|
|
1757
|
-
sanitizeSlackUserDisplayName,
|
|
1758
|
-
resolveSlackUserMentionsInMessage,
|
|
1759
|
-
resolveSlackSelectedModel,
|
|
1760
|
-
resolveSlackReactionIngressPolicy,
|
|
1761
|
-
resolveSlackOutboundThreadTs,
|
|
1762
|
-
resolveSlackMessageIngressPolicy,
|
|
1763
|
-
resolveSlackMessageFiles,
|
|
1764
|
-
resolveSlackFileMetadata,
|
|
1765
|
-
resolveSlackConcreteActivity,
|
|
1766
|
-
resolveSlackChatType,
|
|
1767
|
-
resolveSlackAppMentionIngressPolicy,
|
|
1768
|
-
normalizeSlackReactionName,
|
|
1769
|
-
isSlackBotAuthoredInboundMessage,
|
|
1770
|
-
isProcessableSlackInboundMessage,
|
|
1771
|
-
isOwnSlackBotInboundMessage,
|
|
1772
|
-
formatSlackLifecycleErrorMessage,
|
|
1773
|
-
fetchSlackFile,
|
|
1774
|
-
createSlackStatusController,
|
|
1775
|
-
createSlackMessageActionAdapter,
|
|
1776
|
-
createSlackChannelSender,
|
|
1777
|
-
collectSlackFiles,
|
|
1778
|
-
buildSlackModelPickerBlocks,
|
|
1779
|
-
SLACK_MODEL_SELECT_ACTION_ID,
|
|
1780
|
-
SLACK_ASSISTANT_WORKING_STATUS,
|
|
1781
|
-
SLACK_ASSISTANT_STARTUP_STATUS
|
|
1782
|
-
};
|
|
1783
|
-
|
|
1784
|
-
//# debugId=8BFA257B3E552D1A64756E2164756E21
|