@zhin.js/core 1.8.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.
- package/lib/built/chat-role-reader.d.ts +145 -0
- package/lib/built/chat-role-reader.js +183 -0
- package/lib/built/roles.d.ts +55 -1
- package/lib/built/roles.js +84 -7
- package/lib/built/user-interaction.js +3 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/plugin-runtime/im/ambient-switch.d.ts +49 -0
- package/lib/plugin-runtime/im/ambient-switch.js +70 -0
- package/lib/plugin-runtime/im/command-feedback.js +22 -5
- package/lib/plugin-runtime/im/contracts.d.ts +15 -0
- package/lib/plugin-runtime/im/contracts.js +20 -1
- package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +3 -1
- package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
- package/lib/plugin-runtime/im/im-runtime.js +9 -0
- package/lib/plugin-runtime/im/inbound-outcome-ledger.d.ts +103 -0
- package/lib/plugin-runtime/im/inbound-outcome-ledger.js +311 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +3 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +138 -13
- package/lib/plugin-runtime/im/inbound-spine.d.ts +20 -3
- package/lib/plugin-runtime/im/inbound-spine.js +93 -6
- package/lib/plugin-runtime/im/index.d.ts +5 -1
- package/lib/plugin-runtime/im/index.js +3 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +45 -14
- package/lib/plugin-runtime/im/message-diagnostics.d.ts +16 -0
- package/lib/plugin-runtime/im/message-diagnostics.js +12 -0
- package/lib/plugin-runtime/im/message-events.js +27 -0
- package/lib/plugin-runtime/im/message-outcome.d.ts +97 -0
- package/lib/plugin-runtime/im/message-outcome.js +125 -0
- package/package.json +9 -9
|
@@ -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, 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
|
-
|
|
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
|
-
|
|
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) =>
|
|
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
|
-
|
|
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,15 @@ 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
|
+
reportInboundOutcome(message, { outcome: 'filtered_by_policy', reason: 'middleware_stopped', stage: 'middleware',
|
|
259
|
+
visibility: 'admin', owner });
|
|
212
260
|
diagnostics?.route('middleware');
|
|
213
261
|
diagnostics?.step('middleware', 'stopped');
|
|
214
262
|
return { dispatch: { matched: true, command: 'middleware', owner } };
|
|
@@ -218,6 +266,7 @@ export async function runInboundMiddlewareAndSpine(envelope, diagnostics) {
|
|
|
218
266
|
const text = userFacingErrorText(error, message.locale);
|
|
219
267
|
if (text === undefined)
|
|
220
268
|
return undefined;
|
|
269
|
+
reportInboundOutcome(message, { outcome: 'refused', reason: 'user_facing_error', stage: 'middleware', owner });
|
|
221
270
|
diagnostics?.step('middleware', 'replaced');
|
|
222
271
|
if (!downstream?.dispatch.matched)
|
|
223
272
|
diagnostics?.route('middleware');
|
|
@@ -227,6 +276,7 @@ export async function runInboundMiddlewareAndSpine(envelope, diagnostics) {
|
|
|
227
276
|
};
|
|
228
277
|
},
|
|
229
278
|
replace: (owner, value, downstream) => {
|
|
279
|
+
reportInboundOutcome(message, { outcome: 'handler_replied', reason: 'middleware', stage: 'middleware', owner });
|
|
230
280
|
diagnostics?.step('middleware', 'replaced');
|
|
231
281
|
if (!downstream?.dispatch.matched)
|
|
232
282
|
diagnostics?.route('middleware');
|
|
@@ -280,6 +330,7 @@ export async function dispatchInboundHandlers({ lease, event, args, signal = lea
|
|
|
280
330
|
if (text === undefined)
|
|
281
331
|
return false;
|
|
282
332
|
if (payload instanceof RuntimeMessage) {
|
|
333
|
+
reportInboundOutcome(payload, { outcome: 'refused', reason: 'user_facing_error', stage: 'handlers', owner });
|
|
283
334
|
await bindOperationInput(payload, owner, snapshot).$reply(text);
|
|
284
335
|
return true;
|
|
285
336
|
}
|
|
@@ -383,3 +434,39 @@ export function withEndpointEventPayload(source, payload) {
|
|
|
383
434
|
[operationInputBinding]: (owner, snapshot) => withEndpointEventPayload(source, bindOperationInput(payload, owner, snapshot)),
|
|
384
435
|
});
|
|
385
436
|
}
|
|
437
|
+
/**
|
|
438
|
+
* ADR 0061 §1: a private chat, a mention, the command prefix, or a reply (to the bot; the outbound
|
|
439
|
+
* ledger check happens in the inbound runtime, which passes `repliedToBot`).
|
|
440
|
+
*/
|
|
441
|
+
export function isAddressedMessage(message, repliedToBot = false) {
|
|
442
|
+
if (message.conversation.kind === 'private' || message.mentioned === true || repliedToBot)
|
|
443
|
+
return true;
|
|
444
|
+
const prefix = message.commandPrefix;
|
|
445
|
+
return typeof prefix === 'string' && prefix.length > 0 && message.content.trim().startsWith(prefix);
|
|
446
|
+
}
|
|
447
|
+
/** Maps one command dispatch fact to its outcome (ADR 0061 §1.1 / §1.2). */
|
|
448
|
+
function reportCommandOutcome(message, result) {
|
|
449
|
+
if (!result.matched)
|
|
450
|
+
return;
|
|
451
|
+
const base = { stage: 'command', ...(result.command ? { command: result.command } : {}), ...(result.owner ? { owner: result.owner } : {}) };
|
|
452
|
+
const refused = result.refused === true;
|
|
453
|
+
switch (result.status) {
|
|
454
|
+
case 'invalid':
|
|
455
|
+
reportInboundOutcome(message, { ...base, outcome: 'invalid_input', reason: 'invalid',
|
|
456
|
+
...(result.issues?.length ? { detail: result.issues.map(issue => `${issue.field}: ${issue.message}`).join('; ') } : {}) });
|
|
457
|
+
return;
|
|
458
|
+
case 'denied': {
|
|
459
|
+
const permit = result.denial?.permit;
|
|
460
|
+
const category = typeof permit === 'string' && permit ? permit.split(/[:.]/u)[0] : undefined;
|
|
461
|
+
reportInboundOutcome(message, { ...base, outcome: 'permission_denied', reason: category ? `denied:${category}` : 'denied' });
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
case 'limited':
|
|
465
|
+
reportInboundOutcome(message, { ...base, outcome: 'rate_limited', reason: result.limit?.reason ?? 'limited' });
|
|
466
|
+
return;
|
|
467
|
+
default:
|
|
468
|
+
reportInboundOutcome(message, refused
|
|
469
|
+
? { ...base, outcome: 'refused', reason: 'user_facing_error' }
|
|
470
|
+
: { ...base, outcome: 'command_replied', reason: result.menu ? 'menu' : 'executed' });
|
|
471
|
+
}
|
|
472
|
+
}
|
|
@@ -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
|
|
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
|
|
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 :
|
|
138
|
+
return explicit ? false : taken(message.content, false);
|
|
121
139
|
}
|
|
122
|
-
return
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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)
|
|
@@ -85,6 +85,30 @@ export function previewMessageContent(content) {
|
|
|
85
85
|
? `${text.slice(0, messagePreviewLimit)}…`
|
|
86
86
|
: text;
|
|
87
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Branded SendContent wrappers (#1250): a component call (`component('status-card', props)`, not yet
|
|
90
|
+
* rendered) reads as its text children, or `[name] title` / `[name]`, never as serialized JSON;
|
|
91
|
+
* untrusted content reads as the content it wraps; raw platform payloads as `[raw]`.
|
|
92
|
+
*/
|
|
93
|
+
function flattenBrandedContent(record, depth) {
|
|
94
|
+
switch (record.$content) {
|
|
95
|
+
case 'zhin.component-call/1': {
|
|
96
|
+
const name = typeof record.name === 'string' && record.name ? record.name : 'component';
|
|
97
|
+
const props = record.props && typeof record.props === 'object' ? record.props : {};
|
|
98
|
+
const children = props.children === undefined ? '' : flattenNode(props.children, depth + 1).trim();
|
|
99
|
+
if (children)
|
|
100
|
+
return children;
|
|
101
|
+
const title = ['title', 'text', 'label'].map(key => props[key]).find((value) => typeof value === 'string' && value.trim() !== '');
|
|
102
|
+
return title ? `[${name}] ${title.trim()}` : `[${name}]`;
|
|
103
|
+
}
|
|
104
|
+
case 'zhin.untrusted-content/1':
|
|
105
|
+
return flattenNode(record.content, depth + 1);
|
|
106
|
+
case 'zhin.raw-content/1':
|
|
107
|
+
return '[raw]';
|
|
108
|
+
default:
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
88
112
|
/**
|
|
89
113
|
* Flattens any SendContent-like value to display text; non-text segments become `[type]`.
|
|
90
114
|
* Markdown keeps its source text, buttons (keyboard rows and JSX `<button>`) become `[label]`, and
|
|
@@ -126,6 +150,9 @@ function flattenNode(content, depth) {
|
|
|
126
150
|
}
|
|
127
151
|
if (typeof record.text === 'string')
|
|
128
152
|
return record.text;
|
|
153
|
+
const branded = flattenBrandedContent(record, depth);
|
|
154
|
+
if (branded !== undefined)
|
|
155
|
+
return branded;
|
|
129
156
|
try {
|
|
130
157
|
return JSON.stringify(content) ?? '';
|
|
131
158
|
}
|
|
@@ -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 {};
|