@segmentstream/ontology 0.96.0 → 0.98.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/README.md +15 -3
- package/dist/agent-review.d.ts +95 -0
- package/dist/agent-review.js +200 -0
- package/dist/analyze.d.ts +10 -2
- package/dist/analyze.js +240 -19
- package/dist/bin/check.js +2 -0
- package/dist/chat.d.ts +16 -0
- package/dist/diagnostics.d.ts +3 -3
- package/dist/diagnostics.js +2 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/manifest.d.ts +505 -2
- package/dist/manifest.js +55 -2
- package/dist/migrate/model.d.ts +272 -0
- package/dist/ontology.d.ts +3 -0
- package/dist/ontology.js +1 -0
- package/dist/permissions.d.ts +5 -3
- package/dist/permissions.js +9 -5
- package/dist/runtime/agents.js +53 -0
- package/dist/service/agent/protocol.d.ts +18 -0
- package/dist/service/agent/protocol.js +33 -0
- package/dist/service/agent/server.js +48 -1
- package/dist/service/catalog.js +10 -1
- package/dist/service/chat/archive.d.ts +2 -1
- package/dist/service/chat/delivery.js +11 -0
- package/dist/service/chat/envelope.d.ts +16 -16
- package/dist/service/chat/providers/provider.d.ts +2 -0
- package/dist/service/chat/providers/slack.js +1 -1
- package/dist/service/chat/providers/telegram.d.ts +6 -1
- package/dist/service/chat/providers/telegram.js +14 -3
- package/dist/service/chat/providers/whatsapp.js +1 -1
- package/dist/service/chat/review-delivery.d.ts +38 -0
- package/dist/service/chat/review-delivery.js +258 -0
- package/dist/service/connections.js +1 -0
- package/dist/service/discovery-search.d.ts +1 -1
- package/dist/service/mcp/runtime-policy.js +5 -1
- package/dist/service/mcp/server.js +13 -1
- package/dist/service/mcp/tools.d.ts +5 -0
- package/dist/service/mcp/tools.js +30 -0
- package/dist/service/operations.d.ts +3 -1
- package/dist/service/operations.js +16 -1
- package/dist/service/runtime-contract.d.ts +28 -0
- package/dist/service/schemas.d.ts +62 -0
- package/dist/service/toolsets.d.ts +49 -0
- package/dist/service/toolsets.js +284 -0
- package/dist/slack.js +3 -1
- package/dist/toolset.d.ts +141 -0
- package/dist/toolset.js +154 -0
- package/dist/whatsapp.js +3 -1
- package/package.json +1 -1
|
@@ -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
|
}
|
package/dist/service/catalog.js
CHANGED
|
@@ -10,11 +10,20 @@ export function catalogFor(manifest, permissions) {
|
|
|
10
10
|
if (permissions === undefined) {
|
|
11
11
|
return manifest;
|
|
12
12
|
}
|
|
13
|
-
const { metrics: declared, ...rest } = manifest;
|
|
13
|
+
const { metrics: declared, toolsets: served, ...rest } = manifest;
|
|
14
14
|
const metrics = declared === undefined ? [] : modelMetricsFor(manifest, permissions);
|
|
15
|
+
// A caller sees a toolset with the tools its permissions grant, and no toolset without one.
|
|
16
|
+
const toolsets = (served ?? []).flatMap((toolset) => {
|
|
17
|
+
const actions = toolset.actions.filter((action) => isAllowed(action.permission ?? `${toolset.name}:${action.name}`, { permissions }));
|
|
18
|
+
const names = new Set(actions.map((action) => action.name));
|
|
19
|
+
return actions.length === 0
|
|
20
|
+
? []
|
|
21
|
+
: [{ ...toolset, actions, tools: toolset.tools.filter((tool) => names.has(tool.name)) }];
|
|
22
|
+
});
|
|
15
23
|
return {
|
|
16
24
|
...rest,
|
|
17
25
|
...(metrics.length === 0 ? {} : { metrics }),
|
|
26
|
+
...(toolsets.length === 0 ? {} : { toolsets }),
|
|
18
27
|
entities: manifest.entities
|
|
19
28
|
.filter((entity) => entity.source === undefined ||
|
|
20
29
|
isAllowed(entity.permissions?.read ?? `${entity.name}:read`, { permissions }))
|
|
@@ -7,7 +7,8 @@ export interface DeliveryEvent {
|
|
|
7
7
|
readonly provider: string;
|
|
8
8
|
readonly chatId: string;
|
|
9
9
|
readonly chatType: "group" | "private";
|
|
10
|
-
|
|
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* () {
|
|
@@ -51,6 +51,13 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
|
|
|
51
51
|
readonly chat_id: string;
|
|
52
52
|
readonly thread_id: string;
|
|
53
53
|
readonly message_id?: string | undefined;
|
|
54
|
+
readonly attachments?: readonly {
|
|
55
|
+
readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
|
|
56
|
+
readonly file_id: string;
|
|
57
|
+
readonly staged_id: string;
|
|
58
|
+
readonly file_unique_id?: string | undefined;
|
|
59
|
+
readonly media_type?: string | undefined;
|
|
60
|
+
}[] | undefined;
|
|
54
61
|
readonly reply_to_message_id?: string | undefined;
|
|
55
62
|
readonly callback_query_id?: string | undefined;
|
|
56
63
|
readonly sender?: string | undefined;
|
|
@@ -60,15 +67,8 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
|
|
|
60
67
|
readonly horizontal_accuracy?: number | undefined;
|
|
61
68
|
readonly live_period?: number | undefined;
|
|
62
69
|
} | undefined;
|
|
63
|
-
readonly attachments?: readonly {
|
|
64
|
-
readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
|
|
65
|
-
readonly file_id: string;
|
|
66
|
-
readonly staged_id: string;
|
|
67
|
-
readonly file_unique_id?: string | undefined;
|
|
68
|
-
readonly media_type?: string | undefined;
|
|
69
|
-
}[] | undefined;
|
|
70
70
|
} | {
|
|
71
|
-
readonly kind: "
|
|
71
|
+
readonly kind: "private" | "group";
|
|
72
72
|
readonly provider: "whatsapp" | "slack";
|
|
73
73
|
readonly chat_id: string;
|
|
74
74
|
readonly thread_id: string;
|
|
@@ -103,6 +103,13 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
|
|
|
103
103
|
readonly chat_id: string;
|
|
104
104
|
readonly thread_id: string;
|
|
105
105
|
readonly message_id?: string | undefined;
|
|
106
|
+
readonly attachments?: readonly {
|
|
107
|
+
readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
|
|
108
|
+
readonly file_id: string;
|
|
109
|
+
readonly staged_id: string;
|
|
110
|
+
readonly file_unique_id?: string | undefined;
|
|
111
|
+
readonly media_type?: string | undefined;
|
|
112
|
+
}[] | undefined;
|
|
106
113
|
readonly reply_to_message_id?: string | undefined;
|
|
107
114
|
readonly callback_query_id?: string | undefined;
|
|
108
115
|
readonly sender?: string | undefined;
|
|
@@ -112,15 +119,8 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
|
|
|
112
119
|
readonly horizontal_accuracy?: number | undefined;
|
|
113
120
|
readonly live_period?: number | undefined;
|
|
114
121
|
} | undefined;
|
|
115
|
-
readonly attachments?: readonly {
|
|
116
|
-
readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
|
|
117
|
-
readonly file_id: string;
|
|
118
|
-
readonly staged_id: string;
|
|
119
|
-
readonly file_unique_id?: string | undefined;
|
|
120
|
-
readonly media_type?: string | undefined;
|
|
121
|
-
}[] | undefined;
|
|
122
122
|
} | {
|
|
123
|
-
readonly kind: "
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
|
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
|
+
}
|
|
@@ -38,6 +38,7 @@ const REASONS = {
|
|
|
38
38
|
connection_response_too_large: "invalid_response",
|
|
39
39
|
invalid_connection: "invalid_request",
|
|
40
40
|
invalid_request: "invalid_request",
|
|
41
|
+
mcp_request_not_permitted: "invalid_request",
|
|
41
42
|
};
|
|
42
43
|
const MESSAGES = {
|
|
43
44
|
authorization_required: "Configure or authorize this connection in SegmentStream.",
|
|
@@ -23,8 +23,8 @@ export declare function searchDocuments(documents: ReadonlyArray<SearchDocument>
|
|
|
23
23
|
readonly summary_truncated: boolean;
|
|
24
24
|
readonly entity?: string | undefined;
|
|
25
25
|
readonly metrics?: readonly string[] | undefined;
|
|
26
|
-
readonly relevance?: number | undefined;
|
|
27
26
|
readonly tools?: readonly string[] | undefined;
|
|
27
|
+
readonly relevance?: number | undefined;
|
|
28
28
|
}[];
|
|
29
29
|
/** Bytewise canonical-name ordering is independent of a function instance's locale. */
|
|
30
30
|
export declare function compareRefs(left: string, right: string): number;
|
|
@@ -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) ||
|
|
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
|
});
|
|
@@ -29,6 +29,7 @@ import { RequestId, errorBodyForWire, expectedFailure, internalError, isStorageF
|
|
|
29
29
|
import { publicOrigin } from "../oauth/protocol.js";
|
|
30
30
|
import { mcpChallenge, mcpResource } from "../oauth/server.js";
|
|
31
31
|
import { identityToken, makeOperations, toQuery } from "../operations.js";
|
|
32
|
+
import { resultText } from "../toolsets.js";
|
|
32
33
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
33
34
|
import { WarehouseQueries } from "../warehouse-platform.js";
|
|
34
35
|
import { runtimeCredential } from "../runtime-identity.js";
|
|
@@ -453,6 +454,17 @@ function runTool(server, tool, args, request, preview) {
|
|
|
453
454
|
const { id, ...params } = yield* decodeArguments(HistoryArguments, args);
|
|
454
455
|
return structured(yield* encoded(HistoryPage, yield* operations.history(target.planned, id, params)));
|
|
455
456
|
}
|
|
457
|
+
case "toolset": {
|
|
458
|
+
// Every argument is the provider's: toolset tools take no action options.
|
|
459
|
+
const result = yield* operations.runToolsetTool(target.toolset, target.tool, {
|
|
460
|
+
input: args,
|
|
461
|
+
identityToken: identityToken(request),
|
|
462
|
+
});
|
|
463
|
+
return {
|
|
464
|
+
text: resultText(result),
|
|
465
|
+
structured: (result.structuredContent ?? { content: result.content }),
|
|
466
|
+
};
|
|
467
|
+
}
|
|
456
468
|
case "action": {
|
|
457
469
|
if (target.planned.name === "agent_chat" && target.action.name === "post_message") {
|
|
458
470
|
yield* decodeArguments(caller.kind === "runtime" ? RuntimeChatPostWire : ChatPostWire, args);
|
|
@@ -512,7 +524,7 @@ function callTool(server, params, request, preview) {
|
|
|
512
524
|
}
|
|
513
525
|
if (tool === undefined) {
|
|
514
526
|
const candidates = visibleTools(server.tools, principal, caller)
|
|
515
|
-
.filter((candidate) => candidate.target.kind === "action")
|
|
527
|
+
.filter((candidate) => candidate.target.kind === "action" || candidate.target.kind === "toolset")
|
|
516
528
|
.map((candidate) => candidate.name);
|
|
517
529
|
const suggestions = typeof call.name === "string" ? suggestNames(call.name, candidates) : [];
|
|
518
530
|
return {
|