@segmentstream/agent 0.103.1 → 0.105.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 (50) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +13 -2
  3. package/dist/_chunks/{build-metadata-ByWwCQd1.mjs → build-metadata-DhAF_QGj.mjs} +1 -1
  4. package/dist/_chunks/{silent-CWcAjHwt.mjs → silent-DwObe1UV.mjs} +18 -3
  5. package/dist/extension/lib/adapter-view.d.ts +15 -0
  6. package/dist/extension/lib/adapter-view.mjs +32 -0
  7. package/dist/extension/lib/attachments-dispatch.d.ts +8 -0
  8. package/dist/extension/lib/attachments-dispatch.mjs +17 -10
  9. package/dist/extension/lib/build-metadata.mjs +1 -1
  10. package/dist/extension/lib/chat-recorder.d.ts +2 -0
  11. package/dist/extension/lib/chat-recorder.mjs +65 -20
  12. package/dist/extension/lib/connection-proxy.d.ts +6 -0
  13. package/dist/extension/lib/connection-proxy.mjs +32 -1
  14. package/dist/extension/lib/deliver-route.d.ts +27 -0
  15. package/dist/extension/lib/deliver-route.mjs +35 -0
  16. package/dist/extension/lib/email/attachments-send.d.ts +2 -0
  17. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  18. package/dist/extension/lib/email/channel.mjs +34 -47
  19. package/dist/extension/lib/reply-part.d.ts +11 -0
  20. package/dist/extension/lib/reply-part.mjs +17 -0
  21. package/dist/extension/lib/reply.d.ts +115 -0
  22. package/dist/extension/lib/reply.mjs +107 -0
  23. package/dist/extension/lib/review/files.d.ts +3 -2
  24. package/dist/extension/lib/review/files.mjs +1 -1
  25. package/dist/extension/lib/review/hold.d.ts +7 -0
  26. package/dist/extension/lib/review/hold.mjs +3 -3
  27. package/dist/extension/lib/review/reply.d.ts +24 -0
  28. package/dist/extension/lib/review/reply.mjs +18 -6
  29. package/dist/extension/lib/review/revision.mjs +3 -1
  30. package/dist/extension/lib/sent-files.d.ts +9 -0
  31. package/dist/extension/lib/sent-files.mjs +15 -1
  32. package/dist/extension/lib/slack/adapter.mjs +2 -1
  33. package/dist/extension/lib/telegram/adapter.d.ts +3 -1
  34. package/dist/extension/lib/telegram/adapter.mjs +64 -50
  35. package/dist/extension/lib/telegram/deliver.d.ts +77 -0
  36. package/dist/extension/lib/telegram/deliver.mjs +334 -0
  37. package/dist/extension/lib/telegram/health.mjs +1 -1
  38. package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
  39. package/dist/extension/lib/telegram/routing-context.mjs +1 -1
  40. package/dist/extension/lib/telegram/silent.d.ts +3 -1
  41. package/dist/extension/lib/telegram/silent.mjs +1 -1
  42. package/dist/extension/lib/whatsapp/adapter.mjs +2 -1
  43. package/dist/extension/lib/workspace-channel/channel.d.ts +4 -1
  44. package/dist/extension/lib/workspace-channel/channel.mjs +14 -5
  45. package/dist/extension/tools/attachments_send.mjs +1 -1
  46. package/dist/extension/tools/reply.d.ts +19 -0
  47. package/dist/extension/tools/reply.mjs +180 -0
  48. package/dist/tools/index.d.ts +1 -0
  49. package/dist/tools/index.mjs +2 -1
  50. package/package.json +4 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,72 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.105.0
4
+
5
+ The Telegram channel delivers the messages the ontology sends, a post in either voice, a draft a
6
+ member approves and a reply its review lets go, at
7
+ `POST /eve/segmentstream/v1/telegram/<name>/deliver`, for the deployment's own functions only. It
8
+ sends what the ontology rendered through its bot, as the ontology's own sender did, and never
9
+ rewrites it:
10
+
11
+ - each text message in order, in the chat's send queue, which its own replies share, in the chat's
12
+ forum topic and as a reply to the message it answers, the buttons under the last; a text Telegram
13
+ refuses the formatting of goes once more as plain text;
14
+ - the files after the text, or under it as their caption when the text fits one and the files go
15
+ as one message; nothing follows a text that did not certainly reach the person;
16
+ - each file read by its short-lived link before the queue is taken, and refused, sending nothing,
17
+ when its size is not the one the ontology checked; a file too large for an album goes by its link,
18
+ which the connection proxy reads from storage.
19
+
20
+ Telegram's flood control, which sent nothing, is waited out, up to three attempts; nothing else is
21
+ sent twice, and no adapter retries a send. Telegram's refusal, or the connection's before the call
22
+ reached Telegram, answers that nothing was sent (`recipient_unreachable` for a person who blocked
23
+ the bot, `thread_unavailable` for a topic Telegram no longer has); anything else is uncertain, with
24
+ each file's result. The original errors, Telegram's explanation included, go to the deployment's
25
+ logs with credentials redacted, under the reference the answer names. A channel on another
26
+ connection than the one the ontology's `chat` names for it answers `channel_unknown`, and the
27
+ ontology sends the message itself.
28
+
29
+ An ontology SDK from before the route never calls it and sends its Telegram messages itself, so
30
+ this release works with the ontology SDK's previous release, and the ontology SDK's next release
31
+ works with this agent SDK's previous one, which answers it 404.
32
+
33
+ Pins @segmentstream/ontology 0.184.0.
34
+
35
+ ## 0.104.0
36
+
37
+ The starter's `agent/agent/instructions.md` tells the agent, in the workspace's words, to answer in
38
+ channel chats with `segmentstream__reply`: once, with the whole message and nothing outside it,
39
+ files in `files`, `to` and `cc` only to change whom of a mail thread's people it goes to, and a
40
+ `note` for the team; `segmentstream__no_reply` when a message needs no answer; plain text in the
41
+ app's own chat. A workspace's instructions are its own: copy the paragraph into yours and change
42
+ its words as you like.
43
+
44
+ The agent replies in channel chats with a call: `segmentstream__reply({ text, files?, to?, cc?,
45
+ replyTo?, note? })`, offered in every chat on an email, Telegram, WhatsApp, Slack or workspace
46
+ channel, a guest's included, and never in the web chat, a workflow's task or a redraft. The call is
47
+ the turn's reply and ends the turn without another model call. When the turn ends, the chat's
48
+ channel sends it, holds it for review or, on email and workspace channels with `review`, proposes it
49
+ to the ontology, as it did a turn's final text; Telegram, WhatsApp and Slack post it as they post a
50
+ reply part. `files` go with the reply in a reviewed chat and are sent ahead of it in any other, as
51
+ `attachments_send` sends them. `to` and `cc` choose, for a reply to mail, whom of the thread's people
52
+ it goes to and copies, and refuse anyone else. `replyTo` names the message a Telegram or workspace
53
+ channel reply answers. `note` is kept for staff as an `internal` message of the turn in the chat
54
+ store, never sent; the agent's logs show it as a call of `segmentstream__reply`, and the chat figures
55
+ do not count it as an unanswered question.
56
+
57
+ A turn's final text without the call still reaches the person, as a deprecated fallback: in a
58
+ reviewed chat it is held as a draft without the decision model reading it, and in any other chat it
59
+ is sent as before. The messages it answered carry the reason code `final_text` on their disposition.
60
+ A turn that writes both sends the call's reply and drops the text. The web chat is unchanged.
61
+
62
+ On WhatsApp and Slack, a reviewed reply now reads the files the turn attached from the session as
63
+ eve hands it to the channel; before, such a reply was neither sent nor held.
64
+
65
+ Action required: tell your agent to reply with `segmentstream__reply` in channel chats, as the
66
+ starter's `agent/agent/instructions.md` now does. Until then a reviewed chat holds every reply the
67
+ decision model would have judged, and a turn's final text in a channel chat is deprecated: it
68
+ reaches the person until 2027-05-28, and is removed once such replies are near zero.
69
+
3
70
  ## 0.103.1
4
71
 
5
72
  Pins @segmentstream/ontology 0.183.0.
package/README.md CHANGED
@@ -299,6 +299,7 @@ continue using GET lookup. Starter templates and pins remain unchanged in this s
299
299
  | `segmentstream__email` | `channels` | `POST /eve/segmentstream/v1/email`: the `GmailConnection` mailbox in `channels.email`, which SegmentStream wakes; a Gmail thread is a chat per person, or one chat (`chats`). |
300
300
  | `segmentstream__attachments_list`, `_read`, `_promote`, `_discard` | `tools` | The member's temporary attachments in this chat: list, read, keep through an action, drop. |
301
301
  | `segmentstream__attachments_send` | `tools` | Sends readable stored ontology files into the current Telegram, Slack, WhatsApp or email chat. |
302
+ | `segmentstream__reply` | `tools` | In a channel chat, never the web chat: the turn's reply, with its files, `to`/`cc`, `replyTo` and a `note` for staff; ends the turn, and the channel sends, holds or proposes it. |
302
303
  | `segmentstream__no_reply` | `tools` | Eve's `no_reply`: ends the turn without a message and keeps the model's reason in the session and the archive. |
303
304
  | `segmentstream__bash`, `_read_file`, `_write_file` | `tools` | With `"sandbox": true`, for `agent_tool:sandbox`: eve's file tools, only in the sandbox `@segmentstream/agent/sandbox` opened. |
304
305
  | `segmentstream__attachments_stage` | `tools` | With `"sandbox": true`, for `agent_tool:sandbox`: copies a chat attachment or a stored record's file, read as the member, into the sandbox. |
@@ -599,8 +600,18 @@ The SDK adds no text to the prompt.
599
600
  the preview and show a Telegram link when available; archive failure is distinct from send failure.
600
601
  Agent SDK 0.6.0 prepares this flow; delivery becomes available when the ontology advertises the
601
602
  protocol below. The old instruction receiver `/eve/v1/telegram/messages` is removed. Telegram
602
- routes now serve only the inbound webhook and authenticated health; old instruction relay calls
603
- fail instead of starting an agent turn.
603
+ routes now serve only the inbound webhook, authenticated health and the deliver route; old
604
+ instruction relay calls fail instead of starting an agent turn.
605
+ - **Messages the ontology sends.** The ontology renders each Telegram message it sends, a post, an
606
+ approved draft or a reply its review lets go, and hands it to the channel of the chat's name at
607
+ `POST /eve/segmentstream/v1/telegram/<name>/deliver`, for the deployment's own functions only.
608
+ The channel sends it through its bot in the chat's send queue, as the ontology's own sender did,
609
+ and answers what reached the person. See `docs/agent.md`, "Telegram messages the ontology sends".
610
+ - **Replies.** The model answers with `segmentstream__reply`, which ends the turn; at its end the
611
+ channel posts the call's text as it posts a reply part, quoting the message its `replyTo` names.
612
+ <!-- @legacy agent.final-text-replies -->
613
+ Final text of a turn without the call is still sent, or held unjudged in a reviewed chat, and
614
+ dropped when the turn has one. See `docs/agent.md`, "Replying in channel chats".
604
615
  - **Silence.** When the model calls `segmentstream__no_reply` (eve's `no_reply`), the turn ends
605
616
  without a message; the call and its reason are recorded in the session and the chat
606
617
  archive like any tool call. Empty and whitespace-only final text also send nothing. The turn
@@ -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.103.1";
7
+ var version = "0.105.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -8,12 +8,17 @@ import { confirmationLocale } from "../extension/lib/telegram/confirmation-text.
8
8
  import { It as chatAddressOf, St as reportTelegramError, bt as failureText, ht as currentLocale, i as memberIdOf, mt as TelegramDeliveryError, vt as customerMessage } from "./principal-DIQHp6AG.mjs";
9
9
  import { splitTelegramText } from "../extension/lib/telegram/format.mjs";
10
10
  import { inTelegramSendQueue } from "../extension/lib/telegram/send-queue.mjs";
11
+ import { supersededByToolReply, toolReplyOf } from "../extension/lib/reply.mjs";
11
12
  import { redactDiagnostic } from "../extension/lib/diagnostics.mjs";
12
13
  import { appOrigin, channelsEnabled } from "../extension/lib/environment.mjs";
14
+ import { isToolReplyPart } from "../extension/lib/reply-part.mjs";
13
15
  import { runtimeToken } from "../extension/lib/runtime-token.mjs";
14
16
  import { randomUUID } from "node:crypto";
15
17
  import { calls, reply } from "eve/events";
16
18
  const ATTACH_TOOL = /(?:^|__)attachments_send$/u;
19
+ function attaches(name) {
20
+ return name === "segmentstream__reply" || ATTACH_TOOL.test(name);
21
+ }
17
22
  const NONE = {
18
23
  files: [],
19
24
  captions: []
@@ -36,7 +41,7 @@ function attachedOf(output) {
36
41
  };
37
42
  }
38
43
  function attachments(view, turnId) {
39
- return calls(view, { turnId }).filter((call) => ATTACH_TOOL.test(call.name) && call.outcome !== void 0).flatMap((call) => {
44
+ return calls(view, { turnId }).filter((call) => attaches(call.name) && call.outcome !== void 0).flatMap((call) => {
40
45
  const attached = attachedOf(call.output);
41
46
  return attached === void 0 || attached.files.length === 0 ? [] : [{
42
47
  ...attached,
@@ -57,6 +62,7 @@ function turnFiles(view, turnId) {
57
62
  return merged(attachments(view, turnId));
58
63
  }
59
64
  function partFiles(view, turnId, partId) {
65
+ if (isToolReplyPart(partId)) return turnFiles(view, turnId);
60
66
  const parts = replyParts(view, turnId);
61
67
  const index = parts.findIndex((part) => part.partId === partId);
62
68
  if (index < 0) return NONE;
@@ -65,6 +71,7 @@ function partFiles(view, turnId, partId) {
65
71
  return merged(attachments(view, turnId).filter((attached) => attached.endedAt > start && (end === "" || attached.endedAt <= end)));
66
72
  }
67
73
  function filesAfterReply(view, turnId) {
74
+ if (toolReplyOf(view, turnId) !== void 0) return NONE;
68
75
  const last = replyParts(view, turnId).at(-1)?.startedAt;
69
76
  return merged(attachments(view, turnId).filter((attached) => last === void 0 || attached.endedAt > last));
70
77
  }
@@ -204,6 +211,10 @@ function interimTexts(limit = 256) {
204
211
  function replyDelivery(scope = () => "telegram", interim, review, identifiers = () => "block") {
205
212
  return async (event, context) => {
206
213
  if (event.data.kind !== "text" || event.data.interrupted) return;
214
+ if (supersededByToolReply(event, {
215
+ session: context.session ?? {},
216
+ view: context.view
217
+ })) return;
207
218
  const channel = context.channel;
208
219
  const textValue = typeof event.data.value === "string" ? event.data.value : "";
209
220
  const kind = completionKind(textValue, event.data.phase === "reply" ? "stop" : "tool-calls");
@@ -216,6 +227,7 @@ function replyDelivery(scope = () => "telegram", interim, review, identifiers =
216
227
  const key = textValue.trim();
217
228
  if (turn !== void 0 && interim.delivered.has(turn, key)) return;
218
229
  const turnId = event.scope?.turnId ?? null;
230
+ const named = isToolReplyPart(event.data.partId) ? toolReplyOf(context.view, turnId)?.replyTo : void 0;
219
231
  const files = reviewed && !isInterim && turnId !== null && context.view !== void 0 ? partFiles(context.view, turnId, event.data.partId) : void 0;
220
232
  if (reviewed && !await review.sendOrHold({
221
233
  principal: context.session?.auth.current,
@@ -223,10 +235,13 @@ function replyDelivery(scope = () => "telegram", interim, review, identifiers =
223
235
  turnId,
224
236
  partId: event.data.partId,
225
237
  text: textValue,
226
- ...files === void 0 || files.files.length === 0 ? {} : { files }
238
+ ...files === void 0 || files.files.length === 0 ? {} : { files },
239
+ ...named === void 0 ? {} : { replyTo: named },
240
+ ...isToolReplyPart(event.data.partId) ? {} : { fallback: true }
227
241
  })) return;
228
242
  const message = customerMessage(textValue, confirmationLocale(context.session?.auth.current ?? null, currentLocale()), identifiers());
229
- const replyTo = (context.session?.auth.current)?.attributes.replyToMessageId;
243
+ const principal = context.session?.auth.current;
244
+ const replyTo = named ?? principal?.attributes.replyToMessageId;
230
245
  const replyParameters = typeof replyTo === "string" && /^[1-9]\d*$/u.test(replyTo) ? { reply_parameters: {
231
246
  message_id: Number(replyTo),
232
247
  allow_sending_without_reply: true
@@ -0,0 +1,15 @@
1
+ import { type SessionView } from "eve/events";
2
+ /**
3
+ * The session's view at a channel adapter's seam, as eve's selectors (`calls`, `reply`, …) read
4
+ * it. eve hands the handlers on a channel's `adapter`, which the SDK wraps for review and for a
5
+ * turn's `reply` on WhatsApp and Slack, its own internal tables, and only the handlers of a channel
6
+ * defined with `defineChannel` the `SessionView` its selectors take: eve offers no public way from
7
+ * one to the other. So the view is read the way eve gives it to a channel's handler, through a
8
+ * channel of one handler for the event. A view that already is a `SessionView`, as tests and
9
+ * channels defined with `defineChannel` pass, is returned as it is; none, undefined.
10
+ */
11
+ export declare function adapterView(event: {
12
+ readonly type?: string;
13
+ }, context: {
14
+ readonly view?: unknown;
15
+ }): Promise<SessionView | undefined>;
@@ -0,0 +1,32 @@
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 { position } from "eve/events";
8
+ import { defineChannel } from "eve/channels";
9
+ async function adapterView(event, context) {
10
+ const view = context.view;
11
+ if (view === void 0 || view === null) return;
12
+ if (isSessionView(view)) return view;
13
+ const type = event.type;
14
+ if (type === void 0) return;
15
+ let seen;
16
+ await defineChannel({
17
+ routes: [],
18
+ events: { [type]: (_event, ctx) => {
19
+ seen = ctx.view;
20
+ } }
21
+ }).adapter[type]?.(event, context);
22
+ return seen;
23
+ }
24
+ function isSessionView(value) {
25
+ try {
26
+ position(value);
27
+ return true;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+ export { adapterView };
@@ -14,6 +14,14 @@ export declare function sendStoredFiles(input: {
14
14
  readonly turnId: string | null;
15
15
  /** Names the send in an email thread, so one run again finds the reply it sent. */
16
16
  readonly callId: string;
17
+ /**
18
+ * In an email thread, whom the files go to and copy, when a turn's `reply` named them: the files
19
+ * reach the people its text does. Absent, the person and the channel's copies.
20
+ */
21
+ readonly email?: {
22
+ readonly to?: ReadonlyArray<string>;
23
+ readonly cc?: ReadonlyArray<string>;
24
+ };
17
25
  }): Promise<unknown>;
18
26
  /**
19
27
  * The sender of a reviewed chat's passed reply's files, through the channel the chat is on, with
@@ -6,13 +6,14 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { channelOf } from "../config.mjs";
8
8
  import { It as chatAddressOf, Lt as chatChannel } from "../../_chunks/principal-DIQHp6AG.mjs";
9
- import "../../_chunks/silent-CWcAjHwt.mjs";
9
+ import "../../_chunks/silent-DwObe1UV.mjs";
10
10
  import { sendEmailAttachments } from "./email/attachments-send.mjs";
11
11
  import { replyCopies } from "./email/channel.mjs";
12
12
  import { sendSlackAttachments } from "./slack/attachments-send.mjs";
13
13
  import { sendAttachments } from "./telegram/attachments-send.mjs";
14
14
  import { sendWhatsAppAttachments } from "./whatsapp/attachments-send.mjs";
15
15
  import { sendChannelAttachments } from "./workspace-channel/attachments-send.mjs";
16
+ import { EMAIL_RECIPIENTS_LIMIT } from "@segmentstream/ontology/email";
16
17
  async function sendStoredFiles(input) {
17
18
  const { channels, principal } = input;
18
19
  const chat = chatAddressOf(principal);
@@ -27,14 +28,19 @@ async function sendStoredFiles(input) {
27
28
  ...options,
28
29
  connection: channelOf(channels, "slack", name)?.connection
29
30
  });
30
- if (provider === "email") return sendEmailAttachments({
31
- ...options,
32
- callId: input.callId,
33
- connection: channelOf(channels, "email", name)?.connection,
34
- cc: replyCopies(principal, channelOf(channels, "email", name)),
35
- signature: channelOf(channels, "email", name)?.signature === true,
36
- quote: channelOf(channels, "email", name)?.quote
37
- });
31
+ if (provider === "email") {
32
+ const settings = channelOf(channels, "email", name);
33
+ const to = input.email?.to;
34
+ return sendEmailAttachments({
35
+ ...options,
36
+ callId: input.callId,
37
+ connection: settings?.connection,
38
+ ...to === void 0 ? {} : { to },
39
+ cc: (input.email?.cc ?? replyCopies(principal, settings)).filter((address) => !to?.includes(address)).slice(0, Math.max(EMAIL_RECIPIENTS_LIMIT - (to?.length ?? 1), 0)),
40
+ signature: settings?.signature === true,
41
+ quote: settings?.quote
42
+ });
43
+ }
38
44
  if (provider === "whatsapp") return sendWhatsAppAttachments({
39
45
  ...options,
40
46
  turnId: input.turnId,
@@ -68,7 +74,8 @@ function replyFilesSender(channels) {
68
74
  principal: input.principal ?? null,
69
75
  sessionId: input.sessionId,
70
76
  turnId: input.turnId,
71
- callId: `${input.partId}:files`
77
+ callId: `${input.partId}:files`,
78
+ ...input.recipients === void 0 ? {} : { email: input.recipients }
72
79
  });
73
80
  const files = result.files;
74
81
  if (typeof result.error === "string" || files?.some((file) => file.error !== void 0) === true) console.error("[segmentstream] a passed reply's files were not all sent", {
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { t as agentBuild } from "../../_chunks/build-metadata-ByWwCQd1.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-DhAF_QGj.mjs";
@@ -76,4 +76,6 @@ export declare function chatRecorder(archive?: ChatArchive,
76
76
  reviewed?: (principal: HookContext["session"]["auth"]["current"]) => boolean): (event: HookEvent, context: HookContext) => Promise<void>;
77
77
  /** The store's id of a message eve delivered to a session, which has no provider id of its own. */
78
78
  export declare function deliveredMessageId(sessionId: string, deliveryId: string): string;
79
+ /** The store's id of the note for staff on a turn's `reply`, by its call. */
80
+ export declare function replyNoteId(sessionId: string, callId: string): string;
79
81
  export {};
@@ -12,8 +12,9 @@ import { revisionOf } from "./review/revision.mjs";
12
12
  import { It as chatAddressOf, Lt as chatChannel, Vt as participantsOf, i as memberIdOf, st as guestIdOf } from "../../_chunks/principal-DIQHp6AG.mjs";
13
13
  import { keyChannel, principalChannel } from "./channel-scope.mjs";
14
14
  import { parseAddress } from "./telegram/sessions.mjs";
15
- import { n as completionKind } from "../../_chunks/silent-CWcAjHwt.mjs";
15
+ import { n as completionKind } from "../../_chunks/silent-DwObe1UV.mjs";
16
16
  import { recordModelServiceAlert } from "./model-service-alert.mjs";
17
+ import { FINAL_TEXT_REASON, repliesWithTool, replyOf, supersededByToolReply, toolReplyOf } from "./reply.mjs";
17
18
  import { call, deliveries } from "eve/events";
18
19
  function isTelegram(context) {
19
20
  return context.session.auth.current?.authenticator === "segmentstream-telegram" || context.channel.kind?.includes("telegram") === true;
@@ -192,6 +193,17 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
192
193
  errorText: contentText(event.data.error?.message, CONTENT_CAPS.error)
193
194
  }));
194
195
  if (event.type === "turn.settled" || event.type === "session.ended") await recordModelServiceAlert(archive, base, event.data.error);
196
+ } else if (event.type === "turn.settled" && event.data.outcome === "completed") {
197
+ const reply = toolReplyOf(context.view, event.data.turnId);
198
+ if (reply !== void 0 && !RECORDS_REPLIES.has(sessionKind(context) ?? "") && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
199
+ ...base,
200
+ eventId: `${eventId}:outbound`,
201
+ kind: "outbound",
202
+ text: reply.text,
203
+ senderId: "agent",
204
+ senderIsBot: true,
205
+ status: "completed"
206
+ }));
195
207
  } else if (event.type === "model.retried") await archive.append(chatEvent({
196
208
  ...base,
197
209
  eventId,
@@ -205,7 +217,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
205
217
  }),
206
218
  errorText: contentText(event.data.error?.message, CONTENT_CAPS.error)
207
219
  }));
208
- else if (event.type === "content.completed" && event.data.kind === "text" && event.data.phase === "reply" && !event.data.interrupted) {
220
+ else if (event.type === "content.completed" && event.data.kind === "text" && event.data.phase === "reply" && !event.data.interrupted && !supersededByToolReply(event, context)) {
209
221
  const message = typeof event.data.value === "string" ? event.data.value : "";
210
222
  const kind = completionKind(message);
211
223
  const silent = kind !== "reply";
@@ -347,13 +359,27 @@ async function recordMessages(input) {
347
359
  });
348
360
  return;
349
361
  }
350
- if (event.type !== "content.completed" || event.data.kind !== "text" || event.data.phase !== "reply" || event.data.interrupted) return;
351
- const message = typeof event.data.value === "string" ? event.data.value : "";
352
- const silent = completionKind(message) !== "reply";
353
- const turnId = event.scope?.turnId ?? context.session.turn.id;
354
- if (turnId !== void 0 && turnId !== null) {
355
- const answered = RECORDS_MESSAGES.has(sessionKind(context) ?? "") ? (await deliveredMessages(store, base, turnDeliveries(context, turnId).map((delivery) => delivery.deliveryId))).map((messageId) => ({ messageId })) : turnMessages(context, turnId, isTelegram(context));
356
- for (const target of answered) await store.change({
362
+ if (event.type === "call.settled" && event.data.outcome === "completed") {
363
+ const note = call(context.view, event.data.callId)?.name === "segmentstream__reply" ? replyOf(event.data.output)?.note : void 0;
364
+ if (note !== void 0) await store.record({
365
+ channel: base.provider,
366
+ chatId: base.chatId,
367
+ ...base.threadId === null ? {} : { threadId: base.threadId },
368
+ chatType: base.chatType,
369
+ participants: base.participantIds.filter((id) => UUID.test(id)),
370
+ direction: "internal",
371
+ author: "agent",
372
+ messageId: replyNoteId(context.session.id, event.data.callId),
373
+ text: note.slice(0, 1e5),
374
+ at: base.at,
375
+ sessionId: context.session.id,
376
+ ...base.turnId === null ? {} : { turnId: base.turnId }
377
+ });
378
+ return;
379
+ }
380
+ const answered = async (turnId, reason) => {
381
+ const targets = RECORDS_MESSAGES.has(sessionKind(context) ?? "") ? (await deliveredMessages(store, base, turnDeliveries(context, turnId).map((delivery) => delivery.deliveryId))).map((messageId) => ({ messageId })) : turnMessages(context, turnId, isTelegram(context));
382
+ for (const target of targets) await store.change({
357
383
  channel: base.provider,
358
384
  chatId: base.chatId,
359
385
  ...target,
@@ -361,22 +387,41 @@ async function recordMessages(input) {
361
387
  disposition: "turn",
362
388
  sessionId: context.session.id,
363
389
  turnId,
364
- ...silent ? { reason: "silent" } : {}
390
+ ...reason === void 0 ? {} : { reason }
365
391
  });
392
+ };
393
+ const replied = async (text) => {
394
+ if (!RECORDS_REPLIES.has(sessionKind(context) ?? "") && !input.reviewed(context.session.auth.current)) await archive.append(chatEvent({
395
+ ...base,
396
+ eventId: `${eventId}:outbound`,
397
+ kind: "outbound",
398
+ text,
399
+ senderId: "agent",
400
+ senderIsBot: true,
401
+ status: "completed"
402
+ }));
403
+ };
404
+ if (event.type === "turn.settled" && event.data.outcome === "completed") {
405
+ const reply = toolReplyOf(context.view, event.data.turnId);
406
+ if (reply !== void 0) {
407
+ await answered(event.data.turnId, void 0);
408
+ await replied(reply.text);
409
+ }
410
+ return;
366
411
  }
367
- if (!RECORDS_REPLIES.has(sessionKind(context) ?? "") && !silent && !input.reviewed(context.session.auth.current)) await archive.append(chatEvent({
368
- ...base,
369
- eventId: `${eventId}:outbound`,
370
- kind: "outbound",
371
- text: message,
372
- senderId: "agent",
373
- senderIsBot: true,
374
- status: "completed"
375
- }));
412
+ if (event.type !== "content.completed" || event.data.kind !== "text" || event.data.phase !== "reply" || event.data.interrupted || supersededByToolReply(event, context)) return;
413
+ const message = typeof event.data.value === "string" ? event.data.value : "";
414
+ const silent = completionKind(message) !== "reply";
415
+ const turnId = event.scope?.turnId ?? context.session.turn.id;
416
+ if (turnId !== void 0 && turnId !== null) await answered(turnId, silent ? "silent" : repliesWithTool(context.session.auth.current) ? FINAL_TEXT_REASON : void 0);
417
+ if (!silent) await replied(message);
418
+ }
419
+ function replyNoteId(sessionId, callId) {
420
+ return `eve:${sessionId}:note:${callId}`;
376
421
  }
377
422
  function resultErrorMessage(output) {
378
423
  if (typeof output === "string") return output;
379
424
  if (output !== null && typeof output === "object" && "message" in output && typeof output.message === "string") return output.message;
380
425
  return null;
381
426
  }
382
- export { chatCoordinates, chatRecorder, deliveredMessageId, isTelegram, sessionKind, stampedChat };
427
+ export { chatCoordinates, chatRecorder, deliveredMessageId, isTelegram, replyNoteId, sessionKind, stampedChat };
@@ -75,6 +75,12 @@ export declare class ConnectionProxyError extends Error {
75
75
  readonly cause?: unknown;
76
76
  });
77
77
  }
78
+ /**
79
+ * Whether a failed proxy call proves the provider never saw it, so nothing was sent: a refusal
80
+ * before the proxy relayed it, as the ontology classifies its own connection failures. A timeout,
81
+ * a lost answer or any other failure may have reached the provider, and a send is then uncertain.
82
+ */
83
+ export declare function definiteProxyFailure(error: unknown): boolean;
78
84
  export interface ConnectionProxy {
79
85
  readonly connection: string;
80
86
  request(call: ProxyCall, abortSignal?: AbortSignal): Promise<ProxyReply>;
@@ -37,6 +37,37 @@ var ConnectionProxyError = class extends Error {
37
37
  this.requestId = input.requestId;
38
38
  }
39
39
  };
40
+ const UNRELAYED_PROXY_CODES = new Set([
41
+ "connection_authorization_required",
42
+ "connections_not_deployed",
43
+ "connections_redeployment_required",
44
+ "connection_not_found",
45
+ "connection_not_granted",
46
+ "runtime_unauthorized",
47
+ "runtime_value_not_granted",
48
+ "unauthorized",
49
+ "connection_provider_refused",
50
+ "invalid_connection",
51
+ "invalid_request",
52
+ "mcp_request_not_permitted"
53
+ ]);
54
+ const RELAYED_PROXY_CODES = new Set([
55
+ "connection_provider_unavailable",
56
+ "connection_provider_timeout",
57
+ "connection_proxy_unavailable",
58
+ "connection_response_too_large",
59
+ "service_unavailable",
60
+ "timeout",
61
+ "unavailable",
62
+ "invalid_response",
63
+ "too_large"
64
+ ]);
65
+ function definiteProxyFailure(error) {
66
+ if (!(error instanceof ConnectionProxyError)) return false;
67
+ if (UNRELAYED_PROXY_CODES.has(error.code)) return true;
68
+ if (RELAYED_PROXY_CODES.has(error.code)) return false;
69
+ return error.status !== void 0 && error.status < 500;
70
+ }
40
71
  function isRecord(value) {
41
72
  return typeof value === "object" && value !== null && !Array.isArray(value);
42
73
  }
@@ -227,4 +258,4 @@ async function framedReply(connection, body, maxBytes) {
227
258
  body: new Uint8Array(Buffer.concat(chunks))
228
259
  };
229
260
  }
230
- export { ConnectionProxyError, MAXIMUM_DOWNLOAD_BYTES, MAXIMUM_PROXY_BODY_BYTES, MAXIMUM_PROXY_FRAME_BYTES, PROXY_STREAM_MEDIA_TYPE, connectionProxy };
261
+ export { ConnectionProxyError, MAXIMUM_DOWNLOAD_BYTES, MAXIMUM_PROXY_BODY_BYTES, MAXIMUM_PROXY_FRAME_BYTES, PROXY_STREAM_MEDIA_TYPE, connectionProxy, definiteProxyFailure };
@@ -0,0 +1,27 @@
1
+ import { type Environment } from "./environment.js";
2
+ import type { RuntimeTokenVerifier } from "./runtime-identity.js";
3
+ /**
4
+ * What every channel's deliver route shares: the route the ontology hands a message it decided and
5
+ * rendered, for the channel to send through its provider (`emailDeliverRoute` and
6
+ * `telegramDeliverRoute` of the ontology SDK). Only the deployment's own functions may call one,
7
+ * with its runtime identity; outside production it answers `404`, as it does where the agent has
8
+ * no such route. It serves the agent's channel the path names, by `:channel`, and refuses one the
9
+ * agent has not with `422 channel_unknown`, which an agent without the route never answers.
10
+ */
11
+ /** A deliver route's refusal: its code, and what the ontology may act on beside it. */
12
+ export declare function deliverError(code: string, status: number, detail?: Readonly<Record<string, unknown>>): Response;
13
+ /**
14
+ * The deliver request: its caller verified, its channel's name, and the JSON object it carries; or
15
+ * the response that refuses it.
16
+ */
17
+ export declare function deliverRequest(request: Request, params: Readonly<Record<string, string | undefined>>, options: {
18
+ readonly environment: Environment;
19
+ readonly verify: () => RuntimeTokenVerifier;
20
+ /** Whether the agent has a channel of the route's kind by this name. */
21
+ readonly declared: (name: string) => boolean;
22
+ }): Promise<{
23
+ readonly failure: Response;
24
+ } | {
25
+ readonly channel: string;
26
+ readonly body: Readonly<Record<string, unknown>>;
27
+ }>;
@@ -0,0 +1,35 @@
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 { CHANNEL_NAME } from "../config.mjs";
8
+ import { channelsEnabled } from "./environment.mjs";
9
+ import { runtimeRequestFailure } from "./telegram/runtime-request.mjs";
10
+ function deliverError(code, status, detail = {}) {
11
+ return Response.json({
12
+ error: code,
13
+ ...detail
14
+ }, { status });
15
+ }
16
+ async function deliverRequest(request, params, options) {
17
+ const failure = await runtimeRequestFailure(request, {
18
+ enabled: () => true,
19
+ configured: () => channelsEnabled(options.environment),
20
+ verify: options.verify
21
+ });
22
+ if (failure !== void 0) return { failure };
23
+ const channel = params.channel ?? "";
24
+ if (!CHANNEL_NAME.test(channel) || !options.declared(channel)) return { failure: deliverError("channel_unknown", 422) };
25
+ try {
26
+ const value = await request.json();
27
+ return {
28
+ channel,
29
+ body: typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}
30
+ };
31
+ } catch {
32
+ return { failure: deliverError("invalid_request", 400) };
33
+ }
34
+ }
35
+ export { deliverError, deliverRequest };
@@ -35,6 +35,8 @@ export declare function sendEmailAttachments(options: {
35
35
  readonly callId: string;
36
36
  /** The connection of the email channel the chat is on, such as `channels.email.connection`. */
37
37
  readonly connection: string | undefined;
38
+ /** Whom the reply goes to, when a turn's `reply` named them; absent, the person. */
39
+ readonly to?: ReadonlyArray<string>;
38
40
  /** The thread's other people the reply copies, as the channel's text replies do. */
39
41
  readonly cc?: ReadonlyArray<string>;
40
42
  /** Whether the reply ends with the mailbox's own signature, as the channel's text replies do. */
@@ -103,7 +103,7 @@ async function sendEmailAttachments(options) {
103
103
  try {
104
104
  const id = await mailbox.reply({
105
105
  threadId: chat.threadId,
106
- to: chat.peer,
106
+ to: options.to === void 0 || options.to.length === 0 ? chat.peer : options.to.length === 1 ? options.to[0] : options.to,
107
107
  ...options.cc === void 0 || options.cc.length === 0 ? {} : { cc: options.cc },
108
108
  text: input.caption ?? "",
109
109
  key: replyKeyOf(options.sessionId, options.callId, "files"),