@zhin.js/core 1.10.0 → 1.11.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.
@@ -1 +1 @@
1
- export declare const interactionMessages: (locale: import("@zhin.js/plugin-runtime").Locale | undefined, key: "number" | "fallback" | "minLength" | "maxLength" | "pattern" | "integer" | "min" | "max" | "confirmOrCancel" | "select" | "invalidSelection" | "minSelections" | "maxSelections" | "minItems" | "maxItems" | "invalidNumbers" | "invalidBooleans" | "confirm" | "cancel" | "confirmation" | "selection" | "multiple" | "list" | "ended" | "denied" | "expired" | "timeout", values?: import("@zhin.js/plugin-runtime").MessageValues) => string;
1
+ export declare const interactionMessages: (locale: import("@zhin.js/plugin-runtime").Locale | undefined, key: "number" | "list" | "fallback" | "minLength" | "maxLength" | "pattern" | "integer" | "min" | "max" | "confirmOrCancel" | "select" | "invalidSelection" | "minSelections" | "maxSelections" | "minItems" | "maxItems" | "invalidNumbers" | "invalidBooleans" | "confirm" | "cancel" | "confirmation" | "selection" | "multiple" | "ended" | "denied" | "expired" | "timeout", values?: import("@zhin.js/plugin-runtime").MessageValues) => string;
@@ -59,6 +59,18 @@ export function renderKeyboardAsText(data, allocatedMap) {
59
59
  const lines = [];
60
60
  const flat = data.rows.flat();
61
61
  const entries = Object.entries(allocatedMap ?? effectiveKeyboardFallbackMap(data)).sort(([a], [b]) => Number(a) - Number(b));
62
+ if (data.fallback?.layout === 'inline' && entries.length) {
63
+ if (data.fallback.hint)
64
+ lines.push(data.fallback.hint);
65
+ lines.push(entries.map(([key, payload]) => {
66
+ const label = flat.find((b) => !b.disabled && b.payload === payload)?.label.trim() ?? '·';
67
+ return `${key}. ${label}`;
68
+ }).join(' '));
69
+ for (const button of flat)
70
+ if (button.disabled)
71
+ lines.push(`— ${button.label} (不可用)`);
72
+ return lines.join('\n');
73
+ }
62
74
  if (!entries.length) {
63
75
  lines.push('当前无可用操作。');
64
76
  }
@@ -23,6 +23,12 @@ export type ButtonData = {
23
23
  export type KeyboardFallback = {
24
24
  hint: string;
25
25
  map: Record<string, string>;
26
+ /**
27
+ * Text rendering on endpoints without buttons (`interactive: 'text'`): `list` (default) puts
28
+ * one option per line; `inline` puts the options on one line (`1. 要牌 2. 停牌 3. 放弃`) and
29
+ * prints the hint line only when it is non-empty.
30
+ */
31
+ layout?: 'list' | 'inline';
26
32
  };
27
33
  export type KeyboardSegmentData = {
28
34
  rows: ButtonData[][];
@@ -149,12 +149,39 @@ export declare function platformStandingOf(sender: unknown): PlatformStanding |
149
149
  /** `platform:admin` is met by `admin` and `owner` standings, `platform:owner` only by `owner`. */
150
150
  export declare function platformStandingIncludes(held: PlatformStandingLevel | undefined, required: 'owner' | 'admin'): boolean;
151
151
  /**
152
- * Identity + context of a message's sender. `context.conversationKey` is the conversation key, or —
153
- * when the conversation cannot be keyed (unknown kind, an id that cannot be part of a key) — the
154
- * receiving endpoint's key, so roles granted at the endpoint level and above still resolve.
155
- * Threads / topics (`conversation.threadId`) share their parent conversation's key, and a platform
156
- * container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
157
- * Undefined when not even the endpoint can be addressed.
152
+ * Why a message's sender could not be resolved for chat roles (ADR 0056 / zhinjs/zhin#1250):
153
+ * - `no-conversation`: the message carries no conversation with an endpoint id;
154
+ * - `unknown-endpoint`: that endpoint is not an account of this generation's adapters;
155
+ * - `no-adapter`: the endpoint resolves to no adapter instance alias;
156
+ * - `no-sender`: the message has no sender id;
157
+ * - `simulated-sender`: the sender id is reserved (`~…`, e.g. a Sandbox simulated sender), which never holds a role;
158
+ * - `invalid-sender`: any other sender id that cannot be a chat identity (control characters, over 256 characters).
159
+ * @public
160
+ */
161
+ export type ChatRoleSubjectFailure = 'no-conversation' | 'unknown-endpoint' | 'no-adapter' | 'no-sender' | 'simulated-sender' | 'invalid-sender';
162
+ /** @public */
163
+ export type ChatRoleSubjectResolution = Readonly<{
164
+ ok: true;
165
+ identity: ChatIdentity;
166
+ context: ChatRoleContext & {
167
+ conversationKey: string;
168
+ };
169
+ }> | Readonly<{
170
+ ok: false;
171
+ reason: ChatRoleSubjectFailure;
172
+ }>;
173
+ /**
174
+ * Identity + context of a message's sender, or why there is none. `context.conversationKey` is the
175
+ * conversation key, or — when the conversation cannot be keyed (unknown kind, an id that cannot be
176
+ * part of a key) — the receiving endpoint's key, so roles granted at the endpoint level and above
177
+ * still resolve. Threads / topics (`conversation.threadId`) share their parent conversation's key,
178
+ * and a platform container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
179
+ * @public
180
+ */
181
+ export declare function resolveChatRoleMessageContext(snapshot: ChatRoleSnapshot, message: unknown): ChatRoleSubjectResolution;
182
+ /**
183
+ * Identity + context of a message's sender ({@link resolveChatRoleMessageContext} without the
184
+ * reason). Undefined when not even the endpoint can be addressed or the sender is no chat identity.
158
185
  */
159
186
  export declare function chatRoleMessageContext(snapshot: ChatRoleSnapshot, message: unknown): {
160
187
  identity: ChatIdentity;
@@ -247,39 +247,51 @@ export function platformStandingIncludes(held, required) {
247
247
  return required === 'owner' ? held === 'owner' : held === 'owner' || held === 'admin';
248
248
  }
249
249
  /**
250
- * Identity + context of a message's sender. `context.conversationKey` is the conversation key, or —
251
- * when the conversation cannot be keyed (unknown kind, an id that cannot be part of a key) — the
252
- * receiving endpoint's key, so roles granted at the endpoint level and above still resolve.
253
- * Threads / topics (`conversation.threadId`) share their parent conversation's key, and a platform
254
- * container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
255
- * Undefined when not even the endpoint can be addressed.
250
+ * Identity + context of a message's sender, or why there is none. `context.conversationKey` is the
251
+ * conversation key, or — when the conversation cannot be keyed (unknown kind, an id that cannot be
252
+ * part of a key) — the receiving endpoint's key, so roles granted at the endpoint level and above
253
+ * still resolve. Threads / topics (`conversation.threadId`) share their parent conversation's key,
254
+ * and a platform container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
255
+ * @public
256
256
  */
257
- export function chatRoleMessageContext(snapshot, message) {
257
+ export function resolveChatRoleMessageContext(snapshot, message) {
258
+ const fail = (reason) => Object.freeze({ ok: false, reason });
258
259
  if (!record(message) || !record(message.conversation) || !record(message.conversation.endpoint))
259
- return undefined;
260
+ return fail('no-conversation');
260
261
  const conversation = message.conversation;
261
262
  if (typeof conversation.endpoint.id !== 'string')
262
- return undefined;
263
+ return fail('no-conversation');
263
264
  const key = resolveEndpointFeatureKey(snapshot, conversation.endpoint.id, typeof message.endpointId === 'string' ? message.endpointId : undefined, conversation);
264
265
  if (!key)
265
- return undefined;
266
+ return fail('unknown-endpoint');
266
267
  let adapter;
267
268
  try {
268
269
  adapter = parseFeatureResolutionKey(key).adapter;
269
270
  }
270
271
  catch {
271
- return undefined;
272
+ return fail('no-adapter');
272
273
  }
273
274
  if (!adapter)
274
- return undefined;
275
+ return fail('no-adapter');
275
276
  const parsed = parseFeatureConversationKey(key);
276
277
  const sender = record(message.sender) ? message.sender : undefined;
277
- const identity = { adapter, userId: typeof sender?.id === 'string' ? sender.id : '' };
278
+ const userId = typeof sender?.id === 'string' ? sender.id : '';
279
+ if (!userId)
280
+ return fail('no-sender');
281
+ const identity = { adapter, userId };
278
282
  if (!isChatIdentity(identity))
279
- return undefined;
283
+ return fail(userId.startsWith(RESERVED_SENDER_PREFIX) ? 'simulated-sender' : 'invalid-sender');
280
284
  const kind = parsed?.conversation.kind ?? conversation.kind;
281
285
  const platform = kind === 'private' ? undefined : platformStandingOf(sender);
282
- return { identity, context: { conversationKey: key, ...(platform ? { platform } : {}) } };
286
+ return Object.freeze({ ok: true, identity, context: { conversationKey: key, ...(platform ? { platform } : {}) } });
287
+ }
288
+ /**
289
+ * Identity + context of a message's sender ({@link resolveChatRoleMessageContext} without the
290
+ * reason). Undefined when not even the endpoint can be addressed or the sender is no chat identity.
291
+ */
292
+ export function chatRoleMessageContext(snapshot, message) {
293
+ const resolved = resolveChatRoleMessageContext(snapshot, message);
294
+ return resolved.ok ? { identity: resolved.identity, context: resolved.context } : undefined;
283
295
  }
284
296
  /**
285
297
  * Inbound sender enricher: drops any adapter-supplied `chatRole` / `chatRoleLevels`, normalizes
@@ -151,6 +151,7 @@ export const outboundSegmentJsonSchema = {
151
151
  fallback: interactiveDataObject({
152
152
  hint: { type: 'string' },
153
153
  map: { type: 'object', additionalProperties: { type: 'string' } },
154
+ layout: { type: 'string', enum: ['list', 'inline'] },
154
155
  }, ['hint', 'map']),
155
156
  }, ['rows'])),
156
157
  strictBranch('action', interactiveDataObject({
@@ -197,6 +197,54 @@ export interface OutboundMessageService {
197
197
  */
198
198
  registerInteractiveHandler(prefix: string, handler: (message: Message) => Promise<boolean> | boolean): () => void;
199
199
  }
200
+ /**
201
+ * Inbound secret guard (ADR 0060 §3.3, zhinjs/zhin#1250): recognizes a message that carries a one-time
202
+ * secret (the chat-owner claim code) before anything else sees it. A recognized message is never
203
+ * recorded in the conversation history, never handed to middlewares, handlers, commands, interaction
204
+ * prompts or the Agent, and is logged and published only as {@link InboundSecretMatch.redacted}.
205
+ */
206
+ export interface InboundSecretGuard {
207
+ match(input: Readonly<{
208
+ /** The text a command would be matched against (leading quotes and mentions dropped, trimmed). */
209
+ text: string;
210
+ /** The command prefix of this conversation (`''`: none). */
211
+ prefix: string;
212
+ conversation: ConversationRef;
213
+ snapshot: RuntimeSnapshot;
214
+ }>): InboundSecretMatch | undefined;
215
+ /**
216
+ * Whether an Endpoint event other than `message.receive` carries the secret: native platform events
217
+ * (`platform.receive` and any other side event) and canonical notices, requests (a friend or join
218
+ * request's comment) and system events. Such an event is neither recorded nor dispatched to Handlers:
219
+ * its payload is platform-shaped, so it cannot be redacted reliably. A payload too large to inspect
220
+ * completely should count as carrying it (fail closed).
221
+ */
222
+ inspectNative?(payload: unknown, event?: Readonly<{
223
+ name: string;
224
+ }>): boolean;
225
+ /**
226
+ * A notice, request or system event withheld by {@link inspectNative} was still seen on the platform
227
+ * (a join request's comment is shown to the group's admins): revoke the secret when the payload
228
+ * really carries it (not merely too large to inspect). Not called for `platform.receive`: the same
229
+ * message's `message.receive` still reaches {@link match}.
230
+ */
231
+ discardNative?(payload: unknown, event?: Readonly<{
232
+ name: string;
233
+ }>): Promise<void> | void;
234
+ }
235
+ export interface InboundSecretMatch {
236
+ /** Reported as the outcome's command (for example `claim`). */
237
+ readonly name: string;
238
+ /** What logs and the message event stream show instead of the text (for example `认领 ***`). */
239
+ readonly redacted: string;
240
+ /** Handles the message; the returned content is replied through the normal send chain by the root Plugin. */
241
+ handle(message: Message): Promise<SendContent | undefined> | SendContent | undefined;
242
+ /**
243
+ * The message is dropped before {@link handle} (not ready, another bot or one of ours posted it, dedup
244
+ * failure): a secret it carries was still seen by others, so the guard revokes it.
245
+ */
246
+ discard?(): Promise<void> | void;
247
+ }
200
248
  export interface MessageDispatchResult {
201
249
  readonly matched: boolean;
202
250
  readonly status?: 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed';
@@ -10,6 +10,7 @@ export function inboundOutcomeFacade(sink) {
10
10
  const facade = Object.freeze({
11
11
  report: (candidate) => sink.report(candidate),
12
12
  enter: (stage) => sink.enter(stage),
13
+ replied: (owner) => sink.replied?.(owner) === true,
13
14
  });
14
15
  facades.add(facade);
15
16
  return facade;
@@ -1,4 +1,5 @@
1
1
  import { MemoryConversationEventStore, conversationRefKey, messageRefKey, } from '@zhin.js/im-contract';
2
+ import { redactChatOwnerClaimText } from '@zhin.js/kernel';
2
3
  import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
3
4
  import { segmentsToPlainText } from '../../built/segment-contract/text.js';
4
5
  import { SCENE_ONLY_EVENT_TYPES, SCENE_EVENT_TEXT_MAX, clipSceneText } from '../../side-event/scene-events.js';
@@ -9,6 +10,14 @@ import { flattenContent } from './message-events.js';
9
10
  */
10
11
  export const CONVERSATION_CONTEXT_MAX_AGE_MS = 30 * 60 * 1000;
11
12
  const MAX_TRACKED_INTERACTION_ANSWERS = 1_000;
13
+ /** A text segment with any claim code replaced by `***`; other segments unchanged. */
14
+ function redactClaimSegment(segment) {
15
+ const data = segment.data;
16
+ if (segment.type !== 'text' || typeof data?.text !== 'string')
17
+ return segment;
18
+ const text = redactChatOwnerClaimText(data.text);
19
+ return text === data.text ? segment : { ...segment, data: { ...data, text } };
20
+ }
12
21
  /** Owns one ImRuntime's conversation fact store, projections, and consumer cursors. */
13
22
  export class ConversationRuntime {
14
23
  #events;
@@ -103,9 +112,10 @@ export class ConversationRuntime {
103
112
  actor: sender
104
113
  ? Object.freeze({ id: sender.id, ...(sender.name ? { displayName: sender.name } : {}) })
105
114
  : UNKNOWN_SENDER,
115
+ // Backstop (ADR 0060 §3.3): an open chat-owner claim code is stored as `***`.
106
116
  segments: Object.freeze(input.segments?.length
107
- ? [...input.segments]
108
- : [{ type: 'text', data: { text: input.content } }]),
117
+ ? input.segments.map(redactClaimSegment)
118
+ : [{ type: 'text', data: { text: redactChatOwnerClaimText(input.content) } }]),
109
119
  timestamp,
110
120
  ...(input.replyTo
111
121
  ? { replyTo: Object.freeze({ conversation: input.conversation, id: input.replyTo.id }) }
@@ -297,7 +297,7 @@ export function readStatementKind(statement, dialect) {
297
297
  * Tables the Console never changes: the gateway's `console_*` (never even read), migration
298
298
  * bookkeeping and engine catalogs. Reads of the latter are allowed.
299
299
  */
300
- const PROTECTED_TABLE = /^(?:__zhin_persistent_state|_migrations|agent_schedule_migration|sqlite_\w+|pg_\w+|information_schema|mysql|performance_schema|sys)$/;
300
+ const PROTECTED_TABLE = /^(?:__zhin_persistent_state|_migrations|agent_schedule_migration|engagement_event_migrations|sqlite_\w+|pg_\w+|information_schema|mysql|performance_schema|sys)$/;
301
301
  export function isProtectedConsoleTable(name) {
302
302
  const bare = String(name).trim().toLowerCase();
303
303
  return isGatewayOwnedTable(bare) || PROTECTED_TABLE.test(bare);
@@ -2,7 +2,7 @@ import { Scope, generationAdmissionBinder, type GenerationAdmissionGate, type Ru
2
2
  import { PermissionHost } from '@zhin.js/permission';
3
3
  import { type EndpointContentResolveContext, type EndpointEventGateway, type PeerRegistry } from '@zhin.js/adapter';
4
4
  import { type ConversationEventStore, type ConversationEventReader, type ConversationContextBlock, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
5
- import { Message, type IncomingMessage, type OutboundMessageService, type MessageSenderRef, type SendRequest } from './contracts.js';
5
+ import { Message, type IncomingMessage, type OutboundMessageService, type InboundSecretGuard, type MessageSenderRef, type SendRequest } from './contracts.js';
6
6
  import { LoginAssist } from '../../built/login-assist.js';
7
7
  import type { UserInteraction } from '@zhin.js/im-contract';
8
8
  import type { OutboundRenderer } from './outbound-renderer.js';
@@ -29,6 +29,11 @@ export interface ImRuntimeOptions {
29
29
  readonly conversationEvents?: ConversationEventStore;
30
30
  /** Process-root ingress claim (pending interaction, authentication challenge, etc.). */
31
31
  readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
32
+ /**
33
+ * Recognizes messages that carry a one-time secret (ADR 0060 §3.3: the chat-owner claim code) before
34
+ * anything records, logs or routes them; see {@link InboundSecretGuard}.
35
+ */
36
+ readonly inboundSecret?: InboundSecretGuard;
32
37
  /**
33
38
  * 探测 `inboundClaim` 这类进程级 prompt 在该 Endpoint 上、对该发送者是否有待回答项。
34
39
  * Room Router 用它把消息送到持有待回答状态的成员 Endpoint。必须同步、无副作用。
@@ -87,6 +87,7 @@ export class ImRuntime {
87
87
  return readLeasedRootResource(snapshots, input.lease, imOperationResourcesToken)?.open({ ...input, snapshots });
88
88
  },
89
89
  inboundClaim: options.inboundClaim,
90
+ ...(options.inboundSecret ? { inboundSecret: options.inboundSecret } : {}),
90
91
  originClassifier,
91
92
  deduper,
92
93
  registry,
@@ -6,6 +6,12 @@ export declare const inboundOutcomeSink: unique symbol;
6
6
  export interface InboundOutcomeSink {
7
7
  report(candidate: MessageOutcomeCandidate): boolean;
8
8
  enter(stage: MessageOutcomeStage): void;
9
+ /**
10
+ * True once a reply to this message was delivered (`status: 'sent'`); with `owner`, only a reply
11
+ * sent by that plugin counts. Lets the framework tell a middleware that answered and then stopped
12
+ * dispatch from one that dropped the message (#1250).
13
+ */
14
+ replied?(owner?: string): boolean;
9
15
  }
10
16
  /** Administrator detail: secrets masked (same patterns as the decision audit), one line, ≤ 200 chars. */
11
17
  export declare function boundedOutcomeDetail(value: unknown): string | undefined;
@@ -32,6 +38,9 @@ export declare class InboundOutcomeLedger implements InboundOutcomeSink {
32
38
  get lastStage(): MessageOutcomeStage;
33
39
  /** Current winning candidate (before settle). */
34
40
  get current(): MessageOutcomeCandidate | undefined;
41
+ /** Records one delivered reply and its author (called by the inbound reply port on `status: 'sent'`). */
42
+ noteReplyDelivered(owner?: string): void;
43
+ replied(owner?: string): boolean;
35
44
  markAddressed(addressed: boolean): void;
36
45
  linkDiagnostic(id: string | undefined): void;
37
46
  enter(stage: MessageOutcomeStage): void;
@@ -60,6 +69,11 @@ export declare class InboundOutcomeLedger implements InboundOutcomeSink {
60
69
  * @public
61
70
  */
62
71
  export declare function reportInboundOutcome(message: unknown, candidate: MessageOutcomeCandidate): boolean;
72
+ /**
73
+ * Whether a reply to this inbound message has been delivered so far (ADR 0061 §1.1); with `owner`,
74
+ * only a reply that plugin sent counts. @internal
75
+ */
76
+ export declare function inboundOutcomeReplied(message: unknown, owner?: string): boolean;
63
77
  /** Marks the stage a message is entering, for `unrecorded` diagnosis. @public */
64
78
  export declare function enterInboundOutcomeStage(message: unknown, stage: MessageOutcomeStage): void;
65
79
  /** Filters of {@link MessageOutcomeReader.list}. @public */
@@ -55,6 +55,8 @@ export class InboundOutcomeLedger {
55
55
  #best;
56
56
  #facets = [];
57
57
  #lastStage = 'ingress';
58
+ #replies = 0;
59
+ #replyOwners = new Set();
58
60
  #settled;
59
61
  constructor(init) {
60
62
  this.#init = init;
@@ -65,6 +67,15 @@ export class InboundOutcomeLedger {
65
67
  get lastStage() { return this.#lastStage; }
66
68
  /** Current winning candidate (before settle). */
67
69
  get current() { return this.#best; }
70
+ /** Records one delivered reply and its author (called by the inbound reply port on `status: 'sent'`). */
71
+ noteReplyDelivered(owner) {
72
+ if (this.#settled)
73
+ return;
74
+ this.#replies++;
75
+ if (owner)
76
+ this.#replyOwners.add(String(owner));
77
+ }
78
+ replied(owner) { return owner === undefined ? this.#replies > 0 : this.#replyOwners.has(String(owner)); }
68
79
  markAddressed(addressed) { if (addressed)
69
80
  this.#addressed = true; }
70
81
  linkDiagnostic(id) { if (id)
@@ -200,6 +211,13 @@ function stageThrow(stage) {
200
211
  export function reportInboundOutcome(message, candidate) {
201
212
  return inboundOutcomeSinkOf(message)?.report(candidate) ?? false;
202
213
  }
214
+ /**
215
+ * Whether a reply to this inbound message has been delivered so far (ADR 0061 §1.1); with `owner`,
216
+ * only a reply that plugin sent counts. @internal
217
+ */
218
+ export function inboundOutcomeReplied(message, owner) {
219
+ return inboundOutcomeSinkOf(message)?.replied?.(owner) === true;
220
+ }
203
221
  /** Marks the stage a message is entering, for `unrecorded` diagnosis. @public */
204
222
  export function enterInboundOutcomeStage(message, stage) {
205
223
  inboundOutcomeSinkOf(message)?.enter(stage);
@@ -5,7 +5,7 @@ import { type DeliveryReceipt, type UserInteraction } from '@zhin.js/im-contract
5
5
  import type { GenerationAdmissionGate, PluginId, RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
6
6
  import type { Notice } from '../../notice.js';
7
7
  import type { Request } from '../../request.js';
8
- import { RuntimeMessage, type CaptureEndpointOperationInput, type CapturedEndpointOperation, type IncomingMessage, type Message, type MessageSenderRef, type SendRequest } from './contracts.js';
8
+ import { RuntimeMessage, type CaptureEndpointOperationInput, type CapturedEndpointOperation, type IncomingMessage, type InboundSecretGuard, type Message, type MessageSenderRef, type SendRequest } from './contracts.js';
9
9
  import type { InboundDeduper } from './inbound-dedup.js';
10
10
  import type { InboundOriginClassifier } from './inbound-origin.js';
11
11
  import { type InboundInteractionPort } from './inbound-spine.js';
@@ -27,6 +27,8 @@ interface InboundRuntimeContext {
27
27
  signal: AbortSignal;
28
28
  }>): OperationResourceView | undefined;
29
29
  readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
30
+ /** One-time secrets (ADR 0060 §3.3 claim code): handled before anything records, logs or routes them. */
31
+ readonly inboundSecret?: InboundSecretGuard;
30
32
  /** Trusted origin classifier. Absent: messages carry no origin (legacy behavior). */
31
33
  readonly originClassifier?: InboundOriginClassifier;
32
34
  /** Cross-Endpoint dedup of human group messages. Absent: no dedup. */
@@ -6,14 +6,22 @@ import { requireAdapters } from './endpoint-runtime.js';
6
6
  import { arbitrateRoomInboundDeduplication, dispatchCanonicalEndpointEvent, dispatchInboundHandlers, dispatchInboundInteractive, handlers, interactionResult, isAddressedMessage, messageLocale, resolveIngressRoute, resolveRoomMembership, runInboundMiddlewareAndSpine, withEndpointEventPayload, } from './inbound-spine.js';
7
7
  import { InboundOutcomeLedger } from './inbound-outcome-ledger.js';
8
8
  import { QUIET_MESSAGE_OUTCOMES } from './message-outcome.js';
9
- import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
9
+ import { defaultCommandPrefixResolver, MessageDispatcher, normalizeCommandInputText } from './message-dispatcher.js';
10
10
  import { suggestCommandReply } from './command-suggestion.js';
11
11
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
12
12
  const logger = getLogger('im.inbound');
13
+ /** Conversations remembered for the per-minute `not_addressed` info line (bounded; cleared when full). */
14
+ const QUIET_LOG_CONVERSATIONS = 2_000;
13
15
  /** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
14
16
  export class InboundRuntime {
15
17
  context;
16
18
  #dispatcher;
19
+ /**
20
+ * zhinjs/zhin#1250 (`unaddressed-message-no-record`): the minute of the last `not_addressed` line
21
+ * logged at info per conversation. The first unaddressed message of a conversation each minute
22
+ * is logged at info (the instance log the Console shows), the rest of that minute at debug.
23
+ */
24
+ #quietLogged = new Map();
17
25
  constructor(context, commandPrefix) {
18
26
  this.context = context;
19
27
  this.#dispatcher = new MessageDispatcher(commandPrefix === undefined
@@ -111,11 +119,14 @@ export class InboundRuntime {
111
119
  ...(source.payload.message ? { message: Object.freeze({ ...source.payload.message, conversation }) } : {}),
112
120
  });
113
121
  this.context.diagnostics?.identify(conversation);
122
+ // ADR 0060 §3.3: a one-time secret is recognized before it is logged, recorded or routed.
123
+ const secret = this.#matchSecret(input, lease.value);
124
+ const visibleContent = secret ? secret.redacted : input.content;
114
125
  logger.debug(formatCompact({
115
126
  op: 'receive',
116
127
  conv: formatConversationLog(conversation),
117
128
  sender: `${input.sender?.name || 'undefined'}(${input.sender?.id || 'undefined'})`,
118
- preview: truncatePreview(input.content),
129
+ preview: truncatePreview(visibleContent),
119
130
  }));
120
131
  const enrichedSender = this.context.enrichSender
121
132
  ? this.context.enrichSender(input.sender, conversation, lease.value)
@@ -132,6 +143,8 @@ export class InboundRuntime {
132
143
  const origin = classified?.origin;
133
144
  this.context.diagnostics?.step('origin', origin ?? 'unclassified');
134
145
  if (origin === 'self') {
146
+ // One of our own accounts posted the secret where others saw it: revoke it like any drop.
147
+ await this.#discardSecret(secret);
135
148
  ledger.report({ outcome: 'ignored_self', reason: 'self_echo', stage: 'ingress' });
136
149
  this.context.diagnostics?.route('self_echo');
137
150
  logger.debug(formatCompact({
@@ -149,6 +162,7 @@ export class InboundRuntime {
149
162
  ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
150
163
  });
151
164
  if (!readiness.ready) {
165
+ await this.#discardSecret(secret);
152
166
  ledger.markAddressed(input.mentioned === true || conversation.kind === 'private');
153
167
  ledger.report({ outcome: 'dropped_unready', reason: 'venue_unready', stage: 'ingress',
154
168
  detail: readiness.unreadyEndpoints?.join(',') ?? '' });
@@ -201,8 +215,8 @@ export class InboundRuntime {
201
215
  content,
202
216
  incoming: {
203
217
  sender: enrichedSender,
204
- content: input.content,
205
- segments: input.segments,
218
+ content: visibleContent,
219
+ ...(secret ? {} : { segments: input.segments }),
206
220
  messageId: input.message?.id,
207
221
  timestamp: receivedAt,
208
222
  endpointId: input.endpointId,
@@ -214,6 +228,8 @@ export class InboundRuntime {
214
228
  const delivery = commandOperation && this.context.runCommandOperation
215
229
  ? this.context.runCommandOperation(commandOperation, deliver) : deliver();
216
230
  return Promise.resolve(delivery).then((receipt) => {
231
+ if (receipt?.status === 'sent')
232
+ ledger.noteReplyDelivered(replyRequester);
217
233
  if (receipt && receipt.status !== 'sent') {
218
234
  ledger.report({ outcome: 'delivery_failed', reason: receipt.failure?.code ?? receipt.status, stage: 'delivery',
219
235
  ...(receipt.failure?.deliveryUnknown ? { facets: ['delivery_unknown'] } : {}) });
@@ -293,7 +309,8 @@ export class InboundRuntime {
293
309
  resolveCommands: (message) => this.#dispatcher.commandEnvironment(message, lease.value),
294
310
  },
295
311
  });
296
- const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
312
+ // A secret-bearing message never enters the conversation history.
313
+ const conversationSequence = secret ? undefined : await this.context.recordIncoming(input, enrichedSender);
297
314
  let result = Object.freeze({ matched: false });
298
315
  let reply;
299
316
  ledger.markAddressed(isAddressedMessage(message));
@@ -308,19 +325,21 @@ export class InboundRuntime {
308
325
  return result;
309
326
  }
310
327
  if (recordOnly === 'dedup_error') {
328
+ await this.#discardSecret(secret);
311
329
  ledger.report({ outcome: 'dropped_dedup_error', reason: 'dedup_error', stage: 'ingress' });
312
330
  this.context.diagnostics?.route('dedup_error');
313
331
  this.context.publish({
314
332
  direction: 'inbound',
315
333
  conversation,
316
334
  ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
317
- contentPreview: previewMessageContent(input.content),
335
+ contentPreview: previewMessageContent(visibleContent),
318
336
  ...(input.message?.id ? { messageId: input.message.id } : {}),
319
337
  timestamp: receivedAt,
320
338
  });
321
339
  return result;
322
340
  }
323
341
  if (origin === 'member' || origin === 'peer_bot') {
342
+ await this.#discardSecret(secret);
324
343
  ledger.report({ outcome: 'ignored_bot', reason: origin, stage: 'ingress' });
325
344
  this.context.diagnostics?.route('bot_origin');
326
345
  logger.debug(formatCompact({
@@ -333,7 +352,28 @@ export class InboundRuntime {
333
352
  direction: 'inbound',
334
353
  conversation,
335
354
  ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
336
- contentPreview: previewMessageContent(input.content),
355
+ contentPreview: previewMessageContent(visibleContent),
356
+ ...(input.message?.id ? { messageId: input.message.id } : {}),
357
+ timestamp: receivedAt,
358
+ });
359
+ return result;
360
+ }
361
+ if (secret) {
362
+ // Handled here alone: no middleware, handler, command, interaction prompt or Agent sees it.
363
+ ledger.enter('command');
364
+ this.context.diagnostics?.route('command');
365
+ const content = await secret.handle(message);
366
+ ledger.report({ outcome: 'command_replied', reason: 'secret', stage: 'command', command: secret.name, owner: lease.value.root });
367
+ result = Object.freeze({ matched: true, status: 'executed', command: secret.name, owner: lease.value.root });
368
+ this.context.diagnostics?.dispatch(result);
369
+ await commandOperation?.stopProgress();
370
+ if (content !== undefined)
371
+ await message.$replyFrom(lease.value.root, content);
372
+ this.context.publish({
373
+ direction: 'inbound',
374
+ conversation,
375
+ ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
376
+ contentPreview: previewMessageContent(visibleContent),
337
377
  ...(input.message?.id ? { messageId: input.message.id } : {}),
338
378
  timestamp: receivedAt,
339
379
  });
@@ -406,7 +446,7 @@ export class InboundRuntime {
406
446
  direction: 'inbound',
407
447
  conversation,
408
448
  ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
409
- contentPreview: previewMessageContent(input.content),
449
+ contentPreview: previewMessageContent(visibleContent),
410
450
  ...(input.message?.id ? { messageId: input.message.id } : {}),
411
451
  timestamp: receivedAt,
412
452
  });
@@ -424,6 +464,67 @@ export class InboundRuntime {
424
464
  await close();
425
465
  }
426
466
  }
467
+ /** The guard's match for this message; a throwing guard matches nothing (logged). */
468
+ #matchSecret(input, snapshot) {
469
+ const guard = this.context.inboundSecret;
470
+ if (!guard)
471
+ return undefined;
472
+ try {
473
+ return guard.match({ text: normalizeCommandInputText(input), prefix: this.#dispatcher.prefixOf(input, snapshot),
474
+ conversation: input.conversation, snapshot });
475
+ }
476
+ catch (error) {
477
+ logger.warn(formatCompact({ op: 'inbound_secret_guard_failed', error: logSafeError(error) }));
478
+ return undefined;
479
+ }
480
+ }
481
+ /**
482
+ * ADR 0060 §3.3 (#1289 review): an Endpoint event other than a message (native platform events,
483
+ * notices, requests and their comments, system events) that carries the secret is neither recorded
484
+ * nor dispatched to Handlers.
485
+ */
486
+ #withholdSecretEvent(event) {
487
+ if (!this.#nativeCarriesSecret(event))
488
+ return false;
489
+ logger.debug(formatCompact({ op: 'native_secret_withheld', event: event.name, endpoint: String(event.endpoint.id) }));
490
+ return true;
491
+ }
492
+ #nativeCarriesSecret(event) {
493
+ const inspect = this.context.inboundSecret?.inspectNative;
494
+ if (!inspect)
495
+ return false;
496
+ try {
497
+ return inspect.call(this.context.inboundSecret, event.payload, { name: event.name }) === true;
498
+ }
499
+ catch (error) {
500
+ // Fail closed: an event that cannot be inspected is not dispatched while a secret is open.
501
+ logger.warn(formatCompact({ op: 'inbound_secret_guard_failed', error: logSafeError(error) }));
502
+ return true;
503
+ }
504
+ }
505
+ /**
506
+ * A withheld notice, request or system event was still seen on the platform (an admin reads a join
507
+ * request's comment): the guard revokes the secret it carries (#1291 review). `platform.receive` is
508
+ * not revoked here: the same message's `message.receive` still reaches the claim.
509
+ */
510
+ async #discardNativeSecret(event) {
511
+ const guard = this.context.inboundSecret;
512
+ try {
513
+ await guard?.discardNative?.(event.payload, { name: event.name });
514
+ }
515
+ catch (error) {
516
+ logger.warn(formatCompact({ op: 'inbound_secret_discard_failed', error: logSafeError(error) }));
517
+ }
518
+ }
519
+ /** A dropped message's secret is revoked; a failing guard is logged, never the message's failure. */
520
+ async #discardSecret(secret) {
521
+ try {
522
+ await secret?.discard?.();
523
+ }
524
+ catch (error) {
525
+ logger.warn(formatCompact({ op: 'inbound_secret_discard_failed', error: logSafeError(error) }));
526
+ }
527
+ }
427
528
  /** Claim resolution with the answer classification, when the coordinator offers it. */
428
529
  #resolveClaim(message) {
429
530
  const interactions = this.context.interactions;
@@ -431,6 +532,16 @@ export class InboundRuntime {
431
532
  return interactions.resolveClaimDetailed(message) || undefined;
432
533
  return interactions.resolveClaim(message) ? { answerLike: true } : undefined;
433
534
  }
535
+ /** True for the first `not_addressed` of `conv` in the minute of `at` (see {@link InboundRuntime.#quietLogged}). */
536
+ #firstQuietThisMinute(conv, at) {
537
+ const minute = Math.floor(at / 60_000);
538
+ if (this.#quietLogged.get(conv) === minute)
539
+ return false;
540
+ if (this.#quietLogged.size >= QUIET_LOG_CONVERSATIONS && !this.#quietLogged.has(conv))
541
+ this.#quietLogged.clear();
542
+ this.#quietLogged.set(conv, minute);
543
+ return true;
544
+ }
434
545
  /** Settles the ledger once (ADR 0061 §4.1); never throws over the original failure. */
435
546
  #settleOutcome(ledger, failed, failure) {
436
547
  let record;
@@ -476,13 +587,22 @@ export class InboundRuntime {
476
587
  logger.warn(formatCompact({ ...fields, op: 'inbound_outcome_unrecorded', lastStage: record.lastStage }));
477
588
  }
478
589
  else if (!record.addressed && QUIET_MESSAGE_OUTCOMES.has(record.outcome)) {
479
- logger.debug(formatCompact(fields));
590
+ if (record.outcome === 'not_addressed' && this.#firstQuietThisMinute(conv, record.settledAt)) {
591
+ logger.info(formatCompact({ ...fields, sampled: 'first_per_minute' }));
592
+ }
593
+ else {
594
+ logger.debug(formatCompact(fields));
595
+ }
480
596
  }
481
597
  else {
482
598
  logger.info(formatCompact(fields));
483
599
  }
484
600
  }
485
601
  async #receiveCanonicalEndpointEvent(source) {
602
+ if (this.#withholdSecretEvent(source)) {
603
+ await this.#discardNativeSecret(source);
604
+ return;
605
+ }
486
606
  const lease = this.context.acquire();
487
607
  let active = true;
488
608
  let endpointLease;
@@ -541,6 +661,8 @@ export class InboundRuntime {
541
661
  }
542
662
  }
543
663
  async #receiveSideEvent(event) {
664
+ if (this.#withholdSecretEvent(event))
665
+ return;
544
666
  let active = true;
545
667
  const lease = this.context.acquire();
546
668
  let endpointLease;
@@ -1,6 +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
+ import { userFacingErrorText, userFacingRefusalReason } from '@zhin.js/command';
4
4
  import { isMiddlewareIndex, middlewareFeatureId, } from '@zhin.js/middleware';
5
5
  import { createToken, projectLocaleToken, resolveLocale, userLocalePreferencesToken, } from '@zhin.js/plugin-runtime';
6
6
  import { handlerFeatureId, isHandlerIndex } from '../../feature/handler.js';
@@ -10,7 +10,7 @@ import { RuntimeRequest } from '../../request.js';
10
10
  import { RuntimeSystemEvent } from '../../system-event.js';
11
11
  import { RuntimeMessage, } from './contracts.js';
12
12
  import { formatConversationLog } from './message-events.js';
13
- import { enterInboundOutcomeStage, reportInboundOutcome } from './inbound-outcome-ledger.js';
13
+ import { enterInboundOutcomeStage, inboundOutcomeReplied, reportInboundOutcome } from './inbound-outcome-ledger.js';
14
14
  export { arbitrateRoomInboundDeduplication, buildRoomInboundRouteInput, resolveRoomMembership, } from './inbound-dedup.js';
15
15
  const logger = getLogger('im.inbound');
16
16
  /** Normalizes the legacy boolean and the structured route result. */
@@ -255,8 +255,16 @@ export async function runInboundMiddlewareAndSpine(envelope, diagnostics) {
255
255
  const outcome = isMiddlewareIndex(middleware)
256
256
  ? await middleware.runInbound(message, terminal, {
257
257
  stop: (owner) => {
258
- reportInboundOutcome(message, { outcome: 'filtered_by_policy', reason: 'middleware_stopped', stage: 'middleware',
259
- visibility: 'admin', owner });
258
+ // #1250: a middleware that answered the message itself (game input, menus) and then
259
+ // stopped dispatch handled it. A reply some other plugin sent earlier does not count:
260
+ // a stop by an owner that delivered no reply is still a policy drop.
261
+ if (inboundOutcomeReplied(message, owner)) {
262
+ reportInboundOutcome(message, { outcome: 'handler_replied', reason: 'middleware_replied', stage: 'middleware', owner });
263
+ }
264
+ else {
265
+ reportInboundOutcome(message, { outcome: 'filtered_by_policy', reason: 'middleware_stopped', stage: 'middleware',
266
+ visibility: 'admin', owner });
267
+ }
260
268
  diagnostics?.route('middleware');
261
269
  diagnostics?.step('middleware', 'stopped');
262
270
  return { dispatch: { matched: true, command: 'middleware', owner } };
@@ -444,6 +452,10 @@ export function isAddressedMessage(message, repliedToBot = false) {
444
452
  const prefix = message.commandPrefix;
445
453
  return typeof prefix === 'string' && prefix.length > 0 && message.content.trim().startsWith(prefix);
446
454
  }
455
+ function refusalReasonOf(result) {
456
+ // The same closed code shape `UserFacingError.reason` is kept to (one rule, in @zhin.js/command).
457
+ return userFacingRefusalReason(result.refusalReason);
458
+ }
447
459
  /** Maps one command dispatch fact to its outcome (ADR 0061 §1.1 / §1.2). */
448
460
  function reportCommandOutcome(message, result) {
449
461
  if (!result.matched)
@@ -465,8 +477,9 @@ function reportCommandOutcome(message, result) {
465
477
  reportInboundOutcome(message, { ...base, outcome: 'rate_limited', reason: result.limit?.reason ?? 'limited' });
466
478
  return;
467
479
  default:
480
+ // The command's own closed refusal code (UserFacingError `reason`), else the generic one.
468
481
  reportInboundOutcome(message, refused
469
- ? { ...base, outcome: 'refused', reason: 'user_facing_error' }
482
+ ? { ...base, outcome: 'refused', reason: refusalReasonOf(result) ?? 'user_facing_error' }
470
483
  : { ...base, outcome: 'command_replied', reason: result.menu ? 'menu' : 'executed' });
471
484
  }
472
485
  }
@@ -22,6 +22,10 @@ export declare const defaultCommandPrefixResolver: CommandPrefixResolver;
22
22
  export declare class MessageDispatcher {
23
23
  private readonly resolvePrefix;
24
24
  constructor(resolvePrefix?: CommandPrefixResolver);
25
+ /** The command prefix this message must carry (`''`: none). */
26
+ prefixOf(message: Pick<Message, 'conversation' | 'endpointId'> & Readonly<{
27
+ commandPrefix?: string;
28
+ }>, snapshot: RuntimeSnapshot): string;
25
29
  commandEnvironment(message: Message, snapshot: RuntimeSnapshot): Readonly<{
26
30
  prefix: string;
27
31
  menu?: string;
@@ -30,3 +34,5 @@ export declare class MessageDispatcher {
30
34
  /** @internal The inbound runtime retains reply authorship without changing command facts. */
31
35
  dispatchWithReply(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchOutcome>;
32
36
  }
37
+ /** @internal The text a command is matched against: leading quotes and mentions dropped, trimmed. */
38
+ export declare function normalizeCommandInputText(message: Pick<Message, 'content' | 'segments' | 'conversation'>): string;
@@ -59,6 +59,10 @@ export class MessageDispatcher {
59
59
  constructor(resolvePrefix = defaultCommandPrefixResolver) {
60
60
  this.resolvePrefix = resolvePrefix;
61
61
  }
62
+ /** The command prefix this message must carry (`''`: none). */
63
+ prefixOf(message, snapshot) {
64
+ return message.commandPrefix ?? this.resolvePrefix(message, snapshot);
65
+ }
62
66
  commandEnvironment(message, snapshot) {
63
67
  const prefix = this.resolvePrefix(message, snapshot);
64
68
  const commands = gatedCommandIndex(message, snapshot);
@@ -145,7 +149,8 @@ function hasTextAfterLeadingMentions(segments) {
145
149
  }
146
150
  return false;
147
151
  }
148
- function normalizeCommandInputText(message) {
152
+ /** @internal The text a command is matched against: leading quotes and mentions dropped, trimmed. */
153
+ export function normalizeCommandInputText(message) {
149
154
  const raw = message.content.trim();
150
155
  const segments = message.segments;
151
156
  if (segments && hasTextAfterLeadingMentions(segments)) {
@@ -169,7 +169,7 @@ export function applyOutboundInteractivePolicy(payload, policy, remember) {
169
169
  const data = item.data;
170
170
  const remembered = remember?.(effectiveKeyboardFallbackMap(data));
171
171
  const map = remembered && typeof remembered === 'object' && !Array.isArray(remembered) ? remembered : undefined;
172
- const projected = map ? { ...data, fallback: { hint: data.fallback?.hint ?? '', map } } : data;
172
+ const projected = map ? { ...data, fallback: { ...data.fallback, hint: data.fallback?.hint ?? '', map } } : data;
173
173
  return { type: 'text', data: { text: renderKeyboardAsText(projected, map) } };
174
174
  });
175
175
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.10.0",
3
+ "version": "1.11.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.3.2",
56
- "@zhin.js/command": "1.3.1",
57
- "@zhin.js/component": "1.1.19",
55
+ "@zhin.js/adapter": "1.3.3",
56
+ "@zhin.js/command": "1.4.0",
57
+ "@zhin.js/component": "1.2.0",
58
58
  "@zhin.js/database": "1.2.2",
59
+ "@zhin.js/handler": "1.1.20",
59
60
  "@zhin.js/im-contract": "1.3.0",
60
- "@zhin.js/kernel": "1.2.0",
61
+ "@zhin.js/kernel": "1.3.0",
61
62
  "@zhin.js/logger": "1.3.0",
62
- "@zhin.js/middleware": "1.1.19",
63
- "@zhin.js/permission": "1.2.2",
64
- "@zhin.js/plugin-runtime": "1.3.0",
65
- "@zhin.js/schedule-feature": "1.1.18",
63
+ "@zhin.js/middleware": "1.1.20",
64
+ "@zhin.js/permission": "1.2.3",
65
+ "@zhin.js/plugin-runtime": "1.4.0",
66
+ "@zhin.js/schedule-feature": "1.1.19",
66
67
  "@zhin.js/schema": "1.1.7",
67
68
  "@zhin.js/jsx": "1.1.15",
68
- "@zhin.js/feature-kit": "1.1.18",
69
- "@zhin.js/handler": "1.1.19"
69
+ "@zhin.js/feature-kit": "1.1.19"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@types/node": "^26.1.2",