@segmentstream/agent 0.37.1 → 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.
- package/dist/_chunks/{build-metadata-C0Kz75P3.mjs → build-metadata-C3r5IXad.mjs} +1 -1
- package/dist/extension/instructions.md +4 -3
- package/dist/extension/lib/attachment-tools.d.ts +2 -0
- package/dist/extension/lib/attachment-tools.mjs +8 -5
- package/dist/extension/lib/attachments.d.ts +3 -3
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/sent-files.d.ts +56 -0
- package/dist/extension/lib/sent-files.mjs +124 -0
- package/dist/extension/lib/slack/adapter.d.ts +10 -1
- package/dist/extension/lib/slack/adapter.mjs +43 -3
- package/dist/extension/lib/slack/attachments-send.d.ts +43 -0
- package/dist/extension/lib/slack/attachments-send.mjs +209 -0
- package/dist/extension/lib/slack/files.d.ts +38 -0
- package/dist/extension/lib/slack/files.mjs +94 -0
- package/dist/extension/lib/telegram/adapter.mjs +1 -1
- package/dist/extension/lib/telegram/attachments-send.d.ts +2 -6
- package/dist/extension/lib/telegram/attachments-send.mjs +43 -98
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/dist/extension/tools/attachments_send.mjs +14 -5
- package/package.json +2 -2
|
@@ -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.
|
|
7
|
+
var version = "0.38.0";
|
|
8
8
|
function agentBuild(environment = process.env) {
|
|
9
9
|
return {
|
|
10
10
|
agent: version,
|
|
@@ -111,9 +111,10 @@ rejection or perform actions.
|
|
|
111
111
|
The existing `agent_chat` registry records group purpose and usage; update those only when permitted.
|
|
112
112
|
- Send stored ontology documents with `segmentstream__attachments_send`: give `documentIds`
|
|
113
113
|
(1 to 10 document record ids), or `{ entity, id, property? }` references for other records with
|
|
114
|
-
file properties. The tool derives the member
|
|
115
|
-
the member's read access and returns each file's
|
|
116
|
-
|
|
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.
|
|
117
118
|
When a request asks a question with documents, send the documents with that question as the
|
|
118
119
|
caption (at most 1024 characters). Ask one question per message. Do not post the same question
|
|
119
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 {
|
|
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
|
|
22
|
-
if (memberId === void 0 || memberId === "" ||
|
|
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:
|
|
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
|
|
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-
|
|
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
|
|
@@ -48,6 +50,8 @@ export interface SlackChannelOptions {
|
|
|
48
50
|
readonly identities?: AgentIdentities;
|
|
49
51
|
/** The chat registry the channels are reported to; tests pass their own. */
|
|
50
52
|
readonly chats?: AgentChats;
|
|
53
|
+
/** Where members' files are stored as attachments; tests pass their own. */
|
|
54
|
+
readonly attachments?: AgentAttachments;
|
|
51
55
|
/** Seconds since the epoch; tests pass a fixed clock. */
|
|
52
56
|
readonly now?: () => number;
|
|
53
57
|
}
|
|
@@ -111,7 +115,7 @@ export declare function followsThreadReply(input: {
|
|
|
111
115
|
*/
|
|
112
116
|
export declare function receive(input: {
|
|
113
117
|
readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit" | "slack">;
|
|
114
|
-
readonly message: Pick<SlackMessage, "author" | "text" | "attachments">;
|
|
118
|
+
readonly message: Pick<SlackMessage, "author" | "text" | "attachments" | "ts">;
|
|
115
119
|
readonly direct: boolean;
|
|
116
120
|
readonly admission: AdmissionSettings;
|
|
117
121
|
readonly identities: AgentIdentities;
|
|
@@ -120,4 +124,9 @@ export declare function receive(input: {
|
|
|
120
124
|
readonly chats?: AgentChats;
|
|
121
125
|
/** Keeps the report alive after the turn starts; without it the report is awaited. */
|
|
122
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
|
+
};
|
|
123
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";
|
|
@@ -228,6 +231,15 @@ function segmentstreamSlack(options) {
|
|
|
228
231
|
});
|
|
229
232
|
return lookup.status === "paired" ? slackPrincipal(lookup.member, user) : null;
|
|
230
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
|
+
};
|
|
231
243
|
const admit = (direct) => (ctx, message) => {
|
|
232
244
|
const waitUntil = requestWork.getStore();
|
|
233
245
|
return receive({
|
|
@@ -238,6 +250,7 @@ function segmentstreamSlack(options) {
|
|
|
238
250
|
identities: pairing(),
|
|
239
251
|
environment,
|
|
240
252
|
chats,
|
|
253
|
+
files,
|
|
241
254
|
...waitUntil === void 0 ? {} : { waitUntil }
|
|
242
255
|
});
|
|
243
256
|
};
|
|
@@ -345,13 +358,31 @@ async function receive(input) {
|
|
|
345
358
|
if (input.waitUntil === void 0) await reported;
|
|
346
359
|
else input.waitUntil(reported);
|
|
347
360
|
}
|
|
348
|
-
|
|
361
|
+
if (!turn) return null;
|
|
362
|
+
const auth = withConversation(slackPrincipal(resolution.member, user), {
|
|
349
363
|
provider: "slack",
|
|
350
364
|
chatId: ctx.slack.channelId,
|
|
351
365
|
threadId: ctx.slack.threadTs,
|
|
352
366
|
kind: input.direct ? "private" : "group",
|
|
353
367
|
...input.direct ? { peer: user } : {}
|
|
354
|
-
})
|
|
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
|
+
};
|
|
355
386
|
case "pairing_required": {
|
|
356
387
|
const text = localizedText(admission.replies.pairingRequired);
|
|
357
388
|
if (text !== void 0 && ctx.edit === void 0) {
|
|
@@ -395,6 +426,15 @@ function report(operation, error) {
|
|
|
395
426
|
error: redactDiagnostic(error, new Set())
|
|
396
427
|
});
|
|
397
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
|
+
}
|
|
398
438
|
function digest(value) {
|
|
399
439
|
return createHash("sha256").update(value, "utf8").digest();
|
|
400
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-
|
|
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
|
|
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
|
|
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 {
|
|
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
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
filename
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
188
|
-
|
|
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-
|
|
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-
|
|
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.
|
|
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
|
|
53
|
+
label: { start: () => "Send stored attachments" },
|
|
52
54
|
async execute(input, ctx) {
|
|
53
|
-
|
|
55
|
+
const principal = ctx.session.auth.current;
|
|
56
|
+
const options = {
|
|
54
57
|
input: sendAttachmentsInput(input),
|
|
55
|
-
principal
|
|
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
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/agent",
|
|
3
|
-
"version": "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.
|
|
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",
|