@segmentstream/ontology 0.165.1 → 0.166.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.166.1
4
+
5
+ In an app preview that runs the agent, the agent's tools and recall now act for an eval session's
6
+ test member over `/mcp` as they do over the REST routes. MCP requests now see the preview's
7
+ deployment, so eval grants count there, and a preview's capability limits apply to them.
8
+
9
+ ## 0.166.0
10
+
11
+ `agent_chat.draft({ chat, message?, note? })` asks the agent to draft a reply in a person's private
12
+ chat, usually to a message it stayed silent on, under its own permission `agent_chat:draft`.
13
+
14
+ - The agent writes it in the redraft's session, which acts as the person, reads only and has none
15
+ of the agent's own tools, and holds it as a pending `agent_draft` with the new `mode`
16
+ `requested`, keyed `request:<request>` as the action returns. The requester is its `notedBy`
17
+ and their note its `note`; its `basis` is where the chat stood when it was asked for.
18
+ - Nothing is sent: only an approval of the draft sends it.
19
+ - Refused for the agent's own sessions and tasks, guests, group chats, chats without one person,
20
+ email threads, and a message that is not the person's.
21
+
22
+ Action required: grant `agent_chat:draft` to the roles, or the workflow, that should ask for
23
+ drafts. A reader of `agent_draft.mode` that lists the modes should take `requested`, and any mode
24
+ it does not know, as a draft held for review.
25
+
3
26
  ## 0.165.1
4
27
 
5
28
  An approved draft sent without some of its files is recorded as a message the agent did not write,
@@ -35,6 +35,17 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
35
35
  chat: string;
36
36
  handled_by: null;
37
37
  }>;
38
+ readonly draft: import("./action.js").Action<Schema.Struct<{
39
+ readonly chat: Schema.Codec<string, string, never, never>;
40
+ readonly message: Schema.optionalKey<Schema.String>;
41
+ readonly note: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
42
+ }>, {
43
+ chat: string;
44
+ request: string;
45
+ key: string;
46
+ message: string;
47
+ status: "requested";
48
+ }>;
38
49
  readonly previewMessage: import("./action.js").Action<Schema.Struct<{
39
50
  readonly chat: Schema.String;
40
51
  readonly text: Schema.String;
@@ -1,5 +1,6 @@
1
1
  import { Effect, Option, Schema } from "effect";
2
2
  import { action } from "./action.js";
3
+ import { AGENT_DRAFT_NOTE_LIMIT } from "./agent-draft.js";
3
4
  import { entity } from "./entity.js";
4
5
  import { ActionRejected } from "./errors.js";
5
6
  import { ChatDelivery, ChatHistoryImportInput, ChatPostInput, ChatSendInput } from "./chat.js";
@@ -179,6 +180,52 @@ export const AgentChat = entity("agent_chat", {
179
180
  return { chat: chat.id, handled_by: null };
180
181
  }),
181
182
  }),
183
+ draft: action({
184
+ description: "Ask the agent to draft a reply in a person's private chat, such as to a message it " +
185
+ "stayed silent on while the chat was handed over: message names the person's message by " +
186
+ "its id in the chat store, their latest when omitted, and note says what to write, in " +
187
+ "your words. The agent writes it in a session of its own, acting as the person and " +
188
+ "reading only, and holds it as an agent_draft with mode requested and the key this " +
189
+ "returns, which a member then approves, edits, rejects or sends back like any draft. " +
190
+ "Nothing is sent. The person and the agent's chat with them never see the note. Refused " +
191
+ "for a group chat, a chat with no one person, the agent's own sessions and its tasks.",
192
+ hints: { destructive: false, irreversible: false, idempotent: false },
193
+ input: Schema.Struct({
194
+ chat: self.ref,
195
+ message: Schema.optionalKey(Schema.String.check(Schema.isUUID()).annotate({
196
+ description: "The person's message to answer, by its id in the chat store; omit it for their " +
197
+ "latest message.",
198
+ })),
199
+ note: Schema.optionalKey(p.text({
200
+ maxLength: AGENT_DRAFT_NOTE_LIMIT,
201
+ description: "What the agent should write, in your words.",
202
+ })),
203
+ }),
204
+ connections: [],
205
+ prepare: ({ input }) => Effect.gen(function* () {
206
+ const delivery = yield* Effect.serviceOption(ChatDelivery);
207
+ const draft = Option.isSome(delivery) ? delivery.value.draft : undefined;
208
+ if (draft === undefined) {
209
+ return yield* new ActionRejected({
210
+ message: "Drafting a reply requires the authenticated ontology service.",
211
+ });
212
+ }
213
+ const note = input.note?.trim();
214
+ return yield* draft({
215
+ chat: String(input.chat),
216
+ ...(input.message === undefined ? {} : { message: input.message }),
217
+ ...(note === undefined || note === "" ? {} : { note }),
218
+ });
219
+ }),
220
+ // The draft is held once the agent wrote it, under the key returned.
221
+ handler: ({ input, prepared }) => Effect.succeed({
222
+ chat: String(input.chat),
223
+ request: prepared.request,
224
+ key: prepared.key,
225
+ message: prepared.message,
226
+ status: "requested",
227
+ }),
228
+ }),
182
229
  previewMessage: action({
183
230
  description: "Render an exact chat message with its verified destination and sender attribution, without reserving a key, " +
184
231
  "writing history or sending. Requires the same explicit post permission as delivery. " +
@@ -43,6 +43,9 @@ export declare const AGENT_DRAFT_MODES: readonly [{
43
43
  }, {
44
44
  readonly value: "whenUnsure";
45
45
  readonly description: "The decision model was not sure enough that staff would send it as written.";
46
+ }, {
47
+ readonly value: "requested";
48
+ readonly description: string;
46
49
  }];
47
50
  /** The longest reply a draft holds; a provider may accept less in one message. */
48
51
  export declare const AGENT_DRAFT_TEXT_LIMIT = 20000;
@@ -99,7 +102,7 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
99
102
  readonly files: Schema.optionalKey<import("./property.js").Property<Schema.Json, false, false>>;
100
103
  readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
101
104
  readonly status: import("./property.js").Property<"pending" | "sent" | "failed" | "uncertain" | "rejected" | "superseded" | "dismissed", false, false>;
102
- readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
105
+ readonly mode: import("./property.js").Property<"requested" | "always" | "whenUnsure", false, false>;
103
106
  readonly confidence: Schema.optionalKey<import("./property.js").Property<number, false, false>>;
104
107
  readonly messageId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
105
108
  readonly decidedAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
@@ -189,7 +192,7 @@ export declare const AgentDraft: import("./entity.js").Entity<"agent_draft", {
189
192
  readonly files: Schema.Json;
190
193
  readonly text: string | null;
191
194
  readonly status: "pending" | "sent" | "failed" | "uncertain" | "rejected" | "superseded" | "dismissed";
192
- readonly mode: "always" | "whenUnsure";
195
+ readonly mode: "requested" | "always" | "whenUnsure";
193
196
  readonly confidence: number | null;
194
197
  readonly messageId: string | null;
195
198
  readonly decidedAt: string | null;
@@ -225,7 +228,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
225
228
  readonly files: Schema.optionalKey<import("./property.js").Property<Schema.Json, false, false>>;
226
229
  readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
227
230
  readonly status: import("./property.js").Property<"pending" | "sent" | "failed" | "uncertain" | "rejected" | "superseded" | "dismissed", false, false>;
228
- readonly mode: import("./property.js").Property<"always" | "whenUnsure", false, false>;
231
+ readonly mode: import("./property.js").Property<"requested" | "always" | "whenUnsure", false, false>;
229
232
  readonly confidence: Schema.optionalKey<import("./property.js").Property<number, false, false>>;
230
233
  readonly messageId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
231
234
  readonly decidedAt: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
@@ -315,7 +318,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_draft", {
315
318
  readonly files: Schema.Json;
316
319
  readonly text: string | null;
317
320
  readonly status: "pending" | "sent" | "failed" | "uncertain" | "rejected" | "superseded" | "dismissed";
318
- readonly mode: "always" | "whenUnsure";
321
+ readonly mode: "requested" | "always" | "whenUnsure";
319
322
  readonly confidence: number | null;
320
323
  readonly messageId: string | null;
321
324
  readonly decidedAt: string | null;
@@ -361,6 +364,9 @@ export declare const AGENT_REVIEW_MODES: readonly [{
361
364
  }, {
362
365
  readonly value: "whenUnsure";
363
366
  readonly description: "The decision model was not sure enough that staff would send it as written.";
367
+ }, {
368
+ readonly value: "requested";
369
+ readonly description: string;
364
370
  }];
365
371
  /** @deprecated Use {@link AGENT_DRAFT_TEXT_LIMIT}. */
366
372
  export declare const AGENT_REVIEW_TEXT_LIMIT = 20000;
@@ -45,6 +45,11 @@ export const AGENT_DRAFT_MODES = [
45
45
  value: "whenUnsure",
46
46
  description: "The decision model was not sure enough that staff would send it as written.",
47
47
  },
48
+ {
49
+ value: "requested",
50
+ description: "A member or workflow asked the agent for it in the chat with agent_chat.draft, such as " +
51
+ "to a message it stayed silent on.",
52
+ },
48
53
  ];
49
54
  /** The longest reply a draft holds; a provider may accept less in one message. */
50
55
  export const AGENT_DRAFT_TEXT_LIMIT = 20_000;
@@ -310,8 +315,9 @@ export const AgentDraft = entity("agent_draft", {
310
315
  managed: true,
311
316
  maxLength: AGENT_DRAFT_NOTE_LIMIT,
312
317
  display: "multiline",
313
- description: "What the member asked the agent to change when they asked it to redraft the reply. " +
314
- "Only the redraft reads it; the person and the agent's chat with them never see it.",
318
+ description: "What the member asked the agent to change when they asked it to redraft the reply, or " +
319
+ "to write when they asked it for the draft. Only the session that wrote it reads it; the " +
320
+ "person and the agent's chat with them never see it.",
315
321
  }),
316
322
  revision: p.text({
317
323
  optional: true,
@@ -346,7 +352,7 @@ export const AgentDraft = entity("agent_draft", {
346
352
  inverse: "notedAgentDrafts",
347
353
  onDelete: "setNull",
348
354
  phrase: ["was sent back by", "sent back"],
349
- description: "The member who last asked the agent to redraft the reply.",
355
+ description: "The member who last asked the agent to redraft the reply, or who asked it for the draft.",
350
356
  }),
351
357
  revises: rel.one("agent_draft", {
352
358
  optional: true,
package/dist/chat.d.ts CHANGED
@@ -265,6 +265,22 @@ export interface ReviewReviseInput {
265
265
  export interface ReviewReviseResult {
266
266
  readonly revision: string;
267
267
  }
268
+ /** A request that the agent draft a reply in a person's private chat, held for a member. */
269
+ export interface ChatDraftInput {
270
+ /** The `agent_chat` record's id. */
271
+ readonly chat: string;
272
+ /** The person's message to answer, by its id in the chat store; their latest when absent. */
273
+ readonly message?: string;
274
+ /** What to write, in the requester's words; only the drafting session reads it. */
275
+ readonly note?: string;
276
+ }
277
+ /** The draft the agent started: it is held as an `agent_draft` keyed `key` once written. */
278
+ export interface ChatDraftResult {
279
+ readonly request: string;
280
+ readonly key: string;
281
+ /** The chat store's id of the message the draft answers. */
282
+ readonly message: string;
283
+ }
268
284
  declare const ChatDelivery_base: Context.ServiceClass<ChatDelivery, "@segmentstream/ontology/ChatDelivery", {
269
285
  readonly preview: (input: ChatPostInput) => Effect.Effect<ChatPreview, ActionError>;
270
286
  readonly validate: (input: ChatPostInput) => Effect.Effect<void, ActionError>;
@@ -277,6 +293,8 @@ declare const ChatDelivery_base: Context.ServiceClass<ChatDelivery, "@segmentstr
277
293
  readonly draftsNewer?: (drafts: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<DraftNewer>, ActionError>;
278
294
  /** Asks the agent to redraft a reply it held for review, in a session of its own. */
279
295
  readonly reviseReview?: (input: ReviewReviseInput) => Effect.Effect<ReviewReviseResult, ActionError>;
296
+ /** Asks the agent to draft a reply in a chat, in a session of its own; nothing is sent. */
297
+ readonly draft?: (input: ChatDraftInput) => Effect.Effect<ChatDraftResult, ActionError>;
280
298
  /** Adds a chat's messages from before the agent recorded it, each in its place by its time. */
281
299
  readonly importHistory?: (input: ChatHistoryImportInput) => Effect.Effect<ChatHistoryImportResult, ActionError>;
282
300
  /** The channels whose private chats staff may take over, as the ontology's inbox lists them. */
package/dist/index.d.ts CHANGED
@@ -66,7 +66,7 @@ export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_
66
66
  export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatTemplateMedia, 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 { DraftNewer, InboxOptions, ReviewReviseInput, ReviewReviseResult, ReviewSendInput, ReviewSendResult, } from "./chat.js";
69
+ export type { DraftNewer, InboxOptions, ChatDraftInput, ChatDraftResult, 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";
@@ -296,23 +296,35 @@ export function sqlAgentStore(ontology, sql) {
296
296
  turn_id: resolved.kind === "revision"
297
297
  ? nullableText(resolved.previous.turn_id)
298
298
  : (input.turnId ?? null),
299
+ // A draft asked for was written from the chat as it stood when it was asked for.
299
300
  basis: resolved.kind === "revision"
300
301
  ? nullableText(resolved.previous.basis)
301
- : input.turnId === undefined
302
- ? null
303
- : yield* turnBasis(input.channel, input.chatId, input.turnId),
302
+ : input.requested !== undefined
303
+ ? input.requested.basis
304
+ : input.turnId === undefined
305
+ ? null
306
+ : yield* turnBasis(input.channel, input.chatId, input.turnId),
304
307
  draft: input.text,
305
308
  files: (input.files ?? []).length === 0 ? null : input.files,
306
309
  text: null,
307
310
  status: "pending",
308
311
  // Select values are stored by their wire names.
309
- mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
312
+ mode: input.mode === "whenUnsure" ? "when_unsure" : input.mode,
310
313
  confidence: input.confidence,
311
314
  message_id: null,
312
315
  decided_at: null,
313
316
  person: input.memberId,
314
317
  agent_chat: chat === undefined ? null : String(chat.id),
315
318
  ...(resolved.kind === "revision" ? { revises: String(resolved.previous.id) } : {}),
319
+ // Who asked for a draft, and their note, which only the drafting session read.
320
+ ...(input.requested === undefined
321
+ ? {}
322
+ : {
323
+ note: input.requested.note ?? null,
324
+ noted_by: isRecordId(input.requested.notedBy)
325
+ ? input.requested.notedBy
326
+ : null,
327
+ }),
316
328
  },
317
329
  });
318
330
  if (resolved.kind === "revision") {
@@ -213,6 +213,8 @@ export interface ChatMessageQuery {
213
213
  readonly after?: string;
214
214
  readonly before?: ChatCursor;
215
215
  readonly messageId?: string;
216
+ /** The message by its id in the store; an id that is no UUID finds nothing. */
217
+ readonly id?: string;
216
218
  /**
217
219
  * Outbound messages still `pending`: sends still to deliver. A delivery the service reserved
218
220
  * (`operation` under {@link DELIVERY_OPERATION_PREFIX}) is never one of them.
@@ -33,6 +33,7 @@ export const CHAT_PURGE_BATCH = 1000;
33
33
  export const CHAT_PURGE_BATCHES = 20;
34
34
  const INSTANT = String.raw `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:\d{2})`;
35
35
  const UUID = String.raw `[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`;
36
+ const UUID_TEXT = new RegExp(`^${UUID}$`, "i");
36
37
  const CURSOR = new RegExp(`^(${INSTANT})(?:~(${UUID}))?$`, "i");
37
38
  /** The cursor a page continues at; `undefined` for text that is none. */
38
39
  export function parseChatCursor(value) {
@@ -543,6 +544,9 @@ export function sqlChatMessageStore(sql) {
543
544
  if (input.messageId !== undefined) {
544
545
  conditions.push(`"message_id" = ${params.add(input.messageId)}`);
545
546
  }
547
+ if (input.id !== undefined) {
548
+ conditions.push(UUID_TEXT.test(input.id) ? `"id" = ${params.add(input.id, "uuid")}` : "FALSE");
549
+ }
546
550
  if (input.pending === true) {
547
551
  conditions.push(`"direction" = 'outbound'`, `"status" = 'pending'`,
548
552
  // A delivery the service reserved is never a channel's to send: one whose receipt was
@@ -157,9 +157,14 @@ export declare const ReviewRequest: Schema.Struct<{
157
157
  readonly id: Schema.String;
158
158
  readonly property: Schema.optionalKey<Schema.String>;
159
159
  }>>>;
160
- readonly mode: Schema.Literals<readonly ["always", "whenUnsure"]>;
160
+ readonly mode: Schema.Literals<readonly ["always", "whenUnsure", "requested"]>;
161
161
  readonly confidence: Schema.NullOr<Schema.Number>;
162
162
  readonly turn_id: Schema.optionalKey<Schema.String>;
163
+ readonly requested: Schema.optionalKey<Schema.Struct<{
164
+ readonly note: Schema.optionalKey<Schema.String>;
165
+ readonly noted_by: Schema.String;
166
+ readonly basis: Schema.String;
167
+ }>>;
163
168
  }>;
164
169
  export type ReviewRequest = typeof ReviewRequest.Type;
165
170
  /**
@@ -1,6 +1,6 @@
1
1
  import { randomInt } from "node:crypto";
2
2
  import { Schema } from "effect";
3
- import { AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_PARTICIPANTS_LIMIT } from "../../agent-draft.js";
3
+ import { AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_NOTE_LIMIT, AGENT_DRAFT_PARTICIPANTS_LIMIT, } from "../../agent-draft.js";
4
4
  import { ChatChannelName } from "../../chat-channel.js";
5
5
  import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
6
6
  import { EMAIL_PATTERN } from "../../property.js";
@@ -238,8 +238,9 @@ export const ReviewRequest = Schema.Struct({
238
238
  description: "Record files the reply carries, in order, which the person may read: approval sends " +
239
239
  "the revision each holds now.",
240
240
  })),
241
- mode: Schema.Literals(["always", "whenUnsure"]).annotate({
242
- description: "Why the reply was held: every reply is reviewed, or the model was unsure.",
241
+ mode: Schema.Literals(["always", "whenUnsure", "requested"]).annotate({
242
+ description: "Why the reply was held: every reply is reviewed, the model was unsure, or a member or " +
243
+ "workflow asked for the draft (agent_chat.draft).",
243
244
  }),
244
245
  confidence: Schema.NullOr(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1))).annotate({
245
246
  description: "The decision model's probability that staff would send it as written.",
@@ -247,6 +248,17 @@ export const ReviewRequest = Schema.Struct({
247
248
  turn_id: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)).annotate({
248
249
  description: "The agent's turn that wrote the reply.",
249
250
  })),
251
+ requested: Schema.optionalKey(Schema.Struct({
252
+ note: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_NOTE_LIMIT))).annotate({ description: "What the requester asked the agent to write." }),
253
+ noted_by: Schema.String.check(Schema.isUUID()).annotate({
254
+ description: "The user who asked for the draft.",
255
+ }),
256
+ basis: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(128)).annotate({
257
+ description: "Where the chat stood when the draft was asked for, <time>~<id>.",
258
+ }),
259
+ })).annotate({
260
+ description: "A draft asked for with agent_chat.draft: who asked, their note, and the chat's place.",
261
+ }),
250
262
  });
251
263
  /**
252
264
  * `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
@@ -19,6 +19,7 @@ import { issueEvalToken } from "./eval-tokens.js";
19
19
  import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
20
20
  import { CHAT_RETENTION_DAYS } from "../../manifest.js";
21
21
  import { snapshotDraftFiles } from "../chat/draft-files.js";
22
+ import { parseChatCursor } from "../../runtime/chat-messages.js";
22
23
  import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
23
24
  import { identityToken } from "../operations.js";
24
25
  /** The agent's endpoints, under the ontology service's path. */
@@ -391,6 +392,17 @@ function holdReply(store, backend, manifest) {
391
392
  { path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
392
393
  ]);
393
394
  }
395
+ // A draft asked for names who asked, and only it does.
396
+ if ((body.mode === "requested") !== (body.requested !== undefined)) {
397
+ return invalidBody(requestId, [
398
+ { path: ["requested"], message: "A draft asked for, and only it, names its request." },
399
+ ]);
400
+ }
401
+ if (body.requested !== undefined && parseChatCursor(body.requested.basis) === undefined) {
402
+ return invalidBody(requestId, [
403
+ { path: ["requested", "basis"], message: "The chat's place is <time>~<id>." },
404
+ ]);
405
+ }
394
406
  const text = body.text ?? "";
395
407
  // A reply is its text, its files, or both.
396
408
  if (text.trim() === "" && body.files === undefined) {
@@ -456,6 +468,15 @@ function holdReply(store, backend, manifest) {
456
468
  mode: body.mode,
457
469
  confidence: body.confidence,
458
470
  ...(body.turn_id === undefined ? {} : { turnId: body.turn_id }),
471
+ ...(body.requested === undefined
472
+ ? {}
473
+ : {
474
+ requested: {
475
+ ...(body.requested.note === undefined ? {} : { note: body.requested.note }),
476
+ notedBy: body.requested.noted_by.toLowerCase(),
477
+ basis: body.requested.basis,
478
+ },
479
+ }),
459
480
  });
460
481
  if (review === undefined) {
461
482
  return toServerResponse(notFound(requestId, "The reply is for no active member."));
@@ -0,0 +1,42 @@
1
+ import { Effect } from "effect";
2
+ import type { ChatDraftInput } from "../../chat.js";
3
+ import { PermissionDenied, type ActionError } from "../../errors.js";
4
+ import type { Principal } from "../../runtime.js";
5
+ import type { CallerContext } from "../caller-context.js";
6
+ import type { OntologyBackend } from "../runtime-contract.js";
7
+ import type { AgentChannelTransport } from "./providers/provider.js";
8
+ import type { Destination } from "./resolve.js";
9
+ /** The permission that asks the agent for a draft in a chat. */
10
+ export declare const CHAT_DRAFT_PERMISSION = "agent_chat:draft";
11
+ /** The key prefix of a draft the agent writes on request: `request:<request>`. */
12
+ export declare const REQUESTED_DRAFT_KEY = "request:";
13
+ /** A private chat the inbox registered, as `agent_chat.send` and `postMessage` find it. */
14
+ export interface DraftChat {
15
+ readonly target: Destination;
16
+ readonly chatId: string;
17
+ readonly threadId: string | null;
18
+ }
19
+ /**
20
+ * Asks the agent to draft a reply in a person's private chat (`agent_chat.draft`), usually to a
21
+ * message it stayed silent on. The redraft session writes it: the agent's
22
+ * `POST /eve/segmentstream/v1/reviews/revise` starts a session of its own that acts as the person,
23
+ * reading only, with the chat and the requester's note, and holds its reply as a pending
24
+ * `agent_draft` keyed `request:<request>`, with mode `requested`. Nothing is sent, here or there:
25
+ * only an approval of that draft sends it. Nothing is recorded before the agent writes the draft,
26
+ * so a request the agent could not take leaves nothing behind.
27
+ */
28
+ export declare function chatDrafter(input: {
29
+ readonly agent: AgentChannelTransport;
30
+ readonly backend: OntologyBackend["Service"];
31
+ readonly principal: Principal;
32
+ readonly caller: CallerContext;
33
+ readonly requestId: string;
34
+ /** The private chat the inbox registered under the record, within the caller's scope. */
35
+ readonly inboxChat: (chat: string) => Effect.Effect<DraftChat | undefined, ActionError | PermissionDenied>;
36
+ /** The kind of the agent's channel `name`, such as telegram. */
37
+ readonly channelKind: (name: string) => string | undefined;
38
+ }): (request: ChatDraftInput) => Effect.Effect<{
39
+ request: `${string}-${string}-${string}-${string}-${string}`;
40
+ key: string;
41
+ message: string;
42
+ }, ActionError, never>;
@@ -0,0 +1,187 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Effect } from "effect";
3
+ import { ActionRejected, PermissionDenied } from "../../errors.js";
4
+ import { isAllowed } from "../../permissions.js";
5
+ import { chatCursorOf } from "../../runtime/chat-messages.js";
6
+ import { describeChatError } from "./diagnostics.js";
7
+ import { AGENT_REVISION_ROUTE } from "./review-revision.js";
8
+ /** The permission that asks the agent for a draft in a chat. */
9
+ export const CHAT_DRAFT_PERMISSION = "agent_chat:draft";
10
+ /** The key prefix of a draft the agent writes on request: `request:<request>`. */
11
+ export const REQUESTED_DRAFT_KEY = "request:";
12
+ /** How long the agent may take to accept the request; it writes the draft afterwards. */
13
+ const AGENT_DRAFT_TIMEOUT_MS = 15_000;
14
+ /** How far back the person's latest message is looked for. */
15
+ const LATEST_MESSAGES = 100;
16
+ /**
17
+ * The person's message a draft answers: one a person wrote in the chat, recorded as it reached the
18
+ * provider. The chat has one person, so a message recorded without its writer's user, as one that
19
+ * arrives while staff hold the chat is, is theirs; one recorded as another user's is not.
20
+ */
21
+ function answerable(message, person) {
22
+ return (message.direction === "inbound" &&
23
+ message.author === "human" &&
24
+ (message.userId === null || message.userId.toLowerCase() === person.toLowerCase()) &&
25
+ message.deletedAt === null &&
26
+ message.replacedBy === null);
27
+ }
28
+ /**
29
+ * Asks the agent to draft a reply in a person's private chat (`agent_chat.draft`), usually to a
30
+ * message it stayed silent on. The redraft session writes it: the agent's
31
+ * `POST /eve/segmentstream/v1/reviews/revise` starts a session of its own that acts as the person,
32
+ * reading only, with the chat and the requester's note, and holds its reply as a pending
33
+ * `agent_draft` keyed `request:<request>`, with mode `requested`. Nothing is sent, here or there:
34
+ * only an approval of that draft sends it. Nothing is recorded before the agent writes the draft,
35
+ * so a request the agent could not take leaves nothing behind.
36
+ */
37
+ export function chatDrafter(input) {
38
+ const { backend, principal, agent } = input;
39
+ const report = (phase, cause) => Effect.logWarning("ontology.agent_chat.draft_diagnostic").pipe(Effect.annotateLogs({
40
+ phase,
41
+ requestId: input.requestId,
42
+ error: describeChatError(cause, (value) => agent.identityToken ? value.split(agent.identityToken).join("[redacted]") : value),
43
+ }));
44
+ return (request) => Effect.gen(function* () {
45
+ if (!isAllowed(CHAT_DRAFT_PERMISSION, principal)) {
46
+ return yield* new PermissionDenied({
47
+ message: `${CHAT_DRAFT_PERMISSION} is required.`,
48
+ permission: CHAT_DRAFT_PERMISSION,
49
+ });
50
+ }
51
+ if (principal.kind === "guest") {
52
+ return yield* new PermissionDenied({ message: "The member is unknown." });
53
+ }
54
+ // The agent's own sessions answer in their chats, and its tasks have no chat: a task's
55
+ // workflow asks for the draft.
56
+ if (input.caller.kind === "runtime") {
57
+ return yield* new ActionRejected({
58
+ message: "The agent's sessions and tasks do not ask the agent for a draft.",
59
+ });
60
+ }
61
+ const requester = yield* backend
62
+ .get({ entity: "user", id: principal.id })
63
+ .pipe(Effect.mapError(() => new PermissionDenied({ message: "The requester is unknown." })));
64
+ if (requester.active !== true || requester.kind !== principal.kind) {
65
+ return yield* new PermissionDenied({ message: "The requester is inactive." });
66
+ }
67
+ const chat = yield* input.inboxChat(request.chat);
68
+ if (chat === undefined) {
69
+ return yield* new ActionRejected({
70
+ message: "Only a person's private chat the inbox registered is drafted in.",
71
+ });
72
+ }
73
+ const personId = chat.target.participantIds?.[0];
74
+ // The draft acts as the person, with the roles they hold now, as their own session does.
75
+ const person = personId === undefined || backend.agents === undefined
76
+ ? undefined
77
+ : yield* backend.agents.member(personId);
78
+ if (personId === undefined || person === undefined) {
79
+ return yield* new ActionRejected({
80
+ message: "The chat's person is no longer an active member.",
81
+ });
82
+ }
83
+ const store = backend.agents?.chatMessages;
84
+ if (store === undefined) {
85
+ return yield* new ActionRejected({
86
+ message: "Drafting a reply requires the workspace chat store.",
87
+ });
88
+ }
89
+ const channel = chat.target.provider;
90
+ const provider = input.channelKind(channel);
91
+ if (provider === undefined) {
92
+ return yield* new ActionRejected({
93
+ message: `The ontology's chat does not declare the channel ${channel}.`,
94
+ });
95
+ }
96
+ const coordinates = { channel, chatId: chat.chatId };
97
+ const recent = yield* store.read({ ...coordinates, limit: LATEST_MESSAGES });
98
+ const message = request.message === undefined
99
+ ? recent.messages.find((found) => answerable(found, personId))
100
+ : (yield* store.read({ ...coordinates, id: request.message, limit: 1 })).messages[0];
101
+ if (message === undefined || !answerable(message, personId)) {
102
+ return yield* new ActionRejected({
103
+ message: request.message === undefined
104
+ ? "The chat holds no message of its person to answer."
105
+ : "The message is no message of the chat's person.",
106
+ });
107
+ }
108
+ if (agent.origin === undefined || agent.identityToken === undefined) {
109
+ return yield* new ActionRejected({
110
+ message: "The agent drafts replies only on the production deployment.",
111
+ });
112
+ }
113
+ // The draft is written from the chat as it is now: a message the person writes after the
114
+ // newest one is newer than the draft.
115
+ const newest = recent.messages[0];
116
+ const id = randomUUID();
117
+ const replyTo = provider === "telegram" &&
118
+ message.messageId !== null &&
119
+ /^[1-9]\d*$/u.test(message.messageId)
120
+ ? message.messageId
121
+ : null;
122
+ const body = {
123
+ request: id,
124
+ ...(request.note === undefined ? {} : { note: request.note }),
125
+ noted_by: principal.id,
126
+ member_id: person.principal.id,
127
+ roles: person.principal.roles,
128
+ provider,
129
+ channel,
130
+ chat_id: chat.chatId,
131
+ thread_id: message.threadId,
132
+ chat_kind: "private",
133
+ // The message's files by what they are; the drafting session reads no file's content.
134
+ message: {
135
+ id: message.id,
136
+ at: message.at,
137
+ text: message.text,
138
+ files: message.files.map((file) => ({
139
+ ...(file.name === undefined ? {} : { name: file.name }),
140
+ ...(file.type === undefined ? {} : { type: file.type }),
141
+ ...(file.size === undefined ? {} : { size: file.size }),
142
+ })),
143
+ },
144
+ recipient: chat.target.external_id,
145
+ reply_thread_id: chat.threadId ?? "",
146
+ reply_to: replyTo,
147
+ basis: newest === undefined ? chatCursorOf(message) : chatCursorOf(newest),
148
+ };
149
+ const answered = yield* Effect.tryPromise(async () => {
150
+ const response = await agent.fetch(new Request(new URL(AGENT_REVISION_ROUTE, agent.origin), {
151
+ method: "POST",
152
+ headers: {
153
+ authorization: `Bearer ${agent.identityToken}`,
154
+ "content-type": "application/json",
155
+ },
156
+ body: JSON.stringify(body),
157
+ signal: AbortSignal.timeout(AGENT_DRAFT_TIMEOUT_MS),
158
+ }));
159
+ await response.body?.cancel();
160
+ return response.status;
161
+ }).pipe(Effect.exit);
162
+ if (answered._tag === "Failure") {
163
+ yield* report("call", answered.cause);
164
+ return yield* new ActionRejected({
165
+ message: "The agent could not be reached to draft a reply. Try again.",
166
+ });
167
+ }
168
+ // An agent from before drafts on request knows only redrafts, and refuses this request.
169
+ if (answered.value === 404 || answered.value === 400) {
170
+ return yield* new ActionRejected({
171
+ message: "The workspace's agent cannot draft replies on request: its @segmentstream/agent " +
172
+ "predates it.",
173
+ });
174
+ }
175
+ if (answered.value < 200 || answered.value >= 300) {
176
+ yield* report("answer", new Error(`The agent answered with status ${answered.value}.`));
177
+ return yield* new ActionRejected({
178
+ message: "The agent could not start drafting a reply. Try again.",
179
+ });
180
+ }
181
+ return {
182
+ request: id,
183
+ key: `${REQUESTED_DRAFT_KEY}${id}`,
184
+ message: message.id,
185
+ };
186
+ });
187
+ }
@@ -16,6 +16,7 @@ import { buttonLines } from "./providers/provider.js";
16
16
  import { reviewSender } from "./review-delivery.js";
17
17
  import { chatPeopleQuery, historyImporter } from "./history-import.js";
18
18
  import { reviewReviser } from "./review-revision.js";
19
+ import { CHAT_DRAFT_PERMISSION, chatDrafter } from "./chat-draft.js";
19
20
  import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
20
21
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
22
  /** The channels a runtime source can name, which a verified pairing's provider is one of. */
@@ -490,6 +491,15 @@ chats) {
490
491
  ...(context.backend.agents?.draftsNewer === undefined
491
492
  ? {}
492
493
  : { draftsNewer: draftsNewer(context, context.backend.agents.draftsNewer) }),
494
+ draft: chatDrafter({
495
+ agent: agentTransport,
496
+ backend: context.backend,
497
+ principal: context.principal,
498
+ caller: context.caller,
499
+ requestId: context.requestId,
500
+ inboxChat: (chat) => inboxChat(chat, CHAT_DRAFT_PERMISSION),
501
+ channelKind: (name) => chatKind(ontology.manifest.chat, name),
502
+ }),
493
503
  sendReview: reviewSender({
494
504
  ontology,
495
505
  connections,
@@ -114,7 +114,10 @@ export function reviewReviser(input) {
114
114
  member_id: person.principal.id,
115
115
  roles: person.principal.roles,
116
116
  session_id: String(review.session_id),
117
- key: String(first.key),
117
+ // A draft asked for in a chat is keyed by its request: its turn names the lookups it made.
118
+ key: first.mode === "requested" && text(first.turn_id) !== null
119
+ ? `${String(first.session_id)}:${String(first.turn_id)}`
120
+ : String(first.key),
118
121
  provider: String(review.channel_kind),
119
122
  channel: text(review.channel) ?? String(review.channel_kind),
120
123
  chat_id: String(review.chat_id),
@@ -4,6 +4,7 @@ import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { ActionRejected } from "../../errors.js";
5
5
  import { currentToolName } from "../../earlier-entity-names.js";
6
6
  import { DeploymentAdmissionError } from "../../deployment.js";
7
+ import { RuntimeDeployment } from "../../runtime/deployment.js";
7
8
  import { effectivePermissions } from "../../permissions.js";
8
9
  import { declaredChatRetentionDaysOf, encodeManifest } from "../../manifest.js";
9
10
  import { describeError, SCOPE_MISMATCH } from "../metric-query-platform.js";
@@ -831,6 +832,12 @@ export function mcpLayer(options) {
831
832
  const router = yield* HttpRouter.HttpRouter;
832
833
  const backend = yield* OntologyBackend;
833
834
  const warehouseQueries = yield* Effect.serviceOption(WarehouseQueries);
835
+ // Requests see only what is provided to them, as the warehouse is: whom a preview's agent may
836
+ // act for, and what a preview may run, depend on its deployment.
837
+ const deployment = yield* Effect.serviceOption(RuntimeDeployment);
838
+ const deployed = (effect) => Option.isSome(deployment)
839
+ ? Effect.provideService(effect, RuntimeDeployment, deployment.value)
840
+ : effect;
834
841
  const tools = mcpTools(options.built, options.chatHistory !== undefined, {
835
842
  attachments: backend.attachments !== undefined,
836
843
  files: backend.blobs !== undefined,
@@ -861,14 +868,14 @@ export function mcpLayer(options) {
861
868
  };
862
869
  const post = handlePost(server, options.verifyToken, options.verifyRuntime, backend, options.workspaceId);
863
870
  yield* router.add("POST", MCP_PATH, (request) => {
864
- const response = post(request);
871
+ const response = deployed(post(request));
865
872
  const served = Option.isSome(warehouseQueries)
866
873
  ? response.pipe(Effect.provideService(WarehouseQueries, warehouseQueries.value))
867
874
  : response;
868
875
  return served.pipe(Effect.map((response) => HttpServerResponse.setHeaders(response, CORS)));
869
876
  });
870
877
  yield* router.add("OPTIONS", MCP_PATH, PREFLIGHT);
871
- yield* router.add("GET", MCP_PATH, (request) => handleGet(request, options, backend).pipe(Effect.map((response) => HttpServerResponse.setHeaders(response, CORS))));
878
+ yield* router.add("GET", MCP_PATH, (request) => deployed(handleGet(request, options, backend)).pipe(Effect.map((response) => HttpServerResponse.setHeaders(response, CORS))));
872
879
  yield* router.add("DELETE", MCP_PATH, METHOD_NOT_ALLOWED);
873
880
  }));
874
881
  }
@@ -842,8 +842,17 @@ export interface HeldReplyInput {
842
842
  readonly text: string;
843
843
  /** Record files the reply carries, as the person could read them when it was held. */
844
844
  readonly files?: ReadonlyArray<AgentDraftFile>;
845
- readonly mode: "always" | "whenUnsure";
845
+ readonly mode: "always" | "whenUnsure" | "requested";
846
846
  readonly confidence: number | null;
847
+ /**
848
+ * A draft asked for with `agent_chat.draft`: who asked, their note, and where the chat stood,
849
+ * `<time>~<id>`, which is the draft's basis.
850
+ */
851
+ readonly requested?: {
852
+ readonly note?: string;
853
+ readonly notedBy: string;
854
+ readonly basis: string;
855
+ };
847
856
  /** The agent's turn that wrote the reply; absent from agents that predate it. */
848
857
  readonly turnId?: string;
849
858
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.165.1",
3
+ "version": "0.166.1",
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",