@segmentstream/ontology 0.98.0 → 0.99.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.
Files changed (46) hide show
  1. package/README.md +8 -5
  2. package/dist/agent-review.d.ts +4 -4
  3. package/dist/agent-review.js +10 -10
  4. package/dist/app-feedback.js +1 -1
  5. package/dist/groups.d.ts +11 -4
  6. package/dist/groups.js +54 -11
  7. package/dist/permissions.d.ts +1 -1
  8. package/dist/permissions.js +1 -1
  9. package/dist/runtime-source.js +3 -3
  10. package/dist/service/agent/{conversation-routes.d.ts → archive-routes.d.ts} +7 -4
  11. package/dist/service/agent/{conversation-routes.js → archive-routes.js} +8 -5
  12. package/dist/service/agent/attachments.d.ts +2 -2
  13. package/dist/service/agent/attachments.js +2 -2
  14. package/dist/service/agent/authentication.d.ts +1 -1
  15. package/dist/service/agent/authentication.js +7 -5
  16. package/dist/service/agent/{conversations.d.ts → chat-archive.d.ts} +11 -11
  17. package/dist/service/agent/{conversations.js → chat-archive.js} +12 -12
  18. package/dist/service/agent/protocol.js +2 -2
  19. package/dist/service/chat/archive.d.ts +2 -2
  20. package/dist/service/chat/archive.js +1 -1
  21. package/dist/service/chat/attribution.d.ts +1 -1
  22. package/dist/service/chat/delivery.d.ts +2 -2
  23. package/dist/service/chat/delivery.js +2 -2
  24. package/dist/service/chat/idempotency.d.ts +3 -3
  25. package/dist/service/chat/reads.d.ts +3 -3
  26. package/dist/service/chat/reads.js +10 -10
  27. package/dist/service/chat/resolve.d.ts +6 -6
  28. package/dist/service/chat/resolve.js +7 -7
  29. package/dist/service/chat/review-delivery.d.ts +1 -1
  30. package/dist/service/chat/review-delivery.js +4 -4
  31. package/dist/service/chat/routes.d.ts +2 -2
  32. package/dist/service/chat/routes.js +7 -7
  33. package/dist/service/errors.js +3 -3
  34. package/dist/service/mcp/server.d.ts +3 -3
  35. package/dist/service/mcp/server.js +20 -16
  36. package/dist/service/mcp/tools.d.ts +2 -2
  37. package/dist/service/mcp/tools.js +12 -14
  38. package/dist/service/member-file-routes.js +26 -2
  39. package/dist/service/member-files.d.ts +7 -7
  40. package/dist/service/member-files.js +2 -2
  41. package/dist/service/service.js +9 -9
  42. package/dist/storage/attachments.d.ts +3 -3
  43. package/dist/storage/attachments.js +16 -15
  44. package/dist/storage/tables.d.ts +4 -0
  45. package/dist/storage/tables.js +4 -0
  46. package/package.json +1 -1
package/README.md CHANGED
@@ -1508,9 +1508,9 @@ history_recorded }`; private chats may have no URL. A receipt-write failure leav
1508
1508
  cannot authorize delivery. Local provider proxies alone cannot replace the production archive.
1509
1509
 
1510
1510
  `chat_history({ chat, before?, limit? })` and `chat_search` read the archive with independent
1511
- conversation authorization: a member reads the group chats they are in (the chat's `members`,
1511
+ chat authorization: a member reads the group chats they are in (the chat's `members`,
1512
1512
  like its attachments), `agent_chat:read` reads every group, and a private chat is read by its
1513
- participant. A posting service cannot read member conversations. The canonical
1513
+ participant. A posting service cannot read member chats. The canonical
1514
1514
  REST facade is `/api/ontology/chat/{list,history,search,actions/post_message}`; the post action
1515
1515
  uses the standard `{ input, options?: { validate_only? } }` envelope and action response.
1516
1516
  Validation checks eligibility and exact text without reserving or sending.
@@ -1543,7 +1543,7 @@ it has no document relay fields.
1543
1543
  `GET /api/ontology/agent/files/:entity/:id[/:property]` returns `{ file, download }` for the
1544
1544
  current file property of an ontology record. Like temporary attachment routes, it requires a
1545
1545
  production runtime bearer token, `X-SegmentStream-Act-As` naming an active paired member,
1546
- and the agent conversation/session headers. It checks `<entity>:read` before returning metadata
1546
+ and the agent chat/session headers. It checks `<entity>:read` before returning metadata
1547
1547
  and rechecks live permissions when granting a download pinned to that revision. The response is
1548
1548
  uncached; the download grant is short lived. Without a property the entity must have exactly one
1549
1549
  file property. Missing records/files return `not_found`, missing read access `forbidden`, and
@@ -1564,8 +1564,11 @@ table exists on deployments with file storage; the migration adds it beside the
1564
1564
  to a database an earlier SDK migrated.
1565
1565
 
1566
1566
  Only the agent calls these routes, with its runtime token, `X-SegmentStream-Act-As`, the chat in
1567
- `X-SegmentStream-Agent-Conversation` (`telegram:<chat id>`) and, inside a turn, the session in
1568
- `X-SegmentStream-Agent-Session`. Another member's attachment, another chat's or another
1567
+ `X-SegmentStream-Agent-Chat` (`telegram:<chat id>`) and, inside a turn, the session in
1568
+ `X-SegmentStream-Agent-Session`. Agents built before name the chat in
1569
+ `X-SegmentStream-Agent-Conversation`, which the service still reads.
1570
+ <!-- @legacy agent.conversation-header --> Another member's attachment, another chat's or another
1571
+
1569
1572
  session's answers 404; an expired or discarded one answers 409; a deactivated member's 403.
1570
1573
 
1571
1574
  | Route | Does |
@@ -1,12 +1,12 @@
1
1
  import { Schema } from "effect";
2
2
  /**
3
3
  * A reply the workspace's agent held for review. `agent/segmentstream.json` says, per role of the
4
- * person the agent replies to, whether a member reviews its replies (`conversations.*.review`);
4
+ * person the agent replies to, whether a member reviews its replies (`chats.*.review`);
5
5
  * the agent records each reply it holds here, and only the actions below change it. Approving sends
6
- * the reply, or the member's edit of it, to the person's conversation as the agent, without the
6
+ * the reply, or the member's edit of it, to the person's chat as the agent, without the
7
7
  * sender attribution a chat post carries, at most once; rejecting discards it. Reading, approving
8
8
  * and rejecting each need a permission that names `agent_review`: an entity wildcard does not cover
9
- * it, since its records hold the workspace's conversations with the people it serves.
9
+ * it, since its records hold the workspace's chats with the people it serves.
10
10
  */
11
11
  export declare const AGENT_REVIEW_STATUSES: readonly [{
12
12
  readonly value: "pending";
@@ -26,7 +26,7 @@ export declare const AGENT_REVIEW_STATUSES: readonly [{
26
26
  }];
27
27
  export declare const AGENT_REVIEW_MODES: readonly [{
28
28
  readonly value: "always";
29
- readonly description: "Every reply in the conversation waits for a member.";
29
+ readonly description: "Every reply in the chat waits for a member.";
30
30
  }, {
31
31
  readonly value: "whenUnsure";
32
32
  readonly description: "The decision model was not sure enough that staff would send it as written.";
@@ -7,12 +7,12 @@ import { p } from "./property.js";
7
7
  import { rel } from "./relationship.js";
8
8
  /**
9
9
  * A reply the workspace's agent held for review. `agent/segmentstream.json` says, per role of the
10
- * person the agent replies to, whether a member reviews its replies (`conversations.*.review`);
10
+ * person the agent replies to, whether a member reviews its replies (`chats.*.review`);
11
11
  * the agent records each reply it holds here, and only the actions below change it. Approving sends
12
- * the reply, or the member's edit of it, to the person's conversation as the agent, without the
12
+ * the reply, or the member's edit of it, to the person's chat as the agent, without the
13
13
  * sender attribution a chat post carries, at most once; rejecting discards it. Reading, approving
14
14
  * and rejecting each need a permission that names `agent_review`: an entity wildcard does not cover
15
- * it, since its records hold the workspace's conversations with the people it serves.
15
+ * it, since its records hold the workspace's chats with the people it serves.
16
16
  */
17
17
  export const AGENT_REVIEW_STATUSES = [
18
18
  { value: "pending", description: "Waiting for a member to approve, edit or reject it." },
@@ -25,7 +25,7 @@ export const AGENT_REVIEW_STATUSES = [
25
25
  { value: "rejected", description: "Rejected: the person never sees it." },
26
26
  ];
27
27
  export const AGENT_REVIEW_MODES = [
28
- { value: "always", description: "Every reply in the conversation waits for a member." },
28
+ { value: "always", description: "Every reply in the chat waits for a member." },
29
29
  {
30
30
  value: "whenUnsure",
31
31
  description: "The decision model was not sure enough that staff would send it as written.",
@@ -39,7 +39,7 @@ export const AgentReview = entity("agent_review", {
39
39
  plural: "Agent reply reviews",
40
40
  title: "draft",
41
41
  description: "A reply the agent wrote to a person and held for a member to review, as the workspace's " +
42
- "conversations settings ask. Approve it, with an edit if needed, to send it to the person as " +
42
+ "chats settings ask. Approve it, with an edit if needed, to send it to the person as " +
43
43
  "the agent; reject it to discard it.",
44
44
  writes: "actions",
45
45
  properties: {
@@ -50,19 +50,19 @@ export const AgentReview = entity("agent_review", {
50
50
  description: "The agent's key for the reply, so a repeated report holds it once.",
51
51
  }),
52
52
  provider: p.text({ managed: true, description: "The channel, for example telegram." }),
53
- chatId: p.text({ managed: true, description: "The conversation's id at the provider." }),
53
+ chatId: p.text({ managed: true, description: "The chat's id at the provider." }),
54
54
  recipient: p.text({
55
55
  managed: true,
56
56
  description: "Whom the provider sends the reply to: the chat's id, or the person's number on WhatsApp.",
57
57
  }),
58
58
  chatKind: p.select([
59
- { value: "private", description: "The person's own conversation with the agent." },
59
+ { value: "private", description: "The person's own chat with the agent." },
60
60
  { value: "group", description: "A group chat." },
61
- ], { managed: true, label: "Chat kind", description: "Whether the conversation is a group." }),
61
+ ], { managed: true, label: "Chat kind", description: "Whether the chat is a group." }),
62
62
  threadId: p.text({
63
63
  optional: true,
64
64
  managed: true,
65
- description: "The thread or topic of the conversation, when it has one.",
65
+ description: "The thread or topic of the chat, when it has one.",
66
66
  }),
67
67
  replyTo: p.text({
68
68
  optional: true,
@@ -94,7 +94,7 @@ export const AgentReview = entity("agent_review", {
94
94
  min: 0,
95
95
  max: 1,
96
96
  description: "The decision model's probability that staff would send the reply as written; empty " +
97
- "when the conversation holds every reply or the model gave none.",
97
+ "when the chat holds every reply or the model gave none.",
98
98
  }),
99
99
  messageId: p.text({
100
100
  optional: true,
@@ -118,7 +118,7 @@ export const AppFeedback = entity("app_feedback", {
118
118
  acknowledge: action({
119
119
  description: "Record that the member has been told the builders' response to their feedback, passing the " +
120
120
  "responded_at of the response you reported. Find their feedback with responded_at set and " +
121
- "seen_at empty at the start of a conversation, tell them what was done, then call this. " +
121
+ "seen_at empty at the start of a chat, tell them what was done, then call this. " +
122
122
  "acknowledged is false when there is no such response, as when the builders answered again " +
123
123
  "meanwhile: read the item again and report the newer response.",
124
124
  hints: { destructive: false, idempotent: true },
package/dist/groups.d.ts CHANGED
@@ -37,7 +37,7 @@ export interface SmartPolicyInput {
37
37
  readonly gapSeconds?: number;
38
38
  };
39
39
  readonly followUpMinutes?: number;
40
- readonly conversationMinutes?: number;
40
+ readonly engagementMinutes?: number;
41
41
  readonly openQuestionMinutes?: number | "unlimited";
42
42
  readonly addresseeGate?: boolean;
43
43
  };
@@ -51,12 +51,12 @@ export interface SmartPolicyInput {
51
51
  readonly neutral?: number;
52
52
  readonly humanThread?: number;
53
53
  /**
54
- * Conversation policy: the agent answers when the decision model gives at least this
54
+ * Chat policy: the agent answers when the decision model gives at least this
55
55
  * probability that it is addressed and that a reply is needed (0.5..1, default 0.5).
56
56
  */
57
57
  readonly reply?: number;
58
58
  /**
59
- * Conversation policy: a message below `reply` but at or above `defer` still reaches the
59
+ * Chat policy: a message below `reply` but at or above `defer` still reaches the
60
60
  * agent, which answers or calls `no_reply`; so does a message the decision model could not
61
61
  * classify. Defaults to `reply`, which leaves no such band.
62
62
  */
@@ -89,7 +89,14 @@ export interface GroupPolicyIssue {
89
89
  readonly message: string;
90
90
  readonly path: ReadonlyArray<string>;
91
91
  }
92
+ /**
93
+ * @legacy agent.conversation-routing-names
94
+ * `groups` with the names its routing settings had before the chat policy took its name: policy
95
+ * `conversation` reads as `chat`, and `engagement.conversationMinutes` as `engagementMinutes`, at
96
+ * the top level, in every chat and in the shadow policy. Anything else is returned as it is.
97
+ */
98
+ export declare function currentGroupPolicyInput<T>(value: T): T;
92
99
  /** Strict validation of the `groups` section that `agent/segmentstream.json` authors. */
93
- export declare function groupPolicyIssues(value: unknown): ReadonlyArray<GroupPolicyIssue>;
100
+ export declare function groupPolicyIssues(authored: unknown): ReadonlyArray<GroupPolicyIssue>;
94
101
  /** Expand authored files before bundling. The caller owns the workspace-relative filesystem boundary. */
95
102
  export declare function expandGroupFiles(input: GroupPolicyInput, read: (path: string) => string): GroupPolicyInput;
package/dist/groups.js CHANGED
@@ -1,6 +1,51 @@
1
1
  const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2
+ /**
3
+ * @legacy agent.conversation-routing-names
4
+ * `groups` with the names its routing settings had before the chat policy took its name: policy
5
+ * `conversation` reads as `chat`, and `engagement.conversationMinutes` as `engagementMinutes`, at
6
+ * the top level, in every chat and in the shadow policy. Anything else is returned as it is.
7
+ */
8
+ export function currentGroupPolicyInput(value) {
9
+ const smart = (input) => {
10
+ if (!object(input) || !object(input.engagement)) {
11
+ return input;
12
+ }
13
+ const { conversationMinutes, ...engagement } = input.engagement;
14
+ return {
15
+ ...input,
16
+ engagement: {
17
+ ...engagement,
18
+ ...(engagement.policy === "conversation" ? { policy: "chat" } : {}),
19
+ ...(conversationMinutes === undefined || engagement.engagementMinutes !== undefined
20
+ ? {}
21
+ : { engagementMinutes: conversationMinutes }),
22
+ },
23
+ };
24
+ };
25
+ if (!object(value)) {
26
+ return value;
27
+ }
28
+ return {
29
+ ...value,
30
+ ...(value.smart === undefined ? {} : { smart: smart(value.smart) }),
31
+ ...(object(value.chats)
32
+ ? {
33
+ chats: Object.fromEntries(Object.entries(value.chats).map(([key, chat]) => [
34
+ key,
35
+ object(chat) && chat.smart !== undefined
36
+ ? { ...chat, smart: smart(chat.smart) }
37
+ : chat,
38
+ ])),
39
+ }
40
+ : {}),
41
+ ...(object(value.observability) && value.observability.shadow !== undefined
42
+ ? { observability: { ...value.observability, shadow: smart(value.observability.shadow) } }
43
+ : {}),
44
+ };
45
+ }
2
46
  /** Strict validation of the `groups` section that `agent/segmentstream.json` authors. */
3
- export function groupPolicyIssues(value) {
47
+ export function groupPolicyIssues(authored) {
48
+ const value = currentGroupPolicyInput(authored);
4
49
  const issues = [];
5
50
  const issue = (path, message) => issues.push({ path, message });
6
51
  function section(value, path, keys) {
@@ -102,7 +147,7 @@ export function groupPolicyIssues(value) {
102
147
  const e = section(s.engagement, [...path, "engagement"], [
103
148
  "policy",
104
149
  "followUpMinutes",
105
- "conversationMinutes",
150
+ "engagementMinutes",
106
151
  "openQuestionMinutes",
107
152
  "addresseeGate",
108
153
  "agentAliases",
@@ -115,8 +160,8 @@ export function groupPolicyIssues(value) {
115
160
  if (e.policy !== undefined &&
116
161
  e.policy !== "legacy" &&
117
162
  e.policy !== "engaged" &&
118
- e.policy !== "conversation") {
119
- issue([...path, "engagement", "policy"], "must be legacy, engaged or conversation");
163
+ e.policy !== "chat") {
164
+ issue([...path, "engagement", "policy"], "must be legacy, engaged or chat");
120
165
  }
121
166
  if (e.agentAliases !== undefined &&
122
167
  (!Array.isArray(e.agentAliases) ||
@@ -141,7 +186,7 @@ export function groupPolicyIssues(value) {
141
186
  Number(burst.quietSeconds) > Number(burst.maxSeconds)) {
142
187
  issue([...path, "engagement", "burst"], "quietSeconds must not exceed maxSeconds");
143
188
  }
144
- for (const key of ["followUpMinutes", "conversationMinutes"]) {
189
+ for (const key of ["followUpMinutes", "engagementMinutes"]) {
145
190
  number(e[key], [...path, "engagement", key], 1, 180);
146
191
  }
147
192
  if (e.openQuestionMinutes !== "unlimited") {
@@ -163,12 +208,10 @@ export function groupPolicyIssues(value) {
163
208
  for (const [key, value] of Object.entries(t)) {
164
209
  number(value, [...path, "thresholds", key], key === "reply" ? 0.5 : 0, 1);
165
210
  }
166
- // The top level's policy defaults to legacy; a chat or shadow policy may inherit conversation.
211
+ // The top level's policy defaults to legacy; a chat or shadow policy may inherit chat.
167
212
  if ((t.reply !== undefined || t.defer !== undefined) &&
168
- (path.length === 1
169
- ? e.policy !== "conversation"
170
- : e.policy !== undefined && e.policy !== "conversation")) {
171
- issue([...path, "thresholds"], "reply and defer apply only to engagement.policy conversation");
213
+ (path.length === 1 ? e.policy !== "chat" : e.policy !== undefined && e.policy !== "chat")) {
214
+ issue([...path, "thresholds"], "reply and defer apply only to engagement.policy chat");
172
215
  }
173
216
  // A chat or shadow policy may inherit `reply`; the agent checks each chat after inheritance.
174
217
  if (path.length === 1
@@ -176,7 +219,7 @@ export function groupPolicyIssues(value) {
176
219
  : t.defer !== undefined && t.reply !== undefined && Number(t.defer) > Number(t.reply)) {
177
220
  issue([...path, "thresholds"], "must satisfy defer <= reply");
178
221
  }
179
- const defaults = e.policy === "conversation"
222
+ const defaults = e.policy === "chat"
180
223
  ? [0.5, 0.9, 0.95]
181
224
  : e.policy === "engaged"
182
225
  ? [0.5, 0.75, 0.9]
@@ -19,7 +19,7 @@ export declare const READ_VERB = "read";
19
19
  * `app_feedback:read`, and only the builders' roles name it unscoped. The built-in sign-in
20
20
  * identities hold every member's external accounts, such as their Telegram id and username: only a
21
21
  * role that names `user_identity` reads them. The agent's held replies hold the workspace's
22
- * conversations with the people it serves, and approving one sends it: only a role that names
22
+ * chats with the people it serves, and approving one sends it: only a role that names
23
23
  * `agent_review` reads, approves or rejects them.
24
24
  */
25
25
  export declare const EXPLICIT_GRANT_ENTITIES: ReadonlySet<string>;
@@ -18,7 +18,7 @@ export const READ_VERB = "read";
18
18
  * `app_feedback:read`, and only the builders' roles name it unscoped. The built-in sign-in
19
19
  * identities hold every member's external accounts, such as their Telegram id and username: only a
20
20
  * role that names `user_identity` reads them. The agent's held replies hold the workspace's
21
- * conversations with the people it serves, and approving one sends it: only a role that names
21
+ * chats with the people it serves, and approving one sends it: only a role that names
22
22
  * `agent_review` reads, approves or rejects them.
23
23
  */
24
24
  export const EXPLICIT_GRANT_ENTITIES = new Set([
@@ -38,9 +38,9 @@ const TelegramRuntimeSource = Schema.Struct({
38
38
  })).check(Schema.isMaxLength(10))),
39
39
  });
40
40
  /**
41
- * A conversation in another channel the agent serves. `kind` says whether it is one person's
42
- * direct conversation; `peer` is that person's id on the provider, which a private destination on
43
- * the same provider names, while `chat_id` names the conversation itself.
41
+ * A chat in another channel the agent serves. `kind` says whether it is one person's
42
+ * direct chat; `peer` is that person's id on the provider, which a private destination on
43
+ * the same provider names, while `chat_id` names the chat itself.
44
44
  */
45
45
  const ChannelRuntimeSource = Schema.Struct({
46
46
  provider: Schema.Literals(["slack", "whatsapp"]),
@@ -4,10 +4,13 @@ import { type SessionExchange, type TokenVerifier } from "../authentication.js";
4
4
  import { RequestId } from "../errors.js";
5
5
  import { OntologyBackend } from "../runtime-contract.js";
6
6
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
7
- import { type ConversationTransport } from "./conversations.js";
8
- /** Same member scope as MCP, accessible to app clients with their usual bearer/session. */
9
- export declare function conversationRoutes(options: {
10
- readonly transport: ConversationTransport;
7
+ import { type ChatArchiveTransport } from "./chat-archive.js";
8
+ /**
9
+ * Same member scope as MCP, accessible to app clients with their usual bearer/session.
10
+ * @legacy agent.legacy-conversation-routes The route keeps its published path until it is removed.
11
+ */
12
+ export declare function archiveRoutes(options: {
13
+ readonly transport: ChatArchiveTransport;
11
14
  readonly verifyToken: TokenVerifier;
12
15
  readonly verifyRuntime?: RuntimeTokenVerifier | undefined;
13
16
  readonly exchangeSession?: SessionExchange | undefined;
@@ -6,10 +6,13 @@ import { RequestId, expectedFailure, errorBodyForWire } from "../errors.js";
6
6
  import { identityToken } from "../operations.js";
7
7
  import { OntologyBackend } from "../runtime-contract.js";
8
8
  import { runtimeCredential } from "../runtime-identity.js";
9
- import { ConversationSearch } from "./conversations.js";
9
+ import { ChatSearch } from "./chat-archive.js";
10
10
  import { withChatMembership } from "../chat/resolve.js";
11
- /** Same member scope as MCP, accessible to app clients with their usual bearer/session. */
12
- export function conversationRoutes(options) {
11
+ /**
12
+ * Same member scope as MCP, accessible to app clients with their usual bearer/session.
13
+ * @legacy agent.legacy-conversation-routes The route keeps its published path until it is removed.
14
+ */
15
+ export function archiveRoutes(options) {
13
16
  return Layer.effectDiscard(Effect.gen(function* () {
14
17
  const router = yield* HttpRouter.HttpRouter;
15
18
  const backend = yield* OntologyBackend;
@@ -17,7 +20,7 @@ export function conversationRoutes(options) {
17
20
  yield* router.add("POST", "/api/ontology/agent/conversations/search", (request) => Effect.gen(function* () {
18
21
  const bearer = yield* HttpApiBuilder.securityDecode(HttpApiSecurity.bearer).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request));
19
22
  const operation = Effect.gen(function* () {
20
- const search = yield* Schema.decodeUnknownEffect(ConversationSearch)(yield* request.json);
23
+ const search = yield* Schema.decodeUnknownEffect(ChatSearch)(yield* request.json);
21
24
  const principal = yield* CurrentPrincipal;
22
25
  const page = yield* transport({
23
26
  search,
@@ -32,7 +35,7 @@ export function conversationRoutes(options) {
32
35
  const failure = expectedFailure(error, requestId);
33
36
  return HttpServerResponse.jsonUnsafe(errorBodyForWire(failure?.body ?? {
34
37
  error: "invalid_request",
35
- detail: "The conversation request is invalid.",
38
+ detail: "The chat archive request is invalid.",
36
39
  requestId,
37
40
  }), { status: failure?.status ?? 400 });
38
41
  })));
@@ -8,12 +8,12 @@ import type { ApiPlan } from "../plan.js";
8
8
  import type { ReplicationKick } from "../replication.js";
9
9
  import { OntologyBackend } from "../runtime-contract.js";
10
10
  import type { RuntimeTokenVerifier } from "../runtime-identity.js";
11
- export { CONVERSATION_HEADER, SESSION_HEADER } from "./authentication.js";
11
+ export { CHAT_HEADER, SESSION_HEADER } from "./authentication.js";
12
12
  /**
13
13
  * The agent's temporary attachments over HTTP (`docs/agent.md`, "Attachments"). Only the
14
14
  * deployment's runtime token reaches these routes, acting as the member in `X-SegmentStream-Act-As`
15
15
  * while they are active. The chat and the agent session come from the agent's runtime in
16
- * `X-SegmentStream-Agent-Conversation` and `X-SegmentStream-Agent-Session`, never from the model's
16
+ * `X-SegmentStream-Agent-Chat` and `X-SegmentStream-Agent-Session`, never from the model's
17
17
  * tool arguments. Storage checks current group participation or chat administration; private files
18
18
  * remain confined to their sender and session.
19
19
  */
@@ -11,12 +11,12 @@ import { OntologyBackend } from "../runtime-contract.js";
11
11
  import { authenticateAgentCaller } from "./authentication.js";
12
12
  import { checkRuntimeOperation } from "../mcp/runtime-policy.js";
13
13
  import { AGENT_PATH } from "./server.js";
14
- export { CONVERSATION_HEADER, SESSION_HEADER } from "./authentication.js";
14
+ export { CHAT_HEADER, SESSION_HEADER } from "./authentication.js";
15
15
  /**
16
16
  * The agent's temporary attachments over HTTP (`docs/agent.md`, "Attachments"). Only the
17
17
  * deployment's runtime token reaches these routes, acting as the member in `X-SegmentStream-Act-As`
18
18
  * while they are active. The chat and the agent session come from the agent's runtime in
19
- * `X-SegmentStream-Agent-Conversation` and `X-SegmentStream-Agent-Session`, never from the model's
19
+ * `X-SegmentStream-Agent-Chat` and `X-SegmentStream-Agent-Session`, never from the model's
20
20
  * tool arguments. Storage checks current group participation or chat administration; private files
21
21
  * remain confined to their sender and session.
22
22
  */
@@ -4,7 +4,7 @@ import type { AttachmentCaller } from "../../storage/attachments.js";
4
4
  import { RequestId } from "../errors.js";
5
5
  import type { AgentStore, OntologyBackend } from "../runtime-contract.js";
6
6
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
7
- export declare const CONVERSATION_HEADER = "x-segmentstream-agent-conversation";
7
+ export declare const CHAT_HEADER = "x-segmentstream-agent-chat";
8
8
  export declare const SESSION_HEADER = "x-segmentstream-agent-session";
9
9
  /** Authenticate the runtime and resolve its member; attachment storage also checks chat access. */
10
10
  export declare function authenticateAgentCaller(input: {
@@ -4,9 +4,11 @@ import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { RequestId, forbidden, notFound, toServerResponse, unauthorized, unavailable, } from "../errors.js";
5
5
  import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
6
  import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
7
- export const CONVERSATION_HEADER = "x-segmentstream-agent-conversation";
7
+ export const CHAT_HEADER = "x-segmentstream-agent-chat";
8
8
  export const SESSION_HEADER = "x-segmentstream-agent-session";
9
- const CONVERSATION = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_-]{1,200}$/;
9
+ /** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
10
+ const EARLIER_CHAT_HEADER = "x-segmentstream-agent-conversation";
11
+ const CHAT = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_-]{1,200}$/;
10
12
  const SESSION = /^[A-Za-z0-9:_.-]{1,200}$/;
11
13
  /** Authenticate the runtime and resolve its member; attachment storage also checks chat access. */
12
14
  export function authenticateAgentCaller(input) {
@@ -59,9 +61,9 @@ export function authenticateAgentCaller(input) {
59
61
  }
60
62
  /** The chat and session every agent request names, with the member it acts for. */
61
63
  function agentCaller(request, requestId, member, delegatedBy) {
62
- const conversation = request.headers[CONVERSATION_HEADER]?.trim() ?? "";
64
+ const chat = (request.headers[CHAT_HEADER] ?? request.headers[EARLIER_CHAT_HEADER])?.trim() ?? "";
63
65
  const session = request.headers[SESSION_HEADER]?.trim() ?? "";
64
- if (!CONVERSATION.test(conversation) || (session !== "" && !SESSION.test(session))) {
66
+ if (!CHAT.test(chat) || (session !== "" && !SESSION.test(session))) {
65
67
  return {
66
68
  ok: false,
67
69
  response: toServerResponse(forbidden(requestId, "The agent names the chat and session of every request.")),
@@ -69,7 +71,7 @@ function agentCaller(request, requestId, member, delegatedBy) {
69
71
  }
70
72
  const caller = {
71
73
  principal: member,
72
- conversation,
74
+ chat,
73
75
  ...(session === "" ? {} : { sessionId: session }),
74
76
  ...(delegatedBy === undefined ? {} : { delegatedBy }),
75
77
  };
@@ -2,7 +2,7 @@ import { Effect, Schema } from "effect";
2
2
  import type { Principal } from "../../runtime.js";
3
3
  import { PermissionDenied } from "../../errors.js";
4
4
  import type { OntologyEnvironment } from "../config.js";
5
- export declare const ConversationSearch: Schema.Struct<{
5
+ export declare const ChatSearch: Schema.Struct<{
6
6
  readonly q: Schema.optionalKey<Schema.String>;
7
7
  readonly provider: Schema.optionalKey<Schema.String>;
8
8
  readonly chatId: Schema.optionalKey<Schema.String>;
@@ -13,28 +13,28 @@ export declare const ConversationSearch: Schema.Struct<{
13
13
  readonly before: Schema.optionalKey<Schema.String>;
14
14
  readonly limit: Schema.optionalKey<Schema.Int>;
15
15
  }>;
16
- export type ConversationSearch = typeof ConversationSearch.Type;
17
- export declare const ConversationPage: Schema.Struct<{
16
+ export type ChatSearch = typeof ChatSearch.Type;
17
+ export declare const ChatPage: Schema.Struct<{
18
18
  readonly events: Schema.$Array<Schema.$Record<Schema.String, Schema.Unknown>>;
19
19
  readonly nextCursor: Schema.NullOr<Schema.String>;
20
20
  }>;
21
- export type ConversationPage = typeof ConversationPage.Type;
22
- declare const ConversationArchiveUnavailable_base: Schema.Class<ConversationArchiveUnavailable, Schema.TaggedStruct<"ConversationArchiveUnavailable", {
21
+ export type ChatPage = typeof ChatPage.Type;
22
+ declare const ChatArchiveUnavailable_base: Schema.Class<ChatArchiveUnavailable, Schema.TaggedStruct<"ChatArchiveUnavailable", {
23
23
  readonly diagnostic: Schema.String;
24
24
  readonly cause: Schema.optionalKey<Schema.Unknown>;
25
25
  }>, import("effect/Cause").YieldableError>;
26
- export declare class ConversationArchiveUnavailable extends ConversationArchiveUnavailable_base {
26
+ export declare class ChatArchiveUnavailable extends ChatArchiveUnavailable_base {
27
27
  }
28
- export type ConversationTransport = (input: {
29
- readonly search: ConversationSearch;
28
+ export type ChatArchiveTransport = (input: {
29
+ readonly search: ChatSearch;
30
30
  readonly principal: Principal;
31
31
  readonly identityToken: string | undefined;
32
32
  /**
33
- * Group conversations (`provider:chatId`) the member is in. Their history is readable without
33
+ * Group chats (`provider:chatId`) the member is in. Their history is readable without
34
34
  * `agent_chat:read`, as their attachments are; see `withChatMembership`.
35
35
  */
36
36
  readonly memberGroups?: ReadonlyArray<string>;
37
- }) => Effect.Effect<ConversationPage, ConversationArchiveUnavailable | PermissionDenied>;
37
+ }) => Effect.Effect<ChatPage, ChatArchiveUnavailable | PermissionDenied>;
38
38
  /** The authenticated ontology service forwards its resolved member, never a caller-supplied ID. */
39
- export declare function platformConversations(environment: OntologyEnvironment, fetchImpl?: typeof fetch): ConversationTransport;
39
+ export declare function platformChatArchive(environment: OntologyEnvironment, fetchImpl?: typeof fetch): ChatArchiveTransport;
40
40
  export {};
@@ -3,7 +3,7 @@ import { PermissionDenied } from "../../errors.js";
3
3
  import { isAllowed } from "../../permissions.js";
4
4
  import { describeError } from "../metric-query-platform.js";
5
5
  const Filter = Schema.String.check(Schema.isMaxLength(1000));
6
- export const ConversationSearch = Schema.Struct({
6
+ export const ChatSearch = Schema.Struct({
7
7
  q: Schema.optionalKey(Filter),
8
8
  provider: Schema.optionalKey(Filter),
9
9
  chatId: Schema.optionalKey(Filter),
@@ -14,28 +14,28 @@ export const ConversationSearch = Schema.Struct({
14
14
  before: Schema.optionalKey(Filter),
15
15
  limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))),
16
16
  });
17
- export const ConversationPage = Schema.Struct({
17
+ export const ChatPage = Schema.Struct({
18
18
  events: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)),
19
19
  nextCursor: Schema.NullOr(Schema.String),
20
20
  });
21
- export class ConversationArchiveUnavailable extends Schema.TaggedError()("ConversationArchiveUnavailable", { diagnostic: Schema.String, cause: Schema.optionalKey(Schema.Unknown) }) {
21
+ export class ChatArchiveUnavailable extends Schema.TaggedError()("ChatArchiveUnavailable", { diagnostic: Schema.String, cause: Schema.optionalKey(Schema.Unknown) }) {
22
22
  }
23
23
  /** The authenticated ontology service forwards its resolved member, never a caller-supplied ID. */
24
- export function platformConversations(environment, fetchImpl = fetch) {
24
+ export function platformChatArchive(environment, fetchImpl = fetch) {
25
25
  return ({ search, principal, identityToken, memberGroups }) => {
26
26
  if (principal.kind !== "member") {
27
27
  return Effect.fail(new PermissionDenied({
28
- message: "Only members may read conversations.",
29
- permission: "conversation:participant",
28
+ message: "Only members may read chats.",
29
+ permission: "chat:participant",
30
30
  }));
31
31
  }
32
32
  if (!identityToken) {
33
- return Effect.fail(new ConversationArchiveUnavailable({ diagnostic: "runtime_identity_missing" }));
33
+ return Effect.fail(new ChatArchiveUnavailable({ diagnostic: "runtime_identity_missing" }));
34
34
  }
35
35
  return Effect.tryPromise({
36
36
  try: async (signal) => {
37
37
  const base = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/`;
38
- const response = await fetchImpl(`${base}${encodeURIComponent(environment.workspaceId)}/agent/conversations/search`, {
38
+ const response = await fetchImpl(`${base}${encodeURIComponent(environment.workspaceId)}/agent/chats/search`, {
39
39
  method: "POST",
40
40
  redirect: "error",
41
41
  headers: {
@@ -55,13 +55,13 @@ export function platformConversations(environment, fetchImpl = fetch) {
55
55
  signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]),
56
56
  });
57
57
  if (!response.ok) {
58
- throw new Error(`Conversation archive returned HTTP ${response.status}; ` +
58
+ throw new Error(`Chat archive returned HTTP ${response.status}; ` +
59
59
  `request ${response.headers.get("x-request-id") ?? "unknown"}.`);
60
60
  }
61
- return Schema.decodeUnknownSync(ConversationPage)(await response.json());
61
+ return Schema.decodeUnknownSync(ChatPage)(await response.json());
62
62
  },
63
- catch: (cause) => new ConversationArchiveUnavailable({ diagnostic: "archive_request_failed", cause }),
64
- }).pipe(Effect.tapError((error) => Effect.logWarning("ontology.conversations.read_failed").pipe(Effect.annotateLogs({
63
+ catch: (cause) => new ChatArchiveUnavailable({ diagnostic: "archive_request_failed", cause }),
64
+ }).pipe(Effect.tapError((error) => Effect.logWarning("ontology.chat_archive.read_failed").pipe(Effect.annotateLogs({
65
65
  diagnostic: error.diagnostic,
66
66
  error: describeError(error.cause, (text) => text.split(identityToken).join("[redacted]")),
67
67
  }))));
@@ -103,12 +103,12 @@ export const ReviewRequest = Schema.Struct({
103
103
  description: "The agent's key for the reply: its session and content part.",
104
104
  }),
105
105
  provider: Provider,
106
- chat_id: ChatId.annotate({ description: "The conversation's id on the channel." }),
106
+ chat_id: ChatId.annotate({ description: "The chat's id on the channel." }),
107
107
  recipient: ChatId.annotate({
108
108
  description: "Whom the provider sends the reply to: the chat's id, or the person's number.",
109
109
  }),
110
110
  thread_id: Schema.String.check(Schema.isMaxLength(MAX_EXTERNAL_ID_LENGTH)).annotate({
111
- description: "The conversation's thread or topic; empty without one.",
111
+ description: "The chat's thread or topic; empty without one.",
112
112
  }),
113
113
  reply_to: Schema.NullOr(ChatId).annotate({
114
114
  description: "The member's message the reply answers, when the channel replies to one.",
@@ -1,6 +1,6 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import type { OntologyEnvironment } from "../config.js";
3
- import type { ConversationRequester } from "./attribution.js";
3
+ import type { ChatRequester } from "./attribution.js";
4
4
  export interface DeliveryEvent {
5
5
  readonly eventId: string;
6
6
  readonly operationId: string;
@@ -26,7 +26,7 @@ export interface DeliveryEvent {
26
26
  readonly argsSummary: string | null;
27
27
  readonly status: "requested" | "sent" | "uncertain" | "failed";
28
28
  readonly attachments: readonly [];
29
- readonly requestedBy: ConversationRequester;
29
+ readonly requestedBy: ChatRequester;
30
30
  readonly url: string | null;
31
31
  readonly at: string;
32
32
  }
@@ -34,7 +34,7 @@ export function platformDeliveryArchive(environment, fetchImpl = fetch) {
34
34
  }
35
35
  const base = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
36
36
  encodeURIComponent(environment.workspaceId);
37
- const response = await fetchImpl(`${base}/agent/conversations/events`, {
37
+ const response = await fetchImpl(`${base}/agent/chats/events`, {
38
38
  method: "POST",
39
39
  redirect: "error",
40
40
  headers: {
@@ -15,7 +15,7 @@ export declare function deliveryRequester(caller: CallerContext, principal: Prin
15
15
  clientName: string | null;
16
16
  attribution: string;
17
17
  }, never, never>;
18
- export interface ConversationRequester {
18
+ export interface ChatRequester {
19
19
  readonly id: string;
20
20
  readonly kind: "member" | "service";
21
21
  readonly name: string;