@segmentstream/ontology 0.124.0 → 0.125.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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.125.0
4
+
5
+ The agent hands a person's private chat over to staff. `agent_chat` gains `handoffAt` and
6
+ `handoffReason`, set through the runtime route `POST /api/ontology/agent/chats/handoff` for a
7
+ registered private chat on a channel `inbox.takeover` lists, for its own person only; a second
8
+ handoff keeps the first one's time and reason. While a handoff waits, the report of the chat says
9
+ `handled: true`, so the agent answers none of the person's messages. `takeOver` answers the handoff
10
+ and clears both fields, as does `handBack`, which returns the chat to the agent.
11
+
3
12
  ## 0.124.0
4
13
 
5
14
  Staff take an inbox chat over from the agent. `agent_chat.takeOver({ chat })` sets the record's new
package/README.md CHANGED
@@ -1400,6 +1400,7 @@ Without either header the agent may call only the agent routes:
1400
1400
  | `GET /api/ontology/agent/identities` | member | `{ identities }`: the member's live identities |
1401
1401
  | `DELETE /api/ontology/agent/identities/{id}` | member | Revokes one of them: 204 |
1402
1402
  | `POST /api/ontology/agent/chats/seen` | agent | `{ provider, externalId, title, memberId?, leftMemberId?, agentLeft?, migratedFrom? }` → `{ id, title, purpose, whenToUse, handled? }` |
1403
+ | `POST /api/ontology/agent/chats/handoff` | agent | `{ provider, externalId, memberId, reason }` → `{ id, handoffAt, handled? }`; 404 for a chat staff do not take over |
1403
1404
 
1404
1405
  A pairing code is eight characters without look-alikes (no 0, O, 1, I or L), stored as its
1405
1406
  SHA-256, valid ten minutes and used once. Each instance allows a client address 60 new
@@ -9,6 +9,8 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
9
9
  readonly recipient: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
10
10
  readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
11
11
  readonly lastMessageAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
12
+ readonly handoffAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
13
+ readonly handoffReason: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
12
14
  readonly purpose: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
13
15
  readonly whenToUse: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
14
16
  }, {
@@ -58,6 +60,8 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
58
60
  readonly recipient: string | null;
59
61
  readonly threadId: string | null;
60
62
  readonly lastMessageAt: string | null;
63
+ readonly handoffAt: string | null;
64
+ readonly handoffReason: string | null;
61
65
  readonly purpose: string | null;
62
66
  readonly whenToUse: string | null;
63
67
  readonly handledById: string | null;
@@ -50,6 +50,22 @@ export const AgentChat = entity("agent_chat", {
50
50
  label: "Last message",
51
51
  description: "When the agent last saw a message in the chat, recorded at most every 15 minutes.",
52
52
  }),
53
+ handoffAt: p.timestamp({
54
+ optional: true,
55
+ managed: true,
56
+ label: "Handed off",
57
+ description: "When the agent handed the person over to staff: until a member takes the chat over or " +
58
+ "hands it back, the agent records the person's messages and answers none of them. Empty " +
59
+ "otherwise.",
60
+ }),
61
+ handoffReason: p.text({
62
+ optional: true,
63
+ managed: true,
64
+ maxLength: 1000,
65
+ display: "multiline",
66
+ label: "Handoff reason",
67
+ description: "What the agent said the person needs from staff when it handed them over.",
68
+ }),
53
69
  purpose: p.text({
54
70
  optional: true,
55
71
  maxLength: 64,
@@ -84,11 +100,11 @@ export const AgentChat = entity("agent_chat", {
84
100
  indexes: [{ properties: ["provider", "externalId"], unique: true }],
85
101
  }).actions((self) => ({
86
102
  takeOver: action({
87
- description: "Take a person's private chat over from the agent, as yourself: until a member hands it " +
88
- "back, the agent records the person's messages and answers none of them, and staff answer " +
89
- "with postMessage. Refused for a group chat, for a chat on a channel the ontology's " +
90
- "inbox.takeover does not list, and for a chat another member took over; taking over a " +
91
- "chat you hold changes nothing.",
103
+ description: "Take a person's private chat over from the agent, as yourself, also when the agent handed " +
104
+ "the person over: until a member hands it back, the agent records the person's messages " +
105
+ "and answers none of them, and staff answer with postMessage. Refused for a group chat, " +
106
+ "for a chat on a channel the ontology's inbox.takeover does not list, and for a chat " +
107
+ "another member took over; taking over a chat you hold changes nothing.",
92
108
  hints: { destructive: false, irreversible: false, idempotent: true },
93
109
  input: Schema.Struct({ chat: self.ref }),
94
110
  handler: ({ input, principal }) => Effect.gen(function* () {
@@ -120,21 +136,27 @@ export const AgentChat = entity("agent_chat", {
120
136
  message: "Another member has taken the chat over: hand it back first.",
121
137
  });
122
138
  }
123
- if (chat.handledById === null) {
124
- yield* self.update(chat, { handledBy: principal.id });
139
+ // Taking the chat over answers the agent's handoff, if it handed the person over.
140
+ if (chat.handledById === null || chat.handoffAt !== null) {
141
+ yield* self.update(chat, {
142
+ handledBy: principal.id,
143
+ handoffAt: null,
144
+ handoffReason: null,
145
+ });
125
146
  }
126
147
  return { chat: chat.id, handled_by: principal.id };
127
148
  }),
128
149
  }),
129
150
  handBack: action({
130
- description: "Hand a chat a member took over back to the agent, which answers the person's next " +
131
- "message with what was said meanwhile in its context. A chat no one holds changes nothing.",
151
+ description: "Hand a chat a member took over, or the agent handed over to staff, back to the agent, " +
152
+ "which answers the person's next message with what was said meanwhile in its context. A " +
153
+ "chat no one holds and no handoff waits on changes nothing.",
132
154
  hints: { destructive: false, irreversible: false, idempotent: true },
133
155
  input: Schema.Struct({ chat: self.ref }),
134
156
  handler: ({ input }) => Effect.gen(function* () {
135
157
  const chat = yield* self.get(input.chat, { forUpdate: true });
136
- if (chat.handledById !== null) {
137
- yield* self.update(chat, { handledBy: null });
158
+ if (chat.handledById !== null || chat.handoffAt !== null) {
159
+ yield* self.update(chat, { handledBy: null, handoffAt: null, handoffReason: null });
138
160
  }
139
161
  return { chat: chat.id, handled_by: null };
140
162
  }),
@@ -547,14 +547,70 @@ export function sqlAgentStore(ontology, sql) {
547
547
  title: String(chat.title),
548
548
  purpose: nullableText(chat.purpose),
549
549
  whenToUse: nullableText(chat.when_to_use),
550
- // A member of staff took the chat over: the agent records the person and answers none.
551
- ...((chat.handled_by_id ?? null) !== null &&
550
+ // A member of staff took the chat over, or the agent handed the person over to staff:
551
+ // the agent records the person and answers none.
552
+ ...(((chat.handled_by_id ?? null) !== null || (chat.handoff_at ?? null) !== null) &&
552
553
  takeoverChannelsOf(ontology.manifest).has(input.provider)
553
554
  ? { handled: true }
554
555
  : {}),
555
556
  };
556
557
  }));
557
558
  }).pipe(Effect.orDie),
559
+ handOffChat: (input) => Effect.gen(function* () {
560
+ // Only a chat staff may take over is handed to them.
561
+ if (!takeoverChannelsOf(ontology.manifest).has(input.provider) ||
562
+ !isRecordId(input.memberId)) {
563
+ return undefined;
564
+ }
565
+ return yield* sql.withTransaction(Effect.gen(function* () {
566
+ yield* beginReplicationWrite(sql);
567
+ yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
568
+ `chat:${input.provider}:${input.externalId}`,
569
+ ]);
570
+ const runtime = makeOntologyRuntime(ontology, sql, {
571
+ action: `${AgentChat.name}.handoff`,
572
+ actionId: randomUUID(),
573
+ principalId: null,
574
+ });
575
+ const [found] = yield* runtime.find({
576
+ entity: AgentChat.name,
577
+ options: {
578
+ where: { provider: input.provider, external_id: input.externalId, kind: "private" },
579
+ limit: 1,
580
+ forUpdate: true,
581
+ },
582
+ });
583
+ if (found === undefined) {
584
+ return undefined;
585
+ }
586
+ const id = String(found.id);
587
+ // Only the chat's own person is handed over: the agent reports the chat it answers.
588
+ const members = yield* runtime.related({
589
+ entity: AgentChat.name,
590
+ id,
591
+ relationship: "members",
592
+ query: { limit: MAX_QUERY_LIMIT },
593
+ });
594
+ if (!members.items.some((member) => String(member.id) === input.memberId)) {
595
+ return undefined;
596
+ }
597
+ // A member of staff holds the chat already, or a handoff waits: nothing changes, and
598
+ // the first handoff keeps its time and reason.
599
+ if ((found.handled_by_id ?? null) !== null) {
600
+ return { id, handoffAt: null, handled: true };
601
+ }
602
+ if ((found.handoff_at ?? null) !== null) {
603
+ return { id, handoffAt: timestampText(found.handoff_at) };
604
+ }
605
+ const at = new Date().toISOString();
606
+ yield* runtime.update({
607
+ entity: AgentChat.name,
608
+ id,
609
+ values: { handoff_at: at, handoff_reason: input.reason },
610
+ });
611
+ return { id, handoffAt: at };
612
+ }));
613
+ }).pipe(Effect.orDie),
558
614
  seeGuestChat: (guestId) => Effect.gen(function* () {
559
615
  // Only the visitors' chats of an inbox that takes the guests.
560
616
  if (!isRecordId(guestId) || !inboxRolesOf(ontology.manifest).has(GUEST_ROLE)) {
@@ -710,3 +766,7 @@ function inInbox(ontology, input, resolution) {
710
766
  ? { ...resolution, inbox: true, takeover: true }
711
767
  : { ...resolution, inbox: true };
712
768
  }
769
+ /** A stored timestamp, as the wire carries it. */
770
+ function timestampText(value) {
771
+ return value instanceof Date ? value.toISOString() : String(value);
772
+ }
@@ -127,6 +127,16 @@ export declare const ChatSeenRequest: Schema.Struct<{
127
127
  readonly recipient: Schema.optionalKey<Schema.String>;
128
128
  readonly threadId: Schema.optionalKey<Schema.String>;
129
129
  }>;
130
+ /**
131
+ * `POST /api/ontology/agent/chats/handoff`: the agent hands a person's private chat over to staff,
132
+ * saying what the person needs.
133
+ */
134
+ export declare const ChatHandoffRequest: Schema.Struct<{
135
+ readonly provider: Schema.String;
136
+ readonly externalId: Schema.String;
137
+ readonly memberId: Schema.String;
138
+ readonly reason: Schema.String;
139
+ }>;
130
140
  /**
131
141
  * `POST /api/ontology/agent/reviews`: a reply the agent held for a member to review, for the member
132
142
  * it answers. `key` names the reply, so a report repeated after a failure finds its review.
@@ -160,6 +160,18 @@ export const ChatSeenRequest = Schema.Struct({
160
160
  })),
161
161
  threadId: Schema.optionalKey(ChatId.annotate({ description: "The thread a reply in the private chat stays in." })),
162
162
  });
163
+ /**
164
+ * `POST /api/ontology/agent/chats/handoff`: the agent hands a person's private chat over to staff,
165
+ * saying what the person needs.
166
+ */
167
+ export const ChatHandoffRequest = Schema.Struct({
168
+ provider: Provider,
169
+ externalId: ChatId.annotate({ description: "The private chat's id on the channel." }),
170
+ memberId: Schema.String.annotate({ description: "The user id of the chat's person." }),
171
+ reason: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1000)).annotate({
172
+ description: "What the person needs from staff, in the agent's words.",
173
+ }),
174
+ });
163
175
  /**
164
176
  * `POST /api/ontology/agent/reviews`: a reply the agent held for a member to review, for the member
165
177
  * it answers. `key` names the reply, so a report repeated after a failure finds its review.
@@ -13,7 +13,7 @@ import { secretHash } from "../oauth/protocol.js";
13
13
  import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
14
14
  import { OntologyBackend } from "../runtime-contract.js";
15
15
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
16
- import { ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
16
+ import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
17
17
  import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
18
18
  import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
19
19
  import { identityToken } from "../operations.js";
@@ -22,6 +22,7 @@ export const AGENT_PATH = `${BASE_PATH}/agent`;
22
22
  const PAIRINGS_PATH = `${AGENT_PATH}/pairings`;
23
23
  const IDENTITIES_PATH = `${AGENT_PATH}/identities`;
24
24
  const CHATS_SEEN_PATH = `${AGENT_PATH}/chats/seen`;
25
+ const CHATS_HANDOFF_PATH = `${AGENT_PATH}/chats/handoff`;
25
26
  const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
26
27
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
27
28
  export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
@@ -265,6 +266,34 @@ function completeLimitNotice(store) {
265
266
  return HttpServerResponse.empty({ status: 204, headers: NO_STORE });
266
267
  });
267
268
  }
269
+ /**
270
+ * `POST /api/ontology/agent/chats/handoff` (runtime): the agent hands a person's private chat over to
271
+ * staff. The chat must be registered, on a channel `inbox.takeover` lists, and the person's own;
272
+ * anything else answers 404. The answer is the chat's id and when the handoff began, or `handled`
273
+ * when a member of staff holds the chat already.
274
+ */
275
+ function handOffChat(store) {
276
+ return (request) => Effect.gen(function* () {
277
+ const requestId = yield* RequestId;
278
+ const decoded = Schema.decodeUnknownResult(ChatHandoffRequest)(yield* jsonBody(request), {
279
+ errors: "all",
280
+ onExcessProperty: "error",
281
+ });
282
+ if (Result.isFailure(decoded)) {
283
+ return invalidBody(requestId, schemaIssues(decoded.failure));
284
+ }
285
+ const handed = yield* store.handOffChat(decoded.success);
286
+ if (handed === undefined) {
287
+ return toServerResponse(notFound(requestId, "The chat is not one staff take over."));
288
+ }
289
+ yield* Effect.logInfo("ontology.agent.chat_handed_off").pipe(Effect.annotateLogs({
290
+ requestId,
291
+ provider: decoded.success.provider,
292
+ chatId: decoded.success.externalId,
293
+ }));
294
+ return json(handed);
295
+ });
296
+ }
268
297
  /**
269
298
  * `POST /api/ontology/agent/chats/seen` (runtime): the agent saw a message in a group chat. The chat
270
299
  * is recorded, or its title kept current, a paired writer joins its members and a paired member who
@@ -484,6 +513,7 @@ export function agentLayer(options) {
484
513
  })));
485
514
  }
486
515
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
516
+ yield* router.add("POST", CHATS_HANDOFF_PATH, asRuntime(handOffChat(store)));
487
517
  yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
488
518
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
489
519
  if (store.web !== undefined && backend.oauth !== undefined) {
@@ -561,6 +561,24 @@ export interface SeenChat {
561
561
  */
562
562
  readonly handled?: true;
563
563
  }
564
+ /** A person's private chat the agent hands over to staff (`POST /api/ontology/agent/chats/handoff`). */
565
+ export interface HandoffInput {
566
+ /** The channel's name. */
567
+ readonly provider: string;
568
+ readonly externalId: string;
569
+ /** The chat's person, whom the agent answers there. */
570
+ readonly memberId: string;
571
+ /** What the person needs from staff, in the agent's words. */
572
+ readonly reason: string;
573
+ }
574
+ /** A handoff the ontology recorded, or found waiting. */
575
+ export interface Handoff {
576
+ readonly id: string;
577
+ /** When the agent handed the person over: the first handoff's time, while it waits. */
578
+ readonly handoffAt: string | null;
579
+ /** A member of staff holds the chat already: nothing changed. */
580
+ readonly handled?: true;
581
+ }
564
582
  /**
565
583
  * Where the app's agent keeps pairing codes and the identities they create: the runtime's agent
566
584
  * tables in the workspace database. Codes are stored only as SHA-256 hashes. Expiry is checked
@@ -652,6 +670,12 @@ export interface AgentStore {
652
670
  * stores that predate the inbox.
653
671
  */
654
672
  readonly seeInboxChat?: (input: InboxChatInput) => Effect.Effect<SeenChat | undefined>;
673
+ /**
674
+ * Hands a registered private chat on a channel staff take chats over on to staff: its
675
+ * `handoffAt` and `handoffReason`. Undefined for any other chat, or when `memberId` is not its
676
+ * person.
677
+ */
678
+ readonly handOffChat: (input: HandoffInput) => Effect.Effect<Handoff | undefined>;
655
679
  /**
656
680
  * Records a website visitor's chat with the agent, `guest:<id>` on the `web` channel, for the
657
681
  * inbox: creates the `agent_chat` of kind `private`, without members, and records when it last
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.124.0",
3
+ "version": "0.125.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",