@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
package/dist/review.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reply review's policy (`docs/agent.md`, "Reply review"): who sends the agent's replies, by the
|
|
3
|
+
* roles of the person a reply answers. The agent declares it in `review` of
|
|
4
|
+
* `agent/segmentstream.json`; the agent SDK validates it and judges replies, and the ontology
|
|
5
|
+
* service applies it with the roles the person holds when the reply is proposed. Both read it
|
|
6
|
+
* here, so a reply is reviewed by one rule wherever it is decided.
|
|
7
|
+
*
|
|
8
|
+
* - `never`: the reply is sent as written;
|
|
9
|
+
* - `always`: every reply waits for a member to approve, edit or reject it;
|
|
10
|
+
* - `whenUnsure`: the reply is sent when the decision model gives at least `minConfidence` that
|
|
11
|
+
* staff would send it as written, and held otherwise. What staff check a reply for, the
|
|
12
|
+
* criteria, stays with the agent: this policy is only the modes and thresholds.
|
|
13
|
+
*/
|
|
14
|
+
export declare const REVIEW_MODES: readonly ["never", "always", "whenUnsure"];
|
|
15
|
+
export type ReviewMode = (typeof REVIEW_MODES)[number];
|
|
16
|
+
/** The key of the review for everyone no role matches. */
|
|
17
|
+
export declare const DEFAULT_REVIEW = "default";
|
|
18
|
+
/** One review: a mode, and for `whenUnsure` the confidence a reply needs to be sent. */
|
|
19
|
+
export type Review = {
|
|
20
|
+
readonly mode: "never";
|
|
21
|
+
} | {
|
|
22
|
+
readonly mode: "always";
|
|
23
|
+
} | {
|
|
24
|
+
readonly mode: "whenUnsure";
|
|
25
|
+
/** The probability, above 0 and at most 1, that staff would send the reply as written. */
|
|
26
|
+
readonly minConfidence: number;
|
|
27
|
+
};
|
|
28
|
+
/** The review per role of the person a reply answers, and the review of everyone else. */
|
|
29
|
+
export interface ReviewSettings<Entry extends Review = Review> {
|
|
30
|
+
/** The first role the person holds wins, in the order written. */
|
|
31
|
+
readonly byRole: Readonly<Record<string, Entry>>;
|
|
32
|
+
/** Everyone no role matches, including a person with no roles. */
|
|
33
|
+
readonly default: Entry;
|
|
34
|
+
}
|
|
35
|
+
/** Without `review`: replies are sent as written. */
|
|
36
|
+
export declare const SEND_REPLIES: {
|
|
37
|
+
readonly mode: "never";
|
|
38
|
+
};
|
|
39
|
+
/** The review for a person with `roles`: the first `byRole` entry they hold, or the default. */
|
|
40
|
+
export declare function reviewFor<Entry extends Review>(settings: ReviewSettings<Entry> | undefined, roles: ReadonlyArray<string>): Entry | typeof SEND_REPLIES;
|
|
41
|
+
/**
|
|
42
|
+
* Whether a reply under `review` is sent as written: always under `never`, never under `always`,
|
|
43
|
+
* and under `whenUnsure` only with a `confidence` of at least `minConfidence`. A reply nobody
|
|
44
|
+
* judged, `null` or `undefined`, is held: a missing judgment never sends a reply unreviewed.
|
|
45
|
+
*/
|
|
46
|
+
export declare function reviewPasses(review: Review, confidence: number | null | undefined): boolean;
|
package/dist/review.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reply review's policy (`docs/agent.md`, "Reply review"): who sends the agent's replies, by the
|
|
3
|
+
* roles of the person a reply answers. The agent declares it in `review` of
|
|
4
|
+
* `agent/segmentstream.json`; the agent SDK validates it and judges replies, and the ontology
|
|
5
|
+
* service applies it with the roles the person holds when the reply is proposed. Both read it
|
|
6
|
+
* here, so a reply is reviewed by one rule wherever it is decided.
|
|
7
|
+
*
|
|
8
|
+
* - `never`: the reply is sent as written;
|
|
9
|
+
* - `always`: every reply waits for a member to approve, edit or reject it;
|
|
10
|
+
* - `whenUnsure`: the reply is sent when the decision model gives at least `minConfidence` that
|
|
11
|
+
* staff would send it as written, and held otherwise. What staff check a reply for, the
|
|
12
|
+
* criteria, stays with the agent: this policy is only the modes and thresholds.
|
|
13
|
+
*/
|
|
14
|
+
export const REVIEW_MODES = ["never", "always", "whenUnsure"];
|
|
15
|
+
/** The key of the review for everyone no role matches. */
|
|
16
|
+
export const DEFAULT_REVIEW = "default";
|
|
17
|
+
/** Without `review`: replies are sent as written. */
|
|
18
|
+
export const SEND_REPLIES = { mode: "never" };
|
|
19
|
+
/** The review for a person with `roles`: the first `byRole` entry they hold, or the default. */
|
|
20
|
+
export function reviewFor(settings, roles) {
|
|
21
|
+
if (settings === undefined) {
|
|
22
|
+
return SEND_REPLIES;
|
|
23
|
+
}
|
|
24
|
+
for (const [role, review] of Object.entries(settings.byRole)) {
|
|
25
|
+
if (roles.includes(role)) {
|
|
26
|
+
return review;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return settings.default;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Whether a reply under `review` is sent as written: always under `never`, never under `always`,
|
|
33
|
+
* and under `whenUnsure` only with a `confidence` of at least `minConfidence`. A reply nobody
|
|
34
|
+
* judged, `null` or `undefined`, is held: a missing judgment never sends a reply unreviewed.
|
|
35
|
+
*/
|
|
36
|
+
export function reviewPasses(review, confidence) {
|
|
37
|
+
switch (review.mode) {
|
|
38
|
+
case "never":
|
|
39
|
+
return true;
|
|
40
|
+
case "always":
|
|
41
|
+
return false;
|
|
42
|
+
case "whenUnsure":
|
|
43
|
+
return (typeof confidence === "number" &&
|
|
44
|
+
Number.isFinite(confidence) &&
|
|
45
|
+
confidence >= review.minConfidence);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { Effect } from "effect";
|
|
3
3
|
import { SqlClient } from "effect/unstable/sql";
|
|
4
4
|
import { signUpRolesOf } from "../manifest.js";
|
|
5
|
-
import { AGENT_GUEST_LINKS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
|
|
5
|
+
import { AGENT_GUEST_LINKS_TABLE, AGENT_COUNTERS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
|
|
6
6
|
import { AGENT_EVAL_CLIENT_ID, AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
|
|
7
7
|
import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, FULL_SCOPE, REFRESH_TOKEN_PREFIX, REFRESH_TOKEN_TTL_MS, newSecret, secretHash, } from "../service/oauth/protocol.js";
|
|
8
8
|
import { addGuestSpend, completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, guestSpendLimited, } from "./agent-counters.js";
|
|
@@ -216,34 +216,55 @@ export function sqlAgentWebStore(ontology, sql, admission) {
|
|
|
216
216
|
.pipe(Effect.orDie);
|
|
217
217
|
return standing === undefined ? undefined : guestPrincipal(ontology, grantId);
|
|
218
218
|
}),
|
|
219
|
-
countGuestTurn: (guestId, input) =>
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
[
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
219
|
+
countGuestTurn: (guestId, input, delivery) => {
|
|
220
|
+
const count = Effect.gen(function* () {
|
|
221
|
+
if (!isRecordId(guestId)) {
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
const limits = yield* effectiveChannelLimits(sql, input);
|
|
225
|
+
// Money first: a guest past a cap starts no turn, and the turn is not counted.
|
|
226
|
+
const spent = yield* guestSpendLimited(sql, { guestId, limits });
|
|
227
|
+
if (spent !== undefined) {
|
|
228
|
+
return spent;
|
|
229
|
+
}
|
|
230
|
+
for (const [scope, subject, limit] of [
|
|
231
|
+
["guestTurnsPerDay", guestId, limits.guest.turnsPerDay],
|
|
232
|
+
["guestWorkspaceTurnsPerDay", "workspace", limits.guest.workspaceTurnsPerDay],
|
|
233
|
+
]) {
|
|
234
|
+
const limited = yield* countAgentAttempt(sql, { scope, subject, window: "day", limit });
|
|
235
|
+
if (limited !== undefined) {
|
|
236
|
+
// The refusal the browser gets is this window's notice.
|
|
237
|
+
if (limited.notificationId !== undefined) {
|
|
238
|
+
yield* completeAgentLimitNotice(sql, {
|
|
239
|
+
notificationId: limited.notificationId,
|
|
240
|
+
delivered: true,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
|
|
241
244
|
}
|
|
242
|
-
return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
|
|
243
245
|
}
|
|
246
|
+
return undefined;
|
|
247
|
+
});
|
|
248
|
+
if (!delivery || !isRecordId(guestId)) {
|
|
249
|
+
return count.pipe(Effect.orDie);
|
|
244
250
|
}
|
|
245
|
-
|
|
246
|
-
|
|
251
|
+
// Provider retries share the accepted turn's charge, including concurrent deliveries.
|
|
252
|
+
const key = `guestDelivery:${guestId}:${secretHash(delivery)}`;
|
|
253
|
+
return sql
|
|
254
|
+
.withTransaction(Effect.gen(function* () {
|
|
255
|
+
const [fresh] = yield* sql.unsafe(`INSERT INTO "${AGENT_COUNTERS_TABLE}" ("key","window_start","count")
|
|
256
|
+
VALUES ($1,date_trunc('day',now()),1) ON CONFLICT ("key","window_start") DO NOTHING RETURNING 1`, [key]);
|
|
257
|
+
if (!fresh) {
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
const limited = yield* count;
|
|
261
|
+
if (limited) {
|
|
262
|
+
yield* sql.unsafe(`DELETE FROM "${AGENT_COUNTERS_TABLE}" WHERE "key"=$1 AND "window_start"=date_trunc('day',now())`, [key]);
|
|
263
|
+
}
|
|
264
|
+
return limited;
|
|
265
|
+
}))
|
|
266
|
+
.pipe(Effect.orDie);
|
|
267
|
+
},
|
|
247
268
|
recordGuestUsage: ({ guestId, costUsd, key }) => isRecordId(guestId) ? addGuestSpend(sql, { guestId, costUsd, key }) : Effect.void,
|
|
248
269
|
countGuestAttempt: ({ scope, subject, limit }) => countAgentAttempt(sql, { scope, subject, window: "hour", limit }).pipe(Effect.map((limited) => limited?.retryAfterSeconds)),
|
|
249
270
|
upgradeGuest: ({ guestId, identity, expiresAt }) => Effect.gen(function* () {
|
package/dist/runtime/agents.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { channelGuestId, guestPrincipal } from "./guests.js";
|
|
1
2
|
import { sqlConfirmationStore } from "./confirmations.js";
|
|
2
3
|
import { randomUUID } from "node:crypto";
|
|
3
4
|
import { Effect, Option, Schema } from "effect";
|
|
@@ -156,6 +157,11 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
156
157
|
const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
|
|
157
158
|
const memberPrincipal = (userId) => resolveMemberById(ontology, userId).pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
158
159
|
const messages = sqlChatMessageStore(sql);
|
|
160
|
+
/**
|
|
161
|
+
* The lock a held reply's key takes until the transaction ends: reports of one reply, and a
|
|
162
|
+
* proposal's hold and its delivery's reservation, run one after the other.
|
|
163
|
+
*/
|
|
164
|
+
const lockDraftKey = (key) => rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${key}`]);
|
|
159
165
|
/** The newest message the turn took in the chat, as the chat store's place; null without one. */
|
|
160
166
|
const turnBasis = (channel, chatId, turnId) => messages
|
|
161
167
|
.turnBasis({ channel, chatId, turnId })
|
|
@@ -214,7 +220,7 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
214
220
|
yield* sql.unsafe(`SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true)`, [`${limits.statementTimeoutMs}ms`, `${limits.lockTimeoutMs}ms`]);
|
|
215
221
|
yield* beginReplicationWrite(sql);
|
|
216
222
|
// Reports of one reply run one after the other: the first creates it, the rest find it.
|
|
217
|
-
yield*
|
|
223
|
+
yield* lockDraftKey(key);
|
|
218
224
|
const edits = [];
|
|
219
225
|
const snapshots = new Map();
|
|
220
226
|
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
@@ -301,9 +307,11 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
301
307
|
? nullableText(resolved.previous.basis)
|
|
302
308
|
: input.requested !== undefined
|
|
303
309
|
? input.requested.basis
|
|
304
|
-
: input.
|
|
305
|
-
?
|
|
306
|
-
:
|
|
310
|
+
: input.basis !== undefined
|
|
311
|
+
? input.basis
|
|
312
|
+
: input.turnId === undefined
|
|
313
|
+
? null
|
|
314
|
+
: yield* turnBasis(input.channel, input.chatId, input.turnId),
|
|
307
315
|
draft: input.text,
|
|
308
316
|
files: (input.files ?? []).length === 0 ? null : input.files,
|
|
309
317
|
text: null,
|
|
@@ -612,6 +620,30 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
612
620
|
return true;
|
|
613
621
|
}))
|
|
614
622
|
.pipe(Effect.orDie),
|
|
623
|
+
channelGuest: (channel, chat, sender) => Effect.gen(function* () {
|
|
624
|
+
const kind = store.channelKind?.(channel);
|
|
625
|
+
if ((kind !== "telegram" && kind !== "slack" && kind !== "whatsapp") ||
|
|
626
|
+
!sender ||
|
|
627
|
+
sender.length > 256 ||
|
|
628
|
+
!chat ||
|
|
629
|
+
chat.length > 256) {
|
|
630
|
+
return undefined;
|
|
631
|
+
}
|
|
632
|
+
const principal = guestPrincipal(ontology, channelGuestId(channel, sender), kind, channel);
|
|
633
|
+
if (!principal) {
|
|
634
|
+
return undefined;
|
|
635
|
+
}
|
|
636
|
+
if (kind === "whatsapp"
|
|
637
|
+
? !/^whatsapp:[^:]+:[0-9]+$/.test(chat) || chat.split(":")[2] !== sender
|
|
638
|
+
: (yield* store.readGroupAccess(`${channel}:${chat}`)) !== "public") {
|
|
639
|
+
return undefined;
|
|
640
|
+
}
|
|
641
|
+
// Linked, inactive and revoked identities alike must pass through member admission.
|
|
642
|
+
if (yield* store.findIdentity({ provider: kind, externalId: sender })) {
|
|
643
|
+
return undefined;
|
|
644
|
+
}
|
|
645
|
+
return { ...principal, chat: { provider: channel, chatId: chat } };
|
|
646
|
+
}),
|
|
615
647
|
readGroupAccess: (key) => rows(`SELECT "group_access" FROM ${quoteIdentifier(tableName(AgentChat.name))}
|
|
616
648
|
WHERE "key" = $1 AND "kind" = 'group' AND "handoff_at" IS NULL AND "handled_by_id" IS NULL`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.group_access))),
|
|
617
649
|
readChatPersona: (key) => rows(`SELECT "agent_persona" FROM ${quoteIdentifier(tableName(AgentChat.name))} WHERE "key" = $1`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.agent_persona))),
|
|
@@ -1012,6 +1044,23 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
1012
1044
|
}));
|
|
1013
1045
|
}).pipe(Effect.orDie),
|
|
1014
1046
|
holdReply: (input) => hold(input.key, input.memberId, () => Effect.succeed({ kind: "reply", reply: input })).pipe(Effect.map((held) => (held === "discarded" ? undefined : held))),
|
|
1047
|
+
// Under the key's lock, after its draft was looked for: a delivery begun holds nothing.
|
|
1048
|
+
holdProposal: (input, delivered) => hold(input.key, input.memberId, () => delivered.pipe(Effect.map((sent) => sent ? { kind: "discarded" } : { kind: "reply", reply: input }))).pipe(Effect.map((held) => (held === "discarded" ? "delivered" : held))),
|
|
1049
|
+
reserveProposal: (input) => sql
|
|
1050
|
+
.withTransaction(Effect.gen(function* () {
|
|
1051
|
+
yield* lockDraftKey(input.key);
|
|
1052
|
+
const [found] = yield* makeOntologyRuntime(ontology, sql)
|
|
1053
|
+
.find({ entity: AgentDraft.name, options: { where: { key: input.key }, limit: 1 } })
|
|
1054
|
+
.pipe(Effect.orDie);
|
|
1055
|
+
if (found !== undefined) {
|
|
1056
|
+
return {
|
|
1057
|
+
kind: "held",
|
|
1058
|
+
review: { id: String(found.id), status: String(found.status), created: false },
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
return { kind: "reserved", value: yield* input.reserve };
|
|
1062
|
+
}))
|
|
1063
|
+
.pipe(Effect.catchTag("SqlError", Effect.die)),
|
|
1015
1064
|
holdRevision: (input) => hold(`revision:${input.revision}`, undefined, (runtime) => Effect.gen(function* () {
|
|
1016
1065
|
// The reply the redraft replaces, while it still waits for this redraft: a member who
|
|
1017
1066
|
// decided it, or asked for another redraft since, leaves this one nothing to replace.
|
package/dist/runtime/guests.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type GuestChannel } from "../sign-in.js";
|
|
1
2
|
import type { Ontology } from "../ontology.js";
|
|
2
3
|
import { type AgentToolVerb } from "../permissions.js";
|
|
3
4
|
import type { Principal } from "../runtime.js";
|
|
@@ -30,4 +31,6 @@ export declare function actingGuestId(actAs: string): string | undefined;
|
|
|
30
31
|
* holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
|
|
31
32
|
* `undefined` when the ontology admits no guests.
|
|
32
33
|
*/
|
|
33
|
-
export declare function guestPrincipal(ontology: Ontology, guestId: string): Principal | undefined;
|
|
34
|
+
export declare function guestPrincipal(ontology: Ontology, guestId: string, channel?: GuestChannel, connection?: string): Principal | undefined;
|
|
35
|
+
/** Budget identity shared across chats on one configured messenger connection. */
|
|
36
|
+
export declare function channelGuestId(channel: string, sender: string): string;
|
package/dist/runtime/guests.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { GUEST_ROLE } from "../names.js";
|
|
2
3
|
import { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, isAllowed, MEMBER_AGENT_TOOLS, permissionsOf, principalScopes, } from "../permissions.js";
|
|
3
|
-
import { WEB_PROVIDER } from "../service/runtime-identity.js";
|
|
4
4
|
import { isRecordId } from "./records.js";
|
|
5
5
|
/**
|
|
6
6
|
* A guest as the agent names them in `X-SegmentStream-Act-As`: `guest:` and their id, so that no
|
|
@@ -49,17 +49,36 @@ export function actingGuestId(actAs) {
|
|
|
49
49
|
* holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
|
|
50
50
|
* `undefined` when the ontology admits no guests.
|
|
51
51
|
*/
|
|
52
|
-
export function guestPrincipal(ontology, guestId) {
|
|
53
|
-
|
|
52
|
+
export function guestPrincipal(ontology, guestId, channel = "web", connection) {
|
|
53
|
+
const settings = ontology.signIn.guest;
|
|
54
|
+
const named = `channel:${connection}`;
|
|
55
|
+
const selected = connection && settings?.channels.includes(named) ? named : channel;
|
|
56
|
+
if (!settings?.channels.includes(selected) || !isRecordId(guestId)) {
|
|
54
57
|
return undefined;
|
|
55
58
|
}
|
|
56
|
-
const roles = [GUEST_ROLE];
|
|
59
|
+
const roles = settings.byChannel?.[selected] ?? [GUEST_ROLE];
|
|
57
60
|
return {
|
|
58
61
|
id: guestId,
|
|
59
62
|
kind: "guest",
|
|
60
63
|
roles,
|
|
61
64
|
permissions: permissionsOf(ontology.roles, roles),
|
|
62
65
|
...principalScopes(ontology.roles, roles),
|
|
63
|
-
authenticatedVia:
|
|
66
|
+
authenticatedVia: channel,
|
|
64
67
|
};
|
|
65
68
|
}
|
|
69
|
+
/** Budget identity shared across chats on one configured messenger connection. */
|
|
70
|
+
export function channelGuestId(channel, sender) {
|
|
71
|
+
const bytes = createHash("sha256")
|
|
72
|
+
.update(JSON.stringify(["group-guest", channel, sender]))
|
|
73
|
+
.digest();
|
|
74
|
+
bytes[6] = (bytes[6] & 15) | 80;
|
|
75
|
+
bytes[8] = (bytes[8] & 63) | 128;
|
|
76
|
+
const hex = bytes.toString("hex");
|
|
77
|
+
return [
|
|
78
|
+
hex.slice(0, 8),
|
|
79
|
+
hex.slice(8, 12),
|
|
80
|
+
hex.slice(12, 16),
|
|
81
|
+
hex.slice(16, 20),
|
|
82
|
+
hex.slice(20, 32),
|
|
83
|
+
].join("-");
|
|
84
|
+
}
|
|
@@ -167,6 +167,57 @@ export declare const ReviewRequest: Schema.Struct<{
|
|
|
167
167
|
}>>;
|
|
168
168
|
}>;
|
|
169
169
|
export type ReviewRequest = typeof ReviewRequest.Type;
|
|
170
|
+
/**
|
|
171
|
+
* `POST /api/ontology/agent/replies`: the reply a turn wrote, which the agent proposes rather than
|
|
172
|
+
* sends. The ontology applies the agent's `review` with the roles the person holds now: it sends a
|
|
173
|
+
* reply its review lets go through the chat's channel, as it sends an approved draft, and holds
|
|
174
|
+
* the rest as drafts, as `POST /api/ontology/agent/drafts` does. `key` names the reply, so a
|
|
175
|
+
* proposal repeated after a failure finds what became of it and never sends it twice.
|
|
176
|
+
*/
|
|
177
|
+
export declare const ReplyProposalRequest: Schema.Struct<{
|
|
178
|
+
readonly key: Schema.String;
|
|
179
|
+
readonly provider: Schema.Literals<readonly ["email", "custom"]>;
|
|
180
|
+
readonly channel: Schema.optionalKey<Schema.String>;
|
|
181
|
+
readonly chat_id: Schema.String;
|
|
182
|
+
readonly recipient: Schema.String;
|
|
183
|
+
readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
184
|
+
readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
185
|
+
readonly participants: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
186
|
+
readonly thread_id: Schema.String;
|
|
187
|
+
readonly reply_to: Schema.NullOr<Schema.String>;
|
|
188
|
+
readonly member_id: Schema.String;
|
|
189
|
+
readonly session_id: Schema.String;
|
|
190
|
+
readonly text: Schema.optionalKey<Schema.String>;
|
|
191
|
+
readonly caption: Schema.optionalKey<Schema.String>;
|
|
192
|
+
readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
193
|
+
readonly entity: Schema.String;
|
|
194
|
+
readonly id: Schema.String;
|
|
195
|
+
readonly property: Schema.optionalKey<Schema.String>;
|
|
196
|
+
}>>>;
|
|
197
|
+
readonly turn_id: Schema.String;
|
|
198
|
+
readonly review: Schema.Struct<{
|
|
199
|
+
readonly byRole: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.Struct<{
|
|
200
|
+
readonly mode: Schema.Literal<"never">;
|
|
201
|
+
}>, Schema.Struct<{
|
|
202
|
+
readonly mode: Schema.Literal<"always">;
|
|
203
|
+
}>, Schema.Struct<{
|
|
204
|
+
readonly mode: Schema.Literal<"whenUnsure">;
|
|
205
|
+
readonly minConfidence: Schema.Number;
|
|
206
|
+
}>]>>;
|
|
207
|
+
readonly default: Schema.Union<readonly [Schema.Struct<{
|
|
208
|
+
readonly mode: Schema.Literal<"never">;
|
|
209
|
+
}>, Schema.Struct<{
|
|
210
|
+
readonly mode: Schema.Literal<"always">;
|
|
211
|
+
}>, Schema.Struct<{
|
|
212
|
+
readonly mode: Schema.Literal<"whenUnsure">;
|
|
213
|
+
readonly minConfidence: Schema.Number;
|
|
214
|
+
}>]>;
|
|
215
|
+
}>;
|
|
216
|
+
readonly confidence: Schema.NullOr<Schema.Number>;
|
|
217
|
+
readonly basis: Schema.NullOr<Schema.String>;
|
|
218
|
+
readonly max_length: Schema.optionalKey<Schema.Int>;
|
|
219
|
+
}>;
|
|
220
|
+
export type ReplyProposalRequest = typeof ReplyProposalRequest.Type;
|
|
170
221
|
/**
|
|
171
222
|
* `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
|
|
172
223
|
* as the member it is for, checked as holding it would check them, without holding anything.
|
|
@@ -2,7 +2,7 @@ import { randomInt } from "node:crypto";
|
|
|
2
2
|
import { Schema } from "effect";
|
|
3
3
|
import { AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_NOTE_LIMIT, AGENT_DRAFT_PARTICIPANTS_LIMIT, } from "../../agent-draft.js";
|
|
4
4
|
import { ChatChannelName } from "../../chat-channel.js";
|
|
5
|
-
import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
|
|
5
|
+
import { EMAIL_MESSAGE_LIMIT, EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
|
|
6
6
|
import { EMAIL_PATTERN } from "../../property.js";
|
|
7
7
|
import { GUEST_USD_CEILINGS, MAX_GUEST_USAGE_REPORT_USD } from "../../runtime/agent-counters.js";
|
|
8
8
|
/** How long a member has to open the connect link, sign in and approve the pairing. */
|
|
@@ -260,6 +260,71 @@ export const ReviewRequest = Schema.Struct({
|
|
|
260
260
|
description: "A draft asked for with agent_chat.draft: who asked, their note, and the chat's place.",
|
|
261
261
|
}),
|
|
262
262
|
});
|
|
263
|
+
/** A `whenUnsure` review's threshold: above 0, at most 1. */
|
|
264
|
+
const MinConfidence = Schema.Number.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1)).annotate({ description: "The confidence a reply needs to be sent." });
|
|
265
|
+
/** One review of the agent's `review`, as data: its mode, and a `whenUnsure` review's threshold. */
|
|
266
|
+
const ProposedReview = Schema.Union([
|
|
267
|
+
Schema.Struct({ mode: Schema.Literal("never") }),
|
|
268
|
+
Schema.Struct({ mode: Schema.Literal("always") }),
|
|
269
|
+
Schema.Struct({ mode: Schema.Literal("whenUnsure"), minConfidence: MinConfidence }),
|
|
270
|
+
]);
|
|
271
|
+
/**
|
|
272
|
+
* `POST /api/ontology/agent/replies`: the reply a turn wrote, which the agent proposes rather than
|
|
273
|
+
* sends. The ontology applies the agent's `review` with the roles the person holds now: it sends a
|
|
274
|
+
* reply its review lets go through the chat's channel, as it sends an approved draft, and holds
|
|
275
|
+
* the rest as drafts, as `POST /api/ontology/agent/drafts` does. `key` names the reply, so a
|
|
276
|
+
* proposal repeated after a failure finds what became of it and never sends it twice.
|
|
277
|
+
*/
|
|
278
|
+
export const ReplyProposalRequest = Schema.Struct({
|
|
279
|
+
key: ReviewRequest.fields.key.annotate({
|
|
280
|
+
description: "The agent's key for the reply: its session and turn.",
|
|
281
|
+
}),
|
|
282
|
+
provider: Schema.Literals(["email", "custom"]).annotate({
|
|
283
|
+
description: "The kind of channel the chat is on: an email channel, or a channel the workspace defines.",
|
|
284
|
+
}),
|
|
285
|
+
channel: ReviewRequest.fields.channel,
|
|
286
|
+
chat_id: ReviewRequest.fields.chat_id,
|
|
287
|
+
recipient: ReviewRequest.fields.recipient,
|
|
288
|
+
to: ReviewRequest.fields.to,
|
|
289
|
+
cc: ReviewRequest.fields.cc,
|
|
290
|
+
participants: ReviewRequest.fields.participants,
|
|
291
|
+
thread_id: ReviewRequest.fields.thread_id,
|
|
292
|
+
reply_to: ReviewRequest.fields.reply_to,
|
|
293
|
+
member_id: ReviewRequest.fields.member_id,
|
|
294
|
+
session_id: ReviewRequest.fields.session_id,
|
|
295
|
+
text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(EMAIL_MESSAGE_LIMIT))).annotate({
|
|
296
|
+
description: "The reply as the agent wrote it, in Markdown; empty or absent only for a reply of files. " +
|
|
297
|
+
"As long as its channel sends: one email, or a workspace channel's parts. A reply its review " +
|
|
298
|
+
"holds is held only within a draft's length.",
|
|
299
|
+
}),
|
|
300
|
+
caption: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(20_000)).annotate({
|
|
301
|
+
description: "The captions the reply's files were attached with: sent as the text of its files' " +
|
|
302
|
+
"message, after the reply, and part of a held draft's text.",
|
|
303
|
+
})),
|
|
304
|
+
files: ReviewRequest.fields.files,
|
|
305
|
+
turn_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)).annotate({
|
|
306
|
+
description: "The agent's turn that wrote the reply.",
|
|
307
|
+
}),
|
|
308
|
+
review: Schema.Struct({
|
|
309
|
+
byRole: Schema.Record(Schema.String, ProposedReview),
|
|
310
|
+
default: ProposedReview,
|
|
311
|
+
}).annotate({
|
|
312
|
+
description: "The agent's review for the channel: per role of the person, the first they hold winning " +
|
|
313
|
+
"in the order written, and the default. Its criteria stay with the agent.",
|
|
314
|
+
}),
|
|
315
|
+
confidence: ReviewRequest.fields.confidence.annotate({
|
|
316
|
+
description: "The decision model's probability that staff would send the reply as written; null when " +
|
|
317
|
+
"the agent did not judge it.",
|
|
318
|
+
}),
|
|
319
|
+
basis: Schema.NullOr(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(128))).annotate({
|
|
320
|
+
description: "Where the chat stood when the turn read it, <time>~<id>; null when the agent does not " +
|
|
321
|
+
"know, and the ontology takes the newest message the turn took.",
|
|
322
|
+
}),
|
|
323
|
+
max_length: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(20_000)).annotate({
|
|
324
|
+
description: "A workspace channel's limits.maxLength: a longer reply is sent in parts of at most this " +
|
|
325
|
+
"many characters, as the agent sends its own.",
|
|
326
|
+
})),
|
|
327
|
+
});
|
|
263
328
|
/**
|
|
264
329
|
* `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
|
|
265
330
|
* as the member it is for, checked as holding it would check them, without holding anything.
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { type PublicActionOptions } from "./public-group-action.js";
|
|
2
1
|
import { Layer, Redacted } from "effect";
|
|
3
2
|
import { HttpRouter } from "effect/unstable/http";
|
|
4
3
|
import { type SessionExchange, type TokenVerifier } from "../authentication.js";
|
|
@@ -11,10 +10,13 @@ import { type VisitorWebsites } from "./web-tokens.js";
|
|
|
11
10
|
import type { BotCheckVerifier } from "./bot-check.js";
|
|
12
11
|
import type { DeploymentObservation } from "../../deployment.js";
|
|
13
12
|
import { type OntologyManifest } from "../../manifest.js";
|
|
13
|
+
import type { ReplyProposals } from "../chat/reply-proposal.js";
|
|
14
14
|
import { GUEST_LINK_PATH, type EmailCodes } from "./guest-sign-up.js";
|
|
15
15
|
import type { ResolvedGuest } from "../../sign-in.js";
|
|
16
16
|
/** The agent's endpoints, under the ontology service's path. */
|
|
17
17
|
export declare const AGENT_PATH = "/api/ontology/agent";
|
|
18
|
+
/** Where the agent proposes a turn's reply, which the ontology sends or holds by its review. */
|
|
19
|
+
export declare const AGENT_REPLIES_PATH = "/api/ontology/agent/replies";
|
|
18
20
|
/** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
|
|
19
21
|
export declare const AGENT_TOKENS_PATH = "/api/ontology/agent/tokens";
|
|
20
22
|
export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
|
|
@@ -34,7 +36,6 @@ export { GUEST_LINK_PATH };
|
|
|
34
36
|
*/
|
|
35
37
|
export declare const PAIRING_LIMIT: RateLimit;
|
|
36
38
|
export interface AgentServerOptions {
|
|
37
|
-
readonly publicGroupAction?: PublicActionOptions;
|
|
38
39
|
readonly verifyToken: TokenVerifier;
|
|
39
40
|
/**
|
|
40
41
|
* The websites whose visitors get an agent token: as guests, and, while `web` is open to sign-up,
|
|
@@ -65,6 +66,11 @@ export interface AgentServerOptions {
|
|
|
65
66
|
readonly evalTokens?: DeploymentObservation;
|
|
66
67
|
/** The ontology, whose record files a held reply carries and whose channels send them. */
|
|
67
68
|
readonly manifest?: OntologyManifest;
|
|
69
|
+
/**
|
|
70
|
+
* Sends the replies the agent proposes that their review lets go, as approved drafts are sent,
|
|
71
|
+
* and holds the rest; without it, the service answers proposals 404, as one before them did.
|
|
72
|
+
*/
|
|
73
|
+
readonly replies?: ReplyProposals;
|
|
68
74
|
}
|
|
69
75
|
/**
|
|
70
76
|
* The routes that pair channel accounts with members for the app's own agent, and record the group
|