@segmentstream/ontology 0.106.3 → 0.108.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 (59) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +45 -11
  3. package/dist/analyze.d.ts +7 -1
  4. package/dist/analyze.js +271 -16
  5. package/dist/authoring.js +6 -0
  6. package/dist/diagnostics.d.ts +3 -3
  7. package/dist/diagnostics.js +1 -0
  8. package/dist/emails.d.ts +36 -5
  9. package/dist/emails.js +139 -2
  10. package/dist/index.d.ts +7 -7
  11. package/dist/index.js +5 -3
  12. package/dist/manifest.d.ts +262 -1
  13. package/dist/manifest.js +73 -4
  14. package/dist/migrate/apply.js +8 -1
  15. package/dist/migrate/model.d.ts +154 -0
  16. package/dist/migrate/storage.d.ts +2 -0
  17. package/dist/migrate/storage.js +8 -0
  18. package/dist/names.d.ts +5 -0
  19. package/dist/names.js +5 -0
  20. package/dist/ontology.d.ts +4 -1
  21. package/dist/permissions.d.ts +30 -2
  22. package/dist/permissions.js +51 -6
  23. package/dist/runtime/agent-counters.d.ts +5 -1
  24. package/dist/runtime/agent-counters.js +21 -6
  25. package/dist/runtime/agent-web.d.ts +9 -6
  26. package/dist/runtime/agent-web.js +101 -5
  27. package/dist/runtime/generated-actions.js +2 -3
  28. package/dist/runtime/guests.d.ts +32 -0
  29. package/dist/runtime/guests.js +64 -0
  30. package/dist/runtime/new-user-hook.js +2 -1
  31. package/dist/runtime/oauth.js +7 -1
  32. package/dist/runtime/pipeline.js +3 -2
  33. package/dist/runtime/principals.js +6 -4
  34. package/dist/runtime/sql-runtime.js +2 -1
  35. package/dist/runtime.d.ts +10 -2
  36. package/dist/service/agent/authentication.d.ts +6 -4
  37. package/dist/service/agent/authentication.js +20 -5
  38. package/dist/service/agent/protocol.d.ts +28 -2
  39. package/dist/service/agent/protocol.js +23 -10
  40. package/dist/service/agent/server.d.ts +9 -2
  41. package/dist/service/agent/server.js +12 -12
  42. package/dist/service/agent/tasks.d.ts +3 -0
  43. package/dist/service/agent/tasks.js +5 -3
  44. package/dist/service/agent/web-tokens.d.ts +28 -13
  45. package/dist/service/agent/web-tokens.js +91 -38
  46. package/dist/service/authentication.d.ts +6 -0
  47. package/dist/service/authentication.js +11 -2
  48. package/dist/service/chat/review-delivery.js +4 -0
  49. package/dist/service/mcp/server.js +3 -3
  50. package/dist/service/mcp/tools.d.ts +4 -2
  51. package/dist/service/mcp/tools.js +14 -2
  52. package/dist/service/oauth/protocol.js +8 -2
  53. package/dist/service/oauth/server.js +5 -1
  54. package/dist/service/runtime-contract.d.ts +58 -6
  55. package/dist/service/schemas.d.ts +40 -0
  56. package/dist/service/service.js +15 -4
  57. package/dist/sign-in.d.ts +66 -9
  58. package/dist/sign-in.js +87 -9
  59. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { Effect } from "effect";
3
- import { CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, USER_TABLE, } from "../migrate/storage.js";
3
+ import { CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
4
4
  import { AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
5
5
  import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, FULL_SCOPE, REFRESH_TOKEN_PREFIX, REFRESH_TOKEN_TTL_MS, newSecret, secretHash, } from "../service/oauth/protocol.js";
6
6
  import { completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, } from "./agent-counters.js";
@@ -8,17 +8,25 @@ import { channelUsersAvailable } from "./member-tables.js";
8
8
  import { runNewUserHook } from "./new-user-hook.js";
9
9
  import { CHANNEL_IDENTITIES_FROM, LIVE_CHANNEL_IDENTITY } from "./user-identity-sql.js";
10
10
  import { WEB_PROVIDER } from "../service/runtime-identity.js";
11
+ import { guestPrincipal } from "./guests.js";
11
12
  import { sqlOAuthStore } from "./oauth.js";
12
13
  import { isMemberBlocked } from "./principals.js";
13
14
  import { isRecordId } from "./records.js";
14
15
  const GRANTS = `"${OAUTH_GRANTS_TABLE}"`;
16
+ const TOKENS = `"${OAUTH_TOKENS_TABLE}"`;
17
+ // @legacy ontology.sign-up-web
18
+ /** How many new website visitors one network address may sign up an hour. */
19
+ export const VISITORS_PER_CLIENT_PER_HOUR = 10;
20
+ /** How many new guests one network address may start an hour. */
21
+ export const GUESTS_PER_CLIENT_PER_HOUR = 10;
22
+ /** How many guests' grants that can no longer be renewed one new guest's issue removes. */
23
+ const EXPIRED_GUESTS_PER_ISSUE = 100;
15
24
  /**
16
25
  * Agent tokens in the ontology's OAuth tables, as channel sessions are: one standing grant per
17
26
  * member and resource for the first-party client `agent-web`, and a new access token on each
18
27
  * request. Blocking or deactivating the member revokes the grant with every other one of theirs.
28
+ * A guest's grant names no user: its id is the guest's, and it lives while its refresh token does.
19
29
  */
20
- /** How many new website visitors one network address may start an hour. */
21
- export const VISITORS_PER_CLIENT_PER_HOUR = 10;
22
30
  export function sqlAgentWebStore(ontology, sql, admission) {
23
31
  const oauth = sqlOAuthStore(ontology, sql);
24
32
  return {
@@ -64,9 +72,96 @@ export function sqlAgentWebStore(ontology, sql, admission) {
64
72
  .pipe(Effect.orDie);
65
73
  return standing === undefined ? undefined : yield* oauth.memberPrincipal(userId);
66
74
  }),
67
- countTurn: (userId) => Effect.gen(function* () {
75
+ grantGuest: (grantId) => Effect.gen(function* () {
76
+ if (ontology.signIn.guest === undefined || !isRecordId(grantId)) {
77
+ return undefined;
78
+ }
79
+ const [standing] = yield* sql
80
+ .unsafe(`SELECT 1 FROM ${GRANTS} WHERE "id" = $1::uuid AND "user_id" IS NULL
81
+ AND "client_id" = $2 AND "revoked_at" IS NULL`, [grantId, AGENT_WEB_CLIENT_ID])
82
+ .pipe(Effect.orDie);
83
+ return standing === undefined ? undefined : guestPrincipal(ontology, grantId);
84
+ }),
85
+ countGuestTurn: (guestId, input) => Effect.gen(function* () {
86
+ if (!isRecordId(guestId)) {
87
+ return undefined;
88
+ }
89
+ const limits = yield* effectiveChannelLimits(sql, input);
90
+ for (const [scope, subject, limit] of [
91
+ ["guestTurnsPerDay", guestId, limits.guest.turnsPerDay],
92
+ ["guestWorkspaceTurnsPerDay", "workspace", limits.guest.workspaceTurnsPerDay],
93
+ ]) {
94
+ const limited = yield* countAgentAttempt(sql, { scope, subject, window: "day", limit });
95
+ if (limited !== undefined) {
96
+ // The refusal the browser gets is this window's notice.
97
+ if (limited.notificationId !== undefined) {
98
+ yield* completeAgentLimitNotice(sql, {
99
+ notificationId: limited.notificationId,
100
+ delivered: true,
101
+ });
102
+ }
103
+ return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
104
+ }
105
+ }
106
+ return undefined;
107
+ }).pipe(Effect.orDie),
108
+ guest: ({ resource, client }) => Effect.gen(function* () {
109
+ if (ontology.signIn.guest === undefined) {
110
+ return { status: "refused" };
111
+ }
112
+ const crowded = yield* countAgentAttempt(sql, {
113
+ scope: "newGuestsPerHour",
114
+ subject: client,
115
+ window: "hour",
116
+ limit: GUESTS_PER_CLIENT_PER_HOUR,
117
+ });
118
+ if (crowded !== undefined) {
119
+ return { status: "limited", retryAfterSeconds: crowded.retryAfterSeconds };
120
+ }
121
+ return yield* sql.withTransaction(Effect.gen(function* () {
122
+ yield* sql.unsafe(`INSERT INTO "${OAUTH_CLIENTS_TABLE}" ("id", "name", "redirect_uris", "auth_method")
123
+ VALUES ($1, $1, '[]'::jsonb, 'none') ON CONFLICT ("id") DO NOTHING`, [AGENT_WEB_CLIENT_ID]);
124
+ // A guest lives while their refresh token does: a grant left without a token that has
125
+ // not expired can never be renewed, so a few of them go with each new guest.
126
+ yield* sql.unsafe(`DELETE FROM ${GRANTS} WHERE "id" IN (
127
+ SELECT "g"."id" FROM ${GRANTS} AS "g"
128
+ WHERE "g"."user_id" IS NULL AND "g"."client_id" = $1
129
+ AND "g"."created_at" < now() - interval '1 hour'
130
+ AND NOT EXISTS (
131
+ SELECT 1 FROM ${TOKENS} AS "t"
132
+ WHERE "t"."grant_id" = "g"."id" AND "t"."expires_at" > now()
133
+ )
134
+ LIMIT ${EXPIRED_GUESTS_PER_ISSUE}
135
+ FOR UPDATE SKIP LOCKED
136
+ )`, [AGENT_WEB_CLIENT_ID]);
137
+ const guestId = randomUUID();
138
+ const token = newSecret(ACCESS_TOKEN_PREFIX);
139
+ const refreshToken = newSecret(REFRESH_TOKEN_PREFIX);
140
+ const now = Date.now();
141
+ const expiresAt = new Date(now + ACCESS_TOKEN_TTL_MS);
142
+ // The grant names no user: the guest is a session, and its id is the guest's.
143
+ yield* sql.unsafe(`INSERT INTO ${GRANTS} ("id", "client_id", "user_id", "scope", "resource")
144
+ VALUES ($1::uuid, $2, NULL, $3, $4)`, [guestId, AGENT_WEB_CLIENT_ID, FULL_SCOPE, resource]);
145
+ yield* oauth.saveTokens([
146
+ { hash: secretHash(token), grantId: guestId, kind: "access", expiresAt },
147
+ {
148
+ hash: secretHash(refreshToken),
149
+ grantId: guestId,
150
+ kind: "refresh",
151
+ expiresAt: new Date(now + REFRESH_TOKEN_TTL_MS),
152
+ },
153
+ ]);
154
+ return { status: "issued", guestId, token, refreshToken, expiresAt };
155
+ }));
156
+ }).pipe(Effect.orDie),
157
+ countTurn: (userId, input) => Effect.gen(function* () {
68
158
  // @legacy ontology.pre-upgrade-database-tolerance
69
- if (!isRecordId(userId) || !(yield* channelUsersAvailable(sql))) {
159
+ // A database before its channel tables' migration neither stores limits nor counts turns.
160
+ const tablesAvailable = yield* channelUsersAvailable(sql);
161
+ if (input !== undefined && tablesAvailable) {
162
+ yield* effectiveChannelLimits(sql, input);
163
+ }
164
+ if (!isRecordId(userId) || !tablesAvailable) {
70
165
  return undefined;
71
166
  }
72
167
  const [lifecycle] = yield* sql.unsafe(`SELECT COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up",
@@ -110,6 +205,7 @@ export function sqlAgentWebStore(ontology, sql, admission) {
110
205
  }
111
206
  return undefined;
112
207
  }).pipe(Effect.orDie),
208
+ // @legacy ontology.sign-up-web
113
209
  visitor: ({ visitorId, resource, client }) => Effect.gen(function* () {
114
210
  const crowded = yield* countAgentAttempt(sql, {
115
211
  scope: "newUsersPerHour",
@@ -8,6 +8,7 @@ import { isCalendarDate, isInstant } from "../query.js";
8
8
  import { OntologyWrites } from "../runtime.js";
9
9
  import { User } from "../user.js";
10
10
  import { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity } from "../user-identity.js";
11
+ import { userRoleNames } from "./guests.js";
11
12
  import { entityModel, ontologyModel, propertyValueSchema, } from "./model.js";
12
13
  /** Generated actions, built once per ontology and entity. */
13
14
  const builtActions = new WeakMap();
@@ -137,9 +138,7 @@ export function writesOnlyThroughActions(ontology, entityName, actionName) {
137
138
  }
138
139
  /** A role a member may be granted: one the ontology declares, never the implicit `member`. */
139
140
  function grantableRole(ontology) {
140
- const declared = ontology.roles
141
- .map((candidate) => candidate.name)
142
- .filter((name) => name !== MEMBER_ROLE);
141
+ const declared = userRoleNames(ontology).filter((name) => name !== MEMBER_ROLE);
143
142
  return declared.length > 0
144
143
  ? Schema.Literals(declared)
145
144
  : Schema.String.check(Schema.makeFilter(() => "Expected a role of the ontology, which declares none"));
@@ -0,0 +1,32 @@
1
+ import type { Ontology } from "../ontology.js";
2
+ import { type AgentToolVerb } from "../permissions.js";
3
+ import type { Principal } from "../runtime.js";
4
+ /**
5
+ * A guest as the agent names them in `X-SegmentStream-Act-As`: `guest:` and their id, so that no
6
+ * guest is ever taken for a user.
7
+ */
8
+ export declare const GUEST_ACT_AS_PREFIX = "guest:";
9
+ /** A guest's chat with the agent, as their agent token names it. */
10
+ export declare function guestChat(guestId: string): string;
11
+ /** Whether a role is the guests' built-in one, which only guests hold, never a user. */
12
+ export declare function isGuestRole(ontology: Ontology, role: string): boolean;
13
+ /**
14
+ * The roles a user, an API key or a workflow may hold: every role of the ontology but the guests'
15
+ * built-in one. A stored assignment of it grants nothing.
16
+ */
17
+ export declare function userRoleNames(ontology: Ontology): ReadonlyArray<string>;
18
+ /**
19
+ * The agent's own tools a caller holds, as every answer naming whom the agent acts for carries them.
20
+ * A guest holds those `guest.permissions` grant, never the sandbox and never implicitly. Anyone
21
+ * else holds those the ontology's roles grant, and the guests' role decides nothing for them: while
22
+ * no other role names an agent tool, they keep the earlier implicit sandbox.
23
+ */
24
+ export declare function agentToolsFor(ontology: Ontology, principal: Principal): ReadonlyArray<AgentToolVerb>;
25
+ /** The guest id `X-SegmentStream-Act-As` names, or `undefined` when it names no guest. */
26
+ export declare function actingGuestId(actAs: string): string | undefined;
27
+ /**
28
+ * The principal of a guest: a session, not a user. Its id is the guest's, which names no user; it
29
+ * holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
30
+ * `undefined` when the ontology admits no guests.
31
+ */
32
+ export declare function guestPrincipal(ontology: Ontology, guestId: string): Principal | undefined;
@@ -0,0 +1,64 @@
1
+ import { GUEST_ROLE } from "../names.js";
2
+ import { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, isAllowed, permissionsOf, principalScopes, } from "../permissions.js";
3
+ import { WEB_PROVIDER } from "../service/runtime-identity.js";
4
+ import { isRecordId } from "./records.js";
5
+ /**
6
+ * A guest as the agent names them in `X-SegmentStream-Act-As`: `guest:` and their id, so that no
7
+ * guest is ever taken for a user.
8
+ */
9
+ export const GUEST_ACT_AS_PREFIX = "guest:";
10
+ /** A guest's chat with the agent, as their agent token names it. */
11
+ export function guestChat(guestId) {
12
+ return `guest:${guestId}`;
13
+ }
14
+ /** Whether a role is the guests' built-in one, which only guests hold, never a user. */
15
+ export function isGuestRole(ontology, role) {
16
+ return role === GUEST_ROLE && ontology.signIn.guest !== undefined;
17
+ }
18
+ /**
19
+ * The roles a user, an API key or a workflow may hold: every role of the ontology but the guests'
20
+ * built-in one. A stored assignment of it grants nothing.
21
+ */
22
+ export function userRoleNames(ontology) {
23
+ return ontology.roles
24
+ .map((candidate) => candidate.name)
25
+ .filter((name) => !isGuestRole(ontology, name));
26
+ }
27
+ /**
28
+ * The agent's own tools a caller holds, as every answer naming whom the agent acts for carries them.
29
+ * A guest holds those `guest.permissions` grant, never the sandbox and never implicitly. Anyone
30
+ * else holds those the ontology's roles grant, and the guests' role decides nothing for them: while
31
+ * no other role names an agent tool, they keep the earlier implicit sandbox.
32
+ */
33
+ export function agentToolsFor(ontology, principal) {
34
+ if (principal.kind === "guest") {
35
+ return AGENT_TOOL_VERBS.filter((tool) => tool !== "sandbox" && isAllowed(agentToolPermission(tool), principal));
36
+ }
37
+ return agentToolsOf(ontology.roles.filter((candidate) => !isGuestRole(ontology, candidate.name)), principal);
38
+ }
39
+ /** The guest id `X-SegmentStream-Act-As` names, or `undefined` when it names no guest. */
40
+ export function actingGuestId(actAs) {
41
+ const id = actAs.startsWith(GUEST_ACT_AS_PREFIX)
42
+ ? actAs.slice(GUEST_ACT_AS_PREFIX.length)
43
+ : undefined;
44
+ return id !== undefined && isRecordId(id) ? id : undefined;
45
+ }
46
+ /**
47
+ * The principal of a guest: a session, not a user. Its id is the guest's, which names no user; it
48
+ * holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
49
+ * `undefined` when the ontology admits no guests.
50
+ */
51
+ export function guestPrincipal(ontology, guestId) {
52
+ if (ontology.signIn.guest === undefined || !isRecordId(guestId)) {
53
+ return undefined;
54
+ }
55
+ const roles = [GUEST_ROLE];
56
+ return {
57
+ id: guestId,
58
+ kind: "guest",
59
+ roles,
60
+ permissions: permissionsOf(ontology.roles, roles),
61
+ ...principalScopes(ontology.roles, roles),
62
+ authenticatedVia: WEB_PROVIDER,
63
+ };
64
+ }
@@ -3,6 +3,7 @@ import { SqlClient } from "effect/unstable/sql";
3
3
  import { CHANNEL_USERS_TABLE } from "../migrate/storage.js";
4
4
  import { FEEDBACK_REPORTER_ROLE, MEMBER_ROLE } from "../names.js";
5
5
  import { permissionsOf, principalScopes } from "../permissions.js";
6
+ import { userRoleNames } from "./guests.js";
6
7
  import { signUpPending } from "./member-tables.js";
7
8
  import { runAction } from "./pipeline.js";
8
9
  /**
@@ -20,7 +21,7 @@ export function runNewUserHook(ontology, sql, principal) {
20
21
  if (hook === undefined) {
21
22
  return false;
22
23
  }
23
- const declared = new Set(ontology.roles.map((candidate) => candidate.name));
24
+ const declared = new Set(userRoleNames(ontology));
24
25
  const roles = signedUp
25
26
  ? principal.roles.filter((role) => declared.has(role) && role !== MEMBER_ROLE && role !== FEEDBACK_REPORTER_ROLE)
26
27
  : [MEMBER_ROLE];
@@ -1,6 +1,8 @@
1
1
  import { Effect } from "effect";
2
2
  import { SqlClient } from "effect/unstable/sql";
3
3
  import { OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_REQUESTS_TABLE, OAUTH_TOKENS_TABLE, } from "../migrate/storage.js";
4
+ import { AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
5
+ import { guestPrincipal } from "./guests.js";
4
6
  import { lockSessionMember, resolveMemberById } from "./principals.js";
5
7
  import { CHANNEL_IDENTITIES_FROM, LIVE_CHANNEL_IDENTITY, USER_IDENTITY_TABLE, } from "./user-identity-sql.js";
6
8
  import { rejectedAccessToken, sameResource } from "../service/oauth/protocol.js";
@@ -68,7 +70,7 @@ function grantOf(row) {
68
70
  return {
69
71
  id: text(row.grant_id),
70
72
  clientId: text(row.client_id),
71
- userId: text(row.user_id),
73
+ userId: nullableText(row.user_id),
72
74
  scope: text(row.scope),
73
75
  resource: text(row.resource),
74
76
  };
@@ -295,5 +297,9 @@ export function sqlOAuthStore(ontology, sql) {
295
297
  `JOIN ${GRANTS} AS "g" ON "g"."id" = "t"."grant_id" WHERE "t"."hash" = $1`, [hash]).pipe(Effect.map(([row]) => (row === undefined ? undefined : grantOf(row)))),
296
298
  revokeGrant: (id) => rows(`UPDATE ${GRANTS} SET "revoked_at" = now() WHERE "id" = $1::uuid AND "revoked_at" IS NULL`, [id]).pipe(Effect.asVoid),
297
299
  memberPrincipal: (userId) => resolveMemberById(ontology, userId).pipe(Effect.provideService(SqlClient.SqlClient, sql)),
300
+ // A guest's grant names no user; its id is the guest's. The grant stands, or no store read it.
301
+ guestPrincipal: (grant) => Effect.succeed(grant.userId === null && grant.clientId === AGENT_WEB_CLIENT_ID
302
+ ? guestPrincipal(ontology, grant.id)
303
+ : undefined),
298
304
  };
299
305
  }
@@ -349,7 +349,8 @@ export function runAction(ontology, request) {
349
349
  const runtime = makeOntologyRuntime(ontology, sql, {
350
350
  action: qualified,
351
351
  actionId,
352
- principalId: request.principal.id,
352
+ // A guest is no user: what they create or change was created and updated by nobody.
353
+ principalId: request.principal.kind === "guest" ? null : request.principal.id,
353
354
  ...(request.principal.execution ? { execution: request.principal.execution } : {}),
354
355
  ...(request.principal.workflow ? { workflow: request.principal.workflow } : {}),
355
356
  ...(key ? { blobActionKey: key } : {}),
@@ -378,7 +379,7 @@ export function runAction(ontology, request) {
378
379
  });
379
380
  const handle = action.handler;
380
381
  const handler = Effect.gen(function* () {
381
- const identities = isRecordId(context.principal.id)
382
+ const identities = context.principal.kind !== "guest" && isRecordId(context.principal.id)
382
383
  ? yield* sql
383
384
  .unsafe(`SELECT "i"."provider", "i"."subject", true AS "verified", "i"."username" ` +
384
385
  `FROM ${CHANNEL_IDENTITIES_FROM} ` +
@@ -18,6 +18,7 @@ import { User } from "../user.js";
18
18
  import { MemberNotFound, PrincipalRejected, UnknownRole } from "./errors.js";
19
19
  import { channelUsersAvailable, recordUserCreation, revokeMemberSessions, } from "./member-tables.js";
20
20
  import { refuseMember, requireGrantable } from "./member-writes.js";
21
+ import { isGuestRole, userRoleNames } from "./guests.js";
21
22
  import { isRecordId } from "./records.js";
22
23
  import { makeOntologyRuntime, makePrincipalUserWriter, } from "./sql-runtime.js";
23
24
  import { accountOfLegacy, CHANNEL_IDENTITIES_FROM, liveSignInIdentities, LIVE_CHANNEL_IDENTITY, LIVE_CHANNEL_RECORD, makeIdentityWriter, NEON_AUTH_PROVIDER, OIDC_PROVIDER, SIGN_IN_ORIGIN_SQL, USER_IDENTITY_TABLE, userIdentitiesAvailable, userOfAccount, } from "./user-identities.js";
@@ -148,8 +149,9 @@ export function rolesOf(ontology, sql, user) {
148
149
  function principalState(ontology, sql, user) {
149
150
  return Effect.gen(function* () {
150
151
  const stored = yield* storedRoles(sql, user.id);
151
- // Ignore forged or historical stored assignments: reporter authority is never persisted.
152
- const assigned = stored.roles.filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE);
152
+ // Ignore forged or historical stored assignments: reporter authority is never persisted, and
153
+ // the guests' role is never a user's.
154
+ const assigned = stored.roles.filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE && !isGuestRole(ontology, role));
153
155
  const roles = user.kind === "member" && stored.signedUp
154
156
  ? assigned.filter((role) => role !== MEMBER_ROLE)
155
157
  : user.kind === "member"
@@ -838,7 +840,7 @@ export function revokeApiKey(input) {
838
840
  /** Replaces a user's roles inside the caller's transaction, failing on a role the ontology lacks. */
839
841
  function writeUserRoles(ontology, sql, input) {
840
842
  return Effect.gen(function* () {
841
- const known = new Set(ontology.roles.map((candidate) => candidate.name));
843
+ const known = new Set(userRoleNames(ontology));
842
844
  const unknown = input.roles.find((role) => toSnakeCase(role) === FEEDBACK_REPORTER_ROLE || !known.has(role));
843
845
  if (unknown !== undefined) {
844
846
  return yield* new UnknownRole({
@@ -1228,7 +1230,7 @@ export function updateMemberRoles(ontology, change) {
1228
1230
  const key = "id" in change ? { id: change.id } : { email: normalizeEmail(change.email) };
1229
1231
  const grant = change.grant === undefined ? undefined : [...new Set(change.grant)];
1230
1232
  const revoke = change.revoke === "all" ? "all" : [...new Set(change.revoke ?? [])];
1231
- const declared = ontology.roles.map((candidate) => candidate.name);
1233
+ const declared = userRoleNames(ontology);
1232
1234
  // Refused before anything is read, whoever the member is.
1233
1235
  yield* requireGrantable(declared, grant ?? []);
1234
1236
  yield* refuseMember(revoke === "all" ? [] : revoke);
@@ -13,6 +13,7 @@ import { InvalidQuery, UndeclaredWrite, UnknownRole, WriteOutsideAction } from "
13
13
  import { grantMemberRoles, inviteMember, queueSignInEmail, revokeMemberRoles, setMemberActive, } from "./member-writes.js";
14
14
  import { entityModel, ontologyModel } from "./model.js";
15
15
  import { loadRecord, notFound, readHistory, relatedCondition, runQuery, validateQuery, } from "./reads.js";
16
+ import { userRoleNames } from "./guests.js";
16
17
  import { createRecord, deleteRecord, linkRecords, unlinkRecords, updateRecord, upsertRecord, } from "./writes.js";
17
18
  import { readScopeOf } from "./where.js";
18
19
  /** A handler wrote an entity its action's `writes` does not list. */
@@ -274,7 +275,7 @@ export function makeOntologyRuntime(ontology, sql, scope) {
274
275
  const identityAction = (action, operation) => scope?.action === action && scope.principalId !== null
275
276
  ? operation(scope)
276
277
  : Effect.die(new Error(`Sign-in identities change only through ${action}, never in another action.`));
277
- const declaredRoles = ontology.roles.map((candidate) => candidate.name);
278
+ const declaredRoles = userRoleNames(ontology);
278
279
  const memberWrite = (operation) => write(User.name, (writeContext, entity) => operation({ ...writeContext, sql, roles: declaredRoles }, entity));
279
280
  const members = {
280
281
  grantRoles: (input) => memberWrite((context, entity) => grantMemberRoles(context, entity, input)).pipe(Effect.catchTag("Conflict", (error) => Effect.die(error))),
package/dist/runtime.d.ts CHANGED
@@ -18,9 +18,17 @@ export interface Principal {
18
18
  };
19
19
  /** Verified authentication mechanism for this request; action contexts always expose it. */
20
20
  readonly authenticatedVia?: string;
21
- /** The id of the principal's `user` record. */
21
+ /**
22
+ * The id of the principal's `user` record. A guest has none: theirs is the id of their session,
23
+ * which names no user, so records they change are created and updated by nobody.
24
+ */
22
25
  readonly id: string;
23
- readonly kind: "member" | "service";
26
+ /**
27
+ * `member`, a person's user; `service`, a service's user, such as an API key's or a workflow's;
28
+ * `guest`, a visitor of a website the ontology's `guest` names, who is no user and holds the
29
+ * built-in role `guest` alone.
30
+ */
31
+ readonly kind: "member" | "service" | "guest";
24
32
  /** Role names the principal holds. Every active member holds `member`. */
25
33
  readonly roles: ReadonlyArray<string>;
26
34
  /**
@@ -28,8 +28,10 @@ export declare function authenticateAgentCaller(input: {
28
28
  readonly response?: undefined;
29
29
  }, never, RequestId | HttpServerRequest.ParsedSearchParams>;
30
30
  /**
31
- * The member the agent acts for on the web: the OAuth grant behind the agent token they showed
32
- * names them and stands, and they are active. `undefined` on a store without web grants.
31
+ * Whom the agent acts for on the web: the member the OAuth grant behind the agent token they showed
32
+ * names, while it stands and they are active; or, for `guest:<id>`, the guest whose grant, which
33
+ * names no user, has that id, while it stands and the ontology admits guests. `undefined` on a
34
+ * store without web grants. A guest is admitted only where the caller says so.
33
35
  */
34
36
  export declare function webMember(agents: AgentStore, userId: string, grantId: string): Effect.Effect<Principal | undefined>;
35
37
  /**
@@ -80,7 +82,7 @@ export declare function delegatedAgentMember(request: HttpServerRequest.HttpServ
80
82
  readonly subject: string;
81
83
  };
82
84
  id: string;
83
- kind: "member" | "service";
85
+ kind: "member" | "service" | "guest";
84
86
  roles: ReadonlyArray<string>;
85
87
  permissions: ReadonlyArray<string>;
86
88
  scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
@@ -108,7 +110,7 @@ export declare function delegatedAccount(agents: AgentStore, actAs: string, prov
108
110
  readonly subject: string;
109
111
  };
110
112
  id: string;
111
- kind: "member" | "service";
113
+ kind: "member" | "service" | "guest";
112
114
  roles: ReadonlyArray<string>;
113
115
  permissions: ReadonlyArray<string>;
114
116
  scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
@@ -3,6 +3,7 @@ import { HttpServerRequest } from "effect/unstable/http";
3
3
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { RequestId, forbidden, notFound, toServerResponse, unauthorized, unavailable, } from "../errors.js";
5
5
  import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
+ import { GUEST_ACT_AS_PREFIX, actingGuestId } from "../../runtime/guests.js";
6
7
  import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
7
8
  export const CHAT_HEADER = "x-segmentstream-agent-chat";
8
9
  export const SESSION_HEADER = "x-segmentstream-agent-session";
@@ -49,17 +50,31 @@ export function authenticateAgentCaller(input) {
49
50
  ? notFound(requestId, "Attachment not found.")
50
51
  : forbidden(requestId, "The member is inactive or has not paired with the agent."));
51
52
  }
53
+ // Attachments, member files and the workspace's code are a member's; a guest has none.
54
+ if (member.kind === "guest") {
55
+ return denied(forbidden(requestId, "A guest has no attachments or files."));
56
+ }
52
57
  return agentCaller(request, requestId, member);
53
58
  });
54
59
  }
55
60
  /**
56
- * The member the agent acts for on the web: the OAuth grant behind the agent token they showed
57
- * names them and stands, and they are active. `undefined` on a store without web grants.
61
+ * Whom the agent acts for on the web: the member the OAuth grant behind the agent token they showed
62
+ * names, while it stands and they are active; or, for `guest:<id>`, the guest whose grant, which
63
+ * names no user, has that id, while it stands and the ontology admits guests. `undefined` on a
64
+ * store without web grants. A guest is admitted only where the caller says so.
58
65
  */
59
66
  export function webMember(agents, userId, grantId) {
60
- return agents.web === undefined
61
- ? Effect.succeed(undefined)
62
- : Effect.map(agents.web.grantMember({ grantId, userId }), (member) => member === undefined ? undefined : { ...member, authenticatedVia: WEB_PROVIDER });
67
+ const web = agents.web;
68
+ if (web === undefined) {
69
+ return Effect.succeed(undefined);
70
+ }
71
+ if (userId.startsWith(GUEST_ACT_AS_PREFIX)) {
72
+ const guestId = actingGuestId(userId);
73
+ return guestId === undefined || guestId !== grantId || web.grantGuest === undefined
74
+ ? Effect.succeed(undefined)
75
+ : web.grantGuest(grantId);
76
+ }
77
+ return Effect.map(web.grantMember({ grantId, userId }), (member) => member === undefined ? undefined : { ...member, authenticatedVia: WEB_PROVIDER });
63
78
  }
64
79
  /**
65
80
  * The member the runtime acts for: a web member by the grant their agent token stands for, anyone
@@ -25,6 +25,22 @@ export declare const PairingRequest: Schema.Struct<{
25
25
  readonly external_id: Schema.String;
26
26
  readonly display: Schema.optionalKey<Schema.NullOr<Schema.String>>;
27
27
  }>;
28
+ /**
29
+ * The agent's limits, as it sends them with a turn: each can only lower the platform's ceiling.
30
+ * `guest` limits guests' turns, apart from those of people who signed up.
31
+ */
32
+ export declare const AgentLimitsRequest: Schema.Struct<{
33
+ readonly perSender: Schema.optionalKey<Schema.Struct<{
34
+ readonly turnsPerMinute: Schema.optionalKey<Schema.Int>;
35
+ readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
36
+ }>>;
37
+ readonly newUsersPerHour: Schema.optionalKey<Schema.Int>;
38
+ readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
39
+ readonly guest: Schema.optionalKey<Schema.Struct<{
40
+ readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
41
+ readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
42
+ }>>;
43
+ }>;
28
44
  export declare const ResolveIdentityRequest: Schema.Struct<{
29
45
  readonly chat: Schema.Literals<readonly ["private", "group"]>;
30
46
  readonly turn: Schema.Boolean;
@@ -39,6 +55,10 @@ export declare const ResolveIdentityRequest: Schema.Struct<{
39
55
  }>>;
40
56
  readonly newUsersPerHour: Schema.optionalKey<Schema.Int>;
41
57
  readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
58
+ readonly guest: Schema.optionalKey<Schema.Struct<{
59
+ readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
60
+ readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
61
+ }>>;
42
62
  }>>;
43
63
  readonly provider: Schema.String;
44
64
  readonly external_id: Schema.String;
@@ -96,14 +116,20 @@ export declare function identityForWire(identity: AgentIdentity): {
96
116
  external_id: string;
97
117
  display: string | null;
98
118
  };
99
- /** The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers. */
119
+ /** Which of the agent's own tools a caller holds: `agentToolsOf` over the ontology's roles. */
120
+ export type AgentToolsOf = (principal: Principal) => ReadonlyArray<string>;
121
+ /**
122
+ * The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers: their
123
+ * roles, and in `agent_tools` the agent's own tools those roles grant, such as `sandbox`.
124
+ */
100
125
  export declare function memberForWire(input: {
101
126
  readonly name: string;
102
127
  readonly principal: Principal;
103
- }): {
128
+ }, agentTools: AgentToolsOf): {
104
129
  user: {
105
130
  id: string;
106
131
  name: string;
107
132
  };
108
133
  roles: readonly string[];
134
+ agent_tools: readonly string[];
109
135
  };
@@ -42,6 +42,22 @@ export const PairingRequest = Schema.Struct({
42
42
  });
43
43
  /** Trusted runtime resolution: channel admission and limits run before expensive processing. */
44
44
  const PositiveLimit = Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_000_000_000));
45
+ /**
46
+ * 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.
48
+ */
49
+ export const AgentLimitsRequest = Schema.Struct({
50
+ perSender: Schema.optionalKey(Schema.Struct({
51
+ turnsPerMinute: Schema.optionalKey(PositiveLimit),
52
+ turnsPerDay: Schema.optionalKey(PositiveLimit),
53
+ })),
54
+ newUsersPerHour: Schema.optionalKey(PositiveLimit),
55
+ workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
56
+ guest: Schema.optionalKey(Schema.Struct({
57
+ turnsPerDay: Schema.optionalKey(PositiveLimit),
58
+ workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
59
+ })),
60
+ });
45
61
  export const ResolveIdentityRequest = Schema.Struct({
46
62
  ...PairingRequest.fields,
47
63
  chat: Schema.Literals(["private", "group"]),
@@ -53,14 +69,7 @@ export const ResolveIdentityRequest = Schema.Struct({
53
69
  description: "Whether the receiving server proved the sender's address, as DMARC does for mail. An " +
54
70
  "email account is admitted only when it is.",
55
71
  }),
56
- limits: Schema.optionalKey(Schema.Struct({
57
- perSender: Schema.optionalKey(Schema.Struct({
58
- turnsPerMinute: Schema.optionalKey(PositiveLimit),
59
- turnsPerDay: Schema.optionalKey(PositiveLimit),
60
- })),
61
- newUsersPerHour: Schema.optionalKey(PositiveLimit),
62
- workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
63
- })),
72
+ limits: Schema.optionalKey(AgentLimitsRequest),
64
73
  });
65
74
  export const IdentityNoticeRequest = Schema.Struct({
66
75
  provider: Provider,
@@ -142,10 +151,14 @@ export function identityForWire(identity) {
142
151
  created_at: identity.createdAt.toISOString(),
143
152
  };
144
153
  }
145
- /** The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers. */
146
- export function memberForWire(input) {
154
+ /**
155
+ * The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers: their
156
+ * roles, and in `agent_tools` the agent's own tools those roles grant, such as `sandbox`.
157
+ */
158
+ export function memberForWire(input, agentTools) {
147
159
  return {
148
160
  user: { id: input.principal.id, name: input.name },
149
161
  roles: input.principal.roles,
162
+ agent_tools: agentTools(input.principal),
150
163
  };
151
164
  }
@@ -5,6 +5,8 @@ import { RequestId } from "../errors.js";
5
5
  import { type RateLimit } from "../rate-limit.js";
6
6
  import { OntologyBackend } from "../runtime-contract.js";
7
7
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
8
+ import { type AgentToolsOf } from "./protocol.js";
9
+ import { type VisitorWebsites } from "./web-tokens.js";
8
10
  /** The agent's endpoints, under the ontology service's path. */
9
11
  export declare const AGENT_PATH = "/api/ontology/agent";
10
12
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
@@ -19,11 +21,16 @@ export declare const AGENT_VISITORS_PATH = "/api/ontology/agent/visitors";
19
21
  export declare const PAIRING_LIMIT: RateLimit;
20
22
  export interface AgentServerOptions {
21
23
  readonly verifyToken: TokenVerifier;
22
- /** The websites whose visitors may sign up on `web`, by origin; none while `web` is closed. */
23
- readonly visitorOrigins?: ReadonlyArray<string>;
24
+ /**
25
+ * The websites whose visitors get an agent token: as guests, and, while `web` is open to sign-up,
26
+ * by signing up. None by default.
27
+ */
28
+ readonly visitorWebsites?: VisitorWebsites;
24
29
  /** The deployment's runtime tokens; `undefined` while runtime authentication is disabled. */
25
30
  readonly verifyRuntime: RuntimeTokenVerifier | undefined;
26
31
  readonly exchangeSession: SessionExchange | undefined;
32
+ /** The agent's own tools a caller holds, which every answer naming whom the agent acts for carries. */
33
+ readonly agentTools: AgentToolsOf;
27
34
  }
28
35
  /**
29
36
  * The routes that pair channel accounts with members for the app's own agent, and record the group