@segmentstream/agent 0.48.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/_chunks/{build-metadata-DjhDPTy-.mjs → build-metadata-DrQtDIMX.mjs} +1 -1
  3. package/dist/_chunks/principal-D5Tualrk.mjs +1836 -0
  4. package/dist/extension/channels/slack.mjs +2 -1
  5. package/dist/extension/channels/whatsapp.mjs +1 -0
  6. package/dist/extension/connections/ontology.mjs +1 -1
  7. package/dist/extension/hooks/authorization.mjs +1 -1
  8. package/dist/extension/instructions/persona.mjs +1 -1
  9. package/dist/extension/lib/actor.mjs +1 -46
  10. package/dist/extension/lib/attachment-tools.mjs +1 -3
  11. package/dist/extension/lib/attachments.d.ts +1 -1
  12. package/dist/extension/lib/attachments.mjs +1 -230
  13. package/dist/extension/lib/build-metadata.mjs +1 -1
  14. package/dist/extension/lib/chat-address.mjs +1 -50
  15. package/dist/extension/lib/chat-context.mjs +1 -1
  16. package/dist/extension/lib/chat-recorder.mjs +1 -2
  17. package/dist/extension/lib/confirmations.mjs +1 -179
  18. package/dist/extension/lib/inbound-media/files.d.ts +91 -0
  19. package/dist/extension/lib/inbound-media/files.mjs +7 -0
  20. package/dist/extension/lib/{telegram → inbound-media}/images.d.ts +2 -0
  21. package/dist/extension/lib/{telegram → inbound-media}/images.mjs +1 -2
  22. package/dist/extension/lib/inbound-media/index.d.ts +55 -0
  23. package/dist/extension/lib/inbound-media/index.mjs +7 -0
  24. package/dist/extension/lib/inbound-media/plan.d.ts +59 -0
  25. package/dist/extension/lib/{telegram/media-policy.mjs → inbound-media/plan.mjs} +56 -4
  26. package/dist/extension/lib/inbound-media/report.d.ts +5 -0
  27. package/dist/extension/lib/inbound-media/report.mjs +7 -0
  28. package/dist/extension/lib/inbound-media/speech.d.ts +52 -0
  29. package/dist/extension/lib/inbound-media/speech.mjs +73 -0
  30. package/dist/extension/lib/ontology-connection.mjs +1 -101
  31. package/dist/extension/lib/ontology-file-call.mjs +1 -4
  32. package/dist/extension/lib/ontology-tools.mjs +1 -377
  33. package/dist/extension/lib/review/hold.mjs +1 -2
  34. package/dist/extension/lib/review/reply.mjs +1 -2
  35. package/dist/extension/lib/role-skill.mjs +1 -1
  36. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  37. package/dist/extension/lib/sent-files.mjs +1 -2
  38. package/dist/extension/lib/slack/adapter.d.ts +49 -7
  39. package/dist/extension/lib/slack/adapter.mjs +79 -21
  40. package/dist/extension/lib/slack/attachments-send.mjs +1 -3
  41. package/dist/extension/lib/slack/files.d.ts +12 -19
  42. package/dist/extension/lib/slack/files.mjs +26 -58
  43. package/dist/extension/lib/stored-files.mjs +1 -3
  44. package/dist/extension/lib/telegram/adapter.d.ts +3 -3
  45. package/dist/extension/lib/telegram/adapter.mjs +13 -17
  46. package/dist/extension/lib/telegram/attachment-description.d.ts +1 -1
  47. package/dist/extension/lib/telegram/attachment-description.mjs +2 -2
  48. package/dist/extension/lib/telegram/attachments-send.mjs +1 -3
  49. package/dist/extension/lib/telegram/callbacks.mjs +1 -2
  50. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  51. package/dist/extension/lib/telegram/confirmations.mjs +1 -3
  52. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  53. package/dist/extension/lib/telegram/files.d.ts +8 -15
  54. package/dist/extension/lib/telegram/files.mjs +32 -107
  55. package/dist/extension/lib/telegram/health.mjs +1 -1
  56. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  57. package/dist/extension/lib/telegram/inbound-request.d.ts +6 -12
  58. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  59. package/dist/extension/lib/telegram/inbound.d.ts +3 -3
  60. package/dist/extension/lib/telegram/inbound.mjs +11 -11
  61. package/dist/extension/lib/telegram/lifecycle.mjs +2 -6
  62. package/dist/extension/lib/telegram/principal.mjs +1 -1
  63. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  64. package/dist/extension/lib/telegram/silent.mjs +1 -1
  65. package/dist/extension/lib/telegram/structured.mjs +1 -1
  66. package/dist/extension/lib/telegram/turn-errors.mjs +1 -2
  67. package/dist/extension/lib/telegram/voice.d.ts +7 -38
  68. package/dist/extension/lib/telegram/voice.mjs +1 -64
  69. package/dist/extension/lib/telegram/workspace-action.mjs +1 -3
  70. package/dist/extension/lib/web/auth.mjs +1 -168
  71. package/dist/extension/lib/web/channel.d.ts +13 -4
  72. package/dist/extension/lib/web/channel.mjs +15 -8
  73. package/dist/extension/lib/whatsapp/adapter.d.ts +37 -1
  74. package/dist/extension/lib/whatsapp/adapter.mjs +118 -21
  75. package/dist/extension/lib/whatsapp/files.d.ts +40 -0
  76. package/dist/extension/lib/whatsapp/files.mjs +70 -0
  77. package/dist/extension/lib/workspace-source.mjs +1 -3
  78. package/dist/extension/model.mjs +1 -1
  79. package/dist/extension/tools/attachments_discard.mjs +1 -1
  80. package/dist/extension/tools/attachments_list.mjs +1 -1
  81. package/dist/extension/tools/attachments_promote.mjs +1 -5
  82. package/dist/extension/tools/attachments_read.mjs +1 -1
  83. package/dist/extension/tools/attachments_send.mjs +1 -2
  84. package/dist/extension/tools/attachments_stage.mjs +1 -1
  85. package/dist/extension/tools/attachments_table.mjs +1 -1
  86. package/dist/extension/tools/questions_ask.mjs +1 -2
  87. package/dist/extension/tools/workspace_source.mjs +1 -1
  88. package/package.json +2 -2
  89. package/dist/_chunks/inbound-request-B3RhCuOw.mjs +0 -413
  90. package/dist/_chunks/principal-Dzs8hUDB.mjs +0 -128
  91. package/dist/extension/lib/telegram/media-policy.d.ts +0 -15
@@ -7,14 +7,16 @@ __eveCreateRequire(import.meta.url);
7
7
  import { admitMessage, localizedText } from "../admission.mjs";
8
8
  import { agentChats } from "../chats.mjs";
9
9
  import { withButtonDecision } from "../confirmation-buttons.mjs";
10
- import { withChatAddress } from "../chat-address.mjs";
10
+ import { S as agentAttachments, ct as withChatAddress, d as prepareInboundMedia, m as turnContent } from "../../../_chunks/principal-D5Tualrk.mjs";
11
11
  import { redactDiagnostic } from "../diagnostics.mjs";
12
12
  import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
13
13
  import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
14
- import { agentAttachments } from "../attachments.mjs";
14
+ import { providerChat } from "../attachment-tools.mjs";
15
15
  import { agentIdentities } from "../identities.mjs";
16
- import { attachmentsContext } from "../telegram/files.mjs";
17
- import { slackFileDownload, stageSlackFiles } from "./files.mjs";
16
+ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
17
+ import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.mjs";
18
+ import { gatewayTranscriber } from "../inbound-media/speech.mjs";
19
+ import { slackFileDownload, slackFiles } from "./files.mjs";
18
20
  import { runtimeToken } from "../runtime-token.mjs";
19
21
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
20
22
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -232,16 +234,28 @@ function segmentstreamSlack(options) {
232
234
  return lookup.status === "paired" ? slackPrincipal(lookup.member, user) : null;
233
235
  }
234
236
  let store = options.attachments;
237
+ const capabilities = options.modelCapabilities ?? gatewayMediaCapabilities(options.fetch, reportWithReference);
235
238
  const files = {
236
239
  attachments: () => store ??= agentAttachments({
237
240
  origin: appOrigin(environment),
238
241
  token,
239
242
  ...options.fetch === void 0 ? {} : { fetch: options.fetch }
240
243
  }),
241
- download: slackFileDownload(slackFetch)
244
+ download: slackFileDownload(slackFetch),
245
+ sttModel: () => options.models?.().stt ?? false,
246
+ transcribe: options.transcribe ?? gatewayTranscriber,
247
+ describeImage: options.describeImage ?? gatewayImageDescriber,
248
+ ...options.models === void 0 ? {} : { plan: (principal, session) => turnMediaPlan({
249
+ models: options.models(),
250
+ principal,
251
+ ...session === void 0 ? {} : { session },
252
+ capabilities,
253
+ environment,
254
+ report: reportWithReference
255
+ }) }
242
256
  };
243
257
  const admit = (direct) => (ctx, message) => {
244
- const waitUntil = requestWork.getStore();
258
+ const work = requestWork.getStore();
245
259
  return receive({
246
260
  ctx,
247
261
  message,
@@ -251,7 +265,12 @@ function segmentstreamSlack(options) {
251
265
  environment,
252
266
  chats,
253
267
  files,
254
- ...waitUntil === void 0 ? {} : { waitUntil }
268
+ ...work === void 0 ? {} : {
269
+ waitUntil: work.waitUntil,
270
+ turn: (media) => {
271
+ work.turn = media;
272
+ }
273
+ }
255
274
  });
256
275
  };
257
276
  const observe = async (relayed, waitUntil) => {
@@ -319,8 +338,29 @@ function gatedRoute(route, options, environment, observe) {
319
338
  handler: async (request, args) => {
320
339
  if (!channelsEnabled(environment) || options.settings() === null || webhookSecret(environment) === void 0) return new Response(null, { status: 404 });
321
340
  const waitUntil = (task) => args.waitUntil(task);
341
+ const work = { waitUntil };
322
342
  await observe(request, waitUntil);
323
- return requestWork.run(waitUntil, () => route.handler(request, args));
343
+ return requestWork.run(work, () => route.handler(request, {
344
+ ...args,
345
+ from: (address) => withTurnMedia(args.from(address), () => work.turn)
346
+ }));
347
+ }
348
+ };
349
+ }
350
+ function withTurnMedia(source, turn) {
351
+ return {
352
+ ...source,
353
+ send(message, options) {
354
+ const current = turn();
355
+ return source.send(current === void 0 ? message : turnContent(message, {
356
+ files: current.media.files,
357
+ keyOf: (part) => {
358
+ const data = part.data;
359
+ const href = data instanceof URL ? data.href : typeof data === "string" ? data : void 0;
360
+ return href === void 0 ? void 0 : current.keys.get(href);
361
+ },
362
+ spoken: current.media.spoken
363
+ }), options);
324
364
  }
325
365
  };
326
366
  }
@@ -367,21 +407,38 @@ async function receive(input) {
367
407
  ...input.direct ? { peer: user } : {}
368
408
  });
369
409
  if (message.attachments.length === 0 || input.files === void 0) return { auth };
370
- const files = await stageSlackFiles({
410
+ const channelId = ctx.slack.channelId;
411
+ const files = slackFiles({
371
412
  files: message.attachments,
372
- channelId: ctx.slack.channelId,
373
- messageTs: message.ts,
374
- memberId: resolution.member.id,
375
- attachments: input.files.attachments(),
376
- download: input.files.download,
377
- report: reportWithReference
413
+ ...message.raw === void 0 ? {} : { raw: message.raw },
414
+ download: input.files.download
415
+ });
416
+ const resolveSession = ctx.resolveSession?.bind(ctx);
417
+ const plan = await input.files.plan?.(auth, resolveSession);
418
+ const media = await prepareInboundMedia({
419
+ caption: message.text,
420
+ files,
421
+ group: !input.direct,
422
+ sttModel: input.files.sttModel?.() ?? false,
423
+ transcribe: input.files.transcribe ?? gatewayTranscriber,
424
+ report: reportWithReference,
425
+ ...plan === void 0 ? {} : { plan },
426
+ ...input.files.describeImage === void 0 ? {} : { describeImage: input.files.describeImage },
427
+ store: {
428
+ attachments: input.files.attachments(),
429
+ memberId: resolution.member.id,
430
+ chat: providerChat("slack", channelId),
431
+ source: "slack",
432
+ sourceRef: (index) => `${channelId}:${message.ts}:${index}`
433
+ }
434
+ });
435
+ input.turn?.({
436
+ media,
437
+ keys: new Map(files.flatMap((file) => file.url === void 0 ? [] : [[file.url, file.key]]))
378
438
  });
379
439
  return {
380
440
  auth,
381
- context: attachmentsContext({
382
- files,
383
- group: !input.direct
384
- })
441
+ context: [...media.context]
385
442
  };
386
443
  case "pairing_required": {
387
444
  const text = localizedText(admission.replies.pairingRequired);
@@ -426,9 +483,10 @@ function report(operation, error) {
426
483
  error: redactDiagnostic(error, new Set())
427
484
  });
428
485
  }
429
- function reportWithReference(operation, error) {
486
+ function reportWithReference(operation, error, metadata = {}) {
430
487
  const reference = randomUUID();
431
488
  console.error("[segmentstream] Slack delivery diagnostic", {
489
+ ...metadata,
432
490
  operation,
433
491
  reference,
434
492
  error: redactDiagnostic(error, new Set())
@@ -438,4 +496,4 @@ function reportWithReference(operation, error) {
438
496
  function digest(value) {
439
497
  return createHash("sha256").update(value, "utf8").digest();
440
498
  }
441
- export { SLACK_AUTHENTICATOR, SlackProxyRouteError, followsThreadReply, proxiedSlackFetch, receive, relayedRequestVerifier, reportMembership, segmentstreamSlack, slackChannelTitle, slackPrincipal };
499
+ export { SLACK_AUTHENTICATOR, SlackProxyRouteError, followsThreadReply, proxiedSlackFetch, receive, relayedRequestVerifier, reportMembership, segmentstreamSlack, slackChannelTitle, slackPrincipal, withTurnMedia };
@@ -5,16 +5,14 @@ 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 { AttachmentError } from "../attachments.mjs";
8
+ import { _ as AttachmentError, ht as failureText, ot as chatAddressOf } from "../../../_chunks/principal-D5Tualrk.mjs";
9
9
  import { MAXIMUM_PROXY_BODY_BYTES, connectionProxy } from "../connection-proxy.mjs";
10
- import { chatAddressOf } from "../chat-address.mjs";
11
10
  import { redactDiagnostic } from "../diagnostics.mjs";
12
11
  import { appOrigin, channelsEnabled, proxyEnvironment } from "../environment.mjs";
13
12
  import { transientFileStatus } from "../file-grant.mjs";
14
13
  import { runtimeToken } from "../runtime-token.mjs";
15
14
  import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
16
15
  import { confirmationLocale } from "../telegram/confirmation-text.mjs";
17
- import { d as failureText } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
18
16
  import { proxiedSlackFetch } from "./adapter.mjs";
19
17
  import { randomUUID } from "node:crypto";
20
18
  const SLACK_API = "https://slack.com/api/";
@@ -1,13 +1,10 @@
1
1
  import type { SlackMessage } from "eve/channels/slack";
2
- import { type AgentAttachments } from "../attachments.js";
3
- import type { StagedFile } from "../telegram/inbound-request.js";
2
+ import type { InboundFile } from "../inbound-media/index.js";
4
3
  /**
5
- * Files a member sends the agent in Slack (`docs/agent.md`, "Attachments"), stored as Telegram's
6
- * are: before the turn starts, each file is downloaded through the Slack connection and stored once
7
- * as a temporary attachment of the member, in this channel, for 24 hours. The turn learns each
8
- * attachment's id from an `<attachments>` block, so the model can read, discard or promote it with
9
- * the attachment tools; eve still hands the model the file itself. A file that cannot be stored
10
- * is named in the block with the reason, never dropped silently.
4
+ * The files of a Slack message, described for the inbound media pipeline (`docs/agent.md`,
5
+ * "Attachments"), which transcribes a voice clip and stores each file once as the member's
6
+ * attachment in this channel. eve still hands the model the file itself, downloading it through
7
+ * the same connection when the turn starts; a voice clip's transcript stands in for it.
11
8
  */
12
9
  /** A Slack file as eve parses it from the message. */
13
10
  type SlackFile = SlackMessage["attachments"][number];
@@ -16,19 +13,15 @@ type SlackFile = SlackMessage["attachments"][number];
16
13
  * gave the file, so that an HTML file is told from Slack's sign-in page.
17
14
  */
18
15
  export type SlackFileDownload = (url: string, maxBytes: number, contentType: string) => Promise<Uint8Array>;
19
- /** Stores the message's files one after another, so that only one file is held at a time. */
20
- export declare function stageSlackFiles(input: {
16
+ /** The message's files, keyed by Slack file id, with the Slack URL each one's file part names. */
17
+ export declare function slackFiles(input: {
21
18
  readonly files: ReadonlyArray<SlackFile>;
22
- /** The channel, direct message or group direct message the files were sent in. */
23
- readonly channelId: string;
24
- /** The message's `ts`, which with the file's position identifies it on redelivery. */
25
- readonly messageTs: string;
26
- readonly memberId: string;
27
- readonly attachments: AgentAttachments;
19
+ /** The message's raw event, whose `files` carry what eve does not parse, such as a clip's length. */
20
+ readonly raw?: Readonly<Record<string, unknown>>;
28
21
  readonly download: SlackFileDownload;
29
- /** Records a failure for operators; answers the reference the model may quote. */
30
- readonly report: (operation: string, error: unknown) => string;
31
- }): Promise<ReadonlyMap<string, StagedFile>>;
22
+ }): ReadonlyArray<InboundFile & {
23
+ readonly url: string | undefined;
24
+ }>;
32
25
  /**
33
26
  * Downloads a Slack file through the channel's transport, which follows Slack's redirect through
34
27
  * the connection proxy. A web page answered for a file that is not one, such as Slack's sign-in
@@ -4,65 +4,33 @@ 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 { providerChat } from "../attachment-tools.mjs";
8
- import { MAXIMUM_ATTACHMENT_BYTES, attachmentUrl } from "../attachments.mjs";
9
- function megabytes(bytes) {
10
- return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
7
+ function record(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
9
+ }
10
+ function kindOf(file, raw) {
11
+ const type = file.mimeType ?? "";
12
+ return raw.subtype === "slack_audio" ? "voice" : raw.subtype === "slack_video" ? "video_note" : type.startsWith("audio/") ? "audio" : type.startsWith("video/") ? "video" : type.startsWith("image/") ? "image" : "document";
11
13
  }
12
- async function stageSlackFiles(input) {
13
- const chat = providerChat("slack", input.channelId);
14
- const staged = new Map();
15
- for (const [index, file] of input.files.entries()) {
16
- const key = file.id === "" ? `file-${index}` : file.id;
17
- const filename = file.name?.trim() || `file-${index}`;
14
+ function slackFiles(input) {
15
+ const raw = Array.isArray(input.raw?.files) ? input.raw.files.map(record) : [];
16
+ return input.files.map((file, index) => {
17
+ const details = raw.find((each) => each.id === file.id) ?? {};
18
18
  const contentType = file.mimeType ?? "application/octet-stream";
19
- if (file.size !== void 0 && file.size > MAXIMUM_ATTACHMENT_BYTES) {
20
- staged.set(key, {
21
- status: "refused",
22
- filename,
23
- reason: `it is ${megabytes(file.size)}, over the ${megabytes(MAXIMUM_ATTACHMENT_BYTES)} the agent accepts`
24
- });
25
- continue;
26
- }
27
- if (file.url === void 0) {
28
- staged.set(key, {
29
- status: "refused",
30
- filename,
31
- reason: "Slack gave no address for it"
32
- });
33
- continue;
34
- }
35
- try {
36
- const bytes = await input.download(file.url, MAXIMUM_ATTACHMENT_BYTES, contentType);
37
- const attachment = await input.attachments.receive({
38
- memberId: input.memberId,
39
- chat
40
- }, {
41
- bytes,
42
- filename,
43
- contentType,
44
- sourceRef: `${input.channelId}:${input.messageTs}:${index}`,
45
- source: "slack"
46
- });
47
- staged.set(key, {
48
- status: "stored",
49
- attachment,
50
- url: attachmentUrl({
51
- id: attachment.id,
52
- memberId: input.memberId,
53
- chat
54
- })
55
- });
56
- } catch (error) {
57
- const reference = input.report("attachment_storage_failed", error);
58
- staged.set(key, {
59
- status: "refused",
60
- filename,
61
- reason: `it could not be stored (reference ${reference})`
62
- });
63
- }
64
- }
65
- return staged;
19
+ const milliseconds = details.duration_ms;
20
+ return {
21
+ key: file.id === "" ? `file-${index}` : file.id,
22
+ kind: kindOf(file, details),
23
+ filename: file.name?.trim() || `file-${index}`,
24
+ contentType,
25
+ url: file.url,
26
+ ...file.size === void 0 ? {} : { size: file.size },
27
+ ...typeof milliseconds === "number" && Number.isFinite(milliseconds) ? { seconds: milliseconds / 1e3 } : {},
28
+ download: (maxBytes) => file.url === void 0 ? Promise.reject(new Error("Slack gave no address for the file.")) : input.download(file.url, maxBytes, contentType)
29
+ };
30
+ });
31
+ }
32
+ function megabytes(bytes) {
33
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
66
34
  }
67
35
  function slackFileDownload(transport) {
68
36
  return async (url, maxBytes, contentType) => {
@@ -91,4 +59,4 @@ function slackFileDownload(transport) {
91
59
  return new Uint8Array(Buffer.concat(chunks));
92
60
  };
93
61
  }
94
- export { slackFileDownload, stageSlackFiles };
62
+ export { slackFileDownload, slackFiles };
@@ -5,9 +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 { OntologyFileUnavailable, ontologyTools } from "./ontology-tools.mjs";
9
- import { i as memberIdOf } from "../../_chunks/principal-Dzs8hUDB.mjs";
10
- import { member } from "./actor.mjs";
8
+ import { M as ontologyTools, O as OntologyFileUnavailable, W as member, i as memberIdOf } from "../../_chunks/principal-D5Tualrk.mjs";
11
9
  import { redactDiagnostic } from "./diagnostics.mjs";
12
10
  import { createHash } from "node:crypto";
13
11
  async function readStoredFile(input, principal, options = {}) {
@@ -7,12 +7,12 @@ import { type Environment } from "../environment.js";
7
7
  import { type ChatArchive } from "../chat-archive.js";
8
8
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
9
9
  import { type RuntimeToken } from "../runtime-token.js";
10
- import { type ImageDescriber } from "./images.js";
11
- import { type CapabilityLookup } from "./media-policy.js";
10
+ import { type ImageDescriber } from "../inbound-media/images.js";
11
+ import { type CapabilityLookup } from "../inbound-media/plan.js";
12
+ import { type Transcriber } from "../inbound-media/speech.js";
12
13
  import { type DecideFunction } from "./router.js";
13
14
  import { type HistoryReader } from "./sessions.js";
14
15
  import { type ChannelReviewOptions } from "../review/reply.js";
15
- import { type Transcriber } from "./voice.js";
16
16
  /**
17
17
  * The SegmentStream Telegram adapter: eve's `telegramChannel`, with its credentials, identity,
18
18
  * voice and routing replaced (`agent-design.md`, section 4). Everything it reads from the mount's
@@ -10,12 +10,12 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback, isWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-DjhDPTy-.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DrQtDIMX.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 { agentAttachments, parseAttachmentUrl } from "../attachments.mjs";
18
+ import { S as agentAttachments, _t as reportTelegramError, c as currentInboundRequest, ht as failureText, l as runInboundRequest, n as chatLanguage, o as telegramPrincipal, s as InboundRequest, u as withReplacedText, ut as currentLocale, vt as safeTelegramFetch, w as parseAttachmentUrl, yt as withDeliveryLocale } from "../../../_chunks/principal-D5Tualrk.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";
@@ -26,11 +26,10 @@ import { runtimeToken } from "../runtime-token.mjs";
26
26
  import { botIdentityCache, proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
27
27
  import { handleConfirmationCallback, telegramConfirmationEvents } from "./confirmations.mjs";
28
28
  import { confirmationLocale } from "./confirmation-text.mjs";
29
- import { d as failureText, h as withDeliveryLocale, i as withReplacedText, m as safeTelegramFetch, n as currentInboundRequest, o as currentLocale, p as reportTelegramError, r as runInboundRequest, t as InboundRequest } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
30
29
  import { telegramAppLinkContext } from "./app-links.mjs";
31
- import { n as chatLanguage, o as telegramPrincipal } from "../../../_chunks/principal-Dzs8hUDB.mjs";
32
- import { gatewayImageDescriber } from "./images.mjs";
33
- import { gatewayMediaCapabilities, planMedia } from "./media-policy.mjs";
30
+ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
31
+ import { chatMediaPlan, gatewayMediaCapabilities, sessionModel } from "../inbound-media/plan.mjs";
32
+ import { gatewayTranscriber } from "../inbound-media/speech.mjs";
34
33
  import { agentChats } from "../chats.mjs";
35
34
  import { handleInboundMessage } from "./inbound.mjs";
36
35
  import { recoverableSessions } from "./session-recovery.mjs";
@@ -43,7 +42,7 @@ import { channelReview } from "../review/reply.mjs";
43
42
  import { telegramSendScope } from "./send-queue.mjs";
44
43
  import { telegramFailureEvents } from "./turn-errors.mjs";
45
44
  import { withDeliveryDiagnostics } from "./delivery-diagnostics.mjs";
46
- import { downloadTelegramFile, gatewayTranscriber } from "./voice.mjs";
45
+ import { downloadTelegramFile } from "./voice.mjs";
47
46
  import { telegramWebhookVerifier } from "./webhook.mjs";
48
47
  import { telegramPreviewEnvironment } from "@segmentstream/ontology/telegram";
49
48
  import { telegramChannel } from "eve/channels/telegram";
@@ -84,7 +83,7 @@ function segmentstreamTelegram(options) {
84
83
  const token = options.token ?? runtimeToken;
85
84
  const readHistory = options.history ?? eveHistory;
86
85
  const readInteractions = options.history ?? eveInteractions;
87
- const capabilities = options.modelCapabilities ?? gatewayMediaCapabilities(options.fetch);
86
+ const capabilities = options.modelCapabilities ?? gatewayMediaCapabilities(options.fetch, reportTelegramError);
88
87
  const archive = options.archive ?? chatArchive({
89
88
  environment,
90
89
  token,
@@ -259,10 +258,7 @@ function segmentstreamTelegram(options) {
259
258
  mediaPlan: async (member, sessionId) => {
260
259
  let selected;
261
260
  if (sessionId !== void 0) try {
262
- for (const event of await readHistory(sessionId)) {
263
- const data = event.data;
264
- if (event.type === "model.started" && typeof data?.modelId === "string") selected = data.modelId;
265
- }
261
+ selected = await sessionModel(await readHistory(sessionId));
266
262
  } catch (error) {
267
263
  reportTelegramError("media_session_model_lookup_failed", error, { sessionId });
268
264
  }
@@ -280,11 +276,11 @@ function segmentstreamTelegram(options) {
280
276
  environment
281
277
  });
282
278
  }
283
- return planMedia(selected === void 0 ? {
284
- known: false,
285
- images: false,
286
- audio: false
287
- } : await capabilities(selected), options.models().imageDescription ?? null);
279
+ return chatMediaPlan({
280
+ model: selected,
281
+ capabilities,
282
+ imageDescription: options.models().imageDescription
283
+ });
288
284
  },
289
285
  identities: chatIdentities(pairing()),
290
286
  bot: botIdentity(),
@@ -1,4 +1,4 @@
1
- import { type ImageDescriber } from "./images.js";
1
+ import { type ImageDescriber } from "../inbound-media/images.js";
2
2
  /** Routing has a separate budget from storing the original or running a full agent turn. */
3
3
  export declare const MAXIMUM_ROUTING_ATTACHMENT_BYTES: number;
4
4
  export declare const ROUTING_ATTACHMENT_TIMEOUT_MS = 15000;
@@ -4,8 +4,8 @@ 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 { describableImage } from "./images.mjs";
8
- import { p as reportTelegramError } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
7
+ import { describableImage } from "../inbound-media/images.mjs";
8
+ import { _t as reportTelegramError } from "../../../_chunks/principal-D5Tualrk.mjs";
9
9
  import { gateway, generateText } from "ai";
10
10
  const MAXIMUM_ROUTING_ATTACHMENT_BYTES = 5242880;
11
11
  const ROUTING_ATTACHMENT_TIMEOUT_MS = 15e3;
@@ -5,17 +5,15 @@ 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 { AttachmentError } from "../attachments.mjs";
8
+ import { _ as AttachmentError, _t as reportTelegramError, gt as formattingRefused, ht as failureText, pt as customerMessage } from "../../../_chunks/principal-D5Tualrk.mjs";
9
9
  import { MAXIMUM_PROXY_BODY_BYTES, connectionProxy } from "../connection-proxy.mjs";
10
10
  import { redactDiagnostic } from "../diagnostics.mjs";
11
11
  import { transientFileStatus } from "../file-grant.mjs";
12
12
  import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
13
13
  import { appOrigin, channelsEnabled, proxyEnvironment } from "../environment.mjs";
14
14
  import { runtimeToken } from "../runtime-token.mjs";
15
- import "../../../_chunks/principal-Dzs8hUDB.mjs";
16
15
  import { confirmationLocale } from "./confirmation-text.mjs";
17
16
  import { inTelegramSendQueue, telegramSendScope } from "./send-queue.mjs";
18
- import { d as failureText, f as formattingRefused, l as customerMessage, p as reportTelegramError } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
19
17
  import { miniAppLinks, telegramAppLinkContext, withMiniAppLinks } from "./app-links.mjs";
20
18
  import { proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
21
19
  import { TELEGRAM_PLACEHOLDER_TOKEN, TELEGRAM_PROXY_ORIGIN, telegramProxyFetch } from "./proxy-fetch.mjs";
@@ -5,8 +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 telegramRuntimeSource, i as memberIdOf, o as telegramPrincipal, u as runtimeEnvelope } from "../../../_chunks/principal-Dzs8hUDB.mjs";
9
- import { n as currentInboundRequest, p as reportTelegramError } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
8
+ import { Ct as runtimeEnvelope, _t as reportTelegramError, c as currentInboundRequest, i as memberIdOf, o as telegramPrincipal, wt as telegramRuntimeSource } from "../../../_chunks/principal-D5Tualrk.mjs";
10
9
  import { formatAddress, parseAddress, scopedAddress } from "./sessions.mjs";
11
10
  import { telegramText } from "./texts.mjs";
12
11
  import { workspaceAction } from "./workspace-action.mjs";
@@ -9,7 +9,7 @@ import { n as contentText, t as CONTENT_CAPS } from "../../../_chunks/content-cD
9
9
  import { chatEvent, sessionFailureEventId } from "../chat-archive.mjs";
10
10
  import { currentConfirmationPrompt } from "../group-routing/messages.mjs";
11
11
  import { messageMetadata } from "./message-metadata.mjs";
12
- import { n as currentInboundRequest, p as reportTelegramError, s as currentThreadId } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
12
+ import { _t as reportTelegramError, c as currentInboundRequest, dt as currentThreadId } from "../../../_chunks/principal-D5Tualrk.mjs";
13
13
  import { reportMembership } from "./membership.mjs";
14
14
  import { currentDeliveryScope } from "./delivery-diagnostics.mjs";
15
15
  import { contentShape, messageContent } from "./content.mjs";
@@ -5,16 +5,14 @@ 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 { confirmations } from "../confirmations.mjs";
8
+ import { I as confirmations, _t as reportTelegramError, c as currentInboundRequest, i as memberIdOf, o as telegramPrincipal } from "../../../_chunks/principal-D5Tualrk.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";
12
12
  import { chatEvent } from "../chat-archive.mjs";
13
13
  import { chatPostCard, chatPostCardStatus, chatPostReceipt, withChatPostCard } from "./chat-post-card.mjs";
14
14
  import { answerMarker, isPendingQuestion, pendingQuestions, questionKey } from "../questions.mjs";
15
- import { n as currentInboundRequest, p as reportTelegramError } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
16
15
  import { confirmationStatus, renderConfirmation, withConfirmationText } from "./confirmation-text.mjs";
17
- import { i as memberIdOf, o as telegramPrincipal } from "../../../_chunks/principal-Dzs8hUDB.mjs";
18
16
  import { formatAddress, scopedAddress } from "./sessions.mjs";
19
17
  import { createHash } from "node:crypto";
20
18
  import { telegramTextLinks } from "@segmentstream/ontology/telegram";
@@ -5,5 +5,5 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { isTechnicalText } from "../customer-text-safety.mjs";
8
- import { a as TelegramDeliveryError, c as customerCopy, d as failureText, f as formattingRefused, h as withDeliveryLocale, l as customerMessage, m as safeTelegramFetch, o as currentLocale, p as reportTelegramError, s as currentThreadId, u as customerText } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
8
+ import { _t as reportTelegramError, dt as currentThreadId, ft as customerCopy, gt as formattingRefused, ht as failureText, lt as TelegramDeliveryError, mt as customerText, pt as customerMessage, ut as currentLocale, vt as safeTelegramFetch, yt as withDeliveryLocale } from "../../../_chunks/principal-D5Tualrk.mjs";
9
9
  export { TelegramDeliveryError, currentLocale, currentThreadId, customerCopy, customerMessage, customerText, failureText, formattingRefused, isTechnicalText, reportTelegramError, safeTelegramFetch, withDeliveryLocale };
@@ -1,21 +1,19 @@
1
1
  import type { TelegramAttachment, TelegramMessage } from "eve/channels/telegram";
2
- import { type AgentAttachments } from "../attachments.js";
2
+ import type { AgentAttachments } from "../attachments.js";
3
+ import type { ImageDescriber } from "../inbound-media/images.js";
4
+ import type { MediaPlan } from "../inbound-media/plan.js";
3
5
  import type { StagedFile } from "./inbound-request.js";
4
- import { type ImageDescriber } from "./images.js";
5
- import type { MediaPlan } from "./media-policy.js";
6
6
  /**
7
- * Photos and documents a member sends the agent (`docs/agent.md`, "Attachments"). Before the turn
8
- * starts, each file is downloaded through the connection and stored once as a temporary attachment
9
- * of the member, in this chat, for 24 hours. The turn reads the stored copy, and the model learns
10
- * each attachment's id from an `<attachments>` block, so that it can read, discard or promote it
11
- * with the attachment tools. A file that cannot be stored is never passed on silently: the turn
12
- * gets a note saying why.
7
+ * Photos and documents a member sends the agent, and the voice, audio and video files eve's
8
+ * Telegram parser leaves out, described for the inbound media pipeline (`docs/agent.md`,
9
+ * "Attachments"), which stores each once as the member's attachment in this chat. The turn reads
10
+ * the stored copy in place of eve's Telegram file part.
13
11
  */
14
12
  /** The chat an attachment belongs to: `telegram:<chat id>`. */
15
13
  export declare function telegramChat(chatId: string): string;
16
14
  /** Eve normalizes photos/documents only. Keep other Telegram files available to attachment tools. */
17
15
  export declare function inboundAttachments(message: TelegramMessage): ReadonlyArray<TelegramAttachment>;
18
- /** Stores the message's files one after another, so that a large album holds one file at a time. */
16
+ /** Stores the message's files through the inbound media pipeline, keyed by Telegram file id. */
19
17
  export declare function stageFiles(input: {
20
18
  readonly message: TelegramMessage;
21
19
  readonly memberId: string;
@@ -24,8 +22,3 @@ export declare function stageFiles(input: {
24
22
  readonly imagePlan?: MediaPlan;
25
23
  readonly describeImage?: ImageDescriber;
26
24
  }): Promise<ReadonlyMap<string, StagedFile>>;
27
- /** The `<attachments>` block that tells the model which attachments the message carries. */
28
- export declare function attachmentsContext(input: {
29
- readonly files: ReadonlyMap<string, StagedFile>;
30
- readonly group: boolean;
31
- }): ReadonlyArray<string>;