@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
@@ -1,5 +1,5 @@
1
1
  import type { Locale } from '@zhin.js/plugin-runtime';
2
- import type { UserInteractionContent, UserInteractionRequest } from '@zhin.js/interaction';
2
+ import type { UserInteractionContent, UserInteractionRequest } from '@zhin.js/im-contract';
3
3
  import type { SendContent } from '../plugin-runtime/im/contracts.js';
4
4
  import type { ButtonStyle } from './interactive-segments/types.js';
5
5
  export interface UserInteractionAction {
@@ -1,6 +1,4 @@
1
1
  /** Authoring API for Command Feature — implementation in `@zhin.js/command`. */
2
2
  export * from '@zhin.js/command';
3
- export { commandFeedbackToken } from '../plugin-runtime/im/command-feedback.js';
4
- export type { CommandFeedback, CommandFeedbackContext, CommandFeedbackRenderer } from '../plugin-runtime/im/command-feedback.js';
5
- export { commandMenuPresentationToken } from '../plugin-runtime/im/command-menu-presentation.js';
6
- export type { CommandMenuPresentationInput, CommandMenuPresenter } from '../plugin-runtime/im/command-menu-presentation.js';
3
+ export { commandFeedbackToken, commandMenuPresentationToken } from '../plugin-runtime/im/command-feedback.js';
4
+ export type { CommandFeedback, CommandFeedbackContext, CommandFeedbackRenderer, CommandMenuPresentationInput, CommandMenuPresenter } from '../plugin-runtime/im/command-feedback.js';
@@ -1,4 +1,3 @@
1
1
  /** Authoring API for Command Feature — implementation in `@zhin.js/command`. */
2
2
  export * from '@zhin.js/command';
3
- export { commandFeedbackToken } from '../plugin-runtime/im/command-feedback.js';
4
- export { commandMenuPresentationToken } from '../plugin-runtime/im/command-menu-presentation.js';
3
+ export { commandFeedbackToken, commandMenuPresentationToken } from '../plugin-runtime/im/command-feedback.js';
@@ -18,5 +18,5 @@ export declare function defineMiddleware<TInput = Message, TConfig = unknown>(de
18
18
  }>): Readonly<Extract<FeatureMiddlewareDefinition<TInput, TConfig>, {
19
19
  readonly target: 'inbound';
20
20
  }>>;
21
- export { outboundPresentationToken } from '../plugin-runtime/im/outbound-presentation.js';
22
- export type { OutboundPresentation, OutboundPresentationContext, OutboundPresentationMode, OutboundPresentationPreferences, } from '../plugin-runtime/im/outbound-presentation.js';
21
+ export { outboundPresentationToken } from '../plugin-runtime/im/outbound-renderer.js';
22
+ export type { OutboundPresentation, OutboundPresentationContext, OutboundPresentationMode, OutboundPresentationPreferences, } from '../plugin-runtime/im/outbound-renderer.js';
@@ -4,4 +4,4 @@ export function defineMiddleware(definition) {
4
4
  const define = defineFeatureMiddleware;
5
5
  return define(definition);
6
6
  }
7
- export { outboundPresentationToken } from '../plugin-runtime/im/outbound-presentation.js';
7
+ export { outboundPresentationToken } from '../plugin-runtime/im/outbound-renderer.js';
package/lib/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export * from './notice.js';
11
11
  export * from './request.js';
12
12
  export * from './system-event.js';
13
13
  export * from './side-event/index.js';
14
- export type * from '@zhin.js/interaction';
14
+ export type * from '@zhin.js/im-contract/interaction';
15
15
  export * from './types.js';
16
16
  export * from './utils.js';
17
17
  export * from './errors.js';
@@ -1,4 +1,4 @@
1
- import type { CommandDispatchResult, CommandExecutionLimit, CommandValidationIssue } from '@zhin.js/command';
1
+ import type { CommandDispatchResult, CommandExecutionLimit, CommandIndex, CommandMenuPage, CommandValidationIssue } from '@zhin.js/command';
2
2
  import type { ConversationRef } from '@zhin.js/im-contract';
3
3
  import { type Locale, type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
4
  import type { Message, MessageSenderRef, SendContent } from './contracts.js';
@@ -35,4 +35,23 @@ export declare function renderCommandFeedback(result: CommandDispatchResult, mes
35
35
  readonly content: SendContent;
36
36
  readonly owner?: PluginId;
37
37
  } | undefined>;
38
+ export interface CommandMenuPresentationInput {
39
+ readonly page: CommandMenuPage;
40
+ readonly conversation: ConversationRef;
41
+ readonly generation: number;
42
+ }
43
+ /** Root-selected menu content. `undefined` retains the built-in presentation. */
44
+ export type CommandMenuPresenter = (input: CommandMenuPresentationInput) => SendContent | undefined | Promise<SendContent | undefined>;
45
+ export declare const commandMenuPresentationToken: import("@zhin.js/plugin-runtime").Token<CommandMenuPresenter>;
46
+ /** The current Root owns both the selected presenter and the resulting content. */
47
+ export declare function presentCommandMenu(page: CommandMenuPage, fallback: SendContent, snapshot: RuntimeSnapshot, conversation: ConversationRef): Promise<SendContent>;
48
+ /** Rendering dependencies for one menu response; callbacks retain the same generation. */
49
+ export interface CommandMenuReplyContext {
50
+ readonly commands: CommandIndex;
51
+ readonly snapshot: RuntimeSnapshot;
52
+ readonly conversation: ConversationRef;
53
+ readonly prefix: string;
54
+ }
55
+ /** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
56
+ export declare function commandMenuReply(result: CommandDispatchResult, { commands, snapshot, conversation, prefix }: CommandMenuReplyContext): Promise<SendContent>;
38
57
  export {};
@@ -1,5 +1,8 @@
1
+ import { readOperationInputResources } from '@zhin.js/feature-kit';
2
+ import { Fragment, jsx } from '@zhin.js/jsx';
1
3
  import { formatCompact, getLogger } from '@zhin.js/logger';
2
4
  import { createToken, createMessages, resolveLocale } from '@zhin.js/plugin-runtime';
5
+ import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
3
6
  /** Explicitly provide this resource in Root setup; descendant bindings are not selected. */
4
7
  export const commandFeedbackToken = createToken('zhin.im.command-feedback');
5
8
  const logger = getLogger('command');
@@ -71,3 +74,63 @@ export async function renderCommandFeedback(result, message, snapshot) {
71
74
  }
72
75
  return { content: defaultFeedback(feedback, resolveLocale(message.locale)), owner: result.owner };
73
76
  }
77
+ export const commandMenuPresentationToken = createToken('zhin.command-menu-presentation', 'Root-selected command menu presentation; framework pagination remains unchanged');
78
+ /** The current Root owns both the selected presenter and the resulting content. */
79
+ export async function presentCommandMenu(page, fallback, snapshot, conversation) {
80
+ const presenter = snapshot.resources.get(snapshot.root)?.get(commandMenuPresentationToken.id);
81
+ if (!presenter)
82
+ return fallback;
83
+ try {
84
+ const view = Object.freeze({
85
+ endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
86
+ kind: conversation.kind, id: conversation.id,
87
+ ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
88
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
89
+ });
90
+ const content = await presenter(Object.freeze({ page, conversation: view, generation: snapshot.generation }));
91
+ return content === undefined ? fallback : content;
92
+ }
93
+ catch {
94
+ // A presentation failure must not expose content, re-run commands or cause a second send.
95
+ logger.warn(formatCompact({ op: 'command_menu_presentation', status: 'fallback', reason: 'presenter_failed', generation: snapshot.generation }));
96
+ return fallback;
97
+ }
98
+ }
99
+ const menuMessages = createMessages({
100
+ page: { 'zh-CN': '**指令菜单** · 第 {page}/{pages} 页', en: '**Command menu** · Page {page}/{pages}' },
101
+ previous: { 'zh-CN': '上一页', en: 'Previous' },
102
+ next: { 'zh-CN': '下一页', en: 'Next' },
103
+ });
104
+ /** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
105
+ export async function commandMenuReply(result, { commands, snapshot, conversation, prefix }) {
106
+ // Only validated menus carry this metadata; other command return values stay opaque.
107
+ const menu = result.menu;
108
+ if (!menu)
109
+ return result.value;
110
+ const content = await presentCommandMenu(menu, result.value, snapshot, conversation);
111
+ if (menu.pages <= 1)
112
+ return content;
113
+ const endpoint = conversation.endpoint.id;
114
+ const supported = resolveOutboundSupportedSegments(endpoint, snapshot);
115
+ if (resolveOutboundMarkdownPolicy(endpoint, snapshot) !== 'native'
116
+ || resolveOutboundInteractivePolicy(endpoint, snapshot) !== 'native'
117
+ || supported && (!supported.includes('markdown') || !supported.includes('keyboard')))
118
+ return content;
119
+ const button = (page, label, disabled) => jsx('button', {
120
+ label, disabled, style: disabled ? 'secondary' : 'primary',
121
+ onClick: async (message) => {
122
+ if (disabled)
123
+ return [];
124
+ const input = `${menu.keyword}${menu.pluginKey ? ` ${menu.pluginKey}` : ''} --page ${page}`;
125
+ const next = await commands.dispatch({ input: input, source: message, commandPrefix: prefix, snapshot: snapshot, locale: menu.locale, operation: readOperationInputResources(message, snapshot) });
126
+ return commandMenuReply(next, { commands: commands, snapshot: snapshot, conversation: message.conversation, prefix: prefix });
127
+ },
128
+ });
129
+ return [content,
130
+ { type: 'markdown', data: { content: menuMessages(menu.locale, 'page', { page: menu.page, pages: menu.pages }) } },
131
+ jsx(Fragment, { children: [
132
+ button(menu.page - 1, menuMessages(menu.locale, 'previous'), menu.page === 1),
133
+ button(menu.page + 1, menuMessages(menu.locale, 'next'), menu.page === menu.pages),
134
+ ] }),
135
+ ];
136
+ }
@@ -1,14 +1,69 @@
1
- import type { CapturedEndpointOperation } from './captured-endpoint-operation.js';
1
+ import type { EndpointChildLease, EndpointControl, EndpointManagement } from '@zhin.js/adapter';
2
2
  import type { JSXElement } from '@zhin.js/jsx';
3
3
  import { type CommandMenuPage } from '@zhin.js/command';
4
- import { type PluginId, type RuntimeSnapshot, type Locale } from '@zhin.js/plugin-runtime';
4
+ import { type PluginId, type RuntimeSnapshot, type SnapshotLease, type SnapshotReader, type Locale } from '@zhin.js/plugin-runtime';
5
5
  import { operationInputBinding, operationInputSignal, operationInputResources, operationSession, type OperationSession, type OperationResourceView, type CapabilityOperationFactory } from '@zhin.js/feature-kit';
6
- import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
6
+ import type { ConversationRef, DeliveryReceipt, MessageRef, SelfProfilePort } from '@zhin.js/im-contract';
7
7
  import type { MessageOrigin } from './inbound-origin.js';
8
- import type { OperationEndpointSource } from './operation-endpoint.js';
8
+ import type { CoreReplyStream, OpenReplyStreamOptions } from './progressive-reply.js';
9
9
  import type { MediaRef, Segment } from '../../built/segment-contract/types.js';
10
- import { interactionOperationScope, type InteractionOperationScope } from './interaction-operation.js';
11
10
  export type { MediaRef, Segment };
11
+ /** Internal send binding retained by one inbound operation; never a wire/config field. */
12
+ export declare const operationEndpoint: unique symbol;
13
+ export interface OperationEndpointSource {
14
+ readonly [operationEndpoint]?: EndpointChildLease;
15
+ }
16
+ /** Capture while the source Message/event is active, before handing work to an asynchronous owner. */
17
+ export interface CaptureEndpointOperationInput {
18
+ /** Canonical complete source address; never an account alias. */
19
+ readonly target: ConversationRef;
20
+ /** Actual source Client, checked against the selected account incarnation. */
21
+ readonly client: unknown;
22
+ /** Lifetime of the work that is retaining the source operation. */
23
+ readonly signal?: AbortSignal;
24
+ /** Author supplied by trusted composition or the owner-bound Host facade. */
25
+ readonly requester?: PluginId;
26
+ }
27
+ /** Retained execution authority for one concrete Client; consumers must release it in finally. */
28
+ export interface CapturedEndpointOperation {
29
+ readonly target: ConversationRef;
30
+ readonly signal: AbortSignal;
31
+ /** The same guarded semantic ports as ordinary calls, pinned to the retained Client. */
32
+ readonly control?: EndpointControl;
33
+ readonly management?: EndpointManagement;
34
+ /** Current account facts and approved mutations, under the same retained operation. */
35
+ readonly profile?: SelfProfilePort;
36
+ /** Uses the ordinary renderer/middleware/delivery pipeline with the captured author. */
37
+ send(content: SendContent, options?: Readonly<{
38
+ locale?: Locale;
39
+ signal?: AbortSignal;
40
+ }>): Promise<DeliveryReceipt>;
41
+ openReplyStream?(options?: OpenReplyStreamOptions): CoreReplyStream | undefined;
42
+ /** Stops new calls and releases source/Root leases after accepted calls drain; never stops the account. */
43
+ release(): void;
44
+ }
45
+ /** Core-only trusted operation binding; never read from message metadata. */
46
+ export declare const interactionOperationScope: unique symbol;
47
+ export interface InteractionOperationScope {
48
+ readonly snapshot: RuntimeSnapshot;
49
+ readonly owner: PluginId;
50
+ /** Explicit stop/source/caller lifetime; not an HMR replacement notification. */
51
+ readonly signal?: AbortSignal;
52
+ /** Pin one actual source Client and independently owned snapshot until the question settles. */
53
+ readonly retain?: () => CapturedEndpointOperation;
54
+ }
55
+ /** Trusted composition port. Only Core supplies the controlled message and real held lease. */
56
+ export interface ImOperationResourcesInput {
57
+ readonly lease: SnapshotLease;
58
+ readonly snapshots: SnapshotReader;
59
+ readonly message: RuntimeMessage;
60
+ readonly owner: PluginId;
61
+ readonly signal: AbortSignal;
62
+ }
63
+ export interface ImOperationResourcesPort {
64
+ open(input: ImOperationResourcesInput): OperationResourceView | undefined;
65
+ }
66
+ export declare const imOperationResourcesToken: import("@zhin.js/plugin-runtime").Token<ImOperationResourcesPort>;
12
67
  declare const componentCallBrand: "zhin.component-call/1";
13
68
  declare const rawContentBrand: "zhin.raw-content/1";
14
69
  export interface ComponentCall<TProps = unknown> {
@@ -1,7 +1,11 @@
1
1
  import { commandFeatureId, isCommandIndex } from '@zhin.js/command';
2
- import { resolveLocale } from '@zhin.js/plugin-runtime';
2
+ import { createRootPrivateToken, resolveLocale } from '@zhin.js/plugin-runtime';
3
3
  import { operationInputBinding, operationInputSignal, operationInputResources, operationSession } from '@zhin.js/feature-kit';
4
- import { interactionOperationScope } from './interaction-operation.js';
4
+ /** Internal send binding retained by one inbound operation; never a wire/config field. */
5
+ export const operationEndpoint = Symbol('zhin.im.operation-endpoint');
6
+ /** Core-only trusted operation binding; never read from message metadata. */
7
+ export const interactionOperationScope = Symbol('InteractionOperationScope');
8
+ export const imOperationResourcesToken = createRootPrivateToken('zhin.im.operation-resources', 'Host resources for one authorized IM capability operation');
5
9
  const componentCallBrand = 'zhin.component-call/1';
6
10
  const rawContentBrand = 'zhin.raw-content/1';
7
11
  export function component(name, props) {
@@ -1,10 +1,9 @@
1
1
  import type { OutboundDeliveryExecution } from './outbound-delivery-runtime.js';
2
- import type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
3
- export type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
2
+ import { type CaptureEndpointOperationInput, type CapturedEndpointOperation, type ConversationAddress, type SendRequest } from './contracts.js';
3
+ export type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './contracts.js';
4
4
  import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type AdapterEndpointSummary, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
5
5
  import { type DeliveryTarget, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
6
6
  import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
7
- import type { ConversationAddress, SendRequest } from './contracts.js';
8
7
  export interface EndpointRuntimeSummary {
9
8
  readonly id: string;
10
9
  readonly endpoint: ConversationRef['endpoint'];
@@ -1,6 +1,6 @@
1
- import { operationEndpoint } from './operation-endpoint.js';
2
1
  import { createCoreReplyStream } from './progressive-reply.js';
3
- import { supportsIncrementalOutbound } from './runtime-middleware.js';
2
+ import { supportsIncrementalOutbound } from './inbound-spine.js';
3
+ import { operationEndpoint, } from './contracts.js';
4
4
  import { adapterFeatureId, isAdapterIndex, } from '@zhin.js/adapter';
5
5
  import { normalizeDeliveryTarget } from '@zhin.js/plugin-runtime';
6
6
  import { EndpointDeliveryError, } from '@zhin.js/im-contract';
@@ -0,0 +1,2 @@
1
+ import { type RootResourceInstaller } from '@zhin.js/plugin-runtime';
2
+ export declare function installComponentHost(): RootResourceInstaller;
@@ -0,0 +1,14 @@
1
+ import { compiler } from '../../../utils.js';
2
+ import { componentHostToken, } from '@zhin.js/plugin-runtime';
3
+ function createComponentHost() {
4
+ return {
5
+ compileTemplate(text, context) {
6
+ return compiler(text, { ...context });
7
+ },
8
+ };
9
+ }
10
+ export function installComponentHost() {
11
+ return ({ resources }) => {
12
+ resources.provide(componentHostToken, createComponentHost());
13
+ };
14
+ }
@@ -0,0 +1,5 @@
1
+ import { type StructuredDatabase } from '@zhin.js/database';
2
+ /** Run before installing the durable event reader into a candidate generation. */
3
+ export declare function migrateConversationColumns(database: StructuredDatabase): Promise<void>;
4
+ /** Older observations without canonical addresses remain explicitly unknown. */
5
+ export declare function migrateInboxColumns(database: StructuredDatabase): Promise<void>;
@@ -0,0 +1,75 @@
1
+ import { INBOX_MESSAGE_QUERY_COLUMNS, INBOX_TABLE_MESSAGE, encodeStorageIdentity } from '@zhin.js/plugin-runtime';
2
+ import { ensureDatabaseColumns, ensureDatabaseIndex } from '@zhin.js/database';
3
+ import { CONVERSATION_EVENT_QUERY_MODEL, conversationEventQueryFields } from '@zhin.js/im-contract';
4
+ /** Run before installing the durable event reader into a candidate generation. */
5
+ export async function migrateConversationColumns(database) {
6
+ if (!['sqlite', 'mysql', 'pg'].includes(database.dialectName))
7
+ return;
8
+ await ensureDatabaseColumns(database, 'conversation_events', CONVERSATION_EVENT_QUERY_MODEL);
9
+ const model = database.models.get('conversation_events');
10
+ if (!model)
11
+ throw new Error('Missing conversation_events model');
12
+ let afterId;
13
+ while (true) {
14
+ const rows = await model.select('id', 'event_json').where({ $and: [
15
+ ...(afterId === undefined ? [] : [{ id: { $gt: afterId } }]),
16
+ { $or: [{ query_version: null }, { message_revision: null }] },
17
+ ] }).orderBy('id').limit(200);
18
+ if (!rows.length)
19
+ break;
20
+ for (const row of rows) {
21
+ const event = JSON.parse(String(row.event_json));
22
+ const fields = conversationEventQueryFields(event);
23
+ await model.update(fields).where({ id: row.id });
24
+ }
25
+ // Seek past the completed batch instead of re-scanning already backfilled rows.
26
+ afterId = rows[rows.length - 1].id;
27
+ }
28
+ // Derived indexes can be rebuilt from event_json; rollback ignores the additive columns/indexes.
29
+ await ensureDatabaseIndex(database, 'conversation_events', 'conversation_events_message_sequence', [
30
+ { name: 'message_key', text: true }, { name: 'event_type', text: true }, { name: 'id' },
31
+ ]);
32
+ await ensureDatabaseIndex(database, 'conversation_events', 'conversation_events_message_revision', [
33
+ { name: 'message_key', text: true }, { name: 'event_type', text: true }, { name: 'message_revision' }, { name: 'id' },
34
+ ]);
35
+ await ensureDatabaseIndex(database, 'conversation_events', 'conversation_events_conversation_time', [{ name: 'conversation_key', text: true }, { name: 'time' }]);
36
+ await ensureDatabaseIndex(database, 'conversation_events', 'conversation_events_type_time', [{ name: 'event_type', text: true }, { name: 'time' }]);
37
+ await ensureDatabaseIndex(database, 'conversation_events', 'conversation_events_scene', [
38
+ { name: 'endpoint_adapter', text: true }, { name: 'endpoint_id', text: true },
39
+ { name: 'conversation_kind', text: true }, { name: 'conversation_id', text: true },
40
+ { name: 'id' },
41
+ ]);
42
+ // Operator scope directory selects only canonical address columns. SQLite/PostgreSQL
43
+ // can cover the full tuple; MySQL TEXT prefixes cannot cover full identities and
44
+ // seven 128-character utf8mb4 prefixes exceed its key budget, so keep an endpoint seek.
45
+ await ensureDatabaseIndex(database, 'conversation_events', 'conversation_events_scope_directory', (database.dialectName === 'mysql' ? ['endpoint_id'] : [
46
+ 'endpoint_id', 'endpoint_adapter', 'conversation_kind', 'conversation_id', 'parent_kind', 'parent_id', 'thread_id',
47
+ ]).map(name => ({ name, text: true })));
48
+ }
49
+ /** Older observations without canonical addresses remain explicitly unknown. */
50
+ export async function migrateInboxColumns(database) {
51
+ if (!['sqlite', 'mysql', 'pg'].includes(database.dialectName))
52
+ return;
53
+ await ensureDatabaseColumns(database, INBOX_TABLE_MESSAGE, INBOX_MESSAGE_QUERY_COLUMNS);
54
+ const model = database.models.get(INBOX_TABLE_MESSAGE);
55
+ while (true) {
56
+ const rows = await model.select('id', 'raw').where({ query_version: null }).orderBy('id').limit(200);
57
+ if (!rows.length)
58
+ break;
59
+ for (const row of rows) {
60
+ let observation;
61
+ try {
62
+ observation = JSON.parse(String(row.raw));
63
+ }
64
+ catch { /* Legacy raw is optional, not a canonical event. */ }
65
+ const current = observation?.$console === 'zhin.message-observation/1' ? observation : undefined;
66
+ const encoded = (value) => typeof value === 'string' ? encodeStorageIdentity(value) : null;
67
+ await model.update({ query_version: 1,
68
+ direction: ['inbound', 'outbound'].includes(current?.direction) ? current.direction : null,
69
+ endpoint_capability_id: encoded(current?.conversation?.endpoint?.id),
70
+ endpoint_adapter_id: encoded(current?.conversation?.endpoint?.adapter),
71
+ thread_id: encoded(current?.conversation?.threadId), }).where({ id: row.id, query_version: null });
72
+ }
73
+ }
74
+ await ensureDatabaseIndex(database, INBOX_TABLE_MESSAGE, 'inbox_message_direction_time', [{ name: 'direction', text: true }, { name: 'created_at' }]);
75
+ }
@@ -0,0 +1,10 @@
1
+ export type DatabaseHostConfig = {
2
+ readonly dialect: string;
3
+ } & Record<string, unknown>;
4
+ /**
5
+ * Validate and normalize the expanded Root database configuration before a
6
+ * third-party driver sees it. Dotenv expansion produces strings, while the
7
+ * network clients require numeric ports and otherwise surface opaque NaN
8
+ * socket errors.
9
+ */
10
+ export declare function normalizeDatabaseHostConfig(input: DatabaseHostConfig): DatabaseHostConfig;
@@ -0,0 +1,114 @@
1
+ const SUPPORTED_DIALECTS = new Set(['memory', 'mongodb', 'mysql', 'pg', 'redis', 'sqlite']);
2
+ function configurationError(path, expectation, envExample) {
3
+ const envHint = envExample
4
+ ? `若这里引用环境变量,请在项目根目录 .env 中设置 ${envExample}。`
5
+ : '若这里引用环境变量,请检查项目根目录 .env 中的对应变量。';
6
+ return new TypeError(`数据库配置 ${path} ${expectation}。${envHint}也可运行 \`zhin setup --database\` 重新配置。`);
7
+ }
8
+ function normalizePort(value, path, envExample) {
9
+ if (value === undefined)
10
+ return undefined;
11
+ const normalized = typeof value === 'number'
12
+ ? value
13
+ : typeof value === 'string' && /^\d+$/u.test(value.trim())
14
+ ? Number(value.trim())
15
+ : Number.NaN;
16
+ if (!Number.isInteger(normalized) || normalized < 1 || normalized > 65535) {
17
+ throw configurationError(path, '必须是 1-65535 的整数,当前值为空或无效', envExample);
18
+ }
19
+ return normalized;
20
+ }
21
+ function normalizeOptionalText(config, key, path, envExample) {
22
+ if (!(key in config))
23
+ return;
24
+ const value = config[key];
25
+ if (typeof value !== 'string' || value.trim() === '') {
26
+ throw configurationError(path, '不能为空', envExample);
27
+ }
28
+ config[key] = value.trim();
29
+ }
30
+ function normalizeRequiredText(config, key, path, envExample) {
31
+ if (!(key in config))
32
+ config[key] = undefined;
33
+ normalizeOptionalText(config, key, path, envExample);
34
+ }
35
+ function normalizeRedisDatabase(value) {
36
+ if (value === undefined)
37
+ return undefined;
38
+ const normalized = typeof value === 'number'
39
+ ? value
40
+ : typeof value === 'string' && /^\d+$/u.test(value.trim())
41
+ ? Number(value.trim())
42
+ : Number.NaN;
43
+ if (!Number.isInteger(normalized) || normalized < 0) {
44
+ throw configurationError('database.database', '必须是大于或等于 0 的整数', 'REDIS_DB=0');
45
+ }
46
+ return normalized;
47
+ }
48
+ /**
49
+ * Validate and normalize the expanded Root database configuration before a
50
+ * third-party driver sees it. Dotenv expansion produces strings, while the
51
+ * network clients require numeric ports and otherwise surface opaque NaN
52
+ * socket errors.
53
+ */
54
+ export function normalizeDatabaseHostConfig(input) {
55
+ const dialect = input.dialect;
56
+ if (!SUPPORTED_DIALECTS.has(dialect)) {
57
+ throw new TypeError(`数据库配置 database.dialect 不支持 ${JSON.stringify(dialect)};`
58
+ + '可选值为 sqlite、mysql、pg、mongodb、redis、memory。');
59
+ }
60
+ const config = { ...input, dialect };
61
+ switch (dialect) {
62
+ case 'mysql':
63
+ normalizeOptionalText(config, 'host', 'database.host', 'DB_HOST=127.0.0.1');
64
+ normalizeOptionalText(config, 'user', 'database.user', 'DB_USER=root');
65
+ normalizeOptionalText(config, 'database', 'database.database', 'DB_DATABASE=zhin_bot');
66
+ normalizeOptionalText(config, 'uri', 'database.uri');
67
+ config.port = normalizePort(config.port, 'database.port', 'DB_PORT=3306');
68
+ if (config.port === undefined)
69
+ delete config.port;
70
+ break;
71
+ case 'pg':
72
+ normalizeOptionalText(config, 'host', 'database.host', 'DB_HOST=127.0.0.1');
73
+ normalizeOptionalText(config, 'user', 'database.user', 'DB_USER=postgres');
74
+ normalizeOptionalText(config, 'database', 'database.database', 'DB_DATABASE=zhin_bot');
75
+ normalizeOptionalText(config, 'connectionString', 'database.connectionString');
76
+ config.port = normalizePort(config.port, 'database.port', 'DB_PORT=5432');
77
+ if (config.port === undefined)
78
+ delete config.port;
79
+ break;
80
+ case 'mongodb':
81
+ normalizeRequiredText(config, 'url', 'database.url', 'DB_URL=mongodb://127.0.0.1:27017');
82
+ normalizeRequiredText(config, 'dbName', 'database.dbName', 'DB_NAME=zhin_bot');
83
+ if (!/^mongodb(?:\+srv)?:\/\//u.test(String(config.url))) {
84
+ throw configurationError('database.url', '必须使用 mongodb:// 或 mongodb+srv://');
85
+ }
86
+ break;
87
+ case 'redis': {
88
+ normalizeOptionalText(config, 'url', 'database.url', 'REDIS_URL=redis://127.0.0.1:6379');
89
+ if (config.socket !== undefined) {
90
+ if (!config.socket || typeof config.socket !== 'object' || Array.isArray(config.socket)) {
91
+ throw configurationError('database.socket', '必须是对象');
92
+ }
93
+ const socket = { ...config.socket };
94
+ normalizeOptionalText(socket, 'host', 'database.socket.host', 'REDIS_HOST=127.0.0.1');
95
+ socket.port = normalizePort(socket.port, 'database.socket.port', 'REDIS_PORT=6379');
96
+ if (socket.port === undefined)
97
+ delete socket.port;
98
+ config.socket = Object.freeze(socket);
99
+ }
100
+ config.database = normalizeRedisDatabase(config.database);
101
+ if (config.database === undefined)
102
+ delete config.database;
103
+ break;
104
+ }
105
+ case 'sqlite':
106
+ if (config.filename === undefined)
107
+ config.filename = './data/bot.db';
108
+ normalizeOptionalText(config, 'filename', 'database.filename');
109
+ break;
110
+ case 'memory':
111
+ break;
112
+ }
113
+ return Object.freeze(config);
114
+ }
@@ -0,0 +1,13 @@
1
+ import { type DatabaseHost, type ConfigDocumentPort, type RootResourceInstaller, type RuntimeConfigDocument } from '@zhin.js/plugin-runtime';
2
+ import { type DatabaseHostConfig } from './database-config.js';
3
+ export type { DatabaseHostConfig } from './database-config.js';
4
+ export declare function createDatabaseHost(config: DatabaseHostConfig): DatabaseHost & {
5
+ readonly db: {
6
+ define: (name: string, definition: unknown) => void;
7
+ start(): Promise<void>;
8
+ stop(): Promise<void>;
9
+ models: Map<string, unknown>;
10
+ };
11
+ };
12
+ export declare function resolveDatabaseConfig(projectRoot: string, config: RuntimeConfigDocument | ConfigDocumentPort): Promise<DatabaseHostConfig>;
13
+ export declare function installDatabaseHost(host: DatabaseHost): RootResourceInstaller;