@segmentstream/ontology 0.129.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.
@@ -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,15 +103,191 @@ 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);
109
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);
110
291
  const store = {
111
292
  confirmations: sqlConfirmationStore(sql),
112
293
  savePairing: (pairing) => sql
@@ -667,65 +848,163 @@ export function sqlAgentStore(ontology, sql) {
667
848
  };
668
849
  }));
669
850
  }).pipe(Effect.orDie),
670
- holdReply: (input) => sql
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" };
864
+ }
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
671
885
  .withTransaction(Effect.gen(function* () {
672
- if (!isRecordId(input.memberId)) {
673
- return undefined;
886
+ if (!isRecordId(input.review) || !isRecordId(input.notedBy)) {
887
+ return false;
674
888
  }
675
889
  yield* beginReplicationWrite(sql);
676
- // Reports of one reply run one after the other: the first creates it, the rest find it.
677
- yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${input.key}`]);
678
890
  const runtime = makeOntologyRuntime(ontology, sql, {
679
- action: `${AgentReview.name}.hold`,
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`,
680
923
  actionId: randomUUID(),
681
924
  principalId: null,
682
925
  });
683
- const [found] = yield* runtime.find({
926
+ const [review] = yield* runtime.find({
684
927
  entity: AgentReview.name,
685
- options: { where: { key: input.key }, limit: 1 },
928
+ options: { where: { id: input.review }, limit: 1, forUpdate: true },
686
929
  });
687
- if (found !== undefined) {
688
- return { id: String(found.id), status: String(found.status), created: false };
930
+ if (review === undefined || review.status !== "pending") {
931
+ return false;
689
932
  }
690
- const [member] = yield* rows(`SELECT 1 FROM ${USERS} WHERE "id" = $1::uuid AND "kind"::text = 'member' AND "active"`, [input.memberId]);
691
- if (member === undefined) {
692
- return undefined;
933
+ if (review.revision !== null && review.revision !== undefined) {
934
+ yield* runtime.update({
935
+ entity: AgentReview.name,
936
+ id: String(review.id),
937
+ values: { revision: null, revision_state: null },
938
+ });
693
939
  }
694
- // The registry keys a chat by its channel's name and its id, as the archive does.
695
- const [chat] = yield* runtime.find({
696
- entity: AgentChat.name,
697
- options: {
698
- where: { provider: input.channel, external_id: input.chatId },
699
- limit: 1,
700
- },
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,
701
953
  });
702
- const review = yield* runtime.create({
954
+ const [previous] = yield* runtime.find({
703
955
  entity: AgentReview.name,
704
- values: {
705
- key: input.key,
706
- provider: input.provider,
707
- channel: input.channel,
708
- chat_id: input.chatId,
709
- recipient: input.recipient,
710
- chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
711
- thread_id: input.threadId === "" ? null : input.threadId,
712
- reply_to: input.replyTo,
713
- session_id: input.sessionId,
714
- draft: input.text,
715
- text: null,
716
- status: "pending",
717
- // Select values are stored by their wire names.
718
- mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
719
- confidence: input.confidence,
720
- message_id: null,
721
- decided_at: null,
722
- person: input.memberId,
723
- agent_chat: chat === undefined ? null : String(chat.id),
724
- },
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;
963
+ }
964
+ yield* runtime.update({
965
+ entity: AgentReview.name,
966
+ id: String(previous.id),
967
+ values: { revision_state: "failed" },
725
968
  });
726
- return { id: String(review.id), status: "pending", created: true };
969
+ return true;
727
970
  }))
728
971
  .pipe(Effect.orDie),
972
+ sessionReviews: (sessionId) => Effect.gen(function* () {
973
+ const runtime = makeOntologyRuntime(ontology, sql);
974
+ // Every reply still waiting, however old, and the latest decisions: a decision on an old
975
+ // reply reaches the session as the newest one.
976
+ const [waiting, decided] = yield* Effect.all([
977
+ runtime.find({
978
+ entity: AgentReview.name,
979
+ options: {
980
+ where: { session_id: sessionId, status: "pending" },
981
+ orderBy: [{ field: "created_at", direction: "desc" }],
982
+ limit: SESSION_REVIEWS,
983
+ },
984
+ }),
985
+ runtime.find({
986
+ entity: AgentReview.name,
987
+ options: {
988
+ where: { session_id: sessionId, status: { ne: "pending" } },
989
+ orderBy: [{ field: "decided_at", direction: "desc" }],
990
+ limit: SESSION_REVIEWS,
991
+ },
992
+ }),
993
+ ]);
994
+ const found = [...waiting, ...decided].sort((first, second) => instant(second.created_at) - instant(first.created_at));
995
+ return found.map((record) => ({
996
+ id: String(record.id),
997
+ status: String(record.status),
998
+ draft: String(record.draft),
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),
1002
+ heldAt: timestampText(record.created_at),
1003
+ decidedAt: record.decided_at === null || record.decided_at === undefined
1004
+ ? null
1005
+ : timestampText(record.decided_at),
1006
+ }));
1007
+ }).pipe(Effect.orDie),
729
1008
  web: sqlAgentWebStore(ontology, sql, {
730
1009
  signUp: (visitorId) => resolveChannelSignIn(ontology, sql, { provider: WEB_PROVIDER, externalId: visitorId }),
731
1010
  }),
@@ -767,6 +1046,10 @@ function inInbox(ontology, input, resolution) {
767
1046
  : { ...resolution, inbox: true };
768
1047
  }
769
1048
  /** A stored timestamp, as the wire carries it. */
1049
+ /** A stored timestamp as milliseconds since the epoch. */
1050
+ function instant(value) {
1051
+ return value instanceof Date ? value.getTime() : Date.parse(String(value));
1052
+ }
770
1053
  function timestampText(value) {
771
1054
  return value instanceof Date ? value.toISOString() : String(value);
772
1055
  }
@@ -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,22 @@ 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
+ }>;
168
+ /**
169
+ * `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
170
+ * next turn learns which the person saw.
171
+ */
172
+ export declare const SessionReviewsRequest: Schema.Struct<{
173
+ readonly session_id: Schema.String;
174
+ }>;
159
175
  /** An identity on the wire, as the member's connect page and settings show it. */
160
176
  export declare function identityForWire(identity: AgentIdentity): {
161
177
  created_at: string;
@@ -209,6 +209,30 @@ 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
+ });
227
+ /**
228
+ * `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
229
+ * next turn learns which the person saw.
230
+ */
231
+ export const SessionReviewsRequest = Schema.Struct({
232
+ session_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
233
+ description: "The agent's session that held the replies.",
234
+ }),
235
+ });
212
236
  /** An identity on the wire, as the member's connect page and settings show it. */
213
237
  export function identityForWire(identity) {
214
238
  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, 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,83 @@ 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
+ }
453
+ /**
454
+ * `POST /api/ontology/agent/reviews/session` (runtime): the replies the session held for review,
455
+ * newest first, with what became of each. Nothing a member wrote about them is in it.
456
+ */
457
+ function sessionReviews(store) {
458
+ return (request) => Effect.gen(function* () {
459
+ const requestId = yield* RequestId;
460
+ const decoded = Schema.decodeUnknownResult(SessionReviewsRequest)(yield* jsonBody(request), {
461
+ errors: "all",
462
+ onExcessProperty: "error",
463
+ });
464
+ if (Result.isFailure(decoded)) {
465
+ return invalidBody(requestId, schemaIssues(decoded.failure));
466
+ }
467
+ if (store.sessionReviews === undefined) {
468
+ return toServerResponse(notFound(requestId, "This ontology service holds no replies."));
469
+ }
470
+ const reviews = yield* store.sessionReviews(decoded.success.session_id);
471
+ return json({
472
+ reviews: reviews.map((review) => ({
473
+ id: review.id,
474
+ status: review.status,
475
+ draft: review.draft,
476
+ edited: review.edited,
477
+ held_at: review.heldAt,
478
+ decided_at: review.decidedAt,
479
+ })),
480
+ });
481
+ });
482
+ }
406
483
  /** `GET /api/ontology/agent/identities` (member): the member's own live identities. */
407
484
  function listIdentities(store, member) {
408
485
  return Effect.gen(function* () {
@@ -515,6 +592,8 @@ export function agentLayer(options) {
515
592
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
516
593
  yield* router.add("POST", CHATS_HANDOFF_PATH, asRuntime(handOffChat(store)));
517
594
  yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
595
+ yield* router.add("POST", `${REVIEWS_PATH}/session`, asRuntime(sessionReviews(store)));
596
+ yield* router.add("POST", `${REVIEWS_PATH}/revision`, asRuntime(revision(store)));
518
597
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
519
598
  if (store.web !== undefined && backend.oauth !== undefined) {
520
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
- return agentTask === undefined
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