@zhin.js/core 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/lib/built/interactive-segments/types.d.ts +6 -0
  2. package/lib/built/login-assist.d.ts +317 -14
  3. package/lib/built/login-assist.js +1139 -64
  4. package/lib/built/login-captcha.d.ts +62 -0
  5. package/lib/built/login-captcha.js +107 -0
  6. package/lib/built/user-interaction.d.ts +3 -1
  7. package/lib/built/user-interaction.js +2 -0
  8. package/lib/feature/command-public-api.d.ts +1 -1
  9. package/lib/feature/command-public-api.js +1 -1
  10. package/lib/index.d.ts +1 -0
  11. package/lib/index.js +1 -0
  12. package/lib/plugin-runtime/im/command-suggestion.d.ts +13 -0
  13. package/lib/plugin-runtime/im/command-suggestion.js +32 -0
  14. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +52 -2
  15. package/lib/plugin-runtime/im/endpoint-runtime.js +74 -2
  16. package/lib/plugin-runtime/im/host/database-config.js +38 -0
  17. package/lib/plugin-runtime/im/host/database-console-schema.d.ts +79 -0
  18. package/lib/plugin-runtime/im/host/database-console-schema.js +477 -0
  19. package/lib/plugin-runtime/im/host/database-console-sql.d.ts +66 -0
  20. package/lib/plugin-runtime/im/host/database-console-sql.js +459 -0
  21. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +48 -17
  22. package/lib/plugin-runtime/im/host/database-host-installer.js +770 -46
  23. package/lib/plugin-runtime/im/im-runtime.js +1 -0
  24. package/lib/plugin-runtime/im/inbound-runtime.js +2 -0
  25. package/lib/plugin-runtime/im/inbound-spine.d.ts +6 -1
  26. package/lib/plugin-runtime/im/inbound-spine.js +51 -1
  27. package/lib/plugin-runtime/im/index.d.ts +1 -1
  28. package/lib/plugin-runtime/im/message-dispatcher.js +2 -1
  29. package/lib/plugin-runtime/im/message-events.d.ts +5 -1
  30. package/lib/plugin-runtime/im/message-events.js +38 -3
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +1 -1
  32. package/package.json +13 -13
@@ -98,6 +98,7 @@ export class ImRuntime {
98
98
  retain: () => this.#retainSnapshot(),
99
99
  release: (lease) => this.#release(lease),
100
100
  send: (request, snapshot, execution) => this.#deliver(request, snapshot, execution),
101
+ loginFlows: () => this.loginAssist.listFlows(),
101
102
  });
102
103
  // ADR 0056 §1: `bot:*` permits read the Bot's own standing through the Adapter index cache;
103
104
  // the Bot's role events drop the cached answer of that conversation.
@@ -4,6 +4,7 @@ import { RuntimeMessage, operationEndpoint, } from './contracts.js';
4
4
  import { requireAdapters } from './endpoint-runtime.js';
5
5
  import { arbitrateRoomInboundDeduplication, dispatchCanonicalEndpointEvent, dispatchInboundHandlers, dispatchInboundInteractive, handlers, interactionResult, messageLocale, resolveIngressRoute, resolveRoomMembership, runInboundMiddlewareAndSpine, withEndpointEventPayload, } from './inbound-spine.js';
6
6
  import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
7
+ import { suggestCommandReply } from './command-suggestion.js';
7
8
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
8
9
  const logger = getLogger('im.inbound');
9
10
  /** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
@@ -317,6 +318,7 @@ export class InboundRuntime {
317
318
  interactions: this.context.interactions,
318
319
  }),
319
320
  dispatchCommand: (observe) => this.#dispatcher.dispatchWithReply(message, lease.value, interactionFactory, observe),
321
+ suggestCommand: () => suggestCommandReply(message, lease.value, message.commandPrefix ?? this.#dispatcher.commandEnvironment(message, lease.value).prefix),
320
322
  hasReplied: () => operationReplied,
321
323
  findEventHandlerName: (event) => handlers(lease.value)?.list().find(descriptor => descriptor.event === event)?.name,
322
324
  }, this.context.diagnostics);
@@ -102,7 +102,7 @@ export declare function supportsIncrementalOutbound(snapshot: RuntimeSnapshot, a
102
102
  export declare function projectLocale(snapshot: RuntimeSnapshot): Locale;
103
103
  /** Resolve once per operation; callbacks retain the original operation's language. */
104
104
  export declare function messageLocale(snapshot: RuntimeSnapshot, conversation: Pick<ConversationRef, 'endpoint'>, senderId?: string): Promise<Locale>;
105
- export type InboundSpineStage = 'pre-route' | 'before-dispatch-route' | 'handlers' | 'interactive' | 'command' | 'agent-ingress' | 'none';
105
+ export type InboundSpineStage = 'pre-route' | 'before-dispatch-route' | 'handlers' | 'interactive' | 'command' | 'agent-ingress' | 'command-suggestion' | 'none';
106
106
  export type InboundCommandObserve = (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void;
107
107
  export interface InboundTurnRecord {
108
108
  readonly turnId: string;
@@ -130,6 +130,11 @@ export interface InboundTurnEnvelope {
130
130
  runHandlers(): Promise<void>;
131
131
  dispatchInteractive(): Promise<MessageDispatchResult | undefined>;
132
132
  dispatchCommand(observe: InboundCommandObserve): Promise<MessageDispatchOutcome>;
133
+ /**
134
+ * Before an unmatched message goes to the AI ingress: a "did you mean" reply when its
135
+ * first words resemble a registered command (issue #1250); `undefined` keeps the AI path.
136
+ */
137
+ suggestCommand?(): Promise<SendContent | undefined>;
133
138
  hasReplied(): boolean;
134
139
  findEventHandlerName?(event: string): string | undefined;
135
140
  }
@@ -1,5 +1,6 @@
1
1
  import { bindOperationInput, operationInputBinding } from '@zhin.js/feature-kit';
2
2
  import { formatCompact, getLogger } from '@zhin.js/logger';
3
+ import { userFacingErrorText } from '@zhin.js/command';
3
4
  import { isMiddlewareIndex, middlewareFeatureId, } from '@zhin.js/middleware';
4
5
  import { createToken, projectLocaleToken, resolveLocale, userLocalePreferencesToken, } from '@zhin.js/plugin-runtime';
5
6
  import { handlerFeatureId, isHandlerIndex } from '../../feature/handler.js';
@@ -122,11 +123,29 @@ export async function executeInboundTurnSpine(envelope, control) {
122
123
  : dispatched?.dispatch.matched
123
124
  ? 'command'
124
125
  : 'none';
126
+ let suggestion;
125
127
  if (!result.matched && ingressRoute) {
126
128
  logger.debug(formatCompact({
127
129
  op: 'unmatched',
128
130
  conv: formatConversationLog(message.conversation),
129
131
  }));
132
+ let suggested;
133
+ if (!repliedDuringHandlers && !envelope.hasReplied()) {
134
+ // A suggestion is a convenience: its failure keeps the ordinary AI path.
135
+ try {
136
+ suggested = await envelope.suggestCommand?.();
137
+ }
138
+ catch {
139
+ suggested = undefined;
140
+ }
141
+ }
142
+ if (suggested !== undefined) {
143
+ diagnostics?.route('command');
144
+ suggestion = { owner: requester, content: suggested };
145
+ stage = 'command-suggestion';
146
+ }
147
+ }
148
+ if (!result.matched && ingressRoute && !suggestion) {
130
149
  const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
131
150
  if (handled) {
132
151
  diagnostics?.route('agent');
@@ -134,7 +153,7 @@ export async function executeInboundTurnSpine(envelope, control) {
134
153
  stage = 'agent-ingress';
135
154
  }
136
155
  }
137
- const response = dispatched?.reply ?? (interactive?.value !== undefined && interactive.owner
156
+ const response = dispatched?.reply ?? suggestion ?? (interactive?.value !== undefined && interactive.owner
138
157
  ? { owner: interactive.owner, content: interactive.value }
139
158
  : undefined);
140
159
  const replied = envelope.hasReplied() || response !== undefined;
@@ -194,6 +213,19 @@ export async function runInboundMiddlewareAndSpine(envelope, diagnostics) {
194
213
  diagnostics?.step('middleware', 'stopped');
195
214
  return { dispatch: { matched: true, command: 'middleware', owner } };
196
215
  },
216
+ // #1250: a UserFacingError thrown by a Middleware becomes its reply (normal outbound chain).
217
+ refuse: (owner, error, downstream) => {
218
+ const text = userFacingErrorText(error, message.locale);
219
+ if (text === undefined)
220
+ return undefined;
221
+ diagnostics?.step('middleware', 'replaced');
222
+ if (!downstream?.dispatch.matched)
223
+ diagnostics?.route('middleware');
224
+ return {
225
+ dispatch: downstream?.dispatch.matched ? downstream.dispatch : { matched: true, command: 'middleware', owner },
226
+ reply: { owner, content: text },
227
+ };
228
+ },
197
229
  replace: (owner, value, downstream) => {
198
230
  diagnostics?.step('middleware', 'replaced');
199
231
  if (!downstream?.dispatch.matched)
@@ -239,6 +271,24 @@ export async function dispatchInboundHandlers({ lease, event, args, signal = lea
239
271
  }
240
272
  return undefined;
241
273
  },
274
+ // #1250: a UserFacingError thrown by a handler is answered in the event's conversation through
275
+ // the normal outbound chain; any other error still propagates (and is only logged).
276
+ recover: async (error, owner) => {
277
+ const payload = args[0]?.payload;
278
+ const locale = payload instanceof RuntimeMessage ? payload.locale : undefined;
279
+ const text = userFacingErrorText(error, locale);
280
+ if (text === undefined)
281
+ return false;
282
+ if (payload instanceof RuntimeMessage) {
283
+ await bindOperationInput(payload, owner, snapshot).$reply(text);
284
+ return true;
285
+ }
286
+ const conversation = payload?.conversation;
287
+ if (!conversation)
288
+ return false;
289
+ await deliver({ conversation, requester: owner, content: text }, snapshot);
290
+ return true;
291
+ },
242
292
  };
243
293
  await index.dispatch(event, args, options);
244
294
  }
@@ -1,6 +1,6 @@
1
1
  export * from './contracts.js';
2
2
  export { EndpointRuntime } from './endpoint-runtime.js';
3
- export type { CaptureEndpointOperationInput, CapturedEndpointOperation, EndpointRuntimeDetail, EndpointRuntimeSummary, RuntimeEndpointEditInput, RuntimeEndpointMessageInput, RuntimeEndpointReactionInput, RuntimeEndpointRemoveReactionInput, RuntimeEndpointSendInput, RuntimeEndpointTypingInput, } from './endpoint-runtime.js';
3
+ export type { CaptureEndpointOperationInput, CapturedEndpointOperation, EndpointRuntimeDetail, EndpointRuntimeFailure, EndpointRuntimeSummary, EndpointRuntimePhase, RuntimeEndpointEditInput, RuntimeEndpointMessageInput, RuntimeEndpointReactionInput, RuntimeEndpointRemoveReactionInput, RuntimeEndpointSendInput, RuntimeEndpointTypingInput, } from './endpoint-runtime.js';
4
4
  export * from './inbound-spine.js';
5
5
  export * from './host/index.js';
6
6
  export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
@@ -107,7 +107,8 @@ export class MessageDispatcher {
107
107
  if (!result.owner)
108
108
  throw new Error('Matched Command is missing its owner');
109
109
  logger.debug(formatCompact({
110
- op: 'dispatch_hit',
110
+ // A UserFacingError refusal is an expected outcome, replied to the sender; logged apart.
111
+ op: result.refused ? 'dispatch_refused' : 'dispatch_hit',
111
112
  command: result.command,
112
113
  owner: result.owner,
113
114
  }));
@@ -81,5 +81,9 @@ export declare class RuntimeSceneEventStream implements RuntimeSceneEventSource
81
81
  export declare function formatConversationLog(conversation: ConversationRef): string;
82
82
  /** Content projection bounded for observer and log surfaces. */
83
83
  export declare function previewMessageContent(content: unknown): string;
84
- /** Flattens any SendContent-like value to display text; non-text segments become `[type]`. */
84
+ /**
85
+ * Flattens any SendContent-like value to display text; non-text segments become `[type]`.
86
+ * Markdown keeps its source text, buttons (keyboard rows and JSX `<button>`) become `[label]`, and
87
+ * unrendered JSX is read through its children, never serialized as an object.
88
+ */
85
89
  export declare function flattenContent(content: unknown): string;
@@ -1,4 +1,5 @@
1
1
  import { EventEmitter } from 'node:events';
2
+ import { isJsxElement } from '@zhin.js/jsx';
2
3
  import { createToken } from '@zhin.js/plugin-runtime';
3
4
  export class MessageBus {
4
5
  emitter = new EventEmitter();
@@ -84,20 +85,43 @@ export function previewMessageContent(content) {
84
85
  ? `${text.slice(0, messagePreviewLimit)}…`
85
86
  : text;
86
87
  }
87
- /** Flattens any SendContent-like value to display text; non-text segments become `[type]`. */
88
+ /**
89
+ * Flattens any SendContent-like value to display text; non-text segments become `[type]`.
90
+ * Markdown keeps its source text, buttons (keyboard rows and JSX `<button>`) become `[label]`, and
91
+ * unrendered JSX is read through its children, never serialized as an object.
92
+ */
88
93
  export function flattenContent(content) {
94
+ return flattenNode(content, 0);
95
+ }
96
+ const MAX_FLATTEN_DEPTH = 32;
97
+ function flattenNode(content, depth) {
89
98
  if (typeof content === 'string')
90
99
  return content;
91
- if (content == null)
100
+ if (content == null || typeof content === 'boolean')
101
+ return '';
102
+ if (typeof content === 'number' || typeof content === 'bigint')
103
+ return String(content);
104
+ if (depth > MAX_FLATTEN_DEPTH)
92
105
  return '';
93
106
  if (Array.isArray(content))
94
- return content.map((item) => flattenContent(item)).join('');
107
+ return content.map((item) => flattenNode(item, depth + 1)).join('');
108
+ if (isJsxElement(content))
109
+ return flattenJsx(content, depth);
95
110
  if (typeof content === 'object') {
96
111
  const record = content;
97
112
  const data = record.data;
98
113
  if (typeof record.type === 'string') {
99
114
  if (data && typeof data.text === 'string')
100
115
  return data.text;
116
+ if (record.type === 'markdown' && data && typeof data.content === 'string')
117
+ return data.content;
118
+ if (record.type === 'keyboard' && data && Array.isArray(data.rows)) {
119
+ const labels = data.rows.flatMap(row => Array.isArray(row) ? row : [])
120
+ .map(button => button && typeof button === 'object' ? button.label : undefined)
121
+ .filter((label) => typeof label === 'string' && label.length > 0);
122
+ if (labels.length)
123
+ return labels.map(label => `[${label}]`).join('');
124
+ }
101
125
  return `[${record.type}]`;
102
126
  }
103
127
  if (typeof record.text === 'string')
@@ -111,3 +135,14 @@ export function flattenContent(content) {
111
135
  }
112
136
  return String(content);
113
137
  }
138
+ function flattenJsx(element, depth) {
139
+ const props = element.props;
140
+ if (element.type === 'button') {
141
+ const label = typeof props.label === 'string' ? props.label : flattenNode(props.children, depth + 1);
142
+ return label ? `[${label}]` : '';
143
+ }
144
+ // Explicit text fallbacks (e.g. <html text="…">) describe the element better than its markup.
145
+ if (typeof props.text === 'string')
146
+ return props.text;
147
+ return flattenNode(props.children, depth + 1);
148
+ }
@@ -308,7 +308,7 @@ export function failedDeliveryReceipt(code, retryable = false) {
308
308
  status: 'failed',
309
309
  failure: Object.freeze({
310
310
  code,
311
- message: 'Outbound delivery failed.',
311
+ message: `Outbound delivery failed (${code}).`,
312
312
  ...(retryable ? { retryable: true } : {}),
313
313
  }),
314
314
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.6.0",
3
+ "version": "1.8.0",
4
4
  "description": "Zhin机器人核心框架",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -52,21 +52,21 @@
52
52
  ],
53
53
  "dependencies": {
54
54
  "qrcode": "^1.5.4",
55
- "@zhin.js/adapter": "1.1.33",
56
- "@zhin.js/command": "1.2.1",
57
- "@zhin.js/component": "1.1.17",
58
- "@zhin.js/database": "1.1.8",
59
- "@zhin.js/handler": "1.1.16",
60
- "@zhin.js/im-contract": "1.1.14",
55
+ "@zhin.js/adapter": "1.3.0",
56
+ "@zhin.js/component": "1.1.19",
57
+ "@zhin.js/handler": "1.1.18",
58
+ "@zhin.js/im-contract": "1.2.0",
61
59
  "@zhin.js/kernel": "1.1.7",
62
60
  "@zhin.js/logger": "1.1.3",
63
- "@zhin.js/middleware": "1.1.17",
64
- "@zhin.js/permission": "1.2.0",
65
- "@zhin.js/plugin-runtime": "1.2.0",
66
- "@zhin.js/schedule-feature": "1.1.16",
61
+ "@zhin.js/middleware": "1.1.19",
62
+ "@zhin.js/permission": "1.2.2",
63
+ "@zhin.js/plugin-runtime": "1.3.0",
64
+ "@zhin.js/schedule-feature": "1.1.18",
67
65
  "@zhin.js/schema": "1.1.7",
68
- "@zhin.js/jsx": "1.1.13",
69
- "@zhin.js/feature-kit": "1.1.16"
66
+ "@zhin.js/jsx": "1.1.14",
67
+ "@zhin.js/feature-kit": "1.1.18",
68
+ "@zhin.js/command": "1.3.0",
69
+ "@zhin.js/database": "1.2.0"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@types/node": "^26.1.2",