@segmentstream/agent 0.94.0 → 0.96.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 CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.96.0
4
+
5
+ Allow a workspace to bind a read-only knowledge lookup for isolated group replies. Only the public facts returned by the workspace enter the reply model. Research runs after admission and shares the guest’s usage budget.
6
+
7
+ ## 0.95.0
8
+
9
+ Workspace channels take files by link, with a file limit of their own and the provider's
10
+ refusals.
11
+
12
+ - **Files by link.** Each file `send` receives is `{ filename, contentType, size, url, read() }`.
13
+ `url` is a short-lived link to the file in the workspace's file storage, to hand to a provider
14
+ that fetches files itself. `read()` reads the bytes once and checks their size. The ontology and
15
+ `segmentstream__attachments_send` no longer put files' bytes in the send route's request, so a
16
+ message can carry more than 3 MiB.
17
+ - **`limits.fileBytes`.** The most bytes of files one message carries, up to 64 MiB, 3 MiB when
18
+ absent. Files past it are refused (`file_too_large`) and nothing is sent.
19
+ - **`file` on the connection.** The channel's connection takes `file`, one of the files `send` was
20
+ given, as the whole body of a `POST`, `PUT` or `PATCH`. SegmentStream reads it from file storage,
21
+ up to 64 MiB, so its bytes never pass through the function.
22
+ - **Refusals.** `send` may return `{ refusal }`: `outside_reply_window`, `recipient_unreachable`
23
+ or `recipient_opted_out`. The message sent nothing, and the platform records the refusal as
24
+ WhatsApp's.
25
+
26
+ Action required for a workspace channel whose `send` reads `file.bytes`: call `await file.read()`,
27
+ or hand `file.url` to the provider. `bytes` is deprecated and present only while a message's files
28
+ are at most 3 MiB together. Upgrade the agent and ontology SDKs together; each still works with
29
+ the other's previous release.
30
+
31
+ Pins @segmentstream/ontology 0.177.0.
32
+
3
33
  ## 0.94.0
4
34
 
5
35
  The ontology's replies to mail, a draft a member approves and a staff reply from the inbox, are
package/README.md CHANGED
@@ -1101,3 +1101,16 @@ or sender. Its configured connection, session recovery, pairing and normal
1101
1101
  ontology authority still apply. The calling channel must authenticate and
1102
1102
  authorize its caller and choose the intended destination before forwarding.
1103
1103
  The reference alone grants no access or messaging authority.
1104
+
1105
+ ## Grounding replies in opened groups
1106
+
1107
+ For an isolated group answer, the workspace can declare `publicGroups.knowledge`
1108
+ with a `connection` key and localized `unavailable` text in its agent configuration.
1109
+ In the agent's extension mount, add a `lookup` function to that object. Its
1110
+ `PublicGroupKnowledgeContext` supplies the current question, a bounded GET on
1111
+ the named connection, a metered private model call and an abort signal. No
1112
+ member session or conversation history is supplied. Only return facts that may
1113
+ be published to everyone in the group. Those facts and the question enter the
1114
+ ordinary answer model; neither model gets a connection tool or credentials.
1115
+ An empty result, unavailable source or missing runtime binding uses the
1116
+ workspace's fallback text. Closed groups and rejected turns do not run a lookup.
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- var version = "0.94.0";
7
+ var version = "0.96.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -2,6 +2,7 @@ import { type GroupPolicyInput } from "@segmentstream/ontology/groups";
2
2
  import { type GroupPolicy } from "./lib/group-routing/policy.js";
3
3
  import { type QuoteSettings } from "./lib/email/quote-settings.js";
4
4
  import { type StructuredInbound } from "./lib/telegram/structured-settings.js";
5
+ import type { PublicGroupKnowledge } from "./lib/public-group-knowledge.js";
5
6
  import type { WorkspaceActionHook } from "./lib/workspace-action.js";
6
7
  import { type TelegramTexts } from "./lib/telegram/texts.js";
7
8
  import { type IdentifierPolicy } from "./lib/customer-text-safety.js";
@@ -76,6 +77,7 @@ export interface FirstContactSettings {
76
77
  export declare const ADMISSION_REPLY_KEYS: readonly ["pairingRequired", "pairingButton", "groupPairingButton", "limited", "perSenderLimited", "workspaceLimited", "registrationsLimited", "groupPairingRequired", "refused"];
77
78
  export type AdmissionReplies = Partial<Record<(typeof ADMISSION_REPLY_KEYS)[number], LocalizedText>>;
78
79
  export interface PublicGroupSettings {
80
+ readonly knowledge?: PublicGroupKnowledge;
79
81
  readonly model: string;
80
82
  /** Workspace-published material for an isolated, text-only answer. */
81
83
  readonly instructions: string;
@@ -1298,18 +1298,47 @@ function validateConfig(input, options = {}) {
1298
1298
  allowed: [
1299
1299
  "model",
1300
1300
  "instructions",
1301
- "trustedJoinChannels"
1301
+ "trustedJoinChannels",
1302
+ "knowledge"
1302
1303
  ],
1303
1304
  issues
1304
1305
  });
1305
1306
  let publicGroups;
1306
1307
  if (publicGroupInput) {
1307
1308
  const { model, instructions, trustedJoinChannels } = publicGroupInput;
1309
+ const knowledge = section({
1310
+ value: publicGroupInput.knowledge,
1311
+ path: ["publicGroups", "knowledge"],
1312
+ allowed: [
1313
+ "connection",
1314
+ "lookup",
1315
+ "unavailable"
1316
+ ],
1317
+ issues
1318
+ });
1319
+ let source;
1320
+ if (knowledge) {
1321
+ const unavailable = localizedText(knowledge.unavailable, [
1322
+ "publicGroups",
1323
+ "knowledge",
1324
+ "unavailable"
1325
+ ], issues, 1e3);
1326
+ if (typeof knowledge.connection !== "string" || !CONNECTION_KEY.test(knowledge.connection) || knowledge.lookup !== void 0 && typeof knowledge.lookup !== "function") issues.push({
1327
+ path: ["publicGroups", "knowledge"],
1328
+ message: "Supply a workspace connection and bind a lookup function in the agent mount."
1329
+ });
1330
+ else source = {
1331
+ connection: knowledge.connection,
1332
+ unavailable,
1333
+ ...knowledge.lookup && { lookup: knowledge.lookup }
1334
+ };
1335
+ }
1308
1336
  if (typeof model !== "string" || !model.trim() || model.length > 256 || typeof instructions !== "string" || !instructions.trim() || instructions.length > 32e3 || trustedJoinChannels !== void 0 && (!Array.isArray(trustedJoinChannels) || !trustedJoinChannels.every((channel) => typeof channel === "string" && Object.hasOwn(channels ?? {}, channel)))) issues.push({
1309
1337
  path: ["publicGroups"],
1310
1338
  message: "Supply a model, public instructions and optional configured channel names."
1311
1339
  });
1312
1340
  else publicGroups = {
1341
+ ...source && { knowledge: source },
1313
1342
  model,
1314
1343
  instructions,
1315
1344
  ...trustedJoinChannels ? { trustedJoinChannels } : {}
@@ -60,3 +60,4 @@ export { replayRouterPayload } from "./lib/group-routing/replay.js";
60
60
  export { chatAddressing as groupChatAddressing } from "./lib/group-routing/addressing.js";
61
61
  export { routingBurst } from "./lib/group-routing/burst.js";
62
62
  export type { TelegramTexts } from "./lib/telegram/texts.js";
63
+ export type { PublicGroupKnowledge, PublicGroupKnowledgeContext, } from "./lib/public-group-knowledge.js";
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { t as agentBuild } from "../../_chunks/build-metadata-Da-608Iv.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-_7QBVYuN.mjs";
@@ -26,6 +26,18 @@ export interface ProxyCall {
26
26
  readonly path: string;
27
27
  readonly headers: ReadonlyArray<readonly [string, string]>;
28
28
  readonly body: Uint8Array;
29
+ /**
30
+ * A file in the workspace's file storage, by its signed read, that the proxy reads and sends as
31
+ * the body in place of `body`, which is then empty: up to 64 MiB, never through this function.
32
+ */
33
+ readonly file?: ProxyFile;
34
+ }
35
+ /** The signed read of a byte range of a stored file, as the proxy reads it. */
36
+ export interface ProxyFile {
37
+ readonly url: string;
38
+ readonly headers: ReadonlyArray<readonly [string, string]>;
39
+ readonly start: number;
40
+ readonly end: number;
29
41
  }
30
42
  /** What the provider answered, buffered by the proxy. */
31
43
  export interface ProxyReply {
@@ -78,7 +78,7 @@ function connectionProxy(input) {
78
78
  method: call.method,
79
79
  path: call.path,
80
80
  headers: call.headers,
81
- body: Buffer.from(call.body).toString("base64")
81
+ ...call.file === void 0 ? { body: Buffer.from(call.body).toString("base64") } : { file: call.file }
82
82
  }),
83
83
  redirect: "error",
84
84
  signal: abortSignal === void 0 ? AbortSignal.timeout(CALL_TIMEOUT_MS) : AbortSignal.any([abortSignal, AbortSignal.timeout(CALL_TIMEOUT_MS)])
@@ -0,0 +1,16 @@
1
+ import { type ChannelConnectionRequestOptions } from "./workspace-channel/connection.js";
2
+ export interface PublicGroupKnowledgeContext {
3
+ readonly question: string;
4
+ readonly signal: AbortSignal;
5
+ /** GET against the one workspace connection bound to this source. Never a model tool. */
6
+ readonly get: (path: string, options?: Pick<ChannelConnectionRequestOptions, "api" | "headers" | "query">) => Promise<string>;
7
+ /** A private, tool-free model call, metered against the same guest budget. */
8
+ readonly reason: (instructions: string, input: string) => Promise<string>;
9
+ }
10
+ /** Trusted workspace code returns only information it permits the group to see. */
11
+ export interface PublicGroupKnowledge {
12
+ readonly connection: string;
13
+ readonly unavailable: Readonly<Record<string, string>>;
14
+ readonly lookup?: (context: PublicGroupKnowledgeContext) => Promise<readonly string[]>;
15
+ }
16
+ export declare function publicGroupEvidence(source: PublicGroupKnowledge, question: string, reason: PublicGroupKnowledgeContext["reason"], signal: AbortSignal): Promise<readonly string[]>;
@@ -0,0 +1,44 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { connectionProxy } from "./connection-proxy.mjs";
8
+ import { proxyEnvironment } from "./environment.mjs";
9
+ import { runtimeToken } from "./runtime-token.mjs";
10
+ import { connectionCall } from "./workspace-channel/connection.mjs";
11
+ async function publicGroupEvidence(source, question, reason, signal) {
12
+ if (!source.lookup) return [];
13
+ let reads = 0;
14
+ let calls = 0;
15
+ try {
16
+ return (await source.lookup({
17
+ question,
18
+ signal,
19
+ reason: (instructions, input) => {
20
+ signal.throwIfAborted();
21
+ if (++calls > 3 || input.length > 6e4 || instructions.length > 8e3) throw new Error("Public research model limit exceeded.");
22
+ return reason(instructions, input);
23
+ },
24
+ get: async (path, options) => {
25
+ signal.throwIfAborted();
26
+ if (++reads > 10) throw new Error("Public research read limit exceeded.");
27
+ const result = await connectionProxy({
28
+ environment: proxyEnvironment(),
29
+ connection: source.connection,
30
+ token: runtimeToken
31
+ }).request(connectionCall({
32
+ ...options,
33
+ method: "GET",
34
+ path
35
+ }), signal);
36
+ if (result.status < 200 || result.status >= 300) throw new Error(`Knowledge source returned HTTP ${result.status}.`);
37
+ return new TextDecoder().decode(result.body);
38
+ }
39
+ })).filter((fact) => typeof fact === "string" && fact.length <= 1e3).slice(0, 8);
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+ export { publicGroupEvidence };
@@ -7,6 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { localizedText } from "./admission.mjs";
8
8
  import { chatRuntimeRequest } from "./chat-persona.mjs";
9
9
  import { ontologyGuestUsage } from "./guest-usage.mjs";
10
+ import { publicGroupEvidence } from "./public-group-knowledge.mjs";
10
11
  import { gatewayCostOf } from "./web-search.mjs";
11
12
  import { gateway, generateText } from "ai";
12
13
  async function isPublicGroup(admission, channel, chat, sender) {
@@ -40,25 +41,39 @@ async function answerPublicGroup(input) {
40
41
  return true;
41
42
  }
42
43
  if (turn?.status !== "admitted" || typeof turn.guestId !== "string") throw new Error("Invalid public group admission.");
43
- const reply = await generateText({
44
- model: gateway(settings.model),
45
- system: settings.instructions,
46
- prompt: input.text.slice(0, 8e3),
47
- maxRetries: 0,
48
- maxOutputTokens: 600,
49
- abortSignal: AbortSignal.timeout(3e4)
44
+ const guestId = turn.guestId;
45
+ const question = input.text.slice(0, 8e3);
46
+ const researchDeadline = AbortSignal.timeout(3e4);
47
+ const messageKey = JSON.stringify([
48
+ input.channel,
49
+ input.chat,
50
+ input.message
51
+ ]);
52
+ let stage = 0;
53
+ const generate = async (system, prompt, privateCall = false) => {
54
+ const usageKey = privateCall ? `research:${++stage}:${messageKey}` : messageKey;
55
+ const reply = await generateText({
56
+ model: gateway(settings.model),
57
+ system,
58
+ prompt,
59
+ maxRetries: 0,
60
+ maxOutputTokens: privateCall ? 1e3 : 600,
61
+ abortSignal: privateCall ? researchDeadline : AbortSignal.timeout(3e4)
62
+ });
63
+ const costUsd = gatewayCostOf(reply.providerMetadata);
64
+ if (costUsd > 0) await ontologyGuestUsage()({
65
+ guestId,
66
+ costUsd,
67
+ key: usageKey.slice(0, 256)
68
+ });
69
+ return reply.text.trim();
70
+ };
71
+ const evidence = settings.knowledge ? await publicGroupEvidence(settings.knowledge, question, (system, prompt) => generate(system, prompt, true), researchDeadline) : void 0;
72
+ const prompt = evidence === void 0 ? question : JSON.stringify({
73
+ question,
74
+ evidence
50
75
  });
51
- const costUsd = gatewayCostOf(reply.providerMetadata);
52
- if (costUsd > 0) await ontologyGuestUsage()({
53
- guestId: turn.guestId,
54
- costUsd,
55
- key: JSON.stringify([
56
- input.channel,
57
- input.chat,
58
- input.message
59
- ]).slice(0, 256)
60
- });
61
- const text = reply.text.trim();
76
+ const text = settings.knowledge && !evidence?.length ? localizedText(settings.knowledge.unavailable, input.locale) : await generate(settings.instructions, prompt);
62
77
  if (!text) throw new Error("The public group answer was empty.");
63
78
  await input.post(text.slice(0, 3500));
64
79
  delivered = true;
@@ -12,7 +12,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
12
12
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
13
13
  import { handleWorkspaceCallback } from "./callbacks.mjs";
14
14
  import { telegramText, withTelegramTexts } from "./texts.mjs";
15
- import { t as agentBuild } from "../../../_chunks/build-metadata-Da-608Iv.mjs";
15
+ import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.mjs";
16
16
  import { attachmentLifecycle } from "./lifecycle.mjs";
17
17
  import { manifestOf } from "../../config.mjs";
18
18
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { t as agentBuild } from "../../../_chunks/build-metadata-Da-608Iv.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.mjs";
8
8
  import { runtimeRequestFailure } from "./runtime-request.mjs";
9
9
  import { GET } from "eve/channels";
10
10
  const HEALTH_ROUTE = "/eve/v1/telegram/health";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { E as OntologyActionNotPermitted, Et as principalRuntimeSource, L as needsConfirmation, Ot as runtimeEnvelope, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as telegramRuntimeSource } from "../../../_chunks/principal-DL9NdRRP.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-Da-608Iv.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -3,14 +3,18 @@ import { type AttachmentSendFailure, type AttachmentSendRefusal } from "../attac
3
3
  import { type Environment } from "../environment.js";
4
4
  import type { RuntimeToken } from "../runtime-token.js";
5
5
  import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
6
- /** The most bytes of files one message carries, as the workspace channel contract declares. */
6
+ /**
7
+ * The most bytes of files one message carries on any workspace channel; the channel's send route
8
+ * refuses those past its own `limits.fileBytes`.
9
+ */
7
10
  export declare const MAXIMUM_SENT_FILE_BYTES: number;
8
11
  /**
9
12
  * `attachments_send` in a chat of a channel the workspace defines in its own code: the stored
10
13
  * files go in one message, the caption as its text, through the channel's own `send`, which the
11
- * agent reaches at the channel's send route as the deployment, as the ontology does. A channel
12
- * whose code takes no files (`limits.files`) refuses them. The checks and failures are every
13
- * channel's (`../attachments-send.ts`).
14
+ * agent reaches at the channel's send route as the deployment, as the ontology does. Each file
15
+ * goes by a short-lived link, never its bytes. A channel whose code takes no files
16
+ * (`limits.files`) refuses them, and one refuses files past its `limits.fileBytes`. The checks and
17
+ * failures are every channel's (`../attachments-send.ts`).
14
18
  */
15
19
  /** What became of one requested file. */
16
20
  export interface ChannelSentFile extends Partial<AttachmentSendFailure> {
@@ -8,10 +8,10 @@ import { It as chatChannel, _ as AttachmentError } from "../../../_chunks/princi
8
8
  import { sendStoredAttachments } from "../attachments-send.mjs";
9
9
  import { redactDiagnostic } from "../diagnostics.mjs";
10
10
  import { ontologyDeploymentHeaders } from "../environment.mjs";
11
- import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
11
+ import { StoredFileError, storedFileGrant } from "../sent-files.mjs";
12
12
  import { randomUUID } from "node:crypto";
13
- import { WORKSPACE_CHANNEL_FILES_BYTES, workspaceChannelFiles, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
14
- const MAXIMUM_SENT_FILE_BYTES = WORKSPACE_CHANNEL_FILES_BYTES;
13
+ import { WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES, isWorkspaceChannelRefusal, workspaceChannelFiles, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
14
+ const MAXIMUM_SENT_FILE_BYTES = WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES;
15
15
  const TOO_LARGE = `One message carries at most ${MAXIMUM_SENT_FILE_BYTES / 1024 / 1024} MiB of files.`;
16
16
  function reportChannelError(operation, error, secrets) {
17
17
  const reference = randomUUID();
@@ -37,26 +37,25 @@ async function sendChannelAttachments(options) {
37
37
  const read = [];
38
38
  let total = 0;
39
39
  for (const [index, reference] of input.documentIds.entries()) try {
40
- const file = await fetchStoredFile({
40
+ const file = await storedFileGrant({
41
41
  reference,
42
42
  owner,
43
43
  origin,
44
44
  token,
45
45
  fetch,
46
- secrets,
47
- tooLarge: () => new AttachmentError({
48
- code: "too_large",
49
- message: TOO_LARGE
50
- }),
51
- limit: ({ size }) => {
52
- if (total + size > MAXIMUM_SENT_FILE_BYTES) throw new AttachmentError({
53
- code: "too_large",
54
- message: TOO_LARGE
55
- });
56
- return MAXIMUM_SENT_FILE_BYTES - total;
57
- }
46
+ secrets
58
47
  });
59
- total += file.bytes.byteLength;
48
+ if (!file.url.startsWith("https://") || Object.keys(file.headers).length > 0) throw new StoredFileError({
49
+ code: "unsupported",
50
+ message: "The file's download link is not one the channel can follow.",
51
+ filename: file.filename
52
+ });
53
+ if (total + file.size > MAXIMUM_SENT_FILE_BYTES) throw new StoredFileError({
54
+ code: "too_large",
55
+ message: TOO_LARGE,
56
+ filename: file.filename
57
+ });
58
+ total += file.size;
60
59
  read.push({
61
60
  index,
62
61
  file
@@ -96,7 +95,7 @@ async function sendChannelAttachments(options) {
96
95
  });
97
96
  const answer = await response.json().catch(() => ({}));
98
97
  if (!response.ok) throw new AttachmentError({
99
- code: answer.error === "files_unsupported" ? "unsupported" : "send_failed",
98
+ code: answer.error === "files_unsupported" ? "unsupported" : answer.error === "file_too_large" ? "too_large" : isWorkspaceChannelRefusal(answer.error) ? answer.error : "send_failed",
100
99
  message: `The channel did not take the files (${String(answer.error ?? response.status)}).`
101
100
  });
102
101
  messageId = typeof answer.message_id === "string" ? answer.message_id : void 0;
@@ -1,5 +1,6 @@
1
1
  import { type Channel, type ChannelEvents } from "eve/channels";
2
2
  import type { SessionAuthContext } from "eve/context";
3
+ import { type WorkspaceChannelRefusal } from "@segmentstream/ontology/workspace-channel";
3
4
  import { type SegmentStreamAgentConfigInput } from "../../config.js";
4
5
  import { type AgentAttachments } from "../attachments.js";
5
6
  import { type ChatArchive } from "../chat-archive.js";
@@ -141,12 +142,36 @@ export type ChannelEvent = ChannelMessageEvent | {
141
142
  /** The provider's refusal of a failed message, as a code such as `recipient_unreachable`. */
142
143
  readonly reason?: string;
143
144
  };
144
- /** A file the agent sends, its bytes read. */
145
+ /**
146
+ * A file the agent sends, by a short-lived link to it in the workspace's file storage: hand `url`
147
+ * to a provider that fetches files itself, send it through the connection with the `file` option,
148
+ * or `read()` its bytes. Its bytes never travel in a request to the agent, so a file may be as large
149
+ * as the channel's `limits.fileBytes`.
150
+ */
145
151
  export interface ChannelReplyFile {
146
152
  readonly filename: string;
147
153
  readonly contentType: string;
148
- readonly bytes: Uint8Array;
154
+ /** Its size in bytes, which `read()` and the connection's `file` check. */
155
+ readonly size: number;
156
+ /**
157
+ * An `https` link that reads the file without credentials, valid about a minute: hand it to the
158
+ * provider at once. Absent only for a file an ontology before links sends, which `read()` reads.
159
+ */
160
+ readonly url?: string;
161
+ /** Its bytes, read once; rejects when the read is not `size` bytes. */
162
+ read(): Promise<Uint8Array>;
163
+ /**
164
+ * @deprecated Call `read()`.
165
+ * @legacy agent.channel-reply-file-bytes Its bytes, read beforehand, only while the message's
166
+ * files are at most 3 MiB together, as files were before links.
167
+ */
168
+ readonly bytes?: Uint8Array;
149
169
  }
170
+ /**
171
+ * Why the provider refused a message, as `send` answers it: nothing was sent, and the platform
172
+ * records the refusal as a first-party channel's, such as WhatsApp's.
173
+ */
174
+ export type ChannelRefusal = WorkspaceChannelRefusal;
150
175
  /** A message the channel's code sends: the agent's reply, a reviewed one, or a chat post. */
151
176
  export interface ChannelReply {
152
177
  /** The person's chat; for a chat post, the one they last wrote from on the channel. */
@@ -213,18 +238,25 @@ export interface ChannelDefinition {
213
238
  * `outbound` message; a delivery receipt is a `status`. An event that holds nothing holds none.
214
239
  */
215
240
  parse(event: unknown, context: ChannelContext): ReadonlyArray<ChannelEvent> | Promise<ReadonlyArray<ChannelEvent>>;
216
- /** Sends one message; answers the provider's id of it, when it gives one. */
241
+ /**
242
+ * Sends one message; answers the provider's id of it, when it gives one, or the provider's
243
+ * refusal of it ({@link ChannelRefusal}), such as a person outside the provider's reply window: a
244
+ * refused message sent nothing. Throw for any other failure, which may have sent it.
245
+ */
217
246
  send(reply: ChannelReply, context: ChannelContext): Promise<{
218
247
  readonly id?: string;
248
+ } | {
249
+ readonly refusal: ChannelRefusal;
219
250
  } | undefined | void>;
220
251
  /**
221
252
  * What the provider takes: `maxLength`, the most characters of one message, longer replies leave
222
- * in several; `files`, whether messages carry files both ways. Without them, any length and no
223
- * files.
253
+ * in several; `files`, whether messages carry files both ways; `fileBytes`, the most bytes of
254
+ * files one message carries, at most 64 MiB. Without them, any length, no files, and 3 MiB.
224
255
  */
225
256
  readonly limits?: {
226
257
  readonly maxLength?: number;
227
258
  readonly files?: boolean;
259
+ readonly fileBytes?: number;
228
260
  };
229
261
  }
230
262
  export interface WorkspaceChannelOptions extends ChannelDefinition {
@@ -21,6 +21,7 @@ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
21
21
  import { gatewayTranscriber } from "../inbound-media/speech.mjs";
22
22
  import { channelReview } from "../review/reply.mjs";
23
23
  import { g as turnFiles, n as completionKind } from "../../../_chunks/silent-xJcJ8SNJ.mjs";
24
+ import { boundedDownload } from "../sent-files.mjs";
24
25
  import { replyFilesSender } from "../attachments-dispatch.mjs";
25
26
  import { runtimeTokenVerifier } from "../runtime-identity.mjs";
26
27
  import { runtimeToken } from "../runtime-token.mjs";
@@ -30,7 +31,7 @@ import { ChannelCheckUnavailable, channelChecks } from "./secrets.mjs";
30
31
  import { decide } from "eve/ai";
31
32
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
32
33
  import { reply } from "eve/events";
33
- import { WORKSPACE_CHANNEL_ID, workspaceChannelRoute, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
34
+ import { WORKSPACE_CHANNEL_FILES_BYTES, WORKSPACE_CHANNEL_ID, WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES, isWorkspaceChannelRefusal, workspaceChannelRoute, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
34
35
  import { POST, defineChannel as defineChannel$1 } from "eve/channels";
35
36
  const WORKSPACE_CHANNEL_AUTHENTICATOR = "segmentstream-channel";
36
37
  const MAXIMUM_CURSOR_LENGTH = 16384;
@@ -39,6 +40,38 @@ var TooManyMessages = class extends Error {
39
40
  name = "TooManyMessages";
40
41
  };
41
42
  const MAXIMUM_TEXT = 2e4;
43
+ const FILE_READ_TIMEOUT_MS = 3e4;
44
+ var ChannelSendRefused = class extends Error {
45
+ refusal;
46
+ name = "ChannelSendRefused";
47
+ constructor(refusal) {
48
+ super(`The provider refused the message (${refusal}).`);
49
+ this.refusal = refusal;
50
+ }
51
+ };
52
+ function replyFile(file, fetchImpl) {
53
+ let read;
54
+ return {
55
+ filename: file.filename,
56
+ contentType: file.contentType,
57
+ size: file.size,
58
+ ...file.url === void 0 ? {} : { url: file.url },
59
+ read: () => read ??= (async () => {
60
+ if (file.bytes !== void 0) return file.bytes;
61
+ const response = await fetchImpl(file.url, {
62
+ redirect: "error",
63
+ signal: AbortSignal.timeout(FILE_READ_TIMEOUT_MS)
64
+ });
65
+ if (!response.ok) {
66
+ await response.body?.cancel();
67
+ throw new Error(`Storage answered the file's read with status ${response.status}.`);
68
+ }
69
+ const bytes = await boundedDownload(response, file.size, () => new Error(`The file's read exceeds the ${file.size} bytes it was sent with.`));
70
+ if (bytes.byteLength !== file.size) throw new Error(`The file's read has ${bytes.byteLength} bytes, not ${file.size}.`);
71
+ return bytes;
72
+ })()
73
+ };
74
+ }
42
75
  function error(code, status) {
43
76
  return Response.json({ error: code }, { status });
44
77
  }
@@ -224,6 +257,8 @@ function workspaceChannelDefinition(options) {
224
257
  const identity = workspaceIdentityProvider(name);
225
258
  const maxLength = options.limits?.maxLength;
226
259
  const files = options.limits?.files === true;
260
+ const fileBytes = options.limits?.fileBytes ?? WORKSPACE_CHANNEL_FILES_BYTES;
261
+ if (!Number.isSafeInteger(fileBytes) || fileBytes < 1 || fileBytes > WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES) throw new TypeError(`limits.fileBytes must be a whole number of bytes from 1 to ${WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES}.`);
227
262
  let connection = options.connection;
228
263
  let identities = options.identities;
229
264
  let attachments = options.attachments;
@@ -259,13 +294,14 @@ function workspaceChannelDefinition(options) {
259
294
  environment,
260
295
  ...transport
261
296
  });
262
- const report = (operation, cause) => {
297
+ const report = (operation, cause) => redacted(operation, cause, new Set());
298
+ const redacted = (operation, cause, secrets) => {
263
299
  const reference = randomUUID();
264
300
  log("[segmentstream] workspace channel diagnostic", {
265
301
  channel: name,
266
302
  operation,
267
303
  reference,
268
- error: redactDiagnostic(cause, new Set())
304
+ error: redactDiagnostic(cause, secrets)
269
305
  });
270
306
  return reference;
271
307
  };
@@ -277,6 +313,7 @@ function workspaceChannelDefinition(options) {
277
313
  text,
278
314
  ...index === 0 || reply.files === void 0 ? {} : { files: [] }
279
315
  }, context());
316
+ if (sent !== void 0 && "refusal" in sent) throw new ChannelSendRefused(sent.refusal);
280
317
  parts.push({
281
318
  text,
282
319
  id: typeof sent?.id === "string" && sent.id !== "" ? sent.id : null
@@ -625,15 +662,34 @@ function workspaceChannelDefinition(options) {
625
662
  if (chatId !== null && (typeof chatId !== "string" || !WORKSPACE_CHANNEL_ID.test(chatId)) || typeof recipient !== "string" || !WORKSPACE_CHANNEL_ID.test(recipient) || replyTo !== null && replyTo !== void 0 && (typeof replyTo !== "string" || !WORKSPACE_CHANNEL_ID.test(replyTo)) || typeof text !== "string" || body.files !== void 0 && sent === void 0) return error("invalid_request", 400);
626
663
  if (sent !== void 0 && !files) return error("files_unsupported", 422);
627
664
  if (sent === void 0 && maxLength !== void 0 && text.length > maxLength) return error("text_too_long", 422);
628
- const replyFiles = [];
665
+ const declared = [];
629
666
  for (const file of sent ?? []) {
630
- if (!isRecord(file) || typeof file.filename !== "string" || typeof file.content_type !== "string" || typeof file.data !== "string") return error("invalid_request", 400);
631
- replyFiles.push({
667
+ if (!isRecord(file) || typeof file.filename !== "string" || typeof file.content_type !== "string" || file.url !== void 0 && (typeof file.url !== "string" || !file.url.startsWith("https://")) || file.data !== void 0 && typeof file.data !== "string" || file.url === void 0 && file.data === void 0) return error("invalid_request", 400);
668
+ const bytes = typeof file.data === "string" ? new Uint8Array(Buffer.from(file.data, "base64")) : void 0;
669
+ const size = file.size ?? bytes?.byteLength;
670
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) return error("invalid_request", 400);
671
+ if (bytes !== void 0 && bytes.byteLength !== size) return error("file_unavailable", 422);
672
+ declared.push({
632
673
  filename: file.filename,
633
674
  contentType: file.content_type,
634
- bytes: new Uint8Array(Buffer.from(file.data, "base64"))
675
+ size,
676
+ ...typeof file.url === "string" ? { url: file.url } : {},
677
+ ...bytes === void 0 ? {} : { bytes }
635
678
  });
636
679
  }
680
+ const total = declared.reduce((sum, file) => sum + file.size, 0);
681
+ if (total > fileBytes) return error("file_too_large", 422);
682
+ const secrets = new Set(declared.flatMap((file) => file.url === void 0 ? [] : [file.url]));
683
+ const replyFiles = declared.map((file) => replyFile(file, options.fetch ?? fetch));
684
+ if (total <= WORKSPACE_CHANNEL_FILES_BYTES) try {
685
+ for (const [index, file] of replyFiles.entries()) replyFiles[index] = {
686
+ ...file,
687
+ bytes: await file.read()
688
+ };
689
+ } catch (cause) {
690
+ redacted("file_unavailable", cause, secrets);
691
+ return error("file_unavailable", 422);
692
+ }
637
693
  let chat;
638
694
  try {
639
695
  chat = typeof chatId === "string" ? chatId : await lastChat(recipient);
@@ -651,9 +707,10 @@ function workspaceChannelDefinition(options) {
651
707
  ...sent === void 0 ? {} : { files: replyFiles }
652
708
  };
653
709
  const answer = await options.send(reply, context());
710
+ if (answer !== void 0 && "refusal" in answer) return error(isWorkspaceChannelRefusal(answer.refusal) ? answer.refusal : "send_refused", 422);
654
711
  return Response.json({ message_id: typeof answer?.id === "string" && answer.id !== "" ? answer.id : null });
655
712
  } catch (cause) {
656
- const reference = report("send_failed", cause);
713
+ const reference = redacted("send_failed", cause, secrets);
657
714
  return Response.json({
658
715
  error: "send_failed",
659
716
  reference
@@ -17,8 +17,17 @@ export interface ChannelConnectionRequestOptions {
17
17
  readonly json?: unknown;
18
18
  /** A form body, sent with `content-type: application/x-www-form-urlencoded`. */
19
19
  readonly form?: Readonly<Record<string, string>>;
20
- /** A raw body. Set at most one of `json`, `form` and `body`. */
20
+ /** A raw body. Set at most one of `json`, `form`, `body` and `file`. */
21
21
  readonly body?: string | Uint8Array;
22
+ /**
23
+ * A file `send` was given, as the whole body of a `POST`, `PUT` or `PATCH`: SegmentStream reads it
24
+ * from the workspace's file storage and sends it, so its bytes never pass through the function.
25
+ * Set its content type in `headers`.
26
+ */
27
+ readonly file?: {
28
+ readonly url?: string;
29
+ readonly size: number;
30
+ };
22
31
  }
23
32
  export interface ChannelConnectionRequest extends ChannelConnectionRequestOptions {
24
33
  readonly method: ChannelConnectionMethod;
@@ -14,7 +14,12 @@ function queryString(query) {
14
14
  return text === "" ? "" : `?${text}`;
15
15
  }
16
16
  function connectionCall(request) {
17
- if ((request.json !== void 0 ? 1 : 0) + (request.form !== void 0 ? 1 : 0) + (request.body !== void 0 ? 1 : 0) > 1) throw new TypeError("Set at most one of json, form and body.");
17
+ if ((request.json !== void 0 ? 1 : 0) + (request.form !== void 0 ? 1 : 0) + (request.body !== void 0 ? 1 : 0) + (request.file !== void 0 ? 1 : 0) > 1) throw new TypeError("Set at most one of json, form, body and file.");
18
+ if (request.file !== void 0 && (request.file.url === void 0 || !Number.isSafeInteger(request.file.size) || request.file.size < 1 || ![
19
+ "POST",
20
+ "PUT",
21
+ "PATCH"
22
+ ].includes(request.method))) throw new TypeError("A file goes as the body of a POST, PUT or PATCH, by its link.");
18
23
  const headers = Array.isArray(request.headers) ? [...request.headers] : Object.entries(request.headers ?? {});
19
24
  const typed = headers.some(([name]) => name.toLowerCase() === "content-type");
20
25
  const encoder = new TextEncoder();
@@ -33,7 +38,13 @@ function connectionCall(request) {
33
38
  method: request.method,
34
39
  path: `${request.path}${separator === "&" ? query.replace("?", "&") : query}`,
35
40
  headers,
36
- body
41
+ body,
42
+ ...request.file === void 0 ? {} : { file: {
43
+ url: request.file.url,
44
+ headers: [],
45
+ start: 0,
46
+ end: request.file.size - 1
47
+ } }
37
48
  };
38
49
  }
39
50
  function channelConnection(proxy) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.94.0",
3
+ "version": "0.96.0",
4
4
  "description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -88,7 +88,7 @@
88
88
  "@chat-adapter/state-memory": "4.42.0",
89
89
  "@chat-adapter/telegram": "4.41.0",
90
90
  "@chat-adapter/whatsapp": "4.42.0",
91
- "@segmentstream/ontology": "0.176.0",
91
+ "@segmentstream/ontology": "0.177.0",
92
92
  "@vercel/oidc": "^3.8.4",
93
93
  "ai": "^7.0.172",
94
94
  "chat": "4.42.0",