@segmentstream/ontology 0.180.0 → 0.182.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 +31 -0
- package/dist/agent-chat.d.ts +2 -2
- package/dist/agent-chat.js +2 -1
- package/dist/agent-draft.d.ts +8 -8
- package/dist/analyze.d.ts +1 -8
- package/dist/analyze.js +108 -52
- package/dist/index.d.ts +1 -1
- package/dist/manifest.d.ts +110 -68
- package/dist/manifest.js +24 -2
- package/dist/migrate/model.d.ts +78 -50
- package/dist/review.d.ts +46 -0
- package/dist/review.js +47 -0
- package/dist/runtime/agent-web.js +47 -26
- package/dist/runtime/agents.js +53 -4
- package/dist/runtime/guests.d.ts +4 -1
- package/dist/runtime/guests.js +24 -5
- package/dist/service/agent/protocol.d.ts +51 -0
- package/dist/service/agent/protocol.js +66 -1
- package/dist/service/agent/server.d.ts +8 -2
- package/dist/service/agent/server.js +208 -48
- package/dist/service/authentication.js +14 -3
- package/dist/service/chat/archive.d.ts +8 -1
- package/dist/service/chat/delivery.js +3 -1
- package/dist/service/chat/envelope.d.ts +8 -8
- package/dist/service/chat/local-reads.d.ts +5 -5
- package/dist/service/chat/providers/custom.js +2 -0
- package/dist/service/chat/providers/provider.d.ts +5 -0
- package/dist/service/chat/reply-proposal.d.ts +122 -0
- package/dist/service/chat/reply-proposal.js +385 -0
- package/dist/service/chat/review-delivery.d.ts +131 -24
- package/dist/service/chat/review-delivery.js +393 -296
- package/dist/service/chat/store-delivery.d.ts +27 -5
- package/dist/service/chat/store-delivery.js +45 -33
- package/dist/service/discovery-search.d.ts +1 -1
- package/dist/service/operations.js +2 -1
- package/dist/service/runtime-contract.d.ts +33 -1
- package/dist/service/runtime-identity.d.ts +1 -0
- package/dist/service/runtime-identity.js +2 -0
- package/dist/service/schemas.d.ts +4 -0
- package/dist/service/service.js +12 -14
- package/dist/service/toolsets.d.ts +1 -1
- package/dist/service/toolsets.js +38 -4
- package/dist/sign-in.d.ts +14 -7
- package/dist/sign-in.js +4 -3
- package/dist/toolset.d.ts +17 -1
- package/dist/workspace-channel.d.ts +6 -0
- package/dist/workspace-channel.js +27 -0
- package/package.json +5 -1
- package/dist/service/agent/public-group-action.d.ts +0 -23
- package/dist/service/agent/public-group-action.js +0 -53
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { ActionRejected, type PermissionDenied } from "../../errors.js";
|
|
3
|
+
import type { Ontology } from "../../ontology.js";
|
|
4
|
+
import { type Review, type ReviewSettings } from "../../review.js";
|
|
5
|
+
import type { ConnectionTransportFactory } from "../connections.js";
|
|
6
|
+
import type { AgentMember, OntologyBackend } from "../runtime-contract.js";
|
|
7
|
+
import type { DeliveryArchive } from "./archive.js";
|
|
8
|
+
import { type DraftFileReference } from "./draft-files.js";
|
|
9
|
+
import type { AgentChannelTransport, ChatFilesRefusal } from "./providers/provider.js";
|
|
10
|
+
import { type AgentReplyDelivered } from "./review-delivery.js";
|
|
11
|
+
/**
|
|
12
|
+
* A turn's reply the agent proposes rather than sends (`POST /api/ontology/agent/replies`, issue
|
|
13
|
+
* #1726). Its key binds the whole reply: the first message's row on the chat store keeps a digest
|
|
14
|
+
* of everything that decides what is sent, written under the key's lock with its reservation, and a
|
|
15
|
+
* held draft holds the reply itself; another reply proposed under the key is refused as
|
|
16
|
+
* `proposal_conflict`, and nothing of it is sent or held. The agent declares `review` and judges a `whenUnsure` reply with its criteria; the
|
|
17
|
+
* ontology decides, with the roles the person holds now, never the ones the session started with:
|
|
18
|
+
*
|
|
19
|
+
* - a reply its review lets go is sent through the chat's channel, as an approved draft is, its
|
|
20
|
+
* delivery claimed on the workspace chat store before the provider is called, and recorded there
|
|
21
|
+
* as the agent's message with its session and turn;
|
|
22
|
+
* - any other reply is held as a pending `agent_draft`, as `POST /api/ontology/agent/drafts` holds
|
|
23
|
+
* one, and a reply nobody judged is held: a missing judgment never sends a reply unreviewed.
|
|
24
|
+
*
|
|
25
|
+
* The proposal's key decides once. What an earlier proposal of it did answers it, read before its
|
|
26
|
+
* files are read again, so a retry after a lost answer finds it however the files changed since.
|
|
27
|
+
* The hold and the first delivery's reservation each take the key's lock and look for the other
|
|
28
|
+
* under it, so overlapping proposals that disagree still decide one way: a reply once held is never
|
|
29
|
+
* sent, nor one sent held, and none is sent twice. The lock never outlasts its transaction: the
|
|
30
|
+
* provider is called after it. A reply goes as the agent sends its own: in the parts a workspace
|
|
31
|
+
* channel's provider takes, then its files in one message with their captions.
|
|
32
|
+
*/
|
|
33
|
+
/** A proposal as the route decoded it. */
|
|
34
|
+
export interface ReplyProposal {
|
|
35
|
+
readonly key: string;
|
|
36
|
+
/** The kind of channel the chat is on. */
|
|
37
|
+
readonly provider: "email" | "custom";
|
|
38
|
+
/** The channel the chat is on, by name. */
|
|
39
|
+
readonly channel: string;
|
|
40
|
+
readonly chatId: string;
|
|
41
|
+
readonly recipient: string;
|
|
42
|
+
readonly to?: ReadonlyArray<string>;
|
|
43
|
+
readonly cc?: ReadonlyArray<string>;
|
|
44
|
+
readonly participants?: ReadonlyArray<string>;
|
|
45
|
+
readonly threadId: string;
|
|
46
|
+
readonly replyTo: string | null;
|
|
47
|
+
readonly memberId: string;
|
|
48
|
+
readonly sessionId: string;
|
|
49
|
+
readonly turnId: string;
|
|
50
|
+
readonly text: string;
|
|
51
|
+
/** The captions of the reply's files, sent with them and held with the reply's text. */
|
|
52
|
+
readonly caption?: string;
|
|
53
|
+
/** Record files the reply carries, which are read as its person may read them now. */
|
|
54
|
+
readonly files: ReadonlyArray<DraftFileReference>;
|
|
55
|
+
readonly review: ReviewSettings;
|
|
56
|
+
readonly confidence: number | null;
|
|
57
|
+
readonly basis: string | null;
|
|
58
|
+
/** A workspace channel's `limits.maxLength`. */
|
|
59
|
+
readonly maxLength?: number;
|
|
60
|
+
}
|
|
61
|
+
/** What became of one delivery: sent, refused (`failed`), or perhaps sent. */
|
|
62
|
+
export type DeliveryOutcome = AgentReplyDelivered["status"];
|
|
63
|
+
/** What the ontology did with a proposed reply, under the review it applied. */
|
|
64
|
+
export type ProposalAnswer = {
|
|
65
|
+
readonly outcome: "held";
|
|
66
|
+
readonly review: Review;
|
|
67
|
+
/** The draft that holds it. */
|
|
68
|
+
readonly draft: string;
|
|
69
|
+
/** Whether an earlier proposal held it. */
|
|
70
|
+
readonly duplicate: boolean;
|
|
71
|
+
} | {
|
|
72
|
+
/** The reply's text, or its files for a reply of files alone. */
|
|
73
|
+
readonly outcome: DeliveryOutcome;
|
|
74
|
+
readonly review: Review;
|
|
75
|
+
/** The provider's id of the reply's first message. */
|
|
76
|
+
readonly messageId: string | null;
|
|
77
|
+
/** Whether an earlier proposal sent it. */
|
|
78
|
+
readonly duplicate: boolean;
|
|
79
|
+
/**
|
|
80
|
+
* Why it was not sent, when it is known: the provider's refusal, or `draft_too_long` for a
|
|
81
|
+
* reply its review holds that is longer than a draft holds.
|
|
82
|
+
*/
|
|
83
|
+
readonly refusal?: string;
|
|
84
|
+
/**
|
|
85
|
+
* What became of the files' message, for a reply of text and files: `unsent` when the text
|
|
86
|
+
* did not go, which they follow.
|
|
87
|
+
*/
|
|
88
|
+
readonly files?: DeliveryOutcome | "unsent";
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* A proposal refused before anything was held or sent: a file its person may no longer read, or
|
|
92
|
+
* files its channel does not send.
|
|
93
|
+
*/
|
|
94
|
+
export interface ProposalFilesRefused {
|
|
95
|
+
readonly refused: ChatFilesRefusal;
|
|
96
|
+
readonly index?: number;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Sends or holds proposals, with one request's identity token. Undefined when the person is no
|
|
100
|
+
* longer an active member, so nothing was held or sent.
|
|
101
|
+
*/
|
|
102
|
+
export type ReplyProposals = (context: {
|
|
103
|
+
readonly backend: OntologyBackend["Service"];
|
|
104
|
+
readonly identityToken: string | undefined;
|
|
105
|
+
readonly requestId: string;
|
|
106
|
+
}) => (proposal: ReplyProposal, member: AgentMember) => Effect.Effect<ProposalAnswer | ProposalFilesRefused | undefined, ActionRejected | PermissionDenied>;
|
|
107
|
+
/** The reply's text and its files' captions, as a held draft and the person read them together. */
|
|
108
|
+
export declare function withCaption(text: string, caption: string | undefined): string;
|
|
109
|
+
/** Sends the replies the review lets go and holds the rest, for the ontology's agent routes. */
|
|
110
|
+
export declare function replyProposals(input: {
|
|
111
|
+
readonly ontology: Ontology;
|
|
112
|
+
readonly connections: ConnectionTransportFactory;
|
|
113
|
+
/** @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message. */
|
|
114
|
+
readonly cloud: DeliveryArchive;
|
|
115
|
+
/** The app's agent at the deployment's production origin, which sends through its channels. */
|
|
116
|
+
readonly agent: {
|
|
117
|
+
readonly origin?: string | undefined;
|
|
118
|
+
readonly fetch?: AgentChannelTransport["fetch"];
|
|
119
|
+
};
|
|
120
|
+
/** Reads a file's bytes by its download grant; `fetch` by default. */
|
|
121
|
+
readonly fetch?: typeof fetch;
|
|
122
|
+
}): ReplyProposals;
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Effect, Schema } from "effect";
|
|
3
|
+
import { addressesOfDraft, AGENT_DRAFT_TEXT_LIMIT, draftFilesOf, participantsOfDraft, } from "../../agent-draft.js";
|
|
4
|
+
import { emailRecipients } from "../../email.js";
|
|
5
|
+
import { ActionRejected } from "../../errors.js";
|
|
6
|
+
import { chatRetentionDaysOf } from "../../manifest.js";
|
|
7
|
+
import { reviewFor, reviewPasses } from "../../review.js";
|
|
8
|
+
import { splitReply, WORKSPACE_CHANNEL_TEXT_LIMIT } from "../../workspace-channel.js";
|
|
9
|
+
import { snapshotDraftFiles } from "./draft-files.js";
|
|
10
|
+
import { agentReplyOperation, deliverAgentReply, earlierAgentReply, prepareAgentReply, } from "./review-delivery.js";
|
|
11
|
+
import { sendBinding, storedReceipt } from "./store-delivery.js";
|
|
12
|
+
/**
|
|
13
|
+
* Who sent a reply the review let go, as the archive records it: the agent, as the platform. The
|
|
14
|
+
* person never sees it.
|
|
15
|
+
*/
|
|
16
|
+
const AGENT_REQUESTER = {
|
|
17
|
+
id: "agent",
|
|
18
|
+
kind: "service",
|
|
19
|
+
name: "agent",
|
|
20
|
+
via: "service",
|
|
21
|
+
clientId: null,
|
|
22
|
+
clientName: null,
|
|
23
|
+
attribution: "agent",
|
|
24
|
+
};
|
|
25
|
+
/** The first delivery's reservation found the key held meanwhile: nothing was reserved. */
|
|
26
|
+
class ProposalHeld extends Schema.TaggedError()("ProposalHeld", {
|
|
27
|
+
draft: Schema.String,
|
|
28
|
+
}) {
|
|
29
|
+
}
|
|
30
|
+
/** A delivery's operation, from what it delivers: the same proposal names the same operation. */
|
|
31
|
+
function operationOf(subject) {
|
|
32
|
+
const hex = createHash("sha256").update(subject).digest("hex");
|
|
33
|
+
return [
|
|
34
|
+
hex.slice(0, 8),
|
|
35
|
+
hex.slice(8, 12),
|
|
36
|
+
`8${hex.slice(13, 16)}`,
|
|
37
|
+
`${((Number.parseInt(hex[16], 16) & 0x3) | 0x8).toString(16)}${hex.slice(17, 20)}`,
|
|
38
|
+
hex.slice(20, 32),
|
|
39
|
+
].join("-");
|
|
40
|
+
}
|
|
41
|
+
/** The reply's text and its files' captions, as a held draft and the person read them together. */
|
|
42
|
+
export function withCaption(text, caption) {
|
|
43
|
+
return [text.trim(), caption?.trim() ?? ""].filter((part) => part !== "").join("\n\n");
|
|
44
|
+
}
|
|
45
|
+
/** Another reply was proposed under a key that decided one: nothing of it is sent or held. */
|
|
46
|
+
function proposalConflict() {
|
|
47
|
+
return new ActionRejected({
|
|
48
|
+
message: "Another reply was proposed under this reply's key, which decided its own; nothing was " +
|
|
49
|
+
"sent or held.",
|
|
50
|
+
refusal: "proposal_conflict",
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The digest of everything that decides what a proposal sends: its chat and whom it goes to, its
|
|
55
|
+
* text, the parts it is sent in, its captions and its files, by their records. The first message's
|
|
56
|
+
* row keeps it, so a replay of the key is the same reply or refused.
|
|
57
|
+
*/
|
|
58
|
+
function proposalBinding(proposal, recipients) {
|
|
59
|
+
return createHash("sha256")
|
|
60
|
+
.update(JSON.stringify([
|
|
61
|
+
proposal.provider,
|
|
62
|
+
proposal.channel,
|
|
63
|
+
proposal.chatId,
|
|
64
|
+
proposal.recipient,
|
|
65
|
+
proposal.threadId,
|
|
66
|
+
proposal.replyTo,
|
|
67
|
+
recipients === undefined ? null : [recipients.to, recipients.cc],
|
|
68
|
+
[...new Set(proposal.participants ?? [])].sort(),
|
|
69
|
+
proposal.memberId,
|
|
70
|
+
proposal.text,
|
|
71
|
+
proposal.caption ?? null,
|
|
72
|
+
proposal.maxLength ?? null,
|
|
73
|
+
proposal.files.map((file) => [file.entity, file.id.toLowerCase(), file.property ?? null]),
|
|
74
|
+
]))
|
|
75
|
+
.digest("hex");
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Whether a draft holds the reply a proposal would hold. What a decision never changes binds it:
|
|
79
|
+
* its chat, whom it goes to and its text with its captions. While it waits, whom it goes to and
|
|
80
|
+
* copies, who reads it and its files are as held too; an approval may change those to what it sent.
|
|
81
|
+
*/
|
|
82
|
+
function draftHolds(draft, proposal, recipients) {
|
|
83
|
+
const text = (value) => (typeof value === "string" ? value : null);
|
|
84
|
+
const same = (one, other) => one.length === other.length && one.every((item, index) => item === other[index]);
|
|
85
|
+
const readers = (list) => [...new Set(list.map((id) => id.toLowerCase()))]
|
|
86
|
+
.filter((id) => id !== proposal.memberId.toLowerCase())
|
|
87
|
+
.sort();
|
|
88
|
+
if (text(draft.channel_kind) !== proposal.provider ||
|
|
89
|
+
(text(draft.channel) ?? text(draft.channel_kind)) !== proposal.channel ||
|
|
90
|
+
text(draft.chat_id) !== proposal.chatId ||
|
|
91
|
+
text(draft.recipient) !== proposal.recipient ||
|
|
92
|
+
(text(draft.thread_id) ?? "") !== proposal.threadId ||
|
|
93
|
+
text(draft.reply_to) !== proposal.replyTo ||
|
|
94
|
+
(text(draft.draft) ?? "") !== withCaption(proposal.text, proposal.caption)) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
if (draft.status !== "pending") {
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
const files = draftFilesOf(draft.files);
|
|
101
|
+
return ((recipients === undefined ||
|
|
102
|
+
(same(addressesOfDraft(draft.to), recipients.to) &&
|
|
103
|
+
same(addressesOfDraft(draft.cc), recipients.cc))) &&
|
|
104
|
+
same(readers(participantsOfDraft(draft.participants)), readers(proposal.participants ?? [])) &&
|
|
105
|
+
files.length === proposal.files.length &&
|
|
106
|
+
files.every((file, index) => {
|
|
107
|
+
const named = proposal.files[index];
|
|
108
|
+
return (file.entity === named.entity &&
|
|
109
|
+
file.id === named.id.toLowerCase() &&
|
|
110
|
+
(named.property === undefined || file.property === named.property));
|
|
111
|
+
}));
|
|
112
|
+
}
|
|
113
|
+
/** A delivery an earlier proposal of the key made, as a replay answers it. */
|
|
114
|
+
function recordedOf(receipt) {
|
|
115
|
+
return {
|
|
116
|
+
status: receipt.status,
|
|
117
|
+
messageId: receipt.messageId,
|
|
118
|
+
duplicate: true,
|
|
119
|
+
...(receipt.refusal === undefined ? {} : { refusal: receipt.refusal }),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* What a reply's deliveries came to, its text's parts then its files' message: `sent` when each
|
|
124
|
+
* part of the text went (its files for a reply of files alone), `failed` when none reached the
|
|
125
|
+
* person, perhaps sent otherwise; the files' own outcome beside it.
|
|
126
|
+
*/
|
|
127
|
+
function answerOf(outcomes, textParts, files, review) {
|
|
128
|
+
const sent = outcomes.slice(0, Math.max(textParts, 1));
|
|
129
|
+
const status = sent.every((outcome) => outcome.status === "sent")
|
|
130
|
+
? "sent"
|
|
131
|
+
: sent.length === 1 && sent[0].status === "failed"
|
|
132
|
+
? "failed"
|
|
133
|
+
: "uncertain";
|
|
134
|
+
const refusal = sent.find((outcome) => outcome.refusal !== undefined)?.refusal;
|
|
135
|
+
const filesOutcome = textParts === 0 || !files ? undefined : (outcomes[textParts]?.status ?? "unsent");
|
|
136
|
+
return {
|
|
137
|
+
outcome: status,
|
|
138
|
+
review,
|
|
139
|
+
messageId: outcomes[0]?.messageId ?? null,
|
|
140
|
+
duplicate: outcomes.length > 0 && outcomes.every((outcome) => outcome.duplicate),
|
|
141
|
+
...(status === "failed" && refusal !== undefined ? { refusal } : {}),
|
|
142
|
+
...(filesOutcome === undefined ? {} : { files: filesOutcome }),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** Sends the replies the review lets go and holds the rest, for the ontology's agent routes. */
|
|
146
|
+
export function replyProposals(input) {
|
|
147
|
+
const retentionDays = chatRetentionDaysOf(input.ontology.manifest);
|
|
148
|
+
return (context) => (proposal, member) => Effect.gen(function* () {
|
|
149
|
+
const { backend } = context;
|
|
150
|
+
const messages = backend.agents?.chatMessages;
|
|
151
|
+
const holdProposal = backend.agents?.holdProposal;
|
|
152
|
+
const reserveProposal = backend.agents?.reserveProposal;
|
|
153
|
+
// The decision and its replay live on the workspace chat store; the route refuses without.
|
|
154
|
+
if (messages === undefined || holdProposal === undefined || reserveProposal === undefined) {
|
|
155
|
+
return yield* new ActionRejected({
|
|
156
|
+
message: "Proposed replies need the workspace chat store; nothing was sent or held.",
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
const transport = {
|
|
160
|
+
ontology: input.ontology,
|
|
161
|
+
connections: input.connections,
|
|
162
|
+
agent: {
|
|
163
|
+
origin: input.agent.origin,
|
|
164
|
+
identityToken: context.identityToken,
|
|
165
|
+
fetch: input.agent.fetch ?? ((request) => fetch(request)),
|
|
166
|
+
},
|
|
167
|
+
cloud: input.cloud,
|
|
168
|
+
backend,
|
|
169
|
+
identityToken: context.identityToken,
|
|
170
|
+
requestId: context.requestId,
|
|
171
|
+
...(input.fetch === undefined ? {} : { fetch: input.fetch }),
|
|
172
|
+
};
|
|
173
|
+
// The review of the person as they are now: their roles decide, not the session's.
|
|
174
|
+
const review = reviewFor(proposal.review, member.principal.roles);
|
|
175
|
+
const held = (draft, duplicate) => ({
|
|
176
|
+
outcome: "held",
|
|
177
|
+
review,
|
|
178
|
+
draft,
|
|
179
|
+
duplicate,
|
|
180
|
+
});
|
|
181
|
+
const recipients = proposal.provider === "email"
|
|
182
|
+
? yield* Effect.try({
|
|
183
|
+
try: () => emailRecipients({ to: proposal.to ?? [proposal.recipient], cc: proposal.cc ?? [] }),
|
|
184
|
+
catch: (cause) => new ActionRejected({ message: "A reply to mail names too many people.", cause }),
|
|
185
|
+
})
|
|
186
|
+
: undefined;
|
|
187
|
+
const binding = proposalBinding(proposal, recipients);
|
|
188
|
+
/** The draft the key holds, read as it is now. */
|
|
189
|
+
const draftOf = backend
|
|
190
|
+
.find({ entity: "agent_draft", query: { where: { key: proposal.key }, limit: 1 } })
|
|
191
|
+
.pipe(Effect.orDie, Effect.map(({ items }) => items[0]));
|
|
192
|
+
/** A draft held under the key answers the same reply held, and refuses another. */
|
|
193
|
+
const heldAs = (draft, id) => draft !== undefined && !draftHolds(draft, proposal, recipients)
|
|
194
|
+
? Effect.fail(proposalConflict())
|
|
195
|
+
: Effect.succeed(held(id, true));
|
|
196
|
+
// A proposal held before answers its draft: a reply once held is never sent by another one.
|
|
197
|
+
const drafted = yield* draftOf;
|
|
198
|
+
if (drafted !== undefined) {
|
|
199
|
+
return yield* heldAs(drafted, String(drafted.id));
|
|
200
|
+
}
|
|
201
|
+
const subject = `agent_reply:${proposal.key}`;
|
|
202
|
+
const firstOperation = agentReplyOperation(subject);
|
|
203
|
+
/** Whether the first message's row binds another reply than this one. */
|
|
204
|
+
const boundElsewhere = (row) => {
|
|
205
|
+
const bound = row === undefined ? undefined : sendBinding(row);
|
|
206
|
+
return bound !== undefined && bound !== binding;
|
|
207
|
+
};
|
|
208
|
+
// A proposal sent before binds its key to its whole reply: another one is refused before any
|
|
209
|
+
// part of it is looked up or sent.
|
|
210
|
+
if (boundElsewhere(yield* messages.findSend(firstOperation))) {
|
|
211
|
+
return yield* proposalConflict();
|
|
212
|
+
}
|
|
213
|
+
const reply = (part) => ({
|
|
214
|
+
// The first message's row keeps what the whole reply is.
|
|
215
|
+
...(part.subject === subject ? { binding } : {}),
|
|
216
|
+
channel: proposal.channel,
|
|
217
|
+
channelKind: proposal.provider,
|
|
218
|
+
declared: false,
|
|
219
|
+
chatId: proposal.chatId,
|
|
220
|
+
recipient: proposal.recipient,
|
|
221
|
+
chatKind: "private",
|
|
222
|
+
threadId: proposal.threadId === "" ? null : proposal.threadId,
|
|
223
|
+
replyTo: proposal.replyTo,
|
|
224
|
+
text: part.text,
|
|
225
|
+
files: part.files,
|
|
226
|
+
...(recipients === undefined ? {} : { recipients }),
|
|
227
|
+
person: proposal.memberId,
|
|
228
|
+
participants: proposal.participants ?? [],
|
|
229
|
+
sessionId: proposal.sessionId,
|
|
230
|
+
turnId: proposal.turnId,
|
|
231
|
+
operationId: operationOf(part.subject),
|
|
232
|
+
subject: part.subject,
|
|
233
|
+
requester: Effect.succeed(AGENT_REQUESTER),
|
|
234
|
+
audit: { action: "agent_reply.propose", principalId: proposal.memberId },
|
|
235
|
+
rejection: (provider, limit) => `The reply is empty or longer than ${limit} characters, which ${provider} accepts in ` +
|
|
236
|
+
"one message; nothing was sent or truncated.",
|
|
237
|
+
});
|
|
238
|
+
// The reply as the agent sends its own: one email, or a workspace channel's parts, each at
|
|
239
|
+
// most what one message through it takes; then its files in a message of their own.
|
|
240
|
+
const texts = proposal.text.trim() === ""
|
|
241
|
+
? []
|
|
242
|
+
: proposal.provider === "custom"
|
|
243
|
+
? splitReply(proposal.text, Math.min(proposal.maxLength ?? WORKSPACE_CHANNEL_TEXT_LIMIT, WORKSPACE_CHANNEL_TEXT_LIMIT))
|
|
244
|
+
: [proposal.text];
|
|
245
|
+
const filesSubject = texts.length === 0 ? subject : `${subject}:files`;
|
|
246
|
+
const withFiles = proposal.files.length > 0;
|
|
247
|
+
const textParts = yield* Effect.forEach(texts, (text, index) => prepareAgentReply(transport, reply({ subject: index === 0 ? subject : `${subject}:${index}`, text, files: [] })).pipe(Effect.result));
|
|
248
|
+
// What earlier proposals of the key delivered, in order, read before the files are read
|
|
249
|
+
// again: a part that did not go ends the reply, as does its last part recorded.
|
|
250
|
+
const recorded = [];
|
|
251
|
+
let ended = false;
|
|
252
|
+
let whole = true;
|
|
253
|
+
for (const part of textParts) {
|
|
254
|
+
const earlier = part._tag === "Failure" ? undefined : yield* earlierAgentReply(transport, part.success);
|
|
255
|
+
if (earlier === undefined) {
|
|
256
|
+
whole = false;
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
recorded.push(recordedOf(earlier));
|
|
260
|
+
if (earlier.status !== "sent") {
|
|
261
|
+
ended = true;
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (!ended && whole && withFiles) {
|
|
266
|
+
// The files' message by its key alone: its files bind it as they were then.
|
|
267
|
+
const operation = agentReplyOperation(filesSubject);
|
|
268
|
+
const row = yield* messages.findSend(operation);
|
|
269
|
+
if (row === undefined) {
|
|
270
|
+
whole = false;
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
recorded.push(recordedOf(storedReceipt(row, { operation, retentionDays, reported: true })));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (recorded.length > 0 && (ended || whole)) {
|
|
277
|
+
return answerOf(recorded, texts.length, withFiles, review);
|
|
278
|
+
}
|
|
279
|
+
// Each file as the person may read it now, and as the channel sends it.
|
|
280
|
+
const snapshot = !withFiles
|
|
281
|
+
? { files: [] }
|
|
282
|
+
: yield* snapshotDraftFiles({
|
|
283
|
+
manifest: input.ontology.manifest,
|
|
284
|
+
backend,
|
|
285
|
+
principal: member.principal,
|
|
286
|
+
channel: proposal.channel,
|
|
287
|
+
files: proposal.files,
|
|
288
|
+
});
|
|
289
|
+
if ("refusal" in snapshot) {
|
|
290
|
+
return {
|
|
291
|
+
refused: snapshot.refusal,
|
|
292
|
+
...(snapshot.index === undefined ? {} : { index: snapshot.index }),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
const files = snapshot.files;
|
|
296
|
+
const prepared = [
|
|
297
|
+
...textParts,
|
|
298
|
+
...(files.length === 0
|
|
299
|
+
? []
|
|
300
|
+
: [
|
|
301
|
+
yield* prepareAgentReply(transport, reply({ subject: filesSubject, text: proposal.caption?.trim() ?? "", files })).pipe(Effect.result),
|
|
302
|
+
]),
|
|
303
|
+
];
|
|
304
|
+
// A reply its review holds, unless a proposal of it began its delivery: under the key's
|
|
305
|
+
// lock, which that delivery's reservation takes too.
|
|
306
|
+
if (recorded.length === 0 && !reviewPasses(review, proposal.confidence)) {
|
|
307
|
+
const text = withCaption(proposal.text, proposal.caption);
|
|
308
|
+
// A reply longer than a draft holds is neither truncated nor sent unreviewed.
|
|
309
|
+
if (text.length > AGENT_DRAFT_TEXT_LIMIT) {
|
|
310
|
+
yield* Effect.logWarning("ontology.agent.reply_too_long_to_hold").pipe(Effect.annotateLogs({
|
|
311
|
+
requestId: context.requestId,
|
|
312
|
+
channel: proposal.channel,
|
|
313
|
+
characters: text.length,
|
|
314
|
+
}));
|
|
315
|
+
return {
|
|
316
|
+
outcome: "failed",
|
|
317
|
+
review,
|
|
318
|
+
messageId: null,
|
|
319
|
+
duplicate: false,
|
|
320
|
+
refusal: "draft_too_long",
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
const draft = yield* holdProposal({
|
|
324
|
+
key: proposal.key,
|
|
325
|
+
provider: proposal.provider,
|
|
326
|
+
channel: proposal.channel,
|
|
327
|
+
chatId: proposal.chatId,
|
|
328
|
+
recipient: proposal.recipient,
|
|
329
|
+
...(recipients === undefined ? {} : { to: recipients.to, cc: recipients.cc }),
|
|
330
|
+
...(proposal.participants === undefined ? {} : { participants: proposal.participants }),
|
|
331
|
+
threadId: proposal.threadId,
|
|
332
|
+
replyTo: proposal.replyTo,
|
|
333
|
+
memberId: proposal.memberId,
|
|
334
|
+
sessionId: proposal.sessionId,
|
|
335
|
+
text,
|
|
336
|
+
...(files.length === 0 ? {} : { files }),
|
|
337
|
+
mode: review.mode === "always" ? "always" : "whenUnsure",
|
|
338
|
+
confidence: proposal.confidence,
|
|
339
|
+
turnId: proposal.turnId,
|
|
340
|
+
...(proposal.basis === null ? {} : { basis: proposal.basis }),
|
|
341
|
+
}, messages
|
|
342
|
+
.findSend(agentReplyOperation(subject))
|
|
343
|
+
.pipe(Effect.map((row) => row !== undefined)));
|
|
344
|
+
if (draft === undefined) {
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
if (draft !== "delivered") {
|
|
348
|
+
return draft.created ? held(draft.id, false) : yield* heldAs(yield* draftOf, draft.id);
|
|
349
|
+
}
|
|
350
|
+
// Another proposal of the key began its delivery meanwhile: its delivery answers this one.
|
|
351
|
+
}
|
|
352
|
+
const ready = [];
|
|
353
|
+
for (const part of prepared) {
|
|
354
|
+
if (part._tag === "Failure") {
|
|
355
|
+
return yield* part.failure;
|
|
356
|
+
}
|
|
357
|
+
ready.push(part.success);
|
|
358
|
+
}
|
|
359
|
+
// One message after another, as the agent sends its own: a part that did not go stops the
|
|
360
|
+
// rest, and files follow only a text that went. The first part's reservation decides the key
|
|
361
|
+
// under its lock, against a hold of it.
|
|
362
|
+
const outcomes = [];
|
|
363
|
+
for (const [index, part] of ready.entries()) {
|
|
364
|
+
const delivered = yield* deliverAgentReply(transport, part, index > 0
|
|
365
|
+
? (reservation) => reservation
|
|
366
|
+
: (reservation) => reserveProposal({
|
|
367
|
+
key: proposal.key,
|
|
368
|
+
// Under the key's lock: a proposal of another reply reserved first binds it.
|
|
369
|
+
reserve: messages
|
|
370
|
+
.findSend(firstOperation)
|
|
371
|
+
.pipe(Effect.flatMap((row) => boundElsewhere(row) ? Effect.fail(proposalConflict()) : reservation)),
|
|
372
|
+
}).pipe(Effect.flatMap((decided) => decided.kind === "held"
|
|
373
|
+
? Effect.fail(new ProposalHeld({ draft: decided.review.id }))
|
|
374
|
+
: Effect.succeed(decided.value)))).pipe(Effect.map((outcome) => ({ outcome })), Effect.catchTag("ProposalHeld", (error) => Effect.succeed({ draft: error.draft })));
|
|
375
|
+
if ("draft" in delivered) {
|
|
376
|
+
return yield* heldAs(yield* draftOf, delivered.draft);
|
|
377
|
+
}
|
|
378
|
+
outcomes.push(delivered.outcome);
|
|
379
|
+
if (delivered.outcome.status !== "sent") {
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return answerOf(outcomes, texts.length, withFiles, review);
|
|
384
|
+
});
|
|
385
|
+
}
|