@segmentstream/ontology 0.162.0 → 0.164.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/deployment.d.ts +13 -1
  3. package/dist/deployment.js +8 -0
  4. package/dist/email.d.ts +1 -1
  5. package/dist/email.js +1 -1
  6. package/dist/gmail-send.d.ts +10 -0
  7. package/dist/gmail-send.js +31 -9
  8. package/dist/index.d.ts +5 -4
  9. package/dist/index.js +5 -4
  10. package/dist/manifest.js +1 -0
  11. package/dist/runtime/agent-web.js +42 -3
  12. package/dist/service/agent/authentication.js +9 -2
  13. package/dist/service/agent/eval-tokens.d.ts +25 -0
  14. package/dist/service/agent/eval-tokens.js +130 -0
  15. package/dist/service/agent/server.d.ts +8 -0
  16. package/dist/service/agent/server.js +11 -1
  17. package/dist/service/agent/web-tokens.d.ts +13 -2
  18. package/dist/service/agent/web-tokens.js +20 -5
  19. package/dist/service/authentication.js +3 -2
  20. package/dist/service/chat/draft-files.d.ts +5 -0
  21. package/dist/service/chat/draft-files.js +28 -1
  22. package/dist/service/chat/providers/custom.js +2 -2
  23. package/dist/service/chat/providers/email.js +13 -11
  24. package/dist/service/chat/providers/files-send.d.ts +36 -0
  25. package/dist/service/chat/providers/files-send.js +182 -0
  26. package/dist/service/chat/providers/provider.d.ts +22 -3
  27. package/dist/service/chat/providers/provider.js +43 -0
  28. package/dist/service/chat/providers/slack.js +4 -1
  29. package/dist/service/chat/providers/telegram.js +23 -3
  30. package/dist/service/chat/providers/whatsapp.js +4 -1
  31. package/dist/service/chat/review-delivery.js +1 -0
  32. package/dist/service/config.js +8 -2
  33. package/dist/service/runtime-contract.d.ts +30 -0
  34. package/dist/service/runtime-identity.d.ts +17 -1
  35. package/dist/service/runtime-identity.js +15 -2
  36. package/dist/service/service.js +63 -11
  37. package/dist/slack-files.d.ts +2 -0
  38. package/dist/slack-files.js +1 -1
  39. package/dist/telegram-files.d.ts +4 -0
  40. package/dist/telegram-files.js +6 -2
  41. package/package.json +1 -1
@@ -265,7 +265,22 @@ export interface AgentWebStore {
265
265
  readonly grantMember: (input: {
266
266
  readonly grantId: string;
267
267
  readonly userId: string;
268
+ /**
269
+ * Whether an `agent-eval` grant counts too: only in a preview that runs the agent, where evals
270
+ * act as a test member. Never in production.
271
+ */
272
+ readonly evalGrants?: boolean;
268
273
  }) => Effect.Effect<Principal | undefined>;
274
+ /**
275
+ * In a preview that runs the agent: an access token of a new `agent-eval` grant to the agent at
276
+ * `resource`, for the active member with `email`, revoking the member's earlier `agent-eval`
277
+ * grants. No refresh token. Absent where the store cannot issue them.
278
+ */
279
+ readonly issueEval?: (input: {
280
+ readonly email: string;
281
+ readonly resource: string;
282
+ readonly expiresAt: Date;
283
+ }) => Effect.Effect<EvalIssue>;
269
284
  /**
270
285
  * Counts one turn a member starts on the web against the agent's limits when `signUp` created
271
286
  * them, as their turns on a messenger are counted, on the same counters; invited and paired
@@ -385,6 +400,21 @@ export type VisitorSignUp = {
385
400
  } | {
386
401
  readonly status: "refused";
387
402
  };
403
+ /** An eval session's credential, as {@link AgentWebStore.issueEval} answers it. */
404
+ export type EvalIssue = {
405
+ readonly status: "issued";
406
+ readonly token: string;
407
+ readonly grantId: string;
408
+ readonly memberId: string;
409
+ }
410
+ /** No member has the address. */
411
+ | {
412
+ readonly status: "not_member";
413
+ }
414
+ /** The member is deactivated or blocked. */
415
+ | {
416
+ readonly status: "inactive";
417
+ };
388
418
  /** A guest's credential, as {@link AgentWebStore.guest} answers it. */
389
419
  export type GuestIssue = {
390
420
  readonly status: "issued";
@@ -30,6 +30,14 @@ export declare const CHAT: RegExp;
30
30
  export declare const SESSION: RegExp;
31
31
  /** The chat and session a request names, or `undefined` without a well-formed chat. */
32
32
  export declare function requestChat(request: HttpServerRequest.HttpServerRequest): ChatProvenance | undefined;
33
+ /**
34
+ * The header the agent of a preview names its own deployment in, as the ontology's own calls to
35
+ * the platform do. Vercel's function tokens name a project and its environment, never a
36
+ * deployment, and every preview of a workspace shares one hosting project, so a preview's ontology
37
+ * checks the header against its own deployment before it trusts a runtime token: an agent of
38
+ * another preview of the same workspace is refused rather than served another branch's data.
39
+ */
40
+ export declare const ONTOLOGY_DEPLOYMENT_HEADER = "x-segmentstream-ontology-deployment-id";
33
41
  /**
34
42
  * Whom the service trusts as its runtime caller: Vercel OIDC tokens of the functions of this
35
43
  * deployment's own project. The app's agent is a service of the same Vercel project as the ontology
@@ -42,6 +50,11 @@ export interface RuntimeIdentityConfig {
42
50
  readonly audience: string;
43
51
  /** The project the token must name, from `VERCEL_PROJECT_ID`. */
44
52
  readonly projectId: string;
53
+ /**
54
+ * The environment the token must name: `production`, unless the platform runs the agent in a
55
+ * hosted preview, whose functions' tokens name `preview`.
56
+ */
57
+ readonly environment?: "production" | "preview";
45
58
  }
46
59
  export type RuntimeVerification = {
47
60
  readonly status: "valid";
@@ -61,10 +74,13 @@ export type RuntimeVerification = {
61
74
  export type RuntimeTokenVerifier = (token: string) => Promise<RuntimeVerification>;
62
75
  /** The issuer's key set, at `<issuer>/.well-known/jwks` as Vercel publishes it. */
63
76
  export declare function runtimeKeySet(issuer: string): JWTVerifyGetKey;
77
+ /** Whether a bearer token claims the runtime issuer, read without verifying it. */
78
+ export declare function claimsRuntimeIssuer(config: RuntimeIdentityConfig, token: string): boolean;
64
79
  /**
65
80
  * Verifies the Vercel OIDC token of a function of this deployment's project, as backend-next
66
81
  * verifies the ontology service's own: RS256 from the team's issuer, for the team's audience,
67
- * unexpired, with `project_id` equal to the configured project and `environment` `production`.
82
+ * unexpired, with `project_id` equal to the configured project and `environment` the configured
83
+ * one, `production` unless set.
68
84
  * The issuer and the audience name the team, so no further owner check is needed. A token that
69
85
  * claims another issuer is `other`, without a key-set fetch.
70
86
  */
@@ -44,6 +44,14 @@ const CLOCK_TOLERANCE_SECONDS = 5;
44
44
  const JWKS_TIMEOUT_MS = 5_000;
45
45
  /** The environment that a Vercel function token must name: channels run only in production. */
46
46
  const PRODUCTION = "production";
47
+ /**
48
+ * The header the agent of a preview names its own deployment in, as the ontology's own calls to
49
+ * the platform do. Vercel's function tokens name a project and its environment, never a
50
+ * deployment, and every preview of a workspace shares one hosting project, so a preview's ontology
51
+ * checks the header against its own deployment before it trusts a runtime token: an agent of
52
+ * another preview of the same workspace is refused rather than served another branch's data.
53
+ */
54
+ export const ONTOLOGY_DEPLOYMENT_HEADER = "x-segmentstream-ontology-deployment-id";
47
55
  /** The issuer without a trailing slash, as Vercel writes it in `iss` and as its JWKS URL starts. */
48
56
  function normalizedIssuer(issuer) {
49
57
  let end = issuer.length;
@@ -83,10 +91,15 @@ function claimedIssuer(token) {
83
91
  return undefined;
84
92
  }
85
93
  }
94
+ /** Whether a bearer token claims the runtime issuer, read without verifying it. */
95
+ export function claimsRuntimeIssuer(config, token) {
96
+ return claimedIssuer(token) === normalizedIssuer(config.issuer);
97
+ }
86
98
  /**
87
99
  * Verifies the Vercel OIDC token of a function of this deployment's project, as backend-next
88
100
  * verifies the ontology service's own: RS256 from the team's issuer, for the team's audience,
89
- * unexpired, with `project_id` equal to the configured project and `environment` `production`.
101
+ * unexpired, with `project_id` equal to the configured project and `environment` the configured
102
+ * one, `production` unless set.
90
103
  * The issuer and the audience name the team, so no further owner check is needed. A token that
91
104
  * claims another issuer is `other`, without a key-set fetch.
92
105
  */
@@ -107,7 +120,7 @@ export function makeRuntimeTokenVerifier(config, keySet) {
107
120
  if (payload.project_id !== config.projectId) {
108
121
  return { status: "invalid", reason: "claim:project_id" };
109
122
  }
110
- if (payload.environment !== PRODUCTION) {
123
+ if (payload.environment !== (config.environment ?? PRODUCTION)) {
111
124
  return { status: "invalid", reason: "claim:environment" };
112
125
  }
113
126
  return { status: "valid" };
@@ -6,6 +6,7 @@ import { validateDeploymentStorage } from "../storage/provider.js";
6
6
  import { captureRuntimeFailure } from "../internal/diagnostics.js";
7
7
  import { deploymentFromEnv, DeploymentAdmissionError, requireDeploymentCapability, } from "../deployment.js";
8
8
  import { RuntimeDeployment } from "../runtime/deployment.js";
9
+ import { previewRunsAgent } from "../deployment.js";
9
10
  import { nameToWire } from "../authoring-names.js";
10
11
  import { bundledNavigationCatalog } from "../navigation-artifact.js";
11
12
  import { parsePageCatalog } from "../navigation-catalog.js";
@@ -56,7 +57,7 @@ import { vercelWorkflowEngine, workflowStarter, workflowsLayer } from "./workflo
56
57
  import { deploymentWorkflowEngine } from "./workflow-deployment.js";
57
58
  import { OntologyBackend } from "./runtime-contract.js";
58
59
  import { currentEntityPath } from "../earlier-entity-names.js";
59
- import { runtimeCredential, runtimeTokenVerifier, } from "./runtime-identity.js";
60
+ import { ONTOLOGY_DEPLOYMENT_HEADER, claimsRuntimeIssuer, runtimeCredential, runtimeTokenVerifier, } from "./runtime-identity.js";
60
61
  /** The header every response carries: the hash of the manifest the service serves. */
61
62
  export const ONTOLOGY_HASH_HEADER = "x-ontology-hash";
62
63
  /** The header every response carries: the correlation id quoted in error bodies and logs. */
@@ -158,6 +159,23 @@ function decorate(response, requestId, hash, durationMs) {
158
159
  headers,
159
160
  });
160
161
  }
162
+ /**
163
+ * The agent routes a preview that runs the agent serves: agent tokens for the preview app's web chat,
164
+ * their introspection, eval sessions, the chat store, held replies, and members' attachments and
165
+ * files.
166
+ */
167
+ const PREVIEW_AGENT_ROUTE = /^\/api\/ontology\/agent\/(?:tokens|eval-tokens|chats|drafts|reviews|attachments|files|conversations)(?:\/|$)/;
168
+ /**
169
+ * Whether a request is not the runtime's, or is the runtime's and names this deployment in
170
+ * `x-segmentstream-ontology-deployment-id`. Every preview of a workspace shares one hosting project,
171
+ * whose function tokens name no deployment, so the header keeps another preview's agent out.
172
+ */
173
+ function sameDeployment(request, identity, deploymentId) {
174
+ const match = /^Bearer\s+(.+)$/iu.exec(request.headers.get("authorization")?.trim() ?? "");
175
+ return (match === null ||
176
+ !claimsRuntimeIssuer(identity, match[1]) ||
177
+ request.headers.get(ONTOLOGY_DEPLOYMENT_HEADER)?.trim() === deploymentId);
178
+ }
161
179
  /**
162
180
  * The ontology service: the derived HttpApi, the MCP server at `/mcp` and the agent's pairing routes,
163
181
  * wired to the runtime, behind Neon Auth, app-token, API-key and runtime-token authentication.
@@ -167,27 +185,45 @@ function decorate(response, requestId, hash, durationMs) {
167
185
  export function createOntologyService(ontology, config) {
168
186
  const ambient = deploymentFromEnv();
169
187
  const requested = ambient.target === "preview" ? ambient : (config.deployment ?? ambient);
188
+ // The agent runs in a hosted preview only where the platform said so and gave the service the
189
+ // preview's runtime identity; production never trusts a preview's tokens.
190
+ const runtimeIdentity = requested.target === "preview"
191
+ ? requested.agent === true && config.runtimeIdentity?.environment === "preview"
192
+ ? config.runtimeIdentity
193
+ : undefined
194
+ : config.runtimeIdentity === undefined
195
+ ? undefined
196
+ : { ...config.runtimeIdentity, environment: "production" };
170
197
  const deployment = deploymentFromEnv({
171
198
  SEGMENTSTREAM_DEPLOYMENT_TARGET: requested.target,
172
199
  SEGMENTSTREAM_ONTOLOGY_DEPLOYMENT_ID: requested.deploymentId,
173
200
  SEGMENTSTREAM_PREVIEW_EXPIRES_AT: requested.target === "preview" ? requested.expiresAt : undefined,
174
201
  SEGMENTSTREAM_PREVIEW_HOST: requested.target === "preview" ? requested.host : undefined,
202
+ ...(requested.target === "preview" && runtimeIdentity !== undefined
203
+ ? {
204
+ SEGMENTSTREAM_RUNTIME_OIDC_ISSUER: runtimeIdentity.issuer,
205
+ SEGMENTSTREAM_RUNTIME_OIDC_AUDIENCE: runtimeIdentity.audience,
206
+ }
207
+ : {}),
175
208
  });
176
209
  const preview = deployment.target === "preview";
210
+ const previewAgent = previewRunsAgent(deployment);
177
211
  config = {
178
212
  ...config,
179
213
  deployment,
180
214
  ...(preview
181
215
  ? {
182
216
  oidc: ontology.signIn.browser ? config.oidc : undefined,
183
- runtimeIdentity: undefined,
217
+ runtimeIdentity,
184
218
  localConnections: undefined,
185
219
  cronSecret: undefined,
186
220
  agentOrigin: undefined,
187
221
  channels: undefined,
188
222
  channelAppProviders: undefined,
189
223
  }
190
- : {}),
224
+ : runtimeIdentity === undefined
225
+ ? {}
226
+ : { runtimeIdentity }),
191
227
  };
192
228
  if (preview && !config.neonAuth && !ontology.signIn.browser?.methods.includes("segmentstream")) {
193
229
  throw new DeploymentAdmissionError("preview_configuration_invalid");
@@ -345,7 +381,8 @@ export function createOntologyService(ontology, config) {
345
381
  ? deployedConnections(config)
346
382
  : localConnections(config.localConnections)));
347
383
  const replicate = deployedReplication(config);
348
- const chatHistory = config.runtimeIdentity === undefined ? undefined : platformChatArchive(config);
384
+ // The platform keeps chat history for production agents only.
385
+ const chatHistory = config.runtimeIdentity === undefined || preview ? undefined : platformChatArchive(config);
349
386
  const chatDelivery = makeChatDelivery(ontology, connections,
350
387
  // @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message.
351
388
  config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
@@ -410,15 +447,18 @@ export function createOntologyService(ontology, config) {
410
447
  verifyToken,
411
448
  })
412
449
  : undefined);
413
- const agent = preview
450
+ // A preview runs the agent for the preview app's web chat and evals only: no visitors, sign-ups,
451
+ // channels or tasks.
452
+ const withoutAgent = preview && !previewAgent;
453
+ const agent = withoutAgent
414
454
  ? Layer.empty
415
455
  : agentLayer({
416
456
  verifyToken,
417
457
  verifyRuntime,
418
458
  exchangeSession,
419
- visitorWebsites,
459
+ visitorWebsites: preview ? { guests: [], signUp: [] } : visitorWebsites,
420
460
  agentTools,
421
- guest,
461
+ guest: preview ? undefined : guest,
422
462
  botCheckVerifier: config.botCheckVerifier ??
423
463
  deployedBotCheckVerifier({
424
464
  segmentstreamUrl: config.segmentstreamUrl,
@@ -431,6 +471,7 @@ export function createOntologyService(ontology, config) {
431
471
  emailCodes,
432
472
  cronSecret: config.cronSecret,
433
473
  chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
474
+ ...(previewAgent ? { evalTokens: deployment } : {}),
434
475
  });
435
476
  const agentTasks = preview
436
477
  ? Layer.empty
@@ -442,7 +483,7 @@ export function createOntologyService(ontology, config) {
442
483
  agentTools,
443
484
  implicitMember: implicitMemberOf(ontology.roles) !== undefined,
444
485
  });
445
- const attachments = preview
486
+ const attachments = withoutAgent
446
487
  ? Layer.empty
447
488
  : attachmentsLayer({
448
489
  plan: built.plan,
@@ -454,7 +495,7 @@ export function createOntologyService(ontology, config) {
454
495
  });
455
496
  const application = Layer.mergeAll(channelApps.length > 0
456
497
  ? Layer.merge(channelSessionLayer(config), channelSignInLayer(channelApps, config, connections))
457
- : Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, preview
498
+ : Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, withoutAgent
458
499
  ? Layer.empty
459
500
  : chatRoutes({
460
501
  built,
@@ -474,7 +515,7 @@ export function createOntologyService(ontology, config) {
474
515
  chatDelivery,
475
516
  verifyToken,
476
517
  exchangeSession,
477
- }), preview ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
518
+ }), withoutAgent ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
478
519
  ? Layer.empty
479
520
  : archiveRoutes({
480
521
  transport: chatHistory,
@@ -547,12 +588,23 @@ export function createOntologyService(ontology, config) {
547
588
  requireDeploymentCapability(deployment);
548
589
  if (preview) {
549
590
  const path = new URL(request.url).pathname;
550
- const blocked = /^\/api\/ontology\/(?:agent|agents|chat|attachments|channels)(?:\/|$)/.test(path)
591
+ // A preview that runs the agent serves the routes its web chat and evals use, and still
592
+ // none of channels, pairings, accounts, visitors or tasks.
593
+ const agentRoute = previewAgent &&
594
+ (PREVIEW_AGENT_ROUTE.test(path) ||
595
+ /^\/api\/ontology\/(?:chat|attachments)(?:\/|$)/.test(path));
596
+ const blocked = !agentRoute &&
597
+ /^\/api\/ontology\/(?:agent|agents|chat|attachments|channels)(?:\/|$)/.test(path)
551
598
  ? "agents"
552
599
  : undefined;
553
600
  if (blocked) {
554
601
  throw new DeploymentAdmissionError("preview_capability_unavailable", blocked);
555
602
  }
603
+ if (previewAgent &&
604
+ runtimeIdentity !== undefined &&
605
+ !sameDeployment(request, runtimeIdentity, deployment.deploymentId)) {
606
+ throw new DeploymentAdmissionError("preview_deployment_mismatch");
607
+ }
556
608
  if (/^\/api\/ontology\/(?:oauth|oidc)(?:\/|$)/.test(path) ||
557
609
  (!browser && /^\/api\/ontology\/federation(?:\/|$)/.test(path)) ||
558
610
  path.startsWith("/.well-known/oauth")) {
@@ -49,5 +49,7 @@ export declare function sendSlackFiles(options: {
49
49
  readonly index?: number;
50
50
  }>;
51
51
  readonly text?: string;
52
+ /** Shares nothing unless every file uploaded, as a reply that must arrive whole does. */
53
+ readonly requireAll?: boolean;
52
54
  readonly definite?: DefiniteFailure;
53
55
  }): Promise<SlackFilesResult>;
@@ -112,7 +112,7 @@ export async function sendSlackFiles(options) {
112
112
  });
113
113
  }
114
114
  }
115
- if (uploaded.length === 0) {
115
+ if (uploaded.length === 0 || (options.requireAll === true && uploaded.length < uploads.length)) {
116
116
  return { uploads };
117
117
  }
118
118
  const part = { files: uploaded.map(({ index }) => index), text: options.text !== undefined };
@@ -28,6 +28,8 @@ export interface TelegramEntity {
28
28
  export interface TelegramFormattedText {
29
29
  readonly text: string;
30
30
  readonly entities: ReadonlyArray<TelegramEntity>;
31
+ /** Text written in Telegram's MarkdownV2, formatted by Telegram, in place of entities. */
32
+ readonly parseMode?: "MarkdownV2";
31
33
  }
32
34
  /** How Telegram sends a file of this content type: as a photo or as a document. */
33
35
  export declare function telegramFileType(contentType: string): "photo" | "document";
@@ -77,5 +79,7 @@ export declare function sendTelegramFiles(options: {
77
79
  readonly index?: number;
78
80
  }>;
79
81
  readonly caption?: TelegramFormattedText;
82
+ /** The caption without its formatting, sent when Telegram refuses the caption's formatting. */
83
+ readonly plainCaption?: TelegramFormattedText;
80
84
  readonly definite?: DefiniteFailure;
81
85
  }): Promise<ReadonlyArray<ChannelPart>>;
@@ -117,6 +117,9 @@ async function multipart(target, files, caption) {
117
117
  if (sent.entities.length > 0) {
118
118
  form.set("caption_entities", JSON.stringify(sent.entities));
119
119
  }
120
+ if (caption.parseMode !== undefined) {
121
+ form.set("parse_mode", caption.parseMode);
122
+ }
120
123
  }
121
124
  }
122
125
  else {
@@ -127,6 +130,7 @@ async function multipart(target, files, caption) {
127
130
  ? {
128
131
  caption: caption.text,
129
132
  ...(caption.entities.length > 0 ? { caption_entities: caption.entities } : {}),
133
+ ...(caption.parseMode === undefined ? {} : { parse_mode: caption.parseMode }),
130
134
  }
131
135
  : {}),
132
136
  }))));
@@ -208,9 +212,9 @@ export async function sendTelegramFiles(options) {
208
212
  try {
209
213
  reply = await send(built);
210
214
  if (caption !== undefined &&
211
- caption.entities.length > 0 &&
215
+ (caption.entities.length > 0 || caption.parseMode !== undefined) &&
212
216
  telegramFormattingRefused(reply.status, replyJson(reply))) {
213
- caption = { text: caption.text, entities: [] };
217
+ caption = options.plainCaption ?? { text: caption.text, entities: [] };
214
218
  reply = await send(await multipart(options.target, batch, caption));
215
219
  }
216
220
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.162.0",
3
+ "version": "0.164.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",