@segmentstream/ontology 0.148.0 → 0.150.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 +52 -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 +271 -0
  18. package/dist/runtime/chat-messages.js +576 -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 +156 -0
  24. package/dist/service/agent/chat-message-routes.js +264 -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,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
  };
@@ -2,6 +2,7 @@ import { Cause, Effect, Layer, Schema } from "effect";
2
2
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
3
3
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
4
4
  import { ActionRejected } from "../../errors.js";
5
+ import { declaredChatRetentionDaysOf } from "../../manifest.js";
5
6
  import { withPrincipal, CurrentPrincipal, } from "../authentication.js";
6
7
  import { runtimeCredential } from "../runtime-identity.js";
7
8
  import { RequestId, failureResponse } from "../errors.js";
@@ -11,12 +12,14 @@ import { ChatSearch } from "../agent/chat-archive.js";
11
12
  import { chatKind, listedChatProviders } from "./providers/index.js";
12
13
  import { chatReads } from "./reads.js";
13
14
  import { withChatMembership } from "./resolve.js";
15
+ import { withChatStore } from "./local-reads.js";
14
16
  import { ChatList, ChatHistory } from "./schemas.js";
15
17
  export function chatRoutes(options) {
16
18
  return Layer.effectDiscard(Effect.gen(function* () {
17
19
  const router = yield* HttpRouter.HttpRouter;
18
20
  const backend = yield* OntologyBackend;
19
- const chatHistory = options.chatHistory && withChatMembership(options.chatHistory, backend);
21
+ const chatHistory = options.chatHistory &&
22
+ withChatMembership(withChatStore(options.chatHistory, backend, declaredChatRetentionDaysOf(options.built.plan.ontology.manifest)), backend);
20
23
  const reads = chatReads(backend, {
21
24
  providers: listedChatProviders(options.built.plan.ontology.manifest.chat),
22
25
  kindOf: (channel) => chatKind(options.built.plan.ontology.manifest.chat, channel),
@@ -22,6 +22,11 @@ export declare const ChatList: Schema.Struct<{
22
22
  export declare const ChatHistory: Schema.Struct<{
23
23
  readonly chat: Schema.String;
24
24
  readonly before: Schema.optionalKey<Schema.String>;
25
+ /**
26
+ * A `revision` of the workspace's chat store, an event's `sequence` there: the chat's messages
27
+ * changed since, oldest change first, and `next_cursor` the revision to read after next.
28
+ */
29
+ readonly after: Schema.optionalKey<Schema.String>;
25
30
  readonly limit: Schema.optionalKey<Schema.Int>;
26
31
  }>;
27
32
  export declare const ChatDestination: Schema.Struct<{
@@ -17,6 +17,11 @@ export const ChatList = Schema.Struct({
17
17
  export const ChatHistory = Schema.Struct({
18
18
  chat: Id,
19
19
  before: Schema.optionalKey(Id),
20
+ /**
21
+ * A `revision` of the workspace's chat store, an event's `sequence` there: the chat's messages
22
+ * changed since, oldest change first, and `next_cursor` the revision to read after next.
23
+ */
24
+ after: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\d{1,18}$/))),
20
25
  limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))),
21
26
  });
22
27
  export const ChatDestination = Schema.Struct({
@@ -0,0 +1,6 @@
1
+ import { Redacted } from "effect";
2
+ /**
3
+ * Whether an `Authorization` header carries the project's cron secret, as Vercel sends it on each
4
+ * cron invocation: compared in constant time, and never equal to an empty secret.
5
+ */
6
+ export declare function bearerEquals(header: string | undefined, secret: Redacted.Redacted<string>): boolean;
@@ -0,0 +1,14 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import { Redacted } from "effect";
3
+ /**
4
+ * Whether an `Authorization` header carries the project's cron secret, as Vercel sends it on each
5
+ * cron invocation: compared in constant time, and never equal to an empty secret.
6
+ */
7
+ export function bearerEquals(header, secret) {
8
+ if (Redacted.value(secret) === "") {
9
+ return false;
10
+ }
11
+ const expected = Buffer.from(`Bearer ${Redacted.value(secret)}`);
12
+ const received = Buffer.from(header ?? "");
13
+ return received.length === expected.length && timingSafeEqual(received, expected);
14
+ }
@@ -4,7 +4,7 @@ import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { ActionRejected } from "../../errors.js";
5
5
  import { DeploymentAdmissionError } from "../../deployment.js";
6
6
  import { effectivePermissions } from "../../permissions.js";
7
- import { encodeManifest } from "../../manifest.js";
7
+ import { declaredChatRetentionDaysOf, encodeManifest } from "../../manifest.js";
8
8
  import { describeError, SCOPE_MISMATCH } from "../metric-query-platform.js";
9
9
  import { gatewayCredential, gatewayDecisions } from "../decisions.js";
10
10
  import { CurrentPrincipal, withPrincipal } from "../authentication.js";
@@ -19,6 +19,7 @@ import { ChatPostResult } from "../../chat.js";
19
19
  import { chatKind, listedChatProviders } from "../chat/providers/index.js";
20
20
  import { chatReads } from "../chat/reads.js";
21
21
  import { withChatMembership } from "../chat/resolve.js";
22
+ import { withChatStore } from "../chat/local-reads.js";
22
23
  import { catalogFor } from "../catalog.js";
23
24
  import { createDiscovery, DiscoveryError } from "../discovery.js";
24
25
  import { suggestNames, suggestionDetail } from "../name-suggestions.js";
@@ -827,7 +828,8 @@ export function mcpLayer(options) {
827
828
  files: backend.blobs !== undefined,
828
829
  }, options.navigation !== undefined);
829
830
  const operations = makeOperations(backend, options.built.plan, options.hooks, options.connections, options.replicate, options.chatDelivery);
830
- const chatHistory = options.chatHistory && withChatMembership(options.chatHistory, backend);
831
+ const chatHistory = options.chatHistory &&
832
+ withChatMembership(withChatStore(options.chatHistory, backend, declaredChatRetentionDaysOf(options.built.plan.ontology.manifest)), backend);
831
833
  const server = {
832
834
  chats: chatReads(backend, {
833
835
  providers: listedChatProviders(options.built.plan.ontology.manifest.chat),
@@ -725,6 +725,8 @@ export interface AgentStore {
725
725
  readonly sessionReviews?: (sessionId: string) => Effect.Effect<ReadonlyArray<SessionReview>>;
726
726
  /** The grants behind agent tokens for the web. Absent on stores that predate them. */
727
727
  readonly web?: AgentWebStore;
728
+ /** The chats' messages, in `_chat_messages`. Absent on stores that predate the chat store. */
729
+ readonly chatMessages?: import("../runtime/chat-messages.js").ChatMessageStore;
728
730
  }
729
731
  /** A reply the agent held for review, as `POST /api/ontology/agent/reviews` reports it. */
730
732
  export interface HeldReplyInput {
@@ -527,7 +527,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
527
527
  readonly description: Schema.String;
528
528
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
529
529
  }>>>;
530
- readonly chat: Schema.optionalKey<Schema.Struct<{
530
+ readonly chat: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
531
531
  readonly telegram: Schema.optionalKey<Schema.Struct<{
532
532
  readonly connection: Schema.String;
533
533
  }>>;
@@ -548,6 +548,9 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
548
548
  readonly template: Schema.optionalKey<Schema.String>;
549
549
  readonly separator: Schema.optionalKey<Schema.String>;
550
550
  }>>;
551
+ readonly retentionDays: Schema.optionalKey<Schema.Int>;
552
+ }>, {
553
+ readonly retentionDays: "retention_days";
551
554
  }>>;
552
555
  readonly inbox: Schema.optionalKey<Schema.Struct<{
553
556
  readonly roles: Schema.$Array<Schema.String>;
@@ -892,7 +895,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
892
895
  readonly description: Schema.String;
893
896
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
894
897
  }>>>>;
895
- readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.Struct<{
898
+ readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
896
899
  readonly telegram: Schema.optionalKey<Schema.Struct<{
897
900
  readonly connection: Schema.String;
898
901
  }>>;
@@ -913,6 +916,9 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
913
916
  readonly template: Schema.optionalKey<Schema.String>;
914
917
  readonly separator: Schema.optionalKey<Schema.String>;
915
918
  }>>;
919
+ readonly retentionDays: Schema.optionalKey<Schema.Int>;
920
+ }>, {
921
+ readonly retentionDays: "retention_days";
916
922
  }>>>;
917
923
  readonly inbox: Schema.toEncoded<Schema.optionalKey<Schema.Struct<{
918
924
  readonly roles: Schema.$Array<Schema.String>;
@@ -9,7 +9,7 @@ import { RuntimeDeployment } from "../runtime/deployment.js";
9
9
  import { nameToWire } from "../authoring-names.js";
10
10
  import { bundledNavigationCatalog } from "../navigation-artifact.js";
11
11
  import { parsePageCatalog } from "../navigation-catalog.js";
12
- import { guestOf, signUpOriginsOf, signUpRolesOf } from "../manifest.js";
12
+ import { chatRetentionDaysOf, declaredChatRetentionDaysOf, guestOf, signUpOriginsOf, signUpRolesOf, } from "../manifest.js";
13
13
  import { isAllowed } from "../permissions.js";
14
14
  import { agentToolsFor } from "../runtime/guests.js";
15
15
  import { implicitMemberOf } from "../role.js";
@@ -425,6 +425,8 @@ export function createOntologyService(ontology, config) {
425
425
  }),
426
426
  emailSignUp: signUpRolesOf(ontology.manifest, "email") !== undefined,
427
427
  emailCodes,
428
+ cronSecret: config.cronSecret,
429
+ chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
428
430
  });
429
431
  const agentTasks = preview
430
432
  ? Layer.empty
@@ -472,6 +474,7 @@ export function createOntologyService(ontology, config) {
472
474
  ? Layer.empty
473
475
  : archiveRoutes({
474
476
  transport: chatHistory,
477
+ chatRetentionDays: declaredChatRetentionDaysOf(ontology.manifest),
475
478
  verifyToken,
476
479
  verifyRuntime,
477
480
  exchangeSession,
@@ -1,4 +1,4 @@
1
- import { createHash, timingSafeEqual } from "node:crypto";
1
+ import { createHash } from "node:crypto";
2
2
  import { Cause, Context, Effect, Exit, Layer, Redacted, Schema } from "effect";
3
3
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
4
4
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
@@ -27,6 +27,7 @@ import { RECOVERY_CONFIRM_MS, RECOVERY_COVERAGE_MARGIN_MS, RECOVERY_FIRST_SWEEP_
27
27
  import { nextCronTime, } from "../workflow.js";
28
28
  import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, workflowStructures, } from "../workflow-runtime.js";
29
29
  import { callbackIdentityToken } from "./workflow-callback.js";
30
+ import { bearerEquals } from "./cron-secret.js";
30
31
  import { expireAgentTask, startAgentTask, } from "./agent/task-start.js";
31
32
  import { CurrentPrincipal, WORKLOAD_TOKEN_TYPE, withPrincipal, workloadKind, } from "./authentication.js";
32
33
  import { CurrentCaller } from "./caller-context.js";
@@ -571,14 +572,6 @@ function workflowView(workflow, now) {
571
572
  : []),
572
573
  };
573
574
  }
574
- function bearerEquals(header, secret) {
575
- if (Redacted.value(secret) === "") {
576
- return false;
577
- }
578
- const expected = Buffer.from(`Bearer ${Redacted.value(secret)}`);
579
- const received = Buffer.from(header ?? "");
580
- return received.length === expected.length && timingSafeEqual(received, expected);
581
- }
582
575
  function isWorkloadToken(token) {
583
576
  try {
584
577
  return decodeProtectedHeader(token).typ === WORKLOAD_TOKEN_TYPE;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.148.0",
3
+ "version": "0.150.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",