@zhin.js/core 1.1.39 → 1.1.40

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.
@@ -1,4 +1,4 @@
1
- import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
1
+ import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type Endpoint, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
2
2
  import type { RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
3
3
  import type { ConversationRef, DeliveryReceipt, EndpointCapabilities, MessageRef } from '@zhin.js/im-contract';
4
4
  import type { ConversationAddress, SendRequest } from './contracts.js';
@@ -8,6 +8,9 @@ export interface EndpointRuntimeSummary {
8
8
  readonly adapter: string;
9
9
  readonly owner: string;
10
10
  readonly connected: boolean;
11
+ readonly admitted: boolean;
12
+ readonly transportState: EndpointTransportState | 'unknown';
13
+ readonly eventDiagnostics: Endpoint['eventDiagnostics'];
11
14
  readonly status: 'online' | 'offline';
12
15
  readonly phase: AdapterEndpointPhase;
13
16
  readonly operations: readonly AdapterOperation[];
@@ -75,5 +78,7 @@ export declare class EndpointRuntime {
75
78
  withManagement<T>(adapter: string, endpointKey: string, run: (management: EndpointManagement) => T | Promise<T>): Promise<T | null>;
76
79
  }
77
80
  export declare function requireAdapters(snapshot: RuntimeSnapshot): AdapterIndex;
81
+ /** Resolves public list identities against the exact operation snapshot; ambiguous aliases never pick an account. */
82
+ export declare function resolveEndpointIdentity(snapshot: RuntimeSnapshot, index: AdapterIndex, adapter: string, endpointKey: string): import("@zhin.js/plugin-runtime").CapabilityId | undefined;
78
83
  export declare function adapterTypeName(packageName: string | undefined): string | undefined;
79
84
  export {};
@@ -12,6 +12,9 @@ export class EndpointRuntime {
12
12
  adapter: adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name,
13
13
  owner: row.owner,
14
14
  connected: row.connected,
15
+ admitted: row.admitted,
16
+ transportState: row.transportState,
17
+ eventDiagnostics: row.eventDiagnostics,
15
18
  status: row.status,
16
19
  phase: row.phase,
17
20
  operations: row.operations,
@@ -21,14 +24,14 @@ export class EndpointRuntime {
21
24
  capabilities(input) {
22
25
  return this.#withLease((snapshot) => {
23
26
  const index = requireAdapters(snapshot);
24
- const id = index.resolve(input.adapter, input.endpointKey);
27
+ const id = resolveEndpointIdentity(snapshot, index, input.adapter, input.endpointKey);
25
28
  return id ? index.capabilities(id) : undefined;
26
29
  }, undefined);
27
30
  }
28
31
  get(adapter, endpointKey) {
29
32
  return this.#withLease((snapshot) => {
30
33
  const index = requireAdapters(snapshot);
31
- const id = index.resolve(adapter, endpointKey);
34
+ const id = resolveEndpointIdentity(snapshot, index, adapter, endpointKey);
32
35
  if (!id)
33
36
  return null;
34
37
  const row = index.describe().find((item) => item.id === id);
@@ -38,6 +41,9 @@ export class EndpointRuntime {
38
41
  name: row.name,
39
42
  adapter: adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name,
40
43
  connected: row.connected,
44
+ admitted: row.admitted,
45
+ transportState: row.transportState,
46
+ eventDiagnostics: row.eventDiagnostics,
41
47
  status: row.status,
42
48
  phase: row.phase,
43
49
  operations: row.operations,
@@ -49,7 +55,7 @@ export class EndpointRuntime {
49
55
  const lease = this.context.acquire();
50
56
  try {
51
57
  const index = requireAdapters(lease.value);
52
- const resolved = index.resolve(input.adapter, input.endpointKey);
58
+ const resolved = resolveEndpointIdentity(lease.value, index, input.adapter, input.endpointKey);
53
59
  if (!resolved)
54
60
  throw new Error('endpoint not found');
55
61
  const requester = index.owner(resolved);
@@ -95,7 +101,9 @@ export class EndpointRuntime {
95
101
  return null;
96
102
  }
97
103
  try {
98
- const endpoint = requireAdapters(lease.value).connection(adapter, endpointKey);
104
+ const index = requireAdapters(lease.value);
105
+ const id = resolveEndpointIdentity(lease.value, index, adapter, endpointKey);
106
+ const endpoint = id ? index.connection(String(id), String(id)) : undefined;
99
107
  if (!endpoint)
100
108
  return null;
101
109
  return await run(resolveEndpointManagement(endpoint) ?? Object.freeze({}));
@@ -114,7 +122,7 @@ export class EndpointRuntime {
114
122
  }
115
123
  try {
116
124
  const index = requireAdapters(lease.value);
117
- const id = index.resolve(adapter, endpointKey);
125
+ const id = resolveEndpointIdentity(lease.value, index, adapter, endpointKey);
118
126
  const control = id ? index.control(id, operation) : undefined;
119
127
  return control ? await run(control) : fallback;
120
128
  }
@@ -148,6 +156,20 @@ export function requireAdapters(snapshot) {
148
156
  }
149
157
  return projection;
150
158
  }
159
+ /** Resolves public list identities against the exact operation snapshot; ambiguous aliases never pick an account. */
160
+ export function resolveEndpointIdentity(snapshot, index, adapter, endpointKey) {
161
+ const live = new Map(index.describe().map(row => [row.id, row.name]));
162
+ const matches = index.list().filter(record => {
163
+ const localName = record.id.split('\0').pop() ?? record.id;
164
+ const alias = adapterTypeName(snapshot.tree.get(record.owner)?.packageName);
165
+ const adapterMatches = alias === adapter || record.name === adapter || String(record.id) === adapter
166
+ || localName === adapter || String(record.owner) === adapter || record.owner.endsWith(`/${adapter}`);
167
+ const endpointMatches = record.name === endpointKey || String(record.id) === endpointKey
168
+ || record.id.endsWith(`/${endpointKey}`) || live.get(record.id) === endpointKey;
169
+ return adapterMatches && endpointMatches;
170
+ });
171
+ return matches.length === 1 ? matches[0].id : undefined;
172
+ }
151
173
  export function adapterTypeName(packageName) {
152
174
  if (!packageName)
153
175
  return undefined;
@@ -1,15 +1,31 @@
1
+ import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
1
2
  import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
2
3
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
3
4
  const logger = getLogger('command');
4
- function ownerOfMessage(message) {
5
- return message.conversation.endpoint.adapter;
5
+ function ownerOfMessage(message, snapshot) {
6
+ // adapter is a platform literal (e.g. terminal), not the Plugin owner.
7
+ const slot = snapshot.capabilities.get(message.conversation.endpoint.id);
8
+ if (slot)
9
+ return slot.owner;
10
+ // Expanded endpoint records have identities distinct from their source slot.
11
+ // Resolve their ownership through the generation's canonical AdapterIndex.
12
+ const adapters = snapshot.projections.get(adapterFeatureId);
13
+ if (!isAdapterIndex(adapters))
14
+ return undefined;
15
+ try {
16
+ return adapters.owner(message.conversation.endpoint.id);
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
6
21
  }
7
22
  /**
8
23
  * 默认解析:读消息所属适配器实例 config 的 `commandPrefix`(默认 `''`);
9
24
  * 实例声明 `endpoints` 数组时,按消息 endpoint 名找 entry,`entry.commandPrefix` 覆盖顶层。
10
25
  */
11
26
  export const defaultCommandPrefixResolver = (message, snapshot) => {
12
- const config = snapshot.config.get(ownerOfMessage(message));
27
+ const owner = ownerOfMessage(message, snapshot);
28
+ const config = (owner ? snapshot.config.get(owner) : undefined);
13
29
  if (!config)
14
30
  return '';
15
31
  const endpointId = message.endpointId;
@@ -43,7 +59,7 @@ export class MessageDispatcher {
43
59
  ? stripCommandPrefix(message.segments, prefix)
44
60
  : undefined;
45
61
  const matchInput = structuredInput ?? input;
46
- const result = await commands.dispatch(matchInput, message, interactionFactory, prefix);
62
+ const result = await commands.dispatch(matchInput, message, interactionFactory, prefix, snapshot);
47
63
  if (result.matched && result.value !== undefined) {
48
64
  if (!result.owner)
49
65
  throw new Error('Matched Command is missing its owner');
@@ -70,6 +86,7 @@ export class MessageDispatcher {
70
86
  function stripCommandPrefix(segments, prefix) {
71
87
  let pendingPrefix = prefix;
72
88
  let atStart = true;
89
+ let trimLeading = true;
73
90
  const result = [];
74
91
  for (const segment of segments) {
75
92
  if (!atStart) {
@@ -84,6 +101,13 @@ function stripCommandPrefix(segments, prefix) {
84
101
  continue;
85
102
  }
86
103
  let text = segment.data.text;
104
+ // Match the leading whitespace normalization of message.content without
105
+ // discarding structured arguments when the prefix follows whitespace.
106
+ if (trimLeading) {
107
+ text = text.trimStart();
108
+ if (text)
109
+ trimLeading = false;
110
+ }
87
111
  if (pendingPrefix) {
88
112
  if (text.startsWith(pendingPrefix)) {
89
113
  text = text.slice(pendingPrefix.length);
@@ -1,5 +1,5 @@
1
1
  import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
- import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
2
+ import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
3
3
  import { type SendRequest } from './contracts.js';
4
4
  import { OutboundRenderer } from './outbound-renderer.js';
5
5
  import { type RuntimeMessageEvent } from './message-events.js';
@@ -1,8 +1,9 @@
1
1
  import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
2
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
2
3
  import { formatCompact, getLogger } from '@zhin.js/logger';
3
4
  import { createOutboundEnvelope } from './contracts.js';
4
5
  import { OutboundRenderer } from './outbound-renderer.js';
5
- import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, } from './outbound-segments.js';
6
+ import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
6
7
  import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
7
8
  import { adapterTypeName, requireAdapters } from './endpoint-runtime.js';
8
9
  import { formatConversationLog, previewMessageContent } from './message-events.js';
@@ -23,7 +24,9 @@ export class OutboundDeliveryRuntime {
23
24
  const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming);
24
25
  initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
25
26
  }
26
- catch {
27
+ catch (error) {
28
+ if (error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent')
29
+ return receiptFromEndpointError(error, false);
27
30
  return rejectedDeliveryReceipt('outbound_payload_rejected');
28
31
  }
29
32
  let adapters;
@@ -31,7 +34,7 @@ export class OutboundDeliveryRuntime {
31
34
  adapters = requireAdapters(snapshot);
32
35
  }
33
36
  catch (error) {
34
- return receiptFromEndpointError(error);
37
+ return receiptFromEndpointError(error, false);
35
38
  }
36
39
  const envelope = createOutboundEnvelope({
37
40
  conversation: request.conversation,
@@ -48,8 +51,9 @@ export class OutboundDeliveryRuntime {
48
51
  try {
49
52
  payload = await prepareOutboundPayload(envelope.payload, request.conversation, snapshot, (map) => this.context.rememberFallback(request.conversation, snapshot.generation, map));
50
53
  }
51
- catch {
52
- receipt = rejectedDeliveryReceipt('outbound_payload_rejected');
54
+ catch (error) {
55
+ receipt = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent'
56
+ ? receiptFromEndpointError(error, false) : rejectedDeliveryReceipt('outbound_payload_rejected');
53
57
  return;
54
58
  }
55
59
  try {
@@ -120,6 +124,13 @@ async function prepareOutboundPayload(rendered, conversation, snapshot, remember
120
124
  }
121
125
  if (!directHtml && Array.isArray(payload))
122
126
  assertCanonicalSegments(payload);
127
+ const supported = resolveOutboundSupportedSegments(adapter, snapshot);
128
+ const supportedPayload = rememberInteractiveFallback ? payload : applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot));
129
+ if (supported && Array.isArray(supportedPayload)) {
130
+ const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object' && typeof segment.type === 'string' && !supported.includes(segment.type));
131
+ if (unsupported)
132
+ throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
133
+ }
123
134
  return payload;
124
135
  }
125
136
  function resolveHtmlRenderer(snapshot) {
@@ -134,19 +145,50 @@ function isDirectHtmlConsumer(snapshot, adapter) {
134
145
  return adapterTypeName(packageName) === 'sandbox';
135
146
  }
136
147
  function receiptFromEndpointResult(messageId, conversation) {
148
+ if (typeof messageId !== 'string' || messageId.trim() === '') {
149
+ return unknownDeliveryReceipt('delivery_unconfirmed');
150
+ }
137
151
  return Object.freeze({
138
152
  status: 'sent',
139
153
  message: Object.freeze({ conversation, id: messageId }),
140
154
  });
141
155
  }
142
- function receiptFromEndpointError(error) {
143
- const message = error instanceof Error ? error.message : String(error);
144
- if (/Unknown Adapter Endpoint|does not support outbound/u.test(message)) {
145
- return unsupportedDeliveryReceipt('outbound_unsupported');
156
+ function receiptFromEndpointError(error, attempted = true) {
157
+ if (error instanceof EndpointDeliveryError) {
158
+ if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found') {
159
+ return unsupportedDeliveryReceipt('outbound_unsupported');
160
+ }
161
+ if (error.code === 'unsupported_operation' && error.disposition === 'not_sent') {
162
+ return unsupportedDeliveryReceipt(error.code);
163
+ }
164
+ if (error.disposition === 'unknown')
165
+ return unknownDeliveryReceipt(error.code);
166
+ return failedDeliveryReceipt(error.code);
167
+ }
168
+ // imhelper ProtocolError exposes stable protocol facts without a Core SDK dependency.
169
+ if (error && typeof error === 'object' && 'protocol' in error && 'kind' in error && 'response' in error
170
+ && error.protocol === 'onebot-v11' && error.kind === 'protocol') {
171
+ const response = error.response;
172
+ if (response && typeof response === 'object' && 'status' in response && response.status === 'failed') {
173
+ return failedDeliveryReceipt('platform_rejected');
174
+ }
146
175
  }
147
- if (/not active/u.test(message))
148
- return failedDeliveryReceipt('endpoint_inactive', true);
149
- return failedDeliveryReceipt('endpoint_send_failed', true);
176
+ // Before the endpoint send boundary no message can have entered a transport.
177
+ if (!attempted)
178
+ return failedDeliveryReceipt('endpoint_send_failed');
179
+ // Unknown SDK/network failures provide no evidence that replay is safe.
180
+ return unknownDeliveryReceipt('endpoint_send_failed');
181
+ }
182
+ function unknownDeliveryReceipt(code) {
183
+ return Object.freeze({
184
+ status: 'failed',
185
+ failure: Object.freeze({
186
+ code,
187
+ message: 'Message delivery is unconfirmed; resending may duplicate delivery.',
188
+ retryable: false,
189
+ deliveryUnknown: true,
190
+ }),
191
+ });
150
192
  }
151
193
  function suppressedDeliveryReceipt() {
152
194
  return Object.freeze({ status: 'suppressed' });
@@ -29,7 +29,7 @@ export class OutboundRenderer {
29
29
  return content;
30
30
  }
31
31
  if (isComponentCall(content)) {
32
- const rendered = await requireComponents(snapshot).render(requester, content.name, content.props);
32
+ const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot });
33
33
  return this.#render(rendered, requester, snapshot, host, ctx, depth + 1);
34
34
  }
35
35
  throw new TypeError('Unsupported SendContent');
@@ -53,6 +53,8 @@ export declare function isOutboundSegment(value: unknown): value is OutboundSegm
53
53
  * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
54
54
  */
55
55
  export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
56
+ /** Read declared support from this operation's snapshot without requiring live admission. */
57
+ export declare function resolveOutboundSupportedSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): readonly string[] | undefined;
56
58
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
57
59
  export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
58
60
  export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
@@ -64,6 +64,14 @@ export function resolveOutboundInteractivePolicy(adapter, snapshot) {
64
64
  return (adapterType ? OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER[adapterType] : undefined)
65
65
  ?? DEFAULT_INTERACTIVE_POLICY;
66
66
  }
67
+ /** Read declared support from this operation's snapshot without requiring live admission. */
68
+ export function resolveOutboundSupportedSegments(adapter, snapshot) {
69
+ const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
70
+ if (!slot?.definition || typeof slot.definition !== 'object')
71
+ return undefined;
72
+ const segments = slot.definition.segments;
73
+ return Array.isArray(segments?.supported) && segments.supported.every(type => typeof type === 'string') ? segments.supported : undefined;
74
+ }
67
75
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
68
76
  export function resolveOutboundMarkdownPolicy(adapter, snapshot) {
69
77
  const slot = snapshot.capabilities.get(adapter)
@@ -3,7 +3,7 @@ import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
3
3
  export async function runRuntimeMiddleware(snapshot, input, terminal, target) {
4
4
  const index = middleware(snapshot);
5
5
  if (index)
6
- await index.run(input, terminal, target);
6
+ await index.run(input, terminal, target, snapshot);
7
7
  else
8
8
  await terminal();
9
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.1.39",
3
+ "version": "1.1.40",
4
4
  "description": "Zhin机器人核心框架",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -68,16 +68,16 @@
68
68
  "dependencies": {
69
69
  "qrcode": "^1.5.4",
70
70
  "segment-matcher": "^1.0.5",
71
- "@zhin.js/adapter": "1.1.15",
72
- "@zhin.js/command": "1.1.3",
73
- "@zhin.js/component": "1.1.2",
71
+ "@zhin.js/adapter": "1.1.16",
72
+ "@zhin.js/command": "1.1.4",
73
+ "@zhin.js/component": "1.1.3",
74
74
  "@zhin.js/database": "1.1.2",
75
75
  "@zhin.js/handler": "1.1.2",
76
- "@zhin.js/im-contract": "1.1.2",
76
+ "@zhin.js/im-contract": "1.1.3",
77
77
  "@zhin.js/interaction": "1.1.0",
78
- "@zhin.js/kernel": "1.1.1",
78
+ "@zhin.js/kernel": "1.1.2",
79
79
  "@zhin.js/logger": "1.1.1",
80
- "@zhin.js/middleware": "1.1.2",
80
+ "@zhin.js/middleware": "1.1.3",
81
81
  "@zhin.js/permission": "1.1.3",
82
82
  "@zhin.js/plugin-runtime": "1.1.11",
83
83
  "@zhin.js/schedule-feature": "1.1.2",
@@ -88,7 +88,7 @@
88
88
  "@types/qrcode": "^1.5.6",
89
89
  "ajv": "8.18.0",
90
90
  "typescript": "^6.0.3",
91
- "@zhin.js/ai": "1.1.35"
91
+ "@zhin.js/ai": "1.1.36"
92
92
  },
93
93
  "repository": {
94
94
  "type": "git",