@segmentstream/ontology 0.161.0 → 0.162.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 +18 -0
- package/dist/agent-draft.d.ts +21 -0
- package/dist/agent-draft.js +57 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/runtime/agents.js +6 -1
- package/dist/service/agent/protocol.d.ts +20 -5
- package/dist/service/agent/protocol.js +25 -3
- package/dist/service/agent/server.d.ts +3 -0
- package/dist/service/agent/server.js +103 -4
- package/dist/service/chat/archive.d.ts +15 -1
- package/dist/service/chat/draft-files.d.ts +56 -0
- package/dist/service/chat/draft-files.js +137 -0
- package/dist/service/chat/idempotency.d.ts +6 -1
- package/dist/service/chat/idempotency.js +7 -1
- package/dist/service/chat/providers/custom.js +12 -2
- package/dist/service/chat/providers/email.d.ts +2 -1
- package/dist/service/chat/providers/email.js +48 -4
- package/dist/service/chat/providers/provider.d.ts +49 -1
- package/dist/service/chat/providers/provider.js +18 -1
- package/dist/service/chat/review-delivery.d.ts +2 -0
- package/dist/service/chat/review-delivery.js +73 -4
- package/dist/service/chat/store-delivery.js +13 -0
- package/dist/service/runtime-contract.d.ts +3 -0
- package/dist/service/service.js +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.162.0
|
|
4
|
+
|
|
5
|
+
A draft can carry record files. `agent_draft.files` lists each file the reply carries as
|
|
6
|
+
`{ entity, id, property, revisionId, filename, contentType, size }`: the revision its person could
|
|
7
|
+
read when the agent held the reply, snapshotted by `POST /api/ontology/agent/drafts` from its new
|
|
8
|
+
`files` (up to 10 record references, read as that person). A draft of files alone has empty text.
|
|
9
|
+
`POST /api/ontology/agent/drafts/files` runs the same check without holding anything, for the
|
|
10
|
+
agent to ask before it promises a file in a reviewed chat.
|
|
11
|
+
|
|
12
|
+
Approving a draft sends its files with the text in the reply's one delivery, each at the revision
|
|
13
|
+
held and read again as the person: by email in the reply's one message (`EMAIL_FILES_BYTES`), and
|
|
14
|
+
through a workspace channel in the `files` of its one `send`. Before anything is reserved, approval
|
|
15
|
+
refuses with the action's `refusal`: `files_unsupported` (the channel sends no files with a reply
|
|
16
|
+
yet, as Telegram, Slack and WhatsApp until a later release, or the chat is still on the archive in
|
|
17
|
+
Cloud), `too_many_files`, `file_too_large` or `file_unavailable`. The delivery binds the files'
|
|
18
|
+
revisions, and the reply's row of the chat store lists them by name, type and size. Chat providers
|
|
19
|
+
declare their `files` limits and a `refuseFiles` check, and `ChatSend` takes `files`.
|
|
20
|
+
|
|
3
21
|
## 0.161.0
|
|
4
22
|
|
|
5
23
|
Agent drafts name their turn, know whether the person wrote after it, and are decided once.
|
package/dist/agent-draft.d.ts
CHANGED
|
@@ -46,6 +46,23 @@ export declare const AGENT_DRAFT_MODES: readonly [{
|
|
|
46
46
|
}];
|
|
47
47
|
/** The longest reply a draft holds; a provider may accept less in one message. */
|
|
48
48
|
export declare const AGENT_DRAFT_TEXT_LIMIT = 20000;
|
|
49
|
+
/** The most files a draft holds, as many as `attachments_send` sends at once. */
|
|
50
|
+
export declare const AGENT_DRAFT_FILES_LIMIT = 10;
|
|
51
|
+
/**
|
|
52
|
+
* A record file a draft holds, snapshotted when the reply was held: the revision the person may
|
|
53
|
+
* read, which approval sends whatever the record holds by then, with what the inbox shows of it.
|
|
54
|
+
*/
|
|
55
|
+
export interface AgentDraftFile {
|
|
56
|
+
readonly entity: string;
|
|
57
|
+
readonly id: string;
|
|
58
|
+
readonly property: string;
|
|
59
|
+
readonly revisionId: string;
|
|
60
|
+
readonly filename: string;
|
|
61
|
+
readonly contentType: string;
|
|
62
|
+
readonly size: number;
|
|
63
|
+
}
|
|
64
|
+
/** The files a draft holds, in order; none for a value that is no list of them. */
|
|
65
|
+
export declare function draftFilesOf(value: unknown): ReadonlyArray<AgentDraftFile>;
|
|
49
66
|
/** The longest reason a member gives for rejecting a reply. */
|
|
50
67
|
export declare const AGENT_DRAFT_REASON_LIMIT = 2000;
|
|
51
68
|
/** The most drafts one `newer` call answers for. */
|
|
@@ -79,6 +96,7 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
|
|
|
79
96
|
readonly basis: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
80
97
|
readonly message: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
81
98
|
readonly draft: import("./property.js").Property<string, false, false>;
|
|
99
|
+
readonly files: Schema.optionalKey<import("./property.js").Property<Schema.Json, false, false>>;
|
|
82
100
|
readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
83
101
|
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed", false, false>;
|
|
84
102
|
readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
|
|
@@ -162,6 +180,7 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
|
|
|
162
180
|
readonly basis: string | null;
|
|
163
181
|
readonly message: string | null;
|
|
164
182
|
readonly draft: string;
|
|
183
|
+
readonly files: Schema.Json;
|
|
165
184
|
readonly text: string | null;
|
|
166
185
|
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed";
|
|
167
186
|
readonly mode: "always" | "whenUnsure";
|
|
@@ -197,6 +216,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
|
|
|
197
216
|
readonly basis: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
198
217
|
readonly message: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
199
218
|
readonly draft: import("./property.js").Property<string, false, false>;
|
|
219
|
+
readonly files: Schema.optionalKey<import("./property.js").Property<Schema.Json, false, false>>;
|
|
200
220
|
readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
201
221
|
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed", false, false>;
|
|
202
222
|
readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
|
|
@@ -280,6 +300,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
|
|
|
280
300
|
readonly basis: string | null;
|
|
281
301
|
readonly message: string | null;
|
|
282
302
|
readonly draft: string;
|
|
303
|
+
readonly files: Schema.Json;
|
|
283
304
|
readonly text: string | null;
|
|
284
305
|
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded" | "dismissed";
|
|
285
306
|
readonly mode: "always" | "whenUnsure";
|
package/dist/agent-draft.js
CHANGED
|
@@ -48,6 +48,55 @@ export const AGENT_DRAFT_MODES = [
|
|
|
48
48
|
];
|
|
49
49
|
/** The longest reply a draft holds; a provider may accept less in one message. */
|
|
50
50
|
export const AGENT_DRAFT_TEXT_LIMIT = 20_000;
|
|
51
|
+
/** The most files a draft holds, as many as `attachments_send` sends at once. */
|
|
52
|
+
export const AGENT_DRAFT_FILES_LIMIT = 10;
|
|
53
|
+
const NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
54
|
+
const RECORD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
55
|
+
/** The files a draft holds, in order; none for a value that is no list of them. */
|
|
56
|
+
export function draftFilesOf(value) {
|
|
57
|
+
const list = typeof value === "string" ? parsed(value) : value;
|
|
58
|
+
if (!Array.isArray(list)) {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
return list.flatMap((item) => {
|
|
62
|
+
const file = item;
|
|
63
|
+
return file !== null &&
|
|
64
|
+
typeof file === "object" &&
|
|
65
|
+
typeof file.entity === "string" &&
|
|
66
|
+
NAME.test(file.entity) &&
|
|
67
|
+
typeof file.id === "string" &&
|
|
68
|
+
RECORD_ID.test(file.id) &&
|
|
69
|
+
typeof file.property === "string" &&
|
|
70
|
+
NAME.test(file.property) &&
|
|
71
|
+
typeof file.revisionId === "string" &&
|
|
72
|
+
file.revisionId !== "" &&
|
|
73
|
+
typeof file.filename === "string" &&
|
|
74
|
+
typeof file.contentType === "string" &&
|
|
75
|
+
typeof file.size === "number" &&
|
|
76
|
+
Number.isSafeInteger(file.size) &&
|
|
77
|
+
file.size >= 0
|
|
78
|
+
? [
|
|
79
|
+
{
|
|
80
|
+
entity: file.entity,
|
|
81
|
+
id: file.id.toLowerCase(),
|
|
82
|
+
property: file.property,
|
|
83
|
+
revisionId: file.revisionId,
|
|
84
|
+
filename: file.filename,
|
|
85
|
+
contentType: file.contentType,
|
|
86
|
+
size: file.size,
|
|
87
|
+
},
|
|
88
|
+
]
|
|
89
|
+
: [];
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function parsed(text) {
|
|
93
|
+
try {
|
|
94
|
+
return JSON.parse(text);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
51
100
|
/** The longest reason a member gives for rejecting a reply. */
|
|
52
101
|
export const AGENT_DRAFT_REASON_LIMIT = 2_000;
|
|
53
102
|
/** The most drafts one `newer` call answers for. */
|
|
@@ -207,7 +256,14 @@ export const AgentDraft = entity("agent_draft", {
|
|
|
207
256
|
managed: true,
|
|
208
257
|
maxLength: AGENT_DRAFT_TEXT_LIMIT,
|
|
209
258
|
display: "multiline",
|
|
210
|
-
description: "The reply as the agent wrote it, in Markdown.",
|
|
259
|
+
description: "The reply as the agent wrote it, in Markdown; empty when the reply is only its files.",
|
|
260
|
+
}),
|
|
261
|
+
files: p.json({
|
|
262
|
+
optional: true,
|
|
263
|
+
managed: true,
|
|
264
|
+
description: "Record files the reply carries, in order, which approval sends with its text: each " +
|
|
265
|
+
"{ entity, id, property, revisionId, filename, contentType, size }, the revision the " +
|
|
266
|
+
"person could read when the reply was held. Empty when the reply is text alone.",
|
|
211
267
|
}),
|
|
212
268
|
text: p.text({
|
|
213
269
|
optional: true,
|
package/dist/index.d.ts
CHANGED
|
@@ -59,7 +59,7 @@ export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, Batc
|
|
|
59
59
|
export { User } from "./user.js";
|
|
60
60
|
export type { UserHandle, UserMemberWrites } from "./user.js";
|
|
61
61
|
export { AgentChat } from "./agent-chat.js";
|
|
62
|
-
export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_NEWER_LIMIT, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT, AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-draft.js";
|
|
62
|
+
export { AgentDraft, AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_MODES, AGENT_DRAFT_NEWER_LIMIT, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT, AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, draftFilesOf, type AgentDraftFile, } from "./agent-draft.js";
|
|
63
63
|
export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
|
|
64
64
|
export type { AttachableIdentityProvider, UserIdentityOrigin } from "./user-identity.js";
|
|
65
65
|
export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
|
package/dist/index.js
CHANGED
|
@@ -34,9 +34,9 @@ export { EMAIL_MARKUP_VALUES, isEmailDocument, unsafeEmailHtml } from "./emails.
|
|
|
34
34
|
export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
|
|
35
35
|
export { User } from "./user.js";
|
|
36
36
|
export { AgentChat } from "./agent-chat.js";
|
|
37
|
-
export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_NEWER_LIMIT, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT,
|
|
37
|
+
export { AgentDraft, AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_MODES, AGENT_DRAFT_NEWER_LIMIT, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT,
|
|
38
38
|
// @legacy ontology.agent-review-entity-name
|
|
39
|
-
AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-draft.js";
|
|
39
|
+
AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, draftFilesOf, } from "./agent-draft.js";
|
|
40
40
|
export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
|
|
41
41
|
export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
|
|
42
42
|
export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatTemplateMedia, ChatPostResult, } from "./chat.js";
|
package/dist/runtime/agents.js
CHANGED
|
@@ -6,7 +6,7 @@ import { action } from "../action.js";
|
|
|
6
6
|
import { AgentChat, agentChatKey } from "../agent-chat.js";
|
|
7
7
|
import { chatChannelKind } from "../chat-channel.js";
|
|
8
8
|
import { historyTableName, quoteIdentifier, tableName } from "../migrate/storage.js";
|
|
9
|
-
import { addressesOfDraft, AgentDraft, participantsOfDraft, draftAddresses, draftParticipants, } from "../agent-draft.js";
|
|
9
|
+
import { addressesOfDraft, AgentDraft, participantsOfDraft, draftAddresses, draftFilesOf, draftParticipants, } from "../agent-draft.js";
|
|
10
10
|
import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
|
|
11
11
|
import { inboxChannelsOf, inboxRolesOf, takeoverChannelsOf, takeoverProvidersOf, } from "../manifest.js";
|
|
12
12
|
import { GUEST_ROLE } from "../names.js";
|
|
@@ -302,6 +302,7 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
302
302
|
? null
|
|
303
303
|
: yield* turnBasis(input.channel, input.chatId, input.turnId),
|
|
304
304
|
draft: input.text,
|
|
305
|
+
files: (input.files ?? []).length === 0 ? null : input.files,
|
|
305
306
|
text: null,
|
|
306
307
|
status: "pending",
|
|
307
308
|
// Select values are stored by their wire names.
|
|
@@ -998,6 +999,10 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
998
999
|
memberId: String(previous.person_id),
|
|
999
1000
|
sessionId: String(previous.session_id),
|
|
1000
1001
|
text: input.text,
|
|
1002
|
+
// A redraft rewrites the text: the files the reply carries stay with it.
|
|
1003
|
+
...(draftFilesOf(previous.files).length === 0
|
|
1004
|
+
? {}
|
|
1005
|
+
: { files: draftFilesOf(previous.files) }),
|
|
1001
1006
|
mode: "always",
|
|
1002
1007
|
confidence: null,
|
|
1003
1008
|
},
|
|
@@ -138,10 +138,6 @@ export declare const ChatHandoffRequest: Schema.Struct<{
|
|
|
138
138
|
readonly memberId: Schema.String;
|
|
139
139
|
readonly reason: Schema.String;
|
|
140
140
|
}>;
|
|
141
|
-
/**
|
|
142
|
-
* `POST /api/ontology/agent/drafts`: a reply the agent kept for a member to review, for the member
|
|
143
|
-
* it answers. `key` names the reply, so a report repeated after a failure finds its draft.
|
|
144
|
-
*/
|
|
145
141
|
export declare const ReviewRequest: Schema.Struct<{
|
|
146
142
|
readonly key: Schema.String;
|
|
147
143
|
readonly provider: Schema.String;
|
|
@@ -155,12 +151,31 @@ export declare const ReviewRequest: Schema.Struct<{
|
|
|
155
151
|
readonly reply_to: Schema.NullOr<Schema.String>;
|
|
156
152
|
readonly member_id: Schema.String;
|
|
157
153
|
readonly session_id: Schema.String;
|
|
158
|
-
readonly text: Schema.String
|
|
154
|
+
readonly text: Schema.optionalKey<Schema.String>;
|
|
155
|
+
readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
156
|
+
readonly entity: Schema.String;
|
|
157
|
+
readonly id: Schema.String;
|
|
158
|
+
readonly property: Schema.optionalKey<Schema.String>;
|
|
159
|
+
}>>>;
|
|
159
160
|
readonly mode: Schema.Literals<readonly ["always", "whenUnsure"]>;
|
|
160
161
|
readonly confidence: Schema.NullOr<Schema.Number>;
|
|
161
162
|
readonly turn_id: Schema.optionalKey<Schema.String>;
|
|
162
163
|
}>;
|
|
163
164
|
export type ReviewRequest = typeof ReviewRequest.Type;
|
|
165
|
+
/**
|
|
166
|
+
* `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
|
|
167
|
+
* as the member it is for, checked as holding it would check them, without holding anything.
|
|
168
|
+
*/
|
|
169
|
+
export declare const DraftFilesRequest: Schema.Struct<{
|
|
170
|
+
readonly provider: Schema.String;
|
|
171
|
+
readonly channel: Schema.optionalKey<Schema.String>;
|
|
172
|
+
readonly member_id: Schema.String;
|
|
173
|
+
readonly files: Schema.$Array<Schema.Struct<{
|
|
174
|
+
readonly entity: Schema.String;
|
|
175
|
+
readonly id: Schema.String;
|
|
176
|
+
readonly property: Schema.optionalKey<Schema.String>;
|
|
177
|
+
}>>;
|
|
178
|
+
}>;
|
|
164
179
|
/**
|
|
165
180
|
* `POST /api/ontology/agent/drafts/revision`: what became of a redraft a member asked for: the new
|
|
166
181
|
* draft, or, without `text`, that the agent could not write one.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomInt } from "node:crypto";
|
|
2
2
|
import { Schema } from "effect";
|
|
3
|
-
import { AGENT_DRAFT_PARTICIPANTS_LIMIT } from "../../agent-draft.js";
|
|
3
|
+
import { AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_PARTICIPANTS_LIMIT } from "../../agent-draft.js";
|
|
4
4
|
import { ChatChannelName } from "../../chat-channel.js";
|
|
5
5
|
import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
|
|
6
6
|
import { EMAIL_PATTERN } from "../../property.js";
|
|
@@ -186,6 +186,12 @@ export const ChatHandoffRequest = Schema.Struct({
|
|
|
186
186
|
* `POST /api/ontology/agent/drafts`: a reply the agent kept for a member to review, for the member
|
|
187
187
|
* it answers. `key` names the reply, so a report repeated after a failure finds its draft.
|
|
188
188
|
*/
|
|
189
|
+
/** A record file a held reply carries, by its entity, record and file property. */
|
|
190
|
+
const HeldFile = Schema.Struct({
|
|
191
|
+
entity: Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,63}$/)),
|
|
192
|
+
id: Schema.String.check(Schema.isUUID()),
|
|
193
|
+
property: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,63}$/))),
|
|
194
|
+
});
|
|
189
195
|
export const ReviewRequest = Schema.Struct({
|
|
190
196
|
key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
|
|
191
197
|
description: "The agent's key for the reply: its session and content part.",
|
|
@@ -223,9 +229,15 @@ export const ReviewRequest = Schema.Struct({
|
|
|
223
229
|
session_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
|
|
224
230
|
description: "The agent's session that wrote the reply.",
|
|
225
231
|
}),
|
|
226
|
-
text: Schema.String.check(Schema.
|
|
227
|
-
description: "The reply as the agent wrote it, in Markdown.",
|
|
232
|
+
text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(20_000))).annotate({
|
|
233
|
+
description: "The reply as the agent wrote it, in Markdown; empty or absent only for a reply of files.",
|
|
228
234
|
}),
|
|
235
|
+
files: Schema.optionalKey(Schema.Array(HeldFile)
|
|
236
|
+
.check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_FILES_LIMIT))
|
|
237
|
+
.annotate({
|
|
238
|
+
description: "Record files the reply carries, in order, which the person may read: approval sends " +
|
|
239
|
+
"the revision each holds now.",
|
|
240
|
+
})),
|
|
229
241
|
mode: Schema.Literals(["always", "whenUnsure"]).annotate({
|
|
230
242
|
description: "Why the reply was held: every reply is reviewed, or the model was unsure.",
|
|
231
243
|
}),
|
|
@@ -236,6 +248,16 @@ export const ReviewRequest = Schema.Struct({
|
|
|
236
248
|
description: "The agent's turn that wrote the reply.",
|
|
237
249
|
})),
|
|
238
250
|
});
|
|
251
|
+
/**
|
|
252
|
+
* `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
|
|
253
|
+
* as the member it is for, checked as holding it would check them, without holding anything.
|
|
254
|
+
*/
|
|
255
|
+
export const DraftFilesRequest = Schema.Struct({
|
|
256
|
+
provider: Provider,
|
|
257
|
+
channel: Schema.optionalKey(ChatChannelName),
|
|
258
|
+
member_id: Schema.String,
|
|
259
|
+
files: Schema.Array(HeldFile).check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_FILES_LIMIT)),
|
|
260
|
+
});
|
|
239
261
|
/**
|
|
240
262
|
* `POST /api/ontology/agent/drafts/revision`: what became of a redraft a member asked for: the new
|
|
241
263
|
* draft, or, without `text`, that the agent could not write one.
|
|
@@ -8,6 +8,7 @@ import { type RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
|
8
8
|
import { type AgentToolsOf } from "./protocol.js";
|
|
9
9
|
import { type VisitorWebsites } from "./web-tokens.js";
|
|
10
10
|
import type { BotCheckVerifier } from "./bot-check.js";
|
|
11
|
+
import { type OntologyManifest } from "../../manifest.js";
|
|
11
12
|
import { GUEST_LINK_PATH, type EmailCodes } from "./guest-sign-up.js";
|
|
12
13
|
import type { ResolvedGuest } from "../../sign-in.js";
|
|
13
14
|
/** The agent's endpoints, under the ontology service's path. */
|
|
@@ -52,6 +53,8 @@ export interface AgentServerOptions {
|
|
|
52
53
|
readonly cronSecret?: Redacted.Redacted<string> | undefined;
|
|
53
54
|
/** How many days the chats' messages are kept, as the ontology declares it. */
|
|
54
55
|
readonly chatRetentionDays?: number;
|
|
56
|
+
/** The ontology, whose record files a held reply carries and whose channels send them. */
|
|
57
|
+
readonly manifest?: OntologyManifest;
|
|
55
58
|
}
|
|
56
59
|
/**
|
|
57
60
|
* The routes that pair channel accounts with members for the app's own agent, and record the group
|
|
@@ -13,10 +13,11 @@ import { secretHash } from "../oauth/protocol.js";
|
|
|
13
13
|
import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
|
|
14
14
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
15
15
|
import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
16
|
-
import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
16
|
+
import { ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
17
17
|
import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
|
|
18
18
|
import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
|
|
19
19
|
import { CHAT_RETENTION_DAYS } from "../../manifest.js";
|
|
20
|
+
import { snapshotDraftFiles } from "../chat/draft-files.js";
|
|
20
21
|
import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
|
|
21
22
|
import { identityToken } from "../operations.js";
|
|
22
23
|
/** The agent's endpoints, under the ontology service's path. */
|
|
@@ -353,7 +354,7 @@ function seeChat(store) {
|
|
|
353
354
|
* pending `agent_draft` for the member it answers, once per key; 404 when that member is not an
|
|
354
355
|
* active member, so the reply is neither sent nor kept.
|
|
355
356
|
*/
|
|
356
|
-
function holdReply(store) {
|
|
357
|
+
function holdReply(store, backend, manifest) {
|
|
357
358
|
return (request) => Effect.gen(function* () {
|
|
358
359
|
const requestId = yield* RequestId;
|
|
359
360
|
const decoded = Schema.decodeUnknownResult(ReviewRequest)(yield* jsonBody(request), {
|
|
@@ -387,6 +388,51 @@ function holdReply(store) {
|
|
|
387
388
|
{ path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
|
|
388
389
|
]);
|
|
389
390
|
}
|
|
391
|
+
const text = body.text ?? "";
|
|
392
|
+
// A reply is its text, its files, or both.
|
|
393
|
+
if (text.trim() === "" && body.files === undefined) {
|
|
394
|
+
return invalidBody(requestId, [
|
|
395
|
+
{ path: ["text"], message: "A reply without files has text." },
|
|
396
|
+
]);
|
|
397
|
+
}
|
|
398
|
+
const channel = body.channel ?? body.provider;
|
|
399
|
+
let files;
|
|
400
|
+
// A report repeated after a lost answer finds the draft its key holds, whatever became of
|
|
401
|
+
// its files since: only a new draft reads them.
|
|
402
|
+
const [existing] = body.files === undefined
|
|
403
|
+
? []
|
|
404
|
+
: (yield* backend
|
|
405
|
+
.find({ entity: "agent_draft", query: { where: { key: body.key }, limit: 1 } })
|
|
406
|
+
.pipe(Effect.orDie)).items;
|
|
407
|
+
if (existing !== undefined) {
|
|
408
|
+
return json({ id: String(existing.id), status: String(existing.status), created: false });
|
|
409
|
+
}
|
|
410
|
+
// Each file as the person may read it now, and as the channel sends it.
|
|
411
|
+
if (body.files !== undefined) {
|
|
412
|
+
const member = yield* store.member(body.member_id);
|
|
413
|
+
if (member === undefined) {
|
|
414
|
+
return toServerResponse(notFound(requestId, "The reply is for no active member."));
|
|
415
|
+
}
|
|
416
|
+
if (manifest === undefined) {
|
|
417
|
+
return HttpServerResponse.jsonUnsafe({ error: "files_unsupported", request_id: requestId }, { status: 422, headers: NO_STORE });
|
|
418
|
+
}
|
|
419
|
+
const snapshot = yield* snapshotDraftFiles({
|
|
420
|
+
manifest,
|
|
421
|
+
backend,
|
|
422
|
+
principal: member.principal,
|
|
423
|
+
channel,
|
|
424
|
+
files: body.files,
|
|
425
|
+
});
|
|
426
|
+
if ("refusal" in snapshot) {
|
|
427
|
+
yield* Effect.logInfo("ontology.agent.reply_files_refused").pipe(Effect.annotateLogs({ requestId, channel, refusal: snapshot.refusal }));
|
|
428
|
+
return HttpServerResponse.jsonUnsafe({
|
|
429
|
+
error: snapshot.refusal,
|
|
430
|
+
...(snapshot.index === undefined ? {} : { index: snapshot.index }),
|
|
431
|
+
request_id: requestId,
|
|
432
|
+
}, { status: 422, headers: NO_STORE });
|
|
433
|
+
}
|
|
434
|
+
files = snapshot.files;
|
|
435
|
+
}
|
|
390
436
|
const review = yield* store.holdReply({
|
|
391
437
|
key: body.key,
|
|
392
438
|
provider: body.provider,
|
|
@@ -402,7 +448,8 @@ function holdReply(store) {
|
|
|
402
448
|
replyTo: body.reply_to,
|
|
403
449
|
memberId: body.member_id,
|
|
404
450
|
sessionId: body.session_id,
|
|
405
|
-
text
|
|
451
|
+
text,
|
|
452
|
+
...(files === undefined ? {} : { files }),
|
|
406
453
|
mode: body.mode,
|
|
407
454
|
confidence: body.confidence,
|
|
408
455
|
...(body.turn_id === undefined ? {} : { turnId: body.turn_id }),
|
|
@@ -421,6 +468,57 @@ function holdReply(store) {
|
|
|
421
468
|
return json({ id: review.id, status: review.status, created: review.created });
|
|
422
469
|
});
|
|
423
470
|
}
|
|
471
|
+
/**
|
|
472
|
+
* `POST /api/ontology/agent/drafts/files` (runtime): the files a reply would carry, read as the
|
|
473
|
+
* member it is for and checked against its channel as holding the reply checks them, without
|
|
474
|
+
* holding anything: the agent asks before it promises a file in a reviewed chat. An ontology
|
|
475
|
+
* without draft files answers 404, which the agent takes as no files in reviewed chats.
|
|
476
|
+
*/
|
|
477
|
+
function checkDraftFiles(store, backend, manifest) {
|
|
478
|
+
return (request) => Effect.gen(function* () {
|
|
479
|
+
const requestId = yield* RequestId;
|
|
480
|
+
const decoded = Schema.decodeUnknownResult(DraftFilesRequest)(yield* jsonBody(request), {
|
|
481
|
+
errors: "all",
|
|
482
|
+
onExcessProperty: "error",
|
|
483
|
+
});
|
|
484
|
+
if (Result.isFailure(decoded)) {
|
|
485
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
486
|
+
}
|
|
487
|
+
const body = decoded.success;
|
|
488
|
+
const member = yield* store.member(body.member_id);
|
|
489
|
+
if (member === undefined) {
|
|
490
|
+
return toServerResponse(notFound(requestId, "The reply is for no active member."));
|
|
491
|
+
}
|
|
492
|
+
const snapshot = manifest === undefined
|
|
493
|
+
? { refusal: "files_unsupported" }
|
|
494
|
+
: yield* snapshotDraftFiles({
|
|
495
|
+
manifest,
|
|
496
|
+
backend,
|
|
497
|
+
principal: member.principal,
|
|
498
|
+
channel: body.channel ?? body.provider,
|
|
499
|
+
files: body.files,
|
|
500
|
+
});
|
|
501
|
+
return "refusal" in snapshot
|
|
502
|
+
? HttpServerResponse.jsonUnsafe({
|
|
503
|
+
error: snapshot.refusal,
|
|
504
|
+
...("index" in snapshot && snapshot.index !== undefined
|
|
505
|
+
? { index: snapshot.index }
|
|
506
|
+
: {}),
|
|
507
|
+
request_id: requestId,
|
|
508
|
+
}, { status: 422, headers: NO_STORE })
|
|
509
|
+
: HttpServerResponse.jsonUnsafe({
|
|
510
|
+
files: snapshot.files.map((file) => ({
|
|
511
|
+
entity: file.entity,
|
|
512
|
+
id: file.id,
|
|
513
|
+
property: file.property,
|
|
514
|
+
revision_id: file.revisionId,
|
|
515
|
+
filename: file.filename,
|
|
516
|
+
content_type: file.contentType,
|
|
517
|
+
size: file.size,
|
|
518
|
+
})),
|
|
519
|
+
}, { headers: NO_STORE });
|
|
520
|
+
});
|
|
521
|
+
}
|
|
424
522
|
/**
|
|
425
523
|
* `POST /api/ontology/agent/drafts/revision` (runtime): the agent redrafted a reply a member sent
|
|
426
524
|
* back, or could not. The new draft becomes a pending draft for the same person and chat that
|
|
@@ -624,10 +722,11 @@ export function agentLayer(options) {
|
|
|
624
722
|
yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.purge}`, purge);
|
|
625
723
|
}
|
|
626
724
|
for (const path of [DRAFTS_PATH, REVIEWS_PATH]) {
|
|
627
|
-
yield* router.add("POST", path, asRuntime(holdReply(store)));
|
|
725
|
+
yield* router.add("POST", path, asRuntime(holdReply(store, backend, options.manifest)));
|
|
628
726
|
yield* router.add("POST", `${path}/session`, asRuntime(sessionReviews(store)));
|
|
629
727
|
yield* router.add("POST", `${path}/revision`, asRuntime(revision(store)));
|
|
630
728
|
}
|
|
729
|
+
yield* router.add("POST", `${DRAFTS_PATH}/files`, asRuntime(checkDraftFiles(store, backend, options.manifest)));
|
|
631
730
|
yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
|
|
632
731
|
if (store.web !== undefined && backend.oauth !== undefined) {
|
|
633
732
|
yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import type { OntologyEnvironment } from "../config.js";
|
|
3
3
|
import type { ChatRequester } from "./attribution.js";
|
|
4
|
+
/** A file of a delivered message, as the chat's history shows it: its name, type and size. */
|
|
5
|
+
export interface DeliveryAttachment {
|
|
6
|
+
readonly id: string;
|
|
7
|
+
readonly kind: "file";
|
|
8
|
+
readonly filename: string;
|
|
9
|
+
readonly contentType: string;
|
|
10
|
+
readonly size: number;
|
|
11
|
+
}
|
|
4
12
|
export interface DeliveryEvent {
|
|
5
13
|
readonly eventId: string;
|
|
6
14
|
readonly operationId: string;
|
|
@@ -27,7 +35,13 @@ export interface DeliveryEvent {
|
|
|
27
35
|
readonly toolName: null;
|
|
28
36
|
readonly argsSummary: string | null;
|
|
29
37
|
readonly status: "requested" | "sent" | "uncertain" | "failed";
|
|
30
|
-
|
|
38
|
+
/** The files the message carries, as its history shows them: none but an approved draft's. */
|
|
39
|
+
readonly attachments: ReadonlyArray<DeliveryAttachment>;
|
|
40
|
+
/**
|
|
41
|
+
* The record files the message carries, each `[entity, id, property, revisionId]` in order,
|
|
42
|
+
* which bind the delivery: absent for a message of text alone, so its binding stays.
|
|
43
|
+
*/
|
|
44
|
+
readonly files?: ReadonlyArray<readonly [string, string, string, string]>;
|
|
31
45
|
readonly requestedBy: ChatRequester;
|
|
32
46
|
readonly url: string | null;
|
|
33
47
|
readonly at: string;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { AgentDraftFile } from "../../agent-draft.js";
|
|
3
|
+
import type { OntologyManifest } from "../../manifest.js";
|
|
4
|
+
import type { Principal } from "../../runtime.js";
|
|
5
|
+
import type { OntologyBackend } from "../runtime-contract.js";
|
|
6
|
+
import type { ChatFilesRefusal, ChatProvider, ChatSendFile } from "./providers/provider.js";
|
|
7
|
+
/**
|
|
8
|
+
* Record files a draft carries with its reply (`agent_draft.files`). The agent names them when it
|
|
9
|
+
* holds the reply; the ontology reads each as the person the reply is for and keeps the revision
|
|
10
|
+
* it read, which approval sends again only after reading it as that person once more. Nothing of a
|
|
11
|
+
* file's bytes is kept with the draft: the record keeps them, as long as it keeps that revision.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Why `provider` cannot send these files in one reply, checked before anything is reserved or
|
|
15
|
+
* sent: `files_unsupported` for a provider that sends none, `too_many_files` past its count,
|
|
16
|
+
* `file_too_large` past its bytes together, else what its own check says.
|
|
17
|
+
*/
|
|
18
|
+
export declare function refuseChatFiles(provider: ChatProvider, files: ReadonlyArray<{
|
|
19
|
+
readonly contentType: string;
|
|
20
|
+
readonly size: number;
|
|
21
|
+
}>): ChatFilesRefusal | undefined;
|
|
22
|
+
/** A file a reply names, by its record and file property. */
|
|
23
|
+
export interface DraftFileReference {
|
|
24
|
+
readonly entity: string;
|
|
25
|
+
readonly id: string;
|
|
26
|
+
readonly property?: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The files a reply on `channel` names, read as `principal`, the person it is for: each record's
|
|
30
|
+
* revision of the file now, with its name, type and size. A file the person may not read, or that
|
|
31
|
+
* is gone, refuses them all as `file_unavailable` with its index; files the channel cannot send
|
|
32
|
+
* as its refusal.
|
|
33
|
+
*/
|
|
34
|
+
export declare function snapshotDraftFiles(input: {
|
|
35
|
+
readonly manifest: OntologyManifest;
|
|
36
|
+
readonly backend: OntologyBackend["Service"];
|
|
37
|
+
readonly principal: Principal;
|
|
38
|
+
readonly channel: string;
|
|
39
|
+
readonly files: ReadonlyArray<DraftFileReference>;
|
|
40
|
+
}): Effect.Effect<{
|
|
41
|
+
readonly files: ReadonlyArray<AgentDraftFile>;
|
|
42
|
+
} | {
|
|
43
|
+
readonly refusal: ChatFilesRefusal;
|
|
44
|
+
readonly index?: number;
|
|
45
|
+
}>;
|
|
46
|
+
/**
|
|
47
|
+
* The bytes of a draft's files for its delivery, each read as `person`, the member the reply is
|
|
48
|
+
* for, at the revision the draft holds; undefined when any of them is gone, no longer retained, or
|
|
49
|
+
* no longer theirs to read, or reads other than the revision held.
|
|
50
|
+
*/
|
|
51
|
+
export declare function readDraftFiles(input: {
|
|
52
|
+
readonly backend: OntologyBackend["Service"];
|
|
53
|
+
readonly person: string | null;
|
|
54
|
+
readonly files: ReadonlyArray<AgentDraftFile>;
|
|
55
|
+
readonly fetch: typeof fetch;
|
|
56
|
+
}): Effect.Effect<ReadonlyArray<ChatSendFile> | undefined>;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { resolveFileRecord } from "../../runtime/files.js";
|
|
3
|
+
import { describeChatError } from "./diagnostics.js";
|
|
4
|
+
import { channelProvider } from "./providers/index.js";
|
|
5
|
+
/**
|
|
6
|
+
* Record files a draft carries with its reply (`agent_draft.files`). The agent names them when it
|
|
7
|
+
* holds the reply; the ontology reads each as the person the reply is for and keeps the revision
|
|
8
|
+
* it read, which approval sends again only after reading it as that person once more. Nothing of a
|
|
9
|
+
* file's bytes is kept with the draft: the record keeps them, as long as it keeps that revision.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Why `provider` cannot send these files in one reply, checked before anything is reserved or
|
|
13
|
+
* sent: `files_unsupported` for a provider that sends none, `too_many_files` past its count,
|
|
14
|
+
* `file_too_large` past its bytes together, else what its own check says.
|
|
15
|
+
*/
|
|
16
|
+
export function refuseChatFiles(provider, files) {
|
|
17
|
+
if (files.length === 0) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
if (provider.files === undefined) {
|
|
21
|
+
return "files_unsupported";
|
|
22
|
+
}
|
|
23
|
+
if (files.length > provider.files.count) {
|
|
24
|
+
return "too_many_files";
|
|
25
|
+
}
|
|
26
|
+
if (files.reduce((total, file) => total + file.size, 0) > provider.files.bytes) {
|
|
27
|
+
return "file_too_large";
|
|
28
|
+
}
|
|
29
|
+
return provider.refuseFiles?.(files);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The files a reply on `channel` names, read as `principal`, the person it is for: each record's
|
|
33
|
+
* revision of the file now, with its name, type and size. A file the person may not read, or that
|
|
34
|
+
* is gone, refuses them all as `file_unavailable` with its index; files the channel cannot send
|
|
35
|
+
* as its refusal.
|
|
36
|
+
*/
|
|
37
|
+
export function snapshotDraftFiles(input) {
|
|
38
|
+
return Effect.gen(function* () {
|
|
39
|
+
const { backend, principal } = input;
|
|
40
|
+
const blobs = backend.blobs;
|
|
41
|
+
const files = [];
|
|
42
|
+
if (blobs === undefined) {
|
|
43
|
+
return { refusal: "file_unavailable", index: 0 };
|
|
44
|
+
}
|
|
45
|
+
for (const [index, reference] of input.files.entries()) {
|
|
46
|
+
const file = yield* resolveFileRecord({
|
|
47
|
+
manifest: input.manifest,
|
|
48
|
+
reads: backend,
|
|
49
|
+
principal,
|
|
50
|
+
reference,
|
|
51
|
+
}).pipe(
|
|
52
|
+
// The revision read, granted to the person: a scoped read they may not make refuses it.
|
|
53
|
+
Effect.tap((resolved) => blobs.download(resolved.entity, resolved.id, resolved.property, { revisionId: resolved.file.id }, principal)), Effect.map((resolved) => ({
|
|
54
|
+
entity: resolved.entity,
|
|
55
|
+
id: resolved.id.toLowerCase(),
|
|
56
|
+
property: resolved.property,
|
|
57
|
+
revisionId: resolved.file.id,
|
|
58
|
+
filename: resolved.file.filename,
|
|
59
|
+
contentType: resolved.file.contentType,
|
|
60
|
+
size: resolved.file.size,
|
|
61
|
+
})),
|
|
62
|
+
// A refusal or a missing record; a defect of the store still fails the request. The
|
|
63
|
+
// original reason stays in the operator log.
|
|
64
|
+
Effect.catch((cause) => Effect.logWarning("ontology.agent_draft.file_unavailable").pipe(Effect.annotateLogs({
|
|
65
|
+
phase: "hold",
|
|
66
|
+
index,
|
|
67
|
+
error: describeChatError(cause, (text) => text),
|
|
68
|
+
}), Effect.as(undefined))));
|
|
69
|
+
if (file === undefined) {
|
|
70
|
+
return { refusal: "file_unavailable", index };
|
|
71
|
+
}
|
|
72
|
+
files.push(file);
|
|
73
|
+
}
|
|
74
|
+
const provider = channelProvider(input.manifest.chat, input.channel);
|
|
75
|
+
const refusal = provider === undefined ? "files_unsupported" : refuseChatFiles(provider, files);
|
|
76
|
+
return refusal === undefined ? { files } : { refusal };
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The bytes of a draft's files for its delivery, each read as `person`, the member the reply is
|
|
81
|
+
* for, at the revision the draft holds; undefined when any of them is gone, no longer retained, or
|
|
82
|
+
* no longer theirs to read, or reads other than the revision held.
|
|
83
|
+
*/
|
|
84
|
+
export function readDraftFiles(input) {
|
|
85
|
+
return Effect.gen(function* () {
|
|
86
|
+
if (input.files.length === 0) {
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
const { blobs, agents } = input.backend;
|
|
90
|
+
const member = input.person === null || agents === undefined
|
|
91
|
+
? undefined
|
|
92
|
+
: yield* agents.member(input.person);
|
|
93
|
+
if (blobs === undefined || member === undefined) {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
const read = [];
|
|
97
|
+
for (const file of input.files) {
|
|
98
|
+
const bytes = yield* blobs
|
|
99
|
+
.download(file.entity, file.id, file.property, { revisionId: file.revisionId }, member.principal)
|
|
100
|
+
.pipe(Effect.flatMap((grant) => Effect.tryPromise(async () => {
|
|
101
|
+
const response = await input.fetch(grant.url, {
|
|
102
|
+
method: grant.method,
|
|
103
|
+
headers: grant.headers,
|
|
104
|
+
});
|
|
105
|
+
if (!response.ok) {
|
|
106
|
+
await response.body?.cancel();
|
|
107
|
+
throw new Error(`Storage answered the file's read with status ${response.status}.`);
|
|
108
|
+
}
|
|
109
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
110
|
+
}).pipe(
|
|
111
|
+
// The grant's link is a credential: no diagnostic shows it.
|
|
112
|
+
Effect.mapError((cause) => ({ cause, secret: grant.url })))), Effect.catch((failure) => Effect.logWarning("ontology.agent_draft.file_unavailable").pipe(Effect.annotateLogs({
|
|
113
|
+
phase: "approve",
|
|
114
|
+
entity: file.entity,
|
|
115
|
+
id: file.id,
|
|
116
|
+
revisionId: file.revisionId,
|
|
117
|
+
error: typeof failure === "object" && failure !== null && "secret" in failure
|
|
118
|
+
? describeChatError(failure.cause, (text) => text.split(failure.secret).join("[redacted]"))
|
|
119
|
+
: describeChatError(failure, (text) => text),
|
|
120
|
+
}), Effect.as(undefined))));
|
|
121
|
+
if (bytes === undefined || bytes.byteLength !== file.size) {
|
|
122
|
+
if (bytes !== undefined) {
|
|
123
|
+
yield* Effect.logWarning("ontology.agent_draft.file_unavailable").pipe(Effect.annotateLogs({
|
|
124
|
+
phase: "approve",
|
|
125
|
+
entity: file.entity,
|
|
126
|
+
id: file.id,
|
|
127
|
+
revisionId: file.revisionId,
|
|
128
|
+
error: `The revision read has ${bytes.byteLength} bytes, not the ${file.size} held.`,
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
read.push({ filename: file.filename, contentType: file.contentType, bytes });
|
|
134
|
+
}
|
|
135
|
+
return read;
|
|
136
|
+
});
|
|
137
|
+
}
|
|
@@ -46,5 +46,10 @@ buttons?: ChatButtonRows,
|
|
|
46
46
|
recipients?: {
|
|
47
47
|
readonly to: ReadonlyArray<string>;
|
|
48
48
|
readonly cc: ReadonlyArray<string>;
|
|
49
|
-
}
|
|
49
|
+
},
|
|
50
|
+
/**
|
|
51
|
+
* The record files a message carries, each `[entity, id, property, revisionId]` in order, bound
|
|
52
|
+
* when given so a key of text alone keeps its binding.
|
|
53
|
+
*/
|
|
54
|
+
files?: ReadonlyArray<readonly [string, string, string, string]>): string;
|
|
50
55
|
export {};
|
|
@@ -27,7 +27,12 @@ buttons,
|
|
|
27
27
|
* Whom a reply to mail goes to beside its destination, bound when given so a key that names no
|
|
28
28
|
* one else keeps its binding.
|
|
29
29
|
*/
|
|
30
|
-
recipients
|
|
30
|
+
recipients,
|
|
31
|
+
/**
|
|
32
|
+
* The record files a message carries, each `[entity, id, property, revisionId]` in order, bound
|
|
33
|
+
* when given so a key of text alone keeps its binding.
|
|
34
|
+
*/
|
|
35
|
+
files) {
|
|
31
36
|
const sorted = (values) => Object.entries(values).sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0));
|
|
32
37
|
const media = template?.header?.media;
|
|
33
38
|
return digest(JSON.stringify([
|
|
@@ -40,6 +45,7 @@ recipients) {
|
|
|
40
45
|
preview.text,
|
|
41
46
|
...(buttons === undefined ? [] : [{ buttons }]),
|
|
42
47
|
...(recipients === undefined ? [] : [{ to: recipients.to, cc: recipients.cc }]),
|
|
48
|
+
...(files === undefined || files.length === 0 ? [] : [{ files }]),
|
|
43
49
|
]
|
|
44
50
|
: [
|
|
45
51
|
{
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
-
import {
|
|
2
|
+
import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
|
|
3
|
+
import { renderWorkspaceChannelText, WORKSPACE_CHANNEL_ID, WORKSPACE_CHANNEL_FILES_BYTES, WORKSPACE_CHANNEL_TEXT_LIMIT, workspaceChannelFiles, workspaceChannelSendRoute, } from "../../../workspace-channel.js";
|
|
3
4
|
import { record } from "./provider.js";
|
|
4
5
|
/** How long the agent has to send one message through a workspace channel. */
|
|
5
6
|
const AGENT_SEND_TIMEOUT_MS = 30_000;
|
|
@@ -15,7 +16,11 @@ const ID = WORKSPACE_CHANNEL_ID;
|
|
|
15
16
|
*/
|
|
16
17
|
export function sendThroughAgent(input) {
|
|
17
18
|
return Effect.gen(function* () {
|
|
18
|
-
const
|
|
19
|
+
const files = input.files ?? [];
|
|
20
|
+
const payload = {
|
|
21
|
+
text: input.finalText,
|
|
22
|
+
...(files.length === 0 ? {} : { files: files.map((file) => file.filename) }),
|
|
23
|
+
};
|
|
19
24
|
const agent = input.agent;
|
|
20
25
|
if (agent?.origin === undefined || agent.identityToken === undefined) {
|
|
21
26
|
return {
|
|
@@ -35,6 +40,9 @@ export function sendThroughAgent(input) {
|
|
|
35
40
|
thread_id: input.threadId ?? null,
|
|
36
41
|
reply_to: input.replyTo,
|
|
37
42
|
text: input.finalText,
|
|
43
|
+
// Every agent with this route reads `files`, and refuses them with `files_unsupported`
|
|
44
|
+
// when the channel's code takes none: nothing is sent then.
|
|
45
|
+
...(files.length === 0 ? {} : { files: workspaceChannelFiles(files) }),
|
|
38
46
|
};
|
|
39
47
|
const answered = yield* Effect.tryPromise(async () => {
|
|
40
48
|
const response = await agent.fetch(new Request(new URL(workspaceChannelSendRoute(input.destination.provider), agent.origin), {
|
|
@@ -99,5 +107,7 @@ export const customProvider = {
|
|
|
99
107
|
return { finalText, plainText: finalText };
|
|
100
108
|
},
|
|
101
109
|
payload: (finalText) => ({ text: finalText }),
|
|
110
|
+
// The files go in the one message the channel's code sends, within the contract's bound.
|
|
111
|
+
files: { count: AGENT_DRAFT_FILES_LIMIT, bytes: WORKSPACE_CHANNEL_FILES_BYTES },
|
|
102
112
|
send: sendThroughAgent,
|
|
103
113
|
};
|
|
@@ -8,7 +8,8 @@ import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provid
|
|
|
8
8
|
* with the thread id, never retried. A reply sends no attribution and names no sender, so it
|
|
9
9
|
* leaves from the mailbox's own address. It carries `Auto-Submitted: auto-replied` and
|
|
10
10
|
* `X-SegmentStream-Reply: review-<review id>`, as the email channel's replies carry their own
|
|
11
|
-
* keys.
|
|
11
|
+
* keys. Files go after the text in the same message, uploaded in chunks when one request cannot
|
|
12
|
+
* carry it (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
|
|
12
13
|
*/
|
|
13
14
|
export declare function sendEmail(input: ChatSend): Effect.Effect<ProviderOutcome>;
|
|
14
15
|
/**
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
-
import {
|
|
2
|
+
import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
|
|
3
|
+
import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, renderEmailHtml, sendGmailMessage, } from "../../../email.js";
|
|
3
4
|
import { EMAIL_PATTERN } from "../../../property.js";
|
|
4
|
-
import { record, transportFailure, } from "./provider.js";
|
|
5
|
+
import { channelRequest, definiteTransportFailure, record, transportFailure, } from "./provider.js";
|
|
5
6
|
/** A Gmail id, of a thread or a message. */
|
|
6
7
|
const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
|
|
7
8
|
const decoder = new TextDecoder();
|
|
@@ -33,7 +34,8 @@ function headersOf(message) {
|
|
|
33
34
|
* with the thread id, never retried. A reply sends no attribution and names no sender, so it
|
|
34
35
|
* leaves from the mailbox's own address. It carries `Auto-Submitted: auto-replied` and
|
|
35
36
|
* `X-SegmentStream-Reply: review-<review id>`, as the email channel's replies carry their own
|
|
36
|
-
* keys.
|
|
37
|
+
* keys. Files go after the text in the same message, uploaded in chunks when one request cannot
|
|
38
|
+
* carry it (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
|
|
37
39
|
*/
|
|
38
40
|
export function sendEmail(input) {
|
|
39
41
|
return Effect.gen(function* () {
|
|
@@ -75,6 +77,7 @@ export function sendEmail(input) {
|
|
|
75
77
|
const key = `review-${input.destination.id}`;
|
|
76
78
|
const to = input.recipients?.to ?? [input.destination.external_id];
|
|
77
79
|
const cc = input.recipients?.cc ?? [];
|
|
80
|
+
const files = input.files ?? [];
|
|
78
81
|
const raw = emailReplyMessage({
|
|
79
82
|
to,
|
|
80
83
|
...(cc.length === 0 ? {} : { cc }),
|
|
@@ -85,8 +88,47 @@ export function sendEmail(input) {
|
|
|
85
88
|
html: input.finalText,
|
|
86
89
|
autoSubmitted: true,
|
|
87
90
|
...(/^[A-Za-z0-9_-]{1,128}$/.test(key) ? { replyKey: key } : {}),
|
|
91
|
+
...(files.length === 0 ? {} : { attachments: files }),
|
|
88
92
|
});
|
|
89
|
-
const payload = {
|
|
93
|
+
const payload = {
|
|
94
|
+
threadId,
|
|
95
|
+
to,
|
|
96
|
+
cc,
|
|
97
|
+
html: input.finalText,
|
|
98
|
+
text: input.plainText,
|
|
99
|
+
...(files.length === 0 ? {} : { files: files.map((file) => file.filename) }),
|
|
100
|
+
};
|
|
101
|
+
// A reply with files is one message too, uploaded when one request cannot carry it.
|
|
102
|
+
if (files.length > 0) {
|
|
103
|
+
return yield* Effect.promise(() => sendGmailMessage({
|
|
104
|
+
request: channelRequest(input.transport, input.connection),
|
|
105
|
+
message: new TextEncoder().encode(raw),
|
|
106
|
+
threadId,
|
|
107
|
+
}).then((answer) => typeof answer.id === "string" && GMAIL_ID.test(answer.id)
|
|
108
|
+
? { payload, status: "sent", messageId: answer.id, url: null }
|
|
109
|
+
: {
|
|
110
|
+
payload,
|
|
111
|
+
status: "uncertain",
|
|
112
|
+
messageId: null,
|
|
113
|
+
url: null,
|
|
114
|
+
cause: new Error("Gmail accepted the reply without its id."),
|
|
115
|
+
}, (cause) => ({
|
|
116
|
+
payload,
|
|
117
|
+
// Gmail's refusal, or a proxy that never reached Gmail, sent nothing; anything else
|
|
118
|
+
// may have, such as an upload whose last answer was lost.
|
|
119
|
+
status: (cause instanceof GmailError &&
|
|
120
|
+
cause.status >= 400 &&
|
|
121
|
+
cause.status < 500 &&
|
|
122
|
+
cause.status !== 408 &&
|
|
123
|
+
cause.status !== 429) ||
|
|
124
|
+
definiteTransportFailure(cause)
|
|
125
|
+
? "failed"
|
|
126
|
+
: "uncertain",
|
|
127
|
+
messageId: null,
|
|
128
|
+
url: null,
|
|
129
|
+
cause,
|
|
130
|
+
})));
|
|
131
|
+
}
|
|
90
132
|
const result = yield* input.transport
|
|
91
133
|
.request({
|
|
92
134
|
connection: input.connection,
|
|
@@ -140,5 +182,7 @@ export const emailProvider = {
|
|
|
140
182
|
return { finalText: renderEmailHtml(text), plainText: text };
|
|
141
183
|
},
|
|
142
184
|
payload: (finalText) => ({ html: finalText }),
|
|
185
|
+
// The files go in the reply's one message, under the bound every email sender keeps.
|
|
186
|
+
files: { count: AGENT_DRAFT_FILES_LIMIT, bytes: EMAIL_FILES_BYTES },
|
|
143
187
|
send: sendEmail,
|
|
144
188
|
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Effect, type Exit } from "effect";
|
|
2
|
+
import type { ChannelRequest } from "../../../channel-files.js";
|
|
2
3
|
import type { ChatButtonRows } from "../../../chat.js";
|
|
3
4
|
import type { TelegramPreviewContext } from "../../../telegram.js";
|
|
4
5
|
import { ConnectionError, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
|
|
@@ -15,7 +16,29 @@ export interface ProviderOutcome {
|
|
|
15
16
|
readonly cause?: unknown;
|
|
16
17
|
/** Why the provider refused a `failed` message, when it says: see `ActionRejected.refusal`. */
|
|
17
18
|
readonly refusal?: ChatRefusal;
|
|
19
|
+
/**
|
|
20
|
+
* What became of each file of a send with files, by its index, when the provider sent them in
|
|
21
|
+
* several messages: one that reached the person, one that did not, or one that may have.
|
|
22
|
+
*/
|
|
23
|
+
readonly files?: ReadonlyArray<{
|
|
24
|
+
readonly index: number;
|
|
25
|
+
readonly status: "sent" | "uncertain" | "failed";
|
|
26
|
+
readonly messageId: string | null;
|
|
27
|
+
}>;
|
|
28
|
+
}
|
|
29
|
+
/** A record file a send carries after its text, read before anything is sent. */
|
|
30
|
+
export interface ChatSendFile {
|
|
31
|
+
readonly filename: string;
|
|
32
|
+
readonly contentType: string;
|
|
33
|
+
readonly bytes: Uint8Array;
|
|
18
34
|
}
|
|
35
|
+
/** How many files one message of a provider carries, and how many bytes of them together. */
|
|
36
|
+
export interface ChatFileLimits {
|
|
37
|
+
readonly count: number;
|
|
38
|
+
readonly bytes: number;
|
|
39
|
+
}
|
|
40
|
+
/** Why a provider cannot send a message's files, before its key is reserved. */
|
|
41
|
+
export type ChatFilesRefusal = "files_unsupported" | "too_many_files" | "file_too_large" | "file_unavailable";
|
|
19
42
|
/** Why a chat's provider refused a message, for code to act on. */
|
|
20
43
|
export type ChatRefusal = "outside_reply_window" | "recipient_unreachable" | "recipient_opted_out";
|
|
21
44
|
/**
|
|
@@ -60,6 +83,11 @@ export interface ChatSend {
|
|
|
60
83
|
* a workspace channel's send receives it, others ignore it.
|
|
61
84
|
*/
|
|
62
85
|
readonly chatId?: string;
|
|
86
|
+
/**
|
|
87
|
+
* Files the message carries after its text, in order, for a provider that declares `files`;
|
|
88
|
+
* the text may be empty with them.
|
|
89
|
+
*/
|
|
90
|
+
readonly files?: ReadonlyArray<ChatSendFile>;
|
|
63
91
|
/**
|
|
64
92
|
* Whom a reply to mail goes to, in `To` and `Cc`, in place of the destination alone; others
|
|
65
93
|
* ignore it.
|
|
@@ -111,6 +139,19 @@ export interface ChatProvider {
|
|
|
111
139
|
* provider that shows no buttons, which refuses them all.
|
|
112
140
|
*/
|
|
113
141
|
readonly refuseButtons?: (rows: ChatButtonRows, finalText: string) => string | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* The files one message carries: absent for a provider that sends none, which refuses every
|
|
144
|
+
* file with `files_unsupported`.
|
|
145
|
+
*/
|
|
146
|
+
readonly files?: ChatFileLimits;
|
|
147
|
+
/**
|
|
148
|
+
* Why the provider cannot send files of these types and sizes beyond its `files` limits, or
|
|
149
|
+
* undefined when it can. It is checked before the message is reserved, as `refuseButtons` is.
|
|
150
|
+
*/
|
|
151
|
+
readonly refuseFiles?: (files: ReadonlyArray<{
|
|
152
|
+
readonly contentType: string;
|
|
153
|
+
readonly size: number;
|
|
154
|
+
}>) => ChatFilesRefusal | undefined;
|
|
114
155
|
/** One attempt: `sent` only when the provider's answer proves it. */
|
|
115
156
|
readonly send: (input: ChatSend) => Effect.Effect<ProviderOutcome>;
|
|
116
157
|
/**
|
|
@@ -130,6 +171,13 @@ export interface ChatProvider {
|
|
|
130
171
|
* before the provider saw it, otherwise `uncertain`, since the provider may have acted on it.
|
|
131
172
|
*/
|
|
132
173
|
export declare function transportFailure(payload: ProviderOutcome["payload"], result: Exit.Failure<ConnectionReply, ConnectionError>): ProviderOutcome;
|
|
174
|
+
/** Whether an error of the connection transport proves the request never reached the provider. */
|
|
175
|
+
export declare function definiteTransportFailure(error: unknown): boolean;
|
|
176
|
+
/**
|
|
177
|
+
* The connection transport as the channels' shared senders call it (`ChannelRequest`): one call on
|
|
178
|
+
* `connection`, which rejects with the transport's own error when it did not relay the call.
|
|
179
|
+
*/
|
|
180
|
+
export declare function channelRequest(transport: ConnectionTransport["Service"], connection: string): ChannelRequest;
|
|
133
181
|
export declare const record: (value: unknown) => Record<string, unknown>;
|
|
134
182
|
/**
|
|
135
183
|
* A message's buttons as its history keeps them, one a line, as the person reads them: a link where
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Cause } from "effect";
|
|
1
|
+
import { Cause, Effect } from "effect";
|
|
2
2
|
import { ConnectionError, } from "../../../connection.js";
|
|
3
3
|
/** The connection failures that prove the request never reached the provider. */
|
|
4
4
|
const DEFINITE_CONNECTION_FAILURES = new Set([
|
|
@@ -23,6 +23,23 @@ export function transportFailure(payload, result) {
|
|
|
23
23
|
cause,
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
|
+
/** Whether an error of the connection transport proves the request never reached the provider. */
|
|
27
|
+
export function definiteTransportFailure(error) {
|
|
28
|
+
return error instanceof ConnectionError && DEFINITE_CONNECTION_FAILURES.has(error.reason);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The connection transport as the channels' shared senders call it (`ChannelRequest`): one call on
|
|
32
|
+
* `connection`, which rejects with the transport's own error when it did not relay the call.
|
|
33
|
+
*/
|
|
34
|
+
export function channelRequest(transport, connection) {
|
|
35
|
+
return async (call) => {
|
|
36
|
+
const exit = await Effect.runPromiseExit(transport.request({ ...call, connection }));
|
|
37
|
+
if (exit._tag === "Failure") {
|
|
38
|
+
throw Cause.squash(exit.cause);
|
|
39
|
+
}
|
|
40
|
+
return exit.value;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
26
43
|
export const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
27
44
|
? value
|
|
28
45
|
: {};
|
|
@@ -36,6 +36,8 @@ export declare function reviewSender(input: {
|
|
|
36
36
|
readonly principal: Principal;
|
|
37
37
|
readonly identityToken: string | undefined;
|
|
38
38
|
readonly requestId: string;
|
|
39
|
+
/** Reads a file's bytes by its download grant; `fetch` by default. */
|
|
40
|
+
readonly fetch?: typeof fetch;
|
|
39
41
|
}): (send: ReviewSendInput) => Effect.Effect<{
|
|
40
42
|
recipients?: EmailRecipients | undefined;
|
|
41
43
|
message?: string | undefined;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
-
import { addressesOfDraft, AGENT_DRAFT_TEXT_LIMIT, participantsOfDraft, } from "../../agent-draft.js";
|
|
2
|
+
import { addressesOfDraft, AGENT_DRAFT_TEXT_LIMIT, draftFilesOf, participantsOfDraft, } from "../../agent-draft.js";
|
|
3
3
|
import { EMAIL_RECIPIENTS_LIMIT, emailRecipients } from "../../email.js";
|
|
4
4
|
import { ActionRejected, PermissionDenied } from "../../errors.js";
|
|
5
5
|
import { effectiveScope } from "../../permissions.js";
|
|
@@ -9,6 +9,7 @@ import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
|
|
|
9
9
|
import { chatRetentionDaysOf } from "../../manifest.js";
|
|
10
10
|
import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
|
|
11
11
|
import { storeDeliveryArchive } from "./store-delivery.js";
|
|
12
|
+
import { readDraftFiles, refuseChatFiles } from "./draft-files.js";
|
|
12
13
|
/**
|
|
13
14
|
* Whether a reply to mail goes to the people a review records it went to: its `to`, else its
|
|
14
15
|
* recipient, and its `cc`, whatever their order and case.
|
|
@@ -19,6 +20,20 @@ function sameRecipients(recipients, review) {
|
|
|
19
20
|
return (set(recipients.to) ===
|
|
20
21
|
set(held.length > 0 ? held : typeof review.recipient === "string" ? [review.recipient] : []) && set(recipients.cc) === set(addressesOfDraft(review.cc)));
|
|
21
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* A draft's files the approval cannot send, refused before anything is reserved: the code names
|
|
25
|
+
* why, and the draft still waits.
|
|
26
|
+
*/
|
|
27
|
+
function refused(code, channel) {
|
|
28
|
+
return Effect.fail(new ActionRejected({
|
|
29
|
+
message: code === "files_unsupported"
|
|
30
|
+
? `The ${channel} channel sends no files with an approved reply; nothing was sent.`
|
|
31
|
+
: code === "file_unavailable"
|
|
32
|
+
? "A file of the reply is gone, or its person may no longer read it; nothing was sent."
|
|
33
|
+
: `The reply's files exceed what ${channel} sends in one reply; nothing was sent.`,
|
|
34
|
+
refusal: code,
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
22
37
|
/**
|
|
23
38
|
* Sends a reply the agent held for review, once a member approved it: the draft or the member's
|
|
24
39
|
* edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
|
|
@@ -148,7 +163,8 @@ export function reviewSender(input) {
|
|
|
148
163
|
try: () => provider.render(text, "", ""),
|
|
149
164
|
catch: (cause) => new ActionRejected({ message: "The Markdown could not be rendered.", cause }),
|
|
150
165
|
});
|
|
151
|
-
|
|
166
|
+
const files = draftFilesOf(review.files);
|
|
167
|
+
if ((text.trim() === "" && files.length === 0) ||
|
|
152
168
|
text.length > AGENT_DRAFT_TEXT_LIMIT ||
|
|
153
169
|
finalText.length > provider.limit ||
|
|
154
170
|
plainText.length > provider.limit ||
|
|
@@ -160,6 +176,11 @@ export function reviewSender(input) {
|
|
|
160
176
|
"sent or truncated.",
|
|
161
177
|
});
|
|
162
178
|
}
|
|
179
|
+
// The files the channel cannot send are refused before anything is reserved: no claim spent.
|
|
180
|
+
const filesRefusal = refuseChatFiles(provider, files);
|
|
181
|
+
if (filesRefusal !== undefined) {
|
|
182
|
+
return yield* refused(filesRefusal, providerName);
|
|
183
|
+
}
|
|
163
184
|
// A guest is no user; `agent_draft` is not theirs to approve.
|
|
164
185
|
if (principal.kind === "guest") {
|
|
165
186
|
return yield* new PermissionDenied({ message: "The approver is unknown." });
|
|
@@ -223,7 +244,8 @@ export function reviewSender(input) {
|
|
|
223
244
|
recipients.to[0] === externalId.toLowerCase())
|
|
224
245
|
? recipients
|
|
225
246
|
: undefined;
|
|
226
|
-
const
|
|
247
|
+
const bindings = files.map((file) => [file.entity, file.id, file.property, file.revisionId]);
|
|
248
|
+
const fingerprint = deliveryFingerprint(preview, requester, undefined, undefined, bound, bindings.length === 0 ? undefined : bindings);
|
|
227
249
|
const event = {
|
|
228
250
|
eventId: `chat-delivery:${operationId}:reserve`,
|
|
229
251
|
operationId,
|
|
@@ -253,7 +275,15 @@ export function reviewSender(input) {
|
|
|
253
275
|
toolName: null,
|
|
254
276
|
argsSummary: JSON.stringify(provider.payload(finalText)),
|
|
255
277
|
status: "requested",
|
|
256
|
-
|
|
278
|
+
// The files as the chat's history shows them, as the agent's own sends record them.
|
|
279
|
+
attachments: files.map((file, index) => ({
|
|
280
|
+
id: `chat-delivery:${operationId}:file:${index}`,
|
|
281
|
+
kind: "file",
|
|
282
|
+
filename: file.filename,
|
|
283
|
+
contentType: file.contentType,
|
|
284
|
+
size: file.size,
|
|
285
|
+
})),
|
|
286
|
+
...(bindings.length === 0 ? {} : { files: bindings }),
|
|
257
287
|
requestedBy: requester,
|
|
258
288
|
url: null,
|
|
259
289
|
at: new Date().toISOString(),
|
|
@@ -265,6 +295,44 @@ export function reviewSender(input) {
|
|
|
265
295
|
const archive = onStore
|
|
266
296
|
? storeDeliveryArchive(store, chatRetentionDaysOf(input.ontology.manifest))
|
|
267
297
|
: input.cloud;
|
|
298
|
+
// Files go only through the workspace chat store: the archive in Cloud is not extended.
|
|
299
|
+
// @legacy agent.cloud-chat-archive
|
|
300
|
+
if (files.length > 0 && !onStore) {
|
|
301
|
+
return yield* refused("files_unsupported", providerName);
|
|
302
|
+
}
|
|
303
|
+
// A replay of an approval that sent its files answers that delivery without reading them
|
|
304
|
+
// again: they may since be gone, which must not refuse what was already sent.
|
|
305
|
+
const earlier = files.length === 0 || archive.find === undefined
|
|
306
|
+
? undefined
|
|
307
|
+
: yield* archive
|
|
308
|
+
.find({ delivery: { scope, key, fingerprint }, identityToken: input.identityToken })
|
|
309
|
+
.pipe(Effect.tapError((error) => report("find", error)), Effect.mapError((cause) => new ActionRejected({
|
|
310
|
+
cause,
|
|
311
|
+
message: cause.diagnostic === "chat_archive_conflict"
|
|
312
|
+
? "The reply was already approved by another member, with another " +
|
|
313
|
+
"text or to other people; it is never sent again."
|
|
314
|
+
: "The delivery could not be read, and nothing was sent. Approve again.",
|
|
315
|
+
})));
|
|
316
|
+
if (earlier !== undefined) {
|
|
317
|
+
return {
|
|
318
|
+
status: earlier.status,
|
|
319
|
+
text,
|
|
320
|
+
messageId: earlier.messageId,
|
|
321
|
+
duplicate: true,
|
|
322
|
+
...(recipients === undefined ? {} : { recipients }),
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
// Each file as its person may read it now, the revision held: everything that can fail is
|
|
326
|
+
// read before the claim, so a refusal spends none.
|
|
327
|
+
const sendFiles = yield* readDraftFiles({
|
|
328
|
+
backend,
|
|
329
|
+
person,
|
|
330
|
+
files,
|
|
331
|
+
fetch: input.fetch ?? fetch,
|
|
332
|
+
});
|
|
333
|
+
if (sendFiles === undefined) {
|
|
334
|
+
return yield* refused("file_unavailable", providerName);
|
|
335
|
+
}
|
|
268
336
|
const reservation = archive({
|
|
269
337
|
event,
|
|
270
338
|
delivery: { phase: "reserve", scope, key, fingerprint },
|
|
@@ -376,6 +444,7 @@ export function reviewSender(input) {
|
|
|
376
444
|
threadId,
|
|
377
445
|
operationId,
|
|
378
446
|
chatId,
|
|
447
|
+
...(sendFiles.length === 0 ? {} : { files: sendFiles }),
|
|
379
448
|
...(recipients === undefined ? {} : { recipients }),
|
|
380
449
|
...(input.agent === undefined ? {} : { agent: input.agent }),
|
|
381
450
|
...(input.previews === undefined ? {} : { previews: input.previews }),
|
|
@@ -52,6 +52,8 @@ function payloadFingerprint(event) {
|
|
|
52
52
|
requester.clientName,
|
|
53
53
|
requester.attribution,
|
|
54
54
|
],
|
|
55
|
+
// A message's files bind it only when it has some, so a text's binding stays.
|
|
56
|
+
...(event.files === undefined || event.files.length === 0 ? [] : [{ files: event.files }]),
|
|
55
57
|
]);
|
|
56
58
|
}
|
|
57
59
|
function object(value) {
|
|
@@ -169,6 +171,17 @@ export function storeDeliveryArchive(store, retentionDays) {
|
|
|
169
171
|
: {}),
|
|
170
172
|
...(event.replyToMessageId === null ? {} : { replyTo: event.replyToMessageId }),
|
|
171
173
|
text: event.text,
|
|
174
|
+
// A message's files as its history shows them, as the agent records the files it sends.
|
|
175
|
+
...(event.attachments.length === 0
|
|
176
|
+
? {}
|
|
177
|
+
: {
|
|
178
|
+
files: event.attachments.map((file) => ({
|
|
179
|
+
id: file.id,
|
|
180
|
+
name: file.filename,
|
|
181
|
+
type: file.contentType,
|
|
182
|
+
size: file.size,
|
|
183
|
+
})),
|
|
184
|
+
}),
|
|
172
185
|
at: event.at,
|
|
173
186
|
// Before the provider is called: the receipt settles it, a lost one leaves it unsent.
|
|
174
187
|
status: "pending",
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AgentDraftFile } from "../agent-draft.js";
|
|
1
2
|
import type { ActionRuntime } from "../runtime-source.js";
|
|
2
3
|
import type { ConfirmationStore } from "../runtime/confirmations.js";
|
|
3
4
|
import { Context, Schema, type Effect, type Layer, type Redacted } from "effect";
|
|
@@ -809,6 +810,8 @@ export interface HeldReplyInput {
|
|
|
809
810
|
readonly memberId: string;
|
|
810
811
|
readonly sessionId: string;
|
|
811
812
|
readonly text: string;
|
|
813
|
+
/** Record files the reply carries, as the person could read them when it was held. */
|
|
814
|
+
readonly files?: ReadonlyArray<AgentDraftFile>;
|
|
812
815
|
readonly mode: "always" | "whenUnsure";
|
|
813
816
|
readonly confidence: number | null;
|
|
814
817
|
/** The agent's turn that wrote the reply; absent from agents that predate it. */
|
package/dist/service/service.js
CHANGED
|
@@ -427,6 +427,7 @@ export function createOntologyService(ontology, config) {
|
|
|
427
427
|
deploymentId: deployment.deploymentId,
|
|
428
428
|
}),
|
|
429
429
|
emailSignUp: signUpRolesOf(ontology.manifest, "email") !== undefined,
|
|
430
|
+
manifest: ontology.manifest,
|
|
430
431
|
emailCodes,
|
|
431
432
|
cronSecret: config.cronSecret,
|
|
432
433
|
chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.162.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",
|