@segmentstream/ontology 0.178.0 → 0.179.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.179.0
4
+
5
+ Opened groups can use a workspace-authored response handler and one explicitly granted ontology action. The action acts for a sender scoped to that group.
6
+
3
7
  ## 0.178.0
4
8
 
5
9
  `agent_chat.draft` asks the agent for a draft in an email thread's chat (`chats: "thread"` on the
package/dist/analyze.d.ts CHANGED
@@ -30,6 +30,13 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
30
30
  * Builders default to declared roles explicitly granting user:grantRoles or user:*.
31
31
  */
32
32
  readonly feedback?: boolean | FeedbackOptions;
33
+ /** One workspace-authored action that the agent may invoke for a sender in an opened group.
34
+ * The named role must grant the action. This does not assign that role to a user. */
35
+ readonly publicGroupAction?: {
36
+ readonly entity: string;
37
+ readonly action: string;
38
+ readonly role: string;
39
+ };
33
40
  /** Opt-in after-commit service execution; only this declared role supplies permissions. */
34
41
  readonly hooks?: {
35
42
  readonly role: string;
package/dist/analyze.js CHANGED
@@ -323,6 +323,22 @@ export function analyze(config, options = {}) {
323
323
  chat = { ...chat, retentionDays };
324
324
  }
325
325
  }
326
+ if (config.publicGroupAction !== undefined) {
327
+ const binding = config.publicGroupAction;
328
+ const validKeys = isPlainObject(binding) &&
329
+ [binding.entity, binding.action, binding.role].every((key) => typeof key === "string" && key.length > 0);
330
+ const target = validKeys
331
+ ? resolved
332
+ .find((item) => item.name === nameToWire(binding.entity))
333
+ ?.actions.find((item) => item.name === nameToWire(binding.action))
334
+ : undefined;
335
+ const role = validKeys
336
+ ? roles.find((item) => item.name === nameToWire(binding.role) && !isImplicitRole(item))
337
+ : undefined;
338
+ if (!target || target.action.confirm || !role?.permissions.includes(target.permission)) {
339
+ report("invalid-permission", "publicGroupAction", "Name an authored action without a member confirmation and a role explicitly granting that action.");
340
+ }
341
+ }
326
342
  checkEntityIdentities(resolved, report);
327
343
  checkMemberNames(resolved, report);
328
344
  const toolsets = resolveToolsets(original.toolsets, resolved, connections, report);
@@ -0,0 +1,23 @@
1
+ import { Effect } from "effect";
2
+ import type { HttpServerRequest } from "effect/unstable/http";
3
+ import { makeOperations } from "../operations.js";
4
+ type Resources = Parameters<typeof makeOperations>;
5
+ export interface PublicActionOptions {
6
+ readonly binding: {
7
+ role: string;
8
+ entity: string;
9
+ action: string;
10
+ };
11
+ readonly plan: Resources[1];
12
+ readonly hooks: Resources[2];
13
+ readonly connections: Resources[3];
14
+ readonly replicate: Resources[4];
15
+ }
16
+ /** Stable UUID in the given namespace. A group action's sender is scoped to that chat. */
17
+ export declare function groupSubject(parts: readonly string[]): string;
18
+ export declare function publicActionForGroup(backend: Resources[0], options: PublicActionOptions): (request: HttpServerRequest.HttpServerRequest, source: {
19
+ channel: string;
20
+ chat: string;
21
+ sender: string;
22
+ }, input: Readonly<Record<string, unknown>>) => Effect.Effect<{} | null, import("../../errors.js").ActionError | import("../../connection.js").ConnectionError | import("../../runtime/errors.js").WorkflowRecoveryUnavailable | import("../../runtime/errors.js").TriggerInputInvalid | import("../errors.js").InvalidActionInput, import("../errors.js").RequestId>;
23
+ export {};
@@ -0,0 +1,53 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Effect } from "effect";
3
+ import { nameToWire } from "../../authoring-names.js";
4
+ import { principalScopes, isAllowed } from "../../permissions.js";
5
+ import { CurrentPrincipal } from "../authentication.js";
6
+ import { makeOperations, identityToken } from "../operations.js";
7
+ /** Stable UUID in the given namespace. A group action's sender is scoped to that chat. */
8
+ export function groupSubject(parts) {
9
+ const bytes = createHash("sha256").update(JSON.stringify(parts)).digest();
10
+ bytes[6] = (bytes[6] & 15) | 80;
11
+ bytes[8] = (bytes[8] & 63) | 128;
12
+ const hex = bytes.toString("hex");
13
+ return [
14
+ hex.slice(0, 8),
15
+ hex.slice(8, 12),
16
+ hex.slice(12, 16),
17
+ hex.slice(16, 20),
18
+ hex.slice(20, 32),
19
+ ].join("-");
20
+ }
21
+ export function publicActionForGroup(backend, options) {
22
+ const { plan, binding } = options;
23
+ const entity = plan.entities.find((item) => item.name === nameToWire(binding.entity));
24
+ const action = entity?.actions.find((item) => !item.generated && item.name === nameToWire(binding.action));
25
+ const role = plan.ontology.roles.find((item) => item.name === nameToWire(binding.role));
26
+ const operations = makeOperations(backend, plan, options.hooks, options.connections, options.replicate);
27
+ return (request, source, input) => Effect.gen(function* () {
28
+ if (!entity || !action || action.action.confirm || !role) {
29
+ return yield* Effect.die(new Error("Invalid public group action."));
30
+ }
31
+ const permissions = action.permissions.filter((permission) => role.permissions.includes(permission));
32
+ const principal = {
33
+ kind: "guest",
34
+ id: groupSubject(["public-action", source.channel, source.chat, source.sender]),
35
+ roles: [role.name],
36
+ permissions,
37
+ ...principalScopes([role], [role.name]),
38
+ chat: { provider: source.channel, chatId: source.chat },
39
+ };
40
+ if (!action.permissions.every((p) => isAllowed(p, principal))) {
41
+ return yield* Effect.die(new Error("Public group action denied."));
42
+ }
43
+ const answer = yield* operations
44
+ .runAction(entity, action, {
45
+ input,
46
+ options: {},
47
+ validateOnly: false,
48
+ identityToken: identityToken(request),
49
+ })
50
+ .pipe(Effect.provideService(CurrentPrincipal, principal));
51
+ return answer.result;
52
+ });
53
+ }
@@ -1,3 +1,4 @@
1
+ import { type PublicActionOptions } from "./public-group-action.js";
1
2
  import { Layer, Redacted } from "effect";
2
3
  import { HttpRouter } from "effect/unstable/http";
3
4
  import { type SessionExchange, type TokenVerifier } from "../authentication.js";
@@ -33,6 +34,7 @@ export { GUEST_LINK_PATH };
33
34
  */
34
35
  export declare const PAIRING_LIMIT: RateLimit;
35
36
  export interface AgentServerOptions {
37
+ readonly publicGroupAction?: PublicActionOptions;
36
38
  readonly verifyToken: TokenVerifier;
37
39
  /**
38
40
  * The websites whose visitors get an agent token: as guests, and, while `web` is open to sign-up,
@@ -1,7 +1,8 @@
1
1
  import { chatPersona, chatPersonaNames, deployedChatPersonas } from "../../chat-personas.js";
2
+ import { publicActionForGroup, groupSubject, } from "./public-group-action.js";
2
3
  import { isAllowed, effectiveScope } from "../../permissions.js";
3
4
  import { confirmationCommand } from "./confirmations.js";
4
- import { createHash, randomUUID } from "node:crypto";
5
+ import { randomUUID } from "node:crypto";
5
6
  import { Effect, Exit, Layer, Redacted, Result, Schema } from "effect";
6
7
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
7
8
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
@@ -10,7 +11,7 @@ import { API_KEY_PREFIX } from "../../runtime/principals.js";
10
11
  import { schemaIssues } from "../../runtime/validation.js";
11
12
  import { BASE_PATH } from "../api.js";
12
13
  import { CurrentPrincipal, withPrincipal, } from "../authentication.js";
13
- import { RequestId, errorBodyForWire, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
14
+ import { RequestId, errorBodyForWire, failureResponse, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
14
15
  import { secretHash } from "../oauth/protocol.js";
15
16
  import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
16
17
  import { OntologyBackend } from "../runtime-contract.js";
@@ -886,6 +887,28 @@ export function agentLayer(options) {
886
887
  }
887
888
  const readAccess = store.readGroupAccess;
888
889
  const countPublicTurn = store.web?.countGuestTurn;
890
+ if (readAccess && options.publicGroupAction) {
891
+ const run = publicActionForGroup(backend, options.publicGroupAction);
892
+ yield* router.add("POST", `${AGENT_PATH}/chats/public-action`, asRuntime((request) => Effect.gen(function* () {
893
+ const requestId = yield* RequestId;
894
+ const part = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
895
+ const decoded = Schema.decodeUnknownResult(Schema.Struct({
896
+ channel: part,
897
+ chat: part,
898
+ sender: part,
899
+ input: Schema.Record(Schema.String, Schema.Unknown),
900
+ }))(yield* jsonBody(request), { onExcessProperty: "error" });
901
+ if (Result.isFailure(decoded)) {
902
+ return invalidBody(requestId, schemaIssues(decoded.failure));
903
+ }
904
+ const { channel, chat, sender, input } = decoded.success;
905
+ if (JSON.stringify(input).length > 12000 ||
906
+ (yield* readAccess(`${channel}:${chat}`)) !== "public") {
907
+ return toServerResponse(forbidden(requestId, "Public action unavailable."));
908
+ }
909
+ return yield* run(request, { channel, chat, sender }, input).pipe(Effect.map((result) => json({ result })), Effect.catchCause((cause) => failureResponse(cause, requestId)));
910
+ })));
911
+ }
889
912
  if (readAccess && countPublicTurn) {
890
913
  yield* router.add("POST", `${AGENT_PATH}/chats/public-turn`, asRuntime((request) => Effect.gen(function* () {
891
914
  const requestId = yield* RequestId;
@@ -910,19 +933,7 @@ export function agentLayer(options) {
910
933
  }
911
934
  // The same sender shares a guest budget across groups on this connection.
912
935
  // The id is for accounting only and never represents a workspace principal.
913
- const bytes = createHash("sha256")
914
- .update(JSON.stringify(["group-guest", channel, sender]))
915
- .digest();
916
- bytes[6] = (bytes[6] & 15) | 80;
917
- bytes[8] = (bytes[8] & 63) | 128;
918
- const hex = bytes.toString("hex");
919
- const guestId = [
920
- hex.slice(0, 8),
921
- hex.slice(8, 12),
922
- hex.slice(12, 16),
923
- hex.slice(16, 20),
924
- hex.slice(20, 32),
925
- ].join("-");
936
+ const guestId = groupSubject(["group-guest", channel, sender]);
926
937
  const limited = yield* countPublicTurn(guestId, limits);
927
938
  return json(limited ? { status: "limited" } : { status: "admitted", guestId });
928
939
  })));
@@ -456,6 +456,16 @@ export function createOntologyService(ontology, config) {
456
456
  verifyToken,
457
457
  verifyRuntime,
458
458
  exchangeSession,
459
+ ...(!preview &&
460
+ ontology.config.publicGroupAction && {
461
+ publicGroupAction: {
462
+ binding: ontology.config.publicGroupAction,
463
+ plan,
464
+ hooks,
465
+ connections,
466
+ replicate,
467
+ },
468
+ }),
459
469
  visitorWebsites: preview ? { guests: [], signUp: [] } : visitorWebsites,
460
470
  agentTools,
461
471
  guest: preview ? undefined : guest,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.178.0",
3
+ "version": "0.179.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",