@segmentstream/ontology 0.95.0 → 0.97.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 (44) hide show
  1. package/README.md +39 -4
  2. package/dist/analyze.d.ts +23 -3
  3. package/dist/analyze.js +431 -17
  4. package/dist/authoring.js +3 -0
  5. package/dist/bin/check.js +2 -0
  6. package/dist/diagnostics.d.ts +3 -3
  7. package/dist/diagnostics.js +2 -0
  8. package/dist/index.d.ts +5 -3
  9. package/dist/index.js +3 -2
  10. package/dist/manifest.d.ts +607 -20
  11. package/dist/manifest.js +96 -4
  12. package/dist/migrate/apply.js +5 -1
  13. package/dist/migrate/model.d.ts +332 -12
  14. package/dist/migrate/storage.js +2 -0
  15. package/dist/ontology.d.ts +5 -2
  16. package/dist/ontology.js +1 -0
  17. package/dist/runtime/member-tables.d.ts +7 -2
  18. package/dist/runtime/member-tables.js +18 -3
  19. package/dist/runtime/new-user-hook.d.ts +11 -1
  20. package/dist/runtime/new-user-hook.js +69 -29
  21. package/dist/runtime/pipeline.d.ts +2 -0
  22. package/dist/runtime/pipeline.js +11 -3
  23. package/dist/runtime/principals.d.ts +13 -0
  24. package/dist/runtime/principals.js +98 -28
  25. package/dist/runtime/resolve-agent-identity.js +43 -12
  26. package/dist/runtime/service-binding.js +10 -4
  27. package/dist/service/catalog.js +10 -1
  28. package/dist/service/chat/envelope.d.ts +16 -16
  29. package/dist/service/connections.js +1 -0
  30. package/dist/service/discovery-search.d.ts +1 -1
  31. package/dist/service/mcp/server.js +13 -1
  32. package/dist/service/mcp/tools.d.ts +5 -0
  33. package/dist/service/mcp/tools.js +30 -0
  34. package/dist/service/operations.d.ts +3 -1
  35. package/dist/service/operations.js +3 -0
  36. package/dist/service/schemas.d.ts +74 -0
  37. package/dist/service/toolsets.d.ts +49 -0
  38. package/dist/service/toolsets.js +284 -0
  39. package/dist/sign-in.d.ts +32 -1
  40. package/dist/sign-in.js +12 -1
  41. package/dist/toolset.d.ts +141 -0
  42. package/dist/toolset.js +154 -0
  43. package/dist/user-identity.d.ts +1 -1
  44. package/package.json +1 -1
@@ -1,37 +1,77 @@
1
1
  import { Cause, Effect } from "effect";
2
2
  import { SqlClient } from "effect/unstable/sql";
3
3
  import { CHANNEL_USERS_TABLE } from "../migrate/storage.js";
4
+ import { FEEDBACK_REPORTER_ROLE, MEMBER_ROLE } from "../names.js";
4
5
  import { permissionsOf, principalScopes } from "../permissions.js";
6
+ import { signUpPending } from "./member-tables.js";
5
7
  import { runAction } from "./pipeline.js";
6
- /** Runs after admission commits, before a model turn or channel-app session. True means retry pending. */
8
+ /**
9
+ * Runs after admission commits, before a model turn or app session. True means retry pending.
10
+ * A user `signUp` created runs `onSignUp` with the roles they hold; a user an open
11
+ * `signIn.channels` created runs `onNewUser` with only `member`. Workload authority never applies.
12
+ */
7
13
  export function runNewUserHook(ontology, sql, principal) {
8
- const hook = ontology.signIn.onNewUser;
9
- if (hook === undefined) {
10
- return Effect.succeed(false);
14
+ return Effect.gen(function* () {
15
+ const [lifecycle] = yield* sql.unsafe(`SELECT to_jsonb("c") ->> 'signed_up' AS "signed_up" FROM "${CHANNEL_USERS_TABLE}" AS "c"
16
+ WHERE "c"."user_id" = $1::uuid`, [principal.id]);
17
+ const signedUp = lifecycle?.signed_up === "true";
18
+ // @legacy ontology.legacy-channel-admission
19
+ const hook = signedUp ? ontology.signIn.onSignUp : ontology.signIn.onNewUser;
20
+ if (hook === undefined) {
21
+ return false;
22
+ }
23
+ const declared = new Set(ontology.roles.map((candidate) => candidate.name));
24
+ const roles = signedUp
25
+ ? principal.roles.filter((role) => declared.has(role) && role !== MEMBER_ROLE && role !== FEEDBACK_REPORTER_ROLE)
26
+ : [MEMBER_ROLE];
27
+ const [entity, action] = hook.split(":");
28
+ yield* runAction(ontology, {
29
+ entity: entity,
30
+ action: action,
31
+ input: {},
32
+ principal: {
33
+ id: principal.id,
34
+ kind: "member",
35
+ ...(principal.authenticatedVia === undefined
36
+ ? {}
37
+ : { authenticatedVia: principal.authenticatedVia }),
38
+ roles,
39
+ permissions: permissionsOf(ontology.roles, roles),
40
+ ...principalScopes(ontology.roles, roles),
41
+ },
42
+ options: { newUserHook: true, ...(signedUp ? { signUpHook: true } : {}) },
43
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.flatMap((outcome) => outcome.validation.ok ? Effect.void : Effect.die(new Error("Invalid onboarding input."))), Effect.catchCause((cause) => Effect.logWarning("ontology.channel.on_new_user_pending", Cause.pretty(cause)
44
+ .replace(/(postgres(?:ql)?:\/\/[^:\s]+:)[^@\s]+@/gi, "$1[redacted]@")
45
+ .replace(/Bearer\s+[^\s"']+/gi, "Bearer [redacted]")
46
+ .replace(/\b(?:sso|ssr|ssc|sss|ssk|ssw)_[A-Za-z0-9_-]+/g, "[redacted]")).pipe(Effect.annotateLogs({
47
+ operation: "ontology.channel.on_new_user",
48
+ userId: principal.id,
49
+ action: hook,
50
+ }))));
51
+ const [stored] = yield* sql.unsafe(`SELECT "on_new_user_completed_at" IS NULL AS "pending" FROM "${CHANNEL_USERS_TABLE}" AS "c"
52
+ WHERE "c"."user_id" = $1::uuid
53
+ AND (COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true'
54
+ OR "c"."created_via" NOT IN ('invite', 'email'))`, [principal.id]);
55
+ return stored?.pending ?? false;
56
+ }).pipe(Effect.orDie);
57
+ }
58
+ /**
59
+ * The federation store, running a signed-up user's pending `onSignUp` once they enroll through a
60
+ * SegmentStream account and on each later federated request until it completes.
61
+ */
62
+ export function withSignUpOnboarding(ontology, sql, store) {
63
+ if (ontology.signIn.onSignUp === undefined) {
64
+ return store;
11
65
  }
12
- const [entity, action] = hook.split(":");
13
- return runAction(ontology, {
14
- entity: entity,
15
- action: action,
16
- input: {},
17
- principal: {
18
- id: principal.id,
19
- kind: "member",
20
- ...(principal.authenticatedVia === undefined
21
- ? {}
22
- : { authenticatedVia: principal.authenticatedVia }),
23
- roles: ["member"],
24
- permissions: permissionsOf(ontology.roles, ["member"]),
25
- ...principalScopes(ontology.roles, ["member"]),
26
- },
27
- options: { newUserHook: true },
28
- }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.flatMap((outcome) => outcome.validation.ok ? Effect.void : Effect.die(new Error("Invalid onNewUser input."))), Effect.catchCause((cause) => Effect.logWarning("ontology.channel.on_new_user_pending", Cause.pretty(cause)
29
- .replace(/(postgres(?:ql)?:\/\/[^:\s]+:)[^@\s]+@/gi, "$1[redacted]@")
30
- .replace(/Bearer\s+[^\s"']+/gi, "Bearer [redacted]")
31
- .replace(/\b(?:sso|ssr|ssc|sss|ssk|ssw)_[A-Za-z0-9_-]+/g, "[redacted]")).pipe(Effect.annotateLogs({
32
- operation: "ontology.channel.on_new_user",
33
- userId: principal.id,
34
- action: hook,
35
- }))), Effect.andThen(sql.unsafe(`SELECT "on_new_user_completed_at" IS NULL AS "pending" FROM "${CHANNEL_USERS_TABLE}"
36
- WHERE "user_id" = $1::uuid AND "created_via" NOT IN ('invite', 'email')`, [principal.id])), Effect.map(([stored]) => stored?.pending ?? false), Effect.orDie);
66
+ const onboard = (principal) => principal === undefined || principal.kind !== "member"
67
+ ? Effect.succeed(principal)
68
+ : signUpPending(sql, principal.id).pipe(Effect.flatMap((pending) => pending ? runNewUserHook(ontology, sql, principal) : Effect.void), Effect.as(principal), Effect.orDie);
69
+ return {
70
+ ...store,
71
+ identity: (issuer, subject) => store.identity(issuer, subject).pipe(Effect.flatMap(onboard)),
72
+ principal: (id) => store.principal(id).pipe(Effect.flatMap(onboard)),
73
+ ...(store.enroll === undefined
74
+ ? {}
75
+ : { enroll: (claims) => store.enroll(claims).pipe(Effect.flatMap(onboard)) }),
76
+ };
37
77
  }
@@ -43,6 +43,8 @@ export interface ActionRequest<R = never> {
43
43
  readonly createIntent?: string;
44
44
  /** Internal channel lifecycle execution; marker commits atomically with the handler. */
45
45
  readonly newUserHook?: true;
46
+ /** With `newUserHook`: the hook is `onSignUp`, for a user sign-up created. */
47
+ readonly signUpHook?: true;
46
48
  /**
47
49
  * Describe what a person confirms before the action runs, in the chat's language, with the
48
50
  * action's `confirm`: decode the input, check the permission, and answer with the confirmation,
@@ -190,8 +190,11 @@ export function runAction(ontology, request) {
190
190
  yield* Effect.sync(() => requireDeploymentCapability(deployment, "connections"));
191
191
  }
192
192
  const newUserHook = request.options?.newUserHook === true;
193
+ const qualifiedHook = `${request.entity}:${request.action}`;
194
+ const signUpHook = newUserHook && request.options?.signUpHook === true;
193
195
  if (newUserHook &&
194
- (ontology.signIn.onNewUser !== `${request.entity}:${request.action}` ||
196
+ // @legacy ontology.legacy-channel-admission
197
+ ((signUpHook ? ontology.signIn.onSignUp : ontology.signIn.onNewUser) !== qualifiedHook ||
195
198
  action.prepare !== undefined ||
196
199
  action.connections.length > 0 ||
197
200
  action.hints?.idempotent !== true ||
@@ -416,9 +419,14 @@ export function runAction(ontology, request) {
416
419
  yield* sql.unsafe(`SELECT "id" FROM "${USER_TABLE}" WHERE "id" = $1::uuid FOR UPDATE`, [
417
420
  request.principal.id,
418
421
  ]);
422
+ // `onSignUp` runs for users sign-up created; `onNewUser` for those an open
423
+ // `signIn.channels` created.
419
424
  const [pending] = yield* sql.unsafe(`SELECT 1 FROM "${CHANNEL_USERS_TABLE}" c JOIN "${USER_TABLE}" u ON u."id" = c."user_id"
420
- WHERE c."user_id" = $1::uuid AND c."created_via" NOT IN ('invite', 'email')
421
- AND c."blocked_at" IS NULL AND c."on_new_user_completed_at" IS NULL AND u."active" FOR UPDATE OF c`, [request.principal.id]);
425
+ WHERE c."user_id" = $1::uuid
426
+ AND CASE WHEN $2 THEN COALESCE(to_jsonb(c) ->> 'signed_up', 'false') = 'true'
427
+ ELSE COALESCE(to_jsonb(c) ->> 'signed_up', 'false') <> 'true'
428
+ AND c."created_via" NOT IN ('invite', 'email') END
429
+ AND c."blocked_at" IS NULL AND c."on_new_user_completed_at" IS NULL AND u."active" FOR UPDATE OF c`, [request.principal.id, signUpHook]);
422
430
  if (pending === undefined) {
423
431
  return null;
424
432
  }
@@ -66,6 +66,11 @@ export declare const MEMBER_HISTORY_ACTIONS: {
66
66
  export interface PrincipalRolesSql {
67
67
  readonly unsafe: (text: string, args: ReadonlyArray<unknown>) => Effect.Effect<ReadonlyArray<Readonly<Record<string, unknown>>>, SqlError>;
68
68
  }
69
+ /**
70
+ * The principal of a user with their current roles. An active member holds `member` beside their
71
+ * assigned roles, unless `signUp` created them: they hold exactly what sign-up and later grants
72
+ * gave them. A service holds exactly the roles it was given.
73
+ */
69
74
  export declare function rolesOf(ontology: Ontology, sql: PrincipalRolesSql, user: UserRow): Effect.Effect<Principal, SqlError>;
70
75
  /** Resolve a workspace-owned identity/session by user id, with current activity and roles. */
71
76
  export declare function resolvePrincipalById(ontology: Ontology, sql: SqlClient.SqlClient, id: string): Effect.Effect<Principal, SqlError | PrincipalRejected, never>;
@@ -78,6 +83,14 @@ export declare function resolvePrincipalById(ontology: Ontology, sql: SqlClient.
78
83
  * deferred to a later request instead of delaying authentication. Inactive users are rejected.
79
84
  */
80
85
  export declare function resolvePrincipalByIdentity(ontology: Ontology, claims: IdentityClaims): Effect.Effect<Principal, PrincipalRejected, SqlClient.SqlClient>;
86
+ /**
87
+ * {@link resolvePrincipalByIdentity}, and whether the user email sign-up created still waits for
88
+ * `onSignUp`. The caller runs it once nothing else holds a transaction; see `runNewUserHook`.
89
+ */
90
+ export declare function resolveSignInState(ontology: Ontology, claims: IdentityClaims): Effect.Effect<{
91
+ readonly principal: Principal;
92
+ readonly signUpPending: boolean;
93
+ }, PrincipalRejected, SqlClient.SqlClient>;
81
94
  /** Resolve the workspace's stable keyless pipeline service, without customer roles or sign-in. */
82
95
  export declare function resolvePipelineWorker(ontology: Ontology, execution: WorkloadExecution): Effect.Effect<Principal, PrincipalRejected, SqlClient.SqlClient>;
83
96
  /** A keyless hook actor with only the workspace's opted-in role; deactivated actors stay inactive. */
@@ -8,7 +8,7 @@ import { entity, } from "../entity.js";
8
8
  import { AGENT_IDENTITIES_TABLE, CHANNEL_USERS_TABLE, API_KEYS_TABLE, USER_ROLES_TABLE, USER_TABLE, } from "../migrate/storage.js";
9
9
  import { MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, toSnakeCase } from "../names.js";
10
10
  import { feedbackRoles } from "../feedback-config.js";
11
- import { buildManifest } from "../manifest.js";
11
+ import { buildManifest, signUpRolesOf, } from "../manifest.js";
12
12
  import { buildOntology } from "../ontology.js";
13
13
  import { EXPLICIT_GRANT_ENTITIES, permissionsOf, principalScopes, WILDCARD_ENTITY_VERBS, } from "../permissions.js";
14
14
  import { EMAIL_PATTERN } from "../property.js";
@@ -97,34 +97,87 @@ export const MEMBER_HISTORY_ACTIONS = {
97
97
  deactivate: "user.deactivate",
98
98
  reactivate: "user.reactivate",
99
99
  };
100
+ /** Clients whose database has `_channel_users`. It is never dropped, so only presence is kept. */
101
+ const channelUsersPresent = new WeakMap();
102
+ /**
103
+ * The user's assigned roles, in order, and whether `signUp` created them. A database last migrated
104
+ * by an earlier SDK may lack `_channel_users`, or its `signed_up` column: nobody signed up there.
105
+ */
106
+ function storedRoles(sql, userId) {
107
+ return Effect.gen(function* () {
108
+ if (!channelUsersPresent.has(sql)) {
109
+ // @legacy ontology.pre-upgrade-database-tolerance
110
+ const [table] = yield* sql.unsafe(`SELECT to_regclass($1) IS NOT NULL AS "present"`, [
111
+ CHANNEL_USERS_TABLE,
112
+ ]);
113
+ if (table?.present !== true) {
114
+ const rows = yield* sql.unsafe(`SELECT "role" FROM "${USER_ROLES_TABLE}" WHERE "user_id" = $1::uuid ORDER BY "role"`, [userId]);
115
+ return {
116
+ roles: rows.map((row) => String(row.role)),
117
+ signedUp: false,
118
+ onboardingPending: false,
119
+ };
120
+ }
121
+ channelUsersPresent.set(sql, true);
122
+ }
123
+ const rows = yield* sql.unsafe(`SELECT "role", NULL AS "signed_up", NULL AS "pending" FROM "${USER_ROLES_TABLE}"
124
+ WHERE "user_id" = $1::uuid
125
+ UNION ALL
126
+ SELECT NULL, to_jsonb("c") ->> 'signed_up',
127
+ ("c"."on_new_user_completed_at" IS NULL AND "c"."blocked_at" IS NULL)::text
128
+ FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid
129
+ ORDER BY 1`, [userId]);
130
+ const lifecycle = rows.find((row) => row.role === null || row.role === undefined);
131
+ const signedUp = lifecycle?.signed_up === "true";
132
+ return {
133
+ roles: rows.flatMap((row) => (typeof row.role === "string" ? [row.role] : [])),
134
+ signedUp,
135
+ onboardingPending: signedUp && lifecycle?.pending === "true",
136
+ };
137
+ });
138
+ }
139
+ /**
140
+ * The principal of a user with their current roles. An active member holds `member` beside their
141
+ * assigned roles, unless `signUp` created them: they hold exactly what sign-up and later grants
142
+ * gave them. A service holds exactly the roles it was given.
143
+ */
100
144
  export function rolesOf(ontology, sql, user) {
145
+ return principalState(ontology, sql, user).pipe(Effect.map((state) => state.principal));
146
+ }
147
+ /** {@link rolesOf}, and whether a user sign-up created still waits for its `onSignUp` action. */
148
+ function principalState(ontology, sql, user) {
101
149
  return Effect.gen(function* () {
102
- const rows = yield* sql.unsafe(`SELECT "role" FROM "${USER_ROLES_TABLE}" WHERE "user_id" = $1::uuid ORDER BY "role"`, [user.id]);
150
+ const stored = yield* storedRoles(sql, user.id);
103
151
  // Ignore forged or historical stored assignments: reporter authority is never persisted.
104
- const assigned = rows
105
- .map((row) => String(row.role))
106
- .filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE);
107
- // Every active member holds `member`; a service holds exactly the roles it was given.
108
- const roles = user.kind === "member"
109
- ? [
110
- MEMBER_ROLE,
111
- ...assigned.filter((role) => role !== MEMBER_ROLE),
112
- ...(ontology.roles.some((role) => role.name === FEEDBACK_REPORTER_ROLE)
113
- ? [FEEDBACK_REPORTER_ROLE]
114
- : []),
115
- ]
116
- : assigned;
152
+ const assigned = stored.roles.filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE);
153
+ const roles = user.kind === "member" && stored.signedUp
154
+ ? assigned.filter((role) => role !== MEMBER_ROLE)
155
+ : user.kind === "member"
156
+ ? [
157
+ MEMBER_ROLE,
158
+ ...assigned.filter((role) => role !== MEMBER_ROLE),
159
+ ...(ontology.roles.some((role) => role.name === FEEDBACK_REPORTER_ROLE)
160
+ ? [FEEDBACK_REPORTER_ROLE]
161
+ : []),
162
+ ]
163
+ : assigned;
117
164
  // A role the deployed ontology no longer declares grants nothing.
118
165
  return {
119
- id: user.id,
120
- kind: user.kind,
121
- roles,
122
- permissions: permissionsOf(ontology.roles, roles),
123
- ...principalScopes(ontology.roles, roles),
166
+ principal: {
167
+ id: user.id,
168
+ kind: user.kind,
169
+ roles,
170
+ permissions: permissionsOf(ontology.roles, roles),
171
+ ...principalScopes(ontology.roles, roles),
172
+ },
173
+ signUpPending: user.kind === "member" && stored.onboardingPending,
124
174
  };
125
175
  });
126
176
  }
127
177
  function activePrincipal(ontology, sql, user) {
178
+ return activePrincipalState(ontology, sql, user).pipe(Effect.map((state) => state.principal));
179
+ }
180
+ function activePrincipalState(ontology, sql, user) {
128
181
  return Effect.gen(function* () {
129
182
  if (!user.active || (user.kind === "member" && (yield* isMemberBlocked(sql, user.id)))) {
130
183
  return yield* new PrincipalRejected({
@@ -132,7 +185,7 @@ function activePrincipal(ontology, sql, user) {
132
185
  message: "The user is inactive.",
133
186
  });
134
187
  }
135
- return yield* rolesOf(ontology, sql, user);
188
+ return yield* principalState(ontology, sql, user);
136
189
  });
137
190
  }
138
191
  function userRow(record) {
@@ -303,7 +356,10 @@ function signIn(ontology, sql, claims) {
303
356
  yield* recordIdentity(String(invited.id), "invite");
304
357
  return userRow(linkedUser);
305
358
  }
306
- if (ontology.signIn.policy !== "open") {
359
+ // `signUp` with `email` creates a user holding its roles; `policy: "open"` one holding member.
360
+ const signUpRoles = signUpRolesOf(ontology.manifest, "email");
361
+ // @legacy ontology.legacy-channel-admission
362
+ if (signUpRoles === undefined && ontology.signIn.policy !== "open") {
307
363
  return yield* new PrincipalRejected({
308
364
  reason: "not_invited",
309
365
  message: "No member was invited with this identity or email.",
@@ -317,7 +373,12 @@ function signIn(ontology, sql, claims) {
317
373
  identity_subject: claims.identitySubject,
318
374
  ...signedIn,
319
375
  });
320
- yield* recordUserCreation(sql, String(created.id), "email");
376
+ yield* recordUserCreation(sql, String(created.id), "email", signUpRoles !== undefined);
377
+ if (signUpRoles !== undefined && signUpRoles.length > 0) {
378
+ yield* platformRuntime(ontology, sql, MEMBER_HISTORY_ACTIONS.grantRoles)
379
+ .members.grantRoles({ id: String(created.id), roles: signUpRoles })
380
+ .pipe(Effect.orDie);
381
+ }
321
382
  yield* recordIdentity(String(created.id), "sign_in");
322
383
  return userRow(created);
323
384
  }));
@@ -332,6 +393,13 @@ function signIn(ontology, sql, claims) {
332
393
  * deferred to a later request instead of delaying authentication. Inactive users are rejected.
333
394
  */
334
395
  export function resolvePrincipalByIdentity(ontology, claims) {
396
+ return resolveSignInState(ontology, claims).pipe(Effect.map((state) => state.principal));
397
+ }
398
+ /**
399
+ * {@link resolvePrincipalByIdentity}, and whether the user email sign-up created still waits for
400
+ * `onSignUp`. The caller runs it once nothing else holds a transaction; see `runNewUserHook`.
401
+ */
402
+ export function resolveSignInState(ontology, claims) {
335
403
  return Effect.gen(function* () {
336
404
  const sql = yield* SqlClient.SqlClient;
337
405
  const attempt = signIn(ontology, sql, claims);
@@ -340,7 +408,7 @@ export function resolvePrincipalByIdentity(ontology, claims) {
340
408
  reason: "identity_conflict",
341
409
  message: "The sign-in conflicts with another user.",
342
410
  }))));
343
- return yield* activePrincipal(ontology, sql, user);
411
+ return yield* activePrincipalState(ontology, sql, user);
344
412
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
345
413
  }
346
414
  /** Resolve the workspace's stable keyless pipeline service, without customer roles or sign-in. */
@@ -1094,16 +1162,18 @@ export function checkSignIn(ontology, email) {
1094
1162
  : `("u"."identity_provider" = $2 AND "u"."identity_subject" IS NOT NULL)`;
1095
1163
  const [row] = yield* sql.unsafe(`SELECT "u"."id"::text AS "id", "u"."active" AS "active", ${neonAuth} AS "neon_auth" ` +
1096
1164
  `FROM "${USER_TABLE}" AS "u" WHERE "u"."kind" = 'member' AND "u"."email" = $1 LIMIT 1`, [address, NEON_AUTH_PROVIDER]);
1165
+ // Anyone may sign in where email is open to sign-up, so the answer reveals nothing.
1166
+ const open = signUpRolesOf(ontology.manifest, "email") !== undefined ||
1167
+ // @legacy ontology.legacy-channel-admission
1168
+ ontology.signIn.policy === "open";
1097
1169
  if (row === undefined) {
1098
- return ontology.signIn.policy === "open"
1099
- ? { allowed: true, method: "link" }
1100
- : { allowed: false };
1170
+ return open ? { allowed: true, method: "link" } : { allowed: false };
1101
1171
  }
1102
1172
  const member = decodeSignInRow(row);
1103
1173
  if (yield* isMemberBlocked(sql, member.id)) {
1104
1174
  return { allowed: false };
1105
1175
  }
1106
- if (ontology.signIn.policy === "open") {
1176
+ if (open) {
1107
1177
  return { allowed: true, method: "link" };
1108
1178
  }
1109
1179
  if (!member.active) {
@@ -2,11 +2,11 @@ import { randomUUID } from "node:crypto";
2
2
  import { Effect, Option, Schema } from "effect";
3
3
  import { isSqlError } from "effect/unstable/sql/SqlError";
4
4
  import { Conflict } from "../errors.js";
5
- import { channelPolicyOf } from "../manifest.js";
5
+ import { channelPolicyOf, signUpRolesOf } from "../manifest.js";
6
6
  import { AGENT_IDENTITIES_TABLE, CHANNEL_USERS_TABLE } from "../migrate/storage.js";
7
7
  import { countAgentAttempt, effectiveChannelLimits } from "./agent-counters.js";
8
8
  import { runNewUserHook } from "./new-user-hook.js";
9
- import { makePrincipalUserWriter } from "./sql-runtime.js";
9
+ import { makeOntologyRuntime, makePrincipalUserWriter } from "./sql-runtime.js";
10
10
  import { makeIdentityWriter, USER_IDENTITY_TABLE } from "./user-identities.js";
11
11
  class RegistrationCapped extends Schema.TaggedError()("RegistrationCapped", {
12
12
  limit: Schema.Int,
@@ -23,6 +23,8 @@ function uniqueFailure(error) {
23
23
  /** Account admission shares pairing's lock and creates User plus identity in one transaction. */
24
24
  export function resolveAgentIdentity(ontology, sql, store, input, context = "agent") {
25
25
  const contact = input.turn || context === "channel_app";
26
+ // A channel `signUp` opens grants these roles; one an open `signIn.channels` opens grants member.
27
+ const signUpRoles = signUpRolesOf(ontology.manifest, input.provider);
26
28
  const policy = effectiveChannelLimits(sql, input.limits);
27
29
  const account = `${input.provider}:${input.externalId}`;
28
30
  const attempt = sql.withTransaction(Effect.gen(function* () {
@@ -36,7 +38,9 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
36
38
  if (identity === undefined) {
37
39
  if (!contact ||
38
40
  input.chat !== "private" ||
39
- channelPolicyOf(ontology.manifest, input.provider) !== "open") {
41
+ // @legacy ontology.legacy-channel-admission
42
+ (signUpRoles === undefined &&
43
+ channelPolicyOf(ontology.manifest, input.provider) !== "open")) {
40
44
  return { status: "pairing_required" };
41
45
  }
42
46
  const limited = yield* countAgentAttempt(sql, {
@@ -82,7 +86,23 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
82
86
  yield* sql.unsafe(`INSERT INTO "${AGENT_IDENTITIES_TABLE}"
83
87
  ("id", "provider", "external_id", "user_id", "display", "origin")
84
88
  VALUES ($1::uuid, $2, $3, $4::uuid, $5, 'provisioned')`, [identityId, input.provider, input.externalId, String(user.id), display]);
85
- yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via") VALUES ($1::uuid, $2)`, [String(user.id), input.provider]);
89
+ if (signUpRoles === undefined) {
90
+ // @legacy ontology.legacy-channel-admission
91
+ yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via") VALUES ($1::uuid, $2)`, [String(user.id), input.provider]);
92
+ }
93
+ else {
94
+ yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via", "signed_up")
95
+ VALUES ($1::uuid, $2, true)`, [String(user.id), input.provider]);
96
+ }
97
+ if (signUpRoles !== undefined && signUpRoles.length > 0) {
98
+ yield* makeOntologyRuntime(ontology, sql, {
99
+ action: "user.grant_roles",
100
+ actionId,
101
+ principalId: null,
102
+ })
103
+ .members.grantRoles({ id: String(user.id), roles: signUpRoles })
104
+ .pipe(Effect.orDie);
105
+ }
86
106
  created = true;
87
107
  identity = yield* store.findIdentity(input);
88
108
  }
@@ -90,8 +110,9 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
90
110
  return yield* Effect.die(new Error("Provisioning did not create an identity."));
91
111
  }
92
112
  const [lifecycle] = yield* sql.unsafe(`SELECT "created_via", "blocked_at" IS NOT NULL AS "blocked",
93
- "on_new_user_completed_at" IS NOT NULL AS "completed"
94
- FROM "${CHANNEL_USERS_TABLE}" WHERE "user_id" = $1::uuid`, [identity.userId]);
113
+ "on_new_user_completed_at" IS NOT NULL AS "completed",
114
+ COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up"
115
+ FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid`, [identity.userId]);
95
116
  if (lifecycle?.blocked) {
96
117
  return { status: "refused", reason: "blocked" };
97
118
  }
@@ -123,11 +144,18 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
123
144
  if (username !== undefined) {
124
145
  yield* sql.unsafe(`UPDATE "${AGENT_IDENTITIES_TABLE}" SET "username" = $2 WHERE "id" = $1::uuid`, [identity.id, username]);
125
146
  }
126
- const provisioned = lifecycle !== undefined && !["invite", "email"].includes(lifecycle.created_via);
127
- if (contact &&
128
- provisioned &&
129
- member.principal.roles.length === 1 &&
130
- member.principal.roles[0] === "member") {
147
+ const signedUp = lifecycle?.signed_up === true;
148
+ // Admitted by themselves rather than invited or paired: a channel account, or anyone sign-up
149
+ // created, including by email. The agent resolves such a user's deferred turns again.
150
+ const provisioned = signedUp ||
151
+ (lifecycle !== undefined && !["invite", "email"].includes(lifecycle.created_via));
152
+ // Everyone sign-up created is counted, whatever roles they hold later.
153
+ const counted = signedUp ||
154
+ // @legacy ontology.legacy-channel-admission
155
+ (provisioned &&
156
+ member.principal.roles.length === 1 &&
157
+ member.principal.roles[0] === "member");
158
+ if (contact && counted) {
131
159
  for (const [scope, subject, window] of [
132
160
  ["turnsPerMinute", identity.userId, "minute"],
133
161
  ["turnsPerDay", identity.userId, "day"],
@@ -154,7 +182,10 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
154
182
  (identity.noticedAt === null ||
155
183
  (input.noticeVersion !== undefined && identity.noticeVersion !== input.noticeVersion) ||
156
184
  (input.noticeSha256 !== undefined && identity.noticeSha256 !== input.noticeSha256)),
157
- onNewUserPending: provisioned && !lifecycle?.completed && ontology.signIn.onNewUser !== undefined,
185
+ onNewUserPending: provisioned &&
186
+ !lifecycle?.completed &&
187
+ // @legacy ontology.legacy-channel-admission
188
+ (signedUp ? ontology.signIn.onSignUp : ontology.signIn.onNewUser) !== undefined,
158
189
  };
159
190
  }));
160
191
  const admission = policy.pipe(Effect.andThen(attempt)).pipe(Effect.catchIf(uniqueFailure, () => attempt), Effect.catchTag("RegistrationCapped", ({ limit }) =>
@@ -19,8 +19,9 @@ import { generatedActions } from "./generated-actions.js";
19
19
  import { sqlChannelSessionStore } from "./channel-sessions.js";
20
20
  import { sqlOAuthStore } from "./oauth.js";
21
21
  import { sqlFederationStore } from "./federation.js";
22
+ import { runNewUserHook, withSignUpOnboarding } from "./new-user-hook.js";
22
23
  import { runAction } from "./pipeline.js";
23
- import { checkSignIn, resolveApiKeyCredential, resolvePrincipalByApiKey, resolvePrincipalByIdentity, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, } from "./principals.js";
24
+ import { checkSignIn, resolveApiKeyCredential, resolvePrincipalByApiKey, resolveSignInState, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, } from "./principals.js";
24
25
  import { postgresTls } from "./postgres-tls.js";
25
26
  import { makeOntologyRuntime } from "./sql-runtime.js";
26
27
  import { NEON_AUTH_PROVIDER, SIGN_IN_ORIGIN_SQL, USER_IDENTITY_TABLE, } from "./user-identity-sql.js";
@@ -206,12 +207,17 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
206
207
  AND i.origin::text IN ${SIGN_IN_ORIGIN_SQL} AND i.revoked_at IS NULL)`, [identity.email, NEON_AUTH_PROVIDER]);
207
208
  return neon ? yield* store.principal(neon.id) : undefined;
208
209
  }).pipe(Effect.orDie)
209
- : withSql(resolvePrincipalByIdentity(ontology, {
210
+ : withSql(resolveSignInState(ontology, {
210
211
  identityProvider: identity.provider,
211
212
  identitySubject: identity.subject,
212
213
  ...(identity.email === undefined ? {} : { email: identity.email }),
213
214
  ...(identity.name === undefined ? {} : { name: identity.name }),
214
- })).pipe(Effect.catchTag("PrincipalRejected", (rejection) => rejection.reason === "not_invited"
215
+ }).pipe(
216
+ // A user email sign-up created runs `onSignUp` once its creation committed,
217
+ // before they use the app; a failure leaves it pending for their next request.
218
+ Effect.tap((state) => state.signUpPending && ontology.signIn.onSignUp !== undefined
219
+ ? runNewUserHook(ontology, sql, state.principal)
220
+ : Effect.void), Effect.map((state) => state.principal))).pipe(Effect.catchTag("PrincipalRejected", (rejection) => rejection.reason === "not_invited"
215
221
  ? rejectedAs("sign_in")(rejection).pipe(Effect.andThen(Effect.fail(new NotInvited({ message: rejection.message }))))
216
222
  : rejectedAs("sign_in")(rejection))),
217
223
  resolveHookService: (heldRole) => withSql(resolveHookService(ontology, heldRole)).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("hook_service"))),
@@ -237,7 +243,7 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
237
243
  .create(input)
238
244
  .pipe(withStarter, Effect.provideService(ActionTransactions, actionTransactions)),
239
245
  },
240
- federation: sqlFederationStore(ontology, sql),
246
+ federation: withSignUpOnboarding(ontology, sql, sqlFederationStore(ontology, sql)),
241
247
  agents: {
242
248
  ...agents,
243
249
  resolveIdentity: (input) => agents
@@ -10,11 +10,20 @@ export function catalogFor(manifest, permissions) {
10
10
  if (permissions === undefined) {
11
11
  return manifest;
12
12
  }
13
- const { metrics: declared, ...rest } = manifest;
13
+ const { metrics: declared, toolsets: served, ...rest } = manifest;
14
14
  const metrics = declared === undefined ? [] : modelMetricsFor(manifest, permissions);
15
+ // A caller sees a toolset with the tools its permissions grant, and no toolset without one.
16
+ const toolsets = (served ?? []).flatMap((toolset) => {
17
+ const actions = toolset.actions.filter((action) => isAllowed(action.permission ?? `${toolset.name}:${action.name}`, { permissions }));
18
+ const names = new Set(actions.map((action) => action.name));
19
+ return actions.length === 0
20
+ ? []
21
+ : [{ ...toolset, actions, tools: toolset.tools.filter((tool) => names.has(tool.name)) }];
22
+ });
15
23
  return {
16
24
  ...rest,
17
25
  ...(metrics.length === 0 ? {} : { metrics }),
26
+ ...(toolsets.length === 0 ? {} : { toolsets }),
18
27
  entities: manifest.entities
19
28
  .filter((entity) => entity.source === undefined ||
20
29
  isAllowed(entity.permissions?.read ?? `${entity.name}:read`, { permissions }))
@@ -51,6 +51,13 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
51
51
  readonly chat_id: string;
52
52
  readonly thread_id: string;
53
53
  readonly message_id?: string | undefined;
54
+ readonly attachments?: readonly {
55
+ readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
56
+ readonly file_id: string;
57
+ readonly staged_id: string;
58
+ readonly file_unique_id?: string | undefined;
59
+ readonly media_type?: string | undefined;
60
+ }[] | undefined;
54
61
  readonly reply_to_message_id?: string | undefined;
55
62
  readonly callback_query_id?: string | undefined;
56
63
  readonly sender?: string | undefined;
@@ -60,16 +67,9 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
60
67
  readonly horizontal_accuracy?: number | undefined;
61
68
  readonly live_period?: number | undefined;
62
69
  } | undefined;
63
- readonly attachments?: readonly {
64
- readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
65
- readonly file_id: string;
66
- readonly staged_id: string;
67
- readonly file_unique_id?: string | undefined;
68
- readonly media_type?: string | undefined;
69
- }[] | undefined;
70
70
  } | {
71
71
  readonly kind: "group" | "private";
72
- readonly provider: "slack" | "whatsapp";
72
+ readonly provider: "whatsapp" | "slack";
73
73
  readonly chat_id: string;
74
74
  readonly thread_id: string;
75
75
  readonly message_id?: string | undefined;
@@ -103,6 +103,13 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
103
103
  readonly chat_id: string;
104
104
  readonly thread_id: string;
105
105
  readonly message_id?: string | undefined;
106
+ readonly attachments?: readonly {
107
+ readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
108
+ readonly file_id: string;
109
+ readonly staged_id: string;
110
+ readonly file_unique_id?: string | undefined;
111
+ readonly media_type?: string | undefined;
112
+ }[] | undefined;
106
113
  readonly reply_to_message_id?: string | undefined;
107
114
  readonly callback_query_id?: string | undefined;
108
115
  readonly sender?: string | undefined;
@@ -112,16 +119,9 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
112
119
  readonly horizontal_accuracy?: number | undefined;
113
120
  readonly live_period?: number | undefined;
114
121
  } | undefined;
115
- readonly attachments?: readonly {
116
- readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
117
- readonly file_id: string;
118
- readonly staged_id: string;
119
- readonly file_unique_id?: string | undefined;
120
- readonly media_type?: string | undefined;
121
- }[] | undefined;
122
122
  } | {
123
123
  readonly kind: "group" | "private";
124
- readonly provider: "slack" | "whatsapp";
124
+ readonly provider: "whatsapp" | "slack";
125
125
  readonly chat_id: string;
126
126
  readonly thread_id: string;
127
127
  readonly message_id?: string | undefined;
@@ -38,6 +38,7 @@ const REASONS = {
38
38
  connection_response_too_large: "invalid_response",
39
39
  invalid_connection: "invalid_request",
40
40
  invalid_request: "invalid_request",
41
+ mcp_request_not_permitted: "invalid_request",
41
42
  };
42
43
  const MESSAGES = {
43
44
  authorization_required: "Configure or authorize this connection in SegmentStream.",
@@ -23,8 +23,8 @@ export declare function searchDocuments(documents: ReadonlyArray<SearchDocument>
23
23
  readonly summary_truncated: boolean;
24
24
  readonly entity?: string | undefined;
25
25
  readonly metrics?: readonly string[] | undefined;
26
- readonly relevance?: number | undefined;
27
26
  readonly tools?: readonly string[] | undefined;
27
+ readonly relevance?: number | undefined;
28
28
  }[];
29
29
  /** Bytewise canonical-name ordering is independent of a function instance's locale. */
30
30
  export declare function compareRefs(left: string, right: string): number;