@segmentstream/ontology 0.159.0 → 0.161.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 +39 -0
- package/dist/agent-draft.d.ts +50 -4
- package/dist/agent-draft.js +120 -9
- package/dist/chat.d.ts +14 -0
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +4 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/runtime/agents.js +186 -2
- package/dist/runtime/chat-messages.d.ts +32 -0
- package/dist/runtime/chat-messages.js +39 -4
- package/dist/service/agent/chat-message-routes.d.ts +5 -1
- package/dist/service/agent/chat-message-routes.js +14 -3
- package/dist/service/agent/protocol.d.ts +1 -0
- package/dist/service/agent/protocol.js +3 -0
- package/dist/service/agent/server.js +2 -0
- package/dist/service/chat/delivery.js +27 -0
- package/dist/service/chat/review-delivery.d.ts +2 -0
- package/dist/service/chat/review-delivery.js +77 -14
- package/dist/service/runtime-contract.d.ts +54 -0
- package/dist/service/schemas.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.161.0
|
|
4
|
+
|
|
5
|
+
Agent drafts name their turn, know whether the person wrote after it, and are decided once.
|
|
6
|
+
|
|
7
|
+
- `agent_draft` has three new managed fields: `turnId`, the agent's turn that wrote the reply;
|
|
8
|
+
`basis`, where that turn had read the chat to (the chat store's place `<time>~<id>` of the
|
|
9
|
+
newest message it took); and `message`, the reply's message in the chat store once an approval
|
|
10
|
+
reserved its delivery.
|
|
11
|
+
- `agent_draft.newer({ drafts })` tells, for up to 50 drafts, whether the person wrote in the chat
|
|
12
|
+
after each draft's turn: `true`, `false`, or `null` when it cannot be told. It needs
|
|
13
|
+
`agent_draft:read`.
|
|
14
|
+
- `agent_draft.approve` takes `unlessNewer: true`: the approval is refused, with nothing reserved
|
|
15
|
+
or sent, when the person wrote after the draft's turn (`refusal: "newer_message"`) or when that
|
|
16
|
+
cannot be told (`refusal: "basis_unknown"`). It is checked under the chat's lock, in the
|
|
17
|
+
transaction that reserves the delivery. Use it for approvals no person reads first, such as a
|
|
18
|
+
workflow's.
|
|
19
|
+
- `agent_draft.dismiss({ draft, reason? })` sets a pending draft aside without judging it, under
|
|
20
|
+
its own permission `agent_draft:dismiss`. Its status, `dismissed`, is final.
|
|
21
|
+
- An approval and a rejection or dismissal of one draft are ordered by the draft's lock: once an
|
|
22
|
+
approval reserved the delivery, a rejection or dismissal is refused (`refusal: "draft_decided"`),
|
|
23
|
+
and an approval of a draft decided meanwhile is refused before anything is sent. Before the chat
|
|
24
|
+
store holds a chat, where they cannot be ordered, the draft records the delivery as the
|
|
25
|
+
approver's, and its history keeps the rejection.
|
|
26
|
+
- Docs: approval by a workflow, with an `after` trigger on the hold, the workspace's own rule and
|
|
27
|
+
`unlessNewer`. A workflow holding `agent_draft:approve` sends replies without a person.
|
|
28
|
+
|
|
29
|
+
Action required: a reader of `agent_draft.status` in workspace code that lists the statuses should
|
|
30
|
+
take `dismissed`, and any status it does not know, as a draft the person never received. Grant
|
|
31
|
+
`agent_draft:dismiss` to the roles that should dismiss drafts.
|
|
32
|
+
|
|
33
|
+
## 0.160.0
|
|
34
|
+
|
|
35
|
+
The agent's decided drafts are deleted on the chat store's retention schedule. The chat store's
|
|
36
|
+
purge (`GET /api/ontology/agent/chats/purge`, the daily cron job) also deletes `agent_draft`
|
|
37
|
+
records decided and held longer ago than `chat.retentionDays`, and answers how many in `drafts`;
|
|
38
|
+
a draft still waiting is kept. The deletion is recorded in history as `agent_draft.retention` and
|
|
39
|
+
replicates, so the warehouse's views drop the draft, and the draft's history keeps who decided
|
|
40
|
+
what and when with the reply's text, the reasons and notes, and its chat scrubbed.
|
|
41
|
+
|
|
3
42
|
## 0.159.0
|
|
4
43
|
|
|
5
44
|
The chats' temporary attachments table is `_chat_attachments`, and its chat column is `chat`.
|
package/dist/agent-draft.d.ts
CHANGED
|
@@ -26,6 +26,9 @@ export declare const AGENT_DRAFT_STATUSES: readonly [{
|
|
|
26
26
|
}, {
|
|
27
27
|
readonly value: "superseded";
|
|
28
28
|
readonly description: "Redrafted at a member's request: the draft that revises it replaces it.";
|
|
29
|
+
}, {
|
|
30
|
+
readonly value: "dismissed";
|
|
31
|
+
readonly description: string;
|
|
29
32
|
}];
|
|
30
33
|
export declare const AGENT_DRAFT_REVISION_STATES: readonly [{
|
|
31
34
|
readonly value: "requested";
|
|
@@ -45,6 +48,8 @@ export declare const AGENT_DRAFT_MODES: readonly [{
|
|
|
45
48
|
export declare const AGENT_DRAFT_TEXT_LIMIT = 20000;
|
|
46
49
|
/** The longest reason a member gives for rejecting a reply. */
|
|
47
50
|
export declare const AGENT_DRAFT_REASON_LIMIT = 2000;
|
|
51
|
+
/** The most drafts one `newer` call answers for. */
|
|
52
|
+
export declare const AGENT_DRAFT_NEWER_LIMIT = 50;
|
|
48
53
|
/** The longest note a member gives the agent for redrafting a reply. */
|
|
49
54
|
export declare const AGENT_DRAFT_NOTE_LIMIT = 2000;
|
|
50
55
|
/** The most members a draft names as the readers of its reply, as many as a reply to mail goes to. */
|
|
@@ -70,9 +75,12 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
|
|
|
70
75
|
readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
71
76
|
readonly replyTo: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
72
77
|
readonly sessionId: import("./property.js").Property<string, false, false>;
|
|
78
|
+
readonly turnId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
79
|
+
readonly basis: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
80
|
+
readonly message: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
73
81
|
readonly draft: import("./property.js").Property<string, false, false>;
|
|
74
82
|
readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
75
|
-
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded", false, false>;
|
|
83
|
+
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed", false, false>;
|
|
76
84
|
readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
|
|
77
85
|
readonly confidence: Schema.optionalKey<import("./property.js").Property<number, false, false>>;
|
|
78
86
|
readonly messageId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
@@ -93,6 +101,7 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
|
|
|
93
101
|
readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
94
102
|
readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
95
103
|
readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
104
|
+
readonly unlessNewer: Schema.optionalKey<Schema.Boolean>;
|
|
96
105
|
}>, {
|
|
97
106
|
to?: readonly string[] | undefined;
|
|
98
107
|
cc?: readonly string[] | undefined;
|
|
@@ -110,6 +119,18 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
|
|
|
110
119
|
review: string;
|
|
111
120
|
status: "rejected";
|
|
112
121
|
}>;
|
|
122
|
+
readonly dismiss: import("./action.js").Action<Schema.Struct<{
|
|
123
|
+
readonly draft: Schema.Codec<string, string, never, never>;
|
|
124
|
+
readonly reason: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
125
|
+
}>, {
|
|
126
|
+
draft: string;
|
|
127
|
+
status: "dismissed";
|
|
128
|
+
}>;
|
|
129
|
+
readonly newer: import("./action.js").Action<Schema.Struct<{
|
|
130
|
+
readonly drafts: Schema.$Array<Schema.Codec<string, string, never, never>>;
|
|
131
|
+
}>, {
|
|
132
|
+
drafts: readonly import("./chat.js").DraftNewer[];
|
|
133
|
+
}>;
|
|
113
134
|
readonly revise: import("./action.js").Action<Schema.Struct<{
|
|
114
135
|
readonly draft: Schema.Codec<string, string, never, never>;
|
|
115
136
|
readonly note: import("./property.js").Property<string, false, false>;
|
|
@@ -137,9 +158,12 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
|
|
|
137
158
|
readonly threadId: string | null;
|
|
138
159
|
readonly replyTo: string | null;
|
|
139
160
|
readonly sessionId: string;
|
|
161
|
+
readonly turnId: string | null;
|
|
162
|
+
readonly basis: string | null;
|
|
163
|
+
readonly message: string | null;
|
|
140
164
|
readonly draft: string;
|
|
141
165
|
readonly text: string | null;
|
|
142
|
-
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded";
|
|
166
|
+
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed";
|
|
143
167
|
readonly mode: "always" | "whenUnsure";
|
|
144
168
|
readonly confidence: number | null;
|
|
145
169
|
readonly messageId: string | null;
|
|
@@ -169,9 +193,12 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
|
|
|
169
193
|
readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
170
194
|
readonly replyTo: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
171
195
|
readonly sessionId: import("./property.js").Property<string, false, false>;
|
|
196
|
+
readonly turnId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
197
|
+
readonly basis: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
198
|
+
readonly message: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
172
199
|
readonly draft: import("./property.js").Property<string, false, false>;
|
|
173
200
|
readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
174
|
-
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded", false, false>;
|
|
201
|
+
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed", false, false>;
|
|
175
202
|
readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
|
|
176
203
|
readonly confidence: Schema.optionalKey<import("./property.js").Property<number, false, false>>;
|
|
177
204
|
readonly messageId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
@@ -192,6 +219,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
|
|
|
192
219
|
readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
193
220
|
readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
194
221
|
readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
222
|
+
readonly unlessNewer: Schema.optionalKey<Schema.Boolean>;
|
|
195
223
|
}>, {
|
|
196
224
|
to?: readonly string[] | undefined;
|
|
197
225
|
cc?: readonly string[] | undefined;
|
|
@@ -209,6 +237,18 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
|
|
|
209
237
|
review: string;
|
|
210
238
|
status: "rejected";
|
|
211
239
|
}>;
|
|
240
|
+
readonly dismiss: import("./action.js").Action<Schema.Struct<{
|
|
241
|
+
readonly draft: Schema.Codec<string, string, never, never>;
|
|
242
|
+
readonly reason: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
243
|
+
}>, {
|
|
244
|
+
draft: string;
|
|
245
|
+
status: "dismissed";
|
|
246
|
+
}>;
|
|
247
|
+
readonly newer: import("./action.js").Action<Schema.Struct<{
|
|
248
|
+
readonly drafts: Schema.$Array<Schema.Codec<string, string, never, never>>;
|
|
249
|
+
}>, {
|
|
250
|
+
drafts: readonly import("./chat.js").DraftNewer[];
|
|
251
|
+
}>;
|
|
212
252
|
readonly revise: import("./action.js").Action<Schema.Struct<{
|
|
213
253
|
readonly draft: Schema.Codec<string, string, never, never>;
|
|
214
254
|
readonly note: import("./property.js").Property<string, false, false>;
|
|
@@ -236,9 +276,12 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
|
|
|
236
276
|
readonly threadId: string | null;
|
|
237
277
|
readonly replyTo: string | null;
|
|
238
278
|
readonly sessionId: string;
|
|
279
|
+
readonly turnId: string | null;
|
|
280
|
+
readonly basis: string | null;
|
|
281
|
+
readonly message: string | null;
|
|
239
282
|
readonly draft: string;
|
|
240
283
|
readonly text: string | null;
|
|
241
|
-
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded";
|
|
284
|
+
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed";
|
|
242
285
|
readonly mode: "always" | "whenUnsure";
|
|
243
286
|
readonly confidence: number | null;
|
|
244
287
|
readonly messageId: string | null;
|
|
@@ -274,6 +317,9 @@ export declare const AGENT_REVIEW_STATUSES: readonly [{
|
|
|
274
317
|
}, {
|
|
275
318
|
readonly value: "superseded";
|
|
276
319
|
readonly description: "Redrafted at a member's request: the draft that revises it replaces it.";
|
|
320
|
+
}, {
|
|
321
|
+
readonly value: "dismissed";
|
|
322
|
+
readonly description: string;
|
|
277
323
|
}];
|
|
278
324
|
/** @deprecated Use {@link AGENT_DRAFT_MODES}. */
|
|
279
325
|
export declare const AGENT_REVIEW_MODES: readonly [{
|
package/dist/agent-draft.js
CHANGED
|
@@ -29,6 +29,11 @@ export const AGENT_DRAFT_STATUSES = [
|
|
|
29
29
|
value: "superseded",
|
|
30
30
|
description: "Redrafted at a member's request: the draft that revises it replaces it.",
|
|
31
31
|
},
|
|
32
|
+
{
|
|
33
|
+
value: "dismissed",
|
|
34
|
+
description: "Dismissed without a judgement on the reply, such as after the person wrote again: the " +
|
|
35
|
+
"person never sees it.",
|
|
36
|
+
},
|
|
32
37
|
];
|
|
33
38
|
export const AGENT_DRAFT_REVISION_STATES = [
|
|
34
39
|
{ value: "requested", description: "A member asked the agent to redraft it; it is redrafting." },
|
|
@@ -45,6 +50,8 @@ export const AGENT_DRAFT_MODES = [
|
|
|
45
50
|
export const AGENT_DRAFT_TEXT_LIMIT = 20_000;
|
|
46
51
|
/** The longest reason a member gives for rejecting a reply. */
|
|
47
52
|
export const AGENT_DRAFT_REASON_LIMIT = 2_000;
|
|
53
|
+
/** The most drafts one `newer` call answers for. */
|
|
54
|
+
export const AGENT_DRAFT_NEWER_LIMIT = 50;
|
|
48
55
|
/** The longest note a member gives the agent for redrafting a reply. */
|
|
49
56
|
export const AGENT_DRAFT_NOTE_LIMIT = 2_000;
|
|
50
57
|
/** The longest list of addresses a draft keeps in `to` or `cc`: as many as a reply goes to. */
|
|
@@ -80,6 +87,22 @@ export function participantsOfDraft(value) {
|
|
|
80
87
|
.map((id) => id.toLowerCase())),
|
|
81
88
|
];
|
|
82
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Refuses a decision on a draft that no longer waits, or whose delivery an approval reserved: the
|
|
92
|
+
* reservation and a rejection or dismissal take the draft's lock in turn, so whichever comes first
|
|
93
|
+
* decides, and the other is refused.
|
|
94
|
+
*/
|
|
95
|
+
function undecided(review, decision) {
|
|
96
|
+
if (review.status === "pending" && (review.message === null || review.message === undefined)) {
|
|
97
|
+
return Effect.void;
|
|
98
|
+
}
|
|
99
|
+
return Effect.fail(new ActionRejected({
|
|
100
|
+
message: review.status === "pending"
|
|
101
|
+
? `An approval is delivering the reply; it cannot be ${decision}.`
|
|
102
|
+
: `The reply was already decided (${review.status}); it cannot be ${decision}.`,
|
|
103
|
+
refusal: "draft_decided",
|
|
104
|
+
}));
|
|
105
|
+
}
|
|
83
106
|
export const AgentDraft = entity("agent_draft", {
|
|
84
107
|
// The id of the entity's first name: a changed id would be a new entity, without its records.
|
|
85
108
|
id: "ent_agent_review",
|
|
@@ -156,6 +179,30 @@ export const AgentDraft = entity("agent_draft", {
|
|
|
156
179
|
description: "The person's message the reply answers, when the provider replies to one.",
|
|
157
180
|
}),
|
|
158
181
|
sessionId: p.text({ managed: true, description: "The agent's session that wrote the reply." }),
|
|
182
|
+
turnId: p.text({
|
|
183
|
+
optional: true,
|
|
184
|
+
managed: true,
|
|
185
|
+
maxLength: 256,
|
|
186
|
+
label: "Turn id",
|
|
187
|
+
description: "The agent's turn that wrote the reply, so that workspace records, such as notes for " +
|
|
188
|
+
"staff, can relate to it. Empty on a draft held before drafts named their turn.",
|
|
189
|
+
}),
|
|
190
|
+
basis: p.text({
|
|
191
|
+
optional: true,
|
|
192
|
+
managed: true,
|
|
193
|
+
maxLength: 128,
|
|
194
|
+
description: "Where the turn that wrote the reply had read the chat to: the newest message it took, " +
|
|
195
|
+
"as the chat store's place in the chat, <time>~<id>. A message the person wrote after " +
|
|
196
|
+
"it is one the reply did not see. Empty until the chat store holds the turn's messages.",
|
|
197
|
+
}),
|
|
198
|
+
message: p.text({
|
|
199
|
+
optional: true,
|
|
200
|
+
managed: true,
|
|
201
|
+
maxLength: 64,
|
|
202
|
+
description: "The reply's message in the chat store once an approval reserved its delivery, by the " +
|
|
203
|
+
"message's id. Empty while it waits, and for a reply delivered before the chat store " +
|
|
204
|
+
"held the chat.",
|
|
205
|
+
}),
|
|
159
206
|
draft: p.text({
|
|
160
207
|
managed: true,
|
|
161
208
|
maxLength: AGENT_DRAFT_TEXT_LIMIT,
|
|
@@ -290,6 +337,12 @@ export const AgentDraft = entity("agent_draft", {
|
|
|
290
337
|
description: "A reply to mail: the addresses it copies, in place of the draft's cc; [] copies " +
|
|
291
338
|
"no one, and omitting it keeps them.",
|
|
292
339
|
})),
|
|
340
|
+
unlessNewer: Schema.optionalKey(Schema.Boolean.annotate({
|
|
341
|
+
description: "true refuses the approval, with refusal newer_message and nothing sent, when the " +
|
|
342
|
+
"person wrote in the chat after the turn that wrote the reply, or basis_unknown when " +
|
|
343
|
+
"that cannot be told. For approvals without a person reading the chat, such as a " +
|
|
344
|
+
"workflow's.",
|
|
345
|
+
})),
|
|
293
346
|
}),
|
|
294
347
|
connections: [],
|
|
295
348
|
prepare: ({ input }) => Effect.gen(function* () {
|
|
@@ -305,19 +358,29 @@ export const AgentDraft = entity("agent_draft", {
|
|
|
305
358
|
...(input.text === undefined ? {} : { text: input.text }),
|
|
306
359
|
...(input.to === undefined ? {} : { to: input.to }),
|
|
307
360
|
...(input.cc === undefined ? {} : { cc: input.cc }),
|
|
361
|
+
...(input.unlessNewer === true ? { unlessNewer: true } : {}),
|
|
308
362
|
});
|
|
309
363
|
}),
|
|
310
364
|
handler: ({ input, prepared, principal }) => Effect.gen(function* () {
|
|
311
365
|
const review = yield* self.get(input.draft, { forUpdate: true });
|
|
312
366
|
const recipients = prepared.recipients;
|
|
313
|
-
//
|
|
314
|
-
//
|
|
367
|
+
// A replay finds the outcome recorded and keeps who decided. Otherwise this approval is
|
|
368
|
+
// the decision: on the chat store its reservation refused while the draft was decided, and
|
|
369
|
+
// a rejection or dismissal refuses once it is reserved. Only a delivery before the store
|
|
370
|
+
// held the chat can meet one taken meanwhile; the record then says what the provider did,
|
|
371
|
+
// as this approval's, and the history keeps the other decision before it.
|
|
372
|
+
const recorded = review.status === "sent" || review.status === "uncertain" || review.status === "failed";
|
|
315
373
|
yield* self.update(review, {
|
|
316
374
|
status: prepared.status,
|
|
317
375
|
text: prepared.text,
|
|
318
376
|
messageId: prepared.messageId,
|
|
319
|
-
|
|
320
|
-
|
|
377
|
+
...(prepared.message === undefined || prepared.message === null
|
|
378
|
+
? {}
|
|
379
|
+
: { message: prepared.message }),
|
|
380
|
+
decidedAt: recorded
|
|
381
|
+
? (review.decidedAt ?? new Date().toISOString())
|
|
382
|
+
: new Date().toISOString(),
|
|
383
|
+
decidedBy: recorded ? (review.decidedById ?? principal.id) : principal.id,
|
|
321
384
|
...(recipients === undefined
|
|
322
385
|
? {}
|
|
323
386
|
: {
|
|
@@ -355,11 +418,7 @@ export const AgentDraft = entity("agent_draft", {
|
|
|
355
418
|
if (review.status === "rejected") {
|
|
356
419
|
return result;
|
|
357
420
|
}
|
|
358
|
-
|
|
359
|
-
return yield* new ActionRejected({
|
|
360
|
-
message: "The reply was already approved and sent; it cannot be rejected.",
|
|
361
|
-
});
|
|
362
|
-
}
|
|
421
|
+
yield* undecided(review, "rejected");
|
|
363
422
|
const reason = input.reason?.trim();
|
|
364
423
|
yield* self.update(review, {
|
|
365
424
|
status: "rejected",
|
|
@@ -370,6 +429,58 @@ export const AgentDraft = entity("agent_draft", {
|
|
|
370
429
|
return result;
|
|
371
430
|
}),
|
|
372
431
|
}),
|
|
432
|
+
dismiss: action({
|
|
433
|
+
description: "Dismiss the agent's draft reply without judging it, such as when the person wrote again " +
|
|
434
|
+
"after it: the person never sees it. Say why in reason; it stays with the draft and never " +
|
|
435
|
+
"reaches the person or the agent's chat with them. Only a draft that still waits can be " +
|
|
436
|
+
"dismissed, and dismissing one already dismissed returns it.",
|
|
437
|
+
hints: { destructive: true, irreversible: false, idempotent: true },
|
|
438
|
+
input: Schema.Struct({
|
|
439
|
+
draft: self.ref,
|
|
440
|
+
reason: Schema.optionalKey(p.text({
|
|
441
|
+
maxLength: AGENT_DRAFT_REASON_LIMIT,
|
|
442
|
+
description: "Why the reply is no longer to be sent.",
|
|
443
|
+
})),
|
|
444
|
+
}),
|
|
445
|
+
handler: ({ input, principal }) => Effect.gen(function* () {
|
|
446
|
+
const review = yield* self.get(input.draft, { forUpdate: true });
|
|
447
|
+
const result = { draft: review.id, status: "dismissed" };
|
|
448
|
+
if (review.status === "dismissed") {
|
|
449
|
+
return result;
|
|
450
|
+
}
|
|
451
|
+
yield* undecided(review, "dismissed");
|
|
452
|
+
const reason = input.reason?.trim();
|
|
453
|
+
yield* self.update(review, {
|
|
454
|
+
status: "dismissed",
|
|
455
|
+
decidedAt: new Date().toISOString(),
|
|
456
|
+
decidedBy: principal.id,
|
|
457
|
+
...(reason === undefined || reason === "" ? {} : { reason }),
|
|
458
|
+
});
|
|
459
|
+
return result;
|
|
460
|
+
}),
|
|
461
|
+
}),
|
|
462
|
+
newer: action({
|
|
463
|
+
description: "Tell, for drafts that wait, whether the person wrote in the chat after the turn that " +
|
|
464
|
+
"wrote each reply: newer true when they did, so the reply did not see it; false when they " +
|
|
465
|
+
"did not; null when it cannot be told, as for a draft whose chat the chat store does not " +
|
|
466
|
+
"hold. approve with unlessNewer refuses exactly when newer is true or null.",
|
|
467
|
+
permission: "agent_draft:read",
|
|
468
|
+
hints: { readOnly: true, destructive: false, irreversible: false, idempotent: true },
|
|
469
|
+
input: Schema.Struct({
|
|
470
|
+
drafts: Schema.Array(self.ref).check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_NEWER_LIMIT)),
|
|
471
|
+
}),
|
|
472
|
+
connections: [],
|
|
473
|
+
prepare: ({ input }) => Effect.gen(function* () {
|
|
474
|
+
const delivery = yield* Effect.serviceOption(ChatDelivery);
|
|
475
|
+
const newer = Option.isSome(delivery) ? delivery.value.draftsNewer : undefined;
|
|
476
|
+
if (newer === undefined) {
|
|
477
|
+
return yield* new ActionRejected({
|
|
478
|
+
message: "Reading drafts' chats requires the authenticated ontology service.",
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
return { drafts: yield* newer(input.drafts.map(String)) };
|
|
482
|
+
}),
|
|
483
|
+
}),
|
|
373
484
|
revise: action({
|
|
374
485
|
description: "Ask the agent to redraft its draft reply, with what to change in note, in the " +
|
|
375
486
|
"member's words. The agent writes it again in a session of its own, which reads the chat " +
|
package/dist/chat.d.ts
CHANGED
|
@@ -210,6 +210,16 @@ export interface ReviewSendInput {
|
|
|
210
210
|
readonly to?: ReadonlyArray<string>;
|
|
211
211
|
/** A reply to mail: the addresses it copies, in place of the review's own. */
|
|
212
212
|
readonly cc?: ReadonlyArray<string>;
|
|
213
|
+
/**
|
|
214
|
+
* Refuse the approval, before anything is reserved or sent, when the person wrote in the chat
|
|
215
|
+
* after the turn that wrote the reply, or when that cannot be told.
|
|
216
|
+
*/
|
|
217
|
+
readonly unlessNewer?: boolean;
|
|
218
|
+
}
|
|
219
|
+
/** Whether the person wrote after a draft's turn; `null` when it cannot be told. */
|
|
220
|
+
export interface DraftNewer {
|
|
221
|
+
readonly draft: string;
|
|
222
|
+
readonly newer: boolean | null;
|
|
213
223
|
}
|
|
214
224
|
/** What sending an approved reply did; `duplicate` when an earlier approval already sent it. */
|
|
215
225
|
export interface ReviewSendResult {
|
|
@@ -218,6 +228,8 @@ export interface ReviewSendResult {
|
|
|
218
228
|
readonly text: string;
|
|
219
229
|
readonly messageId: string | null;
|
|
220
230
|
readonly duplicate: boolean;
|
|
231
|
+
/** The reply's message in the workspace chat store, by its id; absent before the store held it. */
|
|
232
|
+
readonly message?: string | null;
|
|
221
233
|
/** A reply to mail: whom it was sent to, or attempted; absent on another channel. */
|
|
222
234
|
readonly recipients?: {
|
|
223
235
|
readonly to: ReadonlyArray<string>;
|
|
@@ -243,6 +255,8 @@ declare const ChatDelivery_base: Context.ServiceClass<ChatDelivery, "@segmentstr
|
|
|
243
255
|
readonly send?: (input: ChatSendInput) => Effect.Effect<ChatPostResult, ActionError>;
|
|
244
256
|
/** Sends a reply a member approved, as the agent and without attribution, at most once. */
|
|
245
257
|
readonly sendReview?: (input: ReviewSendInput) => Effect.Effect<ReviewSendResult, ActionError>;
|
|
258
|
+
/** Whether the person wrote after each draft's turn, as `approve`'s `unlessNewer` tells it. */
|
|
259
|
+
readonly draftsNewer?: (drafts: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<DraftNewer>, ActionError>;
|
|
246
260
|
/** Asks the agent to redraft a reply it held for review, in a session of its own. */
|
|
247
261
|
readonly reviseReview?: (input: ReviewReviseInput) => Effect.Effect<ReviewReviseResult, ActionError>;
|
|
248
262
|
/** Adds a chat's messages from before the agent recorded it, each in its place by its time. */
|
package/dist/errors.d.ts
CHANGED
|
@@ -68,7 +68,10 @@ declare const ActionRejected_base: Schema.Class<ActionRejected, Schema.TaggedStr
|
|
|
68
68
|
* Why a chat's provider refused a message, for code to act on: `outside_reply_window` (the person
|
|
69
69
|
* last wrote longer ago than the channel lets a free-form message reach them; WhatsApp takes a
|
|
70
70
|
* template), `recipient_unreachable` (the person blocked the sender or cannot receive it) or
|
|
71
|
-
* `recipient_opted_out` (the person stopped such messages).
|
|
71
|
+
* `recipient_opted_out` (the person stopped such messages). A draft's decision says why it was
|
|
72
|
+
* refused too: `newer_message` (the person wrote after the turn that wrote it, refused by
|
|
73
|
+
* `unlessNewer`), `basis_unknown` (whether they did cannot be told) or `draft_decided` (it was
|
|
74
|
+
* decided, or an approval is delivering it).
|
|
72
75
|
*/
|
|
73
76
|
readonly refusal: Schema.optionalKey<Schema.String>;
|
|
74
77
|
}>, import("effect/Cause").YieldableError>;
|
package/dist/errors.js
CHANGED
|
@@ -45,7 +45,10 @@ export class ActionRejected extends Schema.TaggedError()("ActionRejected", {
|
|
|
45
45
|
* Why a chat's provider refused a message, for code to act on: `outside_reply_window` (the person
|
|
46
46
|
* last wrote longer ago than the channel lets a free-form message reach them; WhatsApp takes a
|
|
47
47
|
* template), `recipient_unreachable` (the person blocked the sender or cannot receive it) or
|
|
48
|
-
* `recipient_opted_out` (the person stopped such messages).
|
|
48
|
+
* `recipient_opted_out` (the person stopped such messages). A draft's decision says why it was
|
|
49
|
+
* refused too: `newer_message` (the person wrote after the turn that wrote it, refused by
|
|
50
|
+
* `unlessNewer`), `basis_unknown` (whether they did cannot be told) or `draft_decided` (it was
|
|
51
|
+
* decided, or an approval is delivering it).
|
|
49
52
|
*/
|
|
50
53
|
refusal: Schema.optionalKey(Schema.String),
|
|
51
54
|
}) {
|
package/dist/index.d.ts
CHANGED
|
@@ -59,14 +59,14 @@ export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, Batc
|
|
|
59
59
|
export { User } from "./user.js";
|
|
60
60
|
export type { UserHandle, UserMemberWrites } from "./user.js";
|
|
61
61
|
export { AgentChat } from "./agent-chat.js";
|
|
62
|
-
export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT, AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-draft.js";
|
|
62
|
+
export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_NEWER_LIMIT, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT, AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-draft.js";
|
|
63
63
|
export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
|
|
64
64
|
export type { AttachableIdentityProvider, UserIdentityOrigin } from "./user-identity.js";
|
|
65
65
|
export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
|
|
66
66
|
export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatTemplateMedia, ChatPostResult, } from "./chat.js";
|
|
67
67
|
export { CHAT_CHANNEL_KINDS, CHAT_CHANNEL_NAME, CHAT_KINDS, WORKSPACE_CHANNEL_KIND, channelIdentityProvider, } from "./chat-channel.js";
|
|
68
68
|
export type { ChatChannelKind, ChatKind } from "./chat-channel.js";
|
|
69
|
-
export type { InboxOptions, ReviewReviseInput, ReviewReviseResult, ReviewSendInput, ReviewSendResult, } from "./chat.js";
|
|
69
|
+
export type { DraftNewer, InboxOptions, ReviewReviseInput, ReviewReviseResult, ReviewSendInput, ReviewSendResult, } from "./chat.js";
|
|
70
70
|
export { DEFAULT_QUERY_LIMIT, entityQueryResultSchema, entityQuerySchema, entityQuerySchemas, entityRecordSchema, FILTER_OPERATORS, LIST_FILTER_OPERATORS, MANY_QUANTIFIERS, MAX_IN_VALUES, MAX_QUERY_LIMIT, OrderBy, Query, queryFields, queryJsonSchema, queryLinks, QueryResult, queryResultJsonSchema, queryResultSchema, SortDirection, WHERE_COMBINATORS, } from "./query.js";
|
|
71
71
|
export type { EntityQuerySchemas, FieldFilter, FilterOperator, JsonRecord, ListFilterOperator, ManyFilter, QueryField, QueryLink, StorageType, Where, } from "./query.js";
|
|
72
72
|
export { InvalidQuery, InvalidValues, MemberNotFound, PrincipalRejected, StoredRecordMismatch, UnknownAction, UnknownRole, ValidationIssue, UndeclaredWrite, WriteOutsideAction, } from "./runtime/errors.js";
|
package/dist/index.js
CHANGED
|
@@ -34,7 +34,7 @@ export { EMAIL_MARKUP_VALUES, isEmailDocument, unsafeEmailHtml } from "./emails.
|
|
|
34
34
|
export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
|
|
35
35
|
export { User } from "./user.js";
|
|
36
36
|
export { AgentChat } from "./agent-chat.js";
|
|
37
|
-
export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT,
|
|
37
|
+
export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_NEWER_LIMIT, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT,
|
|
38
38
|
// @legacy ontology.agent-review-entity-name
|
|
39
39
|
AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-draft.js";
|
|
40
40
|
export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
|
package/dist/runtime/agents.js
CHANGED
|
@@ -5,6 +5,7 @@ import { SqlClient } from "effect/unstable/sql";
|
|
|
5
5
|
import { action } from "../action.js";
|
|
6
6
|
import { AgentChat, agentChatKey } from "../agent-chat.js";
|
|
7
7
|
import { chatChannelKind } from "../chat-channel.js";
|
|
8
|
+
import { historyTableName, quoteIdentifier, tableName } from "../migrate/storage.js";
|
|
8
9
|
import { addressesOfDraft, AgentDraft, participantsOfDraft, draftAddresses, draftParticipants, } from "../agent-draft.js";
|
|
9
10
|
import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
|
|
10
11
|
import { inboxChannelsOf, inboxRolesOf, takeoverChannelsOf, takeoverProvidersOf, } from "../manifest.js";
|
|
@@ -17,7 +18,7 @@ import { resolveAgentIdentity } from "./resolve-agent-identity.js";
|
|
|
17
18
|
import { completeAgentLimitNotice } from "./agent-counters.js";
|
|
18
19
|
import { isMemberBlocked, setMemberBlocked, resolveMemberById } from "./principals.js";
|
|
19
20
|
import { sqlAgentWebStore } from "./agent-web.js";
|
|
20
|
-
import { sqlChatMessageStore } from "./chat-messages.js";
|
|
21
|
+
import { chatCursorOf, parseChatCursor, sqlChatMessageStore } from "./chat-messages.js";
|
|
21
22
|
import { guestChat } from "./guests.js";
|
|
22
23
|
import { WEB_PROVIDER } from "../service/runtime-identity.js";
|
|
23
24
|
import { isRecordId } from "./records.js";
|
|
@@ -75,6 +76,32 @@ function kindOf(input) {
|
|
|
75
76
|
? "group"
|
|
76
77
|
: "private";
|
|
77
78
|
}
|
|
79
|
+
/** The most drafts one retention batch deletes, and the most batches one purge runs. */
|
|
80
|
+
const DRAFT_PURGE_BATCH = 200;
|
|
81
|
+
const DRAFT_PURGE_BATCHES = 20;
|
|
82
|
+
/** The action a draft's deletion by retention is recorded under in its history. */
|
|
83
|
+
const RETENTION_ACTION = "retention";
|
|
84
|
+
const DRAFTS = quoteIdentifier(tableName(AgentDraft.name));
|
|
85
|
+
const DRAFT_HISTORY = quoteIdentifier(historyTableName(AgentDraft.name));
|
|
86
|
+
/**
|
|
87
|
+
* What a draft's history says of its reply and its chat, scrubbed once retention deletes it: the
|
|
88
|
+
* text, the reasons and notes members wrote, and whom and where it went.
|
|
89
|
+
*/
|
|
90
|
+
const DRAFT_CONTENT_FIELDS = [
|
|
91
|
+
"draft",
|
|
92
|
+
"text",
|
|
93
|
+
"reason",
|
|
94
|
+
"note",
|
|
95
|
+
"to",
|
|
96
|
+
"cc",
|
|
97
|
+
"recipient",
|
|
98
|
+
"participants",
|
|
99
|
+
"chat_id",
|
|
100
|
+
"thread_id",
|
|
101
|
+
"reply_to",
|
|
102
|
+
"message_id",
|
|
103
|
+
"basis",
|
|
104
|
+
];
|
|
78
105
|
function nullableText(value) {
|
|
79
106
|
return value === null || value === undefined ? null : String(value);
|
|
80
107
|
}
|
|
@@ -128,6 +155,35 @@ const HOLD_DEFINITION = action({
|
|
|
128
155
|
export function sqlAgentStore(ontology, sql) {
|
|
129
156
|
const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
|
|
130
157
|
const memberPrincipal = (userId) => resolveMemberById(ontology, userId).pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
158
|
+
const messages = sqlChatMessageStore(sql);
|
|
159
|
+
/** The newest message the turn took in the chat, as the chat store's place; null without one. */
|
|
160
|
+
const turnBasis = (channel, chatId, turnId) => messages
|
|
161
|
+
.turnBasis({ channel, chatId, turnId })
|
|
162
|
+
.pipe(Effect.map((cursor) => (cursor === undefined ? null : chatCursorOf(cursor))));
|
|
163
|
+
/**
|
|
164
|
+
* Whether the person wrote in a draft's chat after the turn that wrote it: one definition for
|
|
165
|
+
* `approve`'s `unlessNewer` and the `newer` action. The place the turn read to is the draft's
|
|
166
|
+
* basis, or, when its hold came before the chat store named the turn's messages, those messages
|
|
167
|
+
* now; null when neither is known. In a group, only the draft's person counts.
|
|
168
|
+
*/
|
|
169
|
+
const newerOf = (review) => Effect.gen(function* () {
|
|
170
|
+
const channel = nullableText(review.channel) ?? String(review.channel_kind);
|
|
171
|
+
const chatId = String(review.chat_id);
|
|
172
|
+
const turnId = nullableText(review.turn_id);
|
|
173
|
+
const basis = parseChatCursor(nullableText(review.basis) ?? "") ??
|
|
174
|
+
(turnId === null ? undefined : yield* messages.turnBasis({ channel, chatId, turnId }));
|
|
175
|
+
if (basis === undefined) {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
const person = nullableText(review.person_id);
|
|
179
|
+
return yield* messages.wroteAfter({
|
|
180
|
+
channel,
|
|
181
|
+
chatId,
|
|
182
|
+
after: basis,
|
|
183
|
+
...(turnId === null ? {} : { turnId }),
|
|
184
|
+
...(review.chat_kind === "group" && person !== null ? { userId: person } : {}),
|
|
185
|
+
});
|
|
186
|
+
});
|
|
131
187
|
/**
|
|
132
188
|
* Holds a reply for review once per key, in a transaction bounded and admitted as an action's,
|
|
133
189
|
* and starts the workflows whose triggers on `agent_draft` fire for it. `resolve` runs in the
|
|
@@ -236,6 +292,15 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
236
292
|
thread_id: input.threadId === "" ? null : input.threadId,
|
|
237
293
|
reply_to: input.replyTo,
|
|
238
294
|
session_id: input.sessionId,
|
|
295
|
+
// A redraft answers what the reply it replaces answered.
|
|
296
|
+
turn_id: resolved.kind === "revision"
|
|
297
|
+
? nullableText(resolved.previous.turn_id)
|
|
298
|
+
: (input.turnId ?? null),
|
|
299
|
+
basis: resolved.kind === "revision"
|
|
300
|
+
? nullableText(resolved.previous.basis)
|
|
301
|
+
: input.turnId === undefined
|
|
302
|
+
? null
|
|
303
|
+
: yield* turnBasis(input.channel, input.chatId, input.turnId),
|
|
239
304
|
draft: input.text,
|
|
240
305
|
text: null,
|
|
241
306
|
status: "pending",
|
|
@@ -969,6 +1034,86 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
969
1034
|
return true;
|
|
970
1035
|
}))
|
|
971
1036
|
.pipe(Effect.orDie),
|
|
1037
|
+
reserveDraft: (input) => sql
|
|
1038
|
+
.withTransaction(Effect.gen(function* () {
|
|
1039
|
+
if (!isRecordId(input.review)) {
|
|
1040
|
+
return { kind: "missing" };
|
|
1041
|
+
}
|
|
1042
|
+
yield* beginReplicationWrite(sql);
|
|
1043
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
1044
|
+
action: `${AgentDraft.name}.approve`,
|
|
1045
|
+
actionId: randomUUID(),
|
|
1046
|
+
principalId: isRecordId(input.principalId) ? input.principalId : null,
|
|
1047
|
+
});
|
|
1048
|
+
// The draft's lock orders this reservation and any rejection or dismissal of it.
|
|
1049
|
+
const [review] = yield* runtime
|
|
1050
|
+
.find({
|
|
1051
|
+
entity: AgentDraft.name,
|
|
1052
|
+
options: { where: { id: input.review }, limit: 1, forUpdate: true },
|
|
1053
|
+
})
|
|
1054
|
+
.pipe(Effect.orDie);
|
|
1055
|
+
if (review === undefined) {
|
|
1056
|
+
return { kind: "missing" };
|
|
1057
|
+
}
|
|
1058
|
+
const reserved = nullableText(review.message);
|
|
1059
|
+
// An approval reserved the delivery already: its replay reads the receipt.
|
|
1060
|
+
if (reserved === null) {
|
|
1061
|
+
if (review.status !== "pending") {
|
|
1062
|
+
return { kind: "decided", status: String(review.status) };
|
|
1063
|
+
}
|
|
1064
|
+
if (input.unlessNewer) {
|
|
1065
|
+
// The chat's lock, which the reservation takes too, before reading it: a message
|
|
1066
|
+
// being recorded is read once it commits, and none commits before the reservation.
|
|
1067
|
+
yield* messages.lockChat({
|
|
1068
|
+
channel: nullableText(review.channel) ?? String(review.channel_kind),
|
|
1069
|
+
chatId: String(review.chat_id),
|
|
1070
|
+
});
|
|
1071
|
+
const newer = yield* newerOf(review);
|
|
1072
|
+
// Refused before anything changes: a redraft asked for still replaces it.
|
|
1073
|
+
if (newer !== false) {
|
|
1074
|
+
return { kind: "newer", newer };
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
if (review.revision !== null && review.revision !== undefined) {
|
|
1078
|
+
yield* runtime
|
|
1079
|
+
.update({
|
|
1080
|
+
entity: AgentDraft.name,
|
|
1081
|
+
id: String(review.id),
|
|
1082
|
+
values: { revision: null, revision_state: null },
|
|
1083
|
+
})
|
|
1084
|
+
.pipe(Effect.orDie);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
const value = yield* input.reserve;
|
|
1088
|
+
const claim = input.claimOf(value);
|
|
1089
|
+
if (claim !== undefined && claim !== reserved) {
|
|
1090
|
+
yield* runtime
|
|
1091
|
+
.update({
|
|
1092
|
+
entity: AgentDraft.name,
|
|
1093
|
+
id: String(review.id),
|
|
1094
|
+
values: { message: claim },
|
|
1095
|
+
})
|
|
1096
|
+
.pipe(Effect.orDie);
|
|
1097
|
+
}
|
|
1098
|
+
return { kind: "reserved", value };
|
|
1099
|
+
}))
|
|
1100
|
+
.pipe(Effect.catchTag("SqlError", Effect.die)),
|
|
1101
|
+
draftsNewer: (drafts) => Effect.gen(function* () {
|
|
1102
|
+
const ids = drafts.filter(isRecordId);
|
|
1103
|
+
const found = ids.length === 0
|
|
1104
|
+
? []
|
|
1105
|
+
: yield* makeOntologyRuntime(ontology, sql).find({
|
|
1106
|
+
entity: AgentDraft.name,
|
|
1107
|
+
options: { where: { id: { in: ids } }, limit: ids.length },
|
|
1108
|
+
});
|
|
1109
|
+
const byId = new Map(found.map((record) => [String(record.id), record]));
|
|
1110
|
+
return yield* Effect.forEach(drafts, (draft) => {
|
|
1111
|
+
const record = byId.get(draft);
|
|
1112
|
+
return (record === undefined || record.status !== "pending"
|
|
1113
|
+
? Effect.succeed(null)
|
|
1114
|
+
: newerOf(record)).pipe(Effect.map((newer) => ({ draft, newer })));
|
|
1115
|
+
});
|
|
1116
|
+
}).pipe(Effect.orDie),
|
|
972
1117
|
cancelRevision: (input) => sql
|
|
973
1118
|
.withTransaction(Effect.gen(function* () {
|
|
974
1119
|
if (!isRecordId(input.review)) {
|
|
@@ -1026,6 +1171,45 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
1026
1171
|
return true;
|
|
1027
1172
|
}))
|
|
1028
1173
|
.pipe(Effect.orDie),
|
|
1174
|
+
purgeDrafts: ({ retentionDays }) => Effect.gen(function* () {
|
|
1175
|
+
let deleted = 0;
|
|
1176
|
+
let more = false;
|
|
1177
|
+
for (let batch = 0; batch < DRAFT_PURGE_BATCHES; batch++) {
|
|
1178
|
+
// Each batch commits on its own and skips drafts another writer holds.
|
|
1179
|
+
const removed = yield* sql.withTransaction(Effect.gen(function* () {
|
|
1180
|
+
yield* beginReplicationWrite(sql);
|
|
1181
|
+
const expired = yield* rows(`SELECT "id"::text AS "id" FROM ${DRAFTS} WHERE "status"::text <> 'pending' ` +
|
|
1182
|
+
`AND "created_at" < now() - make_interval(days => $1::int) ` +
|
|
1183
|
+
`ORDER BY "created_at" LIMIT $2::int FOR UPDATE SKIP LOCKED`, [retentionDays, DRAFT_PURGE_BATCH]);
|
|
1184
|
+
const ids = expired.map((row) => String(row.id));
|
|
1185
|
+
if (ids.length === 0) {
|
|
1186
|
+
return 0;
|
|
1187
|
+
}
|
|
1188
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
1189
|
+
action: `${AgentDraft.name}.${RETENTION_ACTION}`,
|
|
1190
|
+
actionId: randomUUID(),
|
|
1191
|
+
principalId: null,
|
|
1192
|
+
});
|
|
1193
|
+
// A delete is history, which replicates it: the warehouse's view drops the draft.
|
|
1194
|
+
for (const id of ids) {
|
|
1195
|
+
yield* runtime.delete({ entity: AgentDraft.name, id }).pipe(Effect.orDie);
|
|
1196
|
+
}
|
|
1197
|
+
// History keeps who decided what and when, never what the reply said.
|
|
1198
|
+
yield* rows(`UPDATE ${DRAFT_HISTORY} SET "changes" = (SELECT coalesce(jsonb_object_agg("key", ` +
|
|
1199
|
+
`CASE WHEN "key" = ANY($2::text[]) ` +
|
|
1200
|
+
`THEN jsonb_build_object('before', NULL, 'after', NULL) ELSE "value" END), '{}'::jsonb) ` +
|
|
1201
|
+
`FROM jsonb_each("changes")) ` +
|
|
1202
|
+
`WHERE "record_id"::text = ANY($1::text[])`, [ids, DRAFT_CONTENT_FIELDS]);
|
|
1203
|
+
return ids.length;
|
|
1204
|
+
}));
|
|
1205
|
+
deleted += removed;
|
|
1206
|
+
more = removed >= DRAFT_PURGE_BATCH;
|
|
1207
|
+
if (!more) {
|
|
1208
|
+
break;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
return { deleted, more };
|
|
1212
|
+
}).pipe(Effect.catchTag("SqlError", Effect.die)),
|
|
1029
1213
|
sessionReviews: (sessionId) => Effect.gen(function* () {
|
|
1030
1214
|
const runtime = makeOntologyRuntime(ontology, sql);
|
|
1031
1215
|
// Every reply still waiting, however old, and the latest decisions: a decision on an old
|
|
@@ -1062,7 +1246,7 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
1062
1246
|
: timestampText(record.decided_at),
|
|
1063
1247
|
}));
|
|
1064
1248
|
}).pipe(Effect.orDie),
|
|
1065
|
-
chatMessages:
|
|
1249
|
+
chatMessages: messages,
|
|
1066
1250
|
web: sqlAgentWebStore(ontology, sql, {
|
|
1067
1251
|
signUp: (visitorId) => resolveChannelSignIn(ontology, sql, { provider: WEB_PROVIDER, externalId: visitorId }),
|
|
1068
1252
|
}),
|
|
@@ -298,6 +298,38 @@ export interface ChatMessageStore {
|
|
|
298
298
|
readonly channel: string;
|
|
299
299
|
readonly chatId: string;
|
|
300
300
|
}) => Effect.Effect<boolean>;
|
|
301
|
+
/**
|
|
302
|
+
* Takes a chat's lock until the caller's transaction ends: the lock every write to the chat takes
|
|
303
|
+
* first, so what the caller reads of the chat holds until it commits.
|
|
304
|
+
*/
|
|
305
|
+
readonly lockChat: (chat: {
|
|
306
|
+
readonly channel: string;
|
|
307
|
+
readonly chatId: string;
|
|
308
|
+
}) => Effect.Effect<void>;
|
|
309
|
+
/**
|
|
310
|
+
* The newest message a turn took in a chat (`turn_id`), as the place a draft of the turn's reply
|
|
311
|
+
* was written from; `undefined` when the store holds none of the turn's messages.
|
|
312
|
+
*/
|
|
313
|
+
readonly turnBasis: (input: {
|
|
314
|
+
readonly channel: string;
|
|
315
|
+
readonly chatId: string;
|
|
316
|
+
readonly turnId: string;
|
|
317
|
+
}) => Effect.Effect<{
|
|
318
|
+
readonly at: string;
|
|
319
|
+
readonly id: string;
|
|
320
|
+
} | undefined>;
|
|
321
|
+
/**
|
|
322
|
+
* Whether a person wrote in a chat after `after`: an inbound message of a person, recorded as it
|
|
323
|
+
* arrived and not imported, after that place in the chat, that the turn `turnId` did not take.
|
|
324
|
+
* With `userId`, only that member's messages count, as in a group several people write in.
|
|
325
|
+
*/
|
|
326
|
+
readonly wroteAfter: (input: {
|
|
327
|
+
readonly channel: string;
|
|
328
|
+
readonly chatId: string;
|
|
329
|
+
readonly after: ChatCursor;
|
|
330
|
+
readonly turnId?: string;
|
|
331
|
+
readonly userId?: string;
|
|
332
|
+
}) => Effect.Effect<boolean>;
|
|
301
333
|
/** The send an `operation` keys, its tombstone included; `undefined` when the key has none. */
|
|
302
334
|
readonly findSend: (operation: string) => Effect.Effect<ChatSend | undefined>;
|
|
303
335
|
/** Messages as a reader may read them, row by row: only what reached the provider. */
|
|
@@ -195,10 +195,11 @@ export function sqlChatMessageStore(sql) {
|
|
|
195
195
|
* messages take their revisions in the order they commit: a reader whose bookmark passed a
|
|
196
196
|
* revision never misses a lower one committed after it.
|
|
197
197
|
*/
|
|
198
|
-
const
|
|
199
|
-
.withTransaction(rows(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
|
|
198
|
+
const lockChat = ({ channel, chatId }) => rows(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
|
|
200
199
|
JSON.stringify([CHAT_MESSAGES_TABLE, channel, chatId]),
|
|
201
|
-
]).pipe(Effect.
|
|
200
|
+
]).pipe(Effect.asVoid);
|
|
201
|
+
const inChat = (channel, chatId, write) => sql
|
|
202
|
+
.withTransaction(lockChat({ channel, chatId }).pipe(Effect.andThen(write)))
|
|
202
203
|
.pipe(Effect.catchTag("SqlError", Effect.die));
|
|
203
204
|
const insert = (input) => Effect.gen(function* () {
|
|
204
205
|
const params = parameters();
|
|
@@ -620,6 +621,29 @@ export function sqlChatMessageStore(sql) {
|
|
|
620
621
|
const holds = (chat) => rows(chat === undefined
|
|
621
622
|
? `SELECT EXISTS (SELECT 1 FROM ${TABLE}) AS "holds"`
|
|
622
623
|
: `SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE "channel" = $1 AND "chat_id" = $2) AS "holds"`, chat === undefined ? [] : [chat.channel, chat.chatId]).pipe(Effect.map(([row]) => row?.holds === true || row?.holds === "t"));
|
|
624
|
+
const turnBasis = (input) => rows(`SELECT "id"::text AS "id", ${epochMs(`"at"`)} AS "at" FROM ${TABLE} ` +
|
|
625
|
+
`WHERE "channel" = $1 AND "chat_id" = $2 AND "turn_id" = $3 AND "direction" = 'inbound' ` +
|
|
626
|
+
`AND "purged_at" IS NULL ORDER BY "at" DESC, "id" DESC LIMIT 1`, [input.channel, input.chatId, input.turnId]).pipe(Effect.map(([row]) => row === undefined ? undefined : { at: instant(row.at), id: String(row.id) }));
|
|
627
|
+
const wroteAfter = (input) => {
|
|
628
|
+
const params = parameters();
|
|
629
|
+
const at = params.add(input.after.at, "timestamptz");
|
|
630
|
+
const conditions = [
|
|
631
|
+
`"channel" = ${params.add(input.channel)}`,
|
|
632
|
+
`"chat_id" = ${params.add(input.chatId)}`,
|
|
633
|
+
`"direction" = 'inbound'`,
|
|
634
|
+
`"author" = 'human'`,
|
|
635
|
+
`"imported_at" IS NULL`,
|
|
636
|
+
`"purged_at" IS NULL`,
|
|
637
|
+
input.after.id === undefined
|
|
638
|
+
? `"at" > ${at}`
|
|
639
|
+
: `("at" > ${at} OR ("at" = ${at} AND "id" > ${params.add(input.after.id, "uuid")}))`,
|
|
640
|
+
...(input.turnId === undefined
|
|
641
|
+
? []
|
|
642
|
+
: [`"turn_id" IS DISTINCT FROM ${params.add(input.turnId)}`]),
|
|
643
|
+
...(input.userId === undefined ? [] : [`"user_id" = ${params.add(input.userId, "uuid")}`]),
|
|
644
|
+
];
|
|
645
|
+
return rows(`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE ${conditions.join(" AND ")}) AS "wrote"`, params.values).pipe(Effect.map(([row]) => row?.wrote === true || row?.wrote === "t"));
|
|
646
|
+
};
|
|
623
647
|
const findSend = (operation) => rows(`SELECT "id"::text AS "id", "channel", "chat_id", "status", "message_id", "failure", ` +
|
|
624
648
|
`"fingerprint", "meta"::text AS "meta", ${epochMs(`"at"`)} AS "at", ` +
|
|
625
649
|
`"purged_at" IS NOT NULL AS "purged" FROM ${TABLE} WHERE "operation" = $1 LIMIT 1`, [operation]).pipe(Effect.map(([row]) => row === undefined
|
|
@@ -670,5 +694,16 @@ export function sqlChatMessageStore(sql) {
|
|
|
670
694
|
}
|
|
671
695
|
return { deleted, scrubbed, more };
|
|
672
696
|
});
|
|
673
|
-
return {
|
|
697
|
+
return {
|
|
698
|
+
record,
|
|
699
|
+
change,
|
|
700
|
+
read,
|
|
701
|
+
holds,
|
|
702
|
+
lockChat,
|
|
703
|
+
turnBasis,
|
|
704
|
+
wroteAfter,
|
|
705
|
+
findSend,
|
|
706
|
+
search,
|
|
707
|
+
purge,
|
|
708
|
+
};
|
|
674
709
|
}
|
|
@@ -2,6 +2,7 @@ import { Effect, Redacted, Schema } from "effect";
|
|
|
2
2
|
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
|
3
3
|
import { type ChatMessageStore } from "../../runtime/chat-messages.js";
|
|
4
4
|
import { RequestId } from "../errors.js";
|
|
5
|
+
import type { AgentStore } from "../runtime-contract.js";
|
|
5
6
|
/** `POST /api/ontology/agent/chats/messages`: one message, recorded once by its keys. */
|
|
6
7
|
export declare const ChatMessageRecordRequest: Schema.Struct<{
|
|
7
8
|
readonly channel: Schema.String;
|
|
@@ -141,11 +142,14 @@ export declare function changeChatMessage(store: ChatMessageStore): (request: Ht
|
|
|
141
142
|
export declare function readChatMessages(store: ChatMessageStore): (request: HttpServerRequest.HttpServerRequest) => Answer;
|
|
142
143
|
/**
|
|
143
144
|
* Deletes the messages the workspace keeps no longer, as its cron calls it with the project's cron
|
|
144
|
-
* secret. The ontology declares the window,
|
|
145
|
+
* secret, and the agent's decided drafts on the same schedule. The ontology declares the window,
|
|
146
|
+
* `chat.retentionDays`.
|
|
145
147
|
*/
|
|
146
148
|
export declare function purgeChatMessages(store: ChatMessageStore, options: {
|
|
147
149
|
readonly cronSecret: Redacted.Redacted<string> | undefined;
|
|
148
150
|
readonly retentionDays: number;
|
|
151
|
+
/** Deletes the drafts decided before the window, with their history's contents. */
|
|
152
|
+
readonly purgeDrafts?: AgentStore["purgeDrafts"];
|
|
149
153
|
}): (request: HttpServerRequest.HttpServerRequest) => Answer;
|
|
150
154
|
/** The routes' paths under the agent's path. */
|
|
151
155
|
export declare const CHAT_MESSAGE_PATHS: {
|
|
@@ -254,7 +254,8 @@ export function readChatMessages(store) {
|
|
|
254
254
|
}
|
|
255
255
|
/**
|
|
256
256
|
* Deletes the messages the workspace keeps no longer, as its cron calls it with the project's cron
|
|
257
|
-
* secret. The ontology declares the window,
|
|
257
|
+
* secret, and the agent's decided drafts on the same schedule. The ontology declares the window,
|
|
258
|
+
* `chat.retentionDays`.
|
|
258
259
|
*/
|
|
259
260
|
export function purgeChatMessages(store, options) {
|
|
260
261
|
return (request) => Effect.gen(function* () {
|
|
@@ -264,8 +265,18 @@ export function purgeChatMessages(store, options) {
|
|
|
264
265
|
return refused(requestId, 401, "cron_secret_required");
|
|
265
266
|
}
|
|
266
267
|
const purged = yield* store.purge({ retentionDays: options.retentionDays });
|
|
267
|
-
|
|
268
|
-
|
|
268
|
+
const drafts = options.purgeDrafts === undefined
|
|
269
|
+
? undefined
|
|
270
|
+
: yield* options.purgeDrafts({ retentionDays: options.retentionDays });
|
|
271
|
+
yield* Effect.logInfo("ontology.agent.chat_messages_purged").pipe(Effect.annotateLogs({
|
|
272
|
+
requestId,
|
|
273
|
+
retentionDays: options.retentionDays,
|
|
274
|
+
...purged,
|
|
275
|
+
...(drafts === undefined
|
|
276
|
+
? {}
|
|
277
|
+
: { draftsDeleted: drafts.deleted, draftsMore: drafts.more }),
|
|
278
|
+
}));
|
|
279
|
+
return json(drafts === undefined ? purged : { ...purged, drafts });
|
|
269
280
|
});
|
|
270
281
|
}
|
|
271
282
|
/** The routes' paths under the agent's path. */
|
|
@@ -158,6 +158,7 @@ export declare const ReviewRequest: Schema.Struct<{
|
|
|
158
158
|
readonly text: Schema.String;
|
|
159
159
|
readonly mode: Schema.Literals<readonly ["always", "whenUnsure"]>;
|
|
160
160
|
readonly confidence: Schema.NullOr<Schema.Number>;
|
|
161
|
+
readonly turn_id: Schema.optionalKey<Schema.String>;
|
|
161
162
|
}>;
|
|
162
163
|
export type ReviewRequest = typeof ReviewRequest.Type;
|
|
163
164
|
/**
|
|
@@ -232,6 +232,9 @@ export const ReviewRequest = Schema.Struct({
|
|
|
232
232
|
confidence: Schema.NullOr(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1))).annotate({
|
|
233
233
|
description: "The decision model's probability that staff would send it as written.",
|
|
234
234
|
}),
|
|
235
|
+
turn_id: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)).annotate({
|
|
236
|
+
description: "The agent's turn that wrote the reply.",
|
|
237
|
+
})),
|
|
235
238
|
});
|
|
236
239
|
/**
|
|
237
240
|
* `POST /api/ontology/agent/drafts/revision`: what became of a redraft a member asked for: the new
|
|
@@ -405,6 +405,7 @@ function holdReply(store) {
|
|
|
405
405
|
text: body.text,
|
|
406
406
|
mode: body.mode,
|
|
407
407
|
confidence: body.confidence,
|
|
408
|
+
...(body.turn_id === undefined ? {} : { turnId: body.turn_id }),
|
|
408
409
|
});
|
|
409
410
|
if (review === undefined) {
|
|
410
411
|
return toServerResponse(notFound(requestId, "The reply is for no active member."));
|
|
@@ -613,6 +614,7 @@ export function agentLayer(options) {
|
|
|
613
614
|
const purge = purgeChatMessages(messages, {
|
|
614
615
|
cronSecret: options.cronSecret,
|
|
615
616
|
retentionDays: options.chatRetentionDays ?? CHAT_RETENTION_DAYS.default,
|
|
617
|
+
...(store.purgeDrafts === undefined ? {} : { purgeDrafts: store.purgeDrafts }),
|
|
616
618
|
});
|
|
617
619
|
yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.record}`, asRuntime(recordChatMessage(messages)));
|
|
618
620
|
yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.change}`, asRuntime(changeChatMessage(messages)));
|
|
@@ -486,6 +486,9 @@ chats) {
|
|
|
486
486
|
principal: context.principal,
|
|
487
487
|
requestId: context.requestId,
|
|
488
488
|
}),
|
|
489
|
+
...(context.backend.agents?.draftsNewer === undefined
|
|
490
|
+
? {}
|
|
491
|
+
: { draftsNewer: draftsNewer(context, context.backend.agents.draftsNewer) }),
|
|
489
492
|
sendReview: reviewSender({
|
|
490
493
|
ontology,
|
|
491
494
|
connections,
|
|
@@ -691,3 +694,27 @@ chats) {
|
|
|
691
694
|
}
|
|
692
695
|
};
|
|
693
696
|
}
|
|
697
|
+
/**
|
|
698
|
+
* Whether the person wrote after each draft's turn, for the drafts the caller reads: one outside the
|
|
699
|
+
* records a scoped `agent_draft:read` covers answers `null`, as one that does not exist does.
|
|
700
|
+
*/
|
|
701
|
+
function draftsNewer(context, newer) {
|
|
702
|
+
return (drafts) => Effect.gen(function* () {
|
|
703
|
+
const scope = effectiveScope("agent_draft:read", context.principal);
|
|
704
|
+
const readable = scope === undefined
|
|
705
|
+
? drafts
|
|
706
|
+
: yield* Effect.filter(drafts, (id) => context.backend
|
|
707
|
+
.get({
|
|
708
|
+
entity: "agent_draft",
|
|
709
|
+
id,
|
|
710
|
+
reader: {
|
|
711
|
+
...context.principal,
|
|
712
|
+
permissions: ["agent_draft:read"],
|
|
713
|
+
scopes: [{ permission: "agent_draft:read", where: scope }],
|
|
714
|
+
},
|
|
715
|
+
})
|
|
716
|
+
.pipe(Effect.as(true), Effect.catch(() => Effect.succeed(false))));
|
|
717
|
+
const answered = new Map((yield* newer(readable)).map((entry) => [entry.draft, entry.newer]));
|
|
718
|
+
return drafts.map((draft) => ({ draft, newer: answered.get(draft) ?? null }));
|
|
719
|
+
});
|
|
720
|
+
}
|
|
@@ -38,12 +38,14 @@ export declare function reviewSender(input: {
|
|
|
38
38
|
readonly requestId: string;
|
|
39
39
|
}): (send: ReviewSendInput) => Effect.Effect<{
|
|
40
40
|
recipients?: EmailRecipients | undefined;
|
|
41
|
+
message?: string | undefined;
|
|
41
42
|
status: "sent" | "uncertain" | "failed";
|
|
42
43
|
text: string;
|
|
43
44
|
messageId: string | null;
|
|
44
45
|
duplicate: true;
|
|
45
46
|
} | {
|
|
46
47
|
recipients?: EmailRecipients | undefined;
|
|
48
|
+
message?: string | undefined;
|
|
47
49
|
status: "sent" | "uncertain" | "failed";
|
|
48
50
|
text: string;
|
|
49
51
|
messageId: string | null;
|
|
@@ -8,7 +8,7 @@ import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./i
|
|
|
8
8
|
import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
|
|
9
9
|
import { chatRetentionDaysOf } from "../../manifest.js";
|
|
10
10
|
import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
|
|
11
|
-
import {
|
|
11
|
+
import { storeDeliveryArchive } from "./store-delivery.js";
|
|
12
12
|
/**
|
|
13
13
|
* Whether a reply to mail goes to the people a review records it went to: its `to`, else its
|
|
14
14
|
* recipient, and its `cc`, whatever their order and case.
|
|
@@ -100,13 +100,15 @@ export function reviewSender(input) {
|
|
|
100
100
|
text,
|
|
101
101
|
messageId: typeof review.message_id === "string" ? review.message_id : null,
|
|
102
102
|
duplicate: true,
|
|
103
|
+
...(typeof review.message === "string" ? { message: review.message } : {}),
|
|
103
104
|
...(recipients === undefined ? {} : { recipients }),
|
|
104
105
|
};
|
|
105
106
|
}
|
|
106
107
|
return yield* new ActionRejected({
|
|
107
|
-
message: status === "rejected"
|
|
108
|
-
?
|
|
108
|
+
message: status === "rejected" || status === "dismissed"
|
|
109
|
+
? `The reply was ${status}; it is never sent.`
|
|
109
110
|
: "The reply was already approved; it is never sent again.",
|
|
111
|
+
refusal: "draft_decided",
|
|
110
112
|
});
|
|
111
113
|
}
|
|
112
114
|
// The channel the chat is on, by name. A review held before channels had names has none:
|
|
@@ -256,18 +258,14 @@ export function reviewSender(input) {
|
|
|
256
258
|
url: null,
|
|
257
259
|
at: new Date().toISOString(),
|
|
258
260
|
};
|
|
259
|
-
|
|
260
|
-
// already replaced the reply leaves nothing to approve, and none arriving later replaces it.
|
|
261
|
-
const keeps = yield* backend.agents?.cancelRevision?.({ review: send.review }) ??
|
|
262
|
-
Effect.succeed(true);
|
|
263
|
-
if (!keeps) {
|
|
264
|
-
return yield* new ActionRejected({
|
|
265
|
-
message: "The reply was redrafted meanwhile; approve the redraft instead.",
|
|
266
|
-
});
|
|
267
|
-
}
|
|
261
|
+
const store = backend.agents?.chatMessages;
|
|
268
262
|
// The review's claim and receipt live on the workspace chat store once it holds a message.
|
|
269
|
-
|
|
270
|
-
const
|
|
263
|
+
// @legacy agent.cloud-chat-archive Until then, the chat archive in Cloud holds them.
|
|
264
|
+
const onStore = store !== undefined && (yield* store.holds());
|
|
265
|
+
const archive = onStore
|
|
266
|
+
? storeDeliveryArchive(store, chatRetentionDaysOf(input.ontology.manifest))
|
|
267
|
+
: input.cloud;
|
|
268
|
+
const reservation = archive({
|
|
271
269
|
event,
|
|
272
270
|
delivery: { phase: "reserve", scope, key, fingerprint },
|
|
273
271
|
identityToken: input.identityToken,
|
|
@@ -278,6 +276,69 @@ export function reviewSender(input) {
|
|
|
278
276
|
"or to other people; it is never sent again."
|
|
279
277
|
: "The delivery could not be reserved, and nothing was sent. Approve again.",
|
|
280
278
|
})));
|
|
279
|
+
const reserveDraft = backend.agents?.reserveDraft;
|
|
280
|
+
let reserve;
|
|
281
|
+
if (onStore && reserveDraft !== undefined) {
|
|
282
|
+
// Under the draft's lock, in the reservation's transaction: the draft still waits, a
|
|
283
|
+
// redraft asked for is dropped, and with unlessNewer the person has not written since.
|
|
284
|
+
const reserved = yield* reserveDraft({
|
|
285
|
+
review: send.review,
|
|
286
|
+
principalId: principal.id,
|
|
287
|
+
unlessNewer: send.unlessNewer === true,
|
|
288
|
+
reserve: reservation,
|
|
289
|
+
claimOf: (receipt) => (receipt.claimed ? receipt.claimId : undefined),
|
|
290
|
+
});
|
|
291
|
+
switch (reserved.kind) {
|
|
292
|
+
case "reserved":
|
|
293
|
+
reserve = reserved.value;
|
|
294
|
+
break;
|
|
295
|
+
case "missing":
|
|
296
|
+
return yield* new ActionRejected({ message: "The draft does not exist." });
|
|
297
|
+
case "decided":
|
|
298
|
+
return yield* new ActionRejected({
|
|
299
|
+
message: `The reply was decided meanwhile (${reserved.status}); nothing was sent.`,
|
|
300
|
+
refusal: "draft_decided",
|
|
301
|
+
});
|
|
302
|
+
case "redrafted":
|
|
303
|
+
return yield* new ActionRejected({
|
|
304
|
+
message: "The reply was redrafted meanwhile; approve the redraft instead.",
|
|
305
|
+
});
|
|
306
|
+
case "newer":
|
|
307
|
+
return yield* new ActionRejected({
|
|
308
|
+
message: reserved.newer === true
|
|
309
|
+
? "The person wrote after the turn that wrote the reply; nothing was sent."
|
|
310
|
+
: "Whether the person wrote after the reply cannot be told; nothing was sent.",
|
|
311
|
+
refusal: reserved.newer === true ? "newer_message" : "basis_unknown",
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
// Without the chat store, whether the person wrote since cannot be told.
|
|
317
|
+
if (send.unlessNewer === true) {
|
|
318
|
+
return yield* new ActionRejected({
|
|
319
|
+
message: "Whether the person wrote after the reply cannot be told; nothing was sent.",
|
|
320
|
+
refusal: "basis_unknown",
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
// A redraft asked for is dropped before anything is sent, under the review's lock: one
|
|
324
|
+
// that already replaced the reply leaves nothing to approve, and none arriving later
|
|
325
|
+
// replaces it.
|
|
326
|
+
const keeps = yield* backend.agents?.cancelRevision?.({ review: send.review }) ??
|
|
327
|
+
Effect.succeed(true);
|
|
328
|
+
if (!keeps) {
|
|
329
|
+
return yield* new ActionRejected({
|
|
330
|
+
message: "The reply was redrafted meanwhile; approve the redraft instead.",
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
reserve = yield* reservation;
|
|
334
|
+
}
|
|
335
|
+
const message = onStore
|
|
336
|
+
? reserve.claimed
|
|
337
|
+
? (reserve.claimId ?? null)
|
|
338
|
+
: typeof review.message === "string"
|
|
339
|
+
? review.message
|
|
340
|
+
: null
|
|
341
|
+
: null;
|
|
281
342
|
if (!reserve.claimed) {
|
|
282
343
|
if (reserve.version !== 1 || !reserve.duplicate || reserve.claimId !== undefined) {
|
|
283
344
|
return yield* new ActionRejected({
|
|
@@ -289,6 +350,7 @@ export function reviewSender(input) {
|
|
|
289
350
|
text,
|
|
290
351
|
messageId: reserve.messageId,
|
|
291
352
|
duplicate: true,
|
|
353
|
+
...(message === null ? {} : { message }),
|
|
292
354
|
...(recipients === undefined ? {} : { recipients }),
|
|
293
355
|
};
|
|
294
356
|
}
|
|
@@ -349,6 +411,7 @@ export function reviewSender(input) {
|
|
|
349
411
|
text,
|
|
350
412
|
messageId: outcome.messageId,
|
|
351
413
|
duplicate: false,
|
|
414
|
+
...(message === null ? {} : { message }),
|
|
352
415
|
...(recipients === undefined ? {} : { recipients }),
|
|
353
416
|
};
|
|
354
417
|
});
|
|
@@ -718,11 +718,44 @@ export interface AgentStore {
|
|
|
718
718
|
readonly cancelRevision?: (input: {
|
|
719
719
|
readonly review: string;
|
|
720
720
|
}) => Effect.Effect<boolean>;
|
|
721
|
+
/**
|
|
722
|
+
* Reserves an approved draft's delivery under the draft's lock, in one transaction with
|
|
723
|
+
* `reserve`, the reservation on the chat store: the draft must still wait, a redraft asked for is
|
|
724
|
+
* dropped, and with `unlessNewer` the person must not have written after the draft's turn. Once
|
|
725
|
+
* `reserve` claims the delivery, the draft names its message, `claimOf` of what `reserve`
|
|
726
|
+
* answered, so that a rejection or a dismissal after it is refused. A draft whose delivery is
|
|
727
|
+
* reserved already passes to `reserve` unchecked, which answers its receipt. Absent on stores
|
|
728
|
+
* that predate it.
|
|
729
|
+
*/
|
|
730
|
+
readonly reserveDraft?: <A, E>(input: {
|
|
731
|
+
readonly review: string;
|
|
732
|
+
readonly principalId: string;
|
|
733
|
+
readonly unlessNewer: boolean;
|
|
734
|
+
readonly reserve: Effect.Effect<A, E>;
|
|
735
|
+
readonly claimOf: (reserved: A) => string | undefined;
|
|
736
|
+
}) => Effect.Effect<DraftReservation<A>, E>;
|
|
737
|
+
/** Whether the person wrote after each draft's turn; `null` where it cannot be told. */
|
|
738
|
+
readonly draftsNewer?: (drafts: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<{
|
|
739
|
+
readonly draft: string;
|
|
740
|
+
readonly newer: boolean | null;
|
|
741
|
+
}>>;
|
|
721
742
|
/** Records that the agent could not redraft a reply; false when it is no longer the redraft asked for. */
|
|
722
743
|
readonly failRevision?: (input: {
|
|
723
744
|
readonly review: string;
|
|
724
745
|
readonly revision: string;
|
|
725
746
|
}) => Effect.Effect<boolean>;
|
|
747
|
+
/**
|
|
748
|
+
* Deletes the drafts decided longer ago than the chat store keeps messages, `retentionDays` after
|
|
749
|
+
* they were held, in bounded batches, with their history's contents scrubbed; a draft still
|
|
750
|
+
* waiting is kept. Absent on stores that predate it.
|
|
751
|
+
*/
|
|
752
|
+
readonly purgeDrafts?: (input: {
|
|
753
|
+
readonly retentionDays: number;
|
|
754
|
+
}) => Effect.Effect<{
|
|
755
|
+
readonly deleted: number;
|
|
756
|
+
/** The last batch was full: older drafts may remain for the next run. */
|
|
757
|
+
readonly more: boolean;
|
|
758
|
+
}>;
|
|
726
759
|
/**
|
|
727
760
|
* The replies an agent session held for review, newest first: what became of each, for the
|
|
728
761
|
* session's next turn. Absent on stores that predate it.
|
|
@@ -733,6 +766,25 @@ export interface AgentStore {
|
|
|
733
766
|
/** The chats' messages, in `_chat_messages`. Absent on stores that predate the chat store. */
|
|
734
767
|
readonly chatMessages?: import("../runtime/chat-messages.js").ChatMessageStore;
|
|
735
768
|
}
|
|
769
|
+
/**
|
|
770
|
+
* What reserving an approved draft's delivery came to: `reserved` with what the reservation answered,
|
|
771
|
+
* or refused before anything was reserved: the draft is gone or `decided`, a redraft replaced it,
|
|
772
|
+
* or with `unlessNewer` the person wrote after its turn (`newer` true) or that cannot be told (null).
|
|
773
|
+
*/
|
|
774
|
+
export type DraftReservation<A> = {
|
|
775
|
+
readonly kind: "reserved";
|
|
776
|
+
readonly value: A;
|
|
777
|
+
} | {
|
|
778
|
+
readonly kind: "missing";
|
|
779
|
+
} | {
|
|
780
|
+
readonly kind: "decided";
|
|
781
|
+
readonly status: string;
|
|
782
|
+
} | {
|
|
783
|
+
readonly kind: "redrafted";
|
|
784
|
+
} | {
|
|
785
|
+
readonly kind: "newer";
|
|
786
|
+
readonly newer: true | null;
|
|
787
|
+
};
|
|
736
788
|
/** A reply the agent held for review, as `POST /api/ontology/agent/drafts` reports it. */
|
|
737
789
|
export interface HeldReplyInput {
|
|
738
790
|
readonly key: string;
|
|
@@ -759,6 +811,8 @@ export interface HeldReplyInput {
|
|
|
759
811
|
readonly text: string;
|
|
760
812
|
readonly mode: "always" | "whenUnsure";
|
|
761
813
|
readonly confidence: number | null;
|
|
814
|
+
/** The agent's turn that wrote the reply; absent from agents that predate it. */
|
|
815
|
+
readonly turnId?: string;
|
|
762
816
|
}
|
|
763
817
|
/** A reply the agent redrafted, as `POST /api/ontology/agent/drafts/revision` reports it. */
|
|
764
818
|
export interface RevisedReplyInput {
|
package/dist/service/schemas.js
CHANGED
|
@@ -614,7 +614,7 @@ export const ErrorSchemas = {
|
|
|
614
614
|
limit: Schema.optionalKey(LimitErrorWire),
|
|
615
615
|
// The idempotency key is spent on an operation that did not happen: retry with a new one.
|
|
616
616
|
key_consumed: Schema.optionalKey(Schema.Literal(true)),
|
|
617
|
-
// Why a
|
|
617
|
+
// Why a message or a draft was refused, such as outside_reply_window or newer_message.
|
|
618
618
|
refusal: Schema.optionalKey(Schema.String),
|
|
619
619
|
}),
|
|
620
620
|
rateLimited: errorBody("RateLimited", 429, ["rate_limited"]),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.161.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",
|