@segmentstream/agent 0.101.0 → 0.102.1

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 CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.102.1
4
+
5
+ WhatsApp no longer loses a message that a person sends while the agent is still handling their
6
+ previous one. Before, a second message that arrived on the same instance while the first was
7
+ still being admitted, triaged or transcribed was dropped, after Meta had already been answered,
8
+ so the agent never read it. Now it reaches the agent and joins the running turn. A message Meta
9
+ delivers again still starts only one turn.
10
+
11
+ No configuration changes.
12
+
13
+ ## 0.102.0
14
+
15
+ On email and workspace channels, an agent with `review` proposes each turn's reply to the
16
+ ontology service instead of sending or holding it itself, so the review applies with the roles the
17
+ person holds when the reply is written, never the ones their session started with. The agent still
18
+ judges a reply its session's roles review `whenUnsure` and sends the confidence; the criteria stay
19
+ in the agent. The ontology sends or holds the reply and records it in the chat. Without `review`,
20
+ replies are sent as before.
21
+
22
+ Action required: upgrade `@segmentstream/ontology` with the agent SDK. An ontology service released
23
+ before proposals answers 404, and the agent then reviews the reply itself by the session's roles,
24
+ as before; that fallback is deprecated and stops on 2027-05-28 (`agent.reply-proposals-fallback`),
25
+ after which the agent requires an ontology SDK that serves `POST /api/ontology/agent/replies`.
26
+
27
+ Pins @segmentstream/ontology 0.181.0.
28
+
3
29
  ## 0.101.0
4
30
 
5
31
  `segmentstream__attachments_send` sends files in Telegram and Slack up to the providers' own
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- var version = "0.101.0";
7
+ var version = "0.102.1";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { t as agentBuild } from "../../_chunks/build-metadata-Cgy-C9_E.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-Bnac65E-.mjs";
@@ -66,6 +66,8 @@ export interface EmailChannelOptions {
66
66
  /** Tests pass an archive and a hold in place of the ontology's. */
67
67
  readonly archive?: ChatArchive;
68
68
  readonly hold?: Parameters<typeof channelReview>[0]["hold"];
69
+ /** Tests pass a proposal in place of the ontology's. */
70
+ readonly propose?: Parameters<typeof channelReview>[0]["propose"];
69
71
  /** Sends a passed reply's files; without it such a reply is held. */
70
72
  readonly sendFiles?: Parameters<typeof channelReview>[0]["sendFiles"];
71
73
  };
@@ -50,6 +50,7 @@ var MessageTimeout = class extends Error {
50
50
  };
51
51
  const REPLY_ATTEMPTS = 4;
52
52
  const REPLY_RETRY_MS = 2e3;
53
+ const DELIVER_ATTEMPTS = 3;
53
54
  const REPLY_WAKE_AFTER_MS = 6e5;
54
55
  const REPLY_EXPIRY_MS = 2592e5;
55
56
  const REPLIES_PER_WAKE = 10;
@@ -247,6 +248,7 @@ function emailChannelDefinition(options) {
247
248
  model: options.review.model,
248
249
  ...options.review.archive === void 0 ? {} : { archive: options.review.archive },
249
250
  ...options.review.hold === void 0 ? {} : { hold: options.review.hold },
251
+ ...options.review.propose === void 0 ? {} : { propose: options.review.propose },
250
252
  ...options.review.sendFiles === void 0 ? {} : { sendFiles: options.review.sendFiles }
251
253
  }, {
252
254
  environment,
@@ -1016,7 +1018,7 @@ function emailChannelDefinition(options) {
1016
1018
  });
1017
1019
  return;
1018
1020
  }
1019
- if (!(reviewing === void 0 ? true : await reviewing.sendOrHold({
1021
+ const written = {
1020
1022
  principal,
1021
1023
  sessionId: ctx.session.id,
1022
1024
  turnId,
@@ -1027,7 +1029,32 @@ function emailChannelDefinition(options) {
1027
1029
  cc
1028
1030
  },
1029
1031
  ...files === void 0 || files.files.length === 0 ? {} : { files }
1030
- }))) return;
1032
+ };
1033
+ const proposed = reviewing !== void 0 && reviewing.proposes(principal) ? await reviewing.propose(written) : void 0;
1034
+ if (proposed?.by === "ontology") {
1035
+ if (proposed.outcome !== "sent" && proposed.outcome !== "held") {
1036
+ log("[segmentstream] email reply failed", {
1037
+ sessionId: ctx.session.id,
1038
+ outcome: proposed.outcome,
1039
+ ...proposed.refusal === void 0 ? {} : { refusal: proposed.refusal }
1040
+ });
1041
+ if (files !== void 0 && files.files.length > 0) await reviewing.holdFiles({
1042
+ principal,
1043
+ sessionId: ctx.session.id,
1044
+ turnId,
1045
+ files,
1046
+ recipients: {
1047
+ to: [chat.peer],
1048
+ cc
1049
+ }
1050
+ });
1051
+ } else if (proposed.outcome === "sent" && proposed.files !== void 0 && proposed.files !== "sent") log("[segmentstream] a passed reply's files were not all sent", {
1052
+ sessionId: ctx.session.id,
1053
+ outcome: proposed.files
1054
+ });
1055
+ return;
1056
+ }
1057
+ if (!(proposed !== void 0 ? proposed.send : reviewing === void 0 ? true : await reviewing.sendOrHold(written))) return;
1031
1058
  const memberId = memberIdOf(principal);
1032
1059
  const participantIds = participantsOf(principal) ?? (memberId === void 0 ? [] : [memberId]);
1033
1060
  const reply = {
@@ -1126,15 +1153,22 @@ function emailChannelDefinition(options) {
1126
1153
  return Response.json({ error: "file_unavailable" }, { status: 422 });
1127
1154
  }
1128
1155
  try {
1129
- const id = await mailbox().reply({
1130
- threadId,
1131
- to,
1132
- ...cc.length === 0 ? {} : { cc },
1133
- text,
1134
- key,
1135
- ...attachments.length === 0 ? {} : { attachments },
1136
- ...withSignature()
1137
- });
1156
+ let id;
1157
+ for (let attempt = 1;; attempt++) try {
1158
+ id = await mailbox().reply({
1159
+ threadId,
1160
+ to,
1161
+ ...cc.length === 0 ? {} : { cc },
1162
+ text,
1163
+ key,
1164
+ ...attachments.length === 0 ? {} : { attachments },
1165
+ ...withSignature()
1166
+ });
1167
+ break;
1168
+ } catch (error) {
1169
+ if (!retryable(error) || attempt >= DELIVER_ATTEMPTS) throw error;
1170
+ await sleep(REPLY_RETRY_MS * 4 ** (attempt - 1));
1171
+ }
1138
1172
  return Response.json({ message_id: id === "" ? null : id });
1139
1173
  } catch (cause) {
1140
1174
  const reference = report("deliver_failed", cause);
@@ -1,4 +1,6 @@
1
+ import type { Review as PolicyReview, ReviewSettings as PolicySettings } from "@segmentstream/ontology/review";
1
2
  import type { RuntimeToken } from "../runtime-token.js";
3
+ import type { ReplyFile } from "./files.js";
2
4
  import type { HoldReply } from "./hold.js";
3
5
  /**
4
6
  * Reports a reply kept for review to the ontology service, which records it as a pending
@@ -11,6 +13,79 @@ export declare function agentReviews(input: {
11
13
  readonly token: RuntimeToken;
12
14
  readonly fetch?: typeof fetch;
13
15
  }): HoldReply;
16
+ /** The review the ontology applied, with the roles the person held when it decided. */
17
+ export type AppliedReview = PolicyReview;
18
+ /** What the ontology service did with a turn's reply the agent proposed. */
19
+ export type ProposalOutcome = {
20
+ readonly outcome: "held";
21
+ readonly review: AppliedReview;
22
+ readonly draft: string;
23
+ } | {
24
+ /** The reply's text, or its files for a reply of files alone. */
25
+ readonly outcome: "sent" | "uncertain" | "failed";
26
+ readonly review: AppliedReview;
27
+ readonly messageId: string | null;
28
+ /** Why the provider refused a `failed` reply, when it says. */
29
+ readonly refusal?: string;
30
+ /** What became of the files' message after the text: `unsent` when the text did not go. */
31
+ readonly files?: "sent" | "uncertain" | "failed" | "unsent";
32
+ }
33
+ /**
34
+ * @legacy agent.reply-proposals-fallback
35
+ * An ontology service from before proposals answered 404: the channel reviews the reply itself.
36
+ */
37
+ | {
38
+ readonly outcome: "unsupported";
39
+ };
40
+ /**
41
+ * The reply of a turn, proposed to the ontology service (`POST /api/ontology/agent/replies`) in
42
+ * place of sending it: the ontology applies `review` with the roles the person holds now, and sends
43
+ * or holds it. Its criteria stay here: only the modes and thresholds go.
44
+ */
45
+ export interface ProposedReply {
46
+ /** Names the reply, so a proposal repeated after a failure finds what became of it. */
47
+ readonly key: string;
48
+ readonly provider: "email" | "custom";
49
+ /** The channel the chat is on, by name, when it is not the one named after its kind. */
50
+ readonly channel?: string;
51
+ readonly chatId: string;
52
+ readonly recipient: string;
53
+ readonly threadId: string;
54
+ readonly replyTo: string | null;
55
+ /** A reply to mail: whom it goes to and copies. */
56
+ readonly to?: ReadonlyArray<string>;
57
+ readonly cc?: ReadonlyArray<string>;
58
+ /** The members who read it, in a chat several people share, its member among them. */
59
+ readonly participants?: ReadonlyArray<string>;
60
+ readonly memberId: string;
61
+ readonly sessionId: string;
62
+ readonly turnId: string;
63
+ readonly text: string;
64
+ /** The captions the reply's files were attached with. */
65
+ readonly caption?: string;
66
+ readonly files?: ReadonlyArray<ReplyFile>;
67
+ /** The agent's review for the channel, without its criteria. */
68
+ readonly review: PolicySettings;
69
+ /** The decision model's probability that staff would send it as written; null when unjudged. */
70
+ readonly confidence: number | null;
71
+ /** Where the chat stood when the turn read it, `<time>~<id>`; null when unknown. */
72
+ readonly basis: string | null;
73
+ /** A workspace channel's `limits.maxLength`, in whose parts a longer reply is sent. */
74
+ readonly maxLength?: number;
75
+ }
76
+ /** Proposes a turn's reply; resolves what became of it. */
77
+ export type ProposeReply = (reply: ProposedReply) => Promise<ProposalOutcome>;
78
+ /**
79
+ * Proposes a turn's reply to the ontology service, which sends or holds it by `review` and the
80
+ * roles the person holds now. A refusal, or an answer the agent does not know, rejects, so the
81
+ * reply is neither sent nor lost silently; an ontology service that predates proposals answers
82
+ * 404, which resolves `unsupported`.
83
+ */
84
+ export declare function agentReplies(input: {
85
+ readonly origin: string;
86
+ readonly token: RuntimeToken;
87
+ readonly fetch?: typeof fetch;
88
+ }): ProposeReply;
14
89
  /** What became of a reply an agent session held for review, as the ontology service answers. */
15
90
  export interface SessionReview {
16
91
  readonly id: string;
@@ -99,6 +99,108 @@ function agentReviews(input) {
99
99
  }
100
100
  };
101
101
  }
102
+ const PROPOSAL_TIMEOUT_MS = 2e5;
103
+ const DELIVERY_OUTCOMES = new Set([
104
+ "sent",
105
+ "uncertain",
106
+ "failed"
107
+ ]);
108
+ function appliedReview(value) {
109
+ if (!isRecord(value)) return;
110
+ if (value.mode === "never" || value.mode === "always") return { mode: value.mode };
111
+ return value.mode === "whenUnsure" && typeof value.min_confidence === "number" && Number.isFinite(value.min_confidence) ? {
112
+ mode: "whenUnsure",
113
+ minConfidence: value.min_confidence
114
+ } : void 0;
115
+ }
116
+ function agentReplies(input) {
117
+ const fetchImpl = input.fetch ?? fetch;
118
+ return async (reply) => {
119
+ const token = await input.token();
120
+ let response;
121
+ try {
122
+ response = await fetchImpl(`${input.origin}/api/ontology/agent/replies`, {
123
+ method: "POST",
124
+ headers: {
125
+ authorization: `Bearer ${token}`,
126
+ ...ontologyDeploymentHeaders(),
127
+ accept: "application/json",
128
+ "content-type": "application/json"
129
+ },
130
+ body: JSON.stringify({
131
+ key: reply.key,
132
+ provider: reply.provider,
133
+ ...reply.channel === void 0 ? {} : { channel: reply.channel },
134
+ chat_id: reply.chatId,
135
+ recipient: reply.recipient,
136
+ ...reply.to === void 0 ? {} : {
137
+ to: reply.to,
138
+ cc: reply.cc ?? []
139
+ },
140
+ ...reply.participants === void 0 ? {} : { participants: reply.participants },
141
+ thread_id: reply.threadId,
142
+ reply_to: reply.replyTo,
143
+ member_id: reply.memberId,
144
+ session_id: reply.sessionId,
145
+ text: reply.text,
146
+ ...reply.caption === void 0 ? {} : { caption: reply.caption },
147
+ ...reply.files === void 0 || reply.files.length === 0 ? {} : { files: reply.files.map((file) => ({
148
+ entity: file.entity,
149
+ id: file.id,
150
+ property: file.property
151
+ })) },
152
+ turn_id: reply.turnId,
153
+ review: reply.review,
154
+ confidence: reply.confidence,
155
+ basis: reply.basis,
156
+ ...reply.maxLength === void 0 ? {} : { max_length: reply.maxLength }
157
+ }),
158
+ redirect: "error",
159
+ signal: AbortSignal.timeout(PROPOSAL_TIMEOUT_MS)
160
+ });
161
+ } catch (error) {
162
+ throw new AgentIdentityError({
163
+ code: "unavailable",
164
+ message: "The ontology service could not be reached to propose a reply.",
165
+ cause: redactDiagnostic(error, new Set([token]))
166
+ });
167
+ }
168
+ if (response.status === 404) {
169
+ await response.body?.cancel();
170
+ return { outcome: "unsupported" };
171
+ }
172
+ if (!response.ok) {
173
+ const error = await refusal(response, "reply proposal");
174
+ throw new AgentIdentityError({
175
+ code: error.code,
176
+ ...error.status === void 0 ? {} : { status: error.status },
177
+ ...error.requestId === void 0 ? {} : { requestId: error.requestId },
178
+ message: redactDiagnostic(error.message, new Set([token])),
179
+ cause: redactDiagnostic(error, new Set([token]))
180
+ });
181
+ }
182
+ const body = await response.json().catch(() => void 0);
183
+ const review = isRecord(body) ? appliedReview(body.review) : void 0;
184
+ if (isRecord(body) && review !== void 0) {
185
+ if (body.outcome === "held" && typeof body.draft === "string") return {
186
+ outcome: "held",
187
+ review,
188
+ draft: body.draft
189
+ };
190
+ if (typeof body.outcome === "string" && DELIVERY_OUTCOMES.has(body.outcome) && (body.message_id === null || typeof body.message_id === "string")) return {
191
+ outcome: body.outcome,
192
+ review,
193
+ messageId: body.message_id,
194
+ ...typeof body.refusal === "string" ? { refusal: body.refusal } : {},
195
+ ...body.files === "sent" || body.files === "uncertain" || body.files === "failed" || body.files === "unsent" ? { files: body.files } : {}
196
+ };
197
+ }
198
+ throw new AgentIdentityError({
199
+ code: "unavailable",
200
+ message: "The ontology service answered a reply proposal it did not describe."
201
+ });
202
+ };
203
+ }
102
204
  async function refusedFields(response) {
103
205
  try {
104
206
  const body = await response.clone().json();
@@ -159,4 +261,4 @@ function agentSessionReviews(input) {
159
261
  }] : []);
160
262
  };
161
263
  }
162
- export { agentReviews, agentSessionReviews };
264
+ export { agentReplies, agentReviews, agentSessionReviews };
@@ -1,5 +1,7 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
+ import type { ReviewSettings as PolicySettings } from "@segmentstream/ontology/review";
2
3
  import { type ReviewSettings, type Review } from "../../review.js";
4
+ import type { ProposedReply } from "./client.js";
3
5
  import type { ReplyFile } from "./files.js";
4
6
  /**
5
7
  * Whether the agent sends a reply itself or holds it for a member to review, by the review of the
@@ -93,6 +95,28 @@ export declare function repliesReviewed(settings: ReviewSettings | undefined, pr
93
95
  * gives no probability holds it, so a model outage never sends an unreviewed reply.
94
96
  */
95
97
  export declare function reviewOutcome(review: Review, judge: (criteria: string | undefined) => Promise<number | undefined>, onJudgeFailure?: (error: unknown) => void): Promise<ReviewOutcome>;
98
+ /**
99
+ * The proposal of a turn's reply to `principal` on a channel whose replies the ontology sends,
100
+ * an email or a workspace channel; undefined on another channel, or when the session has no chat
101
+ * or member to propose it for.
102
+ */
103
+ export declare function proposedReply(input: {
104
+ readonly principal: SessionAuthContext | null | undefined;
105
+ readonly sessionId: string;
106
+ readonly partId: string;
107
+ readonly turnId: string;
108
+ readonly text: string;
109
+ readonly caption?: string;
110
+ readonly files?: ReadonlyArray<ReplyFile>;
111
+ /** A reply to mail: whom it goes to and copies. */
112
+ readonly recipients?: {
113
+ readonly to: ReadonlyArray<string>;
114
+ readonly cc: ReadonlyArray<string>;
115
+ };
116
+ readonly review: PolicySettings;
117
+ readonly confidence: number | null;
118
+ readonly maxLength?: number;
119
+ }): ProposedReply | undefined;
96
120
  /**
97
121
  * The held reply for a final reply to `principal`, or undefined when the session has no
98
122
  * chat or member to hold it for, as a workflow task's session does.
@@ -38,6 +38,36 @@ async function reviewOutcome(review, judge, onJudgeFailure = () => void 0) {
38
38
  confidence: confidence ?? null
39
39
  };
40
40
  }
41
+ function proposedReply(input) {
42
+ const chat = chatAddressOf(input.principal);
43
+ const memberId = memberIdOf(input.principal);
44
+ const participants = participantsOf(input.principal);
45
+ if (chat === void 0 || memberId === void 0 || chat.provider !== "email" && chat.provider !== "custom") return;
46
+ return {
47
+ key: `${input.sessionId}:${input.partId}`,
48
+ provider: chat.provider,
49
+ ...chat.channel === void 0 ? {} : { channel: chat.channel },
50
+ chatId: chat.chatId,
51
+ recipient: chat.kind === "private" && chat.peer !== void 0 ? chat.peer : chat.chatId,
52
+ threadId: chat.threadId,
53
+ replyTo: null,
54
+ ...chat.provider === "email" && input.recipients !== void 0 ? {
55
+ to: input.recipients.to,
56
+ cc: input.recipients.cc
57
+ } : {},
58
+ ...participants === void 0 ? {} : { participants },
59
+ memberId,
60
+ sessionId: input.sessionId,
61
+ turnId: input.turnId,
62
+ text: input.text,
63
+ ...input.caption === void 0 || input.caption === "" ? {} : { caption: input.caption },
64
+ ...input.files === void 0 || input.files.length === 0 ? {} : { files: input.files },
65
+ review: input.review,
66
+ confidence: input.confidence,
67
+ basis: null,
68
+ ...input.maxLength === void 0 ? {} : { maxLength: input.maxLength }
69
+ };
70
+ }
41
71
  function heldReply(input) {
42
72
  const chat = chatAddressOf(input.principal);
43
73
  const memberId = memberIdOf(input.principal);
@@ -66,4 +96,4 @@ function heldReply(input) {
66
96
  ...input.turnId === void 0 || input.turnId === null || input.turnId === "" ? {} : { turnId: input.turnId }
67
97
  };
68
98
  }
69
- export { heldReply, repliesReviewed, reviewOf, reviewOutcome };
99
+ export { heldReply, proposedReply, repliesReviewed, reviewOf, reviewOutcome };
@@ -1,9 +1,10 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
2
  import type { SessionView } from "eve/events";
3
- import type { ReviewSettings } from "../../review.js";
3
+ import { type ReviewSettings } from "../../review.js";
4
4
  import { type ChatArchive } from "../chat-archive.js";
5
5
  import { type Environment } from "../environment.js";
6
6
  import type { RuntimeToken } from "../runtime-token.js";
7
+ import { type ProposalOutcome, type ProposeReply } from "./client.js";
7
8
  import { type HoldReply } from "./hold.js";
8
9
  import { type ReviewDecideFunction } from "./judge.js";
9
10
  import { type ReplyFiles } from "./files.js";
@@ -15,6 +16,37 @@ import { type ReplyFiles } from "./files.js";
15
16
  export interface ReplyReview {
16
17
  /** Whether replies to `principal` are reviewed: their review is not `never`. */
17
18
  reviewed(principal: SessionAuthContext | null | undefined): boolean;
19
+ /**
20
+ * Whether a turn's reply to `principal` is proposed to the ontology rather than sent or held
21
+ * here: the agent has `review`, and the chat is on an email or a workspace channel, whose replies
22
+ * the ontology sends.
23
+ */
24
+ proposes(principal: SessionAuthContext | null | undefined): boolean;
25
+ /**
26
+ * Proposes a turn's reply to the ontology, which applies `review` with the roles the person
27
+ * holds now and sends or holds it: the judge still reads a reply whose review by the session's
28
+ * roles is `whenUnsure`, and its confidence goes with the proposal. Files past a draft's ten go in
29
+ * proposals of their own once the reply was sent or held. Answers what the ontology did, or, from
30
+ * an ontology that predates proposals, whether the channel may send the reply itself after
31
+ * {@link ReplyReview.sendOrHold}. Throws when the ontology refused it, so the reply is neither
32
+ * sent nor lost silently.
33
+ */
34
+ propose(input: {
35
+ readonly principal: SessionAuthContext | null | undefined;
36
+ readonly sessionId: string;
37
+ readonly turnId: string;
38
+ readonly partId: string;
39
+ readonly text: string;
40
+ /** A reply to mail: whom it goes to and copies. */
41
+ readonly recipients?: {
42
+ readonly to: ReadonlyArray<string>;
43
+ readonly cc: ReadonlyArray<string>;
44
+ };
45
+ /** The files `attachments_send` attached to the turn's reply, and their captions. */
46
+ readonly files?: ReplyFiles;
47
+ /** A workspace channel's `limits.maxLength`: the ontology sends a longer reply in parts. */
48
+ readonly maxLength?: number;
49
+ }): Promise<ProposedOutcome>;
18
50
  /**
19
51
  * Whether the channel may send `text` now: true for a chat that is not reviewed, or a
20
52
  * reply the judge passed; false once the reply is held for review. Throws when it could not be
@@ -64,6 +96,20 @@ export interface ReplyReview {
64
96
  };
65
97
  }): Promise<void>;
66
98
  }
99
+ /** What became of a turn's reply a channel proposed. */
100
+ export type ProposedOutcome = (Exclude<ProposalOutcome, {
101
+ readonly outcome: "unsupported";
102
+ }> & {
103
+ readonly by: "ontology";
104
+ }) | {
105
+ /**
106
+ * @legacy agent.reply-proposals-fallback
107
+ * The ontology predates proposals: the reply was reviewed here, by the session's roles, and
108
+ * the channel sends it itself when `send` is true, as before.
109
+ */
110
+ readonly by: "agent";
111
+ readonly send: boolean;
112
+ };
67
113
  export declare function replyReview(options: {
68
114
  readonly settings: () => ReviewSettings | undefined;
69
115
  readonly decide: ReviewDecideFunction;
@@ -71,6 +117,11 @@ export declare function replyReview(options: {
71
117
  readonly model: () => string;
72
118
  readonly archive: ChatArchive;
73
119
  readonly hold: HoldReply;
120
+ /**
121
+ * Proposes a turn's reply to the ontology, which sends or holds it; without it, the channels
122
+ * review their replies here, as before proposals.
123
+ */
124
+ readonly propose?: ProposeReply;
74
125
  /**
75
126
  * Sends a passed reply's files in the chat; without it a reply with files is always held, so
76
127
  * they are never lost or sent unreviewed.
@@ -121,6 +172,8 @@ export interface ChannelReviewOptions {
121
172
  readonly model: () => string;
122
173
  /** Holds a reply for review; tests pass a fake. */
123
174
  readonly hold?: HoldReply;
175
+ /** Proposes a turn's reply to the ontology; tests pass a fake. */
176
+ readonly propose?: ProposeReply;
124
177
  /** The chat archive; tests pass a fake. */
125
178
  readonly archive?: ChatArchive;
126
179
  /** Sends a passed reply's files; without it such a reply is held. */
@@ -4,13 +4,14 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
+ import { reviewPolicy } from "../../review.mjs";
7
8
  import { Ft as chatAddressOf, It as chatChannel, i as memberIdOf } from "../../../_chunks/principal-DL9NdRRP.mjs";
8
9
  import { a as chatEvent, r as chatArchive } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
9
10
  import { stampedChat } from "../chat-recorder.mjs";
10
11
  import { appOrigin } from "../environment.mjs";
11
- import { agentReviews } from "./client.mjs";
12
+ import { agentReplies, agentReviews } from "./client.mjs";
12
13
  import { _ as withCaptions, h as partFiles, m as filesAfterReply, n as completionKind, p as fileGroups } from "../../../_chunks/silent-xJcJ8SNJ.mjs";
13
- import { heldReply, repliesReviewed, reviewOf, reviewOutcome } from "./hold.mjs";
14
+ import { heldReply, proposedReply, repliesReviewed, reviewOf, reviewOutcome } from "./hold.mjs";
14
15
  import { judgeReply, readChat } from "./judge.mjs";
15
16
  const VERDICTS_REMEMBERED = 512;
16
17
  function reviewedChat(principal) {
@@ -39,8 +40,150 @@ function replyReview(options) {
39
40
  }
40
41
  return outcome;
41
42
  };
43
+ const recorded = (principal) => ({
44
+ coordinates: reviewedChat(principal),
45
+ memberId: memberIdOf(principal)
46
+ });
47
+ const record = async (input, reason, summary) => {
48
+ const { coordinates, memberId } = recorded(input.principal);
49
+ if (coordinates === void 0) return;
50
+ await options.archive.append(chatEvent({
51
+ ...coordinates,
52
+ eventId: `review:${input.sessionId}:${input.partId}`,
53
+ participantIds: memberId === void 0 ? [] : [memberId],
54
+ sessionId: input.sessionId,
55
+ turnId: input.turnId,
56
+ kind: "decision",
57
+ decision: reason === "review_passed" ? "reply" : "silent",
58
+ reason,
59
+ argsSummary: JSON.stringify(summary)
60
+ }));
61
+ };
62
+ const verdictOf = async (input, review, text) => {
63
+ const key = `${input.sessionId}:${input.partId}`;
64
+ const files = input.files?.files ?? [];
65
+ const coordinates = reviewedChat(input.principal);
66
+ return verdicts.get(key) ?? remember(key, await reviewOutcome(review, async (criteria) => judgeReply({
67
+ decide: options.decide,
68
+ model: options.model(),
69
+ chat: coordinates === void 0 ? [] : await readChat(options.archive, coordinates),
70
+ reply: text,
71
+ ...files.length === 0 ? {} : { files: files.map((file) => file.filename) },
72
+ ...criteria === void 0 ? {} : { criteria }
73
+ }), (error) => console.error("[segmentstream] reply review judge failed; the reply is held", {
74
+ sessionId: input.sessionId,
75
+ error
76
+ })));
77
+ };
78
+ const sendOrHold = async (input) => {
79
+ const review = reviewOf(options.settings(), input.principal);
80
+ if (!repliesReviewed(options.settings(), input.principal) || review.mode === "never") return true;
81
+ const files = input.files?.files ?? [];
82
+ const text = withCaptions(input.text, input.files?.captions ?? []);
83
+ const outcome = await verdictOf(input, review, text);
84
+ const captions = (input.files?.captions ?? []).join("\n\n");
85
+ const verdict = outcome.send && files.length > 0 && (options.sendFiles === void 0 || captions.length > 1024) ? {
86
+ send: false,
87
+ mode: review.mode === "always" ? "always" : "whenUnsure",
88
+ confidence: outcome.confidence ?? null
89
+ } : outcome;
90
+ if (verdict.send) {
91
+ await record(input, "review_passed", {
92
+ mode: review.mode,
93
+ confidence: outcome.confidence ?? null,
94
+ ...review.mode === "whenUnsure" ? { minConfidence: review.minConfidence } : {}
95
+ });
96
+ return true;
97
+ }
98
+ const [first, ...rest] = fileGroups({
99
+ files,
100
+ captions: []
101
+ });
102
+ const held = heldReply({
103
+ ...input,
104
+ text,
105
+ files: first?.files ?? [],
106
+ outcome: verdict
107
+ });
108
+ if (held === void 0) throw new Error("A reply under review has no chat or member to be held for.");
109
+ await options.hold(held);
110
+ for (const [index, group] of rest.entries()) {
111
+ const more = heldReply({
112
+ ...input,
113
+ partId: `${input.partId}:files:${index + 1}`,
114
+ text: "",
115
+ files: group.files,
116
+ outcome: verdict
117
+ });
118
+ if (more !== void 0) await options.hold(more);
119
+ }
120
+ await record(input, "review_held", {
121
+ mode: verdict.mode,
122
+ confidence: verdict.confidence,
123
+ ...review.mode === "whenUnsure" ? { minConfidence: review.minConfidence } : {}
124
+ });
125
+ return false;
126
+ };
42
127
  return {
43
128
  reviewed: (principal) => repliesReviewed(options.settings(), principal),
129
+ proposes: (principal) => {
130
+ const provider = chatAddressOf(principal)?.provider;
131
+ return options.propose !== void 0 && options.settings() !== void 0 && (provider === "email" || provider === "custom") && memberIdOf(principal) !== void 0;
132
+ },
133
+ async propose(input) {
134
+ const settings = options.settings();
135
+ const propose = options.propose;
136
+ if (settings === void 0 || propose === void 0) return {
137
+ by: "agent",
138
+ send: await sendOrHold(input)
139
+ };
140
+ const review = reviewOf(settings, input.principal);
141
+ const files = input.files?.files ?? [];
142
+ const captions = (input.files?.captions ?? []).map((caption) => caption.trim()).filter((caption) => caption !== "");
143
+ const confidence = review.mode === "whenUnsure" ? (await verdictOf(input, review, withCaptions(input.text, captions))).confidence ?? null : null;
144
+ const policy = reviewPolicy(settings);
145
+ const [first, ...rest] = fileGroups({
146
+ files,
147
+ captions: []
148
+ });
149
+ const proposal = (partId, text, group) => proposedReply({
150
+ principal: input.principal,
151
+ sessionId: input.sessionId,
152
+ partId,
153
+ turnId: input.turnId,
154
+ text,
155
+ ...group !== void 0 && group === first && captions.length > 0 ? { caption: captions.join("\n\n") } : {},
156
+ ...group === void 0 ? {} : { files: group.files },
157
+ ...input.recipients === void 0 ? {} : { recipients: input.recipients },
158
+ review: policy,
159
+ confidence,
160
+ ...input.maxLength === void 0 ? {} : { maxLength: input.maxLength }
161
+ });
162
+ const main = proposal(input.partId, input.text, first);
163
+ if (main === void 0) throw new Error("A reply under review has no chat or member to be proposed for.");
164
+ const answer = await propose(main);
165
+ if (answer.outcome === "unsupported") return {
166
+ by: "agent",
167
+ send: await sendOrHold(input)
168
+ };
169
+ await record(input, answer.outcome === "held" ? "review_held" : "review_passed", {
170
+ mode: answer.review.mode,
171
+ confidence,
172
+ ...answer.review.mode === "whenUnsure" ? { minConfidence: answer.review.minConfidence } : {}
173
+ });
174
+ if (answer.outcome === "sent" || answer.outcome === "held") for (const [index, group] of rest.entries()) {
175
+ const more = proposal(`${input.partId}:files:${index + 1}`, "", group);
176
+ const outcome = more === void 0 ? void 0 : await propose(more);
177
+ if (outcome !== void 0 && outcome.outcome !== "sent" && outcome.outcome !== "held") console.error("[segmentstream] a reply's further files were neither sent nor held", {
178
+ sessionId: input.sessionId,
179
+ outcome: outcome.outcome
180
+ });
181
+ }
182
+ return {
183
+ ...answer,
184
+ by: "ontology"
185
+ };
186
+ },
44
187
  async sendFiles(input) {
45
188
  for (const [index, files] of fileGroups(input.files).entries()) await options.sendFiles({
46
189
  ...input,
@@ -70,82 +213,7 @@ function replyReview(options) {
70
213
  await options.hold(held);
71
214
  }
72
215
  },
73
- async sendOrHold(input) {
74
- const review = reviewOf(options.settings(), input.principal);
75
- if (!repliesReviewed(options.settings(), input.principal) || review.mode === "never") return true;
76
- const files = input.files?.files ?? [];
77
- const text = withCaptions(input.text, input.files?.captions ?? []);
78
- const coordinates = reviewedChat(input.principal);
79
- const key = `${input.sessionId}:${input.partId}`;
80
- const outcome = verdicts.get(key) ?? remember(key, await reviewOutcome(review, async (criteria) => judgeReply({
81
- decide: options.decide,
82
- model: options.model(),
83
- chat: coordinates === void 0 ? [] : await readChat(options.archive, coordinates),
84
- reply: text,
85
- ...files.length === 0 ? {} : { files: files.map((file) => file.filename) },
86
- ...criteria === void 0 ? {} : { criteria }
87
- }), (error) => console.error("[segmentstream] reply review judge failed; the reply is held", {
88
- sessionId: input.sessionId,
89
- error
90
- })));
91
- const record = async (reason, summary) => {
92
- if (coordinates === void 0) return;
93
- const memberId = memberIdOf(input.principal);
94
- await options.archive.append(chatEvent({
95
- ...coordinates,
96
- eventId: `review:${input.sessionId}:${input.partId}`,
97
- participantIds: memberId === void 0 ? [] : [memberId],
98
- sessionId: input.sessionId,
99
- turnId: input.turnId,
100
- kind: "decision",
101
- decision: reason === "review_passed" ? "reply" : "silent",
102
- reason,
103
- argsSummary: JSON.stringify(summary)
104
- }));
105
- };
106
- const captions = (input.files?.captions ?? []).join("\n\n");
107
- const verdict = outcome.send && files.length > 0 && (options.sendFiles === void 0 || captions.length > 1024) ? {
108
- send: false,
109
- mode: review.mode === "always" ? "always" : "whenUnsure",
110
- confidence: outcome.confidence ?? null
111
- } : outcome;
112
- if (verdict.send) {
113
- await record("review_passed", {
114
- mode: review.mode,
115
- confidence: outcome.confidence ?? null,
116
- ...review.mode === "whenUnsure" ? { minConfidence: review.minConfidence } : {}
117
- });
118
- return true;
119
- }
120
- const [first, ...rest] = fileGroups({
121
- files,
122
- captions: []
123
- });
124
- const held = heldReply({
125
- ...input,
126
- text,
127
- files: first?.files ?? [],
128
- outcome: verdict
129
- });
130
- if (held === void 0) throw new Error("A reply under review has no chat or member to be held for.");
131
- await options.hold(held);
132
- for (const [index, group] of rest.entries()) {
133
- const more = heldReply({
134
- ...input,
135
- partId: `${input.partId}:files:${index + 1}`,
136
- text: "",
137
- files: group.files,
138
- outcome: verdict
139
- });
140
- if (more !== void 0) await options.hold(more);
141
- }
142
- await record("review_held", {
143
- mode: verdict.mode,
144
- confidence: verdict.confidence,
145
- ...review.mode === "whenUnsure" ? { minConfidence: review.minConfidence } : {}
146
- });
147
- return false;
148
- }
216
+ sendOrHold
149
217
  };
150
218
  }
151
219
  function withReviewedReplies(channel, review, archive) {
@@ -240,6 +308,10 @@ function channelReview(options, runtime) {
240
308
  hold: options.hold ?? ((reply) => agentReviews({
241
309
  origin: appOrigin(runtime.environment),
242
310
  ...transport
311
+ })(reply)),
312
+ propose: options.propose ?? ((reply) => agentReplies({
313
+ origin: appOrigin(runtime.environment),
314
+ ...transport
243
315
  })(reply))
244
316
  })
245
317
  };
@@ -13,7 +13,7 @@ import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
13
13
  import { handleWorkspaceCallback } from "./callbacks.mjs";
14
14
  import { workspaceTriage } from "../triage.mjs";
15
15
  import { telegramText, withTelegramTexts } from "./texts.mjs";
16
- import { t as agentBuild } from "../../../_chunks/build-metadata-Cgy-C9_E.mjs";
16
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Bnac65E-.mjs";
17
17
  import { attachmentLifecycle } from "./lifecycle.mjs";
18
18
  import { manifestOf } from "../../config.mjs";
19
19
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { t as agentBuild } from "../../../_chunks/build-metadata-Cgy-C9_E.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Bnac65E-.mjs";
8
8
  import { runtimeRequestFailure } from "./runtime-request.mjs";
9
9
  import { GET } from "eve/channels";
10
10
  const HEALTH_ROUTE = "/eve/v1/telegram/health";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { E as OntologyActionNotPermitted, Et as principalRuntimeSource, L as needsConfirmation, Ot as runtimeEnvelope, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as telegramRuntimeSource } from "../../../_chunks/principal-DL9NdRRP.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-Cgy-C9_E.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Bnac65E-.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -329,6 +329,7 @@ function segmentstreamWhatsApp(options) {
329
329
  userName: "agent",
330
330
  adapters: { whatsapp: adapter },
331
331
  state: createMemoryState(),
332
+ concurrency: "concurrent",
332
333
  streaming: false,
333
334
  resolveInputAuth: async (event) => {
334
335
  const principal = event.user?.userId === void 0 ? null : await pairedPrincipal(event.user.userId);
@@ -1,6 +1,6 @@
1
1
  import { type Channel, type ChannelEvents } from "eve/channels";
2
2
  import type { SessionAuthContext } from "eve/context";
3
- import { type WorkspaceChannelRefusal } from "@segmentstream/ontology/workspace-channel";
3
+ import { splitReply, type WorkspaceChannelRefusal } from "@segmentstream/ontology/workspace-channel";
4
4
  import { type SegmentStreamAgentConfigInput } from "../../config.js";
5
5
  import { type AgentAttachments } from "../attachments.js";
6
6
  import { type ChatArchive } from "../chat-archive.js";
@@ -10,6 +10,7 @@ import { type AgentIdentities, type PairedMember } from "../identities.js";
10
10
  import { type CapabilityLookup } from "../inbound-media/plan.js";
11
11
  import { type ImageDescriber } from "../inbound-media/images.js";
12
12
  import { type Transcriber } from "../inbound-media/speech.js";
13
+ import type { ProposeReply } from "../review/client.js";
13
14
  import type { HoldReply } from "../review/hold.js";
14
15
  import type { ReviewDecideFunction } from "../review/judge.js";
15
16
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
@@ -265,6 +266,8 @@ export interface WorkspaceChannelOptions extends ChannelDefinition {
265
266
  /** Tests pass an archive and a hold in place of the ontology's. */
266
267
  readonly archive?: ChatArchive;
267
268
  readonly hold?: HoldReply;
269
+ /** Tests pass a proposal in place of the ontology's. */
270
+ readonly propose?: ProposeReply;
268
271
  };
269
272
  readonly environment?: Environment;
270
273
  readonly token?: RuntimeToken;
@@ -289,11 +292,8 @@ export interface WorkspaceChannelOptions extends ChannelDefinition {
289
292
  * delivery is answered 413.
290
293
  */
291
294
  export declare const MAXIMUM_MESSAGES = 50;
292
- /**
293
- * A reply in parts of at most `maxLength` characters: at a paragraph, else a line, else a space,
294
- * else where the length ends.
295
- */
296
- export declare function splitReply(text: string, maxLength: number | undefined): ReadonlyArray<string>;
295
+ /** A reply in parts the provider takes, as the ontology splits a turn's reply it sends. */
296
+ export { splitReply };
297
297
  /**
298
298
  * The principal of a workspace channel's session: the member who writes from the account, on the
299
299
  * channel, in their private chat with it.
@@ -32,7 +32,7 @@ import { ChannelCheckUnavailable, channelChecks } from "./secrets.mjs";
32
32
  import { decide } from "eve/ai";
33
33
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
34
34
  import { reply } from "eve/events";
35
- import { WORKSPACE_CHANNEL_FILES_BYTES, WORKSPACE_CHANNEL_ID, WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES, isWorkspaceChannelRefusal, workspaceChannelRoute, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
35
+ import { WORKSPACE_CHANNEL_FILES_BYTES, WORKSPACE_CHANNEL_ID, WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES, isWorkspaceChannelRefusal, splitReply, workspaceChannelRoute, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
36
36
  import { POST, defineChannel as defineChannel$1 } from "eve/channels";
37
37
  const WORKSPACE_CHANNEL_AUTHENTICATOR = "segmentstream-channel";
38
38
  const MAXIMUM_CURSOR_LENGTH = 16384;
@@ -169,23 +169,6 @@ function validEvent(value) {
169
169
  }
170
170
  };
171
171
  }
172
- function splitReply(text, maxLength) {
173
- if (maxLength === void 0 || text.length <= maxLength) return [text];
174
- const parts = [];
175
- let rest = text;
176
- while (rest.length > maxLength) {
177
- const window = rest.slice(0, maxLength);
178
- const end = [
179
- window.lastIndexOf("\n\n"),
180
- window.lastIndexOf("\n"),
181
- window.lastIndexOf(" ")
182
- ].find((index) => index > 0) ?? maxLength;
183
- parts.push(rest.slice(0, end).trimEnd());
184
- rest = rest.slice(end).trimStart();
185
- }
186
- if (rest !== "") parts.push(rest);
187
- return parts;
188
- }
189
172
  function replyText(view, turnId) {
190
173
  return reply(view, turnId).filter((part) => part.kind === "text" && part.interrupted !== true).flatMap((part) => typeof part.value === "string" ? [part.value] : []).join("\n").trim();
191
174
  }
@@ -290,6 +273,7 @@ function workspaceChannelDefinition(options) {
290
273
  model: () => config.models.decision,
291
274
  ...options.review.archive === void 0 ? {} : { archive: options.review.archive },
292
275
  ...options.review.hold === void 0 ? {} : { hold: options.review.hold },
276
+ ...options.review.propose === void 0 ? {} : { propose: options.review.propose },
293
277
  sendFiles: replyFilesSender(() => config.channels)
294
278
  }, {
295
279
  environment,
@@ -766,14 +750,24 @@ function workspaceChannelDefinition(options) {
766
750
  });
767
751
  return;
768
752
  }
769
- if (!(reviewing === void 0 ? true : await reviewing.sendOrHold({
753
+ const reply = {
770
754
  principal,
771
755
  sessionId: ctx.session.id,
772
756
  turnId,
773
757
  partId: turnId,
774
758
  text,
775
759
  ...files === void 0 || files.files.length === 0 ? {} : { files }
776
- }))) return;
760
+ };
761
+ const proposed = reviewing !== void 0 && reviewing.proposes(principal) ? await reviewing.propose({
762
+ ...reply,
763
+ ...maxLength === void 0 ? {} : { maxLength }
764
+ }) : void 0;
765
+ if (proposed?.by === "ontology") {
766
+ if (proposed.outcome !== "sent" && proposed.outcome !== "held") report("reply_failed", new Error(`The ontology's send of the reply was ${proposed.outcome}` + (proposed.refusal === void 0 ? "." : ` (${proposed.refusal}).`)));
767
+ else if (proposed.outcome === "sent" && proposed.files !== void 0 && proposed.files !== "sent") report("reply_files_failed", new Error(`The ontology's send of the reply's files was ${proposed.files}.`));
768
+ return;
769
+ }
770
+ if (!(proposed !== void 0 ? proposed.send : reviewing === void 0 ? true : await reviewing.sendOrHold(reply))) return;
777
771
  let parts;
778
772
  try {
779
773
  parts = await deliver({
@@ -15,33 +15,33 @@
15
15
  * as persona texts are: by the SDK when the agent is built, and put inline by the platform when it
16
16
  * deploys.
17
17
  */
18
+ import { DEFAULT_REVIEW, REVIEW_MODES, reviewFor, SEND_REPLIES, type Review as PolicyReview, type ReviewMode, type ReviewSettings as PolicySettings } from "@segmentstream/ontology/review";
18
19
  /** The directory beside `segmentstream.json` that holds the review criteria. */
19
20
  export declare const REVIEW_DIRECTORY = "review";
20
21
  /** The longest criteria the decision model reads; longer ones fail validation. */
21
22
  export declare const MAXIMUM_CRITERIA_LENGTH = 8000;
22
- /** The key of the review for everyone no role matches, and the name of its criteria file. */
23
- export declare const DEFAULT_REVIEW = "default";
24
- export declare const REVIEW_MODES: readonly ["never", "always", "whenUnsure"];
25
- export type ReviewMode = (typeof REVIEW_MODES)[number];
26
- export type Review = {
27
- readonly mode: "never";
28
- } | {
29
- readonly mode: "always";
30
- } | {
23
+ /**
24
+ * The modes, the default's key and which review applies to a person are the policy's, which the
25
+ * ontology service applies with the person's current roles: one source for both
26
+ * (`@segmentstream/ontology/review`).
27
+ */
28
+ export { DEFAULT_REVIEW, REVIEW_MODES, reviewFor, SEND_REPLIES, type ReviewMode };
29
+ /** A review as the agent declares it: the policy's, with a `whenUnsure` review's criteria. */
30
+ export type Review = Exclude<PolicyReview, {
31
+ readonly mode: "whenUnsure";
32
+ }> | (Extract<PolicyReview, {
31
33
  readonly mode: "whenUnsure";
32
- /** The probability, from 0 to 1, that staff would send the reply as written, to send it. */
33
- readonly minConfidence: number;
34
+ }> & {
34
35
  /** `agent/review/<role>.md`: what staff check a reply for. Put inline, not written by hand. */
35
36
  readonly criteria?: string;
36
- };
37
- export interface ReviewSettings {
38
- /** The review per role of the person the agent replies to; the first role they hold wins. */
39
- readonly byRole: Readonly<Record<string, Review>>;
40
- /** Everyone no role matches, including a person with no roles. */
41
- readonly default: Review;
42
- }
43
- /** Without `review`, or for a key it leaves out: the agent sends its replies itself. */
44
- export declare const SEND_REPLIES: Review;
37
+ });
38
+ /** The review per role of the person the agent replies to; the first role they hold wins. */
39
+ export type ReviewSettings = PolicySettings<Review>;
40
+ /**
41
+ * The policy of `settings` as the ontology service applies it: every mode and threshold, without
42
+ * the criteria, which never leave the agent.
43
+ */
44
+ export declare function reviewPolicy(settings: ReviewSettings): PolicySettings;
45
45
  /** One validation failure, in Standard Schema's issue shape. */
46
46
  interface Issue {
47
47
  readonly message: string;
@@ -49,8 +49,6 @@ interface Issue {
49
49
  }
50
50
  /** The path of a key's criteria, relative to the directory of `segmentstream.json`. */
51
51
  export declare function reviewFile(key: string): string | undefined;
52
- /** The review for a person with `roles`: the first `byRole` entry they hold, or the default. */
53
- export declare function reviewFor(settings: ReviewSettings | undefined, roles: ReadonlyArray<string>): Review;
54
52
  /** Validates `review` of `agent/segmentstream.json`; `undefined` when absent. */
55
53
  export declare function reviewSettings(value: unknown, issues: Issue[]): ReviewSettings | undefined;
56
54
  /**
@@ -67,4 +65,3 @@ export declare function criteriaFiles(value: unknown): ReadonlyArray<{
67
65
  readonly path: ReadonlyArray<string>;
68
66
  readonly file: string;
69
67
  }>;
70
- export {};
@@ -4,15 +4,19 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
+ import { DEFAULT_REVIEW, REVIEW_MODES, SEND_REPLIES, reviewFor } from "@segmentstream/ontology/review";
7
8
  const REVIEW_DIRECTORY = "review";
8
9
  const MAXIMUM_CRITERIA_LENGTH = 8e3;
9
- const DEFAULT_REVIEW = "default";
10
- const REVIEW_MODES = [
11
- "never",
12
- "always",
13
- "whenUnsure"
14
- ];
15
- const SEND_REPLIES = { mode: "never" };
10
+ function reviewPolicy(settings) {
11
+ const policy = (review) => review.mode === "whenUnsure" ? {
12
+ mode: review.mode,
13
+ minConfidence: review.minConfidence
14
+ } : { mode: review.mode };
15
+ return {
16
+ byRole: Object.fromEntries(Object.entries(settings.byRole).map(([role, review]) => [role, policy(review)])),
17
+ default: policy(settings.default)
18
+ };
19
+ }
16
20
  const FILE_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
17
21
  function isRecord(value) {
18
22
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -20,11 +24,6 @@ function isRecord(value) {
20
24
  function reviewFile(key) {
21
25
  return FILE_NAME.test(key) ? `${REVIEW_DIRECTORY}/${key}.md` : void 0;
22
26
  }
23
- function reviewFor(settings, roles) {
24
- if (settings === void 0) return SEND_REPLIES;
25
- for (const [role, review] of Object.entries(settings.byRole)) if (roles.includes(role)) return review;
26
- return settings.default;
27
- }
28
27
  function review(value, path, issues) {
29
28
  if (!isRecord(value)) {
30
29
  issues.push({
@@ -92,7 +91,7 @@ function reviewSettings(value, issues) {
92
91
  });
93
92
  return;
94
93
  }
95
- for (const key of Object.keys(value)) if (key !== "byRole" && key !== "default") issues.push({
94
+ for (const key of Object.keys(value)) if (key !== "byRole" && key !== DEFAULT_REVIEW) issues.push({
96
95
  message: "is not a known setting",
97
96
  path: [...path, key]
98
97
  });
@@ -128,7 +127,7 @@ function reviewSettings(value, issues) {
128
127
  }
129
128
  return {
130
129
  byRole,
131
- default: (value.default === void 0 ? SEND_REPLIES : review(value.default, [...path, "default"], issues)) ?? SEND_REPLIES
130
+ default: (value.default === void 0 ? SEND_REPLIES : review(value.default, [...path, DEFAULT_REVIEW], issues)) ?? SEND_REPLIES
132
131
  };
133
132
  }
134
133
  function earlierReviewInput(value) {
@@ -155,4 +154,4 @@ function criteriaFiles(value) {
155
154
  file
156
155
  }] : []);
157
156
  }
158
- export { DEFAULT_REVIEW, MAXIMUM_CRITERIA_LENGTH, REVIEW_DIRECTORY, REVIEW_MODES, SEND_REPLIES, criteriaFiles, earlierReviewInput, reviewFile, reviewFor, reviewSettings };
157
+ export { DEFAULT_REVIEW, MAXIMUM_CRITERIA_LENGTH, REVIEW_DIRECTORY, REVIEW_MODES, SEND_REPLIES, criteriaFiles, earlierReviewInput, reviewFile, reviewFor, reviewPolicy, reviewSettings };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.101.0",
3
+ "version": "0.102.1",
4
4
  "description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -88,7 +88,7 @@
88
88
  "@chat-adapter/state-memory": "4.42.0",
89
89
  "@chat-adapter/telegram": "4.41.0",
90
90
  "@chat-adapter/whatsapp": "4.42.0",
91
- "@segmentstream/ontology": "0.180.0",
91
+ "@segmentstream/ontology": "0.181.0",
92
92
  "@vercel/oidc": "^3.8.4",
93
93
  "ai": "^7.0.172",
94
94
  "chat": "4.42.0",