@segmentstream/ontology 0.106.3 → 0.107.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 +49 -0
  2. package/README.md +38 -8
  3. package/dist/analyze.d.ts +7 -1
  4. package/dist/analyze.js +237 -13
  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/index.d.ts +6 -6
  9. package/dist/index.js +5 -3
  10. package/dist/manifest.d.ts +69 -1
  11. package/dist/manifest.js +51 -4
  12. package/dist/migrate/apply.js +8 -1
  13. package/dist/migrate/model.d.ts +32 -0
  14. package/dist/migrate/storage.d.ts +2 -0
  15. package/dist/migrate/storage.js +8 -0
  16. package/dist/names.d.ts +5 -0
  17. package/dist/names.js +5 -0
  18. package/dist/ontology.d.ts +4 -1
  19. package/dist/permissions.d.ts +30 -2
  20. package/dist/permissions.js +51 -6
  21. package/dist/runtime/agent-counters.d.ts +5 -1
  22. package/dist/runtime/agent-counters.js +21 -6
  23. package/dist/runtime/agent-web.d.ts +9 -6
  24. package/dist/runtime/agent-web.js +101 -5
  25. package/dist/runtime/generated-actions.js +2 -3
  26. package/dist/runtime/guests.d.ts +32 -0
  27. package/dist/runtime/guests.js +64 -0
  28. package/dist/runtime/new-user-hook.js +2 -1
  29. package/dist/runtime/oauth.js +7 -1
  30. package/dist/runtime/pipeline.js +3 -2
  31. package/dist/runtime/principals.js +6 -4
  32. package/dist/runtime/sql-runtime.js +2 -1
  33. package/dist/runtime.d.ts +10 -2
  34. package/dist/service/agent/authentication.d.ts +6 -4
  35. package/dist/service/agent/authentication.js +20 -5
  36. package/dist/service/agent/protocol.d.ts +28 -2
  37. package/dist/service/agent/protocol.js +23 -10
  38. package/dist/service/agent/server.d.ts +9 -2
  39. package/dist/service/agent/server.js +12 -12
  40. package/dist/service/agent/tasks.d.ts +3 -0
  41. package/dist/service/agent/tasks.js +5 -3
  42. package/dist/service/agent/web-tokens.d.ts +28 -13
  43. package/dist/service/agent/web-tokens.js +91 -38
  44. package/dist/service/authentication.d.ts +6 -0
  45. package/dist/service/authentication.js +11 -2
  46. package/dist/service/chat/review-delivery.js +4 -0
  47. package/dist/service/mcp/server.js +3 -3
  48. package/dist/service/mcp/tools.d.ts +4 -2
  49. package/dist/service/mcp/tools.js +14 -2
  50. package/dist/service/oauth/protocol.js +8 -2
  51. package/dist/service/oauth/server.js +5 -1
  52. package/dist/service/runtime-contract.d.ts +58 -6
  53. package/dist/service/schemas.d.ts +8 -0
  54. package/dist/service/service.js +15 -4
  55. package/dist/sign-in.d.ts +58 -9
  56. package/dist/sign-in.js +87 -9
  57. package/package.json +1 -1
@@ -21,11 +21,13 @@ export const READ_VERB = "read";
21
21
  * chats with the people it serves, and approving one sends it: only a role that names
22
22
  * `agent_review` reads, approves or rejects them. The workspace's deployed code is no entity, but
23
23
  * {@link WORKSPACE_SOURCE_PERMISSION} is covered the same way: `workspace_source:read` or
24
- * `workspace_source:*` grants it, `*:read` and `*:*` do not.
24
+ * `workspace_source:*` grants it, `*:read` and `*:*` do not. So are the agent's own tools
25
+ * ({@link AGENT_TOOL}): `agent_tool:sandbox` or `agent_tool:*` grants the sandbox, `*:*` does not.
25
26
  */
26
27
  export const EXPLICIT_GRANT_ENTITIES = new Set([
27
28
  "agent_chat",
28
29
  "agent_review",
30
+ "agent_tool",
29
31
  "app_feedback",
30
32
  "app_feedback_file",
31
33
  "user_identity",
@@ -41,6 +43,23 @@ export const WORKSPACE_SOURCE = "workspace_source";
41
43
  * member it acts for, through `GET /api/ontology/agent/source`. Only a role that names it grants it.
42
44
  */
43
45
  export const WORKSPACE_SOURCE_PERMISSION = `${WORKSPACE_SOURCE}:${READ_VERB}`;
46
+ /**
47
+ * The built-in permissions' entity for the tools the app's agent has of its own, beside the
48
+ * ontology's: `agent_tool:<tool>`. It names no entity: `check` refuses an entity or a toolset of
49
+ * this name, a scoped grant of it, and any verb of it but those of {@link AGENT_TOOL_VERBS}.
50
+ */
51
+ export const AGENT_TOOL = "agent_tool";
52
+ /**
53
+ * The agent's own tools a role may grant. `sandbox`: the shell and file tools in the agent's
54
+ * sandbox, copying a file the caller may read into it, and calling an ontology tool with arguments
55
+ * from a file in it. `web`: fetching pages from the domains the agent's configuration lists. The
56
+ * agent's configuration says which of them the agent has; the roles say which caller gets them.
57
+ */
58
+ export const AGENT_TOOL_VERBS = ["sandbox", "web"];
59
+ /** `agent_tool:sandbox`. */
60
+ export function agentToolPermission(tool) {
61
+ return `${AGENT_TOOL}:${tool}`;
62
+ }
44
63
  /** The built-in user's entity name in permissions. */
45
64
  const USER_ENTITY = "user";
46
65
  /**
@@ -167,9 +186,9 @@ function isUserAdministration(required) {
167
186
  !wildcardEntityCovers(USER_ENTITY, toSnakeCase(wanted.verb)));
168
187
  }
169
188
  /**
170
- * Feedback, the agent's held replies and the workspace's code always need named grants, including
171
- * for pipeline workloads: nothing a pipeline runs approves a reply to a person or reads the code it
172
- * runs from. The workspace's own pipeline code reads sign-in identities, for example to address a
189
+ * Feedback, the agent's held replies, the workspace's code and the agent's own tools always need
190
+ * named grants, including for pipeline workloads: nothing a pipeline runs approves a reply to a
191
+ * person, reads the code it runs from or uses the agent's tools. The workspace's own pipeline code reads sign-in identities, for example to address a
173
192
  * member in a chat, but nothing it runs writes them: only the platform does.
174
193
  */
175
194
  function workloadWildcardCovers(required) {
@@ -179,12 +198,12 @@ function workloadWildcardCovers(required) {
179
198
  }
180
199
  return (!isUserAdministration(required) &&
181
200
  (wanted === undefined ||
182
- !["app_feedback", "app_feedback_file", "agent_review", WORKSPACE_SOURCE].includes(toSnakeCase(wanted.entity))));
201
+ !["app_feedback", "app_feedback_file", "agent_review", WORKSPACE_SOURCE, AGENT_TOOL].includes(toSnakeCase(wanted.entity))));
183
202
  }
184
203
  /**
185
204
  * Whether the principal may do what `required` names: one of its permissions equals it, or covers it
186
205
  * through a wildcard. Workload wildcards exclude user administration, feedback, the agent's held
187
- * replies, the workspace's code and writes of sign-in identities.
206
+ * replies, the workspace's code, the agent's own tools and writes of sign-in identities.
188
207
  */
189
208
  export function isAllowed(required, principal) {
190
209
  return (
@@ -295,3 +314,29 @@ export function rolesGranting(roles, required) {
295
314
  .filter((candidate) => isAllowed(required, { permissions: candidate.permissions ?? [] }))
296
315
  .map((candidate) => candidate.name);
297
316
  }
317
+ /** Whether a role's permission names an agent tool: `agent_tool:<tool>` or `agent_tool:*`. */
318
+ function namesAgentTool(permission) {
319
+ const parsed = parsePermission(permission);
320
+ return parsed !== undefined && toSnakeCase(parsed.entity) === AGENT_TOOL;
321
+ }
322
+ /**
323
+ * Whether one of the ontology's roles, `member` and the roles sign-up gives included, names an agent
324
+ * tool. Only then do the roles alone decide who gets the agent's tools.
325
+ */
326
+ export function namesAgentTools(roles) {
327
+ // `check` reads authored roles, whose permissions may not be a list yet.
328
+ return roles.some((candidate) => Array.isArray(candidate.permissions) && candidate.permissions.some(namesAgentTool));
329
+ }
330
+ /**
331
+ * The agent's own tools a caller holds, as the ontology tells the agent whom it acts for: each of
332
+ * {@link AGENT_TOOL_VERBS} whose `agent_tool:<tool>` the caller's current permissions grant, in
333
+ * that order. `roles` are the ontology's roles.
334
+ */
335
+ export function agentToolsOf(roles, holder) {
336
+ // @legacy ontology.implicit-agent-sandbox
337
+ // Until a role names an agent tool, every caller has the sandbox, as before they were permissions.
338
+ if (!namesAgentTools(roles)) {
339
+ return ["sandbox"];
340
+ }
341
+ return AGENT_TOOL_VERBS.filter((tool) => isAllowed(agentToolPermission(tool), holder));
342
+ }
@@ -6,7 +6,11 @@ export declare const DEFAULT_AGENT_LIMITS: AgentLimits;
6
6
  /** Platform ceilings. Workspace policy can only lower these values. */
7
7
  export declare const PLATFORM_CHANNEL_LIMITS: AgentLimits;
8
8
  export declare function clampChannelLimits(input: ResolveIdentityInput["limits"]): AgentLimits;
9
- /** Only trusted runtimes submit limits; channel-app callers omit them and reuse the latest policy. */
9
+ /**
10
+ * Only trusted runtimes submit limits; channel-app callers omit them and reuse the latest policy.
11
+ * The agent sends guest limits only from its web channel, so limits without `guest` keep the guest
12
+ * limits stored before.
13
+ */
10
14
  export declare function effectiveChannelLimits(sql: SqlClient.SqlClient, input?: ResolveIdentityInput["limits"]): Effect.Effect<AgentLimits, never, never>;
11
15
  type Limited = Extract<AgentResolution, {
12
16
  status: "limited";
@@ -6,6 +6,7 @@ export const DEFAULT_AGENT_LIMITS = Object.freeze({
6
6
  perSender: Object.freeze({ turnsPerMinute: 6, turnsPerDay: 80 }),
7
7
  newUsersPerHour: 30,
8
8
  workspaceTurnsPerDay: 3000,
9
+ guest: Object.freeze({ turnsPerDay: 20, workspaceTurnsPerDay: 1000 }),
9
10
  });
10
11
  /** Platform ceilings. Workspace policy can only lower these values. */
11
12
  export const PLATFORM_CHANNEL_LIMITS = DEFAULT_AGENT_LIMITS;
@@ -13,6 +14,11 @@ const Limits = Schema.Struct({
13
14
  perSender: Schema.Struct({ turnsPerMinute: Schema.Int, turnsPerDay: Schema.Int }),
14
15
  newUsersPerHour: Schema.Int,
15
16
  workspaceTurnsPerDay: Schema.Int,
17
+ // Absent from limits an SDK before guests kept.
18
+ guest: Schema.optionalKey(Schema.Struct({
19
+ turnsPerDay: Schema.optionalKey(Schema.Int),
20
+ workspaceTurnsPerDay: Schema.optionalKey(Schema.Int),
21
+ })),
16
22
  });
17
23
  export function clampChannelLimits(input) {
18
24
  const clamp = (value, ceiling) => Number.isSafeInteger(value) && value > 0 ? Math.min(value, ceiling) : ceiling;
@@ -23,21 +29,30 @@ export function clampChannelLimits(input) {
23
29
  },
24
30
  newUsersPerHour: clamp(input?.newUsersPerHour, PLATFORM_CHANNEL_LIMITS.newUsersPerHour),
25
31
  workspaceTurnsPerDay: clamp(input?.workspaceTurnsPerDay, PLATFORM_CHANNEL_LIMITS.workspaceTurnsPerDay),
32
+ guest: {
33
+ turnsPerDay: clamp(input?.guest?.turnsPerDay, PLATFORM_CHANNEL_LIMITS.guest.turnsPerDay),
34
+ workspaceTurnsPerDay: clamp(input?.guest?.workspaceTurnsPerDay, PLATFORM_CHANNEL_LIMITS.guest.workspaceTurnsPerDay),
35
+ },
26
36
  };
27
37
  }
28
- /** Only trusted runtimes submit limits; channel-app callers omit them and reuse the latest policy. */
38
+ /**
39
+ * Only trusted runtimes submit limits; channel-app callers omit them and reuse the latest policy.
40
+ * The agent sends guest limits only from its web channel, so limits without `guest` keep the guest
41
+ * limits stored before.
42
+ */
29
43
  export function effectiveChannelLimits(sql, input) {
30
44
  return Effect.gen(function* () {
45
+ const [stored] = yield* sql.unsafe(`SELECT "limits" FROM "${CHANNEL_LIMITS_TABLE}" WHERE "id"`);
46
+ const kept = stored === undefined ? undefined : Schema.decodeUnknownSync(Limits)(stored.limits);
31
47
  if (input !== undefined) {
32
- const limits = clampChannelLimits(input);
48
+ const limits = clampChannelLimits(input.guest === undefined && kept?.guest !== undefined
49
+ ? { ...input, guest: kept.guest }
50
+ : input);
33
51
  yield* sql.unsafe(`INSERT INTO "${CHANNEL_LIMITS_TABLE}" ("id", "limits") VALUES (true, $1::jsonb)
34
52
  ON CONFLICT ("id") DO UPDATE SET "limits" = EXCLUDED."limits"`, [JSON.stringify(limits)]);
35
53
  return limits;
36
54
  }
37
- const [stored] = yield* sql.unsafe(`SELECT "limits" FROM "${CHANNEL_LIMITS_TABLE}" WHERE "id"`);
38
- return stored === undefined
39
- ? DEFAULT_AGENT_LIMITS
40
- : clampChannelLimits(Schema.decodeUnknownSync(Limits)(stored.limits));
55
+ return kept === undefined ? DEFAULT_AGENT_LIMITS : clampChannelLimits(kept);
41
56
  }).pipe(Effect.orDie);
42
57
  }
43
58
  const Counter = Schema.Struct({ count: Schema.Int, retry_after: Schema.Int });
@@ -2,15 +2,18 @@ import { Effect } from "effect";
2
2
  import type { SqlClient } from "effect/unstable/sql";
3
3
  import type { Ontology } from "../ontology.js";
4
4
  import type { AgentResolution, AgentWebStore } from "../service/runtime-contract.js";
5
- /**
6
- * Agent tokens in the ontology's OAuth tables, as channel sessions are: one standing grant per
7
- * member and resource for the first-party client `agent-web`, and a new access token on each
8
- * request. Blocking or deactivating the member revokes the grant with every other one of theirs.
9
- */
10
- /** How many new website visitors one network address may start an hour. */
5
+ /** How many new website visitors one network address may sign up an hour. */
11
6
  export declare const VISITORS_PER_CLIENT_PER_HOUR = 10;
7
+ /** How many new guests one network address may start an hour. */
8
+ export declare const GUESTS_PER_CLIENT_PER_HOUR = 10;
12
9
  export interface AgentWebAdmission {
13
10
  /** Admits a new visitor on `web` as `signUp` admits a channel account: their user, or why not. */
14
11
  readonly signUp: (visitorId: string) => Effect.Effect<AgentResolution>;
15
12
  }
13
+ /**
14
+ * Agent tokens in the ontology's OAuth tables, as channel sessions are: one standing grant per
15
+ * member and resource for the first-party client `agent-web`, and a new access token on each
16
+ * request. Blocking or deactivating the member revokes the grant with every other one of theirs.
17
+ * A guest's grant names no user: its id is the guest's, and it lives while its refresh token does.
18
+ */
16
19
  export declare function sqlAgentWebStore(ontology: Ontology, sql: SqlClient.SqlClient, admission: AgentWebAdmission): AgentWebStore;
@@ -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>;