@segmentstream/ontology 0.129.0 → 0.130.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 +8 -0
- package/dist/agent-review.d.ts +5 -0
- package/dist/agent-review.js +23 -4
- package/dist/runtime/agents.d.ts +3 -1
- package/dist/runtime/agents.js +184 -55
- package/dist/runtime/service-binding.js +6 -0
- package/dist/service/agent/protocol.d.ts +7 -0
- package/dist/service/agent/protocol.js +9 -0
- package/dist/service/agent/server.js +32 -1
- package/dist/service/runtime-contract.d.ts +17 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.130.0
|
|
4
|
+
|
|
5
|
+
Reply review now gives the workspace what it needs to learn from staff decisions, and gives the agent what became of its replies.
|
|
6
|
+
|
|
7
|
+
- **Reason for a rejection.** `agent_review.reject({ review, reason })` keeps a member's reason as the review's `reason`. `useInboxChat`'s `reject(reply, reason)` passes it. Neither the person nor the agent's chat with them sees it.
|
|
8
|
+
- **Workflows on reviews.** `after(...)` on `AgentReview.actions.approve` or `reject` runs a workspace workflow after a member's decision. `after(...)` on `AgentReview` with `when: (event) => event.action === "agent_review.hold"` runs one when the agent holds a reply, for example to tell reviewers. Holding starts these runs like an action does.
|
|
9
|
+
- **What the agent learns.** At its next turn, the agent's session gets a `<held_replies>` block for each reply it held: `waiting`, `sent` (`edited` when a member sent their own version), `uncertain` (approved, but delivery is in doubt) or `not_sent`. It now goes on from what the person actually saw, without learning anything a member wrote. The ontology service answers it at `POST /api/ontology/agent/reviews/session`. An ontology service that predates the route answers nothing, and the agent behaves as before.
|
|
10
|
+
|
|
3
11
|
## 0.129.0
|
|
4
12
|
|
|
5
13
|
A provider's secret for checking what it sends, such as a webhook signing secret, lives on its
|
package/dist/agent-review.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export declare const AGENT_REVIEW_MODES: readonly [{
|
|
|
33
33
|
}];
|
|
34
34
|
/** The longest reply a review holds; a provider may accept less in one message. */
|
|
35
35
|
export declare const AGENT_REVIEW_TEXT_LIMIT = 20000;
|
|
36
|
+
/** The longest reason a member gives for rejecting a reply. */
|
|
37
|
+
export declare const AGENT_REVIEW_REASON_LIMIT = 2000;
|
|
36
38
|
export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
37
39
|
readonly key: import("./property.js").Property<string, false, true>;
|
|
38
40
|
readonly provider: import("./property.js").Property<string, false, false>;
|
|
@@ -50,6 +52,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
|
50
52
|
readonly confidence: Schema.optionalKey<import("./property.js").Property<number, false, false>>;
|
|
51
53
|
readonly messageId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
52
54
|
readonly decidedAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
55
|
+
readonly reason: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
53
56
|
}, {
|
|
54
57
|
readonly person: import("./relationship.js").OneRelationship<false, false, "user">;
|
|
55
58
|
readonly decidedBy: import("./relationship.js").OneRelationship<true, false, "user">;
|
|
@@ -66,6 +69,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
|
66
69
|
}>;
|
|
67
70
|
readonly reject: import("./action.js").Action<Schema.Struct<{
|
|
68
71
|
readonly review: Schema.Codec<string, string, never, never>;
|
|
72
|
+
readonly reason: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
69
73
|
}>, {
|
|
70
74
|
review: string;
|
|
71
75
|
status: "rejected";
|
|
@@ -92,6 +96,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
|
92
96
|
readonly confidence: number | null;
|
|
93
97
|
readonly messageId: string | null;
|
|
94
98
|
readonly decidedAt: string | null;
|
|
99
|
+
readonly reason: string | null;
|
|
95
100
|
readonly personId: string;
|
|
96
101
|
readonly decidedById: string | null;
|
|
97
102
|
readonly agentChatId: string | null;
|
package/dist/agent-review.js
CHANGED
|
@@ -33,6 +33,8 @@ export const AGENT_REVIEW_MODES = [
|
|
|
33
33
|
];
|
|
34
34
|
/** The longest reply a review holds; a provider may accept less in one message. */
|
|
35
35
|
export const AGENT_REVIEW_TEXT_LIMIT = 20_000;
|
|
36
|
+
/** The longest reason a member gives for rejecting a reply. */
|
|
37
|
+
export const AGENT_REVIEW_REASON_LIMIT = 2_000;
|
|
36
38
|
export const AgentReview = entity("agent_review", {
|
|
37
39
|
id: "ent_agent_review",
|
|
38
40
|
label: "Agent reply review",
|
|
@@ -118,6 +120,14 @@ export const AgentReview = entity("agent_review", {
|
|
|
118
120
|
label: "Decided",
|
|
119
121
|
description: "When a member approved or rejected the reply.",
|
|
120
122
|
}),
|
|
123
|
+
reason: p.text({
|
|
124
|
+
optional: true,
|
|
125
|
+
managed: true,
|
|
126
|
+
maxLength: AGENT_REVIEW_REASON_LIMIT,
|
|
127
|
+
display: "multiline",
|
|
128
|
+
description: "Why the member rejected the reply, when they said: for the workspace's own review of " +
|
|
129
|
+
"the agent's replies. The person and the agent's chat with them never see it.",
|
|
130
|
+
}),
|
|
121
131
|
},
|
|
122
132
|
relationships: {
|
|
123
133
|
// By name, so that an ontology rebuilt with the deployed `user` still resolves it.
|
|
@@ -143,7 +153,7 @@ export const AgentReview = entity("agent_review", {
|
|
|
143
153
|
"is in, or a person's private chat in the inbox. Empty when the chat is not registered.",
|
|
144
154
|
}),
|
|
145
155
|
},
|
|
146
|
-
indexes: [{ properties: ["status"] }],
|
|
156
|
+
indexes: [{ properties: ["status"] }, { properties: ["sessionId"] }],
|
|
147
157
|
}).actions((self) => ({
|
|
148
158
|
approve: action({
|
|
149
159
|
description: "Send a reply the agent held for review to the person, as written or with your edit in " +
|
|
@@ -193,10 +203,17 @@ export const AgentReview = entity("agent_review", {
|
|
|
193
203
|
}),
|
|
194
204
|
}),
|
|
195
205
|
reject: action({
|
|
196
|
-
description: "Discard a reply the agent held for review: the person never sees it.
|
|
197
|
-
"
|
|
206
|
+
description: "Discard a reply the agent held for review: the person never sees it. Say why in reason " +
|
|
207
|
+
"when the member gives one; it stays with the review and never reaches the person or the " +
|
|
208
|
+
"agent's chat with them. A review already approved is refused.",
|
|
198
209
|
hints: { destructive: true, irreversible: false, idempotent: true },
|
|
199
|
-
input: Schema.Struct({
|
|
210
|
+
input: Schema.Struct({
|
|
211
|
+
review: self.ref,
|
|
212
|
+
reason: Schema.optionalKey(p.text({
|
|
213
|
+
maxLength: AGENT_REVIEW_REASON_LIMIT,
|
|
214
|
+
description: "Why the reply should not be sent, in the member's words.",
|
|
215
|
+
})),
|
|
216
|
+
}),
|
|
200
217
|
handler: ({ input, principal }) => Effect.gen(function* () {
|
|
201
218
|
const review = yield* self.get(input.review, { forUpdate: true });
|
|
202
219
|
if (review.status === "rejected") {
|
|
@@ -207,10 +224,12 @@ export const AgentReview = entity("agent_review", {
|
|
|
207
224
|
message: "The reply was already approved and sent; it cannot be rejected.",
|
|
208
225
|
});
|
|
209
226
|
}
|
|
227
|
+
const reason = input.reason?.trim();
|
|
210
228
|
yield* self.update(review, {
|
|
211
229
|
status: "rejected",
|
|
212
230
|
decidedAt: new Date().toISOString(),
|
|
213
231
|
decidedBy: principal.id,
|
|
232
|
+
...(reason === undefined || reason === "" ? {} : { reason }),
|
|
214
233
|
});
|
|
215
234
|
return { review: review.id, status: "rejected" };
|
|
216
235
|
}),
|
package/dist/runtime/agents.d.ts
CHANGED
|
@@ -6,7 +6,9 @@ import { type AgentResolution, type AgentStore, type ResolveIdentityInput, type
|
|
|
6
6
|
* The agent store on the runtime's agent tables, as `ontology_app`. Expiry is the database's
|
|
7
7
|
* `now()`; a pairing is consumed with one `UPDATE … WHERE "consumed_at" IS NULL`, so two concurrent
|
|
8
8
|
* approvals cannot both succeed. Ids that are not UUIDs find nothing rather than fail the cast.
|
|
9
|
-
* Chats the agent sees are `agent_chat` records, written as the platform with history.
|
|
9
|
+
* Chats the agent sees are `agent_chat` records, written as the platform with history. Holding a
|
|
10
|
+
* reply is admitted, bounded and starts the workflows whose triggers on `agent_review` fire for it as
|
|
11
|
+
* an action is and does, with the `ActionTransactions` and `WorkflowStarter` it runs with.
|
|
10
12
|
*/
|
|
11
13
|
export declare function sqlAgentStore(ontology: Ontology, sql: SqlClient.SqlClient): AgentStore;
|
|
12
14
|
/** Shared verified admission for agents and channel-app adapters; never expose trusted inputs to browsers. */
|
package/dist/runtime/agents.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { sqlConfirmationStore } from "./confirmations.js";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { Effect } from "effect";
|
|
3
|
+
import { Effect, Option, Schema } from "effect";
|
|
4
4
|
import { SqlClient } from "effect/unstable/sql";
|
|
5
|
+
import { action } from "../action.js";
|
|
5
6
|
import { AgentChat } from "../agent-chat.js";
|
|
6
7
|
import { chatChannelKind } from "../chat-channel.js";
|
|
7
8
|
import { AgentReview } from "../agent-review.js";
|
|
@@ -20,6 +21,10 @@ import { guestChat } from "./guests.js";
|
|
|
20
21
|
import { WEB_PROVIDER } from "../service/runtime-identity.js";
|
|
21
22
|
import { isRecordId } from "./records.js";
|
|
22
23
|
import { makeOntologyRuntime } from "./sql-runtime.js";
|
|
24
|
+
import { ACTION_TRANSACTION_LIMITS, ActionTransactions } from "./action-transactions.js";
|
|
25
|
+
import { actionTransaction } from "./action-deadlocks.js";
|
|
26
|
+
import { canonicalInstant } from "./records.js";
|
|
27
|
+
import { actionTriggers, evaluateTriggers, insertStarts, startCommitted, WorkflowStarter, } from "./workflow-starts.js";
|
|
23
28
|
import { CHANNEL_IDENTITIES_FROM, CHANNEL_ORIGIN_SQL, CHANNEL_REVOKED_AT, LIVE_CHANNEL_IDENTITY, makeIdentityWriter, USER_IDENTITY_TABLE, } from "./user-identities.js";
|
|
24
29
|
const PAIRINGS = `"${AGENT_PAIRINGS_TABLE}"`;
|
|
25
30
|
/** The legacy channel accounts, written beside `user_identity` for earlier SDKs. */
|
|
@@ -98,11 +103,26 @@ function identityOf(row) {
|
|
|
98
103
|
noticeVersion: nullableText(row.notice_version),
|
|
99
104
|
};
|
|
100
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* The action a held reply's record is written by, `agent_review.hold`. Only the agent holds replies,
|
|
108
|
+
* through the reviews route, so it is no action of the entity anyone can call: action triggers on
|
|
109
|
+
* `agent_review` itself fire for it, with its input and the review as the result.
|
|
110
|
+
*/
|
|
111
|
+
const HOLD_ACTION = "hold";
|
|
112
|
+
/** The most waiting, and the most decided, held replies of one session its next turn learns about. */
|
|
113
|
+
const SESSION_REVIEWS = 50;
|
|
114
|
+
const HOLD_DEFINITION = action({
|
|
115
|
+
description: "The agent held a reply for review.",
|
|
116
|
+
input: Schema.Struct({}),
|
|
117
|
+
handler: () => Effect.void,
|
|
118
|
+
});
|
|
101
119
|
/**
|
|
102
120
|
* The agent store on the runtime's agent tables, as `ontology_app`. Expiry is the database's
|
|
103
121
|
* `now()`; a pairing is consumed with one `UPDATE … WHERE "consumed_at" IS NULL`, so two concurrent
|
|
104
122
|
* approvals cannot both succeed. Ids that are not UUIDs find nothing rather than fail the cast.
|
|
105
|
-
* Chats the agent sees are `agent_chat` records, written as the platform with history.
|
|
123
|
+
* Chats the agent sees are `agent_chat` records, written as the platform with history. Holding a
|
|
124
|
+
* reply is admitted, bounded and starts the workflows whose triggers on `agent_review` fire for it as
|
|
125
|
+
* an action is and does, with the `ActionTransactions` and `WorkflowStarter` it runs with.
|
|
106
126
|
*/
|
|
107
127
|
export function sqlAgentStore(ontology, sql) {
|
|
108
128
|
const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
|
|
@@ -667,65 +687,170 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
667
687
|
};
|
|
668
688
|
}));
|
|
669
689
|
}).pipe(Effect.orDie),
|
|
670
|
-
holdReply: (input) =>
|
|
671
|
-
|
|
690
|
+
holdReply: (input) => Effect.gen(function* () {
|
|
691
|
+
// The triggers on `agent_review` itself, which fire for any of its actions: holding is one.
|
|
692
|
+
const triggers = actionTriggers(ontology).filter((trigger) => trigger.entity === AgentReview.name &&
|
|
693
|
+
(trigger.action === undefined || trigger.action === HOLD_ACTION));
|
|
694
|
+
const starter = triggers.length > 0
|
|
695
|
+
? Option.getOrUndefined(yield* Effect.serviceOption(WorkflowStarter))
|
|
696
|
+
: undefined;
|
|
697
|
+
// Admitted and bounded as an action's transaction is, by the same gate and limits.
|
|
698
|
+
const admission = Option.getOrUndefined(yield* Effect.serviceOption(ActionTransactions));
|
|
699
|
+
const limits = admission?.limits ?? ACTION_TRANSACTION_LIMITS;
|
|
700
|
+
const qualified = `${AgentReview.name}.${HOLD_ACTION}`;
|
|
701
|
+
const actionId = randomUUID();
|
|
672
702
|
if (!isRecordId(input.memberId)) {
|
|
673
703
|
return undefined;
|
|
674
704
|
}
|
|
675
|
-
|
|
676
|
-
//
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
action: `${AgentReview.name}.hold`,
|
|
680
|
-
actionId: randomUUID(),
|
|
681
|
-
principalId: null,
|
|
682
|
-
});
|
|
683
|
-
const [found] = yield* runtime.find({
|
|
684
|
-
entity: AgentReview.name,
|
|
685
|
-
options: { where: { key: input.key }, limit: 1 },
|
|
686
|
-
});
|
|
687
|
-
if (found !== undefined) {
|
|
688
|
-
return { id: String(found.id), status: String(found.status), created: false };
|
|
705
|
+
// Before the transaction: whatever it commits must be swept if this request does not start
|
|
706
|
+
// it. The transaction rolls back rather than commit after the deadline the sweep covers.
|
|
707
|
+
if (starter !== undefined) {
|
|
708
|
+
yield* starter.ensureRecovery({ commitBy: Date.now() + limits.handlerTimeoutMs });
|
|
689
709
|
}
|
|
690
|
-
const
|
|
691
|
-
|
|
710
|
+
const transaction = actionTransaction(sql, () => Effect.gen(function* () {
|
|
711
|
+
yield* sql.unsafe(`SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true)`, [`${limits.statementTimeoutMs}ms`, `${limits.lockTimeoutMs}ms`]);
|
|
712
|
+
yield* beginReplicationWrite(sql);
|
|
713
|
+
// Reports of one reply run one after the other: the first creates it, the rest find it.
|
|
714
|
+
yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${input.key}`]);
|
|
715
|
+
const edits = [];
|
|
716
|
+
const snapshots = new Map();
|
|
717
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
718
|
+
action: qualified,
|
|
719
|
+
actionId,
|
|
720
|
+
principalId: null,
|
|
721
|
+
...(triggers.length > 0
|
|
722
|
+
? {
|
|
723
|
+
onEdit: (edit) => edits.push(edit),
|
|
724
|
+
onSnapshot: (snapshot) => {
|
|
725
|
+
if (snapshot.entity === AgentReview.name) {
|
|
726
|
+
snapshots.set(snapshot.id, {
|
|
727
|
+
before: snapshots.get(snapshot.id)?.before ?? snapshot.before,
|
|
728
|
+
after: snapshot.after,
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
}
|
|
733
|
+
: {}),
|
|
734
|
+
});
|
|
735
|
+
const [found] = yield* runtime.find({
|
|
736
|
+
entity: AgentReview.name,
|
|
737
|
+
options: { where: { key: input.key }, limit: 1 },
|
|
738
|
+
});
|
|
739
|
+
if (found !== undefined) {
|
|
740
|
+
return {
|
|
741
|
+
review: { id: String(found.id), status: String(found.status), created: false },
|
|
742
|
+
starts: [],
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
const [member] = yield* rows(`SELECT 1 FROM ${USERS} WHERE "id" = $1::uuid AND "kind"::text = 'member' AND "active"`, [input.memberId]);
|
|
746
|
+
if (member === undefined) {
|
|
747
|
+
return undefined;
|
|
748
|
+
}
|
|
749
|
+
// The registry keys a chat by its channel's name and its id, as the archive does.
|
|
750
|
+
const [chat] = yield* runtime.find({
|
|
751
|
+
entity: AgentChat.name,
|
|
752
|
+
options: {
|
|
753
|
+
where: { provider: input.channel, external_id: input.chatId },
|
|
754
|
+
limit: 1,
|
|
755
|
+
},
|
|
756
|
+
});
|
|
757
|
+
const review = yield* runtime.create({
|
|
758
|
+
entity: AgentReview.name,
|
|
759
|
+
values: {
|
|
760
|
+
key: input.key,
|
|
761
|
+
provider: input.provider,
|
|
762
|
+
channel: input.channel,
|
|
763
|
+
chat_id: input.chatId,
|
|
764
|
+
recipient: input.recipient,
|
|
765
|
+
chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
|
|
766
|
+
thread_id: input.threadId === "" ? null : input.threadId,
|
|
767
|
+
reply_to: input.replyTo,
|
|
768
|
+
session_id: input.sessionId,
|
|
769
|
+
draft: input.text,
|
|
770
|
+
text: null,
|
|
771
|
+
status: "pending",
|
|
772
|
+
// Select values are stored by their wire names.
|
|
773
|
+
mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
|
|
774
|
+
confidence: input.confidence,
|
|
775
|
+
message_id: null,
|
|
776
|
+
decided_at: null,
|
|
777
|
+
person: input.memberId,
|
|
778
|
+
agent_chat: chat === undefined ? null : String(chat.id),
|
|
779
|
+
},
|
|
780
|
+
});
|
|
781
|
+
const result = { review: String(review.id), status: "pending" };
|
|
782
|
+
let starts = [];
|
|
783
|
+
if (triggers.length > 0) {
|
|
784
|
+
const principal = yield* memberPrincipal(input.memberId);
|
|
785
|
+
const [now] = yield* rows(`SELECT to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "at"`);
|
|
786
|
+
if (principal !== undefined) {
|
|
787
|
+
starts = yield* evaluateTriggers(triggers, {
|
|
788
|
+
ontology,
|
|
789
|
+
entity: AgentReview.name,
|
|
790
|
+
action: HOLD_ACTION,
|
|
791
|
+
definition: HOLD_DEFINITION,
|
|
792
|
+
generated: false,
|
|
793
|
+
actionId,
|
|
794
|
+
at: canonicalInstant(String(now.at)),
|
|
795
|
+
principal,
|
|
796
|
+
input,
|
|
797
|
+
result,
|
|
798
|
+
edits,
|
|
799
|
+
held: snapshots,
|
|
800
|
+
load: (id) => runtime.get({ entity: AgentReview.name, id }).pipe(Effect.map((record) => record), Effect.catchTag("NotFound", () => Effect.succeed(undefined))),
|
|
801
|
+
});
|
|
802
|
+
yield* insertStarts(sql, starts);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
return { review: { id: result.review, status: "pending", created: true }, starts };
|
|
806
|
+
}), {
|
|
807
|
+
qualified,
|
|
808
|
+
actionId,
|
|
809
|
+
retryOnDeadlock: false,
|
|
810
|
+
handlerTimeoutMs: limits.handlerTimeoutMs,
|
|
811
|
+
});
|
|
812
|
+
const held = yield* admission === undefined ? transaction : admission.admit(transaction);
|
|
813
|
+
if (held === undefined) {
|
|
692
814
|
return undefined;
|
|
693
815
|
}
|
|
694
|
-
// The
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
const
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
816
|
+
// The decided runs start once the review committed; a failure leaves them to the sweep.
|
|
817
|
+
yield* startCommitted(sql, starter, held.starts, actionId);
|
|
818
|
+
return held.review;
|
|
819
|
+
}).pipe(Effect.orDie),
|
|
820
|
+
sessionReviews: (sessionId) => Effect.gen(function* () {
|
|
821
|
+
const runtime = makeOntologyRuntime(ontology, sql);
|
|
822
|
+
// Every reply still waiting, however old, and the latest decisions: a decision on an old
|
|
823
|
+
// reply reaches the session as the newest one.
|
|
824
|
+
const [waiting, decided] = yield* Effect.all([
|
|
825
|
+
runtime.find({
|
|
826
|
+
entity: AgentReview.name,
|
|
827
|
+
options: {
|
|
828
|
+
where: { session_id: sessionId, status: "pending" },
|
|
829
|
+
orderBy: [{ field: "created_at", direction: "desc" }],
|
|
830
|
+
limit: SESSION_REVIEWS,
|
|
831
|
+
},
|
|
832
|
+
}),
|
|
833
|
+
runtime.find({
|
|
834
|
+
entity: AgentReview.name,
|
|
835
|
+
options: {
|
|
836
|
+
where: { session_id: sessionId, status: { ne: "pending" } },
|
|
837
|
+
orderBy: [{ field: "decided_at", direction: "desc" }],
|
|
838
|
+
limit: SESSION_REVIEWS,
|
|
839
|
+
},
|
|
840
|
+
}),
|
|
841
|
+
]);
|
|
842
|
+
const found = [...waiting, ...decided].sort((first, second) => instant(second.created_at) - instant(first.created_at));
|
|
843
|
+
return found.map((record) => ({
|
|
844
|
+
id: String(record.id),
|
|
845
|
+
status: String(record.status),
|
|
846
|
+
draft: String(record.draft),
|
|
847
|
+
edited: record.text !== null && record.text !== undefined && record.text !== record.draft,
|
|
848
|
+
heldAt: timestampText(record.created_at),
|
|
849
|
+
decidedAt: record.decided_at === null || record.decided_at === undefined
|
|
850
|
+
? null
|
|
851
|
+
: timestampText(record.decided_at),
|
|
852
|
+
}));
|
|
853
|
+
}).pipe(Effect.orDie),
|
|
729
854
|
web: sqlAgentWebStore(ontology, sql, {
|
|
730
855
|
signUp: (visitorId) => resolveChannelSignIn(ontology, sql, { provider: WEB_PROVIDER, externalId: visitorId }),
|
|
731
856
|
}),
|
|
@@ -767,6 +892,10 @@ function inInbox(ontology, input, resolution) {
|
|
|
767
892
|
: { ...resolution, inbox: true };
|
|
768
893
|
}
|
|
769
894
|
/** A stored timestamp, as the wire carries it. */
|
|
895
|
+
/** A stored timestamp as milliseconds since the epoch. */
|
|
896
|
+
function instant(value) {
|
|
897
|
+
return value instanceof Date ? value.getTime() : Date.parse(String(value));
|
|
898
|
+
}
|
|
770
899
|
function timestampText(value) {
|
|
771
900
|
return value instanceof Date ? value.toISOString() : String(value);
|
|
772
901
|
}
|
|
@@ -258,6 +258,12 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
|
|
|
258
258
|
resolveIdentity: (input) => agents
|
|
259
259
|
.resolveIdentity(input)
|
|
260
260
|
.pipe(withStarter, Effect.provideService(ActionTransactions, actionTransactions)),
|
|
261
|
+
// Holding a reply starts the workflows triggered on `agent_review`, as an action would.
|
|
262
|
+
...(agents.holdReply === undefined
|
|
263
|
+
? {}
|
|
264
|
+
: {
|
|
265
|
+
holdReply: (input) => agents.holdReply(input).pipe(withStarter, Effect.provideService(ActionTransactions, actionTransactions)),
|
|
266
|
+
}),
|
|
261
267
|
},
|
|
262
268
|
});
|
|
263
269
|
}));
|
|
@@ -156,6 +156,13 @@ export declare const ReviewRequest: Schema.Struct<{
|
|
|
156
156
|
readonly confidence: Schema.NullOr<Schema.Number>;
|
|
157
157
|
}>;
|
|
158
158
|
export type ReviewRequest = typeof ReviewRequest.Type;
|
|
159
|
+
/**
|
|
160
|
+
* `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
|
|
161
|
+
* next turn learns which the person saw.
|
|
162
|
+
*/
|
|
163
|
+
export declare const SessionReviewsRequest: Schema.Struct<{
|
|
164
|
+
readonly session_id: Schema.String;
|
|
165
|
+
}>;
|
|
159
166
|
/** An identity on the wire, as the member's connect page and settings show it. */
|
|
160
167
|
export declare function identityForWire(identity: AgentIdentity): {
|
|
161
168
|
created_at: string;
|
|
@@ -209,6 +209,15 @@ export const ReviewRequest = Schema.Struct({
|
|
|
209
209
|
description: "The decision model's probability that staff would send it as written.",
|
|
210
210
|
}),
|
|
211
211
|
});
|
|
212
|
+
/**
|
|
213
|
+
* `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
|
|
214
|
+
* next turn learns which the person saw.
|
|
215
|
+
*/
|
|
216
|
+
export const SessionReviewsRequest = Schema.Struct({
|
|
217
|
+
session_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
|
|
218
|
+
description: "The agent's session that held the replies.",
|
|
219
|
+
}),
|
|
220
|
+
});
|
|
212
221
|
/** An identity on the wire, as the member's connect page and settings show it. */
|
|
213
222
|
export function identityForWire(identity) {
|
|
214
223
|
return {
|
|
@@ -13,7 +13,7 @@ import { secretHash } from "../oauth/protocol.js";
|
|
|
13
13
|
import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
|
|
14
14
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
15
15
|
import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
16
|
-
import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
16
|
+
import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
17
17
|
import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
|
|
18
18
|
import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
|
|
19
19
|
import { identityToken } from "../operations.js";
|
|
@@ -403,6 +403,36 @@ function holdReply(store) {
|
|
|
403
403
|
return json({ id: review.id, status: review.status, created: review.created });
|
|
404
404
|
});
|
|
405
405
|
}
|
|
406
|
+
/**
|
|
407
|
+
* `POST /api/ontology/agent/reviews/session` (runtime): the replies the session held for review,
|
|
408
|
+
* newest first, with what became of each. Nothing a member wrote about them is in it.
|
|
409
|
+
*/
|
|
410
|
+
function sessionReviews(store) {
|
|
411
|
+
return (request) => Effect.gen(function* () {
|
|
412
|
+
const requestId = yield* RequestId;
|
|
413
|
+
const decoded = Schema.decodeUnknownResult(SessionReviewsRequest)(yield* jsonBody(request), {
|
|
414
|
+
errors: "all",
|
|
415
|
+
onExcessProperty: "error",
|
|
416
|
+
});
|
|
417
|
+
if (Result.isFailure(decoded)) {
|
|
418
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
419
|
+
}
|
|
420
|
+
if (store.sessionReviews === undefined) {
|
|
421
|
+
return toServerResponse(notFound(requestId, "This ontology service holds no replies."));
|
|
422
|
+
}
|
|
423
|
+
const reviews = yield* store.sessionReviews(decoded.success.session_id);
|
|
424
|
+
return json({
|
|
425
|
+
reviews: reviews.map((review) => ({
|
|
426
|
+
id: review.id,
|
|
427
|
+
status: review.status,
|
|
428
|
+
draft: review.draft,
|
|
429
|
+
edited: review.edited,
|
|
430
|
+
held_at: review.heldAt,
|
|
431
|
+
decided_at: review.decidedAt,
|
|
432
|
+
})),
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
}
|
|
406
436
|
/** `GET /api/ontology/agent/identities` (member): the member's own live identities. */
|
|
407
437
|
function listIdentities(store, member) {
|
|
408
438
|
return Effect.gen(function* () {
|
|
@@ -515,6 +545,7 @@ export function agentLayer(options) {
|
|
|
515
545
|
yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
|
|
516
546
|
yield* router.add("POST", CHATS_HANDOFF_PATH, asRuntime(handOffChat(store)));
|
|
517
547
|
yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
|
|
548
|
+
yield* router.add("POST", `${REVIEWS_PATH}/session`, asRuntime(sessionReviews(store)));
|
|
518
549
|
yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
|
|
519
550
|
if (store.web !== undefined && backend.oauth !== undefined) {
|
|
520
551
|
yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
|
|
@@ -689,6 +689,11 @@ export interface AgentStore {
|
|
|
689
689
|
* not an active member of the app. Absent on stores that predate reviews.
|
|
690
690
|
*/
|
|
691
691
|
readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
|
|
692
|
+
/**
|
|
693
|
+
* The replies an agent session held for review, newest first: what became of each, for the
|
|
694
|
+
* session's next turn. Absent on stores that predate it.
|
|
695
|
+
*/
|
|
696
|
+
readonly sessionReviews?: (sessionId: string) => Effect.Effect<ReadonlyArray<SessionReview>>;
|
|
692
697
|
/** The grants behind agent tokens for the web. Absent on stores that predate them. */
|
|
693
698
|
readonly web?: AgentWebStore;
|
|
694
699
|
}
|
|
@@ -732,6 +737,18 @@ export interface HeldReview {
|
|
|
732
737
|
/** Whether this report created it, rather than finding the review an earlier one created. */
|
|
733
738
|
readonly created: boolean;
|
|
734
739
|
}
|
|
740
|
+
/** A reply an agent session held for review, as the session learns its outcome. */
|
|
741
|
+
export interface SessionReview {
|
|
742
|
+
readonly id: string;
|
|
743
|
+
/** `pending`, `sent`, `uncertain`, `failed` or `rejected`, as the review holds it. */
|
|
744
|
+
readonly status: string;
|
|
745
|
+
/** The reply as the session wrote it. */
|
|
746
|
+
readonly draft: string;
|
|
747
|
+
/** Whether a member sent their edit of the draft instead of the draft. */
|
|
748
|
+
readonly edited: boolean;
|
|
749
|
+
readonly heldAt: string;
|
|
750
|
+
readonly decidedAt: string | null;
|
|
751
|
+
}
|
|
735
752
|
declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segmentstream/ontology/OntologyBackend", {
|
|
736
753
|
readonly workflowAdmissions?: {
|
|
737
754
|
readonly ensureRecovery: (commitBy: number) => Effect.Effect<number, WorkflowRecoveryUnavailable>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.130.0",
|
|
4
4
|
"description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "SegmentStream",
|