@segmentstream/ontology 0.178.0 → 0.180.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/CHANGELOG.md +29 -0
- package/dist/analyze.d.ts +7 -0
- package/dist/analyze.js +16 -0
- package/dist/channel-files.d.ts +40 -0
- package/dist/channel-files.js +10 -0
- package/dist/service/agent/public-group-action.d.ts +23 -0
- package/dist/service/agent/public-group-action.js +53 -0
- package/dist/service/agent/server.d.ts +2 -0
- package/dist/service/agent/server.js +26 -15
- package/dist/service/chat/providers/email.js +2 -2
- package/dist/service/chat/providers/provider.d.ts +10 -2
- package/dist/service/chat/providers/provider.js +18 -1
- package/dist/service/service.js +10 -0
- package/dist/slack-files.d.ts +23 -5
- package/dist/slack-files.js +108 -16
- package/dist/slack.d.ts +3 -3
- package/dist/slack.js +2 -2
- package/dist/telegram-files.d.ts +27 -7
- package/dist/telegram-files.js +111 -31
- package/dist/telegram.d.ts +3 -3
- package/dist/telegram.js +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.180.0
|
|
4
|
+
|
|
5
|
+
`segmentstream__attachments_send` sends files in Telegram and Slack up to the providers' own
|
|
6
|
+
limits, not the connection proxy's 2 MiB request body.
|
|
7
|
+
|
|
8
|
+
- **Telegram.** Photos go up to 10 MB and other files up to 50 MB, Telegram's limits for a bot's
|
|
9
|
+
uploads. A file of up to 1,984 KiB is sent in its request's body and may share an album, as
|
|
10
|
+
before. A larger one goes alone in its message: the connection proxy reads it from the
|
|
11
|
+
workspace's file storage and sends it inside the multipart form the agent builds around it, so
|
|
12
|
+
its bytes never pass through the agent.
|
|
13
|
+
- **Slack.** A file goes up to Slack's 1 GB. Its bytes stream from the workspace's file storage
|
|
14
|
+
straight to the upload address `files.getUploadURLExternal` answers, which needs no credential,
|
|
15
|
+
without passing through the connection proxy; each file must reach Slack within two minutes.
|
|
16
|
+
- Files a member sends to the agent are still stored up to 20 MB in every channel. In a chat whose
|
|
17
|
+
replies are reviewed, files still go with the reply at most 2 MiB each in Telegram and Slack,
|
|
18
|
+
since approval may send the reply through the ontology.
|
|
19
|
+
|
|
20
|
+
The ontology SDK's channel senders take the files this needs: `sendTelegramFiles` and
|
|
21
|
+
`sendSlackFiles` accept a `ChannelStoredFile` (`{ filename, contentType, size, read() }`), which
|
|
22
|
+
Telegram's sender sends as a `ChannelCall` with a `file` (a signed read with `prefix` and `suffix`
|
|
23
|
+
bytes around it) and Slack's uploads with the new `fetch` option. `telegramFileRefusal` takes
|
|
24
|
+
`{ stored: true }` and `slackFileRefusal` `{ direct: true }` to check a file against the
|
|
25
|
+
provider's limit alone. `TELEGRAM_INLINE_FILE_BYTES`, `SLACK_UPLOAD_BYTES` and
|
|
26
|
+
`CHANNEL_FILE_FRAME_BYTES` name the bounds. Without these options both senders behave as before.
|
|
27
|
+
|
|
28
|
+
## 0.179.0
|
|
29
|
+
|
|
30
|
+
Opened groups can use a workspace-authored response handler and one explicitly granted ontology action. The action acts for a sender scoped to that group.
|
|
31
|
+
|
|
3
32
|
## 0.178.0
|
|
4
33
|
|
|
5
34
|
`agent_chat.draft` asks the agent for a draft in an email thread's chat (`chats: "thread"` on the
|
package/dist/analyze.d.ts
CHANGED
|
@@ -30,6 +30,13 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
|
|
|
30
30
|
* Builders default to declared roles explicitly granting user:grantRoles or user:*.
|
|
31
31
|
*/
|
|
32
32
|
readonly feedback?: boolean | FeedbackOptions;
|
|
33
|
+
/** One workspace-authored action that the agent may invoke for a sender in an opened group.
|
|
34
|
+
* The named role must grant the action. This does not assign that role to a user. */
|
|
35
|
+
readonly publicGroupAction?: {
|
|
36
|
+
readonly entity: string;
|
|
37
|
+
readonly action: string;
|
|
38
|
+
readonly role: string;
|
|
39
|
+
};
|
|
33
40
|
/** Opt-in after-commit service execution; only this declared role supplies permissions. */
|
|
34
41
|
readonly hooks?: {
|
|
35
42
|
readonly role: string;
|
package/dist/analyze.js
CHANGED
|
@@ -323,6 +323,22 @@ export function analyze(config, options = {}) {
|
|
|
323
323
|
chat = { ...chat, retentionDays };
|
|
324
324
|
}
|
|
325
325
|
}
|
|
326
|
+
if (config.publicGroupAction !== undefined) {
|
|
327
|
+
const binding = config.publicGroupAction;
|
|
328
|
+
const validKeys = isPlainObject(binding) &&
|
|
329
|
+
[binding.entity, binding.action, binding.role].every((key) => typeof key === "string" && key.length > 0);
|
|
330
|
+
const target = validKeys
|
|
331
|
+
? resolved
|
|
332
|
+
.find((item) => item.name === nameToWire(binding.entity))
|
|
333
|
+
?.actions.find((item) => item.name === nameToWire(binding.action))
|
|
334
|
+
: undefined;
|
|
335
|
+
const role = validKeys
|
|
336
|
+
? roles.find((item) => item.name === nameToWire(binding.role) && !isImplicitRole(item))
|
|
337
|
+
: undefined;
|
|
338
|
+
if (!target || target.action.confirm || !role?.permissions.includes(target.permission)) {
|
|
339
|
+
report("invalid-permission", "publicGroupAction", "Name an authored action without a member confirmation and a role explicitly granting that action.");
|
|
340
|
+
}
|
|
341
|
+
}
|
|
326
342
|
checkEntityIdentities(resolved, report);
|
|
327
343
|
checkMemberNames(resolved, report);
|
|
328
344
|
const toolsets = resolveToolsets(original.toolsets, resolved, connections, report);
|
package/dist/channel-files.d.ts
CHANGED
|
@@ -12,6 +12,30 @@ export interface ChannelCall {
|
|
|
12
12
|
readonly path: string;
|
|
13
13
|
readonly headers: ReadonlyArray<readonly [string, string]>;
|
|
14
14
|
readonly body: Uint8Array;
|
|
15
|
+
/**
|
|
16
|
+
* A stored file the connection reads from the workspace's file storage and sends as the body,
|
|
17
|
+
* in place of `body`, which is then empty: only a transport that reads stored files sends it.
|
|
18
|
+
*/
|
|
19
|
+
readonly file?: ChannelCallFile;
|
|
20
|
+
}
|
|
21
|
+
/** The most bytes a call sends before, and the most after, the stored file it carries. */
|
|
22
|
+
export declare const CHANNEL_FILE_FRAME_BYTES: number;
|
|
23
|
+
/**
|
|
24
|
+
* The body of a call that carries a stored file: `prefix`, the file's bytes from `start` to `end`
|
|
25
|
+
* inclusive, read by the connection by the file's signed read, then `suffix`, such as a multipart
|
|
26
|
+
* form's fields and its closing boundary around the file's part. Each of `prefix` and `suffix` is
|
|
27
|
+
* at most {@link CHANNEL_FILE_FRAME_BYTES}.
|
|
28
|
+
*/
|
|
29
|
+
export interface ChannelCallFile extends ChannelFileRead {
|
|
30
|
+
readonly start: number;
|
|
31
|
+
readonly end: number;
|
|
32
|
+
readonly prefix?: Uint8Array;
|
|
33
|
+
readonly suffix?: Uint8Array;
|
|
34
|
+
}
|
|
35
|
+
/** A signed read of a file in the workspace's file storage, valid for about a minute. */
|
|
36
|
+
export interface ChannelFileRead {
|
|
37
|
+
readonly url: string;
|
|
38
|
+
readonly headers: ReadonlyArray<readonly [string, string]>;
|
|
15
39
|
}
|
|
16
40
|
/** The provider's answer, as the connection relayed it. */
|
|
17
41
|
export interface ChannelReply {
|
|
@@ -30,6 +54,22 @@ export interface ChannelFile {
|
|
|
30
54
|
readonly contentType: string;
|
|
31
55
|
readonly bytes: Uint8Array;
|
|
32
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* A file the channel sends without its bytes passing through the sender: they stay in the
|
|
59
|
+
* workspace's file storage, which the provider's request reads by a signed read asked for just
|
|
60
|
+
* before it. A file too large for a request's own body goes this way.
|
|
61
|
+
*/
|
|
62
|
+
export interface ChannelStoredFile {
|
|
63
|
+
readonly filename: string;
|
|
64
|
+
readonly contentType: string;
|
|
65
|
+
readonly size: number;
|
|
66
|
+
/** A fresh signed read of the file; when it rejects, the file is not sent. */
|
|
67
|
+
readonly read: () => Promise<ChannelFileRead>;
|
|
68
|
+
}
|
|
69
|
+
/** Whether a file is sent by its signed read rather than its bytes. */
|
|
70
|
+
export declare function isStoredFile(file: ChannelFile | ChannelStoredFile): file is ChannelStoredFile;
|
|
71
|
+
/** How many bytes a file has. */
|
|
72
|
+
export declare function fileSize(file: ChannelFile | ChannelStoredFile): number;
|
|
33
73
|
/**
|
|
34
74
|
* What became of one visible message, or one step before any, a sender attempted:
|
|
35
75
|
* - `sent`: the provider's answer proves it;
|
package/dist/channel-files.js
CHANGED
|
@@ -5,6 +5,16 @@
|
|
|
5
5
|
* agent's connection proxy, or the ontology's connection transport. The sender never retries, and
|
|
6
6
|
* it reports per part what the provider's answer proves.
|
|
7
7
|
*/
|
|
8
|
+
/** The most bytes a call sends before, and the most after, the stored file it carries. */
|
|
9
|
+
export const CHANNEL_FILE_FRAME_BYTES = 64 * 1024;
|
|
10
|
+
/** Whether a file is sent by its signed read rather than its bytes. */
|
|
11
|
+
export function isStoredFile(file) {
|
|
12
|
+
return !("bytes" in file);
|
|
13
|
+
}
|
|
14
|
+
/** How many bytes a file has. */
|
|
15
|
+
export function fileSize(file) {
|
|
16
|
+
return isStoredFile(file) ? file.size : file.bytes.byteLength;
|
|
17
|
+
}
|
|
8
18
|
/** At most this many characters of an answer that is not JSON are kept on an error. */
|
|
9
19
|
const ANSWER_TEXT_LIMIT = 2000;
|
|
10
20
|
/**
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { HttpServerRequest } from "effect/unstable/http";
|
|
3
|
+
import { makeOperations } from "../operations.js";
|
|
4
|
+
type Resources = Parameters<typeof makeOperations>;
|
|
5
|
+
export interface PublicActionOptions {
|
|
6
|
+
readonly binding: {
|
|
7
|
+
role: string;
|
|
8
|
+
entity: string;
|
|
9
|
+
action: string;
|
|
10
|
+
};
|
|
11
|
+
readonly plan: Resources[1];
|
|
12
|
+
readonly hooks: Resources[2];
|
|
13
|
+
readonly connections: Resources[3];
|
|
14
|
+
readonly replicate: Resources[4];
|
|
15
|
+
}
|
|
16
|
+
/** Stable UUID in the given namespace. A group action's sender is scoped to that chat. */
|
|
17
|
+
export declare function groupSubject(parts: readonly string[]): string;
|
|
18
|
+
export declare function publicActionForGroup(backend: Resources[0], options: PublicActionOptions): (request: HttpServerRequest.HttpServerRequest, source: {
|
|
19
|
+
channel: string;
|
|
20
|
+
chat: string;
|
|
21
|
+
sender: string;
|
|
22
|
+
}, input: Readonly<Record<string, unknown>>) => Effect.Effect<{} | null, import("../../errors.js").ActionError | import("../../connection.js").ConnectionError | import("../../runtime/errors.js").WorkflowRecoveryUnavailable | import("../../runtime/errors.js").TriggerInputInvalid | import("../errors.js").InvalidActionInput, import("../errors.js").RequestId>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { nameToWire } from "../../authoring-names.js";
|
|
4
|
+
import { principalScopes, isAllowed } from "../../permissions.js";
|
|
5
|
+
import { CurrentPrincipal } from "../authentication.js";
|
|
6
|
+
import { makeOperations, identityToken } from "../operations.js";
|
|
7
|
+
/** Stable UUID in the given namespace. A group action's sender is scoped to that chat. */
|
|
8
|
+
export function groupSubject(parts) {
|
|
9
|
+
const bytes = createHash("sha256").update(JSON.stringify(parts)).digest();
|
|
10
|
+
bytes[6] = (bytes[6] & 15) | 80;
|
|
11
|
+
bytes[8] = (bytes[8] & 63) | 128;
|
|
12
|
+
const hex = bytes.toString("hex");
|
|
13
|
+
return [
|
|
14
|
+
hex.slice(0, 8),
|
|
15
|
+
hex.slice(8, 12),
|
|
16
|
+
hex.slice(12, 16),
|
|
17
|
+
hex.slice(16, 20),
|
|
18
|
+
hex.slice(20, 32),
|
|
19
|
+
].join("-");
|
|
20
|
+
}
|
|
21
|
+
export function publicActionForGroup(backend, options) {
|
|
22
|
+
const { plan, binding } = options;
|
|
23
|
+
const entity = plan.entities.find((item) => item.name === nameToWire(binding.entity));
|
|
24
|
+
const action = entity?.actions.find((item) => !item.generated && item.name === nameToWire(binding.action));
|
|
25
|
+
const role = plan.ontology.roles.find((item) => item.name === nameToWire(binding.role));
|
|
26
|
+
const operations = makeOperations(backend, plan, options.hooks, options.connections, options.replicate);
|
|
27
|
+
return (request, source, input) => Effect.gen(function* () {
|
|
28
|
+
if (!entity || !action || action.action.confirm || !role) {
|
|
29
|
+
return yield* Effect.die(new Error("Invalid public group action."));
|
|
30
|
+
}
|
|
31
|
+
const permissions = action.permissions.filter((permission) => role.permissions.includes(permission));
|
|
32
|
+
const principal = {
|
|
33
|
+
kind: "guest",
|
|
34
|
+
id: groupSubject(["public-action", source.channel, source.chat, source.sender]),
|
|
35
|
+
roles: [role.name],
|
|
36
|
+
permissions,
|
|
37
|
+
...principalScopes([role], [role.name]),
|
|
38
|
+
chat: { provider: source.channel, chatId: source.chat },
|
|
39
|
+
};
|
|
40
|
+
if (!action.permissions.every((p) => isAllowed(p, principal))) {
|
|
41
|
+
return yield* Effect.die(new Error("Public group action denied."));
|
|
42
|
+
}
|
|
43
|
+
const answer = yield* operations
|
|
44
|
+
.runAction(entity, action, {
|
|
45
|
+
input,
|
|
46
|
+
options: {},
|
|
47
|
+
validateOnly: false,
|
|
48
|
+
identityToken: identityToken(request),
|
|
49
|
+
})
|
|
50
|
+
.pipe(Effect.provideService(CurrentPrincipal, principal));
|
|
51
|
+
return answer.result;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type PublicActionOptions } from "./public-group-action.js";
|
|
1
2
|
import { Layer, Redacted } from "effect";
|
|
2
3
|
import { HttpRouter } from "effect/unstable/http";
|
|
3
4
|
import { type SessionExchange, type TokenVerifier } from "../authentication.js";
|
|
@@ -33,6 +34,7 @@ export { GUEST_LINK_PATH };
|
|
|
33
34
|
*/
|
|
34
35
|
export declare const PAIRING_LIMIT: RateLimit;
|
|
35
36
|
export interface AgentServerOptions {
|
|
37
|
+
readonly publicGroupAction?: PublicActionOptions;
|
|
36
38
|
readonly verifyToken: TokenVerifier;
|
|
37
39
|
/**
|
|
38
40
|
* The websites whose visitors get an agent token: as guests, and, while `web` is open to sign-up,
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { chatPersona, chatPersonaNames, deployedChatPersonas } from "../../chat-personas.js";
|
|
2
|
+
import { publicActionForGroup, groupSubject, } from "./public-group-action.js";
|
|
2
3
|
import { isAllowed, effectiveScope } from "../../permissions.js";
|
|
3
4
|
import { confirmationCommand } from "./confirmations.js";
|
|
4
|
-
import {
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
5
6
|
import { Effect, Exit, Layer, Redacted, Result, Schema } from "effect";
|
|
6
7
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
|
7
8
|
import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
|
|
@@ -10,7 +11,7 @@ import { API_KEY_PREFIX } from "../../runtime/principals.js";
|
|
|
10
11
|
import { schemaIssues } from "../../runtime/validation.js";
|
|
11
12
|
import { BASE_PATH } from "../api.js";
|
|
12
13
|
import { CurrentPrincipal, withPrincipal, } from "../authentication.js";
|
|
13
|
-
import { RequestId, errorBodyForWire, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
|
|
14
|
+
import { RequestId, errorBodyForWire, failureResponse, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
|
|
14
15
|
import { secretHash } from "../oauth/protocol.js";
|
|
15
16
|
import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
|
|
16
17
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
@@ -886,6 +887,28 @@ export function agentLayer(options) {
|
|
|
886
887
|
}
|
|
887
888
|
const readAccess = store.readGroupAccess;
|
|
888
889
|
const countPublicTurn = store.web?.countGuestTurn;
|
|
890
|
+
if (readAccess && options.publicGroupAction) {
|
|
891
|
+
const run = publicActionForGroup(backend, options.publicGroupAction);
|
|
892
|
+
yield* router.add("POST", `${AGENT_PATH}/chats/public-action`, asRuntime((request) => Effect.gen(function* () {
|
|
893
|
+
const requestId = yield* RequestId;
|
|
894
|
+
const part = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
|
|
895
|
+
const decoded = Schema.decodeUnknownResult(Schema.Struct({
|
|
896
|
+
channel: part,
|
|
897
|
+
chat: part,
|
|
898
|
+
sender: part,
|
|
899
|
+
input: Schema.Record(Schema.String, Schema.Unknown),
|
|
900
|
+
}))(yield* jsonBody(request), { onExcessProperty: "error" });
|
|
901
|
+
if (Result.isFailure(decoded)) {
|
|
902
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
903
|
+
}
|
|
904
|
+
const { channel, chat, sender, input } = decoded.success;
|
|
905
|
+
if (JSON.stringify(input).length > 12000 ||
|
|
906
|
+
(yield* readAccess(`${channel}:${chat}`)) !== "public") {
|
|
907
|
+
return toServerResponse(forbidden(requestId, "Public action unavailable."));
|
|
908
|
+
}
|
|
909
|
+
return yield* run(request, { channel, chat, sender }, input).pipe(Effect.map((result) => json({ result })), Effect.catchCause((cause) => failureResponse(cause, requestId)));
|
|
910
|
+
})));
|
|
911
|
+
}
|
|
889
912
|
if (readAccess && countPublicTurn) {
|
|
890
913
|
yield* router.add("POST", `${AGENT_PATH}/chats/public-turn`, asRuntime((request) => Effect.gen(function* () {
|
|
891
914
|
const requestId = yield* RequestId;
|
|
@@ -910,19 +933,7 @@ export function agentLayer(options) {
|
|
|
910
933
|
}
|
|
911
934
|
// The same sender shares a guest budget across groups on this connection.
|
|
912
935
|
// The id is for accounting only and never represents a workspace principal.
|
|
913
|
-
const
|
|
914
|
-
.update(JSON.stringify(["group-guest", channel, sender]))
|
|
915
|
-
.digest();
|
|
916
|
-
bytes[6] = (bytes[6] & 15) | 80;
|
|
917
|
-
bytes[8] = (bytes[8] & 63) | 128;
|
|
918
|
-
const hex = bytes.toString("hex");
|
|
919
|
-
const guestId = [
|
|
920
|
-
hex.slice(0, 8),
|
|
921
|
-
hex.slice(8, 12),
|
|
922
|
-
hex.slice(12, 16),
|
|
923
|
-
hex.slice(16, 20),
|
|
924
|
-
hex.slice(20, 32),
|
|
925
|
-
].join("-");
|
|
936
|
+
const guestId = groupSubject(["group-guest", channel, sender]);
|
|
926
937
|
const limited = yield* countPublicTurn(guestId, limits);
|
|
927
938
|
return json(limited ? { status: "limited" } : { status: "admitted", guestId });
|
|
928
939
|
})));
|
|
@@ -5,7 +5,7 @@ import { mailboxSignature } from "../../../gmail-send.js";
|
|
|
5
5
|
import { ActionRejected } from "../../../errors.js";
|
|
6
6
|
import { EMAIL_PATTERN } from "../../../property.js";
|
|
7
7
|
import { describeChatError } from "../diagnostics.js";
|
|
8
|
-
import { channelRequest, definiteTransportFailure, filesWithBytes, record, transportFailure, } from "./provider.js";
|
|
8
|
+
import { channelRequest, definiteTransportFailure, filesWithBytes, record, transportCall, transportFailure, } from "./provider.js";
|
|
9
9
|
/** A Gmail id, of a thread or a message. */
|
|
10
10
|
const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
|
|
11
11
|
const decoder = new TextDecoder();
|
|
@@ -99,7 +99,7 @@ function signatureOf(input) {
|
|
|
99
99
|
return Effect.tryPromise({
|
|
100
100
|
try: () => mailboxSignature({
|
|
101
101
|
mailbox: input.connection,
|
|
102
|
-
request: (call) => Effect.runPromise(input.transport.request(
|
|
102
|
+
request: (call) => Effect.runPromise(input.transport.request(transportCall(call, input.connection))),
|
|
103
103
|
}),
|
|
104
104
|
// The original failure, Gmail's explanation or the connection's, with its causes and stack.
|
|
105
105
|
catch: (cause) => cause,
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Effect, type Exit } from "effect";
|
|
2
|
-
import type { ChannelPart, ChannelRequest } from "../../../channel-files.js";
|
|
2
|
+
import type { ChannelCall, ChannelPart, ChannelRequest } from "../../../channel-files.js";
|
|
3
3
|
import type { ChatButtonRows } from "../../../chat.js";
|
|
4
4
|
import type { TelegramPreviewContext } from "../../../telegram.js";
|
|
5
|
-
import { ConnectionError, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
|
|
5
|
+
import { ConnectionError, type ConnectionCall, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
|
|
6
6
|
import type { ActionRejected } from "../../../errors.js";
|
|
7
7
|
import type { Destination } from "../resolve.js";
|
|
8
8
|
import type { ResolvedTemplate, StoredFileLink, StoredFileReference, TemplateRequest } from "./whatsapp-template.js";
|
|
@@ -221,6 +221,14 @@ export interface ChatProvider {
|
|
|
221
221
|
export declare function transportFailure(payload: ProviderOutcome["payload"], result: Exit.Failure<ConnectionReply, ConnectionError>): ProviderOutcome;
|
|
222
222
|
/** Whether an error of the connection transport proves the request never reached the provider. */
|
|
223
223
|
export declare function definiteTransportFailure(error: unknown): boolean;
|
|
224
|
+
/**
|
|
225
|
+
* A shared sender's call as the connection transport takes it. The ontology's deliveries hand the
|
|
226
|
+
* senders files by their bytes, so no call carries a stored file's read, which only the agent's
|
|
227
|
+
* proxy sends; one that did is refused without being sent.
|
|
228
|
+
*/
|
|
229
|
+
export declare function transportCall(call: ChannelCall, connection: string): ConnectionCall & {
|
|
230
|
+
readonly connection: string;
|
|
231
|
+
};
|
|
224
232
|
/**
|
|
225
233
|
* The connection transport as the channels' shared senders call it (`ChannelRequest`): one call on
|
|
226
234
|
* `connection`, which rejects with the transport's own error when it did not relay the call.
|
|
@@ -70,13 +70,30 @@ export function transportFailure(payload, result) {
|
|
|
70
70
|
export function definiteTransportFailure(error) {
|
|
71
71
|
return error instanceof ConnectionError && DEFINITE_CONNECTION_FAILURES.has(error.reason);
|
|
72
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* A shared sender's call as the connection transport takes it. The ontology's deliveries hand the
|
|
75
|
+
* senders files by their bytes, so no call carries a stored file's read, which only the agent's
|
|
76
|
+
* proxy sends; one that did is refused without being sent.
|
|
77
|
+
*/
|
|
78
|
+
export function transportCall(call, connection) {
|
|
79
|
+
const { file, ...rest } = call;
|
|
80
|
+
if (file !== undefined) {
|
|
81
|
+
throw new ConnectionError({
|
|
82
|
+
connection,
|
|
83
|
+
reason: "invalid_request",
|
|
84
|
+
message: "The delivery sends no stored file's read.",
|
|
85
|
+
retryable: false,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return { ...rest, connection };
|
|
89
|
+
}
|
|
73
90
|
/**
|
|
74
91
|
* The connection transport as the channels' shared senders call it (`ChannelRequest`): one call on
|
|
75
92
|
* `connection`, which rejects with the transport's own error when it did not relay the call.
|
|
76
93
|
*/
|
|
77
94
|
export function channelRequest(transport, connection) {
|
|
78
95
|
return async (call) => {
|
|
79
|
-
const exit = await Effect.runPromiseExit(transport.request(
|
|
96
|
+
const exit = await Effect.runPromiseExit(transport.request(transportCall(call, connection)));
|
|
80
97
|
if (exit._tag === "Failure") {
|
|
81
98
|
throw Cause.squash(exit.cause);
|
|
82
99
|
}
|
package/dist/service/service.js
CHANGED
|
@@ -456,6 +456,16 @@ export function createOntologyService(ontology, config) {
|
|
|
456
456
|
verifyToken,
|
|
457
457
|
verifyRuntime,
|
|
458
458
|
exchangeSession,
|
|
459
|
+
...(!preview &&
|
|
460
|
+
ontology.config.publicGroupAction && {
|
|
461
|
+
publicGroupAction: {
|
|
462
|
+
binding: ontology.config.publicGroupAction,
|
|
463
|
+
plan,
|
|
464
|
+
hooks,
|
|
465
|
+
connections,
|
|
466
|
+
replicate,
|
|
467
|
+
},
|
|
468
|
+
}),
|
|
459
469
|
visitorWebsites: preview ? { guests: [], signUp: [] } : visitorWebsites,
|
|
460
470
|
agentTools,
|
|
461
471
|
guest: preview ? undefined : guest,
|
package/dist/slack-files.d.ts
CHANGED
|
@@ -1,19 +1,30 @@
|
|
|
1
|
-
import { type ChannelFile, type ChannelPart, type ChannelRequest, type DefiniteFailure } from "./channel-files.js";
|
|
1
|
+
import { type ChannelFile, type ChannelPart, type ChannelRequest, type ChannelStoredFile, type DefiniteFailure } from "./channel-files.js";
|
|
2
2
|
/**
|
|
3
3
|
* Slack's message with files, which the agent's `attachments_send` and the ontology's delivery of
|
|
4
4
|
* an approved draft both send, with Slack's external upload: each file's bytes go to the address
|
|
5
5
|
* `files.getUploadURLExternal` answers, then one `files.completeUploadExternal` shares all of them
|
|
6
6
|
* in the chat with the text, as one visible message. Nothing is visible until that share, so a
|
|
7
7
|
* file that fails to upload is left out without anything reaching the person. The Web API calls
|
|
8
|
-
* go on the connection's `web` API
|
|
8
|
+
* go on the connection's `web` API. The bytes go on its `files` API, within one request's body,
|
|
9
|
+
* or, given a `fetch`, straight to the upload address, which carries its own authorization and
|
|
10
|
+
* needs no credential of the connection's: a stored file then streams from the workspace's file
|
|
11
|
+
* storage to Slack without being held whole, up to Slack's own bound.
|
|
9
12
|
*/
|
|
10
13
|
/** The most bytes of one file a single connection request carries to Slack. */
|
|
11
14
|
export declare const SLACK_FILE_BYTES: number;
|
|
15
|
+
/** The most bytes Slack takes of one file, as an upload straight to its address may send. */
|
|
16
|
+
export declare const SLACK_UPLOAD_BYTES: number;
|
|
12
17
|
/** The most files one `files.completeUploadExternal` shares. */
|
|
13
18
|
export declare const SLACK_FILES_PER_MESSAGE = 10;
|
|
14
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* Why Slack cannot take this file through one connection request, or, uploaded straight to its
|
|
21
|
+
* address (`direct`), at all; undefined when it can.
|
|
22
|
+
*/
|
|
15
23
|
export declare function slackFileRefusal(file: {
|
|
16
24
|
readonly size: number;
|
|
25
|
+
}, options?: {
|
|
26
|
+
/** Whether the file is uploaded straight to Slack's address, held to Slack's bound alone. */
|
|
27
|
+
readonly direct?: boolean;
|
|
17
28
|
}): {
|
|
18
29
|
readonly code: "too_large" | "empty";
|
|
19
30
|
readonly message: string;
|
|
@@ -39,13 +50,20 @@ export interface SlackFilesResult {
|
|
|
39
50
|
* Uploads `files`, then shares those that uploaded in `channel`, in `threadTs` when given, with
|
|
40
51
|
* `text` as the message's text. The share is `sent` when Slack confirms it, `failed` when Slack
|
|
41
52
|
* refused it with a code that proves nothing was posted, otherwise `uncertain`. Nothing is
|
|
42
|
-
* retried.
|
|
53
|
+
* retried. A stored file uploads only straight to Slack, with `fetch`; without it, it is not
|
|
54
|
+
* uploaded (`unsupported`).
|
|
43
55
|
*/
|
|
44
56
|
export declare function sendSlackFiles(options: {
|
|
45
57
|
readonly request: ChannelRequest;
|
|
58
|
+
/**
|
|
59
|
+
* Posts each file's bytes straight to Slack's upload address instead of through the
|
|
60
|
+
* connection, reading a stored file from the workspace's storage: up to
|
|
61
|
+
* {@link SLACK_UPLOAD_BYTES} a file, each within two minutes.
|
|
62
|
+
*/
|
|
63
|
+
readonly fetch?: typeof fetch;
|
|
46
64
|
readonly channel: string;
|
|
47
65
|
readonly threadTs?: string;
|
|
48
|
-
readonly files: ReadonlyArray<ChannelFile & {
|
|
66
|
+
readonly files: ReadonlyArray<(ChannelFile | ChannelStoredFile) & {
|
|
49
67
|
readonly index?: number;
|
|
50
68
|
}>;
|
|
51
69
|
readonly text?: string;
|
package/dist/slack-files.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ChannelAnswerError, isRecord, replyJson, unrelayed, } from "./channel-files.js";
|
|
1
|
+
import { ChannelAnswerError, fileSize, isRecord, isStoredFile, replyJson, unrelayed, } from "./channel-files.js";
|
|
2
2
|
import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
|
|
3
3
|
/**
|
|
4
4
|
* Slack's message with files, which the agent's `attachments_send` and the ontology's delivery of
|
|
@@ -6,10 +6,17 @@ import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
|
|
|
6
6
|
* `files.getUploadURLExternal` answers, then one `files.completeUploadExternal` shares all of them
|
|
7
7
|
* in the chat with the text, as one visible message. Nothing is visible until that share, so a
|
|
8
8
|
* file that fails to upload is left out without anything reaching the person. The Web API calls
|
|
9
|
-
* go on the connection's `web` API
|
|
9
|
+
* go on the connection's `web` API. The bytes go on its `files` API, within one request's body,
|
|
10
|
+
* or, given a `fetch`, straight to the upload address, which carries its own authorization and
|
|
11
|
+
* needs no credential of the connection's: a stored file then streams from the workspace's file
|
|
12
|
+
* storage to Slack without being held whole, up to Slack's own bound.
|
|
10
13
|
*/
|
|
11
14
|
/** The most bytes of one file a single connection request carries to Slack. */
|
|
12
15
|
export const SLACK_FILE_BYTES = MAXIMUM_CONNECTION_BODY_BYTES;
|
|
16
|
+
/** The most bytes Slack takes of one file, as an upload straight to its address may send. */
|
|
17
|
+
export const SLACK_UPLOAD_BYTES = 1024 * 1024 * 1024;
|
|
18
|
+
/** How long one file's upload straight to Slack may take, its read from storage included. */
|
|
19
|
+
const SLACK_UPLOAD_MS = 120_000;
|
|
13
20
|
/** The most files one `files.completeUploadExternal` shares. */
|
|
14
21
|
export const SLACK_FILES_PER_MESSAGE = 10;
|
|
15
22
|
/** Where Slack's upload addresses are, which the connection's `files` API reaches. */
|
|
@@ -23,9 +30,18 @@ const POSSIBLY_POSTED = new Set([
|
|
|
23
30
|
"fatal_error",
|
|
24
31
|
"service_unavailable",
|
|
25
32
|
]);
|
|
26
|
-
/**
|
|
27
|
-
|
|
28
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Why Slack cannot take this file through one connection request, or, uploaded straight to its
|
|
35
|
+
* address (`direct`), at all; undefined when it can.
|
|
36
|
+
*/
|
|
37
|
+
export function slackFileRefusal(file, options = {}) {
|
|
38
|
+
if (options.direct === true && file.size > SLACK_UPLOAD_BYTES) {
|
|
39
|
+
return {
|
|
40
|
+
code: "too_large",
|
|
41
|
+
message: `Slack takes at most ${SLACK_UPLOAD_BYTES} bytes a file.`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
if (options.direct !== true && file.size > SLACK_FILE_BYTES) {
|
|
29
45
|
return {
|
|
30
46
|
code: "too_large",
|
|
31
47
|
message: `The connection takes at most ${SLACK_FILE_BYTES} bytes per upload.`,
|
|
@@ -47,18 +63,89 @@ class SlackCallError extends Error {
|
|
|
47
63
|
name = "SlackCallError";
|
|
48
64
|
constructor(message, code, status,
|
|
49
65
|
/** Slack's answer, kept for operators. */
|
|
50
|
-
answer) {
|
|
51
|
-
super(message);
|
|
66
|
+
answer, cause) {
|
|
67
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
52
68
|
this.code = code;
|
|
53
69
|
this.status = status;
|
|
54
70
|
this.answer = answer;
|
|
55
71
|
}
|
|
56
72
|
}
|
|
73
|
+
/** A stream of exactly `size` bytes, which fails at once when the source sends more or fewer. */
|
|
74
|
+
function exactly(size) {
|
|
75
|
+
let seen = 0;
|
|
76
|
+
return new TransformStream({
|
|
77
|
+
transform(chunk, controller) {
|
|
78
|
+
seen += chunk.byteLength;
|
|
79
|
+
if (seen > size) {
|
|
80
|
+
controller.error(new Error(`Storage sent more than the file's ${size} bytes.`));
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
controller.enqueue(chunk);
|
|
84
|
+
},
|
|
85
|
+
flush(controller) {
|
|
86
|
+
if (seen !== size) {
|
|
87
|
+
controller.error(new Error(`Storage sent ${seen} of the file's ${size} bytes.`));
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Posts a file's bytes straight to the upload address Slack answered, as raw bytes of the file's
|
|
94
|
+
* type. A stored file is read from the workspace's storage by a fresh signed read and streamed as
|
|
95
|
+
* Slack reads it, with its length declared, so it is never held whole.
|
|
96
|
+
*/
|
|
97
|
+
async function uploadDirectly(fetchImpl, address, file) {
|
|
98
|
+
const signal = AbortSignal.timeout(SLACK_UPLOAD_MS);
|
|
99
|
+
let body;
|
|
100
|
+
if (isStoredFile(file)) {
|
|
101
|
+
let read;
|
|
102
|
+
try {
|
|
103
|
+
read = await file.read();
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
throw new SlackCallError("The file's signed read could not be had.", "unavailable", 0, undefined, error);
|
|
107
|
+
}
|
|
108
|
+
const source = await fetchImpl(read.url, {
|
|
109
|
+
headers: read.headers.map(([name, value]) => [name, value]),
|
|
110
|
+
redirect: "error",
|
|
111
|
+
signal,
|
|
112
|
+
});
|
|
113
|
+
if (!source.ok || source.body === null) {
|
|
114
|
+
await source.body?.cancel();
|
|
115
|
+
throw new SlackCallError(`File storage answered the file's read with status ${source.status}.`, "unavailable", source.status);
|
|
116
|
+
}
|
|
117
|
+
body = source.body.pipeThrough(exactly(file.size));
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
body = file.bytes;
|
|
121
|
+
}
|
|
122
|
+
// `duplex` lets a stream be a request's body; the DOM's types do not name it yet.
|
|
123
|
+
const init = {
|
|
124
|
+
method: "POST",
|
|
125
|
+
headers: {
|
|
126
|
+
"content-type": file.contentType,
|
|
127
|
+
"content-length": String(fileSize(file)),
|
|
128
|
+
},
|
|
129
|
+
body: body,
|
|
130
|
+
duplex: "half",
|
|
131
|
+
redirect: "error",
|
|
132
|
+
signal,
|
|
133
|
+
};
|
|
134
|
+
const response = await fetchImpl(address, init);
|
|
135
|
+
const headers = [];
|
|
136
|
+
response.headers.forEach((value, name) => headers.push([name, value]));
|
|
137
|
+
return {
|
|
138
|
+
status: response.status,
|
|
139
|
+
headers,
|
|
140
|
+
body: new Uint8Array(await response.arrayBuffer()),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
57
143
|
/**
|
|
58
144
|
* Uploads `files`, then shares those that uploaded in `channel`, in `threadTs` when given, with
|
|
59
145
|
* `text` as the message's text. The share is `sent` when Slack confirms it, `failed` when Slack
|
|
60
146
|
* refused it with a code that proves nothing was posted, otherwise `uncertain`. Nothing is
|
|
61
|
-
* retried.
|
|
147
|
+
* retried. A stored file uploads only straight to Slack, with `fetch`; without it, it is not
|
|
148
|
+
* uploaded (`unsupported`).
|
|
62
149
|
*/
|
|
63
150
|
export async function sendSlackFiles(options) {
|
|
64
151
|
/** One Web API call; Slack's own refusal (`ok: false`) throws with its error code. */
|
|
@@ -82,22 +169,27 @@ export async function sendSlackFiles(options) {
|
|
|
82
169
|
for (const [position, file] of options.files.entries()) {
|
|
83
170
|
const index = file.index ?? position;
|
|
84
171
|
try {
|
|
172
|
+
if (isStoredFile(file) && options.fetch === undefined) {
|
|
173
|
+
throw new SlackCallError("A stored file uploads only straight to Slack.", "unsupported", 0);
|
|
174
|
+
}
|
|
85
175
|
const ticket = await call("files.getUploadURLExternal", "application/x-www-form-urlencoded", new URLSearchParams({
|
|
86
176
|
filename: file.filename,
|
|
87
|
-
length: String(file
|
|
177
|
+
length: String(fileSize(file)),
|
|
88
178
|
}).toString());
|
|
89
179
|
if (typeof ticket.upload_url !== "string" ||
|
|
90
180
|
!ticket.upload_url.startsWith(SLACK_FILES) ||
|
|
91
181
|
typeof ticket.file_id !== "string") {
|
|
92
182
|
throw new SlackCallError("Slack answered no upload address.", "invalid_response", 200);
|
|
93
183
|
}
|
|
94
|
-
const reply =
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
184
|
+
const reply = options.fetch !== undefined
|
|
185
|
+
? await uploadDirectly(options.fetch, ticket.upload_url, file)
|
|
186
|
+
: await options.request({
|
|
187
|
+
api: "files",
|
|
188
|
+
method: "POST",
|
|
189
|
+
path: `/${ticket.upload_url.slice(SLACK_FILES.length)}`,
|
|
190
|
+
headers: [["content-type", file.contentType]],
|
|
191
|
+
body: isStoredFile(file) ? new Uint8Array() : file.bytes,
|
|
192
|
+
});
|
|
101
193
|
if (reply.status < 200 || reply.status >= 300) {
|
|
102
194
|
throw new SlackCallError("Slack refused the file's bytes.", "send_failed", reply.status, replyJson(reply) ?? new TextDecoder().decode(reply.body).slice(0, 2000));
|
|
103
195
|
}
|
package/dist/slack.d.ts
CHANGED
|
@@ -13,6 +13,6 @@ export declare function escapeSlackMarkdown(text: string): string;
|
|
|
13
13
|
* Markdown.
|
|
14
14
|
*/
|
|
15
15
|
export declare function renderSlack(markdown: string, attribution: string, separator?: string): string;
|
|
16
|
-
export type { ChannelCall, ChannelFile, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
|
|
17
|
-
export { ChannelAnswerError } from "./channel-files.js";
|
|
18
|
-
export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, type SlackFilesResult, } from "./slack-files.js";
|
|
16
|
+
export type { ChannelCall, ChannelCallFile, ChannelFile, ChannelFileRead, ChannelPart, ChannelReply, ChannelRequest, ChannelStoredFile, DefiniteFailure, } from "./channel-files.js";
|
|
17
|
+
export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
|
|
18
|
+
export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, SLACK_UPLOAD_BYTES, type SlackFilesResult, } from "./slack-files.js";
|
package/dist/slack.js
CHANGED
|
@@ -21,5 +21,5 @@ export function renderSlack(markdown, attribution, separator = "\n\n") {
|
|
|
21
21
|
? markdown
|
|
22
22
|
: `${markdown}${escapeSlackMarkdown(separator)}_${escapeSlackMarkdown(attribution)}_`;
|
|
23
23
|
}
|
|
24
|
-
export { ChannelAnswerError } from "./channel-files.js";
|
|
25
|
-
export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, } from "./slack-files.js";
|
|
24
|
+
export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
|
|
25
|
+
export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, SLACK_UPLOAD_BYTES, } from "./slack-files.js";
|
package/dist/telegram-files.d.ts
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
-
import { type ChannelFile, type ChannelPart, type ChannelRequest, type DefiniteFailure } from "./channel-files.js";
|
|
1
|
+
import { type ChannelFile, type ChannelPart, type ChannelRequest, type ChannelStoredFile, type DefiniteFailure } from "./channel-files.js";
|
|
2
2
|
/**
|
|
3
3
|
* Telegram's message with files, which the agent's `attachments_send` and the ontology's delivery
|
|
4
4
|
* of an approved draft both send: the files in their order, as few messages as Telegram allows,
|
|
5
5
|
* the caption on the first. Photos go as photos and other files as documents; consecutive files of
|
|
6
6
|
* one type go together as an album of at most ten, as long as one request carries them. Each
|
|
7
7
|
* request is one multipart call on the connection's `bot` API.
|
|
8
|
+
*
|
|
9
|
+
* A file sent by its signed read (`ChannelStoredFile`) goes alone in its message: the connection
|
|
10
|
+
* reads its bytes from the workspace's file storage and sends them inside the form the sender
|
|
11
|
+
* builds around them, so it is held to Telegram's own bounds, not to the connection's request
|
|
12
|
+
* body. Telegram also fetches files by URL, but only up to 5 MB for a photo and 20 MB for another
|
|
13
|
+
* file, and a document only as PDF or ZIP, so every file goes as an upload.
|
|
8
14
|
*/
|
|
9
15
|
/** The most bytes Telegram takes of a photo. */
|
|
10
16
|
export declare const TELEGRAM_PHOTO_BYTES: number;
|
|
@@ -33,19 +39,31 @@ export interface TelegramFormattedText {
|
|
|
33
39
|
}
|
|
34
40
|
/** How Telegram sends a file of this content type: as a photo or as a document. */
|
|
35
41
|
export declare function telegramFileType(contentType: string): "photo" | "document";
|
|
42
|
+
/**
|
|
43
|
+
* The most bytes of a file sent in a request's own body, which leaves room in the connection's
|
|
44
|
+
* request bound for the form around it. Files this small can go together as an album; a larger
|
|
45
|
+
* one goes by its signed read, alone in its message.
|
|
46
|
+
*/
|
|
47
|
+
export declare const TELEGRAM_INLINE_FILE_BYTES: number;
|
|
36
48
|
/**
|
|
37
49
|
* Why Telegram cannot take this file through one connection request, or undefined when it can:
|
|
38
|
-
* `too_large` past Telegram's bound for its type or the
|
|
39
|
-
* bytes.
|
|
50
|
+
* `too_large` past Telegram's bound for its type or, unless the file may go by its signed read
|
|
51
|
+
* (`stored`), the connection's request bound; `empty` for no bytes.
|
|
40
52
|
*/
|
|
41
53
|
export declare function telegramFileRefusal(file: {
|
|
42
54
|
readonly contentType: string;
|
|
43
55
|
readonly size: number;
|
|
56
|
+
}, options?: {
|
|
57
|
+
/**
|
|
58
|
+
* Whether a file too large for a request's own body is sent by its signed read, the
|
|
59
|
+
* connection reading it from storage: Telegram's bound for its type alone then holds.
|
|
60
|
+
*/
|
|
61
|
+
readonly stored?: boolean;
|
|
44
62
|
}): {
|
|
45
63
|
readonly code: "too_large" | "empty";
|
|
46
64
|
readonly message: string;
|
|
47
65
|
} | undefined;
|
|
48
|
-
/** The most bytes of one file a single connection request can carry to Telegram. */
|
|
66
|
+
/** The most bytes of one file a single connection request can carry to Telegram in its body. */
|
|
49
67
|
export declare function telegramFileBytes(contentType: string): number;
|
|
50
68
|
/**
|
|
51
69
|
* The same text with every line break written CRLF, and its entities moved to match. A multipart
|
|
@@ -69,13 +87,15 @@ export interface TelegramFilesTarget {
|
|
|
69
87
|
* Sends `files` to `target` in their order, `caption` on the first message Telegram takes. Each
|
|
70
88
|
* album is one request and one part: `sent` when Telegram names its messages, `failed` when it
|
|
71
89
|
* refused them (`too_large` for 413, `forbidden` for 403, `send_failed` otherwise) or a request
|
|
72
|
-
* could not be built
|
|
73
|
-
*
|
|
90
|
+
* could not be built (`unavailable` for a stored file whose read could not be had), `uncertain`
|
|
91
|
+
* when its answer proves neither. A stored file goes alone, through a `request` that reads stored
|
|
92
|
+
* files. A refusal of the caption's formatting alone sends the album again without it. Nothing is
|
|
93
|
+
* retried otherwise.
|
|
74
94
|
*/
|
|
75
95
|
export declare function sendTelegramFiles(options: {
|
|
76
96
|
readonly request: ChannelRequest;
|
|
77
97
|
readonly target: TelegramFilesTarget;
|
|
78
|
-
readonly files: ReadonlyArray<ChannelFile & {
|
|
98
|
+
readonly files: ReadonlyArray<(ChannelFile | ChannelStoredFile) & {
|
|
79
99
|
readonly index?: number;
|
|
80
100
|
}>;
|
|
81
101
|
readonly caption?: TelegramFormattedText;
|
package/dist/telegram-files.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ChannelAnswerError, isRecord, replyJson, unrelayed, } from "./channel-files.js";
|
|
1
|
+
import { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError, isRecord, isStoredFile, replyJson, unrelayed, } from "./channel-files.js";
|
|
2
2
|
import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
|
|
3
3
|
/**
|
|
4
4
|
* Telegram's message with files, which the agent's `attachments_send` and the ontology's delivery
|
|
@@ -6,6 +6,12 @@ import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
|
|
|
6
6
|
* the caption on the first. Photos go as photos and other files as documents; consecutive files of
|
|
7
7
|
* one type go together as an album of at most ten, as long as one request carries them. Each
|
|
8
8
|
* request is one multipart call on the connection's `bot` API.
|
|
9
|
+
*
|
|
10
|
+
* A file sent by its signed read (`ChannelStoredFile`) goes alone in its message: the connection
|
|
11
|
+
* reads its bytes from the workspace's file storage and sends them inside the form the sender
|
|
12
|
+
* builds around them, so it is held to Telegram's own bounds, not to the connection's request
|
|
13
|
+
* body. Telegram also fetches files by URL, but only up to 5 MB for a photo and 20 MB for another
|
|
14
|
+
* file, and a document only as PDF or ZIP, so every file goes as an upload.
|
|
9
15
|
*/
|
|
10
16
|
/** The most bytes Telegram takes of a photo. */
|
|
11
17
|
export const TELEGRAM_PHOTO_BYTES = 10 * 1024 * 1024;
|
|
@@ -21,18 +27,24 @@ const PHOTOS = new Set(["image/jpeg", "image/png", "image/webp"]);
|
|
|
21
27
|
export function telegramFileType(contentType) {
|
|
22
28
|
return PHOTOS.has(contentType.toLowerCase().split(";")[0].trim()) ? "photo" : "document";
|
|
23
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* The most bytes of a file sent in a request's own body, which leaves room in the connection's
|
|
32
|
+
* request bound for the form around it. Files this small can go together as an album; a larger
|
|
33
|
+
* one goes by its signed read, alone in its message.
|
|
34
|
+
*/
|
|
35
|
+
export const TELEGRAM_INLINE_FILE_BYTES = MAXIMUM_CONNECTION_BODY_BYTES - CHANNEL_FILE_FRAME_BYTES;
|
|
24
36
|
/**
|
|
25
37
|
* Why Telegram cannot take this file through one connection request, or undefined when it can:
|
|
26
|
-
* `too_large` past Telegram's bound for its type or the
|
|
27
|
-
* bytes.
|
|
38
|
+
* `too_large` past Telegram's bound for its type or, unless the file may go by its signed read
|
|
39
|
+
* (`stored`), the connection's request bound; `empty` for no bytes.
|
|
28
40
|
*/
|
|
29
|
-
export function telegramFileRefusal(file) {
|
|
41
|
+
export function telegramFileRefusal(file, options = {}) {
|
|
30
42
|
const type = telegramFileType(file.contentType);
|
|
31
43
|
const maximum = type === "photo" ? TELEGRAM_PHOTO_BYTES : TELEGRAM_DOCUMENT_BYTES;
|
|
32
44
|
if (file.size > maximum) {
|
|
33
45
|
return { code: "too_large", message: `Telegram's ${type} limit is ${maximum} bytes.` };
|
|
34
46
|
}
|
|
35
|
-
if (file.size > MAXIMUM_CONNECTION_BODY_BYTES) {
|
|
47
|
+
if (options.stored !== true && file.size > MAXIMUM_CONNECTION_BODY_BYTES) {
|
|
36
48
|
return { code: "too_large", message: TELEGRAM_REQUEST_LIMIT };
|
|
37
49
|
}
|
|
38
50
|
if (file.size === 0) {
|
|
@@ -40,7 +52,7 @@ export function telegramFileRefusal(file) {
|
|
|
40
52
|
}
|
|
41
53
|
return undefined;
|
|
42
54
|
}
|
|
43
|
-
/** The most bytes of one file a single connection request can carry to Telegram. */
|
|
55
|
+
/** The most bytes of one file a single connection request can carry to Telegram in its body. */
|
|
44
56
|
export function telegramFileBytes(contentType) {
|
|
45
57
|
return Math.min(telegramFileType(contentType) === "photo" ? TELEGRAM_PHOTO_BYTES : TELEGRAM_DOCUMENT_BYTES, MAXIMUM_CONNECTION_BODY_BYTES);
|
|
46
58
|
}
|
|
@@ -96,10 +108,15 @@ export function telegramFormattingRefused(status, body) {
|
|
|
96
108
|
(/can't parse entities|cannot parse entities|entity (?:bounds|offset|length)|entities (?:are|too)/iu.test(body.description) ||
|
|
97
109
|
/unsupported (?:start tag|parse mode)/iu.test(body.description)));
|
|
98
110
|
}
|
|
99
|
-
/**
|
|
111
|
+
/**
|
|
112
|
+
* One multipart request of files: one file by its type's method, several as an album. Each file's
|
|
113
|
+
* part comes after every field, and a stored file's part is empty: its bytes are not here.
|
|
114
|
+
*/
|
|
100
115
|
async function multipart(target, files, caption) {
|
|
101
116
|
const form = new FormData();
|
|
102
|
-
const blob = (upload) => new Blob([Buffer.from(upload.file.bytes)], {
|
|
117
|
+
const blob = (upload) => new Blob(isStoredFile(upload.file) ? [] : [Buffer.from(upload.file.bytes)], {
|
|
118
|
+
type: upload.file.contentType,
|
|
119
|
+
});
|
|
103
120
|
form.set("chat_id", target.chatId);
|
|
104
121
|
if (target.messageThreadId !== undefined && /^\d+$/u.test(target.messageThreadId)) {
|
|
105
122
|
form.set("message_thread_id", target.messageThreadId);
|
|
@@ -109,7 +126,6 @@ async function multipart(target, files, caption) {
|
|
|
109
126
|
}
|
|
110
127
|
if (files.length === 1) {
|
|
111
128
|
const upload = files[0];
|
|
112
|
-
form.set(upload.type, blob(upload), upload.file.filename);
|
|
113
129
|
if (caption !== undefined) {
|
|
114
130
|
// The form sends its line breaks as CRLF anyway; the entities must count them so.
|
|
115
131
|
const sent = withCrlfLineBreaks(caption);
|
|
@@ -121,6 +137,8 @@ async function multipart(target, files, caption) {
|
|
|
121
137
|
form.set("parse_mode", caption.parseMode);
|
|
122
138
|
}
|
|
123
139
|
}
|
|
140
|
+
// Last, so that a stored file's bytes go right before the form's closing boundary.
|
|
141
|
+
form.set(upload.type, blob(upload), upload.file.filename);
|
|
124
142
|
}
|
|
125
143
|
else {
|
|
126
144
|
form.set("media", JSON.stringify(files.map((upload, index) => ({
|
|
@@ -148,6 +166,59 @@ async function multipart(target, files, caption) {
|
|
|
148
166
|
body: new Uint8Array(await request.arrayBuffer()),
|
|
149
167
|
};
|
|
150
168
|
}
|
|
169
|
+
const TELEGRAM_FRAME_LIMIT = `The form around a stored file exceeds the connection's ` +
|
|
170
|
+
`${CHANNEL_FILE_FRAME_BYTES}-byte bound before and after it.`;
|
|
171
|
+
/** A stored file's request that could not be built, so nothing of it was sent. */
|
|
172
|
+
class FramingError extends Error {
|
|
173
|
+
code;
|
|
174
|
+
name = "FramingError";
|
|
175
|
+
constructor(code, message, cause) {
|
|
176
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
177
|
+
this.code = code;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* The form of one stored file, split where its bytes go: everything before them, and the closing
|
|
182
|
+
* boundary after them. The form's last part is the file's, which is empty here, so what follows
|
|
183
|
+
* it is exactly the boundary's close.
|
|
184
|
+
*/
|
|
185
|
+
function framing(built) {
|
|
186
|
+
const boundary = /;\s*boundary="?([^";]+)"?/u.exec(built.contentType)?.[1];
|
|
187
|
+
const suffix = new TextEncoder().encode(`\r\n--${boundary ?? ""}--\r\n`);
|
|
188
|
+
const tail = built.body.subarray(built.body.byteLength - suffix.byteLength);
|
|
189
|
+
if (boundary === undefined ||
|
|
190
|
+
built.body.byteLength < suffix.byteLength ||
|
|
191
|
+
!Buffer.from(tail).equals(Buffer.from(suffix))) {
|
|
192
|
+
throw new FramingError("send_failed", "The form does not end with the file's part.");
|
|
193
|
+
}
|
|
194
|
+
return { prefix: built.body.slice(0, built.body.byteLength - suffix.byteLength), suffix };
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The call of one stored file's form: the form around the file's part as the call's prefix and
|
|
198
|
+
* suffix, and a fresh signed read of the file, which the connection reads and sends between them.
|
|
199
|
+
*/
|
|
200
|
+
async function storedCall(message, file) {
|
|
201
|
+
const { prefix, suffix } = framing(message);
|
|
202
|
+
if (prefix.byteLength > CHANNEL_FILE_FRAME_BYTES ||
|
|
203
|
+
suffix.byteLength > CHANNEL_FILE_FRAME_BYTES) {
|
|
204
|
+
throw new FramingError("too_large", TELEGRAM_FRAME_LIMIT);
|
|
205
|
+
}
|
|
206
|
+
let read;
|
|
207
|
+
try {
|
|
208
|
+
read = await file.read();
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
throw new FramingError("unavailable", "The file's signed read could not be had.", error);
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
api: "bot",
|
|
215
|
+
method: "POST",
|
|
216
|
+
path: `/${message.method}`,
|
|
217
|
+
headers: [["content-type", message.contentType]],
|
|
218
|
+
body: new Uint8Array(),
|
|
219
|
+
file: { ...read, start: 0, end: file.size - 1, prefix, suffix },
|
|
220
|
+
};
|
|
221
|
+
}
|
|
151
222
|
/** The message ids Telegram's answer to a batch names, one per file, or undefined. */
|
|
152
223
|
function messageIds(answer, count) {
|
|
153
224
|
if (!isRecord(answer) || answer.ok !== true) {
|
|
@@ -160,12 +231,18 @@ function messageIds(answer, count) {
|
|
|
160
231
|
? messages.map((message) => String(message.message_id))
|
|
161
232
|
: undefined;
|
|
162
233
|
}
|
|
234
|
+
/** A part whose request was never sent: nothing of it reached the person. */
|
|
235
|
+
function unsent(part, code, cause) {
|
|
236
|
+
return { ...part, status: "failed", messageIds: [], code, cause };
|
|
237
|
+
}
|
|
163
238
|
/**
|
|
164
239
|
* Sends `files` to `target` in their order, `caption` on the first message Telegram takes. Each
|
|
165
240
|
* album is one request and one part: `sent` when Telegram names its messages, `failed` when it
|
|
166
241
|
* refused them (`too_large` for 413, `forbidden` for 403, `send_failed` otherwise) or a request
|
|
167
|
-
* could not be built
|
|
168
|
-
*
|
|
242
|
+
* could not be built (`unavailable` for a stored file whose read could not be had), `uncertain`
|
|
243
|
+
* when its answer proves neither. A stored file goes alone, through a `request` that reads stored
|
|
244
|
+
* files. A refusal of the caption's formatting alone sends the album again without it. Nothing is
|
|
245
|
+
* retried otherwise.
|
|
169
246
|
*/
|
|
170
247
|
export async function sendTelegramFiles(options) {
|
|
171
248
|
const uploads = options.files.map((file, position) => ({
|
|
@@ -178,10 +255,13 @@ export async function sendTelegramFiles(options) {
|
|
|
178
255
|
let cursor = 0;
|
|
179
256
|
while (cursor < uploads.length) {
|
|
180
257
|
const batch = [uploads[cursor++]];
|
|
258
|
+
const first = batch[0].file;
|
|
181
259
|
let built = await multipart(options.target, batch, caption);
|
|
182
|
-
// An album holds files of one type only; the request's order is kept.
|
|
183
|
-
while (
|
|
260
|
+
// An album holds files of one type only, each sent inline; the request's order is kept.
|
|
261
|
+
while (!isStoredFile(first) &&
|
|
262
|
+
cursor < uploads.length &&
|
|
184
263
|
batch.length < TELEGRAM_FILES_PER_MESSAGE &&
|
|
264
|
+
!isStoredFile(uploads[cursor].file) &&
|
|
185
265
|
uploads[cursor].type === batch[0].type) {
|
|
186
266
|
const candidate = await multipart(options.target, [...batch, uploads[cursor]], caption);
|
|
187
267
|
if (candidate.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
|
|
@@ -191,35 +271,35 @@ export async function sendTelegramFiles(options) {
|
|
|
191
271
|
built = candidate;
|
|
192
272
|
}
|
|
193
273
|
const part = { files: batch.map((upload) => upload.index), text: caption !== undefined };
|
|
194
|
-
if (built.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
|
|
195
|
-
parts.push(
|
|
196
|
-
...part,
|
|
197
|
-
status: "failed",
|
|
198
|
-
messageIds: [],
|
|
199
|
-
code: "too_large",
|
|
200
|
-
cause: new Error(TELEGRAM_REQUEST_LIMIT),
|
|
201
|
-
});
|
|
274
|
+
if (!isStoredFile(first) && built.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
|
|
275
|
+
parts.push(unsent(part, "too_large", new Error(TELEGRAM_REQUEST_LIMIT)));
|
|
202
276
|
continue;
|
|
203
277
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
278
|
+
// A stored file's request reads the file afresh each time it is sent.
|
|
279
|
+
const call = (message) => isStoredFile(first)
|
|
280
|
+
? storedCall(message, first)
|
|
281
|
+
: Promise.resolve({
|
|
282
|
+
api: "bot",
|
|
283
|
+
method: "POST",
|
|
284
|
+
path: `/${message.method}`,
|
|
285
|
+
headers: [["content-type", message.contentType]],
|
|
286
|
+
body: message.body,
|
|
287
|
+
});
|
|
211
288
|
let reply;
|
|
212
289
|
try {
|
|
213
|
-
reply = await
|
|
290
|
+
reply = await options.request(await call(built));
|
|
214
291
|
if (caption !== undefined &&
|
|
215
292
|
(caption.entities.length > 0 || caption.parseMode !== undefined) &&
|
|
216
293
|
telegramFormattingRefused(reply.status, replyJson(reply))) {
|
|
217
294
|
caption = options.plainCaption ?? { text: caption.text, entities: [] };
|
|
218
|
-
|
|
295
|
+
built = await multipart(options.target, batch, caption);
|
|
296
|
+
reply = await options.request(await call(built));
|
|
219
297
|
}
|
|
220
298
|
}
|
|
221
299
|
catch (error) {
|
|
222
|
-
parts.push(
|
|
300
|
+
parts.push(error instanceof FramingError
|
|
301
|
+
? unsent(part, error.code, error)
|
|
302
|
+
: unrelayed(part, error, options.definite));
|
|
223
303
|
continue;
|
|
224
304
|
}
|
|
225
305
|
const answer = replyJson(reply);
|
package/dist/telegram.d.ts
CHANGED
|
@@ -66,6 +66,6 @@ export declare function telegramStartParam(page: string): string | undefined;
|
|
|
66
66
|
export declare function miniAppLink(url: string, origins: ReadonlySet<string>, botUsername: string): string | undefined;
|
|
67
67
|
/** A username Telegram accepts in a `t.me` link; any other leaves every link as it is. */
|
|
68
68
|
export declare function isTelegramBotUsername(username: string): boolean;
|
|
69
|
-
export type { ChannelCall, ChannelFile, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
|
|
70
|
-
export { ChannelAnswerError } from "./channel-files.js";
|
|
71
|
-
export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_PHOTO_BYTES, type TelegramEntity, type TelegramFilesTarget, type TelegramFormattedText, } from "./telegram-files.js";
|
|
69
|
+
export type { ChannelCall, ChannelCallFile, ChannelFile, ChannelFileRead, ChannelPart, ChannelReply, ChannelRequest, ChannelStoredFile, DefiniteFailure, } from "./channel-files.js";
|
|
70
|
+
export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
|
|
71
|
+
export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_INLINE_FILE_BYTES, TELEGRAM_PHOTO_BYTES, type TelegramEntity, type TelegramFilesTarget, type TelegramFormattedText, } from "./telegram-files.js";
|
package/dist/telegram.js
CHANGED
|
@@ -314,5 +314,5 @@ export function miniAppLink(url, origins, botUsername) {
|
|
|
314
314
|
export function isTelegramBotUsername(username) {
|
|
315
315
|
return /^[A-Za-z0-9_]{1,64}$/u.test(username);
|
|
316
316
|
}
|
|
317
|
-
export { ChannelAnswerError } from "./channel-files.js";
|
|
318
|
-
export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_PHOTO_BYTES, } from "./telegram-files.js";
|
|
317
|
+
export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
|
|
318
|
+
export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_INLINE_FILE_BYTES, TELEGRAM_PHOTO_BYTES, } from "./telegram-files.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.180.0",
|
|
4
4
|
"description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "SegmentStream",
|