@segmentstream/agent 0.83.1 → 0.86.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 (102) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +31 -16
  3. package/dist/_chunks/{build-metadata-DLgMHYWG.mjs → build-metadata-CKp7rmO0.mjs} +1 -1
  4. package/dist/_chunks/{chat-archive-D4HRgOSo.mjs → chat-archive-By3MnPEC.mjs} +1 -1
  5. package/dist/_chunks/{principal-dEQyjF1n.mjs → principal-C1g8wCIg.mjs} +12 -3
  6. package/dist/_chunks/silent-C9x3GcMg.mjs +262 -0
  7. package/dist/extension/channels/email.mjs +3 -1
  8. package/dist/extension/channels/slack.mjs +3 -1
  9. package/dist/extension/channels/telegram.mjs +3 -1
  10. package/dist/extension/channels/whatsapp.mjs +3 -1
  11. package/dist/extension/connections/ontology.mjs +1 -1
  12. package/dist/extension/hooks/authorization.mjs +1 -1
  13. package/dist/extension/instructions/persona.mjs +1 -1
  14. package/dist/extension/lib/actor.mjs +1 -1
  15. package/dist/extension/lib/agent-task.mjs +2 -1
  16. package/dist/extension/lib/attachment-tools.mjs +1 -1
  17. package/dist/extension/lib/attachments-dispatch.d.ts +23 -0
  18. package/dist/extension/lib/attachments-dispatch.mjs +79 -0
  19. package/dist/extension/lib/attachments-send.mjs +1 -1
  20. package/dist/extension/lib/attachments.mjs +1 -1
  21. package/dist/extension/lib/build-metadata.mjs +1 -1
  22. package/dist/extension/lib/chat-address.mjs +1 -1
  23. package/dist/extension/lib/chat-context.mjs +1 -1
  24. package/dist/extension/lib/chat-recorder.mjs +2 -2
  25. package/dist/extension/lib/chat-store.mjs +3 -1
  26. package/dist/extension/lib/confirmations.mjs +1 -1
  27. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  28. package/dist/extension/lib/email/channel.d.ts +2 -0
  29. package/dist/extension/lib/email/channel.mjs +40 -6
  30. package/dist/extension/lib/environment.d.ts +16 -1
  31. package/dist/extension/lib/environment.mjs +12 -2
  32. package/dist/extension/lib/evals.d.ts +3 -1
  33. package/dist/extension/lib/evals.mjs +3 -1
  34. package/dist/extension/lib/guest-usage.mjs +3 -2
  35. package/dist/extension/lib/identities.mjs +2 -0
  36. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  37. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  38. package/dist/extension/lib/ontology-connection.mjs +1 -1
  39. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  40. package/dist/extension/lib/ontology-recall.mjs +1 -1
  41. package/dist/extension/lib/ontology-tools.mjs +1 -1
  42. package/dist/extension/lib/review/client.mjs +8 -0
  43. package/dist/extension/lib/review/files.d.ts +101 -0
  44. package/dist/extension/lib/review/files.mjs +7 -0
  45. package/dist/extension/lib/review/hold.d.ts +7 -0
  46. package/dist/extension/lib/review/hold.mjs +2 -1
  47. package/dist/extension/lib/review/judge.d.ts +2 -0
  48. package/dist/extension/lib/review/judge.mjs +1 -0
  49. package/dist/extension/lib/review/reply.d.ts +66 -0
  50. package/dist/extension/lib/review/reply.mjs +91 -9
  51. package/dist/extension/lib/review/revision.mjs +2 -0
  52. package/dist/extension/lib/role-skill.mjs +1 -1
  53. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  54. package/dist/extension/lib/sent-files.mjs +3 -1
  55. package/dist/extension/lib/slack/adapter.mjs +1 -1
  56. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  57. package/dist/extension/lib/slack/callbacks.mjs +1 -1
  58. package/dist/extension/lib/stored-files.mjs +1 -1
  59. package/dist/extension/lib/telegram/adapter.mjs +11 -6
  60. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  61. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  62. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  63. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  64. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  65. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  66. package/dist/extension/lib/telegram/files.mjs +1 -1
  67. package/dist/extension/lib/telegram/health.mjs +1 -1
  68. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  69. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  70. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  71. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  72. package/dist/extension/lib/telegram/principal.mjs +1 -1
  73. package/dist/extension/lib/telegram/routing-context.mjs +1 -1
  74. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  75. package/dist/extension/lib/telegram/silent.mjs +1 -84
  76. package/dist/extension/lib/telegram/store-capture.mjs +1 -1
  77. package/dist/extension/lib/telegram/structured.mjs +1 -1
  78. package/dist/extension/lib/telegram/turn-errors.mjs +2 -2
  79. package/dist/extension/lib/web/auth.d.ts +13 -3
  80. package/dist/extension/lib/web/auth.mjs +1 -1
  81. package/dist/extension/lib/web/channel.mjs +1 -1
  82. package/dist/extension/lib/whatsapp/adapter.mjs +2 -2
  83. package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
  84. package/dist/extension/lib/whatsapp/callbacks.mjs +1 -1
  85. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  86. package/dist/extension/lib/workspace-action.mjs +1 -1
  87. package/dist/extension/lib/workspace-channel/attachments-send.d.ts +1 -1
  88. package/dist/extension/lib/workspace-channel/attachments-send.mjs +3 -1
  89. package/dist/extension/lib/workspace-channel/channel.mjs +24 -5
  90. package/dist/extension/lib/workspace-source.mjs +1 -1
  91. package/dist/extension/model.mjs +1 -1
  92. package/dist/extension/tools/attachments_discard.mjs +1 -1
  93. package/dist/extension/tools/attachments_list.mjs +1 -1
  94. package/dist/extension/tools/attachments_promote.mjs +1 -1
  95. package/dist/extension/tools/attachments_read.mjs +1 -1
  96. package/dist/extension/tools/attachments_send.mjs +18 -38
  97. package/dist/extension/tools/attachments_stage.mjs +1 -1
  98. package/dist/extension/tools/attachments_table.mjs +1 -1
  99. package/dist/extension/tools/handoff.mjs +1 -1
  100. package/dist/extension/tools/questions_ask.mjs +1 -1
  101. package/dist/extension/tools/workspace_source.mjs +1 -1
  102. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.86.0
4
+
5
+ `@segmentstream/agent/evals` also offers eve's value assertions (`includes`, `equals`, `matches`,
6
+ `satisfies`, `similarity`) for `t.check`, so an eval imports nothing but this package.
7
+
8
+ ## 0.85.0
9
+
10
+ In a chat whose replies are reviewed, `segmentstream__attachments_send` no longer sends files
11
+ ahead of the reply. It asks the ontology (`POST /api/ontology/agent/drafts/files`) whether the
12
+ person may read each file and the chat's channel can send it, answers `{ attached: true }` or a
13
+ refusal, and the files join the turn's reply: the decision model reads their names with it, a reply
14
+ it passes goes out followed by its files, and a held reply carries them into its `agent_draft`,
15
+ which approval sends together. A call's caption joins the reply's text. Files no reply carries,
16
+ such as a reply of files alone, are held on their own and never sent unreviewed; a failed or
17
+ interrupted turn drops them. With an ontology SDK that holds no files with a draft, the call is
18
+ refused with `unsupported`: upgrade `@segmentstream/ontology` with the agent SDK to send files in
19
+ reviewed chats.
20
+
21
+ Pins @segmentstream/ontology 0.164.0.
22
+
23
+ ## 0.84.0
24
+
25
+ The agent runs in app previews. Where the platform sets `SEGMENTSTREAM_DEPLOYMENT_TARGET=preview`,
26
+ the agent calls the ontology of its own deployment (`VERCEL_URL`) instead of the hosting project's
27
+ production domain, names its deployment in `X-SegmentStream-Ontology-Deployment-Id` on every
28
+ runtime request to the ontology, and runs no channels.
29
+
30
+ `webAuth` is now an eve-channel authenticator (`EveAuthFn`). In an app preview, a test member's eval
31
+ session token, which the ontology answers with `eval: true`, may read `GET /eve/v1/info`, so `eve
32
+ eval --url` runs against the preview as that member with `EVE_EVAL_AUTH_TOKEN`. Every other web
33
+ token, and every token in production, stays a member who cannot read it.
34
+
35
+ Pins @segmentstream/ontology 0.163.0.
36
+
3
37
  ## 0.83.1
4
38
 
5
39
  Pins @segmentstream/ontology 0.162.0.
package/README.md CHANGED
@@ -757,8 +757,20 @@ this formatter does not rewrite approved posts or their confirmation cards. The
757
757
  `eve dev` in `agent/` runs the agent locally. The Telegram channel stays silent outside production.
758
758
  To reach a local ontology service, set `SEGMENTSTREAM_AGENT_ONTOLOGY_URL=http://localhost:3000`.
759
759
  `vercel env pull` writes a `VERCEL_OIDC_TOKEN` for the token. The ontology service admits only
760
- production tokens of the workspace's project, though, so a local run gets the ontology only from a
761
- local ontology service configured to accept that token.
760
+ production tokens of the workspace's project, or in an app preview its hosting project's preview
761
+ tokens, though, so a local run gets the ontology only from a local ontology service configured to
762
+ accept that token.
763
+
764
+ ## App previews
765
+
766
+ An app preview of an SDK that supports it runs the agent from the preview's commit, in the preview's
767
+ hosting project, beside the preview's own ontology. The platform sets
768
+ `SEGMENTSTREAM_DEPLOYMENT_TARGET=preview` and the preview's `SEGMENTSTREAM_ONTOLOGY_DEPLOYMENT_ID`;
769
+ the agent then calls the ontology on its own deployment (`VERCEL_URL`), names the deployment in
770
+ `X-SegmentStream-Ontology-Deployment-Id` on every runtime request, and runs no channels. A test
771
+ member's eval session token, which the ontology answers with `eval: true` there alone, may read
772
+ `GET /eve/v1/info`, so `eve eval --url` runs against the preview as that member; a production agent
773
+ never lets a member read it.
762
774
 
763
775
  Building the package needs Node.js 24, as eve does: `pnpm run build` runs `eve extension build`,
764
776
  which writes the agent-shaped `dist/extension` tree, its declarations and eve's compatibility
@@ -777,20 +789,23 @@ This guard does not intercept Eve's own workflow streams or third-party tools.
777
789
  The platform sets every variable on the workspace's Vercel project. None of them is a model key or
778
790
  a provider token.
779
791
 
780
- | Variable | Used for |
781
- | ------------------------------------- | ------------------------------------------------------------------------------- |
782
- | `VERCEL_PROJECT_PRODUCTION_URL` | The app's origin: `/mcp`, `/api/ontology/agent/*` and the `/agent/connect` link |
783
- | `SEGMENTSTREAM_AGENT_ONTOLOGY_URL` | Overrides that origin in local development |
784
- | `SEGMENTSTREAM_URL` | backend-next, where the connection proxy answers |
785
- | `SEGMENTSTREAM_WORKSPACE_ID` | The workspace in the proxy's path |
786
- | `SEGMENTSTREAM_ORGANIZATION_ID` | The tenant the proxy selects |
787
- | `SEGMENTSTREAM_AGENT_WEBHOOK_SECRET` | The Telegram webhook secret; the only secret |
788
- | `SEGMENTSTREAM_RUNTIME_OIDC_ISSUER` | The team's OIDC issuer, which signs the tokens the health and task routes take |
789
- | `SEGMENTSTREAM_RUNTIME_OIDC_AUDIENCE` | The audience those tokens must name |
790
- | `VERCEL_PROJECT_ID` | The project those tokens must name |
791
- | `VERCEL_ENV` | Channels run only in `production`; `preview` selects the preview model |
792
- | `VERCEL_OIDC_TOKEN` | The runtime token outside a request; Vercel sends it on each request otherwise |
793
- | `AI_GATEWAY_API_KEY` | Optional. AI Gateway uses the OIDC token when it is unset |
792
+ | Variable | Used for |
793
+ | -------------------------------------- | ------------------------------------------------------------------------------- |
794
+ | `VERCEL_PROJECT_PRODUCTION_URL` | The app's origin: `/mcp`, `/api/ontology/agent/*` and the `/agent/connect` link |
795
+ | `SEGMENTSTREAM_AGENT_ONTOLOGY_URL` | Overrides that origin in local development |
796
+ | `SEGMENTSTREAM_URL` | backend-next, where the connection proxy answers |
797
+ | `SEGMENTSTREAM_WORKSPACE_ID` | The workspace in the proxy's path |
798
+ | `SEGMENTSTREAM_ORGANIZATION_ID` | The tenant the proxy selects |
799
+ | `SEGMENTSTREAM_AGENT_WEBHOOK_SECRET` | The Telegram webhook secret; the only secret |
800
+ | `SEGMENTSTREAM_RUNTIME_OIDC_ISSUER` | The team's OIDC issuer, which signs the tokens the health and task routes take |
801
+ | `SEGMENTSTREAM_RUNTIME_OIDC_AUDIENCE` | The audience those tokens must name |
802
+ | `VERCEL_PROJECT_ID` | The project those tokens must name |
803
+ | `VERCEL_ENV` | Channels run only in `production`; `preview` selects the preview model |
804
+ | `SEGMENTSTREAM_DEPLOYMENT_TARGET` | `preview` in an app preview, which runs no channels |
805
+ | `SEGMENTSTREAM_ONTOLOGY_DEPLOYMENT_ID` | In an app preview, the deployment named to its ontology |
806
+ | `VERCEL_URL` | In an app preview, the deployment's own origin, where its ontology answers |
807
+ | `VERCEL_OIDC_TOKEN` | The runtime token outside a request; Vercel sends it on each request otherwise |
808
+ | `AI_GATEWAY_API_KEY` | Optional. AI Gateway uses the OIDC token when it is unset |
794
809
 
795
810
  ## License
796
811
 
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- var version = "0.83.1";
7
+ var version = "0.86.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -10,7 +10,7 @@ import { n as contentText, t as CONTENT_CAPS } from "./content-cDtVnr8Y.mjs";
10
10
  import { C as sendFingerprint, S as reasonCode, _ as boundedMeta, a as chatEvent, b as messageInput, f as sessionFailureEventId, p as storeOf, v as cutText, w as storedFiles, x as metaOf } from "./chat-archive-DavfKJDI.mjs";
11
11
  import { applyChatChange } from "../extension/lib/chat-messages.mjs";
12
12
  import { ChatStoreError } from "../extension/lib/chat-store.mjs";
13
- import { c as currentInboundRequest, ht as currentThreadId, xt as reportTelegramError } from "./principal-dEQyjF1n.mjs";
13
+ import { c as currentInboundRequest, ht as currentThreadId, xt as reportTelegramError } from "./principal-C1g8wCIg.mjs";
14
14
  import { telegramReaction } from "../extension/lib/telegram/reactions.mjs";
15
15
  import { currentConfirmationPrompt } from "../extension/lib/group-routing/messages.mjs";
16
16
  import { messageMetadata } from "../extension/lib/telegram/message-metadata.mjs";
@@ -6,11 +6,11 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { AGENT_TOOLS_ATTRIBUTE, SANDBOX_TOOL, agentToolsAnswer, agentToolsAttribute } from "../extension/lib/agent-tools.mjs";
8
8
  import { redactDiagnostic } from "../extension/lib/diagnostics.mjs";
9
+ import { appOrigin, ontologyDeploymentHeaders, previewDeployment } from "../extension/lib/environment.mjs";
9
10
  import { telegramText, withTelegramTexts } from "../extension/lib/telegram/texts.mjs";
10
11
  import { isTechnicalText, isUnsafeText } from "../extension/lib/customer-text-safety.mjs";
11
12
  import { miniAppLinks, originalLinkPreview, withMiniAppLinks } from "../extension/lib/telegram/app-links.mjs";
12
13
  import { CHANNEL_NAME, admissionLimitsOf } from "../extension/config.mjs";
13
- import { appOrigin } from "../extension/lib/environment.mjs";
14
14
  import { channelAttributes, currentChannel, principalChannel } from "../extension/lib/channel-scope.mjs";
15
15
  import { redactTelegramDiagnostic } from "../extension/lib/telegram/diagnostic-redaction.mjs";
16
16
  import { CONFIRMATION_FACTS, CONFIRMATION_PREVIEW_METHOD, ConfirmationRefused, UnsafeConfirmationTarget, confirmationCard, describeConfirmation, factsConfirmation, object } from "../extension/lib/confirmation-description.mjs";
@@ -531,6 +531,7 @@ function webMemberOf(body) {
531
531
  roles,
532
532
  agentTools,
533
533
  ...typeof answer.name === "string" && answer.name !== "" ? { name: answer.name } : {},
534
+ ...answer.eval === true ? { eval: true } : {},
534
535
  ...limitedOf(answer.limited)
535
536
  };
536
537
  }
@@ -540,6 +541,7 @@ function ontologyIntrospection(options = {}) {
540
541
  method: "POST",
541
542
  headers: {
542
543
  authorization: `Bearer ${await (options.token ?? runtimeToken)()}`,
544
+ ...ontologyDeploymentHeaders(options.environment ?? process.env),
543
545
  "content-type": "application/json"
544
546
  },
545
547
  body: JSON.stringify(body),
@@ -678,7 +680,11 @@ function webAuth(options = {}) {
678
680
  message: "The agent token is invalid or expired."
679
681
  });
680
682
  if (member.limited !== void 0) throw new TurnLimitedError(member.limited.retryAfterSeconds, member.limited.scope);
681
- return withButtonDecision(webPrincipal(member), answersOf(body));
683
+ const principal = withButtonDecision(webPrincipal(member), answersOf(body));
684
+ return member.kind !== "guest" && member.eval === true && previewDeployment(options.environment ?? process.env) !== void 0 ? {
685
+ ...principal,
686
+ allowAgentInfo: true
687
+ } : principal;
682
688
  };
683
689
  }
684
690
  const ACT_AS_HEADER = "X-SegmentStream-Act-As";
@@ -1004,6 +1010,7 @@ function ontologyTools(options = {}) {
1004
1010
  method: "POST",
1005
1011
  headers: {
1006
1012
  authorization: `Bearer ${credential}`,
1013
+ ...ontologyDeploymentHeaders(options.environment ?? process.env),
1007
1014
  ...acting,
1008
1015
  ...chatHeaders(own, options.sessionId),
1009
1016
  "content-type": "application/json",
@@ -1351,7 +1358,8 @@ function ontologyConnection(input) {
1351
1358
  expected: actor,
1352
1359
  secret: input.secret
1353
1360
  }),
1354
- ...chatHeaders(context.session.auth.current, context.session.id)
1361
+ ...chatHeaders(context.session.auth.current, context.session.id),
1362
+ ...ontologyDeploymentHeaders(input.environment ?? process.env)
1355
1363
  });
1356
1364
  const common = {
1357
1365
  url: `${origin}/mcp`,
@@ -1538,6 +1546,7 @@ function agentAttachments(input) {
1538
1546
  method: body === void 0 ? "GET" : "POST",
1539
1547
  headers: {
1540
1548
  authorization: `Bearer ${token}`,
1549
+ ...ontologyDeploymentHeaders(),
1541
1550
  accept: "application/json",
1542
1551
  [ACT_AS_HEADER]: owner.memberId,
1543
1552
  [CHAT_HEADER]: owner.chat,
@@ -0,0 +1,262 @@
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 { confirmationLocale } from "../extension/lib/telegram/confirmation-text.mjs";
8
+ import { Ft as chatAddressOf, _t as customerMessage, i as memberIdOf, mt as currentLocale, pt as TelegramDeliveryError, xt as reportTelegramError, yt as failureText } from "./principal-C1g8wCIg.mjs";
9
+ import { splitTelegramText } from "../extension/lib/telegram/format.mjs";
10
+ import { inTelegramSendQueue } from "../extension/lib/telegram/send-queue.mjs";
11
+ import { redactDiagnostic } from "../extension/lib/diagnostics.mjs";
12
+ import { appOrigin, channelsEnabled } from "../extension/lib/environment.mjs";
13
+ import { runtimeToken } from "../extension/lib/runtime-token.mjs";
14
+ import { randomUUID } from "node:crypto";
15
+ import { calls, reply } from "eve/events";
16
+ const ATTACH_TOOL = /(?:^|__)attachments_send$/u;
17
+ const NONE = {
18
+ files: [],
19
+ captions: []
20
+ };
21
+ function isRecord(value) {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+ function attachedOf(output) {
25
+ if (!isRecord(output) || output.attached !== true || !Array.isArray(output.files)) return;
26
+ return {
27
+ files: output.files.flatMap((file) => isRecord(file) && typeof file.entity === "string" && typeof file.id === "string" && typeof file.property === "string" && typeof file.filename === "string" && typeof file.contentType === "string" && typeof file.size === "number" ? [{
28
+ entity: file.entity,
29
+ id: file.id,
30
+ property: file.property,
31
+ filename: file.filename,
32
+ contentType: file.contentType,
33
+ size: file.size
34
+ }] : []),
35
+ captions: typeof output.caption === "string" && output.caption.trim() !== "" ? [output.caption] : []
36
+ };
37
+ }
38
+ function attachments(view, turnId) {
39
+ return calls(view, { turnId }).filter((call) => ATTACH_TOOL.test(call.name) && call.outcome !== void 0).flatMap((call) => {
40
+ const attached = attachedOf(call.output);
41
+ return attached === void 0 || attached.files.length === 0 ? [] : [{
42
+ ...attached,
43
+ endedAt: call.endedAt ?? ""
44
+ }];
45
+ }).sort((one, other) => one.endedAt < other.endedAt ? -1 : one.endedAt > other.endedAt ? 1 : 0);
46
+ }
47
+ function merged(list) {
48
+ return list.length === 0 ? NONE : {
49
+ files: list.flatMap((item) => item.files),
50
+ captions: list.flatMap((item) => item.captions)
51
+ };
52
+ }
53
+ function replyParts(view, turnId) {
54
+ return reply(view, turnId).filter((part) => part.kind === "text" && part.phase === "reply" && part.interrupted !== true && typeof part.value === "string" && completionKind(part.value) === "reply");
55
+ }
56
+ function turnFiles(view, turnId) {
57
+ return merged(attachments(view, turnId));
58
+ }
59
+ function partFiles(view, turnId, partId) {
60
+ const parts = replyParts(view, turnId);
61
+ const index = parts.findIndex((part) => part.partId === partId);
62
+ if (index < 0) return NONE;
63
+ const start = index > 0 ? parts[index - 1].startedAt ?? "" : "";
64
+ const end = index >= 0 ? parts[index].startedAt ?? "" : "";
65
+ return merged(attachments(view, turnId).filter((attached) => attached.endedAt > start && (end === "" || attached.endedAt <= end)));
66
+ }
67
+ function filesAfterReply(view, turnId) {
68
+ const last = replyParts(view, turnId).at(-1)?.startedAt;
69
+ return merged(attachments(view, turnId).filter((attached) => last === void 0 || attached.endedAt > last));
70
+ }
71
+ const DRAFT_FILES_LIMIT = 10;
72
+ const CAPTION_LIMIT = 1024;
73
+ function fileGroups(files) {
74
+ const groups = [];
75
+ for (let start = 0; start < files.files.length; start += 10) groups.push({
76
+ files: files.files.slice(start, start + 10),
77
+ captions: start === 0 ? files.captions : []
78
+ });
79
+ return groups;
80
+ }
81
+ function withCaptions(text, captions) {
82
+ return [text.trim(), ...captions.map((caption) => caption.trim())].filter((part) => part !== "").join("\n\n");
83
+ }
84
+ var ReplyFilesRefused = class extends Error {
85
+ code;
86
+ status;
87
+ index;
88
+ name = "ReplyFilesRefused";
89
+ constructor(code, status, index) {
90
+ super(`The ontology refused the reply's files: ${code}.`);
91
+ this.code = code;
92
+ this.status = status;
93
+ this.index = index;
94
+ }
95
+ };
96
+ async function checkReplyFiles(input) {
97
+ const chat = chatAddressOf(input.principal);
98
+ const memberId = memberIdOf(input.principal);
99
+ if (chat === void 0 || chat.provider === "web" || memberId === void 0) throw new ReplyFilesRefused("unsupported", 0);
100
+ const token = await input.token();
101
+ let response;
102
+ try {
103
+ response = await (input.fetch ?? fetch)(`${input.origin}/api/ontology/agent/drafts/files`, {
104
+ method: "POST",
105
+ headers: {
106
+ authorization: `Bearer ${token}`,
107
+ accept: "application/json",
108
+ "content-type": "application/json"
109
+ },
110
+ body: JSON.stringify({
111
+ provider: chat.provider,
112
+ ...chat.channel === void 0 ? {} : { channel: chat.channel },
113
+ member_id: memberId,
114
+ files: input.files.map((file) => ({
115
+ entity: file.entity,
116
+ id: file.id,
117
+ ...file.property === void 0 ? {} : { property: file.property }
118
+ }))
119
+ }),
120
+ redirect: "error",
121
+ signal: AbortSignal.timeout(1e4)
122
+ });
123
+ } catch (error) {
124
+ console.error("[segmentstream] the reply's files could not be checked", { error: redactDiagnostic(error, new Set([token])) });
125
+ throw new ReplyFilesRefused("unavailable", 0);
126
+ }
127
+ const body = await response.json().catch(() => void 0);
128
+ if (response.status === 404) throw new ReplyFilesRefused("unsupported", 404);
129
+ if (!response.ok) throw new ReplyFilesRefused(isRecord(body) && typeof body.error === "string" ? body.error : "unavailable", response.status, isRecord(body) && typeof body.index === "number" ? body.index : void 0);
130
+ return (isRecord(body) && Array.isArray(body.files) ? body.files : []).flatMap((file) => isRecord(file) && typeof file.entity === "string" && typeof file.id === "string" && typeof file.property === "string" && typeof file.filename === "string" && typeof file.content_type === "string" && typeof file.size === "number" ? [{
131
+ entity: file.entity,
132
+ id: file.id,
133
+ property: file.property,
134
+ filename: file.filename,
135
+ contentType: file.content_type,
136
+ size: file.size
137
+ }] : []);
138
+ }
139
+ async function attachToReply(input) {
140
+ const environment = input.environment ?? process.env;
141
+ const locale = confirmationLocale(input.principal);
142
+ const refuse = (error, diagnostic, index) => {
143
+ const reference = randomUUID();
144
+ console.error("[segmentstream] attachment refused for a reviewed reply", {
145
+ reference,
146
+ error,
147
+ diagnostic
148
+ });
149
+ return {
150
+ error,
151
+ detail: failureText(reference, "attachment", locale),
152
+ reference,
153
+ ...index === void 0 ? {} : { index }
154
+ };
155
+ };
156
+ if (!channelsEnabled(environment)) return refuse("channels_disabled", "Attachments can be sent only in production.");
157
+ try {
158
+ return {
159
+ attached: true,
160
+ files: await checkReplyFiles({
161
+ origin: appOrigin(environment),
162
+ token: input.token ?? runtimeToken,
163
+ ...input.fetch === void 0 ? {} : { fetch: input.fetch },
164
+ principal: input.principal,
165
+ files: input.files
166
+ }),
167
+ ...input.caption === void 0 || input.caption.trim() === "" ? {} : { caption: input.caption }
168
+ };
169
+ } catch (error) {
170
+ return error instanceof ReplyFilesRefused ? refuse(error.code, error.message, error.index) : refuse("unavailable", error);
171
+ }
172
+ }
173
+ const NO_REPLY_TOOL = "no_reply";
174
+ function isNoReplyCall(name) {
175
+ const parts = name?.split("__") ?? [];
176
+ return parts.length <= 2 && parts.at(-1) === NO_REPLY_TOOL;
177
+ }
178
+ const SILENT_MARKERS = new Set(["[silent]", "no_reply"]);
179
+ function isSilentReply(text) {
180
+ return SILENT_MARKERS.has(text.trim().toLowerCase());
181
+ }
182
+ function completionKind(message, finishReason) {
183
+ if (finishReason === "tool-calls") return "tool_calls";
184
+ if (message === void 0 || message === null || message === "") return "empty";
185
+ if (message.trim() === "") return "whitespace";
186
+ return isSilentReply(message) ? "silent_marker" : "reply";
187
+ }
188
+ const INTERIM_TURNS = 256;
189
+ function interimTexts(limit = 256) {
190
+ const turns = new Map();
191
+ return {
192
+ has: (turn, text) => turns.get(turn)?.has(text) ?? false,
193
+ add(turn, text) {
194
+ const texts = turns.get(turn) ?? new Set();
195
+ turns.delete(turn);
196
+ turns.set(turn, texts.add(text));
197
+ for (const oldest of turns.keys()) {
198
+ if (turns.size <= limit) break;
199
+ turns.delete(oldest);
200
+ }
201
+ }
202
+ };
203
+ }
204
+ function replyDelivery(scope = () => "telegram", interim, review, identifiers = () => "block") {
205
+ return async (event, context) => {
206
+ if (event.data.kind !== "text" || event.data.interrupted) return;
207
+ const channel = context.channel;
208
+ const textValue = typeof event.data.value === "string" ? event.data.value : "";
209
+ const kind = completionKind(textValue, event.data.phase === "reply" ? "stop" : "tool-calls");
210
+ const interimOn = interim?.enabled() === true;
211
+ const isInterim = kind === "tool_calls" && interimOn && completionKind(textValue) === "reply";
212
+ if (kind !== "reply" && !isInterim) return;
213
+ const reviewed = review?.reviewed(context.session?.auth.current) === true;
214
+ if (reviewed && isInterim) return;
215
+ const turn = interimOn && typeof event.scope?.turnId === "string" && event.scope?.turnId !== "" ? JSON.stringify([context.session?.id ?? "", event.scope?.turnId]) : void 0;
216
+ const key = textValue.trim();
217
+ if (turn !== void 0 && interim.delivered.has(turn, key)) return;
218
+ const turnId = event.scope?.turnId ?? null;
219
+ const files = reviewed && !isInterim && turnId !== null && context.view !== void 0 ? partFiles(context.view, turnId, event.data.partId) : void 0;
220
+ if (reviewed && !await review.sendOrHold({
221
+ principal: context.session?.auth.current,
222
+ sessionId: context.session?.id ?? "",
223
+ turnId,
224
+ partId: event.data.partId,
225
+ text: textValue,
226
+ ...files === void 0 || files.files.length === 0 ? {} : { files }
227
+ })) return;
228
+ const message = customerMessage(textValue, confirmationLocale(context.session?.auth.current ?? null, currentLocale()), identifiers());
229
+ const replyTo = (context.session?.auth.current)?.attributes.replyToMessageId;
230
+ const replyParameters = typeof replyTo === "string" && /^[1-9]\d*$/u.test(replyTo) ? { reply_parameters: {
231
+ message_id: Number(replyTo),
232
+ allow_sending_without_reply: true
233
+ } } : {};
234
+ await inTelegramSendQueue(scope(), channel.telegram.chatId, async () => {
235
+ const messageIds = [];
236
+ try {
237
+ for (const part of splitTelegramText(message)) {
238
+ const result = await channel.telegram.post({
239
+ ...part,
240
+ ...replyParameters
241
+ });
242
+ if (!/^[1-9]\d*$/u.test(result.id)) throw new Error("Telegram did not acknowledge the reply with a message id.");
243
+ messageIds.push(Number(result.id));
244
+ }
245
+ } catch (error) {
246
+ const reference = reportTelegramError(isInterim ? "telegram_interim_delivery_failed" : "telegram_reply_delivery_failed", error, { messageIds });
247
+ throw new TelegramDeliveryError(reference, error instanceof TelegramDeliveryError ? error.delivery : "unknown", messageIds);
248
+ }
249
+ return messageIds;
250
+ });
251
+ if (isInterim && turn !== void 0) interim.delivered.add(turn, key);
252
+ if (files !== void 0 && files.files.length > 0) await review.sendFiles({
253
+ principal: context.session?.auth.current,
254
+ sessionId: context.session?.id ?? "",
255
+ turnId,
256
+ partId: event.data.partId,
257
+ files
258
+ });
259
+ };
260
+ }
261
+ const deliverUnlessSilent = replyDelivery();
262
+ export { withCaptions as _, isNoReplyCall as a, CAPTION_LIMIT as c, attachToReply as d, checkReplyFiles as f, turnFiles as g, partFiles as h, interimTexts as i, DRAFT_FILES_LIMIT as l, filesAfterReply as m, completionKind as n, isSilentReply as o, fileGroups as p, deliverUnlessSilent as r, replyDelivery as s, INTERIM_TURNS as t, ReplyFilesRefused as u };
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { channelOf } from "../config.mjs";
8
8
  import segmentstream from "../extension.mjs";
9
+ import { replyFilesSender } from "../lib/attachments-dispatch.mjs";
9
10
  import { segmentstreamEmail } from "../lib/email/channel.mjs";
10
11
  import { decide } from "eve/ai";
11
12
  var email_default = segmentstreamEmail({
@@ -15,7 +16,8 @@ var email_default = segmentstreamEmail({
15
16
  review: {
16
17
  settings: () => segmentstream.config.review,
17
18
  decide: (options) => decide(options),
18
- model: () => segmentstream.config.models.decision
19
+ model: () => segmentstream.config.models.decision,
20
+ sendFiles: replyFilesSender(() => segmentstream.config.channels)
19
21
  }
20
22
  });
21
23
  export { email_default as default };
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { channelOf } from "../config.mjs";
8
8
  import segmentstream from "../extension.mjs";
9
+ import { replyFilesSender } from "../lib/attachments-dispatch.mjs";
9
10
  import { segmentstreamSlack } from "../lib/slack/adapter.mjs";
10
11
  import { decide } from "eve/ai";
11
12
  var slack_default = segmentstreamSlack({
@@ -17,7 +18,8 @@ var slack_default = segmentstreamSlack({
17
18
  review: {
18
19
  settings: () => segmentstream.config.review,
19
20
  decide: (options) => decide(options),
20
- model: () => segmentstream.config.models.decision
21
+ model: () => segmentstream.config.models.decision,
22
+ sendFiles: replyFilesSender(() => segmentstream.config.channels)
21
23
  }
22
24
  });
23
25
  export { slack_default as default };
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { channelOf } from "../config.mjs";
8
8
  import segmentstream from "../extension.mjs";
9
+ import { replyFilesSender } from "../lib/attachments-dispatch.mjs";
9
10
  import { segmentstreamTelegram } from "../lib/telegram/adapter.mjs";
10
11
  import { decide } from "eve/ai";
11
12
  var telegram_default = segmentstreamTelegram({
@@ -19,7 +20,8 @@ var telegram_default = segmentstreamTelegram({
19
20
  decide: (options) => decide(options),
20
21
  review: {
21
22
  settings: () => segmentstream.config.review,
22
- decide: (options) => decide(options)
23
+ decide: (options) => decide(options),
24
+ sendFiles: replyFilesSender(() => segmentstream.config.channels)
23
25
  }
24
26
  });
25
27
  export { telegram_default as default };
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { channelOf } from "../config.mjs";
8
8
  import segmentstream from "../extension.mjs";
9
+ import { replyFilesSender } from "../lib/attachments-dispatch.mjs";
9
10
  import { segmentstreamWhatsApp } from "../lib/whatsapp/adapter.mjs";
10
11
  import { decide } from "eve/ai";
11
12
  var whatsapp_default = segmentstreamWhatsApp({
@@ -16,7 +17,8 @@ var whatsapp_default = segmentstreamWhatsApp({
16
17
  review: {
17
18
  settings: () => segmentstream.config.review,
18
19
  decide: (options) => decide(options),
19
- model: () => segmentstream.config.models.decision
20
+ model: () => segmentstream.config.models.decision,
21
+ sendFiles: replyFilesSender(() => segmentstream.config.channels)
20
22
  }
21
23
  });
22
24
  export { whatsapp_default as default };
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
- import { T as ontologyConnection } from "../../_chunks/principal-dEQyjF1n.mjs";
8
+ import { T as ontologyConnection } from "../../_chunks/principal-C1g8wCIg.mjs";
9
9
  import { defineDynamic } from "eve/connections";
10
10
  var ontology_default = defineDynamic(async (context) => {
11
11
  if (!segmentstream.config.ontology.connection) return null;
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
8
  import { localizedText } from "../lib/admission.mjs";
9
9
  import { confirmationLocale } from "../lib/telegram/confirmation-text.mjs";
10
- import "../../_chunks/principal-dEQyjF1n.mjs";
10
+ import "../../_chunks/principal-C1g8wCIg.mjs";
11
11
  import { defineHook } from "eve/hooks";
12
12
  var authorization_default = defineHook({ events: { "interaction.opened": (event, context) => {
13
13
  const principal = context.session.auth.current;
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
- import { a as rolesOf } from "../../_chunks/principal-dEQyjF1n.mjs";
8
+ import { a as rolesOf } from "../../_chunks/principal-C1g8wCIg.mjs";
9
9
  import { personaFor } from "../personas.mjs";
10
10
  import { defineDynamic, defineInstructions } from "eve/instructions";
11
11
  var persona_default = defineDynamic((context) => {
@@ -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 { R as ACT_AS_HEADER, z as ActorRequiredError, B as actorHeaders, V as actorKey, H as actorOf, U as isGuestSession, W as member, G as memberTool, K as notForGuests } from "../../_chunks/principal-dEQyjF1n.mjs";
7
+ export { R as ACT_AS_HEADER, z as ActorRequiredError, B as actorHeaders, V as actorKey, H as actorOf, U as isGuestSession, W as member, G as memberTool, K as notForGuests } from "../../_chunks/principal-C1g8wCIg.mjs";
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { agentToolsAnswer, agentToolsAttribute } from "./agent-tools.mjs";
8
8
  import { redactDiagnostic } from "./diagnostics.mjs";
9
- import { appOrigin } from "./environment.mjs";
9
+ import { appOrigin, ontologyDeploymentHeaders } from "./environment.mjs";
10
10
  import { runtimeToken } from "./runtime-token.mjs";
11
11
  import { randomUUID } from "node:crypto";
12
12
  import { defineState } from "eve/context";
@@ -111,6 +111,7 @@ function agentTasks(options = {}) {
111
111
  signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
112
112
  headers: {
113
113
  authorization: `Bearer ${credential}`,
114
+ ...ontologyDeploymentHeaders(),
114
115
  accept: "application/json",
115
116
  ...init.secret === void 0 ? {} : { [AGENT_TASK_HEADER]: init.secret },
116
117
  ...init.body === void 0 ? {} : { "content-type": "application/json" }
@@ -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, b as agentAttachments, i as memberIdOf } from "../../_chunks/principal-dEQyjF1n.mjs";
7
+ import { Ft as chatAddressOf, It as chatChannel, b as agentAttachments, i as memberIdOf } from "../../_chunks/principal-C1g8wCIg.mjs";
8
8
  import { detectFile, documentText } from "./attachment-formats.mjs";
9
9
  import { readSheets, typedTable } from "./attachment-tables.mjs";
10
10
  import { appOrigin } from "./environment.mjs";
@@ -0,0 +1,23 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import type { SendReplyFiles } from "./review/reply.js";
3
+ import { type SendAttachmentsInput } from "./telegram/attachments-send.js";
4
+ /**
5
+ * Sends stored files in the turn's chat through the channel the chat is on: its bot, app, number
6
+ * or mailbox, by that channel's own sender. `attachments_send` sends this way outside reviewed
7
+ * chats, and a reviewed chat's reply sends its files this way once the judge passed it.
8
+ */
9
+ export declare function sendStoredFiles(input: {
10
+ readonly channels: Readonly<Record<string, unknown>> | null | undefined;
11
+ readonly files: SendAttachmentsInput;
12
+ readonly principal: SessionAuthContext | null;
13
+ readonly sessionId: string;
14
+ readonly turnId: string | null;
15
+ /** Names the send in an email thread, so one run again finds the reply it sent. */
16
+ readonly callId: string;
17
+ }): Promise<unknown>;
18
+ /**
19
+ * The sender of a reviewed chat's passed reply's files, through the channel the chat is on, with
20
+ * their calls' captions when they fit one caption: a failure is logged, as the reply's text was
21
+ * already sent.
22
+ */
23
+ export declare function replyFilesSender(channels: () => Readonly<Record<string, unknown>> | null | undefined): SendReplyFiles;