@segmentstream/ontology 0.204.0 → 0.206.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.206.0
4
+
5
+ A Telegram Mini App can opt into pairing the original sender with an invited workspace email account, with the same signed browser challenge as Cloud sign-in.
6
+
7
+ ## 0.205.0
8
+
9
+ 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.
10
+
3
11
  ## 0.204.0
4
12
 
5
13
  Workflow tasks can read messages from a registered group by record id within their existing `agent_chat:read` scope.
@@ -1,4 +1,4 @@
1
- import { type TokenVerifier } from "../authentication.js";
1
+ import { type SessionExchange, type TokenVerifier } from "../authentication.js";
2
2
  import type { OntologyServiceConfig } from "../config.js";
3
3
  import type { ConnectionTransportFactory } from "../connections.js";
4
4
  import { RequestId } from "../errors.js";
@@ -6,4 +6,4 @@ import { OntologyBackend } from "../runtime-contract.js";
6
6
  import type { ChannelAppProvider } from "./provider.js";
7
7
  /** A public button names the request. Telegram proves its original sender, then signs
8
8
  * a fresh challenge in the browser that completed Cloud login. Neither link is a credential. */
9
- export declare function telegramPairingLayer(config: OntologyServiceConfig, connections: ConnectionTransportFactory, telegram: ChannelAppProvider, connection: string, verifyToken: TokenVerifier): import("effect/Layer").Layer<never, never, OntologyBackend | import("effect/unstable/http/HttpRouter").HttpRouter | import("effect/unstable/http/HttpRouter").Request<"Requires", RequestId> | import("effect/unstable/http/HttpRouter").Request<"Error", import("effect/unstable/http/HttpServerError").HttpServerError>>;
9
+ export declare function telegramPairingLayer(config: OntologyServiceConfig, connections: ConnectionTransportFactory, telegram: ChannelAppProvider, connection: string, verifyToken: TokenVerifier, exchangeEmailSession?: SessionExchange): import("effect/Layer").Layer<never, never, OntologyBackend | import("effect/unstable/http/HttpRouter").HttpRouter | import("effect/unstable/http/HttpRouter").Request<"Requires", RequestId> | import("effect/unstable/http/HttpRouter").Request<"Error", import("effect/unstable/http/HttpServerError").HttpServerError>>;
@@ -2,7 +2,7 @@ import { randomBytes, randomUUID } from "node:crypto";
2
2
  import { Effect, Redacted } from "effect";
3
3
  import { HttpServerResponse } from "effect/unstable/http";
4
4
  import { use as routes } from "effect/unstable/http/HttpRouter";
5
- import { CurrentPrincipal, sessionMayAuthenticate, withPrincipal, } from "../authentication.js";
5
+ import { CurrentPrincipal, NEON_AUTH_SESSION_COOKIE, sessionMayAuthenticate, withPrincipal, } from "../authentication.js";
6
6
  import { FEDERATION_TOKEN_PREFIX } from "../../runtime/federation.js";
7
7
  import { botUsername } from "../chat/providers/telegram.js";
8
8
  import { identityToken } from "../operations.js";
@@ -11,7 +11,7 @@ import { clientAddress, fixedWindowLimiter } from "../rate-limit.js";
11
11
  import { OntologyBackend } from "../runtime-contract.js";
12
12
  const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
13
13
  const launch = new RegExp("^sslink_(" + UUID + ")$");
14
- const finish = new RegExp("^ssverify_(" + UUID + ")_([A-Za-z0-9_-]{32})$");
14
+ const finish = new RegExp("^ssverify(?:email)?_(" + UUID + ")_([A-Za-z0-9_-]{32})$");
15
15
  const json = (status, body, cookie) => HttpServerResponse.jsonUnsafe(body, {
16
16
  status,
17
17
  headers: {
@@ -21,7 +21,7 @@ const json = (status, body, cookie) => HttpServerResponse.jsonUnsafe(body, {
21
21
  });
22
22
  /** A public button names the request. Telegram proves its original sender, then signs
23
23
  * a fresh challenge in the browser that completed Cloud login. Neither link is a credential. */
24
- export function telegramPairingLayer(config, connections, telegram, connection, verifyToken) {
24
+ export function telegramPairingLayer(config, connections, telegram, connection, verifyToken, exchangeEmailSession) {
25
25
  const suffix = config.workspaceId.replace(/[^A-Za-z0-9_-]/g, "_");
26
26
  const cookieName = (id) => "__Host-ss_telegram_link." + suffix + "." + id;
27
27
  const cookie = (id, value, age) => cookieName(id) + "=" + value + "; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=" + age;
@@ -67,26 +67,50 @@ export function telegramPairingLayer(config, connections, telegram, connection,
67
67
  if (!pairing) {
68
68
  return json(403, { error: "pairing_unavailable" });
69
69
  }
70
+ // Telegram signs the chosen method along with the challenge on the second launch.
71
+ const email = initial
72
+ ? request.headers["x-segmentstream-pairing-method"] === "email"
73
+ : start.startsWith("ssverifyemail_");
74
+ if (email && !exchangeEmailSession) {
75
+ return json(403, { error: "email_pairing_unavailable" });
76
+ }
70
77
  if (initial) {
71
78
  const username = yield* botUsername(transport, connection);
72
79
  if (!username) {
73
80
  return json(503, { error: "bot_unavailable" });
74
81
  }
75
82
  const nonce = randomBytes(24).toString("base64url");
76
- const continuation = "ssverify_" + id + "_" + nonce;
83
+ const continuation = (email ? "ssverifyemail_" : "ssverify_") + id + "_" + nonce;
77
84
  return json(200, { reopen: "https://t.me/" + username + "?startapp=" + continuation }, cookie(id, continuation, 600));
78
85
  }
79
86
  if (request.cookies[cookieName(id)] !== start) {
80
87
  return json(403, { error: "browser_mismatch" });
81
88
  }
82
- const token = request.cookies["__Host-ss_oidc_session." + suffix];
83
- if (!token?.startsWith(FEDERATION_TOKEN_PREFIX)) {
89
+ let token = request.cookies["__Host-ss_oidc_session." + suffix];
90
+ if (email && exchangeEmailSession) {
91
+ const session = request.cookies[NEON_AUTH_SESSION_COOKIE];
92
+ if (!session) {
93
+ return json(401, { error: "email_login_required" });
94
+ }
95
+ const proof = yield* Effect.promise(() => exchangeEmailSession(Redacted.make(session), request.headers.origin));
96
+ if (proof.status === "unavailable") {
97
+ return json(503, { error: "sign_in_unavailable" });
98
+ }
99
+ if (proof.status !== "token") {
100
+ return json(401, { error: "email_login_required" });
101
+ }
102
+ token = proof.token;
103
+ }
104
+ if (!token || (!email && !token.startsWith(FEDERATION_TOKEN_PREFIX))) {
84
105
  return json(401, { error: "cloud_login_required" });
85
106
  }
86
107
  return yield* withPrincipal(Redacted.make(token), verifyToken, backend, Effect.gen(function* () {
87
108
  const member = yield* CurrentPrincipal;
88
- if (member.kind !== "member" || member.authenticatedVia !== "oidc") {
89
- return json(403, { error: "cloud_login_required" });
109
+ if (member.kind !== "member" ||
110
+ member.authenticatedVia !== (email ? "neon-auth" : "oidc")) {
111
+ return json(403, {
112
+ error: email ? "email_login_required" : "cloud_login_required",
113
+ });
90
114
  }
91
115
  const linked = yield* store
92
116
  .approvePairing({
@@ -69,6 +69,8 @@ export interface OntologyEnvironment {
69
69
  /** Explicit Mini App exchange opt-in; omitted means no exchange route. */
70
70
  readonly miniApp?: {
71
71
  readonly testPublicKeyHex?: string;
72
+ /** Offer verified workspace email sessions when linking a Telegram sender. */
73
+ readonly emailPairing?: boolean;
72
74
  };
73
75
  };
74
76
  };
@@ -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 }),
@@ -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";
@@ -563,8 +565,11 @@ export function createOntologyService(ontology, config) {
563
565
  });
564
566
  const application = Layer.mergeAll(channelApps.length > 0
565
567
  ? Layer.merge(channelSessionLayer(config), channelSignInLayer(channelApps, config, connections))
566
- : Layer.empty, !preview && telegram?.miniApp && telegramConnection && federationConfig
567
- ? telegramPairingLayer(config, connections, telegramAppProvider(telegramConnection, testKey), telegramConnection, verifyToken)
568
+ : Layer.empty, !preview &&
569
+ telegram?.miniApp &&
570
+ telegramConnection &&
571
+ (federationConfig || (telegram.miniApp.emailPairing && exchangeSession))
572
+ ? telegramPairingLayer(config, connections, telegramAppProvider(telegramConnection, testKey), telegramConnection, verifyToken, telegram.miniApp.emailPairing ? exchangeSession : undefined)
568
573
  : Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, withoutAgent
569
574
  ? Layer.empty
570
575
  : chatRoutes({
@@ -646,6 +651,15 @@ export function createOntologyService(ontology, config) {
646
651
  if (parts[1] === "api" && parts[2] === "ontology" && entity !== undefined) {
647
652
  return `/api/ontology/${entity.name}/*`;
648
653
  }
654
+ if (parts[1] === "api" && parts[2] === "ontology" && parts[3] === "workflows") {
655
+ const workflow = ontology.workflows.find((item) => item.name === parts[4]);
656
+ if (workflow) {
657
+ const trigger = parts[5] === "triggers" && workflow.triggers.find((item) => item.name === parts[6]);
658
+ return trigger
659
+ ? `/api/ontology/workflows/${workflow.name}/triggers/${trigger.name}`
660
+ : `/api/ontology/workflows/${workflow.name}`;
661
+ }
662
+ }
649
663
  if (parts[1] === "api" && parts[2] === "webhooks") {
650
664
  const declared = ontology.workflows.some((workflow) => workflow.triggers.some((trigger) => trigger.kind === "webhook" && trigger.name === parts[3]));
651
665
  // Never the token segment.
@@ -659,6 +673,7 @@ export function createOntologyService(ontology, config) {
659
673
  async handler(request) {
660
674
  const started = performance.now();
661
675
  const requestId = crypto.randomUUID();
676
+ const activity = new DatabaseActivity();
662
677
  const logMcpRequest = observeMcpRequest(request);
663
678
  let response;
664
679
  try {
@@ -688,7 +703,7 @@ export function createOntologyService(ontology, config) {
688
703
  throw new DeploymentAdmissionError("preview_authentication_unavailable");
689
704
  }
690
705
  }
691
- response = await web.handler(withCurrentEntityPath(request), Context.make(RequestId, requestId));
706
+ response = await web.handler(withCurrentEntityPath(request), Context.make(RequestId, requestId).pipe(Context.add(CurrentDatabaseActivity, activity), Context.add(Tracer.Tracer, activity.tracer(Tracer.nativeTracer))));
692
707
  }
693
708
  catch (error) {
694
709
  if (error instanceof DeploymentAdmissionError) {
@@ -715,7 +730,13 @@ export function createOntologyService(ontology, config) {
715
730
  status: response.status,
716
731
  durationMs,
717
732
  };
718
- console.info(JSON.stringify({ event: "ontology.request", ...timing }));
733
+ const route = timing.operation.split("/");
734
+ const cron = route[3] === "workflows" && route[5] === "triggers";
735
+ const databaseActivity = activity.measurement(cron ? "workflow:" + route[4] : timing.operation, {
736
+ target: deployment.target,
737
+ ...(cron ? { workflow: route[4], trigger: route[4] + "." + route[6] } : {}),
738
+ });
739
+ console.info(JSON.stringify({ event: "ontology.request", ...timing, databaseActivity }));
719
740
  await logMcpRequest?.(response, requestId, durationMs);
720
741
  return decorate(response, requestId, hash, durationMs);
721
742
  },
@@ -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.204.0",
3
+ "version": "0.206.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",