@zhin.js/core 1.7.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.
- package/lib/built/interactive-segments/types.d.ts +6 -0
- package/lib/built/user-interaction.d.ts +3 -1
- package/lib/built/user-interaction.js +2 -0
- package/lib/feature/command-public-api.d.ts +1 -1
- package/lib/feature/command-public-api.js +1 -1
- package/lib/plugin-runtime/im/command-suggestion.d.ts +13 -0
- package/lib/plugin-runtime/im/command-suggestion.js +32 -0
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +28 -1
- package/lib/plugin-runtime/im/endpoint-runtime.js +23 -4
- package/lib/plugin-runtime/im/inbound-runtime.js +2 -0
- package/lib/plugin-runtime/im/inbound-spine.d.ts +6 -1
- package/lib/plugin-runtime/im/inbound-spine.js +51 -1
- package/lib/plugin-runtime/im/index.d.ts +1 -1
- package/lib/plugin-runtime/im/message-dispatcher.js +2 -1
- package/lib/plugin-runtime/im/message-events.d.ts +5 -1
- package/lib/plugin-runtime/im/message-events.js +38 -3
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +1 -1
- package/package.json +13 -13
|
@@ -27,6 +27,12 @@ export type KeyboardFallback = {
|
|
|
27
27
|
export type KeyboardSegmentData = {
|
|
28
28
|
rows: ButtonData[][];
|
|
29
29
|
fallback?: KeyboardFallback;
|
|
30
|
+
/**
|
|
31
|
+
* Optional presentation marker set by the Host (`UserInteractionRequest.purpose`):
|
|
32
|
+
* `approval` = a human approval prompt. Surfaces that understand it (Sandbox Console)
|
|
33
|
+
* label the card; every other renderer ignores it.
|
|
34
|
+
*/
|
|
35
|
+
purpose?: 'approval';
|
|
30
36
|
};
|
|
31
37
|
export type ActionSegmentData = {
|
|
32
38
|
id: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Locale } from '@zhin.js/plugin-runtime';
|
|
2
|
-
import type { UserInteractionContent, UserInteractionRequest } from '@zhin.js/im-contract';
|
|
2
|
+
import type { UserInteractionContent, UserInteractionPurpose, 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 {
|
|
@@ -9,6 +9,8 @@ export interface UserInteractionAction {
|
|
|
9
9
|
}
|
|
10
10
|
export interface UserInteractionView extends UserInteractionContent {
|
|
11
11
|
readonly actions?: readonly UserInteractionAction[];
|
|
12
|
+
/** Copied from the request; rendered as keyboard `data.purpose` so surfaces can label approvals. */
|
|
13
|
+
readonly purpose?: UserInteractionPurpose;
|
|
12
14
|
}
|
|
13
15
|
export interface UserInteractionProgress extends UserInteractionContent {
|
|
14
16
|
readonly index: number;
|
|
@@ -61,6 +61,7 @@ export function renderUserInteraction(view, actionPayload = (value) => value, lo
|
|
|
61
61
|
{
|
|
62
62
|
type: 'keyboard',
|
|
63
63
|
data: {
|
|
64
|
+
...(view.purpose ? { purpose: view.purpose } : {}),
|
|
64
65
|
rows: chunk(buttons, 5),
|
|
65
66
|
fallback: {
|
|
66
67
|
hint: t(locale, 'fallback'),
|
|
@@ -92,6 +93,7 @@ export function projectUserInteraction(request, progress, locale = 'zh-CN') {
|
|
|
92
93
|
: stepDescription || undefined,
|
|
93
94
|
tip: [request.tip, instruction, progress?.tip].filter(Boolean).join('\n'),
|
|
94
95
|
...(actions ? { actions: Object.freeze(actions) } : {}),
|
|
96
|
+
...(request.purpose ? { purpose: request.purpose } : {}),
|
|
95
97
|
});
|
|
96
98
|
}
|
|
97
99
|
/** Parse and validate one user reply without transport knowledge. */
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
* Command authoring and Root-selected IM presentation contracts.
|
|
3
3
|
* @module zhin.js/command
|
|
4
4
|
*/
|
|
5
|
-
export { defineCommand, commandFeedbackToken, commandMenuPresentationToken, type CommandContext, type CommandConversation, type CommandDefiner, type CommandDefinition, type CommandMessage, type CommandParameterDefinition, type CommandParamSchema, type CommandScene, type CommandSegment, type CommandSender, type CommandSession, type CommandDynamicValue, type CommandParameterType, type CommandParameterValue, type CommandExecutionPolicy, type CommandExecutionLimit, type CommandParams, type CommandOptions, type CommandOptionSchema, type InferCommandParams, type InferCommandOptions, type CommandFeedback, type CommandFeedbackContext, type CommandFeedbackRenderer, type CommandMenuPresentationInput, type CommandMenuPresenter, type CommandMenuPage, type CommandMenuNavigation, type CommandMenuEntry, type CommandMenuAppearance, type CommandValidationIssue, } from './command.js';
|
|
5
|
+
export { defineCommand, commandFeedbackToken, commandMenuPresentationToken, UserFacingError, isUserFacingError, type CommandContext, type CommandConversation, type CommandDefiner, type CommandDefinition, type CommandMessage, type CommandParameterDefinition, type CommandParamSchema, type CommandScene, type CommandSegment, type CommandSender, type CommandSession, type CommandDynamicValue, type CommandParameterType, type CommandParameterValue, type CommandExecutionPolicy, type CommandExecutionLimit, type CommandParams, type CommandOptions, type CommandOptionSchema, type InferCommandParams, type InferCommandOptions, type CommandFeedback, type CommandFeedbackContext, type CommandFeedbackRenderer, type CommandMenuPresentationInput, type CommandMenuPresenter, type CommandMenuPage, type CommandMenuNavigation, type CommandMenuEntry, type CommandMenuAppearance, type CommandValidationIssue, } from './command.js';
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
* Command authoring and Root-selected IM presentation contracts.
|
|
3
3
|
* @module zhin.js/command
|
|
4
4
|
*/
|
|
5
|
-
export { defineCommand, commandFeedbackToken, commandMenuPresentationToken, } from './command.js';
|
|
5
|
+
export { defineCommand, commandFeedbackToken, commandMenuPresentationToken, UserFacingError, isUserFacingError, } from './command.js';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import type { Message } from './contracts.js';
|
|
3
|
+
/**
|
|
4
|
+
* "No such command, did you mean …" for a message that did not route (issue #1250).
|
|
5
|
+
*
|
|
6
|
+
* Only a message addressed to the Bot (private chat, an @mention of the Bot, or a configured
|
|
7
|
+
* command prefix the message uses) is considered, so ambient group chat that merely starts
|
|
8
|
+
* with a word resembling a command is left alone. The reply goes out through the ordinary
|
|
9
|
+
* inbound reply path (`$replyFrom`), never a parallel send. Without a configured prefix the
|
|
10
|
+
* message must also be short and command-like (no question words or marks), and namespace
|
|
11
|
+
* matches (`rss …` for `rss-list`) are off, so questions like `rss 是什么` still reach the AI.
|
|
12
|
+
*/
|
|
13
|
+
export declare function suggestCommandReply(message: Message, snapshot: RuntimeSnapshot, prefix: string): Promise<string | undefined>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { gatedCommandIndex } from './feature-gate.js';
|
|
2
|
+
/**
|
|
3
|
+
* "No such command, did you mean …" for a message that did not route (issue #1250).
|
|
4
|
+
*
|
|
5
|
+
* Only a message addressed to the Bot (private chat, an @mention of the Bot, or a configured
|
|
6
|
+
* command prefix the message uses) is considered, so ambient group chat that merely starts
|
|
7
|
+
* with a word resembling a command is left alone. The reply goes out through the ordinary
|
|
8
|
+
* inbound reply path (`$replyFrom`), never a parallel send. Without a configured prefix the
|
|
9
|
+
* message must also be short and command-like (no question words or marks), and namespace
|
|
10
|
+
* matches (`rss …` for `rss-list`) are off, so questions like `rss 是什么` still reach the AI.
|
|
11
|
+
*/
|
|
12
|
+
export async function suggestCommandReply(message, snapshot, prefix) {
|
|
13
|
+
const commands = gatedCommandIndex(message, snapshot);
|
|
14
|
+
if (!commands)
|
|
15
|
+
return undefined;
|
|
16
|
+
let text = message.content.trim();
|
|
17
|
+
if (message.conversation.kind !== 'private')
|
|
18
|
+
text = text.replace(/^(?:@\S+\s+)+/u, '').trim();
|
|
19
|
+
if (prefix) {
|
|
20
|
+
if (!text.startsWith(prefix))
|
|
21
|
+
return undefined;
|
|
22
|
+
text = text.slice(prefix.length).trim();
|
|
23
|
+
}
|
|
24
|
+
else if (message.conversation.kind !== 'private' && message.mentioned !== true) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
if (!text)
|
|
28
|
+
return undefined;
|
|
29
|
+
// Only a message that used the configured prefix is an explicit command attempt; private
|
|
30
|
+
// chat and @mentions without one are often questions for the AI (`rss 是什么`).
|
|
31
|
+
return commands.suggestReply(text, { source: message, commandPrefix: prefix, explicitPrefix: prefix.length > 0, snapshot });
|
|
32
|
+
}
|
|
@@ -5,6 +5,19 @@ import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type Ad
|
|
|
5
5
|
import type { LoginFlowSnapshot } from '../../built/login-assist.js';
|
|
6
6
|
import { type DeliveryTarget, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
|
|
7
7
|
import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
|
|
8
|
+
/**
|
|
9
|
+
* Adapter phase plus `awaiting_assist`: the account is starting and its login flow waits for a
|
|
10
|
+
* person (LoginAssist challenge).
|
|
11
|
+
*/
|
|
12
|
+
export type EndpointRuntimePhase = AdapterEndpointPhase | 'awaiting_assist';
|
|
13
|
+
/** Console `lastError` of an account (same shape as the MCP client failure). */
|
|
14
|
+
export interface EndpointRuntimeFailure {
|
|
15
|
+
readonly category: 'auth' | 'network' | 'timeout' | 'config' | 'process_exit' | 'unknown';
|
|
16
|
+
/** Redacted, ≤ 200 characters. */
|
|
17
|
+
readonly message: string;
|
|
18
|
+
/** Epoch milliseconds. */
|
|
19
|
+
readonly at: number;
|
|
20
|
+
}
|
|
8
21
|
export interface EndpointRuntimeSummary {
|
|
9
22
|
readonly id: string;
|
|
10
23
|
readonly endpoint: ConversationRef['endpoint'];
|
|
@@ -16,9 +29,23 @@ export interface EndpointRuntimeSummary {
|
|
|
16
29
|
readonly transportState: EndpointTransportState | 'unknown';
|
|
17
30
|
readonly eventDiagnostics: AdapterEndpointSummary['eventDiagnostics'];
|
|
18
31
|
readonly status: 'online' | 'offline';
|
|
19
|
-
readonly phase:
|
|
32
|
+
readonly phase: EndpointRuntimePhase;
|
|
20
33
|
readonly operations: readonly AdapterOperation[];
|
|
21
34
|
readonly managementCapabilities: readonly EndpointManagementCapability[];
|
|
35
|
+
/** Start attempts of the background start supervision (0 = none pending). */
|
|
36
|
+
readonly startAttempt: number;
|
|
37
|
+
/** Last failed start (code only) while the account is not online. */
|
|
38
|
+
readonly startFailure?: Readonly<{
|
|
39
|
+
code: string;
|
|
40
|
+
at: number;
|
|
41
|
+
}>;
|
|
42
|
+
/** Epoch milliseconds of the next automatic start retry. */
|
|
43
|
+
readonly nextRetryAt?: number;
|
|
44
|
+
/**
|
|
45
|
+
* Classified, redacted reason of the last failed start while the account is not online (#1250);
|
|
46
|
+
* the Adapter masks credentials before it records the message.
|
|
47
|
+
*/
|
|
48
|
+
readonly lastError?: EndpointRuntimeFailure;
|
|
22
49
|
/** ADR 0058: an unfinished login flow of this Endpoint waits for a person. */
|
|
23
50
|
readonly pendingLogin: boolean;
|
|
24
51
|
/** ADR 0058: where the unfinished login flow is (1-based step of the timeline). */
|
|
@@ -24,9 +24,10 @@ export class EndpointRuntime {
|
|
|
24
24
|
transportState: row.transportState,
|
|
25
25
|
eventDiagnostics: row.eventDiagnostics,
|
|
26
26
|
status: row.status,
|
|
27
|
-
phase: row.
|
|
27
|
+
phase: runtimePhase(flows, row, adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name),
|
|
28
28
|
operations: row.operations,
|
|
29
29
|
managementCapabilities: row.managementCapabilities,
|
|
30
|
+
...startFacts(row),
|
|
30
31
|
})), Object.freeze([]));
|
|
31
32
|
}
|
|
32
33
|
capabilities(input) {
|
|
@@ -56,9 +57,10 @@ export class EndpointRuntime {
|
|
|
56
57
|
transportState: row.transportState,
|
|
57
58
|
eventDiagnostics: row.eventDiagnostics,
|
|
58
59
|
status: row.status,
|
|
59
|
-
phase: row.
|
|
60
|
+
phase: runtimePhase(flows, row, adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name),
|
|
60
61
|
operations: row.operations,
|
|
61
62
|
managementCapabilities: row.managementCapabilities,
|
|
63
|
+
...startFacts(row),
|
|
62
64
|
});
|
|
63
65
|
}, null);
|
|
64
66
|
}
|
|
@@ -420,10 +422,27 @@ function assertSameEndpoint(expected, actual) {
|
|
|
420
422
|
}
|
|
421
423
|
}
|
|
422
424
|
/** ADR 0058: pending-login facts of one Endpoint row from the latest login flows. */
|
|
423
|
-
function
|
|
424
|
-
|
|
425
|
+
function loginFlowOf(flows, row, adapter) {
|
|
426
|
+
return flows.find((item) => item.endpointIdentity?.canonicalId === String(row.id))
|
|
425
427
|
?? flows.find((item) => !item.endpointIdentity && item.adapter === adapter
|
|
426
428
|
&& (item.endpointKey === row.name || item.endpointKey === String(row.id)));
|
|
429
|
+
}
|
|
430
|
+
/** A starting account whose login flow is active waits for a person, not for the platform. */
|
|
431
|
+
function runtimePhase(flows, row, adapter) {
|
|
432
|
+
return row.phase === 'starting' && loginFlowOf(flows, row, adapter)?.state === 'active' ? 'awaiting_assist' : row.phase;
|
|
433
|
+
}
|
|
434
|
+
function startFacts(row) {
|
|
435
|
+
const failure = row.startFailure;
|
|
436
|
+
return {
|
|
437
|
+
startAttempt: row.startAttempt ?? 0,
|
|
438
|
+
...(failure ? { startFailure: Object.freeze({ code: failure.code, at: failure.at }) } : {}),
|
|
439
|
+
...(failure ? { lastError: Object.freeze({ category: failure.category ?? 'unknown',
|
|
440
|
+
message: (failure.message ?? failure.code).slice(0, 200), at: failure.at }) } : {}),
|
|
441
|
+
...(row.nextRetryAt !== undefined ? { nextRetryAt: row.nextRetryAt } : {}),
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
function loginFacts(flows, row, adapter, declaration) {
|
|
445
|
+
const flow = loginFlowOf(flows, row, adapter);
|
|
427
446
|
const unfinished = !!flow && (flow.state === 'active' || flow.state === 'expired');
|
|
428
447
|
const index = unfinished && flow.currentStep ? flow.steps.findIndex((step) => step.id === flow.currentStep) : -1;
|
|
429
448
|
return {
|
|
@@ -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
|
-
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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) =>
|
|
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:
|
|
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.
|
|
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/
|
|
56
|
-
"@zhin.js/component": "1.1.
|
|
57
|
-
"@zhin.js/
|
|
58
|
-
"@zhin.js/
|
|
59
|
-
"@zhin.js/adapter": "1.1.34",
|
|
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",
|
|
60
59
|
"@zhin.js/kernel": "1.1.7",
|
|
61
60
|
"@zhin.js/logger": "1.1.3",
|
|
62
|
-
"@zhin.js/
|
|
63
|
-
"@zhin.js/
|
|
64
|
-
"@zhin.js/plugin-runtime": "1.
|
|
65
|
-
"@zhin.js/schedule-feature": "1.1.
|
|
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",
|
|
66
65
|
"@zhin.js/schema": "1.1.7",
|
|
67
|
-
"@zhin.js/
|
|
68
|
-
"@zhin.js/
|
|
69
|
-
"@zhin.js/
|
|
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",
|