@segmentstream/ontology 0.116.0 → 0.118.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,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.118.0
4
+
5
+ A reply the agent holds for review is linked to its chat: `agent_review` gains `agentChat`, the
6
+ chat's `agent_chat` record when the registry has it (a group the agent is in, or a person's private
7
+ chat in the inbox), whose inverse on `agent_chat` is `reviews`. `agent_chat` `find` with
8
+ `where: { reviews: { some: { status: "pending" } } }` lists the chats where replies wait for staff.
9
+ `chatKind` now comes from that record, or from the chat's id, so a reply held in a Slack channel is
10
+ a group's and its approval reaches the channel. A workspace relationship whose inverse on
11
+ `agent_chat` is `reviews` must be renamed.
12
+
13
+ ## 0.117.0
14
+
15
+ Staff reply in the inbox: `agent_chat.postMessage({ chat: <record id>, text, idempotencyKey })` to a
16
+ private chat the inbox registered sends to the chat's recipient in its thread, on every channel the
17
+ ontology's `chat` declares, email included, where the reply stays in the person's thread. A
18
+ member's own session in the app may post such a reply, signed with their name through
19
+ `chat.attribution`; it needs `agent_chat:post_message` within a scope that holds the record. The
20
+ archive keeps the reply under the chat as the member's own message, so the chat's history shows
21
+ it and the agent reads it as a person's. With an inbox declared, the chat post action may use the
22
+ email connection, for these replies only.
23
+
3
24
  ## 0.116.0
4
25
 
5
26
  A webhook trigger may name the connection whose provider sends to it:
@@ -53,6 +53,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
53
53
  }, {
54
54
  readonly person: import("./relationship.js").OneRelationship<false, false, "user">;
55
55
  readonly decidedBy: import("./relationship.js").OneRelationship<true, false, "user">;
56
+ readonly agentChat: import("./relationship.js").OneRelationship<true, false, "agent_chat">;
56
57
  }, import("./entity.js").InvocableActions<{
57
58
  readonly approve: import("./action.js").Action<Schema.Struct<{
58
59
  readonly review: Schema.Codec<string, string, never, never>;
@@ -93,5 +94,6 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
93
94
  readonly decidedAt: string | null;
94
95
  readonly personId: string;
95
96
  readonly decidedById: string | null;
97
+ readonly agentChatId: string | null;
96
98
  }>, Readonly<Record<never, never>>, "actions">;
97
99
  export type AgentReview = typeof AgentReview.Type;
@@ -134,6 +134,14 @@ export const AgentReview = entity("agent_review", {
134
134
  phrase: ["was decided by", "decided"],
135
135
  description: "The member who approved or rejected the reply.",
136
136
  }),
137
+ agentChat: rel.one("agent_chat", {
138
+ optional: true,
139
+ inverse: "reviews",
140
+ onDelete: "setNull",
141
+ phrase: ["was held in", "holds"],
142
+ description: "The chat the reply was held in, as the agent_chat registry has it: a group the agent " +
143
+ "is in, or a person's private chat in the inbox. Empty when the chat is not registered.",
144
+ }),
137
145
  },
138
146
  indexes: [{ properties: ["status"] }],
139
147
  }).actions((self) => ({
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
  : {
@@ -56,6 +56,17 @@ function messageDue(lastMessageAt, now) {
56
56
  const last = typeof lastMessageAt === "string" ? Date.parse(lastMessageAt) : Number.NaN;
57
57
  return Number.isNaN(last) || now.getTime() - last >= CHAT_MESSAGE_RECORD_INTERVAL_MS;
58
58
  }
59
+ /**
60
+ * Whether a held reply's chat is a group, by its id, for a chat the registry does not have:
61
+ * Telegram's groups and channels have negative ids, and Slack's channels and group messages start
62
+ * with C or G. Every other chat with the agent is a person's own.
63
+ */
64
+ function kindOf(input) {
65
+ return (input.provider === "telegram" && input.chatId.startsWith("-")) ||
66
+ (input.provider === "slack" && /^[CG]/u.test(input.chatId))
67
+ ? "group"
68
+ : "private";
69
+ }
59
70
  function nullableText(value) {
60
71
  return value === null || value === undefined ? null : String(value);
61
72
  }
@@ -561,6 +572,14 @@ export function sqlAgentStore(ontology, sql) {
561
572
  if (member === undefined) {
562
573
  return undefined;
563
574
  }
575
+ // The registry keys a chat by its channel's name and its id, as the archive does.
576
+ const [chat] = yield* runtime.find({
577
+ entity: AgentChat.name,
578
+ options: {
579
+ where: { provider: input.channel, external_id: input.chatId },
580
+ limit: 1,
581
+ },
582
+ });
564
583
  const review = yield* runtime.create({
565
584
  entity: AgentReview.name,
566
585
  values: {
@@ -569,10 +588,7 @@ export function sqlAgentStore(ontology, sql) {
569
588
  channel: input.channel,
570
589
  chat_id: input.chatId,
571
590
  recipient: input.recipient,
572
- // Telegram's groups and channels have negative ids; WhatsApp chats are private.
573
- chat_kind: input.provider === "telegram" && input.chatId.startsWith("-")
574
- ? "group"
575
- : "private",
591
+ chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
576
592
  thread_id: input.threadId === "" ? null : input.threadId,
577
593
  reply_to: input.replyTo,
578
594
  session_id: input.sessionId,
@@ -585,6 +601,7 @@ export function sqlAgentStore(ontology, sql) {
585
601
  message_id: null,
586
602
  decided_at: null,
587
603
  person: input.memberId,
604
+ agent_chat: chat === undefined ? null : String(chat.id),
588
605
  },
589
606
  });
590
607
  return { id: String(review.id), status: "pending", created: true };
@@ -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: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.116.0",
3
+ "version": "0.118.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",