@zhin.js/core 1.9.0 → 1.10.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.
@@ -8,6 +8,8 @@ import { RuntimeMessage, interactionOperationScope, operationEndpoint, } from '.
8
8
  import { actionPayloadFromSegments, isJsxButtonPayload, isPluginIncarnationAlive, JsxButtonRegistry, RuntimeInteractiveRouter, } from './interactive-router.js';
9
9
  export { isPluginIncarnationAlive } from './interactive-router.js';
10
10
  const ASK_ACTION_PREFIX = 'zhin:ask:';
11
+ /** Claim subject of a prompt that anyone in the conversation may answer (`answeredBy: 'anyone'`). */
12
+ const ANYONE_SUBJECT = '\u0000anyone';
11
13
  class UserInteractionTimeoutError extends Error {
12
14
  constructor(message) {
13
15
  super(message);
@@ -88,8 +90,14 @@ export class RuntimeInteractionCoordinator {
88
90
  return this.#buttons.prepare(request, snapshot);
89
91
  }
90
92
  resolveClaim(message, snapshot) {
93
+ return this.resolveClaimDetailed(message, snapshot) !== false;
94
+ }
95
+ /** {@link resolveClaim} plus whether the text was answer-like (ADR 0061 `interaction_answered` / `interaction_consumed`). */
96
+ resolveClaimDetailed(message, snapshot) {
91
97
  const effectiveSnapshot = snapshot ?? (message instanceof RuntimeMessage ? message[interactionOperationScope]()?.snapshot : undefined);
92
- const claim = this.#claims.get(this.#conversationKey(message));
98
+ const own = this.#claims.get(this.#conversationKey(message));
99
+ const claim = own?.isLiveFor(message.generation, effectiveSnapshot)
100
+ ? own : this.#claims.get(this.#conversationKey(message, ANYONE_SUBJECT)) ?? own;
93
101
  const claimLive = claim?.isLiveFor(message.generation, effectiveSnapshot) === true;
94
102
  if (claim && !claimLive && effectiveSnapshot && claim.incarnation && !isPluginIncarnationAlive(claim.incarnation, effectiveSnapshot)) {
95
103
  claim.reject(new Error('User interaction operation retired'));
@@ -111,15 +119,25 @@ export class RuntimeInteractionCoordinator {
111
119
  return false;
112
120
  if (!claim || !claimLive)
113
121
  return false;
122
+ const taken = (raw, action) => {
123
+ let answerLike = true;
124
+ try {
125
+ answerLike = claim.classify?.(raw, action) ?? true;
126
+ }
127
+ catch {
128
+ answerLike = false;
129
+ }
130
+ return claim.accept(raw, action) ? Object.freeze({ answerLike, ...(claim.owner ? { owner: claim.owner } : {}) }) : false;
131
+ };
114
132
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
115
133
  const answer = claim.actions.get(payload);
116
134
  if (answer !== undefined)
117
- return claim.accept(answer, true);
135
+ return taken(answer, true);
118
136
  // Native stale callbacks never answer a new question. Plain text remains
119
137
  // the current question's input even if an old fallback once used its label.
120
- return explicit ? false : claim.accept(message.content);
138
+ return explicit ? false : taken(message.content, false);
121
139
  }
122
- return claim.accept(payload ?? message.content);
140
+ return taken(payload ?? message.content, false);
123
141
  }
124
142
  /**
125
143
  * Probe used by Room routing: is this message the answer to something pending on this exact
@@ -128,7 +146,9 @@ export class RuntimeInteractionCoordinator {
128
146
  * alone does not count. Changes no state.
129
147
  */
130
148
  hasPendingAnswer(conversation, senderId, generation, input, snapshot) {
131
- const claim = this.#claims.get(`${conversationRefKey(conversation)}:${senderId}`);
149
+ const own = this.#claims.get(`${conversationRefKey(conversation)}:${senderId}`);
150
+ const claim = own?.isLiveFor(generation, snapshot) ? own
151
+ : this.#claims.get(`${conversationRefKey(conversation)}:${ANYONE_SUBJECT}`) ?? own;
132
152
  const explicit = actionPayloadFromSegments(input?.segments);
133
153
  if (explicit?.startsWith(ASK_ACTION_PREFIX)
134
154
  && (!claim?.isLiveFor(generation, snapshot) || !claim.actions.has(explicit)))
@@ -184,26 +204,35 @@ export class RuntimeInteractionCoordinator {
184
204
  const deadline = Date.now() + timeout;
185
205
  const view = projectUserInteraction(request, progress, locale);
186
206
  let prompt = view;
207
+ // ADR 0061 decision 11: after an invalid answer the prompt is sent again at most once;
208
+ // later invalid answers keep waiting silently until the deadline.
209
+ let invalidAnswers = 0;
210
+ const classify = (raw, action) => parseUserInteractionAnswer(request, raw, locale, action).ok;
211
+ const answeredBy = request.answeredBy === 'anyone' ? ANYONE_SUBJECT : undefined;
187
212
  while (true) {
188
- const claim = this.#reserveClaim({ deadline, timeoutText, prompt, locale, actions: view.actions }, {
189
- conversation: source.conversation, subjectId: subjectId ?? source.sender?.id ?? '',
213
+ const claim = this.#reserveClaim({ deadline, timeoutText, prompt, locale, actions: view.actions, classify,
214
+ ...(operation?.owner ? { owner: String(operation.owner) } : {}) }, {
215
+ conversation: source.conversation, subjectId: answeredBy ?? subjectId ?? source.sender?.id ?? '',
190
216
  generation: source.generation, signal: request.signal, operation, source: retained,
191
217
  });
192
218
  try {
193
219
  claim.check();
194
- const actions = [...claim.actions.keys()];
195
- const receipt = await reply(renderUserInteraction(prompt, (_value, index) => actions[index], locale));
196
- assertLifetime();
197
- if (receipt.status !== 'sent')
198
- throw new UserInteractionDeliveryError(receipt);
220
+ if (invalidAnswers <= 1) {
221
+ const actions = [...claim.actions.keys()];
222
+ const receipt = await reply(renderUserInteraction(prompt, (_value, index) => actions[index], locale));
223
+ assertLifetime();
224
+ if (receipt.status !== 'sent')
225
+ throw new UserInteractionDeliveryError(receipt);
226
+ if (receipt.message)
227
+ this.#markPrompt?.(receipt.message);
228
+ }
199
229
  claim.delivered();
200
- if (receipt.message)
201
- this.#markPrompt?.(receipt.message);
202
230
  const raw = await claim.answer;
203
231
  claim.check();
204
232
  const result = parseUserInteractionAnswer(request, raw.value, locale, raw.action);
205
233
  if (result.ok)
206
234
  return result.value;
235
+ invalidAnswers += 1;
207
236
  prompt = {
208
237
  ...view,
209
238
  tip: [request.invalidText ?? result.message, view.tip].filter(Boolean).join('\n'),
@@ -325,6 +354,8 @@ export class RuntimeInteractionCoordinator {
325
354
  ...(incarnation ? { incarnation } : {}),
326
355
  isLiveFor,
327
356
  actions: answers,
357
+ ...(request.classify ? { classify: request.classify } : {}),
358
+ ...(request.owner ? { owner: request.owner } : {}),
328
359
  answer,
329
360
  accept: (raw, action = false) => {
330
361
  if (failure || buffered !== undefined)
@@ -1,6 +1,16 @@
1
1
  import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
2
2
  import type { RuntimeMessageRendering } from './message-events.js';
3
3
  import type { CommandExecutionLimit } from '@zhin.js/command';
4
+ import type { MessageOutcome, MessageOutcomeRecord } from './message-outcome.js';
5
+ /** The settled outcome as the 15-minute diagnostics timeline shows it (ADR 0061 §2). */
6
+ export interface RuntimeMessageDiagnosticOutcome {
7
+ readonly id: string;
8
+ readonly outcome: MessageOutcome;
9
+ readonly reason?: string;
10
+ readonly stage: MessageOutcomeRecord['stage'];
11
+ readonly addressed: boolean;
12
+ readonly facets: readonly string[];
13
+ }
4
14
  export interface RuntimeMessageDiagnosticStep {
5
15
  readonly stage: 'received' | 'origin' | 'prefix' | 'middleware' | 'handlers' | 'dispatch' | 'delivery';
6
16
  readonly status: 'accepted' | 'human' | 'member' | 'peer_bot' | 'self' | 'unclassified' | 'matched' | 'mismatch' | 'empty_input' | 'commands_unavailable' | 'started' | 'entered' | 'stopped' | 'replaced' | 'completed' | 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed' | 'interaction' | 'middleware' | 'command' | 'agent' | 'self_echo' | 'duplicate' | 'bot_origin' | 'dedup_error' | 'sent' | 'failed' | 'unsupported' | 'rejected' | 'suppressed' | 'unknown';
@@ -26,6 +36,8 @@ export interface RuntimeMessageDiagnostic {
26
36
  readonly command?: string;
27
37
  readonly dispatchStatus?: 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed';
28
38
  readonly limit?: CommandExecutionLimit;
39
+ /** ADR 0061: the message's settled outcome (absent while processing). */
40
+ readonly outcome?: RuntimeMessageDiagnosticOutcome;
29
41
  /** Some evidence exceeded the per-operation bound; the record is not a complete timeline. */
30
42
  readonly truncated: boolean;
31
43
  readonly steps: readonly RuntimeMessageDiagnosticStep[];
@@ -59,6 +71,10 @@ export declare class RuntimeMessageDiagnostics implements RuntimeMessageDiagnost
59
71
  status?: RuntimeMessageDiagnostic['dispatchStatus'];
60
72
  limit?: CommandExecutionLimit;
61
73
  }>): void;
74
+ /** Id of the current operation's record, linked from the outcome record. */
75
+ currentId(): string | undefined;
76
+ /** Attaches the settled outcome (ADR 0061 §2) to the current operation's record. */
77
+ outcome(record: MessageOutcomeRecord): void;
62
78
  route(route: NonNullable<RuntimeMessageDiagnostic['route']>): void;
63
79
  delivery(generation: number, conversation: ConversationRef, receipt: DeliveryReceipt, rendering?: RuntimeMessageRendering): void;
64
80
  list(options?: Readonly<{
@@ -83,6 +83,18 @@ export class RuntimeMessageDiagnostics {
83
83
  ...(result.limit.retryAfterMs !== undefined ? { retryAfterMs: result.limit.retryAfterMs } : {}) });
84
84
  this.step('dispatch', result.status ?? record.route);
85
85
  }
86
+ /** Id of the current operation's record, linked from the outcome record. */
87
+ currentId() {
88
+ return this.#current()?.id;
89
+ }
90
+ /** Attaches the settled outcome (ADR 0061 §2) to the current operation's record. */
91
+ outcome(record) {
92
+ const current = this.#current();
93
+ if (!current)
94
+ return;
95
+ current.outcome = Object.freeze({ id: record.id, outcome: record.outcome, ...(record.reason ? { reason: record.reason } : {}),
96
+ stage: record.stage, addressed: record.addressed, facets: Object.freeze([...record.facets]) });
97
+ }
86
98
  route(route) {
87
99
  const record = this.#current();
88
100
  if (record)
@@ -0,0 +1,97 @@
1
+ /**
2
+ * ADR 0061 §1: every inbound message ends with exactly one outcome. This module holds the closed
3
+ * code table (append-only: deprecated codes stay), the priority order used when one message
4
+ * collects several candidates, the default visibility / reply per code and the zh-CN / en
5
+ * templates shown to the sender and to administrators.
6
+ */
7
+ import type { ConversationRef } from '@zhin.js/im-contract';
8
+ import type { Locale, PluginId } from '@zhin.js/plugin-runtime';
9
+ /** Outcome codes (ADR 0061 §1.1–§1.6). Snake case, append-only. @public */
10
+ export declare const MESSAGE_OUTCOMES: readonly ["replied", "command_replied", "handler_replied", "interaction_answered", "suggested", "refused", "invalid_input", "permission_denied", "rate_limited", "approval_denied", "approval_timeout", "approval_unavailable", "tool_failed_reported", "model_timeout", "model_error", "budget_exhausted", "not_addressed", "feature_disabled", "ambient_silent", "model_silent", "merged", "superseded", "cleared", "interaction_consumed", "filtered_by_policy", "media_rejected", "ignored_self", "ignored_bot", "dropped_duplicate", "dropped_unready", "dropped_dedup_error", "dropped_retired", "delivery_failed", "internal_error", "unrecorded"];
11
+ /** @public */
12
+ export type MessageOutcome = typeof MESSAGE_OUTCOMES[number];
13
+ /** Where an outcome was decided (ADR 0061 §2 `stage`). @public */
14
+ export declare const MESSAGE_OUTCOME_STAGES: readonly ["ingress", "interaction", "middleware", "handlers", "command", "suggestion", "agent_gate", "ambient", "admission", "model", "tool", "delivery"];
15
+ /** @public */
16
+ export type MessageOutcomeStage = typeof MESSAGE_OUTCOME_STAGES[number];
17
+ /** Who may read the human-readable reason: the sender, administrators only, or the replay only. @public */
18
+ export type MessageOutcomeVisibility = 'sender' | 'admin' | 'replay';
19
+ /** Whether the bot said something in chat: `yes`, `no` (by design) or `throttled` (at most once per minute). @public */
20
+ export type MessageOutcomeReply = 'yes' | 'no' | 'throttled';
21
+ /** One candidate reported while the message is processed; the ledger keeps the highest. @public */
22
+ export interface MessageOutcomeCandidate {
23
+ readonly outcome: MessageOutcome;
24
+ /** Closed sub-reason; existing codes (command status, decision reason codes, `ProviderErrorKind`) are reused. */
25
+ readonly reason?: string;
26
+ readonly stage: MessageOutcomeStage;
27
+ readonly visibility?: MessageOutcomeVisibility;
28
+ readonly reply?: MessageOutcomeReply;
29
+ readonly command?: string;
30
+ readonly owner?: PluginId | string;
31
+ readonly turnId?: string;
32
+ readonly mergedInto?: string;
33
+ readonly errorId?: string;
34
+ /** Administrator-only detail; redacted and cut to 200 characters before it is kept. */
35
+ readonly detail?: string;
36
+ /** Extra codes kept beside the winning outcome (for example `media_rejected:too_large`). */
37
+ readonly facets?: readonly string[];
38
+ }
39
+ /** The settled outcome of one inbound message. No message body is kept (ADR 0061 §2). @public */
40
+ export interface MessageOutcomeRecord {
41
+ readonly id: string;
42
+ readonly receivedAt: number;
43
+ readonly settledAt: number;
44
+ readonly generation?: number;
45
+ readonly conversation: ConversationRef;
46
+ /** Platform (client adapter) and `<scope>:<sceneId>`, the same as `ai_decision_events`. */
47
+ readonly platform: string;
48
+ readonly sceneId: string;
49
+ readonly senderId?: string;
50
+ readonly messageId?: string;
51
+ /** Private chat, mention, command prefix, or a reply to the bot (ADR 0061 §1). */
52
+ readonly addressed: boolean;
53
+ readonly outcome: MessageOutcome;
54
+ readonly reason?: string;
55
+ readonly facets: readonly string[];
56
+ readonly stage: MessageOutcomeStage;
57
+ readonly visibility: MessageOutcomeVisibility;
58
+ readonly reply: MessageOutcomeReply;
59
+ readonly command?: string;
60
+ readonly owner?: string;
61
+ readonly turnId?: string;
62
+ readonly diagnosticId?: string;
63
+ readonly errorId?: string;
64
+ readonly mergedInto?: string;
65
+ readonly detail?: string;
66
+ /** Last stage the message reached; set on `unrecorded`. */
67
+ readonly lastStage?: MessageOutcomeStage;
68
+ }
69
+ /** Priority rank (higher wins). `internal_error` > `delivery_failed` > model > approval > tool > refusals > replies > silent > `unrecorded`. @public */
70
+ export declare function messageOutcomePriority(outcome: MessageOutcome): number;
71
+ /** Outcomes with no chat reply that are sampled per conversation (ADR 0061 §2). @public */
72
+ export declare const QUIET_MESSAGE_OUTCOMES: ReadonlySet<MessageOutcome>;
73
+ /** Default visibility of a code (ADR 0061 §1 tables); callers may narrow it per reason. @public */
74
+ export declare function defaultOutcomeVisibility(outcome: MessageOutcome, addressed?: boolean): MessageOutcomeVisibility;
75
+ /** Default `reply` of a code (ADR 0061 §1 tables). @public */
76
+ export declare function defaultOutcomeReply(outcome: MessageOutcome): MessageOutcomeReply;
77
+ type Bilingual = Readonly<Record<Locale, string>>;
78
+ /** Human-readable templates per code (ADR 0061 §1): `sender` for the person who sent it, `admin` for administrators. @public */
79
+ export interface MessageOutcomeTemplate {
80
+ readonly sender: Bilingual;
81
+ readonly admin: Bilingual;
82
+ }
83
+ /** Placeholders a template may use; each maps to a record field. @public */
84
+ export declare const MESSAGE_OUTCOME_PLACEHOLDERS: readonly ["command", "owner", "reason", "stage", "turnId", "errorId", "mergedInto", "detail"];
85
+ /** @public */
86
+ export declare const MESSAGE_OUTCOME_TEMPLATES: Readonly<Record<MessageOutcome, MessageOutcomeTemplate>>;
87
+ /**
88
+ * Renders the human-readable reason of a record for one audience. Missing placeholders read as
89
+ * `—`; `detail` and `errorId` are only filled for the `admin` audience with `includeDetail`.
90
+ * @public
91
+ */
92
+ export declare function formatMessageOutcome(record: Pick<MessageOutcomeRecord, 'outcome'> & Partial<MessageOutcomeRecord>, options: Readonly<{
93
+ audience: 'sender' | 'admin';
94
+ locale?: Locale;
95
+ includeDetail?: boolean;
96
+ }>): string;
97
+ export {};
@@ -0,0 +1,125 @@
1
+ /** Outcome codes (ADR 0061 §1.1–§1.6). Snake case, append-only. @public */
2
+ export const MESSAGE_OUTCOMES = Object.freeze([
3
+ // §1.1 replied
4
+ 'replied', 'command_replied', 'handler_replied', 'interaction_answered', 'suggested', 'refused',
5
+ // §1.2 not executed, explained in chat
6
+ 'invalid_input', 'permission_denied', 'rate_limited', 'approval_denied', 'approval_timeout', 'approval_unavailable',
7
+ 'tool_failed_reported', 'model_timeout', 'model_error', 'budget_exhausted',
8
+ // §1.3 no reply by design
9
+ 'not_addressed', 'feature_disabled', 'ambient_silent', 'model_silent', 'merged', 'superseded', 'cleared',
10
+ 'interaction_consumed',
11
+ // §1.4 filtered by policy
12
+ 'filtered_by_policy', 'media_rejected',
13
+ // §1.5 replay only
14
+ 'ignored_self', 'ignored_bot', 'dropped_duplicate', 'dropped_unready', 'dropped_dedup_error', 'dropped_retired',
15
+ // §1.6 failures
16
+ 'delivery_failed', 'internal_error', 'unrecorded',
17
+ ]);
18
+ /** Where an outcome was decided (ADR 0061 §2 `stage`). @public */
19
+ export const MESSAGE_OUTCOME_STAGES = Object.freeze([
20
+ 'ingress', 'interaction', 'middleware', 'handlers', 'command', 'suggestion', 'agent_gate', 'ambient',
21
+ 'admission', 'model', 'tool', 'delivery',
22
+ ]);
23
+ const TIER = Object.freeze({
24
+ internal_error: 9,
25
+ delivery_failed: 8,
26
+ model_timeout: 7, model_error: 7, budget_exhausted: 7,
27
+ approval_denied: 6, approval_timeout: 6, approval_unavailable: 6,
28
+ tool_failed_reported: 5,
29
+ refused: 4, permission_denied: 4, rate_limited: 4, invalid_input: 4, filtered_by_policy: 4,
30
+ replied: 3, command_replied: 3, handler_replied: 3, interaction_answered: 3, suggested: 3,
31
+ not_addressed: 2, feature_disabled: 2, ambient_silent: 2, model_silent: 2, merged: 2, superseded: 2, cleared: 2,
32
+ interaction_consumed: 2, media_rejected: 2, ignored_self: 2, ignored_bot: 2, dropped_duplicate: 2,
33
+ dropped_unready: 2, dropped_dedup_error: 2, dropped_retired: 2,
34
+ unrecorded: 0,
35
+ });
36
+ /** Priority rank (higher wins). `internal_error` > `delivery_failed` > model > approval > tool > refusals > replies > silent > `unrecorded`. @public */
37
+ export function messageOutcomePriority(outcome) {
38
+ return TIER[outcome] ?? 0;
39
+ }
40
+ /** Outcomes with no chat reply that are sampled per conversation (ADR 0061 §2). @public */
41
+ export const QUIET_MESSAGE_OUTCOMES = new Set([
42
+ 'not_addressed', 'ignored_bot', 'ignored_self', 'dropped_duplicate',
43
+ ]);
44
+ const REPLY = Object.freeze({ 9: 'throttled', 8: 'throttled' });
45
+ const NO_REPLY = new Set([
46
+ 'not_addressed', 'feature_disabled', 'ambient_silent', 'model_silent', 'merged', 'superseded', 'interaction_consumed',
47
+ 'filtered_by_policy', 'media_rejected', 'ignored_self', 'ignored_bot', 'dropped_duplicate', 'dropped_unready',
48
+ 'dropped_dedup_error', 'dropped_retired',
49
+ ]);
50
+ const REPLAY_ONLY = new Set([
51
+ 'ignored_self', 'ignored_bot', 'dropped_duplicate', 'dropped_unready', 'dropped_dedup_error', 'dropped_retired',
52
+ ]);
53
+ const ADMIN_ONLY = new Set(['feature_disabled', 'unrecorded']);
54
+ /** Default visibility of a code (ADR 0061 §1 tables); callers may narrow it per reason. @public */
55
+ export function defaultOutcomeVisibility(outcome, addressed = false) {
56
+ if (REPLAY_ONLY.has(outcome)) {
57
+ // §1.5: a sender who addressed the bot during a restart / outage is told to send again.
58
+ return addressed && (outcome === 'dropped_unready' || outcome === 'dropped_dedup_error' || outcome === 'dropped_retired')
59
+ ? 'sender' : 'replay';
60
+ }
61
+ return ADMIN_ONLY.has(outcome) ? 'admin' : 'sender';
62
+ }
63
+ /** Default `reply` of a code (ADR 0061 §1 tables). @public */
64
+ export function defaultOutcomeReply(outcome) {
65
+ if (outcome === 'unrecorded')
66
+ return 'no';
67
+ return REPLY[TIER[outcome]] ?? (NO_REPLY.has(outcome) ? 'no' : 'yes');
68
+ }
69
+ const tpl = (senderZh, senderEn, adminZh, adminEn) => Object.freeze({ sender: Object.freeze({ 'zh-CN': senderZh, en: senderEn }), admin: Object.freeze({ 'zh-CN': adminZh, en: adminEn }) });
70
+ /** Placeholders a template may use; each maps to a record field. @public */
71
+ export const MESSAGE_OUTCOME_PLACEHOLDERS = Object.freeze(['command', 'owner', 'reason', 'stage', 'turnId', 'errorId', 'mergedInto', 'detail']);
72
+ /** @public */
73
+ export const MESSAGE_OUTCOME_TEMPLATES = Object.freeze({
74
+ replied: tpl('已回复。', 'Replied.', '由 Agent 回复,回合 {turnId}。', 'Replied by the agent, turn {turnId}.'),
75
+ command_replied: tpl('已执行指令 {command}。', 'Ran command {command}.', '指令 {command}(插件 {owner})。', 'Command {command} (plugin {owner}).'),
76
+ handler_replied: tpl('已由插件处理。', 'Handled by a plugin.', '由插件 {owner} 的 {stage} 回复。', 'Replied by {owner} ({stage}).'),
77
+ interaction_answered: tpl('已作为对等待中提问的回答。', 'Taken as your answer to a pending question.', '提问方 {owner}。', 'Prompt by {owner}.'),
78
+ suggested: tpl('没有这条指令,已提示相近的指令。', 'No such command; suggested a close one.', '近似匹配提示,来自 {owner}。', 'Near-match suggestion from {owner}.'),
79
+ refused: tpl('插件拒绝了这次请求。', 'The plugin declined.', 'UserFacingError 来自 {owner}({stage})。', 'UserFacingError from {owner} ({stage}).'),
80
+ invalid_input: tpl('指令参数不对,已回复用法。', 'Wrong arguments; usage was sent.', '指令 {command} 参数校验失败。', 'Command {command} failed validation.'),
81
+ permission_denied: tpl('你没有权限执行这条指令。', 'You are not allowed to run this command.', '指令 {command} 缺少权限({reason})。', 'Command {command} denied ({reason}).'),
82
+ rate_limited: tpl('太频繁或正忙,这次没有处理,请稍后再试。', 'Too frequent or busy; not processed this time.', '限流:{reason}。', 'Limited: {reason}.'),
83
+ approval_denied: tpl('需要确认的操作被拒绝了,没有执行。', 'The action needing approval was declined and did not run.', '审批被拒绝:{detail}。', 'Approval declined: {detail}.'),
84
+ approval_timeout: tpl('等确认超时了,操作没有执行。', 'Approval timed out; the action did not run.', '审批超时:{detail}。', 'Approval timed out: {detail}.'),
85
+ approval_unavailable: tpl('这个操作需要有人确认,但现在没有可确认的渠道,没有执行。', 'This action needs approval but no one can approve it here; it did not run.', '无审批通道({reason})。', 'No approval channel ({reason}).'),
86
+ tool_failed_reported: tpl('有一步操作失败了,回复里已说明。', 'A step failed; the reply says so.', '工具失败:{detail}。', 'Tool failed: {detail}.'),
87
+ model_timeout: tpl('模型服务没有响应,这次没回上,请稍后再试。', 'The model did not respond; please try again later.', '模型超时({reason})。', 'Model timed out ({reason}).'),
88
+ model_error: tpl('模型服务出错了,这次没回上,请稍后再试。', 'The model service failed; please try again later.', '模型失败({reason})。', 'Model failed ({reason}).'),
89
+ budget_exhausted: tpl('这件事步骤太多,做到一半停下了。', 'Too many steps; stopped partway.', '超出预算 {reason}。', 'Budget {reason} exceeded.'),
90
+ not_addressed: tpl('这条消息没有 @ 我,也不是指令,本群我只在被 @ 时回复。', 'You did not mention me and it is not a command; here I only answer when mentioned.', '未点名、未匹配指令,本群不插话({reason})。', 'Not addressed, no command, no interjection here ({reason}).'),
91
+ feature_disabled: tpl('这里没有开启相关功能。', 'That feature is not enabled here.', '功能在此处关闭({reason})。', 'Feature disabled here ({reason}).'),
92
+ ambient_silent: tpl('我判断这句不需要我插话。', 'I decided not to chime in.', '旁听判定不插话({reason})。', 'Ambient judge declined ({reason}).'),
93
+ model_silent: tpl('我看了,但这次决定不回复。', 'I read it but chose not to reply.', '回合 {turnId} 完成但没有输出。', 'Turn {turnId} completed with no output.'),
94
+ merged: tpl('和你前后几句合在一起回复了。', 'Answered together with your other messages.', '合入回合 {mergedInto}。', 'Merged into turn {mergedInto}.'),
95
+ superseded: tpl('你很快又发了新消息,按新消息处理了。', 'You sent a newer message; that one was handled instead.', '被新消息顶替({reason})。', 'Superseded ({reason}).'),
96
+ cleared: tpl('已清空上下文。', 'Context cleared.', '已清空上下文。', 'Context cleared.'),
97
+ interaction_consumed: tpl('刚才在等一个提问的回答,这句被当成了回答。', 'I was waiting for an answer to a question and took this as it.', '被等待中的提问吃掉,提问方 {owner}({reason})。', 'Captured by a pending prompt of {owner} ({reason}).'),
98
+ filtered_by_policy: tpl('机器人在这里暂停回复或无法发言。', 'The bot is paused or cannot speak here.', '被策略过滤({reason})。', 'Filtered by policy ({reason}).'),
99
+ media_rejected: tpl('你发的媒体我读不了,只看了文字部分。', 'I could not read your media; only the text was used.', '媒体被拒({reason})。', 'Media rejected ({reason}).'),
100
+ ignored_self: tpl('机器人自己发出的消息回显。', 'Echo of the bot\'s own message.', '机器人自己发出的消息回显。', 'Echo of the bot\'s own message.'),
101
+ ignored_bot: tpl('来自其他机器人,只记录。', 'From another bot; recorded only.', '来自其他机器人({reason}),只记录。', 'From another bot ({reason}); recorded only.'),
102
+ dropped_duplicate: tpl('同一条消息已由另一个端点处理。', 'Already handled by another endpoint.', '同一条消息已由另一个端点处理。', 'Already handled by another endpoint.'),
103
+ dropped_unready: tpl('机器人刚才在重启或暂时不可用,请再发一次。', 'The bot was restarting or unavailable; please send it again.', '场地成员尚未上报自身 ID,消息未处理:{detail}。', 'Venue members not ready: {detail}.'),
104
+ dropped_dedup_error: tpl('机器人刚才暂时不可用,请再发一次。', 'The bot was briefly unavailable; please send it again.', '去重存储出错,按失败关闭丢弃:{detail}。', 'Dedup store failed closed: {detail}.'),
105
+ dropped_retired: tpl('机器人刚才在重启,请再发一次。', 'The bot was restarting; please send it again.', '实例正在重载 / 关闭,消息未被接纳。', 'Instance reloading or stopping.'),
106
+ delivery_failed: tpl('回复已经生成,但发到平台时失败了。', 'The reply was ready but the platform rejected it.', '发送失败({reason})。', 'Delivery failed ({reason}).'),
107
+ internal_error: tpl('处理时出错了,已记录(错误号 {errorId})。', 'Something went wrong; logged as {errorId}.', '{stage} 抛出异常({reason}),插件 {owner}:{detail}', '{stage} threw ({reason}), plugin {owner}: {detail}'),
108
+ unrecorded: tpl('这条消息的处理结果没有记录下来。', 'No outcome was recorded.', '没有结局记录,最后阶段 {stage};这是框架缺陷,请报告。', 'No outcome recorded, last stage {stage}; a framework bug.'),
109
+ });
110
+ /**
111
+ * Renders the human-readable reason of a record for one audience. Missing placeholders read as
112
+ * `—`; `detail` and `errorId` are only filled for the `admin` audience with `includeDetail`.
113
+ * @public
114
+ */
115
+ export function formatMessageOutcome(record, options) {
116
+ const template = MESSAGE_OUTCOME_TEMPLATES[record.outcome] ?? MESSAGE_OUTCOME_TEMPLATES.unrecorded;
117
+ const locale = options.locale === 'en' ? 'en' : 'zh-CN';
118
+ const text = template[options.audience][locale];
119
+ return text.replace(/\{(\w+)\}/gu, (_match, name) => {
120
+ if ((name === 'detail' || name === 'errorId') && options.audience === 'admin' && !options.includeDetail)
121
+ return '—';
122
+ const value = name === 'stage' ? record.lastStage ?? record.stage : record[name];
123
+ return typeof value === 'string' && value ? value : '—';
124
+ });
125
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.9.0",
3
+ "version": "1.10.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.1",
56
- "@zhin.js/command": "1.3.0",
57
- "@zhin.js/database": "1.2.1",
58
- "@zhin.js/handler": "1.1.18",
55
+ "@zhin.js/adapter": "1.3.2",
56
+ "@zhin.js/command": "1.3.1",
59
57
  "@zhin.js/component": "1.1.19",
60
- "@zhin.js/im-contract": "1.2.0",
61
- "@zhin.js/kernel": "1.1.7",
62
- "@zhin.js/logger": "1.2.0",
58
+ "@zhin.js/database": "1.2.2",
59
+ "@zhin.js/im-contract": "1.3.0",
60
+ "@zhin.js/kernel": "1.2.0",
61
+ "@zhin.js/logger": "1.3.0",
63
62
  "@zhin.js/middleware": "1.1.19",
64
63
  "@zhin.js/permission": "1.2.2",
65
64
  "@zhin.js/plugin-runtime": "1.3.0",
66
65
  "@zhin.js/schedule-feature": "1.1.18",
67
66
  "@zhin.js/schema": "1.1.7",
68
- "@zhin.js/jsx": "1.1.14",
69
- "@zhin.js/feature-kit": "1.1.18"
67
+ "@zhin.js/jsx": "1.1.15",
68
+ "@zhin.js/feature-kit": "1.1.18",
69
+ "@zhin.js/handler": "1.1.19"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@types/node": "^26.1.2",