@segmentstream/agent 0.81.1 → 0.82.1

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 (95) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +11 -11
  3. package/dist/_chunks/{build-metadata-DyupzJpt.mjs → build-metadata-DCwk8DOP.mjs} +1 -1
  4. package/dist/_chunks/{chat-archive-BBd_iZ1d.mjs → chat-archive-D4HRgOSo.mjs} +1 -1
  5. package/dist/_chunks/{principal-CVV9C_nO.mjs → principal-dEQyjF1n.mjs} +2 -3
  6. package/dist/extension/config.d.ts +5 -5
  7. package/dist/extension/connections/ontology.mjs +1 -1
  8. package/dist/extension/hooks/authorization.mjs +1 -1
  9. package/dist/extension/instructions/persona.mjs +1 -1
  10. package/dist/extension/lib/actor.mjs +1 -1
  11. package/dist/extension/lib/attachment-tools.mjs +1 -1
  12. package/dist/extension/lib/attachments-send.d.ts +2 -1
  13. package/dist/extension/lib/attachments-send.mjs +1 -1
  14. package/dist/extension/lib/attachments.mjs +1 -1
  15. package/dist/extension/lib/build-metadata.mjs +1 -1
  16. package/dist/extension/lib/chat-address.mjs +1 -1
  17. package/dist/extension/lib/chat-context.mjs +1 -1
  18. package/dist/extension/lib/chat-recorder.mjs +1 -1
  19. package/dist/extension/lib/confirmations.mjs +1 -1
  20. package/dist/extension/lib/email/attachments-send.d.ts +2 -2
  21. package/dist/extension/lib/email/attachments-send.mjs +4 -3
  22. package/dist/extension/lib/email/channel.mjs +1 -1
  23. package/dist/extension/lib/email/gmail.d.ts +4 -10
  24. package/dist/extension/lib/email/gmail.mjs +6 -99
  25. package/dist/extension/lib/guest-usage.mjs +1 -1
  26. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  27. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  28. package/dist/extension/lib/ontology-connection.mjs +1 -1
  29. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  30. package/dist/extension/lib/ontology-recall.mjs +1 -1
  31. package/dist/extension/lib/ontology-tools.mjs +1 -1
  32. package/dist/extension/lib/review/client.d.ts +3 -3
  33. package/dist/extension/lib/review/client.mjs +3 -2
  34. package/dist/extension/lib/review/hold.mjs +1 -1
  35. package/dist/extension/lib/review/reply.d.ts +1 -1
  36. package/dist/extension/lib/review/reply.mjs +1 -1
  37. package/dist/extension/lib/review/revision.mjs +2 -1
  38. package/dist/extension/lib/review/routes.d.ts +9 -0
  39. package/dist/extension/lib/review/routes.mjs +15 -0
  40. package/dist/extension/lib/role-skill.mjs +1 -1
  41. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  42. package/dist/extension/lib/sent-files.mjs +1 -1
  43. package/dist/extension/lib/slack/adapter.mjs +1 -1
  44. package/dist/extension/lib/slack/attachments-send.d.ts +2 -1
  45. package/dist/extension/lib/slack/attachments-send.mjs +63 -104
  46. package/dist/extension/lib/slack/callbacks.mjs +1 -1
  47. package/dist/extension/lib/stored-files.mjs +1 -1
  48. package/dist/extension/lib/telegram/adapter.mjs +3 -3
  49. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  50. package/dist/extension/lib/telegram/attachments-send.d.ts +0 -2
  51. package/dist/extension/lib/telegram/attachments-send.mjs +43 -107
  52. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  53. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  54. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  55. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  56. package/dist/extension/lib/telegram/files.mjs +1 -1
  57. package/dist/extension/lib/telegram/format.d.ts +2 -6
  58. package/dist/extension/lib/telegram/format.mjs +1 -28
  59. package/dist/extension/lib/telegram/health.mjs +1 -1
  60. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  61. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  62. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  63. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  64. package/dist/extension/lib/telegram/principal.mjs +1 -1
  65. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  66. package/dist/extension/lib/telegram/silent.mjs +1 -1
  67. package/dist/extension/lib/telegram/store-capture.mjs +1 -1
  68. package/dist/extension/lib/telegram/structured.mjs +1 -1
  69. package/dist/extension/lib/telegram/turn-errors.mjs +2 -2
  70. package/dist/extension/lib/web/auth.mjs +1 -1
  71. package/dist/extension/lib/web/channel.mjs +1 -1
  72. package/dist/extension/lib/whatsapp/adapter.d.ts +9 -0
  73. package/dist/extension/lib/whatsapp/adapter.mjs +10 -2
  74. package/dist/extension/lib/whatsapp/attachments-send.d.ts +2 -10
  75. package/dist/extension/lib/whatsapp/attachments-send.mjs +71 -43
  76. package/dist/extension/lib/whatsapp/callbacks.mjs +1 -1
  77. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  78. package/dist/extension/lib/workspace-action.mjs +1 -1
  79. package/dist/extension/lib/workspace-channel/attachments-send.d.ts +1 -1
  80. package/dist/extension/lib/workspace-channel/attachments-send.mjs +5 -9
  81. package/dist/extension/lib/workspace-channel/channel.mjs +1 -1
  82. package/dist/extension/lib/workspace-source.mjs +1 -1
  83. package/dist/extension/model.mjs +1 -1
  84. package/dist/extension/review.d.ts +1 -1
  85. package/dist/extension/tools/attachments_discard.mjs +1 -1
  86. package/dist/extension/tools/attachments_list.mjs +1 -1
  87. package/dist/extension/tools/attachments_promote.mjs +1 -1
  88. package/dist/extension/tools/attachments_read.mjs +1 -1
  89. package/dist/extension/tools/attachments_send.mjs +1 -1
  90. package/dist/extension/tools/attachments_stage.mjs +1 -1
  91. package/dist/extension/tools/attachments_table.mjs +1 -1
  92. package/dist/extension/tools/handoff.mjs +1 -1
  93. package/dist/extension/tools/questions_ask.mjs +1 -1
  94. package/dist/extension/tools/workspace_source.mjs +1 -1
  95. package/package.json +2 -2
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { reviewFor } from "../../review.mjs";
8
- import { Bt as participantsOf, Ft as chatAddressOf, a as rolesOf, i as memberIdOf } from "../../../_chunks/principal-CVV9C_nO.mjs";
8
+ import { Bt as participantsOf, Ft as chatAddressOf, a as rolesOf, i as memberIdOf } from "../../../_chunks/principal-dEQyjF1n.mjs";
9
9
  function reviewOf(settings, principal) {
10
10
  return reviewFor(settings, rolesOf(principal));
11
11
  }
@@ -7,7 +7,7 @@ import { type HoldReply } from "./hold.js";
7
7
  import { type ReviewDecideFunction } from "./judge.js";
8
8
  /**
9
9
  * Review of a channel's final replies: the reply of a chat whose review is not `never` is
10
- * judged or held before the channel sends it, and held replies become `agent_review` records. The
10
+ * judged or held before the channel sends it, and held replies become `agent_draft` records. The
11
11
  * archive keeps each verdict for operators: a held reply is never recorded as sent.
12
12
  */
13
13
  export interface ReplyReview {
@@ -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 { Ft as chatAddressOf, It as chatChannel, i as memberIdOf } from "../../../_chunks/principal-CVV9C_nO.mjs";
7
+ import { Ft as chatAddressOf, It as chatChannel, i as memberIdOf } from "../../../_chunks/principal-dEQyjF1n.mjs";
8
8
  import { a as chatEvent, r as chatArchive } from "../../../_chunks/chat-archive-DavfKJDI.mjs";
9
9
  import { stampedChat } from "../chat-recorder.mjs";
10
10
  import { appOrigin } from "../environment.mjs";
@@ -7,6 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { redactDiagnostic } from "../diagnostics.mjs";
8
8
  import { AgentIdentityError, refusal } from "../identities.mjs";
9
9
  import { readChat } from "./judge.mjs";
10
+ import { postDraftRoute } from "./routes.mjs";
10
11
  const REVISION_AUTHENTICATOR = "segmentstream-review-revision";
11
12
  const REVISION_ROUTE = "/eve/segmentstream/v1/reviews/revise";
12
13
  const REVISION_SCOPE = "ontology:read";
@@ -173,7 +174,7 @@ function agentRevisions(input) {
173
174
  let response;
174
175
  let failure;
175
176
  try {
176
- response = await fetchImpl(`${input.origin}/api/ontology/agent/reviews/revision`, {
177
+ response = await postDraftRoute(fetchImpl, input.origin, "/revision", {
177
178
  method: "POST",
178
179
  headers: {
179
180
  authorization: `Bearer ${token}`,
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Posts to one of the ontology service's draft routes, `/api/ontology/agent/drafts{path}`, and, when
3
+ * the service answers 404, once more to the route's earlier name, `/agent/reviews{path}`: an ontology
4
+ * service released before the drafts' rename serves only that one. A current service answers 404
5
+ * there too when the reply is for no active member, so the second answer is the one that counts.
6
+ */
7
+ export declare function postDraftRoute(fetchImpl: typeof fetch, origin: string, path: "" | "/session" | "/revision", init: RequestInit & {
8
+ readonly body: string;
9
+ }): Promise<Response>;
@@ -0,0 +1,15 @@
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
+ async function postDraftRoute(fetchImpl, origin, path, init) {
8
+ const response = await fetchImpl(`${origin}/api/ontology/agent/drafts${path}`, init);
9
+ if (response.status === 404) {
10
+ await response.body?.cancel();
11
+ return await fetchImpl(`${origin}/api/ontology/agent/reviews${path}`, init);
12
+ }
13
+ return response;
14
+ }
15
+ export { postDraftRoute };
@@ -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 { a as rolesOf } from "../../_chunks/principal-CVV9C_nO.mjs";
7
+ import { a as rolesOf } from "../../_chunks/principal-dEQyjF1n.mjs";
8
8
  import { defineDynamic, defineSkill } from "eve/skills";
9
9
  function forRoles(roles, skill) {
10
10
  if (!Array.isArray(roles) || roles.length === 0 || !roles.every((role) => typeof role === "string" && role.trim() !== "")) throw new TypeError("forRoles() needs at least one role name; a skill for everyone is an ordinary skill file.");
@@ -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 { wt as RUNTIME_SOURCE_PROTOCOL, Tt as compatibleRuntimeEnvelope, Et as principalRuntimeSource, Dt as readableRuntimeEnvelope, Ot as runtimeEnvelope, kt as telegramRuntimeSource } from "../../_chunks/principal-CVV9C_nO.mjs";
7
+ export { wt as RUNTIME_SOURCE_PROTOCOL, Tt as compatibleRuntimeEnvelope, Et as principalRuntimeSource, Dt as readableRuntimeEnvelope, Ot as runtimeEnvelope, kt as telegramRuntimeSource } from "../../_chunks/principal-dEQyjF1n.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 { Pt as SESSION_HEADER, R as ACT_AS_HEADER, _ as AttachmentError, jt as CHAT_HEADER, v as EARLIER_CHAT_HEADER } from "../../_chunks/principal-CVV9C_nO.mjs";
7
+ import { Pt as SESSION_HEADER, R as ACT_AS_HEADER, _ as AttachmentError, jt as CHAT_HEADER, v as EARLIER_CHAT_HEADER } from "../../_chunks/principal-dEQyjF1n.mjs";
8
8
  import { fetchFileGrant, transientFileStatus } from "./file-grant.mjs";
9
9
  var StoredFileError = class extends AttachmentError {
10
10
  filename;
@@ -8,7 +8,7 @@ import { admitMessage, localizedText } from "../admission.mjs";
8
8
  import { agentToolsAttribute } from "../agent-tools.mjs";
9
9
  import { agentChats, channelChats } from "../chats.mjs";
10
10
  import { withButtonDecision } from "../confirmation-buttons.mjs";
11
- import { Vt as withChatAddress, b as agentAttachments, d as prepareInboundMedia, m as turnContent } from "../../../_chunks/principal-CVV9C_nO.mjs";
11
+ import { Vt as withChatAddress, b as agentAttachments, d as prepareInboundMedia, m as turnContent } from "../../../_chunks/principal-dEQyjF1n.mjs";
12
12
  import { channelAttributes, currentChannel, withNamedRoutes, withSessionChannels } from "../channel-scope.mjs";
13
13
  import { redactDiagnostic } from "../diagnostics.mjs";
14
14
  import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
@@ -7,7 +7,8 @@ import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
7
7
  * `attachments_send` in Slack: stored ontology files posted into the turn's Slack chat,
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
- * them all in the chat with the caption. Every call goes through the Slack connection,
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,
11
12
  * which adds the bot token and needs `files:write`; each upload carries at most the connection
12
13
  * proxy's 2 MiB, as Telegram's do. The checks and failures are every channel's
13
14
  * (`../attachments-send.ts`).
@@ -4,19 +4,15 @@ 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 { _ as AttachmentError } from "../../../_chunks/principal-CVV9C_nO.mjs";
7
+ import { _ as AttachmentError } from "../../../_chunks/principal-dEQyjF1n.mjs";
8
8
  import { sendStoredAttachments } from "../attachments-send.mjs";
9
- import { MAXIMUM_PROXY_BODY_BYTES, connectionProxy } from "../connection-proxy.mjs";
9
+ import { connectionProxy } from "../connection-proxy.mjs";
10
10
  import { redactDiagnostic } from "../diagnostics.mjs";
11
11
  import { proxyEnvironment } from "../environment.mjs";
12
12
  import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
13
- import { proxiedSlackFetch } from "./adapter.mjs";
14
13
  import { randomUUID } from "node:crypto";
15
- const SLACK_API = "https://slack.com/api/";
14
+ import { SLACK_FILE_BYTES, sendSlackFiles, slackFileRefusal } from "@segmentstream/ontology/slack";
16
15
  const PROXY_LIMIT = "The connection proxy takes at most 2 MiB per upload.";
17
- function isRecord(value) {
18
- return typeof value === "object" && value !== null && !Array.isArray(value);
19
- }
20
16
  function refused(code, message) {
21
17
  return new AttachmentError({
22
18
  code,
@@ -41,122 +37,85 @@ async function sendSlackAttachments(options) {
41
37
  async send(context) {
42
38
  const { input, chat, connection, owner, origin, environment, fetch, token, secrets } = context;
43
39
  const failed = context.failed;
44
- const slack = proxiedSlackFetch(() => connectionProxy({
40
+ const proxy = connectionProxy({
45
41
  environment: proxyEnvironment(environment),
46
42
  connection,
47
43
  token,
48
44
  fetch
49
- }), fetch);
50
- const call = async (method, init) => {
51
- const response = await slack(`${SLACK_API}${method}`, {
52
- method: "POST",
53
- ...init
54
- });
55
- const answer = await response.json().catch(() => void 0);
56
- if (!response.ok || !isRecord(answer) || answer.ok !== true) {
57
- const code = isRecord(answer) && typeof answer.error === "string" ? answer.error : "";
58
- throw new AttachmentError({
59
- code: code === "missing_scope" || code === "not_in_channel" ? "forbidden" : "send_failed",
60
- message: `Slack refused ${method}${code === "" ? "" : `: ${code}`}.`,
61
- status: response.status
62
- });
63
- }
64
- return answer;
65
- };
45
+ });
66
46
  const results = input.documentIds.map(({ id }) => ({
67
47
  id,
68
48
  filename: ""
69
49
  }));
70
- const uploaded = [];
71
- for (const [index, reference] of input.documentIds.entries()) {
72
- const fail = (error, operation) => {
73
- const stored = error instanceof StoredFileError ? error : void 0;
74
- results[index] = {
75
- id: reference.id,
76
- filename: stored?.filename ?? results[index].filename,
77
- ...failed(error, operation)
78
- };
79
- };
80
- let file;
81
- try {
82
- file = await fetchStoredFile({
83
- reference,
84
- owner,
85
- origin,
86
- token,
87
- fetch,
88
- secrets,
89
- tooLarge: () => refused("too_large", PROXY_LIMIT),
90
- limit: ({ size }) => {
91
- if (size > 2097152) throw refused("too_large", PROXY_LIMIT);
92
- if (size === 0) throw refused("unsupported", "Slack cannot share an empty file.");
93
- return MAXIMUM_PROXY_BODY_BYTES;
94
- }
95
- });
96
- } catch (error) {
97
- fail(error, "stored_attachment_fetch_failed");
98
- continue;
99
- }
50
+ const read = [];
51
+ for (const [index, reference] of input.documentIds.entries()) try {
52
+ const file = await fetchStoredFile({
53
+ reference,
54
+ owner,
55
+ origin,
56
+ token,
57
+ 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
+ }
65
+ });
100
66
  results[index] = {
101
67
  id: reference.id,
102
68
  filename: file.filename
103
69
  };
104
- try {
105
- const ticket = await call("files.getUploadURLExternal", {
106
- headers: { "content-type": "application/x-www-form-urlencoded" },
107
- body: new URLSearchParams({
108
- filename: file.filename,
109
- length: String(file.bytes.byteLength)
110
- }).toString()
111
- });
112
- if (typeof ticket.upload_url !== "string" || typeof ticket.file_id !== "string") throw refused("invalid_response", "Slack answered no upload address.");
113
- secrets.add(ticket.upload_url);
114
- const upload = await slack(ticket.upload_url, {
115
- method: "POST",
116
- headers: { "content-type": file.contentType },
117
- body: Buffer.from(file.bytes)
118
- });
119
- await upload.body?.cancel();
120
- if (!upload.ok) throw new AttachmentError({
121
- code: "send_failed",
122
- message: "Slack refused the file's bytes.",
123
- status: upload.status
124
- });
125
- uploaded.push({
126
- index,
127
- slackId: ticket.file_id
128
- });
129
- } catch (error) {
130
- fail(error, "attachment_upload_failed");
131
- }
132
- }
133
- if (uploaded.length === 0) return { files: results };
134
- try {
135
- const shared = await call("files.completeUploadExternal", {
136
- headers: { "content-type": "application/json; charset=utf-8" },
137
- body: JSON.stringify({
138
- files: uploaded.map(({ index, slackId }) => ({
139
- id: slackId,
140
- title: results[index].filename
141
- })),
142
- channel_id: chat.chatId,
143
- ...chat.threadId === "" ? {} : { thread_ts: chat.threadId },
144
- ...input.caption === void 0 ? {} : { initial_comment: input.caption }
145
- })
70
+ read.push({
71
+ ...file,
72
+ index
146
73
  });
147
- if (!Array.isArray(shared.files)) throw refused("invalid_response", "Slack did not answer the shared files.");
148
- for (const { index, slackId } of uploaded) results[index] = {
149
- ...results[index],
150
- slackFileId: slackId
151
- };
152
74
  } catch (error) {
153
- const failure = failed(error, "attachment_share_failed");
154
- for (const { index } of uploaded) results[index] = {
75
+ results[index] = {
76
+ id: reference.id,
77
+ filename: error instanceof StoredFileError ? error.filename : "",
78
+ ...failed(error, "stored_attachment_fetch_failed")
79
+ };
80
+ }
81
+ if (read.length === 0) return { files: results };
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
+ },
88
+ channel: chat.chatId,
89
+ ...chat.threadId === "" ? {} : { threadTs: chat.threadId },
90
+ files: read,
91
+ ...input.caption === void 0 ? {} : { text: input.caption }
92
+ });
93
+ for (const upload of sent.uploads) if ("code" in upload) results[upload.index] = {
94
+ ...results[upload.index],
95
+ ...failed(new AttachmentError({
96
+ code: upload.code,
97
+ message: "Slack did not take the file.",
98
+ cause: upload.cause
99
+ }), "attachment_upload_failed")
100
+ };
101
+ const share = sent.share;
102
+ if (share !== void 0 && share.status !== "sent") {
103
+ const failure = failed(new AttachmentError({
104
+ code: share.code ?? "send_failed",
105
+ message: "Slack did not share the files.",
106
+ cause: share.cause
107
+ }), "attachment_share_failed");
108
+ for (const index of share.files) results[index] = {
155
109
  ...results[index],
156
110
  error: failure.error,
157
111
  detail: failure.detail,
158
112
  reference: failure.reference
159
113
  };
114
+ } else if (share !== void 0) {
115
+ for (const upload of sent.uploads) if ("slackFileId" in upload) results[upload.index] = {
116
+ ...results[upload.index],
117
+ slackFileId: upload.slackFileId
118
+ };
160
119
  }
161
120
  return { files: results };
162
121
  }
@@ -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 { Ot as runtimeEnvelope, Rt as chatRuntimeSource, Vt as withChatAddress } from "../../../_chunks/principal-CVV9C_nO.mjs";
7
+ import { Ot as runtimeEnvelope, Rt as chatRuntimeSource, Vt as withChatAddress } from "../../../_chunks/principal-dEQyjF1n.mjs";
8
8
  import { currentChannel } from "../channel-scope.mjs";
9
9
  import { pressWorkspaceButton, queueWorkspaceButtonTurn, workspaceAction, workspaceButtonToken } from "../workspace-action.mjs";
10
10
  import { pairingNotice } from "./pairing.mjs";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { object } from "./confirmation-description.mjs";
8
- import { D as OntologyFileUnavailable, W as member, i as memberIdOf, j as ontologyTools } from "../../_chunks/principal-CVV9C_nO.mjs";
8
+ import { D as OntologyFileUnavailable, W as member, i as memberIdOf, j as ontologyTools } from "../../_chunks/principal-dEQyjF1n.mjs";
9
9
  import { redactDiagnostic } from "./diagnostics.mjs";
10
10
  import { createHash } from "node:crypto";
11
11
  async function readStoredFile(input, principal, options = {}) {
@@ -10,17 +10,17 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-DyupzJpt.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DCwk8DOP.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
17
17
  import { chooseModel } from "../../model.mjs";
18
- import { Ct as withDeliveryLocale, S as fetchStoredAttachment, St as safeTelegramFetch, b as agentAttachments, c as currentInboundRequest, l as runInboundRequest, mt as currentLocale, n as chatLanguage, o as telegramPrincipal, s as InboundRequest, u as withReplacedText, xt as reportTelegramError, yt as failureText } from "../../../_chunks/principal-CVV9C_nO.mjs";
18
+ import { Ct as withDeliveryLocale, S as fetchStoredAttachment, St as safeTelegramFetch, b as agentAttachments, c as currentInboundRequest, l as runInboundRequest, mt as currentLocale, n as chatLanguage, o as telegramPrincipal, s as InboundRequest, u as withReplacedText, xt as reportTelegramError, yt as failureText } from "../../../_chunks/principal-dEQyjF1n.mjs";
19
19
  import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
20
20
  import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
21
21
  import { agentIdentities } from "../identities.mjs";
22
22
  import { h as topicContext, r as chatArchive } from "../../../_chunks/chat-archive-DavfKJDI.mjs";
23
- import { a as captureTelegramFetch, h as telegramChatCapture, i as captureRouteDecider, s as chatIdentities, u as recordGateDecision } from "../../../_chunks/chat-archive-BBd_iZ1d.mjs";
23
+ import { a as captureTelegramFetch, h as telegramChatCapture, i as captureRouteDecider, s as chatIdentities, u as recordGateDecision } from "../../../_chunks/chat-archive-D4HRgOSo.mjs";
24
24
  import { runtimeTokenVerifier } from "../runtime-identity.mjs";
25
25
  import { runtimeToken } from "../runtime-token.mjs";
26
26
  import { botIdentityCache, proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { describableImage } from "../inbound-media/images.mjs";
8
- import { xt as reportTelegramError } from "../../../_chunks/principal-CVV9C_nO.mjs";
8
+ import { xt as reportTelegramError } from "../../../_chunks/principal-dEQyjF1n.mjs";
9
9
  import { gateway, generateText } from "ai";
10
10
  const MAXIMUM_ROUTING_ATTACHMENT_BYTES = 5242880;
11
11
  const ROUTING_ATTACHMENT_TIMEOUT_MS = 15e3;
@@ -4,8 +4,6 @@ import { type DocumentReference } from "../sent-files.js";
4
4
  import { type Environment } from "../environment.js";
5
5
  import { type RuntimeToken } from "../runtime-token.js";
6
6
  import { type TelegramAppLinkSettings } from "./app-links.js";
7
- export declare const MAXIMUM_PHOTO_BYTES: number;
8
- export declare const MAXIMUM_DOCUMENT_BYTES: number;
9
7
  export type { DocumentReference } from "../sent-files.js";
10
8
  export interface SendAttachmentsInput {
11
9
  readonly documentIds: ReadonlyArray<DocumentReference>;
@@ -5,26 +5,17 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { attachmentOwner } from "../attachment-tools.mjs";
8
- import { _ as AttachmentError, _t as customerMessage, bt as formattingRefused, xt as reportTelegramError, yt as failureText } from "../../../_chunks/principal-CVV9C_nO.mjs";
8
+ import { _ as AttachmentError, _t as customerMessage, xt as reportTelegramError, yt as failureText } from "../../../_chunks/principal-dEQyjF1n.mjs";
9
9
  import { attachmentFailure } from "../attachments-send.mjs";
10
- import { MAXIMUM_PROXY_BODY_BYTES, connectionProxy } from "../connection-proxy.mjs";
11
- import { redactDiagnostic } from "../diagnostics.mjs";
10
+ import { connectionProxy } from "../connection-proxy.mjs";
12
11
  import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
13
12
  import { appOrigin, channelsEnabled, proxyEnvironment } from "../environment.mjs";
14
13
  import { runtimeToken } from "../runtime-token.mjs";
15
14
  import { confirmationLocale } from "./confirmation-text.mjs";
16
15
  import { inTelegramSendQueue, telegramSendScope } from "./send-queue.mjs";
17
- import { withCrlfLineBreaks } from "./format.mjs";
18
16
  import { miniAppLinks, telegramAppLinkContext, withMiniAppLinks } from "./app-links.mjs";
19
17
  import { proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
20
- import { TELEGRAM_PLACEHOLDER_TOKEN, TELEGRAM_PROXY_ORIGIN, telegramProxyFetch } from "./proxy-fetch.mjs";
21
- const MAXIMUM_PHOTO_BYTES = 10485760;
22
- const MAXIMUM_DOCUMENT_BYTES = 52428800;
23
- const PHOTOS = new Set([
24
- "image/jpeg",
25
- "image/png",
26
- "image/webp"
27
- ]);
18
+ import { sendTelegramFiles, telegramFileBytes, telegramFileRefusal } from "@segmentstream/ontology/telegram";
28
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;
29
20
  const NAME = /^[a-z][a-z0-9_]{0,63}$/;
30
21
  function isRecord(value) {
@@ -111,15 +102,13 @@ async function sendAttachmentsInOrder(options) {
111
102
  token,
112
103
  fetch: fetchImpl
113
104
  });
114
- const telegram = telegramProxyFetch(proxy, scope);
115
105
  const results = options.input.documentIds.map(({ id }) => ({
116
106
  id,
117
107
  filename: ""
118
108
  }));
119
109
  const uploads = [];
120
110
  for (const [index, reference] of options.input.documentIds.entries()) try {
121
- let type = "document";
122
- const { filename, contentType, bytes } = await fetchStoredFile({
111
+ const file = await fetchStoredFile({
123
112
  reference,
124
113
  owner,
125
114
  origin,
@@ -128,20 +117,17 @@ async function sendAttachmentsInOrder(options) {
128
117
  secrets,
129
118
  tooLarge: () => refused("too_large", PROXY_LIMIT),
130
119
  limit: ({ contentType, size }) => {
131
- type = PHOTOS.has(contentType) ? "photo" : "document";
132
- const maximum = type === "photo" ? MAXIMUM_PHOTO_BYTES : MAXIMUM_DOCUMENT_BYTES;
133
- if (size > maximum) throw refused("too_large", `Telegram's ${type} limit is ${maximum / 1024 / 1024} MiB.`);
134
- if (size > 2097152) throw refused("too_large", PROXY_LIMIT);
135
- if (size === 0) throw refused("unsupported", "Telegram cannot send an empty file.");
136
- return Math.min(maximum, MAXIMUM_PROXY_BODY_BYTES);
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);
137
126
  }
138
127
  });
139
128
  uploads.push({
140
129
  index,
141
- id: reference.id,
142
- filename,
143
- type,
144
- blob: new Blob([Buffer.from(bytes)], { type: contentType })
130
+ file
145
131
  });
146
132
  } catch (error) {
147
133
  const errorId = reportTelegramError("stored_attachment_fetch_failed", error, { id: reference.id }, secrets);
@@ -156,37 +142,6 @@ async function sendAttachmentsInOrder(options) {
156
142
  })
157
143
  };
158
144
  }
159
- function multipart(files, caption) {
160
- const form = new FormData();
161
- form.set("chat_id", principal.attributes.chatId);
162
- const thread = principal.attributes.messageThreadId;
163
- if (typeof thread === "string" && /^\d+$/.test(thread)) form.set("message_thread_id", thread);
164
- if (options.input.replyToMessageId !== void 0) form.set("reply_parameters", JSON.stringify({ message_id: options.input.replyToMessageId }));
165
- if (files.length === 1) {
166
- const file = files[0];
167
- form.set(file.type, file.blob, file.filename);
168
- if (caption !== void 0) {
169
- const sent = withCrlfLineBreaks(caption);
170
- form.set("caption", sent.text);
171
- if (sent.entities.length > 0) form.set("caption_entities", JSON.stringify(sent.entities));
172
- }
173
- } else {
174
- form.set("media", JSON.stringify(files.map((file, index) => ({
175
- type: file.type,
176
- media: `attach://file${index}`,
177
- ...index === 0 && caption !== void 0 ? {
178
- caption: caption.text,
179
- ...caption.entities.length > 0 ? { caption_entities: caption.entities } : {}
180
- } : {}
181
- }))));
182
- files.forEach((file, index) => form.set(`file${index}`, file.blob, file.filename));
183
- }
184
- const method = files.length > 1 ? "sendMediaGroup" : files[0].type === "photo" ? "sendPhoto" : "sendDocument";
185
- return new Request(`${TELEGRAM_PROXY_ORIGIN}/bot${TELEGRAM_PLACEHOLDER_TOKEN}/${method}`, {
186
- method: "POST",
187
- body: form
188
- });
189
- }
190
145
  let caption = options.input.caption === void 0 ? void 0 : customerMessage(options.input.caption, locale, options.identifiers);
191
146
  const appLinks = caption === void 0 ? void 0 : telegramAppLinkContext(options.appLinks, environment, async () => (await runtimeBotIdentity(scope)({ request: (method, body) => proxiedBotRequest(proxy, method, body) }))?.username);
192
147
  if (caption !== void 0 && appLinks !== void 0) {
@@ -196,60 +151,41 @@ async function sendAttachmentsInOrder(options) {
196
151
  entities: withMiniAppLinks(caption.entities, links)
197
152
  };
198
153
  }
199
- let cursor = 0;
200
- while (cursor < uploads.length) {
201
- const batch = [uploads[cursor++]];
202
- let request = multipart(batch, caption);
203
- let size = (await request.clone().arrayBuffer()).byteLength;
204
- while (cursor < uploads.length && batch.length < 10 && uploads[cursor].type === batch[0].type) {
205
- const candidate = multipart([...batch, uploads[cursor]], caption);
206
- const candidateSize = (await candidate.clone().arrayBuffer()).byteLength;
207
- if (candidateSize > 2097152) break;
208
- batch.push(uploads[cursor++]);
209
- request = candidate;
210
- size = candidateSize;
211
- }
212
- try {
213
- if (size > 2097152) throw refused("too_large", PROXY_LIMIT);
214
- let response = await telegram(request);
215
- if (caption !== void 0 && caption.entities.length > 0 && await formattingRefused(response)) {
216
- caption = {
217
- text: caption.text,
218
- entities: []
219
- };
220
- response = await telegram(multipart(batch, caption));
221
- }
222
- const answer = await response.json();
223
- if (!response.ok || !isRecord(answer) || answer.ok !== true) {
224
- console.error("[segmentstream] Telegram attachment upload refused", {
225
- status: response.status,
226
- answer: redactDiagnostic(answer, secrets)
227
- });
228
- throw refused(response.status === 413 ? "too_large" : response.status === 403 ? "forbidden" : "send_failed", "Telegram refused the attachment upload.");
229
- }
230
- const messages = batch.length === 1 ? [answer.result] : answer.result;
231
- if (!Array.isArray(messages) || messages.length !== batch.length || !messages.every((message) => isRecord(message) && Number.isSafeInteger(message.message_id))) throw refused("invalid_response", "Telegram did not return the uploaded files' message ids.");
232
- batch.forEach((file, index) => {
233
- results[file.index] = {
234
- id: file.id,
235
- filename: file.filename,
236
- telegramMessageId: messages[index].message_id
237
- };
238
- });
239
- caption = void 0;
240
- } catch (error) {
241
- const errorId = reportTelegramError("attachment_upload_failed", error, {}, secrets);
242
- batch.forEach((file) => {
243
- results[file.index] = {
244
- id: file.id,
245
- filename: file.filename,
246
- error: error instanceof AttachmentError ? error.code : "send_failed",
247
- detail: failureText(errorId, "attachment", locale),
248
- reference: errorId
154
+ const thread = principal.attributes.messageThreadId;
155
+ const parts = await sendTelegramFiles({
156
+ request: (call) => proxy.request(call),
157
+ target: {
158
+ chatId: principal.attributes.chatId,
159
+ ...typeof thread === "string" ? { messageThreadId: thread } : {},
160
+ ...options.input.replyToMessageId === void 0 ? {} : { replyTo: options.input.replyToMessageId }
161
+ },
162
+ files: uploads.map(({ index, file }) => ({
163
+ ...file,
164
+ index
165
+ })),
166
+ ...caption === void 0 ? {} : { caption }
167
+ });
168
+ const filenames = new Map(uploads.map(({ index, file }) => [index, file.filename]));
169
+ for (const part of parts) {
170
+ if (part.status === "sent") {
171
+ part.files.forEach((index, position) => {
172
+ results[index] = {
173
+ id: results[index].id,
174
+ filename: filenames.get(index) ?? "",
175
+ telegramMessageId: Number(part.messageIds[position])
249
176
  };
250
177
  });
178
+ continue;
251
179
  }
180
+ const errorId = reportTelegramError("attachment_upload_failed", part.cause, {}, secrets);
181
+ for (const index of part.files) results[index] = {
182
+ id: results[index].id,
183
+ filename: filenames.get(index) ?? "",
184
+ error: part.code ?? "send_failed",
185
+ detail: failureText(errorId, "attachment", locale),
186
+ reference: errorId
187
+ };
252
188
  }
253
189
  return { files: results };
254
190
  }
255
- export { MAXIMUM_DOCUMENT_BYTES, MAXIMUM_PHOTO_BYTES, sendAttachments, sendAttachmentsInput };
191
+ export { sendAttachments, sendAttachmentsInput };
@@ -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 { Ot as runtimeEnvelope, c as currentInboundRequest, i as memberIdOf, kt as telegramRuntimeSource, o as telegramPrincipal, xt as reportTelegramError } from "../../../_chunks/principal-CVV9C_nO.mjs";
7
+ import { Ot as runtimeEnvelope, c as currentInboundRequest, i as memberIdOf, kt as telegramRuntimeSource, o as telegramPrincipal, xt as reportTelegramError } from "../../../_chunks/principal-dEQyjF1n.mjs";
8
8
  import { formatAddress, parseAddress, scopedAddress } from "./sessions.mjs";
9
9
  import { telegramText } from "./texts.mjs";
10
10
  import { isWorkspaceCallback, pressWorkspaceButton, queueWorkspaceButtonTurn, workspaceAction, workspaceButtonToken } from "../workspace-action.mjs";
@@ -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 REVISION_CLAIM_TTL_MS, n as attachmentIdentity, r as attachmentRefs, i as captureRouteDecider, a as captureTelegramFetch, o as captureTelegramWebhook, s as chatIdentities, c as currentCapture, l as participants, u as recordGateDecision, d as recordInboundContent, f as recordRouteDecision, p as recordSessionFailure, m as registerCapture, h as telegramChatCapture } from "../../../_chunks/chat-archive-BBd_iZ1d.mjs";
7
+ export { t as REVISION_CLAIM_TTL_MS, n as attachmentIdentity, r as attachmentRefs, i as captureRouteDecider, a as captureTelegramFetch, o as captureTelegramWebhook, s as chatIdentities, c as currentCapture, l as participants, u as recordGateDecision, d as recordInboundContent, f as recordRouteDecision, p as recordSessionFailure, m as registerCapture, h as telegramChatCapture } from "../../../_chunks/chat-archive-D4HRgOSo.mjs";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { telegramText } from "./texts.mjs";
8
- import { F as confirmations, It as chatChannel, c as currentInboundRequest, i as memberIdOf, o as telegramPrincipal, xt as reportTelegramError } from "../../../_chunks/principal-CVV9C_nO.mjs";
8
+ import { F as confirmations, It as chatChannel, c as currentInboundRequest, i as memberIdOf, o as telegramPrincipal, xt as reportTelegramError } from "../../../_chunks/principal-dEQyjF1n.mjs";
9
9
  import { humanText } from "../confirmation-description.mjs";
10
10
  import { withConfirmationPrompt } from "../group-routing/messages.mjs";
11
11
  import { chatPostOperationId, isChatPost } from "../chat-post-confirmation.mjs";