@segmentstream/ontology 0.109.0 → 0.110.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 (57) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +21 -0
  3. package/dist/analyze.js +55 -3
  4. package/dist/index.d.ts +5 -5
  5. package/dist/index.js +2 -2
  6. package/dist/manifest.d.ts +94 -5
  7. package/dist/manifest.js +41 -6
  8. package/dist/migrate/apply.d.ts +4 -3
  9. package/dist/migrate/apply.js +8 -3
  10. package/dist/migrate/model.d.ts +46 -2
  11. package/dist/migrate/plan.js +1 -1
  12. package/dist/migrate/preview.js +2 -1
  13. package/dist/migrate/storage.d.ts +13 -1
  14. package/dist/migrate/storage.js +33 -1
  15. package/dist/runtime/agent-counters.d.ts +36 -0
  16. package/dist/runtime/agent-counters.js +84 -0
  17. package/dist/runtime/agent-web.d.ts +1 -1
  18. package/dist/runtime/agent-web.js +175 -3
  19. package/dist/runtime/batch.js +4 -6
  20. package/dist/runtime/history.d.ts +24 -0
  21. package/dist/runtime/history.js +35 -1
  22. package/dist/runtime/pipeline.js +3 -0
  23. package/dist/runtime/principals.d.ts +6 -0
  24. package/dist/runtime/principals.js +25 -6
  25. package/dist/runtime/reads.js +9 -2
  26. package/dist/runtime/sign-in-links.d.ts +10 -0
  27. package/dist/runtime/sign-in-links.js +26 -25
  28. package/dist/runtime/sql-runtime.d.ts +1 -1
  29. package/dist/runtime/sql-runtime.js +3 -2
  30. package/dist/runtime/writes.js +4 -6
  31. package/dist/runtime.d.ts +18 -0
  32. package/dist/service/agent/authentication.d.ts +3 -2
  33. package/dist/service/agent/authentication.js +2 -11
  34. package/dist/service/agent/bot-check.d.ts +42 -0
  35. package/dist/service/agent/bot-check.js +32 -0
  36. package/dist/service/agent/guest-sign-up.d.ts +140 -0
  37. package/dist/service/agent/guest-sign-up.js +545 -0
  38. package/dist/service/agent/protocol.d.ts +33 -1
  39. package/dist/service/agent/protocol.js +41 -1
  40. package/dist/service/agent/server.d.ts +17 -0
  41. package/dist/service/agent/server.js +42 -3
  42. package/dist/service/agent/web-tokens.d.ts +21 -3
  43. package/dist/service/agent/web-tokens.js +79 -6
  44. package/dist/service/authentication.d.ts +8 -1
  45. package/dist/service/authentication.js +26 -5
  46. package/dist/service/config.d.ts +10 -0
  47. package/dist/service/operations.d.ts +5 -0
  48. package/dist/service/runtime-contract.d.ts +124 -1
  49. package/dist/service/runtime-identity.d.ts +23 -0
  50. package/dist/service/runtime-identity.js +31 -0
  51. package/dist/service/schemas.d.ts +46 -2
  52. package/dist/service/service.js +27 -1
  53. package/dist/service/webhooks.d.ts +15 -0
  54. package/dist/service/webhooks.js +15 -4
  55. package/dist/sign-in.d.ts +29 -0
  56. package/dist/sign-in.js +8 -0
  57. package/package.json +1 -1
@@ -11,6 +11,35 @@ export const ACT_AS_HEADER = "x-segmentstream-act-as";
11
11
  * workflow user, on `/mcp` and the task routes only; every other route refuses it.
12
12
  */
13
13
  export const AGENT_TASK_HEADER = "x-segmentstream-agent-task";
14
+ /**
15
+ * The chat a runtime request comes from, `<provider>:<chat id>` as the chat archive names it, and
16
+ * the agent's session there. The app's agent names them on its attachment routes, and on every
17
+ * request it acts in a chat with, so that history keeps the chat an action came from.
18
+ */
19
+ export const CHAT_HEADER = "x-segmentstream-agent-chat";
20
+ export const SESSION_HEADER = "x-segmentstream-agent-session";
21
+ /** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
22
+ export const EARLIER_CHAT_HEADER = "x-segmentstream-agent-conversation";
23
+ /**
24
+ * `provider:chat id`. An email chat is a Gmail thread and the person's address
25
+ * (`email:<thread>:<address>`), so an id may hold an address's `@`, `.` and `+`.
26
+ */
27
+ export const CHAT = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_.@+-]{1,320}$/;
28
+ export const SESSION = /^[A-Za-z0-9:_.-]{1,200}$/;
29
+ /** The chat and session a request names, or `undefined` without a well-formed chat. */
30
+ export function requestChat(request) {
31
+ const chat = (request.headers[CHAT_HEADER] ?? request.headers[EARLIER_CHAT_HEADER])?.trim() ?? "";
32
+ const session = request.headers[SESSION_HEADER]?.trim() ?? "";
33
+ if (!CHAT.test(chat) || (session !== "" && !SESSION.test(session))) {
34
+ return undefined;
35
+ }
36
+ const colon = chat.indexOf(":");
37
+ return {
38
+ provider: chat.slice(0, colon),
39
+ chatId: chat.slice(colon + 1),
40
+ ...(session === "" ? {} : { sessionId: session }),
41
+ };
42
+ }
14
43
  const CLOCK_TOLERANCE_SECONDS = 5;
15
44
  const JWKS_TIMEOUT_MS = 5_000;
16
45
  /** The environment that a Vercel function token must name: channels run only in production. */
@@ -122,11 +151,13 @@ export function runtimeCredential(verify, request) {
122
151
  const provider = request.headers[ACT_AS_PROVIDER_HEADER]?.trim();
123
152
  const agentTask = agentTaskSecret(request);
124
153
  const grant = request.headers[AGENT_GRANT_HEADER]?.trim();
154
+ const chat = requestChat(request);
125
155
  return {
126
156
  verify,
127
157
  actAs: actAs === undefined || actAs === "" ? undefined : actAs,
128
158
  ...(provider ? { provider } : {}),
129
159
  ...(agentTask === undefined ? {} : { agentTask }),
130
160
  ...(grant ? { grant } : {}),
161
+ ...(chat === undefined ? {} : { chat }),
131
162
  };
132
163
  }
@@ -62,6 +62,11 @@ export declare const HistoryEntry: Schema.decodeTo<Schema.Struct<{
62
62
  readonly issuedAt: Schema.Number;
63
63
  readonly expiresAt: Schema.Number;
64
64
  }>>;
65
+ readonly chat: Schema.optionalKey<Schema.Struct<{
66
+ readonly provider: Schema.String;
67
+ readonly chatId: Schema.String;
68
+ readonly sessionId: Schema.optionalKey<Schema.String>;
69
+ }>>;
65
70
  readonly id: Schema.String;
66
71
  readonly recordId: Schema.String;
67
72
  readonly action: Schema.String;
@@ -94,6 +99,11 @@ export declare const HistoryEntry: Schema.decodeTo<Schema.Struct<{
94
99
  readonly issuedAt: Schema.Number;
95
100
  readonly expiresAt: Schema.Number;
96
101
  }>>>;
102
+ readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.Struct<{
103
+ readonly provider: Schema.String;
104
+ readonly chatId: Schema.String;
105
+ readonly sessionId: Schema.optionalKey<Schema.String>;
106
+ }>>>;
97
107
  readonly id: Schema.toEncoded<Schema.String>;
98
108
  readonly record_id: Schema.toEncoded<Schema.String>;
99
109
  readonly action: Schema.toEncoded<Schema.String>;
@@ -128,6 +138,11 @@ export declare const HistoryPage: Schema.decodeTo<Schema.Struct<{
128
138
  readonly issuedAt: Schema.Number;
129
139
  readonly expiresAt: Schema.Number;
130
140
  }>>;
141
+ readonly chat: Schema.optionalKey<Schema.Struct<{
142
+ readonly provider: Schema.String;
143
+ readonly chatId: Schema.String;
144
+ readonly sessionId: Schema.optionalKey<Schema.String>;
145
+ }>>;
131
146
  readonly id: Schema.String;
132
147
  readonly recordId: Schema.String;
133
148
  readonly action: Schema.String;
@@ -160,6 +175,11 @@ export declare const HistoryPage: Schema.decodeTo<Schema.Struct<{
160
175
  readonly issuedAt: Schema.Number;
161
176
  readonly expiresAt: Schema.Number;
162
177
  }>>>;
178
+ readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.Struct<{
179
+ readonly provider: Schema.String;
180
+ readonly chatId: Schema.String;
181
+ readonly sessionId: Schema.optionalKey<Schema.String>;
182
+ }>>>;
163
183
  readonly id: Schema.toEncoded<Schema.String>;
164
184
  readonly record_id: Schema.toEncoded<Schema.String>;
165
185
  readonly action: Schema.toEncoded<Schema.String>;
@@ -195,6 +215,11 @@ export declare const HistoryPage: Schema.decodeTo<Schema.Struct<{
195
215
  readonly issuedAt: Schema.Number;
196
216
  readonly expiresAt: Schema.Number;
197
217
  }>>;
218
+ readonly chat: Schema.optionalKey<Schema.Struct<{
219
+ readonly provider: Schema.String;
220
+ readonly chatId: Schema.String;
221
+ readonly sessionId: Schema.optionalKey<Schema.String>;
222
+ }>>;
198
223
  readonly id: Schema.String;
199
224
  readonly recordId: Schema.String;
200
225
  readonly action: Schema.String;
@@ -227,6 +252,11 @@ export declare const HistoryPage: Schema.decodeTo<Schema.Struct<{
227
252
  readonly issuedAt: Schema.Number;
228
253
  readonly expiresAt: Schema.Number;
229
254
  }>>>;
255
+ readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.Struct<{
256
+ readonly provider: Schema.String;
257
+ readonly chatId: Schema.String;
258
+ readonly sessionId: Schema.optionalKey<Schema.String>;
259
+ }>>>;
230
260
  readonly id: Schema.toEncoded<Schema.String>;
231
261
  readonly record_id: Schema.toEncoded<Schema.String>;
232
262
  readonly action: Schema.toEncoded<Schema.String>;
@@ -428,9 +458,16 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
428
458
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
429
459
  }>>;
430
460
  readonly onSignUp: Schema.optionalKey<Schema.String>;
431
- readonly guest: Schema.optionalKey<Schema.Struct<{
461
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
432
462
  readonly channels: Schema.$Array<Schema.String>;
433
463
  readonly origins: Schema.$Array<Schema.String>;
464
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
465
+ readonly scheme: Schema.String;
466
+ readonly secret: Schema.String;
467
+ }>>;
468
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
469
+ }>, {
470
+ readonly botCheck: "bot_check";
434
471
  }>>;
435
472
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
436
473
  }>, {
@@ -724,9 +761,16 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
724
761
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
725
762
  }>>;
726
763
  readonly onSignUp: Schema.optionalKey<Schema.String>;
727
- readonly guest: Schema.optionalKey<Schema.Struct<{
764
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
728
765
  readonly channels: Schema.$Array<Schema.String>;
729
766
  readonly origins: Schema.$Array<Schema.String>;
767
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
768
+ readonly scheme: Schema.String;
769
+ readonly secret: Schema.String;
770
+ }>>;
771
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
772
+ }>, {
773
+ readonly botCheck: "bot_check";
730
774
  }>>;
731
775
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
732
776
  }>, {
@@ -9,7 +9,7 @@ import { RuntimeDeployment } from "../runtime/deployment.js";
9
9
  import { nameToWire } from "../authoring-names.js";
10
10
  import { bundledNavigationCatalog } from "../navigation-artifact.js";
11
11
  import { parsePageCatalog } from "../navigation-catalog.js";
12
- import { guestOf, signUpOriginsOf } from "../manifest.js";
12
+ import { guestOf, signUpOriginsOf, signUpRolesOf } from "../manifest.js";
13
13
  import { isAllowed } from "../permissions.js";
14
14
  import { agentToolsFor } from "../runtime/guests.js";
15
15
  import { sqlServiceRuntime } from "../runtime/service-binding.js";
@@ -48,6 +48,8 @@ import { channelSignInLayer } from "./channel/sign-in.js";
48
48
  import { telegramAppProvider } from "./channel/providers/telegram.js";
49
49
  import { planApi } from "./plan.js";
50
50
  import { deployedWebhookTokenVerifier, deployedWebhookVerifier } from "./webhooks.js";
51
+ import { deployedBotCheckVerifier } from "./agent/bot-check.js";
52
+ import { neonEmailCodes } from "./agent/guest-sign-up.js";
51
53
  import { vercelWorkflowEngine, workflowStarter, workflowsLayer } from "./workflows.js";
52
54
  import { deploymentWorkflowEngine } from "./workflow-deployment.js";
53
55
  import { OntologyBackend } from "./runtime-contract.js";
@@ -384,6 +386,20 @@ export function createOntologyService(ontology, config) {
384
386
  }), oauth);
385
387
  // Every answer that tells the agent whom it acts for names the agent's own tools they hold.
386
388
  const agentTools = (principal) => agentToolsFor(ontology, principal);
389
+ const guest = guestOf(ontology.manifest);
390
+ // A guest proves an address with the app's own code email, which needs the production app.
391
+ const emailCodes = config.emailCodes ??
392
+ ((!browser || browser.methods.includes("email")) &&
393
+ config.neonAuth !== undefined &&
394
+ config.agentOrigin !== undefined &&
395
+ config.browserEnvironment !== "local" &&
396
+ !preview
397
+ ? neonEmailCodes({
398
+ baseUrl: config.neonAuth.baseUrl,
399
+ origin: config.agentOrigin,
400
+ verifyToken,
401
+ })
402
+ : undefined);
387
403
  const agent = preview
388
404
  ? Layer.empty
389
405
  : agentLayer({
@@ -392,6 +408,16 @@ export function createOntologyService(ontology, config) {
392
408
  exchangeSession,
393
409
  visitorWebsites,
394
410
  agentTools,
411
+ guest,
412
+ botCheckVerifier: config.botCheckVerifier ??
413
+ deployedBotCheckVerifier({
414
+ segmentstreamUrl: config.segmentstreamUrl,
415
+ workspaceId: config.workspaceId,
416
+ organizationId: config.organizationId,
417
+ deploymentId: deployment.deploymentId,
418
+ }),
419
+ emailSignUp: signUpRolesOf(ontology.manifest, "email") !== undefined,
420
+ emailCodes,
395
421
  });
396
422
  const agentTasks = preview
397
423
  ? Layer.empty
@@ -8,6 +8,8 @@ import type { WebhookSignatureScheme } from "../webhooks.js";
8
8
  /** What SegmentStream's backend answered about a delivery's signature. */
9
9
  export type WebhookVerification = {
10
10
  readonly outcome: "valid";
11
+ /** For a challenge check: the hostname of the page the challenge was solved on. */
12
+ readonly hostname?: string;
11
13
  } | {
12
14
  readonly outcome: "invalid";
13
15
  }
@@ -64,6 +66,19 @@ export declare function deployedWebhookTokenVerifier(environment: {
64
66
  readonly deploymentId?: string | undefined;
65
67
  readonly previewCredential?: Redacted.Redacted<string> | undefined;
66
68
  }, fetchImpl?: typeof fetch): WebhookTokenVerifier;
69
+ /**
70
+ * A check against a workspace secret that SegmentStream's backend makes for the deployed ontology
71
+ * service, admitted only for the secrets its manifest names: the secret never leaves the backend,
72
+ * and the answer says only whether the check passed. `verify-challenge` checks a bot check's token
73
+ * with the challenge provider.
74
+ */
75
+ export declare function deployedSecretVerifier(environment: {
76
+ readonly segmentstreamUrl: string;
77
+ readonly workspaceId: string;
78
+ readonly organizationId: string;
79
+ readonly deploymentId?: string | undefined;
80
+ readonly previewCredential?: Redacted.Redacted<string> | undefined;
81
+ }, operation: "verify-hmac" | "verify-token" | "verify-challenge", fetchImpl: typeof fetch): (request: Pick<WebhookVerifyRequest, "secret" | "identityToken" | "requestId">, payload: unknown) => Promise<WebhookVerification>;
67
82
  /** The bytes a scheme's signatures cover and the signatures to compare, or why it refused. */
68
83
  export type SignedContent = {
69
84
  readonly ok: true;
@@ -21,14 +21,20 @@ export function deployedWebhookTokenVerifier(environment, fetchImpl = fetch) {
21
21
  const verify = deployedSecretVerifier(environment, "verify-token", fetchImpl);
22
22
  return (request) => verify(request, { token: request.token });
23
23
  }
24
- function deployedSecretVerifier(environment, operation, fetchImpl) {
24
+ /**
25
+ * A check against a workspace secret that SegmentStream's backend makes for the deployed ontology
26
+ * service, admitted only for the secrets its manifest names: the secret never leaves the backend,
27
+ * and the answer says only whether the check passed. `verify-challenge` checks a bot check's token
28
+ * with the challenge provider.
29
+ */
30
+ export function deployedSecretVerifier(environment, operation, fetchImpl) {
25
31
  const base = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
26
32
  `${encodeURIComponent(environment.workspaceId)}/secrets/`;
27
33
  return async (request, payload) => {
28
34
  if (request.identityToken === undefined || request.identityToken === "") {
29
35
  return {
30
36
  outcome: "unavailable",
31
- cause: new Error("The request carries no Vercel OIDC token for webhook verification."),
37
+ cause: new Error(`The request carries no Vercel OIDC token for ${operation}.`),
32
38
  };
33
39
  }
34
40
  try {
@@ -64,12 +70,17 @@ function deployedSecretVerifier(environment, operation, fetchImpl) {
64
70
  return { outcome: "secret_missing" };
65
71
  }
66
72
  if (response.ok && typeof answer.valid === "boolean") {
67
- return { outcome: answer.valid ? "valid" : "invalid" };
73
+ return answer.valid
74
+ ? {
75
+ outcome: "valid",
76
+ ...(typeof answer.hostname === "string" ? { hostname: answer.hostname } : {}),
77
+ }
78
+ : { outcome: "invalid" };
68
79
  }
69
80
  return {
70
81
  outcome: "unavailable",
71
82
  status: response.status,
72
- cause: new Error(`SegmentStream answered ${response.status} to the signature check: ${text.slice(0, 500)}`),
83
+ cause: new Error(`SegmentStream answered ${response.status} to ${operation}: ${text.slice(0, 500)}`),
73
84
  };
74
85
  }
75
86
  catch (cause) {
package/dist/sign-in.d.ts CHANGED
@@ -69,11 +69,40 @@ export interface GuestOptions<P = unknown> {
69
69
  * cannot use `me`. `[]` lets guests talk to the agent and nothing more.
70
70
  */
71
71
  readonly permissions: ReadonlyArray<P>;
72
+ /**
73
+ * A bot check before a guest exists: the website shows a challenge, and a new guest's agent token
74
+ * is issued only for a token from it that the challenge's provider accepts. `scheme` names the
75
+ * provider; `secret` names the workspace secret holding the provider's secret key, which only the
76
+ * platform reads. Absent, no challenge is asked for.
77
+ */
78
+ readonly botCheck?: GuestBotCheck;
79
+ /**
80
+ * Whether a guest may confirm an action that needs a confirmation, with the buttons of the
81
+ * website's chat, as a member confirms one. Off when absent: such an action is refused for a guest.
82
+ */
83
+ readonly confirmations?: boolean;
84
+ }
85
+ /**
86
+ * The challenge providers a guest's bot check can verify. `turnstile` is Cloudflare Turnstile: the
87
+ * website renders its widget with the site key, and the workspace secret holds its secret key.
88
+ */
89
+ export declare const GUEST_BOT_CHECK_SCHEMES: readonly ["turnstile"];
90
+ export type GuestBotCheckScheme = (typeof GUEST_BOT_CHECK_SCHEMES)[number];
91
+ export declare function isGuestBotCheckScheme(value: unknown): value is GuestBotCheckScheme;
92
+ /** The challenge a website's visitor passes before they become a guest. */
93
+ export interface GuestBotCheck {
94
+ readonly scheme: GuestBotCheckScheme;
95
+ /** The workspace secret holding the provider's secret key, such as `turnstile-secret-key`. */
96
+ readonly secret: string;
72
97
  }
73
98
  /** Guests as the manifest carries them; the built-in role `guest` holds their permissions. */
74
99
  export interface ResolvedGuest {
75
100
  readonly channels: ReadonlyArray<GuestChannel>;
76
101
  readonly origins: ReadonlyArray<string>;
102
+ /** The challenge a new guest passes, when declared. */
103
+ readonly botCheck?: GuestBotCheck;
104
+ /** Present when guests may confirm actions that need a confirmation. */
105
+ readonly confirmations?: true;
77
106
  }
78
107
  /**
79
108
  * A website's origin as `guest.origins` and `signUp.origins` accept it, written as an origin alone,
package/dist/sign-in.js CHANGED
@@ -26,6 +26,14 @@ export const GUEST_CHANNELS = ["web"];
26
26
  export function isGuestChannel(value) {
27
27
  return GUEST_CHANNELS.includes(value);
28
28
  }
29
+ /**
30
+ * The challenge providers a guest's bot check can verify. `turnstile` is Cloudflare Turnstile: the
31
+ * website renders its widget with the site key, and the workspace secret holds its secret key.
32
+ */
33
+ export const GUEST_BOT_CHECK_SCHEMES = ["turnstile"];
34
+ export function isGuestBotCheckScheme(value) {
35
+ return GUEST_BOT_CHECK_SCHEMES.includes(value);
36
+ }
29
37
  /** A DNS label, lowercase, as a browser serializes it in an origin. */
30
38
  const DNS_LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;
31
39
  /** A top-level domain: letters, or an internationalized name in its ASCII form. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.109.0",
3
+ "version": "0.110.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",