@segmentstream/ontology 0.146.1 → 0.148.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.
@@ -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,17 @@
1
1
  import { Effect, type Scope } from "effect";
2
2
  import { ConnectionError, type ConnectionReply, type ConnectionStreamReply } from "../connection.js";
3
3
  export declare const CONNECTION_STREAM_MEDIA_TYPE = "application/vnd.segmentstream.proxy-stream.v1+ndjson";
4
+ /**
5
+ * The extra time a call that sends a stored file allows backend-next to read it from file
6
+ * storage before the provider request starts; backend-next's read deadline matches it.
7
+ */
8
+ export declare const STORED_FILE_READ_MS = 15000;
4
9
  /** Negotiates once; never retries a provider operation to change response formats. */
5
10
  export declare function openConnectionStream(input: {
6
11
  readonly connection: string;
7
12
  readonly request: (signal: AbortSignal) => Promise<Response>;
8
13
  readonly legacy: (value: unknown) => ConnectionReply;
9
14
  readonly refusal: (status: number, value: unknown, cause?: unknown) => ConnectionError;
15
+ /** Whether backend-next reads the body from file storage first, which takes longer. */
16
+ readonly storedFile?: boolean;
10
17
  }): Effect.Effect<ConnectionStreamReply, ConnectionError, Scope.Scope>;
@@ -5,6 +5,11 @@ const MAX_FRAME_BYTES = 128 * 1024;
5
5
  const MAX_CHUNK_BYTES = 65_536;
6
6
  const MAX_LEGACY_BYTES = 4 * 1024 * 1024;
7
7
  const CALL_TIMEOUT_MS = 40_000;
8
+ /**
9
+ * The extra time a call that sends a stored file allows backend-next to read it from file
10
+ * storage before the provider request starts; backend-next's read deadline matches it.
11
+ */
12
+ export const STORED_FILE_READ_MS = 15_000;
8
13
  function invalid(connection, cause) {
9
14
  return new ConnectionError({
10
15
  connection,
@@ -69,7 +74,10 @@ async function* frames(reader, connection) {
69
74
  export function openConnectionStream(input) {
70
75
  return Effect.gen(function* () {
71
76
  const controller = yield* Effect.acquireRelease(Effect.sync(() => new AbortController()), (controller) => Effect.sync(() => controller.abort()));
72
- const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(CALL_TIMEOUT_MS)]);
77
+ const signal = AbortSignal.any([
78
+ controller.signal,
79
+ AbortSignal.timeout(CALL_TIMEOUT_MS + (input.storedFile === true ? STORED_FILE_READ_MS : 0)),
80
+ ]);
73
81
  const failure = (cause) => {
74
82
  if (cause instanceof ConnectionError) {
75
83
  return cause;
@@ -104,9 +104,59 @@ function collected(connection, reply) {
104
104
  body: new Uint8Array(Buffer.concat(chunks)),
105
105
  })));
106
106
  }
107
- /** Shared admission and wire requests for buffered and streamed responses. */
108
- function transport(fetchImpl, resolve) {
109
- const open = (call) => resolve(call).pipe(Effect.flatMap((selected) => openConnectionStream({
107
+ /**
108
+ * A file's signed byte range, read by this process: the local proxy route takes no file, so a
109
+ * request run with `segmentstream exec` sends it inline, within the 2 MiB body limit.
110
+ */
111
+ function readFileRange(fetchImpl, connection, source) {
112
+ const length = source.end - source.start + 1;
113
+ if (length > MAXIMUM_CONNECTION_BODY_BYTES) {
114
+ return Effect.fail(failure(connection, "invalid_request", "file_inline_too_large"));
115
+ }
116
+ return Effect.tryPromise({
117
+ try: async (signal) => {
118
+ const response = await fetchImpl(source.url, {
119
+ headers: { ...source.headers, range: `bytes=${source.start}-${source.end}` },
120
+ redirect: "error",
121
+ signal,
122
+ });
123
+ const bytes = new Uint8Array(await response.arrayBuffer());
124
+ if (![200, 206].includes(response.status) || bytes.byteLength !== length) {
125
+ throw new Error(`file storage answered ${response.status} with ${bytes.byteLength} bytes`);
126
+ }
127
+ return bytes;
128
+ },
129
+ catch: (cause) => failure(connection, "unavailable", "file_storage_unavailable", undefined, cause),
130
+ });
131
+ }
132
+ /**
133
+ * Shared admission and wire requests for buffered and streamed responses. A deployed service
134
+ * sends a request's `file` as its signed read, which backend-next fetches from the workspace's
135
+ * file storage; `inlineFiles` reads it here instead and sends its bytes.
136
+ */
137
+ function transport(fetchImpl, resolve, options = {}) {
138
+ const payload = (call) => Effect.gen(function* () {
139
+ const source = call.source;
140
+ if (call.file !== undefined && source === undefined) {
141
+ return yield* Effect.fail(failure(call.connection, "invalid_request", "file_storage_unavailable"));
142
+ }
143
+ if (source === undefined) {
144
+ return { body: Buffer.from(call.body).toString("base64") };
145
+ }
146
+ if (options.inlineFiles === true) {
147
+ const bytes = yield* readFileRange(fetchImpl, call.connection, source);
148
+ return { body: Buffer.from(bytes).toString("base64") };
149
+ }
150
+ return {
151
+ file: {
152
+ url: source.url,
153
+ headers: Object.entries(source.headers),
154
+ start: source.start,
155
+ end: source.end,
156
+ },
157
+ };
158
+ });
159
+ const open = (call) => Effect.all([resolve(call), payload(call)]).pipe(Effect.flatMap(([selected, content]) => openConnectionStream({
110
160
  connection: call.connection,
111
161
  request: (signal) => fetchImpl(selected.url, {
112
162
  method: "POST",
@@ -120,13 +170,14 @@ function transport(fetchImpl, resolve) {
120
170
  method: selected.call.method,
121
171
  path: selected.call.path,
122
172
  headers: selected.call.headers,
123
- body: Buffer.from(selected.call.body).toString("base64"),
173
+ ...content,
124
174
  }),
125
175
  redirect: "error",
126
176
  signal,
127
177
  }),
128
178
  legacy: (value) => reply(call.connection, value),
129
179
  refusal: (status, value, cause) => refusal(call.connection, status, value, cause),
180
+ storedFile: "file" in content,
130
181
  })));
131
182
  return {
132
183
  request: (call) => open(call).pipe(Effect.flatMap((reply) => collected(call.connection, reply)), Effect.scoped),
@@ -183,7 +234,7 @@ export function localConnections(context, fetchImpl = fetch) {
183
234
  headers: { "x-segmentstream-connection-grant": context.proxyGrant },
184
235
  call: { ...call, api },
185
236
  });
186
- });
237
+ }, { inlineFiles: true });
187
238
  }
188
239
  function localConnection(value) {
189
240
  if (!isRecord(value) ||
@@ -12,8 +12,8 @@ export declare function normalizeSearch(text: string): string;
12
12
  /** Rank only caller-projected documents; forbidden fields never affect ranking or explanations. */
13
13
  export declare function searchDocuments(documents: ReadonlyArray<SearchDocument>, input: DiscoverInput): {
14
14
  readonly kind: "entity" | "metric" | "action";
15
- readonly name: string;
16
15
  readonly description: string;
16
+ readonly name: string;
17
17
  readonly label: string;
18
18
  readonly ref: string;
19
19
  readonly matched_on: readonly {
@@ -972,19 +972,20 @@ export function workflowsLayer(options) {
972
972
  "ConnectionError",
973
973
  ])),
974
974
  });
975
- const services = Context.make(OntologyReads, reads).pipe(Context.add(Files, backend.blobs?.files?.({
975
+ const files = backend.blobs?.files?.({
976
976
  principal,
977
977
  idempotencyKey: createHash("sha256")
978
978
  .update(`${step.workflowRunId}:${step.stepId}`)
979
979
  .digest("hex"),
980
- }) ?? unavailableFiles), Context.add(OntologyWrites, writes), Context.add(OntologyActions, actions), Context.merge(connectionContext(workflow.declaration.connections, options.connections({
980
+ }) ?? unavailableFiles;
981
+ const services = Context.make(OntologyReads, reads).pipe(Context.add(Files, files), Context.add(OntologyWrites, writes), Context.add(OntologyActions, actions), Context.merge(connectionContext(workflow.declaration.connections, options.connections({
981
982
  identityToken,
982
983
  audit: {
983
984
  action: `workflow.${workflow.manifest.name}`,
984
985
  principalId: principal.id,
985
986
  requestId,
986
987
  },
987
- }))));
988
+ }), { files })));
988
989
  console.info(JSON.stringify({
989
990
  event: "ontology.workflow.step.started",
990
991
  workflow: workflow.manifest.name,
@@ -682,6 +682,32 @@ export function blobRuntime(ontology, sql, provider, fetchImpl = fetch) {
682
682
  body: yield* openFile({ grant, size: Number(blob.size), fetch: fetchImpl }),
683
683
  };
684
684
  })),
685
+ source: (input) => publicErrors(Effect.gen(function* () {
686
+ const blob = yield* prepareDownload(input.entity, input.id, input.property, { revisionId: input.revisionId }, invocation.principal);
687
+ const size = Number(blob.size);
688
+ const start = input.start ?? 0;
689
+ const end = input.end ?? size - 1;
690
+ if (!Number.isSafeInteger(start) ||
691
+ !Number.isSafeInteger(end) ||
692
+ start < 0 ||
693
+ end < start ||
694
+ end >= size) {
695
+ return yield* new ActionRejected({ message: "file_range_invalid" });
696
+ }
697
+ const grant = yield* provider.download({
698
+ key: blob.key,
699
+ filename: blob.filename,
700
+ contentType: blob.content_type,
701
+ inline: false,
702
+ });
703
+ return {
704
+ url: grant.url,
705
+ headers: grant.headers,
706
+ start,
707
+ end,
708
+ contentType: blob.content_type,
709
+ };
710
+ })),
685
711
  });
686
712
  };
687
713
  return { begin, list, status, target, part, complete, cancel, download, downloadFile, files };
@@ -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.1",
3
+ "version": "0.148.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",