@lingyao037/openclaw-lingyao-cli 0.3.0-alpha.1

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.
@@ -0,0 +1,1229 @@
1
+ import { a as LingyaoAccountConfig, L as LingyaoRuntime, A as AccountManager, S as SyncRequest, b as SyncResponse, c as LingyaoMessage, D as DeviceInfo, d as DeviceToken, e as LingyaoConfig, N as NotifyPayload, H as HealthStatus } from './accounts-Bkwmg14Q.js';
2
+ export { f as AckRequest, g as DiarySyncPayload, F as FailedEntry, h as LINGYAO_SERVER_URL, i as LingyaoAccount, M as MemorySyncPayload, j as MessageType, k as NotifyAction, l as NotifyRequest, P as PairingCode, m as PairingConfirmRequest, n as PairingConfirmResponse, o as PollRequest, p as PollResponse, Q as QueuedMessage, T as TokenRefreshRequest, q as TokenRefreshResponse, W as WebSocketConnection } from './accounts-Bkwmg14Q.js';
3
+
4
+ /**
5
+ * Config Adapter - Account resolution, config validation
6
+ *
7
+ * serverUrl is NOT exposed to users — hardcoded as LINGYAO_SERVER_URL.
8
+ */
9
+
10
+ /**
11
+ * Resolved account after config resolution.
12
+ */
13
+ interface ResolvedAccount {
14
+ readonly id: string;
15
+ readonly enabled: boolean;
16
+ readonly dmPolicy: 'paired' | 'open' | 'deny';
17
+ readonly allowFrom: readonly string[];
18
+ readonly rawConfig: LingyaoAccountConfig;
19
+ }
20
+
21
+ /**
22
+ * 灵爻服务器 HTTP 客户端
23
+ *
24
+ * 主动连接到灵爻服务器,实现 Gateway 注册、心跳、消息推送
25
+ * 符合 openapi.yaml 规范
26
+ */
27
+
28
+ /**
29
+ * 服务器 API 配置
30
+ */
31
+ interface ServerConfig {
32
+ baseURL: string;
33
+ apiBase: string;
34
+ timeout: number;
35
+ connectionTimeout: number;
36
+ }
37
+ /**
38
+ * Gateway 注册响应
39
+ */
40
+ interface GatewayRegisterResponse {
41
+ gatewayToken: string;
42
+ expiresAt: number;
43
+ webhookSecret: string;
44
+ serverConfig: {
45
+ heartbeatInterval: number;
46
+ maxOfflineMessages: number;
47
+ supportedMessageTypes: string[];
48
+ };
49
+ }
50
+ /**
51
+ * 心跳响应
52
+ */
53
+ interface HeartbeatResponse {
54
+ serverTime: number;
55
+ pendingMessages: number;
56
+ }
57
+ /**
58
+ * 发送消息请求
59
+ */
60
+ interface SendMessageRequest {
61
+ deviceId: string;
62
+ message: {
63
+ id: string;
64
+ type: 'notify_text' | 'notify_action';
65
+ timestamp: number;
66
+ payload: {
67
+ title?: string;
68
+ body?: string;
69
+ action?: {
70
+ type: 'open_memory' | 'view_diary' | 'custom';
71
+ params?: Record<string, unknown>;
72
+ };
73
+ };
74
+ };
75
+ options?: {
76
+ priority?: 'normal' | 'low' | 'high';
77
+ ttl?: number;
78
+ };
79
+ }
80
+ /**
81
+ * 发送消息响应
82
+ */
83
+ interface SendMessageResponse {
84
+ messageId: string;
85
+ status: 'queued' | 'delivered' | 'failed';
86
+ deliveredAt: number | null;
87
+ queued: boolean;
88
+ }
89
+ /**
90
+ * Gateway 状态
91
+ */
92
+ type GatewayStatus = 'online' | 'offline' | 'maintenance';
93
+ /**
94
+ * HTTP 客户端实现
95
+ */
96
+ declare class ServerHttpClient {
97
+ private runtime;
98
+ private config;
99
+ private axiosInstance;
100
+ private gatewayToken;
101
+ private webhookSecret;
102
+ private tokenExpiresAt;
103
+ private heartbeatInterval;
104
+ private heartbeatTimer;
105
+ private gatewayId;
106
+ private isRegistered;
107
+ private isConnecting;
108
+ private storagePrefix;
109
+ constructor(runtime: LingyaoRuntime, gatewayId: string, serverConfig?: Partial<ServerConfig>, storagePrefix?: string);
110
+ /**
111
+ * 注册 Gateway 到服务器
112
+ */
113
+ register(capabilities?: {
114
+ websocket?: boolean;
115
+ compression?: boolean;
116
+ maxMessageSize?: number;
117
+ }): Promise<GatewayRegisterResponse>;
118
+ /**
119
+ * 发送心跳
120
+ */
121
+ heartbeat(status?: GatewayStatus, activeConnections?: number): Promise<HeartbeatResponse>;
122
+ /**
123
+ * 发送消息到灵爻 App
124
+ */
125
+ sendMessage(deviceId: string, messageType: 'notify_text' | 'notify_action', payload: SendMessageRequest['message']['payload'], options?: SendMessageRequest['options']): Promise<SendMessageResponse>;
126
+ /**
127
+ * 启动心跳循环
128
+ */
129
+ private startHeartbeat;
130
+ /**
131
+ * 停止心跳循环
132
+ */
133
+ stopHeartbeat(): void;
134
+ /**
135
+ * 获取 Webhook Secret
136
+ */
137
+ getWebhookSecret(): string | null;
138
+ /**
139
+ * 获取 Gateway Token
140
+ */
141
+ getGatewayToken(): string | null;
142
+ /**
143
+ * 检查 Token 是否即将过期
144
+ */
145
+ isTokenExpiringSoon(thresholdMs?: number): boolean;
146
+ /**
147
+ * 检查是否已注册
148
+ */
149
+ isReady(): boolean;
150
+ /**
151
+ * 从存储恢复会话
152
+ */
153
+ restoreFromStorage(): Promise<boolean>;
154
+ /**
155
+ * Build a namespaced storage key for multi-account support
156
+ */
157
+ private storageKey;
158
+ /**
159
+ * 生成消息 ID
160
+ */
161
+ private generateMessageId;
162
+ }
163
+
164
+ /**
165
+ * Lingyao WebSocket Client
166
+ *
167
+ * 主动连接到 lingyao.live 服务器的 WebSocket 客户端
168
+ * 实现:
169
+ * - 自动连接和重连
170
+ * - 心跳机制
171
+ * - 消息发送和接收
172
+ * - 在线状态管理
173
+ */
174
+
175
+ /**
176
+ * WebSocket 连接状态
177
+ */
178
+ type ConnectionState = "connecting" | "connected" | "disconnected" | "error";
179
+ /**
180
+ * WebSocket 消息类型
181
+ */
182
+ declare enum WSMessageType {
183
+ REGISTER = "register",
184
+ HEARTBEAT = "heartbeat",
185
+ SEND_MESSAGE = "send_message",
186
+ ACK = "ack",
187
+ REGISTERED = "registered",
188
+ HEARTBEAT_ACK = "heartbeat_ack",
189
+ MESSAGE_DELIVERED = "message_delivered",
190
+ MESSAGE_FAILED = "message_failed",
191
+ APP_MESSAGE = "app_message",// 来自 App 的消息
192
+ DEVICE_ONLINE = "device_online",
193
+ ERROR = "error"
194
+ }
195
+ /**
196
+ * WebSocket 消息基础格式
197
+ */
198
+ interface WSMessage {
199
+ type: WSMessageType | string;
200
+ id: string;
201
+ timestamp: number;
202
+ payload?: any;
203
+ }
204
+ /**
205
+ * 接收到的 App 消息
206
+ */
207
+ interface AppMessage extends WSMessage {
208
+ type: WSMessageType.APP_MESSAGE;
209
+ payload: {
210
+ deviceId: string;
211
+ message: {
212
+ id: string;
213
+ type: "sync_diary" | "sync_memory" | "heartbeat";
214
+ timestamp: number;
215
+ content: string;
216
+ metadata?: Record<string, unknown>;
217
+ };
218
+ };
219
+ }
220
+ /**
221
+ * WebSocket 客户端事件
222
+ */
223
+ type WSClientEvent = {
224
+ type: "connected";
225
+ connectionId: string;
226
+ } | {
227
+ type: "disconnected";
228
+ code: number;
229
+ reason: string;
230
+ } | {
231
+ type: "error";
232
+ error: Error;
233
+ } | {
234
+ type: "message";
235
+ message: WSMessage;
236
+ } | {
237
+ type: "appMessage";
238
+ deviceId: string;
239
+ message: AppMessage["payload"]["message"];
240
+ };
241
+ /**
242
+ * WebSocket 客户端配置
243
+ */
244
+ interface WSClientConfig {
245
+ url: string;
246
+ gatewayId: string;
247
+ token?: string;
248
+ reconnectInterval: number;
249
+ heartbeatInterval: number;
250
+ messageHandler?: (message: AppMessage) => void | Promise<void>;
251
+ eventHandler?: (event: WSClientEvent) => void;
252
+ }
253
+ /**
254
+ * Lingyao WebSocket Client
255
+ *
256
+ * 主动连接到 lingyao.live 服务器的 WebSocket 客户端
257
+ */
258
+ declare class LingyaoWSClient {
259
+ private config;
260
+ private ws;
261
+ private state;
262
+ private connectionId;
263
+ private heartbeatTimer;
264
+ private reconnectTimer;
265
+ private messageHandlers;
266
+ private logger;
267
+ constructor(runtime: LingyaoRuntime, config: WSClientConfig);
268
+ /**
269
+ * 连接到服务器
270
+ */
271
+ connect(): Promise<void>;
272
+ /**
273
+ * 设置 WebSocket 事件处理器
274
+ */
275
+ private setupWebSocketHandlers;
276
+ /**
277
+ * 处理连接打开
278
+ */
279
+ private handleOpen;
280
+ /**
281
+ * 处理接收消息
282
+ */
283
+ private handleMessage;
284
+ /**
285
+ * 处理连接错误
286
+ */
287
+ private handleErrorEvent;
288
+ /**
289
+ * 处理连接关闭
290
+ */
291
+ private handleClose;
292
+ /**
293
+ * 发送注册消息
294
+ */
295
+ private sendRegister;
296
+ /**
297
+ * 处理注册响应
298
+ */
299
+ private handleRegistered;
300
+ /**
301
+ * 发送心跳
302
+ */
303
+ private sendHeartbeat;
304
+ /**
305
+ * 处理心跳确认
306
+ */
307
+ private handleHeartbeatAck;
308
+ /**
309
+ * 启动心跳
310
+ */
311
+ private startHeartbeat;
312
+ /**
313
+ * 停止心跳
314
+ */
315
+ private stopHeartbeat;
316
+ /**
317
+ * 安排重连
318
+ */
319
+ private scheduleReconnect;
320
+ /**
321
+ * 发送消息到服务器
322
+ */
323
+ send(message: WSMessage): void;
324
+ /**
325
+ * 发送通知到鸿蒙 App
326
+ */
327
+ sendNotification(deviceId: string, notification: any): void;
328
+ /**
329
+ * 处理 App 消息
330
+ */
331
+ private handleAppMessage;
332
+ /**
333
+ * 处理消息发送成功
334
+ */
335
+ private handleMessageDelivered;
336
+ /**
337
+ * 处理消息发送失败
338
+ */
339
+ private handleMessageFailed;
340
+ /**
341
+ * 处理服务器错误
342
+ */
343
+ private handleError;
344
+ /**
345
+ * 注册消息处理器
346
+ */
347
+ registerMessageHandler(type: string, handler: (message: WSMessage) => void): void;
348
+ /**
349
+ * 发送事件
350
+ */
351
+ private emitEvent;
352
+ /**
353
+ * 断开连接
354
+ */
355
+ disconnect(): void;
356
+ /**
357
+ * 获取连接状态
358
+ */
359
+ getState(): ConnectionState;
360
+ /**
361
+ * 获取连接 ID
362
+ */
363
+ getConnectionId(): string | null;
364
+ /**
365
+ * 是否已连接
366
+ */
367
+ isConnected(): boolean;
368
+ /**
369
+ * 生成消息 ID
370
+ */
371
+ private generateMessageId;
372
+ /**
373
+ * 生成连接 ID
374
+ */
375
+ private generateConnectionId;
376
+ }
377
+
378
+ /**
379
+ * Agent message format - messages passed directly to Agent
380
+ */
381
+ interface AgentMessage {
382
+ id: string;
383
+ type: "diary" | "memory" | "heartbeat";
384
+ from: string;
385
+ deviceId: string;
386
+ content: string;
387
+ metadata: Record<string, unknown>;
388
+ timestamp: number;
389
+ }
390
+ /**
391
+ * Message handler callback for delivering messages to Agent
392
+ */
393
+ type MessageHandler = (message: AgentMessage) => void | Promise<void>;
394
+ /**
395
+ * Message Processor - Handles incoming messages and routes them to Agent
396
+ */
397
+ declare class MessageProcessor {
398
+ private runtime;
399
+ private accountManager;
400
+ private messageQueue;
401
+ private seenMessages;
402
+ private messageHandler;
403
+ private readonly maxQueueSize;
404
+ constructor(runtime: LingyaoRuntime, accountManager: AccountManager);
405
+ /**
406
+ * Initialize the message processor
407
+ */
408
+ initialize(): Promise<void>;
409
+ /**
410
+ * Set the message handler for delivering messages to Agent
411
+ */
412
+ setMessageHandler(handler: MessageHandler): void;
413
+ /**
414
+ * Get the currently registered Agent message handler.
415
+ */
416
+ getMessageHandler(): MessageHandler | null;
417
+ /**
418
+ * Deliver a normalized message directly to the registered Agent handler.
419
+ */
420
+ deliverToAgent(message: AgentMessage): Promise<void>;
421
+ /**
422
+ * Process sync request from app
423
+ */
424
+ processSync(deviceId: string, request: SyncRequest): Promise<SyncResponse>;
425
+ /**
426
+ * Process a single message
427
+ */
428
+ private processMessage;
429
+ /**
430
+ * Process diary sync - Pass directly to Agent
431
+ */
432
+ private processDiarySync;
433
+ /**
434
+ * Process memory sync - Pass directly to Agent
435
+ */
436
+ private processMemorySync;
437
+ /**
438
+ * Process sync acknowledgment
439
+ */
440
+ private processSyncAck;
441
+ /**
442
+ * Process heartbeat
443
+ */
444
+ private processHeartbeat;
445
+ /**
446
+ * Poll for new messages (long-polling)
447
+ */
448
+ pollMessages(deviceId: string, timeout?: number): Promise<LingyaoMessage[]>;
449
+ /**
450
+ * Queue a message for a device
451
+ */
452
+ queueMessage(deviceId: string, message: LingyaoMessage): boolean;
453
+ /**
454
+ * Acknowledge messages
455
+ */
456
+ acknowledgeMessages(messageIds: string[]): Promise<void>;
457
+ /**
458
+ * Check if message has been seen (deduplication)
459
+ */
460
+ private isMessageSeen;
461
+ /**
462
+ * Mark message as seen
463
+ */
464
+ private markMessageSeen;
465
+ /**
466
+ * Get queue size for a device
467
+ */
468
+ getQueueSize(deviceId: string): number;
469
+ /**
470
+ * Get total queue size
471
+ */
472
+ getTotalQueueSize(): number;
473
+ }
474
+
475
+ /**
476
+ * 监控和指标收集模块
477
+ */
478
+
479
+ /**
480
+ * 指标类型
481
+ */
482
+ declare enum MetricType {
483
+ COUNTER = "counter",
484
+ GAUGE = "gauge",
485
+ HISTOGRAM = "histogram"
486
+ }
487
+ /**
488
+ * 指标数据
489
+ */
490
+ interface MetricData {
491
+ name: string;
492
+ type: MetricType;
493
+ value: number;
494
+ timestamp: number;
495
+ labels?: Record<string, string>;
496
+ }
497
+ /**
498
+ * 指标配置
499
+ */
500
+ interface MetricConfig {
501
+ name: string;
502
+ type: MetricType;
503
+ description?: string;
504
+ labels?: string[];
505
+ buckets?: number[];
506
+ }
507
+ /**
508
+ * 监控指标管理器
509
+ */
510
+ declare class MetricsManager {
511
+ private metrics;
512
+ private counters;
513
+ private gauges;
514
+ private histograms;
515
+ private histogramBuckets;
516
+ constructor(_runtime: LingyaoRuntime);
517
+ /**
518
+ * 初始化默认指标
519
+ */
520
+ private initializeDefaultMetrics;
521
+ /**
522
+ * 声明指标
523
+ */
524
+ declareMetric(config: MetricConfig): void;
525
+ /**
526
+ * 计数器增加
527
+ */
528
+ incrementCounter(name: string, value?: number, labels?: Record<string, string>): void;
529
+ /**
530
+ * 设置仪表盘值
531
+ */
532
+ setGauge(name: string, value: number, labels?: Record<string, string>): void;
533
+ /**
534
+ * 记录直方图值
535
+ */
536
+ recordHistogram(name: string, value: number, labels?: Record<string, string>): void;
537
+ /**
538
+ * 记录指标
539
+ */
540
+ private recordMetric;
541
+ /**
542
+ * 获取所有指标
543
+ */
544
+ getMetrics(): MetricData[];
545
+ /**
546
+ * 获取特定指标的当前值
547
+ */
548
+ getMetricValue(name: string): number | undefined;
549
+ /**
550
+ * 获取直方图统计数据
551
+ */
552
+ getHistogramStats(name: string): {
553
+ count: number;
554
+ min: number;
555
+ max: number;
556
+ avg: number;
557
+ p50: number;
558
+ p95: number;
559
+ p99: number;
560
+ } | null;
561
+ /**
562
+ * 重置所有指标
563
+ */
564
+ reset(): void;
565
+ /**
566
+ * 生成 Prometheus 格式的指标导出
567
+ */
568
+ exportPrometheus(): string;
569
+ }
570
+ /**
571
+ * 监控事件
572
+ */
573
+ declare enum MonitoringEvent {
574
+ CONNECTION_OPEN = "connection_open",
575
+ CONNECTION_CLOSE = "connection_close",
576
+ CONNECTION_ERROR = "connection_error",
577
+ RECONNECT = "reconnect",
578
+ MESSAGE_RECEIVED = "message_received",
579
+ MESSAGE_SENT = "message_sent",
580
+ MESSAGE_DELIVERED = "message_delivered",
581
+ MESSAGE_FAILED = "message_failed",
582
+ HEARTBEAT_SENT = "heartbeat_sent",
583
+ HEARTBEAT_RECEIVED = "heartbeat_received",
584
+ HEARTBEAT_MISSED = "heartbeat_missed",
585
+ ERROR_OCCURRED = "error_occurred"
586
+ }
587
+ /**
588
+ * 监控事件数据
589
+ */
590
+ interface MonitoringEventData {
591
+ event: MonitoringEvent;
592
+ timestamp: number;
593
+ data: Record<string, unknown>;
594
+ }
595
+ /**
596
+ * 监控器
597
+ */
598
+ declare class Monitor {
599
+ private runtime;
600
+ private metrics;
601
+ private eventHandlers;
602
+ constructor(runtime: LingyaoRuntime);
603
+ /**
604
+ * 记录事件
605
+ */
606
+ recordEvent(event: MonitoringEvent, data?: Record<string, unknown>): void;
607
+ /**
608
+ * 为事件更新指标
609
+ */
610
+ private updateMetricsForEvent;
611
+ /**
612
+ * 注册事件处理器
613
+ */
614
+ on(event: MonitoringEvent, handler: (data: MonitoringEventData) => void): void;
615
+ /**
616
+ * 移除事件处理器
617
+ */
618
+ off(event: MonitoringEvent, handler: (data: MonitoringEventData) => void): void;
619
+ /**
620
+ * 获取指标管理器
621
+ */
622
+ getMetrics(): MetricsManager;
623
+ /**
624
+ * 获取摘要报告
625
+ */
626
+ getSummary(): {
627
+ uptime: number;
628
+ connections: number;
629
+ messages: {
630
+ sent: number;
631
+ received: number;
632
+ failed: number;
633
+ };
634
+ errors: number;
635
+ heartbeats: {
636
+ sent: number;
637
+ missed: number;
638
+ };
639
+ };
640
+ }
641
+
642
+ /**
643
+ * 错误处理模块
644
+ */
645
+
646
+ /**
647
+ * 错误严重级别
648
+ */
649
+ declare enum ErrorSeverity {
650
+ LOW = "low",
651
+ MEDIUM = "medium",
652
+ HIGH = "high",
653
+ CRITICAL = "critical"
654
+ }
655
+ /**
656
+ * Lingyao 错误基类
657
+ */
658
+ declare class LingyaoError extends Error {
659
+ readonly code: string;
660
+ readonly severity: ErrorSeverity;
661
+ readonly timestamp: number;
662
+ readonly context?: Record<string, unknown>;
663
+ readonly cause?: Error;
664
+ constructor(message: string, code: string, severity?: ErrorSeverity, context?: Record<string, unknown>, cause?: Error);
665
+ /**
666
+ * 转换为 JSON 可序列化格式
667
+ */
668
+ toJSON(): Record<string, unknown>;
669
+ }
670
+ /**
671
+ * 错误处理器
672
+ */
673
+ declare class ErrorHandler {
674
+ private runtime;
675
+ private errorCounts;
676
+ private lastErrors;
677
+ private errorThresholds;
678
+ constructor(runtime: LingyaoRuntime);
679
+ /**
680
+ * 处理错误
681
+ */
682
+ handleError(error: Error | LingyaoError): void;
683
+ /**
684
+ * 记录错误
685
+ */
686
+ private recordError;
687
+ /**
688
+ * 检查错误阈值
689
+ */
690
+ private checkThresholds;
691
+ /**
692
+ * 触发警报
693
+ */
694
+ private triggerAlert;
695
+ /**
696
+ * 设置错误阈值
697
+ */
698
+ setErrorThreshold(code: string, threshold: {
699
+ count: number;
700
+ window: number;
701
+ }): void;
702
+ /**
703
+ * 获取错误统计
704
+ */
705
+ getErrorStats(): {
706
+ byCode: Record<string, number>;
707
+ total: number;
708
+ recent: Array<{
709
+ code: string;
710
+ error: LingyaoError;
711
+ timestamp: number;
712
+ }>;
713
+ };
714
+ /**
715
+ * 重置错误计数
716
+ */
717
+ resetErrorCounts(code?: string): void;
718
+ /**
719
+ * 包装异步函数以自动处理错误
720
+ */
721
+ wrapAsync<T>(fn: () => Promise<T>, context?: {
722
+ operation?: string;
723
+ fallback?: T;
724
+ retryable?: boolean;
725
+ }): Promise<T>;
726
+ /**
727
+ * 创建带有错误处理的重试逻辑
728
+ */
729
+ retry<T>(fn: () => Promise<T>, options?: {
730
+ maxRetries?: number;
731
+ retryDelay?: number;
732
+ backoff?: boolean;
733
+ onRetry?: (error: Error, attempt: number) => void;
734
+ }): Promise<T>;
735
+ /**
736
+ * 判断错误是否可重试
737
+ */
738
+ isRetryable(error: Error): boolean;
739
+ /**
740
+ * 判断错误是否需要降级处理
741
+ */
742
+ shouldDegrade(error: Error): boolean;
743
+ /**
744
+ * 创建降级响应
745
+ */
746
+ createDegradedResponse<T>(fallback: T, error?: Error): {
747
+ success: false;
748
+ degraded: true;
749
+ fallback: T;
750
+ error?: Error;
751
+ };
752
+ }
753
+
754
+ /**
755
+ * Directory Adapter - List paired devices (peers)
756
+ *
757
+ * Implements ChannelDirectoryAdapter:
758
+ * - listPeers: return all active paired devices for an account
759
+ *
760
+ * SDK passes:
761
+ * listPeers({ cfg, accountId?, query?, limit?, runtime })
762
+ *
763
+ * Returns ChannelDirectoryEntry[] with { kind, id, name?, ... }
764
+ *
765
+ * Uses AccountManager to get the device list.
766
+ * Each device is returned as a "user" peer (no groups in Lingyao).
767
+ */
768
+
769
+ /**
770
+ * Matches SDK's ChannelDirectoryEntry.
771
+ */
772
+ interface DirectoryEntry {
773
+ kind: 'user' | 'group' | 'channel';
774
+ id: string;
775
+ name?: string;
776
+ handle?: string;
777
+ avatarUrl?: string;
778
+ rank?: number;
779
+ raw?: unknown;
780
+ }
781
+
782
+ /**
783
+ * Status Adapter - Health checks and channel summary
784
+ *
785
+ * Implements ChannelStatusAdapter:
786
+ * - probeAccount: run health checks for a specific account
787
+ * - buildChannelSummary: aggregate status for a single account
788
+ *
789
+ * SDK passes:
790
+ * probeAccount({ account, timeoutMs, cfg })
791
+ * buildChannelSummary({ account, cfg, defaultAccountId, snapshot })
792
+ *
793
+ * Wraps existing Probe and Monitor classes.
794
+ */
795
+
796
+ /**
797
+ * Probe result structure.
798
+ */
799
+ interface LingyaoProbeResult {
800
+ ok: boolean;
801
+ status: 'healthy' | 'degraded' | 'unhealthy';
802
+ wsConnected: boolean;
803
+ uptime?: number;
804
+ checks?: Record<string, {
805
+ passed: boolean;
806
+ message: string;
807
+ duration?: number;
808
+ }>;
809
+ error?: string;
810
+ }
811
+
812
+ /**
813
+ * Outbound Adapter - Send messages from Agent to App devices
814
+ *
815
+ * Implements ChannelOutboundAdapter:
816
+ * - deliveryMode: "direct" (synchronous via WS)
817
+ * - sendText: send plain text notification
818
+ * - sendPayload: send structured payload notification
819
+ * - resolveTarget: validate and resolve target deviceId
820
+ *
821
+ * SDK passes ChannelOutboundContext = { cfg, to, text, accountId?, ... }
822
+ * and expects OutboundDeliveryResult = { channel, messageId, ... } return.
823
+ *
824
+ * Routes through MultiAccountOrchestrator to the correct
825
+ * account's WS connection.
826
+ */
827
+
828
+ /**
829
+ * Minimal subset of ChannelOutboundContext that we need.
830
+ */
831
+ interface OutboundContext {
832
+ cfg?: unknown;
833
+ to: string;
834
+ text: string;
835
+ mediaUrl?: string;
836
+ accountId?: string | null;
837
+ silent?: boolean;
838
+ }
839
+ /**
840
+ * Minimal ChannelOutboundPayloadContext.
841
+ */
842
+ interface OutboundPayloadContext extends OutboundContext {
843
+ payload: unknown;
844
+ }
845
+ /**
846
+ * OutboundDeliveryResult - what SDK expects back.
847
+ */
848
+ interface DeliveryResult {
849
+ channel: string;
850
+ messageId: string;
851
+ chatId?: string;
852
+ timestamp?: number;
853
+ meta?: Record<string, unknown>;
854
+ }
855
+
856
+ /**
857
+ * Gateway Adapter - Account lifecycle management
858
+ *
859
+ * Implements ChannelGatewayAdapter:
860
+ * - startAccount: create WS/HTTP connections for an account
861
+ * - stopAccount: tear down connections for an account
862
+ *
863
+ * Delegates to MultiAccountOrchestrator for all operations.
864
+ *
865
+ * SDK passes ChannelGatewayContext which includes:
866
+ * cfg, accountId, account, runtime, abortSignal, log,
867
+ * getStatus, setStatus, channelRuntime?
868
+ */
869
+
870
+ /**
871
+ * Minimal subset of ChannelGatewayContext that we need.
872
+ * We define this locally to avoid importing internal SDK types.
873
+ */
874
+ interface GatewayContext {
875
+ accountId: string;
876
+ account: ResolvedAccount;
877
+ cfg?: unknown;
878
+ runtime?: unknown;
879
+ abortSignal?: AbortSignal;
880
+ log?: {
881
+ info: (msg: string) => void;
882
+ warn: (msg: string) => void;
883
+ error: (msg: string) => void;
884
+ debug?: (msg: string) => void;
885
+ };
886
+ getStatus?: () => unknown;
887
+ setStatus?: (next: unknown) => void;
888
+ }
889
+
890
+ /**
891
+ * Token management utilities
892
+ */
893
+ declare class TokenManager {
894
+ constructor(_runtime: LingyaoRuntime);
895
+ /**
896
+ * Generate a new device token
897
+ */
898
+ generateDeviceToken(pairingId: string, deviceInfo: DeviceInfo, expiryDays?: number): DeviceToken;
899
+ /**
900
+ * Validate a device token
901
+ */
902
+ validateToken(token: string, storedSecret: string): boolean;
903
+ /**
904
+ * Check if token is expired
905
+ */
906
+ isTokenExpired(token: DeviceToken): boolean;
907
+ /**
908
+ * Refresh an existing token
909
+ */
910
+ refreshToken(oldToken: DeviceToken, expiryDays?: number): DeviceToken;
911
+ /**
912
+ * Extract device ID from token string
913
+ */
914
+ extractDeviceId(token: string): string | null;
915
+ /**
916
+ * Generate a unique device ID
917
+ */
918
+ private generateDeviceId;
919
+ /**
920
+ * Generate a random secret key
921
+ */
922
+ private generateSecret;
923
+ /**
924
+ * Generate a JWT-like token string
925
+ */
926
+ private generateTokenString;
927
+ /**
928
+ * Sign data with secret
929
+ */
930
+ private sign;
931
+ /**
932
+ * Base64URL encode without padding
933
+ */
934
+ private base64UrlEncode;
935
+ }
936
+
937
+ /**
938
+ * 灵爻频道插件 - 服务器中转模式
939
+ */
940
+ declare class LingyaoChannel {
941
+ private runtime;
942
+ private config;
943
+ private accountManager;
944
+ private tokenManager;
945
+ private serverClient;
946
+ private wsClient;
947
+ private processor;
948
+ private probe;
949
+ private monitor;
950
+ private errorHandler;
951
+ private startTime;
952
+ private gatewayId;
953
+ private isRunning;
954
+ private messageHandler;
955
+ constructor(runtime: LingyaoRuntime, config: LingyaoConfig);
956
+ /**
957
+ * 初始化频道
958
+ */
959
+ initialize(): Promise<void>;
960
+ /**
961
+ * 启动频道
962
+ */
963
+ start(): Promise<void>;
964
+ /**
965
+ * 向 lingyao 服务器注册 Gateway
966
+ */
967
+ private registerToServer;
968
+ /**
969
+ * 处理来自鸿蒙 App 的消息
970
+ */
971
+ private handleAppMessage;
972
+ /**
973
+ * 处理同步消息(日记、记忆等)
974
+ */
975
+ private handleSyncMessage;
976
+ /**
977
+ * 映射消息类型
978
+ */
979
+ private mapMessageType;
980
+ /**
981
+ * 处理 WebSocket 客户端事件
982
+ */
983
+ private handleClientEvent;
984
+ /**
985
+ * 停止频道
986
+ */
987
+ stop(): Promise<void>;
988
+ /**
989
+ * 发送通知到设备
990
+ */
991
+ sendNotification(deviceId: string, notification: NotifyPayload): Promise<{
992
+ success: boolean;
993
+ error?: string;
994
+ queued?: boolean;
995
+ }>;
996
+ /**
997
+ * 发送文本到设备
998
+ */
999
+ sendText(deviceId: string, text: string): Promise<{
1000
+ success: boolean;
1001
+ error?: string;
1002
+ queued?: boolean;
1003
+ }>;
1004
+ /**
1005
+ * 获取健康状态
1006
+ */
1007
+ getHealthStatus(): Promise<HealthStatus>;
1008
+ /**
1009
+ * 获取配置
1010
+ */
1011
+ getConfig(): LingyaoConfig;
1012
+ /**
1013
+ * 更新配置
1014
+ */
1015
+ updateConfig(updates: Partial<LingyaoConfig>): Promise<void>;
1016
+ /**
1017
+ * 获取账号管理器
1018
+ */
1019
+ getAccountManager(): AccountManager;
1020
+ /**
1021
+ * 获取 Token 管理器
1022
+ */
1023
+ getTokenManager(): TokenManager;
1024
+ /**
1025
+ * 获取服务器客户端
1026
+ */
1027
+ getServerClient(): ServerHttpClient | null;
1028
+ /**
1029
+ /**
1030
+ * 获取 WebSocket 客户端
1031
+ */
1032
+ getWSClient(): LingyaoWSClient | null;
1033
+ /**
1034
+ * 获取消息处理器
1035
+ */
1036
+ getMessageProcessor(): MessageProcessor | null;
1037
+ /**
1038
+ * 设置消息处理器
1039
+ */
1040
+ setMessageHandler(handler: (message: AgentMessage) => void | Promise<void>): void;
1041
+ /**
1042
+ * 获取监控器
1043
+ */
1044
+ getMonitor(): Monitor;
1045
+ /**
1046
+ * 获取错误处理器
1047
+ */
1048
+ getErrorHandler(): ErrorHandler;
1049
+ /**
1050
+ * 获取监控摘要
1051
+ */
1052
+ getMonitoringSummary(): {
1053
+ uptime: number;
1054
+ connections: number;
1055
+ messages: {
1056
+ sent: number;
1057
+ received: number;
1058
+ failed: number;
1059
+ };
1060
+ errors: number;
1061
+ heartbeats: {
1062
+ sent: number;
1063
+ missed: number;
1064
+ };
1065
+ };
1066
+ /**
1067
+ * 获取错误统计
1068
+ */
1069
+ getErrorStats(): {
1070
+ byCode: Record<string, number>;
1071
+ total: number;
1072
+ recent: Array<{
1073
+ code: string;
1074
+ error: LingyaoError;
1075
+ timestamp: number;
1076
+ }>;
1077
+ };
1078
+ /**
1079
+ * 生成 Gateway ID
1080
+ */
1081
+ private generateGatewayId;
1082
+ /**
1083
+ * 获取运行时主机名
1084
+ */
1085
+ private getRuntimeHostname;
1086
+ }
1087
+
1088
+ /**
1089
+ * Validate configuration object
1090
+ */
1091
+ declare function validateConfig(config: unknown): LingyaoConfig;
1092
+ /**
1093
+ * Get default configuration
1094
+ */
1095
+ declare function getDefaultConfig(): LingyaoConfig;
1096
+
1097
+ /**
1098
+ * Create a LingyaoChannel instance (legacy API).
1099
+ * Use this for standalone usage without the OpenClaw SDK.
1100
+ */
1101
+ declare function createPlugin(runtime: LingyaoRuntime, config?: Partial<LingyaoConfig>): Promise<LingyaoChannel>;
1102
+ /**
1103
+ * Plugin metadata (legacy API).
1104
+ */
1105
+ declare const pluginMetadata: {
1106
+ name: string;
1107
+ version: string;
1108
+ description: string;
1109
+ type: string;
1110
+ capabilities: {
1111
+ chatTypes: string[];
1112
+ media: boolean;
1113
+ reactions: boolean;
1114
+ threads: boolean;
1115
+ };
1116
+ defaultConfig: LingyaoConfig;
1117
+ };
1118
+ declare const pluginEntry: {
1119
+ id: string;
1120
+ name: string;
1121
+ description: string;
1122
+ setRuntime(runtime: unknown): void;
1123
+ readonly plugin: {
1124
+ id: "lingyao";
1125
+ meta: {
1126
+ id: string;
1127
+ label: string;
1128
+ selectionLabel: string;
1129
+ docsPath: string;
1130
+ docsLabel: string;
1131
+ blurb: string;
1132
+ order: number;
1133
+ aliases: string[];
1134
+ };
1135
+ capabilities: {
1136
+ chatTypes: readonly ["direct"];
1137
+ media: boolean;
1138
+ reactions: boolean;
1139
+ threads: boolean;
1140
+ polls: boolean;
1141
+ edit: boolean;
1142
+ unsend: boolean;
1143
+ reply: boolean;
1144
+ effects: boolean;
1145
+ groupManagement: boolean;
1146
+ nativeCommands: boolean;
1147
+ blockStreaming: boolean;
1148
+ };
1149
+ config: {
1150
+ listAccountIds(cfg: unknown): string[];
1151
+ resolveAccount(cfg: unknown, accountId?: string | null): ResolvedAccount;
1152
+ isConfigured(_account: ResolvedAccount): boolean;
1153
+ isEnabled(account: ResolvedAccount): boolean;
1154
+ };
1155
+ gateway: {
1156
+ startAccount(ctx: GatewayContext): Promise<void>;
1157
+ stopAccount(ctx: GatewayContext): Promise<void>;
1158
+ };
1159
+ outbound: {
1160
+ deliveryMode: "direct";
1161
+ sendText(ctx: OutboundContext): Promise<DeliveryResult>;
1162
+ sendPayload(ctx: OutboundPayloadContext): Promise<DeliveryResult>;
1163
+ resolveTarget(params: {
1164
+ cfg?: unknown;
1165
+ to?: string;
1166
+ accountId?: string | null;
1167
+ }): {
1168
+ ok: true;
1169
+ to: string;
1170
+ } | {
1171
+ ok: false;
1172
+ error: Error;
1173
+ };
1174
+ };
1175
+ status: {
1176
+ probeAccount(params: {
1177
+ account: ResolvedAccount;
1178
+ timeoutMs: number;
1179
+ cfg: unknown;
1180
+ }): Promise<LingyaoProbeResult>;
1181
+ buildChannelSummary(params: {
1182
+ account: ResolvedAccount;
1183
+ cfg: unknown;
1184
+ defaultAccountId: string;
1185
+ snapshot: Record<string, unknown>;
1186
+ }): Promise<Record<string, unknown>>;
1187
+ };
1188
+ directory: {
1189
+ listPeers(params: {
1190
+ cfg: unknown;
1191
+ accountId?: string | null;
1192
+ query?: string | null;
1193
+ limit?: number | null;
1194
+ runtime?: unknown;
1195
+ }): Promise<DirectoryEntry[]>;
1196
+ };
1197
+ messaging: {
1198
+ normalizeTarget(raw: string): string | undefined;
1199
+ resolveSessionTarget(params: {
1200
+ kind: "group" | "channel";
1201
+ id: string;
1202
+ threadId?: string | null;
1203
+ }): string | undefined;
1204
+ inferTargetChatType(_params: {
1205
+ to: string;
1206
+ }): "direct" | undefined;
1207
+ };
1208
+ };
1209
+ security: {
1210
+ dm: {
1211
+ channelKey: string;
1212
+ resolvePolicy: (account: ResolvedAccount) => "paired" | "open" | "deny";
1213
+ resolveAllowFrom: (account: ResolvedAccount) => readonly string[];
1214
+ defaultPolicy: "paired";
1215
+ };
1216
+ };
1217
+ pairing: {
1218
+ text: {
1219
+ idLabel: string;
1220
+ message: string;
1221
+ notify: (params: {
1222
+ cfg: unknown;
1223
+ id: string;
1224
+ }) => Promise<void>;
1225
+ };
1226
+ };
1227
+ };
1228
+
1229
+ export { type AgentMessage, DeviceInfo, DeviceToken, HealthStatus, LingyaoAccountConfig, LingyaoChannel, LingyaoConfig, LingyaoMessage, LingyaoRuntime, NotifyPayload, SyncRequest, SyncResponse, createPlugin, pluginEntry as default, getDefaultConfig, pluginMetadata, validateConfig };