@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.
@@ -6,6 +6,9 @@ export function assertUserInteractionRequest(request) {
6
6
  if (request.timeout !== undefined && (!Number.isFinite(request.timeout) || request.timeout <= 0)) {
7
7
  throw new RangeError('User interaction timeout must be a positive finite number');
8
8
  }
9
+ if (request.answeredBy !== undefined && request.answeredBy !== 'target' && request.answeredBy !== 'anyone') {
10
+ throw new TypeError("User interaction answeredBy must be 'target' or 'anyone'");
11
+ }
9
12
  if (request.type === 'text' && !validRange(request.minLength, request.maxLength)) {
10
13
  throw new RangeError('User interaction text length range is invalid');
11
14
  }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * ADR 0062 §23 / Q23: group interjection ("插话", ambient engagement) is a feature in the layered
3
+ * feature overrides (ADR 0050 / 0055). The global default stays `ai.trigger.ambient` in the
4
+ * configuration file; adapter / endpoint / conversation switches are stored in `feature_overrides`
5
+ * under the reserved feature id {@link AMBIENT_FEATURE_ID} (not a Plugin instance path, so it can
6
+ * never collide with one).
7
+ *
8
+ * Stored row shape: `enabled: false` switches interjection off at that level and locks the levels
9
+ * below (as for Plugins); `patch.engage === true` switches it on there (needed because the global
10
+ * default is off for conversations outside `ai.trigger.ambient.conversations`).
11
+ */
12
+ import { type FeatureConfigLevel, type FeatureConversationOverride, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
13
+ /** Reserved feature id of group interjection in the feature override store. @public */
14
+ export declare const AMBIENT_FEATURE_ID = "@ambient";
15
+ /** Words that name group interjection in chat feature commands (`功能 关闭 插话`). @public */
16
+ export declare const AMBIENT_FEATURE_WORDS: ReadonlySet<string>;
17
+ /** Patch field marking an explicit "on" override. @public */
18
+ export declare const AMBIENT_ENGAGE_FIELD = "engage";
19
+ /** Effective interjection switch for one conversation. @public */
20
+ export interface AmbientSwitchResolution {
21
+ readonly enabled: boolean;
22
+ /** Level that decided: `global` is the configuration file default. */
23
+ readonly source: FeatureConfigLevel;
24
+ /** Set when an upper level switched it off (lower levels cannot turn it back on). */
25
+ readonly lockedBy?: Exclude<FeatureConfigLevel, 'global' | 'conversation'>;
26
+ }
27
+ type OverrideReader = {
28
+ get(plugin: string, key: string): FeatureConversationOverride | undefined;
29
+ };
30
+ /** Ancestor keys (adapter, endpoint, conversation) of a resolution key that exist. */
31
+ export declare function ambientScopeKeys(key: string): ReadonlyArray<readonly [Exclude<FeatureConfigLevel, 'global'>, string]>;
32
+ /** Resolves the switch from stored overrides at `key` on top of the file default `globalEnabled`. @public */
33
+ export declare function resolveAmbientSwitchAt(reader: OverrideReader | undefined, key: string | undefined, globalEnabled: boolean, level?: Exclude<FeatureConfigLevel, 'global'>): AmbientSwitchResolution;
34
+ /**
35
+ * Whether interjection is on for a message's conversation in this generation: the stored
36
+ * overrides on top of `globalEnabled` (the file allowlist `ai.trigger.ambient.conversations`).
37
+ * @public
38
+ */
39
+ export declare function resolveAmbientSwitch(snapshot: Pick<RuntimeSnapshot, 'root' | 'resources' | 'projections' | 'tree'> | undefined, message: Readonly<{
40
+ conversation: Readonly<{
41
+ endpoint: Readonly<{
42
+ id: string;
43
+ }>;
44
+ kind: string;
45
+ id: string;
46
+ }>;
47
+ endpointId?: string;
48
+ }>, globalEnabled: boolean): AmbientSwitchResolution;
49
+ export {};
@@ -0,0 +1,70 @@
1
+ /**
2
+ * ADR 0062 §23 / Q23: group interjection ("插话", ambient engagement) is a feature in the layered
3
+ * feature overrides (ADR 0050 / 0055). The global default stays `ai.trigger.ambient` in the
4
+ * configuration file; adapter / endpoint / conversation switches are stored in `feature_overrides`
5
+ * under the reserved feature id {@link AMBIENT_FEATURE_ID} (not a Plugin instance path, so it can
6
+ * never collide with one).
7
+ *
8
+ * Stored row shape: `enabled: false` switches interjection off at that level and locks the levels
9
+ * below (as for Plugins); `patch.engage === true` switches it on there (needed because the global
10
+ * default is off for conversations outside `ai.trigger.ambient.conversations`).
11
+ */
12
+ import { parseFeatureResolutionKey, readFeatureConversationOverrides, resolveEndpointFeatureKey, } from '@zhin.js/plugin-runtime';
13
+ /** Reserved feature id of group interjection in the feature override store. @public */
14
+ export const AMBIENT_FEATURE_ID = '@ambient';
15
+ /** Words that name group interjection in chat feature commands (`功能 关闭 插话`). @public */
16
+ export const AMBIENT_FEATURE_WORDS = new Set(['插话', '群插话', 'ambient']);
17
+ /** Patch field marking an explicit "on" override. @public */
18
+ export const AMBIENT_ENGAGE_FIELD = 'engage';
19
+ /** Ancestor keys (adapter, endpoint, conversation) of a resolution key that exist. */
20
+ export function ambientScopeKeys(key) {
21
+ let parsed;
22
+ try {
23
+ parsed = parseFeatureResolutionKey(key);
24
+ }
25
+ catch {
26
+ return [];
27
+ }
28
+ if (!parsed.adapter)
29
+ return [];
30
+ const keys = [['adapter', parsed.adapter]];
31
+ if (parsed.endpointId !== undefined)
32
+ keys.push(['endpoint', `${parsed.adapter}/${parsed.endpointId}`]);
33
+ if (parsed.conversation !== undefined)
34
+ keys.push(['conversation', key]);
35
+ return keys;
36
+ }
37
+ /** Resolves the switch from stored overrides at `key` on top of the file default `globalEnabled`. @public */
38
+ export function resolveAmbientSwitchAt(reader, key, globalEnabled, level) {
39
+ if (!reader || !key)
40
+ return Object.freeze({ enabled: globalEnabled, source: 'global' });
41
+ let on;
42
+ for (const [scopeLevel, scopeKey] of ambientScopeKeys(key)) {
43
+ const row = reader.get(AMBIENT_FEATURE_ID, scopeKey);
44
+ if (row?.enabled === false) {
45
+ const locks = scopeLevel !== 'conversation' && level !== undefined && scopeLevel !== level;
46
+ return Object.freeze({ enabled: false, source: scopeLevel,
47
+ ...(locks ? { lockedBy: scopeLevel } : {}) });
48
+ }
49
+ if (row?.patch?.[AMBIENT_ENGAGE_FIELD] === true)
50
+ on = scopeLevel;
51
+ }
52
+ return Object.freeze(on ? { enabled: true, source: on } : { enabled: globalEnabled, source: 'global' });
53
+ }
54
+ /**
55
+ * Whether interjection is on for a message's conversation in this generation: the stored
56
+ * overrides on top of `globalEnabled` (the file allowlist `ai.trigger.ambient.conversations`).
57
+ * @public
58
+ */
59
+ export function resolveAmbientSwitch(snapshot, message, globalEnabled) {
60
+ if (!snapshot)
61
+ return Object.freeze({ enabled: globalEnabled, source: 'global' });
62
+ let key;
63
+ try {
64
+ key = resolveEndpointFeatureKey(snapshot, String(message.conversation.endpoint.id), message.endpointId, { kind: message.conversation.kind, id: message.conversation.id });
65
+ }
66
+ catch {
67
+ key = undefined;
68
+ }
69
+ return resolveAmbientSwitchAt(readFeatureConversationOverrides(snapshot), key, globalEnabled);
70
+ }
@@ -6,10 +6,13 @@ import { operationInputBinding, operationInputSignal, operationInputResources, o
6
6
  import type { ConversationRef, DeliveryReceipt, MessageRef, PlatformStanding, SelfProfilePort } from '@zhin.js/im-contract';
7
7
  import type { ChatRole, ChatRoleLevels } from '../../built/roles.js';
8
8
  import type { MessageOrigin } from './inbound-origin.js';
9
+ import { inboundOutcomeSink, type InboundOutcomeSink } from './inbound-outcome-ledger.js';
9
10
  import type { CoreReplyStream, OpenReplyStreamOptions } from './progressive-reply.js';
10
11
  import type { MediaRef, Segment } from '../../built/segment-contract/types.js';
11
12
  import type { OutboundMediaTrust } from '../../built/outbound-media-trust.js';
12
13
  export type { MediaRef, Segment };
14
+ /** A frozen `{ report, enter }` port over an outcome sink (idempotent for an existing facade). */
15
+ export declare function inboundOutcomeFacade(sink: InboundOutcomeSink): InboundOutcomeSink;
13
16
  /** Internal send binding retained by one inbound operation; never a wire/config field. */
14
17
  export declare const operationEndpoint: unique symbol;
15
18
  export interface OperationEndpointSource {
@@ -286,6 +289,11 @@ export interface RuntimeMessageOperation {
286
289
  }>) => OperationResourceView | undefined;
287
290
  readonly registerOperationView?: (view: object, owner: PluginId) => void;
288
291
  readonly presentation?: RuntimeMessagePresentation;
292
+ /**
293
+ * ADR 0061: report port of this message's outcome ledger, shared by every author view. Only
294
+ * `report` / `enter` are kept (a frozen facade); settling stays with the inbound runtime.
295
+ */
296
+ readonly outcomes?: InboundOutcomeSink;
289
297
  }
290
298
  /** Canonical runtime message with optional plugin-owned extensions. */
291
299
  export type Message<T extends object = {}> = MessageBase & T;
@@ -319,6 +327,8 @@ export declare class RuntimeMessage implements MessageBase {
319
327
  [operationInputResources](snapshot: RuntimeSnapshot): CapabilityOperationFactory | undefined;
320
328
  /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
321
329
  [operationInputSignal](): AbortSignal | undefined;
330
+ /** @internal The inbound outcome ledger (ADR 0061); reports after settlement are ignored by it. */
331
+ [inboundOutcomeSink](): InboundOutcomeSink | undefined;
322
332
  /** @internal The command/handler author's actual leased operation. */
323
333
  [interactionOperationScope](): InteractionOperationScope | undefined;
324
334
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
@@ -1,6 +1,19 @@
1
1
  import { commandFeatureId, isCommandIndex } from '@zhin.js/command';
2
2
  import { createRootPrivateToken, resolveLocale } from '@zhin.js/plugin-runtime';
3
3
  import { operationInputBinding, operationInputSignal, operationInputResources, operationSession } from '@zhin.js/feature-kit';
4
+ import { inboundOutcomeSink } from './inbound-outcome-ledger.js';
5
+ const facades = new WeakSet();
6
+ /** A frozen `{ report, enter }` port over an outcome sink (idempotent for an existing facade). */
7
+ export function inboundOutcomeFacade(sink) {
8
+ if (facades.has(sink))
9
+ return sink;
10
+ const facade = Object.freeze({
11
+ report: (candidate) => sink.report(candidate),
12
+ enter: (stage) => sink.enter(stage),
13
+ });
14
+ facades.add(facade);
15
+ return facade;
16
+ }
4
17
  /** Internal send binding retained by one inbound operation; never a wire/config field. */
5
18
  export const operationEndpoint = Symbol('zhin.im.operation-endpoint');
6
19
  /** Core-only trusted operation binding; never read from message metadata. */
@@ -82,7 +95,9 @@ export class RuntimeMessage {
82
95
  /** Core owns these immutable facts; author rebinding shares them and the captured operation. */
83
96
  constructor(facts, operation) {
84
97
  this.#facts = Object.freeze(facts);
85
- this.#operation = Object.freeze(operation);
98
+ // Never hand the ledger itself to views: plugins only get the report port (no `settle`).
99
+ const outcomes = operation.outcomes;
100
+ this.#operation = Object.freeze(outcomes ? { ...operation, outcomes: inboundOutcomeFacade(outcomes) } : operation);
86
101
  const { conversation, content, sender, segments, message, endpointId, mentioned, replyTo } = facts;
87
102
  const { reply } = operation;
88
103
  this.conversation = conversation;
@@ -195,6 +210,10 @@ export class RuntimeMessage {
195
210
  this.#operation.assertActive?.();
196
211
  return this.#operation.signal;
197
212
  }
213
+ /** @internal The inbound outcome ledger (ADR 0061); reports after settlement are ignored by it. */
214
+ [inboundOutcomeSink]() {
215
+ return this.#operation.outcomes;
216
+ }
198
217
  /** @internal The command/handler author's actual leased operation. */
199
218
  [interactionOperationScope]() {
200
219
  this.#operation.assertActive?.();
@@ -11,6 +11,7 @@ import { EndpointRuntime } from './endpoint-runtime.js';
11
11
  import { MessageBus, type RuntimeMessageEventSource, type RuntimeSceneEventSource } from './message-events.js';
12
12
  import { InboundDeduper } from './inbound-dedup.js';
13
13
  import { type RuntimeMessageDiagnosticsReader } from './message-diagnostics.js';
14
+ import { type MessageOutcomeReader } from './inbound-outcome-ledger.js';
14
15
  /**
15
16
  * Plugin Runtime login-assist port(与出站消息服务并列)。
16
17
  * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
@@ -48,6 +49,8 @@ export interface ImRuntimeOptions {
48
49
  }
49
50
  export declare class ImRuntime implements OutboundMessageService {
50
51
  #private;
52
+ /** ADR 0061: settled inbound message outcomes (process memory, 2000 rows / 24 h). */
53
+ readonly messageOutcomes: MessageOutcomeReader;
51
54
  readonly messageDiagnostics: RuntimeMessageDiagnosticsReader;
52
55
  readonly messageEvents: RuntimeMessageEventSource;
53
56
  /** #996: scene facts (mute, join request, poke, …) as soon as they are stored, for wake-up observers. */
@@ -15,6 +15,7 @@ import { messageLocale } from './inbound-spine.js';
15
15
  import { InboundDeduper } from './inbound-dedup.js';
16
16
  import { createInboundOriginClassifier, OutboundLedger, ledgerScopeOf } from './inbound-origin.js';
17
17
  import { RuntimeMessageDiagnostics } from './message-diagnostics.js';
18
+ import { MessageOutcomeLog } from './inbound-outcome-ledger.js';
18
19
  import { createChatRoleSenderEnricher } from '../../built/roles.js';
19
20
  /**
20
21
  * Plugin Runtime login-assist port(与出站消息服务并列)。
@@ -27,6 +28,13 @@ export class ImRuntime {
27
28
  #commandExecution = new CommandExecutionBudget();
28
29
  #commandOperation = new AsyncLocalStorage();
29
30
  #messageDiagnostics = new RuntimeMessageDiagnostics();
31
+ #messageOutcomes = new MessageOutcomeLog();
32
+ /** ADR 0061: settled inbound message outcomes (process memory, 2000 rows / 24 h). */
33
+ messageOutcomes = Object.freeze({
34
+ persistent: false,
35
+ list: (query) => this.#messageOutcomes.list(query),
36
+ get: (id) => this.#messageOutcomes.get(id),
37
+ });
30
38
  messageDiagnostics = Object.freeze({
31
39
  list: (options) => this.#messageDiagnostics.list(options),
32
40
  get: (id) => this.#messageDiagnostics.get(id),
@@ -69,6 +77,7 @@ export class ImRuntime {
69
77
  commandExecution: this.#commandExecution,
70
78
  runCommandOperation: (controller, operation) => this.#commandOperation.run(controller, operation),
71
79
  diagnostics: this.#messageDiagnostics,
80
+ outcomes: this.#messageOutcomes,
72
81
  interactions: this.#interactions,
73
82
  captureOperation: input => this.endpoints.captureOperation(input),
74
83
  createOperationResources: input => {
@@ -0,0 +1,103 @@
1
+ import type { ConversationRef } from '@zhin.js/im-contract';
2
+ import { type MessageOutcome, type MessageOutcomeCandidate, type MessageOutcomeRecord, type MessageOutcomeStage } from './message-outcome.js';
3
+ /** Symbol of the `RuntimeMessage` method returning its ledger port. @internal */
4
+ export declare const inboundOutcomeSink: unique symbol;
5
+ /** What a message view exposes of its ledger. @public */
6
+ export interface InboundOutcomeSink {
7
+ report(candidate: MessageOutcomeCandidate): boolean;
8
+ enter(stage: MessageOutcomeStage): void;
9
+ }
10
+ /** Administrator detail: secrets masked (same patterns as the decision audit), one line, ≤ 200 chars. */
11
+ export declare function boundedOutcomeDetail(value: unknown): string | undefined;
12
+ export interface InboundOutcomeLedgerInit {
13
+ readonly conversation: ConversationRef;
14
+ readonly senderId?: string;
15
+ readonly messageId?: string;
16
+ readonly receivedAt: number;
17
+ readonly generation?: number;
18
+ readonly addressed?: boolean;
19
+ readonly now?: () => number;
20
+ }
21
+ /** Listener for `unrecorded` outcomes (tests fail on stages outside the allowlist, ADR 0061 §4.3). */
22
+ export type UnrecordedOutcomeListener = (record: MessageOutcomeRecord) => void;
23
+ /** Observes every `unrecorded` outcome in this process; returns the unsubscribe function. @public */
24
+ export declare function onUnrecordedInboundOutcome(listener: UnrecordedOutcomeListener): () => void;
25
+ /** One inbound message's outcome accumulator; settles once. @public */
26
+ export declare class InboundOutcomeLedger implements InboundOutcomeSink {
27
+ #private;
28
+ readonly id: `${string}-${string}-${string}-${string}-${string}`;
29
+ constructor(init: InboundOutcomeLedgerInit);
30
+ get settled(): MessageOutcomeRecord | undefined;
31
+ get addressed(): boolean;
32
+ get lastStage(): MessageOutcomeStage;
33
+ /** Current winning candidate (before settle). */
34
+ get current(): MessageOutcomeCandidate | undefined;
35
+ markAddressed(addressed: boolean): void;
36
+ linkDiagnostic(id: string | undefined): void;
37
+ enter(stage: MessageOutcomeStage): void;
38
+ /**
39
+ * Adds one candidate; the highest priority wins, ties keep the earlier one. False after settle,
40
+ * and for a code outside {@link MESSAGE_OUTCOMES} or a framework-only code (`internal_error`,
41
+ * `unrecorded`), which are dropped with one debug line.
42
+ */
43
+ report(candidate: MessageOutcomeCandidate): boolean;
44
+ /**
45
+ * Settles the message once. With `error`, the outcome is `internal_error` (the caller logs and
46
+ * rethrows); without any candidate it is `unrecorded`.
47
+ */
48
+ settle(input?: Readonly<{
49
+ error?: Readonly<{
50
+ errorId: string;
51
+ name?: string;
52
+ message?: string;
53
+ owner?: string;
54
+ }>;
55
+ }>): MessageOutcomeRecord;
56
+ }
57
+ /**
58
+ * Reports one outcome candidate for an inbound message (ADR 0061 §4.1). Agent and plugins call it
59
+ * with the message they received; a message without a ledger (outbound, synthetic) is ignored.
60
+ * @public
61
+ */
62
+ export declare function reportInboundOutcome(message: unknown, candidate: MessageOutcomeCandidate): boolean;
63
+ /** Marks the stage a message is entering, for `unrecorded` diagnosis. @public */
64
+ export declare function enterInboundOutcomeStage(message: unknown, stage: MessageOutcomeStage): void;
65
+ /** Filters of {@link MessageOutcomeReader.list}. @public */
66
+ export interface MessageOutcomeQuery {
67
+ readonly conversation?: Pick<ConversationRef, 'endpoint' | 'kind' | 'id'>;
68
+ readonly senderId?: string;
69
+ readonly messageId?: string;
70
+ readonly outcome?: MessageOutcome;
71
+ readonly since?: number;
72
+ readonly limit?: number;
73
+ }
74
+ /** Read side of settled outcomes. @public */
75
+ export interface MessageOutcomeReader {
76
+ /** False: process memory only (no `im_message_outcomes` persistence yet). */
77
+ readonly persistent: boolean;
78
+ list(query?: MessageOutcomeQuery): readonly MessageOutcomeRecord[];
79
+ get(id: string): MessageOutcomeRecord | undefined;
80
+ }
81
+ export interface MessageOutcomeLogOptions {
82
+ readonly capacity?: number;
83
+ readonly ttlMs?: number;
84
+ /** Quiet rows per conversation per minute before aggregation (`im.outcomes.quietSampleLimit`, default 30). */
85
+ readonly quietSampleLimit?: number;
86
+ readonly now?: () => number;
87
+ }
88
+ /**
89
+ * Process-local outcome log: 2000 rows / 24 hours by default. Quiet outcomes (`not_addressed`,
90
+ * `ignored_bot`, `ignored_self`, `dropped_duplicate`) of one conversation beyond the per-minute
91
+ * limit collapse into one aggregated row per minute (`facets: ['aggregated:<n>']`, no message id);
92
+ * addressed messages and other outcomes are never sampled (ADR 0061 §2).
93
+ * @public
94
+ */
95
+ export declare class MessageOutcomeLog implements MessageOutcomeReader {
96
+ #private;
97
+ private readonly options;
98
+ readonly persistent = false;
99
+ constructor(options?: MessageOutcomeLogOptions);
100
+ record(record: MessageOutcomeRecord): MessageOutcomeRecord;
101
+ list(query?: MessageOutcomeQuery): readonly MessageOutcomeRecord[];
102
+ get(id: string): MessageOutcomeRecord | undefined;
103
+ }
@@ -0,0 +1,311 @@
1
+ /**
2
+ * ADR 0061 §4.1: the inbound outcome ledger. `InboundRuntime.#receiveMessage` opens one ledger per
3
+ * message, every stage reports candidates through {@link reportInboundOutcome}, and the `finally`
4
+ * block settles exactly one {@link MessageOutcomeRecord}. Settled records go to the process-local
5
+ * {@link MessageOutcomeLog} (ring buffer, ADR 0061 §2 "无数据库"); persistence in
6
+ * `im_message_outcomes` is a later phase (P3).
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import { redactSecretText } from '@zhin.js/kernel';
10
+ import { formatCompact, getLogger } from '@zhin.js/logger';
11
+ import { MESSAGE_OUTCOMES, defaultOutcomeReply, defaultOutcomeVisibility, messageOutcomePriority, QUIET_MESSAGE_OUTCOMES, } from './message-outcome.js';
12
+ const logger = getLogger('im.inbound');
13
+ const KNOWN_OUTCOMES = new Set(MESSAGE_OUTCOMES);
14
+ /** Set only by the framework when it settles (ADR 0061 §4.1); never accepted from a report. */
15
+ const SYSTEM_OUTCOMES = new Set(['internal_error', 'unrecorded']);
16
+ /** Symbol of the `RuntimeMessage` method returning its ledger port. @internal */
17
+ export const inboundOutcomeSink = Symbol('zhin.im.inbound-outcome-sink');
18
+ const MAX_DETAIL_CHARS = 200;
19
+ const MAX_FACETS = 16;
20
+ const MAX_CODE_CHARS = 120;
21
+ function boundedCode(value) {
22
+ if (typeof value !== 'string')
23
+ return undefined;
24
+ const text = value.replace(/[^\w:./-]/gu, '_').slice(0, MAX_CODE_CHARS);
25
+ return text || undefined;
26
+ }
27
+ /** Administrator detail: secrets masked (same patterns as the decision audit), one line, ≤ 200 chars. */
28
+ export function boundedOutcomeDetail(value) {
29
+ if (typeof value !== 'string' || !value.trim())
30
+ return undefined;
31
+ const text = redactSecretText(value).replace(/\p{Cc}+/gu, ' ').trim();
32
+ const chars = [...text];
33
+ return chars.length > MAX_DETAIL_CHARS ? `${chars.slice(0, MAX_DETAIL_CHARS - 1).join('')}…` : text;
34
+ }
35
+ /**
36
+ * One listener set per process, even when this module is loaded more than once (two copies of
37
+ * the package, or source and build in one test run), so the test guard cannot silently miss one.
38
+ */
39
+ const UNRECORDED_LISTENERS = Symbol.for('zhin.im.inbound-outcome.unrecorded-listeners');
40
+ const unrecordedListeners = (() => {
41
+ const host = globalThis;
42
+ return host[UNRECORDED_LISTENERS] ??= new Set();
43
+ })();
44
+ /** Observes every `unrecorded` outcome in this process; returns the unsubscribe function. @public */
45
+ export function onUnrecordedInboundOutcome(listener) {
46
+ unrecordedListeners.add(listener);
47
+ return () => unrecordedListeners.delete(listener);
48
+ }
49
+ /** One inbound message's outcome accumulator; settles once. @public */
50
+ export class InboundOutcomeLedger {
51
+ id = randomUUID();
52
+ #init;
53
+ #addressed;
54
+ #diagnosticId;
55
+ #best;
56
+ #facets = [];
57
+ #lastStage = 'ingress';
58
+ #settled;
59
+ constructor(init) {
60
+ this.#init = init;
61
+ this.#addressed = init.addressed === true;
62
+ }
63
+ get settled() { return this.#settled; }
64
+ get addressed() { return this.#addressed; }
65
+ get lastStage() { return this.#lastStage; }
66
+ /** Current winning candidate (before settle). */
67
+ get current() { return this.#best; }
68
+ markAddressed(addressed) { if (addressed)
69
+ this.#addressed = true; }
70
+ linkDiagnostic(id) { if (id)
71
+ this.#diagnosticId = id; }
72
+ enter(stage) {
73
+ if (!this.#settled)
74
+ this.#lastStage = stage;
75
+ }
76
+ /**
77
+ * Adds one candidate; the highest priority wins, ties keep the earlier one. False after settle,
78
+ * and for a code outside {@link MESSAGE_OUTCOMES} or a framework-only code (`internal_error`,
79
+ * `unrecorded`), which are dropped with one debug line.
80
+ */
81
+ report(candidate) {
82
+ if (this.#settled)
83
+ return false;
84
+ const code = candidate?.outcome;
85
+ if (typeof code !== 'string' || !KNOWN_OUTCOMES.has(code) || SYSTEM_OUTCOMES.has(code)) {
86
+ logger.debug(formatCompact({ op: 'inbound_outcome_report_rejected', outcome: boundedCode(code) ?? typeof code,
87
+ reason: typeof code === 'string' && SYSTEM_OUTCOMES.has(code) ? 'framework_only' : 'unknown_outcome' }));
88
+ return false;
89
+ }
90
+ this.#lastStage = candidate.stage;
91
+ for (const facet of candidate.facets ?? [])
92
+ this.#addFacet(facet);
93
+ const best = this.#best;
94
+ if (!best) {
95
+ this.#best = candidate;
96
+ return true;
97
+ }
98
+ if (messageOutcomePriority(candidate.outcome) > messageOutcomePriority(best.outcome)) {
99
+ this.#addFacet(facetOf(best));
100
+ this.#best = { ...candidate, ...(candidate.turnId === undefined && best.turnId ? { turnId: best.turnId } : {}) };
101
+ }
102
+ else {
103
+ this.#addFacet(facetOf(candidate));
104
+ if (best.turnId === undefined && candidate.turnId)
105
+ this.#best = { ...best, turnId: candidate.turnId };
106
+ }
107
+ return true;
108
+ }
109
+ #addFacet(value) {
110
+ const facet = boundedCode(value);
111
+ if (facet && !this.#facets.includes(facet) && this.#facets.length < MAX_FACETS)
112
+ this.#facets.push(facet);
113
+ }
114
+ /**
115
+ * Settles the message once. With `error`, the outcome is `internal_error` (the caller logs and
116
+ * rethrows); without any candidate it is `unrecorded`.
117
+ */
118
+ settle(input = {}) {
119
+ if (this.#settled)
120
+ return this.#settled;
121
+ const init = this.#init;
122
+ let candidate = this.#best ?? { outcome: 'unrecorded', reason: 'missing_outcome', stage: this.#lastStage };
123
+ if (input.error) {
124
+ if (this.#best)
125
+ this.#addFacet(facetOf(this.#best));
126
+ candidate = {
127
+ outcome: 'internal_error',
128
+ reason: `${stageThrow(this.#lastStage)}`,
129
+ stage: this.#lastStage,
130
+ errorId: input.error.errorId,
131
+ ...(input.error.owner ? { owner: input.error.owner } : {}),
132
+ detail: [input.error.name, input.error.message].filter(Boolean).join(': '),
133
+ };
134
+ }
135
+ const outcome = candidate.outcome;
136
+ const conversation = init.conversation;
137
+ const detail = boundedOutcomeDetail(candidate.detail);
138
+ const record = Object.freeze({
139
+ id: this.id,
140
+ receivedAt: init.receivedAt,
141
+ settledAt: (init.now ?? Date.now)(),
142
+ ...(init.generation !== undefined ? { generation: init.generation } : {}),
143
+ conversation,
144
+ platform: conversation.endpoint.adapter,
145
+ sceneId: `${conversation.kind}:${conversation.id}`,
146
+ ...(init.senderId ? { senderId: init.senderId } : {}),
147
+ ...(init.messageId ? { messageId: init.messageId } : {}),
148
+ addressed: this.#addressed,
149
+ outcome,
150
+ ...(boundedCode(candidate.reason) ? { reason: boundedCode(candidate.reason) } : {}),
151
+ facets: Object.freeze([...this.#facets]),
152
+ stage: candidate.stage,
153
+ visibility: candidate.visibility ?? defaultOutcomeVisibility(outcome, this.#addressed),
154
+ reply: candidate.reply ?? defaultOutcomeReply(outcome),
155
+ ...(candidate.command ? { command: String(candidate.command).slice(0, 200) } : {}),
156
+ ...(candidate.owner ? { owner: String(candidate.owner).slice(0, 200) } : {}),
157
+ ...(candidate.turnId ? { turnId: String(candidate.turnId).slice(0, 200) } : {}),
158
+ ...(this.#diagnosticId ? { diagnosticId: this.#diagnosticId } : {}),
159
+ ...(candidate.errorId ? { errorId: candidate.errorId } : {}),
160
+ ...(candidate.mergedInto ? { mergedInto: String(candidate.mergedInto).slice(0, 200) } : {}),
161
+ ...(detail ? { detail } : {}),
162
+ ...(outcome === 'unrecorded' ? { lastStage: this.#lastStage } : {}),
163
+ });
164
+ this.#settled = record;
165
+ if (outcome === 'unrecorded') {
166
+ for (const listener of unrecordedListeners) {
167
+ try {
168
+ listener(record);
169
+ }
170
+ catch (error) {
171
+ if (process.env.NODE_ENV === 'test')
172
+ throw error;
173
+ }
174
+ }
175
+ }
176
+ return record;
177
+ }
178
+ }
179
+ function facetOf(candidate) {
180
+ return candidate.reason ? `${candidate.outcome}:${candidate.reason}` : candidate.outcome;
181
+ }
182
+ function stageThrow(stage) {
183
+ switch (stage) {
184
+ case 'command': return 'command_threw';
185
+ case 'handlers': return 'handler_threw';
186
+ case 'middleware': return 'middleware_threw';
187
+ case 'agent_gate':
188
+ case 'ambient':
189
+ case 'admission':
190
+ case 'model':
191
+ case 'tool': return 'agent_threw';
192
+ default: return 'inbound_threw';
193
+ }
194
+ }
195
+ /**
196
+ * Reports one outcome candidate for an inbound message (ADR 0061 §4.1). Agent and plugins call it
197
+ * with the message they received; a message without a ledger (outbound, synthetic) is ignored.
198
+ * @public
199
+ */
200
+ export function reportInboundOutcome(message, candidate) {
201
+ return inboundOutcomeSinkOf(message)?.report(candidate) ?? false;
202
+ }
203
+ /** Marks the stage a message is entering, for `unrecorded` diagnosis. @public */
204
+ export function enterInboundOutcomeStage(message, stage) {
205
+ inboundOutcomeSinkOf(message)?.enter(stage);
206
+ }
207
+ function inboundOutcomeSinkOf(message) {
208
+ if (!message || typeof message !== 'object')
209
+ return undefined;
210
+ const method = message[inboundOutcomeSink];
211
+ return typeof method === 'function' ? method.call(message) : undefined;
212
+ }
213
+ /**
214
+ * Process-local outcome log: 2000 rows / 24 hours by default. Quiet outcomes (`not_addressed`,
215
+ * `ignored_bot`, `ignored_self`, `dropped_duplicate`) of one conversation beyond the per-minute
216
+ * limit collapse into one aggregated row per minute (`facets: ['aggregated:<n>']`, no message id);
217
+ * addressed messages and other outcomes are never sampled (ADR 0061 §2).
218
+ * @public
219
+ */
220
+ export class MessageOutcomeLog {
221
+ options;
222
+ persistent = false;
223
+ #records = new Map();
224
+ /** Ids of silent-tier rows, oldest first: evicted before any other row when the log is full. */
225
+ #silent = new Set();
226
+ #quiet = new Map();
227
+ constructor(options = {}) {
228
+ this.options = options;
229
+ }
230
+ #now() { return (this.options.now ?? Date.now)(); }
231
+ record(record) {
232
+ this.#prune();
233
+ let stored = record;
234
+ if (!record.addressed && QUIET_MESSAGE_OUTCOMES.has(record.outcome)) {
235
+ const key = `${conversationKey(record.conversation)}\0${record.outcome}\0${record.reason ?? ''}`;
236
+ const minute = Math.floor(record.settledAt / 60_000);
237
+ let window = this.#quiet.get(key);
238
+ if (!window || window.minute !== minute) {
239
+ window = { minute, count: 0 };
240
+ this.#quiet.set(key, window);
241
+ if (this.#quiet.size > 4096)
242
+ this.#quiet.delete(this.#quiet.keys().next().value);
243
+ }
244
+ window.count += 1;
245
+ const limit = this.options.quietSampleLimit ?? 30;
246
+ if (window.count > limit) {
247
+ const n = window.count - limit;
248
+ const id = window.aggregate?.id ?? randomUUID();
249
+ const { messageId: _messageId, senderId: _senderId, ...rest } = record;
250
+ stored = Object.freeze({ ...rest, id, facets: Object.freeze([...record.facets.filter(f => !f.startsWith('aggregated:')), `aggregated:${n}`]) });
251
+ window.aggregate = { id, outcome: record.outcome, ...(record.reason ? { reason: record.reason } : {}), n };
252
+ this.#delete(id);
253
+ }
254
+ }
255
+ this.#records.set(stored.id, stored);
256
+ if (isSilentOutcome(stored.outcome))
257
+ this.#silent.add(stored.id);
258
+ const capacity = this.options.capacity ?? 2000;
259
+ // A flood of silent rows (not addressed, bot echoes) never pushes out failures or replies.
260
+ while (this.#records.size > capacity) {
261
+ const oldest = this.#silent.size > 0 ? this.#silent.values().next().value : this.#records.keys().next().value;
262
+ this.#delete(oldest);
263
+ }
264
+ return stored;
265
+ }
266
+ #delete(id) {
267
+ this.#records.delete(id);
268
+ this.#silent.delete(id);
269
+ }
270
+ list(query = {}) {
271
+ this.#prune();
272
+ const limit = Number.isSafeInteger(query.limit) ? Math.min(500, Math.max(1, query.limit)) : 50;
273
+ const key = query.conversation ? conversationKey(query.conversation) : undefined;
274
+ const out = [];
275
+ for (const record of [...this.#records.values()].reverse()) {
276
+ if (key !== undefined && conversationKey(record.conversation) !== key)
277
+ continue;
278
+ if (query.senderId !== undefined && record.senderId !== query.senderId)
279
+ continue;
280
+ if (query.messageId !== undefined && record.messageId !== query.messageId)
281
+ continue;
282
+ if (query.outcome !== undefined && record.outcome !== query.outcome)
283
+ continue;
284
+ if (query.since !== undefined && record.settledAt < query.since)
285
+ continue;
286
+ out.push(record);
287
+ if (out.length >= limit)
288
+ break;
289
+ }
290
+ return Object.freeze(out);
291
+ }
292
+ get(id) {
293
+ this.#prune();
294
+ return this.#records.get(id);
295
+ }
296
+ #prune() {
297
+ const threshold = this.#now() - (this.options.ttlMs ?? 24 * 60 * 60_000);
298
+ for (const [id, record] of this.#records) {
299
+ if (record.settledAt >= threshold)
300
+ break;
301
+ this.#delete(id);
302
+ }
303
+ }
304
+ }
305
+ /** Silent tier (ADR 0061 §1.3–§1.5): no reply by design, the bulk of the traffic. */
306
+ function isSilentOutcome(outcome) {
307
+ return messageOutcomePriority(outcome) === messageOutcomePriority('not_addressed');
308
+ }
309
+ function conversationKey(conversation) {
310
+ return JSON.stringify([conversation.endpoint.id, conversation.kind, conversation.id]);
311
+ }