@zhin.js/core 1.8.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/lib/built/chat-role-reader.d.ts +145 -0
  2. package/lib/built/chat-role-reader.js +183 -0
  3. package/lib/built/roles.d.ts +55 -1
  4. package/lib/built/roles.js +84 -7
  5. package/lib/built/user-interaction.js +3 -0
  6. package/lib/index.d.ts +1 -0
  7. package/lib/index.js +1 -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/command-feedback.js +22 -5
  11. package/lib/plugin-runtime/im/contracts.d.ts +15 -0
  12. package/lib/plugin-runtime/im/contracts.js +20 -1
  13. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +3 -1
  14. package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
  15. package/lib/plugin-runtime/im/im-runtime.js +9 -0
  16. package/lib/plugin-runtime/im/inbound-outcome-ledger.d.ts +103 -0
  17. package/lib/plugin-runtime/im/inbound-outcome-ledger.js +311 -0
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +3 -0
  19. package/lib/plugin-runtime/im/inbound-runtime.js +138 -13
  20. package/lib/plugin-runtime/im/inbound-spine.d.ts +20 -3
  21. package/lib/plugin-runtime/im/inbound-spine.js +93 -6
  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-events.js +27 -0
  29. package/lib/plugin-runtime/im/message-outcome.d.ts +97 -0
  30. package/lib/plugin-runtime/im/message-outcome.js +125 -0
  31. package/package.json +9 -9
@@ -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
+ }
@@ -1,5 +1,6 @@
1
1
  import { readOperationInputResources } from '@zhin.js/feature-kit';
2
2
  import { Fragment, jsx } from '@zhin.js/jsx';
3
+ import { parsePermitName } from '@zhin.js/permission';
3
4
  import { formatCompact, getLogger } from '@zhin.js/logger';
4
5
  import { createToken, createMessages, resolveLocale } from '@zhin.js/plugin-runtime';
5
6
  import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
@@ -22,6 +23,15 @@ function feedbackFrom(result) {
22
23
  const feedbackMessages = createMessages({
23
24
  denied: { 'zh-CN': '没有权限执行此指令。', en: 'You do not have permission to run this command.' },
24
25
  deniedBecause: { 'zh-CN': '无法执行此指令:{reason}', en: 'This command cannot run here: {reason}' },
26
+ // ADR 0060 §5.3: zhin role conditions say where roles come from (never which role or who holds it).
27
+ deniedRole: {
28
+ 'zh-CN': '没有权限执行此指令:它需要 zhin 角色。请联系本机器人的主人授予,或由主人在 Console「聊天角色」页授予。',
29
+ en: 'You do not have permission to run this command: it needs a zhin role. Ask the owner of this bot to grant one, in chat or on the Console "Chat roles" page.',
30
+ },
31
+ deniedRoleStanding: {
32
+ 'zh-CN': '没有权限执行此指令:它需要 zhin 角色,群主 / 群管理员的平台身份不等于 zhin 角色。请联系本机器人的主人授予,或由主人在 Console「聊天角色」页授予。',
33
+ en: 'You do not have permission to run this command: it needs a zhin role, and being a group owner / admin on the platform is not one. Ask the owner of this bot to grant one, in chat or on the Console "Chat roles" page.',
34
+ },
25
35
  cooldown: { 'zh-CN': '此指令仍在冷却,请稍后再试。', en: 'This command is on cooldown. Try again later.' },
26
36
  wait: { 'zh-CN': '此指令仍在冷却,约 {seconds} 秒后再试。', en: 'This command is on cooldown. Try again in about {seconds} seconds.' },
27
37
  busy: { 'zh-CN': '你的上一条同类指令仍在处理中,请等待执行完成,避免重复触发。', en: 'Your previous command is still running. Wait for it to finish before trying again.' },
@@ -31,15 +41,22 @@ const feedbackMessages = createMessages({
31
41
  function explainsDenial(permit) {
32
42
  return typeof permit === 'string' && /^(platform|platform-role|platform-permission|bot|bot-role|bot-permission):/u.test(permit);
33
43
  }
34
- function defaultFeedback(feedback, locale) {
44
+ function deniesZhinRole(permit) {
45
+ return typeof permit === 'string' && parsePermitName(permit)?.kind === 'role';
46
+ }
47
+ function defaultFeedback(feedback, locale, standing) {
35
48
  if (feedback.status === 'invalid') {
36
49
  return [...feedback.issues.map(issue => issue.message), feedback.help].filter(Boolean).join('\n');
37
50
  }
38
51
  // Platform / Bot conditions say what is missing (e.g. 「机器人不是本群管理员」); zhin role and
39
52
  // conversation conditions keep the generic sentence.
40
- if (feedback.status === 'denied')
41
- return feedback.reason && explainsDenial(feedback.permit)
42
- ? feedbackMessages(locale, 'deniedBecause', { reason: feedback.reason }) : feedbackMessages(locale, 'denied');
53
+ if (feedback.status === 'denied') {
54
+ if (feedback.reason && explainsDenial(feedback.permit))
55
+ return feedbackMessages(locale, 'deniedBecause', { reason: feedback.reason });
56
+ if (deniesZhinRole(feedback.permit))
57
+ return feedbackMessages(locale, standing === 'owner' || standing === 'admin' ? 'deniedRoleStanding' : 'deniedRole');
58
+ return feedbackMessages(locale, 'denied');
59
+ }
43
60
  const reason = feedback.limit?.reason;
44
61
  const waitMs = feedback.limit?.retryAfterMs;
45
62
  return reason === 'cooldown'
@@ -84,7 +101,7 @@ export async function renderCommandFeedback(result, message, snapshot) {
84
101
  logger.warn(formatCompact({ op: 'command_feedback_error', generation: snapshot.generation, status: feedback.status }));
85
102
  }
86
103
  }
87
- return { content: defaultFeedback(feedback, resolveLocale(message.locale)), owner: result.owner };
104
+ return { content: defaultFeedback(feedback, resolveLocale(message.locale), message.sender?.platform?.standing), owner: result.owner };
88
105
  }
89
106
  export const commandMenuPresentationToken = createToken('zhin.command-menu-presentation', 'Root-selected command menu presentation; framework pagination remains unchanged');
90
107
  /** The current Root owns both the selected presenter and the resulting content. */
@@ -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 {
@@ -115,6 +118,11 @@ export interface MessageSenderRef {
115
118
  readonly chatRole?: ChatRole;
116
119
  /** Per role, the topmost level it is held at on this conversation's chain. Set by the Runtime only. */
117
120
  readonly chatRoleLevels?: ChatRoleLevels;
121
+ /**
122
+ * The person the sender's identity belongs to (ADR 0060 §2.3): a stored `cp_…` id, or
123
+ * `implicit:<alias>:<userId>`. Set by the Runtime only; an adapter's own value is dropped.
124
+ */
125
+ readonly chatPrincipal?: string;
118
126
  }
119
127
  export interface IncomingMessage {
120
128
  /** Original SDK message callback object; operation-only, not a persistence field. */
@@ -281,6 +289,11 @@ export interface RuntimeMessageOperation {
281
289
  }>) => OperationResourceView | undefined;
282
290
  readonly registerOperationView?: (view: object, owner: PluginId) => void;
283
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;
284
297
  }
285
298
  /** Canonical runtime message with optional plugin-owned extensions. */
286
299
  export type Message<T extends object = {}> = MessageBase & T;
@@ -314,6 +327,8 @@ export declare class RuntimeMessage implements MessageBase {
314
327
  [operationInputResources](snapshot: RuntimeSnapshot): CapabilityOperationFactory | undefined;
315
328
  /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
316
329
  [operationInputSignal](): AbortSignal | undefined;
330
+ /** @internal The inbound outcome ledger (ADR 0061); reports after settlement are ignored by it. */
331
+ [inboundOutcomeSink](): InboundOutcomeSink | undefined;
317
332
  /** @internal The command/handler author's actual leased operation. */
318
333
  [interactionOperationScope](): InteractionOperationScope | undefined;
319
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?.();
@@ -5,12 +5,14 @@
5
5
  import { type AdapterIndex } from '@zhin.js/adapter';
6
6
  import type { OperationSession } from '@zhin.js/feature-kit';
7
7
  import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
8
- import { type ChatRoleService } from '../../../built/roles.js';
8
+ import { type ChatIdentitySighting, type ChatRoleService } from '../../../built/roles.js';
9
9
  import type { ImRuntime } from '../im-runtime.js';
10
10
  export type ConfigurationChatAuthorizer = (session: OperationSession<string>, adapters: AdapterIndex) => boolean;
11
11
  export interface SenderEnricherOptions {
12
12
  /** Chat role resolution of the instance; undefined while it is not available. */
13
13
  readonly roles: () => ChatRoleService | undefined;
14
+ /** Every addressable sender (ADR 0060 §2.2 `last_seen_at` / display name cache); errors are ignored. */
15
+ readonly observe?: (sighting: ChatIdentitySighting) => void;
14
16
  }
15
17
  /** `ImRuntime` `enrichSender` option over the chat role model. */
16
18
  export declare function createSenderEnricher(options: SenderEnricherOptions): NonNullable<NonNullable<ConstructorParameters<typeof ImRuntime>[0]>['enrichSender']>;
@@ -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
+ }