@zhin.js/core 1.1.48 → 1.1.49

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.
@@ -8,6 +8,7 @@
8
8
  * 3. 私聊直接对话 - 私聊时直接对话
9
9
  * 4. 关键词触发 - 非群/频道场景下匹配关键词时触发
10
10
  */
11
+ import type { AmbientEngagementConfig } from '@zhin.js/ai';
11
12
  import type { Message } from "../plugin-runtime/im/contracts.js";
12
13
  import type { MessageElement, ToolScope } from "../types.js";
13
14
  import { type SenderRole } from './roles.js';
@@ -37,6 +38,8 @@ export interface AITriggerConfig {
37
38
  masters?: string[];
38
39
  /** 全局 trusted(trigger 级) */
39
40
  trusted?: string[];
41
+ /** 群聊旁听:没人叫机器人时,由判断模型决定是否接话 */
42
+ ambient?: AmbientEngagementConfig;
40
43
  }
41
44
  /**
42
45
  * AI 触发检查结果
@@ -26,6 +26,7 @@ export const DEFAULT_AI_TRIGGER_CONFIG = {
26
26
  errorTemplate: '❌ AI 处理失败: {error}',
27
27
  masters: [],
28
28
  trusted: [],
29
+ ambient: {},
29
30
  };
30
31
  // ============================================================================
31
32
  // 工具函数
@@ -29,3 +29,8 @@ export declare class ConversationRuntime {
29
29
  recordOutbound(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
30
30
  recordNotice(notice: Notice): Promise<void>;
31
31
  }
32
+ /**
33
+ * Label of the bot's own messages. Outbound messages are recorded without an actor; without
34
+ * them the model cannot tell its own words from the members' or follow the order of the chat.
35
+ */
36
+ export declare const OWN_MESSAGE_LABEL = "You (this bot)";
@@ -37,19 +37,24 @@ export class ConversationRuntime {
37
37
  const events = await this.#events.listBetween(conversation, cursor, throughSequence, limit);
38
38
  const notBefore = Date.now() - CONVERSATION_CONTEXT_MAX_AGE_MS;
39
39
  const relevant = [];
40
+ // The bot's own messages it later recalled (an activity indicator) never were part of the chat.
41
+ const excluded = new Set(excludeMessageId ? [excludeMessageId] : []);
40
42
  for (const entry of events) {
41
43
  // Only message timestamps are runtime-assigned; notice clocks are adapter-defined.
42
44
  if (entry.event.type === 'message.created' && entry.event.timestamp < notBefore)
43
45
  continue;
44
- if (await this.#isOwnRecall(entry.event))
46
+ if (await this.#isOwnRecall(entry.event)) {
47
+ if (entry.event.type === 'message.recalled')
48
+ excluded.add(entry.event.message.id);
45
49
  continue;
50
+ }
46
51
  if (entry.event.type === 'message.created'
47
52
  && this.#interactionAnswers.has(messageRefKey(entry.event.message.ref)))
48
53
  continue;
49
54
  relevant.push(entry);
50
55
  }
51
56
  return Object.freeze({
52
- blocks: aggregateConversationContext(relevant, excludeMessageId),
57
+ blocks: aggregateConversationContext(relevant, excluded),
53
58
  cursor: Math.max(cursor, throughSequence),
54
59
  });
55
60
  }
@@ -92,10 +97,10 @@ export class ConversationRuntime {
92
97
  type: 'message.created',
93
98
  message: Object.freeze({
94
99
  ref: input.message,
95
- ...(sender ? { actor: Object.freeze({
96
- id: sender.id,
97
- ...(sender.name ? { displayName: sender.name } : {}),
98
- }) } : {}),
100
+ // An actor-less message means the bot's own outbound; never leave an inbound one without.
101
+ actor: sender
102
+ ? Object.freeze({ id: sender.id, ...(sender.name ? { displayName: sender.name } : {}) })
103
+ : UNKNOWN_SENDER,
99
104
  segments: Object.freeze(input.segments?.length
100
105
  ? [...input.segments]
101
106
  : [{ type: 'text', data: { text: input.content } }]),
@@ -225,12 +230,12 @@ function conversationEventFromNotice(notice) {
225
230
  return undefined;
226
231
  }
227
232
  }
228
- function aggregateConversationContext(events, excludeMessageId) {
233
+ function aggregateConversationContext(events, excluded) {
229
234
  const ordinary = [];
230
235
  const noisy = new Map();
231
236
  for (const { sequence, event } of events) {
232
237
  if (event.type === 'message.created') {
233
- if (event.message.ref.id === excludeMessageId)
238
+ if (excluded.has(event.message.ref.id))
234
239
  continue;
235
240
  const text = describeConversationMessage(event.message);
236
241
  if (!text)
@@ -294,13 +299,21 @@ function describeConversationEvent(event) {
294
299
  return '';
295
300
  }
296
301
  }
302
+ /**
303
+ * Label of the bot's own messages. Outbound messages are recorded without an actor; without
304
+ * them the model cannot tell its own words from the members' or follow the order of the chat.
305
+ */
306
+ export const OWN_MESSAGE_LABEL = 'You (this bot)';
307
+ const UNKNOWN_SENDER = Object.freeze({ id: 'unknown', displayName: 'Unknown sender' });
308
+ /** In-turn progress updates (the Agent's `⏳ ` marker) are not part of the conversation. */
309
+ const OWN_PROGRESS_PREFIX = /^⏳\s*/u;
297
310
  function describeConversationMessage(message) {
311
+ const text = segmentsToPlainText(message.segments).trim();
312
+ if (!message.actor && OWN_PROGRESS_PREFIX.test(text))
313
+ return '';
298
314
  const actor = message.actor
299
315
  ? `${message.actor.displayName ?? message.actor.id} (${message.actor.id})`
300
- : undefined;
301
- if (!actor)
302
- return '';
303
- const text = segmentsToPlainText(message.segments).trim();
316
+ : OWN_MESSAGE_LABEL;
304
317
  const attachmentTypes = [...new Set(message.segments
305
318
  .filter((segment) => segment.type !== 'text' && segment.type !== 'mention' && segment.type !== 'at')
306
319
  .map((segment) => segment.type))];
@@ -30,7 +30,7 @@ export class ImRuntime {
30
30
  messageEvents = Object.freeze({
31
31
  subscribe: (listener) => this.#messageEventStream.subscribe(listener),
32
32
  });
33
- #interactions = new RuntimeInteractionCoordinator();
33
+ #interactions = new RuntimeInteractionCoordinator(undefined, (message) => this.#conversations.markInteractionAnswer(message));
34
34
  #conversations;
35
35
  #outbound;
36
36
  #inbound;
@@ -1,4 +1,4 @@
1
- import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
1
+ import { type ConversationRef, type DeliveryReceipt, type MessageRef } from '@zhin.js/im-contract';
2
2
  import type { UserInteraction } from '@zhin.js/interaction';
3
3
  import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
4
  import { type Message, type MessageSenderRef, type SendContent, type SendRequest } from './contracts.js';
@@ -15,7 +15,8 @@ export interface UserInteractionSource {
15
15
  /** Owns one ImRuntime's conversational claims, actions, and keyboard fallback state. */
16
16
  export declare class RuntimeInteractionCoordinator<Admission = never> {
17
17
  #private;
18
- constructor(router?: RuntimeInteractiveRouter<Admission>);
18
+ /** `markPrompt` keeps a delivered prompt out of conversation context, like its answer. */
19
+ constructor(router?: RuntimeInteractiveRouter<Admission>, markPrompt?: (message: MessageRef) => void);
19
20
  register(prefix: string, handler: (message: Message) => Promise<boolean> | boolean, admission?: Admission): () => void;
20
21
  rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string>;
21
22
  dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
@@ -30,8 +30,11 @@ export class RuntimeInteractionCoordinator {
30
30
  #router;
31
31
  #claims = new Map();
32
32
  #buttons = new JsxButtonRegistry();
33
- constructor(router = new RuntimeInteractiveRouter()) {
33
+ #markPrompt;
34
+ /** `markPrompt` keeps a delivered prompt out of conversation context, like its answer. */
35
+ constructor(router = new RuntimeInteractiveRouter(), markPrompt) {
34
36
  this.#router = router;
37
+ this.#markPrompt = markPrompt;
35
38
  }
36
39
  register(prefix, handler, admission) {
37
40
  return this.#router.register(prefix, handler, admission);
@@ -142,6 +145,8 @@ export class RuntimeInteractionCoordinator {
142
145
  if (receipt.status !== 'sent')
143
146
  throw new UserInteractionDeliveryError(receipt);
144
147
  claim.delivered();
148
+ if (receipt.message)
149
+ this.#markPrompt?.(receipt.message);
145
150
  const raw = await claim.answer;
146
151
  claim.check();
147
152
  const result = parseUserInteractionAnswer(request, raw);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.1.48",
3
+ "version": "1.1.49",
4
4
  "description": "Zhin机器人核心框架",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -64,7 +64,7 @@
64
64
  "@zhin.js/handler": "1.1.7",
65
65
  "@zhin.js/im-contract": "1.1.5",
66
66
  "@zhin.js/interaction": "1.1.2",
67
- "@zhin.js/kernel": "1.1.4",
67
+ "@zhin.js/kernel": "1.1.5",
68
68
  "@zhin.js/logger": "1.1.2",
69
69
  "@zhin.js/middleware": "1.1.8",
70
70
  "@zhin.js/permission": "1.1.7",
@@ -79,7 +79,7 @@
79
79
  "@types/qrcode": "^1.5.6",
80
80
  "ajv": "8.18.0",
81
81
  "typescript": "^6.0.3",
82
- "@zhin.js/ai": "1.1.42"
82
+ "@zhin.js/ai": "1.1.43"
83
83
  },
84
84
  "repository": {
85
85
  "type": "git",