@segmentstream/agent 0.34.1 → 0.36.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.
@@ -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.34.1";
7
+ var version = "0.36.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `POST /eve/v1/slack`: the bot of the workspace's `SlackConnection`, through the Slack app
3
+ * SegmentStream created for it and named in `channels.slack`. SegmentStream relays the app's
4
+ * events, interactions and slash commands here. Without that setting, or outside production, the
5
+ * route answers 404.
6
+ */
7
+ declare const _default: import("eve/channels/slack").SlackChannel;
8
+ export default _default;
@@ -0,0 +1,14 @@
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 { segmentstreamSlack } from "../lib/slack/adapter.mjs";
9
+ var slack_default = segmentstreamSlack({
10
+ settings: () => segmentstream.config.channels.slack,
11
+ admission: () => segmentstream.config,
12
+ groups: () => segmentstream.config.groups
13
+ });
14
+ export { slack_default as default };
@@ -100,6 +100,10 @@ export interface SegmentStreamAgentConfigInput {
100
100
  /** The key of the workspace's `WhatsAppConnection`, such as `whatsapp`. */
101
101
  readonly connection: string;
102
102
  };
103
+ readonly slack?: {
104
+ /** The key of the workspace's `SlackConnection`, such as `slack`. */
105
+ readonly connection: string;
106
+ };
103
107
  };
104
108
  readonly models?: {
105
109
  /**
@@ -200,6 +204,7 @@ export interface SegmentStreamAgentConfig extends AdmissionSettings {
200
204
  readonly channels: {
201
205
  readonly telegram: TelegramSettings | null;
202
206
  readonly whatsapp: WhatsAppSettings | null;
207
+ readonly slack: SlackSettings | null;
203
208
  };
204
209
  readonly models: {
205
210
  /**
@@ -224,6 +229,14 @@ export interface ConfigIssue {
224
229
  readonly message: string;
225
230
  readonly path: ReadonlyArray<string>;
226
231
  }
232
+ /** A setting `agent/segmentstream.json` sets that configures nothing: accepted, and ignored. */
233
+ export type ConfigWarning = ConfigIssue;
234
+ /**
235
+ * Every setting the configuration sets that configures nothing, for the deploy output and the
236
+ * console, so the builder learns of it where they work: retired session and group keys, and the
237
+ * older policies' thresholds where the conversation policy applies. The agent also logs them.
238
+ */
239
+ export declare function configWarnings(value: unknown): ReadonlyArray<ConfigWarning>;
227
240
  type Validation = {
228
241
  readonly value: SegmentStreamAgentConfig;
229
242
  readonly issues?: undefined;
@@ -243,6 +256,14 @@ export declare class SegmentStreamAgentConfigError extends Error {
243
256
  export interface WhatsAppSettings {
244
257
  readonly connection: string;
245
258
  }
259
+ /**
260
+ * The Slack channel: the bot of the workspace's `SlackConnection`, through the Slack app
261
+ * SegmentStream created for it, answers the members who paired their Slack account. SegmentStream
262
+ * relays the app's events, interactions and slash commands to the agent.
263
+ */
264
+ export interface SlackSettings {
265
+ readonly connection: string;
266
+ }
246
267
  /**
247
268
  * The chat model choice `agent.ts` passes to `segmentstream.model()`, validated like `models.chat`
248
269
  * of `agent/segmentstream.json`, where it normally comes from.
@@ -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 { effectiveGroupPolicy, groupPolicy, ignoredGroupSettings } from "./lib/group-routing/policy.mjs";
7
+ import { effectiveGroupPolicy, groupPolicy, ignoredGroupSettings, inapplicableGroupThresholds } from "./lib/group-routing/policy.mjs";
8
8
  import { localizedText as localizedText$1 } from "./lib/admission.mjs";
9
9
  import { STRUCTURED_KINDS } from "./lib/telegram/structured-settings.mjs";
10
10
  import { TELEGRAM_TEXT_KEYS } from "./lib/telegram/texts.mjs";
@@ -38,6 +38,29 @@ const ADMISSION_REPLY_KEYS = [
38
38
  "refused"
39
39
  ];
40
40
  const SESSION_SCOPES = ["chat", "thread"];
41
+ const IGNORED_SESSION_KEYS = [
42
+ "compactAt",
43
+ "timezone",
44
+ "idleResetHours"
45
+ ];
46
+ const INAPPLICABLE_THRESHOLD = "applies only to the legacy and engaged policies; the conversation policy reads thresholds.reply and thresholds.defer, so remove it";
47
+ function configWarnings(value) {
48
+ const root = value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
49
+ return [
50
+ ...(root?.sessions !== null && typeof root?.sessions === "object" && !Array.isArray(root.sessions) ? Object.keys(root.sessions) : []).filter((key) => IGNORED_SESSION_KEYS.includes(key)).map((key) => ({
51
+ path: ["sessions", key],
52
+ message: "no longer configures anything: eve compacts sessions and ends idle ones after limits.sessionTimeoutMs in agent.ts, so remove it"
53
+ })),
54
+ ...ignoredGroupSettings(root?.groups, ["groups"]).map((path) => ({
55
+ path: path.split("."),
56
+ message: "no longer configures anything: group routing reads the chat's recent messages and has no conversation timers, so remove it"
57
+ })),
58
+ ...inapplicableGroupThresholds(root?.groups).map((path) => ({
59
+ path: ["groups", ...path],
60
+ message: INAPPLICABLE_THRESHOLD
61
+ }))
62
+ ];
63
+ }
41
64
  var SegmentStreamAgentConfigError = class extends Error {
42
65
  issues;
43
66
  name = "SegmentStreamAgentConfigError";
@@ -85,6 +108,24 @@ function whatsappSettings(value, issues) {
85
108
  }
86
109
  return { connection: whatsapp.connection };
87
110
  }
111
+ function slackSettings(value, issues) {
112
+ const path = ["channels", "slack"];
113
+ const slack = section({
114
+ value,
115
+ path,
116
+ allowed: ["connection"],
117
+ issues
118
+ });
119
+ if (slack === void 0) return null;
120
+ if (typeof slack.connection !== "string" || !CONNECTION_KEY.test(slack.connection)) {
121
+ issues.push({
122
+ message: "must be a connection key such as slack",
123
+ path: [...path, "connection"]
124
+ });
125
+ return null;
126
+ }
127
+ return { connection: slack.connection };
128
+ }
88
129
  function telegramSettings(value, issues) {
89
130
  const path = ["channels", "telegram"];
90
131
  const telegram = section({
@@ -326,12 +367,8 @@ function isSessionScope(value) {
326
367
  return SESSION_SCOPES.some((scope) => scope === value);
327
368
  }
328
369
  let ignoredGroupSettingsReported = false;
329
- const IGNORED_SESSION_KEYS = [
330
- "compactAt",
331
- "timezone",
332
- "idleResetHours"
333
- ];
334
370
  let ignoredSessionKeysReported = false;
371
+ let inapplicableThresholdsReported = false;
335
372
  function sessionSettings(value, issues) {
336
373
  const path = ["sessions"];
337
374
  const sessions = section({
@@ -553,7 +590,11 @@ function validateConfig(input, options = {}) {
553
590
  const channels = section({
554
591
  value: root?.channels,
555
592
  path: ["channels"],
556
- allowed: ["telegram", "whatsapp"],
593
+ allowed: [
594
+ "telegram",
595
+ "whatsapp",
596
+ "slack"
597
+ ],
557
598
  issues
558
599
  });
559
600
  const models = section({
@@ -586,6 +627,7 @@ function validateConfig(input, options = {}) {
586
627
  });
587
628
  const telegram = telegramSettings(channels?.telegram, issues);
588
629
  const whatsapp = whatsappSettings(channels?.whatsapp, issues);
630
+ const slack = slackSettings(channels?.slack, issues);
589
631
  for (const issue of groupPolicyIssues(root?.groups)) issues.push({
590
632
  ...issue,
591
633
  path: ["groups", ...issue.path]
@@ -595,6 +637,11 @@ function validateConfig(input, options = {}) {
595
637
  ignoredGroupSettingsReported = true;
596
638
  console.warn(`[segmentstream] agent/segmentstream.json: ${ignoredGroups.join(", ")} no longer configure anything and are ignored. Group routing has no conversation timers: the classifier reads the chat's last groups.smart.context.messages messages, however old; remove these keys.`);
597
639
  }
640
+ const inapplicable = inapplicableGroupThresholds(root?.groups);
641
+ if (inapplicable.length > 0 && !inapplicableThresholdsReported) {
642
+ inapplicableThresholdsReported = true;
643
+ console.warn(`[segmentstream] agent/segmentstream.json: ${inapplicable.map((path) => ["groups", ...path].join(".")).join(", ")} ${INAPPLICABLE_THRESHOLD}.`);
644
+ }
598
645
  let authoredGroups = root?.groups;
599
646
  if (authoredGroups !== void 0 && groupPolicyIssues(authoredGroups).length === 0) try {
600
647
  authoredGroups = expandGroupFiles(authoredGroups, (path) => {
@@ -704,6 +751,10 @@ function validateConfig(input, options = {}) {
704
751
  message: "is required for WhatsApp",
705
752
  path: ["replies", "pairingRequired"]
706
753
  });
754
+ if (slack !== null && replies.pairingRequired === void 0) issues.push({
755
+ message: "is required for Slack",
756
+ path: ["replies", "pairingRequired"]
757
+ });
707
758
  if (typeof connection !== "boolean") issues.push({
708
759
  message: "must be true or false",
709
760
  path: ["ontology", "connection"]
@@ -721,7 +772,8 @@ function validateConfig(input, options = {}) {
721
772
  ...telegram,
722
773
  policy: groups.mode
723
774
  },
724
- whatsapp
775
+ whatsapp,
776
+ slack
725
777
  },
726
778
  models: {
727
779
  chat,
@@ -750,4 +802,4 @@ function manifestOf(config) {
750
802
  if (validation.issues !== void 0) throw new SegmentStreamAgentConfigError(validation.issues);
751
803
  return validation.value;
752
804
  }
753
- export { ADMISSION_REPLY_KEYS, DEFAULT_ADMISSION_LIMITS, DEFAULT_ATTACHMENTS_MODEL, DEFAULT_DECISION_MODEL, DEFAULT_IMAGE_DESCRIPTION_MODEL, DEFAULT_STT_MODEL, SESSION_SCOPES, SegmentStreamAgentConfigError, TELEGRAM_POLICIES, chatModelChoiceOf, configSchema, isLegacyAgentArchive, manifestOf, validateConfig };
805
+ export { ADMISSION_REPLY_KEYS, DEFAULT_ADMISSION_LIMITS, DEFAULT_ATTACHMENTS_MODEL, DEFAULT_DECISION_MODEL, DEFAULT_IMAGE_DESCRIPTION_MODEL, DEFAULT_STT_MODEL, SESSION_SCOPES, SegmentStreamAgentConfigError, TELEGRAM_POLICIES, chatModelChoiceOf, configSchema, configWarnings, isLegacyAgentArchive, manifestOf, validateConfig };
@@ -9,8 +9,8 @@ import { redactDiagnostic } from "./diagnostics.mjs";
9
9
  import { channelsEnabled, runtimeIdentityEnvironment } from "./environment.mjs";
10
10
  import { runtimeTokenVerifier } from "./runtime-identity.mjs";
11
11
  import { runtimeRequestFailure } from "./telegram/runtime-request.mjs";
12
- import { POST, defineChannel } from "eve/channels";
13
12
  import { interaction, reply } from "eve/events";
13
+ import { POST, defineChannel } from "eve/channels";
14
14
  import { SessionNotActiveError } from "eve/sessions";
15
15
  const RETIRE_TIMEOUT_MS = 2e4;
16
16
  const FAILED = {
@@ -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-BMjP89Jo.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-DZwapj-X.mjs";
@@ -8,8 +8,8 @@ import { agentTaskIdOf } from "./agent-task.mjs";
8
8
  import { conversationCoordinates } from "./conversation-runtime.mjs";
9
9
  import { collapseConversationEvents, conversations, topicContext } from "./conversations.mjs";
10
10
  import { p as reportTelegramError } from "../../_chunks/inbound-request-DgQB4g1J.mjs";
11
- import { deliveries, runs, turns } from "eve/events";
12
11
  import { createHash } from "node:crypto";
12
+ import { deliveries, runs, turns } from "eve/events";
13
13
  import { defineState } from "eve/context";
14
14
  const chatContextState = defineState("segmentstream.chatContext", () => ({}));
15
15
  const OVERLAP_MS = 6e5;
@@ -78,6 +78,15 @@ export declare const IGNORED_GROUP_SETTINGS: {
78
78
  export declare function ignoredGroupSetting(path: ReadonlyArray<string>): boolean;
79
79
  /** The dotted paths of ignored settings an authored `groups` value sets, for a deploy warning. */
80
80
  export declare function ignoredGroupSettings(value: unknown, prefix?: ReadonlyArray<string>): string[];
81
+ /**
82
+ * Paths of `engaged`, `neutral` and `humanThread` thresholds an authored `groups` value sets
83
+ * where the conversation policy applies and nothing reads them. Chats inherit the top level and a
84
+ * chat scope its parent chat; the shadow policy overlays each chat's effective policy, and takes
85
+ * that policy when it names none. Switching policy keeps authored thresholds
86
+ * (`overlaySmartPolicy`), so a threshold stays applicable while any section on an older policy
87
+ * inherits it.
88
+ */
89
+ export declare function inapplicableGroupThresholds(value: unknown): string[][];
81
90
  export declare function groupPolicy(input?: GroupPolicyInput, aliases?: {
82
91
  readonly mode?: string;
83
92
  readonly model?: string;
@@ -106,6 +106,61 @@ function ignoredGroupSettings(value, prefix = []) {
106
106
  if (value === null || typeof value !== "object" || Array.isArray(value)) return ignoredGroupSetting(prefix) ? [prefix.join(".")] : [];
107
107
  return Object.entries(value).flatMap(([key, child]) => ignoredGroupSettings(child, [...prefix, key]));
108
108
  }
109
+ const PARTICIPANT_THRESHOLDS = [
110
+ "engaged",
111
+ "neutral",
112
+ "humanThread"
113
+ ];
114
+ function inapplicableGroupThresholds(value) {
115
+ const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : void 0;
116
+ const policyOf = (smart) => {
117
+ const policy = object(object(smart)?.engagement)?.policy;
118
+ return typeof policy === "string" ? policy : void 0;
119
+ };
120
+ const thresholdsOf = (smart) => object(object(smart)?.thresholds) ?? {};
121
+ const groups = object(value);
122
+ const chats = object(groups?.chats) ?? {};
123
+ const contexts = [{
124
+ path: ["smart"],
125
+ thresholds: thresholdsOf(groups?.smart),
126
+ parent: void 0,
127
+ policy: policyOf(groups?.smart) ?? "legacy"
128
+ }];
129
+ for (const key of Object.keys(chats).sort((a, b) => Number(a.includes("/")) - Number(b.includes("/")))) {
130
+ const parentKey = key.includes("/") ? key.slice(0, key.indexOf("/")) : void 0;
131
+ const found = contexts.findIndex((c) => c.path[1] === parentKey);
132
+ const parent = found === -1 ? 0 : found;
133
+ const smart = object(chats[key])?.smart;
134
+ contexts.push({
135
+ path: [
136
+ "chats",
137
+ key,
138
+ "smart"
139
+ ],
140
+ thresholds: thresholdsOf(smart),
141
+ parent,
142
+ policy: policyOf(smart) ?? contexts[parent].policy
143
+ });
144
+ }
145
+ const shadow = object(groups?.observability)?.shadow;
146
+ const shadowThresholds = thresholdsOf(shadow);
147
+ const shadowPolicy = policyOf(shadow);
148
+ const source = (index, key) => {
149
+ for (let i = index; i !== void 0; i = contexts[i].parent) if (key in contexts[i].thresholds) return i;
150
+ };
151
+ const shadowReads = (key) => shadow !== void 0 && shadowPolicy !== void 0 && shadowPolicy !== "conversation" && !(key in shadowThresholds);
152
+ const participant = (thresholds) => Object.keys(thresholds).filter((key) => PARTICIPANT_THRESHOLDS.includes(key));
153
+ return [...contexts.flatMap((context, index) => context.policy !== "conversation" ? [] : participant(context.thresholds).filter((key) => !shadowReads(key) && !contexts.some((other, i) => other.policy !== "conversation" && source(i, key) === index)).map((key) => [
154
+ ...context.path,
155
+ "thresholds",
156
+ key
157
+ ])), ...(shadowPolicy ?? (contexts.some((c) => c.policy !== "conversation") ? "" : "conversation")) === "conversation" ? participant(shadowThresholds).map((key) => [
158
+ "observability",
159
+ "shadow",
160
+ "thresholds",
161
+ key
162
+ ]) : []];
163
+ }
109
164
  function authored(value, source) {
110
165
  return Object.fromEntries(Object.entries(sources(value, source)).filter(([path]) => !ignoredGroupSetting(path.split("."))));
111
166
  }
@@ -188,4 +243,4 @@ function effectiveGroupPolicy(base, key) {
188
243
  if (thresholds.defer !== void 0 && thresholds.defer > thresholds.reply) throw new RangeError("Group thresholds must satisfy defer <= reply after inheritance.");
189
244
  return result;
190
245
  }
191
- export { DEFAULT_CRITERIA, DEFAULT_GROUP_POLICY, ENGAGED_CRITERIA, ENGAGED_INSTRUCTIONS, IGNORED_GROUP_SETTINGS, LEGACY_INSTRUCTIONS, effectiveGroupPolicy, groupPolicy, ignoredGroupSetting, ignoredGroupSettings, overlaySmartPolicy, smartPolicy };
246
+ export { DEFAULT_CRITERIA, DEFAULT_GROUP_POLICY, ENGAGED_CRITERIA, ENGAGED_INSTRUCTIONS, IGNORED_GROUP_SETTINGS, LEGACY_INSTRUCTIONS, effectiveGroupPolicy, groupPolicy, ignoredGroupSetting, ignoredGroupSettings, inapplicableGroupThresholds, overlaySmartPolicy, smartPolicy };
@@ -0,0 +1,82 @@
1
+ import { type SlackChannel, type SlackInboundMessageContext, type SlackMentionResult, type SlackMessage } from "eve/channels/slack";
2
+ import type { SessionAuthContext } from "eve/context";
3
+ import type { AdmissionSettings, SlackSettings } from "../../config.js";
4
+ import type { GroupPolicy } from "../group-routing/policy.js";
5
+ import { type ConnectionProxy } from "../connection-proxy.js";
6
+ import { type Environment } from "../environment.js";
7
+ import { type AgentIdentities, type PairedMember } from "../identities.js";
8
+ import { type RuntimeToken } from "../runtime-token.js";
9
+ /**
10
+ * The SegmentStream Slack channel (`agent-design.md`, "Channels"): eve's Slack channel at
11
+ * `POST /eve/v1/slack`, for the Slack app SegmentStream created for the workspace's
12
+ * `SlackConnection`. The app sends its events, interactions and slash commands to SegmentStream,
13
+ * which checks them with the app's signing secret and relays them here signed as Slack signs, with
14
+ * the project's `SEGMENTSTREAM_AGENT_WEBHOOK_SECRET`. Every Web API call and file download goes
15
+ * through the connection proxy, which adds the bot token: no Slack credential enters this process.
16
+ *
17
+ * eve does the rest: mentions and direct messages start a turn in a thread, the thread's later
18
+ * replies continue it, and approvals and questions are buttons. Only paired members are answered;
19
+ * anyone else gets the workspace's `replies.pairingRequired` text and a link to the app's
20
+ * `/agent/connect`, privately.
21
+ */
22
+ /** The authenticator of a Slack session's principal. */
23
+ export declare const SLACK_AUTHENTICATOR = "segmentstream-slack";
24
+ /** eve sent a request this channel does not route through the proxy. */
25
+ export declare class SlackProxyRouteError extends Error {
26
+ readonly name = "SlackProxyRouteError";
27
+ }
28
+ export interface SlackChannelOptions {
29
+ /** The mounted `channels.slack`, or `null` when the workspace has no Slack channel. */
30
+ readonly settings: () => SlackSettings | null;
31
+ readonly admission: () => AdmissionSettings;
32
+ /**
33
+ * The workspace's group routing. In `mention` mode a reply in a followed thread reaches the
34
+ * agent only when it mentions the bot; in `smart` mode the model decides.
35
+ */
36
+ readonly groups?: () => Pick<GroupPolicy, "mode">;
37
+ readonly environment?: Environment;
38
+ readonly token?: RuntimeToken;
39
+ /** For the proxy and the ontology service; tests pass a fake. */
40
+ readonly fetch?: typeof fetch;
41
+ /** The ontology's pairing routes; tests pass a fake. */
42
+ readonly identities?: AgentIdentities;
43
+ /** Seconds since the epoch; tests pass a fixed clock. */
44
+ readonly now?: () => number;
45
+ }
46
+ /** The principal of a paired member's Slack session, as the Telegram channel stamps one. */
47
+ export declare function slackPrincipal(member: PairedMember, user: string): SessionAuthContext;
48
+ /**
49
+ * Checks a relayed request's signature, Slack's own scheme keyed with the project's agent webhook
50
+ * secret. Throws on anything else, which eve answers as unauthorized.
51
+ */
52
+ export declare function relayedRequestVerifier(secret: () => string | undefined, now?: () => number): (request: Request, body: string) => true;
53
+ /**
54
+ * eve's Slack transport carried by the connection proxy: a Web API method becomes a `web` call
55
+ * and a file download a `files` call. The placeholder bot token never leaves this process.
56
+ */
57
+ export declare function proxiedSlackFetch(proxy: () => ConnectionProxy): typeof fetch;
58
+ /** Builds the channel. Everything it reads from the mount is read per request. */
59
+ export declare function segmentstreamSlack(options: SlackChannelOptions): SlackChannel;
60
+ /**
61
+ * Whether a message no other hook took reaches the agent: a person's reply, or an edit, in a
62
+ * thread the agent already serves. Mentions and direct messages have their own hooks; a reply
63
+ * without a mention is the model's to answer or not, unless the workspace routes groups by
64
+ * mention only.
65
+ */
66
+ export declare function followsThreadReply(input: {
67
+ readonly ctx: Pick<SlackInboundMessageContext, "edit" | "isSubscribed">;
68
+ readonly message: Pick<SlackMessage, "author" | "ts" | "threadTs">;
69
+ readonly mode: GroupPolicy["mode"] | undefined;
70
+ }): Promise<boolean>;
71
+ /**
72
+ * Admits one inbound message: a turn as the paired member who wrote something, or `null` after
73
+ * privately answering anyone else with the workspace's reply, if it has one.
74
+ */
75
+ export declare function receive(input: {
76
+ readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit">;
77
+ readonly message: Pick<SlackMessage, "author" | "text" | "attachments">;
78
+ readonly direct: boolean;
79
+ readonly admission: AdmissionSettings;
80
+ readonly identities: AgentIdentities;
81
+ readonly environment: Environment;
82
+ }): Promise<SlackMentionResult>;
@@ -0,0 +1,237 @@
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 { admitMessage, localizedText } from "../admission.mjs";
8
+ import { redactDiagnostic } from "../diagnostics.mjs";
9
+ import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
10
+ import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
11
+ import { agentIdentities } from "../identities.mjs";
12
+ import { runtimeToken } from "../runtime-token.mjs";
13
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
14
+ import { slackChannel } from "eve/channels/slack";
15
+ const SLACK_AUTHENTICATOR = "segmentstream-slack";
16
+ const SLACK_API = "https://slack.com/api/";
17
+ const SLACK_FILES = "https://files.slack.com/";
18
+ const PLACEHOLDER = "xoxb-segmentstream-connection";
19
+ const MAXIMUM_SKEW_SECONDS = 300;
20
+ const THREAD_GUIDANCE = "You are part of this Slack thread, so you see replies people send each other. This reply doesn't mention you. Answer only if it's meant for you; otherwise call `no_reply`.";
21
+ var SlackProxyRouteError = class extends Error {
22
+ name = "SlackProxyRouteError";
23
+ };
24
+ function slackPrincipal(member, user) {
25
+ return {
26
+ authenticator: SLACK_AUTHENTICATOR,
27
+ issuer: "slack",
28
+ principalId: `slack:${user}`,
29
+ principalType: "user",
30
+ subject: user,
31
+ attributes: {
32
+ memberId: member.id,
33
+ identityProvider: "slack",
34
+ roles: member.roles,
35
+ ...member.name === null ? {} : { memberName: member.name },
36
+ ...member.locale === void 0 ? {} : { locale: member.locale }
37
+ }
38
+ };
39
+ }
40
+ function relayedRequestVerifier(secret, now = () => Date.now() / 1e3) {
41
+ return (request, body) => {
42
+ const key = secret();
43
+ const timestamp = request.headers.get("x-slack-request-timestamp")?.trim() ?? "";
44
+ const signature = request.headers.get("x-slack-signature")?.trim().toLowerCase() ?? "";
45
+ if (key === void 0 || !/^[0-9]{1,12}$/.test(timestamp) || Math.abs(now() - Number(timestamp)) > MAXIMUM_SKEW_SECONDS) throw new Error("The Slack request is not one SegmentStream relayed.");
46
+ const expected = `v0=${createHmac("sha256", key).update(`v0:${timestamp}:${body}`).digest("hex")}`;
47
+ if (!timingSafeEqual(digest(expected), digest(signature))) throw new Error("The Slack request is not one SegmentStream relayed.");
48
+ return true;
49
+ };
50
+ }
51
+ function proxiedSlackFetch(proxy) {
52
+ return async (input, init) => {
53
+ const request = new Request(input, init);
54
+ const url = new URL(request.url);
55
+ const headers = [...request.headers].filter(([name]) => name.toLowerCase() !== "authorization").map(([name, value]) => [name, value]);
56
+ const body = new Uint8Array(await request.arrayBuffer());
57
+ const method = request.method.toUpperCase();
58
+ let reply;
59
+ if (url.href.startsWith(SLACK_API)) reply = await proxy().request({
60
+ api: "web",
61
+ method,
62
+ path: `/${url.href.slice(22)}`,
63
+ headers,
64
+ body
65
+ }, request.signal);
66
+ else if (url.href.startsWith(SLACK_FILES)) reply = await proxy().download({
67
+ api: "files",
68
+ method,
69
+ path: `/${url.href.slice(24)}`,
70
+ headers,
71
+ body
72
+ }, MAXIMUM_DOWNLOAD_BYTES, request.signal);
73
+ else throw new SlackProxyRouteError("The Slack channel reaches only Slack's API and files.");
74
+ return new Response(reply.body.byteLength === 0 ? null : Buffer.from(reply.body), {
75
+ status: reply.status,
76
+ headers: reply.headers.map(([name, value]) => [name, value])
77
+ });
78
+ };
79
+ }
80
+ function segmentstreamSlack(options) {
81
+ const environment = options.environment ?? process.env;
82
+ const token = options.token ?? runtimeToken;
83
+ const proxies = new Map();
84
+ let identities = options.identities;
85
+ const proxy = () => {
86
+ const connection = options.settings()?.connection;
87
+ if (connection === void 0) throw new Error("The Slack channel is not configured in agent/segmentstream.json.");
88
+ let existing = proxies.get(connection);
89
+ if (existing === void 0) {
90
+ existing = connectionProxy({
91
+ environment: proxyEnvironment(environment),
92
+ connection,
93
+ token,
94
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
95
+ });
96
+ proxies.set(connection, existing);
97
+ }
98
+ return existing;
99
+ };
100
+ const pairing = () => identities ??= agentIdentities({
101
+ origin: appOrigin(environment),
102
+ token,
103
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
104
+ });
105
+ async function pairedPrincipal(user) {
106
+ const lookup = await pairing().lookup({
107
+ provider: "slack",
108
+ externalId: user
109
+ });
110
+ return lookup.status === "paired" ? slackPrincipal(lookup.member, user) : null;
111
+ }
112
+ const admit = (direct) => (ctx, message) => receive({
113
+ ctx,
114
+ message,
115
+ direct,
116
+ admission: options.admission(),
117
+ identities: pairing(),
118
+ environment
119
+ });
120
+ const channel = slackChannel({
121
+ credentials: {
122
+ botToken: PLACEHOLDER,
123
+ webhookVerifier: relayedRequestVerifier(() => webhookSecret(environment), options.now ?? (() => Date.now() / 1e3))
124
+ },
125
+ api: {
126
+ apiBaseUrl: SLACK_API,
127
+ fileBaseUrl: SLACK_FILES,
128
+ fetch: proxiedSlackFetch(proxy)
129
+ },
130
+ onAppMention: admit(false),
131
+ onDirectMessage: admit(true),
132
+ onMessage: async (ctx, message) => {
133
+ if (!await followsThreadReply({
134
+ ctx,
135
+ message,
136
+ mode: options.groups?.().mode
137
+ })) return null;
138
+ const admitted = await admit(false)(ctx, message);
139
+ return admitted === null ? null : {
140
+ ...admitted,
141
+ status: "deferred",
142
+ guidance: THREAD_GUIDANCE
143
+ };
144
+ },
145
+ onAnswers: async (_ctx, submission) => {
146
+ const auth = await pairedPrincipal(submission.user.id);
147
+ return auth === null ? null : { auth };
148
+ }
149
+ });
150
+ return {
151
+ ...channel,
152
+ routes: channel.routes.map((route) => gatedRoute(route, options, environment))
153
+ };
154
+ }
155
+ async function followsThreadReply(input) {
156
+ const { ctx, message } = input;
157
+ if (message.author?.isBot !== false || message.threadTs === message.ts || input.mode === "mention") return false;
158
+ return ctx.edit !== void 0 || await ctx.isSubscribed();
159
+ }
160
+ function gatedRoute(route, options, environment) {
161
+ if (route.transport === "websocket") return route;
162
+ return {
163
+ ...route,
164
+ handler: async (request, args) => channelsEnabled(environment) && options.settings() !== null && webhookSecret(environment) !== void 0 ? route.handler(request, args) : new Response(null, { status: 404 })
165
+ };
166
+ }
167
+ async function receive(input) {
168
+ const { ctx, message, admission, identities } = input;
169
+ const author = message.author;
170
+ if (author === void 0 || author.isBot || author.isMe) return null;
171
+ const user = author.userId;
172
+ const display = (author.fullName ?? author.displayName ?? author.userName)?.trim() || void 0;
173
+ const turn = message.text.trim() !== "" || message.attachments.length > 0;
174
+ const notify = (text) => ctx.edit === void 0 ? ctx.thread.postEphemeral(user, text) : Promise.resolve(void 0);
175
+ const resolution = await admitMessage({
176
+ identity: {
177
+ provider: "slack",
178
+ externalId: user,
179
+ chat: input.direct ? "private" : "group",
180
+ turn,
181
+ ...display === void 0 ? {} : { display }
182
+ },
183
+ identities,
184
+ settings: admission,
185
+ sendNotice: (text) => notify(text),
186
+ noticeFailed: (error) => report("notice_failed", error)
187
+ });
188
+ switch (resolution.status) {
189
+ case "existing":
190
+ case "created": return turn ? { auth: slackPrincipal(resolution.member, user) } : null;
191
+ case "pairing_required": {
192
+ const text = localizedText(admission.replies.pairingRequired);
193
+ if (text !== void 0 && ctx.edit === void 0) {
194
+ const code = (await identities.createPairing({
195
+ provider: "slack",
196
+ externalId: user,
197
+ ...display === void 0 ? {} : { display }
198
+ })).code;
199
+ await notify(`${text}\n\n${appOrigin(input.environment)}/agent/connect?code=${encodeURIComponent(code)}`);
200
+ }
201
+ return null;
202
+ }
203
+ case "refused": {
204
+ const text = localizedText(admission.replies.refused);
205
+ if (text !== void 0) await notify(text);
206
+ return null;
207
+ }
208
+ case "limited": {
209
+ const replies = admission.replies;
210
+ const configured = resolution.scope === "workspaceTurnsPerDay" ? replies.workspaceLimited : resolution.scope === "newUsersPerHour" ? replies.registrationsLimited : replies.perSenderLimited;
211
+ const text = resolution.notify ? localizedText(configured ?? replies.limited) : void 0;
212
+ if (text !== void 0) {
213
+ let delivered = false;
214
+ try {
215
+ await notify(text);
216
+ delivered = true;
217
+ } finally {
218
+ if (resolution.notificationId !== void 0) await identities.completeLimitNotice({
219
+ notificationId: resolution.notificationId,
220
+ delivered
221
+ }).catch((error) => report("limit_notice_completion_failed", error));
222
+ }
223
+ }
224
+ return null;
225
+ }
226
+ }
227
+ }
228
+ function report(operation, error) {
229
+ console.error("[segmentstream] Slack delivery diagnostic", {
230
+ operation,
231
+ error: redactDiagnostic(error, new Set())
232
+ });
233
+ }
234
+ function digest(value) {
235
+ return createHash("sha256").update(value, "utf8").digest();
236
+ }
237
+ export { SLACK_AUTHENTICATOR, SlackProxyRouteError, followsThreadReply, proxiedSlackFetch, receive, relayedRequestVerifier, segmentstreamSlack, slackPrincipal };
@@ -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-BMjP89Jo.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DZwapj-X.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -16,9 +16,9 @@ import { n as currentInboundRequest, p as reportTelegramError } from "../../../_
16
16
  import { confirmationStatus, renderConfirmation, withConfirmationText } from "./confirmation-text.mjs";
17
17
  import { i as memberIdOf, o as telegramPrincipal } from "../../../_chunks/principal-UlkbLrgQ.mjs";
18
18
  import { formatAddress, scopedAddress } from "./sessions.mjs";
19
- import { call } from "eve/events";
20
19
  import { createHash } from "node:crypto";
21
20
  import { telegramTextLinks } from "@segmentstream/ontology/telegram";
21
+ import { call } from "eve/events";
22
22
  const PREFIX = "ss-confirm:";
23
23
  const recoveredContinuation = (address) => address !== void 0 && /:recovery:[a-f0-9]{64}$/u.test(address);
24
24
  function aliasesPendingTopic(scope, token) {
@@ -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-BMjP89Jo.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DZwapj-X.mjs";
8
8
  import { runtimeRequestFailure } from "./runtime-request.mjs";
9
9
  import { GET } from "eve/channels";
10
10
  const HEALTH_ROUTE = "/eve/v1/telegram/health";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { d as telegramRuntimeSource, l as principalRuntimeSource, u as runtimeEnvelope } from "../../../_chunks/principal-UlkbLrgQ.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-BMjP89Jo.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DZwapj-X.mjs";
9
9
  import { n as currentInboundRequest } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
10
10
  import { object } from "../confirmation-description.mjs";
11
11
  import { needsConfirmation } from "../confirmations.mjs";
@@ -7,8 +7,8 @@ __eveCreateRequire(import.meta.url);
7
7
  import { chatModelChoiceOf } from "./config.mjs";
8
8
  import { isPreview } from "./lib/environment.mjs";
9
9
  import { a as rolesOf } from "../_chunks/principal-UlkbLrgQ.mjs";
10
- import { runs } from "eve/events";
11
10
  import { defineDynamic } from "eve";
11
+ import { runs } from "eve/events";
12
12
  function chooseModel(input) {
13
13
  const { choice } = input;
14
14
  if (choice.preview !== void 0 && isPreview(input.environment ?? process.env)) return choice.preview;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.34.1",
4
- "description": "Mount a SegmentStream workspace's agent on eve: the ontology as tools, acting as the member who writes, and Telegram through the workspace's connection.",
3
+ "version": "0.36.0",
4
+ "description": "Mount a SegmentStream workspace's agent on eve: the ontology as tools, acting as the member who writes, and Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
7
7
  "homepage": "https://segmentstream.com",