@segmentstream/ontology 0.198.0 → 0.200.1

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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.200.1
4
+
5
+ A role can scope `agent_chat:send` to registered destination chat records. The ontology check recognizes the built-in send action's destination check before provider delivery.
6
+
7
+ ## 0.200.0
8
+
9
+ An agent preview can import and search chat history in its own database. Existing member permissions and chat scopes apply to the fixture messages. A new preview starts with an empty chat history.
10
+
11
+ ## 0.199.0
12
+
13
+ Support sender-verified Telegram Mini App pairing in groups and personal chats. Workspace admission can check the delivery chat and require a Cloud sign-in before the agent starts a turn.
14
+
3
15
  ## 0.198.0
4
16
 
5
17
  A user who leaves keeps no credential of an owned connection (`owner="user"`). Once an action that
package/dist/analyze.js CHANGED
@@ -3790,10 +3790,17 @@ function checkScope(input) {
3790
3790
  return;
3791
3791
  }
3792
3792
  const unscopable = entities
3793
- .flatMap((candidate) => candidate.actions.map((action) => ({ entity: candidate.name, action })))
3794
- .find(({ action }) => openingPermissions(action).includes(permission) && writesNothing(action));
3793
+ .flatMap((entity) => entity.actions.map((action) => ({ entity, action })))
3794
+ .find(({ entity, action }) => {
3795
+ // The built-in agent voice checks its exact destination record in prepare, before sending.
3796
+ const scopedDelivery = permission === "agent_chat:send" &&
3797
+ entity.builtIn &&
3798
+ entity.name === AgentChat.name &&
3799
+ action.name === "send";
3800
+ return (openingPermissions(action).includes(permission) && writesNothing(action) && !scopedDelivery);
3801
+ });
3795
3802
  if (unscopable !== undefined) {
3796
- report("invalid-scope", path, `${permission} runs ${unscopable.entity}.${unscopable.action.name}, a readOnly or ` +
3803
+ report("invalid-scope", path, `${permission} runs ${unscopable.entity.name}.${unscopable.action.name}, a readOnly or ` +
3797
3804
  "prepare-only action that writes nothing a scope could check; list it as a string, or " +
3798
3805
  "give the action a handler that writes the record.");
3799
3806
  return;
@@ -414,6 +414,8 @@ export function sqlAgentStore(ontology, sql) {
414
414
  return inserted.length > 0;
415
415
  }))
416
416
  .pipe(Effect.orDie),
417
+ telegramLaunchPairing: (id, sender) => rows(`SELECT "code_hash" FROM ${PAIRINGS} WHERE "id" = $1::uuid AND "provider" = 'telegram'
418
+ AND "external_id" = $2 AND "expires_at" > now()`, [id, sender]).pipe(Effect.map(([row]) => (row ? { codeHash: String(row.code_hash) } : undefined))),
417
419
  findPairing: (codeHash) => rows([
418
420
  `SELECT ${PAIRING_COLUMNS}`,
419
421
  `FROM ${PAIRINGS}`,
@@ -4,13 +4,13 @@ import { type SessionExchange, type TokenVerifier } from "../authentication.js";
4
4
  import { RequestId } from "../errors.js";
5
5
  import { OntologyBackend } from "../runtime-contract.js";
6
6
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
7
- import { type ChatArchiveTransport } from "./chat-archive.js";
7
+ import { type ChatHistorySource } from "../chat/local-reads.js";
8
8
  /**
9
9
  * Same member scope as MCP, accessible to app clients with their usual bearer/session.
10
10
  * @legacy agent.legacy-conversation-routes The route keeps its published path until it is removed.
11
11
  */
12
12
  export declare function archiveRoutes(options: {
13
- readonly transport: ChatArchiveTransport;
13
+ readonly transport: ChatHistorySource;
14
14
  /** The days the ontology declares it keeps its chats' messages, if it declares them. */
15
15
  readonly chatRetentionDays?: number | undefined;
16
16
  readonly verifyToken: TokenVerifier;
@@ -98,6 +98,10 @@ export declare const ResolveIdentityRequest: Schema.Struct<{
98
98
  readonly provider: Schema.String;
99
99
  readonly external_id: Schema.String;
100
100
  readonly display: Schema.optionalKey<Schema.NullOr<Schema.String>>;
101
+ readonly delivery: Schema.optionalKey<Schema.Struct<{
102
+ readonly channel: Schema.String;
103
+ readonly chat_id: Schema.String;
104
+ }>>;
101
105
  }>;
102
106
  export declare const IdentityNoticeRequest: Schema.Struct<{
103
107
  readonly provider: Schema.String;
@@ -107,6 +107,10 @@ export const GuestSignUpRequest = Schema.Union([
107
107
  }),
108
108
  ]);
109
109
  export const ResolveIdentityRequest = Schema.Struct({
110
+ delivery: Schema.optionalKey(Schema.Struct({
111
+ channel: ChatChannelName,
112
+ chat_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
113
+ })),
110
114
  ...PairingRequest.fields,
111
115
  chat: Schema.Literals(["private", "group"]),
112
116
  turn: Schema.Boolean,
@@ -109,8 +109,9 @@ function createPairing(store, limiter) {
109
109
  for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt++) {
110
110
  const code = newPairingCode();
111
111
  const expiresAt = new Date(Date.now() + PAIRING_TTL_MS);
112
+ const id = randomUUID();
112
113
  const saved = yield* store.savePairing({
113
- id: randomUUID(),
114
+ id,
114
115
  codeHash: secretHash(code),
115
116
  provider,
116
117
  externalId,
@@ -118,7 +119,7 @@ function createPairing(store, limiter) {
118
119
  expiresAt,
119
120
  });
120
121
  if (saved) {
121
- return json({ code, expires_at: expiresAt.toISOString() }, 201);
122
+ return json({ id, code, expires_at: expiresAt.toISOString() }, 201);
122
123
  }
123
124
  }
124
125
  return yield* Effect.die(new Error("No free pairing code after several attempts."));
@@ -207,8 +208,10 @@ function resolveChannelIdentity(store, agentTools, guest) {
207
208
  if (Result.isFailure(decoded)) {
208
209
  return invalidBody(requestId, schemaIssues(decoded.failure));
209
210
  }
210
- const { external_id: externalId, notice_version, notice_sha256, address_verified, ...input } = decoded.success;
211
- const resolution = yield* store.resolveIdentity({
211
+ const { external_id: externalId, notice_version, notice_sha256, address_verified, delivery, ...input } = decoded.success;
212
+ const resolve = store.inboundIdentity?.get(input.provider) ?? store.resolveIdentity;
213
+ const resolution = yield* resolve({
214
+ ...(delivery && { delivery: { channel: delivery.channel, chatId: delivery.chat_id } }),
212
215
  ...input,
213
216
  externalId,
214
217
  ...(notice_version === undefined ? {} : { noticeVersion: notice_version }),
@@ -0,0 +1,9 @@
1
+ import { type TokenVerifier } from "../authentication.js";
2
+ import type { OntologyServiceConfig } from "../config.js";
3
+ import type { ConnectionTransportFactory } from "../connections.js";
4
+ import { RequestId } from "../errors.js";
5
+ import { OntologyBackend } from "../runtime-contract.js";
6
+ import type { ChannelAppProvider } from "./provider.js";
7
+ /** A public button names the request. Telegram proves its original sender, then signs
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>>;
@@ -0,0 +1,114 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { Effect, Redacted } from "effect";
3
+ import { HttpServerResponse } from "effect/unstable/http";
4
+ import { use as routes } from "effect/unstable/http/HttpRouter";
5
+ import { CurrentPrincipal, sessionMayAuthenticate, withPrincipal, } from "../authentication.js";
6
+ import { FEDERATION_TOKEN_PREFIX } from "../../runtime/federation.js";
7
+ import { botUsername } from "../chat/providers/telegram.js";
8
+ import { identityToken } from "../operations.js";
9
+ import { RequestId } from "../errors.js";
10
+ import { clientAddress, fixedWindowLimiter } from "../rate-limit.js";
11
+ import { OntologyBackend } from "../runtime-contract.js";
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
+ const launch = new RegExp("^sslink_(" + UUID + ")$");
14
+ const finish = new RegExp("^ssverify_(" + UUID + ")_([A-Za-z0-9_-]{32})$");
15
+ const json = (status, body, cookie) => HttpServerResponse.jsonUnsafe(body, {
16
+ status,
17
+ headers: {
18
+ "cache-control": "no-store",
19
+ ...(cookie && { "set-cookie": cookie }),
20
+ },
21
+ });
22
+ /** A public button names the request. Telegram proves its original sender, then signs
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) {
25
+ const suffix = config.workspaceId.replace(/[^A-Za-z0-9_-]/g, "_");
26
+ const cookieName = (id) => "__Host-ss_telegram_link." + suffix + "." + id;
27
+ const cookie = (id, value, age) => cookieName(id) + "=" + value + "; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=" + age;
28
+ const limiter = fixedWindowLimiter({ limit: 30, windowMs: 60000, maxKeys: 10000 });
29
+ return routes((router) => Effect.gen(function* () {
30
+ const backend = yield* OntologyBackend;
31
+ const store = backend.agents;
32
+ if (!store?.telegramLaunchPairing) {
33
+ return;
34
+ }
35
+ const read = store.telegramLaunchPairing;
36
+ yield* router.add("POST", "/api/ontology/agent/telegram-link", (request) => Effect.gen(function* () {
37
+ if (!sessionMayAuthenticate(request)) {
38
+ return json(403, { error: "cross_origin_session" });
39
+ }
40
+ if (limiter.take(clientAddress(request)) !== undefined) {
41
+ return json(429, { error: "rate_limited" });
42
+ }
43
+ const assertion = yield* request.text;
44
+ if (assertion.length > 16384) {
45
+ return json(400, { error: "invalid_assertion" });
46
+ }
47
+ const transport = connections({
48
+ identityToken: identityToken(request),
49
+ audit: {
50
+ action: "agent.telegram_link",
51
+ principalId: "anonymous",
52
+ requestId: yield* RequestId,
53
+ },
54
+ });
55
+ const identity = yield* telegram.verify(assertion, { connections: transport });
56
+ if (!identity) {
57
+ return json(403, { error: "invalid_assertion" });
58
+ }
59
+ const start = new URLSearchParams(assertion).get("start_param") ?? "";
60
+ const initial = launch.exec(start);
61
+ const completed = finish.exec(start);
62
+ const id = initial?.[1] ?? completed?.[1];
63
+ if (!id) {
64
+ return json(400, { error: "invalid_launch" });
65
+ }
66
+ const pairing = yield* read(id, identity.externalId);
67
+ if (!pairing) {
68
+ return json(403, { error: "pairing_unavailable" });
69
+ }
70
+ if (initial) {
71
+ const username = yield* botUsername(transport, connection);
72
+ if (!username) {
73
+ return json(503, { error: "bot_unavailable" });
74
+ }
75
+ const nonce = randomBytes(24).toString("base64url");
76
+ const continuation = "ssverify_" + id + "_" + nonce;
77
+ return json(200, { reopen: "https://t.me/" + username + "?startapp=" + continuation }, cookie(id, continuation, 600));
78
+ }
79
+ if (request.cookies[cookieName(id)] !== start) {
80
+ return json(403, { error: "browser_mismatch" });
81
+ }
82
+ const token = request.cookies["__Host-ss_oidc_session." + suffix];
83
+ if (!token?.startsWith(FEDERATION_TOKEN_PREFIX)) {
84
+ return json(401, { error: "cloud_login_required" });
85
+ }
86
+ return yield* withPrincipal(Redacted.make(token), verifyToken, backend, Effect.gen(function* () {
87
+ const member = yield* CurrentPrincipal;
88
+ if (member.kind !== "member" || member.authenticatedVia !== "oidc") {
89
+ return json(403, { error: "cloud_login_required" });
90
+ }
91
+ const linked = yield* store
92
+ .approvePairing({
93
+ codeHash: pairing.codeHash,
94
+ userId: member.id,
95
+ identityId: randomUUID(),
96
+ })
97
+ .pipe(Effect.catchTag("IdentityInUse", () => Effect.succeed("conflict")));
98
+ if (linked === "conflict") {
99
+ return json(409, { error: "identity_in_use" });
100
+ }
101
+ if (!linked) {
102
+ const owner = yield* store.findIdentity({
103
+ provider: "telegram",
104
+ externalId: identity.externalId,
105
+ });
106
+ if (!owner || owner.revokedAt !== null || owner.userId !== member.id) {
107
+ return json(410, { error: "pairing_expired" });
108
+ }
109
+ }
110
+ return json(200, { linked: true }, cookie(id, "", 0));
111
+ }));
112
+ }));
113
+ }));
114
+ }
@@ -41,6 +41,6 @@ agent?: {
41
41
  readonly fetch?: AgentChannelTransport["fetch"];
42
42
  },
43
43
  /** The archive a chat's earlier history is imported to; without it nothing is. */
44
- history?: HistoryArchive,
44
+ history?: HistoryArchive | "workspace",
45
45
  /** The chat archive's reads, which find the chat a person writes from on a channel. */
46
46
  chats?: ChatArchiveTransport): ChatDeliveryFactory;
@@ -72,7 +72,7 @@ export declare function historyImporter(input: {
72
72
  readonly identityToken: string | undefined;
73
73
  readonly requestId: string;
74
74
  /** @legacy agent.cloud-chat-archive */
75
- readonly archive: HistoryArchive;
75
+ readonly archive: HistoryArchive | "workspace";
76
76
  /** How long the workspace keeps its chats' messages: an older one is not imported. */
77
77
  readonly retentionDays: number;
78
78
  /** The kind of the agent's channel `name`, which its files' attachments name as their source. */
@@ -344,7 +344,7 @@ export function historyImporter(input) {
344
344
  }
345
345
  const store = backend.agents?.chatMessages;
346
346
  // The store holds the agent's messages: the chat's history joins them there.
347
- if (store !== undefined && (yield* store.holds())) {
347
+ if (store !== undefined && (input.archive === "workspace" || (yield* store.holds()))) {
348
348
  const kind = input.channelKind(history.provider);
349
349
  return yield* importLocally({
350
350
  backend,
@@ -358,6 +358,9 @@ export function historyImporter(input) {
358
358
  : "channel",
359
359
  });
360
360
  }
361
+ if (input.archive === "workspace") {
362
+ return yield* new ActionRejected({ message: "The workspace chat store is unavailable." });
363
+ }
361
364
  // @legacy agent.cloud-chat-archive Until the agent records into the store, the archive in
362
365
  // Cloud takes the history, as it takes the agent's messages: text alone.
363
366
  if (uploads.length > 0 ||
@@ -1,6 +1,8 @@
1
1
  import { type ChatMessage } from "../../runtime/chat-messages.js";
2
- import type { ChatArchiveTransport } from "../agent/chat-archive.js";
2
+ import { type ChatArchiveTransport } from "../agent/chat-archive.js";
3
3
  import type { OntologyBackend } from "../runtime-contract.js";
4
+ /** A preview reads its own branch even before the first message is imported. */
5
+ export type ChatHistorySource = ChatArchiveTransport | "workspace";
4
6
  /**
5
7
  * A message of the workspace's chat store as an event of the chat archive's pages, which
6
8
  * `chat_history` and `chat_search` have always answered: the archive's fields, and the message's
@@ -70,4 +72,4 @@ export declare function chatMessageEvent(message: ChatMessage): {
70
72
  * (`internal`). Reads after a `revision`, or before a cursor of the store, are the store's alone.
71
73
  * Any other read goes to `transport`, within the retention the ontology declares, `retentionDays`.
72
74
  */
73
- export declare function withChatStore(transport: ChatArchiveTransport, backend: OntologyBackend["Service"], retentionDays: number | undefined): ChatArchiveTransport;
75
+ export declare function withChatStore(transport: ChatHistorySource, backend: OntologyBackend["Service"], retentionDays: number | undefined): ChatArchiveTransport;
@@ -2,6 +2,7 @@ import { Clock, Effect } from "effect";
2
2
  import { ActionRejected, PermissionDenied } from "../../errors.js";
3
3
  import { isAllowed } from "../../permissions.js";
4
4
  import { parseChatCursor, } from "../../runtime/chat-messages.js";
5
+ import { ChatArchiveUnavailable } from "../agent/chat-archive.js";
5
6
  /** A cursor of the chat archive in Cloud: its sequence, negative for imported history. */
6
7
  const ARCHIVE_SEQUENCE = /^-?\d+$/;
7
8
  /** The sender the chat archive gives the agent's own messages; `author` says it now. */
@@ -107,15 +108,24 @@ export function withChatStore(transport, backend, retentionDays) {
107
108
  ? undefined
108
109
  : { channel: search.provider, chatId: search.chatId };
109
110
  if (store === undefined ||
110
- !(after !== undefined ||
111
+ !(transport === "workspace" ||
112
+ after !== undefined ||
111
113
  cursor !== undefined ||
112
114
  (search.before === undefined && (yield* store.holds(chat))))) {
113
115
  // @legacy agent.cloud-chat-archive A chat the store does not hold, a search of every chat
114
116
  // while the store holds no message, and a page of the archive's own are read from the
115
117
  // chat archive in Cloud. A chat whose messages the store purged reads there too, never
116
118
  // beyond the declared retention.
119
+ if (transport === "workspace") {
120
+ return yield* new ChatArchiveUnavailable({
121
+ diagnostic: "workspace_chat_store_unavailable",
122
+ });
123
+ }
117
124
  return yield* transport(withinRetention(input, retentionDays, yield* Clock.currentTimeMillis));
118
125
  }
126
+ if (transport === "workspace" && search.before !== undefined && cursor === undefined) {
127
+ return yield* new ActionRejected({ message: "invalid_chat_cursor" });
128
+ }
119
129
  const { principal, memberGroups, chats } = input;
120
130
  const key = chat === undefined ? undefined : `${chat.channel}:${chat.chatId}`;
121
131
  // A service, such as a workflow's user, reads only the exact chats the ontology checked.
@@ -18,6 +18,8 @@ export declare function renderTelegram(markdown: string, attribution: string, se
18
18
  * closes, would take the attribution in.
19
19
  */
20
20
  export declare function telegramRichMarkdown(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string | undefined;
21
+ /** The bot's username from Telegram's `getMe`; undefined, and nothing cached, when it fails. */
22
+ export declare function botUsername(transport: ConnectionTransport["Service"], connection: string): Effect.Effect<string | undefined>;
21
23
  /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
22
24
  export declare function telegramKeyboard(rows: ChatButtonRows, links?: ReadonlyMap<string, string>): Readonly<Record<string, unknown>>;
23
25
  /** Where a text goes: the chat, its forum topic and the message it answers. */
@@ -128,7 +128,7 @@ export function telegramRichMarkdown(markdown, attribution, separator = "\n\n",
128
128
  const botUsernames = new Map();
129
129
  const BOT_USERNAME_TTL_MS = 60 * 60_000;
130
130
  /** The bot's username from Telegram's `getMe`; undefined, and nothing cached, when it fails. */
131
- function botUsername(transport, connection) {
131
+ export function botUsername(transport, connection) {
132
132
  const known = botUsernames.get(connection);
133
133
  if (known !== undefined && known.until > Date.now()) {
134
134
  return Effect.succeed(known.username);
@@ -8,15 +8,15 @@ import type { BuiltApi } from "../api.js";
8
8
  import type { AfterCommitHook } from "../config.js";
9
9
  import type { ConnectionTransportFactory } from "../connections.js";
10
10
  import type { ReplicationKick } from "../replication.js";
11
- import { type ChatArchiveTransport } from "../agent/chat-archive.js";
12
11
  import type { ChatDeliveryFactory } from "./delivery.js";
12
+ import { type ChatHistorySource } from "./local-reads.js";
13
13
  export declare function chatRoutes(options: {
14
14
  readonly built: BuiltApi;
15
15
  readonly hooks: ReadonlyMap<string, AfterCommitHook>;
16
16
  readonly connections: ConnectionTransportFactory;
17
17
  readonly replicate: ReplicationKick;
18
18
  readonly chatDelivery: ChatDeliveryFactory;
19
- readonly chatHistory?: ChatArchiveTransport;
19
+ readonly chatHistory?: ChatHistorySource;
20
20
  readonly verifyToken: TokenVerifier;
21
21
  readonly verifyRuntime?: RuntimeTokenVerifier;
22
22
  readonly exchangeSession?: SessionExchange;
@@ -5,9 +5,9 @@ import type { MetricQueries } from "../metric-query.js";
5
5
  import { type Decide } from "../decisions.js";
6
6
  import type { BuiltApi } from "../api.js";
7
7
  import { type TokenVerifier } from "../authentication.js";
8
+ import { type ChatHistorySource } from "../chat/local-reads.js";
8
9
  import type { PageCatalogV1 } from "../../navigation-catalog.js";
9
10
  import type { AfterCommitHook } from "../config.js";
10
- import { type ChatArchiveTransport } from "../agent/chat-archive.js";
11
11
  import type { ConnectionTransportFactory } from "../connections.js";
12
12
  import { RequestId } from "../errors.js";
13
13
  import type { ReplicationKick } from "../replication.js";
@@ -33,7 +33,7 @@ export interface McpServerOptions {
33
33
  readonly metricQueries: MetricQueries;
34
34
  /** Authenticated exact-text delivery for the built-in chat action. */
35
35
  readonly chatDelivery?: ChatDeliveryFactory | undefined;
36
- readonly chatHistory?: ChatArchiveTransport | undefined;
36
+ readonly chatHistory?: ChatHistorySource | undefined;
37
37
  /** The workspace whose workflows' tasks authenticate here; without it the task header is refused. */
38
38
  readonly workspaceId?: string | undefined;
39
39
  /** How `discover` asks the ontology's decision model: AI Gateway by default. Tests replace it. */
@@ -514,6 +514,11 @@ export interface ResolveIdentityInput {
514
514
  readonly provider: string;
515
515
  readonly externalId: string;
516
516
  readonly chat: "private" | "group";
517
+ /** Trusted delivery address from the verified channel update. */
518
+ readonly delivery?: {
519
+ readonly channel: string;
520
+ readonly chatId: string;
521
+ };
517
522
  readonly turn: boolean;
518
523
  readonly display?: string | null;
519
524
  readonly username?: string;
@@ -566,6 +571,7 @@ export type AgentResolution = {
566
571
  readonly takeover?: true;
567
572
  } | {
568
573
  readonly status: "pairing_required";
574
+ readonly telegramMiniApp?: true;
569
575
  } | {
570
576
  readonly status: "refused";
571
577
  readonly reason: "blocked" | "inactive";
@@ -622,6 +628,10 @@ export interface AgentStore {
622
628
  readonly codeHash: string;
623
629
  }) => Effect.Effect<boolean>;
624
630
  /** A pairing that has neither expired nor been approved. */
631
+ /** The hash stays inside the service. A public launch id alone cannot approve a pairing. */
632
+ readonly telegramLaunchPairing?: (id: string, sender: string) => Effect.Effect<{
633
+ readonly codeHash: string;
634
+ } | undefined>;
625
635
  readonly findPairing: (codeHash: string) => Effect.Effect<AgentPairing | undefined>;
626
636
  /**
627
637
  * Consumes a live pairing once. The same account on the same member is idempotent; another
@@ -635,6 +645,8 @@ export interface AgentStore {
635
645
  }) => Effect.Effect<AgentIdentity | undefined, IdentityInUse>;
636
646
  /** Finds an active identity, or provisions a private sender when the channel admits strangers. */
637
647
  readonly resolveIdentity: (input: ResolveIdentityInput) => Effect.Effect<AgentResolution>;
648
+ /** Optional inbound admission handlers keyed by messenger provider. Each may delegate to resolveIdentity. */
649
+ readonly inboundIdentity?: ReadonlyMap<string, AgentStore["resolveIdentity"]>;
638
650
  /** Complete the leased limit-reply claim only after delivery, or release it after failure. */
639
651
  readonly completeLimitNotice: (input: {
640
652
  readonly notificationId: string;
@@ -1,3 +1,4 @@
1
+ import { telegramPairingLayer } from "./channel/telegram-pairing.js";
1
2
  import { Cause, Context, Effect, Layer, Redacted } from "effect";
2
3
  import { HttpRouter, HttpServer, HttpServerError, HttpServerRequest } from "effect/unstable/http";
3
4
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
@@ -397,7 +398,9 @@ export function createOntologyService(ontology, config) {
397
398
  : localConnections(config.localConnections)));
398
399
  const replicate = deployedReplication(config);
399
400
  // The platform keeps chat history for production agents only.
400
- const chatHistory = config.runtimeIdentity === undefined || preview ? undefined : platformChatArchive(config);
401
+ const cloudChatHistory = config.runtimeIdentity === undefined || preview ? undefined : platformChatArchive(config);
402
+ // Provisioning clears the copied chat store. Preview history always stays in this branch.
403
+ const chatHistory = previewAgent ? "workspace" : cloudChatHistory;
401
404
  // @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message.
402
405
  const deliveries = config.chatArchive ?? platformDeliveryArchive(config);
403
406
  // The app's agent sends through a workspace channel, at the origin it takes its tasks at.
@@ -405,7 +408,11 @@ export function createOntologyService(ontology, config) {
405
408
  origin: config.agentOrigin,
406
409
  ...(config.agentTaskTransport === undefined ? {} : { fetch: config.agentTaskTransport }),
407
410
  };
408
- const chatDelivery = makeChatDelivery(ontology, connections, deliveries, { settings: config.channels?.telegram, ownOrigins: config.appOrigins }, agentChannels, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
411
+ const chatDelivery = makeChatDelivery(ontology, connections, deliveries, { settings: config.channels?.telegram, ownOrigins: config.appOrigins }, agentChannels, preview
412
+ ? previewAgent
413
+ ? "workspace"
414
+ : undefined
415
+ : (config.chatHistoryArchive ?? platformHistoryArchive(config)), cloudChatHistory);
409
416
  const metricQueries = makeMetricQueries({
410
417
  ontology,
411
418
  transport: platformMetricQueries({ ...config, manifestHash: ontology.manifest.hash }),
@@ -529,6 +536,8 @@ export function createOntologyService(ontology, config) {
529
536
  });
530
537
  const application = Layer.mergeAll(channelApps.length > 0
531
538
  ? Layer.merge(channelSessionLayer(config), channelSignInLayer(channelApps, config, connections))
539
+ : Layer.empty, !preview && telegram?.miniApp && telegramConnection && federationConfig
540
+ ? telegramPairingLayer(config, connections, telegramAppProvider(telegramConnection, testKey), telegramConnection, verifyToken)
532
541
  : Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, withoutAgent
533
542
  ? Layer.empty
534
543
  : chatRoutes({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.198.0",
3
+ "version": "0.200.1",
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",