@segmentstream/ontology 0.109.0 → 0.111.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 (79) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +28 -1
  3. package/dist/agent-review.d.ts +2 -0
  4. package/dist/agent-review.js +11 -1
  5. package/dist/analyze.d.ts +34 -34
  6. package/dist/analyze.js +104 -29
  7. package/dist/chat-channel.d.ts +22 -0
  8. package/dist/chat-channel.js +35 -0
  9. package/dist/index.d.ts +8 -6
  10. package/dist/index.js +3 -2
  11. package/dist/manifest.d.ts +194 -29
  12. package/dist/manifest.js +54 -10
  13. package/dist/migrate/apply.d.ts +4 -3
  14. package/dist/migrate/apply.js +8 -3
  15. package/dist/migrate/model.d.ts +90 -2
  16. package/dist/migrate/plan.js +1 -1
  17. package/dist/migrate/preview.js +2 -1
  18. package/dist/migrate/storage.d.ts +13 -1
  19. package/dist/migrate/storage.js +33 -1
  20. package/dist/runtime/agent-counters.d.ts +36 -0
  21. package/dist/runtime/agent-counters.js +84 -0
  22. package/dist/runtime/agent-web.d.ts +1 -1
  23. package/dist/runtime/agent-web.js +175 -3
  24. package/dist/runtime/agents.js +3 -0
  25. package/dist/runtime/batch.js +4 -6
  26. package/dist/runtime/history.d.ts +24 -0
  27. package/dist/runtime/history.js +35 -1
  28. package/dist/runtime/pipeline.js +3 -0
  29. package/dist/runtime/principals.d.ts +6 -0
  30. package/dist/runtime/principals.js +25 -6
  31. package/dist/runtime/reads.js +9 -2
  32. package/dist/runtime/sign-in-links.d.ts +10 -0
  33. package/dist/runtime/sign-in-links.js +26 -25
  34. package/dist/runtime/sql-runtime.d.ts +1 -1
  35. package/dist/runtime/sql-runtime.js +3 -2
  36. package/dist/runtime/writes.js +4 -6
  37. package/dist/runtime-source.d.ts +4 -0
  38. package/dist/runtime-source.js +5 -0
  39. package/dist/runtime.d.ts +21 -0
  40. package/dist/service/agent/authentication.d.ts +3 -2
  41. package/dist/service/agent/authentication.js +2 -11
  42. package/dist/service/agent/bot-check.d.ts +42 -0
  43. package/dist/service/agent/bot-check.js +32 -0
  44. package/dist/service/agent/guest-sign-up.d.ts +140 -0
  45. package/dist/service/agent/guest-sign-up.js +545 -0
  46. package/dist/service/agent/protocol.d.ts +34 -1
  47. package/dist/service/agent/protocol.js +46 -1
  48. package/dist/service/agent/server.d.ts +17 -0
  49. package/dist/service/agent/server.js +53 -3
  50. package/dist/service/agent/web-tokens.d.ts +21 -3
  51. package/dist/service/agent/web-tokens.js +79 -6
  52. package/dist/service/authentication.d.ts +9 -1
  53. package/dist/service/authentication.js +31 -5
  54. package/dist/service/chat/delivery.js +9 -5
  55. package/dist/service/chat/envelope.d.ts +6 -0
  56. package/dist/service/chat/providers/index.d.ts +19 -9
  57. package/dist/service/chat/providers/index.js +31 -11
  58. package/dist/service/chat/reads.d.ts +6 -3
  59. package/dist/service/chat/reads.js +26 -14
  60. package/dist/service/chat/resolve.d.ts +6 -2
  61. package/dist/service/chat/resolve.js +7 -3
  62. package/dist/service/chat/review-delivery.d.ts +2 -2
  63. package/dist/service/chat/review-delivery.js +16 -8
  64. package/dist/service/chat/routes.js +2 -1
  65. package/dist/service/chat/schemas.d.ts +2 -0
  66. package/dist/service/chat/schemas.js +8 -1
  67. package/dist/service/config.d.ts +10 -0
  68. package/dist/service/mcp/server.js +2 -1
  69. package/dist/service/operations.d.ts +5 -0
  70. package/dist/service/runtime-contract.d.ts +133 -1
  71. package/dist/service/runtime-identity.d.ts +23 -0
  72. package/dist/service/runtime-identity.js +31 -0
  73. package/dist/service/schemas.d.ts +54 -2
  74. package/dist/service/service.js +27 -1
  75. package/dist/service/webhooks.d.ts +15 -0
  76. package/dist/service/webhooks.js +15 -4
  77. package/dist/sign-in.d.ts +29 -0
  78. package/dist/sign-in.js +8 -0
  79. package/package.json +1 -1
@@ -1,5 +1,7 @@
1
1
  import { randomInt } from "node:crypto";
2
2
  import { Schema } from "effect";
3
+ import { ChatChannelName } from "../../chat-channel.js";
4
+ import { GUEST_USD_CEILINGS, MAX_GUEST_USAGE_REPORT_USD } from "../../runtime/agent-counters.js";
3
5
  /** How long a member has to open the connect link, sign in and approve the pairing. */
4
6
  export const PAIRING_TTL_MS = 10 * 60 * 1000;
5
7
  /**
@@ -42,9 +44,14 @@ export const PairingRequest = Schema.Struct({
42
44
  });
43
45
  /** Trusted runtime resolution: channel admission and limits run before expensive processing. */
44
46
  const PositiveLimit = Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_000_000_000));
47
+ /** A cap on guests' daily model cost, in US dollars: more than nothing, at most `ceiling`. */
48
+ function usdCap(ceiling) {
49
+ return Schema.Number.check(Schema.isFinite(), Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(ceiling));
50
+ }
45
51
  /**
46
52
  * The agent's limits, as it sends them with a turn: each can only lower the platform's ceiling.
47
- * `guest` limits guests' turns, apart from those of people who signed up.
53
+ * `guest` limits guests' turns, apart from those of people who signed up, and, when the agent sets
54
+ * them, the model cost of each guest's turns and of every guest's together each day.
48
55
  */
49
56
  export const AgentLimitsRequest = Schema.Struct({
50
57
  perSender: Schema.optionalKey(Schema.Struct({
@@ -56,8 +63,42 @@ export const AgentLimitsRequest = Schema.Struct({
56
63
  guest: Schema.optionalKey(Schema.Struct({
57
64
  turnsPerDay: Schema.optionalKey(PositiveLimit),
58
65
  workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
66
+ usdPerDay: Schema.optionalKey(usdCap(GUEST_USD_CEILINGS.usdPerDay)),
67
+ workspaceUsdPerDay: Schema.optionalKey(usdCap(GUEST_USD_CEILINGS.workspaceUsdPerDay)),
59
68
  })),
60
69
  });
70
+ /**
71
+ * `POST /api/ontology/agent/guests/usage` (runtime): the model cost of a guest's turn, as the
72
+ * runtime recorded it, for the guests' money caps. `key` names the report, so a retry adds nothing.
73
+ */
74
+ export const GuestUsageRequest = Schema.Struct({
75
+ guest_id: Schema.String.check(Schema.isUUID()),
76
+ cost_usd: Schema.Number.check(Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(MAX_GUEST_USAGE_REPORT_USD)),
77
+ key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
78
+ });
79
+ /** An email address a guest gives, as the app's sign-in takes one. */
80
+ const GuestEmail = Schema.String.check(Schema.isMinLength(3), Schema.isMaxLength(320));
81
+ /**
82
+ * `POST /api/ontology/agent/guests/email-code`: the address a guest proves, and the page of the
83
+ * guest's website an emailed link returns to.
84
+ */
85
+ export const GuestEmailCodeRequest = Schema.Struct({
86
+ email: GuestEmail,
87
+ return_to: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2048))),
88
+ });
89
+ /**
90
+ * `POST /api/ontology/agent/guests/sign-up`: the address and the code it received, or the handoff
91
+ * an opened link gave the guest's browser.
92
+ */
93
+ export const GuestSignUpRequest = Schema.Union([
94
+ Schema.Struct({
95
+ email: GuestEmail,
96
+ code: Schema.String.check(Schema.isPattern(/^[0-9]{4,12}$/)),
97
+ }),
98
+ Schema.Struct({
99
+ handoff: Schema.String.check(Schema.isMinLength(16), Schema.isMaxLength(256)),
100
+ }),
101
+ ]);
61
102
  export const ResolveIdentityRequest = Schema.Struct({
62
103
  ...PairingRequest.fields,
63
104
  chat: Schema.Literals(["private", "group"]),
@@ -116,6 +157,10 @@ export const ReviewRequest = Schema.Struct({
116
157
  description: "The agent's key for the reply: its session and content part.",
117
158
  }),
118
159
  provider: Provider,
160
+ channel: Schema.optionalKey(ChatChannelName.annotate({
161
+ description: "The channel the chat is on, by name, when it is not the one named after its kind, " +
162
+ "such as sales_whatsapp: approval sends the reply through its connection.",
163
+ })),
119
164
  chat_id: ChatId.annotate({ description: "The chat's id on the channel." }),
120
165
  recipient: ChatId.annotate({
121
166
  description: "Whom the provider sends the reply to: the chat's id, or the person's number.",
@@ -7,6 +7,9 @@ import { OntologyBackend } from "../runtime-contract.js";
7
7
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
8
8
  import { type AgentToolsOf } from "./protocol.js";
9
9
  import { type VisitorWebsites } from "./web-tokens.js";
10
+ import type { BotCheckVerifier } from "./bot-check.js";
11
+ import { GUEST_LINK_PATH, type EmailCodes } from "./guest-sign-up.js";
12
+ import type { ResolvedGuest } from "../../sign-in.js";
10
13
  /** The agent's endpoints, under the ontology service's path. */
11
14
  export declare const AGENT_PATH = "/api/ontology/agent";
12
15
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
@@ -14,6 +17,12 @@ export declare const AGENT_TOKENS_PATH = "/api/ontology/agent/tokens";
14
17
  export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
15
18
  /** Where a browser on a declared website signs its visitor up on `web`. */
16
19
  export declare const AGENT_VISITORS_PATH = "/api/ontology/agent/visitors";
20
+ /** A website's guests' own routes: becoming a user, and the runtime's report of their spend. */
21
+ export declare const AGENT_GUESTS_PATH = "/api/ontology/agent/guests";
22
+ export declare const GUEST_EMAIL_CODE_PATH = "/api/ontology/agent/guests/email-code";
23
+ export declare const GUEST_SIGN_UP_PATH = "/api/ontology/agent/guests/sign-up";
24
+ export declare const GUEST_USAGE_PATH = "/api/ontology/agent/guests/usage";
25
+ export { GUEST_LINK_PATH };
17
26
  /**
18
27
  * Pairings one client address may start per minute; each one is a row in the database. The agent's
19
28
  * functions share a few egress addresses, so the limit leaves room for a busy channel.
@@ -31,6 +40,14 @@ export interface AgentServerOptions {
31
40
  readonly exchangeSession: SessionExchange | undefined;
32
41
  /** The agent's own tools a caller holds, which every answer naming whom the agent acts for carries. */
33
42
  readonly agentTools: AgentToolsOf;
43
+ /** The guests the ontology declares: their bot check and whether they confirm actions. */
44
+ readonly guest?: ResolvedGuest | undefined;
45
+ /** Checks a new guest's challenge token when `guest.botCheck` asks for one. */
46
+ readonly botCheckVerifier?: BotCheckVerifier | undefined;
47
+ /** Whether `signUp` lists `email`, on which a guest who proves an address becomes a user. */
48
+ readonly emailSignUp?: boolean;
49
+ /** The app's email sign-in, through which a guest proves an address; none when unavailable. */
50
+ readonly emailCodes?: EmailCodes | undefined;
34
51
  }
35
52
  /**
36
53
  * The routes that pair channel accounts with members for the app's own agent, and record the group
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { Effect, Layer, Redacted, Result, Schema } from "effect";
4
4
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
5
5
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
6
+ import { isChatChannelKind } from "../../chat-channel.js";
6
7
  import { API_KEY_PREFIX } from "../../runtime/principals.js";
7
8
  import { schemaIssues } from "../../runtime/validation.js";
8
9
  import { BASE_PATH } from "../api.js";
@@ -13,7 +14,9 @@ import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
13
14
  import { OntologyBackend } from "../runtime-contract.js";
14
15
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
15
16
  import { ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
16
- import { AGENT_TOKEN_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
17
+ import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
18
+ import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
19
+ import { identityToken } from "../operations.js";
17
20
  /** The agent's endpoints, under the ontology service's path. */
18
21
  export const AGENT_PATH = `${BASE_PATH}/agent`;
19
22
  const PAIRINGS_PATH = `${AGENT_PATH}/pairings`;
@@ -25,6 +28,12 @@ export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
25
28
  export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
26
29
  /** Where a browser on a declared website signs its visitor up on `web`. */
27
30
  export const AGENT_VISITORS_PATH = `${AGENT_PATH}/visitors`;
31
+ /** A website's guests' own routes: becoming a user, and the runtime's report of their spend. */
32
+ export const AGENT_GUESTS_PATH = `${AGENT_PATH}/guests`;
33
+ export const GUEST_EMAIL_CODE_PATH = `${AGENT_GUESTS_PATH}/email-code`;
34
+ export const GUEST_SIGN_UP_PATH = `${AGENT_GUESTS_PATH}/sign-up`;
35
+ export const GUEST_USAGE_PATH = `${AGENT_GUESTS_PATH}/usage`;
36
+ export { GUEST_LINK_PATH };
28
37
  /**
29
38
  * Pairings one client address may start per minute; each one is a row in the database. The agent's
30
39
  * functions share a few egress addresses, so the limit leaves room for a busy channel.
@@ -297,9 +306,18 @@ function holdReply(store) {
297
306
  return toServerResponse(notFound(requestId, "This ontology service holds no replies."));
298
307
  }
299
308
  const body = decoded.success;
309
+ // A channel named after a kind is that kind.
310
+ if (body.channel !== undefined &&
311
+ isChatChannelKind(body.channel) &&
312
+ body.channel !== body.provider) {
313
+ return invalidBody(requestId, [
314
+ { path: ["channel"], message: "A channel named after a kind is that kind." },
315
+ ]);
316
+ }
300
317
  const review = yield* store.holdReply({
301
318
  key: body.key,
302
319
  provider: body.provider,
320
+ channel: body.channel ?? body.provider,
303
321
  chatId: body.chat_id,
304
322
  recipient: body.recipient,
305
323
  threadId: body.thread_id,
@@ -316,6 +334,7 @@ function holdReply(store) {
316
334
  yield* Effect.logInfo("ontology.agent.reply_held").pipe(Effect.annotateLogs({
317
335
  requestId,
318
336
  provider: body.provider,
337
+ channel: body.channel ?? body.provider,
319
338
  reviewId: review.id,
320
339
  created: review.created,
321
340
  mode: body.mode,
@@ -437,11 +456,42 @@ export function agentLayer(options) {
437
456
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
438
457
  if (store.web !== undefined && backend.oauth !== undefined) {
439
458
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
440
- yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools)));
459
+ yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools, options.guest)));
441
460
  const websites = options.visitorWebsites ?? { guests: [], signUp: [] };
461
+ const botCheck = options.guest?.botCheck === undefined || options.botCheckVerifier === undefined
462
+ ? undefined
463
+ : {
464
+ check: options.guest.botCheck,
465
+ verify: options.botCheckVerifier,
466
+ identityToken,
467
+ limiter: fixedWindowLimiter(BOT_CHECK_LIMIT),
468
+ };
469
+ // A declared bot check that cannot be verified admits no new guest.
470
+ if (options.guest?.botCheck !== undefined && botCheck === undefined) {
471
+ return yield* Effect.die(new Error("guest.botCheck needs a bot check verifier."));
472
+ }
442
473
  if (websites.guests.length > 0 || websites.signUp.length > 0) {
443
474
  yield* router.add("OPTIONS", AGENT_VISITORS_PATH, visitorPreflight(websites));
444
- yield* router.add("POST", AGENT_VISITORS_PATH, issueVisitorToken(store.web, websites));
475
+ yield* router.add("POST", AGENT_VISITORS_PATH, issueVisitorToken(store.web, websites, botCheck));
476
+ }
477
+ if (websites.guests.length > 0) {
478
+ const guests = guestSignUpRoutes({
479
+ emailSignUp: options.emailSignUp === true,
480
+ web: store.web,
481
+ oauth: backend.oauth,
482
+ origins: websites.guests,
483
+ emailCodes: options.emailCodes,
484
+ exchangeSession: options.exchangeSession,
485
+ verifyToken: options.verifyToken,
486
+ });
487
+ const preflight = guestRoutesPreflight(websites.guests);
488
+ yield* router.add("OPTIONS", GUEST_EMAIL_CODE_PATH, preflight);
489
+ yield* router.add("POST", GUEST_EMAIL_CODE_PATH, guests.emailCode);
490
+ yield* router.add("OPTIONS", GUEST_SIGN_UP_PATH, preflight);
491
+ yield* router.add("POST", GUEST_SIGN_UP_PATH, guests.signUp);
492
+ // Where an emailed link lands, signed in on the app's origin: a top-level navigation.
493
+ yield* router.add("GET", GUEST_LINK_PATH, guests.link);
494
+ yield* router.add("POST", GUEST_USAGE_PATH, asRuntime(recordGuestUsage(store.web)));
445
495
  }
446
496
  }
447
497
  }));
@@ -4,6 +4,8 @@ import type { Principal } from "../../runtime.js";
4
4
  import { RequestId } from "../errors.js";
5
5
  import { type RateLimit, type RateLimiter } from "../rate-limit.js";
6
6
  import type { AgentStore, AgentWebStore, OAuthStore } from "../runtime-contract.js";
7
+ import { type GuestBotCheck, type ResolvedGuest } from "../../sign-in.js";
8
+ import { type BotCheckVerifier } from "./bot-check.js";
7
9
  import { type AgentToolsOf } from "./protocol.js";
8
10
  /**
9
11
  * A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
@@ -34,7 +36,11 @@ export declare function issueAgentToken(store: AgentStore, web: AgentWebStore, l
34
36
  * `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
35
37
  * turns counts against the agent's guest limits.
36
38
  */
37
- export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore, agentTools: AgentToolsOf): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
39
+ export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore, agentTools: AgentToolsOf, guests?: Pick<ResolvedGuest, "confirmations">): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
40
+ /** The headers that let a website on `origin` read an answer to its visitor's browser. */
41
+ export declare function websiteHeaders(origin: string): Record<string, string>;
42
+ /** The declared website a browser's request comes from, when it comes from one. */
43
+ export declare function websiteOf(request: HttpServerRequest.HttpServerRequest, origins: ReadonlyArray<string>): string | undefined;
38
44
  /**
39
45
  * The websites whose visitors get an agent token at `POST /api/ontology/agent/visitors`: those whose
40
46
  * visitors are guests, and those whose visitors sign up on `web`. A website both declare is the
@@ -49,6 +55,16 @@ export interface VisitorWebsites {
49
55
  * its visitor's agent token; any other origin gets no permission.
50
56
  */
51
57
  export declare function visitorPreflight(websites: VisitorWebsites): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, never>;
58
+ /** Bot checks one network address may have verified a minute, before any reaches the provider. */
59
+ export declare const BOT_CHECK_LIMIT: RateLimit;
60
+ /** How a new guest passes `guest.botCheck`, when the ontology declares one. */
61
+ export interface VisitorBotCheck {
62
+ readonly check: GuestBotCheck;
63
+ readonly verify: BotCheckVerifier;
64
+ /** The deployment's Vercel OIDC token for a request, which the backend's check admits. */
65
+ readonly identityToken: (request: HttpServerRequest.HttpServerRequest) => string | undefined;
66
+ readonly limiter: RateLimiter;
67
+ }
52
68
  /**
53
69
  * `POST /api/ontology/agent/visitors`, for a browser on one of the declared websites, answers
54
70
  * `{ token, expires_at, refresh_token, chat }`: an agent token like a member's, whose refresh token
@@ -57,6 +73,8 @@ export declare function visitorPreflight(websites: VisitorWebsites): (request: H
57
73
  * user, nobody is signed up, and the chat is `guest:<id>`. On a website `signUp.origins` names, the
58
74
  * visitor is signed up on `web` with the roles `signUp` gives it. Any other origin is refused. A
59
75
  * browser's Origin proves no sender, so the limits on new visitors per network address, and on
60
- * their turns, are what bound it.
76
+ * their turns, are what bound it, and, with `guest.botCheck`, the challenge's token in `bot_check`:
77
+ * without one a new guest is refused `bot_check_required`, with one the provider does not accept
78
+ * `bot_check_failed`.
61
79
  */
62
- export declare function issueVisitorToken(web: AgentWebStore, websites: VisitorWebsites): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
80
+ export declare function issueVisitorToken(web: AgentWebStore, websites: VisitorWebsites, botCheck?: VisitorBotCheck): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
@@ -8,6 +8,7 @@ import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, callerOfAccessToken, publicOr
8
8
  import { clientAddress } from "../rate-limit.js";
9
9
  import { matchesWebsite } from "../../sign-in.js";
10
10
  import { guestChat } from "../../runtime/guests.js";
11
+ import { MAX_BOT_CHECK_TOKEN_LENGTH } from "./bot-check.js";
11
12
  import { AgentLimitsRequest } from "./protocol.js";
12
13
  /**
13
14
  * A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
@@ -91,7 +92,7 @@ function originOf(value, request) {
91
92
  * `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
92
93
  * turns counts against the agent's guest limits.
93
94
  */
94
- export function introspectAgentToken(store, web, oauth, agentTools) {
95
+ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
95
96
  return (request) => Effect.gen(function* () {
96
97
  const requestId = yield* RequestId;
97
98
  const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
@@ -136,6 +137,8 @@ export function introspectAgentToken(store, web, oauth, agentTools) {
136
137
  grant_id: authenticated.grantId,
137
138
  chat: guestChat(guest.id),
138
139
  agent_tools: agentTools(guest),
140
+ // Guests confirm actions in the website's chat only where `guest.confirmations` says so.
141
+ ...(guests?.confirmations === true ? { confirmations: true } : {}),
139
142
  ...limitedAs(limited),
140
143
  });
141
144
  }
@@ -162,11 +165,16 @@ export function introspectAgentToken(store, web, oauth, agentTools) {
162
165
  });
163
166
  }
164
167
  /** The headers that let a website on `origin` read an answer to its visitor's browser. */
165
- function websiteHeaders(origin) {
166
- return { "access-control-allow-origin": origin, vary: "Origin" };
168
+ export function websiteHeaders(origin) {
169
+ // A refusal's Retry-After stays readable, so the website can say when to try again.
170
+ return {
171
+ "access-control-allow-origin": origin,
172
+ "access-control-expose-headers": "Retry-After",
173
+ vary: "Origin",
174
+ };
167
175
  }
168
176
  /** The declared website a browser's request comes from, when it comes from one. */
169
- function websiteOf(request, origins) {
177
+ export function websiteOf(request, origins) {
170
178
  const origin = request.headers.origin;
171
179
  return origin !== undefined && matchesWebsite(origins, origin) ? origin : undefined;
172
180
  }
@@ -191,6 +199,12 @@ export function visitorPreflight(websites) {
191
199
  });
192
200
  });
193
201
  }
202
+ /** Bot checks one network address may have verified a minute, before any reaches the provider. */
203
+ export const BOT_CHECK_LIMIT = { limit: 30, windowMs: 60_000, maxKeys: 10_000 };
204
+ /** The challenge token a visitor's browser sends with its request, when it sends one. */
205
+ const VisitorRequest = Schema.Struct({
206
+ bot_check: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(MAX_BOT_CHECK_TOKEN_LENGTH))),
207
+ });
194
208
  /**
195
209
  * `POST /api/ontology/agent/visitors`, for a browser on one of the declared websites, answers
196
210
  * `{ token, expires_at, refresh_token, chat }`: an agent token like a member's, whose refresh token
@@ -199,9 +213,11 @@ export function visitorPreflight(websites) {
199
213
  * user, nobody is signed up, and the chat is `guest:<id>`. On a website `signUp.origins` names, the
200
214
  * visitor is signed up on `web` with the roles `signUp` gives it. Any other origin is refused. A
201
215
  * browser's Origin proves no sender, so the limits on new visitors per network address, and on
202
- * their turns, are what bound it.
216
+ * their turns, are what bound it, and, with `guest.botCheck`, the challenge's token in `bot_check`:
217
+ * without one a new guest is refused `bot_check_required`, with one the provider does not accept
218
+ * `bot_check_failed`.
203
219
  */
204
- export function issueVisitorToken(web, websites) {
220
+ export function issueVisitorToken(web, websites, botCheck) {
205
221
  return (request) => Effect.gen(function* () {
206
222
  const requestId = yield* RequestId;
207
223
  const guestSite = websiteOf(request, websites.guests);
@@ -225,6 +241,63 @@ export function issueVisitorToken(web, websites) {
225
241
  requestId,
226
242
  }), { status: 403, headers });
227
243
  const client = createHash("sha256").update(clientAddress(request)).digest("hex");
244
+ const refusal = (error, status, extra = {}) => HttpServerResponse.jsonUnsafe(errorBodyForWire({ error, detail: error, requestId }), {
245
+ status,
246
+ headers: { ...headers, ...extra },
247
+ });
248
+ if (guestSite !== undefined && botCheck !== undefined) {
249
+ const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
250
+ try {
251
+ return text.trim() === "" ? {} : JSON.parse(text);
252
+ }
253
+ catch {
254
+ return undefined;
255
+ }
256
+ });
257
+ const decoded = Schema.decodeUnknownResult(VisitorRequest)(body);
258
+ const token = Result.isSuccess(decoded) ? decoded.success.bot_check : undefined;
259
+ if (token === undefined) {
260
+ return refusal("bot_check_required", 403);
261
+ }
262
+ const retryAfter = botCheck.limiter.take(client);
263
+ if (retryAfter !== undefined) {
264
+ return refusal("rate_limited", 429, { "retry-after": String(retryAfter) });
265
+ }
266
+ const verified = yield* Effect.promise(() => botCheck.verify({
267
+ check: botCheck.check,
268
+ token,
269
+ // Only an address the provider can compare; a proxy that names none passes nothing.
270
+ remoteIp: /^[0-9a-f:.]{2,45}$/i.test(clientAddress(request))
271
+ ? clientAddress(request)
272
+ : undefined,
273
+ identityToken: botCheck.identityToken(request),
274
+ requestId,
275
+ }));
276
+ if (verified.outcome === "invalid") {
277
+ return refusal("bot_check_failed", 403);
278
+ }
279
+ // A challenge solved on another page, such as a site that copied the website's site key,
280
+ // proves nothing about this website's visitor.
281
+ if (verified.outcome === "valid" &&
282
+ verified.hostname !== undefined &&
283
+ verified.hostname.toLowerCase() !== new URL(guestSite).hostname) {
284
+ return refusal("bot_check_failed", 403);
285
+ }
286
+ if (verified.outcome !== "valid" || verified.hostname === undefined) {
287
+ yield* Effect.logError("ontology.agent.bot_check_unavailable", verified.outcome === "unavailable"
288
+ ? verified.cause
289
+ : verified.outcome === "valid"
290
+ ? "The challenge check answered without the page's hostname."
291
+ : verified.outcome).pipe(Effect.annotateLogs({
292
+ requestId,
293
+ outcome: verified.outcome,
294
+ ...(verified.outcome === "unavailable" && verified.status !== undefined
295
+ ? { status: verified.status }
296
+ : {}),
297
+ }));
298
+ return refusal("bot_check_unavailable", 503);
299
+ }
300
+ }
228
301
  if (guestSite !== undefined) {
229
302
  const issued = web.guest === undefined
230
303
  ? { status: "refused" }
@@ -5,7 +5,7 @@ import { type JWTVerifyGetKey } from "jose";
5
5
  import { type DeploymentObservation } from "../deployment.js";
6
6
  import { type BrowserRevision } from "./federation-status.js";
7
7
  import type { WorkloadExecution } from "../runtime/workload.js";
8
- import type { Principal } from "../runtime.js";
8
+ import type { ChatProvenance, Principal } from "../runtime.js";
9
9
  import type { NeonAuthEnvironment } from "./config.js";
10
10
  import { RequestId } from "./errors.js";
11
11
  import { CurrentCaller, type VerifiedCaller } from "./caller-context.js";
@@ -205,6 +205,14 @@ export interface CredentialOptions {
205
205
  */
206
206
  readonly guests?: true;
207
207
  }
208
+ /**
209
+ * The chat a verified runtime caller names, kept as the principal's when it can be the chat it acts
210
+ * in: on the web, the member's or guest's own chat, which their agent token names; on a messenger,
211
+ * a chat on a channel of the kind the member wrote from. The chat names its channel by name, as
212
+ * the archive does; `kindOf` answers the channel's kind, as the ontology's `chat` declares it.
213
+ * Anything else is left out, never refused: it only attributes.
214
+ */
215
+ export declare function actingChat(principal: Principal, provider: string | undefined, chat: ChatProvenance | undefined, kindOf?: (channel: string) => string | undefined): ChatProvenance | undefined;
208
216
  /** Resolves a bearer credential to its current principal and verified credential provenance. */
209
217
  export declare function authenticate(credential: Redacted.Redacted<string>, verifyToken: TokenVerifier, options?: CredentialOptions): Effect.Effect<Authenticated, never, OntologyBackend>;
210
218
  /** A browser's request, which may authenticate with the app's Neon Auth session cookie. */
@@ -450,12 +450,34 @@ export function sessionMayAuthenticate(request) {
450
450
  const origin = request.headers.origin;
451
451
  return origin !== undefined && origin === requestOrigin(request);
452
452
  }
453
+ /**
454
+ * The chat a verified runtime caller names, kept as the principal's when it can be the chat it acts
455
+ * in: on the web, the member's or guest's own chat, which their agent token names; on a messenger,
456
+ * a chat on a channel of the kind the member wrote from. The chat names its channel by name, as
457
+ * the archive does; `kindOf` answers the channel's kind, as the ontology's `chat` declares it.
458
+ * Anything else is left out, never refused: it only attributes.
459
+ */
460
+ export function actingChat(principal, provider, chat, kindOf = (channel) => channel) {
461
+ if (chat === undefined) {
462
+ return undefined;
463
+ }
464
+ if (chat.provider === WEB_PROVIDER || provider === WEB_PROVIDER) {
465
+ const own = `${principal.kind === "guest" ? "guest" : "member"}:${principal.id}`;
466
+ return chat.provider === WEB_PROVIDER && provider === WEB_PROVIDER && chat.chatId === own
467
+ ? chat
468
+ : undefined;
469
+ }
470
+ // The member's identity is of a kind; a channel of another name, such as `sales_whatsapp`,
471
+ // counts as the kind the ontology's chat declares for it.
472
+ return provider === undefined || provider === kindOf(chat.provider) ? chat : undefined;
473
+ }
453
474
  /**
454
475
  * The member a verified runtime caller acts for: the member `X-SegmentStream-Act-As` names, with the
455
476
  * roles they hold now, while they are active and paired with the agent. Without the header, the
456
- * runtime may call only the agent's own routes, which authenticate it themselves.
477
+ * runtime may call only the agent's own routes, which authenticate it themselves. The chat it names
478
+ * becomes the principal's, as {@link actingChat} admits it.
457
479
  */
458
- function actingMember(actAs, provider, grant, guests = false) {
480
+ function actingMember(actAs, provider, grant, guests = false, chat) {
459
481
  return Effect.gen(function* () {
460
482
  const backend = yield* OntologyBackend;
461
483
  if (actAs === undefined) {
@@ -475,11 +497,15 @@ function actingMember(actAs, provider, grant, guests = false) {
475
497
  : provider === WEB_PROVIDER
476
498
  ? yield* webMember(backend.agents, actAs, grant)
477
499
  : yield* backend.agents.actingMember(actAs, provider);
500
+ const acting = member === undefined
501
+ ? undefined
502
+ : actingChat(member, provider, chat, backend.agents?.channelKind);
503
+ const withChat = acting === undefined ? {} : { chat: acting };
478
504
  if (member?.kind === "guest") {
479
505
  return guests
480
506
  ? {
481
507
  status: "authenticated",
482
- principal: member,
508
+ principal: { ...member, ...withChat },
483
509
  caller: { kind: "runtime", subjectId: member.id },
484
510
  }
485
511
  : { status: "forbidden", detail: "This route does not admit guests." };
@@ -491,7 +517,7 @@ function actingMember(actAs, provider, grant, guests = false) {
491
517
  }
492
518
  : {
493
519
  status: "authenticated",
494
- principal: { ...member, authenticatedVia: provider ?? "agent" },
520
+ principal: { ...member, authenticatedVia: provider ?? "agent", ...withChat },
495
521
  caller: { kind: "runtime", subjectId: member.id },
496
522
  };
497
523
  });
@@ -662,7 +688,7 @@ export function authenticate(credential, verifyToken, options = {}) {
662
688
  switch (runtime.status) {
663
689
  case "valid":
664
690
  return agentTask === undefined
665
- ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true)
691
+ ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true, options.runtime.chat)
666
692
  : yield* agentTaskPrincipal(agentTask, actAs, options.agentTasks);
667
693
  case "invalid":
668
694
  yield* logRuntimeRejection(runtime.reason);
@@ -7,7 +7,7 @@ import { isAllowed } from "../../permissions.js";
7
7
  import { describeChatError } from "./diagnostics.js";
8
8
  import { deliveryRequester } from "./attribution.js";
9
9
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
10
- import { chatConnection, chatProvider, listedChatProviders } from "./providers/index.js";
10
+ import { channelProvider, chatConnection, chatKind, listedChatProviders, } from "./providers/index.js";
11
11
  import { chatResolver } from "./resolve.js";
12
12
  import { reviewSender } from "./review-delivery.js";
13
13
  /** The channels a runtime source can name, which a verified pairing's provider is one of. */
@@ -18,7 +18,8 @@ const CHANNEL_PROVIDERS = new Set(["telegram", "slack", "whatsapp"]);
18
18
  * private source matches a private destination on the same provider by its `peer`.
19
19
  */
20
20
  export function sameChat(source, target) {
21
- if (source.provider !== target.provider) {
21
+ // The target's provider is the channel it is on, by name; the source's is its kind.
22
+ if ((source.channel ?? source.provider) !== target.provider) {
22
23
  return false;
23
24
  }
24
25
  if (source.chat_id === target.external_id) {
@@ -58,9 +59,12 @@ export function makeChatDelivery(ontology, connections, archive, previews = {})
58
59
  message: "The requester must still be paired and active.",
59
60
  });
60
61
  }
61
- const target = yield* chatResolver(context.backend, context.principal, providers).resolve(input.chat);
62
- // A chat is a destination only on a provider the ontology declares a connection for.
63
- const provider = chatProvider(target.provider);
62
+ const target = yield* chatResolver(context.backend, context.principal, providers, {
63
+ kindOf: (channel) => chatKind(ontology.manifest.chat, channel),
64
+ }).resolve(input.chat);
65
+ // A chat is a destination only on a channel the ontology declares a connection for; the
66
+ // channel's kind sends it.
67
+ const provider = channelProvider(ontology.manifest.chat, target.provider);
64
68
  const connection = chatConnection(ontology.manifest.chat, target.provider);
65
69
  const replyTo = input.replyTo ?? null;
66
70
  if (provider === undefined || !connection) {
@@ -8,6 +8,7 @@ declare const RuntimeEnvelope: Schema.Struct<{
8
8
  readonly operation_id: Schema.optionalKey<Schema.String>;
9
9
  readonly source: Schema.optionalKey<Schema.Union<readonly [Schema.Struct<{
10
10
  readonly provider: Schema.Literal<"telegram">;
11
+ readonly channel: Schema.optionalKey<Schema.String>;
11
12
  readonly chat_id: Schema.String;
12
13
  readonly thread_id: Schema.String;
13
14
  readonly message_id: Schema.optionalKey<Schema.String>;
@@ -29,6 +30,7 @@ declare const RuntimeEnvelope: Schema.Struct<{
29
30
  }>>>;
30
31
  }>, Schema.Struct<{
31
32
  readonly provider: Schema.Literals<readonly ["slack", "whatsapp"]>;
33
+ readonly channel: Schema.optionalKey<Schema.String>;
32
34
  readonly chat_id: Schema.String;
33
35
  readonly thread_id: Schema.String;
34
36
  readonly kind: Schema.Literals<readonly ["private", "group"]>;
@@ -51,6 +53,7 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
51
53
  readonly chat_id: string;
52
54
  readonly thread_id: string;
53
55
  readonly message_id?: string | undefined;
56
+ readonly channel?: string | undefined;
54
57
  readonly attachments?: readonly {
55
58
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
56
59
  readonly file_id: string;
@@ -73,6 +76,7 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
73
76
  readonly chat_id: string;
74
77
  readonly thread_id: string;
75
78
  readonly message_id?: string | undefined;
79
+ readonly channel?: string | undefined;
76
80
  readonly sender?: string | undefined;
77
81
  readonly peer?: string | undefined;
78
82
  } | undefined;
@@ -103,6 +107,7 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
103
107
  readonly chat_id: string;
104
108
  readonly thread_id: string;
105
109
  readonly message_id?: string | undefined;
110
+ readonly channel?: string | undefined;
106
111
  readonly attachments?: readonly {
107
112
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
108
113
  readonly file_id: string;
@@ -125,6 +130,7 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
125
130
  readonly chat_id: string;
126
131
  readonly thread_id: string;
127
132
  readonly message_id?: string | undefined;
133
+ readonly channel?: string | undefined;
128
134
  readonly sender?: string | undefined;
129
135
  readonly peer?: string | undefined;
130
136
  } | undefined;
@@ -12,15 +12,25 @@ export declare const CHAT_PROVIDERS: {
12
12
  readonly email: ChatProvider;
13
13
  };
14
14
  export type ChatProviderName = keyof typeof CHAT_PROVIDERS;
15
- /** The provider a destination's chat is on, when the platform posts to it. */
16
- export declare function chatProvider(name: string): ChatProvider | undefined;
17
- /** The connection the ontology declares for posting to a provider's chats, if it declares one. */
18
- export declare function chatConnection(chat: OntologyManifest["chat"], provider: string): string | undefined;
19
- /** The providers the ontology declares a posting connection for: the destinations it posts to. */
20
- export declare function declaredChatProviders(chat: OntologyManifest["chat"]): ReadonlyArray<ChatProviderName>;
15
+ /** The provider of a kind of channel, when the platform posts to it. */
16
+ export declare function chatProvider(kind: string): ChatProvider | undefined;
21
17
  /**
22
- * The providers whose chats the chat tools list, read and resolve: Telegram's, whose chats the
23
- * tools always listed, and each declared one. Posting still requires the target's provider to
24
- * be declared.
18
+ * The kind of the agent's channel `name` the ontology's `chat` declares: the name itself for the
19
+ * channel named after its kind, which a chat on it before channels had names also is.
20
+ */
21
+ export declare function chatKind(chat: OntologyManifest["chat"], name: string): string | undefined;
22
+ /** The provider of the agent's channel `name`, by its kind, when the platform posts to it. */
23
+ export declare function channelProvider(chat: OntologyManifest["chat"], name: string): ChatProvider | undefined;
24
+ /** The connection the ontology declares for the agent's channel `name`, if it declares one. */
25
+ export declare function chatConnection(chat: OntologyManifest["chat"], name: string): string | undefined;
26
+ /**
27
+ * The channels the ontology declares a posting connection for, by name: the destinations it posts
28
+ * to. The channel named after each kind comes first, then the others.
29
+ */
30
+ export declare function declaredChatProviders(chat: OntologyManifest["chat"]): ReadonlyArray<string>;
31
+ /**
32
+ * The channels whose chats the chat tools list, read and resolve, by name: Telegram's, whose
33
+ * chats the tools always listed, and each declared one. Posting still requires the target's
34
+ * channel to be declared.
25
35
  */
26
36
  export declare function listedChatProviders(chat: OntologyManifest["chat"]): ReadonlyArray<string>;