@zhin.js/core 1.8.0 → 1.9.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.
@@ -0,0 +1,145 @@
1
+ /**
2
+ * ADR 0060 §6: the public read side of chat roles for plugins.
3
+ *
4
+ * - {@link isOwner} / {@link hasChatRole}: pure checks of the current message's sender, from the
5
+ * facts the Runtime wrote (`sender.chatRole` / `sender.chatRoleLevels`); no database access.
6
+ * - {@link chatRolesToken}: a read-only {@link ChatRoleReader} for code outside a message context
7
+ * (schedules, webhooks, notifications): who holds a role, what a platform identity holds, change
8
+ * notifications. Writes stay with the Console RPC and the chat commands (thresholds + audit).
9
+ *
10
+ * Plugins should read roles here instead of keeping their own `masters` / admin lists.
11
+ */
12
+ import { type ChatRoleLevel, type ChatRoleLevels, type ConversationRef } from '@zhin.js/im-contract';
13
+ import { type ChatIdentity, type ChatRole, type ChatRoleService } from './roles.js';
14
+ export { implicitChatPrincipalId } from './roles.js';
15
+ /** The sender facts the Runtime writes on every inbound message (`sender.chatRole` / `sender.chatRoleLevels`). */
16
+ export interface ChatRoleSenderFacts {
17
+ readonly chatRole?: unknown;
18
+ readonly chatRoleLevels?: unknown;
19
+ }
20
+ /**
21
+ * Whether the sender is an `owner` at `level` or above on this conversation's chain. The default
22
+ * level `global` means "the owner of this host" (exec, files, restart …); a conversation- or
23
+ * account-level owner is not.
24
+ */
25
+ export declare function isOwner(sender: ChatRoleSenderFacts | null | undefined, options?: Readonly<{
26
+ level?: ChatRoleLevel;
27
+ }>): boolean;
28
+ /**
29
+ * Whether the sender holds `role` (or a higher one) at `level` or above on this conversation's
30
+ * chain. The default level `conversation` accepts a role held anywhere on the chain. Same rule as
31
+ * {@link chatRoleHeldAt}, which stays exported.
32
+ */
33
+ export declare function hasChatRole(sender: ChatRoleSenderFacts | null | undefined, role: ChatRole, options?: Readonly<{
34
+ level?: ChatRoleLevel;
35
+ }>): boolean;
36
+ /** A scope of the four-level chain (ADR 0056 §2). */
37
+ export type ChatScopeRef = {
38
+ readonly level: 'global';
39
+ } | {
40
+ readonly level: 'adapter';
41
+ readonly adapter: string;
42
+ } | {
43
+ readonly level: 'endpoint';
44
+ readonly adapter: string;
45
+ readonly endpointId: string;
46
+ } | {
47
+ readonly level: 'conversation';
48
+ readonly conversation: ConversationRef;
49
+ };
50
+ /**
51
+ * A person (ADR 0060 §2): a stored person has a `cp_…` id; an identity without one is its own
52
+ * implicit single-identity person, with the id `implicit:<alias>:<userId>`.
53
+ */
54
+ export interface ChatPrincipalView {
55
+ readonly id: string;
56
+ readonly displayName?: string;
57
+ readonly identities: readonly ChatIdentity[];
58
+ }
59
+ /** A stored grant was written (`grant`, including a changed role) or removed (`revoke`). */
60
+ export interface ChatRoleGrantChange {
61
+ readonly kind: 'grant' | 'revoke';
62
+ /** The identity the grant was written for. */
63
+ readonly identity: ChatIdentity;
64
+ /** The person holding the grant (ADR 0060 §2.3). */
65
+ readonly principalId?: string;
66
+ readonly level: ChatRoleLevel;
67
+ /** Normalized scope key (`''` for global). */
68
+ readonly key: string;
69
+ /** The role after a `grant`; absent on a `revoke`. */
70
+ readonly role?: ChatRole;
71
+ }
72
+ /**
73
+ * Who belongs to whom changed (ADR 0060 §2.2): `merge` moved every identity of `from` to
74
+ * `principalId` (grants kept, the higher one where both held a scope); `split` gave `identities`
75
+ * their own new person `principalId`, out of `from`.
76
+ */
77
+ export interface ChatPrincipalChange {
78
+ readonly kind: 'merge' | 'split';
79
+ readonly principalId: string;
80
+ readonly from: string;
81
+ readonly identities: readonly ChatIdentity[];
82
+ }
83
+ /** Role or ownership changes (`ChatRoleReader.subscribe`). */
84
+ export type ChatRoleChange = ChatRoleGrantChange | ChatPrincipalChange;
85
+ /** The sender facts of one identity in one conversation (what the Runtime writes on `sender`). */
86
+ export interface ChatRoleFacts {
87
+ readonly identity: ChatIdentity;
88
+ /** The person the identity belongs to (what the Runtime writes as `sender.chatPrincipal`). */
89
+ readonly chatPrincipal?: string;
90
+ readonly chatRole?: ChatRole;
91
+ readonly chatRoleLevels?: ChatRoleLevels;
92
+ }
93
+ export interface ChatRoleHoldersOptions {
94
+ /** Only grants held at this level or above (default: `global` without `scope`, any level with it). */
95
+ readonly level?: ChatRoleLevel;
96
+ /** Grants effective at this scope (its own and inherited from above); default global. */
97
+ readonly scope?: ChatScopeRef;
98
+ /** Only identities on this adapter instance alias. */
99
+ readonly adapter?: string;
100
+ }
101
+ /** Read-only chat roles (ADR 0060 §6). Plugins are trusted code and may read every holder. */
102
+ export interface ChatRoleReader {
103
+ /** Highest role of a platform identity effective at `scope` (default global). */
104
+ roleOf(identity: ChatIdentity, scope?: ChatScopeRef): ChatRole | undefined;
105
+ /** The person an identity belongs to (its implicit single-identity person when none is stored). */
106
+ principalOf(identity: ChatIdentity): ChatPrincipalView;
107
+ /** People holding `role` (or a higher one), with their identities — e.g. whom to notify. */
108
+ holders(role: ChatRole, options?: ChatRoleHoldersOptions): readonly ChatPrincipalView[];
109
+ /**
110
+ * The facts the Runtime writes on `sender` for `userId` speaking in `conversation`; undefined
111
+ * when the conversation cannot be addressed.
112
+ */
113
+ factsOf(conversation: ConversationRef, userId: string): ChatRoleFacts | undefined;
114
+ /** Grant / revoke / merge / split notifications; returns the unsubscribe function. */
115
+ subscribe(listener: (change: ChatRoleChange) => void): () => void;
116
+ /**
117
+ * ADR 0060 §5.4: the identity on `conversation`'s adapter of the person linked to Console user
118
+ * `consoleUserId` (the first one when the person has several there); undefined when the user is
119
+ * not linked or the person has no identity on that adapter. A local simulation (the Console
120
+ * Sandbox) speaks as it for an authenticated Console user who chose 「以我的聊天身份发言」.
121
+ * Optional for readers built before P3.
122
+ *
123
+ * When the linked person holds a global grant, it counts for every identity of the person, so
124
+ * the identity is returned only with `canManageGlobal: true` (the Console caller holds global
125
+ * `iam.manage`); otherwise undefined — the same rule as `chat-identities.simulated.ensure`.
126
+ */
127
+ consoleSpeaker?(conversation: ConversationRef, consoleUserId: string, options?: ChatConsoleSpeakerOptions): ChatIdentity | undefined;
128
+ }
129
+ /** What the Console caller behind {@link ChatRoleReader.consoleSpeaker} may do. */
130
+ export interface ChatConsoleSpeakerOptions {
131
+ /** The caller holds global `iam.manage`; required to speak as a person who holds a global grant. */
132
+ readonly canManageGlobal?: boolean;
133
+ }
134
+ export declare const chatRolesToken: import("@zhin.js/plugin-runtime").Token<ChatRoleReader>;
135
+ export interface ChatRoleReaderOptions {
136
+ /** The role resolution (undefined while the stores are not loaded: nothing is held). */
137
+ readonly roles: () => ChatRoleService | undefined;
138
+ /** Scope key of a conversation in the current generation (conversation key, else the endpoint key). */
139
+ readonly conversationKey: (conversation: ConversationRef) => string | undefined;
140
+ readonly subscribe?: (listener: (change: ChatRoleChange) => void) => () => void;
141
+ /** Stored person linked to a Console user id (ADR 0060 §2.4); absent: no Console links. */
142
+ readonly consolePrincipal?: (consoleUserId: string) => string | undefined;
143
+ }
144
+ /** The read side over a {@link ChatRoleService}; the instance provides it as {@link chatRolesToken}. */
145
+ export declare function createChatRoleReader(options: ChatRoleReaderOptions): ChatRoleReader;
@@ -0,0 +1,183 @@
1
+ /**
2
+ * ADR 0060 §6: the public read side of chat roles for plugins.
3
+ *
4
+ * - {@link isOwner} / {@link hasChatRole}: pure checks of the current message's sender, from the
5
+ * facts the Runtime wrote (`sender.chatRole` / `sender.chatRoleLevels`); no database access.
6
+ * - {@link chatRolesToken}: a read-only {@link ChatRoleReader} for code outside a message context
7
+ * (schedules, webhooks, notifications): who holds a role, what a platform identity holds, change
8
+ * notifications. Writes stay with the Console RPC and the chat commands (thresholds + audit).
9
+ *
10
+ * Plugins should read roles here instead of keeping their own `masters` / admin lists.
11
+ */
12
+ import { CHAT_ROLE_LEVELS, chatRoleHeldAt, normalizeChatRoleLevels, } from '@zhin.js/im-contract';
13
+ import { createToken } from '@zhin.js/plugin-runtime';
14
+ import { chatPrincipalOf, chatRoleEntryAppliesTo, chatRoleEntryPrincipalId, chatRoleIncludes, chatScopeChain, higherChatRole, implicitChatPrincipalId, isChatIdentity, normalizeChatRoleScope, } from './roles.js';
15
+ export { implicitChatPrincipalId } from './roles.js';
16
+ /**
17
+ * Whether the sender is an `owner` at `level` or above on this conversation's chain. The default
18
+ * level `global` means "the owner of this host" (exec, files, restart …); a conversation- or
19
+ * account-level owner is not.
20
+ */
21
+ export function isOwner(sender, options) {
22
+ return chatRoleHeldAt(sender, 'owner', options?.level ?? 'global');
23
+ }
24
+ /**
25
+ * Whether the sender holds `role` (or a higher one) at `level` or above on this conversation's
26
+ * chain. The default level `conversation` accepts a role held anywhere on the chain. Same rule as
27
+ * {@link chatRoleHeldAt}, which stays exported.
28
+ */
29
+ export function hasChatRole(sender, role, options) {
30
+ return chatRoleHeldAt(sender, role, options?.level ?? 'conversation');
31
+ }
32
+ export const chatRolesToken = createToken('zhin.chat-roles', 'Read-only chat roles (ADR 0060 §6): roleOf / principalOf / holders / factsOf / subscribe');
33
+ const LEVEL_INDEX = (level) => CHAT_ROLE_LEVELS.indexOf(level);
34
+ /** The read side over a {@link ChatRoleService}; the instance provides it as {@link chatRolesToken}. */
35
+ export function createChatRoleReader(options) {
36
+ const scopeKey = (scope) => {
37
+ if (!scope || scope.level === 'global')
38
+ return '';
39
+ try {
40
+ if (scope.level === 'adapter')
41
+ return normalizeChatRoleScope('adapter', scope.adapter);
42
+ if (scope.level === 'endpoint') {
43
+ if (typeof scope.endpointId !== 'string' || !scope.endpointId || typeof scope.adapter !== 'string' || scope.adapter.includes('/'))
44
+ return undefined;
45
+ return normalizeChatRoleScope('endpoint', `${scope.adapter}/${scope.endpointId}`);
46
+ }
47
+ return options.conversationKey(scope.conversation);
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ };
53
+ const chainOf = (key) => key === '' ? [''] : chatScopeChain(key);
54
+ const view = (identity, service) => {
55
+ const record = service ? chatPrincipalOf(service.store, identity) : undefined;
56
+ return Object.freeze({
57
+ id: record?.id ?? implicitChatPrincipalId(identity),
58
+ ...(record?.displayName ? { displayName: record.displayName } : {}),
59
+ identities: Object.freeze((record?.identities ?? [identity]).map(held => Object.freeze({ adapter: held.adapter, userId: held.userId }))),
60
+ });
61
+ };
62
+ const api = {
63
+ roleOf(identity, scope) {
64
+ const service = options.roles();
65
+ const key = scopeKey(scope);
66
+ if (!service || key === undefined || !isChatIdentity(identity))
67
+ return undefined;
68
+ try {
69
+ return service.roleAt(identity, key);
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ },
75
+ principalOf(identity) {
76
+ let service;
77
+ try {
78
+ service = options.roles();
79
+ }
80
+ catch {
81
+ service = undefined;
82
+ }
83
+ return view(identity, isChatIdentity(identity) ? service : undefined);
84
+ },
85
+ holders(role, holderOptions = {}) {
86
+ const service = options.roles();
87
+ const key = scopeKey(holderOptions.scope);
88
+ if (!service || key === undefined)
89
+ return Object.freeze([]);
90
+ const chain = chainOf(key);
91
+ const minimum = holderOptions.level ?? (holderOptions.scope ? 'conversation' : 'global');
92
+ // Per person, the identities the matching grants count for (ADR 0060 Q10: below global
93
+ // only those on the scope's adapter), optionally narrowed to one adapter.
94
+ const seen = new Map();
95
+ const entries = service.store.list();
96
+ for (const entry of entries) {
97
+ if (!chain.includes(entry.key) || !chatRoleIncludes(entry.role, role))
98
+ continue;
99
+ if (LEVEL_INDEX(entry.level) > LEVEL_INDEX(minimum))
100
+ continue;
101
+ const id = chatRoleEntryPrincipalId(entry);
102
+ const stored = entry.principalId ? service.store.principal?.(entry.principalId) : undefined;
103
+ const principal = stored
104
+ ? Object.freeze({ id: stored.id, ...(stored.displayName ? { displayName: stored.displayName } : {}), identities: stored.identities })
105
+ : view(entry, undefined);
106
+ const holder = seen.get(id) ?? { view: principal, identities: new Map() };
107
+ for (const identity of principal.identities) {
108
+ if (!chatRoleEntryAppliesTo(entry, identity))
109
+ continue;
110
+ if (holderOptions.adapter !== undefined && identity.adapter !== holderOptions.adapter)
111
+ continue;
112
+ holder.identities.set(`${identity.adapter}\0${identity.userId}`, Object.freeze({ adapter: identity.adapter, userId: identity.userId }));
113
+ }
114
+ seen.set(id, holder);
115
+ }
116
+ return Object.freeze([...seen.values()].filter(holder => holder.identities.size > 0)
117
+ .map(holder => Object.freeze({ ...holder.view, identities: Object.freeze([...holder.identities.values()]) })));
118
+ },
119
+ factsOf(conversation, userId) {
120
+ const key = scopeKey({ level: 'conversation', conversation });
121
+ if (key === undefined)
122
+ return undefined;
123
+ const adapter = chainOf(key)[1];
124
+ const identity = { adapter, userId };
125
+ if (!adapter || !isChatIdentity(identity))
126
+ return undefined;
127
+ const service = options.roles();
128
+ let entries = [];
129
+ let chatPrincipal;
130
+ try {
131
+ chatPrincipal = service?.principalOf(identity).id;
132
+ entries = service?.entriesFor(identity, key) ?? [];
133
+ }
134
+ catch {
135
+ entries = [];
136
+ }
137
+ let chatRole;
138
+ const levels = {};
139
+ for (const entry of entries)
140
+ chatRole = higherChatRole(chatRole, entry.role);
141
+ for (const candidate of ['owner', 'admin', 'trusted']) {
142
+ // Entries come sorted global first: the first holder is the topmost level.
143
+ const top = entries.find(entry => chatRoleIncludes(entry.role, candidate));
144
+ if (top)
145
+ levels[candidate] = top.level;
146
+ }
147
+ const chatRoleLevels = normalizeChatRoleLevels(levels);
148
+ return Object.freeze({ identity: Object.freeze(identity), ...(chatPrincipal ? { chatPrincipal } : {}),
149
+ ...(chatRole ? { chatRole } : {}), ...(chatRole && chatRoleLevels ? { chatRoleLevels } : {}) });
150
+ },
151
+ subscribe(listener) {
152
+ return options.subscribe ? options.subscribe(listener) : () => undefined;
153
+ },
154
+ consoleSpeaker(conversation, consoleUserId, speakerOptions) {
155
+ if (typeof consoleUserId !== 'string' || !consoleUserId || !options.consolePrincipal)
156
+ return undefined;
157
+ const key = scopeKey({ level: 'conversation', conversation });
158
+ if (key === undefined)
159
+ return undefined;
160
+ const adapter = chainOf(key)[1];
161
+ if (!adapter)
162
+ return undefined;
163
+ let principalId;
164
+ let service;
165
+ try {
166
+ principalId = options.consolePrincipal(consoleUserId);
167
+ service = options.roles();
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ if (!principalId || !service)
173
+ return undefined;
174
+ // A link must never be worth the person's global grants (ADR 0060 §5.4, security review).
175
+ if (speakerOptions?.canManageGlobal !== true
176
+ && service.store.list().some(entry => entry.level === 'global' && chatRoleEntryPrincipalId(entry) === principalId))
177
+ return undefined;
178
+ const held = service.store.principal?.(principalId)?.identities.find(identity => identity.adapter === adapter && isChatIdentity(identity));
179
+ return held ? Object.freeze({ adapter: held.adapter, userId: held.userId }) : undefined;
180
+ },
181
+ };
182
+ return Object.freeze(api);
183
+ }
@@ -43,6 +43,12 @@ export declare function chatScopeLevel(key: string): FeatureConfigLevel;
43
43
  /** Where an entry comes from: `grant` (the `chat_roles` table). */
44
44
  export type ChatRoleSourceKind = 'grant';
45
45
  export interface ChatRoleEntry extends ChatIdentity {
46
+ /**
47
+ * The person holding the grant (ADR 0060 §2.3). `adapter` / `userId` are the identity the grant
48
+ * was written for (kept for rollback); absent on entries without a stored person, which belong
49
+ * to the implicit single-identity person of `adapter` / `userId`.
50
+ */
51
+ readonly principalId?: string;
46
52
  readonly level: FeatureConfigLevel;
47
53
  /** Normalized scope key (`''` for global). */
48
54
  readonly key: string;
@@ -58,10 +64,36 @@ export interface ChatRoleContext {
58
64
  readonly conversationKey?: string;
59
65
  readonly platform?: PlatformStanding;
60
66
  }
67
+ /** A stored person (ADR 0060 §2.1) and its platform identities. */
68
+ export interface ChatPrincipalRecord {
69
+ readonly id: string;
70
+ readonly displayName?: string;
71
+ readonly identities: readonly ChatIdentity[];
72
+ }
61
73
  /** Stored grants (the instance's `chat_roles` table, held in memory). */
62
74
  export interface ChatRoleGrantStore {
63
75
  list(): readonly ChatRoleEntry[];
76
+ /**
77
+ * The stored person an identity belongs to (ADR 0060 §2.2); undefined: the identity is its own
78
+ * implicit single-identity person.
79
+ */
80
+ principalOf?(identity: ChatIdentity): ChatPrincipalRecord | undefined;
81
+ /** A stored person by id. */
82
+ principal?(id: string): ChatPrincipalRecord | undefined;
64
83
  }
84
+ /** Id of the implicit single-identity person of `identity` (no stored person yet). */
85
+ export declare function implicitChatPrincipalId(identity: ChatIdentity): string;
86
+ /** The person of an identity: the stored one, else its implicit single-identity person. */
87
+ export declare function chatPrincipalOf(store: ChatRoleGrantStore, identity: ChatIdentity): ChatPrincipalRecord;
88
+ /** Id of the person holding `entry`. */
89
+ export declare function chatRoleEntryPrincipalId(entry: ChatRoleEntry): string;
90
+ /** Adapter alias a scope key belongs to (`undefined` for global). */
91
+ export declare function chatScopeAdapter(key: string): string | undefined;
92
+ /**
93
+ * ADR 0060 §2.3 / Q10: a grant below global only counts for the person's identities on the
94
+ * scope's own adapter; a global grant counts for every identity of the person.
95
+ */
96
+ export declare function chatRoleEntryAppliesTo(entry: Pick<ChatRoleEntry, 'key'>, identity: ChatIdentity): boolean;
65
97
  /** Effective roles of one sender in one conversation. */
66
98
  export interface ChatRoleResolution {
67
99
  readonly identity: ChatIdentity;
@@ -80,7 +112,17 @@ export declare class ChatRoleService<TStore extends ChatRoleGrantStore = ChatRol
80
112
  constructor(options: Readonly<{
81
113
  store: TStore;
82
114
  }>);
83
- /** Entries of `identity` effective at `scopeKey` (own scope and every ancestor). */
115
+ /** The person `identity` belongs to (ADR 0060 §2): stored, else its implicit single-identity person. */
116
+ principalOf(identity: ChatIdentity): ChatPrincipalRecord;
117
+ /**
118
+ * Every stored entry of the person `identity` belongs to that counts for `identity` (any scope):
119
+ * global grants and grants at scopes of the identity's own adapter (ADR 0060 Q10).
120
+ */
121
+ heldBy(identity: ChatIdentity): readonly ChatRoleEntry[];
122
+ /**
123
+ * Entries of `identity` effective at `scopeKey` (own scope and every ancestor): the grants of
124
+ * the person it belongs to, below global only those on the identity's own adapter (ADR 0060 Q10).
125
+ */
84
126
  entriesFor(identity: ChatIdentity, scopeKey: string): readonly ChatRoleEntry[];
85
127
  /** Highest role of `identity` effective at `scopeKey`. */
86
128
  roleAt(identity: ChatIdentity, scopeKey: string): ChatRole | undefined;
@@ -122,9 +164,19 @@ export declare function chatRoleMessageContext(snapshot: ChatRoleSnapshot, messa
122
164
  } | undefined;
123
165
  export interface ChatRoleSenderFields {
124
166
  readonly id: string;
167
+ readonly name?: string;
125
168
  readonly platform?: PlatformStanding;
126
169
  readonly chatRole?: ChatRole;
127
170
  readonly chatRoleLevels?: ChatRoleLevels;
171
+ /** The person the sender's identity belongs to (ADR 0060 §2.3). Set by the Runtime only. */
172
+ readonly chatPrincipal?: string;
173
+ }
174
+ /** One inbound sighting of an identity (ADR 0060 §2.2 `last_seen_at`; never used for authorization). */
175
+ export interface ChatIdentitySighting {
176
+ readonly identity: ChatIdentity;
177
+ /** The conversation key (or the endpoint key when the conversation cannot be keyed). */
178
+ readonly scopeKey: string;
179
+ readonly displayName?: string;
128
180
  }
129
181
  /**
130
182
  * Inbound sender enricher: drops any adapter-supplied `chatRole` / `chatRoleLevels`, normalizes
@@ -133,6 +185,8 @@ export interface ChatRoleSenderFields {
133
185
  */
134
186
  export declare function createChatRoleSenderEnricher(options: Readonly<{
135
187
  roles: () => ChatRoleService | undefined;
188
+ /** Told about every addressable sender (display name cache, recent speakers); errors are ignored. */
189
+ observe?: (sighting: ChatIdentitySighting) => void;
136
190
  }>): <TSender extends ChatRoleSenderFields>(sender: TSender | undefined, conversation: ConversationRef, snapshot?: RuntimeSnapshot) => TSender | undefined;
137
191
  /**
138
192
  * 转义用户正文里所有自造的 `[sender:` / `[origin:` 标签(任意位置、大小写不敏感,
@@ -46,10 +46,19 @@ export function expandChatRole(role) {
46
46
  const ADAPTER_ALIAS = /^[a-z0-9][a-z0-9-]*$/u;
47
47
  // eslint-disable-next-line no-control-regex
48
48
  const CONTROL = /[\u0000-\u001f\u007f]/u;
49
+ /**
50
+ * ADR 0060 §5.4: sender ids starting with `~` are reserved for **simulated** speakers (a local
51
+ * simulation such as the Console Sandbox writes a client-chosen id as `~sim:<id>`). They are not
52
+ * chat identities: they never hold, receive or resolve a role, never belong to a person and are
53
+ * never recorded as recent speakers — so typing someone's id into a simulation cannot borrow
54
+ * their role.
55
+ */
56
+ const RESERVED_SENDER_PREFIX = '~';
49
57
  export function isChatIdentity(value) {
50
58
  const identity = value;
51
59
  return !!identity && typeof identity.adapter === 'string' && ADAPTER_ALIAS.test(identity.adapter)
52
- && typeof identity.userId === 'string' && identity.userId.length > 0 && identity.userId.length <= 256 && !CONTROL.test(identity.userId);
60
+ && typeof identity.userId === 'string' && identity.userId.length > 0 && identity.userId.length <= 256 && !CONTROL.test(identity.userId)
61
+ && !identity.userId.startsWith(RESERVED_SENDER_PREFIX);
53
62
  }
54
63
  /** Validates `level` + `key` and returns the normalized scope key; throws TypeError. */
55
64
  export function normalizeChatRoleScope(level, key) {
@@ -94,6 +103,33 @@ export function chatScopeCovers(upper, lower) {
94
103
  export function chatScopeLevel(key) {
95
104
  return key === '' ? 'global' : featureKeyLevel(key);
96
105
  }
106
+ /** Id of the implicit single-identity person of `identity` (no stored person yet). */
107
+ export function implicitChatPrincipalId(identity) {
108
+ return `implicit:${identity.adapter}:${identity.userId}`;
109
+ }
110
+ /** The person of an identity: the stored one, else its implicit single-identity person. */
111
+ export function chatPrincipalOf(store, identity) {
112
+ const stored = store.principalOf?.(identity);
113
+ if (stored)
114
+ return stored;
115
+ return Object.freeze({ id: implicitChatPrincipalId(identity),
116
+ identities: Object.freeze([Object.freeze({ adapter: identity.adapter, userId: identity.userId })]) });
117
+ }
118
+ /** Id of the person holding `entry`. */
119
+ export function chatRoleEntryPrincipalId(entry) {
120
+ return entry.principalId ?? implicitChatPrincipalId(entry);
121
+ }
122
+ /** Adapter alias a scope key belongs to (`undefined` for global). */
123
+ export function chatScopeAdapter(key) {
124
+ return key === '' ? undefined : chatScopeChain(key)[1];
125
+ }
126
+ /**
127
+ * ADR 0060 §2.3 / Q10: a grant below global only counts for the person's identities on the
128
+ * scope's own adapter; a global grant counts for every identity of the person.
129
+ */
130
+ export function chatRoleEntryAppliesTo(entry, identity) {
131
+ return entry.key === '' || chatScopeAdapter(entry.key) === identity.adapter;
132
+ }
97
133
  /** Per role, the level of the topmost entry holding it (entries sorted global first). */
98
134
  function chatRoleLevelsOf(entries) {
99
135
  const levels = {};
@@ -119,10 +155,28 @@ export class ChatRoleService {
119
155
  constructor(options) {
120
156
  this.store = options.store;
121
157
  }
122
- /** Entries of `identity` effective at `scopeKey` (own scope and every ancestor). */
158
+ /** The person `identity` belongs to (ADR 0060 §2): stored, else its implicit single-identity person. */
159
+ principalOf(identity) {
160
+ return chatPrincipalOf(this.store, identity);
161
+ }
162
+ /**
163
+ * Every stored entry of the person `identity` belongs to that counts for `identity` (any scope):
164
+ * global grants and grants at scopes of the identity's own adapter (ADR 0060 Q10).
165
+ */
166
+ heldBy(identity) {
167
+ // A reserved (simulated) or malformed sender id holds nothing, whatever is stored (ADR 0060 §5.4).
168
+ if (!isChatIdentity(identity))
169
+ return Object.freeze([]);
170
+ const principal = this.principalOf(identity).id;
171
+ return Object.freeze(this.store.list().filter(entry => chatRoleEntryPrincipalId(entry) === principal && chatRoleEntryAppliesTo(entry, identity)));
172
+ }
173
+ /**
174
+ * Entries of `identity` effective at `scopeKey` (own scope and every ancestor): the grants of
175
+ * the person it belongs to, below global only those on the identity's own adapter (ADR 0060 Q10).
176
+ */
123
177
  entriesFor(identity, scopeKey) {
124
178
  const chain = chatScopeChain(scopeKey);
125
- const stored = this.store.list().filter(entry => entry.adapter === identity.adapter && entry.userId === identity.userId && chain.includes(entry.key));
179
+ const stored = this.heldBy(identity).filter(entry => chain.includes(entry.key));
126
180
  return Object.freeze([...stored].sort((left, right) => chain.indexOf(left.key) - chain.indexOf(right.key)));
127
181
  }
128
182
  /** Highest role of `identity` effective at `scopeKey`. */
@@ -164,9 +218,20 @@ export class ChatRoleService {
164
218
  ownersOf(scopeKey, adapter) {
165
219
  const chain = chatScopeChain(scopeKey);
166
220
  const owners = this.store.list()
167
- .filter(entry => entry.role === 'owner' && entry.adapter === adapter && chain.includes(entry.key))
221
+ .filter(entry => entry.role === 'owner' && chain.includes(entry.key))
168
222
  .sort((left, right) => chain.indexOf(right.key) - chain.indexOf(left.key));
169
- return Object.freeze([...new Set(owners.map(entry => entry.userId))]);
223
+ const userIds = [];
224
+ for (const entry of owners) {
225
+ // The person's identities on `adapter` (a stored person's, else the grant's own identity).
226
+ const principal = entry.principalId ? this.store.principal?.(entry.principalId) : undefined;
227
+ for (const identity of principal?.identities ?? [{ adapter: entry.adapter, userId: entry.userId }]) {
228
+ if (identity.adapter !== adapter || !chatRoleEntryAppliesTo(entry, identity))
229
+ continue;
230
+ if (!userIds.includes(identity.userId))
231
+ userIds.push(identity.userId);
232
+ }
233
+ }
234
+ return Object.freeze(userIds);
170
235
  }
171
236
  }
172
237
  // ============================================================================
@@ -225,7 +290,9 @@ export function createChatRoleSenderEnricher(options) {
225
290
  return (sender, conversation, snapshot) => {
226
291
  if (!sender?.id)
227
292
  return sender;
228
- const { chatRole: _spoofed, chatRoleLevels: _spoofedLevels, platform: _reported, ...rest } = sender;
293
+ // Adapters and plugins never set the Runtime's facts: `chatRole`, `chatRoleLevels` and
294
+ // `chatPrincipal` they supply are dropped (ADR 0060 §2.3).
295
+ const { chatRole: _spoofed, chatRoleLevels: _spoofedLevels, chatPrincipal: _spoofedPrincipal, platform: _reported, ...rest } = sender;
229
296
  const platform = conversation.kind === 'private' ? undefined : platformStandingOf(sender);
230
297
  const base = { ...rest, ...(platform ? { platform } : {}) };
231
298
  const service = options.roles();
@@ -235,14 +302,24 @@ export function createChatRoleSenderEnricher(options) {
235
302
  if (!subject)
236
303
  return Object.freeze(base);
237
304
  let entries;
305
+ let principal;
238
306
  try {
307
+ principal = service.principalOf(subject.identity).id;
239
308
  entries = service.entriesFor(subject.identity, subject.context.conversationKey);
240
309
  }
241
310
  catch {
242
311
  entries = [];
243
312
  }
313
+ if (options.observe) {
314
+ try {
315
+ const name = typeof base.name === 'string' && base.name ? base.name : undefined;
316
+ options.observe(Object.freeze({ identity: subject.identity, scopeKey: subject.context.conversationKey, ...(name ? { displayName: name } : {}) }));
317
+ }
318
+ catch { /* a sighting never breaks a message */ }
319
+ }
244
320
  const role = highest(entries);
245
- return Object.freeze({ ...base, ...(role ? { chatRole: role, chatRoleLevels: chatRoleLevelsOf(entries) } : {}) });
321
+ return Object.freeze({ ...base, ...(principal ? { chatPrincipal: principal } : {}),
322
+ ...(role ? { chatRole: role, chatRoleLevels: chatRoleLevelsOf(entries) } : {}) });
246
323
  };
247
324
  }
248
325
  // ============================================================================
package/lib/index.d.ts CHANGED
@@ -24,6 +24,7 @@ export type { AgentTurnMessage, SyntheticMessageInput } from './built/message-en
24
24
  export * from './built/tool-access.js';
25
25
  export * from './built/common-adapter-tools.js';
26
26
  export * from './built/roles.js';
27
+ export * from './built/chat-role-reader.js';
27
28
  export * from './im-session-id.js';
28
29
  export * from './built/ai-trigger.js';
29
30
  export * from './built/ai-access.js';
package/lib/index.js CHANGED
@@ -24,6 +24,7 @@ export * from './built/message-enrich.js';
24
24
  export * from './built/tool-access.js';
25
25
  export * from './built/common-adapter-tools.js';
26
26
  export * from './built/roles.js';
27
+ export * from './built/chat-role-reader.js';
27
28
  export * from './im-session-id.js';
28
29
  export * from './built/ai-trigger.js';
29
30
  export * from './built/ai-access.js';
@@ -1,5 +1,6 @@
1
1
  import { readOperationInputResources } from '@zhin.js/feature-kit';
2
2
  import { Fragment, jsx } from '@zhin.js/jsx';
3
+ import { parsePermitName } from '@zhin.js/permission';
3
4
  import { formatCompact, getLogger } from '@zhin.js/logger';
4
5
  import { createToken, createMessages, resolveLocale } from '@zhin.js/plugin-runtime';
5
6
  import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
@@ -22,6 +23,15 @@ function feedbackFrom(result) {
22
23
  const feedbackMessages = createMessages({
23
24
  denied: { 'zh-CN': '没有权限执行此指令。', en: 'You do not have permission to run this command.' },
24
25
  deniedBecause: { 'zh-CN': '无法执行此指令:{reason}', en: 'This command cannot run here: {reason}' },
26
+ // ADR 0060 §5.3: zhin role conditions say where roles come from (never which role or who holds it).
27
+ deniedRole: {
28
+ 'zh-CN': '没有权限执行此指令:它需要 zhin 角色。请联系本机器人的主人授予,或由主人在 Console「聊天角色」页授予。',
29
+ en: 'You do not have permission to run this command: it needs a zhin role. Ask the owner of this bot to grant one, in chat or on the Console "Chat roles" page.',
30
+ },
31
+ deniedRoleStanding: {
32
+ 'zh-CN': '没有权限执行此指令:它需要 zhin 角色,群主 / 群管理员的平台身份不等于 zhin 角色。请联系本机器人的主人授予,或由主人在 Console「聊天角色」页授予。',
33
+ en: 'You do not have permission to run this command: it needs a zhin role, and being a group owner / admin on the platform is not one. Ask the owner of this bot to grant one, in chat or on the Console "Chat roles" page.',
34
+ },
25
35
  cooldown: { 'zh-CN': '此指令仍在冷却,请稍后再试。', en: 'This command is on cooldown. Try again later.' },
26
36
  wait: { 'zh-CN': '此指令仍在冷却,约 {seconds} 秒后再试。', en: 'This command is on cooldown. Try again in about {seconds} seconds.' },
27
37
  busy: { 'zh-CN': '你的上一条同类指令仍在处理中,请等待执行完成,避免重复触发。', en: 'Your previous command is still running. Wait for it to finish before trying again.' },
@@ -31,15 +41,22 @@ const feedbackMessages = createMessages({
31
41
  function explainsDenial(permit) {
32
42
  return typeof permit === 'string' && /^(platform|platform-role|platform-permission|bot|bot-role|bot-permission):/u.test(permit);
33
43
  }
34
- function defaultFeedback(feedback, locale) {
44
+ function deniesZhinRole(permit) {
45
+ return typeof permit === 'string' && parsePermitName(permit)?.kind === 'role';
46
+ }
47
+ function defaultFeedback(feedback, locale, standing) {
35
48
  if (feedback.status === 'invalid') {
36
49
  return [...feedback.issues.map(issue => issue.message), feedback.help].filter(Boolean).join('\n');
37
50
  }
38
51
  // Platform / Bot conditions say what is missing (e.g. 「机器人不是本群管理员」); zhin role and
39
52
  // conversation conditions keep the generic sentence.
40
- if (feedback.status === 'denied')
41
- return feedback.reason && explainsDenial(feedback.permit)
42
- ? feedbackMessages(locale, 'deniedBecause', { reason: feedback.reason }) : feedbackMessages(locale, 'denied');
53
+ if (feedback.status === 'denied') {
54
+ if (feedback.reason && explainsDenial(feedback.permit))
55
+ return feedbackMessages(locale, 'deniedBecause', { reason: feedback.reason });
56
+ if (deniesZhinRole(feedback.permit))
57
+ return feedbackMessages(locale, standing === 'owner' || standing === 'admin' ? 'deniedRoleStanding' : 'deniedRole');
58
+ return feedbackMessages(locale, 'denied');
59
+ }
43
60
  const reason = feedback.limit?.reason;
44
61
  const waitMs = feedback.limit?.retryAfterMs;
45
62
  return reason === 'cooldown'
@@ -84,7 +101,7 @@ export async function renderCommandFeedback(result, message, snapshot) {
84
101
  logger.warn(formatCompact({ op: 'command_feedback_error', generation: snapshot.generation, status: feedback.status }));
85
102
  }
86
103
  }
87
- return { content: defaultFeedback(feedback, resolveLocale(message.locale)), owner: result.owner };
104
+ return { content: defaultFeedback(feedback, resolveLocale(message.locale), message.sender?.platform?.standing), owner: result.owner };
88
105
  }
89
106
  export const commandMenuPresentationToken = createToken('zhin.command-menu-presentation', 'Root-selected command menu presentation; framework pagination remains unchanged');
90
107
  /** The current Root owns both the selected presenter and the resulting content. */
@@ -115,6 +115,11 @@ export interface MessageSenderRef {
115
115
  readonly chatRole?: ChatRole;
116
116
  /** Per role, the topmost level it is held at on this conversation's chain. Set by the Runtime only. */
117
117
  readonly chatRoleLevels?: ChatRoleLevels;
118
+ /**
119
+ * The person the sender's identity belongs to (ADR 0060 §2.3): a stored `cp_…` id, or
120
+ * `implicit:<alias>:<userId>`. Set by the Runtime only; an adapter's own value is dropped.
121
+ */
122
+ readonly chatPrincipal?: string;
118
123
  }
119
124
  export interface IncomingMessage {
120
125
  /** Original SDK message callback object; operation-only, not a persistence field. */
@@ -5,12 +5,14 @@
5
5
  import { type AdapterIndex } from '@zhin.js/adapter';
6
6
  import type { OperationSession } from '@zhin.js/feature-kit';
7
7
  import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
8
- import { type ChatRoleService } from '../../../built/roles.js';
8
+ import { type ChatIdentitySighting, type ChatRoleService } from '../../../built/roles.js';
9
9
  import type { ImRuntime } from '../im-runtime.js';
10
10
  export type ConfigurationChatAuthorizer = (session: OperationSession<string>, adapters: AdapterIndex) => boolean;
11
11
  export interface SenderEnricherOptions {
12
12
  /** Chat role resolution of the instance; undefined while it is not available. */
13
13
  readonly roles: () => ChatRoleService | undefined;
14
+ /** Every addressable sender (ADR 0060 §2.2 `last_seen_at` / display name cache); errors are ignored. */
15
+ readonly observe?: (sighting: ChatIdentitySighting) => void;
14
16
  }
15
17
  /** `ImRuntime` `enrichSender` option over the chat role model. */
16
18
  export declare function createSenderEnricher(options: SenderEnricherOptions): NonNullable<NonNullable<ConstructorParameters<typeof ImRuntime>[0]>['enrichSender']>;
@@ -85,6 +85,30 @@ export function previewMessageContent(content) {
85
85
  ? `${text.slice(0, messagePreviewLimit)}…`
86
86
  : text;
87
87
  }
88
+ /**
89
+ * Branded SendContent wrappers (#1250): a component call (`component('status-card', props)`, not yet
90
+ * rendered) reads as its text children, or `[name] title` / `[name]`, never as serialized JSON;
91
+ * untrusted content reads as the content it wraps; raw platform payloads as `[raw]`.
92
+ */
93
+ function flattenBrandedContent(record, depth) {
94
+ switch (record.$content) {
95
+ case 'zhin.component-call/1': {
96
+ const name = typeof record.name === 'string' && record.name ? record.name : 'component';
97
+ const props = record.props && typeof record.props === 'object' ? record.props : {};
98
+ const children = props.children === undefined ? '' : flattenNode(props.children, depth + 1).trim();
99
+ if (children)
100
+ return children;
101
+ const title = ['title', 'text', 'label'].map(key => props[key]).find((value) => typeof value === 'string' && value.trim() !== '');
102
+ return title ? `[${name}] ${title.trim()}` : `[${name}]`;
103
+ }
104
+ case 'zhin.untrusted-content/1':
105
+ return flattenNode(record.content, depth + 1);
106
+ case 'zhin.raw-content/1':
107
+ return '[raw]';
108
+ default:
109
+ return undefined;
110
+ }
111
+ }
88
112
  /**
89
113
  * Flattens any SendContent-like value to display text; non-text segments become `[type]`.
90
114
  * Markdown keeps its source text, buttons (keyboard rows and JSX `<button>`) become `[label]`, and
@@ -126,6 +150,9 @@ function flattenNode(content, depth) {
126
150
  }
127
151
  if (typeof record.text === 'string')
128
152
  return record.text;
153
+ const branded = flattenBrandedContent(record, depth);
154
+ if (branded !== undefined)
155
+ return branded;
129
156
  try {
130
157
  return JSON.stringify(content) ?? '';
131
158
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "Zhin机器人核心框架",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -52,21 +52,21 @@
52
52
  ],
53
53
  "dependencies": {
54
54
  "qrcode": "^1.5.4",
55
- "@zhin.js/adapter": "1.3.0",
56
- "@zhin.js/component": "1.1.19",
55
+ "@zhin.js/adapter": "1.3.1",
56
+ "@zhin.js/command": "1.3.0",
57
+ "@zhin.js/database": "1.2.1",
57
58
  "@zhin.js/handler": "1.1.18",
59
+ "@zhin.js/component": "1.1.19",
58
60
  "@zhin.js/im-contract": "1.2.0",
59
61
  "@zhin.js/kernel": "1.1.7",
60
- "@zhin.js/logger": "1.1.3",
62
+ "@zhin.js/logger": "1.2.0",
61
63
  "@zhin.js/middleware": "1.1.19",
62
64
  "@zhin.js/permission": "1.2.2",
63
65
  "@zhin.js/plugin-runtime": "1.3.0",
64
66
  "@zhin.js/schedule-feature": "1.1.18",
65
67
  "@zhin.js/schema": "1.1.7",
66
68
  "@zhin.js/jsx": "1.1.14",
67
- "@zhin.js/feature-kit": "1.1.18",
68
- "@zhin.js/command": "1.3.0",
69
- "@zhin.js/database": "1.2.0"
69
+ "@zhin.js/feature-kit": "1.1.18"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@types/node": "^26.1.2",