@segmentstream/ontology 0.109.0 → 0.111.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +77 -0
- package/README.md +28 -1
- package/dist/agent-review.d.ts +2 -0
- package/dist/agent-review.js +11 -1
- package/dist/analyze.d.ts +34 -34
- package/dist/analyze.js +104 -29
- package/dist/chat-channel.d.ts +22 -0
- package/dist/chat-channel.js +35 -0
- package/dist/index.d.ts +8 -6
- package/dist/index.js +3 -2
- package/dist/manifest.d.ts +194 -29
- package/dist/manifest.js +54 -10
- package/dist/migrate/apply.d.ts +4 -3
- package/dist/migrate/apply.js +8 -3
- package/dist/migrate/model.d.ts +90 -2
- package/dist/migrate/plan.js +1 -1
- package/dist/migrate/preview.js +2 -1
- package/dist/migrate/storage.d.ts +13 -1
- package/dist/migrate/storage.js +33 -1
- package/dist/runtime/agent-counters.d.ts +36 -0
- package/dist/runtime/agent-counters.js +84 -0
- package/dist/runtime/agent-web.d.ts +1 -1
- package/dist/runtime/agent-web.js +175 -3
- package/dist/runtime/agents.js +3 -0
- package/dist/runtime/batch.js +4 -6
- package/dist/runtime/history.d.ts +24 -0
- package/dist/runtime/history.js +35 -1
- package/dist/runtime/pipeline.js +3 -0
- package/dist/runtime/principals.d.ts +6 -0
- package/dist/runtime/principals.js +25 -6
- package/dist/runtime/reads.js +9 -2
- package/dist/runtime/sign-in-links.d.ts +10 -0
- package/dist/runtime/sign-in-links.js +26 -25
- package/dist/runtime/sql-runtime.d.ts +1 -1
- package/dist/runtime/sql-runtime.js +3 -2
- package/dist/runtime/writes.js +4 -6
- package/dist/runtime-source.d.ts +4 -0
- package/dist/runtime-source.js +5 -0
- package/dist/runtime.d.ts +21 -0
- package/dist/service/agent/authentication.d.ts +3 -2
- package/dist/service/agent/authentication.js +2 -11
- package/dist/service/agent/bot-check.d.ts +42 -0
- package/dist/service/agent/bot-check.js +32 -0
- package/dist/service/agent/guest-sign-up.d.ts +140 -0
- package/dist/service/agent/guest-sign-up.js +545 -0
- package/dist/service/agent/protocol.d.ts +34 -1
- package/dist/service/agent/protocol.js +46 -1
- package/dist/service/agent/server.d.ts +17 -0
- package/dist/service/agent/server.js +53 -3
- package/dist/service/agent/web-tokens.d.ts +21 -3
- package/dist/service/agent/web-tokens.js +79 -6
- package/dist/service/authentication.d.ts +9 -1
- package/dist/service/authentication.js +31 -5
- package/dist/service/chat/delivery.js +9 -5
- package/dist/service/chat/envelope.d.ts +6 -0
- package/dist/service/chat/providers/index.d.ts +19 -9
- package/dist/service/chat/providers/index.js +31 -11
- package/dist/service/chat/reads.d.ts +6 -3
- package/dist/service/chat/reads.js +26 -14
- package/dist/service/chat/resolve.d.ts +6 -2
- package/dist/service/chat/resolve.js +7 -3
- package/dist/service/chat/review-delivery.d.ts +2 -2
- package/dist/service/chat/review-delivery.js +16 -8
- package/dist/service/chat/routes.js +2 -1
- package/dist/service/chat/schemas.d.ts +2 -0
- package/dist/service/chat/schemas.js +8 -1
- package/dist/service/config.d.ts +10 -0
- package/dist/service/mcp/server.js +2 -1
- package/dist/service/operations.d.ts +5 -0
- package/dist/service/runtime-contract.d.ts +133 -1
- package/dist/service/runtime-identity.d.ts +23 -0
- package/dist/service/runtime-identity.js +31 -0
- package/dist/service/schemas.d.ts +54 -2
- package/dist/service/service.js +27 -1
- package/dist/service/webhooks.d.ts +15 -0
- package/dist/service/webhooks.js +15 -4
- package/dist/sign-in.d.ts +29 -0
- package/dist/sign-in.js +8 -0
- package/package.json +1 -1
|
@@ -14,22 +14,42 @@ export const CHAT_PROVIDERS = {
|
|
|
14
14
|
};
|
|
15
15
|
const NAMES = Object.keys(CHAT_PROVIDERS);
|
|
16
16
|
const isChatProvider = (name) => Object.hasOwn(CHAT_PROVIDERS, name);
|
|
17
|
-
/** The provider a
|
|
18
|
-
export function chatProvider(
|
|
19
|
-
return isChatProvider(
|
|
17
|
+
/** The provider of a kind of channel, when the platform posts to it. */
|
|
18
|
+
export function chatProvider(kind) {
|
|
19
|
+
return isChatProvider(kind) ? CHAT_PROVIDERS[kind] : undefined;
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
/**
|
|
22
|
+
* The kind of the agent's channel `name` the ontology's `chat` declares: the name itself for the
|
|
23
|
+
* channel named after its kind, which a chat on it before channels had names also is.
|
|
24
|
+
*/
|
|
25
|
+
export function chatKind(chat, name) {
|
|
26
|
+
return isChatProvider(name) ? name : chat?.channels?.[name]?.kind;
|
|
27
|
+
}
|
|
28
|
+
/** The provider of the agent's channel `name`, by its kind, when the platform posts to it. */
|
|
29
|
+
export function channelProvider(chat, name) {
|
|
30
|
+
const kind = chatKind(chat, name);
|
|
31
|
+
return kind === undefined ? undefined : chatProvider(kind);
|
|
24
32
|
}
|
|
25
|
-
/** The
|
|
33
|
+
/** The connection the ontology declares for the agent's channel `name`, if it declares one. */
|
|
34
|
+
export function chatConnection(chat, name) {
|
|
35
|
+
return isChatProvider(name) ? chat?.[name]?.connection : chat?.channels?.[name]?.connection;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The channels the ontology declares a posting connection for, by name: the destinations it posts
|
|
39
|
+
* to. The channel named after each kind comes first, then the others.
|
|
40
|
+
*/
|
|
26
41
|
export function declaredChatProviders(chat) {
|
|
27
|
-
return
|
|
42
|
+
return [
|
|
43
|
+
...NAMES.filter((name) => chat?.[name] !== undefined && CHAT_PROVIDERS[name].posts !== false),
|
|
44
|
+
...Object.entries(chat?.channels ?? {})
|
|
45
|
+
.filter(([, channel]) => chatProvider(channel.kind)?.posts !== false)
|
|
46
|
+
.map(([name]) => name),
|
|
47
|
+
];
|
|
28
48
|
}
|
|
29
49
|
/**
|
|
30
|
-
* The
|
|
31
|
-
* tools always listed, and each declared one. Posting still requires the target's
|
|
32
|
-
* be declared.
|
|
50
|
+
* The channels whose chats the chat tools list, read and resolve, by name: Telegram's, whose
|
|
51
|
+
* chats the tools always listed, and each declared one. Posting still requires the target's
|
|
52
|
+
* channel to be declared.
|
|
33
53
|
*/
|
|
34
54
|
export function listedChatProviders(chat) {
|
|
35
55
|
return [...new Set(["telegram", ...declaredChatProviders(chat)])];
|
|
@@ -6,18 +6,21 @@ import type { OntologyBackend } from "../runtime-contract.js";
|
|
|
6
6
|
import type { ChatArchiveTransport } from "../agent/chat-archive.js";
|
|
7
7
|
import type { ChatList, ChatHistory } from "./schemas.js";
|
|
8
8
|
export declare function chatReads(backend: OntologyBackend["Service"], options: {
|
|
9
|
-
/** The
|
|
9
|
+
/** The channels whose chats are listed, as `listedChatProviders` gives them. */
|
|
10
10
|
readonly providers: ReadonlyArray<string>;
|
|
11
|
+
/** The kind of each channel, as `chatKind` gives it; the name by default. */
|
|
12
|
+
readonly kindOf?: (channel: string) => string | undefined;
|
|
11
13
|
readonly chatHistory?: ChatArchiveTransport;
|
|
12
14
|
readonly attribution?: ChatAttributionSettings;
|
|
13
15
|
}): {
|
|
14
16
|
list: (input: typeof ChatList.Type) => Effect.Effect<{
|
|
15
17
|
items: {
|
|
18
|
+
external_id: string;
|
|
19
|
+
attribution: string | null;
|
|
20
|
+
kind?: "telegram" | "email" | "whatsapp" | "slack" | undefined;
|
|
16
21
|
id: string;
|
|
17
22
|
title: string;
|
|
18
23
|
provider: string;
|
|
19
|
-
external_id: string;
|
|
20
|
-
attribution: string | null;
|
|
21
24
|
}[];
|
|
22
25
|
next_cursor: string | null;
|
|
23
26
|
}, ActionRejected | PermissionDenied | import("../../errors.js").NotFound, CurrentPrincipal>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isChatChannelKind } from "../../chat-channel.js";
|
|
1
2
|
import { Effect } from "effect";
|
|
2
3
|
import { ActionRejected, PermissionDenied } from "../../errors.js";
|
|
3
4
|
import { isAllowed } from "../../permissions.js";
|
|
@@ -5,16 +6,20 @@ import { CurrentPrincipal } from "../authentication.js";
|
|
|
5
6
|
import { currentCaller } from "../caller-context.js";
|
|
6
7
|
import { chatAttribution } from "./attribution.js";
|
|
7
8
|
import { chatResolver, groupChatKey, isChatMember } from "./resolve.js";
|
|
8
|
-
/** The
|
|
9
|
-
const
|
|
9
|
+
/** The kinds of channel whose archived chats are keyed by the chat a destination names. */
|
|
10
|
+
const HISTORY_KINDS = new Set(["telegram"]);
|
|
10
11
|
export function chatReads(backend, options) {
|
|
11
12
|
const { providers, chatHistory, attribution } = options;
|
|
13
|
+
const kindOf = options.kindOf ?? ((channel) => channel);
|
|
14
|
+
const history = [
|
|
15
|
+
...new Set(["telegram", ...providers.filter((name) => HISTORY_KINDS.has(kindOf(name) ?? ""))]),
|
|
16
|
+
];
|
|
12
17
|
return {
|
|
13
18
|
list: (input) => Effect.gen(function* () {
|
|
14
19
|
const principal = yield* CurrentPrincipal;
|
|
15
20
|
const caller = yield* currentCaller;
|
|
16
21
|
const query = input.query?.toLowerCase();
|
|
17
|
-
const items = (yield* chatResolver(backend, principal, providers).list(input.chat))
|
|
22
|
+
const items = (yield* chatResolver(backend, principal, providers, { kindOf }).list(input.chat))
|
|
18
23
|
.filter((item) => query === undefined || item.title.toLowerCase().includes(query))
|
|
19
24
|
.sort((a, b) => a.id.localeCompare(b.id));
|
|
20
25
|
const user = yield* backend.get({ entity: "user", id: principal.id });
|
|
@@ -25,13 +30,19 @@ export function chatReads(backend, options) {
|
|
|
25
30
|
});
|
|
26
31
|
}
|
|
27
32
|
const limit = input.limit ?? 50;
|
|
28
|
-
const selected = items.slice(start, start + limit).map((item) =>
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
const selected = items.slice(start, start + limit).map((item) => {
|
|
34
|
+
// The kind of the channel the chat is on, so that a reader renders a post to a
|
|
35
|
+
// channel of another name, such as sales_whatsapp, as that kind does.
|
|
36
|
+
const kind = kindOf(item.provider);
|
|
37
|
+
return {
|
|
38
|
+
id: item.id,
|
|
39
|
+
title: item.title,
|
|
40
|
+
provider: item.provider,
|
|
41
|
+
...(isChatChannelKind(kind) ? { kind } : {}),
|
|
42
|
+
external_id: item.external_id,
|
|
43
|
+
attribution: chatAttribution(caller, String(user.name), attribution),
|
|
44
|
+
};
|
|
45
|
+
});
|
|
35
46
|
return {
|
|
36
47
|
items: selected,
|
|
37
48
|
next_cursor: start + limit < items.length ? selected.at(-1).id : null,
|
|
@@ -42,11 +53,12 @@ export function chatReads(backend, options) {
|
|
|
42
53
|
if (principal.kind !== "member") {
|
|
43
54
|
return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
|
|
44
55
|
}
|
|
45
|
-
// History reads
|
|
46
|
-
// session's address with private coordinates, not under the chat a destination
|
|
47
|
-
// their history would be incomplete until the archive keys them the same way.
|
|
48
|
-
const target = yield* chatResolver(backend, principal,
|
|
56
|
+
// History reads the chats of Telegram channels only. Other channels archive a chat under
|
|
57
|
+
// their session's address with private coordinates, not under the chat a destination
|
|
58
|
+
// names, so their history would be incomplete until the archive keys them the same way.
|
|
59
|
+
const target = yield* chatResolver(backend, principal, history, {
|
|
49
60
|
memberGroups: true,
|
|
61
|
+
kindOf,
|
|
50
62
|
}).resolve(input.chat);
|
|
51
63
|
// A group's members read its history, as they read its attachments; agent_chat:read reads
|
|
52
64
|
// every group. A private chat is read only by its participant.
|
|
@@ -26,12 +26,16 @@ export declare function isChatMember(backend: OntologyBackend["Service"], princi
|
|
|
26
26
|
*/
|
|
27
27
|
export declare function withChatMembership(transport: ChatArchiveTransport, backend: OntologyBackend["Service"]): ChatArchiveTransport;
|
|
28
28
|
/**
|
|
29
|
-
* Resolves the chats of `providers
|
|
30
|
-
* chat on each
|
|
29
|
+
* Resolves the chats of `providers`, the agent's channels by name: their group chats in the
|
|
30
|
+
* registry, and each member's private chat on each channel whose kind they have a live identity
|
|
31
|
+
* on, `<channel>:private:<member id>`. People are not per channel: one identity of a kind reaches
|
|
32
|
+
* the member on every channel of that kind.
|
|
31
33
|
*/
|
|
32
34
|
export declare function chatResolver(backend: OntologyBackend["Service"], principal: Principal, providers: ReadonlyArray<string>, options?: {
|
|
33
35
|
/** Also resolve the group chats a member is in without chat read or post permission. */
|
|
34
36
|
readonly memberGroups?: boolean;
|
|
37
|
+
/** The kind of each channel, whose identities reach its private chats; the name by default. */
|
|
38
|
+
readonly kindOf?: (channel: string) => string | undefined;
|
|
35
39
|
}): {
|
|
36
40
|
list: (chat?: string) => Effect.Effect<Destination[], ActionRejected | PermissionDenied, never>;
|
|
37
41
|
resolve: (chat: string) => Effect.Effect<Destination, ActionRejected | PermissionDenied, never>;
|
|
@@ -66,10 +66,13 @@ export function withChatMembership(transport, backend) {
|
|
|
66
66
|
})), Effect.flatMap((memberGroups) => transport({ ...input, memberGroups })));
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
|
-
* Resolves the chats of `providers
|
|
70
|
-
* chat on each
|
|
69
|
+
* Resolves the chats of `providers`, the agent's channels by name: their group chats in the
|
|
70
|
+
* registry, and each member's private chat on each channel whose kind they have a live identity
|
|
71
|
+
* on, `<channel>:private:<member id>`. People are not per channel: one identity of a kind reaches
|
|
72
|
+
* the member on every channel of that kind.
|
|
71
73
|
*/
|
|
72
74
|
export function chatResolver(backend, principal, providers, options = {}) {
|
|
75
|
+
const kindOf = options.kindOf ?? ((channel) => channel);
|
|
73
76
|
const canGroup = isAllowed("agent_chat:read", principal) || isAllowed("agent_chat:post_message", principal);
|
|
74
77
|
const memberGroups = options.memberGroups === true && principal.kind === "member";
|
|
75
78
|
const canDirectory = isAllowed("user:read", principal) || isAllowed("agent_chat:post_message", principal);
|
|
@@ -125,7 +128,8 @@ export function chatResolver(backend, principal, providers, options = {}) {
|
|
|
125
128
|
}
|
|
126
129
|
const identities = yield* backend.agents.listIdentities(member.principal.id);
|
|
127
130
|
for (const provider of named === undefined ? providers : [named]) {
|
|
128
|
-
const
|
|
131
|
+
const kind = kindOf(provider);
|
|
132
|
+
const identity = identities.find((item) => kind !== undefined && item.provider === kind && item.revokedAt === null);
|
|
129
133
|
if (identity !== undefined) {
|
|
130
134
|
result.push({
|
|
131
135
|
id: `${provider}:private:${member.principal.id}`,
|
|
@@ -9,8 +9,8 @@ import type { OntologyBackend } from "../runtime-contract.js";
|
|
|
9
9
|
import type { DeliveryArchive } from "./archive.js";
|
|
10
10
|
/**
|
|
11
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 chat through the ontology's chat connection
|
|
13
|
-
* the agent and without attribution. The archive's delivery claim, keyed by the review and not by
|
|
12
|
+
* edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
|
|
13
|
+
* as the agent and without attribution. The archive's delivery claim, keyed by the review and not by
|
|
14
14
|
* the member, makes it at most once: a replay of the same approval returns the delivery, and a
|
|
15
15
|
* different approval, by another member or with another text, is refused. A provider that refused
|
|
16
16
|
* it consumes the claim: the reply is never sent again.
|
|
@@ -4,11 +4,11 @@ import { ActionRejected, PermissionDenied } from "../../errors.js";
|
|
|
4
4
|
import { effectiveScope } from "../../permissions.js";
|
|
5
5
|
import { describeChatError } from "./diagnostics.js";
|
|
6
6
|
import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
|
|
7
|
-
import { chatConnection,
|
|
7
|
+
import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
|
|
8
8
|
/**
|
|
9
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 chat through the ontology's chat connection
|
|
11
|
-
* the agent and without attribution. The archive's delivery claim, keyed by the review and not by
|
|
10
|
+
* edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
|
|
11
|
+
* as the agent and without attribution. The archive's delivery claim, keyed by the review and not by
|
|
12
12
|
* the member, makes it at most once: a replay of the same approval returns the delivery, and a
|
|
13
13
|
* different approval, by another member or with another text, is refused. A provider that refused
|
|
14
14
|
* it consumes the claim: the reply is never sent again.
|
|
@@ -62,13 +62,21 @@ export function reviewSender(input) {
|
|
|
62
62
|
: "The reply was already approved; it is never sent again.",
|
|
63
63
|
});
|
|
64
64
|
}
|
|
65
|
-
|
|
66
|
-
|
|
65
|
+
// The channel the chat is on, by name. A review held before channels had names has none:
|
|
66
|
+
// it is on the channel named after its kind.
|
|
67
|
+
// @legacy ontology.reviews-without-channel
|
|
68
|
+
const providerName = typeof review.channel === "string" && review.channel !== ""
|
|
69
|
+
? review.channel
|
|
70
|
+
: String(review.provider);
|
|
71
|
+
const provider = channelProvider(input.ontology.manifest.chat, providerName);
|
|
67
72
|
const connection = chatConnection(input.ontology.manifest.chat, providerName);
|
|
68
|
-
if (provider === undefined ||
|
|
73
|
+
if (provider === undefined ||
|
|
74
|
+
!connection ||
|
|
75
|
+
chatKind(input.ontology.manifest.chat, providerName) !== String(review.provider)) {
|
|
69
76
|
return yield* new ActionRejected({
|
|
70
|
-
message: `Sending a reviewed reply needs chat.${providerName}.connection in defineOntology
|
|
71
|
-
|
|
77
|
+
message: `Sending a reviewed reply needs chat.${providerName}.connection in defineOntology, ` +
|
|
78
|
+
`of kind ${String(review.provider)}: the connection of the bot, number or mailbox ` +
|
|
79
|
+
"the person talks to.",
|
|
72
80
|
});
|
|
73
81
|
}
|
|
74
82
|
const kind = review.chat_kind === "group" ? "group" : "private";
|
|
@@ -8,7 +8,7 @@ import { RequestId, failureResponse } from "../errors.js";
|
|
|
8
8
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
9
9
|
import { identityToken, makeOperations } from "../operations.js";
|
|
10
10
|
import { ChatSearch } from "../agent/chat-archive.js";
|
|
11
|
-
import { listedChatProviders } from "./providers/index.js";
|
|
11
|
+
import { chatKind, listedChatProviders } from "./providers/index.js";
|
|
12
12
|
import { chatReads } from "./reads.js";
|
|
13
13
|
import { withChatMembership } from "./resolve.js";
|
|
14
14
|
import { ChatList, ChatHistory } from "./schemas.js";
|
|
@@ -19,6 +19,7 @@ export function chatRoutes(options) {
|
|
|
19
19
|
const chatHistory = options.chatHistory && withChatMembership(options.chatHistory, backend);
|
|
20
20
|
const reads = chatReads(backend, {
|
|
21
21
|
providers: listedChatProviders(options.built.plan.ontology.manifest.chat),
|
|
22
|
+
kindOf: (channel) => chatKind(options.built.plan.ontology.manifest.chat, channel),
|
|
22
23
|
chatHistory,
|
|
23
24
|
attribution: options.built.plan.ontology.config.chat?.attribution,
|
|
24
25
|
});
|
|
@@ -28,6 +28,7 @@ export declare const ChatDestination: Schema.Struct<{
|
|
|
28
28
|
readonly id: Schema.String;
|
|
29
29
|
readonly title: Schema.String;
|
|
30
30
|
readonly provider: Schema.String;
|
|
31
|
+
readonly kind: Schema.optionalKey<Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email"]>>;
|
|
31
32
|
readonly external_id: Schema.String;
|
|
32
33
|
readonly attribution: Schema.NullOr<Schema.String>;
|
|
33
34
|
}>;
|
|
@@ -36,6 +37,7 @@ export declare const ChatListResult: Schema.Struct<{
|
|
|
36
37
|
readonly id: Schema.String;
|
|
37
38
|
readonly title: Schema.String;
|
|
38
39
|
readonly provider: Schema.String;
|
|
40
|
+
readonly kind: Schema.optionalKey<Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email"]>>;
|
|
39
41
|
readonly external_id: Schema.String;
|
|
40
42
|
readonly attribution: Schema.NullOr<Schema.String>;
|
|
41
43
|
}>>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
2
|
import { ChatPostInput } from "../../chat.js";
|
|
3
|
+
import { CHAT_CHANNEL_KINDS } from "../../chat-channel.js";
|
|
3
4
|
const Id = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512));
|
|
4
5
|
export const ChatPostWire = ChatPostInput.pipe(Schema.encodeKeys({ replyTo: "reply_to", idempotencyKey: "idempotency_key" }));
|
|
5
6
|
export const RuntimeChatPostWire = Schema.Struct({
|
|
@@ -21,7 +22,13 @@ export const ChatHistory = Schema.Struct({
|
|
|
21
22
|
export const ChatDestination = Schema.Struct({
|
|
22
23
|
id: Id,
|
|
23
24
|
title: Schema.String,
|
|
24
|
-
provider: Schema.String
|
|
25
|
+
provider: Schema.String.annotate({
|
|
26
|
+
description: "The agent's channel the chat is on, by its name: its kind for the channel named after " +
|
|
27
|
+
"its kind, such as telegram.",
|
|
28
|
+
}),
|
|
29
|
+
kind: Schema.optionalKey(Schema.Literals(CHAT_CHANNEL_KINDS).annotate({
|
|
30
|
+
description: "The kind of that channel, which decides how a message to the chat renders.",
|
|
31
|
+
})),
|
|
25
32
|
external_id: Id,
|
|
26
33
|
attribution: Schema.NullOr(Schema.String),
|
|
27
34
|
});
|
package/dist/service/config.d.ts
CHANGED
|
@@ -194,6 +194,16 @@ export interface OntologyServiceConfig extends OntologyEnvironment {
|
|
|
194
194
|
readonly webhookVerifier?: import("./webhooks.js").WebhookVerifier;
|
|
195
195
|
/** How registration tokens are compared against backend-held workspace secrets. */
|
|
196
196
|
readonly webhookTokenVerifier?: import("./webhooks.js").WebhookTokenVerifier;
|
|
197
|
+
/**
|
|
198
|
+
* How a new guest's challenge token is checked when `guest.botCheck` asks for one:
|
|
199
|
+
* SegmentStream's backend, which holds the workspace secret, by default. Tests replace it.
|
|
200
|
+
*/
|
|
201
|
+
readonly botCheckVerifier?: import("./agent/bot-check.js").BotCheckVerifier;
|
|
202
|
+
/**
|
|
203
|
+
* How a guest proves an email address: the app's email sign-in, in production, by default. Tests
|
|
204
|
+
* replace it.
|
|
205
|
+
*/
|
|
206
|
+
readonly emailCodes?: import("./agent/guest-sign-up.js").EmailCodes;
|
|
197
207
|
/** How `agentTask` calls the app's agent at `agentOrigin`: `fetch` by default. Tests replace it. */
|
|
198
208
|
readonly agentTaskTransport?: import("./agent/task-start.js").AgentTransport;
|
|
199
209
|
/**
|
|
@@ -14,7 +14,7 @@ import { CONFIRMATION_PREVIEW_METHOD, previewLocale, withoutConfirmation } from
|
|
|
14
14
|
import { consumeChatEnvelope, CurrentChatCall } from "../chat/envelope.js";
|
|
15
15
|
import { ChatList, ChatHistory, ChatPostWire, RuntimeChatPostWire } from "../chat/schemas.js";
|
|
16
16
|
import { ChatPostResult } from "../../chat.js";
|
|
17
|
-
import { listedChatProviders } from "../chat/providers/index.js";
|
|
17
|
+
import { chatKind, listedChatProviders } from "../chat/providers/index.js";
|
|
18
18
|
import { chatReads } from "../chat/reads.js";
|
|
19
19
|
import { withChatMembership } from "../chat/resolve.js";
|
|
20
20
|
import { catalogFor } from "../catalog.js";
|
|
@@ -850,6 +850,7 @@ export function mcpLayer(options) {
|
|
|
850
850
|
const server = {
|
|
851
851
|
chats: chatReads(backend, {
|
|
852
852
|
providers: listedChatProviders(options.built.plan.ontology.manifest.chat),
|
|
853
|
+
kindOf: (channel) => chatKind(options.built.plan.ontology.manifest.chat, channel),
|
|
853
854
|
chatHistory,
|
|
854
855
|
attribution: options.built.plan.ontology.config.chat?.attribution,
|
|
855
856
|
}),
|
|
@@ -118,6 +118,11 @@ export declare function makeOperations(backend: Backend, plan: ApiPlan, hooks: R
|
|
|
118
118
|
readonly principalId: string | null;
|
|
119
119
|
readonly recordId: string;
|
|
120
120
|
readonly actionId: string;
|
|
121
|
+
readonly chat?: {
|
|
122
|
+
readonly chatId: string;
|
|
123
|
+
readonly provider: string;
|
|
124
|
+
readonly sessionId?: string | undefined;
|
|
125
|
+
} | undefined;
|
|
121
126
|
readonly execution?: {
|
|
122
127
|
readonly issuer: string;
|
|
123
128
|
readonly audience: string;
|
|
@@ -284,6 +284,73 @@ export interface AgentWebStore {
|
|
|
284
284
|
* {@link countTurn}. The limit the turn exceeds, or `undefined` when it may run.
|
|
285
285
|
*/
|
|
286
286
|
readonly countGuestTurn?: (guestId: string, limits?: ResolveIdentityInput["limits"]) => Effect.Effect<WebTurnLimit | undefined>;
|
|
287
|
+
/**
|
|
288
|
+
* Adds the model cost of a guest's turn, in US dollars, to that day's spend of the guest and of
|
|
289
|
+
* every guest together, which {@link countGuestTurn} holds against the agent's
|
|
290
|
+
* `limits.guest.usdPerDay` and `workspaceUsdPerDay`. `key` names the report: a report repeated
|
|
291
|
+
* with the same key adds nothing.
|
|
292
|
+
*/
|
|
293
|
+
readonly recordGuestUsage?: (input: {
|
|
294
|
+
readonly guestId: string;
|
|
295
|
+
readonly costUsd: number;
|
|
296
|
+
readonly key: string;
|
|
297
|
+
}) => Effect.Effect<void>;
|
|
298
|
+
/**
|
|
299
|
+
* Counts one attempt of a guest's against a fixed hourly window, such as asking for an email
|
|
300
|
+
* code: the seconds until the next may run once `limit` is exceeded, else `undefined`.
|
|
301
|
+
*/
|
|
302
|
+
readonly countGuestAttempt?: (input: {
|
|
303
|
+
readonly scope: "guestEmailCodesPerHour" | "guestSignUpAttemptsPerHour";
|
|
304
|
+
readonly subject: string;
|
|
305
|
+
readonly limit: number;
|
|
306
|
+
}) => Effect.Effect<number | undefined>;
|
|
307
|
+
/**
|
|
308
|
+
* Makes a guest the user an email address they proved is theirs, by the app's own email sign-in:
|
|
309
|
+
* the user `signUp` created with that address, or a new one `signUp` creates on `email`. The
|
|
310
|
+
* guest's grant becomes the user's, with new access and refresh tokens in place of the guest's.
|
|
311
|
+
* An address another kind of user holds, such as an invited member's, is refused.
|
|
312
|
+
*/
|
|
313
|
+
readonly upgradeGuest?: (input: {
|
|
314
|
+
readonly guestId: string;
|
|
315
|
+
readonly identity: SignInIdentity;
|
|
316
|
+
readonly expiresAt: Date;
|
|
317
|
+
}) => Effect.Effect<GuestUpgrade>;
|
|
318
|
+
/**
|
|
319
|
+
* How the app's email sign-in reaches an address: `code` for one a user holds who signed in with
|
|
320
|
+
* Neon Auth before, whose account receives codes, else `link`.
|
|
321
|
+
*/
|
|
322
|
+
readonly guestEmailMethod?: (email: string) => Effect.Effect<"code" | "link">;
|
|
323
|
+
/**
|
|
324
|
+
* Records a guest's pending sign-up by an emailed link: the address the link must prove, where it
|
|
325
|
+
* returns to, and the hash of the link's nonce, until `expiresAt`.
|
|
326
|
+
*/
|
|
327
|
+
readonly requestGuestLink?: (input: {
|
|
328
|
+
readonly guestId: string;
|
|
329
|
+
readonly email: string;
|
|
330
|
+
readonly returnTo: string | undefined;
|
|
331
|
+
readonly nonceHash: string;
|
|
332
|
+
readonly expiresAt: Date;
|
|
333
|
+
}) => Effect.Effect<void>;
|
|
334
|
+
/**
|
|
335
|
+
* Opens a guest's link once, for the identity the link signed in: it must have proven the very
|
|
336
|
+
* address. Admits that user as {@link upgradeGuest} does, without moving the guest's grant, and
|
|
337
|
+
* records the hash of the single-use handoff that moves it.
|
|
338
|
+
*/
|
|
339
|
+
readonly openGuestLink?: (input: {
|
|
340
|
+
readonly nonceHash: string;
|
|
341
|
+
readonly identity: SignInIdentity;
|
|
342
|
+
readonly handoffHash: string;
|
|
343
|
+
readonly handoffExpiresAt: Date;
|
|
344
|
+
}) => Effect.Effect<GuestLinkOpening>;
|
|
345
|
+
/**
|
|
346
|
+
* Moves a guest's grant to the user their link admitted, with new tokens, for the handoff alone
|
|
347
|
+
* and only for the guest it was minted for: another guest's request is refused, and leaves it.
|
|
348
|
+
*/
|
|
349
|
+
readonly takeGuestHandoff?: (input: {
|
|
350
|
+
readonly handoffHash: string;
|
|
351
|
+
readonly guestId: string;
|
|
352
|
+
readonly expiresAt: Date;
|
|
353
|
+
}) => Effect.Effect<GuestHandoff>;
|
|
287
354
|
/**
|
|
288
355
|
* A new guest of a declared website: a grant to the agent at `resource` that names no user, with
|
|
289
356
|
* its access and refresh tokens. No user or identity is created. `client` keys how many guests one
|
|
@@ -331,6 +398,58 @@ export type GuestIssue = {
|
|
|
331
398
|
} | {
|
|
332
399
|
readonly status: "refused";
|
|
333
400
|
};
|
|
401
|
+
/** A guest who proved an email address, as {@link AgentWebStore.upgradeGuest} answers it. */
|
|
402
|
+
export type GuestUpgrade = {
|
|
403
|
+
readonly status: "upgraded";
|
|
404
|
+
/** The user the guest became. */
|
|
405
|
+
readonly userId: string;
|
|
406
|
+
/** Whether `signUp` created the user now, rather than finding the one it created before. */
|
|
407
|
+
readonly created: boolean;
|
|
408
|
+
readonly token: string;
|
|
409
|
+
readonly refreshToken: string;
|
|
410
|
+
readonly expiresAt: Date;
|
|
411
|
+
}
|
|
412
|
+
/** `signUp` does not list `email`, so a proven address makes nobody a user. */
|
|
413
|
+
| {
|
|
414
|
+
readonly status: "sign_up_closed";
|
|
415
|
+
}
|
|
416
|
+
/** The address is a user's that sign-up did not create, such as an invited member's. */
|
|
417
|
+
| {
|
|
418
|
+
readonly status: "member_address";
|
|
419
|
+
}
|
|
420
|
+
/** The guest is gone, or the user may not sign in. */
|
|
421
|
+
| {
|
|
422
|
+
readonly status: "refused";
|
|
423
|
+
};
|
|
424
|
+
/** A guest's emailed link, opened, as {@link AgentWebStore.openGuestLink} answers it. */
|
|
425
|
+
export type GuestLinkOpening = {
|
|
426
|
+
/** The user is admitted and the handoff recorded. */
|
|
427
|
+
readonly status: "handed_off";
|
|
428
|
+
readonly returnTo: string | undefined;
|
|
429
|
+
readonly created: boolean;
|
|
430
|
+
}
|
|
431
|
+
/** No pending link has the nonce, it was opened or expired, or it proves another address. */
|
|
432
|
+
| {
|
|
433
|
+
readonly status: "link_invalid";
|
|
434
|
+
readonly returnTo?: string | undefined;
|
|
435
|
+
} | {
|
|
436
|
+
readonly status: "sign_up_closed" | "member_address" | "refused";
|
|
437
|
+
readonly returnTo: string | undefined;
|
|
438
|
+
};
|
|
439
|
+
/** A handoff taken, as {@link AgentWebStore.takeGuestHandoff} answers it. */
|
|
440
|
+
export type GuestHandoff = Extract<GuestUpgrade, {
|
|
441
|
+
readonly status: "upgraded";
|
|
442
|
+
}>
|
|
443
|
+
/** No handoff has the secret, or it was taken or expired. */
|
|
444
|
+
| {
|
|
445
|
+
readonly status: "handoff_invalid";
|
|
446
|
+
}
|
|
447
|
+
/** The handoff is another guest's: a link opened in another browser hands nothing to it. */
|
|
448
|
+
| {
|
|
449
|
+
readonly status: "handoff_other_browser";
|
|
450
|
+
} | {
|
|
451
|
+
readonly status: "refused";
|
|
452
|
+
};
|
|
334
453
|
/** The limit a member's turn on the web exceeds, and when the next one may run. */
|
|
335
454
|
export interface WebTurnLimit {
|
|
336
455
|
readonly scope: AgentLimitScope;
|
|
@@ -353,9 +472,13 @@ export interface AgentLimits {
|
|
|
353
472
|
readonly guest: {
|
|
354
473
|
readonly turnsPerDay: number;
|
|
355
474
|
readonly workspaceTurnsPerDay: number;
|
|
475
|
+
/** The model cost each guest's turns may reach a day, in US dollars; no cap when absent. */
|
|
476
|
+
readonly usdPerDay?: number;
|
|
477
|
+
/** The model cost every guest's turns together may reach a day; no cap when absent. */
|
|
478
|
+
readonly workspaceUsdPerDay?: number;
|
|
356
479
|
};
|
|
357
480
|
}
|
|
358
|
-
export type AgentLimitScope = "turnsPerMinute" | "turnsPerDay" | "newUsersPerHour" | "workspaceTurnsPerDay" | "guestTurnsPerDay" | "guestWorkspaceTurnsPerDay" | "newGuestsPerHour";
|
|
481
|
+
export type AgentLimitScope = "turnsPerMinute" | "turnsPerDay" | "newUsersPerHour" | "workspaceTurnsPerDay" | "guestTurnsPerDay" | "guestWorkspaceTurnsPerDay" | "guestUsdPerDay" | "guestWorkspaceUsdPerDay" | "newGuestsPerHour" | "guestEmailCodesPerHour" | "guestSignUpAttemptsPerHour";
|
|
359
482
|
export interface ResolveIdentityInput {
|
|
360
483
|
readonly provider: string;
|
|
361
484
|
readonly externalId: string;
|
|
@@ -476,6 +599,12 @@ export interface AgentStore {
|
|
|
476
599
|
readonly member: (userId: string) => Effect.Effect<AgentMember | undefined>;
|
|
477
600
|
/** The member a runtime caller acts for: active, and with a live identity. */
|
|
478
601
|
readonly actingMember: (userId: string, provider?: string) => Effect.Effect<Principal | undefined>;
|
|
602
|
+
/**
|
|
603
|
+
* The kind of the agent's channel `name`, as the ontology's `chat` declares it: the name itself
|
|
604
|
+
* for the channel named after its kind, such as `telegram`; `undefined` for another name it does
|
|
605
|
+
* not declare. Without it, every channel is taken for the one named after its kind.
|
|
606
|
+
*/
|
|
607
|
+
readonly channelKind?: (name: string) => string | undefined;
|
|
479
608
|
/**
|
|
480
609
|
* Records a message the agent saw in a group chat: creates the `agent_chat` or keeps its title
|
|
481
610
|
* current, records when the chat last had a message (at most every 15 minutes, so that history
|
|
@@ -507,7 +636,10 @@ export interface AgentStore {
|
|
|
507
636
|
/** A reply the agent held for review, as `POST /api/ontology/agent/reviews` reports it. */
|
|
508
637
|
export interface HeldReplyInput {
|
|
509
638
|
readonly key: string;
|
|
639
|
+
/** The kind of channel the chat is on, such as whatsapp. */
|
|
510
640
|
readonly provider: string;
|
|
641
|
+
/** The channel the chat is on, by name: its kind for the channel named after its kind. */
|
|
642
|
+
readonly channel: string;
|
|
511
643
|
readonly chatId: string;
|
|
512
644
|
/** Whom the provider sends the reply to: the chat's id, or the person's id where it differs. */
|
|
513
645
|
readonly recipient: string;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Effect, Redacted } from "effect";
|
|
2
2
|
import type { HttpServerRequest } from "effect/unstable/http";
|
|
3
3
|
import { type JWTVerifyGetKey } from "jose";
|
|
4
|
+
import type { ChatProvenance } from "../runtime.js";
|
|
4
5
|
/**
|
|
5
6
|
* The header in which a runtime caller names the member it acts for: the member's user id. The
|
|
6
7
|
* service honours it only with a verified runtime token, so nobody else can claim a member with it.
|
|
@@ -12,6 +13,23 @@ export declare const ACT_AS_HEADER = "x-segmentstream-act-as";
|
|
|
12
13
|
* workflow user, on `/mcp` and the task routes only; every other route refuses it.
|
|
13
14
|
*/
|
|
14
15
|
export declare const AGENT_TASK_HEADER = "x-segmentstream-agent-task";
|
|
16
|
+
/**
|
|
17
|
+
* The chat a runtime request comes from, `<provider>:<chat id>` as the chat archive names it, and
|
|
18
|
+
* the agent's session there. The app's agent names them on its attachment routes, and on every
|
|
19
|
+
* request it acts in a chat with, so that history keeps the chat an action came from.
|
|
20
|
+
*/
|
|
21
|
+
export declare const CHAT_HEADER = "x-segmentstream-agent-chat";
|
|
22
|
+
export declare const SESSION_HEADER = "x-segmentstream-agent-session";
|
|
23
|
+
/** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
|
|
24
|
+
export declare const EARLIER_CHAT_HEADER = "x-segmentstream-agent-conversation";
|
|
25
|
+
/**
|
|
26
|
+
* `provider:chat id`. An email chat is a Gmail thread and the person's address
|
|
27
|
+
* (`email:<thread>:<address>`), so an id may hold an address's `@`, `.` and `+`.
|
|
28
|
+
*/
|
|
29
|
+
export declare const CHAT: RegExp;
|
|
30
|
+
export declare const SESSION: RegExp;
|
|
31
|
+
/** The chat and session a request names, or `undefined` without a well-formed chat. */
|
|
32
|
+
export declare function requestChat(request: HttpServerRequest.HttpServerRequest): ChatProvenance | undefined;
|
|
15
33
|
/**
|
|
16
34
|
* Whom the service trusts as its runtime caller: Vercel OIDC tokens of the functions of this
|
|
17
35
|
* deployment's own project. The app's agent is a service of the same Vercel project as the ontology
|
|
@@ -74,6 +92,11 @@ export interface RuntimeCredential {
|
|
|
74
92
|
readonly agentTask?: Redacted.Redacted<string>;
|
|
75
93
|
/** The grant in `X-SegmentStream-Agent-Grant`; `undefined` without the header. */
|
|
76
94
|
readonly grant?: string;
|
|
95
|
+
/**
|
|
96
|
+
* The chat in `X-SegmentStream-Agent-Chat` and the session in `X-SegmentStream-Agent-Session`;
|
|
97
|
+
* trusted only once the runtime token is verified, and only as the chat the member acts in.
|
|
98
|
+
*/
|
|
99
|
+
readonly chat?: ChatProvenance;
|
|
77
100
|
}
|
|
78
101
|
/** The task secret a request presents; `undefined` without the header. */
|
|
79
102
|
export declare function agentTaskSecret(request: HttpServerRequest.HttpServerRequest): Redacted.Redacted<string> | undefined;
|
|
@@ -11,6 +11,35 @@ export const ACT_AS_HEADER = "x-segmentstream-act-as";
|
|
|
11
11
|
* workflow user, on `/mcp` and the task routes only; every other route refuses it.
|
|
12
12
|
*/
|
|
13
13
|
export const AGENT_TASK_HEADER = "x-segmentstream-agent-task";
|
|
14
|
+
/**
|
|
15
|
+
* The chat a runtime request comes from, `<provider>:<chat id>` as the chat archive names it, and
|
|
16
|
+
* the agent's session there. The app's agent names them on its attachment routes, and on every
|
|
17
|
+
* request it acts in a chat with, so that history keeps the chat an action came from.
|
|
18
|
+
*/
|
|
19
|
+
export const CHAT_HEADER = "x-segmentstream-agent-chat";
|
|
20
|
+
export const SESSION_HEADER = "x-segmentstream-agent-session";
|
|
21
|
+
/** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
|
|
22
|
+
export const EARLIER_CHAT_HEADER = "x-segmentstream-agent-conversation";
|
|
23
|
+
/**
|
|
24
|
+
* `provider:chat id`. An email chat is a Gmail thread and the person's address
|
|
25
|
+
* (`email:<thread>:<address>`), so an id may hold an address's `@`, `.` and `+`.
|
|
26
|
+
*/
|
|
27
|
+
export const CHAT = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_.@+-]{1,320}$/;
|
|
28
|
+
export const SESSION = /^[A-Za-z0-9:_.-]{1,200}$/;
|
|
29
|
+
/** The chat and session a request names, or `undefined` without a well-formed chat. */
|
|
30
|
+
export function requestChat(request) {
|
|
31
|
+
const chat = (request.headers[CHAT_HEADER] ?? request.headers[EARLIER_CHAT_HEADER])?.trim() ?? "";
|
|
32
|
+
const session = request.headers[SESSION_HEADER]?.trim() ?? "";
|
|
33
|
+
if (!CHAT.test(chat) || (session !== "" && !SESSION.test(session))) {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
const colon = chat.indexOf(":");
|
|
37
|
+
return {
|
|
38
|
+
provider: chat.slice(0, colon),
|
|
39
|
+
chatId: chat.slice(colon + 1),
|
|
40
|
+
...(session === "" ? {} : { sessionId: session }),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
14
43
|
const CLOCK_TOLERANCE_SECONDS = 5;
|
|
15
44
|
const JWKS_TIMEOUT_MS = 5_000;
|
|
16
45
|
/** The environment that a Vercel function token must name: channels run only in production. */
|
|
@@ -122,11 +151,13 @@ export function runtimeCredential(verify, request) {
|
|
|
122
151
|
const provider = request.headers[ACT_AS_PROVIDER_HEADER]?.trim();
|
|
123
152
|
const agentTask = agentTaskSecret(request);
|
|
124
153
|
const grant = request.headers[AGENT_GRANT_HEADER]?.trim();
|
|
154
|
+
const chat = requestChat(request);
|
|
125
155
|
return {
|
|
126
156
|
verify,
|
|
127
157
|
actAs: actAs === undefined || actAs === "" ? undefined : actAs,
|
|
128
158
|
...(provider ? { provider } : {}),
|
|
129
159
|
...(agentTask === undefined ? {} : { agentTask }),
|
|
130
160
|
...(grant ? { grant } : {}),
|
|
161
|
+
...(chat === undefined ? {} : { chat }),
|
|
131
162
|
};
|
|
132
163
|
}
|