@segmentstream/agent 0.37.0 → 0.38.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.
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- var version = "0.37.0";
7
+ var version = "0.38.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -65,7 +65,9 @@ rejection or perform actions.
65
65
  question, use the answer and continue the pending task without asking for permission again.
66
66
  - Ask only when information is missing or ambiguous. In Telegram, use
67
67
  `segmentstream__questions_ask` with the question and pending task so the session keeps its intent,
68
- member and chat/topic. An answer to a pending question is never chatter and always gets a reply.
68
+ member and chat/topic. In Slack and WhatsApp, ask the question in your reply instead; the member's
69
+ answer continues the conversation. An answer to a pending question is never chatter and always
70
+ gets a reply.
69
71
  - New messages and uploads may arrive together or while you are working. Complete or explicitly
70
72
  report the status of every request and every supplied file. A later message adds work unless
71
73
  the member explicitly cancels or replaces the earlier task. If work is interrupted or blocked,
@@ -109,9 +111,10 @@ rejection or perform actions.
109
111
  The existing `agent_chat` registry records group purpose and usage; update those only when permitted.
110
112
  - Send stored ontology documents with `segmentstream__attachments_send`: give `documentIds`
111
113
  (1 to 10 document record ids), or `{ entity, id, property? }` references for other records with
112
- file properties. The tool derives the member, Telegram chat and topic from this turn, checks
113
- the member's read access and returns each file's Telegram message id or error. It works only
114
- in production Telegram turns; each multipart request is limited to 2 MiB including overhead.
114
+ file properties. The tool derives the member and the chat (Telegram chat and topic, or Slack
115
+ conversation and thread) from this turn, checks the member's read access and returns each file's
116
+ Telegram message id or Slack file id, or its error. It works only in production Telegram and
117
+ Slack turns; each upload is limited to 2 MiB.
115
118
  When a request asks a question with documents, send the documents with that question as the
116
119
  caption (at most 1024 characters). Ask one question per message. Do not post the same question
117
120
  again after the tool already sent it; call `segmentstream__no_reply` when no further message is
@@ -17,6 +17,8 @@ export declare const MAXIMUM_INLINE_BYTES: number;
17
17
  export declare class AttachmentOwnerError extends Error {
18
18
  readonly name = "AttachmentOwnerError";
19
19
  }
20
+ /** The chat a channel stores a message's files under: `<provider>:<chat id>`. */
21
+ export declare function chatConversation(provider: string, chatId: string): string;
20
22
  /** The owner of the turn's attachments, from the session principal and the session id. */
21
23
  export declare function attachmentOwner(input: {
22
24
  readonly principal: SessionAuthContext | null;
@@ -9,20 +9,23 @@ import { detectFile, documentText } from "./attachment-formats.mjs";
9
9
  import { readSheets, typedTable } from "./attachment-tables.mjs";
10
10
  import { appOrigin } from "./environment.mjs";
11
11
  import { runtimeToken } from "./runtime-token.mjs";
12
- import { telegramConversation } from "./telegram/files.mjs";
12
+ import { conversationOf } from "./conversation.mjs";
13
13
  import { i as memberIdOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
14
14
  const MAXIMUM_TEXT_CHARACTERS = 5e4;
15
15
  const MAXIMUM_INLINE_BYTES = 5242880;
16
16
  var AttachmentOwnerError = class extends Error {
17
17
  name = "AttachmentOwnerError";
18
18
  };
19
+ function chatConversation(provider, chatId) {
20
+ return `${provider}:${chatId}`;
21
+ }
19
22
  function attachmentOwner(input) {
20
23
  const memberId = memberIdOf(input.principal);
21
- const chatId = input.principal?.attributes.chatId;
22
- if (memberId === void 0 || memberId === "" || typeof chatId !== "string" || chatId === "") throw new AttachmentOwnerError("Attachments require a workspace member in a chat with the agent.");
24
+ const conversation = conversationOf(input.principal);
25
+ if (memberId === void 0 || memberId === "" || conversation === void 0) throw new AttachmentOwnerError("Attachments require a workspace member in a chat with the agent.");
23
26
  return {
24
27
  memberId,
25
- conversation: telegramConversation(chatId),
28
+ conversation: chatConversation(conversation.provider, conversation.chatId),
26
29
  ...input.sessionId === "" ? {} : { sessionId: input.sessionId }
27
30
  };
28
31
  }
@@ -216,4 +219,4 @@ const ID_INPUT = {
216
219
  required: ["id"],
217
220
  additionalProperties: false
218
221
  };
219
- export { AttachmentOwnerError, ID_INPUT, MAXIMUM_INLINE_BYTES, MAXIMUM_TEXT_CHARACTERS, attachmentForModel, attachmentOwner, boundedResultPage, headerArgument, optionalObject, optionalString, pageInteger, readOutput, stringArgument, toolAttachments };
222
+ export { AttachmentOwnerError, ID_INPUT, MAXIMUM_INLINE_BYTES, MAXIMUM_TEXT_CHARACTERS, attachmentForModel, attachmentOwner, boundedResultPage, chatConversation, headerArgument, optionalObject, optionalString, pageInteger, readOutput, stringArgument, toolAttachments };
@@ -15,12 +15,12 @@ export declare const CONVERSATION_HEADER = "X-SegmentStream-Agent-Conversation";
15
15
  export declare const SESSION_HEADER = "X-SegmentStream-Agent-Session";
16
16
  /** The URL protocol of a file part that names a stored attachment instead of a Telegram file. */
17
17
  export declare const ATTACHMENT_URL_PROTOCOL = "segmentstream-attachment:";
18
- /** Where an attachment comes from; ontology SDK 0.53.0 accepts `sandbox`. */
19
- export type AttachmentSource = "telegram" | "sandbox";
18
+ /** Where an attachment comes from: a channel's message, or the agent's sandbox. */
19
+ export type AttachmentSource = "telegram" | "slack" | "sandbox";
20
20
  /** Who asks for attachment access, from the turn: the member, chat and agent session. */
21
21
  export interface AttachmentOwner {
22
22
  readonly memberId: string;
23
- /** The chat, such as `telegram:12345`. */
23
+ /** The chat, such as `telegram:12345` or `slack:C0123ABCD`. */
24
24
  readonly conversation: string;
25
25
  /** The agent session; absent while a message is received, before the turn has one. */
26
26
  readonly sessionId?: string;
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { t as agentBuild } from "../../_chunks/build-metadata-CnjDv9p8.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-C3r5IXad.mjs";
@@ -0,0 +1,56 @@
1
+ import { AttachmentError } from "./attachments.js";
2
+ import type { AttachmentOwner } from "./attachments.js";
3
+ /**
4
+ * A stored ontology file the agent sends into a chat: its record, the ontology's file grant and
5
+ * the file's bytes, read as the turn's member in the turn's chat. Telegram's and Slack's senders
6
+ * share it; each says how many bytes its destination takes.
7
+ */
8
+ /** A file record: a document by its id, or any entity's record and file property. */
9
+ export interface DocumentReference {
10
+ readonly entity: string;
11
+ readonly id: string;
12
+ readonly property?: string;
13
+ }
14
+ /** A stored file, read whole. */
15
+ export interface StoredFile {
16
+ readonly filename: string;
17
+ /** Lower case. */
18
+ readonly contentType: string;
19
+ readonly bytes: Uint8Array;
20
+ }
21
+ /** A file that could not be read, with what is known of it for the tool's answer. */
22
+ export declare class StoredFileError extends AttachmentError {
23
+ readonly filename: string;
24
+ readonly requestId: string | undefined;
25
+ constructor(input: {
26
+ readonly code: string;
27
+ readonly message: string;
28
+ readonly status?: number;
29
+ readonly filename?: string;
30
+ readonly requestId?: string;
31
+ readonly cause?: unknown;
32
+ });
33
+ }
34
+ /** Do not trust storage metadata or Content-Length to bound the downloaded bytes. */
35
+ export declare function boundedDownload(response: Response, maximum: number, tooLarge: () => Error): Promise<Uint8Array>;
36
+ /**
37
+ * Reads one stored file: its grant from the ontology, then its bytes. `limit` sees the file's type
38
+ * and size before anything is downloaded and answers the most bytes the destination takes, or
39
+ * throws to refuse it. Grant URLs, headers and signed parameters are added to `secrets`, so a
40
+ * diagnostic never shows them.
41
+ */
42
+ export declare function fetchStoredFile(input: {
43
+ readonly reference: DocumentReference;
44
+ readonly owner: AttachmentOwner;
45
+ /** The deployment's own origin, where the ontology service answers. */
46
+ readonly origin: string;
47
+ readonly token: () => Promise<string>;
48
+ readonly fetch: typeof fetch;
49
+ readonly secrets: Set<string>;
50
+ readonly limit: (file: {
51
+ readonly contentType: string;
52
+ readonly size: number;
53
+ }) => number;
54
+ /** The error a download over the limit throws. */
55
+ readonly tooLarge: () => Error;
56
+ }): Promise<StoredFile>;
@@ -0,0 +1,124 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { AttachmentError, CONVERSATION_HEADER, SESSION_HEADER } from "./attachments.mjs";
8
+ import { fetchFileGrant, transientFileStatus } from "./file-grant.mjs";
9
+ import { ACT_AS_HEADER } from "./actor.mjs";
10
+ var StoredFileError = class extends AttachmentError {
11
+ filename;
12
+ requestId;
13
+ constructor(input) {
14
+ super(input);
15
+ this.filename = input.filename ?? "";
16
+ this.requestId = input.requestId;
17
+ }
18
+ };
19
+ function isRecord(value) {
20
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21
+ }
22
+ async function boundedDownload(response, maximum, tooLarge) {
23
+ if (response.body === null) throw new AttachmentError({
24
+ code: "unsupported",
25
+ message: "The stored file is empty."
26
+ });
27
+ const reader = response.body.getReader();
28
+ const chunks = [];
29
+ let size = 0;
30
+ try {
31
+ while (true) {
32
+ const next = await reader.read();
33
+ if (next.done) break;
34
+ size += next.value.byteLength;
35
+ if (size > maximum) throw tooLarge();
36
+ chunks.push(next.value);
37
+ }
38
+ } finally {
39
+ await reader.cancel().catch(() => void 0);
40
+ }
41
+ return new Uint8Array(Buffer.concat(chunks));
42
+ }
43
+ async function fetchStoredFile(input) {
44
+ const { reference, owner } = input;
45
+ let filename = "";
46
+ let requestId;
47
+ try {
48
+ const path = [
49
+ reference.entity,
50
+ reference.id,
51
+ ...reference.property === void 0 ? [] : [reference.property]
52
+ ].map(encodeURIComponent).join("/");
53
+ const response = await fetchFileGrant(async () => input.fetch(`${input.origin}/api/ontology/agent/files/${path}`, {
54
+ headers: {
55
+ authorization: `Bearer ${await input.token()}`,
56
+ [ACT_AS_HEADER]: owner.memberId,
57
+ [CONVERSATION_HEADER]: owner.conversation,
58
+ ...owner.sessionId === void 0 ? {} : { [SESSION_HEADER]: owner.sessionId }
59
+ },
60
+ redirect: "error",
61
+ signal: AbortSignal.timeout(3e4)
62
+ }));
63
+ if (!response.ok) {
64
+ const body = await response.json().catch(() => void 0);
65
+ const upstream = isRecord(body) ? body : {};
66
+ const ref = upstream.request_id ?? upstream.requestId;
67
+ requestId = typeof ref === "string" ? ref : void 0;
68
+ const code = response.status === 404 ? "not_found" : response.status === 403 ? "forbidden" : response.status === 422 ? "unsupported" : response.status === 503 && upstream.error === "ontology_updating" ? "ontology_updating" : transientFileStatus(response.status) ? "retryable" : "unavailable";
69
+ throw new AttachmentError({
70
+ code,
71
+ message: code,
72
+ status: response.status
73
+ });
74
+ }
75
+ const answer = await response.json();
76
+ const file = isRecord(answer) ? answer.file : void 0;
77
+ const grant = isRecord(answer) ? answer.download : void 0;
78
+ if (!isRecord(file) || typeof file.filename !== "string" || typeof file.content_type !== "string" || typeof file.size !== "number" || !Number.isSafeInteger(file.size) || file.size < 0 || !isRecord(grant) || typeof grant.url !== "string" || !/^https?:\/\//.test(grant.url) || grant.method !== "GET" || !isRecord(grant.headers) || !Object.values(grant.headers).every((header) => typeof header === "string")) throw new AttachmentError({
79
+ code: "invalid_response",
80
+ message: "The ontology returned invalid file metadata."
81
+ });
82
+ filename = file.filename;
83
+ input.secrets.add(grant.url);
84
+ Object.values(grant.headers).forEach((header) => input.secrets.add(header));
85
+ new URL(grant.url).searchParams.forEach((value, name) => {
86
+ if (/signature|credential|token|key/i.test(name)) input.secrets.add(value);
87
+ });
88
+ const contentType = file.content_type.toLowerCase();
89
+ const maximum = input.limit({
90
+ contentType,
91
+ size: file.size
92
+ });
93
+ const download = await input.fetch(grant.url, {
94
+ method: "GET",
95
+ headers: grant.headers,
96
+ redirect: "error",
97
+ signal: AbortSignal.timeout(12e4)
98
+ });
99
+ if (!download.ok) throw new AttachmentError({
100
+ code: download.status === 404 ? "not_found" : "unavailable",
101
+ message: "The stored file could not be downloaded."
102
+ });
103
+ const bytes = await boundedDownload(download, maximum, input.tooLarge);
104
+ if (bytes.byteLength !== file.size) throw new AttachmentError({
105
+ code: "invalid_response",
106
+ message: "The downloaded size differs from the stored file metadata."
107
+ });
108
+ return {
109
+ filename,
110
+ contentType,
111
+ bytes
112
+ };
113
+ } catch (error) {
114
+ throw new StoredFileError({
115
+ code: error instanceof AttachmentError ? error.code : "unavailable",
116
+ message: error instanceof Error ? error.message : "The stored file could not be read.",
117
+ ...error instanceof AttachmentError && error.status !== void 0 ? { status: error.status } : {},
118
+ filename,
119
+ ...requestId === void 0 ? {} : { requestId },
120
+ cause: error
121
+ });
122
+ }
123
+ }
124
+ export { StoredFileError, boundedDownload, fetchStoredFile };
@@ -5,7 +5,9 @@ import type { GroupPolicy } from "../group-routing/policy.js";
5
5
  import { type AgentChats } from "../chats.js";
6
6
  import { type ConnectionProxy } from "../connection-proxy.js";
7
7
  import { type Environment } from "../environment.js";
8
+ import { type AgentAttachments } from "../attachments.js";
8
9
  import { type AgentIdentities, type PairedMember } from "../identities.js";
10
+ import { type SlackFileDownload } from "./files.js";
9
11
  import { type RuntimeToken } from "../runtime-token.js";
10
12
  /**
11
13
  * The SegmentStream Slack channel (`agent-design.md`, "Channels"): eve's Slack channel at
@@ -14,6 +16,7 @@ import { type RuntimeToken } from "../runtime-token.js";
14
16
  * which checks them with the app's signing secret and relays them here signed as Slack signs, with
15
17
  * the project's `SEGMENTSTREAM_AGENT_WEBHOOK_SECRET`. Every Web API call and file download goes
16
18
  * through the connection proxy, which adds the bot token: no Slack credential enters this process.
19
+ * Only a download Slack redirects to another host is fetched there directly, without a credential.
17
20
  *
18
21
  * eve does the rest: mentions and direct messages start a turn in a thread, the thread's later
19
22
  * replies continue it, and approvals and questions are buttons. Only paired members are answered;
@@ -47,6 +50,8 @@ export interface SlackChannelOptions {
47
50
  readonly identities?: AgentIdentities;
48
51
  /** The chat registry the channels are reported to; tests pass their own. */
49
52
  readonly chats?: AgentChats;
53
+ /** Where members' files are stored as attachments; tests pass their own. */
54
+ readonly attachments?: AgentAttachments;
50
55
  /** Seconds since the epoch; tests pass a fixed clock. */
51
56
  readonly now?: () => number;
52
57
  }
@@ -82,8 +87,15 @@ export declare function relayedRequestVerifier(secret: () => string | undefined,
82
87
  /**
83
88
  * eve's Slack transport carried by the connection proxy: a Web API method becomes a `web` call
84
89
  * and a file download a `files` call. The placeholder bot token never leaves this process.
90
+ *
91
+ * Redirects are followed as `fetch` follows them, which the proxy does not do for this connection:
92
+ * Slack answers a file's `url_private` with a redirect. A location under Slack's API or files is
93
+ * requested through the proxy again, which adds the bot token as before; any other HTTPS location
94
+ * is fetched directly with no credential, as `fetch` drops the authorization on a redirect to
95
+ * another origin. Every hop, wherever it answered from, is checked the same way and counts toward
96
+ * the same limit. A 303 continues with a GET and no body.
85
97
  */
86
- export declare function proxiedSlackFetch(proxy: () => ConnectionProxy): typeof fetch;
98
+ export declare function proxiedSlackFetch(proxy: () => ConnectionProxy, directFetch?: typeof fetch): typeof fetch;
87
99
  /** Builds the channel. Everything it reads from the mount is read per request. */
88
100
  export declare function segmentstreamSlack(options: SlackChannelOptions): SlackChannel;
89
101
  /**
@@ -103,7 +115,7 @@ export declare function followsThreadReply(input: {
103
115
  */
104
116
  export declare function receive(input: {
105
117
  readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit" | "slack">;
106
- readonly message: Pick<SlackMessage, "author" | "text" | "attachments">;
118
+ readonly message: Pick<SlackMessage, "author" | "text" | "attachments" | "ts">;
107
119
  readonly direct: boolean;
108
120
  readonly admission: AdmissionSettings;
109
121
  readonly identities: AgentIdentities;
@@ -112,4 +124,9 @@ export declare function receive(input: {
112
124
  readonly chats?: AgentChats;
113
125
  /** Keeps the report alive after the turn starts; without it the report is awaited. */
114
126
  readonly waitUntil?: (task: Promise<unknown>) => void;
127
+ /** Stores the message's files as the member's attachments; without it they are not stored. */
128
+ readonly files?: {
129
+ readonly attachments: () => AgentAttachments;
130
+ readonly download: SlackFileDownload;
131
+ };
115
132
  }): Promise<SlackMentionResult>;
@@ -11,9 +11,12 @@ import { withConversation } from "../conversation.mjs";
11
11
  import { redactDiagnostic } from "../diagnostics.mjs";
12
12
  import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
13
13
  import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
14
+ import { agentAttachments } from "../attachments.mjs";
14
15
  import { agentIdentities } from "../identities.mjs";
16
+ import { attachmentsContext } from "../telegram/files.mjs";
17
+ import { slackFileDownload, stageSlackFiles } from "./files.mjs";
15
18
  import { runtimeToken } from "../runtime-token.mjs";
16
- import { createHash, createHmac, timingSafeEqual } from "node:crypto";
19
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
17
20
  import { AsyncLocalStorage } from "node:async_hooks";
18
21
  import { slackChannel } from "eve/channels/slack";
19
22
  const SLACK_AUTHENTICATOR = "segmentstream-slack";
@@ -112,35 +115,77 @@ function relayedRequestVerifier(secret, now = () => Date.now() / 1e3) {
112
115
  return true;
113
116
  };
114
117
  }
115
- function proxiedSlackFetch(proxy) {
118
+ const MAXIMUM_SLACK_REDIRECTS = 5;
119
+ const REDIRECT_STATUSES = new Set([
120
+ 301,
121
+ 302,
122
+ 303,
123
+ 307,
124
+ 308
125
+ ]);
126
+ const NULL_BODY_STATUSES = new Set([
127
+ 101,
128
+ 204,
129
+ 205,
130
+ 304
131
+ ]);
132
+ function proxiedSlackFetch(proxy, directFetch = fetch) {
116
133
  return async (input, init) => {
117
134
  const request = new Request(input, init);
118
- const url = new URL(request.url);
119
135
  const headers = [...request.headers].filter(([name]) => name.toLowerCase() !== "authorization").map(([name, value]) => [name, value]);
120
- const body = new Uint8Array(await request.arrayBuffer());
121
- const method = request.method.toUpperCase();
122
- let reply;
123
- if (url.href.startsWith(SLACK_API)) reply = await proxy().request({
124
- api: "web",
125
- method,
126
- path: `/${url.href.slice(22)}`,
127
- headers,
128
- body
129
- }, request.signal);
130
- else if (url.href.startsWith(SLACK_FILES)) reply = await proxy().download({
131
- api: "files",
132
- method,
133
- path: `/${url.href.slice(24)}`,
134
- headers,
135
- body
136
- }, MAXIMUM_DOWNLOAD_BYTES, request.signal);
137
- else throw new SlackProxyRouteError("The Slack channel reaches only Slack's API and files.");
138
- return new Response(reply.body.byteLength === 0 ? null : Buffer.from(reply.body), {
139
- status: reply.status,
140
- headers: reply.headers.map(([name, value]) => [name, value])
141
- });
136
+ let url = new URL(request.url);
137
+ let method = request.method.toUpperCase();
138
+ let body = new Uint8Array(await request.arrayBuffer());
139
+ for (let redirects = 0;; redirects += 1) {
140
+ const slack = url.href.startsWith(SLACK_API) || url.href.startsWith(SLACK_FILES);
141
+ let response;
142
+ if (slack) {
143
+ const reply = url.href.startsWith(SLACK_API) ? await proxy().request({
144
+ api: "web",
145
+ method,
146
+ path: `/${url.href.slice(22)}`,
147
+ headers,
148
+ body
149
+ }, request.signal) : await proxy().download({
150
+ api: "files",
151
+ method,
152
+ path: `/${url.href.slice(24)}`,
153
+ headers,
154
+ body
155
+ }, MAXIMUM_DOWNLOAD_BYTES, request.signal);
156
+ response = new Response(reply.body.byteLength === 0 || NULL_BODY_STATUSES.has(reply.status) ? null : Buffer.from(reply.body), {
157
+ status: reply.status,
158
+ headers: reply.headers.map(([name, value]) => [name, value])
159
+ });
160
+ } else if (redirects === 0) throw new SlackProxyRouteError("The Slack channel reaches only Slack's API and files.");
161
+ else if (method !== "GET" && method !== "HEAD") throw new SlackProxyRouteError("Slack redirected a call with a body to another host.");
162
+ else response = await directFetch(url, {
163
+ method,
164
+ redirect: "manual",
165
+ signal: request.signal
166
+ });
167
+ const location = response.headers.get("location");
168
+ if (!REDIRECT_STATUSES.has(response.status) || location === null || redirects === MAXIMUM_SLACK_REDIRECTS) return response;
169
+ const next = followable(location, url);
170
+ if (next === void 0) throw new SlackProxyRouteError("Slack redirected the call to an address it cannot follow.");
171
+ await response.body?.cancel();
172
+ if (response.status === 303) {
173
+ method = "GET";
174
+ body = new Uint8Array();
175
+ }
176
+ url = next;
177
+ }
142
178
  };
143
179
  }
180
+ function followable(location, base) {
181
+ let next;
182
+ try {
183
+ next = new URL(location, base);
184
+ } catch {
185
+ return;
186
+ }
187
+ return next.protocol === "https:" && next.username === "" && next.password === "" ? next : void 0;
188
+ }
144
189
  function segmentstreamSlack(options) {
145
190
  const environment = options.environment ?? process.env;
146
191
  const token = options.token ?? runtimeToken;
@@ -186,6 +231,15 @@ function segmentstreamSlack(options) {
186
231
  });
187
232
  return lookup.status === "paired" ? slackPrincipal(lookup.member, user) : null;
188
233
  }
234
+ let store = options.attachments;
235
+ const files = {
236
+ attachments: () => store ??= agentAttachments({
237
+ origin: appOrigin(environment),
238
+ token,
239
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
240
+ }),
241
+ download: slackFileDownload(slackFetch)
242
+ };
189
243
  const admit = (direct) => (ctx, message) => {
190
244
  const waitUntil = requestWork.getStore();
191
245
  return receive({
@@ -196,6 +250,7 @@ function segmentstreamSlack(options) {
196
250
  identities: pairing(),
197
251
  environment,
198
252
  chats,
253
+ files,
199
254
  ...waitUntil === void 0 ? {} : { waitUntil }
200
255
  });
201
256
  };
@@ -303,13 +358,31 @@ async function receive(input) {
303
358
  if (input.waitUntil === void 0) await reported;
304
359
  else input.waitUntil(reported);
305
360
  }
306
- return turn ? { auth: withConversation(slackPrincipal(resolution.member, user), {
361
+ if (!turn) return null;
362
+ const auth = withConversation(slackPrincipal(resolution.member, user), {
307
363
  provider: "slack",
308
364
  chatId: ctx.slack.channelId,
309
365
  threadId: ctx.slack.threadTs,
310
366
  kind: input.direct ? "private" : "group",
311
367
  ...input.direct ? { peer: user } : {}
312
- }) } : null;
368
+ });
369
+ if (message.attachments.length === 0 || input.files === void 0) return { auth };
370
+ const files = await stageSlackFiles({
371
+ files: message.attachments,
372
+ channelId: ctx.slack.channelId,
373
+ messageTs: message.ts,
374
+ memberId: resolution.member.id,
375
+ attachments: input.files.attachments(),
376
+ download: input.files.download,
377
+ report: reportWithReference
378
+ });
379
+ return {
380
+ auth,
381
+ context: attachmentsContext({
382
+ files,
383
+ group: !input.direct
384
+ })
385
+ };
313
386
  case "pairing_required": {
314
387
  const text = localizedText(admission.replies.pairingRequired);
315
388
  if (text !== void 0 && ctx.edit === void 0) {
@@ -353,6 +426,15 @@ function report(operation, error) {
353
426
  error: redactDiagnostic(error, new Set())
354
427
  });
355
428
  }
429
+ function reportWithReference(operation, error) {
430
+ const reference = randomUUID();
431
+ console.error("[segmentstream] Slack delivery diagnostic", {
432
+ operation,
433
+ reference,
434
+ error: redactDiagnostic(error, new Set())
435
+ });
436
+ return reference;
437
+ }
356
438
  function digest(value) {
357
439
  return createHash("sha256").update(value, "utf8").digest();
358
440
  }
@@ -0,0 +1,43 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import { type Environment } from "../environment.js";
3
+ import { type RuntimeToken } from "../runtime-token.js";
4
+ import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
5
+ /**
6
+ * `attachments_send` in Slack: stored ontology files posted into the turn's Slack conversation,
7
+ * in its thread, with Slack's external upload: `files.getUploadURLExternal` for each file, its
8
+ * bytes posted to the address Slack answers, then one `files.completeUploadExternal` that shares
9
+ * them all in the conversation with the caption. Every call goes through the Slack connection,
10
+ * which adds the bot token and needs `files:write`; each upload carries at most the connection
11
+ * proxy's 2 MiB, as Telegram's do.
12
+ */
13
+ /** What became of one requested file. */
14
+ export interface SlackSentFile {
15
+ readonly id: string;
16
+ readonly filename: string;
17
+ /** Slack's id of the shared file. */
18
+ readonly slackFileId?: string;
19
+ readonly error?: string;
20
+ readonly detail?: string;
21
+ readonly reference?: string;
22
+ readonly status?: number;
23
+ readonly retryable?: boolean;
24
+ readonly requestId?: string;
25
+ }
26
+ type SlackSendResult = {
27
+ readonly files: ReadonlyArray<SlackSentFile>;
28
+ } | {
29
+ readonly error: string;
30
+ readonly detail: string;
31
+ readonly reference: string;
32
+ };
33
+ export declare function sendSlackAttachments(options: {
34
+ readonly input: SendAttachmentsInput;
35
+ readonly principal: SessionAuthContext | null;
36
+ readonly sessionId: string;
37
+ /** The workspace's `channels.slack.connection`. */
38
+ readonly connection: string | undefined;
39
+ readonly environment?: Environment;
40
+ readonly token?: RuntimeToken;
41
+ readonly fetch?: typeof fetch;
42
+ }): Promise<SlackSendResult>;
43
+ export {};
@@ -0,0 +1,209 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { attachmentOwner } from "../attachment-tools.mjs";
8
+ import { AttachmentError } from "../attachments.mjs";
9
+ import { MAXIMUM_PROXY_BODY_BYTES, connectionProxy } from "../connection-proxy.mjs";
10
+ import { conversationOf } from "../conversation.mjs";
11
+ import { redactDiagnostic } from "../diagnostics.mjs";
12
+ import { appOrigin, channelsEnabled, proxyEnvironment } from "../environment.mjs";
13
+ import { transientFileStatus } from "../file-grant.mjs";
14
+ import { runtimeToken } from "../runtime-token.mjs";
15
+ import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
16
+ import { confirmationLocale } from "../telegram/confirmation-text.mjs";
17
+ import { d as failureText } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
18
+ import { proxiedSlackFetch } from "./adapter.mjs";
19
+ import { randomUUID } from "node:crypto";
20
+ const SLACK_API = "https://slack.com/api/";
21
+ const PROXY_LIMIT = "The connection proxy takes at most 2 MiB per upload.";
22
+ function isRecord(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+ function refused(code, message) {
26
+ return new AttachmentError({
27
+ code,
28
+ message
29
+ });
30
+ }
31
+ function reportSlackError(operation, error, secrets) {
32
+ const reference = randomUUID();
33
+ console.error("[segmentstream] Slack delivery diagnostic", {
34
+ operation,
35
+ reference,
36
+ error: redactDiagnostic(error, secrets)
37
+ });
38
+ return reference;
39
+ }
40
+ async function sendSlackAttachments(options) {
41
+ const environment = options.environment ?? process.env;
42
+ const principal = options.principal;
43
+ const locale = confirmationLocale(principal);
44
+ const secrets = new Set();
45
+ const unavailable = (error, diagnostic) => {
46
+ const reference = reportSlackError("attachment_send_refused", {
47
+ error,
48
+ diagnostic
49
+ }, secrets);
50
+ return {
51
+ error,
52
+ detail: failureText(reference, "attachment", locale),
53
+ reference
54
+ };
55
+ };
56
+ const conversation = conversationOf(principal);
57
+ if (!channelsEnabled(environment)) return unavailable("channels_disabled", "Attachments can be sent only in production.");
58
+ if (options.connection === void 0) return unavailable("unsupported", "The Slack channel is not configured.");
59
+ if (conversation?.provider !== "slack") return unavailable("no_slack_conversation", "This turn has no Slack conversation.");
60
+ let owner;
61
+ try {
62
+ owner = attachmentOwner({
63
+ principal,
64
+ sessionId: options.sessionId
65
+ });
66
+ } catch (error) {
67
+ const reference = reportSlackError("attachment_owner_refused", error, secrets);
68
+ return {
69
+ error: "forbidden",
70
+ detail: failureText(reference, "attachment", locale),
71
+ reference
72
+ };
73
+ }
74
+ const runtimeToken$1 = options.token ?? runtimeToken;
75
+ const token = async () => {
76
+ const value = await runtimeToken$1();
77
+ secrets.add(value);
78
+ return value;
79
+ };
80
+ const fetchImpl = options.fetch ?? fetch;
81
+ const connection = options.connection;
82
+ const slack = proxiedSlackFetch(() => connectionProxy({
83
+ environment: proxyEnvironment(environment),
84
+ connection,
85
+ token,
86
+ fetch: fetchImpl
87
+ }), fetchImpl);
88
+ const call = async (method, init) => {
89
+ const response = await slack(`${SLACK_API}${method}`, {
90
+ method: "POST",
91
+ ...init
92
+ });
93
+ const answer = await response.json().catch(() => void 0);
94
+ if (!response.ok || !isRecord(answer) || answer.ok !== true) {
95
+ const code = isRecord(answer) && typeof answer.error === "string" ? answer.error : "";
96
+ throw new AttachmentError({
97
+ code: code === "missing_scope" || code === "not_in_channel" ? "forbidden" : "send_failed",
98
+ message: `Slack refused ${method}${code === "" ? "" : `: ${code}`}.`,
99
+ status: response.status
100
+ });
101
+ }
102
+ return answer;
103
+ };
104
+ const results = options.input.documentIds.map(({ id }) => ({
105
+ id,
106
+ filename: ""
107
+ }));
108
+ const uploaded = [];
109
+ for (const [index, reference] of options.input.documentIds.entries()) {
110
+ const failed = (error, operation) => {
111
+ const errorReference = reportSlackError(operation, error, secrets);
112
+ const stored = error instanceof StoredFileError ? error : void 0;
113
+ results[index] = {
114
+ id: reference.id,
115
+ filename: stored?.filename ?? results[index].filename,
116
+ error: error instanceof AttachmentError ? error.code : "send_failed",
117
+ detail: failureText(errorReference, "attachment", locale),
118
+ reference: errorReference,
119
+ ...error instanceof AttachmentError && error.status !== void 0 ? {
120
+ status: error.status,
121
+ retryable: transientFileStatus(error.status)
122
+ } : {},
123
+ ...stored?.requestId === void 0 ? {} : { requestId: stored.requestId }
124
+ };
125
+ };
126
+ let file;
127
+ try {
128
+ file = await fetchStoredFile({
129
+ reference,
130
+ owner,
131
+ origin: appOrigin(environment),
132
+ token,
133
+ fetch: fetchImpl,
134
+ secrets,
135
+ tooLarge: () => refused("too_large", PROXY_LIMIT),
136
+ limit: ({ size }) => {
137
+ if (size > 2097152) throw refused("too_large", PROXY_LIMIT);
138
+ if (size === 0) throw refused("unsupported", "Slack cannot share an empty file.");
139
+ return MAXIMUM_PROXY_BODY_BYTES;
140
+ }
141
+ });
142
+ } catch (error) {
143
+ failed(error, "stored_attachment_fetch_failed");
144
+ continue;
145
+ }
146
+ results[index] = {
147
+ id: reference.id,
148
+ filename: file.filename
149
+ };
150
+ try {
151
+ const ticket = await call("files.getUploadURLExternal", {
152
+ headers: { "content-type": "application/x-www-form-urlencoded" },
153
+ body: new URLSearchParams({
154
+ filename: file.filename,
155
+ length: String(file.bytes.byteLength)
156
+ }).toString()
157
+ });
158
+ if (typeof ticket.upload_url !== "string" || typeof ticket.file_id !== "string") throw refused("invalid_response", "Slack answered no upload address.");
159
+ secrets.add(ticket.upload_url);
160
+ const upload = await slack(ticket.upload_url, {
161
+ method: "POST",
162
+ headers: { "content-type": file.contentType },
163
+ body: Buffer.from(file.bytes)
164
+ });
165
+ await upload.body?.cancel();
166
+ if (!upload.ok) throw new AttachmentError({
167
+ code: "send_failed",
168
+ message: "Slack refused the file's bytes.",
169
+ status: upload.status
170
+ });
171
+ uploaded.push({
172
+ index,
173
+ slackId: ticket.file_id
174
+ });
175
+ } catch (error) {
176
+ failed(error, "attachment_upload_failed");
177
+ }
178
+ }
179
+ if (uploaded.length === 0) return { files: results };
180
+ try {
181
+ const shared = await call("files.completeUploadExternal", {
182
+ headers: { "content-type": "application/json; charset=utf-8" },
183
+ body: JSON.stringify({
184
+ files: uploaded.map(({ index, slackId }) => ({
185
+ id: slackId,
186
+ title: results[index].filename
187
+ })),
188
+ channel_id: conversation.chatId,
189
+ ...conversation.threadId === "" ? {} : { thread_ts: conversation.threadId },
190
+ ...options.input.caption === void 0 ? {} : { initial_comment: options.input.caption }
191
+ })
192
+ });
193
+ if (!Array.isArray(shared.files)) throw refused("invalid_response", "Slack did not answer the shared files.");
194
+ for (const { index, slackId } of uploaded) results[index] = {
195
+ ...results[index],
196
+ slackFileId: slackId
197
+ };
198
+ } catch (error) {
199
+ const reference = reportSlackError("attachment_share_failed", error, secrets);
200
+ for (const { index } of uploaded) results[index] = {
201
+ ...results[index],
202
+ error: error instanceof AttachmentError ? error.code : "send_failed",
203
+ detail: failureText(reference, "attachment", locale),
204
+ reference
205
+ };
206
+ }
207
+ return { files: results };
208
+ }
209
+ export { sendSlackAttachments };
@@ -0,0 +1,38 @@
1
+ import type { SlackMessage } from "eve/channels/slack";
2
+ import { type AgentAttachments } from "../attachments.js";
3
+ import type { StagedFile } from "../telegram/inbound-request.js";
4
+ /**
5
+ * Files a member sends the agent in Slack (`docs/agent.md`, "Attachments"), stored as Telegram's
6
+ * are: before the turn starts, each file is downloaded through the Slack connection and stored once
7
+ * as a temporary attachment of the member, in this channel, for 24 hours. The turn learns each
8
+ * attachment's id from an `<attachments>` block, so the model can read, discard or promote it with
9
+ * the attachment tools; eve still hands the model the file itself. A file that cannot be stored
10
+ * is named in the block with the reason, never dropped silently.
11
+ */
12
+ /** A Slack file as eve parses it from the message. */
13
+ type SlackFile = SlackMessage["attachments"][number];
14
+ /**
15
+ * Downloads a Slack file's `url_private`, at most `maxBytes`. `contentType` is the type Slack
16
+ * gave the file, so that an HTML file is told from Slack's sign-in page.
17
+ */
18
+ export type SlackFileDownload = (url: string, maxBytes: number, contentType: string) => Promise<Uint8Array>;
19
+ /** Stores the message's files one after another, so that only one file is held at a time. */
20
+ export declare function stageSlackFiles(input: {
21
+ readonly files: ReadonlyArray<SlackFile>;
22
+ /** The channel, direct message or group direct message the files were sent in. */
23
+ readonly channelId: string;
24
+ /** The message's `ts`, which with the file's position identifies it on redelivery. */
25
+ readonly messageTs: string;
26
+ readonly memberId: string;
27
+ readonly attachments: AgentAttachments;
28
+ readonly download: SlackFileDownload;
29
+ /** Records a failure for operators; answers the reference the model may quote. */
30
+ readonly report: (operation: string, error: unknown) => string;
31
+ }): Promise<ReadonlyMap<string, StagedFile>>;
32
+ /**
33
+ * Downloads a Slack file through the channel's transport, which follows Slack's redirect through
34
+ * the connection proxy. A web page answered for a file that is not one, such as Slack's sign-in
35
+ * page for a token without `files:read`, is refused rather than stored; an HTML file is kept.
36
+ */
37
+ export declare function slackFileDownload(transport: typeof fetch): SlackFileDownload;
38
+ export {};
@@ -0,0 +1,94 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { chatConversation } from "../attachment-tools.mjs";
8
+ import { MAXIMUM_ATTACHMENT_BYTES, attachmentUrl } from "../attachments.mjs";
9
+ function megabytes(bytes) {
10
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
11
+ }
12
+ async function stageSlackFiles(input) {
13
+ const conversation = chatConversation("slack", input.channelId);
14
+ const staged = new Map();
15
+ for (const [index, file] of input.files.entries()) {
16
+ const key = file.id === "" ? `file-${index}` : file.id;
17
+ const filename = file.name?.trim() || `file-${index}`;
18
+ const contentType = file.mimeType ?? "application/octet-stream";
19
+ if (file.size !== void 0 && file.size > MAXIMUM_ATTACHMENT_BYTES) {
20
+ staged.set(key, {
21
+ status: "refused",
22
+ filename,
23
+ reason: `it is ${megabytes(file.size)}, over the ${megabytes(MAXIMUM_ATTACHMENT_BYTES)} the agent accepts`
24
+ });
25
+ continue;
26
+ }
27
+ if (file.url === void 0) {
28
+ staged.set(key, {
29
+ status: "refused",
30
+ filename,
31
+ reason: "Slack gave no address for it"
32
+ });
33
+ continue;
34
+ }
35
+ try {
36
+ const bytes = await input.download(file.url, MAXIMUM_ATTACHMENT_BYTES, contentType);
37
+ const attachment = await input.attachments.receive({
38
+ memberId: input.memberId,
39
+ conversation
40
+ }, {
41
+ bytes,
42
+ filename,
43
+ contentType,
44
+ sourceRef: `${input.channelId}:${input.messageTs}:${index}`,
45
+ source: "slack"
46
+ });
47
+ staged.set(key, {
48
+ status: "stored",
49
+ attachment,
50
+ url: attachmentUrl({
51
+ id: attachment.id,
52
+ memberId: input.memberId,
53
+ conversation
54
+ })
55
+ });
56
+ } catch (error) {
57
+ const reference = input.report("attachment_storage_failed", error);
58
+ staged.set(key, {
59
+ status: "refused",
60
+ filename,
61
+ reason: `it could not be stored (reference ${reference})`
62
+ });
63
+ }
64
+ }
65
+ return staged;
66
+ }
67
+ function slackFileDownload(transport) {
68
+ return async (url, maxBytes, contentType) => {
69
+ const response = await transport(url, { signal: AbortSignal.timeout(12e4) });
70
+ if (!response.ok) {
71
+ await response.body?.cancel();
72
+ throw new Error(`Slack answered the file download with HTTP ${response.status}.`);
73
+ }
74
+ const mediaType = (type) => type?.split(";")[0]?.trim().toLowerCase() ?? "";
75
+ if (mediaType(response.headers.get("content-type")) === "text/html" && mediaType(contentType) !== "text/html") {
76
+ await response.body?.cancel();
77
+ throw new Error("Slack answered the file download with a web page, not the file.");
78
+ }
79
+ if (response.body === null) return new Uint8Array();
80
+ const reader = response.body.getReader();
81
+ const chunks = [];
82
+ let size = 0;
83
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
84
+ size += next.value.byteLength;
85
+ if (size > maxBytes) {
86
+ await reader.cancel();
87
+ throw new Error(`The file exceeds the ${megabytes(maxBytes)} the agent accepts.`);
88
+ }
89
+ chunks.push(next.value);
90
+ }
91
+ return new Uint8Array(Buffer.concat(chunks));
92
+ };
93
+ }
94
+ export { slackFileDownload, stageSlackFiles };
@@ -10,7 +10,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback, isWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-CnjDv9p8.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-C3r5IXad.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -1,13 +1,10 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
+ import { type DocumentReference } from "../sent-files.js";
2
3
  import { type Environment } from "../environment.js";
3
4
  import { type RuntimeToken } from "../runtime-token.js";
4
5
  export declare const MAXIMUM_PHOTO_BYTES: number;
5
6
  export declare const MAXIMUM_DOCUMENT_BYTES: number;
6
- export interface DocumentReference {
7
- readonly entity: string;
8
- readonly id: string;
9
- readonly property?: string;
10
- }
7
+ export type { DocumentReference } from "../sent-files.js";
11
8
  export interface SendAttachmentsInput {
12
9
  readonly documentIds: ReadonlyArray<DocumentReference>;
13
10
  readonly caption?: string;
@@ -45,4 +42,3 @@ type SendResult = {
45
42
  };
46
43
  /** Reserve the chat before downloading, and keep every album/batch in the same queue slot. */
47
44
  export declare function sendAttachments(options: SendOptions): Promise<SendResult>;
48
- export {};
@@ -5,12 +5,12 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { attachmentOwner } from "../attachment-tools.mjs";
8
- import { AttachmentError, CONVERSATION_HEADER, SESSION_HEADER } from "../attachments.mjs";
8
+ import { AttachmentError } from "../attachments.mjs";
9
9
  import { MAXIMUM_PROXY_BODY_BYTES, connectionProxy } from "../connection-proxy.mjs";
10
10
  import { redactDiagnostic } from "../diagnostics.mjs";
11
- import { fetchFileGrant, transientFileStatus } from "../file-grant.mjs";
11
+ import { transientFileStatus } from "../file-grant.mjs";
12
+ import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
12
13
  import { appOrigin, channelsEnabled, proxyEnvironment } from "../environment.mjs";
13
- import { ACT_AS_HEADER } from "../actor.mjs";
14
14
  import { runtimeToken } from "../runtime-token.mjs";
15
15
  import "../../../_chunks/principal-BIX7T6Hh.mjs";
16
16
  import { confirmationLocale } from "./confirmation-text.mjs";
@@ -58,24 +58,6 @@ function refused(code, message) {
58
58
  });
59
59
  }
60
60
  const PROXY_LIMIT = "The multipart upload exceeds the connection proxy's 2 MiB request limit (including overhead).";
61
- async function boundedDownload(response, maximum) {
62
- if (response.body === null) throw refused("unsupported", "The stored file is empty.");
63
- const reader = response.body.getReader();
64
- const chunks = [];
65
- let size = 0;
66
- try {
67
- while (true) {
68
- const next = await reader.read();
69
- if (next.done) break;
70
- size += next.value.byteLength;
71
- if (size > maximum) throw refused("too_large", PROXY_LIMIT);
72
- chunks.push(next.value);
73
- }
74
- } finally {
75
- await reader.cancel().catch(() => void 0);
76
- }
77
- return new Uint8Array(Buffer.concat(chunks));
78
- }
79
61
  function sendAttachments(options) {
80
62
  const chatId = options.principal?.attributes.chatId;
81
63
  return typeof chatId === "string" && options.connection !== void 0 ? inTelegramSendQueue(telegramSendScope(options.environment ?? process.env, options.connection), chatId, () => sendAttachmentsInOrder(options)) : sendAttachmentsInOrder(options);
@@ -132,84 +114,47 @@ async function sendAttachmentsInOrder(options) {
132
114
  filename: ""
133
115
  }));
134
116
  const uploads = [];
135
- for (const [index, reference] of options.input.documentIds.entries()) {
136
- let filename = "";
137
- let requestId;
138
- try {
139
- const path = [
140
- reference.entity,
141
- reference.id,
142
- ...reference.property === void 0 ? [] : [reference.property]
143
- ].map(encodeURIComponent).join("/");
144
- const response = await fetchFileGrant(async () => fetchImpl(`${origin}/api/ontology/agent/files/${path}`, {
145
- headers: {
146
- authorization: `Bearer ${await token()}`,
147
- [ACT_AS_HEADER]: owner.memberId,
148
- [CONVERSATION_HEADER]: owner.conversation,
149
- ...owner.sessionId === void 0 ? {} : { [SESSION_HEADER]: owner.sessionId }
150
- },
151
- redirect: "error",
152
- signal: AbortSignal.timeout(3e4)
153
- }));
154
- if (!response.ok) {
155
- const body = await response.json().catch(() => void 0);
156
- const upstream = isRecord(body) ? body : {};
157
- const ref = upstream.request_id ?? upstream.requestId;
158
- requestId = typeof ref === "string" ? ref : void 0;
159
- const code = response.status === 404 ? "not_found" : response.status === 403 ? "forbidden" : response.status === 422 ? "unsupported" : response.status === 503 && upstream.error === "ontology_updating" ? "ontology_updating" : transientFileStatus(response.status) ? "retryable" : "unavailable";
160
- throw new AttachmentError({
161
- code,
162
- message: code,
163
- status: response.status
164
- });
117
+ for (const [index, reference] of options.input.documentIds.entries()) try {
118
+ let type = "document";
119
+ const { filename, contentType, bytes } = await fetchStoredFile({
120
+ reference,
121
+ owner,
122
+ origin,
123
+ token,
124
+ fetch: fetchImpl,
125
+ secrets,
126
+ tooLarge: () => refused("too_large", PROXY_LIMIT),
127
+ limit: ({ contentType, size }) => {
128
+ type = PHOTOS.has(contentType) ? "photo" : "document";
129
+ const maximum = type === "photo" ? MAXIMUM_PHOTO_BYTES : MAXIMUM_DOCUMENT_BYTES;
130
+ if (size > maximum) throw refused("too_large", `Telegram's ${type} limit is ${maximum / 1024 / 1024} MiB.`);
131
+ if (size > 2097152) throw refused("too_large", PROXY_LIMIT);
132
+ if (size === 0) throw refused("unsupported", "Telegram cannot send an empty file.");
133
+ return Math.min(maximum, MAXIMUM_PROXY_BODY_BYTES);
165
134
  }
166
- const answer = await response.json();
167
- const file = isRecord(answer) ? answer.file : void 0;
168
- const grant = isRecord(answer) ? answer.download : void 0;
169
- if (!isRecord(file) || typeof file.filename !== "string" || typeof file.content_type !== "string" || typeof file.size !== "number" || !Number.isSafeInteger(file.size) || file.size < 0 || !isRecord(grant) || typeof grant.url !== "string" || !/^https?:\/\//.test(grant.url) || grant.method !== "GET" || !isRecord(grant.headers) || !Object.values(grant.headers).every((header) => typeof header === "string")) throw refused("invalid_response", "The ontology returned invalid file metadata.");
170
- filename = file.filename;
171
- secrets.add(grant.url);
172
- Object.values(grant.headers).forEach((header) => secrets.add(header));
173
- new URL(grant.url).searchParams.forEach((value, name) => {
174
- if (/signature|credential|token|key/i.test(name)) secrets.add(value);
175
- });
176
- const contentType = file.content_type.toLowerCase();
177
- const type = PHOTOS.has(contentType) ? "photo" : "document";
178
- const maximum = type === "photo" ? MAXIMUM_PHOTO_BYTES : MAXIMUM_DOCUMENT_BYTES;
179
- if (file.size > maximum) throw refused("too_large", `Telegram's ${type} limit is ${maximum / 1024 / 1024} MiB.`);
180
- if (file.size > 2097152) throw refused("too_large", PROXY_LIMIT);
181
- if (file.size === 0) throw refused("unsupported", "Telegram cannot send an empty file.");
182
- const download = await fetchImpl(grant.url, {
183
- method: "GET",
184
- headers: grant.headers,
185
- redirect: "error",
186
- signal: AbortSignal.timeout(12e4)
187
- });
188
- if (!download.ok) throw refused(download.status === 404 ? "not_found" : "unavailable", "The stored file could not be downloaded.");
189
- const bytes = await boundedDownload(download, Math.min(maximum, MAXIMUM_PROXY_BODY_BYTES));
190
- if (bytes.byteLength !== file.size) throw refused("invalid_response", "The downloaded size differs from the stored file metadata.");
191
- uploads.push({
192
- index,
193
- id: reference.id,
194
- filename,
195
- type,
196
- blob: new Blob([Buffer.from(bytes)], { type: contentType })
197
- });
198
- } catch (error) {
199
- const errorId = reportTelegramError("stored_attachment_fetch_failed", error, { id: reference.id }, secrets);
200
- results[index] = {
201
- id: reference.id,
202
- filename,
203
- error: error instanceof AttachmentError ? error.code : "unavailable",
204
- detail: failureText(errorId, "attachment", locale),
205
- reference: errorId,
206
- ...error instanceof AttachmentError && error.status !== void 0 ? {
207
- status: error.status,
208
- retryable: transientFileStatus(error.status)
209
- } : {},
210
- ...requestId === void 0 ? {} : { requestId }
211
- };
212
- }
135
+ });
136
+ uploads.push({
137
+ index,
138
+ id: reference.id,
139
+ filename,
140
+ type,
141
+ blob: new Blob([Buffer.from(bytes)], { type: contentType })
142
+ });
143
+ } catch (error) {
144
+ const errorId = reportTelegramError("stored_attachment_fetch_failed", error, { id: reference.id }, secrets);
145
+ const failed = error instanceof StoredFileError ? error : void 0;
146
+ results[index] = {
147
+ id: reference.id,
148
+ filename: failed?.filename ?? "",
149
+ error: error instanceof AttachmentError ? error.code : "unavailable",
150
+ detail: failureText(errorId, "attachment", locale),
151
+ reference: errorId,
152
+ ...error instanceof AttachmentError && error.status !== void 0 ? {
153
+ status: error.status,
154
+ retryable: transientFileStatus(error.status)
155
+ } : {},
156
+ ...failed?.requestId === void 0 ? {} : { requestId: failed.requestId }
157
+ };
213
158
  }
214
159
  function multipart(files, caption) {
215
160
  const form = new FormData();
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { t as agentBuild } from "../../../_chunks/build-metadata-CnjDv9p8.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-C3r5IXad.mjs";
8
8
  import { runtimeRequestFailure } from "./runtime-request.mjs";
9
9
  import { GET } from "eve/channels";
10
10
  const HEALTH_ROUTE = "/eve/v1/telegram/health";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { d as telegramRuntimeSource, l as principalRuntimeSource, u as runtimeEnvelope } from "../../../_chunks/principal-BIX7T6Hh.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-CnjDv9p8.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-C3r5IXad.mjs";
9
9
  import { n as currentInboundRequest } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
10
10
  import { object } from "../confirmation-description.mjs";
11
11
  import { needsConfirmation } from "../confirmations.mjs";
@@ -6,12 +6,14 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
8
8
  import segmentstream from "../extension.mjs";
9
+ import { conversationOf } from "../lib/conversation.mjs";
10
+ import { sendSlackAttachments } from "../lib/slack/attachments-send.mjs";
9
11
  import { sendAttachments, sendAttachmentsInput } from "../lib/telegram/attachments-send.mjs";
10
12
  import { memberTool } from "../lib/actor.mjs";
11
13
  import { defineTool } from "eve/tools";
12
14
  const tool = defineTool({
13
15
  availableInSubagents: false,
14
- description: "Send 1 to 10 stored ontology files to this turn's Telegram chat, as the paired member. Bare ids are document record ids; use entity/id/property references for other file records. Images use sendPhoto, other files sendDocument, with compatible albums when possible. Uploads are limited to 2 MiB including multipart overhead by the connection proxy. Use the question as caption when sending documents with a question; one question per message. In groups follow the chat's purpose and never send restricted documents.",
16
+ description: "Send 1 to 10 stored ontology files to this turn's Telegram chat or Slack conversation, as the paired member. Bare ids are document record ids; use entity/id/property references for other file records. In Telegram, images use sendPhoto, other files sendDocument, with compatible albums when possible; in Slack the files are shared together in the thread, with the caption. Uploads are limited to 2 MiB by the connection proxy. Use the question as caption when sending documents with a question; one question per message. In groups follow the chat's purpose and never send restricted documents.",
15
17
  inputSchema: {
16
18
  type: "object",
17
19
  properties: {
@@ -48,12 +50,19 @@ const tool = defineTool({
48
50
  required: ["documentIds"],
49
51
  additionalProperties: false
50
52
  },
51
- label: { start: () => "Send stored attachments to Telegram" },
53
+ label: { start: () => "Send stored attachments" },
52
54
  async execute(input, ctx) {
53
- return workflowToolResult(await sendAttachments({
55
+ const principal = ctx.session.auth.current;
56
+ const options = {
54
57
  input: sendAttachmentsInput(input),
55
- principal: ctx.session.auth.current,
56
- sessionId: ctx.session.id,
58
+ principal,
59
+ sessionId: ctx.session.id
60
+ };
61
+ return workflowToolResult(conversationOf(principal)?.provider === "slack" ? await sendSlackAttachments({
62
+ ...options,
63
+ connection: segmentstream.config.channels.slack?.connection
64
+ }) : await sendAttachments({
65
+ ...options,
57
66
  connection: segmentstream.config.channels.telegram?.connection
58
67
  }), ctx);
59
68
  }
@@ -7,6 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
8
8
  import { agentTaskIdOf, agentTaskSessions } from "../lib/agent-task.mjs";
9
9
  import { stringArgument } from "../lib/attachment-tools.mjs";
10
+ import { conversationOf } from "../lib/conversation.mjs";
10
11
  import { pendingQuestions, questionKey } from "../lib/questions.mjs";
11
12
  import { i as memberIdOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
12
13
  import { defineTool } from "eve/tools";
@@ -42,6 +43,8 @@ var questions_ask_default = defineTool({
42
43
  } : task);
43
44
  return workflowToolResult({ question: text }, ctx);
44
45
  }
46
+ const conversation = conversationOf(ctx.session.auth.current);
47
+ if (conversation !== void 0 && conversation.provider !== "telegram") throw new Error(`questions_ask is unavailable in ${conversation.provider}: ask the question in your reply; the member's answer continues this conversation.`);
45
48
  const memberId = memberIdOf(ctx.session.auth.current);
46
49
  const chatId = ctx.session.auth.current?.attributes.chatId;
47
50
  if (memberId === void 0 || typeof chatId !== "string") throw new Error("A member in a chat is required.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.37.0",
3
+ "version": "0.38.0",
4
4
  "description": "Mount a SegmentStream workspace's agent on eve: the ontology as tools, acting as the member who writes, and Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -76,7 +76,7 @@
76
76
  "@chat-adapter/state-memory": "4.42.0",
77
77
  "@chat-adapter/telegram": "4.41.0",
78
78
  "@chat-adapter/whatsapp": "4.42.0",
79
- "@segmentstream/ontology": "0.93.0",
79
+ "@segmentstream/ontology": "0.94.0",
80
80
  "@vercel/oidc": "^3.8.4",
81
81
  "ai": "^7.0.137",
82
82
  "chat": "4.42.0",