@segmentstream/ontology 0.146.0 → 0.147.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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.147.0
4
+
5
+ A member whom only SegmentStream app tokens signed in, such as the CLI's, can now sign in to the app
6
+ by email with the same address: Neon Auth links to the member and keeps the app-token identity, instead
7
+ of refusing the sign-in as an identity conflict. Any other identity on the member still conflicts.
8
+
9
+ Exact posts to the agent's Telegram bot (`chat_post_message`, `agent_chat.send`) open links to the app
10
+ in the bot's Mini App when the agent's `channels.telegram.appLinks` is `"miniApp"`, as its replies do:
11
+ only where a link or URL button leads changes, never the post's words or formatting. The platform passes
12
+ the setting with the channel's other settings at each deploy, so a workspace sees it after its next
13
+ `segmentstream deploy`. `@segmentstream/ontology/telegram` exports the Mini App link helpers
14
+ (`miniAppLink`, `telegramStartParam`, `isAppContentPage`) and `TELEGRAM_APP_LINKS`, which the agent SDK
15
+ now uses.
16
+
17
+ ## 0.146.1
18
+
19
+ Ontology replication sends what a warehouse load committed only once. A generation whose events a
20
+ load put in the warehouse no longer sends them all again through Pub/Sub when it starts serving,
21
+ oldest first, ahead of every change written since. Records whose projection a deploy did not change
22
+ stayed on such a generation, so their changes reached the warehouse hours or days late. Delivery
23
+ records the events an earlier version loaded as delivered on its next pass, with no deploy needed.
24
+
3
25
  ## 0.146.0
4
26
 
5
27
  `initialize` lists the channels a tool call's runtime source may name (`telegram`, `slack`,
package/README.md CHANGED
@@ -1240,6 +1240,9 @@ Every route but `status` and `sign-in/check` takes `Authorization: Bearer …`:
1240
1240
  service picks the verifier by the token's issuer; a token from any other issuer is a 401.
1241
1241
  A verified app-token email also resolves an existing Neon Auth member, without replacing
1242
1242
  the member's Neon identity. The service reads that member's current roles and active state.
1243
+ The other way, a member only app tokens signed in, such as the CLI's, moves to Neon Auth
1244
+ when that address signs in by email: the Neon identity is linked and the app-token one kept.
1245
+ Any other identity on the member still conflicts.
1243
1246
  - **API key.** `ssk_…`, held by a service user.
1244
1247
  - **Workload token.** Issued by SegmentStream for production operations and the exact preview
1245
1248
  workflow operations described above. Its subject
@@ -460,8 +460,15 @@ export const finishShadowSegment = (sql, segment, owner) => sql.withTransaction(
460
460
  if (!completed) {
461
461
  return false;
462
462
  }
463
- yield* sql.unsafe(`UPDATE _ontology_replication_delivery SET committed_at=now()
464
- WHERE segment_id=$1::uuid`, [segment.id]);
463
+ // The committed load put the segment's events in the warehouse: they are delivered, as a
464
+ // Pub/Sub receipt would record. Left pending, the generation would send them all again once
465
+ // it serves, oldest first, ahead of every change written since.
466
+ yield* sql.unsafe(`WITH loaded AS (
467
+ UPDATE _ontology_replication_delivery
468
+ SET committed_at=now(), accepted_at=COALESCE(accepted_at, now())
469
+ WHERE segment_id=$1::uuid RETURNING generation, event_id, accepted_at
470
+ ) INSERT INTO _ontology_replication_receipts (generation, event_id, accepted_at)
471
+ SELECT generation, event_id, accepted_at FROM loaded ON CONFLICT DO NOTHING`, [segment.id]);
465
472
  return true;
466
473
  }));
467
474
  export const retryShadowSegment = (sql, segment, owner, failure) => sql.unsafe(`UPDATE _ontology_replication_segments SET attempt=attempt+1,
@@ -26,6 +26,13 @@ export declare const pendingReplicationEvents: (sql: SqlClient.SqlClient, target
26
26
  readonly historyId: string;
27
27
  readonly event: ReplicationEvent;
28
28
  }[], import("effect/unstable/sql/SqlError").SqlError, never>;
29
+ /**
30
+ * Records as delivered, with receipts, the events of a generation an earlier SDK loaded into the
31
+ * warehouse without recording them, so that serving delivery does not send them through Pub/Sub
32
+ * again ahead of the changes written since. A committed load now records its own; this reads only
33
+ * the generation's undelivered rows.
34
+ */
35
+ export declare const recordLoadedReplicationEvents: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<void, import("effect/unstable/sql/SqlError").SqlError, never>;
29
36
  /** Acceptance comes only from Pub/Sub receipts; historical verification columns are not used. */
30
37
  export declare const replicationStatus: (sql: SqlClient.SqlClient, target: ReplicationTarget) => Effect.Effect<{
31
38
  total: string;
@@ -229,6 +229,22 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
229
229
  }
230
230
  return result;
231
231
  });
232
+ // @legacy ontology.replication-loaded-events-pending
233
+ /**
234
+ * Records as delivered, with receipts, the events of a generation an earlier SDK loaded into the
235
+ * warehouse without recording them, so that serving delivery does not send them through Pub/Sub
236
+ * again ahead of the changes written since. A committed load now records its own; this reads only
237
+ * the generation's undelivered rows.
238
+ */
239
+ export const recordLoadedReplicationEvents = (sql, generation) => sql.withTransaction(Effect.gen(function* () {
240
+ yield* shareReplicationLifecycle(sql);
241
+ yield* sql.unsafe(`WITH loaded AS (
242
+ UPDATE _ontology_replication_delivery SET accepted_at = committed_at
243
+ WHERE generation = $1::uuid AND accepted_at IS NULL AND committed_at IS NOT NULL
244
+ RETURNING event_id, accepted_at
245
+ ) INSERT INTO _ontology_replication_receipts (generation, event_id, accepted_at)
246
+ SELECT $1::uuid, event_id, accepted_at FROM loaded ON CONFLICT DO NOTHING`, [generation]);
247
+ }));
232
248
  /** Lost publish responses deliberately leave the same immutable IDs pending. */
233
249
  const acknowledgeReplicationV4 = (sql, generation, ids) => sql.withTransaction(Effect.gen(function* () {
234
250
  // Receipt foreign keys touch targets after delivery rows; drain before migration table locks.
@@ -210,6 +210,9 @@ export function resolvePrincipalById(ontology, sql, id) {
210
210
  return yield* activePrincipal(ontology, sql, userRow(record));
211
211
  });
212
212
  }
213
+ // @legacy app.legacy-segmentstream-sign-in
214
+ /** The provider of the deprecated SegmentStream app tokens, such as the CLI's. */
215
+ const LEGACY_SEGMENTSTREAM_PROVIDER = "segmentstream";
213
216
  /**
214
217
  * Finds the member's user without locking. Links or creates it transactionally when needed. A
215
218
  * user linked to this identity is found; else a member invited with the same email is linked; else
@@ -343,6 +346,23 @@ function signIn(ontology, sql, claims) {
343
346
  yield* recordIdentity(String(invited.id), "invite");
344
347
  return yield* member(invited);
345
348
  }
349
+ // @legacy app.legacy-segmentstream-sign-in
350
+ // A member only the deprecated SegmentStream app tokens (the CLI's) signed in moves to
351
+ // email sign-in, which replaces them: both verified this address, so it is the same
352
+ // person. The SegmentStream identity stays; any other identity still conflicts.
353
+ if (invited.kind === "member" &&
354
+ claims.identityProvider === NEON_AUTH_PROVIDER &&
355
+ held.length > 0 &&
356
+ held.every((identity) => identity.provider === LEGACY_SEGMENTSTREAM_PROVIDER) &&
357
+ (legacy === undefined || legacy.provider === LEGACY_SEGMENTSTREAM_PROVIDER)) {
358
+ const linkedUser = yield* writer.update(invited.id, {
359
+ identity_provider: claims.identityProvider,
360
+ identity_subject: claims.identitySubject,
361
+ ...(invited.active === true ? signedIn : {}),
362
+ });
363
+ yield* recordIdentity(String(invited.id), "link");
364
+ return userRow(linkedUser);
365
+ }
346
366
  if (invited.kind !== "member" ||
347
367
  held.length > 0 ||
348
368
  legacy !== undefined ||
@@ -9,9 +9,9 @@ export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
9
9
  * Render source independently so user Markdown cannot open an entity around the footer. Without an
10
10
  * attribution, as for a reply the agent sends after a member approved it, there is no footer.
11
11
  */
12
- export declare function renderTelegram(markdown: string, attribution: string, separator?: string): string;
12
+ export declare function renderTelegram(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string;
13
13
  /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
14
- export declare function telegramKeyboard(rows: ChatButtonRows): Readonly<Record<string, unknown>>;
14
+ export declare function telegramKeyboard(rows: ChatButtonRows, links?: ReadonlyMap<string, string>): Readonly<Record<string, unknown>>;
15
15
  interface TelegramSend {
16
16
  readonly transport: ConnectionTransport["Service"];
17
17
  readonly connection: string;
@@ -1,23 +1,89 @@
1
- import { telegramMarkdownLinks, telegramTextLinks, telegramPreviewOptions, } from "../../../telegram.js";
1
+ import { isTelegramBotUsername, miniAppLink, telegramMarkdownLinks, telegramMarkdownWithLinks, telegramTextLinks, telegramPreviewOptions, } from "../../../telegram.js";
2
2
  import { escapeMarkdownV2, TelegramFormatConverter } from "@chat-adapter/telegram";
3
3
  import { Effect } from "effect";
4
- import { record, transportFailure } from "./provider.js";
4
+ import { record, transportFailure, } from "./provider.js";
5
5
  export const TELEGRAM_MESSAGE_LIMIT = 4096;
6
6
  const converter = new TelegramFormatConverter();
7
7
  /**
8
8
  * Render source independently so user Markdown cannot open an entity around the footer. Without an
9
9
  * attribution, as for a reply the agent sends after a member approved it, there is no footer.
10
10
  */
11
- export function renderTelegram(markdown, attribution, separator = "\n\n") {
12
- return attribution === ""
11
+ export function renderTelegram(markdown, attribution, separator = "\n\n", links = new Map()) {
12
+ const body = links.size === 0
13
13
  ? converter.fromMarkdown(markdown)
14
- : `${converter.fromMarkdown(markdown)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_`;
14
+ : converter.fromAst(telegramMarkdownWithLinks(markdown, links));
15
+ return attribution === ""
16
+ ? body
17
+ : `${body}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_`;
18
+ }
19
+ /**
20
+ * The usernames of the bots this service looked up, by connection: a `t.me` link names its bot.
21
+ * Each is kept an hour, as the agent keeps its bot's identity, so links follow a connection that
22
+ * was authorized with another bot.
23
+ */
24
+ const botUsernames = new Map();
25
+ const BOT_USERNAME_TTL_MS = 60 * 60_000;
26
+ /** The bot's username from Telegram's `getMe`; undefined, and nothing cached, when it fails. */
27
+ function botUsername(transport, connection) {
28
+ const known = botUsernames.get(connection);
29
+ if (known !== undefined && known.until > Date.now()) {
30
+ return Effect.succeed(known.username);
31
+ }
32
+ return transport
33
+ .request({
34
+ connection,
35
+ api: "bot",
36
+ method: "POST",
37
+ path: "/getMe",
38
+ headers: [["content-type", "application/json"]],
39
+ body: new TextEncoder().encode("{}"),
40
+ })
41
+ .pipe(Effect.map((reply) => {
42
+ try {
43
+ const body = record(JSON.parse(new TextDecoder().decode(reply.body)));
44
+ const username = record(body.result).username;
45
+ if (reply.status >= 200 &&
46
+ reply.status < 300 &&
47
+ body.ok === true &&
48
+ typeof username === "string" &&
49
+ isTelegramBotUsername(username)) {
50
+ botUsernames.set(connection, { username, until: Date.now() + BOT_USERNAME_TTL_MS });
51
+ return username;
52
+ }
53
+ }
54
+ catch {
55
+ // An answer that is not JSON leaves the links as written.
56
+ }
57
+ return undefined;
58
+ }), Effect.catch(() => Effect.succeed(undefined)));
59
+ }
60
+ /**
61
+ * Where each link to the app opens when the agent opens them in its bot's Mini App
62
+ * (`appLinks: "miniApp"`) and this is that bot: the post's links that qualify, each to its `t.me`
63
+ * link. Any other destination, link or failed lookup leaves the links as written.
64
+ */
65
+ function miniAppLinksOf(input, links) {
66
+ const settings = input.previews?.settings;
67
+ if (settings?.appLinks !== "miniApp" || settings.connection !== input.connection) {
68
+ return Effect.succeed(new Map());
69
+ }
70
+ const origins = new Set([...(input.previews?.ownOrigins ?? []), ...(settings.additionalOwnOrigins ?? [])].flatMap((origin) => {
71
+ const parsed = URL.parse(origin);
72
+ return parsed === null ? [] : [parsed.origin];
73
+ }));
74
+ const candidates = [...new Set(links)].filter((url) => miniAppLink(url, origins, "bot") !== undefined);
75
+ if (candidates.length === 0) {
76
+ return Effect.succeed(new Map());
77
+ }
78
+ return botUsername(input.transport, input.connection).pipe(Effect.map((username) => new Map(username === undefined
79
+ ? []
80
+ : candidates.map((url) => [url, miniAppLink(url, origins, username)]))));
15
81
  }
16
82
  /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
17
- export function telegramKeyboard(rows) {
83
+ export function telegramKeyboard(rows, links = new Map()) {
18
84
  return {
19
85
  inline_keyboard: rows.map((row) => row.map((button) => "url" in button
20
- ? { text: button.text, url: button.url }
86
+ ? { text: button.text, url: links.get(button.url) ?? button.url }
21
87
  : { text: button.text, callback_data: `ws:${button.token}` })),
22
88
  };
23
89
  }
@@ -152,20 +218,40 @@ export const telegramProvider = {
152
218
  }),
153
219
  // An inline keyboard takes every row the schema allows; a token fits its callback data.
154
220
  refuseButtons: () => undefined,
155
- send: (input) => sendTelegram({
156
- transport: input.transport,
157
- connection: input.connection,
158
- destination: input.destination,
159
- finalText: input.finalText,
160
- formattedLinks: [
221
+ send: (input) => Effect.gen(function* () {
222
+ const written = [
161
223
  ...telegramMarkdownLinks(input.text),
162
224
  ...telegramTextLinks(input.separator),
163
225
  ...telegramTextLinks(input.attribution),
164
- ],
165
- ...(input.previews === undefined ? {} : { previews: input.previews }),
166
- plainText: input.plainText,
167
- replyTo: input.replyTo,
168
- ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
169
- ...(input.buttons === undefined ? {} : { replyMarkup: telegramKeyboard(input.buttons) }),
226
+ ];
227
+ // Only where a link to the app leads changes: the text reads as the member approved it.
228
+ const buttonUrls = (input.buttons ?? []).flatMap((row) => row.flatMap((button) => ("url" in button ? [button.url] : [])));
229
+ const links = yield* miniAppLinksOf(input, [
230
+ ...telegramMarkdownLinks(input.text),
231
+ ...buttonUrls,
232
+ ]);
233
+ // Previews are chosen from the links as written. Telegram previews the first link it gets,
234
+ // so with every preview on, one that now opens the Mini App names the app's page instead.
235
+ const first = written[0];
236
+ const preview = input.previews?.settings?.linkPreviews === "all" && first !== undefined && links.has(first)
237
+ ? { link_preview_options: { url: first } }
238
+ : {};
239
+ return yield* sendTelegram({
240
+ transport: input.transport,
241
+ connection: input.connection,
242
+ destination: input.destination,
243
+ finalText: links.size === 0
244
+ ? input.finalText
245
+ : renderTelegram(input.text, input.attribution, input.separator, links),
246
+ formattedLinks: written,
247
+ ...(input.previews === undefined ? {} : { previews: input.previews }),
248
+ ...preview,
249
+ plainText: input.plainText,
250
+ replyTo: input.replyTo,
251
+ ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
252
+ ...(input.buttons === undefined
253
+ ? {}
254
+ : { replyMarkup: telegramKeyboard(input.buttons, links) }),
255
+ });
170
256
  }),
171
257
  };
@@ -1,10 +1,16 @@
1
+ import { TelegramFormatConverter } from "@chat-adapter/telegram";
1
2
  export declare const TELEGRAM_LINK_PREVIEWS: readonly ["external", "none", "all"];
2
3
  export type TelegramLinkPreviews = (typeof TELEGRAM_LINK_PREVIEWS)[number];
4
+ export declare const TELEGRAM_APP_LINKS: readonly ["web", "miniApp"];
5
+ /** How a link to the workspace's app opens from Telegram: in a browser, or in the Mini App. */
6
+ export type TelegramAppLinks = (typeof TELEGRAM_APP_LINKS)[number];
3
7
  /** Settings belong to the destination connection, independently of the source channel. */
4
8
  export interface TelegramPreviewSettings {
5
9
  readonly connection: string;
6
10
  readonly linkPreviews?: TelegramLinkPreviews;
7
11
  readonly additionalOwnOrigins?: readonly string[];
12
+ /** The agent's `channels.telegram.appLinks`: `miniApp` opens links to the app in its bot. */
13
+ readonly appLinks?: TelegramAppLinks;
8
14
  }
9
15
  export interface TelegramPreviewContext {
10
16
  readonly settings?: TelegramPreviewSettings;
@@ -16,6 +22,7 @@ export interface TelegramLinkEntity {
16
22
  readonly length: number;
17
23
  readonly url?: string;
18
24
  }
25
+ declare const converter: TelegramFormatConverter;
19
26
  /** Normalize HTTP(S) origins only; credential-bearing and non-web destinations are ineligible. */
20
27
  export declare function httpOrigin(value: string): string | undefined;
21
28
  export declare function isHttpOrigin(value: unknown): value is string;
@@ -28,8 +35,29 @@ export declare function telegramPreviewEnvironment(environment: Readonly<Record<
28
35
  };
29
36
  readonly appOrigins: string[];
30
37
  };
38
+ /**
39
+ * Source Markdown's tree with each link `links` maps pointing there instead: a Markdown link keeps
40
+ * its label, and a bare URL becomes a link labelled with itself, so the text reads the same. Code
41
+ * stays as written.
42
+ */
43
+ export declare function telegramMarkdownWithLinks(markdown: string, links: ReadonlyMap<string, string>): ReturnType<typeof converter.toAst>;
31
44
  export declare function telegramMarkdownLinks(markdown: string): readonly string[];
32
45
  /** Visible URLs and hidden destinations, excluding formatted code and linked-label lookalikes. */
33
46
  export declare function telegramTextLinks(text: string, entities?: readonly TelegramLinkEntity[]): readonly string[];
34
47
  /** Explicit modern > explicit legacy > channel mode > external default. Never merge caller options. */
35
48
  export declare function telegramPreviewOptions(caller: Readonly<Record<string, unknown>>, links: readonly string[], context?: TelegramPreviewContext): Record<string, unknown>;
49
+ /**
50
+ * Whether a link may open the app's page at `pathname`: a local path, also once decoded, that is
51
+ * not an API, an asset, or a page where the member decides something.
52
+ */
53
+ export declare function isAppContentPage(pathname: string): boolean;
54
+ /** The `startapp` value of a page's path and query, or `undefined` when it does not fit. */
55
+ export declare function telegramStartParam(page: string): string | undefined;
56
+ /**
57
+ * The link that opens `url` in the bot's Main Mini App, or `undefined` when it stays as it is: a
58
+ * link to another origin, to a page that is not content, or whose page does not fit.
59
+ */
60
+ export declare function miniAppLink(url: string, origins: ReadonlySet<string>, botUsername: string): string | undefined;
61
+ /** A username Telegram accepts in a `t.me` link; any other leaves every link as it is. */
62
+ export declare function isTelegramBotUsername(username: string): boolean;
63
+ export {};
package/dist/telegram.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { TelegramFormatConverter } from "@chat-adapter/telegram";
2
2
  import { Lexer, Tokenizer } from "marked";
3
3
  export const TELEGRAM_LINK_PREVIEWS = ["external", "none", "all"];
4
+ export const TELEGRAM_APP_LINKS = ["web", "miniApp"];
4
5
  const converter = new TelegramFormatConverter();
5
6
  const urlTokenizer = new Tokenizer({ gfm: true });
6
7
  const visibleUrlStart = new RegExp(String.raw `(?<![\p{L}\p{N}_@/.:+-])(?:https?:\/\/|(?:` +
@@ -29,7 +30,8 @@ export function validateTelegramPreviews(settings) {
29
30
  !TELEGRAM_LINK_PREVIEWS.includes(settings.linkPreviews)) ||
30
31
  (settings.additionalOwnOrigins !== undefined &&
31
32
  (!Array.isArray(settings.additionalOwnOrigins) ||
32
- !settings.additionalOwnOrigins.every(isHttpOrigin)))) {
33
+ !settings.additionalOwnOrigins.every(isHttpOrigin))) ||
34
+ (settings.appLinks !== undefined && !TELEGRAM_APP_LINKS.includes(settings.appLinks))) {
33
35
  throw new Error("Invalid Telegram channel preview settings.");
34
36
  }
35
37
  }
@@ -76,6 +78,56 @@ function bareLinks(text) {
76
78
  return token && httpOrigin(token.href) ? [{ url: token.href, offset: match.index, end }] : [];
77
79
  });
78
80
  }
81
+ /**
82
+ * Source Markdown's tree with each link `links` maps pointing there instead: a Markdown link keeps
83
+ * its label, and a bare URL becomes a link labelled with itself, so the text reads the same. Code
84
+ * stays as written.
85
+ */
86
+ export function telegramMarkdownWithLinks(markdown, links) {
87
+ const tree = converter.toAst(markdown);
88
+ const visit = (node) => {
89
+ if (node.type === "code" || node.type === "inlineCode") {
90
+ return;
91
+ }
92
+ if (node.type === "link" && node.url !== undefined) {
93
+ node.url = links.get(node.url) ?? node.url;
94
+ return;
95
+ }
96
+ if (node.children === undefined) {
97
+ return;
98
+ }
99
+ node.children = node.children.flatMap((child) => {
100
+ if (child.type !== "text" || child.value === undefined) {
101
+ visit(child);
102
+ return [child];
103
+ }
104
+ const text = child.value;
105
+ const parts = [];
106
+ let from = 0;
107
+ for (const link of bareLinks(text)) {
108
+ const target = links.get(link.url);
109
+ if (target === undefined) {
110
+ continue;
111
+ }
112
+ if (link.offset > from) {
113
+ parts.push({ type: "text", value: text.slice(from, link.offset) });
114
+ }
115
+ const label = text.slice(link.offset, link.end);
116
+ parts.push({ type: "link", url: target, children: [{ type: "text", value: label }] });
117
+ from = link.end;
118
+ }
119
+ if (parts.length === 0) {
120
+ return [child];
121
+ }
122
+ if (from < text.length) {
123
+ parts.push({ type: "text", value: text.slice(from) });
124
+ }
125
+ return parts;
126
+ });
127
+ };
128
+ visit(tree);
129
+ return tree;
130
+ }
79
131
  /** Parse source Markdown, never escaped Telegram MarkdownV2. AST offsets are UTF-16. */
80
132
  function markdownLinks(markdown, plain = false) {
81
133
  const links = [];
@@ -171,3 +223,86 @@ export function telegramPreviewOptions(caller, links, context = {}) {
171
223
  link_preview_options: external === undefined ? { is_disabled: true } : { url: external },
172
224
  };
173
225
  }
226
+ /**
227
+ * Links to the workspace's own app that open in the bot's Main Mini App instead of a browser,
228
+ * when `channels.telegram.appLinks` is `miniApp`: the agent's replies and the ontology's posts to
229
+ * the agent's bot share them.
230
+ *
231
+ * A page travels as Telegram's `startapp` parameter, which allows only `[A-Za-z0-9_-]` and at most
232
+ * 512 characters: `p_`, then the page's path and query as `encodeURIComponent` writes them, with
233
+ * `_ . ! ~ * ' ( )` escaped as well and every `%` written as `_`. The page's fragment is not
234
+ * carried: a redirect that named one would replace the fragment Telegram signs the launch with.
235
+ * The app SDK's proxy decodes the parameter and opens the page, where the Mini App sign-in signs
236
+ * the reader in. `tests/fixtures/telegram-app-links.json` is the contract the SDKs test against.
237
+ */
238
+ const START_PARAM_PREFIX = "p_";
239
+ const MAXIMUM_START_PARAM_LENGTH = 512;
240
+ /**
241
+ * The app SDK's paths that are not pages (`NON_PAGE_PATHS` in its `pages.ts`), and its decision
242
+ * pages (`decision-pages.ts`), where the member decides something a link must not open on its own,
243
+ * including `/agent/connect`, whose pairing keeps its own destination. The channel session paths
244
+ * are under `/api`. These SDKs do not depend on the app SDK, so these mirror its lists; the shared
245
+ * fixture holds them to the same pages.
246
+ */
247
+ const NOT_LINKED_PATHS = [
248
+ "/api",
249
+ "/mcp",
250
+ "/.well-known",
251
+ "/_next",
252
+ "/oauth/consent",
253
+ "/agent/connect",
254
+ "/sign-in",
255
+ ];
256
+ const UNSAFE_CHARACTERS = /[\\\u0000-\u001f\u007f]/u;
257
+ function underPath(pathname, prefix) {
258
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
259
+ }
260
+ /**
261
+ * Whether a link may open the app's page at `pathname`: a local path, also once decoded, that is
262
+ * not an API, an asset, or a page where the member decides something.
263
+ */
264
+ export function isAppContentPage(pathname) {
265
+ let decoded;
266
+ try {
267
+ decoded = decodeURIComponent(pathname);
268
+ }
269
+ catch {
270
+ return false;
271
+ }
272
+ return [pathname, decoded].every((path) => path.startsWith("/") &&
273
+ !path.startsWith("//") &&
274
+ !UNSAFE_CHARACTERS.test(path) &&
275
+ !NOT_LINKED_PATHS.some((prefix) => underPath(path, prefix)));
276
+ }
277
+ /** The `startapp` value of a page's path and query, or `undefined` when it does not fit. */
278
+ export function telegramStartParam(page) {
279
+ const startParam = START_PARAM_PREFIX +
280
+ encodeURIComponent(page)
281
+ .replace(/[_.!~*'()]/gu, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)
282
+ .replaceAll("%", "_");
283
+ return startParam.length <= MAXIMUM_START_PARAM_LENGTH ? startParam : undefined;
284
+ }
285
+ /**
286
+ * The link that opens `url` in the bot's Main Mini App, or `undefined` when it stays as it is: a
287
+ * link to another origin, to a page that is not content, or whose page does not fit.
288
+ */
289
+ export function miniAppLink(url, origins, botUsername) {
290
+ const parsed = URL.parse(url);
291
+ if (parsed === null ||
292
+ (parsed.protocol !== "https:" && parsed.protocol !== "http:") ||
293
+ parsed.username !== "" ||
294
+ parsed.password !== "" ||
295
+ !origins.has(parsed.origin) ||
296
+ !isAppContentPage(parsed.pathname) ||
297
+ UNSAFE_CHARACTERS.test(parsed.search)) {
298
+ return undefined;
299
+ }
300
+ const startParam = telegramStartParam(`${parsed.pathname}${parsed.search}`);
301
+ return startParam === undefined
302
+ ? undefined
303
+ : `https://t.me/${botUsername}?startapp=${startParam}`;
304
+ }
305
+ /** A username Telegram accepts in a `t.me` link; any other leaves every link as it is. */
306
+ export function isTelegramBotUsername(username) {
307
+ return /^[A-Za-z0-9_]{1,64}$/u.test(username);
308
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.146.0",
3
+ "version": "0.147.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",