@segmentstream/ontology 0.130.0 → 0.131.1

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.
@@ -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.gen(function* () {
691
- // The triggers on `agent_review` itself, which fire for any of its actions: holding is one.
692
- const triggers = actionTriggers(ontology).filter((trigger) => trigger.entity === AgentReview.name &&
693
- (trigger.action === undefined || trigger.action === HOLD_ACTION));
694
- const starter = triggers.length > 0
695
- ? Option.getOrUndefined(yield* Effect.serviceOption(WorkflowStarter))
696
- : undefined;
697
- // Admitted and bounded as an action's transaction is, by the same gate and limits.
698
- const admission = Option.getOrUndefined(yield* Effect.serviceOption(ActionTransactions));
699
- const limits = admission?.limits ?? ACTION_TRANSACTION_LIMITS;
700
- const qualified = `${AgentReview.name}.${HOLD_ACTION}`;
701
- const actionId = randomUUID();
702
- if (!isRecordId(input.memberId)) {
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
- // Before the transaction: whatever it commits must be swept if this request does not start
706
- // it. The transaction rolls back rather than commit after the deadline the sweep covers.
707
- if (starter !== undefined) {
708
- yield* starter.ensureRecovery({ commitBy: Date.now() + limits.handlerTimeoutMs });
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
- const transaction = actionTransaction(sql, () => Effect.gen(function* () {
711
- yield* sql.unsafe(`SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true)`, [`${limits.statementTimeoutMs}ms`, `${limits.lockTimeoutMs}ms`]);
712
- yield* beginReplicationWrite(sql);
713
- // Reports of one reply run one after the other: the first creates it, the rest find it.
714
- yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${input.key}`]);
715
- const edits = [];
716
- const snapshots = new Map();
717
- const runtime = makeOntologyRuntime(ontology, sql, {
718
- action: qualified,
719
- actionId,
720
- principalId: null,
721
- ...(triggers.length > 0
722
- ? {
723
- onEdit: (edit) => edits.push(edit),
724
- onSnapshot: (snapshot) => {
725
- if (snapshot.entity === AgentReview.name) {
726
- snapshots.set(snapshot.id, {
727
- before: snapshots.get(snapshot.id)?.before ?? snapshot.before,
728
- after: snapshot.after,
729
- });
730
- }
731
- },
732
- }
733
- : {}),
734
- });
735
- const [found] = yield* runtime.find({
736
- entity: AgentReview.name,
737
- options: { where: { key: input.key }, limit: 1 },
738
- });
739
- if (found !== undefined) {
740
- return {
741
- review: { id: String(found.id), status: String(found.status), created: false },
742
- starts: [],
743
- };
744
- }
745
- const [member] = yield* rows(`SELECT 1 FROM ${USERS} WHERE "id" = $1::uuid AND "kind"::text = 'member' AND "active"`, [input.memberId]);
746
- if (member === undefined) {
747
- return undefined;
748
- }
749
- // The registry keys a chat by its channel's name and its id, as the archive does.
750
- const [chat] = yield* runtime.find({
751
- entity: AgentChat.name,
752
- options: {
753
- where: { provider: input.channel, external_id: input.chatId },
754
- limit: 1,
755
- },
756
- });
757
- const review = yield* runtime.create({
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
- values: {
760
- key: input.key,
761
- provider: input.provider,
762
- channel: input.channel,
763
- chat_id: input.chatId,
764
- recipient: input.recipient,
765
- chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
766
- thread_id: input.threadId === "" ? null : input.threadId,
767
- reply_to: input.replyTo,
768
- session_id: input.sessionId,
769
- draft: input.text,
770
- text: null,
771
- status: "pending",
772
- // Select values are stored by their wire names.
773
- mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
774
- confidence: input.confidence,
775
- message_id: null,
776
- decided_at: null,
777
- person: input.memberId,
778
- agent_chat: chat === undefined ? null : String(chat.id),
779
- },
936
+ id: String(review.id),
937
+ values: { revision: null, revision_state: null },
780
938
  });
781
- const result = { review: String(review.id), status: "pending" };
782
- let starts = [];
783
- if (triggers.length > 0) {
784
- const principal = yield* memberPrincipal(input.memberId);
785
- const [now] = yield* rows(`SELECT to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "at"`);
786
- if (principal !== undefined) {
787
- starts = yield* evaluateTriggers(triggers, {
788
- ontology,
789
- entity: AgentReview.name,
790
- action: HOLD_ACTION,
791
- definition: HOLD_DEFINITION,
792
- generated: false,
793
- actionId,
794
- at: canonicalInstant(String(now.at)),
795
- principal,
796
- input,
797
- result,
798
- edits,
799
- held: snapshots,
800
- load: (id) => runtime.get({ entity: AgentReview.name, id }).pipe(Effect.map((record) => record), Effect.catchTag("NotFound", () => Effect.succeed(undefined))),
801
- });
802
- yield* insertStarts(sql, starts);
803
- }
804
- }
805
- return { review: { id: result.review, status: "pending", created: true }, starts };
806
- }), {
807
- qualified,
808
- actionId,
809
- retryOnDeadlock: false,
810
- handlerTimeoutMs: limits.handlerTimeoutMs,
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 held = yield* admission === undefined ? transaction : admission.admit(transaction);
813
- if (held === undefined) {
814
- return undefined;
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
- // The decided runs start once the review committed; a failure leaves them to the sweep.
817
- yield* startCommitted(sql, starter, held.starts, actionId);
818
- return held.review;
819
- }).pipe(Effect.orDie),
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
- edited: record.text !== null && record.text !== undefined && record.text !== 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),
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
- 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
@@ -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,