@segmentstream/agent 0.96.0 → 0.97.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 (29) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/_chunks/{build-metadata-_7QBVYuN.mjs → build-metadata-fijGydlU.mjs} +1 -1
  3. package/dist/extension/channels/email.mjs +1 -0
  4. package/dist/extension/channels/slack.mjs +1 -0
  5. package/dist/extension/channels/telegram.mjs +1 -0
  6. package/dist/extension/channels/whatsapp.mjs +1 -0
  7. package/dist/extension/config.d.ts +13 -0
  8. package/dist/extension/config.mjs +3 -0
  9. package/dist/extension/lib/build-metadata.mjs +1 -1
  10. package/dist/extension/lib/chat-messages.d.ts +16 -8
  11. package/dist/extension/lib/chat-messages.mjs +9 -5
  12. package/dist/extension/lib/email/channel.d.ts +3 -0
  13. package/dist/extension/lib/email/channel.mjs +39 -1
  14. package/dist/extension/lib/slack/adapter.d.ts +11 -0
  15. package/dist/extension/lib/slack/adapter.mjs +31 -1
  16. package/dist/extension/lib/telegram/adapter.d.ts +5 -0
  17. package/dist/extension/lib/telegram/adapter.mjs +14 -2
  18. package/dist/extension/lib/telegram/health.mjs +1 -1
  19. package/dist/extension/lib/telegram/inbound.d.ts +6 -0
  20. package/dist/extension/lib/telegram/inbound.mjs +17 -0
  21. package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
  22. package/dist/extension/lib/triage.d.ts +43 -0
  23. package/dist/extension/lib/triage.mjs +57 -0
  24. package/dist/extension/lib/whatsapp/adapter.d.ts +5 -0
  25. package/dist/extension/lib/whatsapp/adapter.mjs +37 -4
  26. package/dist/extension/lib/workspace-action.d.ts +5 -0
  27. package/dist/extension/lib/workspace-action.mjs +8 -6
  28. package/dist/extension/lib/workspace-channel/channel.mjs +31 -1
  29. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.97.0
4
+
5
+ `triage: { entity, action, contextVersion: 2 }` in `agent/segmentstream.json` names a routine
6
+ ontology action that reads a person's message before it starts a turn, as the member who wrote it:
7
+ a private chat's message in Telegram and WhatsApp, a Slack direct message, mail, and a workspace
8
+ channel's message. It receives `{ channel, chatId, threadId, messageId, text, files }` and answers
9
+ `{ skip: "<code>" }` for a message that needs no reply. The chat keeps a skipped message,
10
+ `skipped` with the code as its reason, and the agent reads it in the chat's context at the next
11
+ turn. Any other answer, a failure, a refusal or no answer within five seconds starts the turn, and
12
+ is logged. Group messages keep their routing. Without `triage` every message starts its turn, as
13
+ before.
14
+
3
15
  ## 0.96.0
4
16
 
5
17
  Allow a workspace to bind a read-only knowledge lookup for isolated group replies. Only the public facts returned by the workspace enter the reply model. Research runs after admission and shares the guest’s usage budget.
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- var version = "0.96.0";
7
+ var version = "0.97.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -12,6 +12,7 @@ import { decide } from "eve/ai";
12
12
  var email_default = segmentstreamEmail({
13
13
  settings: (name) => channelOf(segmentstream.config.channels, "email", name),
14
14
  admission: () => segmentstream.config,
15
+ triage: () => segmentstream.config.triage,
15
16
  models: () => segmentstream.config.models,
16
17
  review: {
17
18
  settings: () => segmentstream.config.review,
@@ -12,6 +12,7 @@ import { decide } from "eve/ai";
12
12
  var slack_default = segmentstreamSlack({
13
13
  settings: (name) => channelOf(segmentstream.config.channels, "slack", name),
14
14
  buttons: () => segmentstream.config.buttons,
15
+ triage: () => segmentstream.config.triage,
15
16
  texts: () => segmentstream.config.texts ?? {},
16
17
  admission: () => segmentstream.config,
17
18
  groups: () => segmentstream.config.groups,
@@ -12,6 +12,7 @@ import { decide } from "eve/ai";
12
12
  var telegram_default = segmentstreamTelegram({
13
13
  settings: (name) => channelOf(segmentstream.config.channels, "telegram", name),
14
14
  buttons: () => segmentstream.config.buttons,
15
+ triage: () => segmentstream.config.triage,
15
16
  groups: () => segmentstream.config.groups,
16
17
  models: () => segmentstream.config.models,
17
18
  confirmationMode: () => "native",
@@ -12,6 +12,7 @@ import { decide } from "eve/ai";
12
12
  var whatsapp_default = segmentstreamWhatsApp({
13
13
  settings: (name) => channelOf(segmentstream.config.channels, "whatsapp", name),
14
14
  buttons: () => segmentstream.config.buttons,
15
+ triage: () => segmentstream.config.triage,
15
16
  admission: () => segmentstream.config,
16
17
  models: () => segmentstream.config.models,
17
18
  review: {
@@ -171,6 +171,17 @@ export interface SegmentStreamAgentConfigInput {
171
171
  readonly buttons?: Omit<WorkspaceActionHook, "contextVersion"> & {
172
172
  readonly contextVersion: number;
173
173
  };
174
+ /**
175
+ * The routine ontology action that reads a person's message before it starts a turn, in every
176
+ * channel's private chats, as the member who wrote it. It receives
177
+ * `{ channel, chatId, threadId, messageId, text, files }` and answers `{ skip: "<code>" }` for a
178
+ * message that needs no reply, which the chat keeps `skipped` with the code; anything else, a
179
+ * failure or no answer within five seconds starts the turn. See `docs/agent.md`, "Triage".
180
+ * Without it every message starts its turn.
181
+ */
182
+ readonly triage?: Omit<WorkspaceActionHook, "contextVersion"> & {
183
+ readonly contextVersion: number;
184
+ };
174
185
  /**
175
186
  * The web the agent may read: `segmentstream__web_fetch` fetches `https://` pages of these
176
187
  * domains, each also covering its subdomains, for callers who hold `agent_tool:web`. No page
@@ -588,6 +599,8 @@ export interface SegmentStreamAgentConfig extends AdmissionSettings {
588
599
  readonly traces?: import("./lib/traces.js").TraceSettings;
589
600
  /** The action a press of a workspace button calls, in every channel; absent without one. */
590
601
  readonly buttons?: WorkspaceActionHook;
602
+ /** The action that reads a message before its turn, in every channel; absent without one. */
603
+ readonly triage?: WorkspaceActionHook;
591
604
  /** The web tools' settings; absent without web tools. See {@link WebSettings}. */
592
605
  readonly web?: WebSettings;
593
606
  /** The agent's browser; absent without the browser tool. See {@link BrowserSettings}. */
@@ -1141,6 +1141,7 @@ function validateConfig(input, options = {}) {
1141
1141
  "handoff",
1142
1142
  "traces",
1143
1143
  "buttons",
1144
+ "triage",
1144
1145
  "web",
1145
1146
  "browser",
1146
1147
  "sessions",
@@ -1411,6 +1412,7 @@ function validateConfig(input, options = {}) {
1411
1412
  path: ["traces", "content"]
1412
1413
  });
1413
1414
  const buttons = workspaceHook(root?.buttons, ["buttons"], issues);
1415
+ const triage = workspaceHook(root?.triage, ["triage"], issues);
1414
1416
  for (const [name, channel] of Object.entries(declared)) {
1415
1417
  const own = channel !== null && "callbacks" in channel ? channel.callbacks : void 0;
1416
1418
  if (buttons !== void 0 && own !== void 0 && (own.entity !== buttons.entity || own.action !== buttons.action)) issues.push({
@@ -1455,6 +1457,7 @@ function validateConfig(input, options = {}) {
1455
1457
  ...handoff === true ? { handoff: true } : {},
1456
1458
  ...tracesInput === void 0 ? {} : { traces: tracesInput.content === void 0 ? {} : { content: tracesInput.content === true } },
1457
1459
  ...buttons === void 0 ? {} : { buttons },
1460
+ ...triage === void 0 ? {} : { triage },
1458
1461
  ...web === null ? {} : { web },
1459
1462
  ...browser === null ? {} : { browser },
1460
1463
  sessions,
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { t as agentBuild } from "../../_chunks/build-metadata-_7QBVYuN.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-fijGydlU.mjs";
@@ -208,13 +208,8 @@ export interface UnadmittedMessage {
208
208
  * and makes nobody a user. True when recorded; nothing is recorded on the chat archive in Cloud.
209
209
  */
210
210
  export declare function recordUnadmittedMessage(archive: ChatArchive, message: UnadmittedMessage, reason: UnadmittedReason): Promise<boolean>;
211
- /**
212
- * Records a person's message in a private chat a member of the workspace took over, which starts
213
- * no turn: the inbox shows it, and the agent reads it in its context once the chat is handed back.
214
- * The event is keyed by the provider's message id, so a redelivered message is recorded once. A
215
- * decision beside it says why the agent did not answer.
216
- */
217
- export declare function recordHandledMessage(archive: ChatArchive, input: {
211
+ /** A message of an admitted member's private chat that starts no turn. */
212
+ export interface SkippedMessage {
218
213
  readonly chat: AdmittedChat;
219
214
  readonly memberId: string;
220
215
  /** The members who read it, in a chat several people share; by default its person. */
@@ -228,4 +223,17 @@ export declare function recordHandledMessage(archive: ChatArchive, input: {
228
223
  readonly replyTo?: string;
229
224
  readonly parts?: ReadonlyArray<ChatPart>;
230
225
  readonly at?: string;
231
- }): Promise<void>;
226
+ }
227
+ /**
228
+ * Records a person's message in a private chat a member of the workspace took over, which starts
229
+ * no turn: the inbox shows it, and the agent reads it in its context once the chat is handed back.
230
+ */
231
+ export declare function recordHandledMessage(archive: ChatArchive, input: SkippedMessage): Promise<void>;
232
+ /**
233
+ * Records an admitted member's message that starts no turn, `skipped` with `reason`: a chat staff
234
+ * took over, or a message the workspace's triage says needs no reply, with its code. The inbox
235
+ * shows it, and the agent reads it in its context at the chat's next turn. The event is keyed by
236
+ * the provider's message id, so a redelivered message is recorded once. A decision beside it says
237
+ * why the agent did not answer.
238
+ */
239
+ export declare function recordSkippedMessage(archive: ChatArchive, input: SkippedMessage, reason: string): Promise<void>;
@@ -257,9 +257,13 @@ async function recordUnadmittedMessage(archive, message, reason) {
257
257
  });
258
258
  return true;
259
259
  }
260
- async function recordHandledMessage(archive, input) {
260
+ const HANDLED = "chat_handled";
261
+ function recordHandledMessage(archive, input) {
262
+ return recordSkippedMessage(archive, input, HANDLED);
263
+ }
264
+ async function recordSkippedMessage(archive, input, reason) {
261
265
  const { chat } = input;
262
- const eventId = `handled:${chat.channel}:${chat.chatId}:${input.messageId}`;
266
+ const eventId = `${reason === HANDLED ? "handled" : "skipped"}:${chat.channel}:${chat.chatId}:${input.messageId}`;
263
267
  await recordChatMessage(archive, {
264
268
  provider: chat.channel,
265
269
  chatId: chat.chatId,
@@ -285,7 +289,7 @@ async function recordHandledMessage(archive, input) {
285
289
  messageId: input.messageId,
286
290
  change: "disposition",
287
291
  disposition: "skipped",
288
- reason: "chat_handled"
292
+ reason
289
293
  });
290
294
  return;
291
295
  }
@@ -300,8 +304,8 @@ async function recordHandledMessage(archive, input) {
300
304
  messageId: input.messageId,
301
305
  kind: "decision",
302
306
  decision: "silent",
303
- reason: "chat_handled",
307
+ reason,
304
308
  status: "completed"
305
309
  }));
306
310
  }
307
- export { MAXIMUM_PARTS, applyChatChange, chatPart, chatParts, recordChatMessage, recordHandledMessage, recordReceivedMessage, recordSentOutside, recordUnadmittedMessage, recordUnreadMessage, stagedFiles };
311
+ export { MAXIMUM_PARTS, applyChatChange, chatPart, chatParts, recordChatMessage, recordHandledMessage, recordReceivedMessage, recordSentOutside, recordSkippedMessage, recordUnadmittedMessage, recordUnreadMessage, stagedFiles };
@@ -13,6 +13,7 @@ import { channelReview } from "../review/reply.js";
13
13
  import type { ReviewDecideFunction } from "../review/judge.js";
14
14
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
15
15
  import { type RuntimeToken } from "../runtime-token.js";
16
+ import type { WorkspaceActionHook } from "../workspace-action.js";
16
17
  import { type Gmail } from "./gmail.js";
17
18
  /**
18
19
  * The email channel (`docs/agent.md`, "Email"). The mailbox of the workspace's `GmailConnection`
@@ -55,6 +56,8 @@ export interface EmailChannelOptions {
55
56
  /** The settings of the email channel `name`, or null when there is no such email channel. */
56
57
  readonly settings: (name: string) => EmailSettings | null;
57
58
  readonly admission: () => AdmissionSettings;
59
+ /** The action that reads mail before its turn, from `triage` in `agent/segmentstream.json`. */
60
+ readonly triage?: () => WorkspaceActionHook | undefined;
58
61
  readonly models?: () => SegmentStreamAgentConfig["models"];
59
62
  readonly review?: {
60
63
  readonly settings: () => ReviewSettings | undefined;
@@ -12,7 +12,7 @@ import { Bt as participantsOf, Ft as chatAddressOf, Mt as PARTICIPANTS_ATTRIBUTE
12
12
  import { channelAttributes, currentChannel, currentKey, inChannel, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
13
13
  import { a as chatEvent, b as messageInput, d as replyRecipients, g as UNVERIFIED, l as replyEvent, p as storeOf, r as chatArchive, t as AGENT_SENDER } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
14
14
  import { ChatStoreError } from "../chat-store.mjs";
15
- import { recordChatMessage, recordHandledMessage, recordSentOutside } from "../chat-messages.mjs";
15
+ import { recordChatMessage, recordHandledMessage, recordSentOutside, recordSkippedMessage } from "../chat-messages.mjs";
16
16
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
17
17
  import { redactDiagnostic } from "../diagnostics.mjs";
18
18
  import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
@@ -25,6 +25,7 @@ import { g as turnFiles, n as completionKind } from "../../../_chunks/silent-xJc
25
25
  import { runtimeTokenVerifier } from "../runtime-identity.mjs";
26
26
  import { runtimeToken } from "../runtime-token.mjs";
27
27
  import { runtimeRequestFailure } from "../telegram/runtime-request.mjs";
28
+ import { workspaceTriage } from "../triage.mjs";
28
29
  import { GMAIL_ID, GmailError, ReplyNotSent, gmail, replyKeyOf } from "./gmail.mjs";
29
30
  import { inboundMail, parseMail, sentMail } from "./message.mjs";
30
31
  import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
@@ -231,6 +232,15 @@ function emailChannelDefinition(options) {
231
232
  origin: appOrigin(environment),
232
233
  ...transport
233
234
  });
235
+ const triage = () => workspaceTriage({
236
+ configuration: options.triage?.(),
237
+ environment,
238
+ ...transport,
239
+ report: (operation, error) => log("[segmentstream] email triage diagnostic", {
240
+ operation,
241
+ error: redactDiagnostic(error, new Set())
242
+ })
243
+ });
234
244
  const review = () => options.review === void 0 ? void 0 : reviewed ??= channelReview({
235
245
  settings: options.review.settings,
236
246
  decide: options.review.decide,
@@ -574,6 +584,34 @@ function emailChannelDefinition(options) {
574
584
  ...participants === void 0 ? {} : { participants }
575
585
  });
576
586
  const memberId = memberIdOf(auth);
587
+ const triaged = await triage()?.({
588
+ principal: auth,
589
+ memberId,
590
+ messageId: added.id,
591
+ text: turnText(mail),
592
+ files: mail.attachments.length
593
+ });
594
+ if (triaged !== void 0) {
595
+ await recordSkippedMessage(archive(), {
596
+ chat: {
597
+ channel: currentChannel("email"),
598
+ chatId,
599
+ threadId: added.threadId
600
+ },
601
+ memberId: resolution.member.id,
602
+ ...participants === void 0 ? {} : { participantIds: participants },
603
+ senderId: mail.from,
604
+ senderName: mail.fromName ?? null,
605
+ messageId: added.id,
606
+ text: mail.text,
607
+ files: mail.attachments.map((file) => ({
608
+ name: file.filename,
609
+ mimeType: file.contentType,
610
+ size: file.bytes.byteLength
611
+ }))
612
+ }, triaged.skip);
613
+ return;
614
+ }
577
615
  const inbound = mail.attachments.map((file, index) => ({
578
616
  key: `${added.id}:${index}`,
579
617
  kind: fileKind(file.contentType),
@@ -16,6 +16,7 @@ import { type Transcriber } from "../inbound-media/speech.js";
16
16
  import { type SlackFileDownload } from "./files.js";
17
17
  import type { TelegramTexts } from "../telegram/texts.js";
18
18
  import type { WorkspaceActionHook } from "../workspace-action.js";
19
+ import { type Triage } from "../triage.js";
19
20
  import { type ChannelReviewOptions } from "../review/reply.js";
20
21
  import { type RuntimeToken } from "../runtime-token.js";
21
22
  import { type ChatArchive } from "../chat-archive.js";
@@ -68,6 +69,11 @@ export interface SlackChannelOptions {
68
69
  * the same in every channel. Without it, a channel's own earlier `callbacks`.
69
70
  */
70
71
  readonly buttons?: () => WorkspaceActionHook | undefined;
72
+ /**
73
+ * The action that reads a direct message before its turn, from `triage` in
74
+ * `agent/segmentstream.json`. A channel's messages keep their group routing.
75
+ */
76
+ readonly triage?: () => WorkspaceActionHook | undefined;
71
77
  /**
72
78
  * The workspace's group routing. In `mention` mode a reply in a followed thread reaches the
73
79
  * agent only when it mentions the bot; in `smart` mode the model decides.
@@ -193,6 +199,11 @@ export declare function receive(input: {
193
199
  * took it; an edit, which changes the message recorded before, gives none.
194
200
  */
195
201
  readonly received?: (message: SlackReceivedMessage) => void;
202
+ /**
203
+ * The workspace's triage, which may skip a direct message that needs no reply; none by default.
204
+ * A channel's messages keep their group routing.
205
+ */
206
+ readonly triage?: Triage;
196
207
  }): Promise<SlackMentionResult>;
197
208
  /** How the Slack channel stores and transcribes a message's files. */
198
209
  export interface SlackFiles {
@@ -23,12 +23,13 @@ import { gatewayTranscriber } from "../inbound-media/speech.mjs";
23
23
  import { slackFileDownload, slackFiles } from "./files.mjs";
24
24
  import { confirmationMessageCalls, slackConfirmationRenderer } from "./confirmation-card.mjs";
25
25
  import { handleWorkspaceCallback } from "./callbacks.mjs";
26
+ import { workspaceTriage } from "../triage.mjs";
26
27
  import { pairingNotice } from "./pairing.mjs";
27
28
  import { recordThreadHistory } from "./thread-history.mjs";
28
29
  import { channelReview, withReviewedReplies } from "../review/reply.mjs";
29
30
  import { runtimeToken } from "../runtime-token.mjs";
30
31
  import { r as chatArchive } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
31
- import { recordHandledMessage, recordReceivedMessage, stagedFiles } from "../chat-messages.mjs";
32
+ import { recordHandledMessage, recordReceivedMessage, recordSkippedMessage, stagedFiles } from "../chat-messages.mjs";
32
33
  import { recordSlackChange, slackChange, slackTime } from "./changes.mjs";
33
34
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
34
35
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -291,6 +292,13 @@ function segmentstreamSlack(options) {
291
292
  chats: chats(),
292
293
  archive,
293
294
  files,
295
+ triage: workspaceTriage({
296
+ configuration: options.triage?.(),
297
+ environment,
298
+ token,
299
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch },
300
+ report
301
+ }),
294
302
  ...work === void 0 ? {} : {
295
303
  waitUntil: work.waitUntil,
296
304
  turn: (media) => {
@@ -541,6 +549,28 @@ async function receive(input) {
541
549
  id: message.ts,
542
550
  sender: user
543
551
  });
552
+ const triaged = input.direct && ctx.edit === void 0 ? await input.triage?.({
553
+ principal: incoming,
554
+ memberId: resolution.member.id,
555
+ messageId: message.ts,
556
+ text: message.text,
557
+ files: message.attachments.length
558
+ }) : void 0;
559
+ if (triaged !== void 0) {
560
+ await recordSkippedMessage(input.archive?.() ?? chatArchive({ environment: input.environment }), {
561
+ chat: {
562
+ channel: currentChannel("slack"),
563
+ chatId: ctx.slack.channelId
564
+ },
565
+ memberId: resolution.member.id,
566
+ senderId: user,
567
+ senderName: display ?? null,
568
+ messageId: message.ts,
569
+ text: message.text,
570
+ files: message.attachments
571
+ }, triaged.skip);
572
+ return null;
573
+ }
544
574
  const auth = await personaPrincipal(admission.personas, incoming, ctx.edit === void 0 ? (text) => ctx.slack.request("chat.postEphemeral", {
545
575
  channel: ctx.slack.channelId,
546
576
  user,
@@ -33,6 +33,11 @@ export interface TelegramAdapterOptions {
33
33
  * the same in every channel. Without it, a channel's own earlier `callbacks`.
34
34
  */
35
35
  readonly buttons?: () => WorkspaceActionHook | undefined;
36
+ /**
37
+ * The action that reads a private chat's message before its turn, from `triage` in
38
+ * `agent/segmentstream.json`. A group's messages keep their own routing.
39
+ */
40
+ readonly triage?: () => WorkspaceActionHook | undefined;
36
41
  readonly groups?: () => GroupPolicy;
37
42
  readonly models: () => {
38
43
  readonly stt: string | false;
@@ -11,8 +11,9 @@ import { archivedRoutingMessages } from "../group-routing/routing-context.mjs";
11
11
  import { groupRoutingHealth } from "../group-routing/health.mjs";
12
12
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
13
13
  import { handleWorkspaceCallback } from "./callbacks.mjs";
14
+ import { workspaceTriage } from "../triage.mjs";
14
15
  import { telegramText, withTelegramTexts } from "./texts.mjs";
15
- import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.mjs";
16
+ import { t as agentBuild } from "../../../_chunks/build-metadata-fijGydlU.mjs";
16
17
  import { attachmentLifecycle } from "./lifecycle.mjs";
17
18
  import { manifestOf } from "../../config.mjs";
18
19
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -25,9 +26,9 @@ import { h as topicContext, r as chatArchive } from "../../../_chunks/chat-archi
25
26
  import { a as captureTelegramFetch, h as telegramChatCapture, i as captureRouteDecider, s as chatIdentities, u as recordGateDecision } from "../../../_chunks/chat-archive-DmCXcI8G.mjs";
26
27
  import { runtimeTokenVerifier } from "../runtime-identity.mjs";
27
28
  import { runtimeToken } from "../runtime-token.mjs";
29
+ import { isWorkspaceCallback } from "../workspace-action.mjs";
28
30
  import { botIdentityCache, proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
29
31
  import { handleConfirmationCallback, telegramConfirmationEvents } from "./confirmations.mjs";
30
- import { isWorkspaceCallback } from "../workspace-action.mjs";
31
32
  import { confirmationLocale } from "./confirmation-text.mjs";
32
33
  import { telegramAppLinkContext } from "./app-links.mjs";
33
34
  import { gatewayImageDescriber } from "../inbound-media/images.mjs";
@@ -232,6 +233,16 @@ function segmentstreamTelegram(options) {
232
233
  inbound.locale = chatLanguage([message.text || message.caption]) ?? message.from?.languageCode ?? "en";
233
234
  inbound.threadId = message.messageThreadId === void 0 ? void 0 : String(message.messageThreadId);
234
235
  }
236
+ const triage = workspaceTriage({
237
+ configuration: options.triage?.(),
238
+ environment,
239
+ token,
240
+ ...options.fetch ? { fetch: options.fetch } : {},
241
+ report: (operation, error) => reportTelegramError(operation, error, {
242
+ chatId: message.chat.id,
243
+ messageId: message.messageId
244
+ })
245
+ });
235
246
  try {
236
247
  const result = await handleInboundMessage({
237
248
  context,
@@ -273,6 +284,7 @@ function segmentstreamTelegram(options) {
273
284
  token,
274
285
  ...options.fetch ? { fetch: options.fetch } : {}
275
286
  }) },
287
+ ...triage === void 0 ? {} : { triage },
276
288
  sessions: options.sessions,
277
289
  admission: options.admission ?? (() => manifestOf({})),
278
290
  sttModel: options.models().stt,
@@ -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-_7QBVYuN.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-fijGydlU.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";
@@ -1,3 +1,4 @@
1
+ import type { Triage } from "../triage.js";
1
2
  import { type StructuredInbound, type StructuredMessage, type StructuredResult } from "./structured.js";
2
3
  import type { RecentMessage } from "../group-routing/messages.js";
3
4
  import { type GroupPolicy } from "../group-routing/policy.js";
@@ -53,6 +54,11 @@ export interface InboundDependencies {
53
54
  readonly recentChat?: (chatId: string, threadId?: string) => Promise<ReadonlyArray<RecentMessage>>;
54
55
  readonly signalSettings?: TelegramSettings["groups"];
55
56
  readonly lifecycle?: (principal: import("eve/context").SessionAuthContext, memberId: string, message: TelegramMessage) => ReturnType<typeof attachmentLifecycle>;
57
+ /**
58
+ * The workspace's triage, which may skip a private chat's message that needs no reply; none by
59
+ * default. A group's messages keep their own routing.
60
+ */
61
+ readonly triage?: Triage;
56
62
  readonly admission: () => AdmissionSettings;
57
63
  readonly sessions: () => SessionSettings;
58
64
  readonly sttModel: string | false;
@@ -640,6 +640,7 @@ async function handleInboundMessage(input) {
640
640
  recordGateDecision("empty_message");
641
641
  return null;
642
642
  }
643
+ const said = text;
643
644
  if (text.trim() === "" && sent.attachments.length > 0) {
644
645
  text = "[attachment]";
645
646
  if (input.request !== void 0) input.request.text = text;
@@ -1035,6 +1036,22 @@ async function handleInboundMessage(input) {
1035
1036
  recordGateDecision("message_already_handled");
1036
1037
  return null;
1037
1038
  }
1039
+ if (dependencies.triage !== void 0 && !group && structured === void 0 && input.request?.structuredContext === void 0 && input.request?.lifecycleKey === void 0 && !(answering && pending !== void 0)) {
1040
+ const triaged = await dependencies.triage({
1041
+ principal: telegramPrincipal({
1042
+ message: sent,
1043
+ member
1044
+ }),
1045
+ memberId: member.id,
1046
+ messageId: String(sent.messageId),
1047
+ text: said,
1048
+ files: sent.attachments.length
1049
+ });
1050
+ if (triaged !== void 0) {
1051
+ recordGateDecision(triaged.skip);
1052
+ return null;
1053
+ }
1054
+ }
1038
1055
  if (operations !== void 0 && dependencies.history !== void 0) {
1039
1056
  let recoverySessionId;
1040
1057
  try {
@@ -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-DL9NdRRP.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-fijGydlU.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -0,0 +1,43 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import type { Environment } from "./environment.js";
3
+ import type { RuntimeToken } from "./runtime-token.js";
4
+ import { type WorkspaceActionHook } from "./workspace-action.js";
5
+ /**
6
+ * The workspace's triage (`docs/agent.md`, "Triage"): the routine action `triage` names reads a
7
+ * person's message in a private chat before it starts a turn, as the member who wrote it, and may
8
+ * answer that it needs no reply. The platform only asks and keeps the answer; which messages need
9
+ * none, and the words of the codes, are the workspace's.
10
+ */
11
+ /** How long the workspace's triage may take before the message starts its turn all the same. */
12
+ export declare const TRIAGE_DEADLINE_MS = 5000;
13
+ /** A person's message about to start a turn, as a channel hands it to the triage. */
14
+ export interface TriageMessage {
15
+ /** The admitted member's principal, with the chat the message came from. */
16
+ readonly principal: SessionAuthContext;
17
+ readonly memberId: string;
18
+ /** The provider's id of the message. */
19
+ readonly messageId: string;
20
+ /** What the person wrote, as the channel has read it. */
21
+ readonly text: string;
22
+ /** How many files the message carries; the triage reads none of them. */
23
+ readonly files: number;
24
+ }
25
+ /** Reads one message: the code it is skipped with, or undefined when it starts its turn. */
26
+ export type Triage = (message: TriageMessage) => Promise<{
27
+ readonly skip: string;
28
+ } | undefined>;
29
+ /**
30
+ * The triage `configuration` names, or undefined without one, when every message starts its turn.
31
+ * A message starts its turn too when the action fails, takes more than {@link TRIAGE_DEADLINE_MS},
32
+ * or answers anything but `{ skip: "<code>" }`: a triage never loses a message. Each of these is
33
+ * reported for operators.
34
+ */
35
+ export declare function workspaceTriage(input: {
36
+ readonly configuration: WorkspaceActionHook | undefined;
37
+ readonly environment?: Environment;
38
+ readonly token?: RuntimeToken;
39
+ readonly fetch?: typeof fetch;
40
+ readonly report: (operation: string, cause: unknown) => void;
41
+ /** Tests pass a shorter deadline. */
42
+ readonly deadline?: number;
43
+ }): Triage | undefined;
@@ -0,0 +1,57 @@
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 { Ft as chatAddressOf, It as chatChannel, Ot as runtimeEnvelope } from "../../_chunks/principal-DL9NdRRP.mjs";
8
+ import { withinDeadline, workspaceAction } from "./workspace-action.mjs";
9
+ const TRIAGE_DEADLINE_MS = 5e3;
10
+ const TEXT_LIMIT = 16384;
11
+ const ID_LIMIT = 512;
12
+ const CODE = /^[a-z][a-z0-9_]{0,63}$/;
13
+ function workspaceTriage(input) {
14
+ const { configuration, report } = input;
15
+ if (configuration === void 0) return;
16
+ const deadline = input.deadline ?? 5e3;
17
+ return async (message) => {
18
+ const chat = chatAddressOf(message.principal);
19
+ let answer;
20
+ try {
21
+ if (chat === void 0) throw new Error("The message's principal names no chat to triage.");
22
+ answer = await withinDeadline((signal) => workspaceAction({
23
+ configuration,
24
+ principal: message.principal,
25
+ memberId: message.memberId,
26
+ input: {
27
+ channel: chatChannel(chat),
28
+ chatId: chat.chatId,
29
+ threadId: chat.threadId,
30
+ messageId: message.messageId,
31
+ text: message.text.slice(0, TEXT_LIMIT),
32
+ files: message.files
33
+ },
34
+ signal,
35
+ envelope: runtimeEnvelope({
36
+ principal: message.principal,
37
+ sessionId: `${chatChannel(chat)}:triage:${message.messageId}`.slice(0, ID_LIMIT),
38
+ callId: message.messageId.slice(0, ID_LIMIT)
39
+ }),
40
+ ...input.environment === void 0 ? {} : { environment: input.environment },
41
+ ...input.token === void 0 ? {} : { token: input.token },
42
+ ...input.fetch === void 0 ? {} : { fetch: input.fetch }
43
+ }), deadline, () => report("triage_timeout", new Error(`The workspace's triage took more than ${deadline} milliseconds.`)));
44
+ } catch (error) {
45
+ report("triage_failed", error);
46
+ return;
47
+ }
48
+ const skip = answer?.skip;
49
+ if (skip === void 0 || skip === null) return;
50
+ if (typeof skip !== "string" || !CODE.test(skip)) {
51
+ report("triage_invalid", new Error("The workspace's triage answered a skip that is not a code."));
52
+ return;
53
+ }
54
+ return { skip };
55
+ };
56
+ }
57
+ export { TRIAGE_DEADLINE_MS, workspaceTriage };
@@ -13,6 +13,7 @@ import { type Environment } from "../environment.js";
13
13
  import { type AgentIdentities, type PairedMember } from "../identities.js";
14
14
  import { type RuntimeToken } from "../runtime-token.js";
15
15
  import { type ChatArchive } from "../chat-archive.js";
16
+ import { type Triage } from "../triage.js";
16
17
  import type { WorkspaceActionHook } from "../workspace-action.js";
17
18
  import { whatsappParts, type WhatsAppChanges } from "./changes.js";
18
19
  import { type WhatsAppEcho } from "./echoes.js";
@@ -71,6 +72,8 @@ export interface WhatsAppChannelOptions {
71
72
  readonly admission: () => AdmissionSettings;
72
73
  /** The action a press of a workspace button calls, from `buttons` in `agent/segmentstream.json`. */
73
74
  readonly buttons?: () => WorkspaceActionHook | undefined;
75
+ /** The action that reads a message before its turn, from `triage` in `agent/segmentstream.json`. */
76
+ readonly triage?: () => WorkspaceActionHook | undefined;
74
77
  readonly environment?: Environment;
75
78
  readonly token?: RuntimeToken;
76
79
  /** For the proxy and the ontology service; tests pass a fake. */
@@ -193,6 +196,8 @@ export declare function receive(input: {
193
196
  readonly archive?: () => ChatArchive;
194
197
  /** Which messages the channel records; `agent` by default. */
195
198
  readonly record?: RecordSetting;
199
+ /** The workspace's triage, which may skip a message that needs no reply; none by default. */
200
+ readonly triage?: Triage;
196
201
  }): Promise<SessionAuthContext | undefined>;
197
202
  /**
198
203
  * The pairing reply: the workspace's text with a button opening the link, which WhatsApp shows as
@@ -22,7 +22,8 @@ import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../
22
22
  import { agentIdentities } from "../identities.mjs";
23
23
  import { runtimeToken } from "../runtime-token.mjs";
24
24
  import { r as chatArchive } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
25
- import { recordHandledMessage, recordReceivedMessage, recordUnadmittedMessage, stagedFiles } from "../chat-messages.mjs";
25
+ import { recordHandledMessage, recordReceivedMessage, recordSkippedMessage, recordUnadmittedMessage, stagedFiles } from "../chat-messages.mjs";
26
+ import { workspaceTriage } from "../triage.mjs";
26
27
  import { handleWorkspaceButton } from "./callbacks.mjs";
27
28
  import { recordWhatsAppChanges, whatsappChanges, whatsappParts } from "./changes.mjs";
28
29
  import { recordEchoes, whatsappEchoes } from "./echoes.mjs";
@@ -402,7 +403,14 @@ function segmentstreamWhatsApp(options) {
402
403
  identities: pairing(),
403
404
  environment,
404
405
  archive: chats,
405
- record: settings()?.record ?? "agent"
406
+ record: settings()?.record ?? "agent",
407
+ triage: workspaceTriage({
408
+ configuration: options.triage?.(),
409
+ environment,
410
+ token,
411
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch },
412
+ report
413
+ })
406
414
  });
407
415
  const memberId = memberIdOf(auth);
408
416
  if (auth === void 0 || memberId === void 0) return;
@@ -564,7 +572,8 @@ async function receive(input) {
564
572
  }).catch((cause) => report("message_record_failed", cause));
565
573
  return;
566
574
  }
567
- return turn ? personaPrincipal(admission.personas, withChatAddress(whatsappPrincipal(resolution.member, sender), {
575
+ if (!turn) return;
576
+ const principal = withChatAddress(whatsappPrincipal(resolution.member, sender), {
568
577
  provider: "whatsapp",
569
578
  ...currentChannel("whatsapp") === "whatsapp" ? {} : { channel: currentChannel("whatsapp") },
570
579
  chatId: thread.id,
@@ -574,7 +583,31 @@ async function receive(input) {
574
583
  }, {
575
584
  id: message.id,
576
585
  sender
577
- }), (text) => thread.post(text)) : void 0;
586
+ });
587
+ const triaged = await input.triage?.({
588
+ principal,
589
+ memberId: resolution.member.id,
590
+ messageId: message.id,
591
+ text: message.text,
592
+ files: message.attachments.length
593
+ });
594
+ if (triaged !== void 0) {
595
+ await recordSkippedMessage(archive(), {
596
+ chat: {
597
+ channel: currentChannel("whatsapp"),
598
+ chatId: thread.id
599
+ },
600
+ memberId: resolution.member.id,
601
+ senderId: sender,
602
+ senderName: display ?? null,
603
+ messageId: message.id,
604
+ text: message.text,
605
+ files: message.attachments,
606
+ ...raw
607
+ }, triaged.skip);
608
+ return;
609
+ }
610
+ return personaPrincipal(admission.personas, principal, (text) => thread.post(text));
578
611
  case "pairing_required": {
579
612
  await unadmitted("identity_unknown");
580
613
  const text = localizedText(admission.replies.pairingRequired);
@@ -26,6 +26,11 @@ export interface WorkspaceButtonAnswer {
26
26
  /** Everything the action returned, for what only one channel reads. */
27
27
  readonly result: Record<string, unknown>;
28
28
  }
29
+ /**
30
+ * What `dispatch` answers within `milliseconds`, or undefined once they passed: its call is then
31
+ * aborted and `timedOut` is told. A failure of `dispatch` before then is thrown.
32
+ */
33
+ export declare function withinDeadline<T>(dispatch: (signal: AbortSignal) => Promise<T>, milliseconds: number, timedOut: () => void): Promise<T | undefined>;
29
34
  /**
30
35
  * Runs a workspace button's action within the deadline every channel gives it, and reads its
31
36
  * answer. Undefined when `dispatch` answers nothing, or when the action took too long: its call is
@@ -18,21 +18,23 @@ function workspaceButtonToken(data) {
18
18
  const WORKSPACE_BUTTON_DEADLINE_MS = 1e4;
19
19
  const ACKNOWLEDGEMENT_LIMIT = 200;
20
20
  const CONTEXT_LIMIT = 16384;
21
- async function pressWorkspaceButton(dispatch, timedOut) {
21
+ async function withinDeadline(dispatch, milliseconds, timedOut) {
22
22
  const controller = new AbortController();
23
23
  let timer;
24
- let result;
25
24
  try {
26
- result = await Promise.race([dispatch(controller.signal), new Promise((resolve) => {
25
+ return await Promise.race([dispatch(controller.signal), new Promise((resolve) => {
27
26
  timer = setTimeout(() => {
28
27
  controller.abort();
29
- timedOut(new Error("A workspace button's action took more than 10 seconds."));
28
+ timedOut();
30
29
  resolve(void 0);
31
- }, WORKSPACE_BUTTON_DEADLINE_MS);
30
+ }, milliseconds);
32
31
  })]);
33
32
  } finally {
34
33
  if (timer !== void 0) clearTimeout(timer);
35
34
  }
35
+ }
36
+ async function pressWorkspaceButton(dispatch, timedOut) {
37
+ const result = await withinDeadline(dispatch, WORKSPACE_BUTTON_DEADLINE_MS, () => timedOut(new Error("A workspace button's action took more than 10 seconds.")));
36
38
  if (result === void 0) return;
37
39
  const { acknowledgement, context } = result;
38
40
  return {
@@ -66,4 +68,4 @@ async function workspaceAction(input) {
66
68
  if (object(envelope.validation).ok === false) throw new Error("The workspace hook rejected its event.");
67
69
  return object(envelope.result ?? envelope);
68
70
  }
69
- export { WORKSPACE_BUTTON_DEADLINE_MS, WORKSPACE_BUTTON_PREFIX, WORKSPACE_TOKEN_BYTES, WorkspaceActionAlreadyDispatched, isWorkspaceCallback, pressWorkspaceButton, queueWorkspaceButtonTurn, workspaceAction, workspaceButtonToken };
71
+ export { WORKSPACE_BUTTON_DEADLINE_MS, WORKSPACE_BUTTON_PREFIX, WORKSPACE_TOKEN_BYTES, WorkspaceActionAlreadyDispatched, isWorkspaceCallback, pressWorkspaceButton, queueWorkspaceButtonTurn, withinDeadline, workspaceAction, workspaceButtonToken };
@@ -11,7 +11,7 @@ import { providerChat } from "../attachment-tools.mjs";
11
11
  import { Ft as chatAddressOf, Ht as workspaceIdentityProvider, S as fetchStoredAttachment, Vt as withChatAddress, b as agentAttachments, d as prepareInboundMedia, i as memberIdOf, m as turnContent } from "../../../_chunks/principal-DL9NdRRP.mjs";
12
12
  import { CHANNEL_ATTRIBUTE, channelKey } from "../channel-scope.mjs";
13
13
  import { S as reasonCode, a as chatEvent, r as chatArchive, t as AGENT_SENDER } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
14
- import { applyChatChange, chatParts, recordHandledMessage, recordReceivedMessage, recordSentOutside, recordUnadmittedMessage, stagedFiles } from "../chat-messages.mjs";
14
+ import { applyChatChange, chatParts, recordHandledMessage, recordReceivedMessage, recordSentOutside, recordSkippedMessage, recordUnadmittedMessage, stagedFiles } from "../chat-messages.mjs";
15
15
  import { connectionProxy } from "../connection-proxy.mjs";
16
16
  import { redactDiagnostic } from "../diagnostics.mjs";
17
17
  import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
@@ -26,6 +26,7 @@ import { replyFilesSender } from "../attachments-dispatch.mjs";
26
26
  import { runtimeTokenVerifier } from "../runtime-identity.mjs";
27
27
  import { runtimeToken } from "../runtime-token.mjs";
28
28
  import { runtimeRequestFailure } from "../telegram/runtime-request.mjs";
29
+ import { workspaceTriage } from "../triage.mjs";
29
30
  import { channelConnection } from "./connection.mjs";
30
31
  import { ChannelCheckUnavailable, channelChecks } from "./secrets.mjs";
31
32
  import { decide } from "eve/ai";
@@ -295,6 +296,12 @@ function workspaceChannelDefinition(options) {
295
296
  ...transport
296
297
  });
297
298
  const report = (operation, cause) => redacted(operation, cause, new Set());
299
+ const triage = workspaceTriage({
300
+ configuration: config.triage,
301
+ environment,
302
+ ...transport,
303
+ report
304
+ });
298
305
  const redacted = (operation, cause, secrets) => {
299
306
  const reference = randomUUID();
300
307
  log("[segmentstream] workspace channel diagnostic", {
@@ -457,6 +464,29 @@ function workspaceChannelDefinition(options) {
457
464
  }
458
465
  const auth = workspaceChannelPrincipal(name, resolution.member, message.sender, message.chatId);
459
466
  const memberId = memberIdOf(auth);
467
+ const triaged = await triage?.({
468
+ principal: auth,
469
+ memberId,
470
+ messageId: message.id,
471
+ text: message.text,
472
+ files: described.length
473
+ });
474
+ if (triaged !== void 0) {
475
+ await recordSkippedMessage(archive(), {
476
+ chat: {
477
+ channel: name,
478
+ chatId: message.chatId
479
+ },
480
+ memberId: resolution.member.id,
481
+ senderId: message.sender.id,
482
+ senderName: message.sender.name ?? null,
483
+ messageId: message.id,
484
+ text: message.text,
485
+ files: described,
486
+ ...beside
487
+ }, triaged.skip);
488
+ return;
489
+ }
460
490
  const inbound = (files ? message.files ?? [] : []).map((file, index) => ({
461
491
  key: `${message.id}:${index}`,
462
492
  kind: fileKind(file.contentType),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.96.0",
3
+ "version": "0.97.0",
4
4
  "description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",