@segmentstream/ontology 0.97.0 → 0.98.1

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.
@@ -94,6 +94,39 @@ export const ChatSeenRequest = Schema.Struct({
94
94
  description: "The chat's id before it became a supergroup: its record moves to externalId.",
95
95
  })),
96
96
  });
97
+ /**
98
+ * `POST /api/ontology/agent/reviews`: a reply the agent held for a member to review, for the member
99
+ * it answers. `key` names the reply, so a report repeated after a failure finds its review.
100
+ */
101
+ export const ReviewRequest = Schema.Struct({
102
+ key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
103
+ description: "The agent's key for the reply: its session and content part.",
104
+ }),
105
+ provider: Provider,
106
+ chat_id: ChatId.annotate({ description: "The conversation's id on the channel." }),
107
+ recipient: ChatId.annotate({
108
+ description: "Whom the provider sends the reply to: the chat's id, or the person's number.",
109
+ }),
110
+ thread_id: Schema.String.check(Schema.isMaxLength(MAX_EXTERNAL_ID_LENGTH)).annotate({
111
+ description: "The conversation's thread or topic; empty without one.",
112
+ }),
113
+ reply_to: Schema.NullOr(ChatId).annotate({
114
+ description: "The member's message the reply answers, when the channel replies to one.",
115
+ }),
116
+ member_id: Schema.String.annotate({ description: "The user id of the member the reply is for." }),
117
+ session_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
118
+ description: "The agent's session that wrote the reply.",
119
+ }),
120
+ text: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(20_000)).annotate({
121
+ description: "The reply as the agent wrote it, in Markdown.",
122
+ }),
123
+ mode: Schema.Literals(["always", "whenUnsure"]).annotate({
124
+ description: "Why the reply was held: every reply is reviewed, or the model was unsure.",
125
+ }),
126
+ confidence: Schema.NullOr(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1))).annotate({
127
+ description: "The decision model's probability that staff would send it as written.",
128
+ }),
129
+ });
97
130
  /** An identity on the wire, as the member's connect page and settings show it. */
98
131
  export function identityForWire(identity) {
99
132
  return {
@@ -12,12 +12,13 @@ import { secretHash } from "../oauth/protocol.js";
12
12
  import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
13
13
  import { OntologyBackend } from "../runtime-contract.js";
14
14
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
15
- import { ChatSeenRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
15
+ import { ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
16
16
  /** The agent's endpoints, under the ontology service's path. */
17
17
  export const AGENT_PATH = `${BASE_PATH}/agent`;
18
18
  const PAIRINGS_PATH = `${AGENT_PATH}/pairings`;
19
19
  const IDENTITIES_PATH = `${AGENT_PATH}/identities`;
20
20
  const CHATS_SEEN_PATH = `${AGENT_PATH}/chats/seen`;
21
+ const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
21
22
  /**
22
23
  * Pairings one client address may start per minute; each one is a row in the database. The agent's
23
24
  * functions share a few egress addresses, so the limit leaves room for a busy channel.
@@ -270,6 +271,51 @@ function seeChat(store) {
270
271
  return json(chat);
271
272
  });
272
273
  }
274
+ /**
275
+ * `POST /api/ontology/agent/reviews` (runtime): the agent held a reply for review. It becomes a
276
+ * pending `agent_review` for the member it answers, once per key; 404 when that member is not an
277
+ * active member, so the reply is neither sent nor held.
278
+ */
279
+ function holdReply(store) {
280
+ return (request) => Effect.gen(function* () {
281
+ const requestId = yield* RequestId;
282
+ const decoded = Schema.decodeUnknownResult(ReviewRequest)(yield* jsonBody(request), {
283
+ errors: "all",
284
+ onExcessProperty: "error",
285
+ });
286
+ if (Result.isFailure(decoded)) {
287
+ return invalidBody(requestId, schemaIssues(decoded.failure));
288
+ }
289
+ if (store.holdReply === undefined) {
290
+ return toServerResponse(notFound(requestId, "This ontology service holds no replies."));
291
+ }
292
+ const body = decoded.success;
293
+ const review = yield* store.holdReply({
294
+ key: body.key,
295
+ provider: body.provider,
296
+ chatId: body.chat_id,
297
+ recipient: body.recipient,
298
+ threadId: body.thread_id,
299
+ replyTo: body.reply_to,
300
+ memberId: body.member_id,
301
+ sessionId: body.session_id,
302
+ text: body.text,
303
+ mode: body.mode,
304
+ confidence: body.confidence,
305
+ });
306
+ if (review === undefined) {
307
+ return toServerResponse(notFound(requestId, "The reply is for no active member."));
308
+ }
309
+ yield* Effect.logInfo("ontology.agent.reply_held").pipe(Effect.annotateLogs({
310
+ requestId,
311
+ provider: body.provider,
312
+ reviewId: review.id,
313
+ created: review.created,
314
+ mode: body.mode,
315
+ }));
316
+ return json({ id: review.id, status: review.status, created: review.created });
317
+ });
318
+ }
273
319
  /** `GET /api/ontology/agent/identities` (member): the member's own live identities. */
274
320
  function listIdentities(store, member) {
275
321
  return Effect.gen(function* () {
@@ -380,6 +426,7 @@ export function agentLayer(options) {
380
426
  })));
381
427
  }
382
428
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
429
+ yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
383
430
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
384
431
  }));
385
432
  }
@@ -7,7 +7,8 @@ export interface DeliveryEvent {
7
7
  readonly provider: string;
8
8
  readonly chatId: string;
9
9
  readonly chatType: "group" | "private";
10
- readonly threadId: null;
10
+ /** A forum topic or thread; a chat post has none. */
11
+ readonly threadId: string | null;
11
12
  readonly participantIds: ReadonlyArray<string>;
12
13
  readonly senderId: string;
13
14
  readonly senderName: string;
@@ -9,6 +9,7 @@ import { deliveryRequester } from "./attribution.js";
9
9
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
10
10
  import { chatConnection, chatProvider, listedChatProviders } from "./providers/index.js";
11
11
  import { chatResolver } from "./resolve.js";
12
+ import { reviewSender } from "./review-delivery.js";
12
13
  /** The channels a runtime source can name, which a verified pairing's provider is one of. */
13
14
  const CHANNEL_PROVIDERS = new Set(["telegram", "slack", "whatsapp"]);
14
15
  /**
@@ -120,6 +121,16 @@ export function makeChatDelivery(ontology, connections, archive, previews = {})
120
121
  error: describeChatError(cause, (text) => context.identityToken ? text.split(context.identityToken).join("[redacted]") : text),
121
122
  }));
122
123
  return {
124
+ sendReview: reviewSender({
125
+ ontology,
126
+ connections,
127
+ archive,
128
+ previews: destinationPreviews,
129
+ backend: context.backend,
130
+ principal: context.principal,
131
+ identityToken: context.identityToken,
132
+ requestId: context.requestId,
133
+ }),
123
134
  preview: (input) => check(input, false).pipe(Effect.map(({ preview }) => preview)),
124
135
  validate: (input) => check(input).pipe(Effect.asVoid),
125
136
  post: (input) => Effect.gen(function* () {
@@ -68,7 +68,7 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
68
68
  readonly live_period?: number | undefined;
69
69
  } | undefined;
70
70
  } | {
71
- readonly kind: "group" | "private";
71
+ readonly kind: "private" | "group";
72
72
  readonly provider: "whatsapp" | "slack";
73
73
  readonly chat_id: string;
74
74
  readonly thread_id: string;
@@ -120,7 +120,7 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
120
120
  readonly live_period?: number | undefined;
121
121
  } | undefined;
122
122
  } | {
123
- readonly kind: "group" | "private";
123
+ readonly kind: "private" | "group";
124
124
  readonly provider: "whatsapp" | "slack";
125
125
  readonly chat_id: string;
126
126
  readonly thread_id: string;
@@ -23,6 +23,8 @@ export interface ChatSend {
23
23
  readonly finalText: string;
24
24
  readonly plainText: string;
25
25
  readonly replyTo: string | null;
26
+ /** The forum topic of a Telegram group to send in; others ignore it. */
27
+ readonly threadId?: string | null;
26
28
  /** Telegram's link preview settings for its destination connection; others ignore them. */
27
29
  readonly previews?: TelegramPreviewContext;
28
30
  }
@@ -86,7 +86,7 @@ export const slackProvider = {
86
86
  isReplyId: (replyTo) => SLACK_TS.test(replyTo),
87
87
  render: (markdown, attribution, separator) => ({
88
88
  finalText: renderSlack(markdown, attribution, separator),
89
- plainText: `${markdown}${separator}${attribution}`,
89
+ plainText: attribution === "" ? markdown : `${markdown}${separator}${attribution}`,
90
90
  }),
91
91
  payload: (finalText) => ({ markdown_text: finalText }),
92
92
  send: sendSlack,
@@ -4,7 +4,10 @@ import type { ConnectionTransport } from "../../../connection.js";
4
4
  import type { Destination } from "../resolve.js";
5
5
  import { type ChatProvider, type ProviderOutcome } from "./provider.js";
6
6
  export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
7
- /** Render source independently so user Markdown cannot open an entity around the footer. */
7
+ /**
8
+ * Render source independently so user Markdown cannot open an entity around the footer. Without an
9
+ * attribution, as for a reply the agent sends after a member approved it, there is no footer.
10
+ */
8
11
  export declare function renderTelegram(markdown: string, attribution: string, separator?: string): string;
9
12
  interface TelegramSend {
10
13
  readonly transport: ConnectionTransport["Service"];
@@ -16,6 +19,8 @@ interface TelegramSend {
16
19
  readonly finalText: string;
17
20
  readonly plainText: string;
18
21
  readonly replyTo: string | null;
22
+ /** The forum topic to send in, for a group with topics. */
23
+ readonly threadId?: string | null;
19
24
  readonly link_preview_options?: Readonly<Record<string, unknown>>;
20
25
  readonly disable_web_page_preview?: boolean;
21
26
  }
@@ -4,9 +4,14 @@ import { Effect } from "effect";
4
4
  import { record, transportFailure } from "./provider.js";
5
5
  export const TELEGRAM_MESSAGE_LIMIT = 4096;
6
6
  const converter = new TelegramFormatConverter();
7
- /** Render source independently so user Markdown cannot open an entity around the footer. */
7
+ /**
8
+ * Render source independently so user Markdown cannot open an entity around the footer. Without an
9
+ * attribution, as for a reply the agent sends after a member approved it, there is no footer.
10
+ */
8
11
  export function renderTelegram(markdown, attribution, separator = "\n\n") {
9
- return `${converter.fromMarkdown(markdown)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_`;
12
+ return attribution === ""
13
+ ? converter.fromMarkdown(markdown)
14
+ : `${converter.fromMarkdown(markdown)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_`;
10
15
  }
11
16
  /** One proxy POST, except one plain retry after a definite 400 entity parse refusal.
12
17
  * Never retry an unknown outcome; never chunk, truncate or invoke an agent.
@@ -40,6 +45,11 @@ function attemptTelegram(input, payload) {
40
45
  headers: [["content-type", "application/json"]],
41
46
  body: new TextEncoder().encode(JSON.stringify({
42
47
  chat_id: input.destination.external_id,
48
+ ...(input.threadId === undefined ||
49
+ input.threadId === null ||
50
+ !/^[1-9][0-9]*$/.test(input.threadId)
51
+ ? {}
52
+ : { message_thread_id: Number(input.threadId) }),
43
53
  ...payload,
44
54
  ...telegramPreviewOptions({
45
55
  link_preview_options: input.link_preview_options,
@@ -121,7 +131,7 @@ export const telegramProvider = {
121
131
  isReplyId: (replyTo) => /^[1-9][0-9]*$/.test(replyTo) && Number.isSafeInteger(Number(replyTo)),
122
132
  render: (markdown, attribution, separator) => ({
123
133
  finalText: renderTelegram(markdown, attribution, separator),
124
- plainText: `${markdown}${separator}${attribution}`,
134
+ plainText: attribution === "" ? markdown : `${markdown}${separator}${attribution}`,
125
135
  }),
126
136
  payload: (finalText) => ({ text: finalText, parse_mode: "MarkdownV2" }),
127
137
  send: (input) => sendTelegram({
@@ -137,5 +147,6 @@ export const telegramProvider = {
137
147
  ...(input.previews === undefined ? {} : { previews: input.previews }),
138
148
  plainText: input.plainText,
139
149
  replyTo: input.replyTo,
150
+ ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
140
151
  }),
141
152
  };
@@ -84,7 +84,7 @@ export const whatsappProvider = {
84
84
  isReplyId: () => false,
85
85
  render: (text, attribution, separator) => ({
86
86
  finalText: renderWhatsApp(text, attribution, separator),
87
- plainText: `${text}${separator}${attribution}`,
87
+ plainText: attribution === "" ? text : `${text}${separator}${attribution}`,
88
88
  }),
89
89
  payload: (finalText) => ({ type: "text", text: { body: finalText, preview_url: false } }),
90
90
  send: sendWhatsApp,
@@ -0,0 +1,38 @@
1
+ import { Effect } from "effect";
2
+ import type { ReviewSendInput } from "../../chat.js";
3
+ import type { TelegramPreviewContext } from "../../telegram.js";
4
+ import { ActionRejected, PermissionDenied } from "../../errors.js";
5
+ import type { Ontology } from "../../ontology.js";
6
+ import type { Principal } from "../../runtime.js";
7
+ import type { ConnectionTransportFactory } from "../connections.js";
8
+ import type { OntologyBackend } from "../runtime-contract.js";
9
+ import type { DeliveryArchive } from "./archive.js";
10
+ /**
11
+ * Sends a reply the agent held for review, once a member approved it: the draft or the member's
12
+ * edit, to the person's conversation through the ontology's chat connection for its provider, as
13
+ * the agent and without attribution. The archive's delivery claim, keyed by the review and not by
14
+ * the member, makes it at most once: a replay of the same approval returns the delivery, and a
15
+ * different approval, by another member or with another text, is refused. A provider that refused
16
+ * it consumes the claim: the reply is never sent again.
17
+ */
18
+ export declare function reviewSender(input: {
19
+ readonly ontology: Ontology;
20
+ readonly connections: ConnectionTransportFactory;
21
+ readonly archive: DeliveryArchive;
22
+ /** Link previews for the destination connection, as a chat post gets them. */
23
+ readonly previews?: TelegramPreviewContext;
24
+ readonly backend: OntologyBackend["Service"];
25
+ readonly principal: Principal;
26
+ readonly identityToken: string | undefined;
27
+ readonly requestId: string;
28
+ }): (send: ReviewSendInput) => Effect.Effect<{
29
+ status: "sent" | "uncertain" | "failed";
30
+ text: string;
31
+ messageId: string | null;
32
+ duplicate: true;
33
+ } | {
34
+ status: "sent" | "uncertain" | "failed";
35
+ text: string;
36
+ messageId: string | null;
37
+ duplicate: false;
38
+ }, ActionRejected | PermissionDenied, never>;
@@ -0,0 +1,258 @@
1
+ import { Effect } from "effect";
2
+ import { AGENT_REVIEW_TEXT_LIMIT } from "../../agent-review.js";
3
+ import { ActionRejected, PermissionDenied } from "../../errors.js";
4
+ import { effectiveScope } from "../../permissions.js";
5
+ import { describeChatError } from "./diagnostics.js";
6
+ import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
7
+ import { chatConnection, chatProvider } from "./providers/index.js";
8
+ /**
9
+ * Sends a reply the agent held for review, once a member approved it: the draft or the member's
10
+ * edit, to the person's conversation through the ontology's chat connection for its provider, as
11
+ * the agent and without attribution. The archive's delivery claim, keyed by the review and not by
12
+ * the member, makes it at most once: a replay of the same approval returns the delivery, and a
13
+ * different approval, by another member or with another text, is refused. A provider that refused
14
+ * it consumes the claim: the reply is never sent again.
15
+ */
16
+ export function reviewSender(input) {
17
+ const { backend, principal } = input;
18
+ const report = (phase, cause) => Effect.logWarning("ontology.agent_review.delivery_diagnostic").pipe(Effect.annotateLogs({
19
+ phase,
20
+ requestId: input.requestId,
21
+ error: describeChatError(cause, (text) => input.identityToken ? text.split(input.identityToken).join("[redacted]") : text),
22
+ }));
23
+ return (send) => Effect.gen(function* () {
24
+ // A role may hold the approval within a scope. The send happens before the action's
25
+ // transaction, whose write guard comes too late for it: a review outside the scope is
26
+ // refused here, read through the approval's own scope.
27
+ const approvable = effectiveScope("agent_review:approve", principal);
28
+ if (approvable !== undefined) {
29
+ yield* backend
30
+ .get({
31
+ entity: "agent_review",
32
+ id: send.review,
33
+ reader: {
34
+ ...principal,
35
+ permissions: ["agent_review:read"],
36
+ scopes: [{ permission: "agent_review:read", where: approvable }],
37
+ },
38
+ })
39
+ .pipe(Effect.mapError(() => new PermissionDenied({
40
+ message: "The review is outside the records agent_review:approve covers.",
41
+ permission: "agent_review:approve",
42
+ })));
43
+ }
44
+ const review = yield* backend
45
+ .get({ entity: "agent_review", id: send.review })
46
+ .pipe(Effect.mapError(() => new ActionRejected({ message: "The review does not exist." })));
47
+ const draft = String(review.draft ?? "");
48
+ const text = send.text ?? draft;
49
+ const status = String(review.status);
50
+ if (status !== "pending") {
51
+ if ((status === "sent" || status === "uncertain") && text === review.text) {
52
+ return {
53
+ status,
54
+ text,
55
+ messageId: typeof review.message_id === "string" ? review.message_id : null,
56
+ duplicate: true,
57
+ };
58
+ }
59
+ return yield* new ActionRejected({
60
+ message: status === "rejected"
61
+ ? "The reply was rejected; it is never sent."
62
+ : "The reply was already approved; it is never sent again.",
63
+ });
64
+ }
65
+ const providerName = String(review.provider);
66
+ const provider = chatProvider(providerName);
67
+ const connection = chatConnection(input.ontology.manifest.chat, providerName);
68
+ if (provider === undefined || !connection) {
69
+ return yield* new ActionRejected({
70
+ message: `Sending a reviewed reply needs chat.${providerName}.connection in defineOntology: ` +
71
+ "the connection of the bot or number the person talks to.",
72
+ });
73
+ }
74
+ const kind = review.chat_kind === "group" ? "group" : "private";
75
+ // The archive keys the conversation by its chat id; the provider takes the recipient, which
76
+ // differs where a channel names a conversation otherwise, as WhatsApp's threads do.
77
+ const chatId = String(review.chat_id);
78
+ const externalId = typeof review.recipient === "string" && review.recipient !== "" ? review.recipient : chatId;
79
+ const threadId = typeof review.thread_id === "string" && review.thread_id !== "" ? review.thread_id : null;
80
+ // A private conversation has one person: the reply needs no quote of their message, which
81
+ // they may have deleted since.
82
+ const replyTo = kind === "group" && typeof review.reply_to === "string" && review.reply_to !== ""
83
+ ? review.reply_to
84
+ : null;
85
+ const { finalText, plainText } = yield* Effect.try({
86
+ try: () => provider.render(text, "", ""),
87
+ catch: (cause) => new ActionRejected({ message: "The Markdown could not be rendered.", cause }),
88
+ });
89
+ if (text.trim() === "" ||
90
+ text.length > AGENT_REVIEW_TEXT_LIMIT ||
91
+ finalText.length > provider.limit ||
92
+ plainText.length > provider.limit ||
93
+ !provider.isTargetId(externalId, kind) ||
94
+ (replyTo !== null && !provider.isReplyId(replyTo))) {
95
+ return yield* new ActionRejected({
96
+ message: `The reply is empty or longer than ${provider.limit} characters, which ` +
97
+ `${providerName} accepts in one message. Approve it with a shorter text; nothing was ` +
98
+ "sent or truncated.",
99
+ });
100
+ }
101
+ const user = yield* backend
102
+ .get({ entity: "user", id: principal.id })
103
+ .pipe(Effect.mapError(() => new PermissionDenied({ message: "The approver is unknown." })));
104
+ if (user.active !== true) {
105
+ return yield* new PermissionDenied({ message: "The approver is inactive." });
106
+ }
107
+ const name = String(user.name ?? "").trim() || principal.id;
108
+ // The archive's record of who sent it; the person never sees it.
109
+ const requester = {
110
+ id: principal.id,
111
+ kind: principal.kind,
112
+ name,
113
+ via: principal.kind === "service" ? "service" : "hq",
114
+ clientId: null,
115
+ clientName: null,
116
+ attribution: name,
117
+ };
118
+ const person = typeof review.person_id === "string" ? review.person_id : null;
119
+ const target = {
120
+ id: String(review.id),
121
+ title: "",
122
+ provider: providerName,
123
+ external_id: externalId,
124
+ kind,
125
+ participantIds: person === null ? [] : [person],
126
+ };
127
+ const preview = {
128
+ chatId: target.id,
129
+ provider: providerName,
130
+ externalId,
131
+ title: "",
132
+ attribution: "",
133
+ text,
134
+ finalText,
135
+ replyTo,
136
+ };
137
+ const operationId = String(review.id);
138
+ const scope = deliveryScopeDigest({
139
+ via: "service",
140
+ subjectId: `agent_review:${operationId}`,
141
+ clientId: null,
142
+ });
143
+ const key = deliveryKeyDigest(`agent_review:${operationId}`);
144
+ const fingerprint = deliveryFingerprint(preview, requester);
145
+ const event = {
146
+ eventId: `chat-delivery:${operationId}:reserve`,
147
+ operationId,
148
+ provider: providerName,
149
+ chatId,
150
+ chatType: kind,
151
+ threadId,
152
+ participantIds: target.participantIds,
153
+ senderId: "agent",
154
+ senderName: "agent",
155
+ senderIsBot: true,
156
+ kind: "outbound",
157
+ messageId: null,
158
+ replyToMessageId: replyTo,
159
+ // The agent's session holds its draft: the session sees an edit as a message it did not
160
+ // write, and the draft sent as written as its own.
161
+ sessionId: text === draft && typeof review.session_id === "string" ? review.session_id : null,
162
+ turnId: null,
163
+ text,
164
+ decision: null,
165
+ reason: null,
166
+ toolCallId: null,
167
+ toolName: null,
168
+ argsSummary: JSON.stringify(provider.payload(finalText)),
169
+ status: "requested",
170
+ attachments: [],
171
+ requestedBy: requester,
172
+ url: null,
173
+ at: new Date().toISOString(),
174
+ };
175
+ const reserve = yield* input
176
+ .archive({
177
+ event,
178
+ delivery: { phase: "reserve", scope, key, fingerprint },
179
+ identityToken: input.identityToken,
180
+ })
181
+ .pipe(Effect.tapError((error) => report("reserve", error)), Effect.mapError((cause) => new ActionRejected({
182
+ cause,
183
+ message: cause.diagnostic === "chat_archive_conflict"
184
+ ? "The reply was already approved by another member or with another text; " +
185
+ "it is never sent again."
186
+ : "The delivery could not be reserved, and nothing was sent. Approve again.",
187
+ })));
188
+ if (!reserve.claimed) {
189
+ if (reserve.version !== 1 || !reserve.duplicate || reserve.claimId !== undefined) {
190
+ return yield* new ActionRejected({
191
+ message: "The archive did not return a valid delivery receipt.",
192
+ });
193
+ }
194
+ return {
195
+ status: reserve.status,
196
+ text,
197
+ messageId: reserve.messageId,
198
+ duplicate: true,
199
+ };
200
+ }
201
+ if (reserve.version !== 1 ||
202
+ reserve.duplicate ||
203
+ !reserve.claimId ||
204
+ reserve.operationId !== operationId ||
205
+ reserve.status !== "uncertain" ||
206
+ reserve.messageId !== null) {
207
+ return yield* new ActionRejected({
208
+ message: "The archive did not grant a fresh delivery claim.",
209
+ });
210
+ }
211
+ const outcome = yield* provider.send({
212
+ destination: target,
213
+ connection,
214
+ text,
215
+ separator: "",
216
+ attribution: "",
217
+ finalText,
218
+ plainText,
219
+ replyTo,
220
+ threadId,
221
+ ...(input.previews === undefined ? {} : { previews: input.previews }),
222
+ transport: input.connections({
223
+ identityToken: input.identityToken,
224
+ audit: {
225
+ action: "agent_review.approve",
226
+ principalId: principal.id,
227
+ requestId: input.requestId,
228
+ },
229
+ }),
230
+ });
231
+ if (outcome.cause !== undefined) {
232
+ yield* report("provider", outcome.cause);
233
+ }
234
+ const saved = yield* input
235
+ .archive({
236
+ event: {
237
+ ...event,
238
+ eventId: `chat-delivery:${operationId}:receipt`,
239
+ status: outcome.status,
240
+ argsSummary: JSON.stringify(outcome.payload),
241
+ messageId: outcome.messageId,
242
+ url: outcome.url,
243
+ },
244
+ delivery: { phase: "receipt", scope, key, fingerprint, claimId: reserve.claimId },
245
+ identityToken: input.identityToken,
246
+ })
247
+ .pipe(Effect.exit);
248
+ if (saved._tag === "Failure") {
249
+ yield* report("receipt", saved.cause);
250
+ }
251
+ return {
252
+ status: outcome.status,
253
+ text,
254
+ messageId: outcome.messageId,
255
+ duplicate: false,
256
+ };
257
+ });
258
+ }
@@ -37,7 +37,11 @@ export function requireRuntimeOperation(operation) {
37
37
  return Effect.gen(function* () {
38
38
  const deployment = Option.getOrUndefined(yield* Effect.serviceOption(RuntimeDeployment));
39
39
  if (deployment) {
40
- yield* Effect.sync(() => requireDeploymentCapability(deployment, invokesAgent(operation) || operation.entity === "agent_chat" ? "agents" : undefined));
40
+ yield* Effect.sync(() => requireDeploymentCapability(deployment, invokesAgent(operation) ||
41
+ operation.entity === "agent_chat" ||
42
+ operation.entity === "agent_review"
43
+ ? "agents"
44
+ : undefined));
41
45
  }
42
46
  return yield* currentCaller.pipe(Effect.flatMap((caller) => checkRuntimeOperation(caller, operation)));
43
47
  });
@@ -460,9 +460,13 @@ function runTool(server, tool, args, request, preview) {
460
460
  input: args,
461
461
  identityToken: identityToken(request),
462
462
  });
463
+ // Structured content only when the provider sent it: a stand-in would repeat the text, and
464
+ // a client that prefers structured content would read the provider's answer twice wrapped.
463
465
  return {
464
466
  text: resultText(result),
465
- structured: (result.structuredContent ?? { content: result.content }),
467
+ ...(result.structuredContent === undefined
468
+ ? {}
469
+ : { structured: result.structuredContent }),
466
470
  };
467
471
  }
468
472
  case "action": {
@@ -241,8 +241,20 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
241
241
  }
242
242
  input = { ...values, idempotency_key: envelope.operation_id };
243
243
  }
244
+ // Approving a held reply sends it to a person: a member, or the agent acting for one with
245
+ // their confirmation, decides; an agent task has no one to confirm it.
246
+ if (planned.name === "agent_review" &&
247
+ name === "approve" &&
248
+ principal.authenticatedVia === AGENT_TASK_AUTHENTICATION) {
249
+ return yield* new ActionRejected({
250
+ message: "Agent tasks cannot approve a held reply: agent_review.approve needs a member to " +
251
+ "confirm the text the person receives.",
252
+ });
253
+ }
244
254
  const requestId = yield* RequestId;
245
- const delivery = planned.name === "agent_chat" && (name === "post_message" || name === "preview_message")
255
+ const delivery = (planned.name === "agent_chat" &&
256
+ (name === "post_message" || name === "preview_message")) ||
257
+ (planned.name === "agent_review" && name === "approve")
246
258
  ? chatDelivery?.({
247
259
  backend,
248
260
  principal,
@@ -380,6 +380,34 @@ export interface AgentStore {
380
380
  readonly agentLeft?: true;
381
381
  readonly migratedFrom?: string;
382
382
  }) => Effect.Effect<SeenChat>;
383
+ /**
384
+ * A reply the agent held for review becomes a pending `agent_review` for the member it answers,
385
+ * once per `key`: a repeated report answers the review it created. `undefined` when the member is
386
+ * not an active member of the app. Absent on stores that predate reviews.
387
+ */
388
+ readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
389
+ }
390
+ /** A reply the agent held for review, as `POST /api/ontology/agent/reviews` reports it. */
391
+ export interface HeldReplyInput {
392
+ readonly key: string;
393
+ readonly provider: string;
394
+ readonly chatId: string;
395
+ /** Whom the provider sends the reply to: the chat's id, or the person's id where it differs. */
396
+ readonly recipient: string;
397
+ readonly threadId: string;
398
+ readonly replyTo: string | null;
399
+ readonly memberId: string;
400
+ readonly sessionId: string;
401
+ readonly text: string;
402
+ readonly mode: "always" | "whenUnsure";
403
+ readonly confidence: number | null;
404
+ }
405
+ /** The review a held reply became. */
406
+ export interface HeldReview {
407
+ readonly id: string;
408
+ readonly status: string;
409
+ /** Whether this report created it, rather than finding the review an earlier one created. */
410
+ readonly created: boolean;
383
411
  }
384
412
  declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segmentstream/ontology/OntologyBackend", {
385
413
  readonly workflowAdmissions?: {