@segmentstream/ontology 0.203.1 → 0.205.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.205.0
4
+
5
+ Report database query counts, elapsed query time and activity intervals for ontology requests and workflow steps. Upgrade and deploy the ontology to make its observations available in workspace usage diagnostics.
6
+
7
+ ## 0.204.0
8
+
9
+ Workflow tasks can read messages from a registered group by record id within their existing `agent_chat:read` scope.
10
+
3
11
  ## 0.203.1
4
12
 
5
13
  An app that declares `signIn.cli` now asks SegmentStream whether the member's consent still holds
@@ -12,29 +12,37 @@ import { chatResolver, groupChatKey, isChatMember } from "./resolve.js";
12
12
  */
13
13
  const HISTORY_KINDS = new Set(["telegram", "slack"]);
14
14
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15
- /**
16
- * A private chat the inbox registered, by its record id, when the caller may read it: a member with
17
- * `agent_chat:read` whose scope holds the record (`staff`), or the person in it. Its `externalId` is
18
- * the chat's id in the archive on every channel. `undefined` for any other id.
19
- */
20
- function registeredPrivateChat(backend, principal, id) {
15
+ /** The registered record whose archive the caller may read by id, and how they may read it. */
16
+ function registeredChat(backend, principal, id) {
21
17
  return Effect.gen(function* () {
18
+ if (isAllowed("agent_chat:read", principal)) {
19
+ const chat = yield* backend
20
+ .get({ entity: "agent_chat", id, reader: principal })
21
+ .pipe(Effect.catchTag("NotFound", () => Effect.succeed(undefined)));
22
+ if (chat?.kind === "private" || (principal.kind === "service" && chat?.kind === "group")) {
23
+ return { chat, staff: true };
24
+ }
25
+ // Members read groups through the channel's normal group-history rules below.
26
+ if (chat?.kind === "group") {
27
+ return undefined;
28
+ }
29
+ }
30
+ if (principal.kind !== "member") {
31
+ return undefined;
32
+ }
22
33
  const [chat] = (yield* backend
23
34
  .find({
24
35
  entity: "agent_chat",
25
36
  query: { where: { and: [{ id: { eq: id } }, { kind: { eq: "private" } }] }, limit: 1 },
26
37
  })
27
38
  .pipe(Effect.mapError((cause) => new ActionRejected({ message: "The chat directory could not be read.", cause })))).items;
28
- // A group chat is read as before; only a private chat the inbox registered is read here.
29
39
  if (chat === undefined || chat.kind !== "private") {
30
40
  return undefined;
31
41
  }
32
- const staff = isAllowed("agent_chat:read", principal) &&
33
- (yield* backend.get({ entity: "agent_chat", id, reader: principal }).pipe(Effect.as(true), Effect.catchTag("NotFound", () => Effect.succeed(false))));
34
- if (!staff && !(yield* isChatMember(backend, principal, id))) {
42
+ if (!(yield* isChatMember(backend, principal, id))) {
35
43
  return yield* new PermissionDenied({ message: "This chat is not readable by the caller." });
36
44
  }
37
- return { provider: String(chat.provider), externalId: String(chat.external_id), staff };
45
+ return { chat, staff: false };
38
46
  });
39
47
  }
40
48
  export function chatReads(backend, options) {
@@ -80,7 +88,9 @@ export function chatReads(backend, options) {
80
88
  history: (input, identityToken) => Effect.gen(function* () {
81
89
  const principal = yield* CurrentPrincipal;
82
90
  if (principal.kind !== "member" && principal.kind !== "service") {
83
- return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
91
+ return yield* new PermissionDenied({
92
+ message: "This chat is not readable by the caller.",
93
+ });
84
94
  }
85
95
  // A page continues one way: older than a cursor, or changed after a revision.
86
96
  if (input.before !== undefined && input.after !== undefined) {
@@ -88,35 +98,41 @@ export function chatReads(backend, options) {
88
98
  }
89
99
  const after = input.after === undefined ? {} : { after: input.after };
90
100
  const registered = UUID.test(input.chat)
91
- ? yield* registeredPrivateChat(backend, principal, input.chat)
101
+ ? yield* registeredChat(backend, principal, input.chat)
92
102
  : undefined;
93
103
  if (registered !== undefined) {
94
104
  if (!chatHistory) {
95
105
  return yield* new ActionRejected({ message: "The chat archive is not configured." });
96
106
  }
97
- const key = `${registered.provider}:${registered.externalId}`;
98
- // Staff read the chat's messages whoever wrote them, and on request its internal ones;
99
- // its person reads the messages they took part in, as in any private chat, so an account
100
- // paired with someone else since shows the earlier person nothing newer.
107
+ const key = groupChatKey(registered.chat);
108
+ // Internal notes are available only on a staff read of a private inbox chat. Its
109
+ // participant reads only messages they took part in, including after a pairing change.
101
110
  return yield* chatHistory({
102
111
  principal,
103
112
  identityToken,
104
113
  search: {
105
- provider: registered.provider,
106
- chatId: registered.externalId,
114
+ provider: String(registered.chat.provider),
115
+ chatId: String(registered.chat.external_id),
107
116
  ...(input.before === undefined ? {} : { before: input.before }),
108
117
  ...(input.limit === undefined ? {} : { limit: input.limit }),
109
118
  },
110
119
  memberGroups: [],
111
120
  ...(registered.staff
112
- ? { chats: [key], ...(input.internal === true ? { internal: true } : {}) }
121
+ ? {
122
+ chats: [key],
123
+ ...(registered.chat.kind === "private" && input.internal === true
124
+ ? { internal: true }
125
+ : {}),
126
+ }
113
127
  : {}),
114
128
  ...after,
115
129
  });
116
130
  }
117
131
  // A service, such as a workflow's user, reads only the registered chats its scope holds.
118
132
  if (principal.kind !== "member") {
119
- return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
133
+ return yield* new PermissionDenied({
134
+ message: "This chat is not readable by the caller.",
135
+ });
120
136
  }
121
137
  // History reads Telegram's chats and Slack's channels, which the archive keeps under the
122
138
  // chat a destination names. Other channels' chats are read by the record the inbox
@@ -0,0 +1,25 @@
1
+ import { Context, Tracer } from "effect";
2
+ /** One observation per request or workflow SDK call. Never inspect SQL, parameters or row values. */
3
+ export declare class DatabaseActivity {
4
+ queries: number;
5
+ returnedRows: number;
6
+ queryMs: number;
7
+ failedQueries: number;
8
+ truncated: boolean;
9
+ tool?: string;
10
+ readonly intervals: Array<[number, number]>;
11
+ tracer(delegate: Tracer.Tracer): Tracer.Tracer;
12
+ /** Coalesce intervals separated by at most one second of a serverless idle window. The reader applies the observed endpoint idle policy. */
13
+ private recordInterval;
14
+ measurement(source: string, context: Record<string, string | number | undefined>): {
15
+ queries: number;
16
+ failedQueries: number;
17
+ queryMs: number;
18
+ returnedRows: number;
19
+ intervals: [number, number][];
20
+ truncated: boolean;
21
+ event: string;
22
+ source: string;
23
+ };
24
+ }
25
+ export declare const CurrentDatabaseActivity: Context.Reference<DatabaseActivity | undefined>;
@@ -0,0 +1,68 @@
1
+ import { Context, Exit, Tracer } from "effect";
2
+ /** One observation per request or workflow SDK call. Never inspect SQL, parameters or row values. */
3
+ export class DatabaseActivity {
4
+ queries = 0;
5
+ returnedRows = 0;
6
+ queryMs = 0;
7
+ failedQueries = 0;
8
+ truncated = false;
9
+ tool;
10
+ intervals = [];
11
+ tracer(delegate) {
12
+ return Tracer.make({
13
+ ...(delegate.context ? { context: delegate.context.bind(delegate) } : {}),
14
+ span: (options) => {
15
+ const span = delegate.span(options);
16
+ if (options.name !== "sql.execute") {
17
+ return span;
18
+ }
19
+ const started = Date.now();
20
+ const tick = performance.now();
21
+ const end = span.end.bind(span);
22
+ span.end = (time, exit) => {
23
+ const finished = Math.max(started, Date.now());
24
+ this.queries++;
25
+ this.queryMs += performance.now() - tick;
26
+ if (Exit.isFailure(exit)) {
27
+ this.failedQueries++;
28
+ }
29
+ else if (Array.isArray(exit.value)) {
30
+ this.returnedRows += exit.value.length;
31
+ }
32
+ this.recordInterval(started, finished);
33
+ end(time, exit);
34
+ };
35
+ return span;
36
+ },
37
+ });
38
+ }
39
+ /** Coalesce intervals separated by at most one second of a serverless idle window. The reader applies the observed endpoint idle policy. */
40
+ recordInterval(start, end) {
41
+ const ranges = this.intervals;
42
+ let index = ranges.length;
43
+ while (index > 0 && ranges[index - 1][1] + 1000 >= start) {
44
+ const previous = ranges[--index];
45
+ start = Math.min(start, previous[0]);
46
+ end = Math.max(end, previous[1]);
47
+ }
48
+ if (index === 64) {
49
+ this.truncated = true;
50
+ return;
51
+ }
52
+ ranges.splice(index, ranges.length - index, [start, end]);
53
+ }
54
+ measurement(source, context) {
55
+ return {
56
+ event: "ontology.database.activity",
57
+ source: this.tool ? "mcp:" + this.tool : source,
58
+ ...context,
59
+ queries: this.queries,
60
+ failedQueries: this.failedQueries,
61
+ queryMs: Math.round(this.queryMs),
62
+ returnedRows: this.returnedRows,
63
+ intervals: this.intervals,
64
+ truncated: this.truncated,
65
+ };
66
+ }
67
+ }
68
+ export const CurrentDatabaseActivity = Context.Reference("segmentstream/ontology/DatabaseActivity", { defaultValue: () => undefined });
@@ -1,3 +1,4 @@
1
+ import { CurrentDatabaseActivity } from "../database-activity.js";
1
2
  import { Cause, Data, Effect, Layer, Option, Redacted, Schema, SchemaTransformation } from "effect";
2
3
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
4
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
@@ -540,6 +541,11 @@ function callTool(server, params, request, preview) {
540
541
  ? { ...params, name: currentToolName(params.name) }
541
542
  : params;
542
543
  const tool = server.tools.find((candidate) => candidate.name === call.name);
544
+ const activity = yield* CurrentDatabaseActivity;
545
+ if (activity && tool) {
546
+ const client = principal.execution ? "pipeline" : principal.chat ? "agent" : caller.kind;
547
+ activity.tool = client + ":" + tool.name;
548
+ }
543
549
  const allowed = yield* requireRuntimeOperation({
544
550
  ...(typeof call.name === "string" ? { name: call.name } : {}),
545
551
  ...(tool === undefined ? {} : { target: tool.target }),
@@ -828,7 +828,8 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
828
828
  description: "Read messages for an exact chat ID/title, with their own pagination. " +
829
829
  "Reads a group chat you are in (every group with agent_chat:read), your own private chat, " +
830
830
  "or, by its agent_chat id, a private chat the inbox registered (a person's, or a website " +
831
- "visitor's), with agent_chat:read within your scope. A workflow's task reads only these.",
831
+ "visitor's), with agent_chat:read within your scope. A workflow reads a registered group " +
832
+ "or private chat by its agent_chat id within its agent_chat:read scope.",
832
833
  inputSchema: encodedJsonSchema(ChatHistory),
833
834
  annotations: READ,
834
835
  permissions: [],
@@ -46,6 +46,8 @@ import { deployedReplication } from "./replication.js";
46
46
  import { mcpLayer } from "./mcp/server.js";
47
47
  import { runtimeAllows } from "./mcp/runtime-policy.js";
48
48
  import { suggestNames } from "./name-suggestions.js";
49
+ import { Tracer } from "effect";
50
+ import { CurrentDatabaseActivity, DatabaseActivity } from "./database-activity.js";
49
51
  import { observeMcpRequest } from "./mcp/request-log.js";
50
52
  import { oauthLayer } from "./oauth/server.js";
51
53
  import { createFederationProvider } from "./federation-provider.js";
@@ -646,6 +648,15 @@ export function createOntologyService(ontology, config) {
646
648
  if (parts[1] === "api" && parts[2] === "ontology" && entity !== undefined) {
647
649
  return `/api/ontology/${entity.name}/*`;
648
650
  }
651
+ if (parts[1] === "api" && parts[2] === "ontology" && parts[3] === "workflows") {
652
+ const workflow = ontology.workflows.find((item) => item.name === parts[4]);
653
+ if (workflow) {
654
+ const trigger = parts[5] === "triggers" && workflow.triggers.find((item) => item.name === parts[6]);
655
+ return trigger
656
+ ? `/api/ontology/workflows/${workflow.name}/triggers/${trigger.name}`
657
+ : `/api/ontology/workflows/${workflow.name}`;
658
+ }
659
+ }
649
660
  if (parts[1] === "api" && parts[2] === "webhooks") {
650
661
  const declared = ontology.workflows.some((workflow) => workflow.triggers.some((trigger) => trigger.kind === "webhook" && trigger.name === parts[3]));
651
662
  // Never the token segment.
@@ -659,6 +670,7 @@ export function createOntologyService(ontology, config) {
659
670
  async handler(request) {
660
671
  const started = performance.now();
661
672
  const requestId = crypto.randomUUID();
673
+ const activity = new DatabaseActivity();
662
674
  const logMcpRequest = observeMcpRequest(request);
663
675
  let response;
664
676
  try {
@@ -688,7 +700,7 @@ export function createOntologyService(ontology, config) {
688
700
  throw new DeploymentAdmissionError("preview_authentication_unavailable");
689
701
  }
690
702
  }
691
- response = await web.handler(withCurrentEntityPath(request), Context.make(RequestId, requestId));
703
+ response = await web.handler(withCurrentEntityPath(request), Context.make(RequestId, requestId).pipe(Context.add(CurrentDatabaseActivity, activity), Context.add(Tracer.Tracer, activity.tracer(Tracer.nativeTracer))));
692
704
  }
693
705
  catch (error) {
694
706
  if (error instanceof DeploymentAdmissionError) {
@@ -715,7 +727,13 @@ export function createOntologyService(ontology, config) {
715
727
  status: response.status,
716
728
  durationMs,
717
729
  };
718
- console.info(JSON.stringify({ event: "ontology.request", ...timing }));
730
+ const route = timing.operation.split("/");
731
+ const cron = route[3] === "workflows" && route[5] === "triggers";
732
+ const databaseActivity = activity.measurement(cron ? "workflow:" + route[4] : timing.operation, {
733
+ target: deployment.target,
734
+ ...(cron ? { workflow: route[4], trigger: route[4] + "." + route[6] } : {}),
735
+ });
736
+ console.info(JSON.stringify({ event: "ontology.request", ...timing, databaseActivity }));
719
737
  await logMcpRequest?.(response, requestId, durationMs);
720
738
  return decorate(response, requestId, hash, durationMs);
721
739
  },
@@ -14,7 +14,9 @@ function runtimeEvent(value) {
14
14
  try {
15
15
  const event = JSON.parse(value.slice(start))?.event;
16
16
  return (typeof event === "string" &&
17
- (event.startsWith("diagnostics.") || event.startsWith("ontology.workflow.")));
17
+ (event.startsWith("diagnostics.") ||
18
+ event.startsWith("ontology.workflow.") ||
19
+ event === "ontology.database.activity"));
18
20
  }
19
21
  catch {
20
22
  // diagnostics-recovery: Ordinary console text is not a structured runtime event.
@@ -1,3 +1,5 @@
1
+ import { Tracer } from "effect";
2
+ import { DatabaseActivity } from "./database-activity.js";
1
3
  import { createHash } from "node:crypto";
2
4
  import { Cause, Context, Effect, Exit, Layer, Redacted, Schema } from "effect";
3
5
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
@@ -765,7 +767,9 @@ export function workflowsLayer(options) {
765
767
  if (runRecords.size >= 1_000) {
766
768
  runRecords.delete(runRecords.keys().next().value);
767
769
  }
770
+ const startedBy = runStartedBy(run.attributes);
768
771
  const recorded = {
772
+ trigger: startedBy?.kind === "trigger" ? startedBy.trigger : startedBy?.kind,
769
773
  workflowName: run.workflowName,
770
774
  owner: recordedOwner(run.attributes),
771
775
  };
@@ -934,6 +938,17 @@ export function workflowsLayer(options) {
934
938
  * token. The start refuses a workflow user that is missing or inactive, as every step does; the
935
939
  * expiry only records the timeout. Failures are logged and thrown as the SDK retries them.
936
940
  */
941
+ function observeStep(workflow, step, effect) {
942
+ const activity = new DatabaseActivity();
943
+ return Effect.updateService(effect, Tracer.Tracer, (tracer) => activity.tracer(tracer)).pipe(Effect.ensuring(Effect.sync(() => console.info(JSON.stringify(activity.measurement("workflow:" + workflow.manifest.name, {
944
+ workflow: workflow.manifest.name,
945
+ trigger: runRecords.get(step.workflowRunId)?.trigger,
946
+ workflowRunId: step.workflowRunId,
947
+ stepId: step.stepId,
948
+ attempt: step.attempt,
949
+ target: options.deployment.target,
950
+ }))))));
951
+ }
937
952
  function runAgentTaskStep(workflow, step, requireUser, program) {
938
953
  const requestId = crypto.randomUUID();
939
954
  const identityToken = callbackIdentityToken() ?? process.env.VERCEL_OIDC_TOKEN;
@@ -951,7 +966,7 @@ export function workflowsLayer(options) {
951
966
  }
952
967
  return yield* program(identityToken);
953
968
  }).pipe(Effect.annotateLogs({ requestId }));
954
- return Effect.runPromiseExitWith(layerServices)(checked).then((exit) => {
969
+ return Effect.runPromiseExitWith(layerServices)(observeStep(workflow, step, checked)).then((exit) => {
955
970
  if (Exit.isSuccess(exit)) {
956
971
  return exit.value;
957
972
  }
@@ -1169,14 +1184,16 @@ export function workflowsLayer(options) {
1169
1184
  }));
1170
1185
  return yield* Effect.provideContext(effect, services);
1171
1186
  });
1172
- return Effect.runPromiseExitWith(layerServices)(program).then(async (exit) => {
1187
+ return Effect.runPromiseExitWith(layerServices)(observeStep(workflow, step, program)).then(async (exit) => {
1173
1188
  if (Exit.isSuccess(exit)) {
1174
1189
  return exit.value;
1175
1190
  }
1176
1191
  const failure = stepFailure(exit.cause, requestId, step, workflow.manifest.name, [
1177
1192
  identityToken,
1178
1193
  options.cronSecret === undefined ? undefined : Redacted.value(options.cronSecret),
1179
- options.webhookSecret === undefined ? undefined : Redacted.value(options.webhookSecret),
1194
+ options.webhookSecret === undefined
1195
+ ? undefined
1196
+ : Redacted.value(options.webhookSecret),
1180
1197
  ]);
1181
1198
  console.error(JSON.stringify({
1182
1199
  event: "ontology.workflow.step.failed",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.203.1",
3
+ "version": "0.205.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",