@segmentstream/ontology 0.94.0 → 0.95.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 +24 -3
  2. package/dist/analyze.js +9 -2
  3. package/dist/index.d.ts +5 -5
  4. package/dist/index.js +3 -3
  5. package/dist/manifest-compatibility.d.ts +7 -0
  6. package/dist/manifest-compatibility.js +12 -0
  7. package/dist/migrate/apply.d.ts +3 -2
  8. package/dist/migrate/apply.js +6 -2
  9. package/dist/migrate/plan.js +9 -1
  10. package/dist/migrate/storage.d.ts +7 -0
  11. package/dist/migrate/storage.js +22 -12
  12. package/dist/permissions.d.ts +9 -0
  13. package/dist/permissions.js +8 -0
  14. package/dist/runtime/channel-identity-admin.d.ts +41 -0
  15. package/dist/runtime/channel-identity-admin.js +223 -0
  16. package/dist/runtime/generated-actions.d.ts +2 -1
  17. package/dist/runtime/generated-actions.js +71 -3
  18. package/dist/runtime/principals.d.ts +24 -3
  19. package/dist/runtime/principals.js +42 -8
  20. package/dist/runtime/service-binding.js +2 -1
  21. package/dist/runtime/sql-runtime.d.ts +14 -1
  22. package/dist/runtime/sql-runtime.js +9 -0
  23. package/dist/runtime/user-identities.d.ts +5 -3
  24. package/dist/runtime/user-identities.js +9 -4
  25. package/dist/runtime/user-identity-sql.d.ts +4 -1
  26. package/dist/runtime/user-identity-sql.js +5 -2
  27. package/dist/runtime-source.d.ts +6 -0
  28. package/dist/runtime-source.js +11 -0
  29. package/dist/service/agent/attachments.js +4 -0
  30. package/dist/service/agent/authentication.d.ts +74 -2
  31. package/dist/service/agent/authentication.js +93 -11
  32. package/dist/service/agent/files.js +8 -1
  33. package/dist/service/agent/server.js +13 -2
  34. package/dist/service/authentication.js +58 -2
  35. package/dist/service/caller-context.d.ts +16 -0
  36. package/dist/service/chat/envelope.d.ts +18 -0
  37. package/dist/service/chat/envelope.js +10 -0
  38. package/dist/service/errors.d.ts +3 -2
  39. package/dist/service/errors.js +9 -3
  40. package/dist/service/runtime-contract.d.ts +9 -0
  41. package/dist/storage/attachments.d.ts +11 -0
  42. package/dist/user-identity.d.ts +14 -5
  43. package/dist/user-identity.js +25 -5
  44. package/package.json +1 -1
@@ -2,7 +2,8 @@ import { Effect, Redacted } from "effect";
2
2
  import { HttpServerRequest } from "effect/unstable/http";
3
3
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { RequestId, forbidden, notFound, toServerResponse, unauthorized, unavailable, } from "../errors.js";
5
- import { ACT_AS_HEADER, AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
5
+ import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
+ import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
6
7
  export const CONVERSATION_HEADER = "x-segmentstream-agent-conversation";
7
8
  export const SESSION_HEADER = "x-segmentstream-agent-session";
8
9
  const CONVERSATION = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_-]{1,200}$/;
@@ -15,8 +16,18 @@ export function authenticateAgentCaller(input) {
15
16
  const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
16
17
  const bearer = yield* Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
17
18
  const token = Redacted.value(bearer);
18
- const verified = token === "" ? undefined : yield* Effect.promise(() => verify(token));
19
19
  const denied = (response) => ({ ok: false, response: toServerResponse(response) });
20
+ if (input.resolveApiKey !== undefined && token.startsWith(API_KEY_PREFIX)) {
21
+ const delegated = yield* delegatedAgentMember(request, agents, input.resolveApiKey, bearer);
22
+ if (delegated.status === "rejected") {
23
+ return denied(unauthorized(requestId, "The bearer token is invalid, expired or revoked."));
24
+ }
25
+ if (delegated.status === "refused") {
26
+ return denied(forbidden(requestId, delegated.detail));
27
+ }
28
+ return agentCaller(request, requestId, delegated.member, delegated.client);
29
+ }
30
+ const verified = token === "" ? undefined : yield* Effect.promise(() => verify(token));
20
31
  switch (verified?.status) {
21
32
  case "valid":
22
33
  break;
@@ -33,8 +44,6 @@ export function authenticateAgentCaller(input) {
33
44
  return denied(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
34
45
  }
35
46
  const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
36
- const conversation = request.headers[CONVERSATION_HEADER]?.trim() ?? "";
37
- const session = request.headers[SESSION_HEADER]?.trim() ?? "";
38
47
  const member = actAs === ""
39
48
  ? undefined
40
49
  : input.allowUnpairedMember
@@ -45,14 +54,87 @@ export function authenticateAgentCaller(input) {
45
54
  ? notFound(requestId, "Attachment not found.")
46
55
  : forbidden(requestId, "The member is inactive or has not paired with the agent."));
47
56
  }
48
- if (!CONVERSATION.test(conversation) || (session !== "" && !SESSION.test(session))) {
49
- return denied(forbidden(requestId, "The agent names the chat and session of every request."));
57
+ return agentCaller(request, requestId, member);
58
+ });
59
+ }
60
+ /** The chat and session every agent request names, with the member it acts for. */
61
+ function agentCaller(request, requestId, member, delegatedBy) {
62
+ const conversation = request.headers[CONVERSATION_HEADER]?.trim() ?? "";
63
+ const session = request.headers[SESSION_HEADER]?.trim() ?? "";
64
+ if (!CONVERSATION.test(conversation) || (session !== "" && !SESSION.test(session))) {
65
+ return {
66
+ ok: false,
67
+ response: toServerResponse(forbidden(requestId, "The agent names the chat and session of every request.")),
68
+ };
69
+ }
70
+ const caller = {
71
+ principal: member,
72
+ conversation,
73
+ ...(session === "" ? {} : { sessionId: session }),
74
+ ...(delegatedBy === undefined ? {} : { delegatedBy }),
75
+ };
76
+ return { ok: true, caller };
77
+ }
78
+ /**
79
+ * The member an external runtime with an API key with delegation acts for on an agent route: the
80
+ * member `X-SegmentStream-Act-As` names, who must be active and hold a live account of the provider
81
+ * `X-SegmentStream-Identity-Provider` names, even where the app's own agent needs no pairing. An
82
+ * ordinary API key, and a task's secret, are refused.
83
+ */
84
+ export function delegatedAgentMember(request, agents, resolveApiKey, bearer) {
85
+ return Effect.gen(function* () {
86
+ const resolved = yield* resolveApiKey(bearer);
87
+ if (resolved === undefined) {
88
+ return { status: "rejected" };
89
+ }
90
+ if (!resolved.delegation) {
91
+ return { status: "refused", detail: "Only the app's agent calls this route." };
50
92
  }
51
- const caller = {
52
- principal: member,
53
- conversation,
54
- ...(session === "" ? {} : { sessionId: session }),
93
+ if (agentTaskSecret(request) !== undefined) {
94
+ return {
95
+ status: "refused",
96
+ detail: `An API key with delegation never presents ${AGENT_TASK_HEADER}.`,
97
+ };
98
+ }
99
+ const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
100
+ const provider = request.headers[ACT_AS_PROVIDER_HEADER]?.trim() ?? "";
101
+ if (actAs === "" || provider === "") {
102
+ return {
103
+ status: "refused",
104
+ detail: `An API key with delegation names the member in ${ACT_AS_HEADER} and the provider of ` +
105
+ `their account in ${ACT_AS_PROVIDER_HEADER}.`,
106
+ };
107
+ }
108
+ const delegated = yield* delegatedAccount(agents, actAs, provider);
109
+ if (delegated === undefined) {
110
+ return {
111
+ status: "refused",
112
+ detail: `The member is inactive or has no live ${provider} account.`,
113
+ };
114
+ }
115
+ return {
116
+ status: "member",
117
+ member: delegated.member,
118
+ client: { id: resolved.principal.id, account: delegated.account },
55
119
  };
56
- return { ok: true, caller };
120
+ });
121
+ }
122
+ /**
123
+ * The active, unblocked member an API key with delegation acts for, with their roles now and
124
+ * `authenticatedVia` the provider, and the live chat account of that provider it acts through;
125
+ * `undefined` for anyone else.
126
+ */
127
+ export function delegatedAccount(agents, actAs, provider) {
128
+ return Effect.gen(function* () {
129
+ const member = yield* agents.actingMember(actAs, provider);
130
+ const account = member === undefined
131
+ ? undefined
132
+ : (yield* agents.listIdentities(member.id)).find((identity) => identity.provider === provider && identity.revokedAt === null);
133
+ return member === undefined || member.kind !== "member" || account === undefined
134
+ ? undefined
135
+ : {
136
+ member: { ...member, authenticatedVia: provider },
137
+ account: { provider: account.provider, subject: account.externalId },
138
+ };
57
139
  });
58
140
  }
@@ -19,7 +19,14 @@ export function filesLayer(options) {
19
19
  }
20
20
  const read = (request) => Effect.gen(function* () {
21
21
  const requestId = yield* RequestId;
22
- const authenticated = yield* authenticateAgentCaller({ request, agents, verify });
22
+ const authenticated = yield* authenticateAgentCaller({
23
+ request,
24
+ agents,
25
+ verify,
26
+ ...(backend.resolveApiKeyCredential === undefined
27
+ ? {}
28
+ : { resolveApiKey: backend.resolveApiKeyCredential }),
29
+ });
23
30
  if (!authenticated.ok) {
24
31
  return authenticated.response;
25
32
  }
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { Effect, Layer, Redacted, Result, Schema } from "effect";
4
4
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
5
5
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
6
+ import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
7
  import { schemaIssues } from "../../runtime/validation.js";
7
8
  import { BASE_PATH } from "../api.js";
8
9
  import { CurrentPrincipal, withPrincipal, } from "../authentication.js";
@@ -307,10 +308,20 @@ export function agentLayer(options) {
307
308
  const limiter = fixedWindowLimiter(PAIRING_LIMIT);
308
309
  const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
309
310
  const bearerOf = (request) => Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
310
- const asRuntime = (answer) => (request) => Effect.gen(function* () {
311
+ const asRuntime = (answer, route = {}) => (request) => Effect.gen(function* () {
311
312
  const requestId = yield* RequestId;
312
313
  const bearer = yield* bearerOf(request);
313
314
  const token = Redacted.value(bearer);
315
+ if (route.delegated === true &&
316
+ token.startsWith(API_KEY_PREFIX) &&
317
+ backend.resolveApiKeyCredential !== undefined) {
318
+ const resolved = yield* backend.resolveApiKeyCredential(bearer);
319
+ if (resolved?.delegation === true) {
320
+ return agentTaskSecret(request) === undefined
321
+ ? yield* answer(request)
322
+ : toServerResponse(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
323
+ }
324
+ }
314
325
  const verified = options.verifyRuntime === undefined || token === ""
315
326
  ? undefined
316
327
  : yield* Effect.promise(() => options.verifyRuntime(token));
@@ -353,7 +364,7 @@ export function agentLayer(options) {
353
364
  yield* router.add("GET", `${PAIRINGS_PATH}/:code`, asMember(() => describePairing(store)));
354
365
  yield* router.add("POST", `${PAIRINGS_PATH}/:code/approve`, asMember((_, member) => approvePairing(store, member)));
355
366
  yield* router.add("GET", IDENTITIES_PATH, asMember((_, member) => listIdentities(store, member)));
356
- yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store)));
367
+ yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store), { delegated: true }));
357
368
  yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store)));
358
369
  yield* router.add("POST", `${IDENTITIES_PATH}/notice`, asRuntime(recordNotice(store)));
359
370
  yield* router.add("POST", `${IDENTITIES_PATH}/limit-notice`, asRuntime(completeLimitNotice(store)));
@@ -11,7 +11,8 @@ import { RequestId, crossOriginSession, forbidden, internalError, notInvited, to
11
11
  import { ACCESS_TOKEN_PREFIX, appSessionResource, publicOrigin, callerOfAccessToken, rejectedAccessToken, } from "./oauth/protocol.js";
12
12
  import { CurrentCaller } from "./caller-context.js";
13
13
  import { OntologyBackend } from "./runtime-contract.js";
14
- import { ACT_AS_HEADER, AGENT_TASK_HEADER, logRuntimeRejection, runtimeCredential, } from "./runtime-identity.js";
14
+ import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, logRuntimeRejection, runtimeCredential, } from "./runtime-identity.js";
15
+ import { delegatedAccount } from "./agent/authentication.js";
15
16
  import { agentTaskCaller } from "./agent/task-caller.js";
16
17
  import { ErrorSchemas } from "./schemas.js";
17
18
  const CLOCK_TOLERANCE_SECONDS = 5;
@@ -478,6 +479,53 @@ function actingMember(actAs, provider) {
478
479
  };
479
480
  });
480
481
  }
482
+ /**
483
+ * The member an API key with delegation acts for: an external agent runtime the workspace trusts,
484
+ * which names the member in `X-SegmentStream-Act-As` and the provider of the account they wrote
485
+ * from in `X-SegmentStream-Identity-Provider`, on the routes that accept the deployment's own
486
+ * runtime. The member must be active, unblocked and hold a live account of that provider; the
487
+ * request runs with the roles they hold now, and the key's own user grants nothing. A key with
488
+ * delegation never runs a workflow's task and never acts without naming a member.
489
+ */
490
+ function delegatedMember(client, runtime) {
491
+ return Effect.gen(function* () {
492
+ const backend = yield* OntologyBackend;
493
+ const refuse = (reason, detail) => Effect.logWarning("ontology.delegation.refused").pipe(Effect.annotateLogs({ client: client.id, reason }), Effect.as({ status: "forbidden", detail }));
494
+ if (runtime === undefined) {
495
+ return yield* refuse("route", "An API key with delegation acts for a member only on the routes the app's agent uses.");
496
+ }
497
+ if (runtime.agentTask !== undefined) {
498
+ return yield* refuse("agent_task", `An API key with delegation acts for a member; it never presents ${AGENT_TASK_HEADER}.`);
499
+ }
500
+ if (runtime.actAs === undefined) {
501
+ return yield* refuse("act_as", `An API key with delegation names the member it acts for in ${ACT_AS_HEADER}.`);
502
+ }
503
+ if (runtime.provider === undefined) {
504
+ return yield* refuse("provider", `An API key with delegation names the provider of the member's account in ` +
505
+ `${ACT_AS_PROVIDER_HEADER}.`);
506
+ }
507
+ const delegated = backend.agents === undefined
508
+ ? undefined
509
+ : yield* delegatedAccount(backend.agents, runtime.actAs, runtime.provider);
510
+ if (delegated === undefined) {
511
+ return yield* refuse("member", `The member is inactive or has no live ${runtime.provider} account.`);
512
+ }
513
+ yield* Effect.logInfo("ontology.delegation.authenticated").pipe(Effect.annotateLogs({
514
+ client: client.id,
515
+ member: delegated.member.id,
516
+ provider: runtime.provider,
517
+ }));
518
+ return {
519
+ status: "authenticated",
520
+ principal: delegated.member,
521
+ caller: {
522
+ kind: "runtime",
523
+ subjectId: delegated.member.id,
524
+ delegatedBy: { id: client.id, account: delegated.account },
525
+ },
526
+ };
527
+ });
528
+ }
481
529
  /**
482
530
  * The workflow user a verified runtime caller acts as while it runs a task a workflow handed it:
483
531
  * the task's secret names it, never the caller. Refused on a route that does not accept tasks, and
@@ -571,7 +619,15 @@ export function authenticate(credential, verifyToken, options = {}) {
571
619
  };
572
620
  }
573
621
  if (token.startsWith(API_KEY_PREFIX)) {
574
- const principal = yield* backend.resolveApiKey(credential);
622
+ const resolved = backend.resolveApiKeyCredential === undefined
623
+ ? yield* backend
624
+ .resolveApiKey(credential)
625
+ .pipe(Effect.map((principal) => principal === undefined ? undefined : { principal, delegation: false }))
626
+ : yield* backend.resolveApiKeyCredential(credential);
627
+ if (resolved?.delegation === true) {
628
+ return yield* delegatedMember(resolved.principal, options.runtime);
629
+ }
630
+ const principal = resolved?.principal;
575
631
  return principal === undefined
576
632
  ? { status: "rejected" }
577
633
  : {
@@ -11,7 +11,23 @@ export type VerifiedCaller = {
11
11
  } | {
12
12
  readonly kind: "runtime" | "service" | "member" | "workload";
13
13
  readonly subjectId: string;
14
+ /**
15
+ * Set only for a runtime caller that authenticated with an API key with delegation: the
16
+ * key's user, and the member's account the request acts through. Its runtime metadata must
17
+ * come from that account.
18
+ */
19
+ readonly delegatedBy?: DelegatingClient;
14
20
  };
21
+ /** An external agent runtime acting for a member with an API key with delegation. */
22
+ export interface DelegatingClient {
23
+ /** The key's user: the external runtime the workspace trusts. */
24
+ readonly id: string;
25
+ /** The member's live chat account the request acts through. */
26
+ readonly account: {
27
+ readonly provider: string;
28
+ readonly subject: string;
29
+ };
30
+ }
15
31
  export type CallerContext = VerifiedCaller | {
16
32
  readonly kind: "unverified";
17
33
  };
@@ -14,6 +14,12 @@ declare const RuntimeEnvelope: Schema.Struct<{
14
14
  readonly reply_to_message_id: Schema.optionalKey<Schema.String>;
15
15
  readonly callback_query_id: Schema.optionalKey<Schema.String>;
16
16
  readonly sender: Schema.optionalKey<Schema.String>;
17
+ readonly location: Schema.optionalKey<Schema.Struct<{
18
+ readonly latitude: Schema.Number;
19
+ readonly longitude: Schema.Number;
20
+ readonly horizontal_accuracy: Schema.optionalKey<Schema.Number>;
21
+ readonly live_period: Schema.optionalKey<Schema.Int>;
22
+ }>>;
17
23
  readonly attachments: Schema.optionalKey<Schema.$Array<Schema.Struct<{
18
24
  readonly file_id: Schema.String;
19
25
  readonly file_unique_id: Schema.optionalKey<Schema.String>;
@@ -48,6 +54,12 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
48
54
  readonly reply_to_message_id?: string | undefined;
49
55
  readonly callback_query_id?: string | undefined;
50
56
  readonly sender?: string | undefined;
57
+ readonly location?: {
58
+ readonly latitude: number;
59
+ readonly longitude: number;
60
+ readonly horizontal_accuracy?: number | undefined;
61
+ readonly live_period?: number | undefined;
62
+ } | undefined;
51
63
  readonly attachments?: readonly {
52
64
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
53
65
  readonly file_id: string;
@@ -94,6 +106,12 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
94
106
  readonly reply_to_message_id?: string | undefined;
95
107
  readonly callback_query_id?: string | undefined;
96
108
  readonly sender?: string | undefined;
109
+ readonly location?: {
110
+ readonly latitude: number;
111
+ readonly longitude: number;
112
+ readonly horizontal_accuracy?: number | undefined;
113
+ readonly live_period?: number | undefined;
114
+ } | undefined;
97
115
  readonly attachments?: readonly {
98
116
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
99
117
  readonly file_id: string;
@@ -34,6 +34,16 @@ export function consumeChatEnvelope(args, caller) {
34
34
  message: "The runtime operation does not match its call.",
35
35
  });
36
36
  }
37
+ // An external runtime acting with an API key with delegation vouches only for messages of the
38
+ // account it acts through: the source names that account as its sender, on its provider.
39
+ if (caller.delegatedBy !== undefined &&
40
+ parsed.source !== undefined &&
41
+ (parsed.source.provider !== caller.delegatedBy.account.provider ||
42
+ parsed.source.sender !== caller.delegatedBy.account.subject)) {
43
+ return yield* new PermissionDenied({
44
+ message: "The runtime source must name the member's own account as its sender, on its provider.",
45
+ });
46
+ }
37
47
  return { input, envelope: parsed };
38
48
  });
39
49
  }
@@ -137,8 +137,9 @@ export declare function routeNotFound(requestId: string, suggestions?: ReadonlyA
137
137
  */
138
138
  export declare function expectedFailure(error: unknown, requestId: string): ErrorResponse | undefined;
139
139
  /**
140
- * Turns a failed request into a response. Expected failures map to their status; anything else is
141
- * logged with the full cause and answered with a sanitized 500 that carries only the request id.
140
+ * Turns a failed request into a response. Expected failures map to their status, and those that map
141
+ * to a 5xx are logged with their full cause; anything else is logged with the full cause and
142
+ * answered with a sanitized 500 that carries only the request id.
142
143
  * Interruptions stay interruptions: the client is gone.
143
144
  */
144
145
  export declare function failureResponse(cause: Cause.Cause<unknown>, requestId: string): Effect.Effect<HttpServerResponse.HttpServerResponse>;
@@ -682,8 +682,9 @@ export function expectedFailure(error, requestId) {
682
682
  return undefined;
683
683
  }
684
684
  /**
685
- * Turns a failed request into a response. Expected failures map to their status; anything else is
686
- * logged with the full cause and answered with a sanitized 500 that carries only the request id.
685
+ * Turns a failed request into a response. Expected failures map to their status, and those that map
686
+ * to a 5xx are logged with their full cause; anything else is logged with the full cause and
687
+ * answered with a sanitized 500 that carries only the request id.
687
688
  * Interruptions stay interruptions: the client is gone.
688
689
  */
689
690
  export function failureResponse(cause, requestId) {
@@ -695,7 +696,12 @@ export function failureResponse(cause, requestId) {
695
696
  const error = typedFailure ?? (defect instanceof DeploymentAdmissionError ? defect : undefined);
696
697
  const expected = error === undefined ? undefined : expectedFailure(error, requestId);
697
698
  if (expected !== undefined) {
698
- return Effect.succeed(toServerResponse(expected));
699
+ const response = toServerResponse(expected);
700
+ // A mapped 5xx is still the service failing: keep its cause for operators under the request id
701
+ // the client sees. Client errors are the caller's and stay unlogged.
702
+ return expected.status >= 500
703
+ ? Effect.logError("ontology.request.failed", cause).pipe(Effect.annotateLogs({ requestId }), Effect.as(response))
704
+ : Effect.succeed(response);
699
705
  }
700
706
  if (isStorageFailure(error)) {
701
707
  return Effect.logError("ontology.storage.failed", cause).pipe(Effect.annotateLogs({ requestId }), Effect.as(toServerResponse(storageUnavailable(requestId))));
@@ -471,6 +471,15 @@ declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segm
471
471
  readonly checkSignIn: (email: string) => Effect.Effect<SignInCheck>;
472
472
  /** The user holding an `ssk_` key, or `undefined` for an unknown or revoked key. */
473
473
  readonly resolveApiKey: (key: Redacted.Redacted<string>) => Effect.Effect<Principal | undefined>;
474
+ /**
475
+ * The user holding an `ssk_` key and whether the key acts with delegation, only for the member
476
+ * each request names; `undefined` for an unknown or revoked key. Without it every key acts with
477
+ * its own user's roles, through {@link resolveApiKey}.
478
+ */
479
+ readonly resolveApiKeyCredential?: (key: Redacted.Redacted<string>) => Effect.Effect<{
480
+ readonly principal: Principal;
481
+ readonly delegation: boolean;
482
+ } | undefined>;
474
483
  /** The manifest hash recorded in the `_ontology` catalog table, or `undefined` before the first. */
475
484
  readonly appliedHash: Effect.Effect<string | undefined>;
476
485
  readonly replicationEnabled?: Effect.Effect<boolean>;
@@ -33,6 +33,17 @@ export interface AttachmentCaller {
33
33
  readonly sessionId?: string;
34
34
  /** Trusted user boundary; never accepted from agent tool arguments. */
35
35
  readonly access?: "member";
36
+ /**
37
+ * Set when an external runtime acts with an API key with delegation: the key's user and the
38
+ * member's account it acts through, which its runtime metadata must name as the sender.
39
+ */
40
+ readonly delegatedBy?: {
41
+ readonly id: string;
42
+ readonly account: {
43
+ readonly provider: string;
44
+ readonly subject: string;
45
+ };
46
+ };
36
47
  }
37
48
  export interface ReceiveAttachment {
38
49
  readonly source: (typeof ATTACHMENT_SOURCES)[number];
@@ -1,12 +1,21 @@
1
1
  /** How a sign-in identity came to be, as the `origin` property stores it. */
2
- export declare const USER_IDENTITY_ORIGINS: readonly ["invite", "sign_in", "link", "pairing", "channel"];
2
+ export declare const USER_IDENTITY_ORIGINS: readonly ["invite", "sign_in", "link", "pairing", "channel", "attach"];
3
3
  export type UserIdentityOrigin = (typeof USER_IDENTITY_ORIGINS)[number];
4
+ /**
5
+ * The chat providers whose accounts an administrator may attach to a member with
6
+ * `user_identity.attach`: the providers the app's agent talks on.
7
+ */
8
+ export declare const ATTACHABLE_IDENTITY_PROVIDERS: readonly ["telegram", "whatsapp", "slack"];
9
+ export type AttachableIdentityProvider = (typeof ATTACHABLE_IDENTITY_PROVIDERS)[number];
4
10
  /**
5
11
  * The built-in record of every external account a member signs in or talks with: their Neon Auth
6
12
  * account, their SegmentStream (OIDC) accounts and their channel accounts, such as Telegram. Every
7
- * ontology includes it next to `User` and `AgentChat`. Only the platform writes it, with history;
8
- * no generated or authored action does. Reading it needs a permission that names it, such as
9
- * `user_identity:read`: an entity wildcard (`*:read`, `*:*`) does not cover it.
13
+ * ontology includes it next to `User` and `AgentChat`. Only the platform writes it, with history:
14
+ * no generated `create`, `update` or `delete` exists and no authored action writes it. Its two
15
+ * platform actions, `attach` and `revoke`, let an administrator attach a chat account to a member
16
+ * and revoke one. Reading it, attaching and revoking each need a permission that names it, such
17
+ * as `user_identity:read` or `user_identity:attach`: an entity wildcard (`*:read`, `*:*`) does not
18
+ * cover it.
10
19
  *
11
20
  * At most one live identity holds an account, and a member holds at most one live identity per
12
21
  * provider other than `oidc`. Both are unique keys that hold a value only while the identity is
@@ -18,7 +27,7 @@ export declare const UserIdentity: import("./entity.js").DraftEntity<"user_ident
18
27
  readonly subject: import("./property.js").Property<string, false, false>;
19
28
  readonly username: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
20
29
  readonly display: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
21
- readonly origin: import("./property.js").Property<"link" | "invite" | "sign_in" | "pairing" | "channel", false, false>;
30
+ readonly origin: import("./property.js").Property<"link" | "invite" | "attach" | "sign_in" | "pairing" | "channel", false, false>;
22
31
  readonly revokedAt: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
23
32
  readonly accountKey: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, true>>;
24
33
  readonly memberKey: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, true>>;
@@ -2,13 +2,28 @@ import { entity } from "./entity.js";
2
2
  import { p } from "./property.js";
3
3
  import { rel } from "./relationship.js";
4
4
  /** How a sign-in identity came to be, as the `origin` property stores it. */
5
- export const USER_IDENTITY_ORIGINS = ["invite", "sign_in", "link", "pairing", "channel"];
5
+ export const USER_IDENTITY_ORIGINS = [
6
+ "invite",
7
+ "sign_in",
8
+ "link",
9
+ "pairing",
10
+ "channel",
11
+ "attach",
12
+ ];
13
+ /**
14
+ * The chat providers whose accounts an administrator may attach to a member with
15
+ * `user_identity.attach`: the providers the app's agent talks on.
16
+ */
17
+ export const ATTACHABLE_IDENTITY_PROVIDERS = ["telegram", "whatsapp", "slack"];
6
18
  /**
7
19
  * The built-in record of every external account a member signs in or talks with: their Neon Auth
8
20
  * account, their SegmentStream (OIDC) accounts and their channel accounts, such as Telegram. Every
9
- * ontology includes it next to `User` and `AgentChat`. Only the platform writes it, with history;
10
- * no generated or authored action does. Reading it needs a permission that names it, such as
11
- * `user_identity:read`: an entity wildcard (`*:read`, `*:*`) does not cover it.
21
+ * ontology includes it next to `User` and `AgentChat`. Only the platform writes it, with history:
22
+ * no generated `create`, `update` or `delete` exists and no authored action writes it. Its two
23
+ * platform actions, `attach` and `revoke`, let an administrator attach a chat account to a member
24
+ * and revoke one. Reading it, attaching and revoking each need a permission that names it, such
25
+ * as `user_identity:read` or `user_identity:attach`: an entity wildcard (`*:read`, `*:*`) does not
26
+ * cover it.
12
27
  *
13
28
  * At most one live identity holds an account, and a member holds at most one live identity per
14
29
  * provider other than `oidc`. Both are unique keys that hold a value only while the identity is
@@ -20,7 +35,8 @@ export const UserIdentity = entity("user_identity", {
20
35
  plural: "Sign-in identities",
21
36
  title: "subject",
22
37
  description: "An external account a member signs in or talks with: their email sign-in, a SegmentStream " +
23
- "account, or a chat account such as Telegram. The platform records them; nobody edits them.",
38
+ "account, or a chat account such as Telegram. The platform records them; an administrator " +
39
+ "may attach a member's chat account and revoke one.",
24
40
  writes: "actions",
25
41
  properties: {
26
42
  provider: p.text({
@@ -70,6 +86,10 @@ export const UserIdentity = entity("user_identity", {
70
86
  value: "channel",
71
87
  description: "An open chat channel created the member for the chat account.",
72
88
  },
89
+ {
90
+ value: "attach",
91
+ description: "An administrator attached the chat account to the member.",
92
+ },
73
93
  ], { managed: true, description: "How the account came to belong to the member." }),
74
94
  revokedAt: p.timestamp({
75
95
  optional: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.94.0",
3
+ "version": "0.95.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",