@segmentstream/agent 0.59.7 → 0.61.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,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.61.0
4
+
5
+ `"handoff": true` in `agent/segmentstream.json` gives the model `segmentstream__handoff({ reason })`
6
+ in a person's private chat on a messenger, mail or workspace channel. It hands the chat over to the
7
+ workspace's staff with what the person needs, and from the person's next message on the agent
8
+ answers nothing there until a member takes the chat over or hands it back. Where staff cannot take
9
+ the chat over, the tool answers `handedOff: false` and the agent goes on helping. Off when absent.
10
+
11
+ Pins @segmentstream/ontology 0.125.0.
12
+
13
+ ## 0.60.0
14
+
15
+ The agent stands down in a private chat staff took over. Where the ontology's inbox lets staff take
16
+ a chat over, the agent reports every message of the person's private chat, and while a member of
17
+ staff holds it, Telegram, WhatsApp, Slack direct messages, email threads and workspace channels
18
+ record the person's message in the archive under the chat, with files by name, and start no turn.
19
+ Once the chat is handed back, the next turn reads what was said meanwhile in its chat context.
20
+
21
+ Pins @segmentstream/ontology 0.124.0.
22
+
3
23
  ## 0.59.7
4
24
 
5
25
  Pins @segmentstream/ontology 0.123.0.
@@ -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.7";
7
+ var version = "0.61.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -135,6 +135,13 @@ export interface SegmentStreamAgentConfigInput {
135
135
  * question it could not answer, for the workspace's builders to read. Off when absent.
136
136
  */
137
137
  readonly unanswered?: boolean;
138
+ /**
139
+ * Whether the model gets `segmentstream__handoff`, which hands a person's private chat over to
140
+ * the workspace's staff on a channel the ontology's `inbox.takeover` lists; the agent then
141
+ * answers none of the person's messages until a member takes the chat over or hands it back.
142
+ * Off when absent.
143
+ */
144
+ readonly handoff?: boolean;
138
145
  /**
139
146
  * The web the agent may read: `segmentstream__web_fetch` fetches `https://` pages of these
140
147
  * domains, each also covering its subdomains, for callers who hold `agent_tool:web`. No web
@@ -467,6 +474,11 @@ export interface SegmentStreamAgentConfig extends AdmissionSettings {
467
474
  * {@link SegmentStreamAgentConfigInput.unanswered}.
468
475
  */
469
476
  readonly unanswered?: boolean;
477
+ /**
478
+ * Whether the handoff tool is on; validation sets it only when it is. See
479
+ * {@link SegmentStreamAgentConfigInput.handoff}.
480
+ */
481
+ readonly handoff?: boolean;
470
482
  /** The domains the web tools reach; absent without web tools. See {@link WebSettings}. */
471
483
  readonly web?: WebSettings;
472
484
  /** The agent's browser; absent without the browser tool. See {@link BrowserSettings}. */
@@ -1013,6 +1013,7 @@ function validateConfig(input, options = {}) {
1013
1013
  "sandbox",
1014
1014
  "workspaceSource",
1015
1015
  "unanswered",
1016
+ "handoff",
1016
1017
  "web",
1017
1018
  "browser",
1018
1019
  "sessions",
@@ -1214,6 +1215,11 @@ function validateConfig(input, options = {}) {
1214
1215
  message: "must be true or false",
1215
1216
  path: ["unanswered"]
1216
1217
  });
1218
+ const handoff = root?.handoff ?? false;
1219
+ if (typeof handoff !== "boolean") issues.push({
1220
+ message: "must be true or false",
1221
+ path: ["handoff"]
1222
+ });
1217
1223
  const web = webSettings(root?.web, issues);
1218
1224
  const browser = browserSettings(root?.browser, issues);
1219
1225
  if (root?.browser !== void 0 && sandbox !== true) issues.push({
@@ -1244,6 +1250,7 @@ function validateConfig(input, options = {}) {
1244
1250
  sandbox: sandbox === true,
1245
1251
  ...workspaceSource === true ? { workspaceSource: true } : {},
1246
1252
  ...unanswered === true ? { unanswered: true } : {},
1253
+ ...handoff === true ? { handoff: true } : {},
1247
1254
  ...web === null ? {} : { web },
1248
1255
  ...browser === null ? {} : { browser },
1249
1256
  sessions,
@@ -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-R1wFbfMQ.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata--ikICimB.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,16 @@ 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;
107
+ }
108
+ /** A handoff the ontology recorded, or found waiting, for a person's private chat. */
109
+ export interface ChatHandoff {
110
+ readonly id: string;
111
+ /** When the agent handed the person over; null when a member of staff holds the chat already. */
112
+ readonly handoffAt: string | null;
113
+ /** A member of staff holds the chat already. */
114
+ readonly handled?: true;
95
115
  }
96
116
  export interface AgentIdentities {
97
117
  lookup(account: ChatAccount): Promise<IdentityLookup>;
@@ -129,6 +149,17 @@ export interface AgentIdentities {
129
149
  readonly recipient?: string;
130
150
  readonly threadId?: string;
131
151
  }): Promise<AgentChat>;
152
+ /**
153
+ * Hands a person's private chat over to the workspace's staff, saying what they need. Undefined
154
+ * when the ontology answers 404: it hands the chat to no one, because the chat is not
155
+ * registered, not on a channel staff take chats over on, or not the person's.
156
+ */
157
+ handOffChat(input: {
158
+ readonly provider: string;
159
+ readonly externalId: string;
160
+ readonly memberId: string;
161
+ readonly reason: string;
162
+ }): Promise<ChatHandoff | undefined>;
132
163
  }
133
164
  /** The ontology service refused or failed a pairing call. Carries its error code, not its body. */
134
165
  export declare class AgentIdentityError extends Error {
@@ -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 {
@@ -93,6 +94,17 @@ function resolution(value) {
93
94
  function nullableString(value) {
94
95
  return value === null || typeof value === "string";
95
96
  }
97
+ function chatHandoff(value) {
98
+ if (!isRecord(value) || typeof value.id !== "string" || !nullableString(value.handoffAt)) throw new AgentIdentityError({
99
+ code: "invalid_response",
100
+ message: "The ontology service answered the chat handoff with an invalid body."
101
+ });
102
+ return {
103
+ id: value.id,
104
+ handoffAt: value.handoffAt,
105
+ ...value.handled === true ? { handled: true } : {}
106
+ };
107
+ }
96
108
  function agentChat(value) {
97
109
  if (!isRecord(value) || typeof value.id !== "string" || typeof value.title !== "string" || !nullableString(value.purpose) || !nullableString(value.whenToUse)) throw new AgentIdentityError({
98
110
  code: "invalid_response",
@@ -102,7 +114,8 @@ function agentChat(value) {
102
114
  id: value.id,
103
115
  title: value.title,
104
116
  purpose: value.purpose,
105
- whenToUse: value.whenToUse
117
+ whenToUse: value.whenToUse,
118
+ ...value.handled === true ? { handled: true } : {}
106
119
  };
107
120
  }
108
121
  async function refusal(response, call) {
@@ -243,6 +256,12 @@ function agentIdentities(input) {
243
256
  const response = await call("/chats/seen", { body: chat });
244
257
  if (!response.ok) throw await safeRefusal(response, "chat report");
245
258
  return agentChat(await response.json());
259
+ },
260
+ async handOffChat(input) {
261
+ const response = await call("/chats/handoff", { body: input });
262
+ if (response.status === 404) return;
263
+ if (!response.ok) throw await safeRefusal(response, "chat handoff");
264
+ return chatHandoff(await response.json());
246
265
  }
247
266
  };
248
267
  }
@@ -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-R1wFbfMQ.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata--ikICimB.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-R1wFbfMQ.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata--ikICimB.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-R1wFbfMQ.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata--ikICimB.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) => ({
@@ -0,0 +1,13 @@
1
+ import { type AgentIdentities } from "../lib/identities.js";
2
+ /**
3
+ * `segmentstream__handoff`: hands the person's private chat over to the workspace's staff, with
4
+ * what they need. The ontology marks the chat (`agent_chat.handoffAt`, `handoffReason`), so the
5
+ * inbox shows it waiting, and from the person's next message on the agent records what they write
6
+ * and answers nothing, until a member takes the chat over or hands it back. The model tells the
7
+ * person in its own words, in this turn. Offered while `agent/segmentstream.json` sets
8
+ * `"handoff": true`, in a person's private chat on a messenger, mail or workspace channel; the
9
+ * ontology refuses a chat on a channel its `inbox.takeover` does not list, and the tool says so.
10
+ */
11
+ export declare function handoffTool(identities: () => AgentIdentities): import("eve/tools").ToolDefinition<Record<string, unknown>, import("../lib/workflow-serializable.js").WorkflowSerializable>;
12
+ declare const _default: import("eve").DynamicSentinel<import("eve/tools").DynamicToolResult, import("eve").DynamicContext>;
13
+ export default _default;
@@ -0,0 +1,60 @@
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 segmentstream from "../extension.mjs";
8
+ import { agentTaskIdOf } from "../lib/agent-task.mjs";
9
+ import { stringArgument } from "../lib/attachment-tools.mjs";
10
+ import { _t as chatChannel, gt as chatAddressOf, i as memberIdOf } from "../../_chunks/principal-TJ6zB2rF.mjs";
11
+ import { appOrigin } from "../lib/environment.mjs";
12
+ import { agentIdentities } from "../lib/identities.mjs";
13
+ import { runtimeToken } from "../lib/runtime-token.mjs";
14
+ import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
15
+ import { defineDynamic, defineTool } from "eve/tools";
16
+ const MAX_REASON = 1e3;
17
+ function handoffChat(principal) {
18
+ const chat = chatAddressOf(principal);
19
+ const memberId = memberIdOf(principal);
20
+ return chat === void 0 || chat.kind !== "private" || chat.provider === "web" || memberId === void 0 || agentTaskIdOf(principal) !== void 0 ? void 0 : {
21
+ provider: chatChannel(chat),
22
+ externalId: chat.chatId,
23
+ memberId
24
+ };
25
+ }
26
+ function handoffTool(identities) {
27
+ return defineTool({
28
+ availableInSubagents: false,
29
+ description: "Hand this conversation over to a person on the workspace's staff: when the person asks for a human, or needs something only staff can do and your instructions say to hand such cases over. Staff see the chat waiting with your reason; from the person's next message on, you answer nothing until staff hand the chat back. After calling it, tell the person in your own words that a colleague will continue here. If it answers handedOff: false, staff cannot take this chat over: keep helping the person yourself.",
30
+ inputSchema: {
31
+ type: "object",
32
+ properties: { reason: {
33
+ type: "string",
34
+ description: "For staff, in a sentence or two: what the person needs and what you already told them."
35
+ } },
36
+ required: ["reason"],
37
+ additionalProperties: false
38
+ },
39
+ async execute(input, ctx) {
40
+ const reason = stringArgument(input ?? {}, "reason").trim().slice(0, MAX_REASON);
41
+ const chat = handoffChat(ctx.session.auth.current);
42
+ if (chat === void 0 || reason === "") return workflowToolResult({ handedOff: false }, ctx);
43
+ const handed = await identities().handOffChat({
44
+ ...chat,
45
+ reason
46
+ });
47
+ return workflowToolResult(handed === void 0 ? { handedOff: false } : handed.handled === true ? {
48
+ handedOff: true,
49
+ staffHoldChat: true
50
+ } : { handedOff: true }, ctx);
51
+ }
52
+ });
53
+ }
54
+ let identities;
55
+ const handoff = handoffTool(() => identities ??= agentIdentities({
56
+ origin: appOrigin(),
57
+ token: runtimeToken
58
+ }));
59
+ var handoff_default = defineDynamic((context) => segmentstream.config.handoff !== true || handoffChat(context.session.auth.current) === void 0 ? null : handoff);
60
+ export { handoff_default as default, handoffTool };
@@ -8,6 +8,7 @@ export { default as attachments_send } from "../extension/tools/attachments_send
8
8
  export { default as attachments_stage } from "../extension/tools/attachments_stage.js";
9
9
  export { default as attachments_table } from "../extension/tools/attachments_table.js";
10
10
  export { default as browser } from "../extension/tools/browser.js";
11
+ export { default as handoff } from "../extension/tools/handoff.js";
11
12
  export { default as no_reply } from "../extension/tools/no_reply.js";
12
13
  export { default as ontology_call_file } from "../extension/tools/ontology_call_file.js";
13
14
  export { default as questions_ask } from "../extension/tools/questions_ask.js";
@@ -12,6 +12,7 @@ import attachments_send_default from "../extension/tools/attachments_send.mjs";
12
12
  import attachments_stage_default from "../extension/tools/attachments_stage.mjs";
13
13
  import attachments_table_default from "../extension/tools/attachments_table.mjs";
14
14
  import browser_default from "../extension/tools/browser.mjs";
15
+ import handoff_default from "../extension/tools/handoff.mjs";
15
16
  import no_reply_default from "../extension/tools/no_reply.mjs";
16
17
  import ontology_call_file_default from "../extension/tools/ontology_call_file.mjs";
17
18
  import questions_ask_default from "../extension/tools/questions_ask.mjs";
@@ -19,4 +20,4 @@ import sandbox_default from "../extension/tools/sandbox.mjs";
19
20
  import unanswered_default from "../extension/tools/unanswered.mjs";
20
21
  import web_fetch_default from "../extension/tools/web_fetch.mjs";
21
22
  import workspace_source_default from "../extension/tools/workspace_source.mjs";
22
- export { attachments_discard_default as attachments_discard, attachments_list_default as attachments_list, attachments_promote_default as attachments_promote, attachments_read_default as attachments_read, attachments_send_default as attachments_send, attachments_stage_default as attachments_stage, attachments_table_default as attachments_table, browser_default as browser, no_reply_default as no_reply, ontology_call_file_default as ontology_call_file, questions_ask_default as questions_ask, sandbox_default as sandbox, unanswered_default as unanswered, web_fetch_default as web_fetch, workspace_source_default as workspace_source };
23
+ export { attachments_discard_default as attachments_discard, attachments_list_default as attachments_list, attachments_promote_default as attachments_promote, attachments_read_default as attachments_read, attachments_send_default as attachments_send, attachments_stage_default as attachments_stage, attachments_table_default as attachments_table, browser_default as browser, handoff_default as handoff, no_reply_default as no_reply, ontology_call_file_default as ontology_call_file, questions_ask_default as questions_ask, sandbox_default as sandbox, unanswered_default as unanswered, web_fetch_default as web_fetch, workspace_source_default as workspace_source };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.59.7",
3
+ "version": "0.61.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.123.0",
83
+ "@segmentstream/ontology": "0.125.0",
84
84
  "@vercel/oidc": "^3.8.4",
85
85
  "ai": "^7.0.172",
86
86
  "chat": "4.42.0",