@segmentstream/ontology 0.195.0 → 0.196.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,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.196.1
4
+
5
+ A Telegram rich message the ontology sends shows a table written on the line right after text as a
6
+ table. Markdown reads such a table as a block of its own, while Telegram took it as more of the
7
+ text before it and showed its rows as one line of pipes; the rich message now has the Markdown's
8
+ blocks a blank line apart, each as written.
9
+
10
+ ## 0.196.0
11
+
12
+ Allow chat persona rules to match a trusted registration time. A workspace can change the initial persona for new groups while preserving inherited settings in established groups.
13
+
3
14
  ## 0.195.0
4
15
 
5
16
  A Telegram message the ontology sends, a post in either voice, an approved draft or a reply its
@@ -189,7 +189,7 @@ export const AgentChat = entity("agent_chat", {
189
189
  provider: policy.channelKinds?.[chat.provider] ?? chat.provider,
190
190
  channel: chat.provider,
191
191
  kind: chat.kind === "private" ? "private" : "group",
192
- }, chat.externalId);
192
+ }, chat.externalId, chat.createdAt);
193
193
  const changesPersona = chatPersona(policy, context, chat.agentPersona).name !==
194
194
  chatPersona(policy, context, input.persona).name;
195
195
  // The scoped write checks record access. A stale selection rolls back the transaction.
@@ -1,5 +1,6 @@
1
1
  /** Trusted delivery coordinates. The channel is the configured connection's channel name. */
2
2
  export interface PersonaContext {
3
+ readonly registeredAt?: string;
3
4
  readonly chat?: string;
4
5
  readonly provider: string;
5
6
  readonly channel: string;
@@ -7,9 +8,12 @@ export interface PersonaContext {
7
8
  readonly audience?: "guest" | "member";
8
9
  }
9
10
  /** Audience is an attribute of an authenticated web chat address. Shared chats can have mixed audiences. */
10
- export declare function chatPersonaContext(address: Omit<PersonaContext, "chat" | "audience">, externalId: string): PersonaContext;
11
+ export declare function chatPersonaContext(address: Omit<PersonaContext, "chat" | "audience" | "registeredAt">, externalId: string, registeredAt?: string | null): PersonaContext;
11
12
  export interface PersonaRule {
12
- readonly when: Partial<PersonaContext>;
13
+ readonly when: Partial<Omit<PersonaContext, "registeredAt">> & {
14
+ /** Strict UTC cutoff against the trusted chat registry. An unseen chat does not match. */
15
+ readonly registeredBefore?: string;
16
+ };
13
17
  readonly use: string;
14
18
  }
15
19
  /** Deployed selection policy. The ontology only needs names and conditions. */
@@ -1,7 +1,11 @@
1
1
  import { agentChatKey } from "./chat-channel.js";
2
2
  /** Audience is an attribute of an authenticated web chat address. Shared chats can have mixed audiences. */
3
- export function chatPersonaContext(address, externalId) {
4
- const context = { ...address, chat: agentChatKey(address.channel, externalId) };
3
+ export function chatPersonaContext(address, externalId, registeredAt) {
4
+ const context = {
5
+ ...address,
6
+ ...(registeredAt && { registeredAt }),
7
+ chat: agentChatKey(address.channel, externalId),
8
+ };
5
9
  if (address.provider === "web" && address.kind === "private") {
6
10
  if (externalId.startsWith("guest:")) {
7
11
  return { ...context, audience: "guest" };
@@ -28,7 +32,10 @@ export function chatPersona(settings, context, assigned) {
28
32
  }
29
33
  for (const rule of settings.rules ?? []) {
30
34
  if (context &&
31
- Object.entries(rule.when).every(([key, value]) => context[key] === value)) {
35
+ Object.entries(rule.when).every(([key, value]) => key === "registeredBefore"
36
+ ? context.registeredAt !== undefined &&
37
+ Date.parse(context.registeredAt) < Date.parse(value)
38
+ : context[key] === value)) {
32
39
  return { name: rule.use, source: "rule" };
33
40
  }
34
41
  }
@@ -5,6 +5,7 @@ import { Effect, Option, Schema } from "effect";
5
5
  import { SqlClient } from "effect/unstable/sql";
6
6
  import { action } from "../action.js";
7
7
  import { AgentChat, agentChatKey } from "../agent-chat.js";
8
+ import { chatPersona, chatPersonaContext, deployedChatPersonas } from "../chat-personas.js";
8
9
  import { chatChannelKind } from "../chat-channel.js";
9
10
  import { historyTableName, quoteIdentifier, tableName } from "../migrate/storage.js";
10
11
  import { addressesOfDraft, AgentDraft, participantsOfDraft, draftAddresses, draftFilesOf, draftParticipants, } from "../agent-draft.js";
@@ -650,10 +651,12 @@ export function sqlAgentStore(ontology, sql) {
650
651
  }),
651
652
  readGroupAccess: (key) => rows(`SELECT "group_access" FROM ${quoteIdentifier(tableName(AgentChat.name))}
652
653
  WHERE "key" = $1 AND "kind" = 'group' AND "handoff_at" IS NULL AND "handled_by_id" IS NULL`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.group_access))),
653
- readChatPersona: (key) => rows(`SELECT "agent_persona", "persona_changed_at" FROM ${quoteIdentifier(tableName(AgentChat.name))}
654
+ readChatPersona: (key) => rows(`SELECT "agent_persona", ${epochMs('"persona_changed_at"')} AS changed_ms,
655
+ ${epochMs('"created_at"')} AS registered_ms FROM ${quoteIdentifier(tableName(AgentChat.name))}
654
656
  WHERE "key" = $1`, [key]).pipe(Effect.map(([chat]) => ({
655
657
  persona: nullableText(chat?.agent_persona),
656
- changedAt: chat?.persona_changed_at == null ? null : timestampText(chat.persona_changed_at),
658
+ registeredAt: chat ? new Date(Number(chat.registered_ms)).toISOString() : null,
659
+ changedAt: chat?.changed_ms == null ? null : new Date(Number(chat.changed_ms)).toISOString(),
657
660
  }))),
658
661
  seeChat: ({ provider, externalId, title, memberId, leftMemberId, agentLeft, migratedFrom }) => sql
659
662
  .withTransaction(Effect.gen(function* () {
@@ -737,6 +740,24 @@ export function sqlAgentStore(ontology, sql) {
737
740
  kept[key] = old[key];
738
741
  }
739
742
  }
743
+ // A new provider id can already have its own row when the migration arrives.
744
+ // Preserve the original group's inherited persona if its registration rule differs.
745
+ const policy = deployedChatPersonas();
746
+ if (policy?.rules?.some((rule) => rule.when.registeredBefore) &&
747
+ found.agent_persona == null &&
748
+ old.agent_persona == null) {
749
+ const address = {
750
+ channel: provider,
751
+ provider: policy.channelKinds?.[provider] ?? provider,
752
+ kind: "group",
753
+ };
754
+ const at = (row) => chatPersona(policy, chatPersonaContext(address, String(row.external_id), timestampText(row.created_at))).name;
755
+ const original = at(old);
756
+ if (original && original !== at(found)) {
757
+ kept.agent_persona = original;
758
+ kept.persona_changed_at = now.toISOString();
759
+ }
760
+ }
740
761
  if (Object.keys(kept).length > 0) {
741
762
  found = yield* runtime.update({
742
763
  entity: AgentChat.name,
@@ -970,7 +970,7 @@ export function agentLayer(options) {
970
970
  provider: store.channelKind?.(channel) ?? channel,
971
971
  channel,
972
972
  kind: chat.kind === "private" ? "private" : "group",
973
- }, String(chat.external_id)), assigned);
973
+ }, String(chat.external_id), String(chat.created_at)), assigned);
974
974
  const group = chat.kind === "group" && store.readGroupAccess
975
975
  ? yield* manageableChat(member, "id", id, "agent_chat:set_access")
976
976
  : undefined;
@@ -12,9 +12,10 @@ export { TELEGRAM_MESSAGE_LIMIT };
12
12
  export declare function renderTelegram(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string;
13
13
  /**
14
14
  * The message as one Telegram rich message, for Markdown with a table, which MarkdownV2 shows only
15
- * as code: the member's Markdown, its links to the app as `renderTelegram` points them, then the
16
- * attribution. Undefined without a table, beyond what one rich message takes, or when a block the
17
- * Markdown leaves open, such as a code fence it never closes, would take the attribution in.
15
+ * as code: the member's Markdown, its blocks a blank line apart and its links to the app as
16
+ * `renderTelegram` points them, then the attribution. Undefined without a table, beyond what one
17
+ * rich message takes, or when a block the Markdown leaves open, such as a code fence it never
18
+ * closes, would take the attribution in.
18
19
  */
19
20
  export declare function telegramRichMarkdown(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string | undefined;
20
21
  /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
@@ -75,18 +75,35 @@ function richShape(tree) {
75
75
  }
76
76
  return shape;
77
77
  }
78
+ /**
79
+ * The Markdown's blocks, each as written, a blank line apart. Markdown takes a table on the line
80
+ * after a paragraph's text as a block of its own; Telegram's rich message takes it as more of the
81
+ * paragraph's text, so a table is sent apart from the text before it, as it was read here.
82
+ */
83
+ function markdownBlocksApart(markdown) {
84
+ const blocks = converter.toAst(markdown).children.map((node) => {
85
+ const start = node.position?.start.offset;
86
+ const end = node.position?.end.offset;
87
+ return start === undefined || end === undefined ? undefined : markdown.slice(start, end);
88
+ });
89
+ return blocks.every((block) => block !== undefined) ? blocks.join("\n\n") : markdown;
90
+ }
78
91
  /**
79
92
  * The message as one Telegram rich message, for Markdown with a table, which MarkdownV2 shows only
80
- * as code: the member's Markdown, its links to the app as `renderTelegram` points them, then the
81
- * attribution. Undefined without a table, beyond what one rich message takes, or when a block the
82
- * Markdown leaves open, such as a code fence it never closes, would take the attribution in.
93
+ * as code: the member's Markdown, its blocks a blank line apart and its links to the app as
94
+ * `renderTelegram` points them, then the attribution. Undefined without a table, beyond what one
95
+ * rich message takes, or when a block the Markdown leaves open, such as a code fence it never
96
+ * closes, would take the attribution in.
83
97
  */
84
98
  export function telegramRichMarkdown(markdown, attribution, separator = "\n\n", links = new Map()) {
85
99
  // A table has pipes: Markdown without one is not parsed again.
86
100
  if (!markdown.includes("|")) {
87
101
  return undefined;
88
102
  }
89
- const body = links.size === 0 ? markdown : stringifyMarkdown(telegramMarkdownWithLinks(markdown, links));
103
+ // Written back from its tree, Markdown with links to the app has its blocks apart already.
104
+ const body = links.size === 0
105
+ ? markdownBlocksApart(markdown)
106
+ : stringifyMarkdown(telegramMarkdownWithLinks(markdown, links));
90
107
  const signed = attribution === "" ? "" : markdownAttribution(attribution, separator);
91
108
  const rich = signed === "" ? body : `${body}\n\n${signed}`;
92
109
  const tree = converter.toAst(rich);
@@ -692,6 +692,7 @@ export interface AgentStore {
692
692
  readonly readChatPersona?: (key: string) => Effect.Effect<{
693
693
  readonly persona: string | null;
694
694
  readonly changedAt: string | null;
695
+ readonly registeredAt?: string | null;
695
696
  }>;
696
697
  readonly seeChat: (input: {
697
698
  readonly provider: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.195.0",
3
+ "version": "0.196.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",