@segmentstream/ontology 0.121.0 → 0.122.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,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.122.0
4
+
5
+ The website's visitors' chats in the inbox: `inbox.roles` may list `guest` where the ontology
6
+ declares `guest`, and each visitor's chat with the agent, `guest:<id>` on the `web` channel, then
7
+ becomes an `agent_chat` record of kind `private` when the service admits a turn of theirs, without
8
+ members and with `lastMessageAt` kept current. A workflow's runs and its agent tasks read registered
9
+ chats as staff do: their role's `agent_chat:read`, within its scope, finds the records and reads a
10
+ chat's messages with `chat_history` by the record id, as the workflow's own user and never as a
11
+ participant. A daily report of the website's chats is then a workflow that finds the day's chats,
12
+ has an agent task summarize them and posts the summary.
13
+
3
14
  ## 0.121.0
4
15
 
5
16
  The platform builds in no role. An ontology without `defineOntology({ member })` names every role
package/dist/analyze.d.ts CHANGED
@@ -116,8 +116,9 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
116
116
  /**
117
117
  * Whose private chats with the agent the workspace's staff work: `{ roles: [client] }`. The agent
118
118
  * registers each private chat of a person holding one of these roles as an `agent_chat` record of
119
- * kind `private`, which `agent_chat:read` within its scope reads with its messages. Absent, no
120
- * private chat is registered and `agent_chat` holds group chats only.
119
+ * kind `private`, which `agent_chat:read` within its scope reads with its messages. With `guest`
120
+ * declared, `"guest"` takes the chats of the website's visitors too. Absent, no private chat is
121
+ * registered and `agent_chat` holds group chats only.
121
122
  */
122
123
  readonly inbox?: InboxOptions<Role | string>;
123
124
  /**
package/dist/analyze.js CHANGED
@@ -102,7 +102,7 @@ export function analyze(config, options = {}) {
102
102
  ...(linkEmail === undefined ? {} : { linkEmail }),
103
103
  ...(codeEmail === undefined ? {} : { codeEmail }),
104
104
  };
105
- const inbox = inboxOptions(config.inbox, declaredRoles, report);
105
+ const inbox = inboxOptions(config.inbox, declaredRoles, guest !== undefined, report);
106
106
  const discovery = config.discovery;
107
107
  if (discovery !== undefined &&
108
108
  (!isPlainObject(discovery) ||
@@ -351,7 +351,9 @@ export function analyze(config, options = {}) {
351
351
  * `inbox`: the wire names of the roles whose private chats join the inbox, each a declared role or
352
352
  * `member`; `undefined` when absent or malformed.
353
353
  */
354
- function inboxOptions(value, declaredRoles, report) {
354
+ function inboxOptions(value, declaredRoles,
355
+ /** Whether the ontology declares `guest`, whose visitors' chats the inbox may take. */
356
+ guests, report) {
355
357
  if (value === undefined) {
356
358
  return undefined;
357
359
  }
@@ -363,6 +365,9 @@ function inboxOptions(value, declaredRoles, report) {
363
365
  return undefined;
364
366
  }
365
367
  const declared = new Set(declaredRoles.map((candidate) => candidate.name));
368
+ if (guests) {
369
+ declared.add(GUEST_ROLE);
370
+ }
366
371
  const roles = [];
367
372
  let valid = true;
368
373
  value.roles.forEach((candidate, index) => {
@@ -372,7 +377,7 @@ function inboxOptions(value, declaredRoles, report) {
372
377
  ? nameToWire(candidate)
373
378
  : undefined;
374
379
  if (name === undefined || !declared.has(name)) {
375
- report("invalid-inbox", `inbox.roles[${index}]`, "Use a role the ontology declares, or member.");
380
+ report("invalid-inbox", `inbox.roles[${index}]`, "Use a role the ontology declares, member, or guest when it declares guest.");
376
381
  valid = false;
377
382
  }
378
383
  else if (!roles.includes(name)) {
package/dist/chat.d.ts CHANGED
@@ -5,7 +5,8 @@ export interface ChatAttributionSettings {
5
5
  }
6
6
  /**
7
7
  * `inbox` of `defineOntology`: the roles of the people whose private chats with the agent the
8
- * workspace's staff work, as `agent_chat` records of kind `private`.
8
+ * workspace's staff work, as `agent_chat` records of kind `private`: declared roles, `member`, or
9
+ * `guest`, the website's visitors, where the ontology declares `guest`.
9
10
  */
10
11
  export interface InboxOptions<R = unknown> {
11
12
  readonly roles: ReadonlyArray<R>;
@@ -7,6 +7,7 @@ import { chatChannelKind } from "../chat-channel.js";
7
7
  import { AgentReview } from "../agent-review.js";
8
8
  import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
9
9
  import { inboxRolesOf } from "../manifest.js";
10
+ import { GUEST_ROLE } from "../names.js";
10
11
  import { MAX_QUERY_LIMIT } from "../query.js";
11
12
  import { beginReplicationWrite } from "../replication/transaction.js";
12
13
  import { IdentityInUse, } from "../service/runtime-contract.js";
@@ -15,6 +16,7 @@ import { resolveAgentIdentity } from "./resolve-agent-identity.js";
15
16
  import { completeAgentLimitNotice } from "./agent-counters.js";
16
17
  import { isMemberBlocked, setMemberBlocked, resolveMemberById } from "./principals.js";
17
18
  import { sqlAgentWebStore } from "./agent-web.js";
19
+ import { guestChat } from "./guests.js";
18
20
  import { WEB_PROVIDER } from "../service/runtime-identity.js";
19
21
  import { isRecordId } from "./records.js";
20
22
  import { makeOntologyRuntime } from "./sql-runtime.js";
@@ -548,6 +550,62 @@ export function sqlAgentStore(ontology, sql) {
548
550
  };
549
551
  }));
550
552
  }).pipe(Effect.orDie),
553
+ seeGuestChat: (guestId) => Effect.gen(function* () {
554
+ // Only the visitors' chats of an inbox that takes the guests.
555
+ if (!isRecordId(guestId) || !inboxRolesOf(ontology.manifest).has(GUEST_ROLE)) {
556
+ return undefined;
557
+ }
558
+ const externalId = guestChat(guestId);
559
+ return yield* sql.withTransaction(Effect.gen(function* () {
560
+ yield* beginReplicationWrite(sql);
561
+ // Turns of one visitor run one after the other: the first creates it, the rest find it.
562
+ yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
563
+ `chat:${WEB_PROVIDER}:${externalId}`,
564
+ ]);
565
+ const runtime = makeOntologyRuntime(ontology, sql, {
566
+ action: `${AgentChat.name}.seen`,
567
+ actionId: randomUUID(),
568
+ principalId: null,
569
+ });
570
+ const [found] = yield* runtime.find({
571
+ entity: AgentChat.name,
572
+ options: {
573
+ where: { provider: WEB_PROVIDER, external_id: externalId },
574
+ limit: 1,
575
+ forUpdate: true,
576
+ },
577
+ });
578
+ if (found !== undefined && found.kind !== "private") {
579
+ return undefined;
580
+ }
581
+ const now = new Date();
582
+ // A visitor has no name: the chat is titled by its key, as the archive keeps it.
583
+ const chat = found === undefined
584
+ ? yield* runtime.create({
585
+ entity: AgentChat.name,
586
+ values: {
587
+ provider: WEB_PROVIDER,
588
+ external_id: externalId,
589
+ kind: "private",
590
+ title: externalId,
591
+ last_message_at: now.toISOString(),
592
+ },
593
+ })
594
+ : messageDue(found.last_message_at, now)
595
+ ? yield* runtime.update({
596
+ entity: AgentChat.name,
597
+ id: String(found.id),
598
+ values: { last_message_at: now.toISOString() },
599
+ })
600
+ : found;
601
+ return {
602
+ id: String(chat.id),
603
+ title: String(chat.title),
604
+ purpose: nullableText(chat.purpose),
605
+ whenToUse: nullableText(chat.when_to_use),
606
+ };
607
+ }));
608
+ }).pipe(Effect.orDie),
551
609
  holdReply: (input) => sql
552
610
  .withTransaction(Effect.gen(function* () {
553
611
  if (!isRecordId(input.memberId)) {
@@ -36,7 +36,8 @@ export type ChatArchiveTransport = (input: {
36
36
  readonly memberGroups?: ReadonlyArray<string>;
37
37
  /**
38
38
  * Chats (`provider:chatId`) of any type the ontology checked the member may read, such as a
39
- * private chat its inbox registered, which `agent_chat:read` within its scope reads.
39
+ * private chat its inbox registered, which `agent_chat:read` within its scope reads. A service
40
+ * principal, such as a workflow's user, reads these alone.
40
41
  */
41
42
  readonly chats?: ReadonlyArray<string>;
42
43
  }) => Effect.Effect<ChatPage, ChatArchiveUnavailable | PermissionDenied>;
@@ -23,7 +23,9 @@ export class ChatArchiveUnavailable extends Schema.TaggedError()("ChatArchiveUna
23
23
  /** The authenticated ontology service forwards its resolved member, never a caller-supplied ID. */
24
24
  export function platformChatArchive(environment, fetchImpl = fetch) {
25
25
  return ({ search, principal, identityToken, memberGroups, chats }) => {
26
- if (principal.kind !== "member") {
26
+ // A service, such as a workflow's user, reads only the exact chats the ontology checked.
27
+ const service = principal.kind === "service" && chats !== undefined && chats.length > 0;
28
+ if (principal.kind !== "member" && !service) {
27
29
  return Effect.fail(new PermissionDenied({
28
30
  message: "Only members may read chats.",
29
31
  permission: "chat:participant",
@@ -45,13 +47,15 @@ export function platformChatArchive(environment, fetchImpl = fetch) {
45
47
  },
46
48
  body: JSON.stringify({
47
49
  search,
48
- reader: {
49
- participantId: principal.id,
50
- groups: isAllowed("agent_chat:read", principal),
51
- groupChats: memberGroups ?? [],
52
- ...(chats === undefined || chats.length === 0 ? {} : { chats }),
53
- admin: false,
54
- },
50
+ reader: service
51
+ ? { participantId: null, groups: false, groupChats: [], chats, admin: false }
52
+ : {
53
+ participantId: principal.id,
54
+ groups: isAllowed("agent_chat:read", principal),
55
+ groupChats: memberGroups ?? [],
56
+ ...(chats === undefined || chats.length === 0 ? {} : { chats }),
57
+ admin: false,
58
+ },
55
59
  }),
56
60
  signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]),
57
61
  });
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { Effect, Result, Schema } from "effect";
2
+ import { Cause, Effect, Exit, Result, Schema } from "effect";
3
3
  import { HttpServerResponse } from "effect/unstable/http";
4
4
  import { schemaIssues } from "../../runtime/validation.js";
5
5
  import { BASE_PATH } from "../api.js";
@@ -130,6 +130,14 @@ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
130
130
  const limited = decoded.success.turn === true && web.countGuestTurn !== undefined
131
131
  ? yield* web.countGuestTurn(guest.id, limits)
132
132
  : undefined;
133
+ // An admitted turn is a message in the visitor's chat: the inbox, where it takes guests,
134
+ // records the chat. The turn goes on whether or not the record could be written.
135
+ if (decoded.success.turn === true && limited === undefined && store.seeGuestChat) {
136
+ const seen = yield* Effect.exit(store.seeGuestChat(guest.id));
137
+ if (Exit.isFailure(seen)) {
138
+ yield* Effect.logWarning("ontology.agent.guest_chat_unrecorded").pipe(Effect.annotateLogs({ requestId, cause: Cause.pretty(seen.cause) }));
139
+ }
140
+ }
133
141
  return json({
134
142
  active: true,
135
143
  guest_id: guest.id,
@@ -76,7 +76,7 @@ export function chatReads(backend, options) {
76
76
  }),
77
77
  history: (input, identityToken) => Effect.gen(function* () {
78
78
  const principal = yield* CurrentPrincipal;
79
- if (principal.kind !== "member") {
79
+ if (principal.kind !== "member" && principal.kind !== "service") {
80
80
  return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
81
81
  }
82
82
  const registered = UUID.test(input.chat)
@@ -103,6 +103,10 @@ export function chatReads(backend, options) {
103
103
  ...(registered.staff ? { chats: [key] } : {}),
104
104
  });
105
105
  }
106
+ // A service, such as a workflow's user, reads only the registered chats its scope holds.
107
+ if (principal.kind !== "member") {
108
+ return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
109
+ }
106
110
  // History reads the chats of Telegram channels only. Other channels archive a chat under
107
111
  // their session's address with private coordinates, not under the chat a destination
108
112
  // names, so their history would be incomplete until the archive keys them the same way.
@@ -801,13 +801,17 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
801
801
  title: "Read chat history",
802
802
  description: "Read messages for an exact chat ID/title, with their own pagination. " +
803
803
  "Reads a group chat you are in (every group with agent_chat:read), your own private chat, " +
804
- "or, by its agent_chat id, a person's private chat the inbox registered, with " +
805
- "agent_chat:read within your scope.",
804
+ "or, by its agent_chat id, a private chat the inbox registered (a person's, or a website " +
805
+ "visitor's), with agent_chat:read within your scope. A workflow's task reads only these.",
806
806
  inputSchema: encodedJsonSchema(ChatHistory),
807
807
  annotations: READ,
808
808
  permissions: [],
809
809
  target: { kind: "chat-history" },
810
- inputSchemaFor: (caller) => "kind" in caller && caller.kind === "member" ? encodedJsonSchema(ChatHistory) : undefined,
810
+ inputSchemaFor: (caller) => "kind" in caller &&
811
+ (caller.kind === "member" ||
812
+ (caller.kind === "service" && isAllowed("agent_chat:read", caller)))
813
+ ? encodedJsonSchema(ChatHistory)
814
+ : undefined,
811
815
  });
812
816
  tools.push({
813
817
  name: "chat_search",
@@ -642,6 +642,13 @@ export interface AgentStore {
642
642
  * stores that predate the inbox.
643
643
  */
644
644
  readonly seeInboxChat?: (input: InboxChatInput) => Effect.Effect<SeenChat | undefined>;
645
+ /**
646
+ * Records a website visitor's chat with the agent, `guest:<id>` on the `web` channel, for the
647
+ * inbox: creates the `agent_chat` of kind `private`, without members, and records when it last
648
+ * had a message, as `seeChat` does. `undefined`, recording nothing, unless the inbox takes
649
+ * `guest`. Absent on stores that predate it.
650
+ */
651
+ readonly seeGuestChat?: (guestId: string) => Effect.Effect<SeenChat | undefined>;
645
652
  /**
646
653
  * A reply the agent held for review becomes a pending `agent_review` for the member it answers,
647
654
  * once per `key`: a repeated report answers the review it created. `undefined` when the member is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.121.0",
3
+ "version": "0.122.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",