@segmentstream/agent 0.59.5 → 0.60.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.60.0
4
+
5
+ The agent stands down in a private chat staff took over. Where the ontology's inbox lets staff take
6
+ a chat over, the agent reports every message of the person's private chat, and while a member of
7
+ staff holds it, Telegram, WhatsApp, Slack direct messages, email threads and workspace channels
8
+ record the person's message in the archive under the chat, with files by name, and start no turn.
9
+ Once the chat is handed back, the next turn reads what was said meanwhile in its chat context.
10
+
11
+ Pins @segmentstream/ontology 0.124.0.
12
+
13
+ ## 0.59.7
14
+
15
+ Pins @segmentstream/ontology 0.123.0.
16
+
17
+ ## 0.59.6
18
+
19
+ The agent no longer tells a member the builders' responses to app feedback when a chat starts.
20
+ It tells them when they ask about their feedback, reading only their own items: a builder who can
21
+ read everyone's feedback was told other members' responses as their own.
22
+
23
+ Pins @segmentstream/ontology 0.122.1.
24
+
3
25
  ## 0.59.5
4
26
 
5
27
  Pins @segmentstream/ontology 0.122.0.
package/README.md CHANGED
@@ -876,7 +876,7 @@ cold start selects the same successor, and Eve hands it over between deployments
876
876
  healthy session. If the successor's own deployment is deleted later, the next successor
877
877
  follows the same rule, up to four in a row. Archived chat context remains
878
878
  available, but the inaccessible session's model history and pending inputs cannot migrate.
879
- `segmentstream history squash` deletes earlier deployments and so ends the sessions
879
+ `segmentstream workspace history squash` deletes earlier deployments and so ends the sessions
880
880
  they own; each affected address continues once at its successor.
881
881
 
882
882
  Recovery applies only to session reads. Dispatch failures are never retried because
@@ -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.59.5";
7
+ var version = "0.60.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -63,9 +63,9 @@ rejection or perform actions.
63
63
  or files still require the member's agreement. First reuse the member's open `app_feedback` with
64
64
  the same subject; claim reporting only after a successful submission or existing-item read.
65
65
  If `app_feedback_file_attach` is available, attach only files the member agreed to share.
66
- When a member starts talking to you, find their `app_feedback` with `responded_at` set and
67
- `seen_at` empty, tell them the builders' response, then call `app_feedback_acknowledge` with
68
- its `responded_at`.
66
+ When a member asks about their feedback, read only their own `app_feedback`: filter by
67
+ `reporter`, their user id from `me`, since builders can read everyone's. Tell them the
68
+ builders' response, then call `app_feedback_acknowledge` with its `responded_at`.
69
69
  - When the current member has permission and gives a clear instruction, act, including necessary
70
70
  routine intermediate steps. Their authorization continues across turns. When they answer your
71
71
  question, use the answer and continue the pending task without asking for permission again.
@@ -11,7 +11,11 @@ export interface AdmittedChat {
11
11
  /** Whom a reply is sent to, where it differs from the chat's id. */
12
12
  readonly recipient?: string;
13
13
  }
14
- /** Channel-independent admission and at-least-once versioned notice delivery. */
14
+ /**
15
+ * Channel-independent admission and at-least-once versioned notice delivery. A private chat a
16
+ * member of staff took over comes back `handled`: the channel records the message with
17
+ * `recordHandledMessage`, or as it records every message, and starts no turn.
18
+ */
15
19
  export declare function admitMessage(input: {
16
20
  readonly identity: ResolveIdentityInput;
17
21
  readonly identities: AgentIdentities;
@@ -31,7 +31,7 @@ async function reportInboxChat(input) {
31
31
  const key = `${chat.channel}:${chat.chatId}`;
32
32
  const now = Date.now();
33
33
  const last = inboxReports.get(key);
34
- if (last !== void 0 && now - last < INBOX_REPORT_INTERVAL_MS) return;
34
+ if (!input.every && last !== void 0 && now - last < INBOX_REPORT_INTERVAL_MS) return;
35
35
  inboxReports.delete(key);
36
36
  inboxReports.set(key, now);
37
37
  if (inboxReports.size > INBOX_REPORTS_REMEMBERED) {
@@ -39,7 +39,7 @@ async function reportInboxChat(input) {
39
39
  if (oldest.done !== true) inboxReports.delete(oldest.value);
40
40
  }
41
41
  try {
42
- await input.identities.seenChat({
42
+ return await input.identities.seenChat({
43
43
  provider: chat.channel,
44
44
  externalId: chat.chatId,
45
45
  title: (identity.display?.trim() || identity.externalId).slice(0, 200),
@@ -51,6 +51,7 @@ async function reportInboxChat(input) {
51
51
  } catch (error) {
52
52
  inboxReports.delete(key);
53
53
  input.failed?.(error);
54
+ return;
54
55
  }
55
56
  }
56
57
  async function admitMessage(input) {
@@ -76,13 +77,20 @@ async function admitMessage(input) {
76
77
  } catch (error) {
77
78
  input.noticeFailed(error);
78
79
  }
79
- if ((resolved.status === "existing" || resolved.status === "created") && resolved.inbox === true && input.identity.chat === "private" && input.chat !== void 0) await reportInboxChat({
80
- identity: input.identity,
81
- identities: input.identities,
82
- chat: input.chat,
83
- memberId: resolved.member.id,
84
- failed: input.inboxFailed ?? ((error) => console.error("[segmentstream] inbox chat report failed", error))
85
- });
80
+ if ((resolved.status === "existing" || resolved.status === "created") && resolved.inbox === true && input.identity.chat === "private" && input.chat !== void 0) {
81
+ const reported = await reportInboxChat({
82
+ identity: input.identity,
83
+ identities: input.identities,
84
+ chat: input.chat,
85
+ memberId: resolved.member.id,
86
+ every: resolved.takeover === true,
87
+ failed: input.inboxFailed ?? ((error) => console.error("[segmentstream] inbox chat report failed", error))
88
+ });
89
+ if (resolved.takeover === true && reported?.handled === true) return {
90
+ ...resolved,
91
+ handled: true
92
+ };
93
+ }
86
94
  return resolved;
87
95
  }
88
96
  export { admitMessage, localizedText };
@@ -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-D5da2afq.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-Bz1thv2O.mjs";
@@ -11,6 +11,7 @@ import { providerChat } from "../attachment-tools.mjs";
11
11
  import { S as fetchStoredAttachment, b as agentAttachments, bt as withChatAddress, d as prepareInboundMedia, gt as chatAddressOf, i as memberIdOf, m as turnContent } from "../../../_chunks/principal-TJ6zB2rF.mjs";
12
12
  import { channelAttributes, currentChannel, currentKey, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
13
13
  import { chatArchive, chatEvent, replyEvent } from "../chat-archive.mjs";
14
+ import { recordHandledMessage } from "../handled-chat.mjs";
14
15
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
15
16
  import { redactDiagnostic } from "../diagnostics.mjs";
16
17
  import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
@@ -367,6 +368,26 @@ function emailChannelDefinition(options) {
367
368
  return;
368
369
  }
369
370
  if (resolution.status !== "existing" && resolution.status !== "created") return;
371
+ if (resolution.handled === true) {
372
+ await recordHandledMessage(archive(), {
373
+ chat: {
374
+ channel: currentChannel("email"),
375
+ chatId: emailChatId(added.threadId, mail.from),
376
+ threadId: added.threadId
377
+ },
378
+ memberId: resolution.member.id,
379
+ senderId: mail.from,
380
+ senderName: mail.fromName ?? null,
381
+ messageId: added.id,
382
+ text: mail.text,
383
+ files: mail.attachments.map((file) => ({
384
+ name: file.filename,
385
+ mimeType: file.contentType,
386
+ size: file.bytes.byteLength
387
+ }))
388
+ });
389
+ return;
390
+ }
370
391
  const auth = emailPrincipal(resolution.member, mail.from, added.threadId);
371
392
  const memberId = memberIdOf(auth);
372
393
  const inbound = mail.attachments.map((file, index) => ({
@@ -0,0 +1,25 @@
1
+ import type { AdmittedChat } from "./admission.js";
2
+ import { type ChatArchive } from "./chat-archive.js";
3
+ /** A file the person sent, by what the provider says of it: no turn runs to store it. */
4
+ export interface HandledFile {
5
+ readonly name?: string;
6
+ readonly mimeType?: string;
7
+ readonly size?: number;
8
+ }
9
+ /**
10
+ * Records a person's message in a private chat a member of staff took over, which starts no turn.
11
+ * The archive keeps it under the chat's coordinates, as the recorder keeps a turn's message, so
12
+ * staff read it in the inbox and the agent reads it in its context once the chat is handed back.
13
+ * The event is keyed by the provider's message id, so a redelivered message is recorded once. A
14
+ * decision beside it says why the agent did not answer.
15
+ */
16
+ export declare function recordHandledMessage(archive: ChatArchive, input: {
17
+ readonly chat: AdmittedChat;
18
+ readonly memberId: string;
19
+ /** The person's account at the provider. */
20
+ readonly senderId: string | null;
21
+ readonly senderName?: string | null;
22
+ readonly messageId: string;
23
+ readonly text: string;
24
+ readonly files?: ReadonlyArray<HandledFile>;
25
+ }): Promise<void>;
@@ -0,0 +1,43 @@
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 { chatEvent } from "./chat-archive.mjs";
8
+ async function recordHandledMessage(archive, input) {
9
+ const { chat } = input;
10
+ const eventId = `handled:${chat.channel}:${chat.chatId}:${input.messageId}`;
11
+ const coordinates = {
12
+ provider: chat.channel,
13
+ chatId: chat.chatId,
14
+ chatType: "private",
15
+ threadId: chat.threadId === void 0 || chat.threadId === "" ? null : chat.threadId,
16
+ participantIds: [input.memberId],
17
+ senderId: input.senderId,
18
+ messageId: input.messageId
19
+ };
20
+ await archive.append(chatEvent({
21
+ ...coordinates,
22
+ eventId,
23
+ kind: "inbound",
24
+ senderName: input.senderName ?? null,
25
+ text: input.text,
26
+ attachments: (input.files ?? []).map((file, index) => ({
27
+ id: `${eventId}:file:${index}`,
28
+ kind: "file",
29
+ ...file.name === void 0 ? {} : { filename: file.name },
30
+ ...file.mimeType === void 0 ? {} : { contentType: file.mimeType },
31
+ ...file.size === void 0 ? {} : { size: file.size }
32
+ }))
33
+ }));
34
+ await archive.append(chatEvent({
35
+ ...coordinates,
36
+ eventId: `${eventId}:decision`,
37
+ kind: "decision",
38
+ decision: "silent",
39
+ reason: "chat_handled",
40
+ status: "completed"
41
+ }));
42
+ }
43
+ export { recordHandledMessage };
@@ -50,6 +50,16 @@ export type IdentityResolution = (({
50
50
  * admitted the message in, which registers it for the workspace's staff.
51
51
  */
52
52
  readonly inbox?: true;
53
+ /**
54
+ * Staff may take the chat over on its channel: the channel reports every message of the
55
+ * private chat, not just every few minutes, so that it hears at once that staff hold it.
56
+ */
57
+ readonly takeover?: true;
58
+ /**
59
+ * A member of staff holds the chat (`admitMessage` sets it from the chat's report): the
60
+ * channel records the person's message without a turn and the agent answers none of it.
61
+ */
62
+ readonly handled?: true;
53
63
  }) | {
54
64
  readonly status: "pairing_required";
55
65
  } | {
@@ -92,6 +102,8 @@ export interface AgentChat {
92
102
  readonly title: string;
93
103
  readonly purpose: string | null;
94
104
  readonly whenToUse: string | null;
105
+ /** A person's private chat a member of staff took over: the agent answers none of it. */
106
+ readonly handled?: true;
95
107
  }
96
108
  export interface AgentIdentities {
97
109
  lookup(account: ChatAccount): Promise<IdentityLookup>;
@@ -70,7 +70,8 @@ function resolution(value) {
70
70
  ...typeof value.counted === "boolean" ? { counted: value.counted } : {},
71
71
  noticeDue: value.notice_due,
72
72
  onNewUserPending: value.on_new_user_pending,
73
- ...value.inbox === true ? { inbox: true } : {}
73
+ ...value.inbox === true ? { inbox: true } : {},
74
+ ...value.takeover === true ? { takeover: true } : {}
74
75
  };
75
76
  if (value.status === "pairing_required") return { status: "pairing_required" };
76
77
  if (value.status === "refused" && (value.reason === "blocked" || value.reason === "inactive")) return {
@@ -102,7 +103,8 @@ function agentChat(value) {
102
103
  id: value.id,
103
104
  title: value.title,
104
105
  purpose: value.purpose,
105
- whenToUse: value.whenToUse
106
+ whenToUse: value.whenToUse,
107
+ ...value.handled === true ? { handled: true } : {}
106
108
  };
107
109
  }
108
110
  async function refusal(response, call) {
@@ -15,6 +15,7 @@ import { type CapabilityLookup, type MediaPlan } from "../inbound-media/plan.js"
15
15
  import { type Transcriber } from "../inbound-media/speech.js";
16
16
  import { type SlackFileDownload } from "./files.js";
17
17
  import { type RuntimeToken } from "../runtime-token.js";
18
+ import { type ChatArchive } from "../chat-archive.js";
18
19
  /**
19
20
  * The SegmentStream Slack channel (`agent-design.md`, "Channels"): eve's Slack channel at
20
21
  * `POST /eve/v1/slack`, for the Slack app SegmentStream created for the workspace's
@@ -152,6 +153,8 @@ export declare function receive(input: {
152
153
  readonly environment: Environment;
153
154
  /** The chat registry a channel a paired member writes in is reported to. */
154
155
  readonly chats?: AgentChats;
156
+ /** Where a direct message staff took over is recorded; by default, the platform's archive. */
157
+ readonly archive?: () => ChatArchive;
155
158
  /** Keeps the report alive after the turn starts; without it the report is awaited. */
156
159
  readonly waitUntil?: (task: Promise<unknown>) => void;
157
160
  /** Stores the message's files as the member's attachments; without it they are not stored. */
@@ -20,6 +20,8 @@ import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.m
20
20
  import { gatewayTranscriber } from "../inbound-media/speech.mjs";
21
21
  import { slackFileDownload, slackFiles } from "./files.mjs";
22
22
  import { runtimeToken } from "../runtime-token.mjs";
23
+ import { chatArchive } from "../chat-archive.mjs";
24
+ import { recordHandledMessage } from "../handled-chat.mjs";
23
25
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
24
26
  import { AsyncLocalStorage } from "node:async_hooks";
25
27
  import { slackChannel } from "eve/channels/slack";
@@ -223,6 +225,12 @@ function segmentstreamSlack(options) {
223
225
  identities: pairing
224
226
  }));
225
227
  const chats = () => registry;
228
+ let records;
229
+ const archive = () => records ??= chatArchive({
230
+ environment,
231
+ token,
232
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
233
+ });
226
234
  const slackFetch = proxiedSlackFetch(proxy);
227
235
  const request = async (method, body) => {
228
236
  return (await slackFetch(`${SLACK_API}${method}`, {
@@ -270,6 +278,7 @@ function segmentstreamSlack(options) {
270
278
  identities: pairing(),
271
279
  environment,
272
280
  chats: chats(),
281
+ archive,
273
282
  files,
274
283
  ...work === void 0 ? {} : {
275
284
  waitUntil: work.waitUntil,
@@ -399,6 +408,21 @@ async function receive(input) {
399
408
  switch (resolution.status) {
400
409
  case "existing":
401
410
  case "created":
411
+ if (resolution.handled === true) {
412
+ if (turn && ctx.edit === void 0) await recordHandledMessage(input.archive?.() ?? chatArchive({ environment: input.environment }), {
413
+ chat: {
414
+ channel: currentChannel("slack"),
415
+ chatId: ctx.slack.channelId
416
+ },
417
+ memberId: resolution.member.id,
418
+ senderId: user,
419
+ senderName: display ?? null,
420
+ messageId: message.ts,
421
+ text: message.text,
422
+ files: message.attachments
423
+ });
424
+ return null;
425
+ }
402
426
  if (turn && !input.direct && input.chats !== void 0) {
403
427
  const channelId = ctx.slack.channelId;
404
428
  const reported = input.chats.seen({
@@ -10,7 +10,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback, isWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-D5da2afq.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Bz1thv2O.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -10,6 +10,7 @@ import { formatAddress, parseAddress, scopedAddress } from "./sessions.mjs";
10
10
  import { telegramText } from "./texts.mjs";
11
11
  import { workspaceAction } from "./workspace-action.mjs";
12
12
  import { admitMessage } from "../admission.mjs";
13
+ import { currentChannel } from "../channel-scope.mjs";
13
14
  const isWorkspaceCallback = (data) => data?.startsWith("ws:") === true;
14
15
  async function handleWorkspaceCallback(input) {
15
16
  const { query, context } = input;
@@ -125,9 +126,13 @@ async function handleWorkspaceCallback(input) {
125
126
  settings: input.admission,
126
127
  languageCode: locale,
127
128
  sendNotice: (text) => context.telegram.post(text),
128
- noticeFailed: (error) => reportTelegramError("workspace_callback_notice_failed", error)
129
+ noticeFailed: (error) => reportTelegramError("workspace_callback_notice_failed", error),
130
+ ...query.message.chat.type === "private" ? { chat: {
131
+ channel: currentChannel("telegram"),
132
+ chatId: query.from.id
133
+ } } : {}
129
134
  });
130
- if (admitted.status !== "existing" && admitted.status !== "created" || admitted.member.id !== memberIdOf(principal)) return;
135
+ if (admitted.status !== "existing" && admitted.status !== "created" || admitted.member.id !== memberIdOf(principal) || admitted.handled === true) return;
131
136
  const sessions = currentInboundRequest()?.sessions;
132
137
  if (sessions === void 0) throw new Error("The callback has no session transport.");
133
138
  const address = scopedAddress(formatAddress({
@@ -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-D5da2afq.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Bz1thv2O.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";
@@ -415,6 +415,14 @@ async function handleInboundMessage(input) {
415
415
  recordGateDecision("structured_context_actor_changed");
416
416
  return null;
417
417
  }
418
+ if (lookup.handled === true) {
419
+ await recordContent({
420
+ text,
421
+ decoded
422
+ });
423
+ recordGateDecision("chat_handled");
424
+ return null;
425
+ }
418
426
  let turnAdmitted = turn || input.request?.structuredContext !== void 0 || !lookup.provisioned || (lookup.counted === void 0 ? member.roles.includes("member") && member.roles.length > 1 : !lookup.counted);
419
427
  let admissionRefused = false;
420
428
  let structuredClaimed = input.request?.structuredContext !== void 0;
@@ -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, Ft as principalRuntimeSource, It as runtimeEnvelope, L as needsConfirmation, Lt as telegramRuntimeSource, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName } from "../../../_chunks/principal-TJ6zB2rF.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-D5da2afq.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Bz1thv2O.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -12,6 +12,7 @@ import { type ConnectionProxy } from "../connection-proxy.js";
12
12
  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
+ import { type ChatArchive } from "../chat-archive.js";
15
16
  /**
16
17
  * The SegmentStream WhatsApp channel (`agent-design.md`, "Channels"): eve's Chat SDK bridge with
17
18
  * the Chat SDK WhatsApp adapter, at `POST /eve/v1/whatsapp` for `channels.whatsapp` and at
@@ -121,10 +122,12 @@ export declare function receive(input: {
121
122
  readonly id: string;
122
123
  readonly post: (message: string | PostableCard) => Promise<unknown>;
123
124
  };
124
- readonly message: Pick<Message, "author" | "text" | "attachments">;
125
+ readonly message: Pick<Message, "id" | "author" | "text" | "attachments">;
125
126
  readonly admission: AdmissionSettings;
126
127
  readonly identities: AgentIdentities;
127
128
  readonly environment: Environment;
129
+ /** Where a message in a chat staff took over is recorded; by default, the platform's archive. */
130
+ readonly archive?: () => ChatArchive;
128
131
  }): Promise<SessionAuthContext | undefined>;
129
132
  /**
130
133
  * The pairing reply: the workspace's text with a button opening the link, which WhatsApp shows as
@@ -20,6 +20,8 @@ import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs
20
20
  import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
21
21
  import { agentIdentities } from "../identities.mjs";
22
22
  import { runtimeToken } from "../runtime-token.mjs";
23
+ import { chatArchive } from "../chat-archive.mjs";
24
+ import { recordHandledMessage } from "../handled-chat.mjs";
23
25
  import { withPlainLinks } from "./links.mjs";
24
26
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
25
27
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -182,6 +184,12 @@ function segmentstreamWhatsApp(options) {
182
184
  const token = options.token ?? runtimeToken;
183
185
  const proxies = new Map();
184
186
  let identities = options.identities;
187
+ let archive;
188
+ const chats = () => archive ??= chatArchive({
189
+ environment,
190
+ token,
191
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
192
+ });
185
193
  const settings = () => options.settings(currentChannel("whatsapp"));
186
194
  const runtime = {
187
195
  enabled: () => channelsEnabled(environment) && settings() !== null && webhookSecret(environment) !== void 0,
@@ -239,7 +247,8 @@ function segmentstreamWhatsApp(options) {
239
247
  message,
240
248
  admission: options.admission(),
241
249
  identities: pairing(),
242
- environment
250
+ environment,
251
+ archive: chats
243
252
  });
244
253
  const memberId = memberIdOf(auth);
245
254
  if (auth === void 0 || memberId === void 0) return;
@@ -322,14 +331,31 @@ async function receive(input) {
322
331
  });
323
332
  switch (resolution.status) {
324
333
  case "existing":
325
- case "created": return turn ? withChatAddress(whatsappPrincipal(resolution.member, sender), {
326
- provider: "whatsapp",
327
- ...currentChannel("whatsapp") === "whatsapp" ? {} : { channel: currentChannel("whatsapp") },
328
- chatId: thread.id,
329
- threadId: "",
330
- kind: "private",
331
- peer: sender
332
- }) : void 0;
334
+ case "created":
335
+ if (resolution.handled === true) {
336
+ if (!turn) return;
337
+ await recordHandledMessage(input.archive?.() ?? chatArchive({ environment: input.environment }), {
338
+ chat: {
339
+ channel: currentChannel("whatsapp"),
340
+ chatId: thread.id
341
+ },
342
+ memberId: resolution.member.id,
343
+ senderId: sender,
344
+ senderName: display ?? null,
345
+ messageId: message.id,
346
+ text: message.text,
347
+ files: message.attachments
348
+ });
349
+ return;
350
+ }
351
+ return turn ? withChatAddress(whatsappPrincipal(resolution.member, sender), {
352
+ provider: "whatsapp",
353
+ ...currentChannel("whatsapp") === "whatsapp" ? {} : { channel: currentChannel("whatsapp") },
354
+ chatId: thread.id,
355
+ threadId: "",
356
+ kind: "private",
357
+ peer: sender
358
+ }) : void 0;
333
359
  case "pairing_required": {
334
360
  const text = localizedText(admission.replies.pairingRequired);
335
361
  if (text !== void 0 && turn) {
@@ -11,6 +11,7 @@ import { providerChat } from "../attachment-tools.mjs";
11
11
  import { S as fetchStoredAttachment, b as agentAttachments, bt as withChatAddress, d as prepareInboundMedia, gt as chatAddressOf, i as memberIdOf, m as turnContent, xt as workspaceIdentityProvider } from "../../../_chunks/principal-TJ6zB2rF.mjs";
12
12
  import { CHANNEL_ATTRIBUTE, channelKey } from "../channel-scope.mjs";
13
13
  import { chatArchive, chatEvent } from "../chat-archive.mjs";
14
+ import { recordHandledMessage } from "../handled-chat.mjs";
14
15
  import { connectionProxy } from "../connection-proxy.mjs";
15
16
  import { redactDiagnostic } from "../diagnostics.mjs";
16
17
  import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
@@ -269,6 +270,25 @@ function workspaceChannelDefinition(options) {
269
270
  return;
270
271
  }
271
272
  if (!turn) return;
273
+ if (resolution.handled === true) {
274
+ await recordHandledMessage(archive(), {
275
+ chat: {
276
+ channel: name,
277
+ chatId: message.chatId
278
+ },
279
+ memberId: resolution.member.id,
280
+ senderId: message.sender.id,
281
+ senderName: message.sender.name ?? null,
282
+ messageId: message.id,
283
+ text: message.text,
284
+ files: (files ? message.files ?? [] : []).map((file) => ({
285
+ name: file.filename,
286
+ mimeType: file.contentType,
287
+ ...file.size === void 0 ? {} : { size: file.size }
288
+ }))
289
+ });
290
+ return;
291
+ }
272
292
  const auth = workspaceChannelPrincipal(name, resolution.member, message.sender, message.chatId);
273
293
  const memberId = memberIdOf(auth);
274
294
  const inbound = (files ? message.files ?? [] : []).map((file, index) => ({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.59.5",
3
+ "version": "0.60.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",
@@ -80,7 +80,7 @@
80
80
  "@chat-adapter/state-memory": "4.42.0",
81
81
  "@chat-adapter/telegram": "4.41.0",
82
82
  "@chat-adapter/whatsapp": "4.42.0",
83
- "@segmentstream/ontology": "0.122.0",
83
+ "@segmentstream/ontology": "0.124.0",
84
84
  "@vercel/oidc": "^3.8.4",
85
85
  "ai": "^7.0.172",
86
86
  "chat": "4.42.0",