@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.
- package/lib/built/interaction-messages.d.ts +1 -1
- package/lib/built/interactive-segments/resolve.js +12 -0
- package/lib/built/interactive-segments/types.d.ts +6 -0
- package/lib/built/roles.d.ts +33 -6
- package/lib/built/roles.js +27 -15
- package/lib/built/segment-contract/json-schema.js +1 -0
- 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 +58 -0
- package/lib/plugin-runtime/im/contracts.js +21 -1
- package/lib/plugin-runtime/im/conversation-runtime.js +12 -2
- package/lib/plugin-runtime/im/host/database-console-sql.js +1 -1
- package/lib/plugin-runtime/im/im-runtime.d.ts +9 -1
- package/lib/plugin-runtime/im/im-runtime.js +10 -0
- package/lib/plugin-runtime/im/inbound-outcome-ledger.d.ts +117 -0
- package/lib/plugin-runtime/im/inbound-outcome-ledger.js +329 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +6 -1
- package/lib/plugin-runtime/im/inbound-runtime.js +268 -21
- package/lib/plugin-runtime/im/inbound-spine.d.ts +20 -3
- package/lib/plugin-runtime/im/inbound-spine.js +107 -7
- 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-dispatcher.d.ts +6 -0
- package/lib/plugin-runtime/im/message-dispatcher.js +6 -1
- package/lib/plugin-runtime/im/message-outcome.d.ts +97 -0
- package/lib/plugin-runtime/im/message-outcome.js +125 -0
- package/lib/plugin-runtime/im/outbound-segments.js +1 -1
- package/package.json +15 -15
|
@@ -0,0 +1,117 @@
|
|
|
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
|
+
* True once a reply to this message was delivered (`status: 'sent'`); with `owner`, only a reply
|
|
11
|
+
* sent by that plugin counts. Lets the framework tell a middleware that answered and then stopped
|
|
12
|
+
* dispatch from one that dropped the message (#1250).
|
|
13
|
+
*/
|
|
14
|
+
replied?(owner?: string): boolean;
|
|
15
|
+
}
|
|
16
|
+
/** Administrator detail: secrets masked (same patterns as the decision audit), one line, ≤ 200 chars. */
|
|
17
|
+
export declare function boundedOutcomeDetail(value: unknown): string | undefined;
|
|
18
|
+
export interface InboundOutcomeLedgerInit {
|
|
19
|
+
readonly conversation: ConversationRef;
|
|
20
|
+
readonly senderId?: string;
|
|
21
|
+
readonly messageId?: string;
|
|
22
|
+
readonly receivedAt: number;
|
|
23
|
+
readonly generation?: number;
|
|
24
|
+
readonly addressed?: boolean;
|
|
25
|
+
readonly now?: () => number;
|
|
26
|
+
}
|
|
27
|
+
/** Listener for `unrecorded` outcomes (tests fail on stages outside the allowlist, ADR 0061 §4.3). */
|
|
28
|
+
export type UnrecordedOutcomeListener = (record: MessageOutcomeRecord) => void;
|
|
29
|
+
/** Observes every `unrecorded` outcome in this process; returns the unsubscribe function. @public */
|
|
30
|
+
export declare function onUnrecordedInboundOutcome(listener: UnrecordedOutcomeListener): () => void;
|
|
31
|
+
/** One inbound message's outcome accumulator; settles once. @public */
|
|
32
|
+
export declare class InboundOutcomeLedger implements InboundOutcomeSink {
|
|
33
|
+
#private;
|
|
34
|
+
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
35
|
+
constructor(init: InboundOutcomeLedgerInit);
|
|
36
|
+
get settled(): MessageOutcomeRecord | undefined;
|
|
37
|
+
get addressed(): boolean;
|
|
38
|
+
get lastStage(): MessageOutcomeStage;
|
|
39
|
+
/** Current winning candidate (before settle). */
|
|
40
|
+
get current(): MessageOutcomeCandidate | undefined;
|
|
41
|
+
/** Records one delivered reply and its author (called by the inbound reply port on `status: 'sent'`). */
|
|
42
|
+
noteReplyDelivered(owner?: string): void;
|
|
43
|
+
replied(owner?: string): boolean;
|
|
44
|
+
markAddressed(addressed: boolean): void;
|
|
45
|
+
linkDiagnostic(id: string | undefined): void;
|
|
46
|
+
enter(stage: MessageOutcomeStage): void;
|
|
47
|
+
/**
|
|
48
|
+
* Adds one candidate; the highest priority wins, ties keep the earlier one. False after settle,
|
|
49
|
+
* and for a code outside {@link MESSAGE_OUTCOMES} or a framework-only code (`internal_error`,
|
|
50
|
+
* `unrecorded`), which are dropped with one debug line.
|
|
51
|
+
*/
|
|
52
|
+
report(candidate: MessageOutcomeCandidate): boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Settles the message once. With `error`, the outcome is `internal_error` (the caller logs and
|
|
55
|
+
* rethrows); without any candidate it is `unrecorded`.
|
|
56
|
+
*/
|
|
57
|
+
settle(input?: Readonly<{
|
|
58
|
+
error?: Readonly<{
|
|
59
|
+
errorId: string;
|
|
60
|
+
name?: string;
|
|
61
|
+
message?: string;
|
|
62
|
+
owner?: string;
|
|
63
|
+
}>;
|
|
64
|
+
}>): MessageOutcomeRecord;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Reports one outcome candidate for an inbound message (ADR 0061 §4.1). Agent and plugins call it
|
|
68
|
+
* with the message they received; a message without a ledger (outbound, synthetic) is ignored.
|
|
69
|
+
* @public
|
|
70
|
+
*/
|
|
71
|
+
export declare function reportInboundOutcome(message: unknown, candidate: MessageOutcomeCandidate): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Whether a reply to this inbound message has been delivered so far (ADR 0061 §1.1); with `owner`,
|
|
74
|
+
* only a reply that plugin sent counts. @internal
|
|
75
|
+
*/
|
|
76
|
+
export declare function inboundOutcomeReplied(message: unknown, owner?: string): boolean;
|
|
77
|
+
/** Marks the stage a message is entering, for `unrecorded` diagnosis. @public */
|
|
78
|
+
export declare function enterInboundOutcomeStage(message: unknown, stage: MessageOutcomeStage): void;
|
|
79
|
+
/** Filters of {@link MessageOutcomeReader.list}. @public */
|
|
80
|
+
export interface MessageOutcomeQuery {
|
|
81
|
+
readonly conversation?: Pick<ConversationRef, 'endpoint' | 'kind' | 'id'>;
|
|
82
|
+
readonly senderId?: string;
|
|
83
|
+
readonly messageId?: string;
|
|
84
|
+
readonly outcome?: MessageOutcome;
|
|
85
|
+
readonly since?: number;
|
|
86
|
+
readonly limit?: number;
|
|
87
|
+
}
|
|
88
|
+
/** Read side of settled outcomes. @public */
|
|
89
|
+
export interface MessageOutcomeReader {
|
|
90
|
+
/** False: process memory only (no `im_message_outcomes` persistence yet). */
|
|
91
|
+
readonly persistent: boolean;
|
|
92
|
+
list(query?: MessageOutcomeQuery): readonly MessageOutcomeRecord[];
|
|
93
|
+
get(id: string): MessageOutcomeRecord | undefined;
|
|
94
|
+
}
|
|
95
|
+
export interface MessageOutcomeLogOptions {
|
|
96
|
+
readonly capacity?: number;
|
|
97
|
+
readonly ttlMs?: number;
|
|
98
|
+
/** Quiet rows per conversation per minute before aggregation (`im.outcomes.quietSampleLimit`, default 30). */
|
|
99
|
+
readonly quietSampleLimit?: number;
|
|
100
|
+
readonly now?: () => number;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Process-local outcome log: 2000 rows / 24 hours by default. Quiet outcomes (`not_addressed`,
|
|
104
|
+
* `ignored_bot`, `ignored_self`, `dropped_duplicate`) of one conversation beyond the per-minute
|
|
105
|
+
* limit collapse into one aggregated row per minute (`facets: ['aggregated:<n>']`, no message id);
|
|
106
|
+
* addressed messages and other outcomes are never sampled (ADR 0061 §2).
|
|
107
|
+
* @public
|
|
108
|
+
*/
|
|
109
|
+
export declare class MessageOutcomeLog implements MessageOutcomeReader {
|
|
110
|
+
#private;
|
|
111
|
+
private readonly options;
|
|
112
|
+
readonly persistent = false;
|
|
113
|
+
constructor(options?: MessageOutcomeLogOptions);
|
|
114
|
+
record(record: MessageOutcomeRecord): MessageOutcomeRecord;
|
|
115
|
+
list(query?: MessageOutcomeQuery): readonly MessageOutcomeRecord[];
|
|
116
|
+
get(id: string): MessageOutcomeRecord | undefined;
|
|
117
|
+
}
|
|
@@ -0,0 +1,329 @@
|
|
|
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
|
+
#replies = 0;
|
|
59
|
+
#replyOwners = new Set();
|
|
60
|
+
#settled;
|
|
61
|
+
constructor(init) {
|
|
62
|
+
this.#init = init;
|
|
63
|
+
this.#addressed = init.addressed === true;
|
|
64
|
+
}
|
|
65
|
+
get settled() { return this.#settled; }
|
|
66
|
+
get addressed() { return this.#addressed; }
|
|
67
|
+
get lastStage() { return this.#lastStage; }
|
|
68
|
+
/** Current winning candidate (before settle). */
|
|
69
|
+
get current() { return this.#best; }
|
|
70
|
+
/** Records one delivered reply and its author (called by the inbound reply port on `status: 'sent'`). */
|
|
71
|
+
noteReplyDelivered(owner) {
|
|
72
|
+
if (this.#settled)
|
|
73
|
+
return;
|
|
74
|
+
this.#replies++;
|
|
75
|
+
if (owner)
|
|
76
|
+
this.#replyOwners.add(String(owner));
|
|
77
|
+
}
|
|
78
|
+
replied(owner) { return owner === undefined ? this.#replies > 0 : this.#replyOwners.has(String(owner)); }
|
|
79
|
+
markAddressed(addressed) { if (addressed)
|
|
80
|
+
this.#addressed = true; }
|
|
81
|
+
linkDiagnostic(id) { if (id)
|
|
82
|
+
this.#diagnosticId = id; }
|
|
83
|
+
enter(stage) {
|
|
84
|
+
if (!this.#settled)
|
|
85
|
+
this.#lastStage = stage;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Adds one candidate; the highest priority wins, ties keep the earlier one. False after settle,
|
|
89
|
+
* and for a code outside {@link MESSAGE_OUTCOMES} or a framework-only code (`internal_error`,
|
|
90
|
+
* `unrecorded`), which are dropped with one debug line.
|
|
91
|
+
*/
|
|
92
|
+
report(candidate) {
|
|
93
|
+
if (this.#settled)
|
|
94
|
+
return false;
|
|
95
|
+
const code = candidate?.outcome;
|
|
96
|
+
if (typeof code !== 'string' || !KNOWN_OUTCOMES.has(code) || SYSTEM_OUTCOMES.has(code)) {
|
|
97
|
+
logger.debug(formatCompact({ op: 'inbound_outcome_report_rejected', outcome: boundedCode(code) ?? typeof code,
|
|
98
|
+
reason: typeof code === 'string' && SYSTEM_OUTCOMES.has(code) ? 'framework_only' : 'unknown_outcome' }));
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
this.#lastStage = candidate.stage;
|
|
102
|
+
for (const facet of candidate.facets ?? [])
|
|
103
|
+
this.#addFacet(facet);
|
|
104
|
+
const best = this.#best;
|
|
105
|
+
if (!best) {
|
|
106
|
+
this.#best = candidate;
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
if (messageOutcomePriority(candidate.outcome) > messageOutcomePriority(best.outcome)) {
|
|
110
|
+
this.#addFacet(facetOf(best));
|
|
111
|
+
this.#best = { ...candidate, ...(candidate.turnId === undefined && best.turnId ? { turnId: best.turnId } : {}) };
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
this.#addFacet(facetOf(candidate));
|
|
115
|
+
if (best.turnId === undefined && candidate.turnId)
|
|
116
|
+
this.#best = { ...best, turnId: candidate.turnId };
|
|
117
|
+
}
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
#addFacet(value) {
|
|
121
|
+
const facet = boundedCode(value);
|
|
122
|
+
if (facet && !this.#facets.includes(facet) && this.#facets.length < MAX_FACETS)
|
|
123
|
+
this.#facets.push(facet);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Settles the message once. With `error`, the outcome is `internal_error` (the caller logs and
|
|
127
|
+
* rethrows); without any candidate it is `unrecorded`.
|
|
128
|
+
*/
|
|
129
|
+
settle(input = {}) {
|
|
130
|
+
if (this.#settled)
|
|
131
|
+
return this.#settled;
|
|
132
|
+
const init = this.#init;
|
|
133
|
+
let candidate = this.#best ?? { outcome: 'unrecorded', reason: 'missing_outcome', stage: this.#lastStage };
|
|
134
|
+
if (input.error) {
|
|
135
|
+
if (this.#best)
|
|
136
|
+
this.#addFacet(facetOf(this.#best));
|
|
137
|
+
candidate = {
|
|
138
|
+
outcome: 'internal_error',
|
|
139
|
+
reason: `${stageThrow(this.#lastStage)}`,
|
|
140
|
+
stage: this.#lastStage,
|
|
141
|
+
errorId: input.error.errorId,
|
|
142
|
+
...(input.error.owner ? { owner: input.error.owner } : {}),
|
|
143
|
+
detail: [input.error.name, input.error.message].filter(Boolean).join(': '),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
const outcome = candidate.outcome;
|
|
147
|
+
const conversation = init.conversation;
|
|
148
|
+
const detail = boundedOutcomeDetail(candidate.detail);
|
|
149
|
+
const record = Object.freeze({
|
|
150
|
+
id: this.id,
|
|
151
|
+
receivedAt: init.receivedAt,
|
|
152
|
+
settledAt: (init.now ?? Date.now)(),
|
|
153
|
+
...(init.generation !== undefined ? { generation: init.generation } : {}),
|
|
154
|
+
conversation,
|
|
155
|
+
platform: conversation.endpoint.adapter,
|
|
156
|
+
sceneId: `${conversation.kind}:${conversation.id}`,
|
|
157
|
+
...(init.senderId ? { senderId: init.senderId } : {}),
|
|
158
|
+
...(init.messageId ? { messageId: init.messageId } : {}),
|
|
159
|
+
addressed: this.#addressed,
|
|
160
|
+
outcome,
|
|
161
|
+
...(boundedCode(candidate.reason) ? { reason: boundedCode(candidate.reason) } : {}),
|
|
162
|
+
facets: Object.freeze([...this.#facets]),
|
|
163
|
+
stage: candidate.stage,
|
|
164
|
+
visibility: candidate.visibility ?? defaultOutcomeVisibility(outcome, this.#addressed),
|
|
165
|
+
reply: candidate.reply ?? defaultOutcomeReply(outcome),
|
|
166
|
+
...(candidate.command ? { command: String(candidate.command).slice(0, 200) } : {}),
|
|
167
|
+
...(candidate.owner ? { owner: String(candidate.owner).slice(0, 200) } : {}),
|
|
168
|
+
...(candidate.turnId ? { turnId: String(candidate.turnId).slice(0, 200) } : {}),
|
|
169
|
+
...(this.#diagnosticId ? { diagnosticId: this.#diagnosticId } : {}),
|
|
170
|
+
...(candidate.errorId ? { errorId: candidate.errorId } : {}),
|
|
171
|
+
...(candidate.mergedInto ? { mergedInto: String(candidate.mergedInto).slice(0, 200) } : {}),
|
|
172
|
+
...(detail ? { detail } : {}),
|
|
173
|
+
...(outcome === 'unrecorded' ? { lastStage: this.#lastStage } : {}),
|
|
174
|
+
});
|
|
175
|
+
this.#settled = record;
|
|
176
|
+
if (outcome === 'unrecorded') {
|
|
177
|
+
for (const listener of unrecordedListeners) {
|
|
178
|
+
try {
|
|
179
|
+
listener(record);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
if (process.env.NODE_ENV === 'test')
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return record;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function facetOf(candidate) {
|
|
191
|
+
return candidate.reason ? `${candidate.outcome}:${candidate.reason}` : candidate.outcome;
|
|
192
|
+
}
|
|
193
|
+
function stageThrow(stage) {
|
|
194
|
+
switch (stage) {
|
|
195
|
+
case 'command': return 'command_threw';
|
|
196
|
+
case 'handlers': return 'handler_threw';
|
|
197
|
+
case 'middleware': return 'middleware_threw';
|
|
198
|
+
case 'agent_gate':
|
|
199
|
+
case 'ambient':
|
|
200
|
+
case 'admission':
|
|
201
|
+
case 'model':
|
|
202
|
+
case 'tool': return 'agent_threw';
|
|
203
|
+
default: return 'inbound_threw';
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Reports one outcome candidate for an inbound message (ADR 0061 §4.1). Agent and plugins call it
|
|
208
|
+
* with the message they received; a message without a ledger (outbound, synthetic) is ignored.
|
|
209
|
+
* @public
|
|
210
|
+
*/
|
|
211
|
+
export function reportInboundOutcome(message, candidate) {
|
|
212
|
+
return inboundOutcomeSinkOf(message)?.report(candidate) ?? false;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Whether a reply to this inbound message has been delivered so far (ADR 0061 §1.1); with `owner`,
|
|
216
|
+
* only a reply that plugin sent counts. @internal
|
|
217
|
+
*/
|
|
218
|
+
export function inboundOutcomeReplied(message, owner) {
|
|
219
|
+
return inboundOutcomeSinkOf(message)?.replied?.(owner) === true;
|
|
220
|
+
}
|
|
221
|
+
/** Marks the stage a message is entering, for `unrecorded` diagnosis. @public */
|
|
222
|
+
export function enterInboundOutcomeStage(message, stage) {
|
|
223
|
+
inboundOutcomeSinkOf(message)?.enter(stage);
|
|
224
|
+
}
|
|
225
|
+
function inboundOutcomeSinkOf(message) {
|
|
226
|
+
if (!message || typeof message !== 'object')
|
|
227
|
+
return undefined;
|
|
228
|
+
const method = message[inboundOutcomeSink];
|
|
229
|
+
return typeof method === 'function' ? method.call(message) : undefined;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Process-local outcome log: 2000 rows / 24 hours by default. Quiet outcomes (`not_addressed`,
|
|
233
|
+
* `ignored_bot`, `ignored_self`, `dropped_duplicate`) of one conversation beyond the per-minute
|
|
234
|
+
* limit collapse into one aggregated row per minute (`facets: ['aggregated:<n>']`, no message id);
|
|
235
|
+
* addressed messages and other outcomes are never sampled (ADR 0061 §2).
|
|
236
|
+
* @public
|
|
237
|
+
*/
|
|
238
|
+
export class MessageOutcomeLog {
|
|
239
|
+
options;
|
|
240
|
+
persistent = false;
|
|
241
|
+
#records = new Map();
|
|
242
|
+
/** Ids of silent-tier rows, oldest first: evicted before any other row when the log is full. */
|
|
243
|
+
#silent = new Set();
|
|
244
|
+
#quiet = new Map();
|
|
245
|
+
constructor(options = {}) {
|
|
246
|
+
this.options = options;
|
|
247
|
+
}
|
|
248
|
+
#now() { return (this.options.now ?? Date.now)(); }
|
|
249
|
+
record(record) {
|
|
250
|
+
this.#prune();
|
|
251
|
+
let stored = record;
|
|
252
|
+
if (!record.addressed && QUIET_MESSAGE_OUTCOMES.has(record.outcome)) {
|
|
253
|
+
const key = `${conversationKey(record.conversation)}\0${record.outcome}\0${record.reason ?? ''}`;
|
|
254
|
+
const minute = Math.floor(record.settledAt / 60_000);
|
|
255
|
+
let window = this.#quiet.get(key);
|
|
256
|
+
if (!window || window.minute !== minute) {
|
|
257
|
+
window = { minute, count: 0 };
|
|
258
|
+
this.#quiet.set(key, window);
|
|
259
|
+
if (this.#quiet.size > 4096)
|
|
260
|
+
this.#quiet.delete(this.#quiet.keys().next().value);
|
|
261
|
+
}
|
|
262
|
+
window.count += 1;
|
|
263
|
+
const limit = this.options.quietSampleLimit ?? 30;
|
|
264
|
+
if (window.count > limit) {
|
|
265
|
+
const n = window.count - limit;
|
|
266
|
+
const id = window.aggregate?.id ?? randomUUID();
|
|
267
|
+
const { messageId: _messageId, senderId: _senderId, ...rest } = record;
|
|
268
|
+
stored = Object.freeze({ ...rest, id, facets: Object.freeze([...record.facets.filter(f => !f.startsWith('aggregated:')), `aggregated:${n}`]) });
|
|
269
|
+
window.aggregate = { id, outcome: record.outcome, ...(record.reason ? { reason: record.reason } : {}), n };
|
|
270
|
+
this.#delete(id);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
this.#records.set(stored.id, stored);
|
|
274
|
+
if (isSilentOutcome(stored.outcome))
|
|
275
|
+
this.#silent.add(stored.id);
|
|
276
|
+
const capacity = this.options.capacity ?? 2000;
|
|
277
|
+
// A flood of silent rows (not addressed, bot echoes) never pushes out failures or replies.
|
|
278
|
+
while (this.#records.size > capacity) {
|
|
279
|
+
const oldest = this.#silent.size > 0 ? this.#silent.values().next().value : this.#records.keys().next().value;
|
|
280
|
+
this.#delete(oldest);
|
|
281
|
+
}
|
|
282
|
+
return stored;
|
|
283
|
+
}
|
|
284
|
+
#delete(id) {
|
|
285
|
+
this.#records.delete(id);
|
|
286
|
+
this.#silent.delete(id);
|
|
287
|
+
}
|
|
288
|
+
list(query = {}) {
|
|
289
|
+
this.#prune();
|
|
290
|
+
const limit = Number.isSafeInteger(query.limit) ? Math.min(500, Math.max(1, query.limit)) : 50;
|
|
291
|
+
const key = query.conversation ? conversationKey(query.conversation) : undefined;
|
|
292
|
+
const out = [];
|
|
293
|
+
for (const record of [...this.#records.values()].reverse()) {
|
|
294
|
+
if (key !== undefined && conversationKey(record.conversation) !== key)
|
|
295
|
+
continue;
|
|
296
|
+
if (query.senderId !== undefined && record.senderId !== query.senderId)
|
|
297
|
+
continue;
|
|
298
|
+
if (query.messageId !== undefined && record.messageId !== query.messageId)
|
|
299
|
+
continue;
|
|
300
|
+
if (query.outcome !== undefined && record.outcome !== query.outcome)
|
|
301
|
+
continue;
|
|
302
|
+
if (query.since !== undefined && record.settledAt < query.since)
|
|
303
|
+
continue;
|
|
304
|
+
out.push(record);
|
|
305
|
+
if (out.length >= limit)
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
return Object.freeze(out);
|
|
309
|
+
}
|
|
310
|
+
get(id) {
|
|
311
|
+
this.#prune();
|
|
312
|
+
return this.#records.get(id);
|
|
313
|
+
}
|
|
314
|
+
#prune() {
|
|
315
|
+
const threshold = this.#now() - (this.options.ttlMs ?? 24 * 60 * 60_000);
|
|
316
|
+
for (const [id, record] of this.#records) {
|
|
317
|
+
if (record.settledAt >= threshold)
|
|
318
|
+
break;
|
|
319
|
+
this.#delete(id);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/** Silent tier (ADR 0061 §1.3–§1.5): no reply by design, the bulk of the traffic. */
|
|
324
|
+
function isSilentOutcome(outcome) {
|
|
325
|
+
return messageOutcomePriority(outcome) === messageOutcomePriority('not_addressed');
|
|
326
|
+
}
|
|
327
|
+
function conversationKey(conversation) {
|
|
328
|
+
return JSON.stringify([conversation.endpoint.id, conversation.kind, conversation.id]);
|
|
329
|
+
}
|
|
@@ -5,16 +5,19 @@ import { type DeliveryReceipt, type UserInteraction } from '@zhin.js/im-contract
|
|
|
5
5
|
import type { GenerationAdmissionGate, PluginId, RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
|
|
6
6
|
import type { Notice } from '../../notice.js';
|
|
7
7
|
import type { Request } from '../../request.js';
|
|
8
|
-
import { RuntimeMessage, type CaptureEndpointOperationInput, type CapturedEndpointOperation, type IncomingMessage, type Message, type MessageSenderRef, type SendRequest } from './contracts.js';
|
|
8
|
+
import { RuntimeMessage, type CaptureEndpointOperationInput, type CapturedEndpointOperation, type IncomingMessage, type InboundSecretGuard, type Message, type MessageSenderRef, type SendRequest } from './contracts.js';
|
|
9
9
|
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<{
|
|
@@ -24,6 +27,8 @@ interface InboundRuntimeContext {
|
|
|
24
27
|
signal: AbortSignal;
|
|
25
28
|
}>): OperationResourceView | undefined;
|
|
26
29
|
readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
|
|
30
|
+
/** One-time secrets (ADR 0060 §3.3 claim code): handled before anything records, logs or routes them. */
|
|
31
|
+
readonly inboundSecret?: InboundSecretGuard;
|
|
27
32
|
/** Trusted origin classifier. Absent: messages carry no origin (legacy behavior). */
|
|
28
33
|
readonly originClassifier?: InboundOriginClassifier;
|
|
29
34
|
/** Cross-Endpoint dedup of human group messages. Absent: no dedup. */
|