@zhin.js/core 1.1.57 → 1.1.59

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.
Files changed (89) hide show
  1. package/lib/built/user-interaction.d.ts +1 -1
  2. package/lib/feature/command.d.ts +2 -4
  3. package/lib/feature/command.js +1 -2
  4. package/lib/feature/middleware.d.ts +2 -2
  5. package/lib/feature/middleware.js +1 -1
  6. package/lib/index.d.ts +1 -1
  7. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  8. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  9. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  10. package/lib/plugin-runtime/im/contracts.js +6 -2
  11. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  12. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  13. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  14. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  15. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  16. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  17. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  18. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  19. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  20. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  21. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  22. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  23. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  24. package/lib/plugin-runtime/im/host/index.js +8 -0
  25. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  26. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  27. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  28. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  29. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  30. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  31. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  32. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  33. package/lib/plugin-runtime/im/inbound-dedup.d.ts +32 -0
  34. package/lib/plugin-runtime/im/inbound-dedup.js +138 -1
  35. package/lib/plugin-runtime/im/inbound-origin.d.ts +24 -2
  36. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  37. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  38. package/lib/plugin-runtime/im/inbound-runtime.js +92 -412
  39. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  40. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  41. package/lib/plugin-runtime/im/index.d.ts +5 -7
  42. package/lib/plugin-runtime/im/index.js +5 -6
  43. package/lib/plugin-runtime/im/interaction-runtime.d.ts +4 -7
  44. package/lib/plugin-runtime/im/interaction-runtime.js +5 -8
  45. package/lib/plugin-runtime/im/interactive-router.d.ts +31 -4
  46. package/lib/plugin-runtime/im/interactive-router.js +134 -2
  47. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  48. package/lib/plugin-runtime/im/message-dispatcher.js +1 -2
  49. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  50. package/lib/plugin-runtime/im/message-events.js +34 -0
  51. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +1 -2
  52. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +4 -8
  53. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  54. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  55. package/package.json +13 -14
  56. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  57. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  58. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  59. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  60. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  61. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  62. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  63. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  64. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  65. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  66. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  67. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  68. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -31
  69. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -135
  70. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  71. package/lib/plugin-runtime/im/locale.js +0 -12
  72. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  73. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  74. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  75. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  76. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  77. package/lib/plugin-runtime/im/message-bus.js +0 -40
  78. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  79. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  80. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  81. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  82. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  83. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  84. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  85. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  86. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  87. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  88. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  89. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -0,0 +1,153 @@
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
3
+ import { outboundHostToken, outboundRootHostToken, PluginOutboundHost, rootPluginId, } from '@zhin.js/plugin-runtime';
4
+ const logger = getLogger('OutboundHost');
5
+ export function createOutboundHost(im) {
6
+ return {
7
+ async sendTarget(target, content, requester, options) {
8
+ try {
9
+ const result = options
10
+ ? await im.endpoints.sendTarget(target, content, requester, options)
11
+ : await im.endpoints.sendTarget(target, content, requester);
12
+ return result.messageId || null;
13
+ }
14
+ catch (error) {
15
+ logger.debug(formatCompact({
16
+ op: 'outbound_send_failed',
17
+ adapter: target.endpoint.adapter,
18
+ endpointKey: target.endpoint.id,
19
+ error: error instanceof Error ? error.message : String(error),
20
+ }));
21
+ throw error;
22
+ }
23
+ },
24
+ captureOperation(input, requester) {
25
+ const captured = im.endpoints.captureOperation({ ...input, requester });
26
+ const control = captured.control;
27
+ return Object.freeze({
28
+ target: captured.target, signal: captured.signal,
29
+ send: async (content, options) => {
30
+ const receipt = await captured.send(content, options);
31
+ if (receipt.status !== 'sent') {
32
+ throw new EndpointDeliveryError(receipt.failure?.code ?? 'outbound_failed', receipt.failure?.message ?? 'Delivery was not confirmed.', receipt.failure?.deliveryUnknown ? 'unknown' : receipt.status === 'rejected' ? 'rejected' : 'not_sent');
33
+ }
34
+ return receipt.message?.id ?? null;
35
+ },
36
+ ...(control?.recall ? { recall: message => control.recall({ message }) } : {}),
37
+ ...(control?.edit ? { edit: (message, content) => control.edit({ message, content }) } : {}),
38
+ ...(control?.addReaction ? { addReaction: (message, emoji, hint) => control.addReaction({ message, emoji, hint }) } : {}),
39
+ ...(control?.removeReaction ? { removeReaction: (message, reactionId) => control.removeReaction({ message, reactionId }) } : {}),
40
+ ...(control?.typing ? { typing: (conversation, active) => control.typing({ conversation, active }) } : {}),
41
+ release: captured.release,
42
+ });
43
+ },
44
+ runWithView: (operation) => im.runWithSnapshotView(operation),
45
+ capabilities(input) {
46
+ const capabilities = im.endpoints.capabilities(input);
47
+ const operations = capabilities?.operations;
48
+ if (!operations)
49
+ return { operations: Object.freeze([]), ...(capabilities?.kinds ? { kinds: capabilities.kinds } : {}) };
50
+ return {
51
+ operations: Object.freeze(['recall', 'edit', 'reaction', 'typing']
52
+ .filter((operation) => operations[operation] === true)),
53
+ ...(capabilities?.kinds ? { kinds: capabilities.kinds } : {}),
54
+ };
55
+ },
56
+ async send(input) {
57
+ try {
58
+ const result = await im.endpoints.send({
59
+ adapter: input.adapter,
60
+ endpointKey: input.endpointKey,
61
+ conversation: input.conversation,
62
+ content: input.content,
63
+ ...(input.locale ? { locale: input.locale } : {}),
64
+ });
65
+ return result.messageId || null;
66
+ }
67
+ catch (error) {
68
+ logger.debug(formatCompact({
69
+ op: 'outbound_send_failed',
70
+ adapter: input.adapter,
71
+ endpointKey: input.endpointKey,
72
+ error: error instanceof Error ? error.message : String(error),
73
+ }));
74
+ // Business callers must distinguish failed delivery from a successful
75
+ // send without a platform message id. Optional activity feedback owns
76
+ // its best-effort handling at the call site.
77
+ throw error;
78
+ }
79
+ },
80
+ async addReaction(input) {
81
+ try {
82
+ return await im.endpoints.addReaction({
83
+ message: input.message,
84
+ emoji: input.emoji,
85
+ sceneType: input.sceneType,
86
+ channelId: input.channelId,
87
+ });
88
+ }
89
+ catch (error) {
90
+ logger.debug(formatCompact({
91
+ op: 'outbound_add_reaction_failed',
92
+ error: error instanceof Error ? error.message : String(error),
93
+ }));
94
+ return null;
95
+ }
96
+ },
97
+ async removeReaction(input) {
98
+ try {
99
+ await im.endpoints.removeReaction({
100
+ message: input.message,
101
+ reactionId: input.reactionId,
102
+ });
103
+ }
104
+ catch (error) {
105
+ logger.debug(formatCompact({
106
+ op: 'outbound_remove_reaction_failed',
107
+ error: error instanceof Error ? error.message : String(error),
108
+ }));
109
+ }
110
+ },
111
+ async recall(input) {
112
+ await im.endpoints.recall({
113
+ message: input.message,
114
+ });
115
+ },
116
+ async edit(input) {
117
+ try {
118
+ return await im.endpoints.edit({
119
+ message: input.message,
120
+ content: input.content,
121
+ });
122
+ }
123
+ catch (error) {
124
+ logger.debug(formatCompact({
125
+ op: 'outbound_edit_failed',
126
+ error: error instanceof Error ? error.message : String(error),
127
+ }));
128
+ return null;
129
+ }
130
+ },
131
+ async typing(input) {
132
+ try {
133
+ await im.endpoints.typing({
134
+ conversation: input.conversation,
135
+ active: input.active,
136
+ });
137
+ }
138
+ catch (error) {
139
+ logger.debug(formatCompact({
140
+ op: 'outbound_typing_failed',
141
+ error: error instanceof Error ? error.message : String(error),
142
+ }));
143
+ }
144
+ },
145
+ };
146
+ }
147
+ export function installOutboundHost(im) {
148
+ return ({ resources, admission }) => {
149
+ const host = createOutboundHost(im);
150
+ resources.provide(outboundRootHostToken, host);
151
+ resources.provide(outboundHostToken, new PluginOutboundHost(rootPluginId(), host, admission));
152
+ };
153
+ }
@@ -0,0 +1,33 @@
1
+ import { type AdapterIndex } from '@zhin.js/adapter';
2
+ import type { OperationSession } from '@zhin.js/feature-kit';
3
+ import type { ImRuntime } from '../im-runtime.js';
4
+ import type { ConversationRef } from '@zhin.js/im-contract';
5
+ import { type ConfigDocumentPort, type RootPluginConfigurationSelection, type RuntimeConfigDocument, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
6
+ export interface EndpointRoleResolver {
7
+ resolveOwner(pluginKey: string, endpointId: string): string | undefined;
8
+ resolveTrusted(pluginKey: string, endpointId: string): readonly string[];
9
+ }
10
+ export type ConfigurationChatAuthorizer = (session: OperationSession<string>, adapters: AdapterIndex) => boolean;
11
+ /** Startup role authority, matched against the actual operation's Adapter and account.
12
+ * C2 (Accept): in a private chat, the sender must be the effective `master` of *any*
13
+ * configured endpoint of the same Adapter that received the message — each endpoint's
14
+ * leaf `master`, else its inherited Plugin-level `master`. The identity therefore stays
15
+ * on the receiving Adapter/platform; masters of other Adapters (including another
16
+ * instance of the same Adapter package) never qualify. `ai.trigger.masters` has no
17
+ * platform dimension and is deliberately not consulted in v1.
18
+ * Direct declared owners are mapped with the canonical PluginId constructor. Nested
19
+ * owners never borrow their parent's role configuration or a legacy display alias.
20
+ */
21
+ export declare function createConfigurationChatAuthorizer(startup: RuntimeConfigDocument, endpointRoles: EndpointRoleResolver): ConfigurationChatAuthorizer;
22
+ /** Resolve account roles inside their declaring Plugin. Legacy aliases are accepted only when unique. */
23
+ export declare function createEndpointRoleResolver(config: RuntimeConfigDocument | ConfigDocumentPort): Promise<EndpointRoleResolver>;
24
+ /** Startup role consumers are process-owned. Keep their configuration honest
25
+ * until restart instead of claiming a new role map which they cannot consume.
26
+ */
27
+ export declare function createEndpointRoleConfigurationSelection(startup: RuntimeConfigDocument, resolver: EndpointRoleResolver): RootPluginConfigurationSelection;
28
+ /** Identity comes from the captured Adapter owner and child desired state, never user payload. */
29
+ export declare function resolveEndpointRoleTarget(conversation: ConversationRef, snapshot?: RuntimeSnapshot, trustedEndpointId?: string): Readonly<{
30
+ pluginKey: string;
31
+ endpointId: string;
32
+ }> | undefined;
33
+ export declare function createSenderEnricher(config: RuntimeConfigDocument | ConfigDocumentPort, endpointRoles: EndpointRoleResolver): Promise<NonNullable<ConstructorParameters<typeof ImRuntime>[0]>['enrichSender']>;
@@ -0,0 +1,215 @@
1
+ import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { childPluginId, expandEnvironmentValue, rootPluginId, readPluginConfigurationMap, } from '@zhin.js/plugin-runtime';
4
+ /** Startup role authority, matched against the actual operation's Adapter and account.
5
+ * C2 (Accept): in a private chat, the sender must be the effective `master` of *any*
6
+ * configured endpoint of the same Adapter that received the message — each endpoint's
7
+ * leaf `master`, else its inherited Plugin-level `master`. The identity therefore stays
8
+ * on the receiving Adapter/platform; masters of other Adapters (including another
9
+ * instance of the same Adapter package) never qualify. `ai.trigger.masters` has no
10
+ * platform dimension and is deliberately not consulted in v1.
11
+ * Direct declared owners are mapped with the canonical PluginId constructor. Nested
12
+ * owners never borrow their parent's role configuration or a legacy display alias.
13
+ */
14
+ export function createConfigurationChatAuthorizer(startup, endpointRoles) {
15
+ const owners = new Map(Object.keys(readPluginConfigurationMap(startup)).map(key => [childPluginId(rootPluginId(), key), key]));
16
+ return (session, adapters) => {
17
+ if (session.scene.kind !== 'private' || !session.sender?.id || !isAdapterIndex(adapters))
18
+ return false;
19
+ const id = session.scene.endpoint.id;
20
+ const adapter = adapters.adapterForEndpoint(id);
21
+ const child = adapter?.find(id);
22
+ if (!adapter || !child || session.adapter !== adapter || session.endpoint !== adapter.getEndpoint(child.desired.instanceId))
23
+ return false;
24
+ if (!child.started || session.signal.aborted)
25
+ return false;
26
+ const key = owners.get(adapter.descriptor.owner);
27
+ if (key === undefined)
28
+ return false;
29
+ const sender = session.sender.id;
30
+ // Receiving endpoint first, then every other endpoint configured on this same Adapter
31
+ // (removed/retiring entries never qualify).
32
+ return endpointRoles.resolveOwner(key, child.desired.endpointId) === sender
33
+ || adapter.list().some(entry => !entry.removed && !entry.retiring && endpointRoles.resolveOwner(key, entry.endpointId) === sender);
34
+ };
35
+ }
36
+ /** Resolve account roles inside their declaring Plugin. Legacy aliases are accepted only when unique. */
37
+ export async function createEndpointRoleResolver(config) {
38
+ const document = await readConfigDocumentValue(config);
39
+ if (!document || typeof document !== 'object')
40
+ return { resolveOwner: () => undefined, resolveTrusted: () => [] };
41
+ const plugins = expandEnvironmentValue(readPluginConfigurationMap(document), key => process.env[key]);
42
+ return compileEndpointRoles(plugins).resolver;
43
+ }
44
+ function compileEndpointRoles(plugins) {
45
+ const scopes = new Map();
46
+ const aliases = new Map();
47
+ const lookupKeys = new Map();
48
+ const contributors = new Map();
49
+ const endpointKeys = new Set();
50
+ const contribute = (key, pluginKey) => {
51
+ const owners = contributors.get(key) ?? new Set();
52
+ owners.add(pluginKey);
53
+ contributors.set(key, owners);
54
+ };
55
+ const alias = (key, scope, pluginKey) => {
56
+ if (!key)
57
+ return;
58
+ lookupKeys.get(pluginKey).add(key);
59
+ contribute(key, pluginKey);
60
+ if (!aliases.has(key))
61
+ aliases.set(key, scope);
62
+ else if (aliases.get(key) !== scope)
63
+ aliases.set(key, undefined);
64
+ };
65
+ for (const [pluginKey, value] of Object.entries(plugins)) {
66
+ if (!isRecord(value))
67
+ continue;
68
+ const scope = { base: roles(value), endpoints: new Map() };
69
+ scopes.set(pluginKey, scope);
70
+ lookupKeys.set(pluginKey, new Set([pluginKey]));
71
+ contribute(pluginKey, pluginKey);
72
+ const entries = Array.isArray(value.endpoints) ? value.endpoints.filter(isRecord) : [];
73
+ for (const entry of entries) {
74
+ const leaf = roles(entry);
75
+ for (const key of new Set([identity(entry.id), identity(entry.name)])) {
76
+ if (!key)
77
+ continue;
78
+ endpointKeys.add(key);
79
+ if (!scope.endpoints.has(key))
80
+ scope.endpoints.set(key, leaf);
81
+ else
82
+ scope.endpoints.set(key, undefined);
83
+ }
84
+ }
85
+ // Preserve old single-account aliases; never merge aliases belonging to different Plugins.
86
+ if (entries.length <= 1) {
87
+ alias(identity(value.name), scope, pluginKey);
88
+ if (entries.length === 1) {
89
+ alias(identity(entries[0].id), scope, pluginKey);
90
+ alias(identity(entries[0].name), scope, pluginKey);
91
+ }
92
+ }
93
+ }
94
+ const lookup = (pluginKey, endpointId) => {
95
+ const scope = scopes.get(pluginKey) ?? aliases.get(pluginKey);
96
+ if (!scope)
97
+ return undefined;
98
+ if (scope.endpoints.has(endpointId) && !scope.endpoints.get(endpointId))
99
+ return undefined;
100
+ return { base: scope.base, leaf: scope.endpoints.get(endpointId) };
101
+ };
102
+ const resolver = {
103
+ resolveOwner(pluginKey, endpointId) {
104
+ const found = lookup(pluginKey, endpointId);
105
+ return found?.leaf?.master ?? found?.base.master;
106
+ },
107
+ resolveTrusted(pluginKey, endpointId) {
108
+ const found = lookup(pluginKey, endpointId);
109
+ return found ? [...new Set([...found.base.trusted, ...(found.leaf?.trusted ?? [])])] : [];
110
+ },
111
+ };
112
+ return { resolver, lookupKeys, contributors, endpointKeys };
113
+ }
114
+ /** Startup role consumers are process-owned. Keep their configuration honest
115
+ * until restart instead of claiming a new role map which they cannot consume.
116
+ */
117
+ export function createEndpointRoleConfigurationSelection(startup, resolver) {
118
+ const initial = compileEndpointRoles(readPluginConfigurationMap(startup));
119
+ return { select(input) {
120
+ const previous = compileEndpointRoles(input.expand(readPluginConfigurationMap(input.previous)));
121
+ const next = compileEndpointRoles(input.expand(readPluginConfigurationMap(input.next)));
122
+ const endpoints = new Set([...initial.endpointKeys, ...previous.endpointKeys, ...next.endpointKeys]);
123
+ // Endpoint identities not declared in YAML still inherit base roles. One
124
+ // absent identity proves that fallback without depending on array position.
125
+ let fallback = '__zhin_role_fallback__';
126
+ while (endpoints.has(fallback))
127
+ fallback += '_';
128
+ endpoints.add(fallback);
129
+ const disabled = new Set(Array.isArray(input.next.disable_plugins) ? input.next.disable_plugins : []);
130
+ const selected = new Set();
131
+ for (const [owner, keys] of next.lookupKeys) {
132
+ // Disabled accounts still retain their old role configuration so a later
133
+ // enable cannot adopt an unconsumed role change. Their legacy aliases do
134
+ // not need to keep removed accounts alive while there is no consumer.
135
+ for (const key of disabled.has(owner) ? [owner] : keys) {
136
+ const differs = [...endpoints].some(endpoint => !isDeepStrictEqual(roleMembership(resolver, key, endpoint), roleMembership(next.resolver, key, endpoint)));
137
+ if (!differs)
138
+ continue;
139
+ selected.add(owner);
140
+ // A legacy alias can become unique when a different owner disappears.
141
+ // Retain all contributing declarations, including a removed owner, so
142
+ // the effective document describes the process's actual ambiguity.
143
+ for (const state of [initial, previous, next])
144
+ for (const contributor of state.contributors.get(key) ?? [])
145
+ selected.add(contributor);
146
+ }
147
+ }
148
+ return [...selected].map(instanceKey => ({ instanceKey, reasonCode: 'endpoint-roles-process-owned' }));
149
+ } };
150
+ }
151
+ function roleMembership(resolver, owner, endpoint) {
152
+ return { master: resolver.resolveOwner(owner, endpoint), trusted: [...new Set(resolver.resolveTrusted(owner, endpoint))].sort() };
153
+ }
154
+ /** Identity comes from the captured Adapter owner and child desired state, never user payload. */
155
+ export function resolveEndpointRoleTarget(conversation, snapshot, trustedEndpointId) {
156
+ const adapters = snapshot?.projections.get(adapterFeatureId);
157
+ if (isAdapterIndex(adapters)) {
158
+ const adapter = adapters.adapterForEndpoint(conversation.endpoint.id);
159
+ const child = adapter?.find(conversation.endpoint.id);
160
+ const owner = adapter && snapshot?.tree.get(adapter.descriptor.owner);
161
+ if (!owner || !child)
162
+ return undefined;
163
+ return { pluginKey: owner.instanceKey, endpointId: child.desired.endpointId };
164
+ }
165
+ // Legacy synthetic callers may provide the framework's explicit endpoint identity.
166
+ // A real captured projection which cannot resolve the account must never take this path.
167
+ if (trustedEndpointId && conversation.endpoint.adapter)
168
+ return { pluginKey: conversation.endpoint.adapter, endpointId: trustedEndpointId };
169
+ return undefined;
170
+ }
171
+ export async function createSenderEnricher(config, endpointRoles) {
172
+ const document = await readConfigDocumentValue(config);
173
+ const readTriggerLists = (doc) => {
174
+ const ai = isRecord(doc) && isRecord(doc.ai) ? doc.ai : undefined;
175
+ const trigger = ai && isRecord(ai.trigger) ? ai.trigger : undefined;
176
+ return {
177
+ masters: normalizeTrustedIdList(trigger?.masters),
178
+ trusted: normalizeTrustedIdList(trigger?.trusted),
179
+ };
180
+ };
181
+ const initialLists = readTriggerLists(document);
182
+ return (sender, conversation, snapshot) => {
183
+ if (!sender?.id)
184
+ return sender;
185
+ const rootDoc = snapshot?.config.get(rootPluginId());
186
+ const activeLists = isRecord(rootDoc) && 'ai' in rootDoc ? readTriggerLists(rootDoc) : initialLists;
187
+ const target = resolveEndpointRoleTarget(conversation, snapshot);
188
+ const master = target && endpointRoles.resolveOwner(target.pluginKey, target.endpointId);
189
+ const trusted = target ? endpointRoles.resolveTrusted(target.pluginKey, target.endpointId) : [];
190
+ const isMaster = activeLists.masters.includes(sender.id) || sender.id === master;
191
+ const isTrusted = !isMaster && (activeLists.trusted.includes(sender.id) || trusted.includes(sender.id));
192
+ if (!isMaster && !isTrusted)
193
+ return sender;
194
+ const role = isMaster ? 'master' : 'trusted';
195
+ const existing = sender.roles ?? [];
196
+ return existing.includes(role) ? sender : { ...sender, roles: [role, ...existing] };
197
+ };
198
+ }
199
+ function isRecord(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
200
+ function identity(value) { return value != null && String(value).trim() ? String(value) : undefined; }
201
+ function roles(value) { return { master: identity(value.master), trusted: normalizeTrustedIdList(value.trusted) }; }
202
+ function normalizeTrustedIdList(input) {
203
+ if (Array.isArray(input))
204
+ return input.map(value => String(value).trim()).filter(Boolean);
205
+ return typeof input === 'string' ? input.split(/[\s,]+/).map(value => value.trim()).filter(Boolean) : [];
206
+ }
207
+ async function readConfigDocumentValue(config) {
208
+ if (!config || typeof config !== 'object')
209
+ return config;
210
+ const candidate = config;
211
+ if (typeof candidate.read !== 'function')
212
+ return config;
213
+ const snapshot = await candidate.read();
214
+ return snapshot && typeof snapshot === 'object' && 'document' in snapshot ? snapshot.document : snapshot;
215
+ }
@@ -1,17 +1,21 @@
1
1
  import { Scope, generationAdmissionBinder, type GenerationAdmissionGate, type RuntimeSnapshot, type SnapshotLease, type SnapshotReader } from '@zhin.js/plugin-runtime';
2
2
  import { PermissionHost } from '@zhin.js/permission';
3
- import { MessageBus } from './message-bus.js';
4
3
  import { type EndpointContentResolveContext, type EndpointEventGateway, type PeerRegistry } from '@zhin.js/adapter';
5
4
  import { type ConversationEventStore, type ConversationEventReader, type ConversationContextBlock, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
6
5
  import { Message, type IncomingMessage, type OutboundMessageService, type MessageSenderRef, type SendRequest } from './contracts.js';
7
6
  import { LoginAssist } from '../../built/login-assist.js';
8
- import type { UserInteraction } from '@zhin.js/interaction';
7
+ import type { UserInteraction } from '@zhin.js/im-contract';
9
8
  import type { OutboundRenderer } from './outbound-renderer.js';
10
9
  import { type PendingUserInteraction } from './interaction-runtime.js';
11
10
  import { EndpointRuntime } from './endpoint-runtime.js';
12
- import { type RuntimeMessageEventSource, type RuntimeSceneEventSource } from './message-events.js';
11
+ import { MessageBus, type RuntimeMessageEventSource, type RuntimeSceneEventSource } from './message-events.js';
13
12
  import { InboundDeduper } from './inbound-dedup.js';
14
13
  import { type RuntimeMessageDiagnosticsReader } from './message-diagnostics.js';
14
+ /**
15
+ * Plugin Runtime login-assist port(与出站消息服务并列)。
16
+ * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
17
+ */
18
+ export declare const loginAssistToken: import("@zhin.js/plugin-runtime").Token<LoginAssist>;
15
19
  /** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
16
20
  export declare const outboundMessageToken: import("@zhin.js/plugin-runtime").Token<OutboundMessageService>;
17
21
  export interface ImRuntimeOptions {
@@ -1,23 +1,25 @@
1
- import { imOperationResourcesToken } from './operation-resources.js';
2
1
  import { OwnerOperation, createToken, readLeasedRootResource, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
3
2
  import { AsyncLocalStorage } from 'node:async_hooks';
4
3
  import { PermissionHost, permissionHostToken } from '@zhin.js/permission';
5
4
  import { CommandExecutionBudget, commandExecutionAdmissionToken } from '@zhin.js/command/internal/execution';
6
- import { MessageBus, messageBusToken } from './message-bus.js';
7
5
  import { endpointEventGatewayToken, getProcessPeerRegistry, } from '@zhin.js/adapter';
8
- import { loginAssistToken } from './login-assist-host.js';
6
+ import { imOperationResourcesToken, } from './contracts.js';
9
7
  import { LoginAssist } from '../../built/login-assist.js';
10
8
  import { RuntimeInteractionCoordinator } from './interaction-runtime.js';
11
9
  import { ConversationRuntime } from './conversation-runtime.js';
12
10
  import { EndpointRuntime, requireAdapters, } from './endpoint-runtime.js';
13
- import { RuntimeMessageEventStream, RuntimeSceneEventStream, } from './message-events.js';
11
+ import { MessageBus, messageBusToken, RuntimeMessageEventStream, RuntimeSceneEventStream, } from './message-events.js';
14
12
  import { OutboundDeliveryRuntime, failedDeliveryReceipt, } from './outbound-delivery-runtime.js';
15
13
  import { InboundRuntime } from './inbound-runtime.js';
16
- import { messageLocale } from './locale.js';
14
+ import { messageLocale } from './inbound-spine.js';
17
15
  import { InboundDeduper } from './inbound-dedup.js';
18
- import { OutboundLedger, ledgerScopeOf } from './outbound-ledger.js';
19
- import { createInboundOriginClassifier } from './inbound-origin.js';
16
+ import { createInboundOriginClassifier, OutboundLedger, ledgerScopeOf } from './inbound-origin.js';
20
17
  import { RuntimeMessageDiagnostics } from './message-diagnostics.js';
18
+ /**
19
+ * Plugin Runtime login-assist port(与出站消息服务并列)。
20
+ * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
21
+ */
22
+ export const loginAssistToken = createToken('zhin.im.login-assist');
21
23
  /** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
22
24
  export const outboundMessageToken = createToken('zhin.im.outbound-message');
23
25
  export class ImRuntime {
@@ -1,4 +1,10 @@
1
+ import type { PeerRegistry } from '@zhin.js/adapter';
1
2
  import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
+ import type { IncomingMessage, MessageSenderRef } from './contracts.js';
5
+ import { requireAdapters } from './endpoint-runtime.js';
6
+ import { type RoomInboundRouteInput, type RoomMembershipPort } from './inbound-origin.js';
7
+ import type { InboundInteractionPort } from './inbound-spine.js';
2
8
  export { roomMembershipToken, type ResolvedRoomInfo, type RoomArbitrationInput, type RoomClaimInput, type RoomInboundRouteInput, type RoomMembershipPort, type RoomReadinessResult, type RoomRouteDecision, } from './inbound-origin.js';
3
9
  export type InboundClaim = 'first' | 'same_endpoint' | 'duplicate' | 'unkeyed';
4
10
  /** Room Router decision as seen by the deduper (the Endpoint ids only). */
@@ -50,3 +56,29 @@ export declare class InboundDeduper {
50
56
  */
51
57
  arbitrate(conversation: ConversationRef, senderId: string, messageId: unknown, compute: () => InboundArbitrationDecision | undefined): InboundArbitration;
52
58
  }
59
+ /** Facts required to route this message within its captured account directory. */
60
+ export interface InboundRoomRouteRequest {
61
+ readonly conversation: IncomingMessage['conversation'];
62
+ readonly senderId: string;
63
+ readonly input: IncomingMessage;
64
+ readonly adapters: ReturnType<typeof requireAdapters>;
65
+ readonly generation: number;
66
+ readonly interactions: InboundInteractionPort;
67
+ readonly registry?: Pick<PeerRegistry, 'isReady' | 'selfOf'>;
68
+ readonly inboundClaimPending?: (conversation: IncomingMessage['conversation'], senderId: string) => boolean;
69
+ readonly resolveReplyTarget?: (conversation: IncomingMessage['conversation'], messageId: string) => string | undefined;
70
+ }
71
+ export declare function buildRoomInboundRouteInput({ conversation, senderId, input, adapters, generation, interactions, registry, inboundClaimPending, resolveReplyTarget, }: InboundRoomRouteRequest): RoomInboundRouteInput;
72
+ export declare function arbitrateRoomInboundDeduplication(input: {
73
+ readonly origin: string | undefined;
74
+ readonly deduper?: Pick<InboundDeduper, 'claim'> & Partial<Pick<InboundDeduper, 'arbitrate'>>;
75
+ readonly roomMembership: RoomMembershipPort | undefined;
76
+ readonly conversation: IncomingMessage['conversation'];
77
+ readonly enrichedSender: MessageSenderRef | undefined;
78
+ readonly incoming: IncomingMessage;
79
+ readonly routeRequest: InboundRoomRouteRequest;
80
+ }): Promise<{
81
+ readonly recordOnly?: 'duplicate' | 'dedup_error';
82
+ readonly routedTarget: boolean;
83
+ }>;
84
+ export declare function resolveRoomMembership(snapshot: RuntimeSnapshot): RoomMembershipPort | undefined;
@@ -1,5 +1,10 @@
1
- import { ledgerScopeOf } from './outbound-ledger.js';
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { readMentionSegmentTarget } from '../../built/segment-contract/mention.js';
3
+ import { ledgerScopeOf, roomMembershipToken, } from './inbound-origin.js';
4
+ import { actionPayloadFromSegments } from './interactive-router.js';
5
+ import { formatConversationLog } from './message-events.js';
2
6
  export { roomMembershipToken, } from './inbound-origin.js';
7
+ const logger = getLogger('im.inbound');
3
8
  /**
4
9
  * @internal 入站去重:同一条人类群消息会到达 N 个成员 Endpoint,
5
10
  * 按 平台 + 会话 + 发送者 + 平台消息 id 只放行第一个 Endpoint,其余仅记录。
@@ -183,3 +188,135 @@ export class InboundDeduper {
183
188
  }
184
189
  }
185
190
  }
191
+ export function buildRoomInboundRouteInput({ conversation, senderId, input, adapters, generation, interactions, registry, inboundClaimPending, resolveReplyTarget, }) {
192
+ const mentionTargets = (input.segments ?? [])
193
+ .map((segment) => readMentionSegmentTarget(segment))
194
+ .filter((target) => target !== '' && target !== 'all');
195
+ const replyToId = input.replyTo?.id;
196
+ const replyToEndpointId = replyToId !== undefined && resolveReplyTarget
197
+ ? resolveReplyTarget(conversation, replyToId)
198
+ : undefined;
199
+ return {
200
+ conversation,
201
+ senderId,
202
+ content: input.content,
203
+ mentionTargets,
204
+ ...(replyToEndpointId !== undefined ? { replyToEndpointId } : {}),
205
+ pending: (endpointId) => {
206
+ try {
207
+ const adapter = adapters.clientAdapter(endpointId);
208
+ const probe = Object.freeze({ ...conversation, endpoint: Object.freeze({ id: endpointId, adapter }) });
209
+ return interactions.hasPendingAnswer?.(probe, senderId, generation, { content: input.content, segments: input.segments }) === true || inboundClaimPending?.(probe, senderId) === true;
210
+ }
211
+ catch {
212
+ return false;
213
+ }
214
+ },
215
+ accountOf: (endpointId) => registry?.selfOf(endpointId),
216
+ isAvailable: (endpointId) => registry?.isReady(endpointId) === true,
217
+ };
218
+ }
219
+ export async function arbitrateRoomInboundDeduplication(input) {
220
+ const { origin, deduper, roomMembership, conversation, enrichedSender, incoming, routeRequest } = input;
221
+ let recordOnly;
222
+ let routedTarget = false;
223
+ let pendingSettle;
224
+ const platformCallback = actionPayloadFromSegments(incoming.segments) !== undefined;
225
+ if ((origin === 'human' || origin === undefined) && deduper && !platformCallback
226
+ && (conversation.kind === 'group' || conversation.kind === 'channel')) {
227
+ try {
228
+ if (roomMembership?.hasRoom?.(conversation) === true) {
229
+ const senderId = String(enrichedSender?.id ?? '');
230
+ if (typeof roomMembership.route === 'function' && typeof deduper.arbitrate === 'function') {
231
+ const route = roomMembership.route.bind(roomMembership);
232
+ const routeInput = buildRoomInboundRouteInput(routeRequest);
233
+ const verdict = deduper.arbitrate(conversation, senderId, incoming.message?.id, () => {
234
+ try {
235
+ const decision = route(routeInput);
236
+ return decision
237
+ ? { target: decision.endpointId, fallbacks: decision.fallbackEndpointIds ?? [] }
238
+ : undefined;
239
+ }
240
+ catch (error) {
241
+ logger.warn(formatCompact({
242
+ op: 'room_route_error',
243
+ conv: formatConversationLog(conversation),
244
+ error: error instanceof Error ? error.message : String(error),
245
+ }));
246
+ return undefined;
247
+ }
248
+ });
249
+ switch (verdict.kind) {
250
+ case 'handle':
251
+ routedTarget = verdict.routed;
252
+ break;
253
+ case 'duplicate':
254
+ recordOnly = 'duplicate';
255
+ logger.debug(formatCompact({
256
+ op: 'room_non_target_copy',
257
+ conv: formatConversationLog(conversation),
258
+ }));
259
+ break;
260
+ case 'wait':
261
+ pendingSettle = verdict;
262
+ break;
263
+ case 'unkeyed':
264
+ break;
265
+ }
266
+ }
267
+ else {
268
+ const claim = deduper.claim(conversation, senderId, incoming.message?.id);
269
+ if (claim === 'duplicate')
270
+ recordOnly = 'duplicate';
271
+ }
272
+ }
273
+ }
274
+ catch (error) {
275
+ logger.warn(formatCompact({
276
+ op: 'inbound_dedup_error',
277
+ conv: formatConversationLog(conversation),
278
+ error: error instanceof Error ? error.message : String(error),
279
+ }));
280
+ recordOnly = 'dedup_error';
281
+ }
282
+ }
283
+ if (pendingSettle) {
284
+ const outcome = await pendingSettle.settle();
285
+ if (outcome === 'handle') {
286
+ routedTarget = true;
287
+ if (!pendingSettle.listed) {
288
+ logger.warn(formatCompact({
289
+ op: 'room_unlisted_member_takeover',
290
+ conv: formatConversationLog(conversation),
291
+ target: pendingSettle.target,
292
+ takeover: conversation.endpoint.id,
293
+ }));
294
+ }
295
+ logger.debug(formatCompact({
296
+ op: 'room_target_missing_takeover',
297
+ conv: formatConversationLog(conversation),
298
+ target: pendingSettle.target,
299
+ takeover: conversation.endpoint.id,
300
+ }));
301
+ }
302
+ else {
303
+ recordOnly = 'duplicate';
304
+ }
305
+ }
306
+ return { recordOnly, routedTarget };
307
+ }
308
+ export function resolveRoomMembership(snapshot) {
309
+ try {
310
+ const candidate = snapshot.resources.get(snapshot.root)?.get(roomMembershipToken.id);
311
+ return candidate
312
+ && typeof candidate === 'object'
313
+ && (typeof candidate.isMember === 'function'
314
+ || typeof candidate.resolveRoom === 'function'
315
+ || typeof candidate.isRoomReady === 'function')
316
+ ? candidate
317
+ : undefined;
318
+ }
319
+ catch {
320
+ return undefined;
321
+ }
322
+ }