@zhin.js/core 1.8.0 → 1.10.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.
- package/lib/built/chat-role-reader.d.ts +145 -0
- package/lib/built/chat-role-reader.js +183 -0
- package/lib/built/roles.d.ts +55 -1
- package/lib/built/roles.js +84 -7
- package/lib/built/user-interaction.js +3 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/plugin-runtime/im/ambient-switch.d.ts +49 -0
- package/lib/plugin-runtime/im/ambient-switch.js +70 -0
- package/lib/plugin-runtime/im/command-feedback.js +22 -5
- package/lib/plugin-runtime/im/contracts.d.ts +15 -0
- package/lib/plugin-runtime/im/contracts.js +20 -1
- package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +3 -1
- package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
- package/lib/plugin-runtime/im/im-runtime.js +9 -0
- package/lib/plugin-runtime/im/inbound-outcome-ledger.d.ts +103 -0
- package/lib/plugin-runtime/im/inbound-outcome-ledger.js +311 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +3 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +138 -13
- package/lib/plugin-runtime/im/inbound-spine.d.ts +20 -3
- package/lib/plugin-runtime/im/inbound-spine.js +93 -6
- package/lib/plugin-runtime/im/index.d.ts +5 -1
- package/lib/plugin-runtime/im/index.js +3 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +45 -14
- package/lib/plugin-runtime/im/message-diagnostics.d.ts +16 -0
- package/lib/plugin-runtime/im/message-diagnostics.js +12 -0
- package/lib/plugin-runtime/im/message-events.js +27 -0
- package/lib/plugin-runtime/im/message-outcome.d.ts +97 -0
- package/lib/plugin-runtime/im/message-outcome.js +125 -0
- package/package.json +9 -9
|
@@ -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
|
+
}
|
package/lib/built/roles.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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:` 标签(任意位置、大小写不敏感,
|
package/lib/built/roles.js
CHANGED
|
@@ -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
|
-
/**
|
|
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.
|
|
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' &&
|
|
221
|
+
.filter(entry => entry.role === 'owner' && chain.includes(entry.key))
|
|
168
222
|
.sort((left, right) => chain.indexOf(right.key) - chain.indexOf(left.key));
|
|
169
|
-
|
|
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
|
-
|
|
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, ...(
|
|
321
|
+
return Object.freeze({ ...base, ...(principal ? { chatPrincipal: principal } : {}),
|
|
322
|
+
...(role ? { chatRole: role, chatRoleLevels: chatRoleLevelsOf(entries) } : {}) });
|
|
246
323
|
};
|
|
247
324
|
}
|
|
248
325
|
// ============================================================================
|
|
@@ -6,6 +6,9 @@ export function assertUserInteractionRequest(request) {
|
|
|
6
6
|
if (request.timeout !== undefined && (!Number.isFinite(request.timeout) || request.timeout <= 0)) {
|
|
7
7
|
throw new RangeError('User interaction timeout must be a positive finite number');
|
|
8
8
|
}
|
|
9
|
+
if (request.answeredBy !== undefined && request.answeredBy !== 'target' && request.answeredBy !== 'anyone') {
|
|
10
|
+
throw new TypeError("User interaction answeredBy must be 'target' or 'anyone'");
|
|
11
|
+
}
|
|
9
12
|
if (request.type === 'text' && !validRange(request.minLength, request.maxLength)) {
|
|
10
13
|
throw new RangeError('User interaction text length range is invalid');
|
|
11
14
|
}
|
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';
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ADR 0062 §23 / Q23: group interjection ("插话", ambient engagement) is a feature in the layered
|
|
3
|
+
* feature overrides (ADR 0050 / 0055). The global default stays `ai.trigger.ambient` in the
|
|
4
|
+
* configuration file; adapter / endpoint / conversation switches are stored in `feature_overrides`
|
|
5
|
+
* under the reserved feature id {@link AMBIENT_FEATURE_ID} (not a Plugin instance path, so it can
|
|
6
|
+
* never collide with one).
|
|
7
|
+
*
|
|
8
|
+
* Stored row shape: `enabled: false` switches interjection off at that level and locks the levels
|
|
9
|
+
* below (as for Plugins); `patch.engage === true` switches it on there (needed because the global
|
|
10
|
+
* default is off for conversations outside `ai.trigger.ambient.conversations`).
|
|
11
|
+
*/
|
|
12
|
+
import { type FeatureConfigLevel, type FeatureConversationOverride, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
13
|
+
/** Reserved feature id of group interjection in the feature override store. @public */
|
|
14
|
+
export declare const AMBIENT_FEATURE_ID = "@ambient";
|
|
15
|
+
/** Words that name group interjection in chat feature commands (`功能 关闭 插话`). @public */
|
|
16
|
+
export declare const AMBIENT_FEATURE_WORDS: ReadonlySet<string>;
|
|
17
|
+
/** Patch field marking an explicit "on" override. @public */
|
|
18
|
+
export declare const AMBIENT_ENGAGE_FIELD = "engage";
|
|
19
|
+
/** Effective interjection switch for one conversation. @public */
|
|
20
|
+
export interface AmbientSwitchResolution {
|
|
21
|
+
readonly enabled: boolean;
|
|
22
|
+
/** Level that decided: `global` is the configuration file default. */
|
|
23
|
+
readonly source: FeatureConfigLevel;
|
|
24
|
+
/** Set when an upper level switched it off (lower levels cannot turn it back on). */
|
|
25
|
+
readonly lockedBy?: Exclude<FeatureConfigLevel, 'global' | 'conversation'>;
|
|
26
|
+
}
|
|
27
|
+
type OverrideReader = {
|
|
28
|
+
get(plugin: string, key: string): FeatureConversationOverride | undefined;
|
|
29
|
+
};
|
|
30
|
+
/** Ancestor keys (adapter, endpoint, conversation) of a resolution key that exist. */
|
|
31
|
+
export declare function ambientScopeKeys(key: string): ReadonlyArray<readonly [Exclude<FeatureConfigLevel, 'global'>, string]>;
|
|
32
|
+
/** Resolves the switch from stored overrides at `key` on top of the file default `globalEnabled`. @public */
|
|
33
|
+
export declare function resolveAmbientSwitchAt(reader: OverrideReader | undefined, key: string | undefined, globalEnabled: boolean, level?: Exclude<FeatureConfigLevel, 'global'>): AmbientSwitchResolution;
|
|
34
|
+
/**
|
|
35
|
+
* Whether interjection is on for a message's conversation in this generation: the stored
|
|
36
|
+
* overrides on top of `globalEnabled` (the file allowlist `ai.trigger.ambient.conversations`).
|
|
37
|
+
* @public
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveAmbientSwitch(snapshot: Pick<RuntimeSnapshot, 'root' | 'resources' | 'projections' | 'tree'> | undefined, message: Readonly<{
|
|
40
|
+
conversation: Readonly<{
|
|
41
|
+
endpoint: Readonly<{
|
|
42
|
+
id: string;
|
|
43
|
+
}>;
|
|
44
|
+
kind: string;
|
|
45
|
+
id: string;
|
|
46
|
+
}>;
|
|
47
|
+
endpointId?: string;
|
|
48
|
+
}>, globalEnabled: boolean): AmbientSwitchResolution;
|
|
49
|
+
export {};
|