@segmentstream/agent 0.47.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 (93) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +14 -15
  3. package/dist/_chunks/{build-metadata-5S6uTvyu.mjs → build-metadata-DrQtDIMX.mjs} +1 -1
  4. package/dist/_chunks/principal-D5Tualrk.mjs +1836 -0
  5. package/dist/extension/channels/slack.mjs +2 -1
  6. package/dist/extension/channels/whatsapp.mjs +1 -0
  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 -46
  11. package/dist/extension/lib/attachment-tools.mjs +1 -3
  12. package/dist/extension/lib/attachments.d.ts +1 -1
  13. package/dist/extension/lib/attachments.mjs +1 -230
  14. package/dist/extension/lib/build-metadata.mjs +1 -1
  15. package/dist/extension/lib/chat-address.mjs +1 -50
  16. package/dist/extension/lib/chat-context.mjs +1 -1
  17. package/dist/extension/lib/chat-recorder.mjs +1 -2
  18. package/dist/extension/lib/confirmations.mjs +1 -179
  19. package/dist/extension/lib/inbound-media/files.d.ts +91 -0
  20. package/dist/extension/lib/inbound-media/files.mjs +7 -0
  21. package/dist/extension/lib/{telegram → inbound-media}/images.d.ts +2 -0
  22. package/dist/extension/lib/{telegram → inbound-media}/images.mjs +1 -2
  23. package/dist/extension/lib/inbound-media/index.d.ts +55 -0
  24. package/dist/extension/lib/inbound-media/index.mjs +7 -0
  25. package/dist/extension/lib/inbound-media/plan.d.ts +59 -0
  26. package/dist/extension/lib/{telegram/media-policy.mjs → inbound-media/plan.mjs} +56 -4
  27. package/dist/extension/lib/inbound-media/report.d.ts +5 -0
  28. package/dist/extension/lib/inbound-media/report.mjs +7 -0
  29. package/dist/extension/lib/inbound-media/speech.d.ts +52 -0
  30. package/dist/extension/lib/inbound-media/speech.mjs +73 -0
  31. package/dist/extension/lib/ontology-connection.mjs +1 -101
  32. package/dist/extension/lib/ontology-file-call.mjs +1 -4
  33. package/dist/extension/lib/ontology-tools.mjs +1 -377
  34. package/dist/extension/lib/review/hold.mjs +1 -2
  35. package/dist/extension/lib/review/reply.mjs +1 -2
  36. package/dist/extension/lib/role-skill.mjs +1 -1
  37. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  38. package/dist/extension/lib/sent-files.mjs +1 -2
  39. package/dist/extension/lib/slack/adapter.d.ts +49 -7
  40. package/dist/extension/lib/slack/adapter.mjs +79 -21
  41. package/dist/extension/lib/slack/attachments-send.mjs +1 -3
  42. package/dist/extension/lib/slack/files.d.ts +12 -19
  43. package/dist/extension/lib/slack/files.mjs +26 -58
  44. package/dist/extension/lib/stored-files.mjs +1 -3
  45. package/dist/extension/lib/telegram/adapter.d.ts +3 -3
  46. package/dist/extension/lib/telegram/adapter.mjs +13 -17
  47. package/dist/extension/lib/telegram/attachment-description.d.ts +1 -1
  48. package/dist/extension/lib/telegram/attachment-description.mjs +2 -2
  49. package/dist/extension/lib/telegram/attachments-send.mjs +1 -3
  50. package/dist/extension/lib/telegram/callbacks.mjs +1 -2
  51. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  52. package/dist/extension/lib/telegram/confirmations.mjs +1 -3
  53. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  54. package/dist/extension/lib/telegram/files.d.ts +8 -15
  55. package/dist/extension/lib/telegram/files.mjs +32 -107
  56. package/dist/extension/lib/telegram/health.mjs +1 -1
  57. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  58. package/dist/extension/lib/telegram/inbound-request.d.ts +6 -12
  59. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  60. package/dist/extension/lib/telegram/inbound.d.ts +3 -3
  61. package/dist/extension/lib/telegram/inbound.mjs +11 -11
  62. package/dist/extension/lib/telegram/lifecycle.mjs +2 -6
  63. package/dist/extension/lib/telegram/principal.mjs +1 -1
  64. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  65. package/dist/extension/lib/telegram/silent.mjs +1 -1
  66. package/dist/extension/lib/telegram/structured.mjs +1 -1
  67. package/dist/extension/lib/telegram/turn-errors.mjs +1 -2
  68. package/dist/extension/lib/telegram/voice.d.ts +7 -38
  69. package/dist/extension/lib/telegram/voice.mjs +1 -64
  70. package/dist/extension/lib/telegram/workspace-action.mjs +1 -3
  71. package/dist/extension/lib/web/auth.d.ts +27 -4
  72. package/dist/extension/lib/web/auth.mjs +1 -124
  73. package/dist/extension/lib/web/channel.d.ts +13 -4
  74. package/dist/extension/lib/web/channel.mjs +15 -8
  75. package/dist/extension/lib/whatsapp/adapter.d.ts +37 -1
  76. package/dist/extension/lib/whatsapp/adapter.mjs +118 -21
  77. package/dist/extension/lib/whatsapp/files.d.ts +40 -0
  78. package/dist/extension/lib/whatsapp/files.mjs +70 -0
  79. package/dist/extension/lib/workspace-source.mjs +1 -3
  80. package/dist/extension/model.mjs +1 -1
  81. package/dist/extension/tools/attachments_discard.mjs +1 -1
  82. package/dist/extension/tools/attachments_list.mjs +1 -1
  83. package/dist/extension/tools/attachments_promote.mjs +1 -5
  84. package/dist/extension/tools/attachments_read.mjs +1 -1
  85. package/dist/extension/tools/attachments_send.mjs +1 -2
  86. package/dist/extension/tools/attachments_stage.mjs +1 -1
  87. package/dist/extension/tools/attachments_table.mjs +1 -1
  88. package/dist/extension/tools/questions_ask.mjs +1 -2
  89. package/dist/extension/tools/workspace_source.mjs +1 -1
  90. package/package.json +2 -2
  91. package/dist/_chunks/inbound-request-B3RhCuOw.mjs +0 -413
  92. package/dist/_chunks/principal-Dzs8hUDB.mjs +0 -128
  93. package/dist/extension/lib/telegram/media-policy.d.ts +0 -15
@@ -0,0 +1,91 @@
1
+ import type { MessageContent } from "eve/channels";
2
+ import { type AgentAttachments, type Attachment, type AttachmentSource } from "../attachments.js";
3
+ import { type ImageDescriber } from "./images.js";
4
+ import type { MediaPlan } from "./plan.js";
5
+ import type { MediaReport } from "./report.js";
6
+ import type { SpeechKind } from "./speech.js";
7
+ /**
8
+ * The files a member sends the agent, in any channel (`docs/agent.md`, "Attachments"). Before the
9
+ * turn starts, each file is downloaded through the channel's connection and stored once as a
10
+ * temporary attachment of the member, in this chat, for 24 hours. The model learns each
11
+ * attachment's id from an `<attachments>` block, so that it can read, discard or promote it with
12
+ * the attachment tools. A file that cannot be stored is never passed on silently: the block names
13
+ * it with the reason.
14
+ */
15
+ /** What a file is, as its channel tells: a spoken kind is transcribed before the turn. */
16
+ export type InboundFileKind = SpeechKind | "image" | "video" | "sticker" | "animation" | "document";
17
+ /** One file of an inbound message, as its channel describes it before downloading it. */
18
+ export interface InboundFile {
19
+ /** The file within its message, such as the provider's file id. */
20
+ readonly key: string;
21
+ readonly kind: InboundFileKind;
22
+ readonly filename: string;
23
+ readonly contentType: string;
24
+ /** Its size in bytes, when the provider says. */
25
+ readonly size?: number;
26
+ /** Its length, when the provider says. */
27
+ readonly seconds?: number;
28
+ /** Its bytes through the channel's connection; fails once they exceed `maxBytes`. */
29
+ download(maxBytes: number, abortSignal?: AbortSignal): Promise<Uint8Array>;
30
+ }
31
+ /** What became of one file of the message: stored as an attachment, or why not. */
32
+ export type StagedFile = {
33
+ readonly status: "stored";
34
+ readonly attachment: Attachment;
35
+ readonly url: URL;
36
+ readonly description?: string;
37
+ readonly imageInput?: "native" | "text";
38
+ /** The image description model's run, and what it answered when it did. */
39
+ readonly described?: {
40
+ readonly model: string;
41
+ readonly content?: string;
42
+ };
43
+ } | {
44
+ readonly status: "refused";
45
+ readonly filename: string;
46
+ readonly reason: string;
47
+ };
48
+ /**
49
+ * Stores the message's files one after another, so that a large album holds one file at a time.
50
+ * With an image plan, each image is marked native or described for the chat model.
51
+ */
52
+ export declare function storeFiles(input: {
53
+ readonly files: ReadonlyArray<InboundFile>;
54
+ readonly memberId: string;
55
+ /** The chat the files arrived in, such as `telegram:<chat id>`. */
56
+ readonly chat: string;
57
+ readonly source: AttachmentSource;
58
+ /** Identifies the message's file at its source, so that a redelivered message stores it once. */
59
+ readonly sourceRef: (index: number) => string;
60
+ readonly attachments: AgentAttachments;
61
+ readonly report: MediaReport;
62
+ readonly imagePlan?: MediaPlan;
63
+ readonly describeImage?: ImageDescriber;
64
+ }): Promise<ReadonlyMap<string, StagedFile>>;
65
+ /** The `<attachments>` block that tells the model which attachments the message carries. */
66
+ export declare function attachmentsContext(input: {
67
+ readonly files: ReadonlyMap<string, StagedFile>;
68
+ readonly group: boolean;
69
+ }): ReadonlyArray<string>;
70
+ type Part = Exclude<MessageContent, string>[number];
71
+ type FilePart = Extract<Part, {
72
+ readonly type: "file";
73
+ }>;
74
+ /**
75
+ * The turn's message with its files' parts as the pipeline left them. An image the chat model does
76
+ * not read natively becomes its description. Spoken files become the text that stands for them,
77
+ * in place of the first of them. `readStored` points each stored file's part at the stored copy,
78
+ * which the channel's `fetchFile` reads, and replaces a file that could not be stored with a note;
79
+ * without it eve downloads the file from the provider as it would without the pipeline.
80
+ */
81
+ export declare function turnContent(message: string | MessageContent, input: {
82
+ readonly files: ReadonlyMap<string, StagedFile>;
83
+ /** The message's file a part carries, by its key. */
84
+ readonly keyOf: (part: FilePart) => string | undefined;
85
+ readonly readStored?: boolean;
86
+ readonly spoken?: {
87
+ readonly keys: ReadonlySet<string>;
88
+ readonly text: string;
89
+ };
90
+ }): string | MessageContent;
91
+ export {};
@@ -0,0 +1,7 @@
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
+ export { f as attachmentsContext, p as storeFiles, m as turnContent } from "../../../_chunks/principal-D5Tualrk.mjs";
@@ -1,3 +1,4 @@
1
+ import type { MediaReport } from "./report.js";
1
2
  /** Storage still accepts up to 20 MiB; description has its own lower cost/transfer bound. */
2
3
  export declare const MAXIMUM_IMAGE_DESCRIPTION_BYTES: number;
3
4
  /** eve's inbound image inlining limit, unchanged from 0.85 through 1.0. */
@@ -16,5 +17,6 @@ export declare function describeReceivedImage(input: {
16
17
  readonly mediaType: string;
17
18
  readonly model: string;
18
19
  readonly describe: ImageDescriber;
20
+ readonly report: MediaReport;
19
21
  readonly retain?: (text: string) => void;
20
22
  }): Promise<string>;
@@ -4,7 +4,6 @@ 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 { p as reportTelegramError } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
8
7
  import { gateway, generateText } from "ai";
9
8
  const MAXIMUM_IMAGE_DESCRIPTION_BYTES = 5242880;
10
9
  const MAXIMUM_NATIVE_IMAGE_BYTES = 3145728;
@@ -42,7 +41,7 @@ async function describeReceivedImage(input) {
42
41
  if (text !== "") input.retain?.(text.slice(0, MAXIMUM_IMAGE_DESCRIPTION_CHARACTERS));
43
42
  return text === "" ? "[image description unavailable: empty result; original remains stored]" : text.length > MAXIMUM_IMAGE_DESCRIPTION_CHARACTERS ? `${text.slice(0, 511)}…` : text;
44
43
  } catch (error) {
45
- return `[image description failed; original remains stored; error reference: ${reportTelegramError("image_description_failed", error)}]`;
44
+ return `[image description failed; original remains stored; error reference: ${input.report("image_description_failed", error)}]`;
46
45
  }
47
46
  }
48
47
  export { MAXIMUM_IMAGE_DESCRIPTIONS, MAXIMUM_IMAGE_DESCRIPTION_BYTES, MAXIMUM_NATIVE_IMAGE_BYTES, describableImage, describeReceivedImage, gatewayImageDescriber };
@@ -0,0 +1,55 @@
1
+ import { type AgentAttachments, type AttachmentSource } from "../attachments.js";
2
+ import { type InboundFile, type StagedFile } from "./files.js";
3
+ import type { ImageDescriber } from "./images.js";
4
+ import type { MediaPlan } from "./plan.js";
5
+ import type { MediaReport } from "./report.js";
6
+ import { type Transcriber } from "./speech.js";
7
+ /**
8
+ * One inbound media pipeline for every channel (`docs/agent.md`, "Attachments"). A channel only
9
+ * describes the files a message carries and how to download each through its connection; the
10
+ * pipeline does the same with them everywhere: spoken files become text with `models.stt`, every
11
+ * file is stored once as the member's 24-hour attachment and named in the `<attachments>` block,
12
+ * and an image the chat model does not read natively becomes a short description.
13
+ *
14
+ * eve hands the model the files themselves; Telegram's turn reads the stored copies instead
15
+ * (`turnContent` with `readStored`). Telegram's group routing decodes its bounded evidence with the
16
+ * same pieces before deciding whether a message starts a turn.
17
+ */
18
+ export { attachmentsContext, storeFiles, turnContent, type InboundFile, type InboundFileKind, type StagedFile, } from "./files.js";
19
+ export type { MediaReport } from "./report.js";
20
+ export type { Transcriber } from "./speech.js";
21
+ /** What the pipeline made of a message's files, for its turn. */
22
+ export interface PreparedMedia {
23
+ /** The message's text: its caption, then the text that stands for each spoken file. */
24
+ readonly text: string;
25
+ /** The spoken files, by key, and the text that stands for them in the turn. */
26
+ readonly spoken: {
27
+ readonly keys: ReadonlySet<string>;
28
+ readonly text: string;
29
+ };
30
+ readonly files: ReadonlyMap<string, StagedFile>;
31
+ /** The `<attachments>` block, then the notes that say which files were spoken. */
32
+ readonly context: ReadonlyArray<string>;
33
+ }
34
+ /** Prepares a message's files for a turn that answers it. */
35
+ export declare function prepareInboundMedia(input: {
36
+ readonly caption: string;
37
+ readonly files: ReadonlyArray<InboundFile>;
38
+ /** Whether everyone in a shared chat reads the turn. */
39
+ readonly group: boolean;
40
+ /** `models.stt`, or `false` when voice is off. */
41
+ readonly sttModel: string | false;
42
+ readonly transcribe: Transcriber;
43
+ readonly report: MediaReport;
44
+ /** How the turn's chat model takes images and audio; without it, images reach it natively. */
45
+ readonly plan?: MediaPlan;
46
+ readonly describeImage?: ImageDescriber;
47
+ /** Where the files are kept; without it, spoken files are only transcribed. */
48
+ readonly store?: {
49
+ readonly attachments: AgentAttachments;
50
+ readonly memberId: string;
51
+ readonly chat: string;
52
+ readonly source: AttachmentSource;
53
+ readonly sourceRef: (index: number) => string;
54
+ };
55
+ }): Promise<PreparedMedia>;
@@ -0,0 +1,7 @@
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
+ export { f as attachmentsContext, d as prepareInboundMedia, p as storeFiles, m as turnContent } from "../../../_chunks/principal-D5Tualrk.mjs";
@@ -0,0 +1,59 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import type { SessionReader } from "eve/sessions";
3
+ import { type ChatModelChoice } from "../../config.js";
4
+ import type { Environment } from "../environment.js";
5
+ import type { MediaReport } from "./report.js";
6
+ /**
7
+ * How a turn's chat model takes the images and audio a member sends, in any channel: images
8
+ * natively when the model reads them, else as a short description from `models.imageDescription`.
9
+ */
10
+ export interface ModelMediaCapabilities {
11
+ readonly known: boolean;
12
+ readonly images: boolean;
13
+ readonly audio: boolean;
14
+ }
15
+ export type CapabilityLookup = (model: string) => Promise<ModelMediaCapabilities>;
16
+ export interface MediaPlan {
17
+ readonly images: "native" | "describe" | "unavailable";
18
+ readonly descriptionModel?: string;
19
+ readonly audio: boolean;
20
+ }
21
+ /** Unknown capabilities never become a claim that the model can see or hear the upload. */
22
+ export declare function planMedia(capabilities: ModelMediaCapabilities, descriptionModel?: string | false | null): MediaPlan;
23
+ /** Public Gateway metadata, never a model-name heuristic or a credential-bearing request. */
24
+ export declare function gatewayMediaCapabilities(fetchImpl?: typeof fetch, report?: MediaReport): CapabilityLookup;
25
+ /** The plan for a turn on `model`, the chat model its session runs on, when known. */
26
+ export declare function chatMediaPlan(input: {
27
+ readonly model: string | undefined;
28
+ readonly capabilities: CapabilityLookup;
29
+ readonly imageDescription: string | false | null | undefined;
30
+ }): Promise<MediaPlan>;
31
+ /**
32
+ * The plan for a turn in a chat: against the model of the chat's session when it has one, since a
33
+ * session keeps the model it started with whoever writes now, else the model the writer would start
34
+ * one with.
35
+ */
36
+ export declare function turnMediaPlan(input: {
37
+ readonly models: {
38
+ readonly chat?: ChatModelChoice | null;
39
+ readonly imageDescription?: string | false | null;
40
+ };
41
+ readonly principal: SessionAuthContext;
42
+ /** The chat's current session; without it, the writer starts the session. */
43
+ readonly session?: () => Promise<SessionReader | undefined>;
44
+ readonly capabilities: CapabilityLookup;
45
+ readonly environment?: Environment;
46
+ readonly report?: MediaReport;
47
+ }): Promise<MediaPlan>;
48
+ /** How many of a session's latest events are read for its model; each of its runs records one. */
49
+ export declare const SESSION_MODEL_TAIL = 400;
50
+ /**
51
+ * The model a session runs on, from the latest run it recorded. A session pins its model when it
52
+ * starts (`model()`), so a later speaker's roles never change it; `undefined` before its first run.
53
+ */
54
+ export declare function sessionModel(events: AsyncIterable<SessionEventLike> | Iterable<SessionEventLike>): Promise<string | undefined>;
55
+ interface SessionEventLike {
56
+ readonly type: string;
57
+ readonly data?: unknown;
58
+ }
59
+ export {};
@@ -5,7 +5,9 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { DEFAULT_IMAGE_DESCRIPTION_MODEL } from "../../config.mjs";
8
- import { p as reportTelegramError } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
8
+ import { chooseModel } from "../../model.mjs";
9
+ import { redactDiagnostic } from "../diagnostics.mjs";
10
+ import { randomUUID } from "node:crypto";
9
11
  function planMedia(capabilities, descriptionModel = null) {
10
12
  if (typeof descriptionModel === "string") return {
11
13
  images: "describe",
@@ -26,7 +28,7 @@ function planMedia(capabilities, descriptionModel = null) {
26
28
  audio: capabilities.audio
27
29
  };
28
30
  }
29
- function gatewayMediaCapabilities(fetchImpl = fetch) {
31
+ function gatewayMediaCapabilities(fetchImpl = fetch, report = reportMediaError) {
30
32
  const cache = new Map();
31
33
  return (model) => {
32
34
  const known = cache.get(model);
@@ -46,7 +48,7 @@ function gatewayMediaCapabilities(fetchImpl = fetch) {
46
48
  audio: modalities.includes("audio")
47
49
  };
48
50
  } catch (error) {
49
- reportTelegramError("media_capability_lookup_failed", error, { model });
51
+ report("media_capability_lookup_failed", error, { model });
50
52
  return {
51
53
  known: false,
52
54
  images: false,
@@ -69,4 +71,54 @@ function gatewayMediaCapabilities(fetchImpl = fetch) {
69
71
  return task;
70
72
  };
71
73
  }
72
- export { gatewayMediaCapabilities, planMedia };
74
+ const UNKNOWN = {
75
+ known: false,
76
+ images: false,
77
+ audio: false
78
+ };
79
+ async function chatMediaPlan(input) {
80
+ return planMedia(input.model === void 0 ? UNKNOWN : await input.capabilities(input.model), input.imageDescription ?? null);
81
+ }
82
+ async function turnMediaPlan(input) {
83
+ const { models } = input;
84
+ let model;
85
+ try {
86
+ const session = await input.session?.();
87
+ model = session === void 0 ? void 0 : await sessionModel(session.stream({
88
+ startIndex: -400,
89
+ follow: false
90
+ }));
91
+ } catch (error) {
92
+ (input.report ?? reportMediaError)("media_session_model_lookup_failed", error);
93
+ }
94
+ model ??= models.chat ? chooseModel({
95
+ choice: models.chat,
96
+ principal: input.principal,
97
+ ...input.environment === void 0 ? {} : { environment: input.environment }
98
+ }) : void 0;
99
+ return chatMediaPlan({
100
+ model,
101
+ capabilities: input.capabilities,
102
+ imageDescription: models.imageDescription
103
+ });
104
+ }
105
+ const SESSION_MODEL_TAIL = 400;
106
+ async function sessionModel(events) {
107
+ let model;
108
+ for await (const event of events) {
109
+ const data = event.data;
110
+ if (event.type === "model.started" && typeof data?.modelId === "string") model = data.modelId;
111
+ }
112
+ return model;
113
+ }
114
+ function reportMediaError(operation, error, metadata = {}) {
115
+ const reference = randomUUID();
116
+ console.error("[segmentstream] media diagnostic", {
117
+ ...metadata,
118
+ operation,
119
+ reference,
120
+ error: redactDiagnostic(error, new Set())
121
+ });
122
+ return reference;
123
+ }
124
+ export { SESSION_MODEL_TAIL, chatMediaPlan, gatewayMediaCapabilities, planMedia, sessionModel, turnMediaPlan };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Records a failure the inbound media pipeline recovers from, for operators, in the channel's own
3
+ * diagnostics. Answers the reference the model may quote and an operator can search for.
4
+ */
5
+ export type MediaReport = (operation: string, error: unknown, metadata?: Readonly<Record<string, unknown>>) => string;
@@ -0,0 +1,7 @@
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
+ export {};
@@ -0,0 +1,52 @@
1
+ import type { MediaReport } from "./report.js";
2
+ /**
3
+ * Voice messages, audio files and video notes, in any channel (`docs/agent.md`, "Attachments").
4
+ * The channel downloads the file through its connection and the configured speech-to-text model
5
+ * (`models.stt`) turns it into text before the session sees it, whatever the chat model accepts.
6
+ */
7
+ /** The files a person speaks in, transcribed before the turn. */
8
+ export type SpeechKind = "voice" | "audio" | "video_note";
9
+ /** What the channel knows about a spoken file before it is downloaded. */
10
+ export interface Speech {
11
+ readonly kind: SpeechKind;
12
+ /** Its length, when the provider says. */
13
+ readonly seconds: number | undefined;
14
+ /** Its size in bytes, when the provider says. */
15
+ readonly size: number | undefined;
16
+ }
17
+ export declare function isSpeech(kind: string): kind is SpeechKind;
18
+ /**
19
+ * Told to the model with a spoken file when the chat model could hear audio: the channel still
20
+ * hands it the transcript.
21
+ */
22
+ export declare const NATIVE_AUDIO_NOTE: string;
23
+ /** The note that tells the model a message was spoken, such as `[voice message, 12 s]`. */
24
+ export declare function speechNote(speech: Speech, detail?: string): string;
25
+ /** Speech to text: the audio bytes in, the transcript out. */
26
+ export type Transcriber = (input: {
27
+ readonly audio: Uint8Array;
28
+ readonly model: string;
29
+ readonly abortSignal?: AbortSignal;
30
+ }) => Promise<string>;
31
+ /**
32
+ * Transcribes through AI Gateway. The Gateway provider authenticates with `AI_GATEWAY_API_KEY`
33
+ * when set and otherwise with the deployment's Vercel OIDC token, so a deployment needs no key.
34
+ */
35
+ export declare const gatewayTranscriber: Transcriber;
36
+ /** What a spoken file becomes: the text of the turn and the note that goes with it. */
37
+ export interface SpeechText {
38
+ readonly text: string;
39
+ readonly note: string;
40
+ readonly processed?: boolean;
41
+ }
42
+ /**
43
+ * Turns a spoken file into text. When it cannot (transcription is off, the file exceeds what the
44
+ * agent downloads, or a call fails), the text says so, so the agent can ask for a typed message.
45
+ */
46
+ export declare function transcribeSpeech(input: {
47
+ readonly speech: Speech;
48
+ readonly model: string | false;
49
+ readonly download: () => Promise<Uint8Array>;
50
+ readonly transcribe: Transcriber;
51
+ readonly report: MediaReport;
52
+ }): Promise<SpeechText>;
@@ -0,0 +1,73 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import "../connection-proxy.mjs";
8
+ import { gateway, transcribe } from "ai";
9
+ const LABELS = {
10
+ voice: "voice message",
11
+ audio: "audio file",
12
+ video_note: "video message"
13
+ };
14
+ function isSpeech(kind) {
15
+ return kind in LABELS;
16
+ }
17
+ const TRANSCRIPTION_TIMEOUT_MS = 6e4;
18
+ const MAXIMUM_TRANSCRIPTION_SECONDS = 600;
19
+ const NATIVE_AUDIO_NOTE = "[The chat model supports audio, but this host cannot deliver native audio. The configured speech-to-text fallback was used if enabled.]";
20
+ function speechNote(speech, detail) {
21
+ const parts = [LABELS[speech.kind]];
22
+ if (speech.seconds !== void 0) parts.push(`${Math.round(speech.seconds)} s`);
23
+ if (detail !== void 0) parts.push(detail);
24
+ return `[${parts.join(", ")}]`;
25
+ }
26
+ const gatewayTranscriber = async ({ audio, model, abortSignal }) => {
27
+ return (await transcribe({
28
+ model: gateway.transcription(model),
29
+ audio,
30
+ abortSignal: abortSignal ?? AbortSignal.timeout(TRANSCRIPTION_TIMEOUT_MS)
31
+ })).text.trim();
32
+ };
33
+ async function transcribeSpeech(input) {
34
+ const { speech, model } = input;
35
+ const note = speechNote(speech);
36
+ if (model === false) return {
37
+ text: speechNote(speech, "voice transcription is off"),
38
+ note
39
+ };
40
+ if (speech.size !== void 0 && speech.size > 20971520) return {
41
+ text: speechNote(speech, "too long to transcribe"),
42
+ note
43
+ };
44
+ if (speech.seconds !== void 0 && speech.seconds > MAXIMUM_TRANSCRIPTION_SECONDS) return {
45
+ text: speechNote(speech, "exceeds the 10 minute transcription limit"),
46
+ note
47
+ };
48
+ try {
49
+ const audio = await input.download();
50
+ if (audio.byteLength > 20971520) return {
51
+ text: speechNote(speech, "too long to transcribe"),
52
+ note
53
+ };
54
+ const transcript = await input.transcribe({
55
+ audio,
56
+ model
57
+ });
58
+ return transcript === "" ? {
59
+ text: speechNote(speech, "no speech recognized"),
60
+ note
61
+ } : {
62
+ text: transcript,
63
+ note,
64
+ processed: true
65
+ };
66
+ } catch (error) {
67
+ return {
68
+ text: speechNote(speech, `could not be transcribed; error reference: ${input.report("voice_transcription_failed", error, { kind: speech.kind })}`),
69
+ note
70
+ };
71
+ }
72
+ }
73
+ export { NATIVE_AUDIO_NOTE, gatewayTranscriber, isSpeech, speechNote, transcribeSpeech };
@@ -4,104 +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
- import { c as compatibleRuntimeEnvelope, u as runtimeEnvelope } from "../../_chunks/principal-Dzs8hUDB.mjs";
8
- import { appOrigin } from "./environment.mjs";
9
- import { actionApproval, confirmations } from "./confirmations.mjs";
10
- import { CHAT_POST_ENVELOPE, CHAT_POST_TOOL, chatPostDigest, chatPostOperationId, isChatPost } from "./chat-post-confirmation.mjs";
11
- import { ontologyTools } from "./ontology-tools.mjs";
12
- import { runtimeToken, tokenExpiry } from "./runtime-token.mjs";
13
- import { ACT_AS_HEADER, ActorRequiredError, actorHeaders, actorKey, actorOf } from "./actor.mjs";
14
- import { WEB_AUTHENTICATOR } from "./web/auth.mjs";
15
- import { defineMcpClientConnection } from "eve/connections";
16
- const DESCRIPTION = "The company's ontology: its records, their history, and the actions that change them, narrowed to what the user you act for may read and do. Each <entity>_find says what its fields mean, its related records and its metrics; list_metrics lists every metric, and query_metrics counts and sums them. An ontology that ranks entities by meaning lists segmentstream__ontology__discover: call it with the member's request and what you understand they want, then the tools it names. Call me for that user.";
17
- function actAsHeaders(input) {
18
- const actor = actorOf(input.principal);
19
- if (actor === void 0) throw new ActorRequiredError("The ontology is reachable only for a member paired with this agent or a live task.");
20
- if (actorKey(actor) !== actorKey(input.expected)) throw new ActorRequiredError("The ontology connection was opened for another member or task.");
21
- return actorHeaders({
22
- actor,
23
- principal: input.principal,
24
- secret: input.secret
25
- });
26
- }
27
- function ontologyConnection(input) {
28
- const actor = actorOf(input.principal);
29
- if (actor === void 0) return null;
30
- const origin = appOrigin(input.environment ?? process.env);
31
- const token = input.token ?? runtimeToken;
32
- const headers = (context) => actAsHeaders({
33
- principal: context.session.auth.current,
34
- expected: actor,
35
- secret: input.secret
36
- });
37
- const common = {
38
- url: `${origin}/mcp`,
39
- protocolVersionDiscovery: false,
40
- description: DESCRIPTION,
41
- approval: actionApproval({
42
- ...ontologyTools(input),
43
- texts: input.texts
44
- }),
45
- auth: {
46
- principalType: "app",
47
- getToken: async () => {
48
- const value = await token();
49
- const expiresAt = tokenExpiry(value);
50
- return expiresAt === void 0 ? { token: value } : {
51
- token: value,
52
- expiresAt
53
- };
54
- }
55
- },
56
- headers
57
- };
58
- if (actor.kind === "task") return defineMcpClientConnection({
59
- ...common,
60
- instanceKey: `${origin}/mcp#task:${actor.taskId}`,
61
- tools: { block: [CHAT_POST_TOOL] }
62
- });
63
- const memberId = actor.memberId;
64
- const web = input.principal?.authenticator === WEB_AUTHENTICATOR;
65
- const chatPosting = input.chatPosting === true && !web;
66
- const chatProtocol = chatPosting ? ":chat-post-v1" : "";
67
- const sourceProtocol = input.runtimeSource ? ":runtime-source-v1" : "";
68
- return defineMcpClientConnection({
69
- ...common,
70
- instanceKey: `${origin}/mcp#member:${memberId}${web ? ":web" : ""}${chatProtocol}${sourceProtocol}`,
71
- ...web ? { tools: { block: [CHAT_POST_TOOL] } } : {},
72
- ...chatPosting || input.runtimeSource ? { toolCall: { providedArguments: { [CHAT_POST_ENVELOPE]: (ctx) => {
73
- headers(ctx);
74
- const base = compatibleRuntimeEnvelope(runtimeEnvelope({
75
- principal: ctx.session.auth.current,
76
- sessionId: ctx.session.id,
77
- callId: ctx.callId
78
- }), input.runtimeSource === true);
79
- if (!isChatPost(ctx.toolName)) return base;
80
- const saved = confirmations.get()[ctx.callId];
81
- const preview = saved?.description?.chatPost;
82
- if (saved?.status !== "consumed" || saved.memberId !== memberId || saved.action.split("__").at(-1) !== ctx.toolName || saved.expiresAt <= Date.now() || preview === void 0 || saved.source === void 0) throw new Error("Exact chat posting requires the original unexpired confirmed call.");
83
- const source = saved.source;
84
- return {
85
- ...base,
86
- operation_id: chatPostOperationId(ctx.session.id, ctx.callId),
87
- source: source.provider === "telegram" ? {
88
- provider: "telegram",
89
- chat_id: source.chatId,
90
- thread_id: source.threadId,
91
- ...base.source
92
- } : {
93
- provider: source.provider,
94
- chat_id: source.chatId,
95
- thread_id: source.threadId,
96
- kind: source.kind,
97
- ...source.peer === void 0 ? {} : { peer: source.peer }
98
- },
99
- expected: {
100
- chat_id: preview.chatId,
101
- digest: chatPostDigest(preview)
102
- }
103
- };
104
- } } } } : {}
105
- });
106
- }
107
- export { ACT_AS_HEADER, actAsHeaders, ontologyConnection };
7
+ export { z as ACT_AS_HEADER, T as actAsHeaders, E as ontologyConnection } from "../../_chunks/principal-D5Tualrk.mjs";
@@ -4,13 +4,10 @@ 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 { actionApproval, confirmations, inputHash } from "./confirmations.mjs";
7
+ import { Ct as runtimeEnvelope, F as actionApproval, H as actorKey, I as confirmations, L as inputHash, M as ontologyTools, U as actorOf } from "../../_chunks/principal-D5Tualrk.mjs";
8
8
  import { isChatPost } from "./chat-post-confirmation.mjs";
9
- import { ontologyTools } from "./ontology-tools.mjs";
10
- import { u as runtimeEnvelope } from "../../_chunks/principal-Dzs8hUDB.mjs";
11
9
  import { sandboxFile } from "./sandbox-session.mjs";
12
10
  import { saveOntologyResult } from "./ontology-result-file.mjs";
13
- import { actorKey, actorOf } from "./actor.mjs";
14
11
  import { defineState } from "eve/context";
15
12
  import { defineTool } from "eve/tools";
16
13
  const snapshots = defineState("segmentstream.ontologyFiles", () => ({}));