@segmentstream/ontology 0.173.0 → 0.174.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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.174.1
4
+
5
+ Telegram messages, edits and delivery receipts keep the bot account that received or sent them.
6
+ Switching bots in a basic group preserves both messages when Telegram reuses a number. Older
7
+ messages keep their original history and a verified redelivery retains its dispatch state.
8
+
9
+ The workspace agent and web chat now use Eve 1.6.0.
10
+
11
+ Action required: pin `eve` to `1.6.0` in the agent, upgrade the Agent and App SDKs together, and upgrade the Ontology SDK before or alongside them.
12
+
13
+ ## 0.174.0
14
+
15
+ Enroll verified SegmentStream browser accounts with workspace-defined roles independently of email sign-up.
16
+
3
17
  ## 0.173.0
4
18
 
5
19
  An ontology may declare 50 action triggers (`after(…)`), up from 20: as many as the workflows it may
package/dist/analyze.js CHANGED
@@ -1801,6 +1801,9 @@ function signUpOptions(config, signIn, declaredRoles, report) {
1801
1801
  ? 'email is opened by signIn.policy "open" too; declare it in signUp only.'
1802
1802
  : `${channel} is opened by signIn.channels too; declare it in signUp only.`);
1803
1803
  }
1804
+ if (channel === "segmentstream" && !signIn.browser?.methods.includes("segmentstream")) {
1805
+ report("invalid-sign-in", "signUp.channels", "SegmentStream sign-up requires the segmentstream browser sign-in method.");
1806
+ }
1804
1807
  if (SIGN_UP_CHAT_CHANNELS.includes(channel)) {
1805
1808
  if (!declaresChatKind(config.chat, channel)) {
1806
1809
  report("invalid-sign-in", `signUp.channels`, `Signing up on ${channel} needs a matching chat.${channel} adapter.`);
@@ -20,7 +20,7 @@ import { principalsOntology, reconcileWorkflowUsers } from "../runtime/principal
20
20
  import { FEDERATION_TABLES } from "../runtime/federation-tables.js";
21
21
  import { syncUserIdentities, USER_IDENTITY_ENTITY_ID } from "../runtime/user-identities.js";
22
22
  import { resolveReplicationSelection } from "../replication/model.js";
23
- import { ACTION_ATTRIBUTION_TABLE, AGENT_TABLES, API_KEYS_TABLE, CATALOG_TABLE, CHANNEL_USERS_TABLE, OAUTH_GRANTS_GUEST_CHECK, OAUTH_TABLES, USER_ROLES_TABLE, quoteIdentifier, quoteLiteral, historyTableName, } from "./storage.js";
23
+ import { ACTION_ATTRIBUTION_TABLE, AGENT_TABLES, API_KEYS_TABLE, CATALOG_TABLE, CHANNEL_USERS_TABLE, CHAT_MESSAGES_TABLE, OAUTH_GRANTS_GUEST_CHECK, OAUTH_TABLES, USER_ROLES_TABLE, quoteIdentifier, quoteLiteral, historyTableName, } from "./storage.js";
24
24
  const CATALOG = quoteIdentifier(CATALOG_TABLE);
25
25
  const IDENTITY_SYNC = "Copy members' sign-in identities the legacy identity stores hold.";
26
26
  /**
@@ -511,6 +511,10 @@ export const readRuntimeTables = (input) => input.sql
511
511
  `JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace ` +
512
512
  `WHERE n.nspname = current_schema() AND t.relname = '_oauth_grants' ` +
513
513
  `AND c.conname = ${quoteLiteral(OAUTH_GRANTS_GUEST_CHECK)})) ` +
514
+ // Reapply the chat DDL once on databases with the old provider-message key.
515
+ `AND ("tablename" <> ${quoteLiteral(CHAT_MESSAGES_TABLE)} OR EXISTS (` +
516
+ `SELECT 1 FROM pg_catalog.pg_indexes WHERE schemaname = current_schema() ` +
517
+ `AND indexname = ${quoteLiteral(CHAT_MESSAGES_TABLE + "_provider_message_key")})) ` +
514
518
  // Without `signed_up` the agent tables' idempotent DDL runs again and adds it.
515
519
  `AND ("tablename" <> ${quoteLiteral(CHANNEL_USERS_TABLE)} OR EXISTS (` +
516
520
  `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
@@ -694,10 +694,12 @@ const CHAT_MESSAGES_DDL = [
694
694
  `CHECK ("disposition" IN ('claimed', 'turn', 'skipped'))`,
695
695
  `)`,
696
696
  ].join("\n"),
697
- // One row per provider message: a redelivery, an echo or an import of it changes nothing.
698
- `CREATE UNIQUE INDEX IF NOT EXISTS "${CHAT_MESSAGES_TABLE}_message_key" ` +
699
- `ON "${CHAT_MESSAGES_TABLE}" ("channel", "chat_id", "message_id") ` +
697
+ // Older rows keep a NULL bot identity. Index the new key before releasing the old one.
698
+ `ALTER TABLE "${CHAT_MESSAGES_TABLE}" ADD COLUMN IF NOT EXISTS "telegram_bot_id" text`,
699
+ `CREATE UNIQUE INDEX IF NOT EXISTS "${CHAT_MESSAGES_TABLE}_provider_message_key" ` +
700
+ `ON "${CHAT_MESSAGES_TABLE}" ("channel", "chat_id", "message_id", coalesce("telegram_bot_id", '')) ` +
700
701
  `WHERE "message_id" IS NOT NULL`,
702
+ `DROP INDEX IF EXISTS "${CHAT_MESSAGES_TABLE}_message_key"`,
701
703
  // One send per idempotency key: a retry finds its row, and a tombstone keeps the key.
702
704
  `CREATE UNIQUE INDEX IF NOT EXISTS "${CHAT_MESSAGES_TABLE}_operation_key" ` +
703
705
  `ON "${CHAT_MESSAGES_TABLE}" ("operation") WHERE "operation" IS NOT NULL`,
@@ -41,6 +41,7 @@ export interface ChatReaction {
41
41
  }
42
42
  /** One message as the store holds it. Times are ISO 8601; `revision` is a decimal. */
43
43
  export interface ChatMessage {
44
+ readonly telegramBotId?: string;
44
45
  readonly id: string;
45
46
  readonly channel: string;
46
47
  readonly chatId: string;
@@ -80,6 +81,7 @@ export interface ChatMessage {
80
81
  }
81
82
  /** A message to record. */
82
83
  export interface ChatMessageInput {
84
+ readonly telegramBotId?: string;
83
85
  readonly channel: string;
84
86
  readonly chatId: string;
85
87
  readonly threadId?: string;
@@ -110,6 +112,7 @@ export interface ChatMessageInput {
110
112
  }
111
113
  /** The message a change is to, by the provider's id of it. */
112
114
  interface Target {
115
+ readonly telegramBotId?: string;
113
116
  readonly channel: string;
114
117
  readonly chatId: string;
115
118
  readonly messageId: string;
@@ -129,6 +132,13 @@ export type ChatMessageChange =
129
132
  readonly meta?: unknown;
130
133
  readonly expected?: unknown;
131
134
  readonly files?: ReadonlyArray<ChatMessageFile>;
135
+ }) | (Target & {
136
+ readonly change: "bind_telegram_bot";
137
+ readonly direction?: "outbound";
138
+ readonly confirmationId?: string;
139
+ readonly telegramBotId: string;
140
+ readonly senderId: string;
141
+ readonly originalAt: string;
132
142
  }) | (Target & {
133
143
  readonly change: "delete";
134
144
  readonly at?: string;
@@ -153,6 +163,7 @@ export type ChatMessageChange =
153
163
  readonly at?: string;
154
164
  }) | {
155
165
  readonly change: "sent";
166
+ readonly telegramBotId?: string;
156
167
  readonly channel: string;
157
168
  readonly chatId: string;
158
169
  readonly operation: string;
@@ -205,6 +216,7 @@ export declare function chatCursorOf(message: Pick<ChatMessage, "at" | "id">): s
205
216
  * The runtime's reads of one chat, or with `pending` or `senderId` of every chat of a channel.
206
217
  */
207
218
  export interface ChatMessageQuery {
219
+ readonly telegramBotId?: string;
208
220
  readonly channel: string;
209
221
  readonly chatId?: string;
210
222
  /** A thread's messages; `null` for those in no thread; absent for every thread. */
@@ -67,6 +67,7 @@ const COLUMNS = [
67
67
  `"sender_name"`,
68
68
  `"user_id"::text AS "user_id"`,
69
69
  `"message_id"`,
70
+ `"telegram_bot_id"`,
70
71
  `"reply_to"`,
71
72
  `"text"`,
72
73
  `"parts"::text AS "parts"`,
@@ -115,6 +116,7 @@ function messageOf(row) {
115
116
  senderId: text(row.sender_id),
116
117
  senderName: text(row.sender_name),
117
118
  userId: text(row.user_id),
119
+ ...(typeof row.telegram_bot_id === "string" ? { telegramBotId: row.telegram_bot_id } : {}),
118
120
  messageId: text(row.message_id),
119
121
  replyTo: text(row.reply_to),
120
122
  text: text(row.text),
@@ -202,6 +204,11 @@ export function sqlChatMessageStore(sql) {
202
204
  const inChat = (channel, chatId, write) => sql
203
205
  .withTransaction(lockChat({ channel, chatId }).pipe(Effect.andThen(write)))
204
206
  .pipe(Effect.catchTag("SqlError", Effect.die));
207
+ // Cloud also copies old, unscoped history into workspaces running an earlier ontology.
208
+ // For those writes the NULL scope must work even before the column has been added.
209
+ const botScope = (botId, bind) => botId === undefined
210
+ ? `(to_jsonb(${TABLE})->>'telegram_bot_id') IS NULL`
211
+ : `"telegram_bot_id" = ${bind(botId)}`;
205
212
  const insert = (input) => Effect.gen(function* () {
206
213
  const params = parameters();
207
214
  const values = [
@@ -229,12 +236,14 @@ export function sqlChatMessageStore(sql) {
229
236
  params.add(input.turnId ?? null),
230
237
  params.add(input.meta === undefined ? null : JSON.stringify(input.meta), "jsonb"),
231
238
  params.add(input.importedAt ?? null, "timestamptz"),
239
+ ...(input.telegramBotId === undefined ? [] : [params.add(input.telegramBotId)]),
232
240
  ];
233
241
  // Any of the keys may be taken: a redelivery, an echo, a retried send. Nothing changes then.
242
+ const botColumn = input.telegramBotId === undefined ? "" : ', "telegram_bot_id"';
234
243
  const [inserted] = yield* rows(`INSERT INTO ${TABLE} ("id", "channel", "chat_id", "thread_id", "chat_type", ` +
235
244
  `"participants", "direction", "author", "sender_id", "sender_name", "user_id", ` +
236
245
  `"message_id", "reply_to", "text", "parts", "files", "at", "status", "operation", ` +
237
- `"fingerprint", "session_id", "turn_id", "meta", "imported_at") ` +
246
+ `"fingerprint", "session_id", "turn_id", "meta", "imported_at"${botColumn}) ` +
238
247
  `VALUES (${values.join(", ")}) ` +
239
248
  `ON CONFLICT DO NOTHING RETURNING "id"::text AS "id"`, params.values);
240
249
  if (inserted !== undefined) {
@@ -252,10 +261,12 @@ export function sqlChatMessageStore(sql) {
252
261
  }
253
262
  const byMessage = input.messageId === undefined
254
263
  ? undefined
255
- : yield* find(`"channel" = $1 AND "chat_id" = $2 AND "message_id" = $3`, [
264
+ : yield* find(`"channel" = $1 AND "chat_id" = $2 AND "message_id" = $3 AND ` +
265
+ botScope(input.telegramBotId, () => "$4"), [
256
266
  input.channel,
257
267
  input.chatId,
258
268
  input.messageId,
269
+ ...(input.telegramBotId === undefined ? [] : [input.telegramBotId]),
259
270
  ]);
260
271
  if (byMessage === undefined) {
261
272
  // The conflicting row was purged between the insert and the read: record it again.
@@ -271,7 +282,7 @@ export function sqlChatMessageStore(sql) {
271
282
  const update = (change, params, assignments, guard = []) => inChat(change.channel, change.chatId, rows(`UPDATE ${TABLE} SET ${assignments.join(", ")} ` +
272
283
  `WHERE "channel" = ${params.add(change.channel)} ` +
273
284
  `AND "chat_id" = ${params.add(change.chatId)} ` +
274
- `AND "message_id" = ${params.add(change.messageId)} ` +
285
+ `AND "message_id" = ${params.add(change.messageId)} AND ${botScope(change.telegramBotId, params.add)} ` +
275
286
  `AND "purged_at" IS NULL${guard.map((condition) => ` AND ${condition}`).join("")} ` +
276
287
  `RETURNING "id"`, params.values)).pipe(Effect.map((updated) => ({ applied: updated.length > 0 })));
277
288
  /**
@@ -296,7 +307,7 @@ export function sqlChatMessageStore(sql) {
296
307
  });
297
308
  const revised = `"revision" = ${NEXT_REVISION}`;
298
309
  const sent = (change) => inChat(change.channel, change.chatId, Effect.gen(function* () {
299
- const [row] = yield* rows(`SELECT "id"::text AS "id", "status" FROM ${TABLE} ` +
310
+ const [row] = yield* rows(`SELECT "id"::text AS "id", "status", to_jsonb(${TABLE})->>'telegram_bot_id' AS "bot" FROM ${TABLE} ` +
300
311
  `WHERE "operation" = $1 AND "channel" = $2 AND "chat_id" = $3 ` +
301
312
  `AND "purged_at" IS NULL FOR UPDATE`, [change.operation, change.channel, change.chatId]);
302
313
  // A receipt is written once: a replay, or one for a send no longer waiting, changes nothing.
@@ -305,11 +316,22 @@ export function sqlChatMessageStore(sql) {
305
316
  row.status === change.status) {
306
317
  return { applied: false };
307
318
  }
319
+ const botId = typeof row.bot === "string" ? row.bot : change.telegramBotId;
320
+ if (change.telegramBotId !== undefined && botId !== change.telegramBotId) {
321
+ return yield* new ChatMessageConflict({ code: "message_conflict" });
322
+ }
308
323
  let echo;
309
324
  if (change.providerMessageId !== undefined) {
310
325
  const [holder] = yield* rows(`SELECT "id"::text AS "id", "operation" FROM ${TABLE} ` +
311
326
  `WHERE "channel" = $1 AND "chat_id" = $2 AND "message_id" = $3 AND "id" <> $4::uuid ` +
312
- `FOR UPDATE`, [change.channel, change.chatId, change.providerMessageId, row.id]);
327
+ `AND ${botScope(botId, () => "$5")} ` +
328
+ `FOR UPDATE`, [
329
+ change.channel,
330
+ change.chatId,
331
+ change.providerMessageId,
332
+ row.id,
333
+ ...(botId === undefined ? [] : [botId]),
334
+ ]);
313
335
  if (holder !== undefined && holder.operation !== null) {
314
336
  return yield* new ChatMessageConflict({ code: "message_conflict" });
315
337
  }
@@ -337,6 +359,7 @@ export function sqlChatMessageStore(sql) {
337
359
  const deleted = `$6::timestamptz IS NOT NULL`;
338
360
  yield* rows(`UPDATE ${TABLE} SET "status" = $2::text, ` +
339
361
  `"message_id" = coalesce($3::text, "message_id"), ` +
362
+ (botId === undefined ? "" : '"telegram_bot_id" = $10, ') +
340
363
  `"failure" = CASE WHEN $2::text = 'failed' THEN $4::text ELSE NULL END, ` +
341
364
  `"text" = CASE WHEN ${deleted} THEN NULL ` +
342
365
  `WHEN $5::timestamptz IS NOT NULL THEN $7::text ELSE "text" END, ` +
@@ -357,6 +380,7 @@ export function sqlChatMessageStore(sql) {
357
380
  echo?.text ?? null,
358
381
  echo?.reactions ?? null,
359
382
  change.meta === undefined ? null : JSON.stringify(change.meta),
383
+ ...(botId === undefined ? [] : [botId]),
360
384
  ]);
361
385
  return { applied: true };
362
386
  }));
@@ -370,12 +394,18 @@ export function sqlChatMessageStore(sql) {
370
394
  const remove = (input) => inChat(input.channel, input.chatId, Effect.gen(function* () {
371
395
  const [deleted] = yield* rows(`WITH "before" AS (SELECT "id", "files" FROM ${TABLE} WHERE "channel" = $1 ` +
372
396
  `AND "chat_id" = $2 AND "message_id" = $3 AND "purged_at" IS NULL ` +
373
- `AND "deleted_at" IS NULL FOR UPDATE) ` +
397
+ `AND ${botScope(input.telegramBotId, () => "$5")} AND "deleted_at" IS NULL FOR UPDATE) ` +
374
398
  `UPDATE ${TABLE} SET "text" = NULL, "parts" = '[]', "files" = '[]', ` +
375
399
  `"reactions" = '[]', "meta" = NULL, ` +
376
400
  `"deleted_at" = date_trunc('milliseconds', coalesce($4::timestamptz, now())), ` +
377
401
  `${revised} FROM "before" WHERE ${TABLE}."id" = "before"."id" ` +
378
- `RETURNING "before"."files"::text AS "files"`, [input.channel, input.chatId, input.messageId, input.at ?? null]);
402
+ `RETURNING "before"."files"::text AS "files"`, [
403
+ input.channel,
404
+ input.chatId,
405
+ input.messageId,
406
+ input.at ?? null,
407
+ ...(input.telegramBotId === undefined ? [] : [input.telegramBotId]),
408
+ ]);
379
409
  if (deleted === undefined) {
380
410
  return { applied: false };
381
411
  }
@@ -385,6 +415,32 @@ export function sqlChatMessageStore(sql) {
385
415
  const change = (input) => {
386
416
  const params = parameters();
387
417
  switch (input.change) {
418
+ // @legacy agent.telegram-unscoped-message-identity
419
+ case "bind_telegram_bot":
420
+ // A retry spanning the upgrade must keep the original dispatch fence. Both the
421
+ // Telegram sender and the message's immutable creation time must identify that row.
422
+ return inChat(input.channel, input.chatId, Effect.gen(function* () {
423
+ const key = `"channel" = $1 AND "chat_id" = $2 AND "message_id" = $3`;
424
+ // Telegram authenticates its own edits. A card can additionally identify itself
425
+ // by its immutable request ID even if sending it crossed a wall-clock second.
426
+ const proof = input.direction === "outbound"
427
+ ? `"direction" = 'outbound' AND $5::text = $4::text AND ` +
428
+ `(date_trunc('second', "at") = $6::timestamptz OR "meta" #>> '{routing,confirmation,requestId}' = $7)`
429
+ : `"direction" = 'inbound' AND "sender_id" = $5 AND ` +
430
+ `coalesce("meta" #>> '{routing,revision,originalAt}' = $6, "at" = $6::text::timestamptz)`;
431
+ const adopted = yield* rows(`UPDATE ${TABLE} SET "telegram_bot_id" = $4 WHERE ${key} AND "telegram_bot_id" IS NULL ` +
432
+ `AND ${proof} ` +
433
+ `AND NOT EXISTS (SELECT 1 FROM ${TABLE} WHERE ${key} AND "telegram_bot_id" = $4) RETURNING "id"`, [
434
+ input.channel,
435
+ input.chatId,
436
+ input.messageId,
437
+ input.telegramBotId,
438
+ input.senderId,
439
+ input.originalAt,
440
+ ...(input.direction === "outbound" ? [input.confirmationId ?? null] : []),
441
+ ]);
442
+ return { applied: adopted.length > 0 };
443
+ }));
388
444
  case "edit": {
389
445
  const edited = params.add(input.text, "text");
390
446
  const at = `date_trunc('milliseconds', coalesce(${params.add(input.at ?? null, "timestamptz")}, now()))`;
@@ -420,6 +476,7 @@ export function sqlChatMessageStore(sql) {
420
476
  `"channel" = ${params.add(input.channel)}`,
421
477
  `"chat_id" = ${params.add(input.chatId)}`,
422
478
  `"message_id" = ${params.add(input.messageId)}`,
479
+ botScope(input.telegramBotId, params.add),
423
480
  `"purged_at" IS NULL`,
424
481
  ];
425
482
  // The files an edit replaced are discarded, as a deleted message's are.
@@ -542,7 +599,7 @@ export function sqlChatMessageStore(sql) {
542
599
  : `"thread_id" = ${params.add(input.threadId)}`);
543
600
  }
544
601
  if (input.messageId !== undefined) {
545
- conditions.push(`"message_id" = ${params.add(input.messageId)}`);
602
+ conditions.push(`"message_id" = ${params.add(input.messageId)}`, botScope(input.telegramBotId, params.add));
546
603
  }
547
604
  if (input.id !== undefined) {
548
605
  conditions.push(UUID_TEXT.test(input.id) ? `"id" = ${params.add(input.id, "uuid")}` : "FALSE");
@@ -381,8 +381,13 @@ function signIn(ontology, sql, claims) {
381
381
  yield* recordIdentity(String(invited.id), "invite");
382
382
  return userRow(linkedUser);
383
383
  }
384
- // `signUp` with `email` creates a user holding its roles; `policy: "open"` one holding member.
385
- const signUpRoles = signUpRolesOf(ontology.manifest, "email");
384
+ // A verified browser federation account can enroll through its own channel. Older
385
+ // workspaces without that declaration keep their existing email enrollment behavior.
386
+ const cloudRoles = account.provider === OIDC_PROVIDER && email !== undefined
387
+ ? signUpRolesOf(ontology.manifest, "segmentstream")
388
+ : undefined;
389
+ const channel = cloudRoles === undefined ? "email" : "segmentstream";
390
+ const signUpRoles = cloudRoles ?? signUpRolesOf(ontology.manifest, "email");
386
391
  // @legacy ontology.legacy-channel-admission
387
392
  if (signUpRoles === undefined && ontology.signIn.policy !== "open") {
388
393
  return yield* new PrincipalRejected({
@@ -398,7 +403,7 @@ function signIn(ontology, sql, claims) {
398
403
  identity_subject: claims.identitySubject,
399
404
  ...signedIn,
400
405
  });
401
- yield* recordUserCreation(sql, String(created.id), "email", signUpRoles !== undefined);
406
+ yield* recordUserCreation(sql, String(created.id), channel, signUpRoles !== undefined);
402
407
  if (signUpRoles !== undefined && signUpRoles.length > 0) {
403
408
  yield* platformRuntime(ontology, sql, MEMBER_HISTORY_ACTIONS.grantRoles)
404
409
  .members.grantRoles({ id: String(created.id), roles: signUpRoles })
@@ -5,6 +5,7 @@ import { RequestId } from "../errors.js";
5
5
  import type { AgentStore } from "../runtime-contract.js";
6
6
  /** `POST /api/ontology/agent/chats/messages`: one message, recorded once by its keys. */
7
7
  export declare const ChatMessageRecordRequest: Schema.Struct<{
8
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
8
9
  readonly channel: Schema.String;
9
10
  readonly chatId: Schema.String;
10
11
  readonly threadId: Schema.optionalKey<Schema.String>;
@@ -36,6 +37,16 @@ export declare const ChatMessageRecordRequest: Schema.Struct<{
36
37
  }>;
37
38
  /** `POST /api/ontology/agent/chats/messages/change`: one change to a message. */
38
39
  export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Struct<{
40
+ readonly change: Schema.Literal<"bind_telegram_bot">;
41
+ readonly direction: Schema.optionalKey<Schema.Literal<"outbound">>;
42
+ readonly confirmationId: Schema.optionalKey<Schema.String>;
43
+ readonly telegramBotId: Schema.String;
44
+ readonly senderId: Schema.String;
45
+ readonly originalAt: Schema.String;
46
+ readonly channel: Schema.String;
47
+ readonly chatId: Schema.String;
48
+ readonly messageId: Schema.String;
49
+ }>, Schema.Struct<{
39
50
  readonly change: Schema.Literal<"edit">;
40
51
  readonly text: Schema.String;
41
52
  readonly at: Schema.optionalKey<Schema.String>;
@@ -47,12 +58,14 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
47
58
  readonly type: Schema.optionalKey<Schema.String>;
48
59
  readonly size: Schema.optionalKey<Schema.Int>;
49
60
  }>>>;
61
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
50
62
  readonly channel: Schema.String;
51
63
  readonly chatId: Schema.String;
52
64
  readonly messageId: Schema.String;
53
65
  }>, Schema.Struct<{
54
66
  readonly change: Schema.Literal<"delete">;
55
67
  readonly at: Schema.optionalKey<Schema.String>;
68
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
56
69
  readonly channel: Schema.String;
57
70
  readonly chatId: Schema.String;
58
71
  readonly messageId: Schema.String;
@@ -60,6 +73,7 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
60
73
  readonly change: Schema.Literal<"reaction">;
61
74
  readonly senderId: Schema.String;
62
75
  readonly emoji: Schema.String;
76
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
63
77
  readonly channel: Schema.String;
64
78
  readonly chatId: Schema.String;
65
79
  readonly messageId: Schema.String;
@@ -67,6 +81,7 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
67
81
  readonly change: Schema.Literal<"status">;
68
82
  readonly status: Schema.Literals<readonly ["sent", "delivered", "read", "failed"]>;
69
83
  readonly failure: Schema.optionalKey<Schema.String>;
84
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
70
85
  readonly channel: Schema.String;
71
86
  readonly chatId: Schema.String;
72
87
  readonly messageId: Schema.String;
@@ -76,6 +91,7 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
76
91
  readonly reason: Schema.optionalKey<Schema.String>;
77
92
  readonly sessionId: Schema.optionalKey<Schema.String>;
78
93
  readonly turnId: Schema.optionalKey<Schema.String>;
94
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
79
95
  readonly channel: Schema.String;
80
96
  readonly chatId: Schema.String;
81
97
  readonly messageId: Schema.String;
@@ -83,12 +99,14 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
83
99
  readonly channel: Schema.String;
84
100
  readonly chatId: Schema.String;
85
101
  readonly change: Schema.Literal<"sent">;
102
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
86
103
  readonly operation: Schema.String;
87
104
  readonly status: Schema.Literals<readonly ["sent", "failed", "uncertain"]>;
88
105
  readonly providerMessageId: Schema.optionalKey<Schema.String>;
89
106
  readonly failure: Schema.optionalKey<Schema.String>;
90
107
  }>, Schema.Struct<{
91
108
  readonly change: Schema.Literal<"release">;
109
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
92
110
  readonly channel: Schema.String;
93
111
  readonly chatId: Schema.String;
94
112
  readonly messageId: Schema.String;
@@ -103,6 +121,7 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
103
121
  readonly type: Schema.optionalKey<Schema.String>;
104
122
  readonly size: Schema.optionalKey<Schema.Int>;
105
123
  }>>>;
124
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
106
125
  readonly channel: Schema.String;
107
126
  readonly chatId: Schema.String;
108
127
  readonly messageId: Schema.String;
@@ -110,6 +129,7 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
110
129
  readonly change: Schema.Literal<"meta">;
111
130
  readonly meta: Schema.Codec<Schema.Json, Schema.Json, never, never>;
112
131
  readonly expected: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
132
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
113
133
  readonly channel: Schema.String;
114
134
  readonly chatId: Schema.String;
115
135
  readonly messageId: Schema.String;
@@ -122,6 +142,7 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
122
142
  * first, in every chat of the channel unless `chatId` names one.
123
143
  */
124
144
  export declare const ChatMessageReadRequest: Schema.Struct<{
145
+ readonly telegramBotId: Schema.optionalKey<Schema.String>;
125
146
  readonly channel: Schema.String;
126
147
  readonly chatId: Schema.optionalKey<Schema.String>;
127
148
  readonly threadId: Schema.optionalKey<Schema.NullOr<Schema.String>>;
@@ -13,6 +13,8 @@ const NO_STORE = { "cache-control": "no-store" };
13
13
  const MAX_JSON_BYTES = 64 * 1024;
14
14
  const Text = (maximum) => Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(maximum));
15
15
  const ChatId = Text(256);
16
+ const BotId = Schema.String.check(Schema.isPattern(/^[1-9]\d{0,19}$/));
17
+ const TelegramBotId = Schema.optionalKey(BotId);
16
18
  const MessageId = Text(512);
17
19
  const Key = Text(512);
18
20
  /** A reason or a refusal: a code such as `mention` or `outside_reply_window`, never prose. */
@@ -31,6 +33,7 @@ const ChatFile = Schema.Struct({
31
33
  });
32
34
  /** `POST /api/ontology/agent/chats/messages`: one message, recorded once by its keys. */
33
35
  export const ChatMessageRecordRequest = Schema.Struct({
36
+ telegramBotId: TelegramBotId,
34
37
  channel: Provider,
35
38
  chatId: ChatId,
36
39
  threadId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),
@@ -57,9 +60,24 @@ export const ChatMessageRecordRequest = Schema.Struct({
57
60
  // it as new and no figure counts it, as an import's. Never a send.
58
61
  imported: Schema.optionalKey(Schema.Literal(true)),
59
62
  });
60
- const Target = { channel: Provider, chatId: ChatId, messageId: MessageId };
63
+ const Target = {
64
+ telegramBotId: TelegramBotId,
65
+ channel: Provider,
66
+ chatId: ChatId,
67
+ messageId: MessageId,
68
+ };
61
69
  /** `POST /api/ontology/agent/chats/messages/change`: one change to a message. */
62
70
  export const ChatMessageChangeRequest = Schema.Union([
71
+ Schema.Struct({
72
+ ...Target,
73
+ // @legacy agent.telegram-unscoped-message-identity
74
+ change: Schema.Literal("bind_telegram_bot"),
75
+ direction: Schema.optionalKey(Schema.Literal("outbound")),
76
+ confirmationId: Schema.optionalKey(Key),
77
+ telegramBotId: BotId,
78
+ senderId: Text(256),
79
+ originalAt: Instant,
80
+ }),
63
81
  Schema.Struct({
64
82
  ...Target,
65
83
  change: Schema.Literal("edit"),
@@ -97,6 +115,7 @@ export const ChatMessageChangeRequest = Schema.Union([
97
115
  channel: Provider,
98
116
  chatId: ChatId,
99
117
  change: Schema.Literal("sent"),
118
+ telegramBotId: TelegramBotId,
100
119
  operation: Key,
101
120
  status: Schema.Literals(["sent", "failed", "uncertain"]),
102
121
  providerMessageId: Schema.optionalKey(MessageId),
@@ -130,6 +149,7 @@ export const ChatMessageChangeRequest = Schema.Union([
130
149
  * first, in every chat of the channel unless `chatId` names one.
131
150
  */
132
151
  export const ChatMessageReadRequest = Schema.Struct({
152
+ telegramBotId: TelegramBotId,
133
153
  channel: Provider,
134
154
  chatId: Schema.optionalKey(ChatId),
135
155
  threadId: Schema.optionalKey(Schema.NullOr(Text(256))),
@@ -13,6 +13,7 @@ export interface DeliveryEvent {
13
13
  readonly eventId: string;
14
14
  readonly operationId: string;
15
15
  readonly provider: string;
16
+ readonly telegramBotId?: string;
16
17
  readonly chatId: string;
17
18
  readonly chatType: "group" | "private";
18
19
  /** A forum topic or thread; a chat post has none. */
@@ -94,6 +95,7 @@ export type DeliveryArchive = ((input: {
94
95
  }) => Effect.Effect<DeliveryReceipt, DeliveryArchiveError>) & {
95
96
  /** Finds a key's receipt before a message that is read when it is sent, such as a template. */
96
97
  readonly find?: DeliveryFinder;
98
+ readonly workspaceStore?: true;
97
99
  };
98
100
  /**
99
101
  * The chat archive in Cloud, which reserves and receipts a delivery while the workspace chat store
@@ -1,4 +1,4 @@
1
- import { validateTelegramPreviews } from "../../telegram.js";
1
+ import { telegramAccountMessageIds, validateTelegramPreviews, } from "../../telegram.js";
2
2
  import { chatRetentionDaysOf, inboxAttributionOf, signsMail, takeoverChannelsOf, } from "../../manifest.js";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { Cause, Effect } from "effect";
@@ -8,6 +8,7 @@ import { effectiveScope, isAllowed } from "../../permissions.js";
8
8
  import { describeChatError } from "./diagnostics.js";
9
9
  import { deliveryRequester } from "./attribution.js";
10
10
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
11
+ import { telegramBotId } from "../channel/providers/telegram.js";
11
12
  import { deliveryArchiveOf } from "./store-delivery.js";
12
13
  import { readDraftFiles, snapshotDraftFiles } from "./draft-files.js";
13
14
  import { channelProvider, chatConnection, chatKind, listedChatProviders, } from "./providers/index.js";
@@ -692,11 +693,22 @@ chats) {
692
693
  });
693
694
  }
694
695
  const operationId = context.envelope?.operation_id ?? randomUUID();
696
+ const chatId = place?.chatId ?? target.external_id;
697
+ const botId = provider.provider === "telegram" &&
698
+ archive.workspaceStore &&
699
+ telegramAccountMessageIds(chatId)
700
+ ? yield* telegramBotId(connection)(transport).pipe(Effect.catchDefect((cause) => Effect.fail(new ActionRejected({
701
+ cause,
702
+ message: "telegram_bot_identity_unavailable",
703
+ refusal: "telegram_bot_identity_unavailable",
704
+ }))))
705
+ : undefined;
695
706
  const event = {
707
+ ...(botId === undefined ? {} : { telegramBotId: botId }),
696
708
  eventId: `chat-delivery:${operationId}:reserve`,
697
709
  operationId,
698
710
  provider: target.provider,
699
- chatId: place?.chatId ?? target.external_id,
711
+ chatId,
700
712
  chatType: target.kind,
701
713
  threadId: place?.threadId ?? null,
702
714
  participantIds,
@@ -157,6 +157,7 @@ export function storeDeliveryArchive(store, retentionDays) {
157
157
  const requester = event.requestedBy;
158
158
  const message = {
159
159
  channel: event.provider,
160
+ ...(event.telegramBotId === undefined ? {} : { telegramBotId: event.telegramBotId }),
160
161
  chatId: event.chatId,
161
162
  ...(event.threadId === null ? {} : { threadId: event.threadId }),
162
163
  chatType: event.chatType,
@@ -256,6 +257,7 @@ export function storeDeliveryArchive(store, retentionDays) {
256
257
  change: "sent",
257
258
  channel: row.channel,
258
259
  chatId: row.chatId,
260
+ ...(event.telegramBotId === undefined ? {} : { telegramBotId: event.telegramBotId }),
259
261
  operation,
260
262
  status,
261
263
  ...(event.messageId === null ? {} : { providerMessageId: event.messageId }),
@@ -292,7 +294,7 @@ export function storeDeliveryArchive(store, retentionDays) {
292
294
  }).pipe(Effect.catchDefect((cause) => storeFailure("chat_store_find_failed", cause)));
293
295
  return Object.assign(({ event, delivery }) => (delivery.phase === "reserve" ? reserve(event, delivery) : receipt(event, delivery)).pipe(Effect.catchDefect((cause) => storeFailure(delivery.phase === "reserve"
294
296
  ? "chat_store_reserve_failed"
295
- : "chat_store_receipt_failed", cause))), { find });
297
+ : "chat_store_receipt_failed", cause))), { find, workspaceStore: true });
296
298
  }
297
299
  /**
298
300
  * Where a delivery reserves and receipts its key: the workspace chat store once it holds a message,
package/dist/sign-in.d.ts CHANGED
@@ -17,7 +17,7 @@ export type ChannelProvider = (typeof CHANNEL_PROVIDERS)[number];
17
17
  * `guest` supersedes; the others are a first private message to the agent, or opening the
18
18
  * Telegram Mini App.
19
19
  */
20
- export declare const SIGN_UP_CHANNELS: readonly ["email", "telegram", "whatsapp", "web"];
20
+ export declare const SIGN_UP_CHANNELS: readonly ["email", "segmentstream", "telegram", "whatsapp", "web"];
21
21
  /**
22
22
  * The people of a channel the workspace defines in its own code, `channel:<name>`, such as
23
23
  * `channel:helpdesk`: the accounts they write from there, which are that channel's alone.
package/dist/sign-in.js CHANGED
@@ -16,7 +16,7 @@ export const CHANNEL_PROVIDERS = ["telegram"];
16
16
  * `guest` supersedes; the others are a first private message to the agent, or opening the
17
17
  * Telegram Mini App.
18
18
  */
19
- export const SIGN_UP_CHANNELS = ["email", "telegram", "whatsapp", "web"];
19
+ export const SIGN_UP_CHANNELS = ["email", "segmentstream", "telegram", "whatsapp", "web"];
20
20
  /** The sign-up channels a person reaches through a chat, which need a matching `chat` adapter. */
21
21
  export const SIGN_UP_CHAT_CHANNELS = ["telegram", "whatsapp"];
22
22
  export function isSignUpChannel(value) {
@@ -1,4 +1,10 @@
1
1
  import { TelegramFormatConverter } from "@chat-adapter/telegram";
2
+ /**
3
+ * Private chats and basic groups number messages per account. Supergroup and channel
4
+ * message numbers are shared. Their Bot API peer IDs start below -1000000000000.
5
+ * https://core.telegram.org/api/bots/ids
6
+ */
7
+ export declare function telegramAccountMessageIds(chatId: string): boolean;
2
8
  export declare const TELEGRAM_LINK_PREVIEWS: readonly ["external", "none", "all"];
3
9
  export type TelegramLinkPreviews = (typeof TELEGRAM_LINK_PREVIEWS)[number];
4
10
  export declare const TELEGRAM_APP_LINKS: readonly ["web", "miniApp"];
package/dist/telegram.js CHANGED
@@ -1,5 +1,13 @@
1
1
  import { TelegramFormatConverter } from "@chat-adapter/telegram";
2
2
  import { Lexer, Tokenizer } from "marked";
3
+ /**
4
+ * Private chats and basic groups number messages per account. Supergroup and channel
5
+ * message numbers are shared. Their Bot API peer IDs start below -1000000000000.
6
+ * https://core.telegram.org/api/bots/ids
7
+ */
8
+ export function telegramAccountMessageIds(chatId) {
9
+ return !/^-[1-9]\d{12,}$/u.test(chatId);
10
+ }
3
11
  export const TELEGRAM_LINK_PREVIEWS = ["external", "none", "all"];
4
12
  export const TELEGRAM_APP_LINKS = ["web", "miniApp"];
5
13
  const converter = new TelegramFormatConverter();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.173.0",
3
+ "version": "0.174.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",