@segmentstream/ontology 0.115.0 → 0.117.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,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.117.0
4
+
5
+ Staff reply in the inbox: `agent_chat.postMessage({ chat: <record id>, text, idempotencyKey })` to a
6
+ private chat the inbox registered sends to the chat's recipient in its thread, on every channel the
7
+ ontology's `chat` declares, email included, where the reply stays in the person's thread. A
8
+ member's own session in the app may post such a reply, signed with their name through
9
+ `chat.attribution`; it needs `agent_chat:post_message` within a scope that holds the record. The
10
+ archive keeps the reply under the chat as the member's own message, so the chat's history shows
11
+ it and the agent reads it as a person's. With an inbox declared, the chat post action may use the
12
+ email connection, for these replies only.
13
+
14
+ ## 0.116.0
15
+
16
+ A webhook trigger may name the connection whose provider sends to it:
17
+ `webhook("paymentEvents", { description, connection: nowpayments })`. The connection must be
18
+ listed in `defineOntology({ connections })`; `check` reports `invalid-connection` or
19
+ `unknown-connection` otherwise. The manifest records its key on the trigger, the workflow list
20
+ presents it as `connection`, and the console shows the webhook on the connection's page.
21
+
22
+ `webhookUrl(trigger)` returns a webhook's full URL in a production deployment, as
23
+ `segmentstream workflow webhooks` prints it: the workspace's domain, `/api/webhooks/<name>` and,
24
+ for a webhook without a signature, its token. Workspace code passes it to the provider through the
25
+ connection, as a payment's callback URL or to register an endpoint. It throws
26
+ `WebhookUrlUnavailable` in previews and local runs, which receive no webhooks. Call it in a step
27
+ or an action's `prepare`. Cloud sets the domain on deployments made after this release.
28
+
3
29
  ## 0.115.0
4
30
 
5
31
  The inbox: `defineOntology({ inbox: { roles: [client] } })` names the roles whose people's private
package/dist/analyze.js CHANGED
@@ -230,10 +230,13 @@ export function analyze(config, options = {}) {
230
230
  agent_chat: "post_message",
231
231
  agent_review: "approve",
232
232
  };
233
- // A chat post never reaches a channel whose kind only sends reviewed replies, and the
234
- // ontology sends nothing through a workspace channel's connection: the agent does.
233
+ // A chat post never reaches a channel whose kind only sends reviewed replies, except a
234
+ // reply in a private chat the inbox registered, and the ontology sends nothing through a
235
+ // workspace channel's connection: the agent does.
235
236
  const reaches = (entity) => handles.filter(([, , kind]) => kind !== WORKSPACE_CHANNEL_KIND &&
236
- (entity === "agent_review" || !REVIEW_ONLY_CHAT_PROVIDERS.has(kind)));
237
+ (entity === "agent_review" ||
238
+ inbox !== undefined ||
239
+ !REVIEW_ONLY_CHAT_PROVIDERS.has(kind)));
237
240
  resolved = resolved.map((entity) => sends[entity.name] === undefined
238
241
  ? entity
239
242
  : {
@@ -585,7 +588,7 @@ function resolveWorkflows(input) {
585
588
  ? resolveCronTrigger(trigger, at, schema, wire, report)
586
589
  : trigger.kind === "action"
587
590
  ? resolveActionTrigger(trigger, at, entities, schema, wire, report)
588
- : resolveWebhookTrigger(trigger, at, report);
591
+ : resolveWebhookTrigger(trigger, at, scope);
589
592
  if (resolvedTrigger === undefined) {
590
593
  valid = false;
591
594
  }
@@ -672,7 +675,8 @@ export function webhookDeliveryJsonSchema() {
672
675
  * A webhook trigger's manifest form, without its name: the signature when declared and the headers
673
676
  * when listed. `undefined` after reporting a problem.
674
677
  */
675
- function resolveWebhookTrigger(trigger, at, report) {
678
+ function resolveWebhookTrigger(trigger, at, scope) {
679
+ const { report } = scope;
676
680
  let valid = true;
677
681
  const signature = trigger.signature;
678
682
  if (signature !== undefined) {
@@ -729,6 +733,17 @@ function resolveWebhookTrigger(trigger, at, report) {
729
733
  }
730
734
  }
731
735
  }
736
+ const connection = trigger.connection;
737
+ if (connection !== undefined) {
738
+ if (!isConnection(connection)) {
739
+ report("invalid-connection", `${at}.connection`, "is not a connection; declare it with connection(key, { … }).");
740
+ valid = false;
741
+ }
742
+ else if (!scope.connections.has(connection.key)) {
743
+ report("unknown-connection", `${at}.connection`, `the connection ${String(connection.key)} is not listed in defineOntology({ connections }).`);
744
+ valid = false;
745
+ }
746
+ }
732
747
  if (!valid) {
733
748
  return undefined;
734
749
  }
@@ -742,6 +757,7 @@ function resolveWebhookTrigger(trigger, at, report) {
742
757
  : { signature: { scheme: trigger.signature.scheme, secret: trigger.signature.secret } }),
743
758
  ...(trigger.verification === undefined ? {} : { verification: { ...trigger.verification } }),
744
759
  ...(listed.length === 0 ? {} : { headers: [...listed] }),
760
+ ...(trigger.connection === undefined ? {} : { connection: trigger.connection.key }),
745
761
  };
746
762
  }
747
763
  /**
package/dist/index.d.ts CHANGED
@@ -31,7 +31,7 @@ export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire
31
31
  export type { MeReference } from "./me.js";
32
32
  export { check, defineOntology } from "./ontology.js";
33
33
  export { webhookDeliveryJsonSchema } from "./analyze.js";
34
- export { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
34
+ export { webhookToken, webhookTokenMatches, webhookUrl, WebhookUrlUnavailable, WEBHOOK_ORIGIN_VARIABLE, WEBHOOK_TOKEN_CONTEXT, } from "./webhook-token.js";
35
35
  export type { Ontology } from "./ontology.js";
36
36
  export { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
37
37
  export type { AgentToolVerb, ParsedPermission, PermissionHolder, RolePermissions, ScopedPermission, ScopeFilter, ScopeValue, ScopeWhere, UserMemberVerb, } from "./permissions.js";
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ export { SYSTEM_PROPERTIES } from "./names.js";
18
18
  export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire, MeTypeId, } from "./me.js";
19
19
  export { check, defineOntology } from "./ontology.js";
20
20
  export { webhookDeliveryJsonSchema } from "./analyze.js";
21
- export { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
21
+ export { webhookToken, webhookTokenMatches, webhookUrl, WebhookUrlUnavailable, WEBHOOK_ORIGIN_VARIABLE, WEBHOOK_TOKEN_CONTEXT, } from "./webhook-token.js";
22
22
  export { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
23
23
  export { p, PROPERTY_TYPES, propertyDefinition } from "./property.js";
24
24
  export { ON_DELETE, rel } from "./relationship.js";
@@ -460,7 +460,8 @@ export type ActionTriggerManifest = typeof ActionTriggerManifest.Type;
460
460
  * delivery to `/api/webhooks/<name>`. With `signature`, deliveries are checked with the provider's
461
461
  * scheme against the named workspace secret; without it, the URL ends in a derived token.
462
462
  * `verification` opts into a registration handshake; `headers` lists the request headers the
463
- * delivery carries. Optional settings are written only when declared.
463
+ * delivery carries; `connection` names the connection whose provider sends to it. Optional
464
+ * settings are written only when declared.
464
465
  */
465
466
  export declare const WebhookTriggerManifest: Schema.Struct<{
466
467
  readonly kind: Schema.Literal<"webhook">;
@@ -475,6 +476,8 @@ export declare const WebhookTriggerManifest: Schema.Struct<{
475
476
  readonly verifyToken: Schema.String;
476
477
  }>>;
477
478
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
479
+ /** The key of the connection whose provider sends to the webhook, when declared. */
480
+ readonly connection: Schema.optionalKey<Schema.String>;
478
481
  }>;
479
482
  export type WebhookTriggerManifest = typeof WebhookTriggerManifest.Type;
480
483
  /**
@@ -513,6 +516,8 @@ export declare const WorkflowTriggerManifest: Schema.Union<readonly [Schema.Stru
513
516
  readonly verifyToken: Schema.String;
514
517
  }>>;
515
518
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
519
+ /** The key of the connection whose provider sends to the webhook, when declared. */
520
+ readonly connection: Schema.optionalKey<Schema.String>;
516
521
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
517
522
  export type WorkflowTriggerManifest = typeof WorkflowTriggerManifest.Type;
518
523
  /** Whether a trigger is a cron trigger. */
@@ -558,6 +563,8 @@ export declare const WorkflowManifest: Schema.Struct<{
558
563
  readonly verifyToken: Schema.String;
559
564
  }>>;
560
565
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
566
+ /** The key of the connection whose provider sends to the webhook, when declared. */
567
+ readonly connection: Schema.optionalKey<Schema.String>;
561
568
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
562
569
  }>;
563
570
  export type WorkflowManifest = typeof WorkflowManifest.Type;
@@ -1213,6 +1220,8 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
1213
1220
  readonly verifyToken: Schema.String;
1214
1221
  }>>;
1215
1222
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
1223
+ /** The key of the connection whose provider sends to the webhook, when declared. */
1224
+ readonly connection: Schema.optionalKey<Schema.String>;
1216
1225
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
1217
1226
  }>>>;
1218
1227
  /**
@@ -1440,6 +1449,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1440
1449
  readonly kind: "webhook";
1441
1450
  readonly name: string;
1442
1451
  readonly description: string;
1452
+ readonly connection?: string | undefined;
1443
1453
  readonly signature?: {
1444
1454
  readonly scheme: string;
1445
1455
  readonly secret: string;
@@ -1752,6 +1762,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1752
1762
  readonly kind: "webhook";
1753
1763
  readonly name: string;
1754
1764
  readonly description: string;
1765
+ readonly connection?: string | undefined;
1755
1766
  readonly signature?: {
1756
1767
  readonly scheme: string;
1757
1768
  readonly secret: string;
@@ -2066,6 +2077,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2066
2077
  readonly kind: "webhook";
2067
2078
  readonly name: string;
2068
2079
  readonly description: string;
2080
+ readonly connection?: string | undefined;
2069
2081
  readonly signature?: {
2070
2082
  readonly scheme: string;
2071
2083
  readonly secret: string;
@@ -2378,6 +2390,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2378
2390
  readonly kind: "webhook";
2379
2391
  readonly name: string;
2380
2392
  readonly description: string;
2393
+ readonly connection?: string | undefined;
2381
2394
  readonly signature?: {
2382
2395
  readonly scheme: string;
2383
2396
  readonly secret: string;
@@ -2889,6 +2902,8 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2889
2902
  readonly verifyToken: Schema.String;
2890
2903
  }>>;
2891
2904
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
2905
+ /** The key of the connection whose provider sends to the webhook, when declared. */
2906
+ readonly connection: Schema.optionalKey<Schema.String>;
2892
2907
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
2893
2908
  }>>>;
2894
2909
  /**
@@ -3304,6 +3319,8 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3304
3319
  readonly verifyToken: Schema.String;
3305
3320
  }>>;
3306
3321
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
3322
+ /** The key of the connection whose provider sends to the webhook, when declared. */
3323
+ readonly connection: Schema.optionalKey<Schema.String>;
3307
3324
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
3308
3325
  }>>>;
3309
3326
  /**
@@ -3523,6 +3540,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3523
3540
  readonly kind: "webhook";
3524
3541
  readonly name: string;
3525
3542
  readonly description: string;
3543
+ readonly connection?: string | undefined;
3526
3544
  readonly signature?: {
3527
3545
  readonly scheme: string;
3528
3546
  readonly secret: string;
@@ -3835,6 +3853,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3835
3853
  readonly kind: "webhook";
3836
3854
  readonly name: string;
3837
3855
  readonly description: string;
3856
+ readonly connection?: string | undefined;
3838
3857
  readonly signature?: {
3839
3858
  readonly scheme: string;
3840
3859
  readonly secret: string;
@@ -4153,6 +4172,7 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
4153
4172
  readonly kind: "webhook";
4154
4173
  readonly name: string;
4155
4174
  readonly description: string;
4175
+ readonly connection?: string | undefined;
4156
4176
  readonly signature?: {
4157
4177
  readonly scheme: string;
4158
4178
  readonly secret: string;
@@ -4465,6 +4485,7 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
4465
4485
  readonly kind: "webhook";
4466
4486
  readonly name: string;
4467
4487
  readonly description: string;
4488
+ readonly connection?: string | undefined;
4468
4489
  readonly signature?: {
4469
4490
  readonly scheme: string;
4470
4491
  readonly secret: string;
package/dist/manifest.js CHANGED
@@ -330,7 +330,8 @@ export const ActionTriggerManifest = Schema.Struct({
330
330
  * delivery to `/api/webhooks/<name>`. With `signature`, deliveries are checked with the provider's
331
331
  * scheme against the named workspace secret; without it, the URL ends in a derived token.
332
332
  * `verification` opts into a registration handshake; `headers` lists the request headers the
333
- * delivery carries. Optional settings are written only when declared.
333
+ * delivery carries; `connection` names the connection whose provider sends to it. Optional
334
+ * settings are written only when declared.
334
335
  */
335
336
  export const WebhookTriggerManifest = Schema.Struct({
336
337
  kind: Schema.Literal("webhook"),
@@ -339,6 +340,8 @@ export const WebhookTriggerManifest = Schema.Struct({
339
340
  signature: Schema.optionalKey(Schema.Struct({ scheme: Schema.String, secret: Schema.String })),
340
341
  verification: Schema.optionalKey(Schema.Struct({ scheme: Schema.String, verifyToken: Schema.String })),
341
342
  headers: Schema.optionalKey(Schema.Array(Schema.String)),
343
+ /** The key of the connection whose provider sends to the webhook, when declared. */
344
+ connection: Schema.optionalKey(Schema.String),
342
345
  });
343
346
  /** The trigger kinds this reader knows. */
344
347
  const KNOWN_TRIGGER_KINDS = ["cron", "action", "webhook"];
@@ -444,6 +444,7 @@ export declare const MigrationPlan: Schema.Struct<{
444
444
  readonly kind: "webhook";
445
445
  readonly name: string;
446
446
  readonly description: string;
447
+ readonly connection?: string | undefined;
447
448
  readonly signature?: {
448
449
  readonly scheme: string;
449
450
  readonly secret: string;
@@ -756,6 +757,7 @@ export declare const MigrationPlan: Schema.Struct<{
756
757
  readonly kind: "webhook";
757
758
  readonly name: string;
758
759
  readonly description: string;
760
+ readonly connection?: string | undefined;
759
761
  readonly signature?: {
760
762
  readonly scheme: string;
761
763
  readonly secret: string;
@@ -1070,6 +1072,7 @@ export declare const MigrationPlan: Schema.Struct<{
1070
1072
  readonly kind: "webhook";
1071
1073
  readonly name: string;
1072
1074
  readonly description: string;
1075
+ readonly connection?: string | undefined;
1073
1076
  readonly signature?: {
1074
1077
  readonly scheme: string;
1075
1078
  readonly secret: string;
@@ -1382,6 +1385,7 @@ export declare const MigrationPlan: Schema.Struct<{
1382
1385
  readonly kind: "webhook";
1383
1386
  readonly name: string;
1384
1387
  readonly description: string;
1388
+ readonly connection?: string | undefined;
1385
1389
  readonly signature?: {
1386
1390
  readonly scheme: string;
1387
1391
  readonly secret: string;
@@ -1817,6 +1821,7 @@ export declare const MigrationPlan: Schema.Struct<{
1817
1821
  readonly verifyToken: Schema.String;
1818
1822
  }>>;
1819
1823
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
1824
+ readonly connection: Schema.optionalKey<Schema.String>;
1820
1825
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
1821
1826
  }>>>;
1822
1827
  readonly toolsets: Schema.optionalKey<Schema.$Array<Schema.Struct<{
@@ -2125,6 +2130,7 @@ export declare const MigrationPlan: Schema.Struct<{
2125
2130
  readonly verifyToken: Schema.String;
2126
2131
  }>>;
2127
2132
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
2133
+ readonly connection: Schema.optionalKey<Schema.String>;
2128
2134
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
2129
2135
  }>>>;
2130
2136
  readonly toolsets: Schema.optionalKey<Schema.$Array<Schema.Struct<{
@@ -2321,6 +2327,7 @@ export declare const MigrationPlan: Schema.Struct<{
2321
2327
  readonly kind: "webhook";
2322
2328
  readonly name: string;
2323
2329
  readonly description: string;
2330
+ readonly connection?: string | undefined;
2324
2331
  readonly signature?: {
2325
2332
  readonly scheme: string;
2326
2333
  readonly secret: string;
@@ -2633,6 +2640,7 @@ export declare const MigrationPlan: Schema.Struct<{
2633
2640
  readonly kind: "webhook";
2634
2641
  readonly name: string;
2635
2642
  readonly description: string;
2643
+ readonly connection?: string | undefined;
2636
2644
  readonly signature?: {
2637
2645
  readonly scheme: string;
2638
2646
  readonly secret: string;
@@ -12,7 +12,8 @@ export interface DeliveryEvent {
12
12
  readonly participantIds: ReadonlyArray<string>;
13
13
  readonly senderId: string;
14
14
  readonly senderName: string;
15
- readonly senderIsBot: true;
15
+ /** `false` only for a member's own reply in the inbox, whose sender is that member. */
16
+ readonly senderIsBot: boolean;
16
17
  readonly kind: "outbound";
17
18
  readonly messageId: string | null;
18
19
  readonly replyToMessageId: string | null;
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { Cause, Effect } from "effect";
4
4
  import { chatOperationId, chatPreviewDigest, } from "../../chat.js";
5
5
  import { ActionRejected, PermissionDenied } from "../../errors.js";
6
- import { isAllowed } from "../../permissions.js";
6
+ import { effectiveScope, isAllowed } from "../../permissions.js";
7
7
  import { describeChatError } from "./diagnostics.js";
8
8
  import { deliveryRequester } from "./attribution.js";
9
9
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
@@ -11,6 +11,7 @@ import { channelProvider, chatConnection, chatKind, listedChatProviders, } from
11
11
  import { chatResolver } from "./resolve.js";
12
12
  import { reviewSender } from "./review-delivery.js";
13
13
  import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
14
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
15
  /** The channels a runtime source can name, which a verified pairing's provider is one of. */
15
16
  const CHANNEL_PROVIDERS = new Set(["telegram", "slack", "whatsapp"]);
16
17
  /**
@@ -57,7 +58,23 @@ agent = {}) {
57
58
  if (user.active !== true || user.kind !== context.principal.kind) {
58
59
  return yield* new PermissionDenied({ message: "The requester is inactive." });
59
60
  }
60
- const requester = yield* deliveryRequester(context.caller, context.principal, String(user.name), attribution);
61
+ const inbox = yield* inboxChat(input.chat);
62
+ // A member answers a person in the inbox from their own session in the app, signed with
63
+ // their name as the workspace's attribution lays it out.
64
+ const requester = inbox !== undefined &&
65
+ context.caller.kind === "member" &&
66
+ context.caller.subjectId === context.principal.id &&
67
+ context.principal.kind === "member"
68
+ ? {
69
+ id: context.principal.id,
70
+ kind: "member",
71
+ name: String(user.name),
72
+ via: "hq",
73
+ clientId: null,
74
+ clientName: null,
75
+ attribution: (attribution?.template ?? "{name}").replace(/\{(name|client)\}/g, (_, key) => (key === "name" ? String(user.name) : "")),
76
+ }
77
+ : yield* deliveryRequester(context.caller, context.principal, String(user.name), attribution);
61
78
  if (context.caller.kind === "runtime" &&
62
79
  (context.backend.agents === undefined ||
63
80
  (yield* context.backend.agents.actingMember(context.principal.id)) === undefined)) {
@@ -65,9 +82,10 @@ agent = {}) {
65
82
  message: "The requester must still be paired and active.",
66
83
  });
67
84
  }
68
- const target = yield* chatResolver(context.backend, context.principal, providers, {
69
- kindOf: (channel) => chatKind(ontology.manifest.chat, channel),
70
- }).resolve(input.chat);
85
+ const target = inbox?.target ??
86
+ (yield* chatResolver(context.backend, context.principal, providers, {
87
+ kindOf: (channel) => chatKind(ontology.manifest.chat, channel),
88
+ }).resolve(input.chat));
71
89
  // A chat is a destination only on a channel the ontology declares a connection for; the
72
90
  // channel's kind sends it.
73
91
  const provider = channelProvider(ontology.manifest.chat, target.provider);
@@ -126,7 +144,77 @@ agent = {}) {
126
144
  });
127
145
  }
128
146
  }
129
- return { target, requester, connection: connection ?? "", provider, preview };
147
+ return { target, requester, connection: connection ?? "", provider, preview, inbox };
148
+ });
149
+ /**
150
+ * The private chat the inbox registered under this record id, when the caller may post there:
151
+ * a role may hold the post within a scope, which must hold the record. `undefined` for any
152
+ * other chat, which the destinations resolve as before.
153
+ */
154
+ const inboxChat = (chat) => Effect.gen(function* () {
155
+ if (!UUID.test(chat)) {
156
+ return undefined;
157
+ }
158
+ const [record] = (yield* context.backend
159
+ .find({
160
+ entity: "agent_chat",
161
+ query: {
162
+ where: { and: [{ id: { eq: chat } }, { kind: { eq: "private" } }] },
163
+ limit: 1,
164
+ },
165
+ })
166
+ .pipe(Effect.mapError((cause) => new ActionRejected({ message: "The chat directory could not be read.", cause })))).items;
167
+ if (record === undefined || record.kind !== "private") {
168
+ return undefined;
169
+ }
170
+ const postable = effectiveScope("agent_chat:post_message", context.principal);
171
+ if (postable !== undefined) {
172
+ yield* context.backend
173
+ .get({
174
+ entity: "agent_chat",
175
+ id: chat,
176
+ reader: {
177
+ ...context.principal,
178
+ permissions: ["agent_chat:read"],
179
+ scopes: [{ permission: "agent_chat:read", where: postable }],
180
+ },
181
+ })
182
+ .pipe(Effect.mapError(() => new PermissionDenied({
183
+ message: "The chat is outside the chats agent_chat:post_message covers.",
184
+ permission: "agent_chat:post_message",
185
+ })));
186
+ }
187
+ // Its person, the chat's one member, takes part in what is posted there: without them the
188
+ // reply would reach nobody who can read it.
189
+ const people = (yield* context.backend
190
+ .find({
191
+ entity: "user",
192
+ query: { where: { agentChats: { some: { id: { eq: chat } } } }, limit: 2 },
193
+ })
194
+ .pipe(Effect.mapError((cause) => new ActionRejected({ message: "The chat's person could not be read.", cause })))).items;
195
+ if (people.length !== 1) {
196
+ return yield* new ActionRejected({
197
+ message: "The chat has no person to answer. Nothing was sent.",
198
+ });
199
+ }
200
+ const chatId = String(record.external_id);
201
+ const recipient = typeof record.recipient === "string" && record.recipient !== ""
202
+ ? record.recipient
203
+ : chatId;
204
+ return {
205
+ target: {
206
+ id: String(record.id),
207
+ title: String(record.title ?? ""),
208
+ provider: String(record.provider),
209
+ external_id: recipient,
210
+ kind: "private",
211
+ participantIds: [String(people[0].id)],
212
+ },
213
+ chatId,
214
+ threadId: typeof record.thread_id === "string" && record.thread_id !== ""
215
+ ? record.thread_id
216
+ : null,
217
+ };
130
218
  });
131
219
  const report = (phase, cause) => Effect.logWarning("ontology.chat.delivery_diagnostic").pipe(Effect.annotateLogs({
132
220
  phase,
@@ -154,7 +242,9 @@ agent = {}) {
154
242
  preview: (input) => check(input, false).pipe(Effect.map(({ preview }) => preview)),
155
243
  validate: (input) => check(input).pipe(Effect.asVoid),
156
244
  post: (input) => Effect.gen(function* () {
157
- const { target, requester, connection, provider, preview } = yield* check(input);
245
+ const { target, requester, connection, provider, preview, inbox } = yield* check(input);
246
+ // A member who answers in the inbox writes as themselves, not as the agent.
247
+ const staff = inbox !== undefined && context.caller.kind === "member";
158
248
  const operationId = context.envelope?.operation_id ?? randomUUID();
159
249
  const scope = deliveryScopeDigest({
160
250
  via: requester.via,
@@ -167,13 +257,13 @@ agent = {}) {
167
257
  eventId: `chat-delivery:${operationId}:reserve`,
168
258
  operationId,
169
259
  provider: target.provider,
170
- chatId: target.external_id,
260
+ chatId: inbox?.chatId ?? target.external_id,
171
261
  chatType: target.kind,
172
- threadId: null,
262
+ threadId: inbox?.threadId ?? null,
173
263
  participantIds: target.participantIds,
174
- senderId: "agent",
175
- senderName: "agent",
176
- senderIsBot: true,
264
+ senderId: staff ? requester.id : "agent",
265
+ senderName: staff ? requester.name : "agent",
266
+ senderIsBot: !staff,
177
267
  kind: "outbound",
178
268
  messageId: null,
179
269
  replyToMessageId: preview.replyTo,
@@ -247,6 +337,7 @@ agent = {}) {
247
337
  replyTo: preview.replyTo,
248
338
  agent: agentTransport,
249
339
  operationId,
340
+ ...(inbox === undefined ? {} : { threadId: inbox.threadId, chatId: inbox.chatId }),
250
341
  transport: connections({
251
342
  identityToken: context.identityToken,
252
343
  audit: {
@@ -589,6 +589,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
589
589
  readonly verifyToken: Schema.String;
590
590
  }>>;
591
591
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
592
+ readonly connection: Schema.optionalKey<Schema.String>;
592
593
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
593
594
  }>>>;
594
595
  readonly toolsets: Schema.optionalKey<Schema.$Array<Schema.Struct<{
@@ -910,6 +911,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
910
911
  readonly verifyToken: Schema.String;
911
912
  }>>;
912
913
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
914
+ readonly connection: Schema.optionalKey<Schema.String>;
913
915
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
914
916
  }>>>>;
915
917
  readonly toolsets: Schema.toEncoded<Schema.optionalKey<Schema.$Array<Schema.Struct<{
@@ -526,6 +526,7 @@ function workflowView(workflow, now) {
526
526
  path: webhookPath(trigger.name),
527
527
  signature: trigger.signature ?? null,
528
528
  headers: trigger.headers ?? [],
529
+ connection: trigger.connection ?? null,
529
530
  },
530
531
  ]
531
532
  : []),
@@ -1,3 +1,4 @@
1
+ import type { WebhookTrigger } from "./workflow.js";
1
2
  /** What a token signs before the webhook's name, so the key derives nothing else. */
2
3
  export declare const WEBHOOK_TOKEN_CONTEXT = "segmentstream.webhook.v1:";
3
4
  /**
@@ -9,3 +10,28 @@ export declare const WEBHOOK_TOKEN_CONTEXT = "segmentstream.webhook.v1:";
9
10
  export declare function webhookToken(secret: string, name: string): string;
10
11
  /** Whether a received token is the webhook's, compared in constant time. */
11
12
  export declare function webhookTokenMatches(secret: string, name: string, received: string): boolean;
13
+ /**
14
+ * The origin providers reach the workspace's webhooks at, the workspace's assigned domain. The
15
+ * platform sets it on production deployments that declare webhook triggers, beside
16
+ * `SEGMENTSTREAM_WEBHOOK_SECRET`; previews and local runs have neither.
17
+ */
18
+ export declare const WEBHOOK_ORIGIN_VARIABLE = "SEGMENTSTREAM_WEBHOOK_ORIGIN";
19
+ /**
20
+ * Why a webhook's URL is not known here: outside a production deployment, which alone receives
21
+ * webhooks, or before the platform set the deployment's webhook variables.
22
+ */
23
+ export declare class WebhookUrlUnavailable extends Error {
24
+ readonly code = "webhook_url_unavailable";
25
+ constructor(webhook: string);
26
+ }
27
+ /**
28
+ * The full URL of a webhook trigger of this deployment, as `segmentstream workflow webhooks` shows
29
+ * it: the workspace's domain and `/api/webhooks/<name>`, followed by the token for a webhook
30
+ * without a signature. Workspace code gives it to the provider through the webhook's connection,
31
+ * to register an endpoint or as a payment's callback URL. A token URL starts runs for anyone who
32
+ * has it: send it only to the provider, never to records, logs or people.
33
+ *
34
+ * Call it in a step or an action's `prepare`, not in a workflow function. It throws
35
+ * {@link WebhookUrlUnavailable} in previews and local runs, which receive no webhooks.
36
+ */
37
+ export declare function webhookUrl(trigger: WebhookTrigger, environment?: Readonly<Record<string, string | undefined>>): string;
@@ -1,4 +1,6 @@
1
1
  import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { nameToWire } from "./authoring-names.js";
3
+ import { webhookPath } from "./webhooks.js";
2
4
  /** What a token signs before the webhook's name, so the key derives nothing else. */
3
5
  export const WEBHOOK_TOKEN_CONTEXT = "segmentstream.webhook.v1:";
4
6
  /**
@@ -16,3 +18,48 @@ export function webhookTokenMatches(secret, name, received) {
16
18
  const actual = Buffer.from(received);
17
19
  return actual.length === expected.length && timingSafeEqual(actual, expected);
18
20
  }
21
+ /**
22
+ * The origin providers reach the workspace's webhooks at, the workspace's assigned domain. The
23
+ * platform sets it on production deployments that declare webhook triggers, beside
24
+ * `SEGMENTSTREAM_WEBHOOK_SECRET`; previews and local runs have neither.
25
+ */
26
+ export const WEBHOOK_ORIGIN_VARIABLE = "SEGMENTSTREAM_WEBHOOK_ORIGIN";
27
+ /** The variable holding the workspace's webhook secret, as the ontology service reads it. */
28
+ const WEBHOOK_SECRET_VARIABLE = "SEGMENTSTREAM_WEBHOOK_SECRET";
29
+ /**
30
+ * Why a webhook's URL is not known here: outside a production deployment, which alone receives
31
+ * webhooks, or before the platform set the deployment's webhook variables.
32
+ */
33
+ export class WebhookUrlUnavailable extends Error {
34
+ code = "webhook_url_unavailable";
35
+ constructor(webhook) {
36
+ super(`The URL of the webhook ${webhook} is known only in a production deployment that declares it.`);
37
+ this.name = "WebhookUrlUnavailable";
38
+ }
39
+ }
40
+ /**
41
+ * The full URL of a webhook trigger of this deployment, as `segmentstream workflow webhooks` shows
42
+ * it: the workspace's domain and `/api/webhooks/<name>`, followed by the token for a webhook
43
+ * without a signature. Workspace code gives it to the provider through the webhook's connection,
44
+ * to register an endpoint or as a payment's callback URL. A token URL starts runs for anyone who
45
+ * has it: send it only to the provider, never to records, logs or people.
46
+ *
47
+ * Call it in a step or an action's `prepare`, not in a workflow function. It throws
48
+ * {@link WebhookUrlUnavailable} in previews and local runs, which receive no webhooks.
49
+ */
50
+ export function webhookUrl(trigger, environment = process.env) {
51
+ const wire = nameToWire(trigger.name);
52
+ const origin = environment[WEBHOOK_ORIGIN_VARIABLE];
53
+ if (!origin) {
54
+ throw new WebhookUrlUnavailable(wire);
55
+ }
56
+ const url = `${new URL(origin).origin}${webhookPath(wire)}`;
57
+ if (trigger.signature !== undefined) {
58
+ return url;
59
+ }
60
+ const secret = environment[WEBHOOK_SECRET_VARIABLE];
61
+ if (!secret) {
62
+ throw new WebhookUrlUnavailable(wire);
63
+ }
64
+ return `${url}/${webhookToken(secret, wire)}`;
65
+ }
@@ -129,6 +129,8 @@ export interface WebhookTrigger<Name extends string = string> {
129
129
  readonly verification?: WebhookVerification | undefined;
130
130
  /** Lowercase names of the request headers the delivery carries. */
131
131
  readonly headers: ReadonlyArray<string>;
132
+ /** The connection whose provider sends to this webhook, when declared. */
133
+ readonly connection?: AnyConnectionHandle | undefined;
132
134
  }
133
135
  export interface WebhookOptions {
134
136
  /** Required, like every declaration: what the provider sends and why. */
@@ -142,6 +144,12 @@ export interface WebhookOptions {
142
144
  readonly verification?: WebhookVerification;
143
145
  /** Lowercase request headers to pass to the workflow, at most ten: `["x-event-type"]`. */
144
146
  readonly headers?: ReadonlyArray<string>;
147
+ /**
148
+ * The connection whose provider sends to this webhook, listed in `defineOntology({ connections })`.
149
+ * Workspace code registers the webhook's URL with the provider through that connection, and the
150
+ * console shows the webhook on the connection's page.
151
+ */
152
+ readonly connection?: AnyConnectionHandle;
145
153
  }
146
154
  /**
147
155
  * Declares a webhook trigger; list it in `workflow(name, { input: webhookDelivery, triggers })`.
package/dist/workflow.js CHANGED
@@ -31,6 +31,7 @@ export function webhook(name, options) {
31
31
  signature: options.signature,
32
32
  ...(options.verification === undefined ? {} : { verification: options.verification }),
33
33
  headers: options.headers ?? [],
34
+ ...(options.connection === undefined ? {} : { connection: options.connection }),
34
35
  };
35
36
  }
36
37
  export function after(name, target, options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.115.0",
3
+ "version": "0.117.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",