@segmentstream/ontology 0.181.0 → 0.183.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 (56) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +23 -15
  3. package/dist/action.d.ts +11 -4
  4. package/dist/agent-chat.d.ts +8 -2
  5. package/dist/agent-chat.js +45 -29
  6. package/dist/agent-draft.d.ts +8 -8
  7. package/dist/analyze.d.ts +7 -9
  8. package/dist/analyze.js +159 -71
  9. package/dist/authoring.js +7 -1
  10. package/dist/chat.d.ts +32 -3
  11. package/dist/chat.js +33 -12
  12. package/dist/index.d.ts +1 -1
  13. package/dist/manifest.d.ts +174 -68
  14. package/dist/manifest.js +33 -2
  15. package/dist/migrate/model.d.ts +94 -50
  16. package/dist/permissions.d.ts +17 -0
  17. package/dist/permissions.js +17 -0
  18. package/dist/render.d.ts +6 -0
  19. package/dist/render.js +25 -10
  20. package/dist/runtime/agent-web.js +47 -26
  21. package/dist/runtime/agents.js +25 -0
  22. package/dist/runtime/guests.d.ts +4 -1
  23. package/dist/runtime/guests.js +24 -5
  24. package/dist/runtime/pipeline.d.ts +3 -3
  25. package/dist/runtime/pipeline.js +11 -4
  26. package/dist/service/agent/server.d.ts +0 -2
  27. package/dist/service/agent/server.js +42 -47
  28. package/dist/service/authentication.js +14 -3
  29. package/dist/service/catalog.js +3 -3
  30. package/dist/service/chat/chat-draft.d.ts +1 -1
  31. package/dist/service/chat/delivery.js +43 -22
  32. package/dist/service/chat/envelope.d.ts +8 -8
  33. package/dist/service/chat/local-reads.d.ts +5 -5
  34. package/dist/service/chat/routes.js +2 -0
  35. package/dist/service/chat/schemas.d.ts +40 -0
  36. package/dist/service/chat/schemas.js +3 -1
  37. package/dist/service/discovery-search.d.ts +1 -1
  38. package/dist/service/mcp/server.js +2 -0
  39. package/dist/service/mcp/tools.d.ts +10 -2
  40. package/dist/service/mcp/tools.js +11 -4
  41. package/dist/service/operations.js +10 -5
  42. package/dist/service/plan.d.ts +3 -1
  43. package/dist/service/plan.js +4 -2
  44. package/dist/service/runtime-contract.d.ts +3 -1
  45. package/dist/service/runtime-identity.d.ts +1 -0
  46. package/dist/service/runtime-identity.js +2 -0
  47. package/dist/service/schemas.d.ts +8 -0
  48. package/dist/service/service.js +2 -12
  49. package/dist/service/toolsets.d.ts +1 -1
  50. package/dist/service/toolsets.js +38 -4
  51. package/dist/sign-in.d.ts +14 -7
  52. package/dist/sign-in.js +4 -3
  53. package/dist/toolset.d.ts +17 -1
  54. package/package.json +1 -1
  55. package/dist/service/agent/public-group-action.d.ts +0 -23
  56. package/dist/service/agent/public-group-action.js +0 -53
@@ -210,6 +210,23 @@ export declare function readScope(entity: string, holder: PermissionHolder): Sco
210
210
  export declare function effectivePermissions(principal: PermissionHolder): ReadonlyArray<string>;
211
211
  /** The first of the required permissions the principal lacks, or `undefined` when it holds all. */
212
212
  export declare function missingPermission(required: ReadonlyArray<string>, principal: PermissionHolder): string | undefined;
213
+ /**
214
+ * What running an action requires: every one of `permissions`, or, with `anyPermission`, any one of
215
+ * them, for an action several permissions open, whose input chooses what it does and which checks
216
+ * inside what that needs, as `agent_chat.send` checks the voice it sends in.
217
+ */
218
+ export interface ActionRequirement {
219
+ readonly permissions: ReadonlyArray<string>;
220
+ readonly anyPermission?: true;
221
+ }
222
+ /** Whether the holder may run an action that requires `required`. */
223
+ export declare function allowsAction(required: ActionRequirement, holder: PermissionHolder): boolean;
224
+ /**
225
+ * What the holder lacks to run an action that requires `required`, for a refusal: the first
226
+ * permission it lacks, or, for an action any one of several permissions opens, all of them joined
227
+ * by `or`. `undefined` when it may run the action.
228
+ */
229
+ export declare function missingActionPermission(required: ActionRequirement, holder: PermissionHolder): string | undefined;
213
230
  /**
214
231
  * What a generated action requires: `<entity>:<action>`, except `upsert_by_<property>`, which may
215
232
  * create or update and so requires both `<entity>:create` and `<entity>:update`.
@@ -269,6 +269,23 @@ export function effectivePermissions(principal) {
269
269
  export function missingPermission(required, principal) {
270
270
  return required.find((permission) => !isAllowed(permission, principal));
271
271
  }
272
+ /** Whether the holder may run an action that requires `required`. */
273
+ export function allowsAction(required, holder) {
274
+ return required.anyPermission === true
275
+ ? required.permissions.some((permission) => isAllowed(permission, holder))
276
+ : required.permissions.every((permission) => isAllowed(permission, holder));
277
+ }
278
+ /**
279
+ * What the holder lacks to run an action that requires `required`, for a refusal: the first
280
+ * permission it lacks, or, for an action any one of several permissions opens, all of them joined
281
+ * by `or`. `undefined` when it may run the action.
282
+ */
283
+ export function missingActionPermission(required, holder) {
284
+ if (required.anyPermission !== true) {
285
+ return missingPermission(required.permissions, holder);
286
+ }
287
+ return allowsAction(required, holder) ? undefined : required.permissions.join(" or ");
288
+ }
272
289
  /**
273
290
  * What a generated action requires: `<entity>:<action>`, except `upsert_by_<property>`, which may
274
291
  * create or update and so requires both `<entity>:create` and `<entity>:update`.
package/dist/render.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ActionManifest, EntityManifest, MetricManifest, ModelMetricManifest, OntologyManifest } from "./manifest.js";
2
+ import { type ActionRequirement } from "./permissions.js";
2
3
  export interface RenderOptions {
3
4
  /**
4
5
  * The permissions of the reader. Only the actions these permissions may run are listed, and only
@@ -9,6 +10,11 @@ export interface RenderOptions {
9
10
  }
10
11
  /** What an action of the manifest requires; version 1 manifests leave it implicit. */
11
12
  export declare function actionPermission(entity: string, action: ActionManifest): string;
13
+ /**
14
+ * What running an action of the manifest requires: its permission, or, for an action several
15
+ * permissions open, any one of them.
16
+ */
17
+ export declare function actionRequirement(entity: string, action: ActionManifest): ActionRequirement;
12
18
  /**
13
19
  * A metric's description followed by its conditions and balance note, as `describe`, the MCP
14
20
  * metric list and the console show it: `Revenue of won orders. Where status = "won".`
package/dist/render.js CHANGED
@@ -1,17 +1,32 @@
1
1
  import { inputEntities, shortestRoutesFrom } from "./metric-routes.js";
2
2
  import { QUERY_METRICS_ROUTE } from "./names.js";
3
- import { isAllowed, permissionOf, READ_VERB, rolesGranting } from "./permissions.js";
3
+ import { allowsAction, isAllowed, permissionOf, READ_VERB, rolesGranting, } from "./permissions.js";
4
4
  import { REFERENCE_ANNOTATION } from "./property.js";
5
5
  /** What an action of the manifest requires; version 1 manifests leave it implicit. */
6
6
  export function actionPermission(entity, action) {
7
7
  return action.permission ?? permissionOf(entity, action.name);
8
8
  }
9
- /** `Requires lead:changeStatus (member, sales).`: the permission and the roles that grant it. */
10
- function requirement(subject, permission, roles) {
11
- const granting = rolesGranting(roles, permission);
12
- return granting.length === 0
13
- ? `${subject} ${permission}, which no role grants.`
14
- : `${subject} ${permission} (${granting.join(", ")}).`;
9
+ /**
10
+ * What running an action of the manifest requires: its permission, or, for an action several
11
+ * permissions open, any one of them.
12
+ */
13
+ export function actionRequirement(entity, action) {
14
+ return action.anyOf !== undefined && action.anyOf.length > 1
15
+ ? { permissions: action.anyOf, anyPermission: true }
16
+ : { permissions: [actionPermission(entity, action)] };
17
+ }
18
+ /**
19
+ * `Requires lead:changeStatus (member, sales).`: the permission and the roles that grant it, or, for
20
+ * an action several permissions open, each of them with its roles, joined by `or`.
21
+ */
22
+ function requirement(subject, permissions, roles) {
23
+ const granted = permissions.map((permission) => {
24
+ const granting = rolesGranting(roles, permission);
25
+ return granting.length === 0 ? permission : `${permission} (${granting.join(", ")})`;
26
+ });
27
+ return permissions.every((permission) => rolesGranting(roles, permission).length === 0)
28
+ ? `${subject} ${permissions.join(" or ")}, which no role grants.`
29
+ : `${subject} ${granted.join(" or ")}.`;
15
30
  }
16
31
  const INDENT = " ";
17
32
  function isRecord(value) {
@@ -310,14 +325,14 @@ export function metricDescription(entity, metric) {
310
325
  function renderEntity(entity, manifest, entities, options) {
311
326
  const reader = options.as;
312
327
  const actions = entity.actions.filter((action) => reader === undefined ||
313
- isAllowed(actionPermission(entity.name, action), { permissions: reader }));
328
+ allowsAction(actionRequirement(entity.name, action), { permissions: reader }));
314
329
  const read = entity.permissions?.read ?? permissionOf(entity.name, READ_VERB);
315
330
  const connections = new Map((manifest.connections ?? []).map((connection) => [connection.key, connection.description]));
316
331
  return [
317
332
  `${entity.label} (${entity.plural.toLowerCase()}): ${entity.description}`,
318
333
  `${INDENT}Identified by: ${entity.title}.`,
319
334
  ...(reader === undefined
320
- ? [`${INDENT}${requirement("Reading requires", read, manifest.roles)}`]
335
+ ? [`${INDENT}${requirement("Reading requires", [read], manifest.roles)}`]
321
336
  : []),
322
337
  ...(entity.source
323
338
  ? [`${INDENT}Source: ${entity.source.asset}; key: ${entity.source.key.join(", ")}.`]
@@ -326,7 +341,7 @@ function renderEntity(entity, manifest, entities, options) {
326
341
  ...section("Metrics", (entity.metrics ?? []).map((metric) => `${metric.name}: ${metricDescription(entity, metric)} (${metric.unit}).`)),
327
342
  ...section("Relationships", relationshipLines(entity, entities, manifest.entities)),
328
343
  ...section(reader === undefined ? "Actions" : "Actions you may run", actions.flatMap((action) => actionLines(action, reader === undefined
329
- ? requirement("Requires", actionPermission(entity.name, action), manifest.roles)
344
+ ? requirement("Requires", actionRequirement(entity.name, action).permissions, manifest.roles)
330
345
  : undefined, connections))),
331
346
  ].join("\n");
332
347
  }
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { Effect } from "effect";
3
3
  import { SqlClient } from "effect/unstable/sql";
4
4
  import { signUpRolesOf } from "../manifest.js";
5
- import { AGENT_GUEST_LINKS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
5
+ import { AGENT_GUEST_LINKS_TABLE, AGENT_COUNTERS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
6
6
  import { AGENT_EVAL_CLIENT_ID, AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
7
7
  import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, FULL_SCOPE, REFRESH_TOKEN_PREFIX, REFRESH_TOKEN_TTL_MS, newSecret, secretHash, } from "../service/oauth/protocol.js";
8
8
  import { addGuestSpend, completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, guestSpendLimited, } from "./agent-counters.js";
@@ -216,34 +216,55 @@ export function sqlAgentWebStore(ontology, sql, admission) {
216
216
  .pipe(Effect.orDie);
217
217
  return standing === undefined ? undefined : guestPrincipal(ontology, grantId);
218
218
  }),
219
- countGuestTurn: (guestId, input) => Effect.gen(function* () {
220
- if (!isRecordId(guestId)) {
221
- return undefined;
222
- }
223
- const limits = yield* effectiveChannelLimits(sql, input);
224
- // Money first: a guest past a cap starts no turn, and the turn is not counted.
225
- const spent = yield* guestSpendLimited(sql, { guestId, limits });
226
- if (spent !== undefined) {
227
- return spent;
228
- }
229
- for (const [scope, subject, limit] of [
230
- ["guestTurnsPerDay", guestId, limits.guest.turnsPerDay],
231
- ["guestWorkspaceTurnsPerDay", "workspace", limits.guest.workspaceTurnsPerDay],
232
- ]) {
233
- const limited = yield* countAgentAttempt(sql, { scope, subject, window: "day", limit });
234
- if (limited !== undefined) {
235
- // The refusal the browser gets is this window's notice.
236
- if (limited.notificationId !== undefined) {
237
- yield* completeAgentLimitNotice(sql, {
238
- notificationId: limited.notificationId,
239
- delivered: true,
240
- });
219
+ countGuestTurn: (guestId, input, delivery) => {
220
+ const count = Effect.gen(function* () {
221
+ if (!isRecordId(guestId)) {
222
+ return undefined;
223
+ }
224
+ const limits = yield* effectiveChannelLimits(sql, input);
225
+ // Money first: a guest past a cap starts no turn, and the turn is not counted.
226
+ const spent = yield* guestSpendLimited(sql, { guestId, limits });
227
+ if (spent !== undefined) {
228
+ return spent;
229
+ }
230
+ for (const [scope, subject, limit] of [
231
+ ["guestTurnsPerDay", guestId, limits.guest.turnsPerDay],
232
+ ["guestWorkspaceTurnsPerDay", "workspace", limits.guest.workspaceTurnsPerDay],
233
+ ]) {
234
+ const limited = yield* countAgentAttempt(sql, { scope, subject, window: "day", limit });
235
+ if (limited !== undefined) {
236
+ // The refusal the browser gets is this window's notice.
237
+ if (limited.notificationId !== undefined) {
238
+ yield* completeAgentLimitNotice(sql, {
239
+ notificationId: limited.notificationId,
240
+ delivered: true,
241
+ });
242
+ }
243
+ return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
241
244
  }
242
- return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
243
245
  }
246
+ return undefined;
247
+ });
248
+ if (!delivery || !isRecordId(guestId)) {
249
+ return count.pipe(Effect.orDie);
244
250
  }
245
- return undefined;
246
- }).pipe(Effect.orDie),
251
+ // Provider retries share the accepted turn's charge, including concurrent deliveries.
252
+ const key = `guestDelivery:${guestId}:${secretHash(delivery)}`;
253
+ return sql
254
+ .withTransaction(Effect.gen(function* () {
255
+ const [fresh] = yield* sql.unsafe(`INSERT INTO "${AGENT_COUNTERS_TABLE}" ("key","window_start","count")
256
+ VALUES ($1,date_trunc('day',now()),1) ON CONFLICT ("key","window_start") DO NOTHING RETURNING 1`, [key]);
257
+ if (!fresh) {
258
+ return undefined;
259
+ }
260
+ const limited = yield* count;
261
+ if (limited) {
262
+ yield* sql.unsafe(`DELETE FROM "${AGENT_COUNTERS_TABLE}" WHERE "key"=$1 AND "window_start"=date_trunc('day',now())`, [key]);
263
+ }
264
+ return limited;
265
+ }))
266
+ .pipe(Effect.orDie);
267
+ },
247
268
  recordGuestUsage: ({ guestId, costUsd, key }) => isRecordId(guestId) ? addGuestSpend(sql, { guestId, costUsd, key }) : Effect.void,
248
269
  countGuestAttempt: ({ scope, subject, limit }) => countAgentAttempt(sql, { scope, subject, window: "hour", limit }).pipe(Effect.map((limited) => limited?.retryAfterSeconds)),
249
270
  upgradeGuest: ({ guestId, identity, expiresAt }) => Effect.gen(function* () {
@@ -1,3 +1,4 @@
1
+ import { channelGuestId, guestPrincipal } from "./guests.js";
1
2
  import { sqlConfirmationStore } from "./confirmations.js";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { Effect, Option, Schema } from "effect";
@@ -619,6 +620,30 @@ export function sqlAgentStore(ontology, sql) {
619
620
  return true;
620
621
  }))
621
622
  .pipe(Effect.orDie),
623
+ channelGuest: (channel, chat, sender) => Effect.gen(function* () {
624
+ const kind = store.channelKind?.(channel);
625
+ if ((kind !== "telegram" && kind !== "slack" && kind !== "whatsapp") ||
626
+ !sender ||
627
+ sender.length > 256 ||
628
+ !chat ||
629
+ chat.length > 256) {
630
+ return undefined;
631
+ }
632
+ const principal = guestPrincipal(ontology, channelGuestId(channel, sender), kind, channel);
633
+ if (!principal) {
634
+ return undefined;
635
+ }
636
+ if (kind === "whatsapp"
637
+ ? !/^whatsapp:[^:]+:[0-9]+$/.test(chat) || chat.split(":")[2] !== sender
638
+ : (yield* store.readGroupAccess(`${channel}:${chat}`)) !== "public") {
639
+ return undefined;
640
+ }
641
+ // Linked, inactive and revoked identities alike must pass through member admission.
642
+ if (yield* store.findIdentity({ provider: kind, externalId: sender })) {
643
+ return undefined;
644
+ }
645
+ return { ...principal, chat: { provider: channel, chatId: chat } };
646
+ }),
622
647
  readGroupAccess: (key) => rows(`SELECT "group_access" FROM ${quoteIdentifier(tableName(AgentChat.name))}
623
648
  WHERE "key" = $1 AND "kind" = 'group' AND "handoff_at" IS NULL AND "handled_by_id" IS NULL`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.group_access))),
624
649
  readChatPersona: (key) => rows(`SELECT "agent_persona" FROM ${quoteIdentifier(tableName(AgentChat.name))} WHERE "key" = $1`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.agent_persona))),
@@ -1,3 +1,4 @@
1
+ import { type GuestChannel } from "../sign-in.js";
1
2
  import type { Ontology } from "../ontology.js";
2
3
  import { type AgentToolVerb } from "../permissions.js";
3
4
  import type { Principal } from "../runtime.js";
@@ -30,4 +31,6 @@ export declare function actingGuestId(actAs: string): string | undefined;
30
31
  * holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
31
32
  * `undefined` when the ontology admits no guests.
32
33
  */
33
- export declare function guestPrincipal(ontology: Ontology, guestId: string): Principal | undefined;
34
+ export declare function guestPrincipal(ontology: Ontology, guestId: string, channel?: GuestChannel, connection?: string): Principal | undefined;
35
+ /** Budget identity shared across chats on one configured messenger connection. */
36
+ export declare function channelGuestId(channel: string, sender: string): string;
@@ -1,6 +1,6 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { GUEST_ROLE } from "../names.js";
2
3
  import { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, isAllowed, MEMBER_AGENT_TOOLS, permissionsOf, principalScopes, } from "../permissions.js";
3
- import { WEB_PROVIDER } from "../service/runtime-identity.js";
4
4
  import { isRecordId } from "./records.js";
5
5
  /**
6
6
  * A guest as the agent names them in `X-SegmentStream-Act-As`: `guest:` and their id, so that no
@@ -49,17 +49,36 @@ export function actingGuestId(actAs) {
49
49
  * holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
50
50
  * `undefined` when the ontology admits no guests.
51
51
  */
52
- export function guestPrincipal(ontology, guestId) {
53
- if (ontology.signIn.guest === undefined || !isRecordId(guestId)) {
52
+ export function guestPrincipal(ontology, guestId, channel = "web", connection) {
53
+ const settings = ontology.signIn.guest;
54
+ const named = `channel:${connection}`;
55
+ const selected = connection && settings?.channels.includes(named) ? named : channel;
56
+ if (!settings?.channels.includes(selected) || !isRecordId(guestId)) {
54
57
  return undefined;
55
58
  }
56
- const roles = [GUEST_ROLE];
59
+ const roles = settings.byChannel?.[selected] ?? [GUEST_ROLE];
57
60
  return {
58
61
  id: guestId,
59
62
  kind: "guest",
60
63
  roles,
61
64
  permissions: permissionsOf(ontology.roles, roles),
62
65
  ...principalScopes(ontology.roles, roles),
63
- authenticatedVia: WEB_PROVIDER,
66
+ authenticatedVia: channel,
64
67
  };
65
68
  }
69
+ /** Budget identity shared across chats on one configured messenger connection. */
70
+ export function channelGuestId(channel, sender) {
71
+ const bytes = createHash("sha256")
72
+ .update(JSON.stringify(["group-guest", channel, sender]))
73
+ .digest();
74
+ bytes[6] = (bytes[6] & 15) | 80;
75
+ bytes[8] = (bytes[8] & 63) | 128;
76
+ const hex = bytes.toString("hex");
77
+ return [
78
+ hex.slice(0, 8),
79
+ hex.slice(8, 12),
80
+ hex.slice(12, 16),
81
+ hex.slice(16, 20),
82
+ hex.slice(20, 32),
83
+ ].join("-");
84
+ }
@@ -5,6 +5,7 @@ import { type AnyAction } from "../action.js";
5
5
  import { ConnectionError, ConnectionTransport } from "../connection.js";
6
6
  import { type ActionError } from "../errors.js";
7
7
  import type { Ontology } from "../ontology.js";
8
+ import { type ActionRequirement } from "../permissions.js";
8
9
  import { type Principal } from "../runtime.js";
9
10
  import { TriggerInputInvalid, UnknownAction, WorkflowRecoveryUnavailable } from "./errors.js";
10
11
  import { Edit } from "./history.js";
@@ -102,10 +103,9 @@ export interface ActionOutcome<Result = unknown> {
102
103
  readonly validation: ActionValidation;
103
104
  readonly edits: ReadonlyArray<Edit>;
104
105
  }
105
- /** An action and every permission a principal needs to run it. */
106
- export interface FoundAction {
106
+ /** An action and every permission a principal needs to run it, or, with `anyPermission`, one. */
107
+ export interface FoundAction extends ActionRequirement {
107
108
  readonly action: AnyAction;
108
- readonly permissions: ReadonlyArray<string>;
109
109
  /**
110
110
  * A generated `create`, `update`, `delete`, `upsert_by_<property>`, `link`, `unlink` or member
111
111
  * action, whose input and result are in wire names.
@@ -16,7 +16,7 @@ import { beginReplicationWrite } from "../replication/transaction.js";
16
16
  import { RuntimeDeployment } from "./deployment.js";
17
17
  import { requireDeploymentCapability } from "../deployment.js";
18
18
  import { authorizeBlobOperation } from "../storage/authorization.js";
19
- import { effectiveScope, generatedActionPermissions, missingPermission, parsePermission, } from "../permissions.js";
19
+ import { effectiveScope, generatedActionPermissions, missingActionPermission, parsePermission, } from "../permissions.js";
20
20
  import { OntologyReads, OntologyRuntime } from "../runtime.js";
21
21
  import { UnknownAction, ValidationIssue, WorkflowRecoveryUnavailable, } from "./errors.js";
22
22
  import { generatedActions, writesOnlyThroughActions } from "./generated-actions.js";
@@ -72,7 +72,13 @@ export function resolveAction(ontology, entityName, actionName) {
72
72
  }
73
73
  const authored = entity.actions.find((candidate) => candidate.name === actionName);
74
74
  if (authored !== undefined) {
75
- return { action: authored.action, permissions: [authored.permission], generated: false };
75
+ return {
76
+ action: authored.action,
77
+ ...(authored.anyOf === undefined
78
+ ? { permissions: [authored.permission] }
79
+ : { permissions: authored.anyOf, anyPermission: true }),
80
+ generated: false,
81
+ };
76
82
  }
77
83
  const generated = generatedActions(ontology, entityName)[actionName];
78
84
  return generated === undefined
@@ -205,10 +211,11 @@ export function runAction(ontology, request) {
205
211
  if (!decoded.ok) {
206
212
  return { result: null, validation: { ok: false, issues: decoded.issues }, edits: [] };
207
213
  }
208
- const missing = missingPermission(found.permissions, request.principal);
214
+ const missing = missingActionPermission(found, request.principal);
209
215
  if (missing !== undefined) {
210
216
  return yield* new PermissionDenied({
211
- permission: missing,
217
+ // Of an action several permissions open, the first it names.
218
+ permission: found.anyPermission === true ? found.permissions[0] : missing,
212
219
  message: `${qualified} requires ${missing}, which the principal's roles do not grant.`,
213
220
  });
214
221
  }
@@ -1,4 +1,3 @@
1
- import { type PublicActionOptions } from "./public-group-action.js";
2
1
  import { Layer, Redacted } from "effect";
3
2
  import { HttpRouter } from "effect/unstable/http";
4
3
  import { type SessionExchange, type TokenVerifier } from "../authentication.js";
@@ -37,7 +36,6 @@ export { GUEST_LINK_PATH };
37
36
  */
38
37
  export declare const PAIRING_LIMIT: RateLimit;
39
38
  export interface AgentServerOptions {
40
- readonly publicGroupAction?: PublicActionOptions;
41
39
  readonly verifyToken: TokenVerifier;
42
40
  /**
43
41
  * The websites whose visitors get an agent token: as guests, and, while `web` is open to sign-up,
@@ -1,5 +1,4 @@
1
1
  import { chatPersona, chatPersonaNames, deployedChatPersonas } from "../../chat-personas.js";
2
- import { publicActionForGroup, groupSubject, } from "./public-group-action.js";
3
2
  import { isAllowed, effectiveScope } from "../../permissions.js";
4
3
  import { confirmationCommand } from "./confirmations.js";
5
4
  import { randomUUID } from "node:crypto";
@@ -11,7 +10,7 @@ import { API_KEY_PREFIX } from "../../runtime/principals.js";
11
10
  import { schemaIssues } from "../../runtime/validation.js";
12
11
  import { BASE_PATH } from "../api.js";
13
12
  import { CurrentPrincipal, withPrincipal, } from "../authentication.js";
14
- import { RequestId, errorBodyForWire, failureResponse, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
13
+ import { RequestId, errorBodyForWire, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
15
14
  import { secretHash } from "../oauth/protocol.js";
16
15
  import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
17
16
  import { OntologyBackend } from "../runtime-contract.js";
@@ -198,7 +197,7 @@ function resolveIdentity(store, agentTools) {
198
197
  });
199
198
  }
200
199
  /** Runtime-only admission; expected refusals and limits are 200 discriminated results. */
201
- function resolveChannelIdentity(store, agentTools) {
200
+ function resolveChannelIdentity(store, agentTools, guest) {
202
201
  return (request) => Effect.gen(function* () {
203
202
  const requestId = yield* RequestId;
204
203
  const decoded = Schema.decodeUnknownResult(ResolveIdentityRequest)(yield* jsonBody(request), {
@@ -223,6 +222,12 @@ function resolveChannelIdentity(store, agentTools) {
223
222
  status: resolution.status,
224
223
  ...memberForWire(resolution.member, agentTools),
225
224
  provisioned: resolution.provisioned,
225
+ ...(input.chat === "group" &&
226
+ guest?.channels.some((channel) => (channel.startsWith("channel:")
227
+ ? store.channelKind?.(channel.slice(8))
228
+ : channel) === input.provider)
229
+ ? { separate_session: true }
230
+ : {}),
226
231
  counted: resolution.counted,
227
232
  notice_due: resolution.noticeDue,
228
233
  on_new_user_pending: resolution.onNewUserPending,
@@ -882,7 +887,7 @@ export function agentLayer(options) {
882
887
  yield* router.add("POST", `${PAIRINGS_PATH}/:code/approve`, asMember((_, member) => approvePairing(store, member)));
883
888
  yield* router.add("GET", IDENTITIES_PATH, asMember((_, member) => listIdentities(store, member)));
884
889
  yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store, options.agentTools), { delegated: true }));
885
- yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store, options.agentTools)));
890
+ yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store, options.agentTools, options.guest)));
886
891
  yield* router.add("POST", `${IDENTITIES_PATH}/notice`, asRuntime(recordNotice(store)));
887
892
  yield* router.add("POST", `${IDENTITIES_PATH}/limit-notice`, asRuntime(completeLimitNotice(store)));
888
893
  for (const blocked of [true, false]) {
@@ -1017,7 +1022,7 @@ export function agentLayer(options) {
1017
1022
  })));
1018
1023
  }
1019
1024
  if (store.readGroupAccess) {
1020
- yield* router.add("POST", `${AGENT_PATH}/chats/public-invite`, asRuntime((request) => Effect.gen(function* () {
1025
+ yield* router.add("POST", `${AGENT_PATH}/chats/invite`, asRuntime((request) => Effect.gen(function* () {
1021
1026
  const requestId = yield* RequestId;
1022
1027
  const decoded = Schema.decodeUnknownResult(Schema.Struct({
1023
1028
  key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)),
@@ -1028,6 +1033,11 @@ export function agentLayer(options) {
1028
1033
  return invalidBody(requestId, schemaIssues(decoded.failure));
1029
1034
  }
1030
1035
  const { key, provider, inviter } = decoded.success;
1036
+ const channel = key.split(":", 1)[0];
1037
+ if (!options.guest?.openOnInvite?.includes(channel) ||
1038
+ store.channelKind?.(channel) !== provider) {
1039
+ return json({ opened: false });
1040
+ }
1031
1041
  const identity = yield* store.findIdentity({ provider, externalId: inviter });
1032
1042
  const principal = identity && identity.revokedAt === null
1033
1043
  ? yield* store.actingMember(identity.userId, provider)
@@ -1049,57 +1059,42 @@ export function agentLayer(options) {
1049
1059
  return json({ opened: Exit.isSuccess(result) });
1050
1060
  })));
1051
1061
  }
1052
- const readAccess = store.readGroupAccess;
1053
- const countPublicTurn = store.web?.countGuestTurn;
1054
- if (readAccess && options.publicGroupAction) {
1055
- const run = publicActionForGroup(backend, options.publicGroupAction);
1056
- yield* router.add("POST", `${AGENT_PATH}/chats/public-action`, asRuntime((request) => Effect.gen(function* () {
1062
+ if (store.channelGuest && store.web?.countGuestTurn) {
1063
+ const admit = store.channelGuest;
1064
+ const count = store.web.countGuestTurn;
1065
+ yield* router.add("POST", `${AGENT_PATH}/chats/admit-guest`, asRuntime((request) => Effect.gen(function* () {
1057
1066
  const requestId = yield* RequestId;
1058
1067
  const part = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
1059
- const decoded = Schema.decodeUnknownResult(Schema.Struct({
1068
+ const parsed = Schema.decodeUnknownResult(Schema.Struct({
1060
1069
  channel: part,
1061
1070
  chat: part,
1062
1071
  sender: part,
1063
- input: Schema.Record(Schema.String, Schema.Unknown),
1064
- }))(yield* jsonBody(request), { onExcessProperty: "error" });
1065
- if (Result.isFailure(decoded)) {
1066
- return invalidBody(requestId, schemaIssues(decoded.failure));
1067
- }
1068
- const { channel, chat, sender, input } = decoded.success;
1069
- if (JSON.stringify(input).length > 12000 ||
1070
- (yield* readAccess(`${channel}:${chat}`)) !== "public") {
1071
- return toServerResponse(forbidden(requestId, "Public action unavailable."));
1072
- }
1073
- return yield* run(request, { channel, chat, sender }, input).pipe(Effect.map((result) => json({ result })), Effect.catchCause((cause) => failureResponse(cause, requestId)));
1074
- })));
1075
- }
1076
- if (readAccess && countPublicTurn) {
1077
- yield* router.add("POST", `${AGENT_PATH}/chats/public-turn`, asRuntime((request) => Effect.gen(function* () {
1078
- const requestId = yield* RequestId;
1079
- const keyPart = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
1080
- const decoded = Schema.decodeUnknownResult(Schema.Struct({
1081
- channel: keyPart,
1082
- chat: keyPart,
1083
- sender: keyPart,
1084
- check: Schema.optionalKey(Schema.Boolean),
1072
+ message: Schema.optionalKey(part),
1073
+ purpose: Schema.optionalKey(Schema.Literal("identify")),
1085
1074
  limits: Schema.optionalKey(AgentLimitsRequest),
1086
1075
  }))(yield* jsonBody(request), { onExcessProperty: "error" });
1087
- if (Result.isFailure(decoded)) {
1088
- return invalidBody(requestId, schemaIssues(decoded.failure));
1076
+ if (Result.isFailure(parsed)) {
1077
+ return invalidBody(requestId, schemaIssues(parsed.failure));
1089
1078
  }
1090
- const { channel, chat, sender, limits } = decoded.success;
1091
- const access = yield* readAccess(`${channel}:${chat}`);
1092
- if (access !== "public") {
1079
+ const { channel, chat, sender, limits } = parsed.success;
1080
+ const principal = yield* admit(channel, chat, sender);
1081
+ if (!principal) {
1093
1082
  return json({ status: "closed" });
1094
1083
  }
1095
- if (decoded.success.check) {
1096
- return json({ status: "public" });
1097
- }
1098
- // The same sender shares a guest budget across groups on this connection.
1099
- // The id is for accounting only and never represents a workspace principal.
1100
- const guestId = groupSubject(["group-guest", channel, sender]);
1101
- const limited = yield* countPublicTurn(guestId, limits);
1102
- return json(limited ? { status: "limited" } : { status: "admitted", guestId });
1084
+ const limited = parsed.success.purpose === "identify"
1085
+ ? undefined
1086
+ : yield* count(principal.id, limits, parsed.success.message
1087
+ ? JSON.stringify([channel, chat, parsed.success.message])
1088
+ : undefined);
1089
+ return json(limited
1090
+ ? { status: "limited" }
1091
+ : {
1092
+ status: "guest",
1093
+ guestId: principal.id,
1094
+ ...(options.guest?.confirmations && { confirmations: true }),
1095
+ roles: principal.roles,
1096
+ agentTools: options.agentTools(principal),
1097
+ });
1103
1098
  })));
1104
1099
  }
1105
1100
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
@@ -1171,7 +1166,7 @@ export function agentLayer(options) {
1171
1166
  // Where an emailed link lands, signed in on the app's origin: a top-level navigation.
1172
1167
  yield* router.add("GET", GUEST_LINK_PATH, guests.link);
1173
1168
  }
1174
- if (websites.guests.length > 0 || readAccess !== undefined) {
1169
+ if (websites.guests.length > 0 || store.channelGuest !== undefined) {
1175
1170
  yield* router.add("POST", GUEST_USAGE_PATH, asRuntime(recordGuestUsage(store.web)));
1176
1171
  }
1177
1172
  }
@@ -488,7 +488,7 @@ export function actingChat(principal, provider, chat, kindOf = (channel) => chan
488
488
  * runtime may call only the agent's own routes, which authenticate it themselves. The chat it names
489
489
  * becomes the principal's, as {@link actingChat} admits it.
490
490
  */
491
- function actingMember(actAs, provider, grant, guests = false, chat) {
491
+ function actingMember(actAs, provider, grant, guests = false, chat, sender) {
492
492
  return Effect.gen(function* () {
493
493
  const backend = yield* OntologyBackend;
494
494
  if (actAs === undefined) {
@@ -507,7 +507,18 @@ function actingMember(actAs, provider, grant, guests = false, chat) {
507
507
  ? undefined
508
508
  : provider === WEB_PROVIDER
509
509
  ? yield* webMember(backend.agents, actAs, grant)
510
- : yield* backend.agents.actingMember(actAs, provider);
510
+ : actAs.startsWith("guest:")
511
+ ? guests &&
512
+ sender &&
513
+ chat &&
514
+ backend.agents.channelGuest &&
515
+ provider === backend.agents.channelKind?.(chat.provider)
516
+ ? yield* backend.agents.channelGuest(chat.provider, chat.chatId, sender)
517
+ : undefined
518
+ : yield* backend.agents.actingMember(actAs, provider);
519
+ if (member?.kind === "guest" && actAs !== `guest:${member.id}`) {
520
+ return { status: "forbidden", detail: "The guest does not match this sender." };
521
+ }
511
522
  const acting = member === undefined
512
523
  ? undefined
513
524
  : actingChat(member, provider, chat, backend.agents?.channelKind);
@@ -707,7 +718,7 @@ export function authenticate(credential, verifyToken, options = {}) {
707
718
  };
708
719
  }
709
720
  const resolved = agentTask === undefined
710
- ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true, options.runtime.chat)
721
+ ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true, options.runtime.chat, options.runtime.sender)
711
722
  : yield* agentTaskPrincipal(agentTask, actAs, options.agentTasks);
712
723
  // Narrowed, the request keeps only the reads of whom it acts for, as an OAuth grant of
713
724
  // that scope does.
@@ -1,6 +1,6 @@
1
1
  import { isValueMatched } from "../manifest.js";
2
- import { isAllowed } from "../permissions.js";
3
- import { actionPermission, modelMetricsFor } from "../render.js";
2
+ import { allowsAction, isAllowed } from "../permissions.js";
3
+ import { actionRequirement, modelMetricsFor } from "../render.js";
4
4
  /**
5
5
  * The catalog for a reader: the manifest, with each entity's actions narrowed to the ones the given
6
6
  * permissions may run, and only the metrics of the model whose every input entity they may read.
@@ -29,7 +29,7 @@ export function catalogFor(manifest, permissions) {
29
29
  isAllowed(entity.permissions?.read ?? `${entity.name}:read`, { permissions }))
30
30
  .map((entity) => ({
31
31
  ...entity,
32
- actions: entity.actions.filter((action) => isAllowed(actionPermission(entity.name, action), { permissions })),
32
+ actions: entity.actions.filter((action) => allowsAction(actionRequirement(entity.name, action), { permissions })),
33
33
  })),
34
34
  };
35
35
  }
@@ -10,7 +10,7 @@ import type { Destination } from "./resolve.js";
10
10
  export declare const CHAT_DRAFT_PERMISSION = "agent_chat:draft";
11
11
  /** The key prefix of a draft the agent writes on request: `request:<request>`. */
12
12
  export declare const REQUESTED_DRAFT_KEY = "request:";
13
- /** A private chat the inbox registered, as `agent_chat.send` and `postMessage` find it. */
13
+ /** A private chat the inbox registered, as `agent_chat.send` finds it in either voice. */
14
14
  export interface DraftChat {
15
15
  readonly target: Destination;
16
16
  readonly chatId: string;