@segmentstream/agent 0.99.0 → 0.101.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,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.101.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
+ Pins @segmentstream/ontology 0.180.0.
29
+
30
+ ## 0.100.0
31
+
32
+ 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.
33
+
34
+ Pins @segmentstream/ontology 0.179.0.
35
+
3
36
  ## 0.99.0
4
37
 
5
38
  The workspace gives the words of a `whenUnsure` review's judge, the decision model that reads a
package/README.md CHANGED
@@ -1104,6 +1104,14 @@ The reference alone grants no access or messaging authority.
1104
1104
 
1105
1105
  ## Grounding replies in opened groups
1106
1106
 
1107
+ An opened group's workspace can bind a TypeScript `publicGroups.respond` handler. It receives the
1108
+ current text, locale, lazy verified evidence, a metered private model call and `act(input)`. Returning
1109
+ a string sends that reply. Returning `undefined` continues the ordinary answer. The model receives
1110
+ no action tool. The ontology opts in separately with `publicGroupAction: { entity, action, role }`.
1111
+ Only that authored action runs, under its explicit permission, for a sender scoped to the group.
1112
+ Use this for narrow requests, with workspace-owned confirmation, deduplication and public-safe
1113
+ receipts. The ontology rechecks group access on every call.
1114
+
1107
1115
  For an isolated group answer, the workspace can declare `publicGroups.knowledge`
1108
1116
  with a `connection` key and localized `unavailable` text in its agent configuration.
1109
1117
  In the agent's extension mount, add a `lookup` function to that object. Its
@@ -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.99.0";
7
+ var version = "0.101.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -77,6 +77,8 @@ export interface FirstContactSettings {
77
77
  export declare const ADMISSION_REPLY_KEYS: readonly ["pairingRequired", "pairingButton", "groupPairingButton", "limited", "perSenderLimited", "workspaceLimited", "registrationsLimited", "groupPairingRequired", "refused"];
78
78
  export type AdmissionReplies = Partial<Record<(typeof ADMISSION_REPLY_KEYS)[number], LocalizedText>>;
79
79
  export interface PublicGroupSettings {
80
+ /** Trusted workspace responder. Its action is bound and authorized by the ontology. */
81
+ readonly respond?: (context: import("./lib/public-group.js").PublicGroupResponseContext) => Promise<string | undefined>;
80
82
  readonly knowledge?: PublicGroupKnowledge;
81
83
  readonly model: string;
82
84
  /** Workspace-published material for an isolated, text-only answer. */
@@ -1300,13 +1300,14 @@ function validateConfig(input, options = {}) {
1300
1300
  "model",
1301
1301
  "instructions",
1302
1302
  "trustedJoinChannels",
1303
- "knowledge"
1303
+ "knowledge",
1304
+ "respond"
1304
1305
  ],
1305
1306
  issues
1306
1307
  });
1307
1308
  let publicGroups;
1308
1309
  if (publicGroupInput) {
1309
- const { model, instructions, trustedJoinChannels } = publicGroupInput;
1310
+ const { model, instructions, trustedJoinChannels, respond } = publicGroupInput;
1310
1311
  const knowledge = section({
1311
1312
  value: publicGroupInput.knowledge,
1312
1313
  path: ["publicGroups", "knowledge"],
@@ -1334,12 +1335,13 @@ function validateConfig(input, options = {}) {
1334
1335
  ...knowledge.lookup && { lookup: knowledge.lookup }
1335
1336
  };
1336
1337
  }
1337
- 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({
1338
+ if (typeof model !== "string" || !model.trim() || model.length > 256 || typeof instructions !== "string" || !instructions.trim() || instructions.length > 32e3 || respond !== void 0 && typeof respond !== "function" || trustedJoinChannels !== void 0 && (!Array.isArray(trustedJoinChannels) || !trustedJoinChannels.every((channel) => typeof channel === "string" && Object.hasOwn(channels ?? {}, channel)))) issues.push({
1338
1339
  path: ["publicGroups"],
1339
1340
  message: "Supply a model, public instructions and optional configured channel names."
1340
1341
  });
1341
1342
  else publicGroups = {
1342
1343
  ...source && { knowledge: source },
1344
+ ...typeof respond === "function" && { respond },
1343
1345
  model,
1344
1346
  instructions,
1345
1347
  ...trustedJoinChannels ? { trustedJoinChannels } : {}
@@ -61,4 +61,5 @@ export { replayRouterPayload } from "./lib/group-routing/replay.js";
61
61
  export { chatAddressing as groupChatAddressing } from "./lib/group-routing/addressing.js";
62
62
  export { routingBurst } from "./lib/group-routing/burst.js";
63
63
  export type { TelegramTexts } from "./lib/telegram/texts.js";
64
+ export type { PublicGroupResponseContext } from "./lib/public-group.js";
64
65
  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-BdnkQsB3.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-Cgy-C9_E.mjs";
@@ -1,7 +1,7 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
2
  import { chatPersona, type PersonaSettings } from "../personas.js";
3
3
  /** A production runtime lookup on the current chat. An outage must not silently change its persona. */
4
- export declare function chatRuntimeRequest(operation: string, data: Record<string, unknown>): Promise<any>;
4
+ export declare function chatRuntimeRequest(operation: string, data: Record<string, unknown>, signal?: AbortSignal): Promise<any>;
5
5
  export declare function resolveChatPersona(settings: PersonaSettings, principal: SessionAuthContext | null | undefined, read?: (key: string) => Promise<string | null>): Promise<{
6
6
  readonly name: string;
7
7
  readonly source: "chat";
@@ -9,7 +9,7 @@ import { Ft as chatAddressOf, It as chatChannel, i as memberIdOf, ot as guestIdO
9
9
  import { appOrigin, ontologyDeploymentHeaders } from "./environment.mjs";
10
10
  import { localizedText } from "./admission.mjs";
11
11
  import { runtimeToken } from "./runtime-token.mjs";
12
- async function chatRuntimeRequest(operation, data) {
12
+ async function chatRuntimeRequest(operation, data, signal = AbortSignal.timeout(5e3)) {
13
13
  const response = await fetch(`${appOrigin()}/api/ontology/agent/chats/${operation}`, {
14
14
  method: "POST",
15
15
  redirect: "error",
@@ -19,7 +19,7 @@ async function chatRuntimeRequest(operation, data) {
19
19
  "content-type": "application/json"
20
20
  },
21
21
  body: JSON.stringify(data),
22
- signal: AbortSignal.timeout(5e3)
22
+ signal
23
23
  });
24
24
  if (!response.ok) throw new Error(`The chat runtime request failed (HTTP ${response.status}).`);
25
25
  return response.json();
@@ -9,6 +9,11 @@ import type { RuntimeToken } from "./runtime-token.js";
9
9
  */
10
10
  /** The largest request or buffered response body the proxy forwards. */
11
11
  export declare const MAXIMUM_PROXY_BODY_BYTES: number;
12
+ /**
13
+ * The most bytes a call sends before, and the most after, a stored file it sends as its body
14
+ * ({@link ProxyFile}'s `prefix` and `suffix`).
15
+ */
16
+ export declare const MAXIMUM_PROXY_FRAME_BYTES: number;
12
17
  /**
13
18
  * The largest file a streamed download takes: what Telegram's Bot API lets a bot download. A
14
19
  * streamed response is relayed in frames rather than buffered, so it is not bound by
@@ -32,12 +37,18 @@ export interface ProxyCall {
32
37
  */
33
38
  readonly file?: ProxyFile;
34
39
  }
35
- /** The signed read of a byte range of a stored file, as the proxy reads it. */
40
+ /**
41
+ * The signed read of a byte range of a stored file, as the proxy reads it, and the bytes it sends
42
+ * before and after the file's, such as a multipart form around the file's part: each at most
43
+ * {@link MAXIMUM_PROXY_FRAME_BYTES}, and the whole body at most 64 MiB.
44
+ */
36
45
  export interface ProxyFile {
37
46
  readonly url: string;
38
47
  readonly headers: ReadonlyArray<readonly [string, string]>;
39
48
  readonly start: number;
40
49
  readonly end: number;
50
+ readonly prefix?: Uint8Array;
51
+ readonly suffix?: Uint8Array;
41
52
  }
42
53
  /** What the provider answered, buffered by the proxy. */
43
54
  export interface ProxyReply {
@@ -5,9 +5,24 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  const MAXIMUM_PROXY_BODY_BYTES = 2097152;
8
+ const MAXIMUM_PROXY_FRAME_BYTES = 65536;
8
9
  const MAXIMUM_DOWNLOAD_BYTES = 20971520;
9
10
  const PROXY_STREAM_MEDIA_TYPE = "application/vnd.segmentstream.proxy-stream.v1+ndjson";
10
11
  const CALL_TIMEOUT_MS = 4e4;
12
+ const STORED_FILE_READ_MS = 15e3;
13
+ function wireFile(file) {
14
+ const base64 = (bytes) => bytes === void 0 || bytes.byteLength === 0 ? void 0 : Buffer.from(bytes).toString("base64");
15
+ const prefix = base64(file.prefix);
16
+ const suffix = base64(file.suffix);
17
+ return {
18
+ url: file.url,
19
+ headers: file.headers,
20
+ start: file.start,
21
+ end: file.end,
22
+ ...prefix === void 0 ? {} : { prefix },
23
+ ...suffix === void 0 ? {} : { suffix }
24
+ };
25
+ }
11
26
  var ConnectionProxyError = class extends Error {
12
27
  name = "ConnectionProxyError";
13
28
  connection;
@@ -63,6 +78,12 @@ function connectionProxy(input) {
63
78
  code: "invalid_request",
64
79
  message: "The request body exceeds the proxy's 2 MiB limit."
65
80
  });
81
+ if ((call.file?.prefix?.byteLength ?? 0) > 65536 || (call.file?.suffix?.byteLength ?? 0) > 65536) throw new ConnectionProxyError({
82
+ connection,
83
+ code: "invalid_request",
84
+ message: "The bytes around a stored file exceed the proxy's 64 KiB limit."
85
+ });
86
+ const timeout = CALL_TIMEOUT_MS + (call.file === void 0 ? 0 : STORED_FILE_READ_MS);
66
87
  const token = await input.token();
67
88
  try {
68
89
  return await fetchImpl(url, {
@@ -78,10 +99,10 @@ function connectionProxy(input) {
78
99
  method: call.method,
79
100
  path: call.path,
80
101
  headers: call.headers,
81
- ...call.file === void 0 ? { body: Buffer.from(call.body).toString("base64") } : { file: call.file }
102
+ ...call.file === void 0 ? { body: Buffer.from(call.body).toString("base64") } : { file: wireFile(call.file) }
82
103
  }),
83
104
  redirect: "error",
84
- signal: abortSignal === void 0 ? AbortSignal.timeout(CALL_TIMEOUT_MS) : AbortSignal.any([abortSignal, AbortSignal.timeout(CALL_TIMEOUT_MS)])
105
+ signal: abortSignal === void 0 ? AbortSignal.timeout(timeout) : AbortSignal.any([abortSignal, AbortSignal.timeout(timeout)])
85
106
  });
86
107
  } catch (error) {
87
108
  throw new ConnectionProxyError({
@@ -206,4 +227,4 @@ async function framedReply(connection, body, maxBytes) {
206
227
  body: new Uint8Array(Buffer.concat(chunks))
207
228
  };
208
229
  }
209
- export { ConnectionProxyError, MAXIMUM_DOWNLOAD_BYTES, MAXIMUM_PROXY_BODY_BYTES, PROXY_STREAM_MEDIA_TYPE, connectionProxy };
230
+ export { ConnectionProxyError, MAXIMUM_DOWNLOAD_BYTES, MAXIMUM_PROXY_BODY_BYTES, MAXIMUM_PROXY_FRAME_BYTES, PROXY_STREAM_MEDIA_TYPE, connectionProxy };
@@ -1,4 +1,13 @@
1
1
  import type { AdmissionSettings } from "../config.js";
2
+ export interface PublicGroupResponseContext {
3
+ readonly question: string;
4
+ readonly locale?: string;
5
+ /** Privately verified facts, fetched at most once. */
6
+ readonly evidence: () => Promise<readonly string[]>;
7
+ readonly reason: (instructions: string, prompt: string) => Promise<string>;
8
+ /** The workspace-authored ontology action. Never offered to a model. */
9
+ readonly act: (input: Readonly<Record<string, unknown>>) => Promise<unknown>;
10
+ }
2
11
  /** Everyone in an opened group sees the reply, including when an employee asks. */
3
12
  export declare function isPublicGroup(admission: AdmissionSettings, channel: string, chat: string, sender: string): Promise<boolean>;
4
13
  /** An unlinked sender can only submit this message to the workspace's public instructions.
@@ -50,7 +50,7 @@ async function answerPublicGroup(input) {
50
50
  input.message
51
51
  ]);
52
52
  let stage = 0;
53
- const generate = async (system, prompt, privateCall = false) => {
53
+ const generate = async (system, prompt, privateCall = false, signal = AbortSignal.timeout(3e4)) => {
54
54
  const usageKey = privateCall ? `research:${++stage}:${messageKey}` : messageKey;
55
55
  const reply = await generateText({
56
56
  model: gateway(settings.model),
@@ -58,7 +58,7 @@ async function answerPublicGroup(input) {
58
58
  prompt,
59
59
  maxRetries: 0,
60
60
  maxOutputTokens: privateCall ? 1e3 : 600,
61
- abortSignal: privateCall ? researchDeadline : AbortSignal.timeout(3e4)
61
+ abortSignal: signal
62
62
  });
63
63
  const costUsd = gatewayCostOf(reply.providerMetadata);
64
64
  if (costUsd > 0) await ontologyGuestUsage()({
@@ -68,12 +68,36 @@ async function answerPublicGroup(input) {
68
68
  });
69
69
  return reply.text.trim();
70
70
  };
71
- const evidence = settings.knowledge ? await publicGroupEvidence(settings.knowledge, question, (system, prompt) => generate(system, prompt, true), researchDeadline) : void 0;
71
+ let research;
72
+ const evidenceForTurn = () => research ??= settings.knowledge ? publicGroupEvidence(settings.knowledge, question, (system, prompt) => generate(system, prompt, true, researchDeadline), researchDeadline) : Promise.resolve([]);
73
+ let calls = 0;
74
+ let actions = 0;
75
+ const response = await settings.respond?.({
76
+ question,
77
+ locale: input.locale,
78
+ evidence: evidenceForTurn,
79
+ reason: (system, prompt) => {
80
+ if (++calls > 2 || system.length > 8e3 || prompt.length > 2e4) throw new Error("Public response limit exceeded.");
81
+ return generate(system, prompt, true);
82
+ },
83
+ act: async (data) => {
84
+ if (++actions > 4 || JSON.stringify(data).length > 12e3) throw new Error("Public action limit exceeded.");
85
+ const reply = await chatRuntimeRequest("public-action", {
86
+ channel: input.channel,
87
+ chat: input.chat,
88
+ sender: input.sender,
89
+ input: data
90
+ }, AbortSignal.timeout(25e3));
91
+ if (!reply || !Object.hasOwn(reply, "result")) throw new Error("Public action failed.");
92
+ return reply.result;
93
+ }
94
+ });
95
+ const evidence = response === void 0 && settings.knowledge ? await evidenceForTurn() : void 0;
72
96
  const prompt = evidence === void 0 ? question : JSON.stringify({
73
97
  question,
74
98
  evidence
75
99
  });
76
- const text = settings.knowledge && !evidence?.length ? localizedText(settings.knowledge.unavailable, input.locale) : await generate(settings.instructions, prompt);
100
+ const text = response ?? (settings.knowledge && !evidence?.length ? localizedText(settings.knowledge.unavailable, input.locale) : await generate(settings.instructions, prompt));
77
101
  if (!text) throw new Error("The public group answer was empty.");
78
102
  await input.post(text.slice(0, 3500));
79
103
  delivered = true;
@@ -1,10 +1,12 @@
1
+ import type { ChannelStoredFile } from "@segmentstream/ontology/telegram";
1
2
  import { AttachmentError } from "./attachments.js";
2
3
  import type { AttachmentOwner } from "./attachments.js";
3
4
  /**
4
5
  * A stored ontology file the agent sends into a chat: its record, the ontology's file grant and
5
6
  * the file's bytes, read as the turn's member in the turn's chat. Every channel's sender shares
6
- * it; each says how many bytes its destination takes. WhatsApp, which sends files by link, reads
7
- * only the grant.
7
+ * it; each says how many bytes its destination takes. A file sent by link, as WhatsApp fetches
8
+ * it, or by its signed read, which the connection proxy or a provider's upload follows, is read
9
+ * only by its grant.
8
10
  */
9
11
  /** A file record: a document by its id, or any entity's record and file property. */
10
12
  export interface DocumentReference {
@@ -45,7 +47,7 @@ export interface StoredFileGrant {
45
47
  readonly headers: Readonly<Record<string, string>>;
46
48
  }
47
49
  /** What reading a stored file needs: the member, the chat and the deployment's credentials. */
48
- interface StoredFileRead {
50
+ export interface StoredFileRead {
49
51
  readonly reference: DocumentReference;
50
52
  readonly owner: AttachmentOwner;
51
53
  /** The deployment's own origin, where the ontology service answers. */
@@ -61,16 +63,30 @@ interface StoredFileRead {
61
63
  */
62
64
  export declare function storedFileGrant(input: StoredFileRead): Promise<StoredFileGrant>;
63
65
  /**
64
- * Reads one stored file: its grant from the ontology, then its bytes. `limit` sees the file's type
65
- * and size before anything is downloaded and answers the most bytes the destination takes, or
66
- * throws to refuse it.
66
+ * A file sent by its signed read, which the connection proxy or a provider's upload follows just
67
+ * before its request: the grant read first, renewed once it is older than a few seconds, so its
68
+ * link is still valid however long the files before it took. A renewal that names a file of
69
+ * another size or type, as when the record's file was replaced meanwhile, rejects.
67
70
  */
68
- export declare function fetchStoredFile(input: StoredFileRead & {
71
+ export declare function storedChannelFile(grant: StoredFileGrant, input: StoredFileRead): ChannelStoredFile & {
72
+ readonly link: () => Promise<StoredFileGrant>;
73
+ };
74
+ /** What a stored file's download needs once its grant is read. */
75
+ interface StoredFileDownload {
76
+ readonly fetch: typeof fetch;
69
77
  readonly limit: (file: {
70
78
  readonly contentType: string;
71
79
  readonly size: number;
72
80
  }) => number;
73
81
  /** The error a download over the limit throws. */
74
82
  readonly tooLarge: () => Error;
75
- }): Promise<StoredFile>;
83
+ }
84
+ /**
85
+ * Reads one stored file: its grant from the ontology, then its bytes. `limit` sees the file's type
86
+ * and size before anything is downloaded and answers the most bytes the destination takes, or
87
+ * throws to refuse it.
88
+ */
89
+ export declare function fetchStoredFile(input: StoredFileRead & Omit<StoredFileDownload, "fetch">): Promise<StoredFile>;
90
+ /** Reads the bytes of a stored file whose grant is read, as {@link fetchStoredFile} does. */
91
+ export declare function downloadStoredFile(grant: StoredFileGrant, input: StoredFileDownload): Promise<StoredFile>;
76
92
  export {};
@@ -110,8 +110,45 @@ async function storedFileGrant(input) {
110
110
  });
111
111
  }
112
112
  }
113
+ const FRESH_GRANT_MS = 15e3;
114
+ function storedChannelFile(grant, input) {
115
+ let current = {
116
+ grant,
117
+ at: Date.now()
118
+ };
119
+ const link = async () => {
120
+ if (Date.now() - current.at > FRESH_GRANT_MS) {
121
+ const renewed = await storedFileGrant(input);
122
+ if (renewed.size !== grant.size || renewed.contentType !== grant.contentType) throw new StoredFileError({
123
+ code: "unavailable",
124
+ message: "The stored file changed while it was being sent.",
125
+ filename: grant.filename
126
+ });
127
+ current = {
128
+ grant: renewed,
129
+ at: Date.now()
130
+ };
131
+ }
132
+ return current.grant;
133
+ };
134
+ return {
135
+ filename: grant.filename,
136
+ contentType: grant.contentType,
137
+ size: grant.size,
138
+ link,
139
+ read: async () => {
140
+ const fresh = await link();
141
+ return {
142
+ url: fresh.url,
143
+ headers: Object.entries(fresh.headers)
144
+ };
145
+ }
146
+ };
147
+ }
113
148
  async function fetchStoredFile(input) {
114
- const grant = await storedFileGrant(input);
149
+ return downloadStoredFile(await storedFileGrant(input), input);
150
+ }
151
+ async function downloadStoredFile(grant, input) {
115
152
  const { filename, contentType } = grant;
116
153
  try {
117
154
  const maximum = input.limit({
@@ -145,4 +182,4 @@ async function fetchStoredFile(input) {
145
182
  });
146
183
  }
147
184
  }
148
- export { StoredFileError, boundedDownload, fetchStoredFile, storedFileGrant };
185
+ export { StoredFileError, boundedDownload, downloadStoredFile, fetchStoredFile, storedChannelFile, storedFileGrant };
@@ -8,10 +8,11 @@ import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
8
8
  * in its thread, with Slack's external upload: `files.getUploadURLExternal` for each file, its
9
9
  * bytes posted to the address Slack answers, then one `files.completeUploadExternal` that shares
10
10
  * them all in the chat with the caption, as the ontology's Slack sender (`sendSlackFiles`) does it.
11
- * Every call goes through the Slack connection,
12
- * which adds the bot token and needs `files:write`; each upload carries at most the connection
13
- * proxy's 2 MiB, as Telegram's do. The checks and failures are every channel's
14
- * (`../attachments-send.ts`).
11
+ * The Web API calls go through the Slack connection, which adds the bot token and needs
12
+ * `files:write`. Each file's bytes go from the workspace's file storage straight to its upload
13
+ * address, which carries its own authorization and needs no credential, streamed, so a file is
14
+ * held to Slack's 1 GB rather than to the connection proxy's request body. The checks and failures
15
+ * are every channel's (`../attachments-send.ts`).
15
16
  */
16
17
  /** What became of one requested file. */
17
18
  export interface SlackSentFile extends Partial<AttachmentSendFailure> {
@@ -9,16 +9,9 @@ import { sendStoredAttachments } from "../attachments-send.mjs";
9
9
  import { connectionProxy } from "../connection-proxy.mjs";
10
10
  import { redactDiagnostic } from "../diagnostics.mjs";
11
11
  import { proxyEnvironment } from "../environment.mjs";
12
- import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
12
+ import { StoredFileError, storedChannelFile, storedFileGrant } from "../sent-files.mjs";
13
13
  import { randomUUID } from "node:crypto";
14
- import { SLACK_FILE_BYTES, sendSlackFiles, slackFileRefusal } from "@segmentstream/ontology/slack";
15
- const PROXY_LIMIT = "The connection proxy takes at most 2 MiB per upload.";
16
- function refused(code, message) {
17
- return new AttachmentError({
18
- code,
19
- message
20
- });
21
- }
14
+ import { sendSlackFiles, slackFileRefusal } from "@segmentstream/ontology/slack";
22
15
  function reportSlackError(operation, error, secrets) {
23
16
  const reference = randomUUID();
24
17
  console.error("[segmentstream] Slack delivery diagnostic", {
@@ -49,26 +42,33 @@ async function sendSlackAttachments(options) {
49
42
  }));
50
43
  const read = [];
51
44
  for (const [index, reference] of input.documentIds.entries()) try {
52
- const file = await fetchStoredFile({
45
+ const grant = await storedFileGrant({
53
46
  reference,
54
47
  owner,
55
48
  origin,
56
49
  token,
57
50
  fetch,
58
- secrets,
59
- tooLarge: () => refused("too_large", PROXY_LIMIT),
60
- limit: ({ size }) => {
61
- const refusal = slackFileRefusal({ size });
62
- if (refusal !== void 0) throw refused(refusal.code === "empty" ? "unsupported" : refusal.code, refusal.message);
63
- return SLACK_FILE_BYTES;
64
- }
51
+ secrets
52
+ });
53
+ const refusal = slackFileRefusal(grant, { direct: true });
54
+ if (refusal !== void 0) throw new StoredFileError({
55
+ code: refusal.code === "empty" ? "unsupported" : refusal.code,
56
+ message: refusal.message,
57
+ filename: grant.filename
65
58
  });
66
59
  results[index] = {
67
60
  id: reference.id,
68
- filename: file.filename
61
+ filename: grant.filename
69
62
  };
70
63
  read.push({
71
- ...file,
64
+ ...storedChannelFile(grant, {
65
+ reference,
66
+ owner,
67
+ origin,
68
+ token,
69
+ fetch,
70
+ secrets
71
+ }),
72
72
  index
73
73
  });
74
74
  } catch (error) {
@@ -80,11 +80,11 @@ async function sendSlackAttachments(options) {
80
80
  }
81
81
  if (read.length === 0) return { files: results };
82
82
  const sent = await sendSlackFiles({
83
- request: (call) => {
84
- if (call.api !== "files") return proxy.request(call);
85
- secrets.add(call.path);
86
- return proxy.download(call);
87
- },
83
+ request: (call) => proxy.request(call),
84
+ fetch: ((address, init) => {
85
+ secrets.add(String(address));
86
+ return fetch(address, init);
87
+ }),
88
88
  channel: chat.chatId,
89
89
  ...chat.threadId === "" ? {} : { threadTs: chat.threadId },
90
90
  files: read,
@@ -13,7 +13,7 @@ import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
13
13
  import { handleWorkspaceCallback } from "./callbacks.mjs";
14
14
  import { workspaceTriage } from "../triage.mjs";
15
15
  import { telegramText, withTelegramTexts } from "./texts.mjs";
16
- import { t as agentBuild } from "../../../_chunks/build-metadata-BdnkQsB3.mjs";
16
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Cgy-C9_E.mjs";
17
17
  import { attachmentLifecycle } from "./lifecycle.mjs";
18
18
  import { manifestOf } from "../../config.mjs";
19
19
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -8,14 +8,14 @@ import { attachmentOwner } from "../attachment-tools.mjs";
8
8
  import { _ as AttachmentError, _t as customerMessage, xt as reportTelegramError, yt as failureText } from "../../../_chunks/principal-DL9NdRRP.mjs";
9
9
  import { attachmentFailure } from "../attachments-send.mjs";
10
10
  import { connectionProxy } from "../connection-proxy.mjs";
11
- import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
11
+ import { StoredFileError, downloadStoredFile, storedChannelFile, storedFileGrant } from "../sent-files.mjs";
12
12
  import { appOrigin, channelsEnabled, proxyEnvironment } from "../environment.mjs";
13
13
  import { runtimeToken } from "../runtime-token.mjs";
14
14
  import { confirmationLocale } from "./confirmation-text.mjs";
15
15
  import { inTelegramSendQueue, telegramSendScope } from "./send-queue.mjs";
16
16
  import { miniAppLinks, telegramAppLinkContext, withMiniAppLinks } from "./app-links.mjs";
17
17
  import { proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
18
- import { sendTelegramFiles, telegramFileBytes, telegramFileRefusal } from "@segmentstream/ontology/telegram";
18
+ import { TELEGRAM_INLINE_FILE_BYTES, sendTelegramFiles, telegramFileRefusal } from "@segmentstream/ontology/telegram";
19
19
  const RECORD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20
20
  const NAME = /^[a-z][a-z0-9_]{0,63}$/;
21
21
  function isRecord(value) {
@@ -49,7 +49,7 @@ function refused(code, message) {
49
49
  message
50
50
  });
51
51
  }
52
- const PROXY_LIMIT = "The multipart upload exceeds the connection proxy's 2 MiB request limit (including overhead).";
52
+ const UNDERSTATED = "The stored file is larger than its record says.";
53
53
  function sendAttachments(options) {
54
54
  const chatId = options.principal?.attributes.chatId;
55
55
  return typeof chatId === "string" && options.connection !== void 0 ? inTelegramSendQueue(telegramSendScope(options.environment ?? process.env, options.connection), chatId, () => sendAttachmentsInOrder(options)) : sendAttachmentsInOrder(options);
@@ -107,40 +107,45 @@ async function sendAttachmentsInOrder(options) {
107
107
  filename: ""
108
108
  }));
109
109
  const uploads = [];
110
- for (const [index, reference] of options.input.documentIds.entries()) try {
111
- const file = await fetchStoredFile({
110
+ for (const [index, reference] of options.input.documentIds.entries()) {
111
+ const read = {
112
112
  reference,
113
113
  owner,
114
114
  origin,
115
115
  token,
116
116
  fetch: fetchImpl,
117
- secrets,
118
- tooLarge: () => refused("too_large", PROXY_LIMIT),
119
- limit: ({ contentType, size }) => {
120
- const refusal = telegramFileRefusal({
121
- contentType,
122
- size
123
- });
124
- if (refusal !== void 0) throw refused(refusal.code === "empty" ? "unsupported" : refusal.code, refusal.message);
125
- return telegramFileBytes(contentType);
126
- }
127
- });
128
- uploads.push({
129
- index,
130
- file
131
- });
132
- } catch (error) {
133
- const errorId = reportTelegramError("stored_attachment_fetch_failed", error, { id: reference.id }, secrets);
134
- results[index] = {
135
- id: reference.id,
136
- filename: error instanceof StoredFileError ? error.filename : "",
137
- ...attachmentFailure({
138
- error,
139
- reference: errorId,
140
- locale,
141
- fallback: "unavailable"
142
- })
117
+ secrets
143
118
  };
119
+ try {
120
+ const grant = await storedFileGrant(read);
121
+ const refusal = telegramFileRefusal(grant, { stored: true });
122
+ if (refusal !== void 0) throw new StoredFileError({
123
+ code: refusal.code === "empty" ? "unsupported" : refusal.code,
124
+ message: refusal.message,
125
+ filename: grant.filename
126
+ });
127
+ const file = grant.size <= TELEGRAM_INLINE_FILE_BYTES ? await downloadStoredFile(grant, {
128
+ fetch: fetchImpl,
129
+ limit: () => TELEGRAM_INLINE_FILE_BYTES,
130
+ tooLarge: () => refused("too_large", UNDERSTATED)
131
+ }) : storedChannelFile(grant, read);
132
+ uploads.push({
133
+ index,
134
+ file
135
+ });
136
+ } catch (error) {
137
+ const errorId = reportTelegramError("stored_attachment_fetch_failed", error, { id: reference.id }, secrets);
138
+ results[index] = {
139
+ id: reference.id,
140
+ filename: error instanceof StoredFileError ? error.filename : "",
141
+ ...attachmentFailure({
142
+ error,
143
+ reference: errorId,
144
+ locale,
145
+ fallback: "unavailable"
146
+ })
147
+ };
148
+ }
144
149
  }
145
150
  let caption = options.input.caption === void 0 ? void 0 : customerMessage(options.input.caption, locale, options.identifiers);
146
151
  const appLinks = caption === void 0 ? void 0 : telegramAppLinkContext(options.appLinks, environment, async () => (await runtimeBotIdentity(scope)({ request: (method, body) => proxiedBotRequest(proxy, method, body) }))?.username);
@@ -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-BdnkQsB3.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Cgy-C9_E.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-BdnkQsB3.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Cgy-C9_E.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -4,6 +4,18 @@ import { type ChatArchive } from "../chat-archive.js";
4
4
  import { type Environment } from "../environment.js";
5
5
  import type { RuntimeToken } from "../runtime-token.js";
6
6
  import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
7
+ /**
8
+ * `attachments_send` in a WhatsApp chat: each stored file is a message to the person, sent through
9
+ * the WhatsApp channel's connection by the ontology's WhatsApp sender (`sendWhatsAppFiles`), to
10
+ * whom the channel's adapter replies, the caption on the first as the adapter writes it; a caption
11
+ * no file can carry goes first on its own, and the call answers its failure as `caption`. The
12
+ * connection admits no media uploads, so WhatsApp fetches each file by the ontology's download
13
+ * grant, a link valid for about a minute: JPEG and PNG images go as images, other files as
14
+ * WhatsApp's types for them, within WhatsApp's size for each. Each message sent is
15
+ * archived in the person's chat with WhatsApp's id of it, so a file WhatsApp reports later it could
16
+ * not fetch, in the message's status, reads failed in the chat's history. The checks and failures
17
+ * are every channel's (`../attachments-send.ts`).
18
+ */
7
19
  /** What became of one requested file. */
8
20
  export interface WhatsAppSentFile extends Partial<AttachmentSendFailure> {
9
21
  readonly id: string;
@@ -10,12 +10,11 @@ import { r as chatArchive } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
10
10
  import { connectionProxy } from "../connection-proxy.mjs";
11
11
  import { redactDiagnostic } from "../diagnostics.mjs";
12
12
  import { proxyEnvironment } from "../environment.mjs";
13
- import { StoredFileError, storedFileGrant } from "../sent-files.mjs";
13
+ import { StoredFileError, storedChannelFile, storedFileGrant } from "../sent-files.mjs";
14
14
  import { ProxiedWhatsAppAdapter } from "./adapter.mjs";
15
15
  import { recordSent } from "./sent.mjs";
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { sendWhatsAppFiles, whatsappFileRefusal } from "@segmentstream/ontology/whatsapp";
18
- const FRESH_LINK_MS = 15e3;
19
18
  function reportWhatsAppError(operation, error, secrets) {
20
19
  const reference = randomUUID();
21
20
  console.error("[segmentstream] WhatsApp delivery diagnostic", {
@@ -86,23 +85,17 @@ async function sendWhatsAppAttachments(options) {
86
85
  id: reference.id,
87
86
  filename: grant.filename
88
87
  };
89
- const granted = {
90
- url: grant.url,
91
- at: Date.now()
92
- };
88
+ const stored = storedChannelFile(grant, {
89
+ reference,
90
+ owner,
91
+ origin,
92
+ token,
93
+ fetch,
94
+ secrets
95
+ });
93
96
  linked.push({
94
97
  index,
95
- link: async () => {
96
- if (Date.now() - granted.at <= FRESH_LINK_MS) return granted.url;
97
- return (await storedFileGrant({
98
- reference,
99
- owner,
100
- origin,
101
- token,
102
- fetch,
103
- secrets
104
- })).url;
105
- },
98
+ link: async () => (await stored.link()).url,
106
99
  filename: grant.filename,
107
100
  contentType: grant.contentType,
108
101
  size: grant.size
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.99.0",
3
+ "version": "0.101.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.178.0",
91
+ "@segmentstream/ontology": "0.180.0",
92
92
  "@vercel/oidc": "^3.8.4",
93
93
  "ai": "^7.0.172",
94
94
  "chat": "4.42.0",