@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.
@@ -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 as a message it did not
175
- // write, and the draft sent as written as its own.
176
- sessionId: text === draft && typeof review.session_id === "string" ? review.session_id : null,
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,40 @@ 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>;
721
+ /**
722
+ * The replies an agent session held for review, newest first: what became of each, for the
723
+ * session's next turn. Absent on stores that predate it.
724
+ */
725
+ readonly sessionReviews?: (sessionId: string) => Effect.Effect<ReadonlyArray<SessionReview>>;
692
726
  /** The grants behind agent tokens for the web. Absent on stores that predate them. */
693
727
  readonly web?: AgentWebStore;
694
728
  }
@@ -710,6 +744,14 @@ export interface HeldReplyInput {
710
744
  readonly mode: "always" | "whenUnsure";
711
745
  readonly confidence: number | null;
712
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
+ }
713
755
  /** A person's private chat the agent saw, as `POST /api/ontology/agent/chats/seen` reports it. */
714
756
  export interface InboxChatInput {
715
757
  /** The channel the chat is on, by name. */
@@ -732,6 +774,18 @@ export interface HeldReview {
732
774
  /** Whether this report created it, rather than finding the review an earlier one created. */
733
775
  readonly created: boolean;
734
776
  }
777
+ /** A reply an agent session held for review, as the session learns its outcome. */
778
+ export interface SessionReview {
779
+ readonly id: string;
780
+ /** `pending`, `sent`, `uncertain`, `failed` or `rejected`, as the review holds it. */
781
+ readonly status: string;
782
+ /** The reply as the session wrote it. */
783
+ readonly draft: string;
784
+ /** Whether a member sent their edit of the draft instead of the draft. */
785
+ readonly edited: boolean;
786
+ readonly heldAt: string;
787
+ readonly decidedAt: string | null;
788
+ }
735
789
  declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segmentstream/ontology/OntologyBackend", {
736
790
  readonly workflowAdmissions?: {
737
791
  readonly ensureRecovery: (commitBy: number) => Effect.Effect<number, WorkflowRecoveryUnavailable>;
@@ -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
- /** Whether the caller is an OAuth client the member consented to reading only. */
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;
@@ -233,9 +233,12 @@ export function callTool(transport, toolset, tool, args) {
233
233
  };
234
234
  });
235
235
  }
236
- /** Whether the caller is an OAuth client the member consented to reading only. */
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.129.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",