@zhin.js/core 1.9.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.
Files changed (33) hide show
  1. package/lib/built/interaction-messages.d.ts +1 -1
  2. package/lib/built/interactive-segments/resolve.js +12 -0
  3. package/lib/built/interactive-segments/types.d.ts +6 -0
  4. package/lib/built/roles.d.ts +33 -6
  5. package/lib/built/roles.js +27 -15
  6. package/lib/built/segment-contract/json-schema.js +1 -0
  7. package/lib/built/user-interaction.js +3 -0
  8. package/lib/plugin-runtime/im/ambient-switch.d.ts +49 -0
  9. package/lib/plugin-runtime/im/ambient-switch.js +70 -0
  10. package/lib/plugin-runtime/im/contracts.d.ts +58 -0
  11. package/lib/plugin-runtime/im/contracts.js +21 -1
  12. package/lib/plugin-runtime/im/conversation-runtime.js +12 -2
  13. package/lib/plugin-runtime/im/host/database-console-sql.js +1 -1
  14. package/lib/plugin-runtime/im/im-runtime.d.ts +9 -1
  15. package/lib/plugin-runtime/im/im-runtime.js +10 -0
  16. package/lib/plugin-runtime/im/inbound-outcome-ledger.d.ts +117 -0
  17. package/lib/plugin-runtime/im/inbound-outcome-ledger.js +329 -0
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +6 -1
  19. package/lib/plugin-runtime/im/inbound-runtime.js +268 -21
  20. package/lib/plugin-runtime/im/inbound-spine.d.ts +20 -3
  21. package/lib/plugin-runtime/im/inbound-spine.js +107 -7
  22. package/lib/plugin-runtime/im/index.d.ts +5 -1
  23. package/lib/plugin-runtime/im/index.js +3 -0
  24. package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -0
  25. package/lib/plugin-runtime/im/interaction-runtime.js +45 -14
  26. package/lib/plugin-runtime/im/message-diagnostics.d.ts +16 -0
  27. package/lib/plugin-runtime/im/message-diagnostics.js +12 -0
  28. package/lib/plugin-runtime/im/message-dispatcher.d.ts +6 -0
  29. package/lib/plugin-runtime/im/message-dispatcher.js +6 -1
  30. package/lib/plugin-runtime/im/message-outcome.d.ts +97 -0
  31. package/lib/plugin-runtime/im/message-outcome.js +125 -0
  32. package/lib/plugin-runtime/im/outbound-segments.js +1 -1
  33. package/package.json +15 -15
@@ -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,8 +10,17 @@ 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, inboundOutcomeReplied, reportInboundOutcome } from './inbound-outcome-ledger.js';
13
14
  export { arbitrateRoomInboundDeduplication, buildRoomInboundRouteInput, resolveRoomMembership, } from './inbound-dedup.js';
14
15
  const logger = getLogger('im.inbound');
16
+ /** Normalizes the legacy boolean and the structured route result. */
17
+ export function readIngressRouteResult(message, result) {
18
+ if (result === undefined || typeof result === 'boolean')
19
+ return result === true;
20
+ if (result.outcome)
21
+ reportInboundOutcome(message, result.outcome);
22
+ return result.handled === true;
23
+ }
15
24
  export const ingressRouteToken = createToken('zhin.im.ingress-route');
16
25
  export function resolveIngressRoute(snapshot) {
17
26
  const candidate = snapshot.resources.get(snapshot.root)?.get(ingressRouteToken.id);
@@ -78,7 +87,9 @@ export async function executeInboundTurnSpine(envelope, control) {
78
87
  };
79
88
  };
80
89
  const ingressRoute = envelope.ingressRoute ?? resolveIngressRoute(lease.value);
81
- const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
90
+ if (ingressRoute?.preRoute)
91
+ enterInboundOutcomeStage(message, 'agent_gate');
92
+ const preRouted = readIngressRouteResult(message, await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence));
82
93
  if (preRouted) {
83
94
  diagnostics?.route('agent');
84
95
  const dispatch = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
@@ -92,7 +103,8 @@ export async function executeInboundTurnSpine(envelope, control) {
92
103
  return finish(dispatch, 'pre-route', replied);
93
104
  }
94
105
  if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
95
- const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
106
+ enterInboundOutcomeStage(message, 'agent_gate');
107
+ const handled = readIngressRouteResult(message, await ingressRoute.route(message, lease, requester, conversationSequence));
96
108
  if (handled) {
97
109
  diagnostics?.route('agent');
98
110
  const dispatch = Object.freeze({ matched: true, command: 'ai', owner: requester });
@@ -107,16 +119,34 @@ export async function executeInboundTurnSpine(envelope, control) {
107
119
  }
108
120
  }
109
121
  const repliedBeforeHandlers = envelope.hasReplied();
122
+ enterInboundOutcomeStage(message, 'handlers');
110
123
  diagnostics?.step('handlers', 'started');
111
124
  await envelope.runHandlers();
112
125
  diagnostics?.step('handlers', 'completed');
113
126
  const repliedDuringHandlers = !repliedBeforeHandlers && envelope.hasReplied();
114
127
  const interactive = await envelope.dispatchInteractive();
115
- if (interactive)
128
+ if (interactive) {
116
129
  diagnostics?.route('interaction');
130
+ reportInboundOutcome(message, { outcome: 'interaction_answered', reason: 'button', stage: 'interaction',
131
+ ...(interactive.owner ? { owner: interactive.owner } : {}) });
132
+ }
133
+ if (!interactive)
134
+ enterInboundOutcomeStage(message, 'command');
135
+ let commandMiss;
117
136
  const dispatched = interactive
118
137
  ? undefined
119
- : await envelope.dispatchCommand((stage, status) => diagnostics?.step(stage, status));
138
+ : await envelope.dispatchCommand((stage, status) => {
139
+ diagnostics?.step(stage, status);
140
+ if (status === 'mismatch')
141
+ commandMiss = 'prefix_mismatch';
142
+ else if (status === 'empty_input')
143
+ commandMiss = 'empty_input';
144
+ else if (status === 'commands_unavailable') {
145
+ reportInboundOutcome(message, { outcome: 'feature_disabled', reason: 'commands_unavailable', stage: 'command' });
146
+ }
147
+ });
148
+ if (dispatched)
149
+ reportCommandOutcome(message, dispatched.dispatch);
120
150
  let result = interactive ?? dispatched.dispatch;
121
151
  let stage = interactive
122
152
  ? 'interactive'
@@ -141,12 +171,14 @@ export async function executeInboundTurnSpine(envelope, control) {
141
171
  }
142
172
  if (suggested !== undefined) {
143
173
  diagnostics?.route('command');
174
+ reportInboundOutcome(message, { outcome: 'suggested', reason: 'near_miss', stage: 'suggestion', owner: requester });
144
175
  suggestion = { owner: requester, content: suggested };
145
176
  stage = 'command-suggestion';
146
177
  }
147
178
  }
148
179
  if (!result.matched && ingressRoute && !suggestion) {
149
- const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
180
+ enterInboundOutcomeStage(message, 'agent_gate');
181
+ const handled = readIngressRouteResult(message, await ingressRoute.route(message, lease, requester, conversationSequence));
150
182
  if (handled) {
151
183
  diagnostics?.route('agent');
152
184
  result = Object.freeze({ matched: true, command: 'ai', owner: requester });
@@ -183,6 +215,8 @@ export async function executeInboundTurnSpine(envelope, control) {
183
215
  }
184
216
  else if (repliedDuringHandlers) {
185
217
  stage = 'handlers';
218
+ reportInboundOutcome(message, { outcome: 'handler_replied', reason: 'handler', stage: 'handlers',
219
+ ...(envelope.findEventHandlerName?.('message.receive') ? { owner: envelope.findEventHandlerName('message.receive') } : {}) });
186
220
  const handlerName = envelope.findEventHandlerName?.('message.receive') ?? 'message.receive';
187
221
  await control?.reportDispatch({
188
222
  matched: true,
@@ -197,6 +231,16 @@ export async function executeInboundTurnSpine(envelope, control) {
197
231
  path: 'none',
198
232
  replied,
199
233
  });
234
+ // ADR 0061 P1/P2: nothing claimed the message. An ingress route reports its own, more
235
+ // specific reason first (`not_addressed` ties keep the earlier one); this is the fallback.
236
+ if (!result.matched && !suggestion) {
237
+ reportInboundOutcome(message, {
238
+ outcome: 'not_addressed',
239
+ reason: commandMiss === 'prefix_mismatch' || commandMiss === 'empty_input' ? commandMiss
240
+ : isAddressedMessage(message) ? 'no_command' : 'no_command_not_ambient',
241
+ stage: 'command',
242
+ });
243
+ }
200
244
  }
201
245
  return finish(result, stage, replied, response);
202
246
  }
@@ -204,11 +248,23 @@ export async function runInboundMiddlewareAndSpine(envelope, diagnostics) {
204
248
  const { message, lease } = envelope;
205
249
  const terminal = (control) => executeInboundTurnSpine(envelope, control);
206
250
  const middleware = gatedMiddlewareIndex(message, lease.value);
207
- if (isMiddlewareIndex(middleware))
251
+ if (isMiddlewareIndex(middleware)) {
252
+ enterInboundOutcomeStage(message, 'middleware');
208
253
  diagnostics?.step('middleware', 'entered');
254
+ }
209
255
  const outcome = isMiddlewareIndex(middleware)
210
256
  ? await middleware.runInbound(message, terminal, {
211
257
  stop: (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
+ }
212
268
  diagnostics?.route('middleware');
213
269
  diagnostics?.step('middleware', 'stopped');
214
270
  return { dispatch: { matched: true, command: 'middleware', owner } };
@@ -218,6 +274,7 @@ export async function runInboundMiddlewareAndSpine(envelope, diagnostics) {
218
274
  const text = userFacingErrorText(error, message.locale);
219
275
  if (text === undefined)
220
276
  return undefined;
277
+ reportInboundOutcome(message, { outcome: 'refused', reason: 'user_facing_error', stage: 'middleware', owner });
221
278
  diagnostics?.step('middleware', 'replaced');
222
279
  if (!downstream?.dispatch.matched)
223
280
  diagnostics?.route('middleware');
@@ -227,6 +284,7 @@ export async function runInboundMiddlewareAndSpine(envelope, diagnostics) {
227
284
  };
228
285
  },
229
286
  replace: (owner, value, downstream) => {
287
+ reportInboundOutcome(message, { outcome: 'handler_replied', reason: 'middleware', stage: 'middleware', owner });
230
288
  diagnostics?.step('middleware', 'replaced');
231
289
  if (!downstream?.dispatch.matched)
232
290
  diagnostics?.route('middleware');
@@ -280,6 +338,7 @@ export async function dispatchInboundHandlers({ lease, event, args, signal = lea
280
338
  if (text === undefined)
281
339
  return false;
282
340
  if (payload instanceof RuntimeMessage) {
341
+ reportInboundOutcome(payload, { outcome: 'refused', reason: 'user_facing_error', stage: 'handlers', owner });
283
342
  await bindOperationInput(payload, owner, snapshot).$reply(text);
284
343
  return true;
285
344
  }
@@ -383,3 +442,44 @@ export function withEndpointEventPayload(source, payload) {
383
442
  [operationInputBinding]: (owner, snapshot) => withEndpointEventPayload(source, bindOperationInput(payload, owner, snapshot)),
384
443
  });
385
444
  }
445
+ /**
446
+ * ADR 0061 §1: a private chat, a mention, the command prefix, or a reply (to the bot; the outbound
447
+ * ledger check happens in the inbound runtime, which passes `repliedToBot`).
448
+ */
449
+ export function isAddressedMessage(message, repliedToBot = false) {
450
+ if (message.conversation.kind === 'private' || message.mentioned === true || repliedToBot)
451
+ return true;
452
+ const prefix = message.commandPrefix;
453
+ return typeof prefix === 'string' && prefix.length > 0 && message.content.trim().startsWith(prefix);
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
+ }
459
+ /** Maps one command dispatch fact to its outcome (ADR 0061 §1.1 / §1.2). */
460
+ function reportCommandOutcome(message, result) {
461
+ if (!result.matched)
462
+ return;
463
+ const base = { stage: 'command', ...(result.command ? { command: result.command } : {}), ...(result.owner ? { owner: result.owner } : {}) };
464
+ const refused = result.refused === true;
465
+ switch (result.status) {
466
+ case 'invalid':
467
+ reportInboundOutcome(message, { ...base, outcome: 'invalid_input', reason: 'invalid',
468
+ ...(result.issues?.length ? { detail: result.issues.map(issue => `${issue.field}: ${issue.message}`).join('; ') } : {}) });
469
+ return;
470
+ case 'denied': {
471
+ const permit = result.denial?.permit;
472
+ const category = typeof permit === 'string' && permit ? permit.split(/[:.]/u)[0] : undefined;
473
+ reportInboundOutcome(message, { ...base, outcome: 'permission_denied', reason: category ? `denied:${category}` : 'denied' });
474
+ return;
475
+ }
476
+ case 'limited':
477
+ reportInboundOutcome(message, { ...base, outcome: 'rate_limited', reason: result.limit?.reason ?? 'limited' });
478
+ return;
479
+ default:
480
+ // The command's own closed refusal code (UserFacingError `reason`), else the generic one.
481
+ reportInboundOutcome(message, refused
482
+ ? { ...base, outcome: 'refused', reason: refusalReasonOf(result) ?? 'user_facing_error' }
483
+ : { ...base, outcome: 'command_replied', reason: result.menu ? 'menu' : 'executed' });
484
+ }
485
+ }
@@ -8,7 +8,10 @@ export type { MessageOrigin, RoomInboundRouteInput, RoomMembershipPort, RoomRout
8
8
  export * from './im-runtime.js';
9
9
  export * from './command-feedback.js';
10
10
  export * from './message-dispatcher.js';
11
- export type { RuntimeMessageDiagnostic, RuntimeMessageDiagnosticStep, RuntimeMessageDiagnosticDelivery, RuntimeMessageDiagnosticsReader, } from './message-diagnostics.js';
11
+ export type { RuntimeMessageDiagnostic, RuntimeMessageDiagnosticStep, RuntimeMessageDiagnosticDelivery, RuntimeMessageDiagnosticsReader, RuntimeMessageDiagnosticOutcome, } from './message-diagnostics.js';
12
+ export * from './message-outcome.js';
13
+ export { enterInboundOutcomeStage, InboundOutcomeLedger, inboundOutcomeSink, MessageOutcomeLog, onUnrecordedInboundOutcome, reportInboundOutcome, type InboundOutcomeLedgerInit, type InboundOutcomeSink, type MessageOutcomeLogOptions, type MessageOutcomeQuery, type MessageOutcomeReader, type UnrecordedOutcomeListener, } from './inbound-outcome-ledger.js';
14
+ export type { InteractionClaimResolution } from './interaction-runtime.js';
12
15
  export { MessageBus, messageBusToken, type EndpointEvent, type MessageBusEventMap, type MessageBusEventName, type RuntimeMessageEvent, type RuntimeMessageEventSource, type RuntimeMessageRendering, type RuntimeSceneEventSignal, type RuntimeSceneEventSource, type OutboundFallbackReason, } from './message-events.js';
13
16
  export * from './outbound-renderer.js';
14
17
  export * from './outbound-segments.js';
@@ -18,3 +21,4 @@ export * from '../../notice.js';
18
21
  export * from '../../request.js';
19
22
  export * from '../../system-event.js';
20
23
  export * from '../../venue/index.js';
24
+ export * from './ambient-switch.js';
@@ -6,6 +6,8 @@ export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
6
6
  export * from './im-runtime.js';
7
7
  export * from './command-feedback.js';
8
8
  export * from './message-dispatcher.js';
9
+ export * from './message-outcome.js';
10
+ export { enterInboundOutcomeStage, InboundOutcomeLedger, inboundOutcomeSink, MessageOutcomeLog, onUnrecordedInboundOutcome, reportInboundOutcome, } from './inbound-outcome-ledger.js';
9
11
  export { MessageBus, messageBusToken, } from './message-events.js';
10
12
  export * from './outbound-renderer.js';
11
13
  export * from './outbound-segments.js';
@@ -14,3 +16,4 @@ export * from '../../notice.js';
14
16
  export * from '../../request.js';
15
17
  export * from '../../system-event.js';
16
18
  export * from '../../venue/index.js';
19
+ export * from './ambient-switch.js';
@@ -13,6 +13,12 @@ export interface PendingUserInteraction {
13
13
  readonly expiresAt: number;
14
14
  readonly segments: SendContent;
15
15
  }
16
+ /** ADR 0061 P5 / decision 11: how a claimed message was taken. */
17
+ export interface InteractionClaimResolution {
18
+ /** The message parses as an answer to the prompt (otherwise it was consumed). */
19
+ readonly answerLike: boolean;
20
+ readonly owner?: string;
21
+ }
16
22
  export interface UserInteractionSource {
17
23
  readonly locale?: Locale;
18
24
  readonly generation?: number;
@@ -30,6 +36,8 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
30
36
  dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
31
37
  prepareButtons(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
32
38
  resolveClaim(message: Message, snapshot?: RuntimeSnapshot): boolean;
39
+ /** {@link resolveClaim} plus whether the text was answer-like (ADR 0061 `interaction_answered` / `interaction_consumed`). */
40
+ resolveClaimDetailed(message: Message, snapshot?: RuntimeSnapshot): false | InteractionClaimResolution;
33
41
  /**
34
42
  * Probe used by Room routing: is this message the answer to something pending on this exact
35
43
  * (Endpoint-scoped) conversation? True when the sender has a pending conversational claim, or
@@ -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)
@@ -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)) {
@@ -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 {};