@zhin.js/core 1.1.56 → 1.1.58

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 (117) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.d.ts +1 -1
  6. package/lib/built/user-interaction.js +3 -1
  7. package/lib/feature/command.d.ts +2 -4
  8. package/lib/feature/command.js +1 -2
  9. package/lib/feature/middleware.d.ts +2 -2
  10. package/lib/feature/middleware.js +1 -1
  11. package/lib/index.d.ts +2 -1
  12. package/lib/index.js +2 -0
  13. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  14. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  15. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  16. package/lib/plugin-runtime/im/contracts.js +6 -2
  17. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  18. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  19. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  20. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  21. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  22. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  23. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  24. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  25. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  26. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  27. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  28. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  29. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  30. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  31. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  32. package/lib/plugin-runtime/im/host/index.js +8 -0
  33. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  34. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  35. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  36. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  37. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  38. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  39. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  40. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  41. package/lib/plugin-runtime/im/inbound-dedup.d.ts +33 -0
  42. package/lib/plugin-runtime/im/inbound-dedup.js +139 -1
  43. package/lib/plugin-runtime/im/inbound-origin.d.ts +51 -2
  44. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  45. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  46. package/lib/plugin-runtime/im/inbound-runtime.js +88 -349
  47. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  48. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  49. package/lib/plugin-runtime/im/index.d.ts +5 -7
  50. package/lib/plugin-runtime/im/index.js +5 -6
  51. package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -10
  52. package/lib/plugin-runtime/im/interaction-runtime.js +86 -28
  53. package/lib/plugin-runtime/im/interactive-router.d.ts +55 -8
  54. package/lib/plugin-runtime/im/interactive-router.js +244 -35
  55. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  56. package/lib/plugin-runtime/im/message-dispatcher.js +58 -7
  57. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  58. package/lib/plugin-runtime/im/message-events.js +34 -0
  59. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +4 -4
  60. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +75 -29
  61. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  62. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  63. package/lib/runtime.d.ts +2 -0
  64. package/lib/runtime.js +2 -0
  65. package/lib/venue/contracts.d.ts +21 -0
  66. package/lib/venue/contracts.js +3 -0
  67. package/lib/venue/floor-controller.d.ts +11 -0
  68. package/lib/venue/floor-controller.js +63 -0
  69. package/lib/venue/index.d.ts +13 -0
  70. package/lib/venue/index.js +11 -0
  71. package/lib/venue/membership-port.d.ts +23 -0
  72. package/lib/venue/membership-port.js +141 -0
  73. package/lib/venue/projector.d.ts +38 -0
  74. package/lib/venue/projector.js +45 -0
  75. package/lib/venue/registry.d.ts +16 -0
  76. package/lib/venue/registry.js +63 -0
  77. package/lib/venue/router.d.ts +19 -0
  78. package/lib/venue/router.js +101 -0
  79. package/lib/venue/send-limiter.d.ts +17 -0
  80. package/lib/venue/send-limiter.js +73 -0
  81. package/lib/venue/validator.d.ts +6 -0
  82. package/lib/venue/validator.js +160 -0
  83. package/package.json +16 -17
  84. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  85. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  86. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  87. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  88. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  89. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  90. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  91. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  92. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  93. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  94. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  95. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  96. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -17
  97. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -98
  98. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  99. package/lib/plugin-runtime/im/locale.js +0 -12
  100. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  101. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  102. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  103. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  104. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  105. package/lib/plugin-runtime/im/message-bus.js +0 -40
  106. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  107. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  108. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  109. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  110. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  111. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  112. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  113. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  114. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  115. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  116. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  117. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -1,38 +0,0 @@
1
- /**
2
- * Generation-owned IM lifecycle event bus.
3
- *
4
- * Runtime services resolve this bus through Scope+Token and never depend on a
5
- * process-global event owner.
6
- */
7
- import type { DeliveryReceipt } from '@zhin.js/im-contract';
8
- import type { Message, OutboundEnvelope, SendContent } from './contracts.js';
9
- export interface EndpointEvent {
10
- readonly adapter: string;
11
- readonly endpointKey: string;
12
- readonly error?: Error;
13
- }
14
- export interface MessageBusEventMap {
15
- 'message.receive': [message: Message];
16
- 'before.sendMessage': [envelope: OutboundEnvelope];
17
- 'message.send': [payload: {
18
- adapter: string;
19
- endpointKey: string;
20
- content: SendContent;
21
- receipt: DeliveryReceipt;
22
- }];
23
- 'endpoint.connect': [event: EndpointEvent];
24
- 'endpoint.disconnect': [event: EndpointEvent];
25
- 'endpoint.error': [event: EndpointEvent];
26
- }
27
- export type MessageBusEventName = keyof MessageBusEventMap;
28
- export declare class MessageBus {
29
- private readonly emitter;
30
- constructor();
31
- on<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
32
- once<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
33
- emit<E extends MessageBusEventName>(event: E, ...args: MessageBusEventMap[E]): void;
34
- off<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): void;
35
- listenerCount(event: MessageBusEventName): number;
36
- removeAllListeners(event?: MessageBusEventName): void;
37
- }
38
- export declare const messageBusToken: import("@zhin.js/plugin-runtime").Token<MessageBus>;
@@ -1,40 +0,0 @@
1
- /**
2
- * Generation-owned IM lifecycle event bus.
3
- *
4
- * Runtime services resolve this bus through Scope+Token and never depend on a
5
- * process-global event owner.
6
- */
7
- import { EventEmitter } from 'node:events';
8
- import { createToken } from '@zhin.js/plugin-runtime';
9
- export class MessageBus {
10
- emitter = new EventEmitter();
11
- constructor() {
12
- this.emitter.setMaxListeners(50);
13
- }
14
- on(event, listener) {
15
- this.emitter.on(event, listener);
16
- return () => this.emitter.off(event, listener);
17
- }
18
- once(event, listener) {
19
- this.emitter.once(event, listener);
20
- return () => this.emitter.off(event, listener);
21
- }
22
- emit(event, ...args) {
23
- this.emitter.emit(event, ...args);
24
- }
25
- off(event, listener) {
26
- this.emitter.off(event, listener);
27
- }
28
- listenerCount(event) {
29
- return this.emitter.listenerCount(event);
30
- }
31
- removeAllListeners(event) {
32
- if (event) {
33
- this.emitter.removeAllListeners(event);
34
- }
35
- else {
36
- this.emitter.removeAllListeners();
37
- }
38
- }
39
- }
40
- export const messageBusToken = createToken('zhin.im.message-bus');
@@ -1,6 +0,0 @@
1
- import type { EndpointChildLease } from '@zhin.js/adapter';
2
- /** Internal send binding retained by one inbound operation; never a wire/config field. */
3
- export declare const operationEndpoint: unique symbol;
4
- export interface OperationEndpointSource {
5
- readonly [operationEndpoint]?: EndpointChildLease;
6
- }
@@ -1,2 +0,0 @@
1
- /** Internal send binding retained by one inbound operation; never a wire/config field. */
2
- export const operationEndpoint = Symbol('zhin.im.operation-endpoint');
@@ -1,15 +0,0 @@
1
- import { type PluginId, type SnapshotLease, type SnapshotReader } from '@zhin.js/plugin-runtime';
2
- import type { OperationResourceView } from '@zhin.js/feature-kit';
3
- import type { RuntimeMessage } from './contracts.js';
4
- /** Trusted composition port. Only Core supplies the controlled message and real held lease. */
5
- export interface ImOperationResourcesInput {
6
- readonly lease: SnapshotLease;
7
- readonly snapshots: SnapshotReader;
8
- readonly message: RuntimeMessage;
9
- readonly owner: PluginId;
10
- readonly signal: AbortSignal;
11
- }
12
- export interface ImOperationResourcesPort {
13
- open(input: ImOperationResourcesInput): OperationResourceView | undefined;
14
- }
15
- export declare const imOperationResourcesToken: import("@zhin.js/plugin-runtime").Token<ImOperationResourcesPort>;
@@ -1,2 +0,0 @@
1
- import { createRootPrivateToken } from '@zhin.js/plugin-runtime';
2
- export const imOperationResourcesToken = createRootPrivateToken('zhin.im.operation-resources', 'Host resources for one authorized IM capability operation');
@@ -1,24 +0,0 @@
1
- import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
2
- /**
3
- * scope 键不含 endpoint id:同一个群里不同 Bot 的 conversationRefKey 不同,
4
- * 但它们互相的回显仍属同一会话。
5
- */
6
- export declare function ledgerScopeOf(conversation: ConversationRef): string;
7
- export declare function digestText(text: string): string | undefined;
8
- export interface LedgerMatch {
9
- readonly endpointId: string;
10
- }
11
- export declare class OutboundLedger {
12
- #private;
13
- private readonly now;
14
- constructor(now?: () => number);
15
- get size(): number;
16
- /** 仅在 `receipt.status === 'sent'` 时记录;`payload` 应为最终投影后的 payload。 */
17
- record(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
18
- matchById(scope: string, messageId: unknown): LedgerMatch | undefined;
19
- /**
20
- * 摘要兜底(“账号 id 对不上”时):30 秒窗口、一次性。
21
- * 权衡:人类在窗口内原样复读 Bot 刚发的文本,会被当作回显丢弃一次。
22
- */
23
- matchByDigest(scope: string, text: string, now?: number): LedgerMatch | undefined;
24
- }
@@ -1,114 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { segmentsToPlainText } from '../../built/segment-contract/text.js';
3
- /**
4
- * @internal 出站 ledger:入站 origin 判定的关联层兜底。
5
- *
6
- * 只保存 message id 与文本摘要(不存原文),有界内存、短 TTL。
7
- * 写入发生在 `deliver` 成功之后的旁路,失败不影响 receipt。
8
- */
9
- const MAX_ENTRIES = 2000;
10
- const TTL_MS = 10 * 60_000;
11
- const DIGEST_WINDOW_MS = 30_000;
12
- const MIN_DIGEST_TEXT = 4;
13
- /**
14
- * scope 键不含 endpoint id:同一个群里不同 Bot 的 conversationRefKey 不同,
15
- * 但它们互相的回显仍属同一会话。
16
- */
17
- export function ledgerScopeOf(conversation) {
18
- return [
19
- conversation.endpoint.adapter,
20
- conversation.kind,
21
- conversation.id,
22
- conversation.parent?.kind ?? '',
23
- conversation.parent?.id ?? '',
24
- conversation.threadId ?? '',
25
- ].join('\0');
26
- }
27
- export function digestText(text) {
28
- const normalized = text.replace(/\s+/g, ' ').trim();
29
- if (normalized.length < MIN_DIGEST_TEXT)
30
- return undefined;
31
- return createHash('sha256').update(normalized).digest('hex').slice(0, 16);
32
- }
33
- function payloadText(payload) {
34
- if (typeof payload === 'string')
35
- return payload;
36
- if (Array.isArray(payload)) {
37
- return segmentsToPlainText(payload.filter((item) => !!item && typeof item === 'object' && typeof item.type === 'string'));
38
- }
39
- return '';
40
- }
41
- export class OutboundLedger {
42
- now;
43
- #entries = [];
44
- constructor(now = Date.now) {
45
- this.now = now;
46
- }
47
- get size() {
48
- return this.#entries.length;
49
- }
50
- /** 仅在 `receipt.status === 'sent'` 时记录;`payload` 应为最终投影后的 payload。 */
51
- record(conversation, receipt, payload) {
52
- if (receipt.status !== 'sent')
53
- return;
54
- const at = this.now();
55
- this.#prune(at);
56
- const rawId = receipt.message?.id;
57
- const messageId = rawId === undefined || rawId === null || String(rawId) === '' ? undefined : String(rawId);
58
- const digest = digestText(payloadText(payload));
59
- if (messageId === undefined && digest === undefined)
60
- return;
61
- this.#entries.push({
62
- scope: ledgerScopeOf(conversation),
63
- endpointId: conversation.endpoint.id,
64
- ...(messageId !== undefined ? { messageId } : {}),
65
- ...(digest !== undefined ? { digest } : {}),
66
- at,
67
- digestConsumed: false,
68
- });
69
- while (this.#entries.length > MAX_ENTRIES)
70
- this.#entries.shift();
71
- }
72
- matchById(scope, messageId) {
73
- if (typeof messageId !== 'string' && typeof messageId !== 'number')
74
- return undefined;
75
- const id = String(messageId);
76
- if (id === '')
77
- return undefined;
78
- const at = this.now();
79
- for (let i = this.#entries.length - 1; i >= 0; i--) {
80
- const entry = this.#entries[i];
81
- if (at - entry.at > TTL_MS)
82
- continue;
83
- if (entry.scope === scope && entry.messageId === id)
84
- return { endpointId: entry.endpointId };
85
- }
86
- return undefined;
87
- }
88
- /**
89
- * 摘要兜底(“账号 id 对不上”时):30 秒窗口、一次性。
90
- * 权衡:人类在窗口内原样复读 Bot 刚发的文本,会被当作回显丢弃一次。
91
- */
92
- matchByDigest(scope, text, now = this.now()) {
93
- const digest = digestText(typeof text === 'string' ? text : '');
94
- if (digest === undefined)
95
- return undefined;
96
- for (let i = this.#entries.length - 1; i >= 0; i--) {
97
- const entry = this.#entries[i];
98
- if (now - entry.at > DIGEST_WINDOW_MS)
99
- continue;
100
- if (entry.digestConsumed || entry.scope !== scope || entry.digest !== digest)
101
- continue;
102
- entry.digestConsumed = true;
103
- return { endpointId: entry.endpointId };
104
- }
105
- return undefined;
106
- }
107
- #prune(at) {
108
- let drop = 0;
109
- while (drop < this.#entries.length && at - this.#entries[drop].at > TTL_MS)
110
- drop++;
111
- if (drop > 0)
112
- this.#entries.splice(0, drop);
113
- }
114
- }
@@ -1,19 +0,0 @@
1
- import type { ConversationRef } from '@zhin.js/im-contract';
2
- import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
- /** Keep the adapter's presentation or prefer its existing readable text fallback. */
4
- export type OutboundPresentationMode = 'default' | 'text';
5
- export interface OutboundPresentationPreferences {
6
- readonly html?: OutboundPresentationMode;
7
- readonly markdown?: OutboundPresentationMode;
8
- readonly interactive?: OutboundPresentationMode;
9
- }
10
- export interface OutboundPresentationContext {
11
- readonly conversation: ConversationRef;
12
- readonly requester: PluginId;
13
- readonly generation: number;
14
- }
15
- /** A synchronous, side-effect-free decision, shared by delivery and target previews. */
16
- export type OutboundPresentation = (context: OutboundPresentationContext) => OutboundPresentationPreferences | undefined;
17
- export declare const outboundPresentationToken: import("@zhin.js/plugin-runtime").Token<OutboundPresentation>;
18
- /** Resolve once per operation; replacements reuse this detached, immutable decision. */
19
- export declare function resolveOutboundPresentation(snapshot: RuntimeSnapshot, conversation: ConversationRef, requester: PluginId): OutboundPresentationPreferences | undefined;
@@ -1,41 +0,0 @@
1
- import { formatCompact, getLogger } from '@zhin.js/logger';
2
- import { createToken } from '@zhin.js/plugin-runtime';
3
- export const outboundPresentationToken = createToken('zhin.outbound-presentation', 'Root-selected outbound presentation within the adapter capability boundary');
4
- const logger = getLogger('im.outbound');
5
- /** Resolve once per operation; replacements reuse this detached, immutable decision. */
6
- export function resolveOutboundPresentation(snapshot, conversation, requester) {
7
- const policy = snapshot.resources.get(snapshot.root)?.get(outboundPresentationToken.id);
8
- if (policy === undefined)
9
- return undefined;
10
- try {
11
- const view = Object.freeze({
12
- endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
13
- kind: conversation.kind,
14
- id: conversation.id,
15
- ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
16
- ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
17
- });
18
- const result = policy(Object.freeze({ conversation: view, requester, generation: snapshot.generation }));
19
- if (result === undefined)
20
- return undefined;
21
- if (result && typeof result === 'object' && 'then' in result) {
22
- // An accidentally async policy is outside the contract. Consume a possible
23
- // rejection without waiting for it or applying a later decision to this send.
24
- void Promise.resolve(result).catch(() => undefined);
25
- throw new TypeError('Outbound presentation must be synchronous');
26
- }
27
- if (!result || typeof result !== 'object')
28
- throw new TypeError('Invalid outbound presentation');
29
- const { html, markdown, interactive } = result;
30
- for (const value of [html, markdown, interactive]) {
31
- if (value !== undefined && value !== 'default' && value !== 'text')
32
- throw new TypeError('Invalid outbound presentation mode');
33
- }
34
- return Object.freeze({ html, markdown, interactive });
35
- }
36
- catch {
37
- // Never log the callback error, content or user-provided values; do not retry it.
38
- logger.warn(formatCompact({ op: 'outbound_presentation', status: 'fallback', reason: 'policy_failed', generation: snapshot.generation }));
39
- return undefined;
40
- }
41
- }
@@ -1,17 +0,0 @@
1
- import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
- import { type ConversationRef } from '@zhin.js/im-contract';
3
- import type { OutboundFallbackReason, RuntimeMessageRendering } from './message-events.js';
4
- import type { OutboundPresentationPreferences } from './outbound-presentation.js';
5
- export interface OutboundProjection {
6
- readonly payload: unknown;
7
- readonly rendering: RuntimeMessageRendering;
8
- }
9
- /** Shared by transport and target-aware previews. Does not send or register callbacks. */
10
- export declare function projectOutboundPayload(rendered: unknown, conversation: ConversationRef, snapshot: RuntimeSnapshot, options?: {
11
- readonly rememberFallback?: (map: Record<string, string>) => Record<string, string> | void;
12
- readonly inheritedFallbacks?: readonly OutboundFallbackReason[];
13
- /** Keep keyboard payloads until outbound middleware has had a chance to replace them. */
14
- readonly deferInteractive?: boolean;
15
- readonly signal?: AbortSignal;
16
- readonly presentation?: OutboundPresentationPreferences;
17
- }): Promise<OutboundProjection>;
@@ -1,55 +0,0 @@
1
- import { htmlRendererToken } from '@zhin.js/plugin-runtime';
2
- import { EndpointDeliveryError } from '@zhin.js/im-contract';
3
- import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
4
- import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
5
- import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundHtmlPolicy, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
6
- /** Shared by transport and target-aware previews. Does not send or register callbacks. */
7
- export async function projectOutboundPayload(rendered, conversation, snapshot, options = {}) {
8
- options.signal?.throwIfAborted();
9
- const adapter = conversation.endpoint.id;
10
- const reasons = new Set(options.inheritedFallbacks);
11
- const values = Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered;
12
- const contains = (type) => (Array.isArray(values) ? values : [values])
13
- .some(value => value && typeof value === 'object' && value.type === type);
14
- const markdown = options.presentation?.markdown === 'text' ? 'text' : resolveOutboundMarkdownPolicy(adapter, snapshot);
15
- if (markdown === 'text' && contains('markdown'))
16
- reasons.add('markdown_text_policy');
17
- const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
18
- let payload = await normalizeOutboundPayload(applyOutboundMarkdownPolicy(values, markdown), host, {
19
- mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
20
- htmlPolicy: options.presentation?.html === 'text' ? 'text' : resolveOutboundHtmlPolicy(adapter, snapshot),
21
- onFallback: reason => reasons.add(reason),
22
- signal: options.signal,
23
- });
24
- options.signal?.throwIfAborted();
25
- const interactive = options.presentation?.interactive === 'text' ? 'text' : resolveOutboundInteractivePolicy(adapter, snapshot);
26
- if (interactive === 'text' && Array.isArray(payload) && payload.some(item => item?.type === 'keyboard')) {
27
- reasons.add('interactive_text_policy');
28
- }
29
- if (!options.deferInteractive)
30
- payload = applyOutboundInteractivePolicy(payload, interactive, options.rememberFallback);
31
- if (Array.isArray(payload)) {
32
- payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
33
- assertCanonicalSegments(payload);
34
- }
35
- const supported = resolveOutboundSupportedSegments(adapter, snapshot);
36
- const supportedPayload = options.deferInteractive ? applyOutboundInteractivePolicy(payload, interactive) : payload;
37
- if (supported && Array.isArray(supportedPayload)) {
38
- const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object'
39
- && typeof segment.type === 'string' && !supported.includes(segment.type));
40
- if (unsupported)
41
- throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
42
- }
43
- const forms = new Set();
44
- for (const item of Array.isArray(payload) ? payload : [payload]) {
45
- if (typeof item === 'string' || item?.type === 'text')
46
- forms.add('text');
47
- else if (item?.type === 'image')
48
- forms.add('image');
49
- else if (item != null)
50
- forms.add('native');
51
- }
52
- return Object.freeze({ payload, rendering: Object.freeze({
53
- forms: Object.freeze([...forms]), fallbacks: Object.freeze([...reasons]),
54
- }) });
55
- }
@@ -1,5 +0,0 @@
1
- import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
- /** Runs the generation-owned middleware projection or the terminal directly. */
3
- export declare function runRuntimeMiddleware<TInput>(snapshot: RuntimeSnapshot, input: TInput, terminal: () => Promise<void>, target: 'inbound' | 'outbound'): Promise<void>;
4
- /** Legacy outbound middleware sees one complete reply unless its author explicitly supports revisions. */
5
- export declare function supportsIncrementalOutbound(snapshot: RuntimeSnapshot, adapter: string): boolean;
@@ -1,18 +0,0 @@
1
- import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
2
- /** Runs the generation-owned middleware projection or the terminal directly. */
3
- export async function runRuntimeMiddleware(snapshot, input, terminal, target) {
4
- const index = middleware(snapshot);
5
- if (index)
6
- await index.run(input, terminal, target, snapshot);
7
- else
8
- await terminal();
9
- }
10
- function middleware(snapshot) {
11
- const projection = snapshot.projections.get(middlewareFeatureId);
12
- return isMiddlewareIndex(projection) ? projection : undefined;
13
- }
14
- /** Legacy outbound middleware sees one complete reply unless its author explicitly supports revisions. */
15
- export function supportsIncrementalOutbound(snapshot, adapter) {
16
- return middleware(snapshot)?.list().every(record => record.target !== 'outbound'
17
- || record.adapter !== undefined && record.adapter !== adapter || record.incremental === true) ?? true;
18
- }