@segmentstream/agent 0.103.0 → 0.104.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 (41) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +6 -0
  3. package/dist/_chunks/{build-metadata-BkLo_nGS.mjs → build-metadata-DkPNOrqc.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/email/attachments-send.d.ts +2 -0
  13. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  14. package/dist/extension/lib/email/channel.mjs +24 -16
  15. package/dist/extension/lib/reply-part.d.ts +11 -0
  16. package/dist/extension/lib/reply-part.mjs +17 -0
  17. package/dist/extension/lib/reply.d.ts +115 -0
  18. package/dist/extension/lib/reply.mjs +107 -0
  19. package/dist/extension/lib/review/files.d.ts +3 -2
  20. package/dist/extension/lib/review/files.mjs +1 -1
  21. package/dist/extension/lib/review/hold.d.ts +7 -0
  22. package/dist/extension/lib/review/hold.mjs +3 -3
  23. package/dist/extension/lib/review/reply.d.ts +24 -0
  24. package/dist/extension/lib/review/reply.mjs +18 -6
  25. package/dist/extension/lib/review/revision.mjs +3 -1
  26. package/dist/extension/lib/slack/adapter.mjs +2 -1
  27. package/dist/extension/lib/telegram/adapter.mjs +55 -50
  28. package/dist/extension/lib/telegram/health.mjs +1 -1
  29. package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
  30. package/dist/extension/lib/telegram/routing-context.mjs +1 -1
  31. package/dist/extension/lib/telegram/silent.d.ts +3 -1
  32. package/dist/extension/lib/telegram/silent.mjs +1 -1
  33. package/dist/extension/lib/whatsapp/adapter.mjs +2 -1
  34. package/dist/extension/lib/workspace-channel/channel.d.ts +4 -1
  35. package/dist/extension/lib/workspace-channel/channel.mjs +14 -5
  36. package/dist/extension/tools/attachments_send.mjs +1 -1
  37. package/dist/extension/tools/reply.d.ts +19 -0
  38. package/dist/extension/tools/reply.mjs +180 -0
  39. package/dist/tools/index.d.ts +1 -0
  40. package/dist/tools/index.mjs +2 -1
  41. package/package.json +4 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.104.0
4
+
5
+ The starter's `agent/agent/instructions.md` tells the agent, in the workspace's words, to answer in
6
+ channel chats with `segmentstream__reply`: once, with the whole message and nothing outside it,
7
+ files in `files`, `to` and `cc` only to change whom of a mail thread's people it goes to, and a
8
+ `note` for the team; `segmentstream__no_reply` when a message needs no answer; plain text in the
9
+ app's own chat. A workspace's instructions are its own: copy the paragraph into yours and change
10
+ its words as you like.
11
+
12
+ The agent replies in channel chats with a call: `segmentstream__reply({ text, files?, to?, cc?,
13
+ replyTo?, note? })`, offered in every chat on an email, Telegram, WhatsApp, Slack or workspace
14
+ channel, a guest's included, and never in the web chat, a workflow's task or a redraft. The call is
15
+ the turn's reply and ends the turn without another model call. When the turn ends, the chat's
16
+ channel sends it, holds it for review or, on email and workspace channels with `review`, proposes it
17
+ to the ontology, as it did a turn's final text; Telegram, WhatsApp and Slack post it as they post a
18
+ reply part. `files` go with the reply in a reviewed chat and are sent ahead of it in any other, as
19
+ `attachments_send` sends them. `to` and `cc` choose, for a reply to mail, whom of the thread's people
20
+ it goes to and copies, and refuse anyone else. `replyTo` names the message a Telegram or workspace
21
+ channel reply answers. `note` is kept for staff as an `internal` message of the turn in the chat
22
+ store, never sent; the agent's logs show it as a call of `segmentstream__reply`, and the chat figures
23
+ do not count it as an unanswered question.
24
+
25
+ A turn's final text without the call still reaches the person, as a deprecated fallback: in a
26
+ reviewed chat it is held as a draft without the decision model reading it, and in any other chat it
27
+ is sent as before. The messages it answered carry the reason code `final_text` on their disposition.
28
+ A turn that writes both sends the call's reply and drops the text. The web chat is unchanged.
29
+
30
+ On WhatsApp and Slack, a reviewed reply now reads the files the turn attached from the session as
31
+ eve hands it to the channel; before, such a reply was neither sent nor held.
32
+
33
+ Action required: tell your agent to reply with `segmentstream__reply` in channel chats, as the
34
+ starter's `agent/agent/instructions.md` now does. Until then a reviewed chat holds every reply the
35
+ decision model would have judged, and a turn's final text in a channel chat is deprecated: it
36
+ reaches the person until 2027-05-28, and is removed once such replies are near zero.
37
+
38
+ ## 0.103.1
39
+
40
+ Pins @segmentstream/ontology 0.183.0.
41
+
3
42
  ## 0.103.0
4
43
 
5
44
  Guest turns on admitted messaging channels use workspace roles, regular agent personas, and ontology tools. Workspaces select guest roles by channel and can handle authorized provider tools in workspace code. This replaces isolated group responses and their dedicated action and connection bindings.
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. |
@@ -601,6 +602,11 @@ The SDK adds no text to the prompt.
601
602
  protocol below. The old instruction receiver `/eve/v1/telegram/messages` is removed. Telegram
602
603
  routes now serve only the inbound webhook and authenticated health; old instruction relay calls
603
604
  fail instead of starting an agent turn.
605
+ - **Replies.** The model answers with `segmentstream__reply`, which ends the turn; at its end the
606
+ channel posts the call's text as it posts a reply part, quoting the message its `replyTo` names.
607
+ <!-- @legacy agent.final-text-replies -->
608
+ Final text of a turn without the call is still sent, or held unjudged in a reviewed chat, and
609
+ dropped when the turn has one. See `docs/agent.md`, "Replying in channel chats".
604
610
  - **Silence.** When the model calls `segmentstream__no_reply` (eve's `no_reply`), the turn ends
605
611
  without a message; the call and its reason are recorded in the session and the chat
606
612
  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.0";
7
+ var version = "0.104.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-BkLo_nGS.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-DkPNOrqc.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 };
@@ -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"),
@@ -20,8 +20,9 @@ import { AgentIdentityError, agentIdentities } from "../identities.mjs";
20
20
  import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.mjs";
21
21
  import { gatewayImageDescriber } from "../inbound-media/images.mjs";
22
22
  import { gatewayTranscriber } from "../inbound-media/speech.mjs";
23
+ import { turnReply } from "../reply.mjs";
23
24
  import { channelReview } from "../review/reply.mjs";
24
- import { g as turnFiles, n as completionKind } from "../../../_chunks/silent-CWcAjHwt.mjs";
25
+ import { g as turnFiles, n as completionKind } from "../../../_chunks/silent-DwObe1UV.mjs";
25
26
  import { runtimeTokenVerifier } from "../runtime-identity.mjs";
26
27
  import { runtimeToken } from "../runtime-token.mjs";
27
28
  import { runtimeRequestFailure } from "../telegram/runtime-request.mjs";
@@ -67,13 +68,13 @@ function waitingReply(event) {
67
68
  const key = event.operationId?.startsWith("reply:") ? event.operationId.slice(6) : void 0;
68
69
  const threadId = event.threadId;
69
70
  const named = replyRecipients(event);
70
- const to = named?.to.length === 1 ? named.to[0] : threadId !== null && event.chatId.startsWith(`${threadId}:`) ? event.chatId.slice(threadId.length + 1) : void 0;
71
- return key === void 0 || threadId === null || !GMAIL_ID.test(threadId) || to === void 0 || !isEmailAddress(to) || event.text === null ? void 0 : {
71
+ const to = named !== void 0 && named.to.length > 0 ? named.to : threadId !== null && event.chatId.startsWith(`${threadId}:`) ? [event.chatId.slice(threadId.length + 1)] : void 0;
72
+ return key === void 0 || threadId === null || !GMAIL_ID.test(threadId) || to === void 0 || !to.every(isEmailAddress) || event.text === null ? void 0 : {
72
73
  key,
73
74
  chatId: event.chatId,
74
75
  threadId,
75
- to,
76
- cc: (named?.cc ?? []).filter(isEmailAddress).slice(0, EMAIL_RECIPIENTS_LIMIT - 1),
76
+ to: to.slice(0, EMAIL_RECIPIENTS_LIMIT),
77
+ cc: (named?.cc ?? []).filter(isEmailAddress).slice(0, Math.max(EMAIL_RECIPIENTS_LIMIT - to.length, 0)),
77
78
  text: event.text,
78
79
  participantIds: event.participantIds,
79
80
  sessionId: event.sessionId,
@@ -275,7 +276,7 @@ function emailChannelDefinition(options) {
275
276
  for (let attempt = 1;; attempt++) try {
276
277
  return await mailbox().reply({
277
278
  threadId: reply.threadId,
278
- to: reply.to,
279
+ to: reply.to.length === 1 ? reply.to[0] : reply.to,
279
280
  ...reply.cc.length === 0 ? {} : { cc: reply.cc },
280
281
  text: reply.text,
281
282
  key: reply.key,
@@ -302,7 +303,7 @@ function emailChannelDefinition(options) {
302
303
  ...messageId === void 0 ? {} : { messageId },
303
304
  ...status === "requested" ? { at: reply.at } : {},
304
305
  recipients: {
305
- to: [reply.to],
306
+ to: reply.to,
306
307
  cc: reply.cc
307
308
  }
308
309
  }));
@@ -1001,8 +1002,10 @@ function emailChannelDefinition(options) {
1001
1002
  const principal = ctx.session.auth.current;
1002
1003
  const chat = chatAddressOf(principal);
1003
1004
  if (outcome !== "completed" || chat?.provider !== "email" || chat.peer === void 0) return;
1004
- const text = replyText(ctx.view, turnId);
1005
- const cc = replyCopies(principal, settings());
1005
+ const replied = turnReply(ctx.view, turnId, replyText(ctx.view, turnId));
1006
+ const text = replied.text;
1007
+ const to = (replied.source === "reply" ? replied.to : void 0) ?? [chat.peer];
1008
+ const cc = ((replied.source === "reply" ? replied.cc : void 0) ?? replyCopies(principal, settings())).filter((address) => !to.includes(address)).slice(0, Math.max(EMAIL_RECIPIENTS_LIMIT - to.length, 0));
1006
1009
  const reviewing = review()?.review;
1007
1010
  const files = reviewing === void 0 ? void 0 : turnFiles(ctx.view, turnId);
1008
1011
  if (completionKind(text) !== "reply") {
@@ -1012,7 +1015,7 @@ function emailChannelDefinition(options) {
1012
1015
  turnId,
1013
1016
  files,
1014
1017
  recipients: {
1015
- to: [chat.peer],
1018
+ to,
1016
1019
  cc
1017
1020
  }
1018
1021
  });
@@ -1025,10 +1028,11 @@ function emailChannelDefinition(options) {
1025
1028
  partId: turnId,
1026
1029
  text,
1027
1030
  recipients: {
1028
- to: [chat.peer],
1031
+ to,
1029
1032
  cc
1030
1033
  },
1031
- ...files === void 0 || files.files.length === 0 ? {} : { files }
1034
+ ...files === void 0 || files.files.length === 0 ? {} : { files },
1035
+ ...replied.source === "final_text" ? { fallback: true } : {}
1032
1036
  };
1033
1037
  const proposed = reviewing !== void 0 && reviewing.proposes(principal) ? await reviewing.propose(written) : void 0;
1034
1038
  if (proposed?.by === "ontology") {
@@ -1044,7 +1048,7 @@ function emailChannelDefinition(options) {
1044
1048
  turnId,
1045
1049
  files,
1046
1050
  recipients: {
1047
- to: [chat.peer],
1051
+ to,
1048
1052
  cc
1049
1053
  }
1050
1054
  });
@@ -1061,7 +1065,7 @@ function emailChannelDefinition(options) {
1061
1065
  key: replyKeyOf(ctx.session.id, turnId),
1062
1066
  chatId: chat.chatId,
1063
1067
  threadId: chat.threadId,
1064
- to: chat.peer,
1068
+ to,
1065
1069
  cc,
1066
1070
  text,
1067
1071
  participantIds,
@@ -1077,7 +1081,11 @@ function emailChannelDefinition(options) {
1077
1081
  sessionId: ctx.session.id,
1078
1082
  turnId,
1079
1083
  partId: turnId,
1080
- files
1084
+ files,
1085
+ recipients: {
1086
+ to,
1087
+ cc
1088
+ }
1081
1089
  });
1082
1090
  else await reviewing.holdFiles({
1083
1091
  principal,
@@ -1085,7 +1093,7 @@ function emailChannelDefinition(options) {
1085
1093
  turnId,
1086
1094
  files,
1087
1095
  recipients: {
1088
- to: [chat.peer],
1096
+ to,
1089
1097
  cc
1090
1098
  }
1091
1099
  });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The reply part a turn's `reply` call goes as on a channel that posts reply parts (Telegram,
3
+ * WhatsApp, Slack): `reply:<callId>`. It is its own module so that the redraft lookups, which
4
+ * `lib/reply.ts` depends on, can name it too.
5
+ */
6
+ /** The id of the reply part a turn's reply through `reply` goes as: its call's. */
7
+ export declare function toolReplyPartId(callId: string): string;
8
+ /** Whether a reply part is a turn's reply through `reply`, rather than text the turn ended with. */
9
+ export declare function isToolReplyPart(partId: string | undefined): boolean;
10
+ /** The `reply` call a reply part goes for; undefined for any other part. */
11
+ export declare function toolReplyCallOf(partId: string): string | undefined;
@@ -0,0 +1,17 @@
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
+ const REPLY_PART = "reply:";
8
+ function toolReplyPartId(callId) {
9
+ return `${REPLY_PART}${callId}`;
10
+ }
11
+ function isToolReplyPart(partId) {
12
+ return partId?.startsWith(REPLY_PART) === true;
13
+ }
14
+ function toolReplyCallOf(partId) {
15
+ return isToolReplyPart(partId) && partId.length > 6 ? partId.slice(6) : void 0;
16
+ }
17
+ export { isToolReplyPart, toolReplyCallOf, toolReplyPartId };