@segmentstream/ontology 0.133.0 → 0.135.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.135.0
4
+
5
+ `agent_chat.send` writes to a chat as the agent, without the sender attribution a post carries,
6
+ for a workflow or a member that writes first, such as a follow-up the workspace decides on. It
7
+ takes the chat, text and idempotency key as `postMessage` does, under its own grant,
8
+ `agent_chat:send`. The archive keeps the message as the agent's, with who asked for it, so the
9
+ person's next session reads it as the agent's. The agent's own sessions and its tasks cannot call
10
+ it: a task's workflow sends what the task wrote.
11
+
12
+ A message a chat's provider refuses says why in `refusal`: `outside_reply_window` (on WhatsApp the
13
+ person last wrote more than 24 hours ago), `recipient_unreachable` or `recipient_opted_out`. The
14
+ ontology's `ActionRejected` carries it, the action's 422 answers it as `refusal`, and the app SDK's
15
+ `SegmentStreamApiError` as `refusal`.
16
+
17
+ A post to a person's private chat named by channel and member is archived under the chat their
18
+ channel keys, the chat the inbox registered for them or the one they last wrote in, so their
19
+ chat's history and their session read it; on WhatsApp and Slack it was kept under their account.
20
+
21
+ A grant of `agent_chat:post_message` or `agent_chat:send` within a scope covers the registered
22
+ chats the scope holds, named by their record id. A person named by channel, or a group by its
23
+ title, is refused with it, since the scope could not be checked for them; posts by a group's title
24
+ were sent outside the scope before.
25
+
26
+ ## 0.134.0
27
+
28
+ The feedback guidance is one text in the ontology SDK. The MCP server's instructions carry it for a
29
+ caller who may submit feedback, and `app_feedback_submit`'s description now carries the same text,
30
+ with the workspace's policy: whether `feedback.automaticFailureReports` preauthorizes technical
31
+ failure reports, and whether files can be attached. The workspace agent reads its tools rather than
32
+ the server's instructions, so it now follows that policy too; before, it could not tell whether
33
+ the workspace preauthorized failure reports. The agent SDK's own copy of the feedback rules is
34
+ removed, and the `submit` action's description no longer states a policy of its own.
35
+
36
+ Upgrade the ontology and agent SDKs together, as `segmentstream upgrade` does: an agent on this
37
+ release beside an ontology from an earlier one has no feedback guidance.
38
+
3
39
  ## 0.133.0
4
40
 
5
41
  Every kind of connection declares verification values, and a connection may hold verification
@@ -57,6 +57,18 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
57
57
  readonly skipped: number;
58
58
  readonly expired: number;
59
59
  }>;
60
+ readonly send: import("./action.js").Action<Schema.Struct<{
61
+ readonly chat: Schema.String;
62
+ readonly text: Schema.String;
63
+ readonly replyTo: Schema.optionalKey<Schema.String>;
64
+ readonly idempotencyKey: Schema.String;
65
+ }>, {
66
+ readonly status: "sent" | "uncertain";
67
+ readonly message_id: string | null;
68
+ readonly url: string | null;
69
+ readonly duplicate: boolean;
70
+ readonly history_recorded: boolean;
71
+ }>;
60
72
  readonly postMessage: import("./action.js").Action<Schema.Struct<{
61
73
  readonly chat: Schema.String;
62
74
  readonly text: Schema.String;
@@ -200,6 +200,29 @@ export const AgentChat = entity("agent_chat", {
200
200
  return yield* delivery.value.importHistory(input);
201
201
  }),
202
202
  }),
203
+ send: action({
204
+ description: "Send a message to a chat as the agent, without the sender attribution a post carries: the " +
205
+ "person reads it as the agent's, and the archive keeps who asked for it. For a workflow or " +
206
+ "a member that writes first, such as a follow-up the workspace decides on. Same chat, text " +
207
+ "and idempotency key as postMessage; text is Markdown each channel renders natively. " +
208
+ "Refused for the agent's own sessions and its tasks: a task's workflow sends what the task " +
209
+ "wrote. Reuse the same idempotency key on replay; an uncertain operation is never resent. A " +
210
+ "message the provider refuses spends its key and says why in refusal: outside_reply_window " +
211
+ "(on WhatsApp the person last wrote more than 24 hours ago), recipient_unreachable or " +
212
+ "recipient_opted_out.",
213
+ input: ChatPostInput,
214
+ hints: { destructive: false, irreversible: true, idempotent: true },
215
+ connections: [],
216
+ prepare: ({ input }) => Effect.gen(function* () {
217
+ const delivery = yield* Effect.serviceOption(ChatDelivery);
218
+ if (Option.isNone(delivery) || delivery.value.send === undefined) {
219
+ return yield* new ActionRejected({
220
+ message: "Sending as the agent requires the authenticated ontology service.",
221
+ });
222
+ }
223
+ return yield* delivery.value.send(input);
224
+ }),
225
+ }),
203
226
  postMessage: action({
204
227
  description: "Post to an eligible chat ID or exact title. text is Markdown (bold, italic, code, lists, " +
205
228
  "[text](url)); each channel renders it natively and degrades constructs it can't show. " +
@@ -66,10 +66,7 @@ export const AppFeedback = entity("app_feedback", {
66
66
  }).actions((self) => ({
67
67
  submit: action({
68
68
  description: "Send the app's builders feedback for the member you act for: something no permitted tool or " +
69
- "data provides, a refused or failing operation, or a change they want. Offer it first, once per " +
70
- "problem, after checking their open app_feedback for the same subject; submit only when the " +
71
- "member agrees to the title and summary you showed them, unless the published workspace " +
72
- "feedback policy preauthorizes minimal technical failure reports during requested work.",
69
+ "data provides, a refused or failing operation, or a change they want.",
73
70
  hints: { destructive: false },
74
71
  input: Schema.Struct({
75
72
  title: p.text({ maxLength: 200, description: "What the feedback is about." }),
package/dist/chat.d.ts CHANGED
@@ -115,6 +115,8 @@ declare const ChatDelivery_base: Context.ServiceClass<ChatDelivery, "@segmentstr
115
115
  readonly preview: (input: ChatPostInput) => Effect.Effect<ChatPreview, ActionError>;
116
116
  readonly validate: (input: ChatPostInput) => Effect.Effect<void, ActionError>;
117
117
  readonly post: (input: ChatPostInput) => Effect.Effect<ChatPostResult, ActionError>;
118
+ /** Sends as the agent, without the requester's attribution, which the archive still keeps. */
119
+ readonly send?: (input: ChatPostInput) => Effect.Effect<ChatPostResult, ActionError>;
118
120
  /** Sends a reply a member approved, as the agent and without attribution, at most once. */
119
121
  readonly sendReview?: (input: ReviewSendInput) => Effect.Effect<ReviewSendResult, ActionError>;
120
122
  /** Asks the agent to redraft a reply it held for review, in a session of its own. */
package/dist/errors.d.ts CHANGED
@@ -64,6 +64,13 @@ declare const ActionRejected_base: Schema.Class<ActionRejected, Schema.TaggedStr
64
64
  * a client that is unsure whether its request took effect retries with the same key.
65
65
  */
66
66
  readonly keyConsumed: Schema.optionalKey<Schema.Literal<true>>;
67
+ /**
68
+ * Why a chat's provider refused a message, for code to act on: `outside_reply_window` (the person
69
+ * last wrote longer ago than the channel lets a free-form message reach them; WhatsApp takes a
70
+ * template), `recipient_unreachable` (the person blocked the sender or cannot receive it) or
71
+ * `recipient_opted_out` (the person stopped such messages).
72
+ */
73
+ readonly refusal: Schema.optionalKey<Schema.String>;
67
74
  }>, import("effect/Cause").YieldableError>;
68
75
  /**
69
76
  * An action refused the request for a business reason. The message is written for the caller and is
package/dist/errors.js CHANGED
@@ -41,6 +41,13 @@ export class ActionRejected extends Schema.TaggedError()("ActionRejected", {
41
41
  * a client that is unsure whether its request took effect retries with the same key.
42
42
  */
43
43
  keyConsumed: Schema.optionalKey(Schema.Literal(true)),
44
+ /**
45
+ * Why a chat's provider refused a message, for code to act on: `outside_reply_window` (the person
46
+ * last wrote longer ago than the channel lets a free-form message reach them; WhatsApp takes a
47
+ * template), `recipient_unreachable` (the person blocked the sender or cannot receive it) or
48
+ * `recipient_opted_out` (the person stopped such messages).
49
+ */
50
+ refusal: Schema.optionalKey(Schema.String),
44
51
  }) {
45
52
  }
46
53
  /**
@@ -7,6 +7,7 @@ import type { ConnectionTransportFactory } from "../connections.js";
7
7
  import type { OntologyBackend } from "../runtime-contract.js";
8
8
  import type { DeliveryArchive } from "./archive.js";
9
9
  import type { RuntimeChatEnvelope } from "./envelope.js";
10
+ import type { ChatArchiveTransport } from "../agent/chat-archive.js";
10
11
  import { type Destination } from "./resolve.js";
11
12
  import type { AgentChannelTransport } from "./providers/provider.js";
12
13
  import { type HistoryArchive } from "./history-import.js";
@@ -34,4 +35,6 @@ agent?: {
34
35
  readonly fetch?: AgentChannelTransport["fetch"];
35
36
  },
36
37
  /** The archive a chat's earlier history is imported to; without it nothing is. */
37
- history?: HistoryArchive): ChatDeliveryFactory;
38
+ history?: HistoryArchive,
39
+ /** The chat archive's reads, which find the chat a person writes from on a channel. */
40
+ chats?: ChatArchiveTransport): ChatDeliveryFactory;
@@ -42,7 +42,9 @@ export function makeChatDelivery(ontology, connections, archive, previews = {},
42
42
  */
43
43
  agent = {},
44
44
  /** The archive a chat's earlier history is imported to; without it nothing is. */
45
- history) {
45
+ history,
46
+ /** The chat archive's reads, which find the chat a person writes from on a channel. */
47
+ chats) {
46
48
  if (previews.settings) {
47
49
  validateTelegramPreviews(previews.settings);
48
50
  }
@@ -53,21 +55,33 @@ history) {
53
55
  const destination = ontology.manifest.chat?.telegram?.connection;
54
56
  const destinationPreviews = previews.settings?.connection === destination ? previews : { ownOrigins: previews.ownOrigins };
55
57
  return (context) => {
56
- const check = (input, approved = true) => Effect.gen(function* () {
57
- if (!isAllowed("agent_chat:post_message", context.principal)) {
58
+ /**
59
+ * A post's destination, requester and exact text. `asAgent` sends it as the agent, without the
60
+ * sender attribution, under `agent_chat:send`; the requester is still recorded with it.
61
+ */
62
+ const check = (input, approved = true, asAgent = false) => Effect.gen(function* () {
63
+ const permission = asAgent ? "agent_chat:send" : "agent_chat:post_message";
64
+ if (!isAllowed(permission, context.principal)) {
58
65
  return yield* new PermissionDenied({
59
- message: "agent_chat:post_message is required.",
60
- permission: "agent_chat:post_message",
66
+ message: `${permission} is required.`,
67
+ permission,
68
+ });
69
+ }
70
+ // The agent's own sessions answer through their channels, and its tasks have nobody to
71
+ // confirm what they send: a task's workflow sends what the task wrote.
72
+ if (asAgent && context.caller.kind === "runtime") {
73
+ return yield* new ActionRejected({
74
+ message: "The agent's sessions do not send as the agent: they answer in their chats.",
61
75
  });
62
76
  }
63
77
  const user = yield* context.backend.get({ entity: "user", id: context.principal.id });
64
78
  if (user.active !== true || user.kind !== context.principal.kind) {
65
79
  return yield* new PermissionDenied({ message: "The requester is inactive." });
66
80
  }
67
- const inbox = yield* inboxChat(input.chat);
81
+ const inbox = yield* inboxChat(input.chat, permission);
68
82
  // A member answers a person in the inbox from their own session in the app, signed with
69
83
  // their name as the workspace's attribution lays it out.
70
- const requester = inbox !== undefined &&
84
+ const requester = (inbox !== undefined || asAgent) &&
71
85
  context.caller.kind === "member" &&
72
86
  context.caller.subjectId === context.principal.id &&
73
87
  context.principal.kind === "member"
@@ -91,7 +105,33 @@ history) {
91
105
  const target = inbox?.target ??
92
106
  (yield* chatResolver(context.backend, context.principal, providers, {
93
107
  kindOf: (channel) => chatKind(ontology.manifest.chat, channel),
108
+ sending: permission,
94
109
  }).resolve(input.chat));
110
+ // A grant within a scope covers the registered chats it holds, named by their record:
111
+ // a person named by channel, or a group by its title, is outside what it can check.
112
+ const scope = effectiveScope(permission, context.principal);
113
+ if (scope !== undefined && inbox === undefined) {
114
+ if (!UUID.test(input.chat) || target.id !== input.chat) {
115
+ return yield* new PermissionDenied({
116
+ message: `A scoped ${permission} names the chat by its agent_chat record.`,
117
+ permission,
118
+ });
119
+ }
120
+ yield* context.backend
121
+ .get({
122
+ entity: "agent_chat",
123
+ id: input.chat,
124
+ reader: {
125
+ ...context.principal,
126
+ permissions: ["agent_chat:read"],
127
+ scopes: [{ permission: "agent_chat:read", where: scope }],
128
+ },
129
+ })
130
+ .pipe(Effect.mapError(() => new PermissionDenied({
131
+ message: `The chat is outside the chats ${permission} covers.`,
132
+ permission,
133
+ })));
134
+ }
95
135
  // A chat is a destination only on a channel the ontology declares a connection for; the
96
136
  // channel's kind sends it.
97
137
  const provider = channelProvider(ontology.manifest.chat, target.provider);
@@ -105,8 +145,10 @@ history) {
105
145
  message: "Chat posting requires a configured connection for the chat's provider.",
106
146
  });
107
147
  }
148
+ // The agent's own message carries no attribution, as a reply a member approved does not.
149
+ const signature = asAgent ? "" : requester.attribution;
108
150
  const { finalText, plainText } = yield* Effect.try({
109
- try: () => provider.render(input.text, requester.attribution, separator),
151
+ try: () => provider.render(input.text, signature, asAgent ? "" : separator),
110
152
  catch: (cause) => new ActionRejected({ message: "The Markdown could not be rendered.", cause }),
111
153
  });
112
154
  if (!input.text.trim() ||
@@ -125,7 +167,7 @@ history) {
125
167
  provider: target.provider,
126
168
  externalId: target.external_id,
127
169
  title: target.title,
128
- attribution: requester.attribution,
170
+ attribution: signature,
129
171
  text: input.text,
130
172
  finalText,
131
173
  replyTo,
@@ -157,7 +199,7 @@ history) {
157
199
  * a role may hold the post within a scope, which must hold the record. `undefined` for any
158
200
  * other chat, which the destinations resolve as before.
159
201
  */
160
- const inboxChat = (chat) => Effect.gen(function* () {
202
+ const inboxChat = (chat, permission = "agent_chat:post_message") => Effect.gen(function* () {
161
203
  if (!UUID.test(chat)) {
162
204
  return undefined;
163
205
  }
@@ -173,7 +215,7 @@ history) {
173
215
  if (record === undefined || record.kind !== "private") {
174
216
  return undefined;
175
217
  }
176
- const postable = effectiveScope("agent_chat:post_message", context.principal);
218
+ const postable = effectiveScope(permission, context.principal);
177
219
  if (postable !== undefined) {
178
220
  yield* context.backend
179
221
  .get({
@@ -186,8 +228,8 @@ history) {
186
228
  },
187
229
  })
188
230
  .pipe(Effect.mapError(() => new PermissionDenied({
189
- message: "The chat is outside the chats agent_chat:post_message covers.",
190
- permission: "agent_chat:post_message",
231
+ message: `The chat is outside the chats ${permission} covers.`,
232
+ permission,
191
233
  })));
192
234
  }
193
235
  // Its person, the chat's one member, takes part in what is posted there: without them the
@@ -222,6 +264,66 @@ history) {
222
264
  : null,
223
265
  };
224
266
  });
267
+ /**
268
+ * The chat a person's private destination is on, as its channel keys it, which differs from
269
+ * the account a post is sent to on WhatsApp and Slack: the chat the inbox registered for them
270
+ * on the channel, else the one they last wrote in, else none, and the post is kept under their
271
+ * account. A post kept there would be missing from their chat's history and their session.
272
+ */
273
+ const personalChat = (target) => Effect.gen(function* () {
274
+ const person = target.participantIds[0];
275
+ if (target.kind !== "private" || person === undefined) {
276
+ return undefined;
277
+ }
278
+ const registered = yield* context.backend
279
+ .find({
280
+ entity: "agent_chat",
281
+ query: {
282
+ where: {
283
+ and: [
284
+ { provider: { eq: target.provider } },
285
+ { kind: { eq: "private" } },
286
+ { members: { some: { id: { eq: person } } } },
287
+ ],
288
+ },
289
+ limit: 1,
290
+ },
291
+ })
292
+ .pipe(Effect.option);
293
+ const record = registered._tag === "Some"
294
+ ? registered.value.items.find((item) => item.kind === "private" && item.provider === target.provider)
295
+ : undefined;
296
+ if (record !== undefined) {
297
+ return {
298
+ chatId: String(record.external_id),
299
+ threadId: typeof record.thread_id === "string" && record.thread_id !== ""
300
+ ? record.thread_id
301
+ : null,
302
+ };
303
+ }
304
+ if (chats === undefined) {
305
+ return undefined;
306
+ }
307
+ // The person's private chats on the channel, newest first: the chat they last wrote in,
308
+ // by a message of theirs, which the channel keeps under its chat. A post kept under their
309
+ // account by a release before this one is no chat of theirs.
310
+ const page = yield* chats({
311
+ search: { provider: target.provider, limit: 50 },
312
+ principal: { id: person, kind: "member", roles: [], permissions: [] },
313
+ identityToken: context.identityToken,
314
+ }).pipe(Effect.option);
315
+ const latest = page._tag === "Some"
316
+ ? page.value.events.find((event) => event.kind === "inbound")
317
+ : undefined;
318
+ return typeof latest?.chatId === "string" && latest.chatId !== ""
319
+ ? {
320
+ chatId: latest.chatId,
321
+ threadId: typeof latest.threadId === "string" && latest.threadId !== ""
322
+ ? latest.threadId
323
+ : null,
324
+ }
325
+ : undefined;
326
+ });
225
327
  const report = (phase, cause) => Effect.logWarning("ontology.chat.delivery_diagnostic").pipe(Effect.annotateLogs({
226
328
  phase,
227
329
  requestId: context.requestId,
@@ -265,10 +367,16 @@ history) {
265
367
  }),
266
368
  preview: (input) => check(input, false).pipe(Effect.map(({ preview }) => preview)),
267
369
  validate: (input) => check(input).pipe(Effect.asVoid),
268
- post: (input) => Effect.gen(function* () {
269
- const { target, requester, connection, provider, preview, inbox } = yield* check(input);
370
+ post: (input) => deliver(input, false),
371
+ send: (input) => deliver(input, true),
372
+ };
373
+ /** One delivery: posted with its requester's attribution, or sent as the agent without it. */
374
+ function deliver(input, asAgent) {
375
+ return Effect.gen(function* () {
376
+ const { target, requester, connection, provider, preview, inbox } = yield* check(input, true, asAgent);
270
377
  // A member who answers in the inbox writes as themselves, not as the agent.
271
- const staff = inbox !== undefined && context.caller.kind === "member";
378
+ const staff = inbox !== undefined && context.caller.kind === "member" && !asAgent;
379
+ const place = inbox ?? (yield* personalChat(target));
272
380
  const operationId = context.envelope?.operation_id ?? randomUUID();
273
381
  const scope = deliveryScopeDigest({
274
382
  via: requester.via,
@@ -281,9 +389,9 @@ history) {
281
389
  eventId: `chat-delivery:${operationId}:reserve`,
282
390
  operationId,
283
391
  provider: target.provider,
284
- chatId: inbox?.chatId ?? target.external_id,
392
+ chatId: place?.chatId ?? target.external_id,
285
393
  chatType: target.kind,
286
- threadId: inbox?.threadId ?? null,
394
+ threadId: place?.threadId ?? null,
287
395
  participantIds: target.participantIds,
288
396
  senderId: staff ? requester.id : "agent",
289
397
  senderName: staff ? requester.name : "agent",
@@ -295,7 +403,7 @@ history) {
295
403
  turnId: null,
296
404
  // The claim binds text immutably. Keep the source here and the actual wire payload
297
405
  // in argsSummary, which can record the plain retry without changing that binding.
298
- text: `${input.text}${separator}${requester.attribution}`,
406
+ text: asAgent ? input.text : `${input.text}${separator}${requester.attribution}`,
299
407
  decision: null,
300
408
  reason: null,
301
409
  toolCallId: null,
@@ -366,7 +474,7 @@ history) {
366
474
  transport: connections({
367
475
  identityToken: context.identityToken,
368
476
  audit: {
369
- action: "agent_chat.post_message",
477
+ action: asAgent ? "agent_chat.send" : "agent_chat.post_message",
370
478
  principalId: context.principal.id,
371
479
  requestId: context.requestId,
372
480
  },
@@ -408,6 +516,7 @@ history) {
408
516
  return yield* new ActionRejected({
409
517
  message: "The provider refused the message. This operation key is consumed.",
410
518
  keyConsumed: true,
519
+ ...(outcome.refusal === undefined ? {} : { refusal: outcome.refusal }),
411
520
  });
412
521
  }
413
522
  return {
@@ -417,7 +526,7 @@ history) {
417
526
  duplicate: false,
418
527
  history_recorded: historyRecorded,
419
528
  };
420
- }),
421
- };
529
+ });
530
+ }
422
531
  };
423
532
  }
@@ -10,7 +10,11 @@ export interface ProviderOutcome {
10
10
  readonly messageId: string | null;
11
11
  readonly url: string | null;
12
12
  readonly cause?: unknown;
13
+ /** Why the provider refused a `failed` message, when it says: see `ActionRejected.refusal`. */
14
+ readonly refusal?: ChatRefusal;
13
15
  }
16
+ /** Why a chat's provider refused a message, for code to act on. */
17
+ export type ChatRefusal = "outside_reply_window" | "recipient_unreachable" | "recipient_opted_out";
14
18
  /**
15
19
  * How the service reaches the app's agent, which sends through a workspace channel: the
16
20
  * deployment's production origin and the service's Vercel OIDC token, each undefined outside
@@ -88,6 +88,8 @@ function attemptTelegram(input, payload) {
88
88
  messageId: null,
89
89
  url: null,
90
90
  cause: new Error(typeof body.description === "string" ? body.description : "Telegram refused the message."),
91
+ // A person who blocked the bot, or never started it, cannot be written to.
92
+ ...(result.value.status === 403 ? { refusal: "recipient_unreachable" } : {}),
91
93
  };
92
94
  }
93
95
  const message = record(body.result);
@@ -3,6 +3,16 @@ import { renderWhatsApp, WHATSAPP_MESSAGE_LIMIT } from "../../../whatsapp.js";
3
3
  import { record, transportFailure, } from "./provider.js";
4
4
  /** A WhatsApp id: the member's number, digits only. */
5
5
  const WA_ID = /^[1-9][0-9]{5,19}$/;
6
+ /**
7
+ * Meta's refusals that code acts on: 131047, the person last wrote more than 24 hours ago, so only a
8
+ * template reaches them; 131026, the message cannot be delivered to the number; 131050, the person
9
+ * stopped marketing messages.
10
+ */
11
+ const REFUSALS = {
12
+ 131047: "outside_reply_window",
13
+ 131026: "recipient_unreachable",
14
+ 131050: "recipient_opted_out",
15
+ };
6
16
  /** The id Meta gives an accepted message. */
7
17
  const WAMID = /^wamid\.[A-Za-z0-9+/=_-]{1,512}$/;
8
18
  /**
@@ -57,6 +67,7 @@ export function sendWhatsApp(input) {
57
67
  const explanation = [error.message, record(error.error_data).details]
58
68
  .filter((text) => typeof text === "string" && text !== "")
59
69
  .join(" ");
70
+ const refusal = REFUSALS[Number(error.code)];
60
71
  return {
61
72
  payload,
62
73
  status: "failed",
@@ -64,6 +75,7 @@ export function sendWhatsApp(input) {
64
75
  url: null,
65
76
  cause: new Error(`WhatsApp refused the message with code ${code}.` +
66
77
  (explanation === "" ? "" : ` ${explanation}`)),
78
+ ...(refusal === undefined ? {} : { refusal }),
67
79
  };
68
80
  }
69
81
  const id = record(Array.isArray(body.messages) ? body.messages[0] : undefined).id;
@@ -37,6 +37,8 @@ export declare function chatResolver(backend: OntologyBackend["Service"], princi
37
37
  readonly memberGroups?: boolean;
38
38
  /** The kind of each channel, whose identities reach its private chats; the name by default. */
39
39
  readonly kindOf?: (channel: string) => string | undefined;
40
+ /** The permission that sends to the destinations: posting by default, or sending as the agent. */
41
+ readonly sending?: "agent_chat:post_message" | "agent_chat:send";
40
42
  }): {
41
43
  list: (chat?: string) => Effect.Effect<Destination[], ActionRejected | PermissionDenied, never>;
42
44
  resolve: (chat: string) => Effect.Effect<Destination, ActionRejected | PermissionDenied, never>;
@@ -78,9 +78,10 @@ export function withChatMembership(transport, backend) {
78
78
  */
79
79
  export function chatResolver(backend, principal, providers, options = {}) {
80
80
  const kindOf = options.kindOf ?? ((channel) => channel);
81
- const canGroup = isAllowed("agent_chat:read", principal) || isAllowed("agent_chat:post_message", principal);
81
+ const sending = options.sending ?? "agent_chat:post_message";
82
+ const canGroup = isAllowed("agent_chat:read", principal) || isAllowed(sending, principal);
82
83
  const memberGroups = options.memberGroups === true && principal.kind === "member";
83
- const canDirectory = isAllowed("user:read", principal) || isAllowed("agent_chat:post_message", principal);
84
+ const canDirectory = isAllowed("user:read", principal) || isAllowed(sending, principal);
84
85
  const destinations = (chat) => Effect.gen(function* () {
85
86
  if (!canGroup && principal.kind !== "member") {
86
87
  return yield* denied();
@@ -490,7 +490,7 @@ export function expectedFailure(error, requestId) {
490
490
  };
491
491
  }
492
492
  if (Predicate.isTagged(error, "ActionRejected")) {
493
- const { message, keyConsumed } = error;
493
+ const { message, keyConsumed, refusal } = error;
494
494
  return {
495
495
  status: 422,
496
496
  body: {
@@ -501,6 +501,7 @@ export function expectedFailure(error, requestId) {
501
501
  ...batchDetails(error),
502
502
  ...limitDetails(error),
503
503
  ...(keyConsumed === true ? { key_consumed: true } : {}),
504
+ ...(typeof refusal === "string" ? { refusal } : {}),
504
505
  },
505
506
  };
506
507
  }
@@ -0,0 +1,16 @@
1
+ export declare const FEEDBACK_SUBMIT_TOOL = "app_feedback_submit";
2
+ export declare const FEEDBACK_ATTACH_TOOL = "app_feedback_file_attach";
3
+ /** The workspace's published feedback policy, as far as an agent's guidance depends on it. */
4
+ export interface FeedbackPolicy {
5
+ /** `feedback: { automaticFailureReports: true }`: technical failure reports need no consent. */
6
+ readonly automaticFailureReports: boolean;
7
+ /** Whether the caller can attach files to their feedback. */
8
+ readonly files: boolean;
9
+ }
10
+ /**
11
+ * How an agent handles app feedback, stated once for every client of the ontology: the MCP server's
12
+ * instructions carry it for a caller who may submit, and `app_feedback_submit`'s description carries
13
+ * it for clients that read tools rather than server instructions, such as the workspace agent. It is
14
+ * platform guidance for the model; the agent words what it tells the member in the chat's language.
15
+ */
16
+ export declare function feedbackGuidance(policy: FeedbackPolicy): string;
@@ -0,0 +1,37 @@
1
+ export const FEEDBACK_SUBMIT_TOOL = "app_feedback_submit";
2
+ export const FEEDBACK_ATTACH_TOOL = "app_feedback_file_attach";
3
+ const PURPOSE = "Feedback reaches the app's builders through app_feedback_submit: something no permitted tool, " +
4
+ "field or data provides, an operation refused for lack of permission, an operation that fails " +
5
+ "unexpectedly or a retryable failure that persists, or something the member says works badly or " +
6
+ "wants new. Do not send what you can do yourself; raise each problem once, and first reuse the " +
7
+ "member's open app_feedback with the same subject.";
8
+ const ASK_FIRST = "Offer it, and submit only after the member agrees to the title and summary you show them in " +
9
+ "their language.";
10
+ const AUTOMATIC = "During requested work, this workspace preauthorizes minimal technical failure reports: record " +
11
+ "an unexpected or persistent tool or connection failure without asking, with only the operation, " +
12
+ "a safe technical reason and the request_id or error code, never business contents, credentials " +
13
+ "or files. Then explain the actual reason and that the report was recorded, in one or two " +
14
+ "sentences, rather than offering to report it. A feature or change request, or sharing task " +
15
+ "contents or files, still needs the member's agreement to the title and summary you show them in " +
16
+ "their language.";
17
+ const RECORDED = "Never say feedback was recorded before a successful submission or a read of the existing item.";
18
+ const FILES = "Attach a screenshot or file with app_feedback_file_attach only when the member agreed to share it.";
19
+ const READ_OWN = "When the member asks about their feedback, read only their own, since builders can read " +
20
+ 'everyone\'s: app_feedback_find with where {"reporter": {"$me": []}}. Tell them the builders\' ' +
21
+ "response, then call app_feedback_acknowledge with its responded_at; acknowledge only a response " +
22
+ "you told them.";
23
+ /**
24
+ * How an agent handles app feedback, stated once for every client of the ontology: the MCP server's
25
+ * instructions carry it for a caller who may submit, and `app_feedback_submit`'s description carries
26
+ * it for clients that read tools rather than server instructions, such as the workspace agent. It is
27
+ * platform guidance for the model; the agent words what it tells the member in the chat's language.
28
+ */
29
+ export function feedbackGuidance(policy) {
30
+ return [
31
+ PURPOSE,
32
+ policy.automaticFailureReports ? AUTOMATIC : ASK_FIRST,
33
+ RECORDED,
34
+ ...(policy.files ? [FILES] : []),
35
+ READ_OWN,
36
+ ].join(" ");
37
+ }
@@ -18,12 +18,6 @@ export declare const MCP_PATH = "/mcp";
18
18
  /** The MCP revisions the server speaks, newest first. */
19
19
  export declare const MCP_PROTOCOL_VERSIONS: readonly ["2025-11-25", "2025-06-18"];
20
20
  export declare const MCP_STREAM_MAX_DURATION_MS = 45000;
21
- /**
22
- * When to offer feedback, for a caller who may send it. Platform guidance for the agent; the agent
23
- * words the offer itself, in the chat's language.
24
- */
25
- export declare const FEEDBACK_INSTRUCTIONS: string;
26
- export declare const AUTOMATIC_FAILURE_REPORT_INSTRUCTIONS: string;
27
21
  export interface McpServerOptions {
28
22
  readonly navigation?: PageCatalogV1;
29
23
  readonly appOrigins?: readonly string[] | undefined;
@@ -39,6 +39,7 @@ import { uploadFields } from "../../storage/attachments.js";
39
39
  import { RECORDS_OR_METRIC_QUERIES } from "../../render.js";
40
40
  import { memberFileOperations } from "../member-files.js";
41
41
  import { ACTION_OPTIONS_ARGUMENT, mcpTools, RUNTIME_SOURCE_META, visibleTools, } from "./tools.js";
42
+ import { FEEDBACK_ATTACH_TOOL, FEEDBACK_SUBMIT_TOOL, feedbackGuidance, } from "./feedback-guidance.js";
42
43
  import { listTools, toolDefinition } from "./listing.js";
43
44
  /** The URL path of the ontology's MCP server, outside `/api/ontology`: one per app. */
44
45
  export const MCP_PATH = "/mcp";
@@ -624,28 +625,6 @@ function readResource({ built, tools }, uri) {
624
625
  }
625
626
  });
626
627
  }
627
- /**
628
- * When to offer feedback, for a caller who may send it. Platform guidance for the agent; the agent
629
- * words the offer itself, in the chat's language.
630
- */
631
- export const FEEDBACK_INSTRUCTIONS = "Feedback: this app accepts feedback for its builders. Offer to send it when the user wants " +
632
- "something no permitted tool, field or data provides, an operation is refused for lack of " +
633
- "permission, an operation fails unexpectedly or a retryable failure persists, or the user says " +
634
- "something works badly or asks for something new. Do not offer what you can do yourself; offer " +
635
- "once per problem. Before submitting, look for the user's open app_feedback with the same " +
636
- "subject. Submit with app_feedback_submit only after the user agrees to the title and summary you " +
637
- "show in their language. When the user asks about their feedback, read only their own, since " +
638
- 'builders can read everyone\'s: app_feedback_find with where {"reporter": {"$me": []}}. Tell ' +
639
- "them the builders' response, then call app_feedback_acknowledge with its responded_at.";
640
- export const AUTOMATIC_FAILURE_REPORT_INSTRUCTIONS = "Feedback: During requested work, this workspace preauthorizes minimal technical failure reports. " +
641
- "Automatically record unexpected or persistent tool/connection failures through app_feedback_submit; " +
642
- "first reuse the caller's open report with the same subject. Include only the operation, safe technical " +
643
- "reason and request_id/error code, never business contents, credentials or files. Explain the actual " +
644
- "reason and that the report was recorded in one or two sentences; do not merely offer to report it, " +
645
- "and never claim it was recorded before a successful submission or existing-item read. " +
646
- "Feature/change requests and sharing task contents or files still require the member's agreement " +
647
- "to the title and summary. Asked about their feedback, read only the caller's own items " +
648
- '(where {"reporter": {"$me": []}}) and acknowledge only the response you relayed.';
649
628
  /**
650
629
  * Fixed guidance keeps initialization independent of ontology size: the feedback paragraph depends
651
630
  * only on whether the caller may run `app_feedback_submit`.
@@ -672,14 +651,7 @@ function instructions(feedback, files, automaticFailureReports, byMeaning, metri
672
651
  "external actions (openWorldHint) require confirmation before preparation; idempotence " +
673
652
  "alone does not waive it. Present confirmations in the chat's language using " +
674
653
  "action, entity, field and option labels and readable record titles, never tool names, ids or JSON.",
675
- ...(feedback
676
- ? [
677
- (automaticFailureReports
678
- ? AUTOMATIC_FAILURE_REPORT_INSTRUCTIONS
679
- : FEEDBACK_INSTRUCTIONS) +
680
- (files ? " Add each screenshot or file with app_feedback_file_attach." : ""),
681
- ]
682
- : []),
654
+ ...(feedback ? [`Feedback: ${feedbackGuidance({ automaticFailureReports, files })}`] : []),
683
655
  ].join("\n\n");
684
656
  }
685
657
  function negotiate(requested) {
@@ -709,7 +681,7 @@ function dispatch(server, message, request) {
709
681
  title: "Ontology",
710
682
  version: server.built.plan.ontology.manifest.hash,
711
683
  },
712
- instructions: instructions(visibleTools(server.tools, principal, caller).some((tool) => tool.name === "app_feedback_submit"), visibleTools(server.tools, principal, caller).some((tool) => tool.name === "app_feedback_file_attach"), server.built.plan.ontology.manifest.feedback?.automaticFailureReports === true, server.built.plan.ontology.config.discovery !== undefined, visibleTools(server.tools, principal, caller).some((tool) => tool.name === "query_metrics")),
684
+ instructions: instructions(visibleTools(server.tools, principal, caller).some((tool) => tool.name === FEEDBACK_SUBMIT_TOOL), visibleTools(server.tools, principal, caller).some((tool) => tool.name === FEEDBACK_ATTACH_TOOL), server.built.plan.ontology.manifest.feedback?.automaticFailureReports === true, server.built.plan.ontology.config.discovery !== undefined, visibleTools(server.tools, principal, caller).some((tool) => tool.name === "query_metrics")),
713
685
  });
714
686
  case "ping":
715
687
  return rpcResult(id, {});
@@ -18,6 +18,7 @@ import { actionDescription, requires } from "../descriptions.js";
18
18
  import { DiscoverInput, DiscoverToolOutput } from "../discovery-schemas.js";
19
19
  import { DIMENSIONS_LIMIT, hasMetrics, VALUES_DEFAULT, VALUES_LIMIT } from "./metric-tools.js";
20
20
  import { isReadScoped } from "../toolsets.js";
21
+ import { FEEDBACK_ATTACH_TOOL, FEEDBACK_SUBMIT_TOOL, feedbackGuidance, } from "./feedback-guidance.js";
21
22
  import { NavigationInput, NavigationToolOutput } from "../navigation-schemas.js";
22
23
  import { METRIC_QUERY_FILTER_OPERATORS, METRIC_QUERY_GRANULARITIES, METRIC_QUERY_LIMITS, METRIC_QUERY_PERIOD_UNITS, METRIC_QUERY_PERIODS, HistoryPage, MAXIMUM_TIMEZONE_LENGTH, Me, } from "../schemas.js";
23
24
  const DEFS = "#/$defs/";
@@ -748,6 +749,19 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
748
749
  for (const toolset of built.plan.ontology.toolsets ?? []) {
749
750
  tools.push(...toolset.tools.map((tool) => toolsetTool(toolset, tool)));
750
751
  }
752
+ const submit = tools.findIndex((tool) => tool.name === FEEDBACK_SUBMIT_TOOL);
753
+ // Clients that read tools rather than the server's instructions, such as the workspace agent, learn
754
+ // the workspace's feedback policy where they learn the tool.
755
+ if (submit >= 0) {
756
+ const guidance = feedbackGuidance({
757
+ automaticFailureReports: manifest.feedback?.automaticFailureReports === true,
758
+ files: tools.some((tool) => tool.name === FEEDBACK_ATTACH_TOOL),
759
+ });
760
+ tools[submit] = {
761
+ ...tools[submit],
762
+ description: `${tools[submit].description}\n\n${guidance}`,
763
+ };
764
+ }
751
765
  const discover = tools.findIndex((tool) => tool.name === "discover");
752
766
  // Word search duplicates the client's own tool search; ranking by meaning does not.
753
767
  if (discover >= 0) {
@@ -223,11 +223,11 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
223
223
  : call.input;
224
224
  // A chat post needs its requester's confirmation, and a task has none (spec decision 7).
225
225
  if (planned.name === "agent_chat" &&
226
- name === "post_message" &&
226
+ (name === "post_message" || name === "send") &&
227
227
  principal.authenticatedVia === AGENT_TASK_AUTHENTICATION) {
228
228
  return yield* new ActionRejected({
229
- message: "Agent tasks cannot post to chat in this release: agent_chat.post_message is refused " +
230
- "for a task whatever its workflow's role grants.",
229
+ message: `Agent tasks cannot post to chat in this release: agent_chat.${name} is refused ` +
230
+ "for a task whatever its workflow's role grants; the workflow sends what the task wrote.",
231
231
  });
232
232
  }
233
233
  if (planned.name === "agent_chat" && name === "post_message" && caller.kind === "runtime") {
@@ -614,6 +614,8 @@ export const ErrorSchemas = {
614
614
  limit: Schema.optionalKey(LimitErrorWire),
615
615
  // The idempotency key is spent on an operation that did not happen: retry with a new one.
616
616
  key_consumed: Schema.optionalKey(Schema.Literal(true)),
617
+ // Why a chat's provider refused a message, such as outside_reply_window.
618
+ refusal: Schema.optionalKey(Schema.String),
617
619
  }),
618
620
  rateLimited: errorBody("RateLimited", 429, ["rate_limited"]),
619
621
  internal: errorBody("InternalError", 500, ["internal_error"]),
@@ -344,13 +344,13 @@ export function createOntologyService(ontology, config) {
344
344
  ? deployedConnections(config)
345
345
  : localConnections(config.localConnections)));
346
346
  const replicate = deployedReplication(config);
347
+ const chatHistory = config.runtimeIdentity === undefined ? undefined : platformChatArchive(config);
347
348
  const chatDelivery = makeChatDelivery(ontology, connections, config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
348
349
  // The app's agent sends through a workspace channel, at the origin it takes its tasks at.
349
350
  {
350
351
  origin: config.agentOrigin,
351
352
  ...(config.agentTaskTransport === undefined ? {} : { fetch: config.agentTaskTransport }),
352
- }, config.chatHistoryArchive ?? platformHistoryArchive(config));
353
- const chatHistory = config.runtimeIdentity === undefined ? undefined : platformChatArchive(config);
353
+ }, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
354
354
  const metricQueries = makeMetricQueries({
355
355
  ontology,
356
356
  transport: platformMetricQueries({ ...config, manifestHash: ontology.manifest.hash }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.133.0",
3
+ "version": "0.135.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",