@segmentstream/ontology 0.130.0 → 0.131.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 +16 -0
- package/dist/agent-review.d.ts +32 -2
- package/dist/agent-review.js +78 -2
- package/dist/chat.d.ts +17 -1
- package/dist/chat.js +4 -1
- package/dist/index.d.ts +1 -1
- package/dist/runtime/agents.js +279 -125
- package/dist/service/agent/protocol.d.ts +9 -0
- package/dist/service/agent/protocol.js +15 -0
- package/dist/service/agent/server.js +49 -1
- package/dist/service/authentication.js +21 -4
- package/dist/service/caller-context.d.ts +2 -0
- package/dist/service/chat/delivery.js +7 -0
- package/dist/service/chat/review-delivery.js +16 -3
- package/dist/service/chat/review-revision.d.ts +24 -0
- package/dist/service/chat/review-revision.js +160 -0
- package/dist/service/runtime-contract.d.ts +37 -0
- package/dist/service/runtime-identity.d.ts +8 -0
- package/dist/service/runtime-identity.js +8 -0
- package/dist/service/toolsets.d.ts +4 -1
- package/dist/service/toolsets.js +5 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.131.0
|
|
4
|
+
|
|
5
|
+
Members can send a reply the agent held for review back with a note on what to change.
|
|
6
|
+
|
|
7
|
+
- **The action.** `agent_review.revise({ review, note })` sends a pending reply back. It needs the permission `agent_review:revise`.
|
|
8
|
+
- **The redraft.** The agent writes the reply again in a session of its own, never in the person's chat session. That session acts as the person, reads only and has none of the agent's own tools. It starts from the chat, what the turn that wrote the reply looked up, and the draft, ahead of the note.
|
|
9
|
+
- **The result.** The new draft becomes a pending review whose `revises` names the reply, which becomes `superseded`. A member approves, edits, rejects or sends it back again.
|
|
10
|
+
- **Learning from it.** The review keeps the member's `note` and `notedBy` for the workspace's own learning. Neither the person nor the agent's chat with them sees the note. Workflows can react with `after(...)` on `AgentReview.actions.revise`, and the hold triggers fire for the redraft.
|
|
11
|
+
|
|
12
|
+
The person's own session learns only that the reply was not sent, and that a rewritten one waits or was sent.
|
|
13
|
+
|
|
14
|
+
- **Agent.** The agent serves `POST /eve/segmentstream/v1/reviews/revise`, which only the deployment's own functions call. It narrows its ontology requests with `X-SegmentStream-Agent-Scope: ontology:read`, which the ontology now accepts from the agent as an OAuth grant of that scope.
|
|
15
|
+
- **App.** `useInboxChat` gains `revise(reply, note)`. Each held reply now carries `revision` (`redrafting` or `failed`) and `revises`.
|
|
16
|
+
|
|
17
|
+
Action required: give the roles that review replies `agent_review:revise` to let them send replies back; `*:*` does not grant it. Redrafting needs both this ontology and this agent release.
|
|
18
|
+
|
|
3
19
|
## 0.130.0
|
|
4
20
|
|
|
5
21
|
Reply review now gives the workspace what it needs to learn from staff decisions, and gives the agent what became of its replies.
|
package/dist/agent-review.d.ts
CHANGED
|
@@ -23,6 +23,16 @@ export declare const AGENT_REVIEW_STATUSES: readonly [{
|
|
|
23
23
|
}, {
|
|
24
24
|
readonly value: "rejected";
|
|
25
25
|
readonly description: "Rejected: the person never sees it.";
|
|
26
|
+
}, {
|
|
27
|
+
readonly value: "superseded";
|
|
28
|
+
readonly description: "Redrafted at a member's request: the review that revises it replaces it.";
|
|
29
|
+
}];
|
|
30
|
+
export declare const AGENT_REVIEW_REVISION_STATES: readonly [{
|
|
31
|
+
readonly value: "requested";
|
|
32
|
+
readonly description: "A member asked the agent to redraft it; it is redrafting.";
|
|
33
|
+
}, {
|
|
34
|
+
readonly value: "failed";
|
|
35
|
+
readonly description: "The agent could not redraft it; it still waits as it is.";
|
|
26
36
|
}];
|
|
27
37
|
export declare const AGENT_REVIEW_MODES: readonly [{
|
|
28
38
|
readonly value: "always";
|
|
@@ -35,6 +45,8 @@ export declare const AGENT_REVIEW_MODES: readonly [{
|
|
|
35
45
|
export declare const AGENT_REVIEW_TEXT_LIMIT = 20000;
|
|
36
46
|
/** The longest reason a member gives for rejecting a reply. */
|
|
37
47
|
export declare const AGENT_REVIEW_REASON_LIMIT = 2000;
|
|
48
|
+
/** The longest note a member gives the agent for redrafting a reply. */
|
|
49
|
+
export declare const AGENT_REVIEW_NOTE_LIMIT = 2000;
|
|
38
50
|
export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
39
51
|
readonly key: import("./property.js").Property<string, false, true>;
|
|
40
52
|
readonly provider: import("./property.js").Property<string, false, false>;
|
|
@@ -47,15 +59,20 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
|
47
59
|
readonly sessionId: import("./property.js").Property<string, false, false>;
|
|
48
60
|
readonly draft: import("./property.js").Property<string, false, false>;
|
|
49
61
|
readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
50
|
-
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected", false, false>;
|
|
62
|
+
readonly status: import("./property.js").Property<"pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded", false, false>;
|
|
51
63
|
readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
|
|
52
64
|
readonly confidence: Schema.optionalKey<import("./property.js").Property<number, false, false>>;
|
|
53
65
|
readonly messageId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
54
66
|
readonly decidedAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
55
67
|
readonly reason: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
68
|
+
readonly note: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
69
|
+
readonly revision: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
|
|
70
|
+
readonly revisionState: Schema.optionalKey<import("./property.js").Property<"failed" | "requested", false, false>>;
|
|
56
71
|
}, {
|
|
57
72
|
readonly person: import("./relationship.js").OneRelationship<false, false, "user">;
|
|
58
73
|
readonly decidedBy: import("./relationship.js").OneRelationship<true, false, "user">;
|
|
74
|
+
readonly notedBy: import("./relationship.js").OneRelationship<true, false, "user">;
|
|
75
|
+
readonly revises: import("./relationship.js").OneRelationship<true, false, "agent_review">;
|
|
59
76
|
readonly agentChat: import("./relationship.js").OneRelationship<true, false, "agent_chat">;
|
|
60
77
|
}, import("./entity.js").InvocableActions<{
|
|
61
78
|
readonly approve: import("./action.js").Action<Schema.Struct<{
|
|
@@ -74,6 +91,14 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
|
74
91
|
review: string;
|
|
75
92
|
status: "rejected";
|
|
76
93
|
}>;
|
|
94
|
+
readonly revise: import("./action.js").Action<Schema.Struct<{
|
|
95
|
+
readonly review: Schema.Codec<string, string, never, never>;
|
|
96
|
+
readonly note: import("./property.js").Property<string, false, false>;
|
|
97
|
+
}>, {
|
|
98
|
+
review: string;
|
|
99
|
+
revision: string;
|
|
100
|
+
status: "requested";
|
|
101
|
+
}>;
|
|
77
102
|
}, "agent_review", {
|
|
78
103
|
readonly id: string;
|
|
79
104
|
readonly createdAt: string;
|
|
@@ -91,14 +116,19 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
|
|
|
91
116
|
readonly sessionId: string;
|
|
92
117
|
readonly draft: string;
|
|
93
118
|
readonly text: string | null;
|
|
94
|
-
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected";
|
|
119
|
+
readonly status: "pending" | "sent" | "uncertain" | "failed" | "rejected" | "superseded";
|
|
95
120
|
readonly mode: "always" | "whenUnsure";
|
|
96
121
|
readonly confidence: number | null;
|
|
97
122
|
readonly messageId: string | null;
|
|
98
123
|
readonly decidedAt: string | null;
|
|
99
124
|
readonly reason: string | null;
|
|
125
|
+
readonly note: string | null;
|
|
126
|
+
readonly revision: string | null;
|
|
127
|
+
readonly revisionState: "failed" | "requested" | null;
|
|
100
128
|
readonly personId: string;
|
|
101
129
|
readonly decidedById: string | null;
|
|
130
|
+
readonly notedById: string | null;
|
|
131
|
+
readonly revisesId: string | null;
|
|
102
132
|
readonly agentChatId: string | null;
|
|
103
133
|
}>, Readonly<Record<never, never>>, "actions">;
|
|
104
134
|
export type AgentReview = typeof AgentReview.Type;
|
package/dist/agent-review.js
CHANGED
|
@@ -23,6 +23,14 @@ export const AGENT_REVIEW_STATUSES = [
|
|
|
23
23
|
},
|
|
24
24
|
{ value: "failed", description: "Approved; the provider refused it, and nothing was sent." },
|
|
25
25
|
{ value: "rejected", description: "Rejected: the person never sees it." },
|
|
26
|
+
{
|
|
27
|
+
value: "superseded",
|
|
28
|
+
description: "Redrafted at a member's request: the review that revises it replaces it.",
|
|
29
|
+
},
|
|
30
|
+
];
|
|
31
|
+
export const AGENT_REVIEW_REVISION_STATES = [
|
|
32
|
+
{ value: "requested", description: "A member asked the agent to redraft it; it is redrafting." },
|
|
33
|
+
{ value: "failed", description: "The agent could not redraft it; it still waits as it is." },
|
|
26
34
|
];
|
|
27
35
|
export const AGENT_REVIEW_MODES = [
|
|
28
36
|
{ value: "always", description: "Every reply in the chat waits for a member." },
|
|
@@ -35,6 +43,8 @@ export const AGENT_REVIEW_MODES = [
|
|
|
35
43
|
export const AGENT_REVIEW_TEXT_LIMIT = 20_000;
|
|
36
44
|
/** The longest reason a member gives for rejecting a reply. */
|
|
37
45
|
export const AGENT_REVIEW_REASON_LIMIT = 2_000;
|
|
46
|
+
/** The longest note a member gives the agent for redrafting a reply. */
|
|
47
|
+
export const AGENT_REVIEW_NOTE_LIMIT = 2_000;
|
|
38
48
|
export const AgentReview = entity("agent_review", {
|
|
39
49
|
id: "ent_agent_review",
|
|
40
50
|
label: "Agent reply review",
|
|
@@ -118,7 +128,7 @@ export const AgentReview = entity("agent_review", {
|
|
|
118
128
|
optional: true,
|
|
119
129
|
managed: true,
|
|
120
130
|
label: "Decided",
|
|
121
|
-
description: "When a member approved or
|
|
131
|
+
description: "When a member approved, rejected or had the reply redrafted.",
|
|
122
132
|
}),
|
|
123
133
|
reason: p.text({
|
|
124
134
|
optional: true,
|
|
@@ -128,6 +138,26 @@ export const AgentReview = entity("agent_review", {
|
|
|
128
138
|
description: "Why the member rejected the reply, when they said: for the workspace's own review of " +
|
|
129
139
|
"the agent's replies. The person and the agent's chat with them never see it.",
|
|
130
140
|
}),
|
|
141
|
+
note: p.text({
|
|
142
|
+
optional: true,
|
|
143
|
+
managed: true,
|
|
144
|
+
maxLength: AGENT_REVIEW_NOTE_LIMIT,
|
|
145
|
+
display: "multiline",
|
|
146
|
+
description: "What the member asked the agent to change when they asked it to redraft the reply. " +
|
|
147
|
+
"Only the redraft reads it; the person and the agent's chat with them never see it.",
|
|
148
|
+
}),
|
|
149
|
+
revision: p.text({
|
|
150
|
+
optional: true,
|
|
151
|
+
managed: true,
|
|
152
|
+
maxLength: 64,
|
|
153
|
+
description: "The redraft last asked for, by its id: only its result replaces the reply.",
|
|
154
|
+
}),
|
|
155
|
+
revisionState: p.select(AGENT_REVIEW_REVISION_STATES, {
|
|
156
|
+
optional: true,
|
|
157
|
+
managed: true,
|
|
158
|
+
label: "Revision",
|
|
159
|
+
description: "Whether the agent is redrafting the reply, or could not.",
|
|
160
|
+
}),
|
|
131
161
|
},
|
|
132
162
|
relationships: {
|
|
133
163
|
// By name, so that an ontology rebuilt with the deployed `user` still resolves it.
|
|
@@ -142,7 +172,21 @@ export const AgentReview = entity("agent_review", {
|
|
|
142
172
|
inverse: "decidedAgentReviews",
|
|
143
173
|
onDelete: "setNull",
|
|
144
174
|
phrase: ["was decided by", "decided"],
|
|
145
|
-
description: "The member who approved or
|
|
175
|
+
description: "The member who approved, rejected or had the reply redrafted.",
|
|
176
|
+
}),
|
|
177
|
+
notedBy: rel.one("user", {
|
|
178
|
+
optional: true,
|
|
179
|
+
inverse: "notedAgentReviews",
|
|
180
|
+
onDelete: "setNull",
|
|
181
|
+
phrase: ["was sent back by", "sent back"],
|
|
182
|
+
description: "The member who last asked the agent to redraft the reply.",
|
|
183
|
+
}),
|
|
184
|
+
revises: rel.one("agent_review", {
|
|
185
|
+
optional: true,
|
|
186
|
+
inverse: "revisions",
|
|
187
|
+
onDelete: "setNull",
|
|
188
|
+
phrase: ["revises", "is revised by"],
|
|
189
|
+
description: "The reply this one redrafts at a member's request.",
|
|
146
190
|
}),
|
|
147
191
|
agentChat: rel.one("agent_chat", {
|
|
148
192
|
optional: true,
|
|
@@ -234,4 +278,36 @@ export const AgentReview = entity("agent_review", {
|
|
|
234
278
|
return { review: review.id, status: "rejected" };
|
|
235
279
|
}),
|
|
236
280
|
}),
|
|
281
|
+
revise: action({
|
|
282
|
+
description: "Ask the agent to redraft a reply it held for review, with what to change in note, in the " +
|
|
283
|
+
"member's words. The agent writes it again in a session of its own, which reads the chat " +
|
|
284
|
+
"and what it looked up for the reply but changes nothing; the new draft replaces this one " +
|
|
285
|
+
"as a review that waits for a member. The person and the agent's chat with them never see " +
|
|
286
|
+
"the note. Only a reply that still waits can be redrafted.",
|
|
287
|
+
hints: { destructive: false, irreversible: false, idempotent: false },
|
|
288
|
+
input: Schema.Struct({
|
|
289
|
+
review: self.ref,
|
|
290
|
+
note: p.text({
|
|
291
|
+
maxLength: AGENT_REVIEW_NOTE_LIMIT,
|
|
292
|
+
description: "What the agent should change, in the member's words.",
|
|
293
|
+
}),
|
|
294
|
+
}),
|
|
295
|
+
connections: [],
|
|
296
|
+
prepare: ({ input }) => Effect.gen(function* () {
|
|
297
|
+
const delivery = yield* Effect.serviceOption(ChatDelivery);
|
|
298
|
+
const revise = Option.isSome(delivery) ? delivery.value.reviseReview : undefined;
|
|
299
|
+
if (revise === undefined) {
|
|
300
|
+
return yield* new ActionRejected({
|
|
301
|
+
message: "Redrafting a reply requires the authenticated ontology service.",
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
return yield* revise({ review: String(input.review), note: input.note.trim() });
|
|
305
|
+
}),
|
|
306
|
+
// The request is recorded before the agent is asked, so that its result always finds it.
|
|
307
|
+
handler: ({ input, prepared }) => Effect.succeed({
|
|
308
|
+
review: String(input.review),
|
|
309
|
+
revision: prepared.revision,
|
|
310
|
+
status: "requested",
|
|
311
|
+
}),
|
|
312
|
+
}),
|
|
237
313
|
}));
|
package/dist/chat.d.ts
CHANGED
|
@@ -62,16 +62,32 @@ export interface ReviewSendResult {
|
|
|
62
62
|
readonly messageId: string | null;
|
|
63
63
|
readonly duplicate: boolean;
|
|
64
64
|
}
|
|
65
|
+
/** A member's request that the agent redraft a reply it held for review. */
|
|
66
|
+
export interface ReviewReviseInput {
|
|
67
|
+
/** The `agent_review` record's id. */
|
|
68
|
+
readonly review: string;
|
|
69
|
+
/** What the agent should change, in the member's words. */
|
|
70
|
+
readonly note: string;
|
|
71
|
+
}
|
|
72
|
+
/** The redraft the agent started: its result replaces the review only while it is the last one. */
|
|
73
|
+
export interface ReviewReviseResult {
|
|
74
|
+
readonly revision: string;
|
|
75
|
+
}
|
|
65
76
|
declare const ChatDelivery_base: Context.ServiceClass<ChatDelivery, "@segmentstream/ontology/ChatDelivery", {
|
|
66
77
|
readonly preview: (input: ChatPostInput) => Effect.Effect<ChatPreview, ActionError>;
|
|
67
78
|
readonly validate: (input: ChatPostInput) => Effect.Effect<void, ActionError>;
|
|
68
79
|
readonly post: (input: ChatPostInput) => Effect.Effect<ChatPostResult, ActionError>;
|
|
69
80
|
/** Sends a reply a member approved, as the agent and without attribution, at most once. */
|
|
70
81
|
readonly sendReview?: (input: ReviewSendInput) => Effect.Effect<ReviewSendResult, ActionError>;
|
|
82
|
+
/** Asks the agent to redraft a reply it held for review, in a session of its own. */
|
|
83
|
+
readonly reviseReview?: (input: ReviewReviseInput) => Effect.Effect<ReviewReviseResult, ActionError>;
|
|
71
84
|
/** The channels whose private chats staff may take over, as the ontology's inbox lists them. */
|
|
72
85
|
readonly takeoverChannels?: ReadonlySet<string>;
|
|
73
86
|
}>;
|
|
74
|
-
/**
|
|
87
|
+
/**
|
|
88
|
+
* Deliver the exact Markdown source through the channel renderer, without invoking an agent; and
|
|
89
|
+
* hand a reply the agent held for review back to the agent to redraft.
|
|
90
|
+
*/
|
|
75
91
|
export declare class ChatDelivery extends ChatDelivery_base {
|
|
76
92
|
}
|
|
77
93
|
export {};
|
package/dist/chat.js
CHANGED
|
@@ -29,6 +29,9 @@ export const chatPreviewDigest = (preview) => chatProtocolDigest([
|
|
|
29
29
|
preview.finalText,
|
|
30
30
|
preview.replyTo,
|
|
31
31
|
]);
|
|
32
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* Deliver the exact Markdown source through the channel renderer, without invoking an agent; and
|
|
34
|
+
* hand a reply the agent held for review back to the agent to redraft.
|
|
35
|
+
*/
|
|
33
36
|
export class ChatDelivery extends Context.Service()("@segmentstream/ontology/ChatDelivery") {
|
|
34
37
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -66,7 +66,7 @@ export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_
|
|
|
66
66
|
export { ChatDelivery, ChatPostInput, ChatPostResult } from "./chat.js";
|
|
67
67
|
export { CHAT_CHANNEL_KINDS, CHAT_CHANNEL_NAME, CHAT_KINDS, WORKSPACE_CHANNEL_KIND, channelIdentityProvider, } from "./chat-channel.js";
|
|
68
68
|
export type { ChatChannelKind, ChatKind } from "./chat-channel.js";
|
|
69
|
-
export type { InboxOptions, ReviewSendInput, ReviewSendResult } from "./chat.js";
|
|
69
|
+
export type { InboxOptions, ReviewReviseInput, ReviewReviseResult, ReviewSendInput, ReviewSendResult, } from "./chat.js";
|
|
70
70
|
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";
|
|
71
71
|
export type { EntityQuerySchemas, FieldFilter, FilterOperator, JsonRecord, ListFilterOperator, ManyFilter, QueryField, QueryLink, StorageType, Where, } from "./query.js";
|
|
72
72
|
export { InvalidQuery, InvalidValues, MemberNotFound, PrincipalRejected, StoredRecordMismatch, UnknownAction, UnknownRole, ValidationIssue, UndeclaredWrite, WriteOutsideAction, } from "./runtime/errors.js";
|
package/dist/runtime/agents.js
CHANGED
|
@@ -127,6 +127,167 @@ const HOLD_DEFINITION = action({
|
|
|
127
127
|
export function sqlAgentStore(ontology, sql) {
|
|
128
128
|
const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
|
|
129
129
|
const memberPrincipal = (userId) => resolveMemberById(ontology, userId).pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
130
|
+
/**
|
|
131
|
+
* Holds a reply for review once per key, in a transaction bounded and admitted as an action's,
|
|
132
|
+
* and starts the workflows whose triggers on `agent_review` fire for it. `resolve` runs in the
|
|
133
|
+
* transaction, after the key is locked and found unused: it names the reply, or the reply a redraft
|
|
134
|
+
* replaces, which it marks superseded, or `discarded` when there is nothing to replace.
|
|
135
|
+
*/
|
|
136
|
+
const hold = (key, memberId, resolve) => Effect.gen(function* () {
|
|
137
|
+
// The triggers on `agent_review` itself, which fire for any of its actions: holding is one.
|
|
138
|
+
const triggers = actionTriggers(ontology).filter((trigger) => trigger.entity === AgentReview.name &&
|
|
139
|
+
(trigger.action === undefined || trigger.action === HOLD_ACTION));
|
|
140
|
+
const starter = triggers.length > 0
|
|
141
|
+
? Option.getOrUndefined(yield* Effect.serviceOption(WorkflowStarter))
|
|
142
|
+
: undefined;
|
|
143
|
+
// Admitted and bounded as an action's transaction is, by the same gate and limits.
|
|
144
|
+
const admission = Option.getOrUndefined(yield* Effect.serviceOption(ActionTransactions));
|
|
145
|
+
const limits = admission?.limits ?? ACTION_TRANSACTION_LIMITS;
|
|
146
|
+
const qualified = `${AgentReview.name}.${HOLD_ACTION}`;
|
|
147
|
+
const actionId = randomUUID();
|
|
148
|
+
if (memberId !== undefined && !isRecordId(memberId)) {
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
// Before the transaction: whatever it commits must be swept if this request does not start
|
|
152
|
+
// it. The transaction rolls back rather than commit after the deadline the sweep covers.
|
|
153
|
+
if (starter !== undefined) {
|
|
154
|
+
yield* starter.ensureRecovery({ commitBy: Date.now() + limits.handlerTimeoutMs });
|
|
155
|
+
}
|
|
156
|
+
const transaction = actionTransaction(sql, () => Effect.gen(function* () {
|
|
157
|
+
yield* sql.unsafe(`SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true)`, [`${limits.statementTimeoutMs}ms`, `${limits.lockTimeoutMs}ms`]);
|
|
158
|
+
yield* beginReplicationWrite(sql);
|
|
159
|
+
// Reports of one reply run one after the other: the first creates it, the rest find it.
|
|
160
|
+
yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${key}`]);
|
|
161
|
+
const edits = [];
|
|
162
|
+
const snapshots = new Map();
|
|
163
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
164
|
+
action: qualified,
|
|
165
|
+
actionId,
|
|
166
|
+
principalId: null,
|
|
167
|
+
...(triggers.length > 0
|
|
168
|
+
? {
|
|
169
|
+
onEdit: (edit) => edits.push(edit),
|
|
170
|
+
onSnapshot: (snapshot) => {
|
|
171
|
+
if (snapshot.entity === AgentReview.name) {
|
|
172
|
+
snapshots.set(snapshot.id, {
|
|
173
|
+
before: snapshots.get(snapshot.id)?.before ?? snapshot.before,
|
|
174
|
+
after: snapshot.after,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
: {}),
|
|
180
|
+
});
|
|
181
|
+
const [found] = yield* runtime.find({
|
|
182
|
+
entity: AgentReview.name,
|
|
183
|
+
options: { where: { key }, limit: 1 },
|
|
184
|
+
});
|
|
185
|
+
if (found !== undefined) {
|
|
186
|
+
return {
|
|
187
|
+
review: { id: String(found.id), status: String(found.status), created: false },
|
|
188
|
+
starts: [],
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
// The reply a redraft replaces changes outside the triggers' view: holding fires for the
|
|
192
|
+
// new review alone.
|
|
193
|
+
const plain = makeOntologyRuntime(ontology, sql, {
|
|
194
|
+
action: qualified,
|
|
195
|
+
actionId,
|
|
196
|
+
principalId: null,
|
|
197
|
+
});
|
|
198
|
+
const resolved = yield* resolve(plain).pipe(Effect.orDie);
|
|
199
|
+
if (resolved.kind === "discarded") {
|
|
200
|
+
return "discarded";
|
|
201
|
+
}
|
|
202
|
+
const input = resolved.reply;
|
|
203
|
+
const [member] = yield* rows(`SELECT 1 FROM ${USERS} WHERE "id" = $1::uuid AND "kind"::text = 'member' AND "active"`, [input.memberId]);
|
|
204
|
+
if (member === undefined) {
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
// The registry keys a chat by its channel's name and its id, as the archive does.
|
|
208
|
+
const [chat] = yield* runtime.find({
|
|
209
|
+
entity: AgentChat.name,
|
|
210
|
+
options: {
|
|
211
|
+
where: { provider: input.channel, external_id: input.chatId },
|
|
212
|
+
limit: 1,
|
|
213
|
+
},
|
|
214
|
+
});
|
|
215
|
+
const review = yield* runtime.create({
|
|
216
|
+
entity: AgentReview.name,
|
|
217
|
+
values: {
|
|
218
|
+
key: input.key,
|
|
219
|
+
provider: input.provider,
|
|
220
|
+
channel: input.channel,
|
|
221
|
+
chat_id: input.chatId,
|
|
222
|
+
recipient: input.recipient,
|
|
223
|
+
chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
|
|
224
|
+
thread_id: input.threadId === "" ? null : input.threadId,
|
|
225
|
+
reply_to: input.replyTo,
|
|
226
|
+
session_id: input.sessionId,
|
|
227
|
+
draft: input.text,
|
|
228
|
+
text: null,
|
|
229
|
+
status: "pending",
|
|
230
|
+
// Select values are stored by their wire names.
|
|
231
|
+
mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
|
|
232
|
+
confidence: input.confidence,
|
|
233
|
+
message_id: null,
|
|
234
|
+
decided_at: null,
|
|
235
|
+
person: input.memberId,
|
|
236
|
+
agent_chat: chat === undefined ? null : String(chat.id),
|
|
237
|
+
...(resolved.kind === "revision" ? { revises: String(resolved.previous.id) } : {}),
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
if (resolved.kind === "revision") {
|
|
241
|
+
yield* plain.update({
|
|
242
|
+
entity: AgentReview.name,
|
|
243
|
+
id: String(resolved.previous.id),
|
|
244
|
+
values: {
|
|
245
|
+
status: "superseded",
|
|
246
|
+
revision_state: null,
|
|
247
|
+
decided_at: new Date().toISOString(),
|
|
248
|
+
decided_by: nullableText(resolved.previous.noted_by_id),
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
const result = { review: String(review.id), status: "pending" };
|
|
253
|
+
let starts = [];
|
|
254
|
+
if (triggers.length > 0) {
|
|
255
|
+
const principal = yield* memberPrincipal(input.memberId);
|
|
256
|
+
const [now] = yield* rows(`SELECT to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "at"`);
|
|
257
|
+
if (principal !== undefined) {
|
|
258
|
+
starts = yield* evaluateTriggers(triggers, {
|
|
259
|
+
ontology,
|
|
260
|
+
entity: AgentReview.name,
|
|
261
|
+
action: HOLD_ACTION,
|
|
262
|
+
definition: HOLD_DEFINITION,
|
|
263
|
+
generated: false,
|
|
264
|
+
actionId,
|
|
265
|
+
at: canonicalInstant(String(now.at)),
|
|
266
|
+
principal,
|
|
267
|
+
input,
|
|
268
|
+
result,
|
|
269
|
+
edits,
|
|
270
|
+
held: snapshots,
|
|
271
|
+
load: (id) => runtime.get({ entity: AgentReview.name, id }).pipe(Effect.map((record) => record), Effect.catchTag("NotFound", () => Effect.succeed(undefined))),
|
|
272
|
+
});
|
|
273
|
+
yield* insertStarts(sql, starts);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return { review: { id: result.review, status: "pending", created: true }, starts };
|
|
277
|
+
}), {
|
|
278
|
+
qualified,
|
|
279
|
+
actionId,
|
|
280
|
+
retryOnDeadlock: false,
|
|
281
|
+
handlerTimeoutMs: limits.handlerTimeoutMs,
|
|
282
|
+
});
|
|
283
|
+
const held = yield* admission === undefined ? transaction : admission.admit(transaction);
|
|
284
|
+
if (held === undefined || held === "discarded") {
|
|
285
|
+
return held;
|
|
286
|
+
}
|
|
287
|
+
// The decided runs start once the review committed; a failure leaves them to the sweep.
|
|
288
|
+
yield* startCommitted(sql, starter, held.starts, actionId);
|
|
289
|
+
return held.review;
|
|
290
|
+
}).pipe(Effect.orDie);
|
|
130
291
|
const store = {
|
|
131
292
|
confirmations: sqlConfirmationStore(sql),
|
|
132
293
|
savePairing: (pairing) => sql
|
|
@@ -687,136 +848,127 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
687
848
|
};
|
|
688
849
|
}));
|
|
689
850
|
}).pipe(Effect.orDie),
|
|
690
|
-
holdReply: (input) => Effect.
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
const
|
|
695
|
-
|
|
696
|
-
:
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
return undefined;
|
|
851
|
+
holdReply: (input) => hold(input.key, input.memberId, () => Effect.succeed({ kind: "reply", reply: input })).pipe(Effect.map((held) => (held === "discarded" ? undefined : held))),
|
|
852
|
+
holdRevision: (input) => hold(`revision:${input.revision}`, undefined, (runtime) => Effect.gen(function* () {
|
|
853
|
+
// The reply the redraft replaces, while it still waits for this redraft: a member who
|
|
854
|
+
// decided it, or asked for another redraft since, leaves this one nothing to replace.
|
|
855
|
+
const [previous] = yield* runtime.find({
|
|
856
|
+
entity: AgentReview.name,
|
|
857
|
+
options: { where: { id: input.review }, limit: 1, forUpdate: true },
|
|
858
|
+
});
|
|
859
|
+
if (previous === undefined ||
|
|
860
|
+
previous.status !== "pending" ||
|
|
861
|
+
previous.revision !== input.revision ||
|
|
862
|
+
previous.revision_state !== "requested") {
|
|
863
|
+
return { kind: "discarded" };
|
|
704
864
|
}
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
865
|
+
return {
|
|
866
|
+
kind: "revision",
|
|
867
|
+
previous,
|
|
868
|
+
reply: {
|
|
869
|
+
key: `revision:${input.revision}`,
|
|
870
|
+
provider: String(previous.provider),
|
|
871
|
+
channel: nullableText(previous.channel) ?? String(previous.provider),
|
|
872
|
+
chatId: String(previous.chat_id),
|
|
873
|
+
recipient: String(previous.recipient),
|
|
874
|
+
threadId: nullableText(previous.thread_id) ?? "",
|
|
875
|
+
replyTo: nullableText(previous.reply_to),
|
|
876
|
+
memberId: String(previous.person_id),
|
|
877
|
+
sessionId: String(previous.session_id),
|
|
878
|
+
text: input.text,
|
|
879
|
+
mode: "always",
|
|
880
|
+
confidence: null,
|
|
881
|
+
},
|
|
882
|
+
};
|
|
883
|
+
})),
|
|
884
|
+
requestRevision: (input) => sql
|
|
885
|
+
.withTransaction(Effect.gen(function* () {
|
|
886
|
+
if (!isRecordId(input.review) || !isRecordId(input.notedBy)) {
|
|
887
|
+
return false;
|
|
709
888
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
});
|
|
757
|
-
const review = yield* runtime.create({
|
|
889
|
+
yield* beginReplicationWrite(sql);
|
|
890
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
891
|
+
action: `${AgentReview.name}.revise`,
|
|
892
|
+
actionId: randomUUID(),
|
|
893
|
+
principalId: input.notedBy,
|
|
894
|
+
});
|
|
895
|
+
const [review] = yield* runtime.find({
|
|
896
|
+
entity: AgentReview.name,
|
|
897
|
+
options: { where: { id: input.review }, limit: 1, forUpdate: true },
|
|
898
|
+
});
|
|
899
|
+
if (review === undefined || review.status !== "pending") {
|
|
900
|
+
return false;
|
|
901
|
+
}
|
|
902
|
+
yield* runtime.update({
|
|
903
|
+
entity: AgentReview.name,
|
|
904
|
+
id: String(review.id),
|
|
905
|
+
values: {
|
|
906
|
+
note: input.note,
|
|
907
|
+
noted_by: input.notedBy,
|
|
908
|
+
revision: input.revision,
|
|
909
|
+
revision_state: "requested",
|
|
910
|
+
},
|
|
911
|
+
});
|
|
912
|
+
return true;
|
|
913
|
+
}))
|
|
914
|
+
.pipe(Effect.orDie),
|
|
915
|
+
cancelRevision: (input) => sql
|
|
916
|
+
.withTransaction(Effect.gen(function* () {
|
|
917
|
+
if (!isRecordId(input.review)) {
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
yield* beginReplicationWrite(sql);
|
|
921
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
922
|
+
action: `${AgentReview.name}.approve`,
|
|
923
|
+
actionId: randomUUID(),
|
|
924
|
+
principalId: null,
|
|
925
|
+
});
|
|
926
|
+
const [review] = yield* runtime.find({
|
|
927
|
+
entity: AgentReview.name,
|
|
928
|
+
options: { where: { id: input.review }, limit: 1, forUpdate: true },
|
|
929
|
+
});
|
|
930
|
+
if (review === undefined || review.status !== "pending") {
|
|
931
|
+
return false;
|
|
932
|
+
}
|
|
933
|
+
if (review.revision !== null && review.revision !== undefined) {
|
|
934
|
+
yield* runtime.update({
|
|
758
935
|
entity: AgentReview.name,
|
|
759
|
-
|
|
760
|
-
|
|
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
|
-
},
|
|
936
|
+
id: String(review.id),
|
|
937
|
+
values: { revision: null, revision_state: null },
|
|
780
938
|
});
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
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,
|
|
939
|
+
}
|
|
940
|
+
return true;
|
|
941
|
+
}))
|
|
942
|
+
.pipe(Effect.orDie),
|
|
943
|
+
failRevision: (input) => sql
|
|
944
|
+
.withTransaction(Effect.gen(function* () {
|
|
945
|
+
if (!isRecordId(input.review)) {
|
|
946
|
+
return false;
|
|
947
|
+
}
|
|
948
|
+
yield* beginReplicationWrite(sql);
|
|
949
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
950
|
+
action: `${AgentReview.name}.${HOLD_ACTION}`,
|
|
951
|
+
actionId: randomUUID(),
|
|
952
|
+
principalId: null,
|
|
811
953
|
});
|
|
812
|
-
const
|
|
813
|
-
|
|
814
|
-
|
|
954
|
+
const [previous] = yield* runtime.find({
|
|
955
|
+
entity: AgentReview.name,
|
|
956
|
+
options: { where: { id: input.review }, limit: 1, forUpdate: true },
|
|
957
|
+
});
|
|
958
|
+
if (previous === undefined ||
|
|
959
|
+
previous.status !== "pending" ||
|
|
960
|
+
previous.revision !== input.revision ||
|
|
961
|
+
previous.revision_state !== "requested") {
|
|
962
|
+
return false;
|
|
815
963
|
}
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
964
|
+
yield* runtime.update({
|
|
965
|
+
entity: AgentReview.name,
|
|
966
|
+
id: String(previous.id),
|
|
967
|
+
values: { revision_state: "failed" },
|
|
968
|
+
});
|
|
969
|
+
return true;
|
|
970
|
+
}))
|
|
971
|
+
.pipe(Effect.orDie),
|
|
820
972
|
sessionReviews: (sessionId) => Effect.gen(function* () {
|
|
821
973
|
const runtime = makeOntologyRuntime(ontology, sql);
|
|
822
974
|
// Every reply still waiting, however old, and the latest decisions: a decision on an old
|
|
@@ -844,7 +996,9 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
844
996
|
id: String(record.id),
|
|
845
997
|
status: String(record.status),
|
|
846
998
|
draft: String(record.draft),
|
|
847
|
-
|
|
999
|
+
// A redraft is a text the session did not write, as a member's edit is.
|
|
1000
|
+
edited: (record.revises_id !== null && record.revises_id !== undefined) ||
|
|
1001
|
+
(record.text !== null && record.text !== undefined && record.text !== record.draft),
|
|
848
1002
|
heldAt: timestampText(record.created_at),
|
|
849
1003
|
decidedAt: record.decided_at === null || record.decided_at === undefined
|
|
850
1004
|
? null
|
|
@@ -156,6 +156,15 @@ 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/revision`: what became of a redraft a member asked for: the new
|
|
161
|
+
* draft, or, without `text`, that the agent could not write one.
|
|
162
|
+
*/
|
|
163
|
+
export declare const RevisionRequest: Schema.Struct<{
|
|
164
|
+
readonly review_id: Schema.String;
|
|
165
|
+
readonly revision: Schema.String;
|
|
166
|
+
readonly text: Schema.optionalKey<Schema.String>;
|
|
167
|
+
}>;
|
|
159
168
|
/**
|
|
160
169
|
* `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
|
|
161
170
|
* next turn learns which the person saw.
|
|
@@ -209,6 +209,21 @@ 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/revision`: what became of a redraft a member asked for: the new
|
|
214
|
+
* draft, or, without `text`, that the agent could not write one.
|
|
215
|
+
*/
|
|
216
|
+
export const RevisionRequest = Schema.Struct({
|
|
217
|
+
review_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64)).annotate({
|
|
218
|
+
description: "The review the redraft replaces.",
|
|
219
|
+
}),
|
|
220
|
+
revision: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64)).annotate({
|
|
221
|
+
description: "The redraft, as the member's request named it.",
|
|
222
|
+
}),
|
|
223
|
+
text: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(20_000))).annotate({
|
|
224
|
+
description: "The new draft, in Markdown; absent when the agent could not write one.",
|
|
225
|
+
}),
|
|
226
|
+
});
|
|
212
227
|
/**
|
|
213
228
|
* `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
|
|
214
229
|
* next turn learns which the person saw.
|
|
@@ -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, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
16
|
+
import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, RevisionRequest, 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,53 @@ 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/revision` (runtime): the agent redrafted a reply a member sent
|
|
408
|
+
* back, or could not. The new draft becomes a pending review for the same person and chat that
|
|
409
|
+
* replaces the earlier one, which becomes `superseded`, once per redraft; a redraft the member no
|
|
410
|
+
* longer waits for, because the reply was decided or redrafted again since, replaces nothing.
|
|
411
|
+
*/
|
|
412
|
+
function revision(store) {
|
|
413
|
+
return (request) => Effect.gen(function* () {
|
|
414
|
+
const requestId = yield* RequestId;
|
|
415
|
+
const decoded = Schema.decodeUnknownResult(RevisionRequest)(yield* jsonBody(request), {
|
|
416
|
+
errors: "all",
|
|
417
|
+
onExcessProperty: "error",
|
|
418
|
+
});
|
|
419
|
+
if (Result.isFailure(decoded)) {
|
|
420
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
421
|
+
}
|
|
422
|
+
if (store.holdRevision === undefined || store.failRevision === undefined) {
|
|
423
|
+
return toServerResponse(notFound(requestId, "This ontology service redrafts no replies."));
|
|
424
|
+
}
|
|
425
|
+
const body = decoded.success;
|
|
426
|
+
if (body.text === undefined) {
|
|
427
|
+
const failed = yield* store.failRevision({
|
|
428
|
+
review: body.review_id,
|
|
429
|
+
revision: body.revision,
|
|
430
|
+
});
|
|
431
|
+
yield* Effect.logInfo("ontology.agent.revision_failed").pipe(Effect.annotateLogs({ requestId, reviewId: body.review_id, recorded: failed }));
|
|
432
|
+
return json({ status: failed ? "failed" : "discarded" });
|
|
433
|
+
}
|
|
434
|
+
const review = yield* store.holdRevision({
|
|
435
|
+
review: body.review_id,
|
|
436
|
+
revision: body.revision,
|
|
437
|
+
text: body.text,
|
|
438
|
+
});
|
|
439
|
+
if (review === undefined) {
|
|
440
|
+
return toServerResponse(notFound(requestId, "The reply is for no active member."));
|
|
441
|
+
}
|
|
442
|
+
yield* Effect.logInfo("ontology.agent.revision_held").pipe(Effect.annotateLogs({
|
|
443
|
+
requestId,
|
|
444
|
+
revises: body.review_id,
|
|
445
|
+
...(review === "discarded" ? {} : { reviewId: review.id, created: review.created }),
|
|
446
|
+
discarded: review === "discarded",
|
|
447
|
+
}));
|
|
448
|
+
return review === "discarded"
|
|
449
|
+
? json({ status: "discarded" })
|
|
450
|
+
: json({ id: review.id, status: review.status, created: review.created });
|
|
451
|
+
});
|
|
452
|
+
}
|
|
406
453
|
/**
|
|
407
454
|
* `POST /api/ontology/agent/reviews/session` (runtime): the replies the session held for review,
|
|
408
455
|
* newest first, with what became of each. Nothing a member wrote about them is in it.
|
|
@@ -546,6 +593,7 @@ export function agentLayer(options) {
|
|
|
546
593
|
yield* router.add("POST", CHATS_HANDOFF_PATH, asRuntime(handOffChat(store)));
|
|
547
594
|
yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
|
|
548
595
|
yield* router.add("POST", `${REVIEWS_PATH}/session`, asRuntime(sessionReviews(store)));
|
|
596
|
+
yield* router.add("POST", `${REVIEWS_PATH}/revision`, asRuntime(revision(store)));
|
|
549
597
|
yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
|
|
550
598
|
if (store.web !== undefined && backend.oauth !== undefined) {
|
|
551
599
|
yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
|
|
@@ -9,10 +9,10 @@ import { API_KEY_PREFIX } from "../runtime/principals.js";
|
|
|
9
9
|
import { FEDERATION_TOKEN_PREFIX, federationDigest } from "../runtime/federation.js";
|
|
10
10
|
import { browserRevisionAdmitted, browserRevisionObservation, browserSessionAdmission, federationStatus, } from "./federation-status.js";
|
|
11
11
|
import { RequestId, crossOriginSession, forbidden, internalError, notInvited, toServerResponse, unauthorized, unavailable, } from "./errors.js";
|
|
12
|
-
import { ACCESS_TOKEN_PREFIX, appSessionResource, publicOrigin, callerOfAccessToken, rejectedAccessToken, } from "./oauth/protocol.js";
|
|
12
|
+
import { ACCESS_TOKEN_PREFIX, appSessionResource, publicOrigin, callerOfAccessToken, READ_SCOPE, rejectedAccessToken, scopedPrincipal, } from "./oauth/protocol.js";
|
|
13
13
|
import { CurrentCaller } from "./caller-context.js";
|
|
14
14
|
import { OntologyBackend } from "./runtime-contract.js";
|
|
15
|
-
import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, logRuntimeRejection, runtimeCredential, } from "./runtime-identity.js";
|
|
15
|
+
import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_SCOPE_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, logRuntimeRejection, runtimeCredential, } from "./runtime-identity.js";
|
|
16
16
|
import { delegatedAccount, webMember } from "./agent/authentication.js";
|
|
17
17
|
import { agentTaskCaller } from "./agent/task-caller.js";
|
|
18
18
|
import { ErrorSchemas } from "./schemas.js";
|
|
@@ -696,10 +696,27 @@ export function authenticate(credential, verifyToken, options = {}) {
|
|
|
696
696
|
const { verify, actAs, provider, agentTask } = options.runtime;
|
|
697
697
|
const runtime = yield* Effect.promise(() => verify(token));
|
|
698
698
|
switch (runtime.status) {
|
|
699
|
-
case "valid":
|
|
700
|
-
|
|
699
|
+
case "valid": {
|
|
700
|
+
const scope = options.runtime.scope;
|
|
701
|
+
if (scope !== undefined && scope !== READ_SCOPE) {
|
|
702
|
+
return {
|
|
703
|
+
status: "forbidden",
|
|
704
|
+
detail: `${AGENT_SCOPE_HEADER} narrows a request to ${READ_SCOPE} only.`,
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
const resolved = agentTask === undefined
|
|
701
708
|
? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true, options.runtime.chat)
|
|
702
709
|
: yield* agentTaskPrincipal(agentTask, actAs, options.agentTasks);
|
|
710
|
+
// Narrowed, the request keeps only the reads of whom it acts for, as an OAuth grant of
|
|
711
|
+
// that scope does.
|
|
712
|
+
return scope === undefined || resolved.status !== "authenticated"
|
|
713
|
+
? resolved
|
|
714
|
+
: {
|
|
715
|
+
...resolved,
|
|
716
|
+
principal: scopedPrincipal(resolved.principal, READ_SCOPE),
|
|
717
|
+
caller: { ...resolved.caller, scope: READ_SCOPE },
|
|
718
|
+
};
|
|
719
|
+
}
|
|
703
720
|
case "invalid":
|
|
704
721
|
yield* logRuntimeRejection(runtime.reason);
|
|
705
722
|
return { status: "rejected" };
|
|
@@ -11,6 +11,8 @@ export type VerifiedCaller = {
|
|
|
11
11
|
} | {
|
|
12
12
|
readonly kind: "runtime" | "service" | "member" | "workload";
|
|
13
13
|
readonly subjectId: string;
|
|
14
|
+
/** Set only for a runtime caller the app's agent narrowed to `ontology:read`. */
|
|
15
|
+
readonly scope?: string;
|
|
14
16
|
/**
|
|
15
17
|
* Set only for a runtime caller that authenticated with an API key with delegation: the
|
|
16
18
|
* key's user, and the member's account the request acts through. Its runtime metadata must
|
|
@@ -11,6 +11,7 @@ import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./i
|
|
|
11
11
|
import { channelProvider, chatConnection, chatKind, listedChatProviders, } from "./providers/index.js";
|
|
12
12
|
import { chatResolver } from "./resolve.js";
|
|
13
13
|
import { reviewSender } from "./review-delivery.js";
|
|
14
|
+
import { reviewReviser } from "./review-revision.js";
|
|
14
15
|
import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
|
|
15
16
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
17
|
/** The channels a runtime source can name, which a verified pairing's provider is one of. */
|
|
@@ -231,6 +232,12 @@ agent = {}) {
|
|
|
231
232
|
};
|
|
232
233
|
return {
|
|
233
234
|
takeoverChannels,
|
|
235
|
+
reviseReview: reviewReviser({
|
|
236
|
+
agent: agentTransport,
|
|
237
|
+
backend: context.backend,
|
|
238
|
+
principal: context.principal,
|
|
239
|
+
requestId: context.requestId,
|
|
240
|
+
}),
|
|
234
241
|
sendReview: reviewSender({
|
|
235
242
|
ontology,
|
|
236
243
|
connections,
|
|
@@ -171,9 +171,13 @@ export function reviewSender(input) {
|
|
|
171
171
|
kind: "outbound",
|
|
172
172
|
messageId: null,
|
|
173
173
|
replyToMessageId: replyTo,
|
|
174
|
-
// The agent's session holds its draft: the session sees an edit
|
|
175
|
-
// write, and
|
|
176
|
-
sessionId: text === draft &&
|
|
174
|
+
// The agent's session holds its draft: the session sees an edit, and a redraft it never
|
|
175
|
+
// wrote, as a message it did not write, and its own draft sent as written as its own.
|
|
176
|
+
sessionId: text === draft &&
|
|
177
|
+
(review.revises_id === null || review.revises_id === undefined) &&
|
|
178
|
+
typeof review.session_id === "string"
|
|
179
|
+
? review.session_id
|
|
180
|
+
: null,
|
|
177
181
|
turnId: null,
|
|
178
182
|
text,
|
|
179
183
|
decision: null,
|
|
@@ -187,6 +191,15 @@ export function reviewSender(input) {
|
|
|
187
191
|
url: null,
|
|
188
192
|
at: new Date().toISOString(),
|
|
189
193
|
};
|
|
194
|
+
// A redraft asked for is dropped before anything is sent, under the review's lock: one that
|
|
195
|
+
// already replaced the reply leaves nothing to approve, and none arriving later replaces it.
|
|
196
|
+
const keeps = yield* backend.agents?.cancelRevision?.({ review: send.review }) ??
|
|
197
|
+
Effect.succeed(true);
|
|
198
|
+
if (!keeps) {
|
|
199
|
+
return yield* new ActionRejected({
|
|
200
|
+
message: "The reply was redrafted meanwhile; approve the redraft instead.",
|
|
201
|
+
});
|
|
202
|
+
}
|
|
190
203
|
const reserve = yield* input
|
|
191
204
|
.archive({
|
|
192
205
|
event,
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { ReviewReviseInput } from "../../chat.js";
|
|
3
|
+
import { ActionRejected, PermissionDenied } from "../../errors.js";
|
|
4
|
+
import type { Principal } from "../../runtime.js";
|
|
5
|
+
import type { OntologyBackend } from "../runtime-contract.js";
|
|
6
|
+
import type { AgentChannelTransport } from "./providers/provider.js";
|
|
7
|
+
/** Where the agent redrafts a reply held for review, on the deployment's production origin. */
|
|
8
|
+
export declare const AGENT_REVISION_ROUTE = "/eve/segmentstream/v1/reviews/revise";
|
|
9
|
+
/**
|
|
10
|
+
* Hands a reply the agent held for review back to it with a member's note: the agent redrafts it in
|
|
11
|
+
* a session of its own, acting as the person the reply is for and reading only, and reports the new
|
|
12
|
+
* draft to `POST /api/ontology/agent/reviews/revision`, where it replaces the review while the review
|
|
13
|
+
* still waits and this is the last redraft asked for. The request is recorded before the agent is
|
|
14
|
+
* called, so however soon the agent reports, its report finds it, and it names everything the agent
|
|
15
|
+
* needs: the agent never looks the review up.
|
|
16
|
+
*/
|
|
17
|
+
export declare function reviewReviser(input: {
|
|
18
|
+
readonly agent: AgentChannelTransport;
|
|
19
|
+
readonly backend: OntologyBackend["Service"];
|
|
20
|
+
readonly principal: Principal;
|
|
21
|
+
readonly requestId: string;
|
|
22
|
+
}): (revise: ReviewReviseInput) => Effect.Effect<{
|
|
23
|
+
revision: `${string}-${string}-${string}-${string}-${string}`;
|
|
24
|
+
}, ActionRejected | PermissionDenied, never>;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Effect, Option } from "effect";
|
|
3
|
+
import { ActionRejected, PermissionDenied } from "../../errors.js";
|
|
4
|
+
import { effectiveScope } from "../../permissions.js";
|
|
5
|
+
import { describeChatError } from "./diagnostics.js";
|
|
6
|
+
/** Where the agent redrafts a reply held for review, on the deployment's production origin. */
|
|
7
|
+
export const AGENT_REVISION_ROUTE = "/eve/segmentstream/v1/reviews/revise";
|
|
8
|
+
/** How long the agent may take to accept a redraft; it writes it afterwards, on its own. */
|
|
9
|
+
const AGENT_REVISION_TIMEOUT_MS = 15_000;
|
|
10
|
+
/** The most redrafts back a request follows to the reply the agent first wrote. */
|
|
11
|
+
const REVISION_DEPTH = 20;
|
|
12
|
+
const text = (value) => typeof value === "string" && value !== "" ? value : null;
|
|
13
|
+
/**
|
|
14
|
+
* Hands a reply the agent held for review back to it with a member's note: the agent redrafts it in
|
|
15
|
+
* a session of its own, acting as the person the reply is for and reading only, and reports the new
|
|
16
|
+
* draft to `POST /api/ontology/agent/reviews/revision`, where it replaces the review while the review
|
|
17
|
+
* still waits and this is the last redraft asked for. The request is recorded before the agent is
|
|
18
|
+
* called, so however soon the agent reports, its report finds it, and it names everything the agent
|
|
19
|
+
* needs: the agent never looks the review up.
|
|
20
|
+
*/
|
|
21
|
+
export function reviewReviser(input) {
|
|
22
|
+
const { backend, principal, agent } = input;
|
|
23
|
+
const report = (phase, cause) => Effect.logWarning("ontology.agent_review.revision_diagnostic").pipe(Effect.annotateLogs({
|
|
24
|
+
phase,
|
|
25
|
+
requestId: input.requestId,
|
|
26
|
+
error: describeChatError(cause, (value) => agent.identityToken ? value.split(agent.identityToken).join("[redacted]") : value),
|
|
27
|
+
}));
|
|
28
|
+
return (revise) => Effect.gen(function* () {
|
|
29
|
+
// The call happens before the action's transaction, whose write guard comes too late for it:
|
|
30
|
+
// a review outside the scope is refused here, read through the request's own scope.
|
|
31
|
+
const revisable = effectiveScope("agent_review:revise", principal);
|
|
32
|
+
if (revisable !== undefined) {
|
|
33
|
+
yield* backend
|
|
34
|
+
.get({
|
|
35
|
+
entity: "agent_review",
|
|
36
|
+
id: revise.review,
|
|
37
|
+
reader: {
|
|
38
|
+
...principal,
|
|
39
|
+
permissions: ["agent_review:read"],
|
|
40
|
+
scopes: [{ permission: "agent_review:read", where: revisable }],
|
|
41
|
+
},
|
|
42
|
+
})
|
|
43
|
+
.pipe(Effect.mapError(() => new PermissionDenied({
|
|
44
|
+
message: "The review is outside the records agent_review:revise covers.",
|
|
45
|
+
permission: "agent_review:revise",
|
|
46
|
+
})));
|
|
47
|
+
}
|
|
48
|
+
if (principal.kind === "guest") {
|
|
49
|
+
return yield* new PermissionDenied({ message: "The member is unknown." });
|
|
50
|
+
}
|
|
51
|
+
const review = yield* backend
|
|
52
|
+
.get({ entity: "agent_review", id: revise.review })
|
|
53
|
+
.pipe(Effect.mapError(() => new ActionRejected({ message: "The review does not exist." })));
|
|
54
|
+
if (review.status !== "pending") {
|
|
55
|
+
return yield* new ActionRejected({
|
|
56
|
+
message: "Only a reply that still waits for a member can be redrafted.",
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
if (revise.note === "") {
|
|
60
|
+
return yield* new ActionRejected({ message: "Say in note what the agent should change." });
|
|
61
|
+
}
|
|
62
|
+
// The redraft acts as the person, with the roles they hold now, as their own session does.
|
|
63
|
+
const personId = text(review.person_id);
|
|
64
|
+
const person = personId === null || backend.agents === undefined
|
|
65
|
+
? undefined
|
|
66
|
+
: yield* backend.agents.member(personId);
|
|
67
|
+
if (person === undefined) {
|
|
68
|
+
return yield* new ActionRejected({
|
|
69
|
+
message: "The person the reply is for is no longer an active member.",
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (agent.origin === undefined || agent.identityToken === undefined) {
|
|
73
|
+
return yield* new ActionRejected({
|
|
74
|
+
message: "The agent redrafts replies only on the production deployment.",
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
// The key of the reply the agent first wrote names the session's turn whose lookups the
|
|
78
|
+
// redraft reads; a redraft of a redraft follows its chain back to it.
|
|
79
|
+
let first = review;
|
|
80
|
+
for (let depth = 0; depth < REVISION_DEPTH; depth += 1) {
|
|
81
|
+
const earlier = text(first.revises_id);
|
|
82
|
+
if (earlier === null) {
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
const found = yield* backend
|
|
86
|
+
.get({ entity: "agent_review", id: earlier })
|
|
87
|
+
.pipe(Effect.option);
|
|
88
|
+
if (Option.isNone(found)) {
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
first = found.value;
|
|
92
|
+
}
|
|
93
|
+
const revision = randomUUID();
|
|
94
|
+
// Recorded before the agent is asked, so that however soon it reports, its report finds the
|
|
95
|
+
// request; a request the agent could not take is recorded as failed.
|
|
96
|
+
const recorded = backend.agents?.requestRevision === undefined
|
|
97
|
+
? false
|
|
98
|
+
: yield* backend.agents.requestRevision({
|
|
99
|
+
review: String(review.id),
|
|
100
|
+
revision,
|
|
101
|
+
note: revise.note,
|
|
102
|
+
notedBy: principal.id,
|
|
103
|
+
});
|
|
104
|
+
if (!recorded) {
|
|
105
|
+
return yield* new ActionRejected({
|
|
106
|
+
message: "Only a reply that still waits for a member can be redrafted.",
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const failed = backend.agents?.failRevision?.({ review: String(review.id), revision }) ?? Effect.void;
|
|
110
|
+
const body = {
|
|
111
|
+
review_id: String(review.id),
|
|
112
|
+
revision,
|
|
113
|
+
note: revise.note,
|
|
114
|
+
member_id: person.principal.id,
|
|
115
|
+
roles: person.principal.roles,
|
|
116
|
+
session_id: String(review.session_id),
|
|
117
|
+
key: String(first.key),
|
|
118
|
+
provider: String(review.provider),
|
|
119
|
+
channel: text(review.channel) ?? String(review.provider),
|
|
120
|
+
chat_id: String(review.chat_id),
|
|
121
|
+
thread_id: text(review.thread_id),
|
|
122
|
+
chat_kind: review.chat_kind === "group" ? "group" : "private",
|
|
123
|
+
draft: String(review.draft ?? ""),
|
|
124
|
+
};
|
|
125
|
+
const answered = yield* Effect.tryPromise(async () => {
|
|
126
|
+
const response = await agent.fetch(new Request(new URL(AGENT_REVISION_ROUTE, agent.origin), {
|
|
127
|
+
method: "POST",
|
|
128
|
+
headers: {
|
|
129
|
+
authorization: `Bearer ${agent.identityToken}`,
|
|
130
|
+
"content-type": "application/json",
|
|
131
|
+
},
|
|
132
|
+
body: JSON.stringify(body),
|
|
133
|
+
signal: AbortSignal.timeout(AGENT_REVISION_TIMEOUT_MS),
|
|
134
|
+
}));
|
|
135
|
+
await response.body?.cancel();
|
|
136
|
+
return response.status;
|
|
137
|
+
}).pipe(Effect.exit);
|
|
138
|
+
if (answered._tag === "Failure") {
|
|
139
|
+
yield* report("call", answered.cause);
|
|
140
|
+
yield* failed;
|
|
141
|
+
return yield* new ActionRejected({
|
|
142
|
+
message: "The agent could not be reached to redraft the reply. Try again.",
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
if (answered.value === 404) {
|
|
146
|
+
yield* failed;
|
|
147
|
+
return yield* new ActionRejected({
|
|
148
|
+
message: "The workspace's agent cannot redraft replies: its @segmentstream/agent predates it.",
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
if (answered.value < 200 || answered.value >= 300) {
|
|
152
|
+
yield* report("answer", new Error(`The agent answered with status ${answered.value}.`));
|
|
153
|
+
yield* failed;
|
|
154
|
+
return yield* new ActionRejected({
|
|
155
|
+
message: "The agent could not start redrafting the reply. Try again.",
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return { revision };
|
|
159
|
+
});
|
|
160
|
+
}
|
|
@@ -689,6 +689,35 @@ 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
|
+
* Holds a reply the agent redrafted at a member's request: a pending review that replaces the one
|
|
694
|
+
* it redrafts, which becomes `superseded`. `discarded` when that review was decided, or another
|
|
695
|
+
* redraft was asked for, since; `undefined` when its person is no longer an active member. Absent
|
|
696
|
+
* on stores that predate it.
|
|
697
|
+
*/
|
|
698
|
+
readonly holdRevision?: (input: RevisedReplyInput) => Effect.Effect<HeldReview | "discarded" | undefined>;
|
|
699
|
+
/**
|
|
700
|
+
* Records a member's request that the agent redraft a pending reply, before the agent is asked:
|
|
701
|
+
* the redraft's result then always finds it. False when the reply no longer waits.
|
|
702
|
+
*/
|
|
703
|
+
readonly requestRevision?: (input: {
|
|
704
|
+
readonly review: string;
|
|
705
|
+
readonly revision: string;
|
|
706
|
+
readonly note: string;
|
|
707
|
+
readonly notedBy: string;
|
|
708
|
+
}) => Effect.Effect<boolean>;
|
|
709
|
+
/**
|
|
710
|
+
* Drops the redraft asked for of a reply a member is approving, so none replaces it; false when the
|
|
711
|
+
* reply no longer waits, as when a redraft already replaced it.
|
|
712
|
+
*/
|
|
713
|
+
readonly cancelRevision?: (input: {
|
|
714
|
+
readonly review: string;
|
|
715
|
+
}) => Effect.Effect<boolean>;
|
|
716
|
+
/** Records that the agent could not redraft a reply; false when it is no longer the redraft asked for. */
|
|
717
|
+
readonly failRevision?: (input: {
|
|
718
|
+
readonly review: string;
|
|
719
|
+
readonly revision: string;
|
|
720
|
+
}) => Effect.Effect<boolean>;
|
|
692
721
|
/**
|
|
693
722
|
* The replies an agent session held for review, newest first: what became of each, for the
|
|
694
723
|
* session's next turn. Absent on stores that predate it.
|
|
@@ -715,6 +744,14 @@ export interface HeldReplyInput {
|
|
|
715
744
|
readonly mode: "always" | "whenUnsure";
|
|
716
745
|
readonly confidence: number | null;
|
|
717
746
|
}
|
|
747
|
+
/** A reply the agent redrafted, as `POST /api/ontology/agent/reviews/revision` reports it. */
|
|
748
|
+
export interface RevisedReplyInput {
|
|
749
|
+
/** The review the redraft replaces. */
|
|
750
|
+
readonly review: string;
|
|
751
|
+
/** The redraft the member asked for, as the review records it. */
|
|
752
|
+
readonly revision: string;
|
|
753
|
+
readonly text: string;
|
|
754
|
+
}
|
|
718
755
|
/** A person's private chat the agent saw, as `POST /api/ontology/agent/chats/seen` reports it. */
|
|
719
756
|
export interface InboxChatInput {
|
|
720
757
|
/** The channel the chat is on, by name. */
|
|
@@ -75,6 +75,12 @@ export declare function runtimeTokenVerifier(config: RuntimeIdentityConfig): Run
|
|
|
75
75
|
export declare function logRuntimeRejection(reason: string): Effect.Effect<void>;
|
|
76
76
|
/** How a request may authenticate as the runtime: the verifier and the member it names, if any. */
|
|
77
77
|
export declare const ACT_AS_PROVIDER_HEADER = "x-segmentstream-identity-provider";
|
|
78
|
+
/**
|
|
79
|
+
* The scope the app's agent narrows a request to, as an OAuth grant would: `ontology:read` keeps
|
|
80
|
+
* only the member's reads. Only the agent's own runtime presents it; it never widens what the
|
|
81
|
+
* member may do.
|
|
82
|
+
*/
|
|
83
|
+
export declare const AGENT_SCOPE_HEADER = "x-segmentstream-agent-scope";
|
|
78
84
|
/**
|
|
79
85
|
* The OAuth grant behind the agent token a member's browser showed the agent, when the agent acts
|
|
80
86
|
* for a member who wrote on the web (`X-SegmentStream-Identity-Provider: web`) instead of a paired
|
|
@@ -92,6 +98,8 @@ export interface RuntimeCredential {
|
|
|
92
98
|
readonly agentTask?: Redacted.Redacted<string>;
|
|
93
99
|
/** The grant in `X-SegmentStream-Agent-Grant`; `undefined` without the header. */
|
|
94
100
|
readonly grant?: string;
|
|
101
|
+
/** The scope in `X-SegmentStream-Agent-Scope`; `undefined` without the header. */
|
|
102
|
+
readonly scope?: string;
|
|
95
103
|
/**
|
|
96
104
|
* The chat in `X-SegmentStream-Agent-Chat` and the session in `X-SegmentStream-Agent-Session`;
|
|
97
105
|
* trusted only once the runtime token is verified, and only as the chat the member acts in.
|
|
@@ -129,6 +129,12 @@ export function logRuntimeRejection(reason) {
|
|
|
129
129
|
}
|
|
130
130
|
/** How a request may authenticate as the runtime: the verifier and the member it names, if any. */
|
|
131
131
|
export const ACT_AS_PROVIDER_HEADER = "x-segmentstream-identity-provider";
|
|
132
|
+
/**
|
|
133
|
+
* The scope the app's agent narrows a request to, as an OAuth grant would: `ontology:read` keeps
|
|
134
|
+
* only the member's reads. Only the agent's own runtime presents it; it never widens what the
|
|
135
|
+
* member may do.
|
|
136
|
+
*/
|
|
137
|
+
export const AGENT_SCOPE_HEADER = "x-segmentstream-agent-scope";
|
|
132
138
|
/**
|
|
133
139
|
* The OAuth grant behind the agent token a member's browser showed the agent, when the agent acts
|
|
134
140
|
* for a member who wrote on the web (`X-SegmentStream-Identity-Provider: web`) instead of a paired
|
|
@@ -151,6 +157,7 @@ export function runtimeCredential(verify, request) {
|
|
|
151
157
|
const provider = request.headers[ACT_AS_PROVIDER_HEADER]?.trim();
|
|
152
158
|
const agentTask = agentTaskSecret(request);
|
|
153
159
|
const grant = request.headers[AGENT_GRANT_HEADER]?.trim();
|
|
160
|
+
const scope = request.headers[AGENT_SCOPE_HEADER]?.trim();
|
|
154
161
|
const chat = requestChat(request);
|
|
155
162
|
return {
|
|
156
163
|
verify,
|
|
@@ -158,6 +165,7 @@ export function runtimeCredential(verify, request) {
|
|
|
158
165
|
...(provider ? { provider } : {}),
|
|
159
166
|
...(agentTask === undefined ? {} : { agentTask }),
|
|
160
167
|
...(grant ? { grant } : {}),
|
|
168
|
+
...(scope ? { scope } : {}),
|
|
161
169
|
...(chat === undefined ? {} : { chat }),
|
|
162
170
|
};
|
|
163
171
|
}
|
|
@@ -37,7 +37,10 @@ export declare function rpcResponse(reply: {
|
|
|
37
37
|
* session and opening a new one once when the server no longer knows it.
|
|
38
38
|
*/
|
|
39
39
|
export declare function callTool(transport: ConnectionTransport["Service"], toolset: ResolvedToolset, tool: ResolvedTool, args: Readonly<Record<string, unknown>>): Effect.Effect<ToolResult, ConnectionError | ActionRejected>;
|
|
40
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
* Whether the caller reads only: an OAuth client the member consented to reading only, or the app's
|
|
42
|
+
* agent acting for a member with its requests narrowed to reading.
|
|
43
|
+
*/
|
|
41
44
|
export declare function isReadScoped(caller: CallerContext): boolean;
|
|
42
45
|
/** The text of a tool result for MCP clients that read `content`: the provider's text items. */
|
|
43
46
|
export declare function resultText(result: ToolResult): string;
|
package/dist/service/toolsets.js
CHANGED
|
@@ -233,9 +233,12 @@ export function callTool(transport, toolset, tool, args) {
|
|
|
233
233
|
};
|
|
234
234
|
});
|
|
235
235
|
}
|
|
236
|
-
/**
|
|
236
|
+
/**
|
|
237
|
+
* Whether the caller reads only: an OAuth client the member consented to reading only, or the app's
|
|
238
|
+
* agent acting for a member with its requests narrowed to reading.
|
|
239
|
+
*/
|
|
237
240
|
export function isReadScoped(caller) {
|
|
238
|
-
return caller.kind === "oauth" && caller.scope === READ_SCOPE;
|
|
241
|
+
return (caller.kind === "oauth" || caller.kind === "runtime") && caller.scope === READ_SCOPE;
|
|
239
242
|
}
|
|
240
243
|
/** The text of a tool result for MCP clients that read `content`: the provider's text items. */
|
|
241
244
|
export function resultText(result) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.131.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",
|