@segmentstream/ontology 0.148.0 → 0.149.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 (40) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +24 -15
  3. package/dist/analyze.d.ts +11 -3
  4. package/dist/analyze.js +21 -4
  5. package/dist/diagnostics.d.ts +3 -3
  6. package/dist/diagnostics.js +1 -0
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/manifest.d.ts +53 -5
  10. package/dist/manifest.js +34 -2
  11. package/dist/migrate/model.d.ts +14 -2
  12. package/dist/migrate/plan.js +1 -1
  13. package/dist/migrate/preview.js +4 -1
  14. package/dist/migrate/storage.d.ts +15 -3
  15. package/dist/migrate/storage.js +86 -3
  16. package/dist/runtime/agents.js +2 -0
  17. package/dist/runtime/chat-messages.d.ts +233 -0
  18. package/dist/runtime/chat-messages.js +523 -0
  19. package/dist/service/agent/archive-routes.d.ts +2 -0
  20. package/dist/service/agent/archive-routes.js +2 -1
  21. package/dist/service/agent/chat-archive.d.ts +12 -3
  22. package/dist/service/agent/chat-archive.js +5 -1
  23. package/dist/service/agent/chat-message-routes.d.ts +124 -0
  24. package/dist/service/agent/chat-message-routes.js +235 -0
  25. package/dist/service/agent/server.d.ts +5 -1
  26. package/dist/service/agent/server.js +15 -0
  27. package/dist/service/chat/local-reads.d.ts +71 -0
  28. package/dist/service/chat/local-reads.js +148 -0
  29. package/dist/service/chat/reads.js +7 -0
  30. package/dist/service/chat/routes.js +4 -1
  31. package/dist/service/chat/schemas.d.ts +5 -0
  32. package/dist/service/chat/schemas.js +5 -0
  33. package/dist/service/cron-secret.d.ts +6 -0
  34. package/dist/service/cron-secret.js +14 -0
  35. package/dist/service/mcp/server.js +4 -2
  36. package/dist/service/runtime-contract.d.ts +2 -0
  37. package/dist/service/schemas.d.ts +8 -2
  38. package/dist/service/service.js +4 -1
  39. package/dist/service/workflows.js +2 -9
  40. package/package.json +1 -1
@@ -0,0 +1,124 @@
1
+ import { Effect, Redacted, Schema } from "effect";
2
+ import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
+ import { type ChatMessageStore } from "../../runtime/chat-messages.js";
4
+ import { RequestId } from "../errors.js";
5
+ /** `POST /api/ontology/agent/chats/messages`: one message, recorded once by its keys. */
6
+ export declare const ChatMessageRecordRequest: Schema.Struct<{
7
+ readonly channel: Schema.String;
8
+ readonly chatId: Schema.String;
9
+ readonly threadId: Schema.optionalKey<Schema.String>;
10
+ readonly chatType: Schema.Literals<readonly ["private", "group", "channel"]>;
11
+ readonly participants: Schema.$Array<Schema.String>;
12
+ readonly direction: Schema.Literals<readonly ["inbound", "outbound", "internal"]>;
13
+ readonly author: Schema.Literals<readonly ["human", "agent", "bot"]>;
14
+ readonly senderId: Schema.optionalKey<Schema.String>;
15
+ readonly senderName: Schema.optionalKey<Schema.String>;
16
+ readonly userId: Schema.optionalKey<Schema.String>;
17
+ readonly messageId: Schema.optionalKey<Schema.String>;
18
+ readonly replyTo: Schema.optionalKey<Schema.String>;
19
+ readonly text: Schema.optionalKey<Schema.String>;
20
+ readonly parts: Schema.optionalKey<Schema.$Array<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>>;
21
+ readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
22
+ readonly id: Schema.String;
23
+ readonly name: Schema.optionalKey<Schema.String>;
24
+ readonly type: Schema.optionalKey<Schema.String>;
25
+ readonly size: Schema.optionalKey<Schema.Int>;
26
+ }>>>;
27
+ readonly at: Schema.optionalKey<Schema.String>;
28
+ readonly status: Schema.optionalKey<Schema.Literals<readonly ["pending", "sent", "delivered", "read", "failed", "uncertain"]>>;
29
+ readonly operation: Schema.optionalKey<Schema.String>;
30
+ readonly fingerprint: Schema.optionalKey<Schema.String>;
31
+ readonly sessionId: Schema.optionalKey<Schema.String>;
32
+ readonly turnId: Schema.optionalKey<Schema.String>;
33
+ readonly meta: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
34
+ }>;
35
+ /** `POST /api/ontology/agent/chats/messages/change`: one change to a message. */
36
+ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Struct<{
37
+ readonly change: Schema.Literal<"edit">;
38
+ readonly text: Schema.String;
39
+ readonly at: Schema.optionalKey<Schema.String>;
40
+ readonly channel: Schema.String;
41
+ readonly chatId: Schema.String;
42
+ readonly messageId: Schema.String;
43
+ }>, Schema.Struct<{
44
+ readonly change: Schema.Literal<"delete">;
45
+ readonly at: Schema.optionalKey<Schema.String>;
46
+ readonly channel: Schema.String;
47
+ readonly chatId: Schema.String;
48
+ readonly messageId: Schema.String;
49
+ }>, Schema.Struct<{
50
+ readonly change: Schema.Literal<"reaction">;
51
+ readonly senderId: Schema.String;
52
+ readonly emoji: Schema.String;
53
+ readonly channel: Schema.String;
54
+ readonly chatId: Schema.String;
55
+ readonly messageId: Schema.String;
56
+ }>, Schema.Struct<{
57
+ readonly change: Schema.Literal<"status">;
58
+ readonly status: Schema.Literals<readonly ["sent", "delivered", "read", "failed"]>;
59
+ readonly failure: Schema.optionalKey<Schema.String>;
60
+ readonly channel: Schema.String;
61
+ readonly chatId: Schema.String;
62
+ readonly messageId: Schema.String;
63
+ }>, Schema.Struct<{
64
+ readonly change: Schema.Literal<"disposition">;
65
+ readonly disposition: Schema.Literals<readonly ["claimed", "turn", "skipped"]>;
66
+ readonly reason: Schema.optionalKey<Schema.String>;
67
+ readonly sessionId: Schema.optionalKey<Schema.String>;
68
+ readonly turnId: Schema.optionalKey<Schema.String>;
69
+ readonly channel: Schema.String;
70
+ readonly chatId: Schema.String;
71
+ readonly messageId: Schema.String;
72
+ }>, Schema.Struct<{
73
+ readonly channel: Schema.String;
74
+ readonly chatId: Schema.String;
75
+ readonly change: Schema.Literal<"sent">;
76
+ readonly operation: Schema.String;
77
+ readonly status: Schema.Literals<readonly ["sent", "failed", "uncertain"]>;
78
+ readonly providerMessageId: Schema.optionalKey<Schema.String>;
79
+ readonly failure: Schema.optionalKey<Schema.String>;
80
+ }>, Schema.Struct<{
81
+ readonly change: Schema.Literal<"meta">;
82
+ readonly meta: Schema.Codec<Schema.Json, Schema.Json, never, never>;
83
+ readonly channel: Schema.String;
84
+ readonly chatId: Schema.String;
85
+ readonly messageId: Schema.String;
86
+ }>]>;
87
+ /**
88
+ * `POST /api/ontology/agent/chats/messages/read`: one chat's messages, newest first, before a
89
+ * cursor; or those changed after a revision; or one by its provider id; or, with `pending`, the
90
+ * sends still to deliver, of every chat of the channel unless `chatId` names one.
91
+ */
92
+ export declare const ChatMessageReadRequest: Schema.Struct<{
93
+ readonly channel: Schema.String;
94
+ readonly chatId: Schema.optionalKey<Schema.String>;
95
+ readonly threadId: Schema.optionalKey<Schema.NullOr<Schema.String>>;
96
+ readonly after: Schema.optionalKey<Schema.String>;
97
+ readonly before: Schema.optionalKey<Schema.String>;
98
+ readonly messageId: Schema.optionalKey<Schema.String>;
99
+ readonly pending: Schema.optionalKey<Schema.Boolean>;
100
+ readonly limit: Schema.optionalKey<Schema.Int>;
101
+ }>;
102
+ type Answer = Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
103
+ /** Records a message; `first` is false when its keys found it recorded already. */
104
+ export declare function recordChatMessage(store: ChatMessageStore): (request: HttpServerRequest.HttpServerRequest) => Answer;
105
+ /** Changes a message; `applied` is false when the store does not hold it or nothing changed. */
106
+ export declare function changeChatMessage(store: ChatMessageStore): (request: HttpServerRequest.HttpServerRequest) => Answer;
107
+ /** Reads messages, in one of the read's modes. */
108
+ export declare function readChatMessages(store: ChatMessageStore): (request: HttpServerRequest.HttpServerRequest) => Answer;
109
+ /**
110
+ * Deletes the messages the workspace keeps no longer, as its cron calls it with the project's cron
111
+ * secret. The ontology declares the window, `chat.retentionDays`.
112
+ */
113
+ export declare function purgeChatMessages(store: ChatMessageStore, options: {
114
+ readonly cronSecret: Redacted.Redacted<string> | undefined;
115
+ readonly retentionDays: number;
116
+ }): (request: HttpServerRequest.HttpServerRequest) => Answer;
117
+ /** The routes' paths under the agent's path. */
118
+ export declare const CHAT_MESSAGE_PATHS: {
119
+ readonly record: "/chats/messages";
120
+ readonly change: "/chats/messages/change";
121
+ readonly read: "/chats/messages/read";
122
+ readonly purge: "/chats/purge";
123
+ };
124
+ export {};
@@ -0,0 +1,235 @@
1
+ import { Effect, Result, Schema } from "effect";
2
+ import { HttpServerResponse } from "effect/unstable/http";
3
+ import { CHAT_DIRECTIONS, CHAT_DISPOSITIONS, CHAT_MESSAGE_AUTHORS, CHAT_MESSAGE_STATUSES, CHAT_TYPES, parseChatCursor, } from "../../runtime/chat-messages.js";
4
+ import { schemaIssues } from "../../runtime/validation.js";
5
+ import { bearerEquals } from "../cron-secret.js";
6
+ import { RequestId, errorBodyForWire } from "../errors.js";
7
+ import { Provider } from "./protocol.js";
8
+ /**
9
+ * The runtime's routes of the workspace chat store (docs/agent-chat-storage.md): record a message,
10
+ * change one, read them. Their refusals are codes, in `error` and `detail` alike.
11
+ */
12
+ const NO_STORE = { "cache-control": "no-store" };
13
+ const MAX_JSON_BYTES = 64 * 1024;
14
+ const Text = (maximum) => Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(maximum));
15
+ const ChatId = Text(256);
16
+ const MessageId = Text(512);
17
+ const Key = Text(512);
18
+ /** A reason or a refusal: a code such as `mention` or `outside_reply_window`, never prose. */
19
+ const Code = Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,63}$/));
20
+ const Instant = Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:\d{2})$/), Schema.makeFilter((value) => (Number.isNaN(Date.parse(value)) ? "invalid_time" : undefined)));
21
+ const Revision = Schema.String.check(Schema.isPattern(/^\d{1,18}$/));
22
+ /** JSON the store keeps as given, within a bound. */
23
+ const BoundedJson = Schema.Json.check(Schema.makeFilter((value) => JSON.stringify(value).length > MAX_JSON_BYTES ? "too_large" : undefined));
24
+ /** A message's part beside its text, such as a location or a contact, named by its `type`. */
25
+ const ChatPart = Schema.Record(Schema.String, Schema.Json).check(Schema.makeFilter((value) => (typeof value.type === "string" ? undefined : "type_required")));
26
+ const ChatFile = Schema.Struct({
27
+ id: Text(256),
28
+ name: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(1024))),
29
+ type: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(255))),
30
+ size: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
31
+ });
32
+ /** `POST /api/ontology/agent/chats/messages`: one message, recorded once by its keys. */
33
+ export const ChatMessageRecordRequest = Schema.Struct({
34
+ channel: Provider,
35
+ chatId: ChatId,
36
+ threadId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),
37
+ chatType: Schema.Literals(CHAT_TYPES),
38
+ participants: Schema.Array(Schema.String.check(Schema.isUUID())).check(Schema.isMaxLength(200)),
39
+ direction: Schema.Literals(CHAT_DIRECTIONS),
40
+ author: Schema.Literals(CHAT_MESSAGE_AUTHORS),
41
+ senderId: Schema.optionalKey(Text(256)),
42
+ senderName: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(200))),
43
+ userId: Schema.optionalKey(Schema.String.check(Schema.isUUID())),
44
+ messageId: Schema.optionalKey(MessageId),
45
+ replyTo: Schema.optionalKey(MessageId),
46
+ text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(100_000))),
47
+ parts: Schema.optionalKey(Schema.Array(ChatPart).check(Schema.isMaxLength(20))),
48
+ files: Schema.optionalKey(Schema.Array(ChatFile).check(Schema.isMaxLength(50))),
49
+ at: Schema.optionalKey(Instant),
50
+ status: Schema.optionalKey(Schema.Literals(CHAT_MESSAGE_STATUSES)),
51
+ operation: Schema.optionalKey(Key),
52
+ fingerprint: Schema.optionalKey(Key),
53
+ sessionId: Schema.optionalKey(Key),
54
+ turnId: Schema.optionalKey(Key),
55
+ meta: Schema.optionalKey(BoundedJson),
56
+ });
57
+ const Target = { channel: Provider, chatId: ChatId, messageId: MessageId };
58
+ /** `POST /api/ontology/agent/chats/messages/change`: one change to a message. */
59
+ export const ChatMessageChangeRequest = Schema.Union([
60
+ Schema.Struct({
61
+ ...Target,
62
+ change: Schema.Literal("edit"),
63
+ text: Schema.String.check(Schema.isMaxLength(100_000)),
64
+ at: Schema.optionalKey(Instant),
65
+ }),
66
+ Schema.Struct({ ...Target, change: Schema.Literal("delete"), at: Schema.optionalKey(Instant) }),
67
+ Schema.Struct({
68
+ ...Target,
69
+ change: Schema.Literal("reaction"),
70
+ senderId: Text(256),
71
+ // An empty emoji removes the sender's reaction.
72
+ emoji: Schema.String.check(Schema.isMaxLength(64)),
73
+ }),
74
+ Schema.Struct({
75
+ ...Target,
76
+ change: Schema.Literal("status"),
77
+ status: Schema.Literals(["sent", "delivered", "read", "failed"]),
78
+ failure: Schema.optionalKey(Code),
79
+ }),
80
+ Schema.Struct({
81
+ ...Target,
82
+ change: Schema.Literal("disposition"),
83
+ disposition: Schema.Literals(CHAT_DISPOSITIONS),
84
+ reason: Schema.optionalKey(Code),
85
+ sessionId: Schema.optionalKey(Key),
86
+ turnId: Schema.optionalKey(Key),
87
+ }),
88
+ // A send's receipt finds its message by the send's key: it had no provider id before.
89
+ Schema.Struct({
90
+ channel: Provider,
91
+ chatId: ChatId,
92
+ change: Schema.Literal("sent"),
93
+ operation: Key,
94
+ status: Schema.Literals(["sent", "failed", "uncertain"]),
95
+ providerMessageId: Schema.optionalKey(MessageId),
96
+ failure: Schema.optionalKey(Code),
97
+ }),
98
+ Schema.Struct({ ...Target, change: Schema.Literal("meta"), meta: BoundedJson }),
99
+ ]);
100
+ /**
101
+ * `POST /api/ontology/agent/chats/messages/read`: one chat's messages, newest first, before a
102
+ * cursor; or those changed after a revision; or one by its provider id; or, with `pending`, the
103
+ * sends still to deliver, of every chat of the channel unless `chatId` names one.
104
+ */
105
+ export const ChatMessageReadRequest = Schema.Struct({
106
+ channel: Provider,
107
+ chatId: Schema.optionalKey(ChatId),
108
+ threadId: Schema.optionalKey(Schema.NullOr(Text(256))),
109
+ after: Schema.optionalKey(Revision),
110
+ before: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(128))),
111
+ messageId: Schema.optionalKey(MessageId),
112
+ pending: Schema.optionalKey(Schema.Boolean),
113
+ limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))),
114
+ });
115
+ function json(body) {
116
+ return HttpServerResponse.jsonUnsafe(body, { status: 200, headers: NO_STORE });
117
+ }
118
+ /** A refusal, by its code. */
119
+ function refused(requestId, status, code, issues) {
120
+ return HttpServerResponse.jsonUnsafe(errorBodyForWire({
121
+ error: code,
122
+ detail: code,
123
+ requestId,
124
+ ...(issues === undefined ? {} : { issues }),
125
+ }), { status, headers: NO_STORE });
126
+ }
127
+ function jsonBody(request) {
128
+ return Effect.map(Effect.orDie(request.text), (text) => {
129
+ try {
130
+ return JSON.parse(text);
131
+ }
132
+ catch {
133
+ return undefined;
134
+ }
135
+ });
136
+ }
137
+ const STRICT = { errors: "all", onExcessProperty: "error" };
138
+ /** Records a message; `first` is false when its keys found it recorded already. */
139
+ export function recordChatMessage(store) {
140
+ return (request) => Effect.gen(function* () {
141
+ const requestId = yield* RequestId;
142
+ const decoded = Schema.decodeUnknownResult(ChatMessageRecordRequest)(yield* jsonBody(request), STRICT);
143
+ if (Result.isFailure(decoded)) {
144
+ return refused(requestId, 400, "invalid_request", schemaIssues(decoded.failure));
145
+ }
146
+ const { threadId, ...message } = decoded.success;
147
+ // A send's replay is told apart from another request by its fingerprint.
148
+ if ((message.operation === undefined) !== (message.fingerprint === undefined)) {
149
+ return refused(requestId, 400, "operation_requires_fingerprint");
150
+ }
151
+ if (message.status !== undefined && message.direction !== "outbound") {
152
+ return refused(requestId, 400, "status_requires_outbound");
153
+ }
154
+ const recorded = yield* store
155
+ .record({ ...message, ...(threadId === undefined || threadId === "" ? {} : { threadId }) })
156
+ .pipe(Effect.result);
157
+ if (Result.isFailure(recorded)) {
158
+ return refused(requestId, 409, recorded.failure.code);
159
+ }
160
+ yield* Effect.logInfo("ontology.agent.chat_message_recorded").pipe(Effect.annotateLogs({
161
+ requestId,
162
+ channel: message.channel,
163
+ direction: message.direction,
164
+ first: recorded.success.first,
165
+ }));
166
+ return json(recorded.success);
167
+ });
168
+ }
169
+ /** Changes a message; `applied` is false when the store does not hold it or nothing changed. */
170
+ export function changeChatMessage(store) {
171
+ return (request) => Effect.gen(function* () {
172
+ const requestId = yield* RequestId;
173
+ const decoded = Schema.decodeUnknownResult(ChatMessageChangeRequest)(yield* jsonBody(request), STRICT);
174
+ if (Result.isFailure(decoded)) {
175
+ return refused(requestId, 400, "invalid_request", schemaIssues(decoded.failure));
176
+ }
177
+ const changed = yield* store.change(decoded.success).pipe(Effect.result);
178
+ if (Result.isFailure(changed)) {
179
+ return refused(requestId, 409, changed.failure.code);
180
+ }
181
+ return json(changed.success);
182
+ });
183
+ }
184
+ /** Reads messages, in one of the read's modes. */
185
+ export function readChatMessages(store) {
186
+ return (request) => Effect.gen(function* () {
187
+ const requestId = yield* RequestId;
188
+ const decoded = Schema.decodeUnknownResult(ChatMessageReadRequest)(yield* jsonBody(request), STRICT);
189
+ if (Result.isFailure(decoded)) {
190
+ return refused(requestId, 400, "invalid_request", schemaIssues(decoded.failure));
191
+ }
192
+ const { before, limit, ...input } = decoded.success;
193
+ const cursor = before === undefined ? undefined : parseChatCursor(before);
194
+ if (before !== undefined && cursor === undefined) {
195
+ return refused(requestId, 400, "invalid_cursor");
196
+ }
197
+ if (input.chatId === undefined && input.pending !== true) {
198
+ return refused(requestId, 400, "chat_required");
199
+ }
200
+ const modes = [input.after, input.messageId, input.pending === true ? true : undefined];
201
+ if (modes.filter((mode) => mode !== undefined).length > 1 ||
202
+ (input.after !== undefined && cursor !== undefined)) {
203
+ return refused(requestId, 400, "read_modes_conflict");
204
+ }
205
+ const page = yield* store.read({
206
+ ...input,
207
+ ...(cursor === undefined ? {} : { before: cursor }),
208
+ limit: limit ?? 50,
209
+ });
210
+ return json({ messages: page.messages, nextCursor: page.nextCursor });
211
+ });
212
+ }
213
+ /**
214
+ * Deletes the messages the workspace keeps no longer, as its cron calls it with the project's cron
215
+ * secret. The ontology declares the window, `chat.retentionDays`.
216
+ */
217
+ export function purgeChatMessages(store, options) {
218
+ return (request) => Effect.gen(function* () {
219
+ const requestId = yield* RequestId;
220
+ if (options.cronSecret === undefined ||
221
+ !bearerEquals(request.headers.authorization, options.cronSecret)) {
222
+ return refused(requestId, 401, "cron_secret_required");
223
+ }
224
+ const purged = yield* store.purge({ retentionDays: options.retentionDays });
225
+ yield* Effect.logInfo("ontology.agent.chat_messages_purged").pipe(Effect.annotateLogs({ requestId, retentionDays: options.retentionDays, ...purged }));
226
+ return json(purged);
227
+ });
228
+ }
229
+ /** The routes' paths under the agent's path. */
230
+ export const CHAT_MESSAGE_PATHS = {
231
+ record: "/chats/messages",
232
+ change: "/chats/messages/change",
233
+ read: "/chats/messages/read",
234
+ purge: "/chats/purge",
235
+ };
@@ -1,4 +1,4 @@
1
- import { Layer } from "effect";
1
+ import { Layer, Redacted } from "effect";
2
2
  import { HttpRouter } from "effect/unstable/http";
3
3
  import { type SessionExchange, type TokenVerifier } from "../authentication.js";
4
4
  import { RequestId } from "../errors.js";
@@ -48,6 +48,10 @@ export interface AgentServerOptions {
48
48
  readonly emailSignUp?: boolean;
49
49
  /** The app's email sign-in, through which a guest proves an address; none when unavailable. */
50
50
  readonly emailCodes?: EmailCodes | undefined;
51
+ /** The project's cron secret, with which its cron purges the chats' old messages. */
52
+ readonly cronSecret?: Redacted.Redacted<string> | undefined;
53
+ /** How many days the chats' messages are kept, as the ontology declares it. */
54
+ readonly chatRetentionDays?: number;
51
55
  }
52
56
  /**
53
57
  * The routes that pair channel accounts with members for the app's own agent, and record the group
@@ -15,6 +15,8 @@ import { OntologyBackend } from "../runtime-contract.js";
15
15
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
16
16
  import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
17
17
  import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
18
+ import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
19
+ import { CHAT_RETENTION_DAYS } from "../../manifest.js";
18
20
  import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
19
21
  import { identityToken } from "../operations.js";
20
22
  /** The agent's endpoints, under the ontology service's path. */
@@ -591,6 +593,19 @@ export function agentLayer(options) {
591
593
  }
592
594
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
593
595
  yield* router.add("POST", CHATS_HANDOFF_PATH, asRuntime(handOffChat(store)));
596
+ if (store.chatMessages !== undefined) {
597
+ const messages = store.chatMessages;
598
+ const purge = purgeChatMessages(messages, {
599
+ cronSecret: options.cronSecret,
600
+ retentionDays: options.chatRetentionDays ?? CHAT_RETENTION_DAYS.default,
601
+ });
602
+ yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.record}`, asRuntime(recordChatMessage(messages)));
603
+ yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.change}`, asRuntime(changeChatMessage(messages)));
604
+ yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.read}`, asRuntime(readChatMessages(messages)));
605
+ // Vercel's cron calls it with GET; an operator may POST, with the same secret.
606
+ yield* router.add("GET", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.purge}`, purge);
607
+ yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.purge}`, purge);
608
+ }
594
609
  yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
595
610
  yield* router.add("POST", `${REVIEWS_PATH}/session`, asRuntime(sessionReviews(store)));
596
611
  yield* router.add("POST", `${REVIEWS_PATH}/revision`, asRuntime(revision(store)));
@@ -0,0 +1,71 @@
1
+ import { type ChatMessage } from "../../runtime/chat-messages.js";
2
+ import type { ChatArchiveTransport } from "../agent/chat-archive.js";
3
+ import type { OntologyBackend } from "../runtime-contract.js";
4
+ /**
5
+ * A message of the workspace's chat store as an event of the chat archive's pages, which
6
+ * `chat_history` and `chat_search` have always answered: the archive's fields, and the message's
7
+ * own beside them. `sequence` is the message's `revision`. An outbound message the provider
8
+ * delivered or read is `sent` in the archive's `status`, and exactly so in `delivery`. Its
9
+ * channel-private `meta` is never read.
10
+ */
11
+ export declare function chatMessageEvent(message: ChatMessage): {
12
+ eventId: string;
13
+ provider: string;
14
+ chatId: string;
15
+ chatType: "channel" | "private" | "group";
16
+ threadId: string | null;
17
+ participantIds: readonly string[];
18
+ senderId: string | null;
19
+ senderName: string | null;
20
+ senderIsBot: boolean;
21
+ kind: "inbound" | "outbound" | "internal";
22
+ messageId: string | null;
23
+ replyToMessageId: string | null;
24
+ sessionId: string | null;
25
+ turnId: string | null;
26
+ text: string | null;
27
+ decision: null;
28
+ reason: string | null;
29
+ toolCallId: null;
30
+ toolName: null;
31
+ argsSummary: null;
32
+ status: string | null;
33
+ operationId: string | null;
34
+ attachments: {
35
+ size?: number | undefined;
36
+ contentType?: string | undefined;
37
+ filename?: string | undefined;
38
+ id: string;
39
+ kind: string;
40
+ }[];
41
+ at: string;
42
+ sequence: string;
43
+ storedAt: string;
44
+ id: string;
45
+ direction: "inbound" | "outbound" | "internal";
46
+ author: "agent" | "human" | "bot";
47
+ sender: {
48
+ id: string | null;
49
+ name: string | null;
50
+ user_id: string | null;
51
+ };
52
+ parts: readonly unknown[];
53
+ files: readonly import("../../runtime/chat-messages.js").ChatMessageFile[];
54
+ reply_to: string | null;
55
+ reactions: {
56
+ sender_id: string;
57
+ emoji: string;
58
+ }[];
59
+ edited: boolean;
60
+ deleted: boolean;
61
+ delivery: "pending" | "read" | "sent" | "uncertain" | "failed" | "delivered" | null;
62
+ disposition: "skipped" | "claimed" | "turn" | null;
63
+ replaced_by: string | null;
64
+ };
65
+ /**
66
+ * Reads a chat from the workspace's chat store, `_chat_messages`, when the store holds its
67
+ * messages, as the reader the chat archive's rule admits, row by row; reads after a `revision`,
68
+ * or before a cursor of the store, are the store's alone. Any other read goes to `transport`,
69
+ * within the retention the ontology declares, `retentionDays`.
70
+ */
71
+ export declare function withChatStore(transport: ChatArchiveTransport, backend: OntologyBackend["Service"], retentionDays: number | undefined): ChatArchiveTransport;
@@ -0,0 +1,148 @@
1
+ import { Clock, Effect } from "effect";
2
+ import { ActionRejected, PermissionDenied } from "../../errors.js";
3
+ import { isAllowed } from "../../permissions.js";
4
+ import { parseChatCursor } from "../../runtime/chat-messages.js";
5
+ /** A cursor of the chat archive in Cloud: its sequence, negative for imported history. */
6
+ const ARCHIVE_SEQUENCE = /^-?\d+$/;
7
+ /** The sender the chat archive gives the agent's own messages; `author` says it now. */
8
+ const AGENT_SENDER = "agent";
9
+ const DAY_MS = 86_400_000;
10
+ /**
11
+ * A message of the workspace's chat store as an event of the chat archive's pages, which
12
+ * `chat_history` and `chat_search` have always answered: the archive's fields, and the message's
13
+ * own beside them. `sequence` is the message's `revision`. An outbound message the provider
14
+ * delivered or read is `sent` in the archive's `status`, and exactly so in `delivery`. Its
15
+ * channel-private `meta` is never read.
16
+ */
17
+ export function chatMessageEvent(message) {
18
+ return {
19
+ eventId: message.id,
20
+ provider: message.channel,
21
+ chatId: message.chatId,
22
+ chatType: message.chatType,
23
+ threadId: message.threadId,
24
+ participantIds: message.participants,
25
+ senderId: message.author === "agent" ? AGENT_SENDER : message.senderId,
26
+ senderName: message.senderName,
27
+ senderIsBot: message.author !== "human",
28
+ kind: message.direction,
29
+ messageId: message.messageId,
30
+ replyToMessageId: message.replyTo,
31
+ sessionId: message.sessionId,
32
+ turnId: message.turnId,
33
+ text: message.text,
34
+ decision: null,
35
+ reason: message.reason,
36
+ toolCallId: null,
37
+ toolName: null,
38
+ argsSummary: null,
39
+ status: message.status === "pending"
40
+ ? "requested"
41
+ : message.status === "delivered" || message.status === "read"
42
+ ? "sent"
43
+ : message.status,
44
+ operationId: message.operation,
45
+ attachments: message.files.map((file) => ({
46
+ id: file.id,
47
+ kind: "file",
48
+ ...(file.name === undefined ? {} : { filename: file.name }),
49
+ ...(file.type === undefined ? {} : { contentType: file.type }),
50
+ ...(file.size === undefined ? {} : { size: file.size }),
51
+ })),
52
+ at: message.at,
53
+ sequence: message.revision,
54
+ storedAt: message.at,
55
+ id: message.id,
56
+ direction: message.direction,
57
+ author: message.author,
58
+ sender: { id: message.senderId, name: message.senderName, user_id: message.userId },
59
+ parts: message.parts,
60
+ files: message.files,
61
+ reply_to: message.replyTo,
62
+ reactions: message.reactions.map((reaction) => ({
63
+ sender_id: reaction.senderId,
64
+ emoji: reaction.emoji,
65
+ })),
66
+ edited: message.editedAt !== null,
67
+ deleted: message.deletedAt !== null,
68
+ delivery: message.status,
69
+ disposition: message.disposition,
70
+ replaced_by: message.replacedBy,
71
+ };
72
+ }
73
+ /**
74
+ * A read of the chat archive in Cloud, from no earlier than the retention the ontology declares,
75
+ * `retentionDays`, so the archive never shows messages the workspace's own store would have
76
+ * purged. Without a declaration the archive keeps its own setting. A `from` that is no time is
77
+ * left for the archive to refuse.
78
+ */
79
+ function withinRetention(input, retentionDays, now) {
80
+ const from = input.search.from;
81
+ if (retentionDays === undefined ||
82
+ (from !== undefined &&
83
+ (Number.isNaN(Date.parse(from)) || Date.parse(from) >= now - retentionDays * DAY_MS))) {
84
+ return input;
85
+ }
86
+ return {
87
+ ...input,
88
+ search: { ...input.search, from: new Date(now - retentionDays * DAY_MS).toISOString() },
89
+ };
90
+ }
91
+ /**
92
+ * Reads a chat from the workspace's chat store, `_chat_messages`, when the store holds its
93
+ * messages, as the reader the chat archive's rule admits, row by row; reads after a `revision`,
94
+ * or before a cursor of the store, are the store's alone. Any other read goes to `transport`,
95
+ * within the retention the ontology declares, `retentionDays`.
96
+ */
97
+ export function withChatStore(transport, backend, retentionDays) {
98
+ return (input) => Effect.gen(function* () {
99
+ const store = backend.agents?.chatMessages;
100
+ const { search, after } = input;
101
+ const archived = search.before !== undefined && ARCHIVE_SEQUENCE.test(search.before);
102
+ const cursor = search.before === undefined || archived ? undefined : parseChatCursor(search.before);
103
+ if (store === undefined ||
104
+ search.provider === undefined ||
105
+ search.chatId === undefined ||
106
+ !(after !== undefined ||
107
+ cursor !== undefined ||
108
+ (search.before === undefined &&
109
+ (yield* store.holds({ channel: search.provider, chatId: search.chatId }))))) {
110
+ // @legacy agent.cloud-chat-archive A chat the store does not hold, a search of every chat
111
+ // and a page of the archive's own are read from the chat archive in Cloud. A chat whose
112
+ // messages the store purged reads there too, never beyond the declared retention.
113
+ return yield* transport(withinRetention(input, retentionDays, yield* Clock.currentTimeMillis));
114
+ }
115
+ const { principal, memberGroups, chats } = input;
116
+ const key = `${search.provider}:${search.chatId}`;
117
+ // A service, such as a workflow's user, reads only the exact chats the ontology checked.
118
+ const service = principal.kind === "service" && (chats ?? []).length > 0;
119
+ if (principal.kind !== "member" && !service) {
120
+ return yield* new PermissionDenied({
121
+ message: "chat_participant_required",
122
+ permission: "chat:participant",
123
+ });
124
+ }
125
+ if ([search.from, search.to].some((time) => time !== undefined && Number.isNaN(Date.parse(time)))) {
126
+ return yield* new ActionRejected({ message: "invalid_chat_search" });
127
+ }
128
+ const page = yield* store.search({
129
+ channel: search.provider,
130
+ chatId: search.chatId,
131
+ ...(search.threadId === undefined ? {} : { threadId: search.threadId }),
132
+ ...(search.q === undefined ? {} : { q: search.q }),
133
+ ...(search.senderId === undefined ? {} : { senderId: search.senderId }),
134
+ ...(search.from === undefined ? {} : { from: search.from }),
135
+ ...(search.to === undefined ? {} : { to: search.to }),
136
+ ...(after === undefined ? {} : { after }),
137
+ ...(cursor === undefined ? {} : { before: cursor }),
138
+ limit: search.limit ?? 50,
139
+ }, service
140
+ ? { participantId: null, groups: false, chat: (chats ?? []).includes(key) }
141
+ : {
142
+ participantId: principal.id,
143
+ groups: isAllowed("agent_chat:read", principal) || (memberGroups ?? []).includes(key),
144
+ chat: (chats ?? []).includes(key),
145
+ });
146
+ return { events: page.messages.map(chatMessageEvent), nextCursor: page.nextCursor };
147
+ });
148
+ }
@@ -82,6 +82,11 @@ export function chatReads(backend, options) {
82
82
  if (principal.kind !== "member" && principal.kind !== "service") {
83
83
  return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
84
84
  }
85
+ // A page continues one way: older than a cursor, or changed after a revision.
86
+ if (input.before !== undefined && input.after !== undefined) {
87
+ return yield* new ActionRejected({ message: "chat_cursor_conflict" });
88
+ }
89
+ const after = input.after === undefined ? {} : { after: input.after };
85
90
  const registered = UUID.test(input.chat)
86
91
  ? yield* registeredPrivateChat(backend, principal, input.chat)
87
92
  : undefined;
@@ -104,6 +109,7 @@ export function chatReads(backend, options) {
104
109
  },
105
110
  memberGroups: [],
106
111
  ...(registered.staff ? { chats: [key] } : {}),
112
+ ...after,
107
113
  });
108
114
  }
109
115
  // A service, such as a workflow's user, reads only the registered chats its scope holds.
@@ -151,6 +157,7 @@ export function chatReads(backend, options) {
151
157
  ...(input.limit === undefined ? {} : { limit: input.limit }),
152
158
  },
153
159
  memberGroups: member ? [groupChatKey(target)] : [],
160
+ ...after,
154
161
  });
155
162
  }),
156
163
  };