@zhin.js/core 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/lib/built/interaction-messages.d.ts +1 -1
  2. package/lib/built/interactive-segments/resolve.js +12 -0
  3. package/lib/built/interactive-segments/types.d.ts +6 -0
  4. package/lib/built/roles.d.ts +33 -6
  5. package/lib/built/roles.js +27 -15
  6. package/lib/built/segment-contract/json-schema.js +1 -0
  7. package/lib/built/user-interaction.js +3 -0
  8. package/lib/plugin-runtime/im/ambient-switch.d.ts +49 -0
  9. package/lib/plugin-runtime/im/ambient-switch.js +70 -0
  10. package/lib/plugin-runtime/im/contracts.d.ts +58 -0
  11. package/lib/plugin-runtime/im/contracts.js +21 -1
  12. package/lib/plugin-runtime/im/conversation-runtime.js +12 -2
  13. package/lib/plugin-runtime/im/host/database-console-sql.js +1 -1
  14. package/lib/plugin-runtime/im/im-runtime.d.ts +9 -1
  15. package/lib/plugin-runtime/im/im-runtime.js +10 -0
  16. package/lib/plugin-runtime/im/inbound-outcome-ledger.d.ts +117 -0
  17. package/lib/plugin-runtime/im/inbound-outcome-ledger.js +329 -0
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +6 -1
  19. package/lib/plugin-runtime/im/inbound-runtime.js +268 -21
  20. package/lib/plugin-runtime/im/inbound-spine.d.ts +20 -3
  21. package/lib/plugin-runtime/im/inbound-spine.js +107 -7
  22. package/lib/plugin-runtime/im/index.d.ts +5 -1
  23. package/lib/plugin-runtime/im/index.js +3 -0
  24. package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -0
  25. package/lib/plugin-runtime/im/interaction-runtime.js +45 -14
  26. package/lib/plugin-runtime/im/message-diagnostics.d.ts +16 -0
  27. package/lib/plugin-runtime/im/message-diagnostics.js +12 -0
  28. package/lib/plugin-runtime/im/message-dispatcher.d.ts +6 -0
  29. package/lib/plugin-runtime/im/message-dispatcher.js +6 -1
  30. package/lib/plugin-runtime/im/message-outcome.d.ts +97 -0
  31. package/lib/plugin-runtime/im/message-outcome.js +125 -0
  32. package/lib/plugin-runtime/im/outbound-segments.js +1 -1
  33. package/package.json +15 -15
@@ -1 +1 @@
1
- export declare const interactionMessages: (locale: import("@zhin.js/plugin-runtime").Locale | undefined, key: "number" | "fallback" | "minLength" | "maxLength" | "pattern" | "integer" | "min" | "max" | "confirmOrCancel" | "select" | "invalidSelection" | "minSelections" | "maxSelections" | "minItems" | "maxItems" | "invalidNumbers" | "invalidBooleans" | "confirm" | "cancel" | "confirmation" | "selection" | "multiple" | "list" | "ended" | "denied" | "expired" | "timeout", values?: import("@zhin.js/plugin-runtime").MessageValues) => string;
1
+ export declare const interactionMessages: (locale: import("@zhin.js/plugin-runtime").Locale | undefined, key: "number" | "list" | "fallback" | "minLength" | "maxLength" | "pattern" | "integer" | "min" | "max" | "confirmOrCancel" | "select" | "invalidSelection" | "minSelections" | "maxSelections" | "minItems" | "maxItems" | "invalidNumbers" | "invalidBooleans" | "confirm" | "cancel" | "confirmation" | "selection" | "multiple" | "ended" | "denied" | "expired" | "timeout", values?: import("@zhin.js/plugin-runtime").MessageValues) => string;
@@ -59,6 +59,18 @@ export function renderKeyboardAsText(data, allocatedMap) {
59
59
  const lines = [];
60
60
  const flat = data.rows.flat();
61
61
  const entries = Object.entries(allocatedMap ?? effectiveKeyboardFallbackMap(data)).sort(([a], [b]) => Number(a) - Number(b));
62
+ if (data.fallback?.layout === 'inline' && entries.length) {
63
+ if (data.fallback.hint)
64
+ lines.push(data.fallback.hint);
65
+ lines.push(entries.map(([key, payload]) => {
66
+ const label = flat.find((b) => !b.disabled && b.payload === payload)?.label.trim() ?? '·';
67
+ return `${key}. ${label}`;
68
+ }).join(' '));
69
+ for (const button of flat)
70
+ if (button.disabled)
71
+ lines.push(`— ${button.label} (不可用)`);
72
+ return lines.join('\n');
73
+ }
62
74
  if (!entries.length) {
63
75
  lines.push('当前无可用操作。');
64
76
  }
@@ -23,6 +23,12 @@ export type ButtonData = {
23
23
  export type KeyboardFallback = {
24
24
  hint: string;
25
25
  map: Record<string, string>;
26
+ /**
27
+ * Text rendering on endpoints without buttons (`interactive: 'text'`): `list` (default) puts
28
+ * one option per line; `inline` puts the options on one line (`1. 要牌 2. 停牌 3. 放弃`) and
29
+ * prints the hint line only when it is non-empty.
30
+ */
31
+ layout?: 'list' | 'inline';
26
32
  };
27
33
  export type KeyboardSegmentData = {
28
34
  rows: ButtonData[][];
@@ -149,12 +149,39 @@ export declare function platformStandingOf(sender: unknown): PlatformStanding |
149
149
  /** `platform:admin` is met by `admin` and `owner` standings, `platform:owner` only by `owner`. */
150
150
  export declare function platformStandingIncludes(held: PlatformStandingLevel | undefined, required: 'owner' | 'admin'): boolean;
151
151
  /**
152
- * Identity + context of a message's sender. `context.conversationKey` is the conversation key, or —
153
- * when the conversation cannot be keyed (unknown kind, an id that cannot be part of a key) — the
154
- * receiving endpoint's key, so roles granted at the endpoint level and above still resolve.
155
- * Threads / topics (`conversation.threadId`) share their parent conversation's key, and a platform
156
- * container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
157
- * Undefined when not even the endpoint can be addressed.
152
+ * Why a message's sender could not be resolved for chat roles (ADR 0056 / zhinjs/zhin#1250):
153
+ * - `no-conversation`: the message carries no conversation with an endpoint id;
154
+ * - `unknown-endpoint`: that endpoint is not an account of this generation's adapters;
155
+ * - `no-adapter`: the endpoint resolves to no adapter instance alias;
156
+ * - `no-sender`: the message has no sender id;
157
+ * - `simulated-sender`: the sender id is reserved (`~…`, e.g. a Sandbox simulated sender), which never holds a role;
158
+ * - `invalid-sender`: any other sender id that cannot be a chat identity (control characters, over 256 characters).
159
+ * @public
160
+ */
161
+ export type ChatRoleSubjectFailure = 'no-conversation' | 'unknown-endpoint' | 'no-adapter' | 'no-sender' | 'simulated-sender' | 'invalid-sender';
162
+ /** @public */
163
+ export type ChatRoleSubjectResolution = Readonly<{
164
+ ok: true;
165
+ identity: ChatIdentity;
166
+ context: ChatRoleContext & {
167
+ conversationKey: string;
168
+ };
169
+ }> | Readonly<{
170
+ ok: false;
171
+ reason: ChatRoleSubjectFailure;
172
+ }>;
173
+ /**
174
+ * Identity + context of a message's sender, or why there is none. `context.conversationKey` is the
175
+ * conversation key, or — when the conversation cannot be keyed (unknown kind, an id that cannot be
176
+ * part of a key) — the receiving endpoint's key, so roles granted at the endpoint level and above
177
+ * still resolve. Threads / topics (`conversation.threadId`) share their parent conversation's key,
178
+ * and a platform container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
179
+ * @public
180
+ */
181
+ export declare function resolveChatRoleMessageContext(snapshot: ChatRoleSnapshot, message: unknown): ChatRoleSubjectResolution;
182
+ /**
183
+ * Identity + context of a message's sender ({@link resolveChatRoleMessageContext} without the
184
+ * reason). Undefined when not even the endpoint can be addressed or the sender is no chat identity.
158
185
  */
159
186
  export declare function chatRoleMessageContext(snapshot: ChatRoleSnapshot, message: unknown): {
160
187
  identity: ChatIdentity;
@@ -247,39 +247,51 @@ export function platformStandingIncludes(held, required) {
247
247
  return required === 'owner' ? held === 'owner' : held === 'owner' || held === 'admin';
248
248
  }
249
249
  /**
250
- * Identity + context of a message's sender. `context.conversationKey` is the conversation key, or —
251
- * when the conversation cannot be keyed (unknown kind, an id that cannot be part of a key) — the
252
- * receiving endpoint's key, so roles granted at the endpoint level and above still resolve.
253
- * Threads / topics (`conversation.threadId`) share their parent conversation's key, and a platform
254
- * container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
255
- * Undefined when not even the endpoint can be addressed.
250
+ * Identity + context of a message's sender, or why there is none. `context.conversationKey` is the
251
+ * conversation key, or — when the conversation cannot be keyed (unknown kind, an id that cannot be
252
+ * part of a key) — the receiving endpoint's key, so roles granted at the endpoint level and above
253
+ * still resolve. Threads / topics (`conversation.threadId`) share their parent conversation's key,
254
+ * and a platform container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
255
+ * @public
256
256
  */
257
- export function chatRoleMessageContext(snapshot, message) {
257
+ export function resolveChatRoleMessageContext(snapshot, message) {
258
+ const fail = (reason) => Object.freeze({ ok: false, reason });
258
259
  if (!record(message) || !record(message.conversation) || !record(message.conversation.endpoint))
259
- return undefined;
260
+ return fail('no-conversation');
260
261
  const conversation = message.conversation;
261
262
  if (typeof conversation.endpoint.id !== 'string')
262
- return undefined;
263
+ return fail('no-conversation');
263
264
  const key = resolveEndpointFeatureKey(snapshot, conversation.endpoint.id, typeof message.endpointId === 'string' ? message.endpointId : undefined, conversation);
264
265
  if (!key)
265
- return undefined;
266
+ return fail('unknown-endpoint');
266
267
  let adapter;
267
268
  try {
268
269
  adapter = parseFeatureResolutionKey(key).adapter;
269
270
  }
270
271
  catch {
271
- return undefined;
272
+ return fail('no-adapter');
272
273
  }
273
274
  if (!adapter)
274
- return undefined;
275
+ return fail('no-adapter');
275
276
  const parsed = parseFeatureConversationKey(key);
276
277
  const sender = record(message.sender) ? message.sender : undefined;
277
- const identity = { adapter, userId: typeof sender?.id === 'string' ? sender.id : '' };
278
+ const userId = typeof sender?.id === 'string' ? sender.id : '';
279
+ if (!userId)
280
+ return fail('no-sender');
281
+ const identity = { adapter, userId };
278
282
  if (!isChatIdentity(identity))
279
- return undefined;
283
+ return fail(userId.startsWith(RESERVED_SENDER_PREFIX) ? 'simulated-sender' : 'invalid-sender');
280
284
  const kind = parsed?.conversation.kind ?? conversation.kind;
281
285
  const platform = kind === 'private' ? undefined : platformStandingOf(sender);
282
- return { identity, context: { conversationKey: key, ...(platform ? { platform } : {}) } };
286
+ return Object.freeze({ ok: true, identity, context: { conversationKey: key, ...(platform ? { platform } : {}) } });
287
+ }
288
+ /**
289
+ * Identity + context of a message's sender ({@link resolveChatRoleMessageContext} without the
290
+ * reason). Undefined when not even the endpoint can be addressed or the sender is no chat identity.
291
+ */
292
+ export function chatRoleMessageContext(snapshot, message) {
293
+ const resolved = resolveChatRoleMessageContext(snapshot, message);
294
+ return resolved.ok ? { identity: resolved.identity, context: resolved.context } : undefined;
283
295
  }
284
296
  /**
285
297
  * Inbound sender enricher: drops any adapter-supplied `chatRole` / `chatRoleLevels`, normalizes
@@ -151,6 +151,7 @@ export const outboundSegmentJsonSchema = {
151
151
  fallback: interactiveDataObject({
152
152
  hint: { type: 'string' },
153
153
  map: { type: 'object', additionalProperties: { type: 'string' } },
154
+ layout: { type: 'string', enum: ['list', 'inline'] },
154
155
  }, ['hint', 'map']),
155
156
  }, ['rows'])),
156
157
  strictBranch('action', interactiveDataObject({
@@ -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 {
@@ -194,6 +197,54 @@ export interface OutboundMessageService {
194
197
  */
195
198
  registerInteractiveHandler(prefix: string, handler: (message: Message) => Promise<boolean> | boolean): () => void;
196
199
  }
200
+ /**
201
+ * Inbound secret guard (ADR 0060 §3.3, zhinjs/zhin#1250): recognizes a message that carries a one-time
202
+ * secret (the chat-owner claim code) before anything else sees it. A recognized message is never
203
+ * recorded in the conversation history, never handed to middlewares, handlers, commands, interaction
204
+ * prompts or the Agent, and is logged and published only as {@link InboundSecretMatch.redacted}.
205
+ */
206
+ export interface InboundSecretGuard {
207
+ match(input: Readonly<{
208
+ /** The text a command would be matched against (leading quotes and mentions dropped, trimmed). */
209
+ text: string;
210
+ /** The command prefix of this conversation (`''`: none). */
211
+ prefix: string;
212
+ conversation: ConversationRef;
213
+ snapshot: RuntimeSnapshot;
214
+ }>): InboundSecretMatch | undefined;
215
+ /**
216
+ * Whether an Endpoint event other than `message.receive` carries the secret: native platform events
217
+ * (`platform.receive` and any other side event) and canonical notices, requests (a friend or join
218
+ * request's comment) and system events. Such an event is neither recorded nor dispatched to Handlers:
219
+ * its payload is platform-shaped, so it cannot be redacted reliably. A payload too large to inspect
220
+ * completely should count as carrying it (fail closed).
221
+ */
222
+ inspectNative?(payload: unknown, event?: Readonly<{
223
+ name: string;
224
+ }>): boolean;
225
+ /**
226
+ * A notice, request or system event withheld by {@link inspectNative} was still seen on the platform
227
+ * (a join request's comment is shown to the group's admins): revoke the secret when the payload
228
+ * really carries it (not merely too large to inspect). Not called for `platform.receive`: the same
229
+ * message's `message.receive` still reaches {@link match}.
230
+ */
231
+ discardNative?(payload: unknown, event?: Readonly<{
232
+ name: string;
233
+ }>): Promise<void> | void;
234
+ }
235
+ export interface InboundSecretMatch {
236
+ /** Reported as the outcome's command (for example `claim`). */
237
+ readonly name: string;
238
+ /** What logs and the message event stream show instead of the text (for example `认领 ***`). */
239
+ readonly redacted: string;
240
+ /** Handles the message; the returned content is replied through the normal send chain by the root Plugin. */
241
+ handle(message: Message): Promise<SendContent | undefined> | SendContent | undefined;
242
+ /**
243
+ * The message is dropped before {@link handle} (not ready, another bot or one of ours posted it, dedup
244
+ * failure): a secret it carries was still seen by others, so the guard revokes it.
245
+ */
246
+ discard?(): Promise<void> | void;
247
+ }
197
248
  export interface MessageDispatchResult {
198
249
  readonly matched: boolean;
199
250
  readonly status?: 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed';
@@ -286,6 +337,11 @@ export interface RuntimeMessageOperation {
286
337
  }>) => OperationResourceView | undefined;
287
338
  readonly registerOperationView?: (view: object, owner: PluginId) => void;
288
339
  readonly presentation?: RuntimeMessagePresentation;
340
+ /**
341
+ * ADR 0061: report port of this message's outcome ledger, shared by every author view. Only
342
+ * `report` / `enter` are kept (a frozen facade); settling stays with the inbound runtime.
343
+ */
344
+ readonly outcomes?: InboundOutcomeSink;
289
345
  }
290
346
  /** Canonical runtime message with optional plugin-owned extensions. */
291
347
  export type Message<T extends object = {}> = MessageBase & T;
@@ -319,6 +375,8 @@ export declare class RuntimeMessage implements MessageBase {
319
375
  [operationInputResources](snapshot: RuntimeSnapshot): CapabilityOperationFactory | undefined;
320
376
  /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
321
377
  [operationInputSignal](): AbortSignal | undefined;
378
+ /** @internal The inbound outcome ledger (ADR 0061); reports after settlement are ignored by it. */
379
+ [inboundOutcomeSink](): InboundOutcomeSink | undefined;
322
380
  /** @internal The command/handler author's actual leased operation. */
323
381
  [interactionOperationScope](): InteractionOperationScope | undefined;
324
382
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
@@ -1,6 +1,20 @@
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
+ replied: (owner) => sink.replied?.(owner) === true,
14
+ });
15
+ facades.add(facade);
16
+ return facade;
17
+ }
4
18
  /** Internal send binding retained by one inbound operation; never a wire/config field. */
5
19
  export const operationEndpoint = Symbol('zhin.im.operation-endpoint');
6
20
  /** Core-only trusted operation binding; never read from message metadata. */
@@ -82,7 +96,9 @@ export class RuntimeMessage {
82
96
  /** Core owns these immutable facts; author rebinding shares them and the captured operation. */
83
97
  constructor(facts, operation) {
84
98
  this.#facts = Object.freeze(facts);
85
- this.#operation = Object.freeze(operation);
99
+ // Never hand the ledger itself to views: plugins only get the report port (no `settle`).
100
+ const outcomes = operation.outcomes;
101
+ this.#operation = Object.freeze(outcomes ? { ...operation, outcomes: inboundOutcomeFacade(outcomes) } : operation);
86
102
  const { conversation, content, sender, segments, message, endpointId, mentioned, replyTo } = facts;
87
103
  const { reply } = operation;
88
104
  this.conversation = conversation;
@@ -195,6 +211,10 @@ export class RuntimeMessage {
195
211
  this.#operation.assertActive?.();
196
212
  return this.#operation.signal;
197
213
  }
214
+ /** @internal The inbound outcome ledger (ADR 0061); reports after settlement are ignored by it. */
215
+ [inboundOutcomeSink]() {
216
+ return this.#operation.outcomes;
217
+ }
198
218
  /** @internal The command/handler author's actual leased operation. */
199
219
  [interactionOperationScope]() {
200
220
  this.#operation.assertActive?.();
@@ -1,4 +1,5 @@
1
1
  import { MemoryConversationEventStore, conversationRefKey, messageRefKey, } from '@zhin.js/im-contract';
2
+ import { redactChatOwnerClaimText } from '@zhin.js/kernel';
2
3
  import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
3
4
  import { segmentsToPlainText } from '../../built/segment-contract/text.js';
4
5
  import { SCENE_ONLY_EVENT_TYPES, SCENE_EVENT_TEXT_MAX, clipSceneText } from '../../side-event/scene-events.js';
@@ -9,6 +10,14 @@ import { flattenContent } from './message-events.js';
9
10
  */
10
11
  export const CONVERSATION_CONTEXT_MAX_AGE_MS = 30 * 60 * 1000;
11
12
  const MAX_TRACKED_INTERACTION_ANSWERS = 1_000;
13
+ /** A text segment with any claim code replaced by `***`; other segments unchanged. */
14
+ function redactClaimSegment(segment) {
15
+ const data = segment.data;
16
+ if (segment.type !== 'text' || typeof data?.text !== 'string')
17
+ return segment;
18
+ const text = redactChatOwnerClaimText(data.text);
19
+ return text === data.text ? segment : { ...segment, data: { ...data, text } };
20
+ }
12
21
  /** Owns one ImRuntime's conversation fact store, projections, and consumer cursors. */
13
22
  export class ConversationRuntime {
14
23
  #events;
@@ -103,9 +112,10 @@ export class ConversationRuntime {
103
112
  actor: sender
104
113
  ? Object.freeze({ id: sender.id, ...(sender.name ? { displayName: sender.name } : {}) })
105
114
  : UNKNOWN_SENDER,
115
+ // Backstop (ADR 0060 §3.3): an open chat-owner claim code is stored as `***`.
106
116
  segments: Object.freeze(input.segments?.length
107
- ? [...input.segments]
108
- : [{ type: 'text', data: { text: input.content } }]),
117
+ ? input.segments.map(redactClaimSegment)
118
+ : [{ type: 'text', data: { text: redactChatOwnerClaimText(input.content) } }]),
109
119
  timestamp,
110
120
  ...(input.replyTo
111
121
  ? { replyTo: Object.freeze({ conversation: input.conversation, id: input.replyTo.id }) }
@@ -297,7 +297,7 @@ export function readStatementKind(statement, dialect) {
297
297
  * Tables the Console never changes: the gateway's `console_*` (never even read), migration
298
298
  * bookkeeping and engine catalogs. Reads of the latter are allowed.
299
299
  */
300
- const PROTECTED_TABLE = /^(?:__zhin_persistent_state|_migrations|agent_schedule_migration|sqlite_\w+|pg_\w+|information_schema|mysql|performance_schema|sys)$/;
300
+ const PROTECTED_TABLE = /^(?:__zhin_persistent_state|_migrations|agent_schedule_migration|engagement_event_migrations|sqlite_\w+|pg_\w+|information_schema|mysql|performance_schema|sys)$/;
301
301
  export function isProtectedConsoleTable(name) {
302
302
  const bare = String(name).trim().toLowerCase();
303
303
  return isGatewayOwnedTable(bare) || PROTECTED_TABLE.test(bare);
@@ -2,7 +2,7 @@ import { Scope, generationAdmissionBinder, type GenerationAdmissionGate, type Ru
2
2
  import { PermissionHost } from '@zhin.js/permission';
3
3
  import { type EndpointContentResolveContext, type EndpointEventGateway, type PeerRegistry } from '@zhin.js/adapter';
4
4
  import { type ConversationEventStore, type ConversationEventReader, type ConversationContextBlock, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
5
- import { Message, type IncomingMessage, type OutboundMessageService, type MessageSenderRef, type SendRequest } from './contracts.js';
5
+ import { Message, type IncomingMessage, type OutboundMessageService, type InboundSecretGuard, type MessageSenderRef, type SendRequest } from './contracts.js';
6
6
  import { LoginAssist } from '../../built/login-assist.js';
7
7
  import type { UserInteraction } from '@zhin.js/im-contract';
8
8
  import type { OutboundRenderer } from './outbound-renderer.js';
@@ -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 消费。
@@ -28,6 +29,11 @@ export interface ImRuntimeOptions {
28
29
  readonly conversationEvents?: ConversationEventStore;
29
30
  /** Process-root ingress claim (pending interaction, authentication challenge, etc.). */
30
31
  readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
32
+ /**
33
+ * Recognizes messages that carry a one-time secret (ADR 0060 §3.3: the chat-owner claim code) before
34
+ * anything records, logs or routes them; see {@link InboundSecretGuard}.
35
+ */
36
+ readonly inboundSecret?: InboundSecretGuard;
31
37
  /**
32
38
  * 探测 `inboundClaim` 这类进程级 prompt 在该 Endpoint 上、对该发送者是否有待回答项。
33
39
  * Room Router 用它把消息送到持有待回答状态的成员 Endpoint。必须同步、无副作用。
@@ -48,6 +54,8 @@ export interface ImRuntimeOptions {
48
54
  }
49
55
  export declare class ImRuntime implements OutboundMessageService {
50
56
  #private;
57
+ /** ADR 0061: settled inbound message outcomes (process memory, 2000 rows / 24 h). */
58
+ readonly messageOutcomes: MessageOutcomeReader;
51
59
  readonly messageDiagnostics: RuntimeMessageDiagnosticsReader;
52
60
  readonly messageEvents: RuntimeMessageEventSource;
53
61
  /** #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 => {
@@ -78,6 +87,7 @@ export class ImRuntime {
78
87
  return readLeasedRootResource(snapshots, input.lease, imOperationResourcesToken)?.open({ ...input, snapshots });
79
88
  },
80
89
  inboundClaim: options.inboundClaim,
90
+ ...(options.inboundSecret ? { inboundSecret: options.inboundSecret } : {}),
81
91
  originClassifier,
82
92
  deduper,
83
93
  registry,