@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.
- package/lib/built/user-interaction.js +3 -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/contracts.d.ts +10 -0
- package/lib/plugin-runtime/im/contracts.js +20 -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-outcome.d.ts +97 -0
- package/lib/plugin-runtime/im/message-outcome.js +125 -0
- package/package.json +10 -10
|
@@ -10,11 +10,14 @@ import type { InboundDeduper } from './inbound-dedup.js';
|
|
|
10
10
|
import type { InboundOriginClassifier } from './inbound-origin.js';
|
|
11
11
|
import { type InboundInteractionPort } from './inbound-spine.js';
|
|
12
12
|
import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
13
|
+
import { type MessageOutcomeLog } from './inbound-outcome-ledger.js';
|
|
13
14
|
import { type RuntimeMessageEvent } from './message-events.js';
|
|
14
15
|
interface InboundRuntimeContext {
|
|
15
16
|
readonly commandExecution?: CommandExecutionBudget;
|
|
16
17
|
runCommandOperation?<T>(controller: CommandOperationController, operation: () => T): T;
|
|
17
18
|
readonly diagnostics?: RuntimeMessageDiagnostics;
|
|
19
|
+
/** ADR 0061: settled inbound outcomes (process-local log). Absent: outcomes are only logged. */
|
|
20
|
+
readonly outcomes?: Pick<MessageOutcomeLog, 'record'>;
|
|
18
21
|
readonly interactions: InboundInteractionPort;
|
|
19
22
|
captureOperation(input: CaptureEndpointOperationInput): CapturedEndpointOperation;
|
|
20
23
|
createOperationResources?(input: Readonly<{
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { normalizePlatformStanding } from '@zhin.js/im-contract';
|
|
2
|
-
import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
3
|
-
import {
|
|
2
|
+
import { createErrorId, formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
3
|
+
import { redactSecretText } from '@zhin.js/kernel';
|
|
4
|
+
import { RuntimeMessage, inboundOutcomeFacade, operationEndpoint, } from './contracts.js';
|
|
4
5
|
import { requireAdapters } from './endpoint-runtime.js';
|
|
5
|
-
import { arbitrateRoomInboundDeduplication, dispatchCanonicalEndpointEvent, dispatchInboundHandlers, dispatchInboundInteractive, handlers, interactionResult, messageLocale, resolveIngressRoute, resolveRoomMembership, runInboundMiddlewareAndSpine, withEndpointEventPayload, } from './inbound-spine.js';
|
|
6
|
+
import { arbitrateRoomInboundDeduplication, dispatchCanonicalEndpointEvent, dispatchInboundHandlers, dispatchInboundInteractive, handlers, interactionResult, isAddressedMessage, messageLocale, resolveIngressRoute, resolveRoomMembership, runInboundMiddlewareAndSpine, withEndpointEventPayload, } from './inbound-spine.js';
|
|
7
|
+
import { InboundOutcomeLedger } from './inbound-outcome-ledger.js';
|
|
8
|
+
import { QUIET_MESSAGE_OUTCOMES } from './message-outcome.js';
|
|
6
9
|
import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
|
|
7
10
|
import { suggestCommandReply } from './command-suggestion.js';
|
|
8
11
|
import { formatConversationLog, previewMessageContent, } from './message-events.js';
|
|
@@ -38,16 +41,55 @@ export class InboundRuntime {
|
|
|
38
41
|
}
|
|
39
42
|
async #receiveMessage(source, admission) {
|
|
40
43
|
const receivedAt = Date.now();
|
|
44
|
+
// ADR 0061 §4.1: one ledger per message, settled exactly once in `finally`.
|
|
45
|
+
const ledger = new InboundOutcomeLedger({
|
|
46
|
+
conversation: { ...source.payload?.conversation, endpoint: { id: source.endpoint.id, adapter: source.endpoint.adapter } },
|
|
47
|
+
// A malformed event without a payload still settles an outcome (the code below then throws).
|
|
48
|
+
...(typeof source.payload?.sender?.id === 'string' ? { senderId: source.payload.sender.id } : {}),
|
|
49
|
+
...(typeof source.payload?.message?.id === 'string' ? { messageId: source.payload.message.id } : {}),
|
|
50
|
+
receivedAt,
|
|
51
|
+
});
|
|
52
|
+
let failure;
|
|
53
|
+
let failed = false;
|
|
41
54
|
const lease = this.context.acquire();
|
|
42
55
|
let active = true;
|
|
43
56
|
let commandOperation;
|
|
44
57
|
let endpointLease;
|
|
58
|
+
/** Drains the operation, releases leases and settles the outcome; a drain failure is a failure. */
|
|
59
|
+
const close = async () => {
|
|
60
|
+
try {
|
|
61
|
+
await commandOperation?.finish();
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
// Without an earlier failure the drain failure is this message's failure and propagates;
|
|
65
|
+
// with one, it is only logged and the original exception is the one the caller sees.
|
|
66
|
+
if (failed) {
|
|
67
|
+
logger.warn(formatCompact({ op: 'inbound_operation_finish_failed', error: logSafeError(error) }));
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
failed = true;
|
|
71
|
+
failure = error;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
active = false;
|
|
77
|
+
try {
|
|
78
|
+
endpointLease?.release();
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
this.context.release(lease);
|
|
82
|
+
this.#settleOutcome(ledger, failed, failure);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
};
|
|
45
86
|
try {
|
|
46
87
|
const adapter = source.endpoint.id;
|
|
47
88
|
this.context.diagnostics?.begin(lease.value.generation, {
|
|
48
89
|
...source.payload.conversation,
|
|
49
90
|
endpoint: { id: source.endpoint.id, adapter: source.endpoint.adapter },
|
|
50
91
|
}, source.payload.message?.id);
|
|
92
|
+
ledger.linkDiagnostic(this.context.diagnostics?.currentId());
|
|
51
93
|
const adapters = requireAdapters(lease.value);
|
|
52
94
|
const requester = adapters.owner(adapter);
|
|
53
95
|
endpointLease = adapters.acquireInbound(adapter, source.client);
|
|
@@ -90,6 +132,7 @@ export class InboundRuntime {
|
|
|
90
132
|
const origin = classified?.origin;
|
|
91
133
|
this.context.diagnostics?.step('origin', origin ?? 'unclassified');
|
|
92
134
|
if (origin === 'self') {
|
|
135
|
+
ledger.report({ outcome: 'ignored_self', reason: 'self_echo', stage: 'ingress' });
|
|
93
136
|
this.context.diagnostics?.route('self_echo');
|
|
94
137
|
logger.debug(formatCompact({
|
|
95
138
|
op: 'self_echo',
|
|
@@ -106,6 +149,9 @@ export class InboundRuntime {
|
|
|
106
149
|
...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
|
|
107
150
|
});
|
|
108
151
|
if (!readiness.ready) {
|
|
152
|
+
ledger.markAddressed(input.mentioned === true || conversation.kind === 'private');
|
|
153
|
+
ledger.report({ outcome: 'dropped_unready', reason: 'venue_unready', stage: 'ingress',
|
|
154
|
+
detail: readiness.unreadyEndpoints?.join(',') ?? '' });
|
|
109
155
|
logger.warn(formatCompact({
|
|
110
156
|
op: 'venue_unready',
|
|
111
157
|
conv: formatConversationLog(conversation),
|
|
@@ -135,6 +181,8 @@ export class InboundRuntime {
|
|
|
135
181
|
},
|
|
136
182
|
});
|
|
137
183
|
const mentioned = routedTarget ? true : input.mentioned;
|
|
184
|
+
ledger.markAddressed(conversation.kind === 'private' || mentioned === true
|
|
185
|
+
|| (input.replyTo?.id !== undefined && this.context.resolveReplyTarget?.(conversation, input.replyTo.id) !== undefined));
|
|
138
186
|
const locale = await messageLocale(lease.value, conversation, enrichedSender?.id);
|
|
139
187
|
let operationReplied = false;
|
|
140
188
|
const operationReply = (content, replyRequester = requester, targetConversation) => {
|
|
@@ -163,8 +211,15 @@ export class InboundRuntime {
|
|
|
163
211
|
}, lease.value);
|
|
164
212
|
// A held Message may reply from another async caller while its operation is
|
|
165
213
|
// draining. Restore that Message's private controller, not the caller's scope.
|
|
166
|
-
|
|
214
|
+
const delivery = commandOperation && this.context.runCommandOperation
|
|
167
215
|
? this.context.runCommandOperation(commandOperation, deliver) : deliver();
|
|
216
|
+
return Promise.resolve(delivery).then((receipt) => {
|
|
217
|
+
if (receipt && receipt.status !== 'sent') {
|
|
218
|
+
ledger.report({ outcome: 'delivery_failed', reason: receipt.failure?.code ?? receipt.status, stage: 'delivery',
|
|
219
|
+
...(receipt.failure?.deliveryUnknown ? { facets: ['delivery_unknown'] } : {}) });
|
|
220
|
+
}
|
|
221
|
+
return receipt;
|
|
222
|
+
});
|
|
168
223
|
};
|
|
169
224
|
commandOperation = this.context.commandExecution?.openOperation({
|
|
170
225
|
snapshot: lease.value, conversation, senderId: enrichedSender?.id,
|
|
@@ -232,6 +287,7 @@ export class InboundRuntime {
|
|
|
232
287
|
boundEndpoint.assertActive();
|
|
233
288
|
},
|
|
234
289
|
...(origin ? { origin } : {}),
|
|
290
|
+
outcomes: inboundOutcomeFacade(ledger),
|
|
235
291
|
presentation: {
|
|
236
292
|
locale,
|
|
237
293
|
resolveCommands: (message) => this.#dispatcher.commandEnvironment(message, lease.value),
|
|
@@ -240,7 +296,9 @@ export class InboundRuntime {
|
|
|
240
296
|
const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
|
|
241
297
|
let result = Object.freeze({ matched: false });
|
|
242
298
|
let reply;
|
|
299
|
+
ledger.markAddressed(isAddressedMessage(message));
|
|
243
300
|
if (recordOnly === 'duplicate') {
|
|
301
|
+
ledger.report({ outcome: 'dropped_duplicate', reason: 'duplicate', stage: 'ingress' });
|
|
244
302
|
this.context.diagnostics?.route('duplicate');
|
|
245
303
|
logger.debug(formatCompact({
|
|
246
304
|
op: 'inbound_duplicate',
|
|
@@ -250,6 +308,7 @@ export class InboundRuntime {
|
|
|
250
308
|
return result;
|
|
251
309
|
}
|
|
252
310
|
if (recordOnly === 'dedup_error') {
|
|
311
|
+
ledger.report({ outcome: 'dropped_dedup_error', reason: 'dedup_error', stage: 'ingress' });
|
|
253
312
|
this.context.diagnostics?.route('dedup_error');
|
|
254
313
|
this.context.publish({
|
|
255
314
|
direction: 'inbound',
|
|
@@ -262,6 +321,7 @@ export class InboundRuntime {
|
|
|
262
321
|
return result;
|
|
263
322
|
}
|
|
264
323
|
if (origin === 'member' || origin === 'peer_bot') {
|
|
324
|
+
ledger.report({ outcome: 'ignored_bot', reason: origin, stage: 'ingress' });
|
|
265
325
|
this.context.diagnostics?.route('bot_origin');
|
|
266
326
|
logger.debug(formatCompact({
|
|
267
327
|
op: 'bot_origin_recorded',
|
|
@@ -279,12 +339,18 @@ export class InboundRuntime {
|
|
|
279
339
|
});
|
|
280
340
|
return result;
|
|
281
341
|
}
|
|
342
|
+
ledger.enter('interaction');
|
|
282
343
|
const claimed = await this.context.inboundClaim?.(message) === true;
|
|
344
|
+
const claim = claimed ? undefined : this.#resolveClaim(message);
|
|
283
345
|
if (claimed) {
|
|
346
|
+
ledger.report({ outcome: 'interaction_answered', reason: 'prompt', stage: 'interaction' });
|
|
284
347
|
this.context.diagnostics?.route('interaction');
|
|
285
348
|
result = interactionResult(requester);
|
|
286
349
|
}
|
|
287
|
-
else if (
|
|
350
|
+
else if (claim) {
|
|
351
|
+
ledger.report(claim.answerLike
|
|
352
|
+
? { outcome: 'interaction_answered', reason: 'prompt', stage: 'interaction', ...(claim.owner ? { owner: claim.owner } : {}) }
|
|
353
|
+
: { outcome: 'interaction_consumed', reason: 'prompt_captured', stage: 'interaction', ...(claim.owner ? { owner: claim.owner } : {}) });
|
|
288
354
|
this.context.diagnostics?.route('interaction');
|
|
289
355
|
if (input.message)
|
|
290
356
|
this.context.markInteractionAnswer?.(input.message);
|
|
@@ -349,20 +415,72 @@ export class InboundRuntime {
|
|
|
349
415
|
return commandOperation && this.context.runCommandOperation
|
|
350
416
|
? await this.context.runCommandOperation(commandOperation, execute) : await execute();
|
|
351
417
|
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
failed = true;
|
|
420
|
+
failure = error;
|
|
421
|
+
throw error;
|
|
422
|
+
}
|
|
352
423
|
finally {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
424
|
+
await close();
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/** Claim resolution with the answer classification, when the coordinator offers it. */
|
|
428
|
+
#resolveClaim(message) {
|
|
429
|
+
const interactions = this.context.interactions;
|
|
430
|
+
if (typeof interactions.resolveClaimDetailed === 'function')
|
|
431
|
+
return interactions.resolveClaimDetailed(message) || undefined;
|
|
432
|
+
return interactions.resolveClaim(message) ? { answerLike: true } : undefined;
|
|
433
|
+
}
|
|
434
|
+
/** Settles the ledger once (ADR 0061 §4.1); never throws over the original failure. */
|
|
435
|
+
#settleOutcome(ledger, failed, failure) {
|
|
436
|
+
let record;
|
|
437
|
+
try {
|
|
438
|
+
if (failed) {
|
|
439
|
+
const errorId = createErrorId();
|
|
440
|
+
record = ledger.settle({ error: { errorId, ...(failure instanceof Error ? { name: failure.name, message: failure.message } : { message: String(failure) }) } });
|
|
441
|
+
let conv;
|
|
358
442
|
try {
|
|
359
|
-
|
|
443
|
+
conv = formatConversationLog(record.conversation);
|
|
360
444
|
}
|
|
361
|
-
|
|
362
|
-
|
|
445
|
+
catch {
|
|
446
|
+
conv = 'unknown';
|
|
363
447
|
}
|
|
448
|
+
logger.error(formatCompact({ op: 'inbound_internal_error', errorId, conv,
|
|
449
|
+
messageId: record.messageId, stage: record.stage,
|
|
450
|
+
error: logSafeError(failure) }));
|
|
451
|
+
}
|
|
452
|
+
else {
|
|
453
|
+
record = ledger.settle();
|
|
364
454
|
}
|
|
365
455
|
}
|
|
456
|
+
catch (error) {
|
|
457
|
+
if (process.env.NODE_ENV === 'test' && !failed)
|
|
458
|
+
throw error;
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
try {
|
|
462
|
+
this.context.diagnostics?.outcome(record);
|
|
463
|
+
this.context.outcomes?.record(record);
|
|
464
|
+
}
|
|
465
|
+
catch { /* silent-ok: observer — the outcome projection never changes the message's result */ }
|
|
466
|
+
let conv;
|
|
467
|
+
try {
|
|
468
|
+
conv = formatConversationLog(record.conversation);
|
|
469
|
+
}
|
|
470
|
+
catch {
|
|
471
|
+
conv = 'unknown';
|
|
472
|
+
}
|
|
473
|
+
const fields = { op: 'inbound_outcome', conv, messageId: record.messageId,
|
|
474
|
+
outcome: record.outcome, reason: record.reason, stage: record.stage, addressed: record.addressed, errorId: record.errorId };
|
|
475
|
+
if (record.outcome === 'unrecorded') {
|
|
476
|
+
logger.warn(formatCompact({ ...fields, op: 'inbound_outcome_unrecorded', lastStage: record.lastStage }));
|
|
477
|
+
}
|
|
478
|
+
else if (!record.addressed && QUIET_MESSAGE_OUTCOMES.has(record.outcome)) {
|
|
479
|
+
logger.debug(formatCompact(fields));
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
logger.info(formatCompact(fields));
|
|
483
|
+
}
|
|
366
484
|
}
|
|
367
485
|
async #receiveCanonicalEndpointEvent(source) {
|
|
368
486
|
const lease = this.context.acquire();
|
|
@@ -478,3 +596,10 @@ function adapterSender(sender) {
|
|
|
478
596
|
...(platform ? { platform } : {}),
|
|
479
597
|
});
|
|
480
598
|
}
|
|
599
|
+
const MAX_LOGGED_ERROR_CHARS = 500;
|
|
600
|
+
/** Error text for the instance log: secrets masked (decision audit patterns), one line, bounded. */
|
|
601
|
+
function logSafeError(failure) {
|
|
602
|
+
const text = redactSecretText(failure instanceof Error ? failure.message : String(failure)).replace(/\p{Cc}+/gu, ' ').trim();
|
|
603
|
+
const chars = [...text];
|
|
604
|
+
return chars.length > MAX_LOGGED_ERROR_CHARS ? `${chars.slice(0, MAX_LOGGED_ERROR_CHARS - 1).join('')}…` : text;
|
|
605
|
+
}
|
|
@@ -11,13 +11,25 @@ import { type CapturedEndpointOperation, type Message, type MessageDispatchResul
|
|
|
11
11
|
import type { RuntimeInteractionCoordinator } from './interaction-runtime.js';
|
|
12
12
|
import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
13
13
|
import type { MessageDispatchOutcome } from './message-dispatcher.js';
|
|
14
|
+
import type { MessageOutcomeCandidate } from './message-outcome.js';
|
|
14
15
|
export { arbitrateRoomInboundDeduplication, buildRoomInboundRouteInput, resolveRoomMembership, type InboundRoomRouteRequest, } from './inbound-dedup.js';
|
|
15
16
|
/** Generation-owned hooks before ordinary dispatch and after it misses. */
|
|
16
17
|
export interface IngressRoute {
|
|
17
|
-
preRoute?(message: Message, lease: SnapshotLease, requester: PluginId, conversationSequence: number | undefined): Promise<boolean>;
|
|
18
|
+
preRoute?(message: Message, lease: SnapshotLease, requester: PluginId, conversationSequence: number | undefined): Promise<boolean | IngressRouteResult>;
|
|
18
19
|
shouldRouteBeforeDispatch?(message: Message): boolean;
|
|
19
|
-
route(message: Message, lease: SnapshotLease, requester: PluginId, conversationSequence: number | undefined): Promise<boolean>;
|
|
20
|
+
route(message: Message, lease: SnapshotLease, requester: PluginId, conversationSequence: number | undefined): Promise<boolean | IngressRouteResult>;
|
|
20
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* ADR 0061 §4.1: what an ingress route returns besides "handled". `outcome` is reported to the
|
|
24
|
+
* message's outcome ledger; a route may also report directly with `reportInboundOutcome`.
|
|
25
|
+
* @public
|
|
26
|
+
*/
|
|
27
|
+
export interface IngressRouteResult {
|
|
28
|
+
readonly handled: boolean;
|
|
29
|
+
readonly outcome?: MessageOutcomeCandidate;
|
|
30
|
+
}
|
|
31
|
+
/** Normalizes the legacy boolean and the structured route result. */
|
|
32
|
+
export declare function readIngressRouteResult(message: Message, result: boolean | IngressRouteResult | undefined): boolean;
|
|
21
33
|
export declare const ingressRouteToken: import("@zhin.js/plugin-runtime").Token<IngressRoute>;
|
|
22
34
|
export declare function resolveIngressRoute(snapshot: RuntimeSnapshot): IngressRoute | undefined;
|
|
23
35
|
/**
|
|
@@ -148,7 +160,7 @@ export interface InboundSpineOutcome {
|
|
|
148
160
|
};
|
|
149
161
|
}
|
|
150
162
|
export declare function executeInboundTurnSpine(envelope: InboundTurnEnvelope, control?: InboundTerminalControl): Promise<InboundSpineOutcome>;
|
|
151
|
-
export type InboundInteractionPort = Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'create' | 'createForMessage' | 'createFromUnknown' | 'dispatch' | 'resolveClaim'> & Partial<Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'hasPendingAnswer'>>;
|
|
163
|
+
export type InboundInteractionPort = Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'create' | 'createForMessage' | 'createFromUnknown' | 'dispatch' | 'resolveClaim'> & Partial<Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'hasPendingAnswer' | 'resolveClaimDetailed'>>;
|
|
152
164
|
export interface InboundOutcome {
|
|
153
165
|
readonly dispatch: MessageDispatchResult;
|
|
154
166
|
readonly reply?: {
|
|
@@ -199,3 +211,8 @@ export declare function interactionResult(requester: PluginId): MessageDispatchR
|
|
|
199
211
|
export declare function withRequestActionScope(request: IncomingRequest, dispatch: (request: IncomingRequest) => Promise<void>, assertOperation: () => void): Promise<void>;
|
|
200
212
|
export declare function handlers(snapshot: RuntimeSnapshot): HandlerIndex | undefined;
|
|
201
213
|
export declare function withEndpointEventPayload<TPayload, TClient, TName extends string>(source: EndpointEvent<unknown, TClient, TName>, payload: TPayload): EndpointEvent<TPayload, TClient, TName>;
|
|
214
|
+
/**
|
|
215
|
+
* ADR 0061 §1: a private chat, a mention, the command prefix, or a reply (to the bot; the outbound
|
|
216
|
+
* ledger check happens in the inbound runtime, which passes `repliedToBot`).
|
|
217
|
+
*/
|
|
218
|
+
export declare function isAddressedMessage(message: Pick<Message, 'conversation' | 'mentioned' | 'content' | 'commandPrefix'>, repliedToBot?: boolean): boolean;
|
|
@@ -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
|