@segmentstream/agent 0.95.0 → 0.96.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,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.96.0
4
+
5
+ Allow a workspace to bind a read-only knowledge lookup for isolated group replies. Only the public facts returned by the workspace enter the reply model. Research runs after admission and shares the guest’s usage budget.
6
+
3
7
  ## 0.95.0
4
8
 
5
9
  Workspace channels take files by link, with a file limit of their own and the provider's
package/README.md CHANGED
@@ -1101,3 +1101,16 @@ or sender. Its configured connection, session recovery, pairing and normal
1101
1101
  ontology authority still apply. The calling channel must authenticate and
1102
1102
  authorize its caller and choose the intended destination before forwarding.
1103
1103
  The reference alone grants no access or messaging authority.
1104
+
1105
+ ## Grounding replies in opened groups
1106
+
1107
+ For an isolated group answer, the workspace can declare `publicGroups.knowledge`
1108
+ with a `connection` key and localized `unavailable` text in its agent configuration.
1109
+ In the agent's extension mount, add a `lookup` function to that object. Its
1110
+ `PublicGroupKnowledgeContext` supplies the current question, a bounded GET on
1111
+ the named connection, a metered private model call and an abort signal. No
1112
+ member session or conversation history is supplied. Only return facts that may
1113
+ be published to everyone in the group. Those facts and the question enter the
1114
+ ordinary answer model; neither model gets a connection tool or credentials.
1115
+ An empty result, unavailable source or missing runtime binding uses the
1116
+ workspace's fallback text. Closed groups and rejected turns do not run a lookup.
@@ -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.95.0";
7
+ var version = "0.96.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -2,6 +2,7 @@ import { type GroupPolicyInput } from "@segmentstream/ontology/groups";
2
2
  import { type GroupPolicy } from "./lib/group-routing/policy.js";
3
3
  import { type QuoteSettings } from "./lib/email/quote-settings.js";
4
4
  import { type StructuredInbound } from "./lib/telegram/structured-settings.js";
5
+ import type { PublicGroupKnowledge } from "./lib/public-group-knowledge.js";
5
6
  import type { WorkspaceActionHook } from "./lib/workspace-action.js";
6
7
  import { type TelegramTexts } from "./lib/telegram/texts.js";
7
8
  import { type IdentifierPolicy } from "./lib/customer-text-safety.js";
@@ -76,6 +77,7 @@ export interface FirstContactSettings {
76
77
  export declare const ADMISSION_REPLY_KEYS: readonly ["pairingRequired", "pairingButton", "groupPairingButton", "limited", "perSenderLimited", "workspaceLimited", "registrationsLimited", "groupPairingRequired", "refused"];
77
78
  export type AdmissionReplies = Partial<Record<(typeof ADMISSION_REPLY_KEYS)[number], LocalizedText>>;
78
79
  export interface PublicGroupSettings {
80
+ readonly knowledge?: PublicGroupKnowledge;
79
81
  readonly model: string;
80
82
  /** Workspace-published material for an isolated, text-only answer. */
81
83
  readonly instructions: string;
@@ -1298,18 +1298,47 @@ function validateConfig(input, options = {}) {
1298
1298
  allowed: [
1299
1299
  "model",
1300
1300
  "instructions",
1301
- "trustedJoinChannels"
1301
+ "trustedJoinChannels",
1302
+ "knowledge"
1302
1303
  ],
1303
1304
  issues
1304
1305
  });
1305
1306
  let publicGroups;
1306
1307
  if (publicGroupInput) {
1307
1308
  const { model, instructions, trustedJoinChannels } = publicGroupInput;
1309
+ const knowledge = section({
1310
+ value: publicGroupInput.knowledge,
1311
+ path: ["publicGroups", "knowledge"],
1312
+ allowed: [
1313
+ "connection",
1314
+ "lookup",
1315
+ "unavailable"
1316
+ ],
1317
+ issues
1318
+ });
1319
+ let source;
1320
+ if (knowledge) {
1321
+ const unavailable = localizedText(knowledge.unavailable, [
1322
+ "publicGroups",
1323
+ "knowledge",
1324
+ "unavailable"
1325
+ ], issues, 1e3);
1326
+ if (typeof knowledge.connection !== "string" || !CONNECTION_KEY.test(knowledge.connection) || knowledge.lookup !== void 0 && typeof knowledge.lookup !== "function") issues.push({
1327
+ path: ["publicGroups", "knowledge"],
1328
+ message: "Supply a workspace connection and bind a lookup function in the agent mount."
1329
+ });
1330
+ else source = {
1331
+ connection: knowledge.connection,
1332
+ unavailable,
1333
+ ...knowledge.lookup && { lookup: knowledge.lookup }
1334
+ };
1335
+ }
1308
1336
  if (typeof model !== "string" || !model.trim() || model.length > 256 || typeof instructions !== "string" || !instructions.trim() || instructions.length > 32e3 || trustedJoinChannels !== void 0 && (!Array.isArray(trustedJoinChannels) || !trustedJoinChannels.every((channel) => typeof channel === "string" && Object.hasOwn(channels ?? {}, channel)))) issues.push({
1309
1337
  path: ["publicGroups"],
1310
1338
  message: "Supply a model, public instructions and optional configured channel names."
1311
1339
  });
1312
1340
  else publicGroups = {
1341
+ ...source && { knowledge: source },
1313
1342
  model,
1314
1343
  instructions,
1315
1344
  ...trustedJoinChannels ? { trustedJoinChannels } : {}
@@ -60,3 +60,4 @@ export { replayRouterPayload } from "./lib/group-routing/replay.js";
60
60
  export { chatAddressing as groupChatAddressing } from "./lib/group-routing/addressing.js";
61
61
  export { routingBurst } from "./lib/group-routing/burst.js";
62
62
  export type { TelegramTexts } from "./lib/telegram/texts.js";
63
+ export type { PublicGroupKnowledge, PublicGroupKnowledgeContext, } from "./lib/public-group-knowledge.js";
@@ -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-CX7xleFw.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-_7QBVYuN.mjs";
@@ -0,0 +1,16 @@
1
+ import { type ChannelConnectionRequestOptions } from "./workspace-channel/connection.js";
2
+ export interface PublicGroupKnowledgeContext {
3
+ readonly question: string;
4
+ readonly signal: AbortSignal;
5
+ /** GET against the one workspace connection bound to this source. Never a model tool. */
6
+ readonly get: (path: string, options?: Pick<ChannelConnectionRequestOptions, "api" | "headers" | "query">) => Promise<string>;
7
+ /** A private, tool-free model call, metered against the same guest budget. */
8
+ readonly reason: (instructions: string, input: string) => Promise<string>;
9
+ }
10
+ /** Trusted workspace code returns only information it permits the group to see. */
11
+ export interface PublicGroupKnowledge {
12
+ readonly connection: string;
13
+ readonly unavailable: Readonly<Record<string, string>>;
14
+ readonly lookup?: (context: PublicGroupKnowledgeContext) => Promise<readonly string[]>;
15
+ }
16
+ export declare function publicGroupEvidence(source: PublicGroupKnowledge, question: string, reason: PublicGroupKnowledgeContext["reason"], signal: AbortSignal): Promise<readonly string[]>;
@@ -0,0 +1,44 @@
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 { connectionProxy } from "./connection-proxy.mjs";
8
+ import { proxyEnvironment } from "./environment.mjs";
9
+ import { runtimeToken } from "./runtime-token.mjs";
10
+ import { connectionCall } from "./workspace-channel/connection.mjs";
11
+ async function publicGroupEvidence(source, question, reason, signal) {
12
+ if (!source.lookup) return [];
13
+ let reads = 0;
14
+ let calls = 0;
15
+ try {
16
+ return (await source.lookup({
17
+ question,
18
+ signal,
19
+ reason: (instructions, input) => {
20
+ signal.throwIfAborted();
21
+ if (++calls > 3 || input.length > 6e4 || instructions.length > 8e3) throw new Error("Public research model limit exceeded.");
22
+ return reason(instructions, input);
23
+ },
24
+ get: async (path, options) => {
25
+ signal.throwIfAborted();
26
+ if (++reads > 10) throw new Error("Public research read limit exceeded.");
27
+ const result = await connectionProxy({
28
+ environment: proxyEnvironment(),
29
+ connection: source.connection,
30
+ token: runtimeToken
31
+ }).request(connectionCall({
32
+ ...options,
33
+ method: "GET",
34
+ path
35
+ }), signal);
36
+ if (result.status < 200 || result.status >= 300) throw new Error(`Knowledge source returned HTTP ${result.status}.`);
37
+ return new TextDecoder().decode(result.body);
38
+ }
39
+ })).filter((fact) => typeof fact === "string" && fact.length <= 1e3).slice(0, 8);
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+ export { publicGroupEvidence };
@@ -7,6 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { localizedText } from "./admission.mjs";
8
8
  import { chatRuntimeRequest } from "./chat-persona.mjs";
9
9
  import { ontologyGuestUsage } from "./guest-usage.mjs";
10
+ import { publicGroupEvidence } from "./public-group-knowledge.mjs";
10
11
  import { gatewayCostOf } from "./web-search.mjs";
11
12
  import { gateway, generateText } from "ai";
12
13
  async function isPublicGroup(admission, channel, chat, sender) {
@@ -40,25 +41,39 @@ async function answerPublicGroup(input) {
40
41
  return true;
41
42
  }
42
43
  if (turn?.status !== "admitted" || typeof turn.guestId !== "string") throw new Error("Invalid public group admission.");
43
- const reply = await generateText({
44
- model: gateway(settings.model),
45
- system: settings.instructions,
46
- prompt: input.text.slice(0, 8e3),
47
- maxRetries: 0,
48
- maxOutputTokens: 600,
49
- abortSignal: AbortSignal.timeout(3e4)
44
+ const guestId = turn.guestId;
45
+ const question = input.text.slice(0, 8e3);
46
+ const researchDeadline = AbortSignal.timeout(3e4);
47
+ const messageKey = JSON.stringify([
48
+ input.channel,
49
+ input.chat,
50
+ input.message
51
+ ]);
52
+ let stage = 0;
53
+ const generate = async (system, prompt, privateCall = false) => {
54
+ const usageKey = privateCall ? `research:${++stage}:${messageKey}` : messageKey;
55
+ const reply = await generateText({
56
+ model: gateway(settings.model),
57
+ system,
58
+ prompt,
59
+ maxRetries: 0,
60
+ maxOutputTokens: privateCall ? 1e3 : 600,
61
+ abortSignal: privateCall ? researchDeadline : AbortSignal.timeout(3e4)
62
+ });
63
+ const costUsd = gatewayCostOf(reply.providerMetadata);
64
+ if (costUsd > 0) await ontologyGuestUsage()({
65
+ guestId,
66
+ costUsd,
67
+ key: usageKey.slice(0, 256)
68
+ });
69
+ return reply.text.trim();
70
+ };
71
+ const evidence = settings.knowledge ? await publicGroupEvidence(settings.knowledge, question, (system, prompt) => generate(system, prompt, true), researchDeadline) : void 0;
72
+ const prompt = evidence === void 0 ? question : JSON.stringify({
73
+ question,
74
+ evidence
50
75
  });
51
- const costUsd = gatewayCostOf(reply.providerMetadata);
52
- if (costUsd > 0) await ontologyGuestUsage()({
53
- guestId: turn.guestId,
54
- costUsd,
55
- key: JSON.stringify([
56
- input.channel,
57
- input.chat,
58
- input.message
59
- ]).slice(0, 256)
60
- });
61
- const text = reply.text.trim();
76
+ const text = settings.knowledge && !evidence?.length ? localizedText(settings.knowledge.unavailable, input.locale) : await generate(settings.instructions, prompt);
62
77
  if (!text) throw new Error("The public group answer was empty.");
63
78
  await input.post(text.slice(0, 3500));
64
79
  delivered = true;
@@ -12,7 +12,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
12
12
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
13
13
  import { handleWorkspaceCallback } from "./callbacks.mjs";
14
14
  import { telegramText, withTelegramTexts } from "./texts.mjs";
15
- import { t as agentBuild } from "../../../_chunks/build-metadata-CX7xleFw.mjs";
15
+ import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.mjs";
16
16
  import { attachmentLifecycle } from "./lifecycle.mjs";
17
17
  import { manifestOf } from "../../config.mjs";
18
18
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -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-CX7xleFw.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.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 { E as OntologyActionNotPermitted, Et as principalRuntimeSource, L as needsConfirmation, Ot as runtimeEnvelope, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as telegramRuntimeSource } from "../../../_chunks/principal-DL9NdRRP.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-CX7xleFw.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-_7QBVYuN.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.95.0",
3
+ "version": "0.96.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",