@segmentstream/ontology 0.179.0 → 0.181.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/channel-files.d.ts +40 -0
  3. package/dist/channel-files.js +10 -0
  4. package/dist/review.d.ts +46 -0
  5. package/dist/review.js +47 -0
  6. package/dist/runtime/agents.js +28 -4
  7. package/dist/service/agent/protocol.d.ts +51 -0
  8. package/dist/service/agent/protocol.js +66 -1
  9. package/dist/service/agent/server.d.ts +8 -0
  10. package/dist/service/agent/server.js +166 -1
  11. package/dist/service/chat/archive.d.ts +8 -1
  12. package/dist/service/chat/delivery.js +3 -1
  13. package/dist/service/chat/providers/custom.js +2 -0
  14. package/dist/service/chat/providers/email.js +2 -2
  15. package/dist/service/chat/providers/provider.d.ts +15 -2
  16. package/dist/service/chat/providers/provider.js +18 -1
  17. package/dist/service/chat/reply-proposal.d.ts +122 -0
  18. package/dist/service/chat/reply-proposal.js +385 -0
  19. package/dist/service/chat/review-delivery.d.ts +131 -24
  20. package/dist/service/chat/review-delivery.js +393 -296
  21. package/dist/service/chat/store-delivery.d.ts +27 -5
  22. package/dist/service/chat/store-delivery.js +45 -33
  23. package/dist/service/runtime-contract.d.ts +30 -0
  24. package/dist/service/service.js +12 -4
  25. package/dist/slack-files.d.ts +23 -5
  26. package/dist/slack-files.js +108 -16
  27. package/dist/slack.d.ts +3 -3
  28. package/dist/slack.js +2 -2
  29. package/dist/telegram-files.d.ts +27 -7
  30. package/dist/telegram-files.js +111 -31
  31. package/dist/telegram.d.ts +3 -3
  32. package/dist/telegram.js +2 -2
  33. package/dist/workspace-channel.d.ts +6 -0
  34. package/dist/workspace-channel.js +27 -0
  35. package/package.json +5 -1
@@ -1,23 +1,45 @@
1
1
  import { Effect } from "effect";
2
- import { type ChatMessageStore } from "../../runtime/chat-messages.js";
2
+ import { type ChatMessageStore, type ChatSend } from "../../runtime/chat-messages.js";
3
3
  import type { OntologyBackend } from "../runtime-contract.js";
4
- import { type DeliveryArchive } from "./archive.js";
4
+ import { type DeliveryArchive, type DeliveryReceipt } from "./archive.js";
5
5
  /**
6
6
  * A delivery's key on the store: one per caller scope and idempotency key, an opaque digest of
7
7
  * both, so neither digest is shown to the chat's readers. No channel's queue of sends due holds it.
8
8
  */
9
9
  export declare function deliveryOperation(scope: string, key: string): string;
10
+ /** The whole reply a proposal's first message belongs to, as its row keeps it; none otherwise. */
11
+ export declare function sendBinding(row: ChatSend): string | undefined;
12
+ /**
13
+ * What a key's delivery answers, from its row. Reported, a `sent` receipt whose message the
14
+ * provider later reported failed reads `failed` with its refusal; the receipt phase reads the
15
+ * receipt as recorded, which its caller compares with its own outcome. `operation` names the
16
+ * attempt that reserved it where the row no longer does, its `meta` gone with a deletion or
17
+ * retention. A row past `retentionDays` or scrubbed to its tombstone answers its outcome without
18
+ * its message.
19
+ */
20
+ export declare function storedReceipt(row: ChatSend, input: {
21
+ readonly operation: string;
22
+ readonly retentionDays: number;
23
+ readonly reported: boolean;
24
+ readonly inserted?: boolean;
25
+ }): DeliveryReceipt;
10
26
  /**
11
27
  * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
12
28
  * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
13
29
  * request claims nothing and answers the row's receipt, and another request is a conflict. Only
14
30
  * the claim records the receipt, once; another outcome for it is a conflict. A row past
15
- * `retentionDays` or scrubbed to its tombstone answers its outcome without its message.
31
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message. A `sent`
32
+ * receipt names the provider's id of the message, unless `unnamedSends`: the channel's provider may
33
+ * take a message without naming it, as a workspace channel's code may.
16
34
  */
17
- export declare function storeDeliveryArchive(store: ChatMessageStore, retentionDays: number): DeliveryArchive;
35
+ export declare function storeDeliveryArchive(store: ChatMessageStore, retentionDays: number, options?: {
36
+ readonly unnamedSends?: boolean;
37
+ }): DeliveryArchive;
18
38
  /**
19
39
  * Where a delivery reserves and receipts its key: the workspace chat store once it holds a message,
20
40
  * the evidence that the agent records there, as a chat's history is imported there from then on.
21
41
  * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
22
42
  */
23
- export declare function deliveryArchiveOf(backend: OntologyBackend["Service"], cloud: DeliveryArchive, retentionDays: number): Effect.Effect<DeliveryArchive>;
43
+ export declare function deliveryArchiveOf(backend: OntologyBackend["Service"], cloud: DeliveryArchive, retentionDays: number, options?: {
44
+ readonly unnamedSends?: boolean;
45
+ }): Effect.Effect<DeliveryArchive>;
@@ -61,6 +61,11 @@ function object(value) {
61
61
  ? value
62
62
  : undefined;
63
63
  }
64
+ /** The whole reply a proposal's first message belongs to, as its row keeps it; none otherwise. */
65
+ export function sendBinding(row) {
66
+ const binding = object(object(row.meta)?.delivery)?.binding;
67
+ return typeof binding === "string" ? binding : undefined;
68
+ }
64
69
  function claimOf(row) {
65
70
  const claim = object(object(row.meta)?.delivery);
66
71
  return {
@@ -101,43 +106,47 @@ const conflict = (reason, cause) => new DeliveryArchiveError({
101
106
  });
102
107
  /** The store could not be read or written: nothing was reserved, or the receipt is not recorded. */
103
108
  const storeFailure = (diagnostic, cause) => Effect.fail(new DeliveryArchiveError({ diagnostic, cause }));
109
+ /**
110
+ * What a key's delivery answers, from its row. Reported, a `sent` receipt whose message the
111
+ * provider later reported failed reads `failed` with its refusal; the receipt phase reads the
112
+ * receipt as recorded, which its caller compares with its own outcome. `operation` names the
113
+ * attempt that reserved it where the row no longer does, its `meta` gone with a deletion or
114
+ * retention. A row past `retentionDays` or scrubbed to its tombstone answers its outcome without
115
+ * its message.
116
+ */
117
+ export function storedReceipt(row, input) {
118
+ const claim = claimOf(row);
119
+ const recorded = recordedOf(row);
120
+ const expired = row.purged || Date.parse(row.at) < Date.now() - input.retentionDays * DAY_MS;
121
+ const retained = !expired && recorded !== undefined;
122
+ const failedLater = input.reported && recorded === "sent" && row.status === "failed";
123
+ const status = failedLater ? "failed" : (recorded ?? "uncertain");
124
+ // Retention scrubs a refusal with the message, as the archive in Cloud did.
125
+ const reason = status === "failed" && !row.purged ? row.failure : null;
126
+ return {
127
+ version: 1,
128
+ claimed: false,
129
+ duplicate: input.inserted !== true,
130
+ operationId: claim.operation ?? input.operation,
131
+ status,
132
+ messageId: retained ? row.messageId : null,
133
+ url: retained ? (claim.url ?? null) : null,
134
+ historyRecorded: retained,
135
+ ...(status === "failed" && reason !== null && REFUSAL.test(reason) ? { refusal: reason } : {}),
136
+ };
137
+ }
104
138
  /**
105
139
  * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
106
140
  * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
107
141
  * request claims nothing and answers the row's receipt, and another request is a conflict. Only
108
142
  * the claim records the receipt, once; another outcome for it is a conflict. A row past
109
- * `retentionDays` or scrubbed to its tombstone answers its outcome without its message.
143
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message. A `sent`
144
+ * receipt names the provider's id of the message, unless `unnamedSends`: the channel's provider may
145
+ * take a message without naming it, as a workspace channel's code may.
110
146
  */
111
- export function storeDeliveryArchive(store, retentionDays) {
147
+ export function storeDeliveryArchive(store, retentionDays, options = {}) {
112
148
  const expired = (row) => row.purged || Date.parse(row.at) < Date.now() - retentionDays * DAY_MS;
113
- /**
114
- * What a key's delivery answers. Reported, a `sent` receipt whose message the provider later
115
- * reported failed reads `failed` with its refusal; the receipt phase reads the receipt as
116
- * recorded, which its caller compares with its own outcome. `operation` names the attempt that
117
- * reserved it where the row no longer does, its `meta` gone with a deletion or retention.
118
- */
119
- const answer = (row, operation, reported, inserted = false) => {
120
- const claim = claimOf(row);
121
- const recorded = recordedOf(row);
122
- const retained = !expired(row) && recorded !== undefined;
123
- const failedLater = reported && recorded === "sent" && row.status === "failed";
124
- const status = failedLater ? "failed" : (recorded ?? "uncertain");
125
- // Retention scrubs a refusal with the message, as the archive in Cloud did.
126
- const reason = status === "failed" && !row.purged ? row.failure : null;
127
- return {
128
- version: 1,
129
- claimed: false,
130
- duplicate: !inserted,
131
- operationId: claim.operation ?? operation,
132
- status,
133
- messageId: retained ? row.messageId : null,
134
- url: retained ? (claim.url ?? null) : null,
135
- historyRecorded: retained,
136
- ...(status === "failed" && reason !== null && REFUSAL.test(reason)
137
- ? { refusal: reason }
138
- : {}),
139
- };
140
- };
149
+ const answer = (row, operation, reported, inserted = false) => storedReceipt(row, { operation, retentionDays, reported, inserted });
141
150
  /** The key's row, which a reservation that found it must have. */
142
151
  const sendOf = (operation) => store
143
152
  .findSend(operation)
@@ -191,6 +200,7 @@ export function storeDeliveryArchive(store, retentionDays) {
191
200
  // while the request alone still finds the key's receipt.
192
201
  fingerprint: `${delivery.fingerprint}:${payloadFingerprint(event)}`,
193
202
  ...(event.sessionId === null ? {} : { sessionId: event.sessionId }),
203
+ ...(event.turnId === null ? {} : { turnId: event.turnId }),
194
204
  meta: {
195
205
  ...payloadOf(event),
196
206
  delivery: {
@@ -201,6 +211,7 @@ export function storeDeliveryArchive(store, retentionDays) {
201
211
  via: requester.via,
202
212
  clientId: requester.clientId,
203
213
  },
214
+ ...(event.binding === undefined ? {} : { binding: event.binding }),
204
215
  },
205
216
  },
206
217
  };
@@ -224,7 +235,8 @@ export function storeDeliveryArchive(store, retentionDays) {
224
235
  });
225
236
  const receipt = (event, delivery) => Effect.gen(function* () {
226
237
  const status = event.status;
227
- if (status === "requested" || (status === "sent" && event.messageId === null)) {
238
+ if (status === "requested" ||
239
+ (status === "sent" && event.messageId === null && options.unnamedSends !== true)) {
228
240
  return yield* new DeliveryArchiveError({ diagnostic: "chat_store_invalid_receipt" });
229
241
  }
230
242
  const operation = deliveryOperation(delivery.scope, delivery.key);
@@ -301,7 +313,7 @@ export function storeDeliveryArchive(store, retentionDays) {
301
313
  * the evidence that the agent records there, as a chat's history is imported there from then on.
302
314
  * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
303
315
  */
304
- export function deliveryArchiveOf(backend, cloud, retentionDays) {
316
+ export function deliveryArchiveOf(backend, cloud, retentionDays, options = {}) {
305
317
  const store = backend.agents?.chatMessages;
306
318
  // @legacy agent.cloud-chat-archive Until the agent records into the store, the archive in Cloud
307
319
  // reserves and receipts the delivery, as it keeps the agent's messages.
@@ -310,5 +322,5 @@ export function deliveryArchiveOf(backend, cloud, retentionDays) {
310
322
  }
311
323
  return store
312
324
  .holds()
313
- .pipe(Effect.map((held) => (held ? storeDeliveryArchive(store, retentionDays) : cloud)));
325
+ .pipe(Effect.map((held) => (held ? storeDeliveryArchive(store, retentionDays, options) : cloud)));
314
326
  }
@@ -728,6 +728,31 @@ export interface AgentStore {
728
728
  * not an active member of the app. Absent on stores that predate reviews.
729
729
  */
730
730
  readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
731
+ /**
732
+ * A reply the agent proposed, held under the lock `holdReply` takes on its key, once per key and
733
+ * only while `delivered`, read under that lock, finds no delivery of it: `delivered` when one
734
+ * began, and nothing is held. With {@link AgentStore.reserveProposal}, which takes the same lock,
735
+ * one proposal of a key decides it, however proposals of it overlap: a reply once held is never
736
+ * sent, nor one sent held. `undefined` when its person is no active member. Absent on stores
737
+ * that predate proposals.
738
+ */
739
+ readonly holdProposal?: (input: HeldReplyInput, delivered: Effect.Effect<boolean>) => Effect.Effect<HeldReview | "delivered" | undefined>;
740
+ /**
741
+ * Reserves a proposed reply's delivery under the lock its hold takes, in one transaction with
742
+ * `reserve`, the reservation on the chat store, only while no draft holds its key: `held` with
743
+ * that draft otherwise, and nothing is reserved. The lock is released with the transaction,
744
+ * before the provider is called. Absent on stores that predate proposals.
745
+ */
746
+ readonly reserveProposal?: <A, E>(input: {
747
+ readonly key: string;
748
+ readonly reserve: Effect.Effect<A, E>;
749
+ }) => Effect.Effect<{
750
+ readonly kind: "reserved";
751
+ readonly value: A;
752
+ } | {
753
+ readonly kind: "held";
754
+ readonly review: HeldReview;
755
+ }, E>;
731
756
  /**
732
757
  * Holds a reply the agent redrafted at a member's request: a pending review that replaces the one
733
758
  * it redrafts, which becomes `superseded`. `discarded` when that review was decided, or another
@@ -858,6 +883,11 @@ export interface HeldReplyInput {
858
883
  };
859
884
  /** The agent's turn that wrote the reply; absent from agents that predate it. */
860
885
  readonly turnId?: string;
886
+ /**
887
+ * Where the chat stood when the turn read it, `<time>~<id>`, as a proposed reply names it: the
888
+ * draft's basis. Without it, the newest message the turn took in the chat store.
889
+ */
890
+ readonly basis?: string;
861
891
  }
862
892
  /** A reply the agent redrafted, as `POST /api/ontology/agent/drafts/revision` reports it. */
863
893
  export interface RevisedReplyInput {
@@ -23,6 +23,7 @@ import { workspaceSourceLayer } from "./agent/source.js";
23
23
  import { platformChatArchive } from "./agent/chat-archive.js";
24
24
  import { archiveRoutes } from "./agent/archive-routes.js";
25
25
  import { makeChatDelivery } from "./chat/delivery.js";
26
+ import { replyProposals } from "./chat/reply-proposal.js";
26
27
  import { platformDeliveryArchive } from "./chat/archive.js";
27
28
  import { platformHistoryArchive } from "./chat/history-import.js";
28
29
  import { chatRoutes } from "./chat/routes.js";
@@ -383,14 +384,14 @@ export function createOntologyService(ontology, config) {
383
384
  const replicate = deployedReplication(config);
384
385
  // The platform keeps chat history for production agents only.
385
386
  const chatHistory = config.runtimeIdentity === undefined || preview ? undefined : platformChatArchive(config);
386
- const chatDelivery = makeChatDelivery(ontology, connections,
387
387
  // @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message.
388
- config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
388
+ const deliveries = config.chatArchive ?? platformDeliveryArchive(config);
389
389
  // The app's agent sends through a workspace channel, at the origin it takes its tasks at.
390
- {
390
+ const agentChannels = {
391
391
  origin: config.agentOrigin,
392
392
  ...(config.agentTaskTransport === undefined ? {} : { fetch: config.agentTaskTransport }),
393
- }, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
393
+ };
394
+ const chatDelivery = makeChatDelivery(ontology, connections, deliveries, { settings: config.channels?.telegram, ownOrigins: config.appOrigins }, agentChannels, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
394
395
  const metricQueries = makeMetricQueries({
395
396
  ontology,
396
397
  transport: platformMetricQueries({ ...config, manifestHash: ontology.manifest.hash }),
@@ -478,6 +479,13 @@ export function createOntologyService(ontology, config) {
478
479
  }),
479
480
  emailSignUp: signUpRolesOf(ontology.manifest, "email") !== undefined,
480
481
  manifest: ontology.manifest,
482
+ // The turn replies the agent proposes go as approved drafts do, through its channels.
483
+ replies: replyProposals({
484
+ ontology,
485
+ connections,
486
+ cloud: deliveries,
487
+ agent: agentChannels,
488
+ }),
481
489
  emailCodes,
482
490
  cronSecret: config.cronSecret,
483
491
  chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
@@ -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 and the bytes on its `files` 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
- /** Why Slack cannot take this file through one connection request, or undefined when it can. */
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;
@@ -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 and the bytes on its `files` 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
- /** Why Slack cannot take this file through one connection request, or undefined when it can. */
27
- export function slackFileRefusal(file) {
28
- if (file.size > SLACK_FILE_BYTES) {
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.bytes.byteLength),
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 = await options.request({
95
- api: "files",
96
- method: "POST",
97
- path: `/${ticket.upload_url.slice(SLACK_FILES.length)}`,
98
- headers: [["content-type", file.contentType]],
99
- body: file.bytes,
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";
@@ -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 connection's request bound, `empty` for no
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, `uncertain` when its answer proves neither. A refusal of the caption's
73
- * formatting alone sends the album again without it. Nothing is retried otherwise.
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;