@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
@@ -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 { CHANNEL_NAME, PUBSUB_TOPIC } from "../../config.mjs";
7
+ import { PUBSUB_TOPIC } from "../../config.mjs";
8
8
  import { admitMessage, localizedText, reportUnadmittedChat } from "../admission.mjs";
9
9
  import { agentToolsAttribute } from "../agent-tools.mjs";
10
10
  import { providerChat } from "../attachment-tools.mjs";
@@ -20,11 +20,13 @@ 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
- import { runtimeRequestFailure } from "../telegram/runtime-request.mjs";
28
+ import { deliverRequest } from "../deliver-route.mjs";
29
+ import { readDeliveredFile } from "../sent-files.mjs";
28
30
  import { workspaceTriage } from "../triage.mjs";
29
31
  import { GMAIL_ID, GmailError, ReplyNotSent, gmail, replyKeyOf } from "./gmail.mjs";
30
32
  import { inboundMail, parseMail, sentMail } from "./message.mjs";
@@ -34,7 +36,6 @@ import { EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, EMAIL_RECIPIENTS_LIMIT, GmailMa
34
36
  import { POST, defineChannel } from "eve/channels";
35
37
  const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
36
38
  const EMAIL_DELIVER_ROUTE = `${EMAIL_ROUTE}/:channel/deliver`;
37
- const DELIVER_FILE_TIMEOUT_MS = 3e4;
38
39
  const EMAIL_AUTHENTICATOR = "segmentstream-email";
39
40
  const MESSAGES_PER_WAKE = 20;
40
41
  const WATCH_RENEW_MS = 864e5;
@@ -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,42 +1093,21 @@ 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
  });
1092
1100
  }
1093
1101
  } });
1094
1102
  let verifier = options.verify;
1095
- async function linkedFile(file) {
1096
- const response = await (transport.fetch ?? fetch)(file.url, {
1097
- redirect: "error",
1098
- signal: AbortSignal.timeout(DELIVER_FILE_TIMEOUT_MS)
1099
- });
1100
- if (!response.ok) {
1101
- await response.body?.cancel();
1102
- throw new Error(`The file storage answered with status ${response.status}.`);
1103
- }
1104
- const bytes = new Uint8Array(await response.arrayBuffer());
1105
- if (bytes.byteLength !== file.size) throw new Error(`The file read has ${bytes.byteLength} bytes, not the ${file.size} named.`);
1106
- return bytes;
1107
- }
1108
1103
  async function deliverRoute(request, args) {
1109
- const failure = await runtimeRequestFailure(request, {
1110
- enabled: () => true,
1111
- configured: () => channelsEnabled(environment),
1112
- verify: () => verifier ??= runtimeTokenVerifier(runtimeIdentityEnvironment(environment))
1104
+ const read = await deliverRequest(request, args.params, {
1105
+ environment,
1106
+ verify: () => verifier ??= runtimeTokenVerifier(runtimeIdentityEnvironment(environment)),
1107
+ declared: (name) => options.settings(name) !== null
1113
1108
  });
1114
- if (failure !== void 0) return failure;
1115
- const name = args.params.channel ?? "";
1116
- if (!CHANNEL_NAME.test(name) || options.settings(name) === null) return Response.json({ error: "channel_unknown" }, { status: 422 });
1117
- let body;
1118
- try {
1119
- const value = await request.json();
1120
- body = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1121
- } catch {
1122
- return Response.json({ error: "invalid_request" }, { status: 400 });
1123
- }
1109
+ if ("failure" in read) return read.failure;
1110
+ const { channel: name, body } = read;
1124
1111
  const addresses = (value) => Array.isArray(value) && value.every((address) => typeof address === "string" && isEmailAddress(address)) ? value : void 0;
1125
1112
  const to = addresses(body.to);
1126
1113
  const cc = addresses(body.cc ?? []);
@@ -1146,7 +1133,7 @@ function emailChannelDefinition(options) {
1146
1133
  attachments.push({
1147
1134
  filename: file.filename,
1148
1135
  contentType: file.content_type,
1149
- bytes: await linkedFile(file)
1136
+ bytes: await readDeliveredFile(file, transport.fetch ?? fetch)
1150
1137
  });
1151
1138
  } catch (cause) {
1152
1139
  report("file_unavailable", cause);
@@ -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 };
@@ -0,0 +1,115 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import { type SessionView } from "eve/events";
3
+ export { isToolReplyPart, toolReplyPartId } from "./reply-part.js";
4
+ /**
5
+ * The reply a turn on a channel chat sends (`docs/agent.md`, "Replying in channel chats"). The
6
+ * session is the agent's own: what reaches the person is a deliberate act, a call of the `reply`
7
+ * tool (`src/tools/reply.ts`) with its fields, not whatever text the turn ended with. The call
8
+ * sends nothing itself and ends the turn. When the turn ends, its channel reads the reply from the
9
+ * call the session recorded, as it reads the files `attachments_send` attached, and sends it,
10
+ * holds it or proposes it to the ontology as it did a turn's final text. Nothing is kept in
11
+ * memory, as eve may run a channel's handler again.
12
+ */
13
+ /** The `reply` tool, as eve names the extension's tools: its mount's prefix, then its own name. */
14
+ export declare const REPLY_TOOL = "segmentstream__reply";
15
+ /**
16
+ * @legacy agent.final-text-replies
17
+ * The reason code of the person's messages a turn answered with its final text instead of a
18
+ * `reply` call. The chat store keeps it on their disposition, which counts such replies per
19
+ * workspace.
20
+ */
21
+ export declare const FINAL_TEXT_REASON = "final_text";
22
+ /**
23
+ * Whether a session replies with `reply`: its chat is on an email, Telegram, WhatsApp, Slack or
24
+ * workspace channel. The web chat streams its final text to the browser, and a workflow's task or
25
+ * a redraft answers with its final text, which is its result.
26
+ */
27
+ export declare function repliesWithTool(principal: SessionAuthContext | null | undefined): boolean;
28
+ /** A turn's reply through `reply`, as its call answered it. */
29
+ export interface ToolReply {
30
+ readonly callId: string;
31
+ readonly text: string;
32
+ /** A reply to mail: whom it goes to, when the call named them. */
33
+ readonly to?: ReadonlyArray<string>;
34
+ /** A reply to mail: whom it copies, when the call named them. */
35
+ readonly cc?: ReadonlyArray<string>;
36
+ /** The id of the person's message the reply answers, where the channel quotes one. */
37
+ readonly replyTo?: string;
38
+ /** For the workspace's staff, never sent: kept as an internal message on the turn. */
39
+ readonly note?: string;
40
+ }
41
+ /** The reply a `reply` call's output carries; undefined for any other output. */
42
+ export declare function replyOf(output: unknown): Omit<ToolReply, "callId"> | undefined;
43
+ /**
44
+ * The turn's reply through `reply`: the last of its calls that succeeded, as a turn sends one
45
+ * reply. Undefined for a turn that wrote none.
46
+ */
47
+ export declare function toolReplyOf(view: SessionView | undefined, turnId: string | null | undefined): ToolReply | undefined;
48
+ /** What a turn sends: its `reply` call, or the text it ended with. */
49
+ export type TurnReply = ({
50
+ readonly source: "reply";
51
+ } & ToolReply) | {
52
+ /** @legacy agent.final-text-replies The turn's final text, without a `reply` call. */
53
+ readonly source: "final_text";
54
+ readonly text: string;
55
+ };
56
+ /**
57
+ * The reply a turn sends: its `reply` call, which wins over any text the turn ended with, which is
58
+ * then dropped. Without one, @legacy agent.final-text-replies its final text, `finalText`, which a
59
+ * reviewed chat holds unjudged and any other chat sends as before.
60
+ */
61
+ export declare function turnReply(view: SessionView | undefined, turnId: string, finalText: string): TurnReply;
62
+ /** A turn's reply part, as eve hands it to a channel's `content.completed`. */
63
+ interface ReplyPartEvent {
64
+ readonly data: {
65
+ readonly kind: string;
66
+ readonly phase: string;
67
+ readonly partId: string;
68
+ readonly value?: unknown;
69
+ readonly interrupted?: true;
70
+ };
71
+ readonly scope?: {
72
+ readonly turnId?: string;
73
+ };
74
+ }
75
+ /** What a channel's handler is given beside an event, as far as a turn's reply needs it. */
76
+ interface ReplyContext {
77
+ readonly session: {
78
+ readonly turn?: {
79
+ readonly id?: string;
80
+ };
81
+ };
82
+ /** The session's tables as of the event, where the turn's calls are read. */
83
+ readonly view?: SessionView;
84
+ }
85
+ /**
86
+ * The reply part a channel that posts a turn's reply parts posts the turn's reply through `reply`
87
+ * as, at the turn's end: a part of its text, named after the call. Undefined for a turn without
88
+ * one.
89
+ */
90
+ export declare function toolReplyPart(view: SessionView | undefined, turnId: string): {
91
+ readonly type: "content.completed";
92
+ readonly data: {
93
+ readonly kind: "text";
94
+ readonly phase: "reply";
95
+ readonly partId: string;
96
+ readonly value: string;
97
+ };
98
+ readonly scope: {
99
+ readonly turnId: string;
100
+ };
101
+ } | undefined;
102
+ /**
103
+ * @legacy agent.final-text-replies
104
+ * Whether a reply part is text a turn wrote though it replied with `reply`: the call wins, and the
105
+ * text is dropped.
106
+ */
107
+ export declare function supersededByToolReply(event: ReplyPartEvent, context: ReplyContext): boolean;
108
+ /**
109
+ * A channel that posts each of a turn's reply parts as it completes, as eve's Chat SDK bridge and
110
+ * Slack channel do. At the turn's end it posts the turn's reply through `reply`, which no reply
111
+ * part carries, the way it posts a reply part: reviewed, recorded and formatted as one. Final text
112
+ * of a turn that replied so is dropped. Works for channels whose handlers live on
113
+ * `channel.adapter`; wrap the channel's review first, so the reply goes through it.
114
+ */
115
+ export declare function withToolReplies<Channel extends object>(channel: Channel): Channel;
@@ -0,0 +1,107 @@
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 { adapterView } from "./adapter-view.mjs";
8
+ import { agentTaskIdOf } from "./agent-task.mjs";
9
+ import { It as chatAddressOf } from "../../_chunks/principal-DIQHp6AG.mjs";
10
+ import { isToolReplyPart, toolReplyPartId } from "./reply-part.mjs";
11
+ import { revisionOf } from "./review/revision.mjs";
12
+ import { calls } from "eve/events";
13
+ const REPLY_TOOL = "segmentstream__reply";
14
+ const FINAL_TEXT_REASON = "final_text";
15
+ function repliesWithTool(principal) {
16
+ const provider = chatAddressOf(principal)?.provider;
17
+ return provider !== void 0 && provider !== "web" && agentTaskIdOf(principal) === void 0 && revisionOf(principal) === void 0;
18
+ }
19
+ function isRecord(value) {
20
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21
+ }
22
+ function strings(value) {
23
+ return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
24
+ }
25
+ function replyOf(output) {
26
+ if (!isRecord(output) || output.replied !== true || typeof output.text !== "string" || output.text.trim() === "") return;
27
+ const to = strings(output.to);
28
+ const cc = strings(output.cc);
29
+ return {
30
+ text: output.text,
31
+ ...to === void 0 ? {} : { to },
32
+ ...cc === void 0 ? {} : { cc },
33
+ ...typeof output.replyTo === "string" && output.replyTo !== "" ? { replyTo: output.replyTo } : {},
34
+ ...typeof output.note === "string" && output.note.trim() !== "" ? { note: output.note } : {}
35
+ };
36
+ }
37
+ function toolReplyOf(view, turnId) {
38
+ if (view === void 0 || turnId === void 0 || turnId === null || turnId === "") return;
39
+ return calls(view, { turnId }).filter((call) => call.name === "segmentstream__reply" && call.outcome === "completed").flatMap((call) => {
40
+ const reply = replyOf(call.output);
41
+ return reply === void 0 ? [] : [{
42
+ reply: {
43
+ ...reply,
44
+ callId: call.callId
45
+ },
46
+ endedAt: call.endedAt ?? ""
47
+ }];
48
+ }).sort((one, other) => one.endedAt < other.endedAt ? -1 : one.endedAt > other.endedAt ? 1 : 0).at(-1)?.reply;
49
+ }
50
+ function turnReply(view, turnId, finalText) {
51
+ const reply = toolReplyOf(view, turnId);
52
+ return reply === void 0 ? {
53
+ source: "final_text",
54
+ text: finalText
55
+ } : {
56
+ source: "reply",
57
+ ...reply
58
+ };
59
+ }
60
+ function toolReplyPart(view, turnId) {
61
+ const reply = toolReplyOf(view, turnId);
62
+ return reply === void 0 ? void 0 : {
63
+ type: "content.completed",
64
+ data: {
65
+ kind: "text",
66
+ phase: "reply",
67
+ partId: toolReplyPartId(reply.callId),
68
+ value: reply.text
69
+ },
70
+ scope: { turnId }
71
+ };
72
+ }
73
+ function supersededByToolReply(event, context) {
74
+ return event.data.kind === "text" && event.data.phase === "reply" && !isToolReplyPart(event.data.partId) && toolReplyOf(context.view, event.scope?.turnId ?? context.session.turn?.id) !== void 0;
75
+ }
76
+ function withToolReplies(channel) {
77
+ const adapter = channel.adapter;
78
+ const completed = adapter?.["content.completed"];
79
+ if (adapter === void 0 || completed === void 0) return channel;
80
+ const handler = async (event, context) => {
81
+ return supersededByToolReply(event, {
82
+ ...context,
83
+ view: await adapterView(event, context)
84
+ }) ? completed({
85
+ ...event,
86
+ data: {
87
+ ...event.data,
88
+ value: ""
89
+ }
90
+ }, context) : completed(event, context);
91
+ };
92
+ const settled = adapter["turn.settled"];
93
+ const settle = async (event, context) => {
94
+ const part = event.data.outcome === "completed" ? toolReplyPart(await adapterView(event, context), event.data.turnId) : void 0;
95
+ if (part !== void 0) await completed(part, context);
96
+ await settled?.(event, context);
97
+ };
98
+ return {
99
+ ...channel,
100
+ adapter: {
101
+ ...adapter,
102
+ "content.completed": handler,
103
+ "turn.settled": settle
104
+ }
105
+ };
106
+ }
107
+ export { FINAL_TEXT_REASON, REPLY_TOOL, isToolReplyPart, repliesWithTool, replyOf, supersededByToolReply, toolReplyOf, toolReplyPart, toolReplyPartId, turnReply, withToolReplies };
@@ -28,12 +28,13 @@ export declare function turnFiles(view: SessionView, turnId: string): ReplyFiles
28
28
  /**
29
29
  * The files that go with reply part `partId`: those attached after the turn's previous reply part
30
30
  * began and before this one did. Files attached after the turn's last reply part are
31
- * {@link filesAfterReply}.
31
+ * {@link filesAfterReply}. The turn's reply through `reply` carries every file the turn attached.
32
32
  */
33
33
  export declare function partFiles(view: SessionView, turnId: string, partId: string): ReplyFiles;
34
34
  /**
35
35
  * The files no reply part of the turn carries: attached after its last reply part began, or every
36
- * file of a turn without a reply. They are held on their own, never sent unreviewed.
36
+ * file of a turn without a reply. They are held on their own, never sent unreviewed. A turn that
37
+ * replied with `reply` leaves none: that reply carries them all.
37
38
  */
38
39
  export declare function filesAfterReply(view: SessionView, turnId: string): ReplyFiles;
39
40
  /** The most files one draft holds, as the ontology's `agent_draft` takes them. */
@@ -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 { c as CAPTION_LIMIT, l as DRAFT_FILES_LIMIT, u as ReplyFilesRefused, d as attachToReply, f as checkReplyFiles, p as fileGroups, m as filesAfterReply, h as partFiles, g as turnFiles, _ as withCaptions } from "../../../_chunks/silent-CWcAjHwt.mjs";
7
+ export { c as CAPTION_LIMIT, l as DRAFT_FILES_LIMIT, u as ReplyFilesRefused, d as attachToReply, f as checkReplyFiles, p as fileGroups, m as filesAfterReply, h as partFiles, g as turnFiles, _ as withCaptions } from "../../../_chunks/silent-DwObe1UV.mjs";
@@ -116,6 +116,8 @@ export declare function proposedReply(input: {
116
116
  readonly review: PolicySettings;
117
117
  readonly confidence: number | null;
118
118
  readonly maxLength?: number;
119
+ /** The id of the person's message a workspace channel's reply answers, from `reply`. */
120
+ readonly replyTo?: string;
119
121
  }): ProposedReply | undefined;
120
122
  /**
121
123
  * The held reply for a final reply to `principal`, or undefined when the session has no
@@ -136,4 +138,9 @@ export declare function heldReply(input: {
136
138
  readonly to: ReadonlyArray<string>;
137
139
  readonly cc: ReadonlyArray<string>;
138
140
  };
141
+ /**
142
+ * The id of the person's message the reply answers, from `reply`; a Telegram reply answers the
143
+ * message that started the turn otherwise.
144
+ */
145
+ readonly replyTo?: string;
139
146
  }): HeldReply | undefined;
@@ -50,7 +50,7 @@ function proposedReply(input) {
50
50
  chatId: chat.chatId,
51
51
  recipient: chat.kind === "private" && chat.peer !== void 0 ? chat.peer : chat.chatId,
52
52
  threadId: chat.threadId,
53
- replyTo: null,
53
+ replyTo: chat.provider === "custom" ? input.replyTo ?? null : null,
54
54
  ...chat.provider === "email" && input.recipients !== void 0 ? {
55
55
  to: input.recipients.to,
56
56
  cc: input.recipients.cc
@@ -71,7 +71,7 @@ function proposedReply(input) {
71
71
  function heldReply(input) {
72
72
  const chat = chatAddressOf(input.principal);
73
73
  const memberId = memberIdOf(input.principal);
74
- const replyTo = input.principal?.attributes.replyToMessageId;
74
+ const replyTo = input.replyTo ?? input.principal?.attributes.replyToMessageId;
75
75
  const participants = participantsOf(input.principal);
76
76
  if (chat === void 0 || memberId === void 0 || !holdsReplies(chat.provider)) return;
77
77
  return {
@@ -81,7 +81,7 @@ function heldReply(input) {
81
81
  chatId: chat.chatId,
82
82
  recipient: chat.kind === "private" && chat.peer !== void 0 ? chat.peer : chat.chatId,
83
83
  threadId: chat.threadId,
84
- replyTo: chat.provider === "telegram" && typeof replyTo === "string" && /^[1-9]\d*$/u.test(replyTo) ? replyTo : null,
84
+ replyTo: chat.provider === "telegram" && typeof replyTo === "string" && /^[1-9]\d*$/u.test(replyTo) ? replyTo : chat.provider === "custom" && input.replyTo !== void 0 ? input.replyTo : null,
85
85
  ...chat.provider === "email" && input.recipients !== void 0 ? {
86
86
  to: input.recipients.to,
87
87
  cc: input.recipients.cc
@@ -46,6 +46,14 @@ export interface ReplyReview {
46
46
  readonly files?: ReplyFiles;
47
47
  /** A workspace channel's `limits.maxLength`: the ontology sends a longer reply in parts. */
48
48
  readonly maxLength?: number;
49
+ /** The id of the person's message a workspace channel's reply answers, from `reply`. */
50
+ readonly replyTo?: string;
51
+ /**
52
+ * @legacy agent.final-text-replies
53
+ * The turn's final text, which it did not send with `reply`: proposed unjudged, so a reviewed
54
+ * chat holds it.
55
+ */
56
+ readonly fallback?: boolean;
49
57
  }): Promise<ProposedOutcome>;
50
58
  /**
51
59
  * Whether the channel may send `text` now: true for a chat that is not reviewed, or a
@@ -69,6 +77,13 @@ export interface ReplyReview {
69
77
  * answers true with files, the channel sends them after the text.
70
78
  */
71
79
  readonly files?: ReplyFiles;
80
+ /** The id of the person's message the reply answers, from `reply`, which a draft keeps. */
81
+ readonly replyTo?: string;
82
+ /**
83
+ * @legacy agent.final-text-replies
84
+ * The turn's final text, which it did not send with `reply`: held unjudged in a reviewed chat.
85
+ */
86
+ readonly fallback?: boolean;
72
87
  }): Promise<boolean>;
73
88
  /**
74
89
  * Holds files the turn attached that no reply carries, such as a reply of files alone: never
@@ -84,6 +99,8 @@ export interface ReplyReview {
84
99
  readonly turnId: string | null;
85
100
  readonly partId: string;
86
101
  readonly files: ReplyFiles;
102
+ /** In an email thread, the people the reply's text went to: its files go to them too. */
103
+ readonly recipients?: ReplyRecipients;
87
104
  }): Promise<void>;
88
105
  holdFiles(input: {
89
106
  readonly principal: SessionAuthContext | null | undefined;
@@ -162,7 +179,14 @@ export type SendReplyFiles = (input: {
162
179
  readonly turnId: string | null;
163
180
  readonly partId: string;
164
181
  readonly files: ReplyFiles;
182
+ /** In an email thread, the people the reply's text went to: its files go to them too. */
183
+ readonly recipients?: ReplyRecipients;
165
184
  }) => Promise<unknown>;
185
+ /** Whom a reply to mail goes to and copies. */
186
+ export interface ReplyRecipients {
187
+ readonly to: ReadonlyArray<string>;
188
+ readonly cc: ReadonlyArray<string>;
189
+ }
166
190
  /** What a channel needs to review its replies; read per reply, as eve binds the mount late. */
167
191
  export interface ChannelReviewOptions {
168
192
  /** `review` of `agent/segmentstream.json`; without it every reply is sent. */
@@ -8,9 +8,11 @@ import { reviewPolicy } from "../../review.mjs";
8
8
  import { It as chatAddressOf, Lt as chatChannel, i as memberIdOf } from "../../../_chunks/principal-DIQHp6AG.mjs";
9
9
  import { a as chatEvent, r as chatArchive } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
10
10
  import { stampedChat } from "../chat-recorder.mjs";
11
+ import { adapterView } from "../adapter-view.mjs";
11
12
  import { appOrigin } from "../environment.mjs";
13
+ import { isToolReplyPart } from "../reply-part.mjs";
12
14
  import { agentReplies, agentReviews } from "./client.mjs";
13
- import { _ as withCaptions, h as partFiles, m as filesAfterReply, n as completionKind, p as fileGroups } from "../../../_chunks/silent-CWcAjHwt.mjs";
15
+ import { _ as withCaptions, h as partFiles, m as filesAfterReply, n as completionKind, p as fileGroups } from "../../../_chunks/silent-DwObe1UV.mjs";
14
16
  import { heldReply, proposedReply, repliesReviewed, reviewOf, reviewOutcome } from "./hold.mjs";
15
17
  import { judgeReply, readChat } from "./judge.mjs";
16
18
  const VERDICTS_REMEMBERED = 512;
@@ -80,7 +82,11 @@ function replyReview(options) {
80
82
  if (!repliesReviewed(options.settings(), input.principal) || review.mode === "never") return true;
81
83
  const files = input.files?.files ?? [];
82
84
  const text = withCaptions(input.text, input.files?.captions ?? []);
83
- const outcome = await verdictOf(input, review, text);
85
+ const outcome = input.fallback === true ? {
86
+ send: false,
87
+ mode: review.mode === "always" ? "always" : "whenUnsure",
88
+ confidence: null
89
+ } : await verdictOf(input, review, text);
84
90
  const captions = (input.files?.captions ?? []).join("\n\n");
85
91
  const verdict = outcome.send && files.length > 0 && (options.sendFiles === void 0 || captions.length > 1024) ? {
86
92
  send: false,
@@ -140,7 +146,7 @@ function replyReview(options) {
140
146
  const review = reviewOf(settings, input.principal);
141
147
  const files = input.files?.files ?? [];
142
148
  const captions = (input.files?.captions ?? []).map((caption) => caption.trim()).filter((caption) => caption !== "");
143
- const confidence = review.mode === "whenUnsure" ? (await verdictOf(input, review, withCaptions(input.text, captions))).confidence ?? null : null;
149
+ const confidence = review.mode === "whenUnsure" && input.fallback !== true ? (await verdictOf(input, review, withCaptions(input.text, captions))).confidence ?? null : null;
144
150
  const policy = reviewPolicy(settings);
145
151
  const [first, ...rest] = fileGroups({
146
152
  files,
@@ -155,6 +161,7 @@ function replyReview(options) {
155
161
  ...group !== void 0 && group === first && captions.length > 0 ? { caption: captions.join("\n\n") } : {},
156
162
  ...group === void 0 ? {} : { files: group.files },
157
163
  ...input.recipients === void 0 ? {} : { recipients: input.recipients },
164
+ ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo },
158
165
  review: policy,
159
166
  confidence,
160
167
  ...input.maxLength === void 0 ? {} : { maxLength: input.maxLength }
@@ -225,14 +232,16 @@ function withReviewedReplies(channel, review, archive) {
225
232
  const text = typeof event.data.value === "string" ? event.data.value : "";
226
233
  if (event.data.kind !== "text" || event.data.phase !== "reply" || event.data.interrupted === true || text.trim() === "" || !review().reviewed(principal)) return completed(event, context);
227
234
  const turnId = event.scope?.turnId ?? context.session.turn?.id ?? null;
228
- const files = turnId === null || context.view === void 0 || completionKind(text) !== "reply" ? void 0 : partFiles(context.view, turnId, event.data.partId);
235
+ const view = turnId === null || completionKind(text) !== "reply" ? void 0 : await adapterView(event, context);
236
+ const files = turnId === null || view === void 0 ? void 0 : partFiles(view, turnId, event.data.partId);
229
237
  if (!await review().sendOrHold({
230
238
  principal,
231
239
  sessionId: context.session.id,
232
240
  turnId,
233
241
  partId: event.data.partId,
234
242
  text,
235
- ...files === void 0 || files.files.length === 0 ? {} : { files }
243
+ ...files === void 0 || files.files.length === 0 ? {} : { files },
244
+ ...isToolReplyPart(event.data.partId) ? {} : { fallback: true }
236
245
  })) return completed({
237
246
  ...event,
238
247
  data: {
@@ -266,7 +275,10 @@ function withReviewedReplies(channel, review, archive) {
266
275
  const settled = adapter["turn.settled"];
267
276
  const settle = async (event, context) => {
268
277
  await settled?.(event, context);
269
- await holdFilesAfterTurn(review(), event, context);
278
+ await holdFilesAfterTurn(review(), event, {
279
+ ...context,
280
+ view: await adapterView(event, context)
281
+ });
270
282
  };
271
283
  return {
272
284
  ...channel,