@segmentstream/ontology 0.179.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/channel-files.d.ts +40 -0
  3. package/dist/channel-files.js +10 -0
  4. package/dist/review.d.ts +46 -0
  5. package/dist/review.js +47 -0
  6. package/dist/runtime/agents.js +28 -4
  7. package/dist/service/agent/protocol.d.ts +51 -0
  8. package/dist/service/agent/protocol.js +66 -1
  9. package/dist/service/agent/server.d.ts +8 -0
  10. package/dist/service/agent/server.js +166 -1
  11. package/dist/service/chat/archive.d.ts +8 -1
  12. package/dist/service/chat/delivery.js +3 -1
  13. package/dist/service/chat/providers/custom.js +2 -0
  14. package/dist/service/chat/providers/email.js +2 -2
  15. package/dist/service/chat/providers/provider.d.ts +15 -2
  16. package/dist/service/chat/providers/provider.js +18 -1
  17. package/dist/service/chat/reply-proposal.d.ts +122 -0
  18. package/dist/service/chat/reply-proposal.js +385 -0
  19. package/dist/service/chat/review-delivery.d.ts +131 -24
  20. package/dist/service/chat/review-delivery.js +393 -296
  21. package/dist/service/chat/store-delivery.d.ts +27 -5
  22. package/dist/service/chat/store-delivery.js +45 -33
  23. package/dist/service/runtime-contract.d.ts +30 -0
  24. package/dist/service/service.js +12 -4
  25. package/dist/slack-files.d.ts +23 -5
  26. package/dist/slack-files.js +108 -16
  27. package/dist/slack.d.ts +3 -3
  28. package/dist/slack.js +2 -2
  29. package/dist/telegram-files.d.ts +27 -7
  30. package/dist/telegram-files.js +111 -31
  31. package/dist/telegram.d.ts +3 -3
  32. package/dist/telegram.js +2 -2
  33. package/dist/workspace-channel.d.ts +6 -0
  34. package/dist/workspace-channel.js +27 -0
  35. package/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,57 @@
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
+
30
+ ## 0.180.0
31
+
32
+ `segmentstream__attachments_send` sends files in Telegram and Slack up to the providers' own
33
+ limits, not the connection proxy's 2 MiB request body.
34
+
35
+ - **Telegram.** Photos go up to 10 MB and other files up to 50 MB, Telegram's limits for a bot's
36
+ uploads. A file of up to 1,984 KiB is sent in its request's body and may share an album, as
37
+ before. A larger one goes alone in its message: the connection proxy reads it from the
38
+ workspace's file storage and sends it inside the multipart form the agent builds around it, so
39
+ its bytes never pass through the agent.
40
+ - **Slack.** A file goes up to Slack's 1 GB. Its bytes stream from the workspace's file storage
41
+ straight to the upload address `files.getUploadURLExternal` answers, which needs no credential,
42
+ without passing through the connection proxy; each file must reach Slack within two minutes.
43
+ - Files a member sends to the agent are still stored up to 20 MB in every channel. In a chat whose
44
+ replies are reviewed, files still go with the reply at most 2 MiB each in Telegram and Slack,
45
+ since approval may send the reply through the ontology.
46
+
47
+ The ontology SDK's channel senders take the files this needs: `sendTelegramFiles` and
48
+ `sendSlackFiles` accept a `ChannelStoredFile` (`{ filename, contentType, size, read() }`), which
49
+ Telegram's sender sends as a `ChannelCall` with a `file` (a signed read with `prefix` and `suffix`
50
+ bytes around it) and Slack's uploads with the new `fetch` option. `telegramFileRefusal` takes
51
+ `{ stored: true }` and `slackFileRefusal` `{ direct: true }` to check a file against the
52
+ provider's limit alone. `TELEGRAM_INLINE_FILE_BYTES`, `SLACK_UPLOAD_BYTES` and
53
+ `CHANNEL_FILE_FRAME_BYTES` name the bounds. Without these options both senders behave as before.
54
+
3
55
  ## 0.179.0
4
56
 
5
57
  Opened groups can use a workspace-authored response handler and one explicitly granted ontology action. The action acts for a sender scoped to that group.
@@ -12,6 +12,30 @@ export interface ChannelCall {
12
12
  readonly path: string;
13
13
  readonly headers: ReadonlyArray<readonly [string, string]>;
14
14
  readonly body: Uint8Array;
15
+ /**
16
+ * A stored file the connection reads from the workspace's file storage and sends as the body,
17
+ * in place of `body`, which is then empty: only a transport that reads stored files sends it.
18
+ */
19
+ readonly file?: ChannelCallFile;
20
+ }
21
+ /** The most bytes a call sends before, and the most after, the stored file it carries. */
22
+ export declare const CHANNEL_FILE_FRAME_BYTES: number;
23
+ /**
24
+ * The body of a call that carries a stored file: `prefix`, the file's bytes from `start` to `end`
25
+ * inclusive, read by the connection by the file's signed read, then `suffix`, such as a multipart
26
+ * form's fields and its closing boundary around the file's part. Each of `prefix` and `suffix` is
27
+ * at most {@link CHANNEL_FILE_FRAME_BYTES}.
28
+ */
29
+ export interface ChannelCallFile extends ChannelFileRead {
30
+ readonly start: number;
31
+ readonly end: number;
32
+ readonly prefix?: Uint8Array;
33
+ readonly suffix?: Uint8Array;
34
+ }
35
+ /** A signed read of a file in the workspace's file storage, valid for about a minute. */
36
+ export interface ChannelFileRead {
37
+ readonly url: string;
38
+ readonly headers: ReadonlyArray<readonly [string, string]>;
15
39
  }
16
40
  /** The provider's answer, as the connection relayed it. */
17
41
  export interface ChannelReply {
@@ -30,6 +54,22 @@ export interface ChannelFile {
30
54
  readonly contentType: string;
31
55
  readonly bytes: Uint8Array;
32
56
  }
57
+ /**
58
+ * A file the channel sends without its bytes passing through the sender: they stay in the
59
+ * workspace's file storage, which the provider's request reads by a signed read asked for just
60
+ * before it. A file too large for a request's own body goes this way.
61
+ */
62
+ export interface ChannelStoredFile {
63
+ readonly filename: string;
64
+ readonly contentType: string;
65
+ readonly size: number;
66
+ /** A fresh signed read of the file; when it rejects, the file is not sent. */
67
+ readonly read: () => Promise<ChannelFileRead>;
68
+ }
69
+ /** Whether a file is sent by its signed read rather than its bytes. */
70
+ export declare function isStoredFile(file: ChannelFile | ChannelStoredFile): file is ChannelStoredFile;
71
+ /** How many bytes a file has. */
72
+ export declare function fileSize(file: ChannelFile | ChannelStoredFile): number;
33
73
  /**
34
74
  * What became of one visible message, or one step before any, a sender attempted:
35
75
  * - `sent`: the provider's answer proves it;
@@ -5,6 +5,16 @@
5
5
  * agent's connection proxy, or the ontology's connection transport. The sender never retries, and
6
6
  * it reports per part what the provider's answer proves.
7
7
  */
8
+ /** The most bytes a call sends before, and the most after, the stored file it carries. */
9
+ export const CHANNEL_FILE_FRAME_BYTES = 64 * 1024;
10
+ /** Whether a file is sent by its signed read rather than its bytes. */
11
+ export function isStoredFile(file) {
12
+ return !("bytes" in file);
13
+ }
14
+ /** How many bytes a file has. */
15
+ export function fileSize(file) {
16
+ return isStoredFile(file) ? file.size : file.bytes.byteLength;
17
+ }
8
18
  /** At most this many characters of an answer that is not JSON are kept on an error. */
9
19
  const ANSWER_TEXT_LIMIT = 2000;
10
20
  /**
@@ -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
+ }
@@ -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* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${key}`]);
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.turnId === undefined
305
- ? null
306
- : yield* turnBasis(input.channel, input.chatId, input.turnId),
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))));