@segmentstream/agent 0.84.0 → 0.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/_chunks/{build-metadata-CFe-5i6d.mjs → build-metadata-CKp7rmO0.mjs} +1 -1
  3. package/dist/_chunks/silent-C9x3GcMg.mjs +262 -0
  4. package/dist/extension/channels/email.mjs +3 -1
  5. package/dist/extension/channels/slack.mjs +3 -1
  6. package/dist/extension/channels/telegram.mjs +3 -1
  7. package/dist/extension/channels/whatsapp.mjs +3 -1
  8. package/dist/extension/lib/attachments-dispatch.d.ts +23 -0
  9. package/dist/extension/lib/attachments-dispatch.mjs +79 -0
  10. package/dist/extension/lib/build-metadata.mjs +1 -1
  11. package/dist/extension/lib/chat-recorder.mjs +1 -1
  12. package/dist/extension/lib/email/channel.d.ts +2 -0
  13. package/dist/extension/lib/email/channel.mjs +39 -5
  14. package/dist/extension/lib/evals.d.ts +3 -1
  15. package/dist/extension/lib/evals.mjs +3 -1
  16. package/dist/extension/lib/review/client.mjs +5 -0
  17. package/dist/extension/lib/review/files.d.ts +101 -0
  18. package/dist/extension/lib/review/files.mjs +7 -0
  19. package/dist/extension/lib/review/hold.d.ts +7 -0
  20. package/dist/extension/lib/review/hold.mjs +1 -0
  21. package/dist/extension/lib/review/judge.d.ts +2 -0
  22. package/dist/extension/lib/review/judge.mjs +1 -0
  23. package/dist/extension/lib/review/reply.d.ts +66 -0
  24. package/dist/extension/lib/review/reply.mjs +90 -8
  25. package/dist/extension/lib/telegram/adapter.mjs +9 -4
  26. package/dist/extension/lib/telegram/health.mjs +1 -1
  27. package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
  28. package/dist/extension/lib/telegram/routing-context.mjs +1 -1
  29. package/dist/extension/lib/telegram/silent.mjs +1 -84
  30. package/dist/extension/lib/whatsapp/adapter.mjs +1 -1
  31. package/dist/extension/lib/workspace-channel/channel.mjs +23 -4
  32. package/dist/extension/tools/attachments_send.mjs +18 -38
  33. package/package.json +2 -2
@@ -0,0 +1,101 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import { type SessionView } from "eve/events";
3
+ import type { DocumentReference } from "../sent-files.js";
4
+ import { type Environment } from "../environment.js";
5
+ import { type RuntimeToken } from "../runtime-token.js";
6
+ /** A file attached to a reply, as the ontology read it for the person the reply is for. */
7
+ export interface ReplyFile {
8
+ readonly entity: string;
9
+ readonly id: string;
10
+ readonly property: string;
11
+ readonly filename: string;
12
+ readonly contentType: string;
13
+ readonly size: number;
14
+ }
15
+ /** The files a reply carries, in order, and the captions their calls gave. */
16
+ export interface ReplyFiles {
17
+ readonly files: ReadonlyArray<ReplyFile>;
18
+ readonly captions: ReadonlyArray<string>;
19
+ }
20
+ /** What `attachments_send` answers in a reviewed chat: nothing sent, the files promised. */
21
+ export interface AttachedFiles {
22
+ readonly attached: true;
23
+ readonly files: ReadonlyArray<ReplyFile>;
24
+ readonly caption?: string;
25
+ }
26
+ /** Every file the turn attached: a channel that sends the turn's reply as one message. */
27
+ export declare function turnFiles(view: SessionView, turnId: string): ReplyFiles;
28
+ /**
29
+ * The files that go with reply part `partId`: those attached after the turn's previous reply part
30
+ * began and before this one did. Files attached after the turn's last reply part are
31
+ * {@link filesAfterReply}.
32
+ */
33
+ export declare function partFiles(view: SessionView, turnId: string, partId: string): ReplyFiles;
34
+ /**
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.
37
+ */
38
+ export declare function filesAfterReply(view: SessionView, turnId: string): ReplyFiles;
39
+ /** The most files one draft holds, as the ontology's `agent_draft` takes them. */
40
+ export declare const DRAFT_FILES_LIMIT = 10;
41
+ /** The most characters of captions a passed reply's files carry, as the narrowest channel takes. */
42
+ export declare const CAPTION_LIMIT = 1024;
43
+ /**
44
+ * A reply's files in groups a draft or one send takes: calls each within the limit may together
45
+ * pass it. The captions go with the first group, as they would with the reply.
46
+ */
47
+ export declare function fileGroups(files: ReplyFiles): ReadonlyArray<ReplyFiles>;
48
+ /** The reply's text with the captions its files' calls gave, as the person reads it. */
49
+ export declare function withCaptions(text: string, captions: ReadonlyArray<string>): string;
50
+ /** Why the ontology refused to let files go with a reply in a reviewed chat. */
51
+ export declare class ReplyFilesRefused extends Error {
52
+ /**
53
+ * `unsupported` when the ontology holds no files with a draft, else its refusal, such as
54
+ * `file_unavailable` or `too_many_files`.
55
+ */
56
+ readonly code: string;
57
+ readonly status: number;
58
+ readonly index?: number | undefined;
59
+ readonly name = "ReplyFilesRefused";
60
+ constructor(
61
+ /**
62
+ * `unsupported` when the ontology holds no files with a draft, else its refusal, such as
63
+ * `file_unavailable` or `too_many_files`.
64
+ */
65
+ code: string, status: number, index?: number | undefined);
66
+ }
67
+ /**
68
+ * Asks the ontology whether a reply to `principal` may carry these files: each read as the person
69
+ * the reply is for and checked against the chat's channel, as holding the reply will check them.
70
+ * Resolves the files as it read them; rejects with {@link ReplyFilesRefused}. An ontology that holds
71
+ * no files with a draft answers 404, which is `unsupported`: the files are never sent unreviewed.
72
+ */
73
+ export declare function checkReplyFiles(input: {
74
+ readonly origin: string;
75
+ readonly token: RuntimeToken;
76
+ readonly fetch?: typeof fetch;
77
+ readonly principal: SessionAuthContext | null;
78
+ readonly files: ReadonlyArray<DocumentReference>;
79
+ }): Promise<ReadonlyArray<ReplyFile>>;
80
+ /** Why `attachments_send` attached nothing, as every channel's refusal reads. */
81
+ export interface AttachRefusal {
82
+ readonly error: string;
83
+ readonly detail: string;
84
+ readonly reference: string;
85
+ readonly index?: number;
86
+ }
87
+ /**
88
+ * `attachments_send` in a reviewed chat: the files join the turn's reply instead of being sent,
89
+ * once the ontology checked them as the person may read them and as the channel sends them.
90
+ * Answers what it attached, or a refusal with the workspace's attachment failure text: in a
91
+ * deployment that is not production, which sends no files, an ontology that holds no files with a
92
+ * draft, or a file it refused.
93
+ */
94
+ export declare function attachToReply(input: {
95
+ readonly files: ReadonlyArray<DocumentReference>;
96
+ readonly caption?: string;
97
+ readonly principal: SessionAuthContext | null;
98
+ readonly environment?: Environment;
99
+ readonly token?: RuntimeToken;
100
+ readonly fetch?: typeof fetch;
101
+ }): Promise<AttachedFiles | AttachRefusal>;
@@ -0,0 +1,7 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ export { 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-C9x3GcMg.mjs";
@@ -1,5 +1,6 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
2
  import { type ReviewSettings, type Review } from "../../review.js";
3
+ import type { ReplyFile } from "./files.js";
3
4
  /**
4
5
  * Whether the agent sends a reply itself or holds it for a member to review, by the review of the
5
6
  * person it replies to: the session's current principal, whose roles `review` reads.
@@ -46,6 +47,11 @@ export interface HeldReply {
46
47
  readonly memberId: string;
47
48
  readonly sessionId: string;
48
49
  readonly text: string;
50
+ /**
51
+ * Record files the reply carries, as the ontology read them for its member, which approval
52
+ * sends with the text. Absent for a reply of text alone, which any ontology service holds.
53
+ */
54
+ readonly files?: ReadonlyArray<ReplyFile>;
49
55
  readonly mode: "always" | "whenUnsure";
50
56
  /** The decision model's probability that staff would send it as written; null when unjudged. */
51
57
  readonly confidence: number | null;
@@ -86,6 +92,7 @@ export declare function heldReply(input: {
86
92
  readonly sessionId: string;
87
93
  readonly partId: string;
88
94
  readonly text: string;
95
+ readonly files?: ReadonlyArray<ReplyFile>;
89
96
  readonly turnId?: string | null;
90
97
  readonly outcome: Extract<ReviewOutcome, {
91
98
  send: false;
@@ -60,6 +60,7 @@ function heldReply(input) {
60
60
  memberId,
61
61
  sessionId: input.sessionId,
62
62
  text: input.text,
63
+ ...input.files === void 0 || input.files.length === 0 ? {} : { files: input.files },
63
64
  mode: input.outcome.mode,
64
65
  confidence: input.outcome.confidence,
65
66
  ...input.turnId === void 0 || input.turnId === null || input.turnId === "" ? {} : { turnId: input.turnId }
@@ -47,6 +47,8 @@ export declare function judgeReply(input: {
47
47
  readonly model: string;
48
48
  readonly chat: ReadonlyArray<string>;
49
49
  readonly reply: string;
50
+ /** The names of the files the reply carries, which the judge weighs with its text. */
51
+ readonly files?: ReadonlyArray<string>;
50
52
  readonly criteria?: string;
51
53
  readonly timeoutMs?: number;
52
54
  }): Promise<number | undefined>;
@@ -57,6 +57,7 @@ async function judgeReply(input) {
57
57
  state: {
58
58
  chat: input.chat,
59
59
  reply: input.reply,
60
+ ...input.files === void 0 || input.files.length === 0 ? {} : { files: input.files },
60
61
  criteria: input.criteria ?? ""
61
62
  },
62
63
  questions: reviewQuestions(),
@@ -1,10 +1,12 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
+ import type { SessionView } from "eve/events";
2
3
  import type { ReviewSettings } from "../../review.js";
3
4
  import { type ChatArchive } from "../chat-archive.js";
4
5
  import { type Environment } from "../environment.js";
5
6
  import type { RuntimeToken } from "../runtime-token.js";
6
7
  import { type HoldReply } from "./hold.js";
7
8
  import { type ReviewDecideFunction } from "./judge.js";
9
+ import { type ReplyFiles } from "./files.js";
8
10
  /**
9
11
  * Review of a channel's final replies: the reply of a chat whose review is not `never` is
10
12
  * judged or held before the channel sends it, and held replies become `agent_draft` records. The
@@ -29,7 +31,38 @@ export interface ReplyReview {
29
31
  readonly to: ReadonlyArray<string>;
30
32
  readonly cc: ReadonlyArray<string>;
31
33
  };
34
+ /**
35
+ * The files `attachments_send` attached to this reply, which the judge weighs with it and a held
36
+ * reply carries into its draft. Their captions join the text, as the person reads them. When it
37
+ * answers true with files, the channel sends them after the text.
38
+ */
39
+ readonly files?: ReplyFiles;
32
40
  }): Promise<boolean>;
41
+ /**
42
+ * Holds files the turn attached that no reply carries, such as a reply of files alone: never
43
+ * judged and never sent unreviewed. Throws when they could not be held.
44
+ */
45
+ /**
46
+ * Sends the files a reply the judge passed carries, after the channel sent its text, with their
47
+ * captions, by the channel's own sender.
48
+ */
49
+ sendFiles(input: {
50
+ readonly principal: SessionAuthContext | null | undefined;
51
+ readonly sessionId: string;
52
+ readonly turnId: string | null;
53
+ readonly partId: string;
54
+ readonly files: ReplyFiles;
55
+ }): Promise<void>;
56
+ holdFiles(input: {
57
+ readonly principal: SessionAuthContext | null | undefined;
58
+ readonly sessionId: string;
59
+ readonly turnId: string;
60
+ readonly files: ReplyFiles;
61
+ readonly recipients?: {
62
+ readonly to: ReadonlyArray<string>;
63
+ readonly cc: ReadonlyArray<string>;
64
+ };
65
+ }): Promise<void>;
33
66
  }
34
67
  export declare function replyReview(options: {
35
68
  readonly settings: () => ReviewSettings | undefined;
@@ -38,6 +71,11 @@ export declare function replyReview(options: {
38
71
  readonly model: () => string;
39
72
  readonly archive: ChatArchive;
40
73
  readonly hold: HoldReply;
74
+ /**
75
+ * Sends a passed reply's files in the chat; without it a reply with files is always held, so
76
+ * they are never lost or sent unreviewed.
77
+ */
78
+ readonly sendFiles?: SendReplyFiles;
41
79
  }): ReplyReview;
42
80
  /**
43
81
  * An eve channel whose final replies are reviewed: its `content.completed` handler sends a reply
@@ -48,6 +86,32 @@ export declare function replyReview(options: {
48
86
  * eve's Chat SDK and Slack channels, whose handlers live on `channel.adapter`.
49
87
  */
50
88
  export declare function withReviewedReplies<Channel extends object>(channel: Channel, review: () => ReplyReview, archive?: () => ChatArchive): Channel;
89
+ /**
90
+ * At a turn's end, holds the files it attached that no reply part carried, such as a reply of files
91
+ * alone, in a chat whose replies are reviewed; a failed or interrupted turn drops them.
92
+ */
93
+ export declare function holdFilesAfterTurn(review: ReplyReview | undefined, event: {
94
+ readonly data: {
95
+ readonly turnId: string;
96
+ readonly outcome: string;
97
+ };
98
+ }, context: {
99
+ readonly session: {
100
+ readonly id: string;
101
+ readonly auth: {
102
+ readonly current: SessionAuthContext | null;
103
+ };
104
+ };
105
+ readonly view?: SessionView;
106
+ }): Promise<void>;
107
+ /** Sends the files of a reply the judge passed, in the reply's chat. */
108
+ export type SendReplyFiles = (input: {
109
+ readonly principal: SessionAuthContext | null | undefined;
110
+ readonly sessionId: string;
111
+ readonly turnId: string | null;
112
+ readonly partId: string;
113
+ readonly files: ReplyFiles;
114
+ }) => Promise<unknown>;
51
115
  /** What a channel needs to review its replies; read per reply, as eve binds the mount late. */
52
116
  export interface ChannelReviewOptions {
53
117
  /** `review` of `agent/segmentstream.json`; without it every reply is sent. */
@@ -59,6 +123,8 @@ export interface ChannelReviewOptions {
59
123
  readonly hold?: HoldReply;
60
124
  /** The chat archive; tests pass a fake. */
61
125
  readonly archive?: ChatArchive;
126
+ /** Sends a passed reply's files; without it such a reply is held. */
127
+ readonly sendFiles?: SendReplyFiles;
62
128
  }
63
129
  /** A channel's {@link ReplyReview}, reporting held replies to the workspace's ontology service. */
64
130
  export declare function channelReview(options: ChannelReviewOptions, runtime: {
@@ -9,6 +9,7 @@ import { a as chatEvent, r as chatArchive } from "../../../_chunks/chat-archive-
9
9
  import { stampedChat } from "../chat-recorder.mjs";
10
10
  import { appOrigin } from "../environment.mjs";
11
11
  import { agentReviews } from "./client.mjs";
12
+ import { _ as withCaptions, h as partFiles, m as filesAfterReply, n as completionKind, p as fileGroups } from "../../../_chunks/silent-C9x3GcMg.mjs";
12
13
  import { heldReply, repliesReviewed, reviewOf, reviewOutcome } from "./hold.mjs";
13
14
  import { judgeReply, readChat } from "./judge.mjs";
14
15
  const VERDICTS_REMEMBERED = 512;
@@ -40,16 +41,48 @@ function replyReview(options) {
40
41
  };
41
42
  return {
42
43
  reviewed: (principal) => repliesReviewed(options.settings(), principal),
44
+ async sendFiles(input) {
45
+ for (const [index, files] of fileGroups(input.files).entries()) await options.sendFiles({
46
+ ...input,
47
+ partId: index === 0 ? input.partId : `${input.partId}:${index}`,
48
+ files
49
+ });
50
+ },
51
+ async holdFiles(input) {
52
+ const review = reviewOf(options.settings(), input.principal);
53
+ if (review.mode === "never") return;
54
+ for (const [index, files] of fileGroups(input.files).entries()) {
55
+ const held = heldReply({
56
+ principal: input.principal,
57
+ sessionId: input.sessionId,
58
+ partId: index === 0 ? `${input.turnId}:files` : `${input.turnId}:files:${index}`,
59
+ turnId: input.turnId,
60
+ text: withCaptions("", files.captions),
61
+ files: files.files,
62
+ ...input.recipients === void 0 ? {} : { recipients: input.recipients },
63
+ outcome: {
64
+ send: false,
65
+ mode: review.mode,
66
+ confidence: null
67
+ }
68
+ });
69
+ if (held === void 0) throw new Error("Files under review have no chat or member to be held for.");
70
+ await options.hold(held);
71
+ }
72
+ },
43
73
  async sendOrHold(input) {
44
74
  const review = reviewOf(options.settings(), input.principal);
45
75
  if (!repliesReviewed(options.settings(), input.principal) || review.mode === "never") return true;
76
+ const files = input.files?.files ?? [];
77
+ const text = withCaptions(input.text, input.files?.captions ?? []);
46
78
  const coordinates = reviewedChat(input.principal);
47
79
  const key = `${input.sessionId}:${input.partId}`;
48
80
  const outcome = verdicts.get(key) ?? remember(key, await reviewOutcome(review, async (criteria) => judgeReply({
49
81
  decide: options.decide,
50
82
  model: options.model(),
51
83
  chat: coordinates === void 0 ? [] : await readChat(options.archive, coordinates),
52
- reply: input.text,
84
+ reply: text,
85
+ ...files.length === 0 ? {} : { files: files.map((file) => file.filename) },
53
86
  ...criteria === void 0 ? {} : { criteria }
54
87
  }), (error) => console.error("[segmentstream] reply review judge failed; the reply is held", {
55
88
  sessionId: input.sessionId,
@@ -70,7 +103,13 @@ function replyReview(options) {
70
103
  argsSummary: JSON.stringify(summary)
71
104
  }));
72
105
  };
73
- if (outcome.send) {
106
+ const captions = (input.files?.captions ?? []).join("\n\n");
107
+ const verdict = outcome.send && files.length > 0 && (options.sendFiles === void 0 || captions.length > 1024) ? {
108
+ send: false,
109
+ mode: review.mode === "always" ? "always" : "whenUnsure",
110
+ confidence: outcome.confidence ?? null
111
+ } : outcome;
112
+ if (verdict.send) {
74
113
  await record("review_passed", {
75
114
  mode: review.mode,
76
115
  confidence: outcome.confidence ?? null,
@@ -78,15 +117,31 @@ function replyReview(options) {
78
117
  });
79
118
  return true;
80
119
  }
120
+ const [first, ...rest] = fileGroups({
121
+ files,
122
+ captions: []
123
+ });
81
124
  const held = heldReply({
82
125
  ...input,
83
- outcome
126
+ text,
127
+ files: first?.files ?? [],
128
+ outcome: verdict
84
129
  });
85
130
  if (held === void 0) throw new Error("A reply under review has no chat or member to be held for.");
86
131
  await options.hold(held);
132
+ for (const [index, group] of rest.entries()) {
133
+ const more = heldReply({
134
+ ...input,
135
+ partId: `${input.partId}:files:${index + 1}`,
136
+ text: "",
137
+ files: group.files,
138
+ outcome: verdict
139
+ });
140
+ if (more !== void 0) await options.hold(more);
141
+ }
87
142
  await record("review_held", {
88
- mode: outcome.mode,
89
- confidence: outcome.confidence,
143
+ mode: verdict.mode,
144
+ confidence: verdict.confidence,
90
145
  ...review.mode === "whenUnsure" ? { minConfidence: review.minConfidence } : {}
91
146
  });
92
147
  return false;
@@ -102,12 +157,14 @@ function withReviewedReplies(channel, review, archive) {
102
157
  const text = typeof event.data.value === "string" ? event.data.value : "";
103
158
  if (event.data.kind !== "text" || event.data.phase !== "reply" || event.data.interrupted === true || text.trim() === "" || !review().reviewed(principal)) return completed(event, context);
104
159
  const turnId = event.scope?.turnId ?? context.session.turn?.id ?? null;
160
+ const files = turnId === null || context.view === void 0 || completionKind(text) !== "reply" ? void 0 : partFiles(context.view, turnId, event.data.partId);
105
161
  if (!await review().sendOrHold({
106
162
  principal,
107
163
  sessionId: context.session.id,
108
164
  turnId,
109
165
  partId: event.data.partId,
110
- text
166
+ text,
167
+ ...files === void 0 || files.files.length === 0 ? {} : { files }
111
168
  })) return completed({
112
169
  ...event,
113
170
  data: {
@@ -116,6 +173,13 @@ function withReviewedReplies(channel, review, archive) {
116
173
  }
117
174
  }, context);
118
175
  await completed(event, context);
176
+ if (files !== void 0 && files.files.length > 0) await review().sendFiles({
177
+ principal,
178
+ sessionId: context.session.id,
179
+ turnId,
180
+ partId: event.data.partId,
181
+ files
182
+ });
119
183
  const chat = reviewedChat(principal);
120
184
  const memberId = memberIdOf(principal);
121
185
  if (chat !== void 0 && archive !== void 0) await archive().append(chatEvent({
@@ -131,14 +195,31 @@ function withReviewedReplies(channel, review, archive) {
131
195
  status: "completed"
132
196
  }));
133
197
  };
198
+ const settled = adapter["turn.settled"];
199
+ const settle = async (event, context) => {
200
+ await settled?.(event, context);
201
+ await holdFilesAfterTurn(review(), event, context);
202
+ };
134
203
  return {
135
204
  ...channel,
136
205
  adapter: {
137
206
  ...adapter,
138
- "content.completed": handler
207
+ "content.completed": handler,
208
+ "turn.settled": settle
139
209
  }
140
210
  };
141
211
  }
212
+ async function holdFilesAfterTurn(review, event, context) {
213
+ const principal = context.session.auth.current;
214
+ if (review === void 0 || event.data.outcome !== "completed" || context.view === void 0 || !review.reviewed(principal)) return;
215
+ const files = filesAfterReply(context.view, event.data.turnId);
216
+ if (files.files.length > 0) await review.holdFiles({
217
+ principal,
218
+ sessionId: context.session.id,
219
+ turnId: event.data.turnId,
220
+ files
221
+ });
222
+ }
142
223
  function channelReview(options, runtime) {
143
224
  const transport = {
144
225
  token: runtime.token,
@@ -155,6 +236,7 @@ function channelReview(options, runtime) {
155
236
  decide: options.decide,
156
237
  model: options.model,
157
238
  archive,
239
+ ...options.sendFiles === void 0 ? {} : { sendFiles: options.sendFiles },
158
240
  hold: options.hold ?? ((reply) => agentReviews({
159
241
  origin: appOrigin(runtime.environment),
160
242
  ...transport
@@ -162,4 +244,4 @@ function channelReview(options, runtime) {
162
244
  })
163
245
  };
164
246
  }
165
- export { channelReview, replyReview, withReviewedReplies };
247
+ export { channelReview, holdFilesAfterTurn, replyReview, withReviewedReplies };
@@ -10,7 +10,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-CFe-5i6d.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CKp7rmO0.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -26,11 +26,11 @@ import { runtimeToken } from "../runtime-token.mjs";
26
26
  import { botIdentityCache, proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
27
27
  import { handleConfirmationCallback, telegramConfirmationEvents } from "./confirmations.mjs";
28
28
  import { confirmationLocale } from "./confirmation-text.mjs";
29
+ import { isWorkspaceCallback } from "../workspace-action.mjs";
29
30
  import { telegramAppLinkContext } from "./app-links.mjs";
30
31
  import { gatewayImageDescriber } from "../inbound-media/images.mjs";
31
32
  import { chatMediaPlan, gatewayMediaCapabilities, sessionModel } from "../inbound-media/plan.mjs";
32
33
  import { gatewayTranscriber } from "../inbound-media/speech.mjs";
33
- import { isWorkspaceCallback } from "../workspace-action.mjs";
34
34
  import { agentChats, channelChats } from "../chats.mjs";
35
35
  import { currentChannel, withNamedRoutes, withSessionChannels } from "../channel-scope.mjs";
36
36
  import { handleInboundMessage } from "./inbound.mjs";
@@ -39,8 +39,8 @@ import { TELEGRAM_PLACEHOLDER_TOKEN, TELEGRAM_PROXY_ORIGIN, telegramProxyFetch }
39
39
  import { healthRoute } from "./health.mjs";
40
40
  import { decisionRouter } from "../group-routing/router.mjs";
41
41
  import { scopedAddress } from "./sessions.mjs";
42
- import { interimTexts, isNoReplyCall, replyDelivery } from "./silent.mjs";
43
- import { channelReview } from "../review/reply.mjs";
42
+ import { a as isNoReplyCall, i as interimTexts, s as replyDelivery } from "../../../_chunks/silent-C9x3GcMg.mjs";
43
+ import { channelReview, holdFilesAfterTurn } from "../review/reply.mjs";
44
44
  import { telegramSendScope } from "./send-queue.mjs";
45
45
  import { telegramFailureEvents } from "./turn-errors.mjs";
46
46
  import { withDeliveryDiagnostics } from "./delivery-diagnostics.mjs";
@@ -403,6 +403,11 @@ function segmentstreamTelegram(options) {
403
403
  await failureEvents["interaction.settled"]?.(event, ctx);
404
404
  await approvalEvents["interaction.settled"]?.(event, ctx);
405
405
  },
406
+ async "turn.settled"(event, ctx) {
407
+ await failureEvents["turn.settled"]?.(event, ctx);
408
+ await approvalEvents["turn.settled"]?.(event, ctx);
409
+ await holdFilesAfterTurn(review, event, ctx);
410
+ },
406
411
  async "content.completed"(event, context) {
407
412
  const channel = context.channel;
408
413
  const message = typeof event.data.value === "string" ? event.data.value : "";
@@ -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 { t as agentBuild } from "../../../_chunks/build-metadata-CFe-5i6d.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CKp7rmO0.mjs";
8
8
  import { runtimeRequestFailure } from "./runtime-request.mjs";
9
9
  import { GET } from "eve/channels";
10
10
  const HEALTH_ROUTE = "/eve/v1/telegram/health";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { E as OntologyActionNotPermitted, Et as principalRuntimeSource, L as needsConfirmation, Ot as runtimeEnvelope, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as telegramRuntimeSource } from "../../../_chunks/principal-C1g8wCIg.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-CFe-5i6d.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CKp7rmO0.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { agentMessage } from "../group-routing/messages.mjs";
8
8
  import "../group-routing/router.mjs";
9
- import { isSilentReply } from "./silent.mjs";
9
+ import { o as isSilentReply } from "../../../_chunks/silent-C9x3GcMg.mjs";
10
10
  import { questionsFromHistory, routingConfirmationState, routingConfirmations } from "./confirmations.mjs";
11
11
  import { questionKey } from "../questions.mjs";
12
12
  import { archivedRoutingMessages } from "../group-routing/routing-context.mjs";
@@ -4,87 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { confirmationLocale } from "./confirmation-text.mjs";
8
- import { _t as customerMessage, mt as currentLocale, pt as TelegramDeliveryError, xt as reportTelegramError } from "../../../_chunks/principal-C1g8wCIg.mjs";
9
- import { splitTelegramText } from "./format.mjs";
10
- import { inTelegramSendQueue } from "./send-queue.mjs";
11
- const NO_REPLY_TOOL = "no_reply";
12
- function isNoReplyCall(name) {
13
- const parts = name?.split("__") ?? [];
14
- return parts.length <= 2 && parts.at(-1) === NO_REPLY_TOOL;
15
- }
16
- const SILENT_MARKERS = new Set(["[silent]", "no_reply"]);
17
- function isSilentReply(text) {
18
- return SILENT_MARKERS.has(text.trim().toLowerCase());
19
- }
20
- function completionKind(message, finishReason) {
21
- if (finishReason === "tool-calls") return "tool_calls";
22
- if (message === void 0 || message === null || message === "") return "empty";
23
- if (message.trim() === "") return "whitespace";
24
- return isSilentReply(message) ? "silent_marker" : "reply";
25
- }
26
- const INTERIM_TURNS = 256;
27
- function interimTexts(limit = 256) {
28
- const turns = new Map();
29
- return {
30
- has: (turn, text) => turns.get(turn)?.has(text) ?? false,
31
- add(turn, text) {
32
- const texts = turns.get(turn) ?? new Set();
33
- turns.delete(turn);
34
- turns.set(turn, texts.add(text));
35
- for (const oldest of turns.keys()) {
36
- if (turns.size <= limit) break;
37
- turns.delete(oldest);
38
- }
39
- }
40
- };
41
- }
42
- function replyDelivery(scope = () => "telegram", interim, review, identifiers = () => "block") {
43
- return async (event, context) => {
44
- if (event.data.kind !== "text" || event.data.interrupted) return;
45
- const channel = context.channel;
46
- const textValue = typeof event.data.value === "string" ? event.data.value : "";
47
- const kind = completionKind(textValue, event.data.phase === "reply" ? "stop" : "tool-calls");
48
- const interimOn = interim?.enabled() === true;
49
- const isInterim = kind === "tool_calls" && interimOn && completionKind(textValue) === "reply";
50
- if (kind !== "reply" && !isInterim) return;
51
- const reviewed = review?.reviewed(context.session?.auth.current) === true;
52
- if (reviewed && isInterim) return;
53
- const turn = interimOn && typeof event.scope?.turnId === "string" && event.scope?.turnId !== "" ? JSON.stringify([context.session?.id ?? "", event.scope?.turnId]) : void 0;
54
- const key = textValue.trim();
55
- if (turn !== void 0 && interim.delivered.has(turn, key)) return;
56
- if (reviewed && !await review.sendOrHold({
57
- principal: context.session?.auth.current,
58
- sessionId: context.session?.id ?? "",
59
- turnId: event.scope?.turnId ?? null,
60
- partId: event.data.partId,
61
- text: textValue
62
- })) return;
63
- const message = customerMessage(textValue, confirmationLocale(context.session?.auth.current ?? null, currentLocale()), identifiers());
64
- const replyTo = (context.session?.auth.current)?.attributes.replyToMessageId;
65
- const replyParameters = typeof replyTo === "string" && /^[1-9]\d*$/u.test(replyTo) ? { reply_parameters: {
66
- message_id: Number(replyTo),
67
- allow_sending_without_reply: true
68
- } } : {};
69
- await inTelegramSendQueue(scope(), channel.telegram.chatId, async () => {
70
- const messageIds = [];
71
- try {
72
- for (const part of splitTelegramText(message)) {
73
- const result = await channel.telegram.post({
74
- ...part,
75
- ...replyParameters
76
- });
77
- if (!/^[1-9]\d*$/u.test(result.id)) throw new Error("Telegram did not acknowledge the reply with a message id.");
78
- messageIds.push(Number(result.id));
79
- }
80
- } catch (error) {
81
- const reference = reportTelegramError(isInterim ? "telegram_interim_delivery_failed" : "telegram_reply_delivery_failed", error, { messageIds });
82
- throw new TelegramDeliveryError(reference, error instanceof TelegramDeliveryError ? error.delivery : "unknown", messageIds);
83
- }
84
- return messageIds;
85
- });
86
- if (isInterim && turn !== void 0) interim.delivered.add(turn, key);
87
- };
88
- }
89
- const deliverUnlessSilent = replyDelivery();
90
- export { INTERIM_TURNS, completionKind, deliverUnlessSilent, interimTexts, isNoReplyCall, isSilentReply, replyDelivery };
7
+ export { t as INTERIM_TURNS, n as completionKind, r as deliverUnlessSilent, i as interimTexts, a as isNoReplyCall, o as isSilentReply, s as replyDelivery } from "../../../_chunks/silent-C9x3GcMg.mjs";
@@ -30,9 +30,9 @@ import { collectSent, noteSent, recordSent } from "./sent.mjs";
30
30
  import { STATUSES_HEADER, STATUSES_RECORDED } from "./statuses.mjs";
31
31
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
32
32
  import { AsyncLocalStorage } from "node:async_hooks";
33
- import { Actions, Card, CardText, ConsoleLogger, LinkButton, convertEmojiPlaceholders } from "chat";
34
33
  import { createMemoryState } from "@chat-adapter/state-memory";
35
34
  import { WhatsAppAdapter, WhatsAppApiError } from "@chat-adapter/whatsapp";
35
+ import { Actions, Card, CardText, ConsoleLogger, LinkButton, convertEmojiPlaceholders } from "chat";
36
36
  import { chatSdkChannel, messageContentOf } from "eve/channels/chat-sdk";
37
37
  const WHATSAPP_AUTHENTICATOR = "segmentstream-whatsapp";
38
38
  const WHATSAPP_PROXY_ORIGIN = "https://whatsapp.segmentstream.invalid";