@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,16 +1,27 @@
1
1
  import { normalizePlatformStanding } from '@zhin.js/im-contract';
2
- import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
3
- import { RuntimeMessage, operationEndpoint, } from './contracts.js';
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 { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.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';
9
+ import { defaultCommandPrefixResolver, MessageDispatcher, normalizeCommandInputText } from './message-dispatcher.js';
7
10
  import { suggestCommandReply } from './command-suggestion.js';
8
11
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
9
12
  const logger = getLogger('im.inbound');
13
+ /** Conversations remembered for the per-minute `not_addressed` info line (bounded; cleared when full). */
14
+ const QUIET_LOG_CONVERSATIONS = 2_000;
10
15
  /** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
11
16
  export class InboundRuntime {
12
17
  context;
13
18
  #dispatcher;
19
+ /**
20
+ * zhinjs/zhin#1250 (`unaddressed-message-no-record`): the minute of the last `not_addressed` line
21
+ * logged at info per conversation. The first unaddressed message of a conversation each minute
22
+ * is logged at info (the instance log the Console shows), the rest of that minute at debug.
23
+ */
24
+ #quietLogged = new Map();
14
25
  constructor(context, commandPrefix) {
15
26
  this.context = context;
16
27
  this.#dispatcher = new MessageDispatcher(commandPrefix === undefined
@@ -38,16 +49,55 @@ export class InboundRuntime {
38
49
  }
39
50
  async #receiveMessage(source, admission) {
40
51
  const receivedAt = Date.now();
52
+ // ADR 0061 §4.1: one ledger per message, settled exactly once in `finally`.
53
+ const ledger = new InboundOutcomeLedger({
54
+ conversation: { ...source.payload?.conversation, endpoint: { id: source.endpoint.id, adapter: source.endpoint.adapter } },
55
+ // A malformed event without a payload still settles an outcome (the code below then throws).
56
+ ...(typeof source.payload?.sender?.id === 'string' ? { senderId: source.payload.sender.id } : {}),
57
+ ...(typeof source.payload?.message?.id === 'string' ? { messageId: source.payload.message.id } : {}),
58
+ receivedAt,
59
+ });
60
+ let failure;
61
+ let failed = false;
41
62
  const lease = this.context.acquire();
42
63
  let active = true;
43
64
  let commandOperation;
44
65
  let endpointLease;
66
+ /** Drains the operation, releases leases and settles the outcome; a drain failure is a failure. */
67
+ const close = async () => {
68
+ try {
69
+ await commandOperation?.finish();
70
+ }
71
+ catch (error) {
72
+ // Without an earlier failure the drain failure is this message's failure and propagates;
73
+ // with one, it is only logged and the original exception is the one the caller sees.
74
+ if (failed) {
75
+ logger.warn(formatCompact({ op: 'inbound_operation_finish_failed', error: logSafeError(error) }));
76
+ }
77
+ else {
78
+ failed = true;
79
+ failure = error;
80
+ throw error;
81
+ }
82
+ }
83
+ finally {
84
+ active = false;
85
+ try {
86
+ endpointLease?.release();
87
+ }
88
+ finally {
89
+ this.context.release(lease);
90
+ this.#settleOutcome(ledger, failed, failure);
91
+ }
92
+ }
93
+ };
45
94
  try {
46
95
  const adapter = source.endpoint.id;
47
96
  this.context.diagnostics?.begin(lease.value.generation, {
48
97
  ...source.payload.conversation,
49
98
  endpoint: { id: source.endpoint.id, adapter: source.endpoint.adapter },
50
99
  }, source.payload.message?.id);
100
+ ledger.linkDiagnostic(this.context.diagnostics?.currentId());
51
101
  const adapters = requireAdapters(lease.value);
52
102
  const requester = adapters.owner(adapter);
53
103
  endpointLease = adapters.acquireInbound(adapter, source.client);
@@ -69,11 +119,14 @@ export class InboundRuntime {
69
119
  ...(source.payload.message ? { message: Object.freeze({ ...source.payload.message, conversation }) } : {}),
70
120
  });
71
121
  this.context.diagnostics?.identify(conversation);
122
+ // ADR 0060 §3.3: a one-time secret is recognized before it is logged, recorded or routed.
123
+ const secret = this.#matchSecret(input, lease.value);
124
+ const visibleContent = secret ? secret.redacted : input.content;
72
125
  logger.debug(formatCompact({
73
126
  op: 'receive',
74
127
  conv: formatConversationLog(conversation),
75
128
  sender: `${input.sender?.name || 'undefined'}(${input.sender?.id || 'undefined'})`,
76
- preview: truncatePreview(input.content),
129
+ preview: truncatePreview(visibleContent),
77
130
  }));
78
131
  const enrichedSender = this.context.enrichSender
79
132
  ? this.context.enrichSender(input.sender, conversation, lease.value)
@@ -90,6 +143,9 @@ export class InboundRuntime {
90
143
  const origin = classified?.origin;
91
144
  this.context.diagnostics?.step('origin', origin ?? 'unclassified');
92
145
  if (origin === 'self') {
146
+ // One of our own accounts posted the secret where others saw it: revoke it like any drop.
147
+ await this.#discardSecret(secret);
148
+ ledger.report({ outcome: 'ignored_self', reason: 'self_echo', stage: 'ingress' });
93
149
  this.context.diagnostics?.route('self_echo');
94
150
  logger.debug(formatCompact({
95
151
  op: 'self_echo',
@@ -106,6 +162,10 @@ export class InboundRuntime {
106
162
  ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
107
163
  });
108
164
  if (!readiness.ready) {
165
+ await this.#discardSecret(secret);
166
+ ledger.markAddressed(input.mentioned === true || conversation.kind === 'private');
167
+ ledger.report({ outcome: 'dropped_unready', reason: 'venue_unready', stage: 'ingress',
168
+ detail: readiness.unreadyEndpoints?.join(',') ?? '' });
109
169
  logger.warn(formatCompact({
110
170
  op: 'venue_unready',
111
171
  conv: formatConversationLog(conversation),
@@ -135,6 +195,8 @@ export class InboundRuntime {
135
195
  },
136
196
  });
137
197
  const mentioned = routedTarget ? true : input.mentioned;
198
+ ledger.markAddressed(conversation.kind === 'private' || mentioned === true
199
+ || (input.replyTo?.id !== undefined && this.context.resolveReplyTarget?.(conversation, input.replyTo.id) !== undefined));
138
200
  const locale = await messageLocale(lease.value, conversation, enrichedSender?.id);
139
201
  let operationReplied = false;
140
202
  const operationReply = (content, replyRequester = requester, targetConversation) => {
@@ -153,8 +215,8 @@ export class InboundRuntime {
153
215
  content,
154
216
  incoming: {
155
217
  sender: enrichedSender,
156
- content: input.content,
157
- segments: input.segments,
218
+ content: visibleContent,
219
+ ...(secret ? {} : { segments: input.segments }),
158
220
  messageId: input.message?.id,
159
221
  timestamp: receivedAt,
160
222
  endpointId: input.endpointId,
@@ -163,8 +225,17 @@ export class InboundRuntime {
163
225
  }, lease.value);
164
226
  // A held Message may reply from another async caller while its operation is
165
227
  // draining. Restore that Message's private controller, not the caller's scope.
166
- return commandOperation && this.context.runCommandOperation
228
+ const delivery = commandOperation && this.context.runCommandOperation
167
229
  ? this.context.runCommandOperation(commandOperation, deliver) : deliver();
230
+ return Promise.resolve(delivery).then((receipt) => {
231
+ if (receipt?.status === 'sent')
232
+ ledger.noteReplyDelivered(replyRequester);
233
+ if (receipt && receipt.status !== 'sent') {
234
+ ledger.report({ outcome: 'delivery_failed', reason: receipt.failure?.code ?? receipt.status, stage: 'delivery',
235
+ ...(receipt.failure?.deliveryUnknown ? { facets: ['delivery_unknown'] } : {}) });
236
+ }
237
+ return receipt;
238
+ });
168
239
  };
169
240
  commandOperation = this.context.commandExecution?.openOperation({
170
241
  snapshot: lease.value, conversation, senderId: enrichedSender?.id,
@@ -232,15 +303,19 @@ export class InboundRuntime {
232
303
  boundEndpoint.assertActive();
233
304
  },
234
305
  ...(origin ? { origin } : {}),
306
+ outcomes: inboundOutcomeFacade(ledger),
235
307
  presentation: {
236
308
  locale,
237
309
  resolveCommands: (message) => this.#dispatcher.commandEnvironment(message, lease.value),
238
310
  },
239
311
  });
240
- const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
312
+ // A secret-bearing message never enters the conversation history.
313
+ const conversationSequence = secret ? undefined : await this.context.recordIncoming(input, enrichedSender);
241
314
  let result = Object.freeze({ matched: false });
242
315
  let reply;
316
+ ledger.markAddressed(isAddressedMessage(message));
243
317
  if (recordOnly === 'duplicate') {
318
+ ledger.report({ outcome: 'dropped_duplicate', reason: 'duplicate', stage: 'ingress' });
244
319
  this.context.diagnostics?.route('duplicate');
245
320
  logger.debug(formatCompact({
246
321
  op: 'inbound_duplicate',
@@ -250,18 +325,22 @@ export class InboundRuntime {
250
325
  return result;
251
326
  }
252
327
  if (recordOnly === 'dedup_error') {
328
+ await this.#discardSecret(secret);
329
+ ledger.report({ outcome: 'dropped_dedup_error', reason: 'dedup_error', stage: 'ingress' });
253
330
  this.context.diagnostics?.route('dedup_error');
254
331
  this.context.publish({
255
332
  direction: 'inbound',
256
333
  conversation,
257
334
  ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
258
- contentPreview: previewMessageContent(input.content),
335
+ contentPreview: previewMessageContent(visibleContent),
259
336
  ...(input.message?.id ? { messageId: input.message.id } : {}),
260
337
  timestamp: receivedAt,
261
338
  });
262
339
  return result;
263
340
  }
264
341
  if (origin === 'member' || origin === 'peer_bot') {
342
+ await this.#discardSecret(secret);
343
+ ledger.report({ outcome: 'ignored_bot', reason: origin, stage: 'ingress' });
265
344
  this.context.diagnostics?.route('bot_origin');
266
345
  logger.debug(formatCompact({
267
346
  op: 'bot_origin_recorded',
@@ -273,18 +352,45 @@ export class InboundRuntime {
273
352
  direction: 'inbound',
274
353
  conversation,
275
354
  ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
276
- contentPreview: previewMessageContent(input.content),
355
+ contentPreview: previewMessageContent(visibleContent),
356
+ ...(input.message?.id ? { messageId: input.message.id } : {}),
357
+ timestamp: receivedAt,
358
+ });
359
+ return result;
360
+ }
361
+ if (secret) {
362
+ // Handled here alone: no middleware, handler, command, interaction prompt or Agent sees it.
363
+ ledger.enter('command');
364
+ this.context.diagnostics?.route('command');
365
+ const content = await secret.handle(message);
366
+ ledger.report({ outcome: 'command_replied', reason: 'secret', stage: 'command', command: secret.name, owner: lease.value.root });
367
+ result = Object.freeze({ matched: true, status: 'executed', command: secret.name, owner: lease.value.root });
368
+ this.context.diagnostics?.dispatch(result);
369
+ await commandOperation?.stopProgress();
370
+ if (content !== undefined)
371
+ await message.$replyFrom(lease.value.root, content);
372
+ this.context.publish({
373
+ direction: 'inbound',
374
+ conversation,
375
+ ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
376
+ contentPreview: previewMessageContent(visibleContent),
277
377
  ...(input.message?.id ? { messageId: input.message.id } : {}),
278
378
  timestamp: receivedAt,
279
379
  });
280
380
  return result;
281
381
  }
382
+ ledger.enter('interaction');
282
383
  const claimed = await this.context.inboundClaim?.(message) === true;
384
+ const claim = claimed ? undefined : this.#resolveClaim(message);
283
385
  if (claimed) {
386
+ ledger.report({ outcome: 'interaction_answered', reason: 'prompt', stage: 'interaction' });
284
387
  this.context.diagnostics?.route('interaction');
285
388
  result = interactionResult(requester);
286
389
  }
287
- else if (this.context.interactions.resolveClaim(message)) {
390
+ else if (claim) {
391
+ ledger.report(claim.answerLike
392
+ ? { outcome: 'interaction_answered', reason: 'prompt', stage: 'interaction', ...(claim.owner ? { owner: claim.owner } : {}) }
393
+ : { outcome: 'interaction_consumed', reason: 'prompt_captured', stage: 'interaction', ...(claim.owner ? { owner: claim.owner } : {}) });
288
394
  this.context.diagnostics?.route('interaction');
289
395
  if (input.message)
290
396
  this.context.markInteractionAnswer?.(input.message);
@@ -340,7 +446,7 @@ export class InboundRuntime {
340
446
  direction: 'inbound',
341
447
  conversation,
342
448
  ...(enrichedSender !== undefined ? { sender: enrichedSender } : {}),
343
- contentPreview: previewMessageContent(input.content),
449
+ contentPreview: previewMessageContent(visibleContent),
344
450
  ...(input.message?.id ? { messageId: input.message.id } : {}),
345
451
  timestamp: receivedAt,
346
452
  });
@@ -349,22 +455,154 @@ export class InboundRuntime {
349
455
  return commandOperation && this.context.runCommandOperation
350
456
  ? await this.context.runCommandOperation(commandOperation, execute) : await execute();
351
457
  }
458
+ catch (error) {
459
+ failed = true;
460
+ failure = error;
461
+ throw error;
462
+ }
352
463
  finally {
353
- try {
354
- await commandOperation?.finish();
355
- }
356
- finally {
357
- active = false;
464
+ await close();
465
+ }
466
+ }
467
+ /** The guard's match for this message; a throwing guard matches nothing (logged). */
468
+ #matchSecret(input, snapshot) {
469
+ const guard = this.context.inboundSecret;
470
+ if (!guard)
471
+ return undefined;
472
+ try {
473
+ return guard.match({ text: normalizeCommandInputText(input), prefix: this.#dispatcher.prefixOf(input, snapshot),
474
+ conversation: input.conversation, snapshot });
475
+ }
476
+ catch (error) {
477
+ logger.warn(formatCompact({ op: 'inbound_secret_guard_failed', error: logSafeError(error) }));
478
+ return undefined;
479
+ }
480
+ }
481
+ /**
482
+ * ADR 0060 §3.3 (#1289 review): an Endpoint event other than a message (native platform events,
483
+ * notices, requests and their comments, system events) that carries the secret is neither recorded
484
+ * nor dispatched to Handlers.
485
+ */
486
+ #withholdSecretEvent(event) {
487
+ if (!this.#nativeCarriesSecret(event))
488
+ return false;
489
+ logger.debug(formatCompact({ op: 'native_secret_withheld', event: event.name, endpoint: String(event.endpoint.id) }));
490
+ return true;
491
+ }
492
+ #nativeCarriesSecret(event) {
493
+ const inspect = this.context.inboundSecret?.inspectNative;
494
+ if (!inspect)
495
+ return false;
496
+ try {
497
+ return inspect.call(this.context.inboundSecret, event.payload, { name: event.name }) === true;
498
+ }
499
+ catch (error) {
500
+ // Fail closed: an event that cannot be inspected is not dispatched while a secret is open.
501
+ logger.warn(formatCompact({ op: 'inbound_secret_guard_failed', error: logSafeError(error) }));
502
+ return true;
503
+ }
504
+ }
505
+ /**
506
+ * A withheld notice, request or system event was still seen on the platform (an admin reads a join
507
+ * request's comment): the guard revokes the secret it carries (#1291 review). `platform.receive` is
508
+ * not revoked here: the same message's `message.receive` still reaches the claim.
509
+ */
510
+ async #discardNativeSecret(event) {
511
+ const guard = this.context.inboundSecret;
512
+ try {
513
+ await guard?.discardNative?.(event.payload, { name: event.name });
514
+ }
515
+ catch (error) {
516
+ logger.warn(formatCompact({ op: 'inbound_secret_discard_failed', error: logSafeError(error) }));
517
+ }
518
+ }
519
+ /** A dropped message's secret is revoked; a failing guard is logged, never the message's failure. */
520
+ async #discardSecret(secret) {
521
+ try {
522
+ await secret?.discard?.();
523
+ }
524
+ catch (error) {
525
+ logger.warn(formatCompact({ op: 'inbound_secret_discard_failed', error: logSafeError(error) }));
526
+ }
527
+ }
528
+ /** Claim resolution with the answer classification, when the coordinator offers it. */
529
+ #resolveClaim(message) {
530
+ const interactions = this.context.interactions;
531
+ if (typeof interactions.resolveClaimDetailed === 'function')
532
+ return interactions.resolveClaimDetailed(message) || undefined;
533
+ return interactions.resolveClaim(message) ? { answerLike: true } : undefined;
534
+ }
535
+ /** True for the first `not_addressed` of `conv` in the minute of `at` (see {@link InboundRuntime.#quietLogged}). */
536
+ #firstQuietThisMinute(conv, at) {
537
+ const minute = Math.floor(at / 60_000);
538
+ if (this.#quietLogged.get(conv) === minute)
539
+ return false;
540
+ if (this.#quietLogged.size >= QUIET_LOG_CONVERSATIONS && !this.#quietLogged.has(conv))
541
+ this.#quietLogged.clear();
542
+ this.#quietLogged.set(conv, minute);
543
+ return true;
544
+ }
545
+ /** Settles the ledger once (ADR 0061 §4.1); never throws over the original failure. */
546
+ #settleOutcome(ledger, failed, failure) {
547
+ let record;
548
+ try {
549
+ if (failed) {
550
+ const errorId = createErrorId();
551
+ record = ledger.settle({ error: { errorId, ...(failure instanceof Error ? { name: failure.name, message: failure.message } : { message: String(failure) }) } });
552
+ let conv;
358
553
  try {
359
- endpointLease?.release();
554
+ conv = formatConversationLog(record.conversation);
360
555
  }
361
- finally {
362
- this.context.release(lease);
556
+ catch {
557
+ conv = 'unknown';
363
558
  }
559
+ logger.error(formatCompact({ op: 'inbound_internal_error', errorId, conv,
560
+ messageId: record.messageId, stage: record.stage,
561
+ error: logSafeError(failure) }));
364
562
  }
563
+ else {
564
+ record = ledger.settle();
565
+ }
566
+ }
567
+ catch (error) {
568
+ if (process.env.NODE_ENV === 'test' && !failed)
569
+ throw error;
570
+ return;
571
+ }
572
+ try {
573
+ this.context.diagnostics?.outcome(record);
574
+ this.context.outcomes?.record(record);
575
+ }
576
+ catch { /* silent-ok: observer — the outcome projection never changes the message's result */ }
577
+ let conv;
578
+ try {
579
+ conv = formatConversationLog(record.conversation);
580
+ }
581
+ catch {
582
+ conv = 'unknown';
583
+ }
584
+ const fields = { op: 'inbound_outcome', conv, messageId: record.messageId,
585
+ outcome: record.outcome, reason: record.reason, stage: record.stage, addressed: record.addressed, errorId: record.errorId };
586
+ if (record.outcome === 'unrecorded') {
587
+ logger.warn(formatCompact({ ...fields, op: 'inbound_outcome_unrecorded', lastStage: record.lastStage }));
588
+ }
589
+ else if (!record.addressed && QUIET_MESSAGE_OUTCOMES.has(record.outcome)) {
590
+ if (record.outcome === 'not_addressed' && this.#firstQuietThisMinute(conv, record.settledAt)) {
591
+ logger.info(formatCompact({ ...fields, sampled: 'first_per_minute' }));
592
+ }
593
+ else {
594
+ logger.debug(formatCompact(fields));
595
+ }
596
+ }
597
+ else {
598
+ logger.info(formatCompact(fields));
365
599
  }
366
600
  }
367
601
  async #receiveCanonicalEndpointEvent(source) {
602
+ if (this.#withholdSecretEvent(source)) {
603
+ await this.#discardNativeSecret(source);
604
+ return;
605
+ }
368
606
  const lease = this.context.acquire();
369
607
  let active = true;
370
608
  let endpointLease;
@@ -423,6 +661,8 @@ export class InboundRuntime {
423
661
  }
424
662
  }
425
663
  async #receiveSideEvent(event) {
664
+ if (this.#withholdSecretEvent(event))
665
+ return;
426
666
  let active = true;
427
667
  const lease = this.context.acquire();
428
668
  let endpointLease;
@@ -478,3 +718,10 @@ function adapterSender(sender) {
478
718
  ...(platform ? { platform } : {}),
479
719
  });
480
720
  }
721
+ const MAX_LOGGED_ERROR_CHARS = 500;
722
+ /** Error text for the instance log: secrets masked (decision audit patterns), one line, bounded. */
723
+ function logSafeError(failure) {
724
+ const text = redactSecretText(failure instanceof Error ? failure.message : String(failure)).replace(/\p{Cc}+/gu, ' ').trim();
725
+ const chars = [...text];
726
+ return chars.length > MAX_LOGGED_ERROR_CHARS ? `${chars.slice(0, MAX_LOGGED_ERROR_CHARS - 1).join('')}…` : text;
727
+ }
@@ -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;