@segmentstream/ontology 0.174.1 → 0.176.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 +23 -0
- package/dist/agent-chat.d.ts +9 -0
- package/dist/agent-chat.js +31 -0
- package/dist/email.d.ts +34 -0
- package/dist/email.js +11 -0
- package/dist/runtime/agents.js +10 -0
- package/dist/service/agent/server.js +88 -7
- package/dist/service/chat/draft-files.js +3 -0
- package/dist/service/chat/providers/email.js +119 -10
- package/dist/service/runtime-contract.d.ts +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.176.0
|
|
4
|
+
|
|
5
|
+
The ontology's replies to mail, a draft a member approves and a staff reply from the inbox, are
|
|
6
|
+
handed to the agent's email channel of the chat's name, which sends them as its own replies: in the
|
|
7
|
+
thread, from the mailbox, keyed so a lost answer is never sent twice, and signed and quoted by the
|
|
8
|
+
channel's `signature` and `quote`, so every reply from the mailbox looks the same. The reply's files
|
|
9
|
+
go by short-lived links to the workspace's file storage, checked against the revision the draft
|
|
10
|
+
holds before anything is reserved; the channel refuses a file whose size differs and sends nothing.
|
|
11
|
+
The channel serves this at `POST /eve/segmentstream/v1/email/<name>/deliver`, for the deployment's
|
|
12
|
+
own functions only.
|
|
13
|
+
|
|
14
|
+
An agent from before the route answers 404, and the ontology sends the reply from the mailbox
|
|
15
|
+
itself, as before: signed by `signature` on its `chat` entry and never quoted.
|
|
16
|
+
|
|
17
|
+
Action required: upgrade `@segmentstream/agent` together with `@segmentstream/ontology`, and set
|
|
18
|
+
`signature` (and `quote`, if wanted) on `channels.email` in `agent/segmentstream.json`. The
|
|
19
|
+
ontology's `chat.email.signature` now signs only replies sent for an agent from before the route; it
|
|
20
|
+
is deprecated and stops working on 2027-05-27.
|
|
21
|
+
|
|
22
|
+
## 0.175.0
|
|
23
|
+
|
|
24
|
+
Allow workspace operators to enable bounded, tool-free answers to unlinked senders in individual Telegram and Slack group chats. Dedicated connections can use a verified inviter's existing permission to open a newly joined group.
|
|
25
|
+
|
|
3
26
|
## 0.174.1
|
|
4
27
|
|
|
5
28
|
Telegram messages, edits and delivery receipts keep the bot account that received or sent them.
|
package/dist/agent-chat.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
|
|
|
17
17
|
readonly lastMessageAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
18
18
|
readonly handoffAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
19
19
|
readonly handoffReason: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
20
|
+
readonly groupAccess: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
20
21
|
readonly personaNoticeAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
21
22
|
readonly agentPersona: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
22
23
|
readonly purpose: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
@@ -25,6 +26,13 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
|
|
|
25
26
|
readonly members: import("./relationship.js").ManyRelationship;
|
|
26
27
|
readonly handledBy: import("./relationship.js").OneRelationship<true, false, "user">;
|
|
27
28
|
}, import("./entity.js").InvocableActions<{
|
|
29
|
+
readonly setAccess: import("./action.js").Action<Schema.Struct<{
|
|
30
|
+
readonly chat: Schema.Codec<string, string, never, never>;
|
|
31
|
+
readonly access: Schema.Literals<readonly ["members", "public"]>;
|
|
32
|
+
readonly expected: Schema.optional<Schema.NullOr<Schema.String>>;
|
|
33
|
+
}>, {
|
|
34
|
+
groupAccess: "members" | "public";
|
|
35
|
+
}>;
|
|
28
36
|
readonly setPersona: import("./action.js").Action<Schema.Struct<{
|
|
29
37
|
readonly chat: Schema.Codec<string, string, never, never>;
|
|
30
38
|
readonly persona: Schema.NullOr<Schema.String>;
|
|
@@ -163,6 +171,7 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
|
|
|
163
171
|
readonly lastMessageAt: string | null;
|
|
164
172
|
readonly handoffAt: string | null;
|
|
165
173
|
readonly handoffReason: string | null;
|
|
174
|
+
readonly groupAccess: string | null;
|
|
166
175
|
readonly personaNoticeAt: string | null;
|
|
167
176
|
readonly agentPersona: string | null;
|
|
168
177
|
readonly purpose: string | null;
|
package/dist/agent-chat.js
CHANGED
|
@@ -86,6 +86,13 @@ export const AgentChat = entity("agent_chat", {
|
|
|
86
86
|
label: "Handoff reason",
|
|
87
87
|
description: "What the agent said the person needs from staff when it handed them over.",
|
|
88
88
|
}),
|
|
89
|
+
groupAccess: p.text({
|
|
90
|
+
optional: true,
|
|
91
|
+
managed: true,
|
|
92
|
+
maxLength: 12,
|
|
93
|
+
label: "Group access",
|
|
94
|
+
description: "Public allows isolated replies to unlinked senders. The default requires a linked account.",
|
|
95
|
+
}),
|
|
89
96
|
personaNoticeAt: p.timestamp({
|
|
90
97
|
optional: true,
|
|
91
98
|
managed: true,
|
|
@@ -132,6 +139,30 @@ export const AgentChat = entity("agent_chat", {
|
|
|
132
139
|
},
|
|
133
140
|
indexes: [{ properties: ["provider", "externalId"], unique: true }],
|
|
134
141
|
}).actions((self) => ({
|
|
142
|
+
setAccess: action({
|
|
143
|
+
description: "Choose who can receive an answer in this group.",
|
|
144
|
+
hints: { destructive: false, irreversible: false, idempotent: true },
|
|
145
|
+
input: Schema.Struct({
|
|
146
|
+
chat: self.ref,
|
|
147
|
+
access: Schema.Literals(["members", "public"]),
|
|
148
|
+
expected: Schema.optional(Schema.NullOr(Schema.String)),
|
|
149
|
+
}),
|
|
150
|
+
handler: ({ input }) => Effect.gen(function* () {
|
|
151
|
+
const chat = yield* self.get(input.chat, { forUpdate: true });
|
|
152
|
+
yield* self.update(chat, { groupAccess: input.access });
|
|
153
|
+
if (chat.kind !== "group") {
|
|
154
|
+
return yield* new ActionRejected({ message: "Choose a group chat." });
|
|
155
|
+
}
|
|
156
|
+
if (chat.groupAccess !== input.access &&
|
|
157
|
+
input.expected !== undefined &&
|
|
158
|
+
(chat.groupAccess ?? null) !== input.expected) {
|
|
159
|
+
return yield* new ActionRejected({
|
|
160
|
+
message: "Group access changed. Reload the chat and try again.",
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
return { groupAccess: input.access };
|
|
164
|
+
}),
|
|
165
|
+
}),
|
|
135
166
|
setPersona: action({
|
|
136
167
|
description: "Assign a deployed persona to this chat and its threads. Pass null to inherit the workspace rules.",
|
|
137
168
|
hints: { destructive: false, irreversible: false, idempotent: true },
|
package/dist/email.d.ts
CHANGED
|
@@ -95,6 +95,40 @@ export interface EmailReply {
|
|
|
95
95
|
}
|
|
96
96
|
/** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
|
|
97
97
|
export declare const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
|
|
98
|
+
/** A reply's key, as {@link EmailReply.replyKey} takes it. */
|
|
99
|
+
export declare const REPLY_KEY: RegExp;
|
|
100
|
+
/**
|
|
101
|
+
* Where the agent's email channel `name` delivers a reply the ontology sends from its mailbox: a
|
|
102
|
+
* draft a member approved or a staff reply from the inbox. The agent renders and sends it as its
|
|
103
|
+
* own replies, with the mailbox's signature and quote, and only the deployment's own functions may
|
|
104
|
+
* call it.
|
|
105
|
+
*/
|
|
106
|
+
export declare function emailDeliverRoute(name: string): string;
|
|
107
|
+
/** One reply for the agent's email channel to send in a thread (`POST` {@link emailDeliverRoute}). */
|
|
108
|
+
export interface EmailDeliver {
|
|
109
|
+
readonly thread_id: string;
|
|
110
|
+
/** Whom the reply goes to, and copies; plain addresses. */
|
|
111
|
+
readonly to: ReadonlyArray<string>;
|
|
112
|
+
readonly cc: ReadonlyArray<string>;
|
|
113
|
+
/** The exact reply, Markdown with the attribution the ontology added. */
|
|
114
|
+
readonly text: string;
|
|
115
|
+
/** The reply's key (`X-SegmentStream-Reply`), so a send after a lost answer is found, not repeated. */
|
|
116
|
+
readonly key: string;
|
|
117
|
+
/** The reply's files, each by a short-lived link to the workspace's file storage. */
|
|
118
|
+
readonly files?: ReadonlyArray<{
|
|
119
|
+
readonly filename: string;
|
|
120
|
+
readonly content_type: string;
|
|
121
|
+
readonly size: number;
|
|
122
|
+
readonly url: string;
|
|
123
|
+
}>;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The agent's answer: `200 { message_id }` once Gmail took the reply. A `4xx` with `{ error }` sent
|
|
127
|
+
* nothing (`404` alone: an agent without the route); anything else may have sent it.
|
|
128
|
+
*/
|
|
129
|
+
export interface EmailDelivered {
|
|
130
|
+
readonly message_id: string | null;
|
|
131
|
+
}
|
|
98
132
|
/**
|
|
99
133
|
* The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
|
|
100
134
|
* a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
|
package/dist/email.js
CHANGED
|
@@ -235,6 +235,17 @@ function fileNameParameter(parameter, filename) {
|
|
|
235
235
|
}
|
|
236
236
|
/** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
|
|
237
237
|
export const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
|
|
238
|
+
/** A reply's key, as {@link EmailReply.replyKey} takes it. */
|
|
239
|
+
export const REPLY_KEY = /^[A-Za-z0-9_-]{1,128}$/;
|
|
240
|
+
/**
|
|
241
|
+
* Where the agent's email channel `name` delivers a reply the ontology sends from its mailbox: a
|
|
242
|
+
* draft a member approved or a staff reply from the inbox. The agent renders and sends it as its
|
|
243
|
+
* own replies, with the mailbox's signature and quote, and only the deployment's own functions may
|
|
244
|
+
* call it.
|
|
245
|
+
*/
|
|
246
|
+
export function emailDeliverRoute(name) {
|
|
247
|
+
return `/eve/segmentstream/v1/email/${name}/deliver`;
|
|
248
|
+
}
|
|
238
249
|
/**
|
|
239
250
|
* The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
|
|
240
251
|
* a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
|
package/dist/runtime/agents.js
CHANGED
|
@@ -612,6 +612,8 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
612
612
|
return true;
|
|
613
613
|
}))
|
|
614
614
|
.pipe(Effect.orDie),
|
|
615
|
+
readGroupAccess: (key) => rows(`SELECT "group_access" FROM ${quoteIdentifier(tableName(AgentChat.name))}
|
|
616
|
+
WHERE "key" = $1 AND "kind" = 'group' AND "handoff_at" IS NULL AND "handled_by_id" IS NULL`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.group_access))),
|
|
615
617
|
readChatPersona: (key) => rows(`SELECT "agent_persona" FROM ${quoteIdentifier(tableName(AgentChat.name))} WHERE "key" = $1`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.agent_persona))),
|
|
616
618
|
seeChat: ({ provider, externalId, title, memberId, leftMemberId, agentLeft, migratedFrom }) => sql
|
|
617
619
|
.withTransaction(Effect.gen(function* () {
|
|
@@ -687,6 +689,7 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
687
689
|
"purpose",
|
|
688
690
|
"when_to_use",
|
|
689
691
|
"agent_persona",
|
|
692
|
+
"group_access",
|
|
690
693
|
"persona_notice_at",
|
|
691
694
|
]) {
|
|
692
695
|
if (nullableText(found[key]) === null && nullableText(old[key]) !== null) {
|
|
@@ -755,6 +758,13 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
755
758
|
}
|
|
756
759
|
}
|
|
757
760
|
if (agentLeft === true) {
|
|
761
|
+
if (chat.group_access != null) {
|
|
762
|
+
yield* runtime.update({
|
|
763
|
+
entity: AgentChat.name,
|
|
764
|
+
id: String(chat.id),
|
|
765
|
+
values: { group_access: null },
|
|
766
|
+
});
|
|
767
|
+
}
|
|
758
768
|
// The agent left: no member is in the chat with it any more. The chat stays; members
|
|
759
769
|
// link again when they write after the agent is back.
|
|
760
770
|
yield* releaseMembers(String(chat.id));
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { chatPersona, chatPersonaNames, deployedChatPersonas } from "../../chat-personas.js";
|
|
2
2
|
import { isAllowed, effectiveScope } from "../../permissions.js";
|
|
3
3
|
import { confirmationCommand } from "./confirmations.js";
|
|
4
|
-
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { Effect, Layer, Redacted, Result, Schema } from "effect";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { Effect, Exit, Layer, Redacted, Result, Schema } from "effect";
|
|
6
6
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
|
7
7
|
import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
|
|
8
8
|
import { isChatChannelKind, WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
|
|
@@ -15,7 +15,7 @@ import { secretHash } from "../oauth/protocol.js";
|
|
|
15
15
|
import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
|
|
16
16
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
17
17
|
import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
18
|
-
import { ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
18
|
+
import { AgentLimitsRequest, ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
19
19
|
import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
|
|
20
20
|
import { issueEvalToken } from "./eval-tokens.js";
|
|
21
21
|
import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
|
|
@@ -733,8 +733,7 @@ export function agentLayer(options) {
|
|
|
733
733
|
}
|
|
734
734
|
// The selector reveals only chat settings. Its row visibility follows the action's scope,
|
|
735
735
|
// including membership traversal, even when the member cannot read the inbox.
|
|
736
|
-
const personaReader = (principal) => {
|
|
737
|
-
const permission = "agent_chat:set_persona";
|
|
736
|
+
const personaReader = (principal, permission = "agent_chat:set_persona") => {
|
|
738
737
|
if (!isAllowed(permission, principal)) {
|
|
739
738
|
return undefined;
|
|
740
739
|
}
|
|
@@ -745,8 +744,8 @@ export function agentLayer(options) {
|
|
|
745
744
|
scopes: scope ? [{ permission: "agent_chat:read", where: scope }] : [],
|
|
746
745
|
};
|
|
747
746
|
};
|
|
748
|
-
const manageableChat = (principal, field, value) => Effect.gen(function* () {
|
|
749
|
-
const reader = personaReader(principal);
|
|
747
|
+
const manageableChat = (principal, field, value, permission = "agent_chat:set_persona") => Effect.gen(function* () {
|
|
748
|
+
const reader = personaReader(principal, permission);
|
|
750
749
|
if (!reader) {
|
|
751
750
|
return undefined;
|
|
752
751
|
}
|
|
@@ -805,7 +804,11 @@ export function agentLayer(options) {
|
|
|
805
804
|
? "guest"
|
|
806
805
|
: "member",
|
|
807
806
|
}, assigned);
|
|
807
|
+
const group = chat.kind === "group" && store.readGroupAccess
|
|
808
|
+
? yield* manageableChat(member, "id", id, "agent_chat:set_access")
|
|
809
|
+
: undefined;
|
|
808
810
|
return json({
|
|
811
|
+
...(group && { groupAccess: group.group_access ?? null }),
|
|
809
812
|
title: chat.title,
|
|
810
813
|
assigned,
|
|
811
814
|
effective: selection.name,
|
|
@@ -848,6 +851,82 @@ export function agentLayer(options) {
|
|
|
848
851
|
return json({ persona: yield* read(decoded.success.key) });
|
|
849
852
|
})));
|
|
850
853
|
}
|
|
854
|
+
if (store.readGroupAccess) {
|
|
855
|
+
yield* router.add("POST", `${AGENT_PATH}/chats/public-invite`, asRuntime((request) => Effect.gen(function* () {
|
|
856
|
+
const requestId = yield* RequestId;
|
|
857
|
+
const decoded = Schema.decodeUnknownResult(Schema.Struct({
|
|
858
|
+
key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)),
|
|
859
|
+
provider: Schema.Literals(["telegram", "slack"]),
|
|
860
|
+
inviter: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
|
|
861
|
+
}))(yield* jsonBody(request), { onExcessProperty: "error" });
|
|
862
|
+
if (Result.isFailure(decoded)) {
|
|
863
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
864
|
+
}
|
|
865
|
+
const { key, provider, inviter } = decoded.success;
|
|
866
|
+
const identity = yield* store.findIdentity({ provider, externalId: inviter });
|
|
867
|
+
const principal = identity && identity.revokedAt === null
|
|
868
|
+
? yield* store.actingMember(identity.userId, provider)
|
|
869
|
+
: undefined;
|
|
870
|
+
const chat = principal
|
|
871
|
+
? yield* manageableChat(principal, "key", key, "agent_chat:set_access")
|
|
872
|
+
: undefined;
|
|
873
|
+
if (!principal || !chat || chat.kind !== "group" || chat.group_access != null) {
|
|
874
|
+
return json({ opened: false });
|
|
875
|
+
}
|
|
876
|
+
const result = yield* Effect.exit(backend.runAction({
|
|
877
|
+
entity: "agent_chat",
|
|
878
|
+
action: "set_access",
|
|
879
|
+
input: { chat: String(chat.id), access: "public", expected: null },
|
|
880
|
+
principal,
|
|
881
|
+
options: {},
|
|
882
|
+
requestId,
|
|
883
|
+
}));
|
|
884
|
+
return json({ opened: Exit.isSuccess(result) });
|
|
885
|
+
})));
|
|
886
|
+
}
|
|
887
|
+
const readAccess = store.readGroupAccess;
|
|
888
|
+
const countPublicTurn = store.web?.countGuestTurn;
|
|
889
|
+
if (readAccess && countPublicTurn) {
|
|
890
|
+
yield* router.add("POST", `${AGENT_PATH}/chats/public-turn`, asRuntime((request) => Effect.gen(function* () {
|
|
891
|
+
const requestId = yield* RequestId;
|
|
892
|
+
const keyPart = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
|
|
893
|
+
const decoded = Schema.decodeUnknownResult(Schema.Struct({
|
|
894
|
+
channel: keyPart,
|
|
895
|
+
chat: keyPart,
|
|
896
|
+
sender: keyPart,
|
|
897
|
+
check: Schema.optionalKey(Schema.Boolean),
|
|
898
|
+
limits: Schema.optionalKey(AgentLimitsRequest),
|
|
899
|
+
}))(yield* jsonBody(request), { onExcessProperty: "error" });
|
|
900
|
+
if (Result.isFailure(decoded)) {
|
|
901
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
902
|
+
}
|
|
903
|
+
const { channel, chat, sender, limits } = decoded.success;
|
|
904
|
+
const access = yield* readAccess(`${channel}:${chat}`);
|
|
905
|
+
if (access !== "public") {
|
|
906
|
+
return json({ status: "closed" });
|
|
907
|
+
}
|
|
908
|
+
if (decoded.success.check) {
|
|
909
|
+
return json({ status: "public" });
|
|
910
|
+
}
|
|
911
|
+
// The same sender shares a guest budget across groups on this connection.
|
|
912
|
+
// The id is for accounting only and never represents a workspace principal.
|
|
913
|
+
const bytes = createHash("sha256")
|
|
914
|
+
.update(JSON.stringify(["group-guest", channel, sender]))
|
|
915
|
+
.digest();
|
|
916
|
+
bytes[6] = (bytes[6] & 15) | 80;
|
|
917
|
+
bytes[8] = (bytes[8] & 63) | 128;
|
|
918
|
+
const hex = bytes.toString("hex");
|
|
919
|
+
const guestId = [
|
|
920
|
+
hex.slice(0, 8),
|
|
921
|
+
hex.slice(8, 12),
|
|
922
|
+
hex.slice(12, 16),
|
|
923
|
+
hex.slice(16, 20),
|
|
924
|
+
hex.slice(20, 32),
|
|
925
|
+
].join("-");
|
|
926
|
+
const limited = yield* countPublicTurn(guestId, limits);
|
|
927
|
+
return json(limited ? { status: "limited" } : { status: "admitted", guestId });
|
|
928
|
+
})));
|
|
929
|
+
}
|
|
851
930
|
yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
|
|
852
931
|
yield* router.add("POST", CHATS_HANDOFF_PATH, asRuntime(handOffChat(store)));
|
|
853
932
|
if (store.chatMessages !== undefined) {
|
|
@@ -915,6 +994,8 @@ export function agentLayer(options) {
|
|
|
915
994
|
yield* router.add("POST", GUEST_SIGN_UP_PATH, guests.signUp);
|
|
916
995
|
// Where an emailed link lands, signed in on the app's origin: a top-level navigation.
|
|
917
996
|
yield* router.add("GET", GUEST_LINK_PATH, guests.link);
|
|
997
|
+
}
|
|
998
|
+
if (websites.guests.length > 0 || readAccess !== undefined) {
|
|
918
999
|
yield* router.add("POST", GUEST_USAGE_PATH, asRuntime(recordGuestUsage(store.web)));
|
|
919
1000
|
}
|
|
920
1001
|
}
|
|
@@ -159,6 +159,9 @@ export function readDraftFiles(input) {
|
|
|
159
159
|
contentType: file.contentType,
|
|
160
160
|
size: file.size,
|
|
161
161
|
bytes,
|
|
162
|
+
// The bytes are checked against the revision before anything is reserved; a provider that
|
|
163
|
+
// has another sender read them, as mail through the agent's channel, grants it a link.
|
|
164
|
+
link: () => Effect.runPromise(blobs.download(file.entity, file.id, file.property, { revisionId: file.revisionId }, member.principal)).then(({ url }) => url),
|
|
162
165
|
});
|
|
163
166
|
}
|
|
164
167
|
return read;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
|
|
3
|
-
import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, withEmailSignature, } from "../../../email.js";
|
|
3
|
+
import { base64Url, emailDeliverRoute, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, withEmailSignature, } from "../../../email.js";
|
|
4
4
|
import { mailboxSignature } from "../../../gmail-send.js";
|
|
5
5
|
import { ActionRejected } from "../../../errors.js";
|
|
6
6
|
import { EMAIL_PATTERN } from "../../../property.js";
|
|
@@ -105,6 +105,97 @@ function signatureOf(input) {
|
|
|
105
105
|
catch: (cause) => cause,
|
|
106
106
|
}).pipe(Effect.catch((cause) => Effect.logWarning("ontology.chat.email_signature_unavailable").pipe(Effect.annotateLogs({ error: describeChatError(cause, (text) => text) }), Effect.as(undefined))));
|
|
107
107
|
}
|
|
108
|
+
/** How long the agent's email channel has to send one reply, files uploaded in chunks included. */
|
|
109
|
+
const AGENT_DELIVER_TIMEOUT_MS = 90_000;
|
|
110
|
+
/**
|
|
111
|
+
* One reply through the agent's email channel (`POST` {@link emailDeliverRoute} on the
|
|
112
|
+
* deployment's production origin, with the service's Vercel OIDC token), never retried: the agent
|
|
113
|
+
* renders it as its own replies, with the mailbox's signature and quote, reads each file by its
|
|
114
|
+
* link and sends it in the thread. Undefined when the agent has no such route (`404`), so the
|
|
115
|
+
* ontology sends it itself. The agent's other `4xx` sent nothing; a timeout, a `5xx` or an answer
|
|
116
|
+
* without its shape may have, and is uncertain.
|
|
117
|
+
*/
|
|
118
|
+
function deliverThroughAgent(input, reply) {
|
|
119
|
+
return Effect.gen(function* () {
|
|
120
|
+
const agent = input.agent;
|
|
121
|
+
const payload = {
|
|
122
|
+
threadId: reply.threadId,
|
|
123
|
+
to: reply.to,
|
|
124
|
+
cc: reply.cc,
|
|
125
|
+
text: input.plainText,
|
|
126
|
+
...(reply.files.length === 0 ? {} : { files: reply.files.map((file) => file.filename) }),
|
|
127
|
+
};
|
|
128
|
+
const failed = (cause) => ({
|
|
129
|
+
payload,
|
|
130
|
+
status: "failed",
|
|
131
|
+
messageId: null,
|
|
132
|
+
url: null,
|
|
133
|
+
cause,
|
|
134
|
+
});
|
|
135
|
+
// Each link is granted just before the reply goes, as the person may still read its file.
|
|
136
|
+
const links = yield* Effect.tryPromise(() => Promise.all(reply.files.map(async (file) => {
|
|
137
|
+
if (file.link === undefined) {
|
|
138
|
+
throw new Error("A file of the reply has no link to read it by.");
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
filename: file.filename,
|
|
142
|
+
content_type: file.contentType,
|
|
143
|
+
size: file.size,
|
|
144
|
+
url: await file.link(),
|
|
145
|
+
};
|
|
146
|
+
}))).pipe(Effect.exit);
|
|
147
|
+
if (links._tag === "Failure") {
|
|
148
|
+
return failed(links.cause);
|
|
149
|
+
}
|
|
150
|
+
const body = {
|
|
151
|
+
thread_id: reply.threadId,
|
|
152
|
+
to: reply.to,
|
|
153
|
+
cc: reply.cc,
|
|
154
|
+
text: input.plainText,
|
|
155
|
+
key: reply.key,
|
|
156
|
+
...(links.value.length === 0 ? {} : { files: links.value }),
|
|
157
|
+
};
|
|
158
|
+
const answered = yield* Effect.tryPromise(async () => {
|
|
159
|
+
const response = await agent.fetch(new Request(new URL(emailDeliverRoute(input.destination.provider), agent.origin), {
|
|
160
|
+
method: "POST",
|
|
161
|
+
headers: {
|
|
162
|
+
authorization: `Bearer ${agent.identityToken}`,
|
|
163
|
+
"content-type": "application/json",
|
|
164
|
+
},
|
|
165
|
+
body: JSON.stringify(body),
|
|
166
|
+
signal: AbortSignal.timeout(AGENT_DELIVER_TIMEOUT_MS),
|
|
167
|
+
}));
|
|
168
|
+
return { status: response.status, text: await response.text() };
|
|
169
|
+
}).pipe(Effect.exit);
|
|
170
|
+
if (answered._tag === "Failure") {
|
|
171
|
+
return { payload, status: "uncertain", messageId: null, url: null, cause: answered.cause };
|
|
172
|
+
}
|
|
173
|
+
const { status, text } = answered.value;
|
|
174
|
+
if (status === 404) {
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
let answer = {};
|
|
178
|
+
try {
|
|
179
|
+
answer = record(JSON.parse(text));
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
// The status still says what happened; the body only adds the message's id.
|
|
183
|
+
}
|
|
184
|
+
if (status >= 400 && status < 500) {
|
|
185
|
+
return failed(new Error(`The agent's email channel refused the reply (${typeof answer.error === "string" ? answer.error : `status ${status}`}).`));
|
|
186
|
+
}
|
|
187
|
+
const id = answer.message_id;
|
|
188
|
+
return status >= 200 && status < 300 && typeof id === "string" && GMAIL_ID.test(id)
|
|
189
|
+
? { payload, status: "sent", messageId: id, url: null }
|
|
190
|
+
: {
|
|
191
|
+
payload,
|
|
192
|
+
status: "uncertain",
|
|
193
|
+
messageId: null,
|
|
194
|
+
url: null,
|
|
195
|
+
cause: new Error(`The agent's email channel answered with status ${status}.`),
|
|
196
|
+
};
|
|
197
|
+
});
|
|
198
|
+
}
|
|
108
199
|
/**
|
|
109
200
|
* One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
|
|
110
201
|
* its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
|
|
@@ -130,6 +221,33 @@ export function sendEmail(input) {
|
|
|
130
221
|
if (threadId === null || !GMAIL_ID.test(threadId)) {
|
|
131
222
|
return failed(new Error("An email reply needs the Gmail thread it answers."));
|
|
132
223
|
}
|
|
224
|
+
// The agent's reply, as the email channel sends its own: marked as a program's, so no
|
|
225
|
+
// autoresponder answers it, and named by its review, or by the post's own operation, so the
|
|
226
|
+
// channel knows it for the workspace's and never records it again as staff's mail.
|
|
227
|
+
const key = input.operationId !== undefined && input.operationId !== input.destination.id
|
|
228
|
+
? `post-${input.operationId}`
|
|
229
|
+
: `review-${input.destination.id}`;
|
|
230
|
+
const to = input.recipients?.to ?? [input.destination.external_id];
|
|
231
|
+
const cc = input.recipients?.cc ?? [];
|
|
232
|
+
const sendFiles = input.files ?? [];
|
|
233
|
+
// The agent's email channel renders and sends it as its own replies, signature and quote
|
|
234
|
+
// included; an agent from before its deliver route answers 404, and the mailbox is used here.
|
|
235
|
+
if (input.agent?.origin !== undefined && input.agent.identityToken !== undefined) {
|
|
236
|
+
const delivered = yield* deliverThroughAgent(input, {
|
|
237
|
+
threadId,
|
|
238
|
+
to,
|
|
239
|
+
cc,
|
|
240
|
+
key,
|
|
241
|
+
files: sendFiles,
|
|
242
|
+
});
|
|
243
|
+
if (delivered !== undefined) {
|
|
244
|
+
return delivered;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// @legacy ontology.email-own-sender The ontology's own mail sender, for an agent without the
|
|
248
|
+
// email channel's deliver route: the files' bytes, read and checked before the reply was
|
|
249
|
+
// reserved, go in its message.
|
|
250
|
+
const files = sendFiles;
|
|
133
251
|
// The headers read with the reply's people, or else the thread as it is now.
|
|
134
252
|
const thread = input.thread !== undefined
|
|
135
253
|
? undefined
|
|
@@ -157,19 +275,10 @@ export function sendEmail(input) {
|
|
|
157
275
|
const messages = thread?._tag === "Success" ? record(parse(thread.value.body)).messages : [];
|
|
158
276
|
return (Array.isArray(messages) ? messages : []).filter((message) => !labelsOf(message).includes("DRAFT"));
|
|
159
277
|
})());
|
|
160
|
-
// The agent's reply, as the email channel sends its own: marked as a program's, so no
|
|
161
|
-
// autoresponder answers it, and named by its review, or by the post's own operation, so the
|
|
162
|
-
// channel knows it for the workspace's and never records it again as staff's mail.
|
|
163
|
-
const key = input.operationId !== undefined && input.operationId !== input.destination.id
|
|
164
|
-
? `post-${input.operationId}`
|
|
165
|
-
: `review-${input.destination.id}`;
|
|
166
278
|
// With the channel's `signature`, the HTML ends with the mailbox's own signature.
|
|
167
279
|
const html = input.signature === true
|
|
168
280
|
? withEmailSignature(input.finalText, yield* signatureOf(input))
|
|
169
281
|
: input.finalText;
|
|
170
|
-
const to = input.recipients?.to ?? [input.destination.external_id];
|
|
171
|
-
const cc = input.recipients?.cc ?? [];
|
|
172
|
-
const files = input.files ?? [];
|
|
173
282
|
const raw = emailReplyMessage({
|
|
174
283
|
to,
|
|
175
284
|
...(cc.length === 0 ? {} : { cc }),
|
|
@@ -685,6 +685,7 @@ export interface AgentStore {
|
|
|
685
685
|
* it has none. Concurrent calls for one chat leave one record.
|
|
686
686
|
*/
|
|
687
687
|
readonly claimChatPersonaNotice?: (id: string, memberId: string) => Effect.Effect<boolean>;
|
|
688
|
+
readonly readGroupAccess?: (key: string) => Effect.Effect<string | null>;
|
|
688
689
|
readonly readChatPersona?: (key: string) => Effect.Effect<string | null>;
|
|
689
690
|
readonly seeChat: (input: {
|
|
690
691
|
readonly provider: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.176.0",
|
|
4
4
|
"description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "SegmentStream",
|