@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
@@ -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
@@ -13,7 +13,9 @@ import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
13
13
  import { OntologyBackend } from "../runtime-contract.js";
14
14
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
15
15
  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";
16
+ import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
17
+ import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
18
+ import { identityToken } from "../operations.js";
17
19
  /** The agent's endpoints, under the ontology service's path. */
18
20
  export const AGENT_PATH = `${BASE_PATH}/agent`;
19
21
  const PAIRINGS_PATH = `${AGENT_PATH}/pairings`;
@@ -25,6 +27,12 @@ export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
25
27
  export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
26
28
  /** Where a browser on a declared website signs its visitor up on `web`. */
27
29
  export const AGENT_VISITORS_PATH = `${AGENT_PATH}/visitors`;
30
+ /** A website's guests' own routes: becoming a user, and the runtime's report of their spend. */
31
+ export const AGENT_GUESTS_PATH = `${AGENT_PATH}/guests`;
32
+ export const GUEST_EMAIL_CODE_PATH = `${AGENT_GUESTS_PATH}/email-code`;
33
+ export const GUEST_SIGN_UP_PATH = `${AGENT_GUESTS_PATH}/sign-up`;
34
+ export const GUEST_USAGE_PATH = `${AGENT_GUESTS_PATH}/usage`;
35
+ export { GUEST_LINK_PATH };
28
36
  /**
29
37
  * Pairings one client address may start per minute; each one is a row in the database. The agent's
30
38
  * functions share a few egress addresses, so the limit leaves room for a busy channel.
@@ -437,11 +445,42 @@ export function agentLayer(options) {
437
445
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
438
446
  if (store.web !== undefined && backend.oauth !== undefined) {
439
447
  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)));
448
+ yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools, options.guest)));
441
449
  const websites = options.visitorWebsites ?? { guests: [], signUp: [] };
450
+ const botCheck = options.guest?.botCheck === undefined || options.botCheckVerifier === undefined
451
+ ? undefined
452
+ : {
453
+ check: options.guest.botCheck,
454
+ verify: options.botCheckVerifier,
455
+ identityToken,
456
+ limiter: fixedWindowLimiter(BOT_CHECK_LIMIT),
457
+ };
458
+ // A declared bot check that cannot be verified admits no new guest.
459
+ if (options.guest?.botCheck !== undefined && botCheck === undefined) {
460
+ return yield* Effect.die(new Error("guest.botCheck needs a bot check verifier."));
461
+ }
442
462
  if (websites.guests.length > 0 || websites.signUp.length > 0) {
443
463
  yield* router.add("OPTIONS", AGENT_VISITORS_PATH, visitorPreflight(websites));
444
- yield* router.add("POST", AGENT_VISITORS_PATH, issueVisitorToken(store.web, websites));
464
+ yield* router.add("POST", AGENT_VISITORS_PATH, issueVisitorToken(store.web, websites, botCheck));
465
+ }
466
+ if (websites.guests.length > 0) {
467
+ const guests = guestSignUpRoutes({
468
+ emailSignUp: options.emailSignUp === true,
469
+ web: store.web,
470
+ oauth: backend.oauth,
471
+ origins: websites.guests,
472
+ emailCodes: options.emailCodes,
473
+ exchangeSession: options.exchangeSession,
474
+ verifyToken: options.verifyToken,
475
+ });
476
+ const preflight = guestRoutesPreflight(websites.guests);
477
+ yield* router.add("OPTIONS", GUEST_EMAIL_CODE_PATH, preflight);
478
+ yield* router.add("POST", GUEST_EMAIL_CODE_PATH, guests.emailCode);
479
+ yield* router.add("OPTIONS", GUEST_SIGN_UP_PATH, preflight);
480
+ yield* router.add("POST", GUEST_SIGN_UP_PATH, guests.signUp);
481
+ // Where an emailed link lands, signed in on the app's origin: a top-level navigation.
482
+ yield* router.add("GET", GUEST_LINK_PATH, guests.link);
483
+ yield* router.add("POST", GUEST_USAGE_PATH, asRuntime(recordGuestUsage(store.web)));
445
484
  }
446
485
  }
447
486
  }));
@@ -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,13 @@ 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 of the provider the member wrote from. Anything else is left out, never refused: it only
212
+ * attributes.
213
+ */
214
+ export declare function actingChat(principal: Principal, provider: string | undefined, chat: ChatProvenance | undefined): ChatProvenance | undefined;
208
215
  /** Resolves a bearer credential to its current principal and verified credential provenance. */
209
216
  export declare function authenticate(credential: Redacted.Redacted<string>, verifyToken: TokenVerifier, options?: CredentialOptions): Effect.Effect<Authenticated, never, OntologyBackend>;
210
217
  /** A browser's request, which may authenticate with the app's Neon Auth session cookie. */
@@ -450,12 +450,31 @@ 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 of the provider the member wrote from. Anything else is left out, never refused: it only
457
+ * attributes.
458
+ */
459
+ export function actingChat(principal, provider, chat) {
460
+ if (chat === undefined) {
461
+ return undefined;
462
+ }
463
+ if (chat.provider === WEB_PROVIDER || provider === WEB_PROVIDER) {
464
+ const own = `${principal.kind === "guest" ? "guest" : "member"}:${principal.id}`;
465
+ return chat.provider === WEB_PROVIDER && provider === WEB_PROVIDER && chat.chatId === own
466
+ ? chat
467
+ : undefined;
468
+ }
469
+ return provider === undefined || provider === chat.provider ? chat : undefined;
470
+ }
453
471
  /**
454
472
  * The member a verified runtime caller acts for: the member `X-SegmentStream-Act-As` names, with the
455
473
  * 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.
474
+ * runtime may call only the agent's own routes, which authenticate it themselves. The chat it names
475
+ * becomes the principal's, as {@link actingChat} admits it.
457
476
  */
458
- function actingMember(actAs, provider, grant, guests = false) {
477
+ function actingMember(actAs, provider, grant, guests = false, chat) {
459
478
  return Effect.gen(function* () {
460
479
  const backend = yield* OntologyBackend;
461
480
  if (actAs === undefined) {
@@ -475,11 +494,13 @@ function actingMember(actAs, provider, grant, guests = false) {
475
494
  : provider === WEB_PROVIDER
476
495
  ? yield* webMember(backend.agents, actAs, grant)
477
496
  : yield* backend.agents.actingMember(actAs, provider);
497
+ const acting = member === undefined ? undefined : actingChat(member, provider, chat);
498
+ const withChat = acting === undefined ? {} : { chat: acting };
478
499
  if (member?.kind === "guest") {
479
500
  return guests
480
501
  ? {
481
502
  status: "authenticated",
482
- principal: member,
503
+ principal: { ...member, ...withChat },
483
504
  caller: { kind: "runtime", subjectId: member.id },
484
505
  }
485
506
  : { status: "forbidden", detail: "This route does not admit guests." };
@@ -491,7 +512,7 @@ function actingMember(actAs, provider, grant, guests = false) {
491
512
  }
492
513
  : {
493
514
  status: "authenticated",
494
- principal: { ...member, authenticatedVia: provider ?? "agent" },
515
+ principal: { ...member, authenticatedVia: provider ?? "agent", ...withChat },
495
516
  caller: { kind: "runtime", subjectId: member.id },
496
517
  };
497
518
  });
@@ -662,7 +683,7 @@ export function authenticate(credential, verifyToken, options = {}) {
662
683
  switch (runtime.status) {
663
684
  case "valid":
664
685
  return agentTask === undefined
665
- ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true)
686
+ ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true, options.runtime.chat)
666
687
  : yield* agentTaskPrincipal(agentTask, actAs, options.agentTasks);
667
688
  case "invalid":
668
689
  yield* logRuntimeRejection(runtime.reason);
@@ -194,6 +194,16 @@ export interface OntologyServiceConfig extends OntologyEnvironment {
194
194
  readonly webhookVerifier?: import("./webhooks.js").WebhookVerifier;
195
195
  /** How registration tokens are compared against backend-held workspace secrets. */
196
196
  readonly webhookTokenVerifier?: import("./webhooks.js").WebhookTokenVerifier;
197
+ /**
198
+ * How a new guest's challenge token is checked when `guest.botCheck` asks for one:
199
+ * SegmentStream's backend, which holds the workspace secret, by default. Tests replace it.
200
+ */
201
+ readonly botCheckVerifier?: import("./agent/bot-check.js").BotCheckVerifier;
202
+ /**
203
+ * How a guest proves an email address: the app's email sign-in, in production, by default. Tests
204
+ * replace it.
205
+ */
206
+ readonly emailCodes?: import("./agent/guest-sign-up.js").EmailCodes;
197
207
  /** How `agentTask` calls the app's agent at `agentOrigin`: `fetch` by default. Tests replace it. */
198
208
  readonly agentTaskTransport?: import("./agent/task-start.js").AgentTransport;
199
209
  /**
@@ -118,6 +118,11 @@ export declare function makeOperations(backend: Backend, plan: ApiPlan, hooks: R
118
118
  readonly principalId: string | null;
119
119
  readonly recordId: string;
120
120
  readonly actionId: string;
121
+ readonly chat?: {
122
+ readonly chatId: string;
123
+ readonly provider: string;
124
+ readonly sessionId?: string | undefined;
125
+ } | undefined;
121
126
  readonly execution?: {
122
127
  readonly issuer: string;
123
128
  readonly audience: string;
@@ -284,6 +284,73 @@ export interface AgentWebStore {
284
284
  * {@link countTurn}. The limit the turn exceeds, or `undefined` when it may run.
285
285
  */
286
286
  readonly countGuestTurn?: (guestId: string, limits?: ResolveIdentityInput["limits"]) => Effect.Effect<WebTurnLimit | undefined>;
287
+ /**
288
+ * Adds the model cost of a guest's turn, in US dollars, to that day's spend of the guest and of
289
+ * every guest together, which {@link countGuestTurn} holds against the agent's
290
+ * `limits.guest.usdPerDay` and `workspaceUsdPerDay`. `key` names the report: a report repeated
291
+ * with the same key adds nothing.
292
+ */
293
+ readonly recordGuestUsage?: (input: {
294
+ readonly guestId: string;
295
+ readonly costUsd: number;
296
+ readonly key: string;
297
+ }) => Effect.Effect<void>;
298
+ /**
299
+ * Counts one attempt of a guest's against a fixed hourly window, such as asking for an email
300
+ * code: the seconds until the next may run once `limit` is exceeded, else `undefined`.
301
+ */
302
+ readonly countGuestAttempt?: (input: {
303
+ readonly scope: "guestEmailCodesPerHour" | "guestSignUpAttemptsPerHour";
304
+ readonly subject: string;
305
+ readonly limit: number;
306
+ }) => Effect.Effect<number | undefined>;
307
+ /**
308
+ * Makes a guest the user an email address they proved is theirs, by the app's own email sign-in:
309
+ * the user `signUp` created with that address, or a new one `signUp` creates on `email`. The
310
+ * guest's grant becomes the user's, with new access and refresh tokens in place of the guest's.
311
+ * An address another kind of user holds, such as an invited member's, is refused.
312
+ */
313
+ readonly upgradeGuest?: (input: {
314
+ readonly guestId: string;
315
+ readonly identity: SignInIdentity;
316
+ readonly expiresAt: Date;
317
+ }) => Effect.Effect<GuestUpgrade>;
318
+ /**
319
+ * How the app's email sign-in reaches an address: `code` for one a user holds who signed in with
320
+ * Neon Auth before, whose account receives codes, else `link`.
321
+ */
322
+ readonly guestEmailMethod?: (email: string) => Effect.Effect<"code" | "link">;
323
+ /**
324
+ * Records a guest's pending sign-up by an emailed link: the address the link must prove, where it
325
+ * returns to, and the hash of the link's nonce, until `expiresAt`.
326
+ */
327
+ readonly requestGuestLink?: (input: {
328
+ readonly guestId: string;
329
+ readonly email: string;
330
+ readonly returnTo: string | undefined;
331
+ readonly nonceHash: string;
332
+ readonly expiresAt: Date;
333
+ }) => Effect.Effect<void>;
334
+ /**
335
+ * Opens a guest's link once, for the identity the link signed in: it must have proven the very
336
+ * address. Admits that user as {@link upgradeGuest} does, without moving the guest's grant, and
337
+ * records the hash of the single-use handoff that moves it.
338
+ */
339
+ readonly openGuestLink?: (input: {
340
+ readonly nonceHash: string;
341
+ readonly identity: SignInIdentity;
342
+ readonly handoffHash: string;
343
+ readonly handoffExpiresAt: Date;
344
+ }) => Effect.Effect<GuestLinkOpening>;
345
+ /**
346
+ * Moves a guest's grant to the user their link admitted, with new tokens, for the handoff alone
347
+ * and only for the guest it was minted for: another guest's request is refused, and leaves it.
348
+ */
349
+ readonly takeGuestHandoff?: (input: {
350
+ readonly handoffHash: string;
351
+ readonly guestId: string;
352
+ readonly expiresAt: Date;
353
+ }) => Effect.Effect<GuestHandoff>;
287
354
  /**
288
355
  * A new guest of a declared website: a grant to the agent at `resource` that names no user, with
289
356
  * its access and refresh tokens. No user or identity is created. `client` keys how many guests one
@@ -331,6 +398,58 @@ export type GuestIssue = {
331
398
  } | {
332
399
  readonly status: "refused";
333
400
  };
401
+ /** A guest who proved an email address, as {@link AgentWebStore.upgradeGuest} answers it. */
402
+ export type GuestUpgrade = {
403
+ readonly status: "upgraded";
404
+ /** The user the guest became. */
405
+ readonly userId: string;
406
+ /** Whether `signUp` created the user now, rather than finding the one it created before. */
407
+ readonly created: boolean;
408
+ readonly token: string;
409
+ readonly refreshToken: string;
410
+ readonly expiresAt: Date;
411
+ }
412
+ /** `signUp` does not list `email`, so a proven address makes nobody a user. */
413
+ | {
414
+ readonly status: "sign_up_closed";
415
+ }
416
+ /** The address is a user's that sign-up did not create, such as an invited member's. */
417
+ | {
418
+ readonly status: "member_address";
419
+ }
420
+ /** The guest is gone, or the user may not sign in. */
421
+ | {
422
+ readonly status: "refused";
423
+ };
424
+ /** A guest's emailed link, opened, as {@link AgentWebStore.openGuestLink} answers it. */
425
+ export type GuestLinkOpening = {
426
+ /** The user is admitted and the handoff recorded. */
427
+ readonly status: "handed_off";
428
+ readonly returnTo: string | undefined;
429
+ readonly created: boolean;
430
+ }
431
+ /** No pending link has the nonce, it was opened or expired, or it proves another address. */
432
+ | {
433
+ readonly status: "link_invalid";
434
+ readonly returnTo?: string | undefined;
435
+ } | {
436
+ readonly status: "sign_up_closed" | "member_address" | "refused";
437
+ readonly returnTo: string | undefined;
438
+ };
439
+ /** A handoff taken, as {@link AgentWebStore.takeGuestHandoff} answers it. */
440
+ export type GuestHandoff = Extract<GuestUpgrade, {
441
+ readonly status: "upgraded";
442
+ }>
443
+ /** No handoff has the secret, or it was taken or expired. */
444
+ | {
445
+ readonly status: "handoff_invalid";
446
+ }
447
+ /** The handoff is another guest's: a link opened in another browser hands nothing to it. */
448
+ | {
449
+ readonly status: "handoff_other_browser";
450
+ } | {
451
+ readonly status: "refused";
452
+ };
334
453
  /** The limit a member's turn on the web exceeds, and when the next one may run. */
335
454
  export interface WebTurnLimit {
336
455
  readonly scope: AgentLimitScope;
@@ -353,9 +472,13 @@ export interface AgentLimits {
353
472
  readonly guest: {
354
473
  readonly turnsPerDay: number;
355
474
  readonly workspaceTurnsPerDay: number;
475
+ /** The model cost each guest's turns may reach a day, in US dollars; no cap when absent. */
476
+ readonly usdPerDay?: number;
477
+ /** The model cost every guest's turns together may reach a day; no cap when absent. */
478
+ readonly workspaceUsdPerDay?: number;
356
479
  };
357
480
  }
358
- export type AgentLimitScope = "turnsPerMinute" | "turnsPerDay" | "newUsersPerHour" | "workspaceTurnsPerDay" | "guestTurnsPerDay" | "guestWorkspaceTurnsPerDay" | "newGuestsPerHour";
481
+ export type AgentLimitScope = "turnsPerMinute" | "turnsPerDay" | "newUsersPerHour" | "workspaceTurnsPerDay" | "guestTurnsPerDay" | "guestWorkspaceTurnsPerDay" | "guestUsdPerDay" | "guestWorkspaceUsdPerDay" | "newGuestsPerHour" | "guestEmailCodesPerHour" | "guestSignUpAttemptsPerHour";
359
482
  export interface ResolveIdentityInput {
360
483
  readonly provider: string;
361
484
  readonly externalId: string;
@@ -1,6 +1,7 @@
1
1
  import { Effect, Redacted } from "effect";
2
2
  import type { HttpServerRequest } from "effect/unstable/http";
3
3
  import { type JWTVerifyGetKey } from "jose";
4
+ import type { ChatProvenance } from "../runtime.js";
4
5
  /**
5
6
  * The header in which a runtime caller names the member it acts for: the member's user id. The
6
7
  * service honours it only with a verified runtime token, so nobody else can claim a member with it.
@@ -12,6 +13,23 @@ export declare const ACT_AS_HEADER = "x-segmentstream-act-as";
12
13
  * workflow user, on `/mcp` and the task routes only; every other route refuses it.
13
14
  */
14
15
  export declare const AGENT_TASK_HEADER = "x-segmentstream-agent-task";
16
+ /**
17
+ * The chat a runtime request comes from, `<provider>:<chat id>` as the chat archive names it, and
18
+ * the agent's session there. The app's agent names them on its attachment routes, and on every
19
+ * request it acts in a chat with, so that history keeps the chat an action came from.
20
+ */
21
+ export declare const CHAT_HEADER = "x-segmentstream-agent-chat";
22
+ export declare const SESSION_HEADER = "x-segmentstream-agent-session";
23
+ /** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
24
+ export declare const EARLIER_CHAT_HEADER = "x-segmentstream-agent-conversation";
25
+ /**
26
+ * `provider:chat id`. An email chat is a Gmail thread and the person's address
27
+ * (`email:<thread>:<address>`), so an id may hold an address's `@`, `.` and `+`.
28
+ */
29
+ export declare const CHAT: RegExp;
30
+ export declare const SESSION: RegExp;
31
+ /** The chat and session a request names, or `undefined` without a well-formed chat. */
32
+ export declare function requestChat(request: HttpServerRequest.HttpServerRequest): ChatProvenance | undefined;
15
33
  /**
16
34
  * Whom the service trusts as its runtime caller: Vercel OIDC tokens of the functions of this
17
35
  * deployment's own project. The app's agent is a service of the same Vercel project as the ontology
@@ -74,6 +92,11 @@ export interface RuntimeCredential {
74
92
  readonly agentTask?: Redacted.Redacted<string>;
75
93
  /** The grant in `X-SegmentStream-Agent-Grant`; `undefined` without the header. */
76
94
  readonly grant?: string;
95
+ /**
96
+ * The chat in `X-SegmentStream-Agent-Chat` and the session in `X-SegmentStream-Agent-Session`;
97
+ * trusted only once the runtime token is verified, and only as the chat the member acts in.
98
+ */
99
+ readonly chat?: ChatProvenance;
77
100
  }
78
101
  /** The task secret a request presents; `undefined` without the header. */
79
102
  export declare function agentTaskSecret(request: HttpServerRequest.HttpServerRequest): Redacted.Redacted<string> | undefined;