@segmentstream/agent 0.103.1 → 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 +35 -0
  2. package/README.md +6 -0
  3. package/dist/_chunks/{build-metadata-ByWwCQd1.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 +3 -2
@@ -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,
@@ -8,6 +8,7 @@ import { redactDiagnostic } from "../diagnostics.mjs";
8
8
  import { AgentIdentityError, refusal } from "../identities.mjs";
9
9
  import { readChat } from "./judge.mjs";
10
10
  import { postDraftRoute } from "./routes.mjs";
11
+ import { toolReplyCallOf } from "../reply-part.mjs";
11
12
  import { ontologyDeploymentHeaders } from "../environment.mjs";
12
13
  import { EMAIL_RECIPIENTS_LIMIT, isEmailAddress } from "@segmentstream/ontology/email";
13
14
  const REVISION_AUTHENTICATOR = "segmentstream-review-revision";
@@ -259,12 +260,13 @@ function shown(value) {
259
260
  }
260
261
  async function turnLookups(stream, sessionId, partId) {
261
262
  const turns = new Map();
263
+ const replyCall = toolReplyCallOf(partId);
262
264
  let turnId;
263
265
  for await (const event of stream(sessionId)) {
264
266
  const turn = event.scope?.turnId;
265
267
  if (turn === void 0) continue;
266
268
  const data = event.data;
267
- if (turn === partId || event.type === "content.completed" && data.partId === partId && turnId === void 0) turnId = turn;
269
+ if (turn === partId || turnId === void 0 && (event.type === "content.completed" && data.partId === partId || replyCall !== void 0 && event.type === "call.requested" && data.callId === replyCall)) turnId = turn;
268
270
  const calls = turns.get(turn) ?? new Map();
269
271
  turns.set(turn, calls);
270
272
  const callId = typeof data.callId === "string" ? data.callId : void 0;
@@ -26,6 +26,7 @@ import { handleWorkspaceCallback } from "./callbacks.mjs";
26
26
  import { workspaceTriage } from "../triage.mjs";
27
27
  import { pairingNotice } from "./pairing.mjs";
28
28
  import { recordThreadHistory } from "./thread-history.mjs";
29
+ import { withToolReplies } from "../reply.mjs";
29
30
  import { channelReview, withReviewedReplies } from "../review/reply.mjs";
30
31
  import { runtimeToken } from "../runtime-token.mjs";
31
32
  import { r as chatArchive } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
@@ -459,7 +460,7 @@ function segmentstreamSlack(options) {
459
460
  token,
460
461
  ...options.fetch === void 0 ? {} : { fetch: options.fetch }
461
462
  });
462
- const replying = reviewed === void 0 ? channel : withReviewedReplies(channel, () => reviewed.review, () => reviewed.archive);
463
+ const replying = withToolReplies(reviewed === void 0 ? channel : withReviewedReplies(channel, () => reviewed.review, () => reviewed.archive));
463
464
  return {
464
465
  ...withSessionChannels("slack", replying),
465
466
  routes: withNamedRoutes("slack", replying.routes.flatMap((route) => route.transport === "websocket" ? [] : [gatedRoute(route, settings, environment, observe, delivered)]), (name) => options.settings(name) !== null)
@@ -12,7 +12,7 @@ import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
12
12
  import { handleWorkspaceCallback } from "./callbacks.mjs";
13
13
  import { workspaceTriage } from "../triage.mjs";
14
14
  import { telegramText, withTelegramTexts } from "./texts.mjs";
15
- import { t as agentBuild } from "../../../_chunks/build-metadata-ByWwCQd1.mjs";
15
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DkPNOrqc.mjs";
16
16
  import { attachmentLifecycle } from "./lifecycle.mjs";
17
17
  import { manifestOf } from "../../config.mjs";
18
18
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -26,8 +26,8 @@ import { a as captureTelegramFetch, h as telegramChatCapture, i as captureRouteD
26
26
  import { runtimeTokenVerifier } from "../runtime-identity.mjs";
27
27
  import { runtimeToken } from "../runtime-token.mjs";
28
28
  import { botIdentityCache, proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
29
- import { isWorkspaceCallback } from "../workspace-action.mjs";
30
29
  import { handleConfirmationCallback, telegramConfirmationEvents } from "./confirmations.mjs";
30
+ import { isWorkspaceCallback } from "../workspace-action.mjs";
31
31
  import { confirmationLocale } from "./confirmation-text.mjs";
32
32
  import { telegramAppLinkContext } from "./app-links.mjs";
33
33
  import { gatewayImageDescriber } from "../inbound-media/images.mjs";
@@ -41,7 +41,8 @@ import { TELEGRAM_PLACEHOLDER_TOKEN, TELEGRAM_PROXY_ORIGIN, telegramProxyFetch }
41
41
  import { healthRoute } from "./health.mjs";
42
42
  import { decisionRouter } from "../group-routing/router.mjs";
43
43
  import { scopedAddress, senderAddress } from "./sessions.mjs";
44
- import { a as isNoReplyCall, i as interimTexts, s as replyDelivery } from "../../../_chunks/silent-CWcAjHwt.mjs";
44
+ import { a as isNoReplyCall, i as interimTexts, s as replyDelivery } from "../../../_chunks/silent-DwObe1UV.mjs";
45
+ import { supersededByToolReply, toolReplyPart } from "../reply.mjs";
45
46
  import { channelReview, holdFilesAfterTurn } from "../review/reply.mjs";
46
47
  import { telegramSendScope } from "./send-queue.mjs";
47
48
  import { telegramFailureEvents } from "./turn-errors.mjs";
@@ -439,59 +440,63 @@ function segmentstreamTelegram(options) {
439
440
  await approvalEvents["interaction.settled"]?.(event, ctx);
440
441
  },
441
442
  async "turn.settled"(event, ctx) {
443
+ const part = event.data.outcome === "completed" ? toolReplyPart(ctx.view, event.data.turnId) : void 0;
444
+ if (part !== void 0) await completed(part, ctx);
442
445
  await failureEvents["turn.settled"]?.(event, ctx);
443
446
  await approvalEvents["turn.settled"]?.(event, ctx);
444
447
  await holdFilesAfterTurn(review, event, ctx);
445
448
  },
446
- async "content.completed"(event, context) {
447
- const channel = context.channel;
448
- const message = typeof event.data.value === "string" ? event.data.value : "";
449
- const principal = context.session.auth.current;
450
- const taskId = principal?.attributes.taskId;
451
- const configuration = settings().attachmentLifecycle;
452
- if (event.data.kind === "text" && event.data.phase === "reply" && !event.data.interrupted && message && configuration && principal && typeof taskId === "string") try {
453
- const memberId = principal.attributes.memberId;
454
- if (typeof memberId !== "string") throw new Error("A current member is required for completion.");
455
- const result = await attachmentLifecycle({
456
- configuration,
457
- principal,
458
- memberId,
459
- environment,
460
- token,
461
- ...options.fetch ? { fetch: options.fetch } : {},
462
- message: {
463
- chat: { id: channel.telegram.chatId },
464
- messageId: String(principal.attributes.triggeringMessageId ?? principal.attributes.replyToMessageId),
465
- messageThreadId: channel.telegram.messageThreadId,
466
- from: { id: principal.subject ?? "" }
467
- }
468
- })("completed", {
469
- key: taskId,
470
- ...configuration.contextVersion === 2 ? { reply: message } : {},
471
- ...typeof principal.attributes.attachmentDispatchToken === "string" ? { dispatch_token: principal.attributes.attachmentDispatchToken } : {}
472
- });
473
- if (result.message !== void 0 || result.complete === false) event = {
474
- ...event,
475
- data: {
476
- ...event.data,
477
- value: result.message ?? ""
478
- }
479
- };
480
- } catch (error) {
481
- const reference = reportTelegramError("intake_completion_failed", error, {
482
- sessionId: context.session.id,
483
- taskId
484
- });
485
- await channel.telegram.post(failureText(reference));
486
- return;
487
- }
488
- await replyDelivery(() => telegramSendScope(environment, settings().connection), {
489
- enabled: () => settings().interimMessages === true,
490
- delivered: interimDelivered
491
- }, review, () => settings().identifiers ?? "block")(event, context);
492
- }
449
+ "content.completed": (event, context) => completed(event, context)
493
450
  }
494
451
  });
452
+ async function completed(...[event, context]) {
453
+ const channel = context.channel;
454
+ const message = typeof event.data.value === "string" ? event.data.value : "";
455
+ const principal = context.session.auth.current;
456
+ const taskId = principal?.attributes.taskId;
457
+ const configuration = settings().attachmentLifecycle;
458
+ if (supersededByToolReply(event, context)) return;
459
+ if (event.data.kind === "text" && event.data.phase === "reply" && !event.data.interrupted && message && configuration && principal && typeof taskId === "string") try {
460
+ const memberId = principal.attributes.memberId;
461
+ if (typeof memberId !== "string") throw new Error("A current member is required for completion.");
462
+ const result = await attachmentLifecycle({
463
+ configuration,
464
+ principal,
465
+ memberId,
466
+ environment,
467
+ token,
468
+ ...options.fetch ? { fetch: options.fetch } : {},
469
+ message: {
470
+ chat: { id: channel.telegram.chatId },
471
+ messageId: String(principal.attributes.triggeringMessageId ?? principal.attributes.replyToMessageId),
472
+ messageThreadId: channel.telegram.messageThreadId,
473
+ from: { id: principal.subject ?? "" }
474
+ }
475
+ })("completed", {
476
+ key: taskId,
477
+ ...configuration.contextVersion === 2 ? { reply: message } : {},
478
+ ...typeof principal.attributes.attachmentDispatchToken === "string" ? { dispatch_token: principal.attributes.attachmentDispatchToken } : {}
479
+ });
480
+ if (result.message !== void 0 || result.complete === false) event = {
481
+ ...event,
482
+ data: {
483
+ ...event.data,
484
+ value: result.message ?? ""
485
+ }
486
+ };
487
+ } catch (error) {
488
+ const reference = reportTelegramError("intake_completion_failed", error, {
489
+ sessionId: context.session.id,
490
+ taskId
491
+ });
492
+ await channel.telegram.post(failureText(reference));
493
+ return;
494
+ }
495
+ await replyDelivery(() => telegramSendScope(environment, settings().connection), {
496
+ enabled: () => settings().interimMessages === true,
497
+ delivered: interimDelivered
498
+ }, review, () => settings().identifiers ?? "block")(event, context);
499
+ }
495
500
  const adapter = channel.adapter;
496
501
  const fetchTelegramFile = adapter?.fetchFile;
497
502
  async function fetchFile(url, context) {
@@ -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-ByWwCQd1.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DkPNOrqc.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 { At as telegramRuntimeSource, Dt as principalRuntimeSource, E as OntologyActionNotPermitted, L as needsConfirmation, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as runtimeEnvelope } from "../../../_chunks/principal-DIQHp6AG.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-ByWwCQd1.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DkPNOrqc.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 { o as isSilentReply } from "../../../_chunks/silent-CWcAjHwt.mjs";
9
+ import { o as isSilentReply } from "../../../_chunks/silent-DwObe1UV.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";
@@ -37,7 +37,9 @@ export interface InterimMessages {
37
37
  * delivered as an interim message in the same turn, whether a repeat or the final reply, is not
38
38
  * delivered again. With `review`, a chat whose replies are reviewed gets no interim
39
39
  * messages, and its final reply is sent only when the review allows it. `identifiers` is the
40
- * channel's `identifiers` setting, which the reply's text is checked under.
40
+ * channel's `identifiers` setting, which the reply's text is checked under. The turn's reply
41
+ * through `reply` arrives as a reply part named after its call, at the turn's end, and answers the
42
+ * message its call names; final text of a turn that replied so is dropped.
41
43
  */
42
44
  export declare function replyDelivery(scope?: () => string, interim?: InterimMessages, review?: ReplyReview, identifiers?: () => IdentifierPolicy): MessageCompleted;
43
45
  export declare const deliverUnlessSilent: MessageCompleted;
@@ -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 INTERIM_TURNS, n as completionKind, r as deliverUnlessSilent, i as interimTexts, a as isNoReplyCall, o as isSilentReply, s as replyDelivery } from "../../../_chunks/silent-CWcAjHwt.mjs";
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-DwObe1UV.mjs";