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