@segmentstream/ontology 0.120.0 → 0.122.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 (45) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +55 -38
  3. package/dist/analyze.d.ts +11 -5
  4. package/dist/analyze.js +79 -34
  5. package/dist/chat.d.ts +2 -1
  6. package/dist/diagnostics.d.ts +3 -3
  7. package/dist/diagnostics.js +1 -0
  8. package/dist/feedback-config.d.ts +10 -1
  9. package/dist/feedback-config.js +46 -20
  10. package/dist/index.d.ts +3 -3
  11. package/dist/index.js +2 -2
  12. package/dist/manifest.d.ts +29 -9
  13. package/dist/manifest.js +12 -5
  14. package/dist/permissions.d.ts +1 -1
  15. package/dist/permissions.js +1 -1
  16. package/dist/role.d.ts +22 -3
  17. package/dist/role.js +42 -6
  18. package/dist/runtime/agents.js +58 -0
  19. package/dist/runtime/generated-actions.js +14 -4
  20. package/dist/runtime/member-writes.d.ts +10 -4
  21. package/dist/runtime/member-writes.js +15 -7
  22. package/dist/runtime/model.d.ts +5 -0
  23. package/dist/runtime/model.js +5 -2
  24. package/dist/runtime/new-user-hook.js +7 -4
  25. package/dist/runtime/principals.d.ts +30 -10
  26. package/dist/runtime/principals.js +88 -44
  27. package/dist/runtime/records.js +1 -1
  28. package/dist/runtime/resolve-agent-identity.js +3 -3
  29. package/dist/runtime/sql-runtime.js +2 -1
  30. package/dist/runtime/user-roles.d.ts +8 -7
  31. package/dist/runtime/user-roles.js +17 -12
  32. package/dist/runtime/where.js +4 -4
  33. package/dist/service/agent/chat-archive.d.ts +2 -1
  34. package/dist/service/agent/chat-archive.js +12 -8
  35. package/dist/service/agent/server.js +1 -0
  36. package/dist/service/agent/tasks.d.ts +2 -0
  37. package/dist/service/agent/tasks.js +7 -4
  38. package/dist/service/agent/web-tokens.js +9 -1
  39. package/dist/service/chat/reads.js +5 -1
  40. package/dist/service/mcp/tools.js +7 -3
  41. package/dist/service/runtime-contract.d.ts +12 -0
  42. package/dist/service/service.js +2 -0
  43. package/dist/storage/authorization.js +9 -6
  44. package/dist/workflow.d.ts +7 -3
  45. package/package.json +1 -1
@@ -1,32 +1,37 @@
1
1
  import { USER_ROLES_TABLE, quoteIdentifier, quoteLiteral } from "../migrate/storage.js";
2
- import { MEMBER_ROLE } from "../names.js";
3
2
  /**
4
- * The built-in user's `roles`: the roles assigned to the user in `_user_roles`, sorted, without the
5
- * `member` every active member holds implicitly. It is the only `list` property, and has no column.
3
+ * The built-in user's `roles`: the roles assigned to the user in `_user_roles`, sorted, without
4
+ * the role names the ontology reserves (the implicit `member` while it declares one). It is the
5
+ * only `list` property, and has no column.
6
6
  */
7
7
  export const USER_ROLES_PROPERTY = "roles";
8
8
  const ROLES = quoteIdentifier(USER_ROLES_TABLE);
9
9
  /** Unlikely to shadow an alias of the enclosing statement, whose aliases are `t0`, `t1`, `j0`… */
10
10
  const ASSIGNED = '"_assigned_role"';
11
- const NOT_MEMBER = `${ASSIGNED}."role" <> ${quoteLiteral(MEMBER_ROLE)}`;
11
+ /** The condition leaving out the reserved names; `TRUE` when the ontology reserves none. */
12
+ function notHidden(hidden) {
13
+ return hidden.length === 0
14
+ ? "TRUE"
15
+ : `${ASSIGNED}."role" NOT IN (${hidden.map((role) => quoteLiteral(role)).join(", ")})`;
16
+ }
12
17
  /**
13
18
  * The roles of the user whose id is the SQL expression `userId`, as a JSON array: sorted, without
14
- * `member`, `[]` when none. As a subquery of the statement that reads the user, it is consistent
15
- * with the row it reads.
19
+ * the `hidden` names, `[]` when none. As a subquery of the statement that reads the user, it is
20
+ * consistent with the row it reads.
16
21
  */
17
- export function userRolesExpression(userId) {
22
+ export function userRolesExpression(userId, hidden) {
18
23
  return (`COALESCE((SELECT json_agg(${ASSIGNED}."role" ORDER BY ${ASSIGNED}."role") ` +
19
- `FROM ${ROLES} AS ${ASSIGNED} WHERE ${ASSIGNED}."user_id" = ${userId} AND ${NOT_MEMBER}), ` +
20
- `'[]'::json)`);
24
+ `FROM ${ROLES} AS ${ASSIGNED} WHERE ${ASSIGNED}."user_id" = ${userId} ` +
25
+ `AND ${notHidden(hidden)}), '[]'::json)`);
21
26
  }
22
27
  /**
23
28
  * Whether the user whose id is the SQL expression `userId` is assigned one of the roles, given as
24
- * SQL expressions such as parameters. `member` is never listed, so it matches no user.
29
+ * SQL expressions such as parameters. A `hidden` name is never listed, so it matches no user.
25
30
  */
26
- export function userHoldsRoleCondition(userId, roles) {
31
+ export function userHoldsRoleCondition(userId, roles, hidden) {
27
32
  if (roles.length === 0) {
28
33
  return "FALSE";
29
34
  }
30
35
  return (`EXISTS (SELECT 1 FROM ${ROLES} AS ${ASSIGNED} WHERE ${ASSIGNED}."user_id" = ${userId} ` +
31
- `AND ${NOT_MEMBER} AND ${ASSIGNED}."role" IN (${roles.join(", ")}))`);
36
+ `AND ${notHidden(hidden)} AND ${ASSIGNED}."role" IN (${roles.join(", ")}))`);
32
37
  }
@@ -284,14 +284,14 @@ export function fieldFilter(field, condition) {
284
284
  * The conditions of a list filter, joined with AND. The only list, the user's `roles`, is an
285
285
  * `EXISTS` on the role assignments of the row whose id `column` holds.
286
286
  */
287
- function listCondition(params, column, filter) {
287
+ function listCondition(params, column, filter, hidden) {
288
288
  const bind = (value) => params.add(value, "text");
289
289
  const parts = [];
290
290
  if (filter.has !== undefined) {
291
- parts.push(userHoldsRoleCondition(column, [bind(filter.has)]));
291
+ parts.push(userHoldsRoleCondition(column, [bind(filter.has)], hidden));
292
292
  }
293
293
  if (filter.hasAny !== undefined) {
294
- parts.push(userHoldsRoleCondition(column, filter.hasAny.map(bind)));
294
+ parts.push(userHoldsRoleCondition(column, filter.hasAny.map(bind), hidden));
295
295
  }
296
296
  return and(parts);
297
297
  }
@@ -299,7 +299,7 @@ function listCondition(params, column, filter) {
299
299
  export function fieldCondition(params, column, field, condition) {
300
300
  const filter = fieldFilter(field, condition);
301
301
  if (field.storage === "list") {
302
- return listCondition(params, column, filter);
302
+ return listCondition(params, column, filter, field.hiddenRoles ?? []);
303
303
  }
304
304
  const bind = (value) => params.add(bindValue(field, value), field.sqlType);
305
305
  const parts = [];
@@ -36,7 +36,8 @@ export type ChatArchiveTransport = (input: {
36
36
  readonly memberGroups?: ReadonlyArray<string>;
37
37
  /**
38
38
  * Chats (`provider:chatId`) of any type the ontology checked the member may read, such as a
39
- * private chat its inbox registered, which `agent_chat:read` within its scope reads.
39
+ * private chat its inbox registered, which `agent_chat:read` within its scope reads. A service
40
+ * principal, such as a workflow's user, reads these alone.
40
41
  */
41
42
  readonly chats?: ReadonlyArray<string>;
42
43
  }) => Effect.Effect<ChatPage, ChatArchiveUnavailable | PermissionDenied>;
@@ -23,7 +23,9 @@ export class ChatArchiveUnavailable extends Schema.TaggedError()("ChatArchiveUna
23
23
  /** The authenticated ontology service forwards its resolved member, never a caller-supplied ID. */
24
24
  export function platformChatArchive(environment, fetchImpl = fetch) {
25
25
  return ({ search, principal, identityToken, memberGroups, chats }) => {
26
- if (principal.kind !== "member") {
26
+ // A service, such as a workflow's user, reads only the exact chats the ontology checked.
27
+ const service = principal.kind === "service" && chats !== undefined && chats.length > 0;
28
+ if (principal.kind !== "member" && !service) {
27
29
  return Effect.fail(new PermissionDenied({
28
30
  message: "Only members may read chats.",
29
31
  permission: "chat:participant",
@@ -45,13 +47,15 @@ export function platformChatArchive(environment, fetchImpl = fetch) {
45
47
  },
46
48
  body: JSON.stringify({
47
49
  search,
48
- reader: {
49
- participantId: principal.id,
50
- groups: isAllowed("agent_chat:read", principal),
51
- groupChats: memberGroups ?? [],
52
- ...(chats === undefined || chats.length === 0 ? {} : { chats }),
53
- admin: false,
54
- },
50
+ reader: service
51
+ ? { participantId: null, groups: false, groupChats: [], chats, admin: false }
52
+ : {
53
+ participantId: principal.id,
54
+ groups: isAllowed("agent_chat:read", principal),
55
+ groupChats: memberGroups ?? [],
56
+ ...(chats === undefined || chats.length === 0 ? {} : { chats }),
57
+ admin: false,
58
+ },
55
59
  }),
56
60
  signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]),
57
61
  });
@@ -206,6 +206,7 @@ function resolveChannelIdentity(store, agentTools) {
206
206
  status: resolution.status,
207
207
  ...memberForWire(resolution.member, agentTools),
208
208
  provisioned: resolution.provisioned,
209
+ counted: resolution.counted,
209
210
  notice_due: resolution.noticeDue,
210
211
  on_new_user_pending: resolution.onNewUserPending,
211
212
  ...(resolution.inbox === true ? { inbox: true } : {}),
@@ -33,6 +33,8 @@ export interface AgentTaskRoutesOptions {
33
33
  readonly engine: WorkflowEngine;
34
34
  /** The agent's own tools a caller holds, which the task's answer carries for its user. */
35
35
  readonly agentTools: AgentToolsOf;
36
+ /** Whether the ontology declares `member`, which the task's user then holds beside its role. */
37
+ readonly implicitMember: boolean;
36
38
  }
37
39
  /**
38
40
  * The routes of the tasks workflows hand the app's agent with `agentTask`. Both take only the
@@ -32,7 +32,7 @@ function json(body, status = 200) {
32
32
  * as, from the ontology's records, never from the agent's request: their roles, and in
33
33
  * `agent_tools` the agent's own tools those roles grant.
34
34
  */
35
- function currentTask(backend, { task, principal }, agentTools) {
35
+ function currentTask(backend, { task, principal }, options) {
36
36
  return Effect.gen(function* () {
37
37
  const user = yield* backend
38
38
  .get({ entity: "user", id: principal.id })
@@ -45,8 +45,11 @@ function currentTask(backend, { task, principal }, agentTools) {
45
45
  principal: {
46
46
  id: principal.id,
47
47
  name: typeof user?.name === "string" ? user.name : task.workflow,
48
- roles: [...new Set([...principal.roles, MEMBER_ROLE])],
49
- agent_tools: agentTools(principal),
48
+ // @legacy ontology.implicit-member
49
+ roles: options.implicitMember
50
+ ? [...new Set([...principal.roles, MEMBER_ROLE])]
51
+ : principal.roles,
52
+ agent_tools: options.agentTools(principal),
50
53
  },
51
54
  });
52
55
  });
@@ -151,7 +154,7 @@ export function agentTasksLayer(options) {
151
154
  ? refused(caller.detail)
152
155
  : yield* answer(request, caller);
153
156
  });
154
- yield* router.add("GET", AGENT_TASK_PATH, asTask((_, live) => currentTask(backend, live, options.agentTools)));
157
+ yield* router.add("GET", AGENT_TASK_PATH, asTask((_, live) => currentTask(backend, live, options)));
155
158
  yield* router.add("POST", AGENT_TASK_RESULT_PATH, asTask((request, live) => reportResult(store, options.engine, request, live)));
156
159
  }));
157
160
  }
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { Effect, Result, Schema } from "effect";
2
+ import { Cause, Effect, Exit, Result, Schema } from "effect";
3
3
  import { HttpServerResponse } from "effect/unstable/http";
4
4
  import { schemaIssues } from "../../runtime/validation.js";
5
5
  import { BASE_PATH } from "../api.js";
@@ -130,6 +130,14 @@ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
130
130
  const limited = decoded.success.turn === true && web.countGuestTurn !== undefined
131
131
  ? yield* web.countGuestTurn(guest.id, limits)
132
132
  : undefined;
133
+ // An admitted turn is a message in the visitor's chat: the inbox, where it takes guests,
134
+ // records the chat. The turn goes on whether or not the record could be written.
135
+ if (decoded.success.turn === true && limited === undefined && store.seeGuestChat) {
136
+ const seen = yield* Effect.exit(store.seeGuestChat(guest.id));
137
+ if (Exit.isFailure(seen)) {
138
+ yield* Effect.logWarning("ontology.agent.guest_chat_unrecorded").pipe(Effect.annotateLogs({ requestId, cause: Cause.pretty(seen.cause) }));
139
+ }
140
+ }
133
141
  return json({
134
142
  active: true,
135
143
  guest_id: guest.id,
@@ -76,7 +76,7 @@ export function chatReads(backend, options) {
76
76
  }),
77
77
  history: (input, identityToken) => Effect.gen(function* () {
78
78
  const principal = yield* CurrentPrincipal;
79
- if (principal.kind !== "member") {
79
+ if (principal.kind !== "member" && principal.kind !== "service") {
80
80
  return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
81
81
  }
82
82
  const registered = UUID.test(input.chat)
@@ -103,6 +103,10 @@ export function chatReads(backend, options) {
103
103
  ...(registered.staff ? { chats: [key] } : {}),
104
104
  });
105
105
  }
106
+ // A service, such as a workflow's user, reads only the registered chats its scope holds.
107
+ if (principal.kind !== "member") {
108
+ return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
109
+ }
106
110
  // History reads the chats of Telegram channels only. Other channels archive a chat under
107
111
  // their session's address with private coordinates, not under the chat a destination
108
112
  // names, so their history would be incomplete until the archive keys them the same way.
@@ -801,13 +801,17 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
801
801
  title: "Read chat history",
802
802
  description: "Read messages for an exact chat ID/title, with their own pagination. " +
803
803
  "Reads a group chat you are in (every group with agent_chat:read), your own private chat, " +
804
- "or, by its agent_chat id, a person's private chat the inbox registered, with " +
805
- "agent_chat:read within your scope.",
804
+ "or, by its agent_chat id, a private chat the inbox registered (a person's, or a website " +
805
+ "visitor's), with agent_chat:read within your scope. A workflow's task reads only these.",
806
806
  inputSchema: encodedJsonSchema(ChatHistory),
807
807
  annotations: READ,
808
808
  permissions: [],
809
809
  target: { kind: "chat-history" },
810
- inputSchemaFor: (caller) => "kind" in caller && caller.kind === "member" ? encodedJsonSchema(ChatHistory) : undefined,
810
+ inputSchemaFor: (caller) => "kind" in caller &&
811
+ (caller.kind === "member" ||
812
+ (caller.kind === "service" && isAllowed("agent_chat:read", caller)))
813
+ ? encodedJsonSchema(ChatHistory)
814
+ : undefined,
811
815
  });
812
816
  tools.push({
813
817
  name: "chat_search",
@@ -516,6 +516,11 @@ export type AgentResolution = {
516
516
  readonly status: "existing" | "created";
517
517
  readonly member: AgentMember;
518
518
  readonly provisioned: boolean;
519
+ /**
520
+ * The person's turns count against the per-sender and workspace turn limits: everyone sign-up
521
+ * created, and an open channel's user while they hold no role but the earlier `member`.
522
+ */
523
+ readonly counted: boolean;
519
524
  readonly noticeDue: boolean;
520
525
  readonly onNewUserPending: boolean;
521
526
  /**
@@ -637,6 +642,13 @@ export interface AgentStore {
637
642
  * stores that predate the inbox.
638
643
  */
639
644
  readonly seeInboxChat?: (input: InboxChatInput) => Effect.Effect<SeenChat | undefined>;
645
+ /**
646
+ * Records a website visitor's chat with the agent, `guest:<id>` on the `web` channel, for the
647
+ * inbox: creates the `agent_chat` of kind `private`, without members, and records when it last
648
+ * had a message, as `seeChat` does. `undefined`, recording nothing, unless the inbox takes
649
+ * `guest`. Absent on stores that predate it.
650
+ */
651
+ readonly seeGuestChat?: (guestId: string) => Effect.Effect<SeenChat | undefined>;
640
652
  /**
641
653
  * A reply the agent held for review becomes a pending `agent_review` for the member it answers,
642
654
  * once per `key`: a repeated report answers the review it created. `undefined` when the member is
@@ -12,6 +12,7 @@ import { parsePageCatalog } from "../navigation-catalog.js";
12
12
  import { guestOf, signUpOriginsOf, signUpRolesOf } from "../manifest.js";
13
13
  import { isAllowed } from "../permissions.js";
14
14
  import { agentToolsFor } from "../runtime/guests.js";
15
+ import { implicitMemberOf } from "../role.js";
15
16
  import { sqlServiceRuntime } from "../runtime/service-binding.js";
16
17
  import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-links.js";
17
18
  import { memberFileRoutes } from "./member-file-routes.js";
@@ -432,6 +433,7 @@ export function createOntologyService(ontology, config) {
432
433
  workspaceId: config.workspaceId,
433
434
  engine: config.workflowEngine ?? vercelWorkflowEngine,
434
435
  agentTools,
436
+ implicitMember: implicitMemberOf(ontology.roles) !== undefined,
435
437
  });
436
438
  const attachments = preview
437
439
  ? Layer.empty
@@ -1,8 +1,9 @@
1
1
  import { Effect } from "effect";
2
2
  import { missingPermission, permissionsOf, principalScopes } from "../permissions.js";
3
3
  import { PermissionDenied } from "../errors.js";
4
- import { MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, toSnakeCase } from "../names.js";
5
- import { rolesOf } from "../runtime/principals.js";
4
+ import { FEEDBACK_REPORTER_ROLE, toSnakeCase } from "../names.js";
5
+ import { implicitRoleNames } from "../role.js";
6
+ import { rolesOf, workflowRoles } from "../runtime/principals.js";
6
7
  import { PIPELINE_WORKER_PROVIDER } from "../runtime/workload.js";
7
8
  import { WORKFLOW_USER_PROVIDER, workflowOfSubject } from "../runtime/workflow-users.js";
8
9
  /** Re-read user and roles in the same transaction that authorizes a storage operation. */
@@ -24,9 +25,10 @@ workflowPrincipal) {
24
25
  const users = yield* sql.unsafe(`SELECT kind::text, active, identity_provider, identity_subject FROM "user" WHERE id = $1::uuid FOR SHARE`, [principalId]);
25
26
  const user = users[0];
26
27
  const roles = yield* sql.unsafe(`SELECT role FROM "_user_roles" WHERE user_id = $1::uuid FOR SHARE`, [principalId]);
28
+ const reserved = implicitRoleNames(ontology.roles);
27
29
  const held = roles
28
30
  .map((row) => String(row.role))
29
- .filter((name) => toSnakeCase(name) !== FEEDBACK_REPORTER_ROLE);
31
+ .filter((name) => !(reserved.length > 0 && toSnakeCase(name) === FEEDBACK_REPORTER_ROLE));
30
32
  // Reuse human principal resolution rather than reconstructing implicit authority here. The
31
33
  // result rechecks required permissions and is the reader for scoped file reads; the caller's
32
34
  // consent-narrowed principal still governs the rest of the operation.
@@ -41,8 +43,9 @@ workflowPrincipal) {
41
43
  user?.kind === "service" &&
42
44
  user.identity_provider === PIPELINE_WORKER_PROVIDER &&
43
45
  user.identity_subject === `pipeline-workers:${execution.workspaceId}`;
44
- // A workflow's runs hold what member and the declared workflow's role grant. The database
45
- // must assign exactly that role: an extra or stale assignment widens nothing and is refused.
46
+ // A workflow's runs hold what the declared workflow's role grants (and the implicit member's,
47
+ // while the ontology declares one). The database must assign exactly that role: an extra or
48
+ // stale assignment widens nothing and is refused.
46
49
  const workflowUser = user?.kind === "service" && user.identity_provider === WORKFLOW_USER_PROVIDER;
47
50
  // The user's subject must be exactly the principal's, workspace id included.
48
51
  const workflow = workflowUser &&
@@ -55,7 +58,7 @@ workflowPrincipal) {
55
58
  execution === undefined &&
56
59
  held.length === 1 &&
57
60
  held[0] === workflow.role;
58
- const liveHeld = workflowUser && workflow ? [MEMBER_ROLE, workflow.role] : (member?.roles ?? held);
61
+ const liveHeld = workflowUser && workflow ? workflowRoles(ontology, workflow.role) : (member?.roles ?? held);
59
62
  const permissions = worker
60
63
  ? ["*:*"]
61
64
  : workflowUser && !declaredWorkflow
@@ -22,7 +22,10 @@ export declare const MAX_ACTION_TRIGGERS = 20;
22
22
  export interface TriggerRuns {
23
23
  /** The action the trigger runs, as its handle: `Lead.actions.notify`. */
24
24
  readonly runs?: AnyActionHandle;
25
- /** The declared role, other than `member`, the runs hold with member's; required with `runs`. */
25
+ /**
26
+ * The declared role the runs hold, required with `runs`: exactly its permissions, with the
27
+ * built-in `member`'s while the ontology declares one.
28
+ */
26
29
  readonly role?: string;
27
30
  }
28
31
  /**
@@ -264,8 +267,9 @@ export interface WorkflowOptions<S extends AnyInputSchema | undefined = undefine
264
267
  /** Required, like every declaration: what the workflow does and why. */
265
268
  readonly description: string;
266
269
  /**
267
- * The declared role, other than `member`, whose permissions the workflow's runs hold together
268
- * with member's. Its runs act as the workflow's own service user.
270
+ * The declared role whose permissions the workflow's runs hold: exactly its permissions, with
271
+ * the built-in `member`'s while the ontology declares one. Its runs act as the workflow's own
272
+ * service user.
269
273
  */
270
274
  readonly role: string;
271
275
  /** A `Schema.Struct` of the workflow's input. Omitted means `{}`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.120.0",
3
+ "version": "0.122.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",