@segmentstream/ontology 0.180.0 → 0.181.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 +27 -0
- package/dist/review.d.ts +46 -0
- package/dist/review.js +47 -0
- package/dist/runtime/agents.js +28 -4
- package/dist/service/agent/protocol.d.ts +51 -0
- package/dist/service/agent/protocol.js +66 -1
- package/dist/service/agent/server.d.ts +8 -0
- package/dist/service/agent/server.js +166 -1
- package/dist/service/chat/archive.d.ts +8 -1
- package/dist/service/chat/delivery.js +3 -1
- package/dist/service/chat/providers/custom.js +2 -0
- package/dist/service/chat/providers/provider.d.ts +5 -0
- package/dist/service/chat/reply-proposal.d.ts +122 -0
- package/dist/service/chat/reply-proposal.js +385 -0
- package/dist/service/chat/review-delivery.d.ts +131 -24
- package/dist/service/chat/review-delivery.js +393 -296
- package/dist/service/chat/store-delivery.d.ts +27 -5
- package/dist/service/chat/store-delivery.js +45 -33
- package/dist/service/runtime-contract.d.ts +30 -0
- package/dist/service/service.js +12 -4
- package/dist/workspace-channel.d.ts +6 -0
- package/dist/workspace-channel.js +27 -0
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.181.0
|
|
4
|
+
|
|
5
|
+
The ontology service applies reply review. `POST /api/ontology/agent/replies` takes a reply the
|
|
6
|
+
agent's turn wrote on an email or workspace channel, with the agent's `review` as data (its modes
|
|
7
|
+
and thresholds, never its criteria) and the decision model's confidence, and decides with the roles
|
|
8
|
+
the person holds now: a reply the review lets go (`never`, or `whenUnsure` at or above
|
|
9
|
+
`minConfidence`) is sent through the agent's channel as an approved draft is, its delivery claimed
|
|
10
|
+
on the workspace chat store and recorded there as the agent's message with its session and turn;
|
|
11
|
+
any other reply, an unjudged one included, is held as a pending `agent_draft`. A proposal's key
|
|
12
|
+
decides once: it is never sent twice, and a reply once held or sent is never decided again, even
|
|
13
|
+
when proposals of it overlap, since holding it and reserving its first message take the key's lock
|
|
14
|
+
in one transaction; a replay answers what was done before the reply's files are read again. The
|
|
15
|
+
key is bound to the whole reply: another reply proposed under it is refused with
|
|
16
|
+
`409 proposal_conflict`, and nothing of it is sent or held. A
|
|
17
|
+
reply goes as long as its channel sends: one email up to 100,000 characters, or a workspace
|
|
18
|
+
channel's parts of at most its `limits.maxLength` and 20,000 characters each; a reply's files
|
|
19
|
+
follow its text in a message of their own with their captions, as the agent sends its own. A reply
|
|
20
|
+
its review holds that is longer than a draft holds is refused as `draft_too_long`, never truncated.
|
|
21
|
+
Proposals need the workspace chat store: the route answers 404 until it holds a message.
|
|
22
|
+
|
|
23
|
+
A workspace channel's message whose `send` answered no id, a proposed reply, an approved draft or
|
|
24
|
+
a chat post, is recorded `sent` on the chat store instead of staying pending.
|
|
25
|
+
|
|
26
|
+
`@segmentstream/ontology/review` exports the policy both SDKs apply: `reviewFor`, `reviewPasses`
|
|
27
|
+
and the `Review` and `ReviewSettings` types. `@segmentstream/ontology/workspace-channel` exports
|
|
28
|
+
`splitReply`. The drafts route stays for agents released before proposals.
|
|
29
|
+
|
|
3
30
|
## 0.180.0
|
|
4
31
|
|
|
5
32
|
`segmentstream__attachments_send` sends files in Telegram and Slack up to the providers' own
|
package/dist/review.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reply review's policy (`docs/agent.md`, "Reply review"): who sends the agent's replies, by the
|
|
3
|
+
* roles of the person a reply answers. The agent declares it in `review` of
|
|
4
|
+
* `agent/segmentstream.json`; the agent SDK validates it and judges replies, and the ontology
|
|
5
|
+
* service applies it with the roles the person holds when the reply is proposed. Both read it
|
|
6
|
+
* here, so a reply is reviewed by one rule wherever it is decided.
|
|
7
|
+
*
|
|
8
|
+
* - `never`: the reply is sent as written;
|
|
9
|
+
* - `always`: every reply waits for a member to approve, edit or reject it;
|
|
10
|
+
* - `whenUnsure`: the reply is sent when the decision model gives at least `minConfidence` that
|
|
11
|
+
* staff would send it as written, and held otherwise. What staff check a reply for, the
|
|
12
|
+
* criteria, stays with the agent: this policy is only the modes and thresholds.
|
|
13
|
+
*/
|
|
14
|
+
export declare const REVIEW_MODES: readonly ["never", "always", "whenUnsure"];
|
|
15
|
+
export type ReviewMode = (typeof REVIEW_MODES)[number];
|
|
16
|
+
/** The key of the review for everyone no role matches. */
|
|
17
|
+
export declare const DEFAULT_REVIEW = "default";
|
|
18
|
+
/** One review: a mode, and for `whenUnsure` the confidence a reply needs to be sent. */
|
|
19
|
+
export type Review = {
|
|
20
|
+
readonly mode: "never";
|
|
21
|
+
} | {
|
|
22
|
+
readonly mode: "always";
|
|
23
|
+
} | {
|
|
24
|
+
readonly mode: "whenUnsure";
|
|
25
|
+
/** The probability, above 0 and at most 1, that staff would send the reply as written. */
|
|
26
|
+
readonly minConfidence: number;
|
|
27
|
+
};
|
|
28
|
+
/** The review per role of the person a reply answers, and the review of everyone else. */
|
|
29
|
+
export interface ReviewSettings<Entry extends Review = Review> {
|
|
30
|
+
/** The first role the person holds wins, in the order written. */
|
|
31
|
+
readonly byRole: Readonly<Record<string, Entry>>;
|
|
32
|
+
/** Everyone no role matches, including a person with no roles. */
|
|
33
|
+
readonly default: Entry;
|
|
34
|
+
}
|
|
35
|
+
/** Without `review`: replies are sent as written. */
|
|
36
|
+
export declare const SEND_REPLIES: {
|
|
37
|
+
readonly mode: "never";
|
|
38
|
+
};
|
|
39
|
+
/** The review for a person with `roles`: the first `byRole` entry they hold, or the default. */
|
|
40
|
+
export declare function reviewFor<Entry extends Review>(settings: ReviewSettings<Entry> | undefined, roles: ReadonlyArray<string>): Entry | typeof SEND_REPLIES;
|
|
41
|
+
/**
|
|
42
|
+
* Whether a reply under `review` is sent as written: always under `never`, never under `always`,
|
|
43
|
+
* and under `whenUnsure` only with a `confidence` of at least `minConfidence`. A reply nobody
|
|
44
|
+
* judged, `null` or `undefined`, is held: a missing judgment never sends a reply unreviewed.
|
|
45
|
+
*/
|
|
46
|
+
export declare function reviewPasses(review: Review, confidence: number | null | undefined): boolean;
|
package/dist/review.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reply review's policy (`docs/agent.md`, "Reply review"): who sends the agent's replies, by the
|
|
3
|
+
* roles of the person a reply answers. The agent declares it in `review` of
|
|
4
|
+
* `agent/segmentstream.json`; the agent SDK validates it and judges replies, and the ontology
|
|
5
|
+
* service applies it with the roles the person holds when the reply is proposed. Both read it
|
|
6
|
+
* here, so a reply is reviewed by one rule wherever it is decided.
|
|
7
|
+
*
|
|
8
|
+
* - `never`: the reply is sent as written;
|
|
9
|
+
* - `always`: every reply waits for a member to approve, edit or reject it;
|
|
10
|
+
* - `whenUnsure`: the reply is sent when the decision model gives at least `minConfidence` that
|
|
11
|
+
* staff would send it as written, and held otherwise. What staff check a reply for, the
|
|
12
|
+
* criteria, stays with the agent: this policy is only the modes and thresholds.
|
|
13
|
+
*/
|
|
14
|
+
export const REVIEW_MODES = ["never", "always", "whenUnsure"];
|
|
15
|
+
/** The key of the review for everyone no role matches. */
|
|
16
|
+
export const DEFAULT_REVIEW = "default";
|
|
17
|
+
/** Without `review`: replies are sent as written. */
|
|
18
|
+
export const SEND_REPLIES = { mode: "never" };
|
|
19
|
+
/** The review for a person with `roles`: the first `byRole` entry they hold, or the default. */
|
|
20
|
+
export function reviewFor(settings, roles) {
|
|
21
|
+
if (settings === undefined) {
|
|
22
|
+
return SEND_REPLIES;
|
|
23
|
+
}
|
|
24
|
+
for (const [role, review] of Object.entries(settings.byRole)) {
|
|
25
|
+
if (roles.includes(role)) {
|
|
26
|
+
return review;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return settings.default;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Whether a reply under `review` is sent as written: always under `never`, never under `always`,
|
|
33
|
+
* and under `whenUnsure` only with a `confidence` of at least `minConfidence`. A reply nobody
|
|
34
|
+
* judged, `null` or `undefined`, is held: a missing judgment never sends a reply unreviewed.
|
|
35
|
+
*/
|
|
36
|
+
export function reviewPasses(review, confidence) {
|
|
37
|
+
switch (review.mode) {
|
|
38
|
+
case "never":
|
|
39
|
+
return true;
|
|
40
|
+
case "always":
|
|
41
|
+
return false;
|
|
42
|
+
case "whenUnsure":
|
|
43
|
+
return (typeof confidence === "number" &&
|
|
44
|
+
Number.isFinite(confidence) &&
|
|
45
|
+
confidence >= review.minConfidence);
|
|
46
|
+
}
|
|
47
|
+
}
|
package/dist/runtime/agents.js
CHANGED
|
@@ -156,6 +156,11 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
156
156
|
const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
|
|
157
157
|
const memberPrincipal = (userId) => resolveMemberById(ontology, userId).pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
158
158
|
const messages = sqlChatMessageStore(sql);
|
|
159
|
+
/**
|
|
160
|
+
* The lock a held reply's key takes until the transaction ends: reports of one reply, and a
|
|
161
|
+
* proposal's hold and its delivery's reservation, run one after the other.
|
|
162
|
+
*/
|
|
163
|
+
const lockDraftKey = (key) => rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${key}`]);
|
|
159
164
|
/** The newest message the turn took in the chat, as the chat store's place; null without one. */
|
|
160
165
|
const turnBasis = (channel, chatId, turnId) => messages
|
|
161
166
|
.turnBasis({ channel, chatId, turnId })
|
|
@@ -214,7 +219,7 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
214
219
|
yield* sql.unsafe(`SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true)`, [`${limits.statementTimeoutMs}ms`, `${limits.lockTimeoutMs}ms`]);
|
|
215
220
|
yield* beginReplicationWrite(sql);
|
|
216
221
|
// Reports of one reply run one after the other: the first creates it, the rest find it.
|
|
217
|
-
yield*
|
|
222
|
+
yield* lockDraftKey(key);
|
|
218
223
|
const edits = [];
|
|
219
224
|
const snapshots = new Map();
|
|
220
225
|
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
@@ -301,9 +306,11 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
301
306
|
? nullableText(resolved.previous.basis)
|
|
302
307
|
: input.requested !== undefined
|
|
303
308
|
? input.requested.basis
|
|
304
|
-
: input.
|
|
305
|
-
?
|
|
306
|
-
:
|
|
309
|
+
: input.basis !== undefined
|
|
310
|
+
? input.basis
|
|
311
|
+
: input.turnId === undefined
|
|
312
|
+
? null
|
|
313
|
+
: yield* turnBasis(input.channel, input.chatId, input.turnId),
|
|
307
314
|
draft: input.text,
|
|
308
315
|
files: (input.files ?? []).length === 0 ? null : input.files,
|
|
309
316
|
text: null,
|
|
@@ -1012,6 +1019,23 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
1012
1019
|
}));
|
|
1013
1020
|
}).pipe(Effect.orDie),
|
|
1014
1021
|
holdReply: (input) => hold(input.key, input.memberId, () => Effect.succeed({ kind: "reply", reply: input })).pipe(Effect.map((held) => (held === "discarded" ? undefined : held))),
|
|
1022
|
+
// Under the key's lock, after its draft was looked for: a delivery begun holds nothing.
|
|
1023
|
+
holdProposal: (input, delivered) => hold(input.key, input.memberId, () => delivered.pipe(Effect.map((sent) => sent ? { kind: "discarded" } : { kind: "reply", reply: input }))).pipe(Effect.map((held) => (held === "discarded" ? "delivered" : held))),
|
|
1024
|
+
reserveProposal: (input) => sql
|
|
1025
|
+
.withTransaction(Effect.gen(function* () {
|
|
1026
|
+
yield* lockDraftKey(input.key);
|
|
1027
|
+
const [found] = yield* makeOntologyRuntime(ontology, sql)
|
|
1028
|
+
.find({ entity: AgentDraft.name, options: { where: { key: input.key }, limit: 1 } })
|
|
1029
|
+
.pipe(Effect.orDie);
|
|
1030
|
+
if (found !== undefined) {
|
|
1031
|
+
return {
|
|
1032
|
+
kind: "held",
|
|
1033
|
+
review: { id: String(found.id), status: String(found.status), created: false },
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
return { kind: "reserved", value: yield* input.reserve };
|
|
1037
|
+
}))
|
|
1038
|
+
.pipe(Effect.catchTag("SqlError", Effect.die)),
|
|
1015
1039
|
holdRevision: (input) => hold(`revision:${input.revision}`, undefined, (runtime) => Effect.gen(function* () {
|
|
1016
1040
|
// The reply the redraft replaces, while it still waits for this redraft: a member who
|
|
1017
1041
|
// decided it, or asked for another redraft since, leaves this one nothing to replace.
|
|
@@ -167,6 +167,57 @@ export declare const ReviewRequest: Schema.Struct<{
|
|
|
167
167
|
}>>;
|
|
168
168
|
}>;
|
|
169
169
|
export type ReviewRequest = typeof ReviewRequest.Type;
|
|
170
|
+
/**
|
|
171
|
+
* `POST /api/ontology/agent/replies`: the reply a turn wrote, which the agent proposes rather than
|
|
172
|
+
* sends. The ontology applies the agent's `review` with the roles the person holds now: it sends a
|
|
173
|
+
* reply its review lets go through the chat's channel, as it sends an approved draft, and holds
|
|
174
|
+
* the rest as drafts, as `POST /api/ontology/agent/drafts` does. `key` names the reply, so a
|
|
175
|
+
* proposal repeated after a failure finds what became of it and never sends it twice.
|
|
176
|
+
*/
|
|
177
|
+
export declare const ReplyProposalRequest: Schema.Struct<{
|
|
178
|
+
readonly key: Schema.String;
|
|
179
|
+
readonly provider: Schema.Literals<readonly ["email", "custom"]>;
|
|
180
|
+
readonly channel: Schema.optionalKey<Schema.String>;
|
|
181
|
+
readonly chat_id: Schema.String;
|
|
182
|
+
readonly recipient: Schema.String;
|
|
183
|
+
readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
184
|
+
readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
185
|
+
readonly participants: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
186
|
+
readonly thread_id: Schema.String;
|
|
187
|
+
readonly reply_to: Schema.NullOr<Schema.String>;
|
|
188
|
+
readonly member_id: Schema.String;
|
|
189
|
+
readonly session_id: Schema.String;
|
|
190
|
+
readonly text: Schema.optionalKey<Schema.String>;
|
|
191
|
+
readonly caption: Schema.optionalKey<Schema.String>;
|
|
192
|
+
readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
193
|
+
readonly entity: Schema.String;
|
|
194
|
+
readonly id: Schema.String;
|
|
195
|
+
readonly property: Schema.optionalKey<Schema.String>;
|
|
196
|
+
}>>>;
|
|
197
|
+
readonly turn_id: Schema.String;
|
|
198
|
+
readonly review: Schema.Struct<{
|
|
199
|
+
readonly byRole: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.Struct<{
|
|
200
|
+
readonly mode: Schema.Literal<"never">;
|
|
201
|
+
}>, Schema.Struct<{
|
|
202
|
+
readonly mode: Schema.Literal<"always">;
|
|
203
|
+
}>, Schema.Struct<{
|
|
204
|
+
readonly mode: Schema.Literal<"whenUnsure">;
|
|
205
|
+
readonly minConfidence: Schema.Number;
|
|
206
|
+
}>]>>;
|
|
207
|
+
readonly default: Schema.Union<readonly [Schema.Struct<{
|
|
208
|
+
readonly mode: Schema.Literal<"never">;
|
|
209
|
+
}>, Schema.Struct<{
|
|
210
|
+
readonly mode: Schema.Literal<"always">;
|
|
211
|
+
}>, Schema.Struct<{
|
|
212
|
+
readonly mode: Schema.Literal<"whenUnsure">;
|
|
213
|
+
readonly minConfidence: Schema.Number;
|
|
214
|
+
}>]>;
|
|
215
|
+
}>;
|
|
216
|
+
readonly confidence: Schema.NullOr<Schema.Number>;
|
|
217
|
+
readonly basis: Schema.NullOr<Schema.String>;
|
|
218
|
+
readonly max_length: Schema.optionalKey<Schema.Int>;
|
|
219
|
+
}>;
|
|
220
|
+
export type ReplyProposalRequest = typeof ReplyProposalRequest.Type;
|
|
170
221
|
/**
|
|
171
222
|
* `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
|
|
172
223
|
* as the member it is for, checked as holding it would check them, without holding anything.
|
|
@@ -2,7 +2,7 @@ import { randomInt } from "node:crypto";
|
|
|
2
2
|
import { Schema } from "effect";
|
|
3
3
|
import { AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_NOTE_LIMIT, AGENT_DRAFT_PARTICIPANTS_LIMIT, } from "../../agent-draft.js";
|
|
4
4
|
import { ChatChannelName } from "../../chat-channel.js";
|
|
5
|
-
import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
|
|
5
|
+
import { EMAIL_MESSAGE_LIMIT, EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
|
|
6
6
|
import { EMAIL_PATTERN } from "../../property.js";
|
|
7
7
|
import { GUEST_USD_CEILINGS, MAX_GUEST_USAGE_REPORT_USD } from "../../runtime/agent-counters.js";
|
|
8
8
|
/** How long a member has to open the connect link, sign in and approve the pairing. */
|
|
@@ -260,6 +260,71 @@ export const ReviewRequest = Schema.Struct({
|
|
|
260
260
|
description: "A draft asked for with agent_chat.draft: who asked, their note, and the chat's place.",
|
|
261
261
|
}),
|
|
262
262
|
});
|
|
263
|
+
/** A `whenUnsure` review's threshold: above 0, at most 1. */
|
|
264
|
+
const MinConfidence = Schema.Number.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1)).annotate({ description: "The confidence a reply needs to be sent." });
|
|
265
|
+
/** One review of the agent's `review`, as data: its mode, and a `whenUnsure` review's threshold. */
|
|
266
|
+
const ProposedReview = Schema.Union([
|
|
267
|
+
Schema.Struct({ mode: Schema.Literal("never") }),
|
|
268
|
+
Schema.Struct({ mode: Schema.Literal("always") }),
|
|
269
|
+
Schema.Struct({ mode: Schema.Literal("whenUnsure"), minConfidence: MinConfidence }),
|
|
270
|
+
]);
|
|
271
|
+
/**
|
|
272
|
+
* `POST /api/ontology/agent/replies`: the reply a turn wrote, which the agent proposes rather than
|
|
273
|
+
* sends. The ontology applies the agent's `review` with the roles the person holds now: it sends a
|
|
274
|
+
* reply its review lets go through the chat's channel, as it sends an approved draft, and holds
|
|
275
|
+
* the rest as drafts, as `POST /api/ontology/agent/drafts` does. `key` names the reply, so a
|
|
276
|
+
* proposal repeated after a failure finds what became of it and never sends it twice.
|
|
277
|
+
*/
|
|
278
|
+
export const ReplyProposalRequest = Schema.Struct({
|
|
279
|
+
key: ReviewRequest.fields.key.annotate({
|
|
280
|
+
description: "The agent's key for the reply: its session and turn.",
|
|
281
|
+
}),
|
|
282
|
+
provider: Schema.Literals(["email", "custom"]).annotate({
|
|
283
|
+
description: "The kind of channel the chat is on: an email channel, or a channel the workspace defines.",
|
|
284
|
+
}),
|
|
285
|
+
channel: ReviewRequest.fields.channel,
|
|
286
|
+
chat_id: ReviewRequest.fields.chat_id,
|
|
287
|
+
recipient: ReviewRequest.fields.recipient,
|
|
288
|
+
to: ReviewRequest.fields.to,
|
|
289
|
+
cc: ReviewRequest.fields.cc,
|
|
290
|
+
participants: ReviewRequest.fields.participants,
|
|
291
|
+
thread_id: ReviewRequest.fields.thread_id,
|
|
292
|
+
reply_to: ReviewRequest.fields.reply_to,
|
|
293
|
+
member_id: ReviewRequest.fields.member_id,
|
|
294
|
+
session_id: ReviewRequest.fields.session_id,
|
|
295
|
+
text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(EMAIL_MESSAGE_LIMIT))).annotate({
|
|
296
|
+
description: "The reply as the agent wrote it, in Markdown; empty or absent only for a reply of files. " +
|
|
297
|
+
"As long as its channel sends: one email, or a workspace channel's parts. A reply its review " +
|
|
298
|
+
"holds is held only within a draft's length.",
|
|
299
|
+
}),
|
|
300
|
+
caption: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(20_000)).annotate({
|
|
301
|
+
description: "The captions the reply's files were attached with: sent as the text of its files' " +
|
|
302
|
+
"message, after the reply, and part of a held draft's text.",
|
|
303
|
+
})),
|
|
304
|
+
files: ReviewRequest.fields.files,
|
|
305
|
+
turn_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)).annotate({
|
|
306
|
+
description: "The agent's turn that wrote the reply.",
|
|
307
|
+
}),
|
|
308
|
+
review: Schema.Struct({
|
|
309
|
+
byRole: Schema.Record(Schema.String, ProposedReview),
|
|
310
|
+
default: ProposedReview,
|
|
311
|
+
}).annotate({
|
|
312
|
+
description: "The agent's review for the channel: per role of the person, the first they hold winning " +
|
|
313
|
+
"in the order written, and the default. Its criteria stay with the agent.",
|
|
314
|
+
}),
|
|
315
|
+
confidence: ReviewRequest.fields.confidence.annotate({
|
|
316
|
+
description: "The decision model's probability that staff would send the reply as written; null when " +
|
|
317
|
+
"the agent did not judge it.",
|
|
318
|
+
}),
|
|
319
|
+
basis: Schema.NullOr(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(128))).annotate({
|
|
320
|
+
description: "Where the chat stood when the turn read it, <time>~<id>; null when the agent does not " +
|
|
321
|
+
"know, and the ontology takes the newest message the turn took.",
|
|
322
|
+
}),
|
|
323
|
+
max_length: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(20_000)).annotate({
|
|
324
|
+
description: "A workspace channel's limits.maxLength: a longer reply is sent in parts of at most this " +
|
|
325
|
+
"many characters, as the agent sends its own.",
|
|
326
|
+
})),
|
|
327
|
+
});
|
|
263
328
|
/**
|
|
264
329
|
* `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
|
|
265
330
|
* as the member it is for, checked as holding it would check them, without holding anything.
|
|
@@ -11,10 +11,13 @@ import { type VisitorWebsites } from "./web-tokens.js";
|
|
|
11
11
|
import type { BotCheckVerifier } from "./bot-check.js";
|
|
12
12
|
import type { DeploymentObservation } from "../../deployment.js";
|
|
13
13
|
import { type OntologyManifest } from "../../manifest.js";
|
|
14
|
+
import type { ReplyProposals } from "../chat/reply-proposal.js";
|
|
14
15
|
import { GUEST_LINK_PATH, type EmailCodes } from "./guest-sign-up.js";
|
|
15
16
|
import type { ResolvedGuest } from "../../sign-in.js";
|
|
16
17
|
/** The agent's endpoints, under the ontology service's path. */
|
|
17
18
|
export declare const AGENT_PATH = "/api/ontology/agent";
|
|
19
|
+
/** Where the agent proposes a turn's reply, which the ontology sends or holds by its review. */
|
|
20
|
+
export declare const AGENT_REPLIES_PATH = "/api/ontology/agent/replies";
|
|
18
21
|
/** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
|
|
19
22
|
export declare const AGENT_TOKENS_PATH = "/api/ontology/agent/tokens";
|
|
20
23
|
export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
|
|
@@ -65,6 +68,11 @@ export interface AgentServerOptions {
|
|
|
65
68
|
readonly evalTokens?: DeploymentObservation;
|
|
66
69
|
/** The ontology, whose record files a held reply carries and whose channels send them. */
|
|
67
70
|
readonly manifest?: OntologyManifest;
|
|
71
|
+
/**
|
|
72
|
+
* Sends the replies the agent proposes that their review lets go, as approved drafts are sent,
|
|
73
|
+
* and holds the rest; without it, the service answers proposals 404, as one before them did.
|
|
74
|
+
*/
|
|
75
|
+
readonly replies?: ReplyProposals;
|
|
68
76
|
}
|
|
69
77
|
/**
|
|
70
78
|
* The routes that pair channel accounts with members for the app's own agent, and record the group
|
|
@@ -16,12 +16,13 @@ import { secretHash } from "../oauth/protocol.js";
|
|
|
16
16
|
import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
|
|
17
17
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
18
18
|
import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
19
|
-
import { AgentLimitsRequest, ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
19
|
+
import { AgentLimitsRequest, ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReplyProposalRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
20
20
|
import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
|
|
21
21
|
import { issueEvalToken } from "./eval-tokens.js";
|
|
22
22
|
import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
|
|
23
23
|
import { CHAT_RETENTION_DAYS } from "../../manifest.js";
|
|
24
24
|
import { snapshotDraftFiles } from "../chat/draft-files.js";
|
|
25
|
+
import { chatKind } from "../chat/providers/index.js";
|
|
25
26
|
import { parseChatCursor } from "../../runtime/chat-messages.js";
|
|
26
27
|
import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
|
|
27
28
|
import { identityToken } from "../operations.js";
|
|
@@ -35,6 +36,8 @@ const DRAFTS_PATH = `${AGENT_PATH}/drafts`;
|
|
|
35
36
|
// @legacy agent.review-runtime-paths
|
|
36
37
|
// The drafts' routes under their earlier name, which agent SDKs released before them call.
|
|
37
38
|
const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
|
|
39
|
+
/** Where the agent proposes a turn's reply, which the ontology sends or holds by its review. */
|
|
40
|
+
export const AGENT_REPLIES_PATH = `${AGENT_PATH}/replies`;
|
|
38
41
|
/** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
|
|
39
42
|
export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
|
|
40
43
|
export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
|
|
@@ -495,6 +498,167 @@ function holdReply(store, backend, manifest) {
|
|
|
495
498
|
return json({ id: review.id, status: review.status, created: review.created });
|
|
496
499
|
});
|
|
497
500
|
}
|
|
501
|
+
/**
|
|
502
|
+
* `POST /api/ontology/agent/replies` (runtime): the reply a turn wrote, which the agent proposes
|
|
503
|
+
* rather than sends. The ontology applies the agent's `review` with the roles the person holds now
|
|
504
|
+
* (`replies`): a reply it lets go is sent through the chat's channel as an approved draft is, and
|
|
505
|
+
* any other is held as the drafts route holds it. Each outcome is answered with the review applied;
|
|
506
|
+
* a delivery that failed, or may have, is an outcome like a sent one, and so is a reply its review
|
|
507
|
+
* holds that is longer than a draft holds (`failed`, `draft_too_long`). 404 when this service sends
|
|
508
|
+
* no proposed replies, or its chat store, where they are decided, holds no message yet, which the
|
|
509
|
+
* agent takes for an ontology that predates them; 409 `proposal_conflict` for another reply under
|
|
510
|
+
* a key that decided one; 422 when the person is no longer an active member, or a file is
|
|
511
|
+
* refused. A refused proposal sends and holds nothing.
|
|
512
|
+
*/
|
|
513
|
+
function proposeReply(store, backend, manifest, replies) {
|
|
514
|
+
return (request) => Effect.gen(function* () {
|
|
515
|
+
const requestId = yield* RequestId;
|
|
516
|
+
const decoded = Schema.decodeUnknownResult(ReplyProposalRequest)(yield* jsonBody(request), {
|
|
517
|
+
errors: "all",
|
|
518
|
+
onExcessProperty: "error",
|
|
519
|
+
});
|
|
520
|
+
if (Result.isFailure(decoded)) {
|
|
521
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
522
|
+
}
|
|
523
|
+
const messages = store.chatMessages;
|
|
524
|
+
if (replies === undefined ||
|
|
525
|
+
messages === undefined ||
|
|
526
|
+
store.holdProposal === undefined ||
|
|
527
|
+
store.reserveProposal === undefined) {
|
|
528
|
+
return toServerResponse(notFound(requestId, "This ontology service sends no proposed replies."));
|
|
529
|
+
}
|
|
530
|
+
const body = decoded.success;
|
|
531
|
+
const channel = body.channel ?? body.provider;
|
|
532
|
+
const refuse = (error, extra = {}, status = 422) => HttpServerResponse.jsonUnsafe({ error, ...extra, request_id: requestId }, { status, headers: NO_STORE });
|
|
533
|
+
// A channel named after a kind is that kind, and a workspace channel has a name of its own,
|
|
534
|
+
// of the kind the ontology declares it with, when it declares it.
|
|
535
|
+
if (body.channel !== undefined &&
|
|
536
|
+
isChatChannelKind(body.channel) &&
|
|
537
|
+
channel !== body.provider) {
|
|
538
|
+
return invalidBody(requestId, [
|
|
539
|
+
{ path: ["channel"], message: "A channel named after a kind is that kind." },
|
|
540
|
+
]);
|
|
541
|
+
}
|
|
542
|
+
if (body.provider === WORKSPACE_CHANNEL_KIND && channel === WORKSPACE_CHANNEL_KIND) {
|
|
543
|
+
return invalidBody(requestId, [
|
|
544
|
+
{ path: ["channel"], message: "A workspace channel's reply names its channel." },
|
|
545
|
+
]);
|
|
546
|
+
}
|
|
547
|
+
const declared = chatKind(manifest?.chat, channel);
|
|
548
|
+
if (declared !== undefined && declared !== body.provider) {
|
|
549
|
+
return invalidBody(requestId, [
|
|
550
|
+
{ path: ["provider"], message: `The ontology declares ${channel} as ${declared}.` },
|
|
551
|
+
]);
|
|
552
|
+
}
|
|
553
|
+
// Only a reply to mail names whom it goes to beside its recipient.
|
|
554
|
+
if (body.provider !== "email" && (body.to !== undefined || body.cc !== undefined)) {
|
|
555
|
+
return invalidBody(requestId, [
|
|
556
|
+
{ path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
|
|
557
|
+
]);
|
|
558
|
+
}
|
|
559
|
+
// Only a workspace channel's code sets the length its provider takes.
|
|
560
|
+
if (body.provider !== WORKSPACE_CHANNEL_KIND && body.max_length !== undefined) {
|
|
561
|
+
return invalidBody(requestId, [
|
|
562
|
+
{ path: ["max_length"], message: "Only a workspace channel's reply has it." },
|
|
563
|
+
]);
|
|
564
|
+
}
|
|
565
|
+
const text = body.text ?? "";
|
|
566
|
+
// A reply is its text, its files, or both; its files' captions go with its files.
|
|
567
|
+
if (text.trim() === "" && body.files === undefined) {
|
|
568
|
+
return invalidBody(requestId, [
|
|
569
|
+
{ path: ["text"], message: "A reply without files has text." },
|
|
570
|
+
]);
|
|
571
|
+
}
|
|
572
|
+
if (body.caption !== undefined && body.files === undefined) {
|
|
573
|
+
return invalidBody(requestId, [
|
|
574
|
+
{ path: ["caption"], message: "Only a reply with files has captions." },
|
|
575
|
+
]);
|
|
576
|
+
}
|
|
577
|
+
if (body.basis !== null && parseChatCursor(body.basis) === undefined) {
|
|
578
|
+
return invalidBody(requestId, [
|
|
579
|
+
{ path: ["basis"], message: "The chat's place is <time>~<id>." },
|
|
580
|
+
]);
|
|
581
|
+
}
|
|
582
|
+
// The review applies to the person as they are now: one no longer active is no one's.
|
|
583
|
+
const member = yield* store.member(body.member_id);
|
|
584
|
+
if (member === undefined) {
|
|
585
|
+
return refuse("member_inactive");
|
|
586
|
+
}
|
|
587
|
+
// @legacy agent.cloud-chat-archive A proposal is decided, and found again, on the workspace
|
|
588
|
+
// chat store: until it holds a message, the agent reviews the reply itself, as before.
|
|
589
|
+
if (!(yield* messages.holds())) {
|
|
590
|
+
return toServerResponse(notFound(requestId, "This ontology service decides replies once its chat store holds one."));
|
|
591
|
+
}
|
|
592
|
+
const answered = yield* replies({
|
|
593
|
+
backend,
|
|
594
|
+
identityToken: identityToken(request),
|
|
595
|
+
requestId,
|
|
596
|
+
})({
|
|
597
|
+
key: body.key,
|
|
598
|
+
provider: body.provider,
|
|
599
|
+
channel,
|
|
600
|
+
chatId: body.chat_id,
|
|
601
|
+
recipient: body.recipient,
|
|
602
|
+
...(body.to === undefined ? {} : { to: body.to.map((address) => address.toLowerCase()) }),
|
|
603
|
+
...(body.cc === undefined ? {} : { cc: body.cc.map((address) => address.toLowerCase()) }),
|
|
604
|
+
...(body.participants === undefined
|
|
605
|
+
? {}
|
|
606
|
+
: { participants: [...new Set(body.participants.map((id) => id.toLowerCase()))] }),
|
|
607
|
+
threadId: body.thread_id,
|
|
608
|
+
replyTo: body.reply_to,
|
|
609
|
+
memberId: body.member_id,
|
|
610
|
+
sessionId: body.session_id,
|
|
611
|
+
turnId: body.turn_id,
|
|
612
|
+
text,
|
|
613
|
+
...(body.caption === undefined ? {} : { caption: body.caption }),
|
|
614
|
+
files: body.files ?? [],
|
|
615
|
+
review: body.review,
|
|
616
|
+
confidence: body.confidence,
|
|
617
|
+
basis: body.basis,
|
|
618
|
+
...(body.max_length === undefined ? {} : { maxLength: body.max_length }),
|
|
619
|
+
}, member).pipe(Effect.result);
|
|
620
|
+
if (Result.isFailure(answered)) {
|
|
621
|
+
const failure = answered.failure;
|
|
622
|
+
yield* Effect.logWarning("ontology.agent.reply_refused").pipe(Effect.annotateLogs({ requestId, channel, reason: failure.message }));
|
|
623
|
+
// Another reply under a key that decided one is a conflict, as a changed approval is.
|
|
624
|
+
return failure._tag === "ActionRejected"
|
|
625
|
+
? refuse(failure.refusal ?? "reply_refused", { message: failure.message }, failure.refusal === "proposal_conflict" ? 409 : 422)
|
|
626
|
+
: toServerResponse(forbidden(requestId, failure.message));
|
|
627
|
+
}
|
|
628
|
+
const answer = answered.success;
|
|
629
|
+
if (answer === undefined) {
|
|
630
|
+
return refuse("member_inactive");
|
|
631
|
+
}
|
|
632
|
+
if ("refused" in answer) {
|
|
633
|
+
yield* Effect.logInfo("ontology.agent.reply_files_refused").pipe(Effect.annotateLogs({ requestId, channel, refusal: answer.refused }));
|
|
634
|
+
return refuse(answer.refused, answer.index === undefined ? {} : { index: answer.index });
|
|
635
|
+
}
|
|
636
|
+
const review = {
|
|
637
|
+
mode: answer.review.mode,
|
|
638
|
+
...(answer.review.mode === "whenUnsure"
|
|
639
|
+
? { min_confidence: answer.review.minConfidence }
|
|
640
|
+
: {}),
|
|
641
|
+
};
|
|
642
|
+
yield* Effect.logInfo("ontology.agent.reply_proposed").pipe(Effect.annotateLogs({
|
|
643
|
+
requestId,
|
|
644
|
+
provider: body.provider,
|
|
645
|
+
channel,
|
|
646
|
+
outcome: answer.outcome,
|
|
647
|
+
mode: answer.review.mode,
|
|
648
|
+
duplicate: answer.duplicate,
|
|
649
|
+
}));
|
|
650
|
+
return answer.outcome === "held"
|
|
651
|
+
? json({ outcome: "held", draft: answer.draft, duplicate: answer.duplicate, review })
|
|
652
|
+
: json({
|
|
653
|
+
outcome: answer.outcome,
|
|
654
|
+
message_id: answer.messageId,
|
|
655
|
+
duplicate: answer.duplicate,
|
|
656
|
+
...(answer.refusal === undefined ? {} : { refusal: answer.refusal }),
|
|
657
|
+
...(answer.files === undefined ? {} : { files: answer.files }),
|
|
658
|
+
review,
|
|
659
|
+
});
|
|
660
|
+
});
|
|
661
|
+
}
|
|
498
662
|
/**
|
|
499
663
|
* `POST /api/ontology/agent/drafts/files` (runtime): the files a reply would carry, read as the
|
|
500
664
|
* member it is for and checked against its channel as holding the reply checks them, without
|
|
@@ -960,6 +1124,7 @@ export function agentLayer(options) {
|
|
|
960
1124
|
yield* router.add("POST", `${path}/revision`, asRuntime(revision(store)));
|
|
961
1125
|
}
|
|
962
1126
|
yield* router.add("POST", `${DRAFTS_PATH}/files`, asRuntime(checkDraftFiles(store, backend, options.manifest)));
|
|
1127
|
+
yield* router.add("POST", AGENT_REPLIES_PATH, asRuntime(proposeReply(store, backend, options.manifest, options.replies)));
|
|
963
1128
|
yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
|
|
964
1129
|
if (store.web !== undefined && backend.oauth !== undefined) {
|
|
965
1130
|
yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
|
|
@@ -27,7 +27,8 @@ export interface DeliveryEvent {
|
|
|
27
27
|
readonly messageId: string | null;
|
|
28
28
|
readonly replyToMessageId: string | null;
|
|
29
29
|
readonly sessionId: string | null;
|
|
30
|
-
|
|
30
|
+
/** The agent's turn that wrote the message: a reply it proposed, which the ontology sent. */
|
|
31
|
+
readonly turnId: string | null;
|
|
31
32
|
readonly text: string;
|
|
32
33
|
readonly decision: null;
|
|
33
34
|
/** A refused delivery's receipt: why the provider refused it, such as outside_reply_window. */
|
|
@@ -46,6 +47,12 @@ export interface DeliveryEvent {
|
|
|
46
47
|
readonly requestedBy: ChatRequester;
|
|
47
48
|
readonly url: string | null;
|
|
48
49
|
readonly at: string;
|
|
50
|
+
/**
|
|
51
|
+
* The whole reply a proposal's first message belongs to, as a digest the workspace chat store
|
|
52
|
+
* keeps with the message's delivery, so another reply proposed under its key is refused. Only
|
|
53
|
+
* the store takes it: a delivery in the archive in Cloud never has one.
|
|
54
|
+
*/
|
|
55
|
+
readonly binding?: string;
|
|
49
56
|
}
|
|
50
57
|
export interface DeliveryCommand {
|
|
51
58
|
readonly phase: "reserve" | "receipt";
|
|
@@ -592,7 +592,9 @@ chats) {
|
|
|
592
592
|
});
|
|
593
593
|
const key = deliveryKeyDigest(input.idempotencyKey);
|
|
594
594
|
// The key's claim and receipt live on the workspace chat store once it holds a message.
|
|
595
|
-
const archive = yield* deliveryArchiveOf(context.backend, cloud, retentionDays
|
|
595
|
+
const archive = yield* deliveryArchiveOf(context.backend, cloud, retentionDays, {
|
|
596
|
+
unnamedSends: provider.unnamedSends === true,
|
|
597
|
+
});
|
|
596
598
|
const unreserved = (cause) => new ActionRejected({
|
|
597
599
|
cause,
|
|
598
600
|
message: cause.diagnostic === "chat_archive_conflict"
|
|
@@ -129,4 +129,6 @@ export const customProvider = {
|
|
|
129
129
|
// bound; the channel refuses those past its own `limits.fileBytes`, sending nothing.
|
|
130
130
|
files: { count: AGENT_DRAFT_FILES_LIMIT, bytes: WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES },
|
|
131
131
|
send: sendThroughAgent,
|
|
132
|
+
// The channel's `send` may take a message without the provider's id of it.
|
|
133
|
+
unnamedSends: true,
|
|
132
134
|
};
|
|
@@ -187,6 +187,11 @@ export interface ChatProvider {
|
|
|
187
187
|
}>) => ChatFilesRefusal | undefined;
|
|
188
188
|
/** One attempt: `sent` only when the provider's answer proves it. */
|
|
189
189
|
readonly send: (input: ChatSend) => Effect.Effect<ProviderOutcome>;
|
|
190
|
+
/**
|
|
191
|
+
* Whether a message the provider took may have no id of it, as a workspace channel's `send` may
|
|
192
|
+
* answer none: its `sent` receipt then names none. Omitted, a `sent` message has its id.
|
|
193
|
+
*/
|
|
194
|
+
readonly unnamedSends?: true;
|
|
190
195
|
/**
|
|
191
196
|
* Whom a reply in a thread several people share goes to, read from the provider before anything
|
|
192
197
|
* is reserved or sent, for a provider whose chat can be such a thread, such as a mailbox's: the
|