@segmentstream/ontology 0.97.0 → 0.98.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/README.md CHANGED
@@ -385,7 +385,8 @@ export default defineOntology({
385
385
  key and `rel.many` a join table. With a warehouse-backed end, `rel.one` declares one `on`
386
386
  pair and is matched by value. `User` is the built-in entity for app users and service
387
387
  principals; `AgentChat` (`agent_chat`) is the built-in entity for the group chats of the
388
- app's agent (see [Agents](#agents)). Every ontology includes both. Text feedback defaults on with built-in `AppFeedback`; files follow the non-feedback-blob policy
388
+ app's agent (see [Agents](#agents)), and `AgentReview` (`agent_review`) for the agent's replies
389
+ held for a member to approve, edit or reject. Every ontology includes them. Text feedback defaults on with built-in `AppFeedback`; files follow the non-feedback-blob policy
389
390
  (or an explicit opt-in) and add `AppFeedbackFile` (see [App feedback](#app-feedback)).
390
391
  - `role(name, { description, permissions })` declares a role: a named set of permissions.
391
392
  `member` is built in: every active app user holds it, with the permissions of
@@ -927,8 +928,8 @@ configured. This preparation does not advertise or enable exact chat posting.
927
928
  A permission is `<entity>:<verb>`. The verbs are `read`, the generated `create`, `update`,
928
929
  `delete`, `link` and `unlink`, and the names of authored actions. A role may use `*` for the
929
930
  entity, the verb or both: `lead:*`, `*:read`, `*:*`. An entity wildcard never covers the
930
- built-in `agent_chat`, `app_feedback` or `app_feedback_file`: reading or changing them needs a
931
- permission that names them, such as `agent_chat:read`.
931
+ built-in `agent_chat`, `agent_review`, `app_feedback`, `app_feedback_file` or `user_identity`:
932
+ reading or changing them needs a permission that names them, such as `agent_chat:read`.
932
933
 
933
934
  - Reads require `<entity>:read`: lists, queries, records, history, both entities of a
934
935
  relationship traversal, and every entity a metric query touches. `include` and a filter through a relationship require `read` on
@@ -0,0 +1,95 @@
1
+ import { Schema } from "effect";
2
+ /**
3
+ * A reply the workspace's agent held for review. `agent/segmentstream.json` says, per role of the
4
+ * person the agent replies to, whether a member reviews its replies (`conversations.*.review`);
5
+ * the agent records each reply it holds here, and only the actions below change it. Approving sends
6
+ * the reply, or the member's edit of it, to the person's conversation as the agent, without the
7
+ * sender attribution a chat post carries, at most once; rejecting discards it. Reading, approving
8
+ * and rejecting each need a permission that names `agent_review`: an entity wildcard does not cover
9
+ * it, since its records hold the workspace's conversations with the people it serves.
10
+ */
11
+ export declare const AGENT_REVIEW_STATUSES: readonly [{
12
+ readonly value: "pending";
13
+ readonly description: "Waiting for a member to approve, edit or reject it.";
14
+ }, {
15
+ readonly value: "sent";
16
+ readonly description: "Approved and delivered to the person.";
17
+ }, {
18
+ readonly value: "uncertain";
19
+ readonly description: "Approved; the provider may have delivered it, and it is never sent again.";
20
+ }, {
21
+ readonly value: "failed";
22
+ readonly description: "Approved; the provider refused it, and nothing was sent.";
23
+ }, {
24
+ readonly value: "rejected";
25
+ readonly description: "Rejected: the person never sees it.";
26
+ }];
27
+ export declare const AGENT_REVIEW_MODES: readonly [{
28
+ readonly value: "always";
29
+ readonly description: "Every reply in the conversation waits for a member.";
30
+ }, {
31
+ readonly value: "whenUnsure";
32
+ readonly description: "The decision model was not sure enough that staff would send it as written.";
33
+ }];
34
+ /** The longest reply a review holds; a provider may accept less in one message. */
35
+ export declare const AGENT_REVIEW_TEXT_LIMIT = 20000;
36
+ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
37
+ readonly key: import("./property.js").Property<string, false, true>;
38
+ readonly provider: import("./property.js").Property<string, false, false>;
39
+ readonly chatId: import("./property.js").Property<string, false, false>;
40
+ readonly recipient: import("./property.js").Property<string, false, false>;
41
+ readonly chatKind: import("./property.js").Property<"private" | "group", false, false>;
42
+ readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
43
+ readonly replyTo: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
44
+ readonly sessionId: import("./property.js").Property<string, false, false>;
45
+ readonly draft: import("./property.js").Property<string, false, false>;
46
+ readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
47
+ readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected", false, false>;
48
+ readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
49
+ readonly confidence: Schema.optionalKey<import("./property.js").Property<number, false, false>>;
50
+ readonly messageId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
51
+ readonly decidedAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
52
+ }, {
53
+ readonly person: import("./relationship.js").OneRelationship<false, false, "user">;
54
+ readonly decidedBy: import("./relationship.js").OneRelationship<true, false, "user">;
55
+ }, import("./entity.js").InvocableActions<{
56
+ readonly approve: import("./action.js").Action<Schema.Struct<{
57
+ readonly review: Schema.Codec<string, string, never, never>;
58
+ readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
59
+ }>, {
60
+ review: string;
61
+ status: "sent" | "uncertain" | "failed";
62
+ message_id: string | null;
63
+ duplicate: boolean;
64
+ }>;
65
+ readonly reject: import("./action.js").Action<Schema.Struct<{
66
+ readonly review: Schema.Codec<string, string, never, never>;
67
+ }>, {
68
+ review: string;
69
+ status: "rejected";
70
+ }>;
71
+ }, "agent_review", {
72
+ readonly id: string;
73
+ readonly createdAt: string;
74
+ readonly updatedAt: string;
75
+ readonly createdBy: string | null;
76
+ readonly updatedBy: string | null;
77
+ readonly key: string;
78
+ readonly provider: string;
79
+ readonly chatId: string;
80
+ readonly recipient: string;
81
+ readonly chatKind: "private" | "group";
82
+ readonly threadId: string | null;
83
+ readonly replyTo: string | null;
84
+ readonly sessionId: string;
85
+ readonly draft: string;
86
+ readonly text: string | null;
87
+ readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected";
88
+ readonly mode: "always" | "whenUnsure";
89
+ readonly confidence: number | null;
90
+ readonly messageId: string | null;
91
+ readonly decidedAt: string | null;
92
+ readonly personId: string;
93
+ readonly decidedById: string | null;
94
+ }>, Readonly<Record<never, never>>, "actions">;
95
+ export type AgentReview = typeof AgentReview.Type;
@@ -0,0 +1,200 @@
1
+ import { Effect, Option, Schema } from "effect";
2
+ import { action } from "./action.js";
3
+ import { ChatDelivery } from "./chat.js";
4
+ import { entity } from "./entity.js";
5
+ import { ActionRejected } from "./errors.js";
6
+ import { p } from "./property.js";
7
+ import { rel } from "./relationship.js";
8
+ /**
9
+ * A reply the workspace's agent held for review. `agent/segmentstream.json` says, per role of the
10
+ * person the agent replies to, whether a member reviews its replies (`conversations.*.review`);
11
+ * the agent records each reply it holds here, and only the actions below change it. Approving sends
12
+ * the reply, or the member's edit of it, to the person's conversation as the agent, without the
13
+ * sender attribution a chat post carries, at most once; rejecting discards it. Reading, approving
14
+ * and rejecting each need a permission that names `agent_review`: an entity wildcard does not cover
15
+ * it, since its records hold the workspace's conversations with the people it serves.
16
+ */
17
+ export const AGENT_REVIEW_STATUSES = [
18
+ { value: "pending", description: "Waiting for a member to approve, edit or reject it." },
19
+ { value: "sent", description: "Approved and delivered to the person." },
20
+ {
21
+ value: "uncertain",
22
+ description: "Approved; the provider may have delivered it, and it is never sent again.",
23
+ },
24
+ { value: "failed", description: "Approved; the provider refused it, and nothing was sent." },
25
+ { value: "rejected", description: "Rejected: the person never sees it." },
26
+ ];
27
+ export const AGENT_REVIEW_MODES = [
28
+ { value: "always", description: "Every reply in the conversation waits for a member." },
29
+ {
30
+ value: "whenUnsure",
31
+ description: "The decision model was not sure enough that staff would send it as written.",
32
+ },
33
+ ];
34
+ /** The longest reply a review holds; a provider may accept less in one message. */
35
+ export const AGENT_REVIEW_TEXT_LIMIT = 20_000;
36
+ export const AgentReview = entity("agent_review", {
37
+ id: "ent_agent_review",
38
+ label: "Agent reply review",
39
+ plural: "Agent reply reviews",
40
+ title: "draft",
41
+ description: "A reply the agent wrote to a person and held for a member to review, as the workspace's " +
42
+ "conversations settings ask. Approve it, with an edit if needed, to send it to the person as " +
43
+ "the agent; reject it to discard it.",
44
+ writes: "actions",
45
+ properties: {
46
+ key: p.text({
47
+ managed: true,
48
+ maxLength: 512,
49
+ unique: true,
50
+ description: "The agent's key for the reply, so a repeated report holds it once.",
51
+ }),
52
+ provider: p.text({ managed: true, description: "The channel, for example telegram." }),
53
+ chatId: p.text({ managed: true, description: "The conversation's id at the provider." }),
54
+ recipient: p.text({
55
+ managed: true,
56
+ description: "Whom the provider sends the reply to: the chat's id, or the person's number on WhatsApp.",
57
+ }),
58
+ chatKind: p.select([
59
+ { value: "private", description: "The person's own conversation with the agent." },
60
+ { value: "group", description: "A group chat." },
61
+ ], { managed: true, label: "Chat kind", description: "Whether the conversation is a group." }),
62
+ threadId: p.text({
63
+ optional: true,
64
+ managed: true,
65
+ description: "The thread or topic of the conversation, when it has one.",
66
+ }),
67
+ replyTo: p.text({
68
+ optional: true,
69
+ managed: true,
70
+ description: "The person's message the reply answers, when the provider replies to one.",
71
+ }),
72
+ sessionId: p.text({ managed: true, description: "The agent's session that wrote the reply." }),
73
+ draft: p.text({
74
+ managed: true,
75
+ maxLength: AGENT_REVIEW_TEXT_LIMIT,
76
+ display: "multiline",
77
+ description: "The reply as the agent wrote it, in Markdown.",
78
+ }),
79
+ text: p.text({
80
+ optional: true,
81
+ managed: true,
82
+ maxLength: AGENT_REVIEW_TEXT_LIMIT,
83
+ display: "multiline",
84
+ description: "The reply as approved: the draft, or the member's edit of it.",
85
+ }),
86
+ status: p.select(AGENT_REVIEW_STATUSES, {
87
+ managed: true,
88
+ description: "Whether the reply waits, was delivered, or was rejected.",
89
+ }),
90
+ mode: p.select(AGENT_REVIEW_MODES, { managed: true, description: "Why the reply was held." }),
91
+ confidence: p.number({
92
+ optional: true,
93
+ managed: true,
94
+ min: 0,
95
+ max: 1,
96
+ description: "The decision model's probability that staff would send the reply as written; empty " +
97
+ "when the conversation holds every reply or the model gave none.",
98
+ }),
99
+ messageId: p.text({
100
+ optional: true,
101
+ managed: true,
102
+ label: "Message id",
103
+ description: "The delivered message's id at the provider.",
104
+ }),
105
+ decidedAt: p.timestamp({
106
+ optional: true,
107
+ managed: true,
108
+ label: "Decided",
109
+ description: "When a member approved or rejected the reply.",
110
+ }),
111
+ },
112
+ relationships: {
113
+ // By name, so that an ontology rebuilt with the deployed `user` still resolves it.
114
+ person: rel.one("user", {
115
+ inverse: "agentReviews",
116
+ onDelete: "cascade",
117
+ phrase: ["answers", "is answered by"],
118
+ description: "The person the reply is for.",
119
+ }),
120
+ decidedBy: rel.one("user", {
121
+ optional: true,
122
+ inverse: "decidedAgentReviews",
123
+ onDelete: "setNull",
124
+ phrase: ["was decided by", "decided"],
125
+ description: "The member who approved or rejected the reply.",
126
+ }),
127
+ },
128
+ indexes: [{ properties: ["status"] }],
129
+ }).actions((self) => ({
130
+ approve: action({
131
+ description: "Send a reply the agent held for review to the person, as written or with your edit in " +
132
+ "text (Markdown), as the agent and without sender attribution. Confirm the final text " +
133
+ "with the member first. It is sent at most once: approving again with the same text " +
134
+ "returns the delivery, and an approved or rejected review is refused otherwise. status " +
135
+ "failed means the provider refused it and nothing was sent.",
136
+ hints: { destructive: false, irreversible: true, idempotent: true },
137
+ input: Schema.Struct({
138
+ review: self.ref,
139
+ text: Schema.optionalKey(p.text({
140
+ maxLength: AGENT_REVIEW_TEXT_LIMIT,
141
+ description: "The member's edit of the reply; omit it to send the draft.",
142
+ })),
143
+ }),
144
+ connections: [],
145
+ prepare: ({ input }) => Effect.gen(function* () {
146
+ const delivery = yield* Effect.serviceOption(ChatDelivery);
147
+ const send = Option.isSome(delivery) ? delivery.value.sendReview : undefined;
148
+ if (send === undefined) {
149
+ return yield* new ActionRejected({
150
+ message: "Sending a reviewed reply requires the authenticated ontology service.",
151
+ });
152
+ }
153
+ return yield* send({
154
+ review: String(input.review),
155
+ ...(input.text === undefined ? {} : { text: input.text }),
156
+ });
157
+ }),
158
+ handler: ({ input, prepared, principal }) => Effect.gen(function* () {
159
+ const review = yield* self.get(input.review, { forUpdate: true });
160
+ // The delivery happened, or definitely did not: the record says what the provider did,
161
+ // even when another member rejected the review meanwhile.
162
+ yield* self.update(review, {
163
+ status: prepared.status,
164
+ text: prepared.text,
165
+ messageId: prepared.messageId,
166
+ decidedAt: review.decidedAt ?? new Date().toISOString(),
167
+ decidedBy: review.decidedById ?? principal.id,
168
+ });
169
+ return {
170
+ review: review.id,
171
+ status: prepared.status,
172
+ message_id: prepared.messageId,
173
+ duplicate: prepared.duplicate,
174
+ };
175
+ }),
176
+ }),
177
+ reject: action({
178
+ description: "Discard a reply the agent held for review: the person never sees it. A review already " +
179
+ "approved is refused.",
180
+ hints: { destructive: true, irreversible: false, idempotent: true },
181
+ input: Schema.Struct({ review: self.ref }),
182
+ handler: ({ input, principal }) => Effect.gen(function* () {
183
+ const review = yield* self.get(input.review, { forUpdate: true });
184
+ if (review.status === "rejected") {
185
+ return { review: review.id, status: "rejected" };
186
+ }
187
+ if (review.status !== "pending") {
188
+ return yield* new ActionRejected({
189
+ message: "The reply was already approved and sent; it cannot be rejected.",
190
+ });
191
+ }
192
+ yield* self.update(review, {
193
+ status: "rejected",
194
+ decidedAt: new Date().toISOString(),
195
+ decidedBy: principal.id,
196
+ });
197
+ return { review: review.id, status: "rejected" };
198
+ }),
199
+ }),
200
+ }));
package/dist/analyze.d.ts CHANGED
@@ -18,8 +18,8 @@ import { type ResolvedToolset, type Toolset } from "./toolset.js";
18
18
  /** The input of `defineOntology` and `check`. */
19
19
  export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = ReadonlyArray<AnyEntity>, Metrics extends ModelMetrics = ModelMetrics> extends EarlierMetricsField<Metrics> {
20
20
  /**
21
- * The app's entities. The built-in `User`, `AgentChat` and `UserIdentity` are always included;
22
- * listing them is optional.
21
+ * The app's entities. The built-in `User`, `AgentChat`, `UserIdentity` and `AgentReview` are
22
+ * always included; listing them is optional.
23
23
  */
24
24
  readonly entities: Entities;
25
25
  /**
package/dist/analyze.js CHANGED
@@ -14,6 +14,7 @@ import { isRole, member, role } from "./role.js";
14
14
  import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isSignInPolicy, isSignUpChannel, } from "./sign-in.js";
15
15
  import { emailOptions } from "./emails.js";
16
16
  import { AgentChat } from "./agent-chat.js";
17
+ import { AgentReview } from "./agent-review.js";
17
18
  import { APP_FEEDBACK_ENTITIES } from "./app-feedback.js";
18
19
  import { feedbackOptions, feedbackRoles, checkFeedbackResponders, } from "./feedback-config.js";
19
20
  import { User } from "./user.js";
@@ -57,6 +58,7 @@ export function analyze(config, options = {}) {
57
58
  options.user ?? User,
58
59
  AgentChat,
59
60
  UserIdentity,
61
+ AgentReview,
60
62
  ...(feedbackSetting !== false ? APP_FEEDBACK_ENTITIES : []),
61
63
  ], report);
62
64
  config = normalized.config;
@@ -123,13 +125,18 @@ export function analyze(config, options = {}) {
123
125
  };
124
126
  }
125
127
  const { feedback, roles } = feedbackRoles(feedbackSetting, files, declaredRoles, report);
126
- // Resolve authored entities before the optional feedback entities, preserving their ordering.
128
+ // Resolve authored entities before the optional feedback entities and the agent's reviews,
129
+ // preserving their ordering: built-ins added later never move an authored entity.
127
130
  const isFeedback = (candidate) => APP_FEEDBACK_ENTITIES.some((feedback) => feedback.name === candidate.name);
131
+ const isReview = (candidate) => candidate.name === AgentReview.name;
128
132
  let resolved = [
129
133
  ...entities
130
- .filter((candidate) => !isFeedback(candidate))
134
+ .filter((candidate) => !isFeedback(candidate) && !isReview(candidate))
131
135
  .map((candidate) => resolveEntity(candidate, scope, properties.get(candidate))),
132
136
  ...entities.filter(isFeedback).map((candidate) => resolveEntity(candidate, scope)),
137
+ ...entities
138
+ .filter(isReview)
139
+ .map((candidate) => resolveEntity(candidate, scope, properties.get(candidate))),
133
140
  ];
134
141
  let chat;
135
142
  if (config.chat !== undefined) {
@@ -168,11 +175,16 @@ export function analyze(config, options = {}) {
168
175
  ...Object.fromEntries(handles.map(([name, handle]) => [name, { connection: handle.key }])),
169
176
  ...(config.chat.attribution === undefined ? {} : { attribution: config.chat.attribution }),
170
177
  };
171
- resolved = resolved.map((entity) => entity.name !== "agent_chat"
178
+ // Posting to a chat and sending a reviewed reply both send through the chat connections.
179
+ const sends = {
180
+ agent_chat: "post_message",
181
+ agent_review: "approve",
182
+ };
183
+ resolved = resolved.map((entity) => sends[entity.name] === undefined
172
184
  ? entity
173
185
  : {
174
186
  ...entity,
175
- actions: entity.actions.map((candidate) => candidate.name !== "post_message"
187
+ actions: entity.actions.map((candidate) => candidate.name !== sends[entity.name]
176
188
  ? candidate
177
189
  : {
178
190
  ...candidate,
@@ -2316,7 +2328,7 @@ function checkRolePermissions(candidate, verbs, workflows, report) {
2316
2328
  }
2317
2329
  if (parsed.entity === WILDCARD && parsed.verb === WILDCARD) {
2318
2330
  report("wildcard-permission", at, "*:* grants every entity and action, including those added later, except agent_chat, " +
2319
- "app_feedback, app_feedback_file, user_identity and " +
2331
+ "agent_review, app_feedback, app_feedback_file, user_identity and " +
2320
2332
  `administering users (${USER_MEMBER_VERBS.map((verb) => `user:${verb}`).join(", ")} ` +
2321
2333
  "and user's authored actions), which only user:<verb> or user:* grants.", "warning");
2322
2334
  return;
package/dist/chat.d.ts CHANGED
@@ -32,10 +32,26 @@ export interface ChatPreview {
32
32
  }
33
33
  export declare const chatOperationId: (sessionId: string, callId: string) => string;
34
34
  export declare const chatPreviewDigest: (preview: ChatPreview) => string;
35
+ /** A member's approval of a reply the agent held for review: the draft, or their edit of it. */
36
+ export interface ReviewSendInput {
37
+ /** The `agent_review` record's id. */
38
+ readonly review: string;
39
+ readonly text?: string;
40
+ }
41
+ /** What sending an approved reply did; `duplicate` when an earlier approval already sent it. */
42
+ export interface ReviewSendResult {
43
+ readonly status: "sent" | "uncertain" | "failed";
44
+ /** The text sent, or attempted. */
45
+ readonly text: string;
46
+ readonly messageId: string | null;
47
+ readonly duplicate: boolean;
48
+ }
35
49
  declare const ChatDelivery_base: Context.ServiceClass<ChatDelivery, "@segmentstream/ontology/ChatDelivery", {
36
50
  readonly preview: (input: ChatPostInput) => Effect.Effect<ChatPreview, ActionError>;
37
51
  readonly validate: (input: ChatPostInput) => Effect.Effect<void, ActionError>;
38
52
  readonly post: (input: ChatPostInput) => Effect.Effect<ChatPostResult, ActionError>;
53
+ /** Sends a reply a member approved, as the agent and without attribution, at most once. */
54
+ readonly sendReview?: (input: ReviewSendInput) => Effect.Effect<ReviewSendResult, ActionError>;
39
55
  }>;
40
56
  /** Deliver the exact Markdown source through the channel renderer, without invoking an agent. */
41
57
  export declare class ChatDelivery extends ChatDelivery_base {
package/dist/index.d.ts CHANGED
@@ -57,10 +57,12 @@ export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, Batc
57
57
  export { User } from "./user.js";
58
58
  export type { UserHandle, UserMemberWrites } from "./user.js";
59
59
  export { AgentChat } from "./agent-chat.js";
60
+ export { AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-review.js";
60
61
  export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
61
62
  export type { AttachableIdentityProvider, UserIdentityOrigin } from "./user-identity.js";
62
63
  export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
63
64
  export { ChatDelivery, ChatPostInput, ChatPostResult } from "./chat.js";
65
+ export type { ReviewSendInput, ReviewSendResult } from "./chat.js";
64
66
  export { DEFAULT_QUERY_LIMIT, entityQueryResultSchema, entityQuerySchema, entityQuerySchemas, entityRecordSchema, FILTER_OPERATORS, LIST_FILTER_OPERATORS, MANY_QUANTIFIERS, MAX_IN_VALUES, MAX_QUERY_LIMIT, OrderBy, Query, queryFields, queryJsonSchema, queryLinks, QueryResult, queryResultJsonSchema, queryResultSchema, SortDirection, WHERE_COMBINATORS, } from "./query.js";
65
67
  export type { EntityQuerySchemas, FieldFilter, FilterOperator, JsonRecord, ListFilterOperator, ManyFilter, QueryField, QueryLink, StorageType, Where, } from "./query.js";
66
68
  export { InvalidQuery, InvalidValues, MemberNotFound, PrincipalRejected, StoredRecordMismatch, UnknownAction, UnknownRole, ValidationIssue, UndeclaredWrite, WriteOutsideAction, } from "./runtime/errors.js";
@@ -84,7 +86,7 @@ export { configFromEnv, ENVIRONMENT_VARIABLES, NEON_AUTH_ENVIRONMENT_VARIABLES,
84
86
  export type { ActionCommitted, AfterCommitHook, NeonAuthEnvironment, OntologyEnvironment, OntologyServiceConfig, } from "./service/config.js";
85
87
  export type { Decide, DecisionRequest } from "./service/decisions.js";
86
88
  export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-contract.js";
87
- export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, SeenChat, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
89
+ export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
88
90
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
89
91
  export { AGENT_PATH } from "./service/agent/server.js";
90
92
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
package/dist/index.js CHANGED
@@ -30,6 +30,7 @@ export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POL
30
30
  export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
31
31
  export { User } from "./user.js";
32
32
  export { AgentChat } from "./agent-chat.js";
33
+ export { AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-review.js";
33
34
  export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
34
35
  export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
35
36
  export { ChatDelivery, ChatPostInput, ChatPostResult } from "./chat.js";
@@ -18,7 +18,9 @@ export declare const READ_VERB = "read";
18
18
  * App feedback is a member's own message to the builders: a member reads theirs through a scoped
19
19
  * `app_feedback:read`, and only the builders' roles name it unscoped. The built-in sign-in
20
20
  * identities hold every member's external accounts, such as their Telegram id and username: only a
21
- * role that names `user_identity` reads them.
21
+ * role that names `user_identity` reads them. The agent's held replies hold the workspace's
22
+ * conversations with the people it serves, and approving one sends it: only a role that names
23
+ * `agent_review` reads, approves or rejects them.
22
24
  */
23
25
  export declare const EXPLICIT_GRANT_ENTITIES: ReadonlySet<string>;
24
26
  /**
@@ -150,8 +152,8 @@ export interface PermissionHolder {
150
152
  }
151
153
  /**
152
154
  * Whether the principal may do what `required` names: one of its permissions equals it, or covers it
153
- * through a wildcard. Workload wildcards exclude user administration, feedback and writes of sign-in
154
- * identities.
155
+ * through a wildcard. Workload wildcards exclude user administration, feedback, the agent's held
156
+ * replies and writes of sign-in identities.
155
157
  */
156
158
  export declare function isAllowed(required: string, principal: PermissionHolder): boolean;
157
159
  /**
@@ -17,10 +17,13 @@ export const READ_VERB = "read";
17
17
  * App feedback is a member's own message to the builders: a member reads theirs through a scoped
18
18
  * `app_feedback:read`, and only the builders' roles name it unscoped. The built-in sign-in
19
19
  * identities hold every member's external accounts, such as their Telegram id and username: only a
20
- * role that names `user_identity` reads them.
20
+ * role that names `user_identity` reads them. The agent's held replies hold the workspace's
21
+ * conversations with the people it serves, and approving one sends it: only a role that names
22
+ * `agent_review` reads, approves or rejects them.
21
23
  */
22
24
  export const EXPLICIT_GRANT_ENTITIES = new Set([
23
25
  "agent_chat",
26
+ "agent_review",
24
27
  "app_feedback",
25
28
  "app_feedback_file",
26
29
  "user_identity",
@@ -151,7 +154,8 @@ function isUserAdministration(required) {
151
154
  !wildcardEntityCovers(USER_ENTITY, toSnakeCase(wanted.verb)));
152
155
  }
153
156
  /**
154
- * Feedback always needs named grants, including for pipeline workloads. The workspace's own pipeline
157
+ * Feedback and the agent's held replies always need named grants, including for pipeline
158
+ * workloads: nothing a pipeline runs approves a reply to a person. The workspace's own pipeline
155
159
  * code reads sign-in identities, for example to address a member in a chat, but nothing it runs
156
160
  * writes them: only the platform does.
157
161
  */
@@ -162,12 +166,12 @@ function workloadWildcardCovers(required) {
162
166
  }
163
167
  return (!isUserAdministration(required) &&
164
168
  (wanted === undefined ||
165
- !["app_feedback", "app_feedback_file"].includes(toSnakeCase(wanted.entity))));
169
+ !["app_feedback", "app_feedback_file", "agent_review"].includes(toSnakeCase(wanted.entity))));
166
170
  }
167
171
  /**
168
172
  * Whether the principal may do what `required` names: one of its permissions equals it, or covers it
169
- * through a wildcard. Workload wildcards exclude user administration, feedback and writes of sign-in
170
- * identities.
173
+ * through a wildcard. Workload wildcards exclude user administration, feedback, the agent's held
174
+ * replies and writes of sign-in identities.
171
175
  */
172
176
  export function isAllowed(required, principal) {
173
177
  return (
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { Effect } from "effect";
4
4
  import { SqlClient } from "effect/unstable/sql";
5
5
  import { AgentChat } from "../agent-chat.js";
6
+ import { AgentReview } from "../agent-review.js";
6
7
  import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
7
8
  import { MAX_QUERY_LIMIT } from "../query.js";
8
9
  import { beginReplicationWrite } from "../replication/transaction.js";
@@ -435,6 +436,58 @@ export function sqlAgentStore(ontology, sql) {
435
436
  };
436
437
  }))
437
438
  .pipe(Effect.orDie),
439
+ holdReply: (input) => sql
440
+ .withTransaction(Effect.gen(function* () {
441
+ if (!isRecordId(input.memberId)) {
442
+ return undefined;
443
+ }
444
+ yield* beginReplicationWrite(sql);
445
+ // Reports of one reply run one after the other: the first creates it, the rest find it.
446
+ yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${input.key}`]);
447
+ const runtime = makeOntologyRuntime(ontology, sql, {
448
+ action: `${AgentReview.name}.hold`,
449
+ actionId: randomUUID(),
450
+ principalId: null,
451
+ });
452
+ const [found] = yield* runtime.find({
453
+ entity: AgentReview.name,
454
+ options: { where: { key: input.key }, limit: 1 },
455
+ });
456
+ if (found !== undefined) {
457
+ return { id: String(found.id), status: String(found.status), created: false };
458
+ }
459
+ const [member] = yield* rows(`SELECT 1 FROM ${USERS} WHERE "id" = $1::uuid AND "kind"::text = 'member' AND "active"`, [input.memberId]);
460
+ if (member === undefined) {
461
+ return undefined;
462
+ }
463
+ const review = yield* runtime.create({
464
+ entity: AgentReview.name,
465
+ values: {
466
+ key: input.key,
467
+ provider: input.provider,
468
+ chat_id: input.chatId,
469
+ recipient: input.recipient,
470
+ // Telegram's groups and channels have negative ids; WhatsApp chats are private.
471
+ chat_kind: input.provider === "telegram" && input.chatId.startsWith("-")
472
+ ? "group"
473
+ : "private",
474
+ thread_id: input.threadId === "" ? null : input.threadId,
475
+ reply_to: input.replyTo,
476
+ session_id: input.sessionId,
477
+ draft: input.text,
478
+ text: null,
479
+ status: "pending",
480
+ // Select values are stored by their wire names.
481
+ mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
482
+ confidence: input.confidence,
483
+ message_id: null,
484
+ decided_at: null,
485
+ person: input.memberId,
486
+ },
487
+ });
488
+ return { id: String(review.id), status: "pending", created: true };
489
+ }))
490
+ .pipe(Effect.orDie),
438
491
  };
439
492
  return store;
440
493
  }
@@ -68,6 +68,24 @@ export declare const ChatSeenRequest: Schema.Struct<{
68
68
  readonly agentLeft: Schema.optionalKey<Schema.Literal<true>>;
69
69
  readonly migratedFrom: Schema.optionalKey<Schema.String>;
70
70
  }>;
71
+ /**
72
+ * `POST /api/ontology/agent/reviews`: a reply the agent held for a member to review, for the member
73
+ * it answers. `key` names the reply, so a report repeated after a failure finds its review.
74
+ */
75
+ export declare const ReviewRequest: Schema.Struct<{
76
+ readonly key: Schema.String;
77
+ readonly provider: Schema.String;
78
+ readonly chat_id: Schema.String;
79
+ readonly recipient: Schema.String;
80
+ readonly thread_id: Schema.String;
81
+ readonly reply_to: Schema.NullOr<Schema.String>;
82
+ readonly member_id: Schema.String;
83
+ readonly session_id: Schema.String;
84
+ readonly text: Schema.String;
85
+ readonly mode: Schema.Literals<readonly ["always", "whenUnsure"]>;
86
+ readonly confidence: Schema.NullOr<Schema.Number>;
87
+ }>;
88
+ export type ReviewRequest = typeof ReviewRequest.Type;
71
89
  /** An identity on the wire, as the member's connect page and settings show it. */
72
90
  export declare function identityForWire(identity: AgentIdentity): {
73
91
  created_at: string;