@anycon/sdk 0.1.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 (104) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +240 -0
  3. package/README.zh-CN.md +188 -0
  4. package/dist/async-queue.d.ts +20 -0
  5. package/dist/async-queue.d.ts.map +1 -0
  6. package/dist/async-queue.js +95 -0
  7. package/dist/async-queue.js.map +1 -0
  8. package/dist/attachments.d.ts +53 -0
  9. package/dist/attachments.d.ts.map +1 -0
  10. package/dist/attachments.js +228 -0
  11. package/dist/attachments.js.map +1 -0
  12. package/dist/client.d.ts +90 -0
  13. package/dist/client.d.ts.map +1 -0
  14. package/dist/client.js +280 -0
  15. package/dist/client.js.map +1 -0
  16. package/dist/connect.d.ts +16 -0
  17. package/dist/connect.d.ts.map +1 -0
  18. package/dist/connect.js +24 -0
  19. package/dist/connect.js.map +1 -0
  20. package/dist/default-storage.d.ts +4 -0
  21. package/dist/default-storage.d.ts.map +1 -0
  22. package/dist/default-storage.js +15 -0
  23. package/dist/default-storage.js.map +1 -0
  24. package/dist/emitter.d.ts +10 -0
  25. package/dist/emitter.d.ts.map +1 -0
  26. package/dist/emitter.js +38 -0
  27. package/dist/emitter.js.map +1 -0
  28. package/dist/errors.d.ts +112 -0
  29. package/dist/errors.d.ts.map +1 -0
  30. package/dist/errors.js +155 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/hub.d.ts +85 -0
  33. package/dist/hub.d.ts.map +1 -0
  34. package/dist/hub.js +362 -0
  35. package/dist/hub.js.map +1 -0
  36. package/dist/index.d.ts +34 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +32 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/link.d.ts +87 -0
  41. package/dist/link.d.ts.map +1 -0
  42. package/dist/link.js +628 -0
  43. package/dist/link.js.map +1 -0
  44. package/dist/node.d.ts +213 -0
  45. package/dist/node.d.ts.map +1 -0
  46. package/dist/node.js +474 -0
  47. package/dist/node.js.map +1 -0
  48. package/dist/pair.d.ts +75 -0
  49. package/dist/pair.d.ts.map +1 -0
  50. package/dist/pair.js +390 -0
  51. package/dist/pair.js.map +1 -0
  52. package/dist/permissions.d.ts +65 -0
  53. package/dist/permissions.d.ts.map +1 -0
  54. package/dist/permissions.js +74 -0
  55. package/dist/permissions.js.map +1 -0
  56. package/dist/runtime.d.ts +5 -0
  57. package/dist/runtime.d.ts.map +1 -0
  58. package/dist/runtime.js +15 -0
  59. package/dist/runtime.js.map +1 -0
  60. package/dist/session.d.ts +208 -0
  61. package/dist/session.d.ts.map +1 -0
  62. package/dist/session.js +504 -0
  63. package/dist/session.js.map +1 -0
  64. package/dist/storage-file.d.ts +21 -0
  65. package/dist/storage-file.d.ts.map +1 -0
  66. package/dist/storage-file.js +62 -0
  67. package/dist/storage-file.js.map +1 -0
  68. package/dist/storage-idb.d.ts +19 -0
  69. package/dist/storage-idb.d.ts.map +1 -0
  70. package/dist/storage-idb.js +64 -0
  71. package/dist/storage-idb.js.map +1 -0
  72. package/dist/storage.d.ts +78 -0
  73. package/dist/storage.d.ts.map +1 -0
  74. package/dist/storage.js +163 -0
  75. package/dist/storage.js.map +1 -0
  76. package/dist/version.d.ts +3 -0
  77. package/dist/version.d.ts.map +1 -0
  78. package/dist/version.js +3 -0
  79. package/dist/version.js.map +1 -0
  80. package/dist/ws.d.ts +41 -0
  81. package/dist/ws.d.ts.map +1 -0
  82. package/dist/ws.js +66 -0
  83. package/dist/ws.js.map +1 -0
  84. package/package.json +65 -0
  85. package/src/async-queue.ts +100 -0
  86. package/src/attachments.ts +301 -0
  87. package/src/client.ts +351 -0
  88. package/src/connect.ts +29 -0
  89. package/src/default-storage.ts +14 -0
  90. package/src/emitter.ts +40 -0
  91. package/src/errors.ts +218 -0
  92. package/src/hub.ts +456 -0
  93. package/src/index.ts +143 -0
  94. package/src/link.ts +699 -0
  95. package/src/node.ts +652 -0
  96. package/src/pair.ts +527 -0
  97. package/src/permissions.ts +134 -0
  98. package/src/runtime.ts +14 -0
  99. package/src/session.ts +697 -0
  100. package/src/storage-file.ts +78 -0
  101. package/src/storage-idb.ts +74 -0
  102. package/src/storage.ts +231 -0
  103. package/src/version.ts +2 -0
  104. package/src/ws.ts +94 -0
@@ -0,0 +1,301 @@
1
+ /**
2
+ * 图片附件(ADR-35,docs/protocol.md § 5.6):经 blob 通道把图片传到 daemon,消息只带 `AttachmentRef`。
3
+ *
4
+ * - 上传:`blob.put_begin` → 每块 `chunk_size`(daemon 给,目前 512 KiB)的 `blob.put_chunk`,最多 2 块在途 →
5
+ * `blob.put_end`,返回 daemon 记录的 `AttachmentRef`(含宽高)。每块都有答复:超时 / 掉线的块自己重试,不整张重传;
6
+ * daemon 明确拒绝的不重试(块答 `finalizing` = `put_end` 已经接手,直接 `put_end` 拿结果)。失败或中止时尽力 `blob.discard`。
7
+ * - 同一个 `Node` 上的上传排队、一张一张传(ADR-35「2026-10 修订」:每个节点 1 张在上传、2 块在途),
8
+ * 免得「允许」「停止」之类的请求排在几 MB 的图后面。
9
+ * - SDK 不缩放、不重编码图片,也不替 daemon 校验(daemon 是唯一的校验点):调用方自己把图控制在长边 ≤ 2000 px、
10
+ * 单张 ≤ 约 1.5 MiB(硬上限:daemon 每张默认 10 MiB、每条消息合计 20 MiB;Claude 单张 base64 后约 5 MB)。
11
+ * - 下载:`blob.get` 按偏移分页拉(每段 ≤ 512 KiB)。
12
+ */
13
+ import { RpcTimeoutError, type AttachmentRef, type BlobPutBeginResult } from '@anycon/protocol'
14
+
15
+ import { AnyconError, AttachmentError, NodeOffline } from './errors.js'
16
+ import type { Node } from './node.js'
17
+
18
+ /** daemon 的上传白名单(agent 收不收还要看它的 `capabilities.attachments`)。 */
19
+ export const IMAGE_MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] as const
20
+ export type ImageMime = (typeof IMAGE_MIME_TYPES)[number]
21
+
22
+ /** 同一个节点同时在途的块数(一块 512 KiB,base64 后约 700 KB)。 */
23
+ export const MAX_CHUNKS_IN_FLIGHT = 2
24
+ /** 超时 / 掉线的块(和 `put_end`)再试几次。 */
25
+ const CHUNK_RETRIES = 2
26
+ const RETRY_DELAY_MS = 400
27
+ /** 块和 `put_end` 的请求超时:慢速上行一块就要十几秒,默认的 30 秒会在数据还在路上时就判超时、白白重发。 */
28
+ const UPLOAD_REQUEST_TIMEOUT_MS = 90_000
29
+ /** 掉线的块重试之前最多等节点重新上线多久。 */
30
+ const OFFLINE_WAIT_MS = 30_000
31
+ /** daemon 给的 `chunk_size` 超出这个范围当作协议错误,不照着切。 */
32
+ const MAX_CHUNK_BYTES = 4 * 1024 * 1024
33
+ /** `blob.get` 每段的上限(daemon 也封在 512 KiB)。 */
34
+ const GET_PAGE_BYTES = 512 * 1024
35
+
36
+ export interface UploadImageOptions {
37
+ /** 展示用的文件名(1–255 字节,不含 `/` `\` 和控制字符)。daemon 不用它拼路径;扩展名和 mime 对不上时 daemon 会补上。 */
38
+ name: string
39
+ /** `image/png` / `image/jpeg` / `image/gif` / `image/webp`。缺省按文件头(magic bytes)判断,认不出抛 `unsupported_image`。 */
40
+ mime?: ImageMime | (string & {})
41
+ /** 中止上传:不再发块、尽力 `blob.discard`,以 `signal.reason` 失败。 */
42
+ signal?: AbortSignal
43
+ /** 已确认的字节数 / 总字节数。从 `(0, total)` 开始,成功时以 `(total, total)` 结束。 */
44
+ onProgress?: (sent: number, total: number) => void
45
+ /** 每块(和 `put_end`)的请求超时,默认 90 秒。 */
46
+ requestTimeoutMs?: number
47
+ }
48
+
49
+ export interface DownloadOptions {
50
+ signal?: AbortSignal
51
+ }
52
+
53
+ export interface DownloadedAttachment {
54
+ /** daemon 记录的元数据(和 `user_message.attachments` 里的一致)。 */
55
+ ref: AttachmentRef
56
+ bytes: Uint8Array
57
+ }
58
+
59
+ const ascii = (s: string): number[] => Array.from(s, (c) => c.charCodeAt(0))
60
+
61
+ /** 按文件头判断图片类型(和 daemon 一样只比前缀,不解码)。认不出返回 `undefined`。 */
62
+ export function detectImageMime(bytes: Uint8Array): ImageMime | undefined {
63
+ const starts = (prefix: readonly number[], at = 0) =>
64
+ bytes.length >= at + prefix.length && prefix.every((b, i) => bytes[at + i] === b)
65
+ if (starts([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png'
66
+ if (starts([0xff, 0xd8, 0xff])) return 'image/jpeg'
67
+ if (starts(ascii('GIF87a')) || starts(ascii('GIF89a'))) return 'image/gif'
68
+ if (starts(ascii('RIFF')) && starts(ascii('WEBP'), 8)) return 'image/webp'
69
+ return undefined
70
+ }
71
+
72
+ /** 标准 base64(带 padding)。 */
73
+ export function bytesToBase64(bytes: Uint8Array): string {
74
+ const B = (globalThis as { Buffer?: NodeBuffer }).Buffer
75
+ if (B) return B.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')
76
+ let binary = ''
77
+ for (let i = 0; i < bytes.length; i += 0x8000) {
78
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
79
+ }
80
+ return btoa(binary)
81
+ }
82
+
83
+ export function base64ToBytes(data: string): Uint8Array {
84
+ const B = (globalThis as { Buffer?: NodeBuffer }).Buffer
85
+ if (B) return new Uint8Array(B.from(data, 'base64'))
86
+ const binary = atob(data)
87
+ const out = new Uint8Array(binary.length)
88
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)
89
+ return out
90
+ }
91
+
92
+ interface NodeBuffer {
93
+ from(data: ArrayBufferLike, offset: number, length: number): { toString(enc: 'base64'): string }
94
+ from(data: string, enc: 'base64'): Uint8Array
95
+ }
96
+
97
+ /** 64 位小写 hex 的 SHA-256(`blob.put_begin` 要整个文件的摘要,daemon 在 `put_end` 校验)。 */
98
+ export async function sha256Hex(bytes: Uint8Array): Promise<string> {
99
+ const subtle = globalThis.crypto?.subtle
100
+ if (!subtle) {
101
+ throw new AnyconError(
102
+ 'unsupported_runtime',
103
+ 'crypto.subtle is not available (a browser page served over plain http?); it is needed to hash attachments',
104
+ )
105
+ }
106
+ const digest = new Uint8Array(await subtle.digest('SHA-256', bytes as Uint8Array<ArrayBuffer>))
107
+ return Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('')
108
+ }
109
+
110
+ function abortReason(signal: AbortSignal): unknown {
111
+ return signal.reason ?? new AnyconError('aborted', 'the upload was aborted')
112
+ }
113
+
114
+ /** 等 `p`,但 `signal` 中止时立刻放弃(在途的请求还会跑完,结果不再有人要)。 */
115
+ export function raceAbort<T>(p: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
116
+ if (!signal) return p
117
+ return new Promise<T>((resolve, reject) => {
118
+ const onAbort = () => reject(abortReason(signal))
119
+ if (signal.aborted) return onAbort()
120
+ signal.addEventListener('abort', onAbort, { once: true })
121
+ p.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort))
122
+ })
123
+ }
124
+
125
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
126
+
127
+ /**
128
+ * 跑 `fn`,超时 / 掉线时最多再试 `CHUNK_RETRIES` 次(掉线的先等节点重新上线)。daemon 的明确答复(`RpcError`)不重试。
129
+ * `put_chunk` 按 `index` 定位、`put_end` 对已完成的 blob 返回同一个结果,所以重发是安全的。
130
+ */
131
+ async function withRetry<T>(
132
+ node: Node,
133
+ fn: () => Promise<T>,
134
+ signal: AbortSignal | undefined,
135
+ ): Promise<T> {
136
+ for (let attempt = 0; ; attempt++) {
137
+ if (signal?.aborted) throw abortReason(signal)
138
+ try {
139
+ return await fn()
140
+ } catch (err) {
141
+ const transient = err instanceof RpcTimeoutError || err instanceof NodeOffline
142
+ if (!transient || attempt >= CHUNK_RETRIES) throw err
143
+ if (err instanceof NodeOffline && !node.online) {
144
+ await raceAbort(node.waitOnline(OFFLINE_WAIT_MS), signal).catch((waitErr: unknown) => {
145
+ throw signal?.aborted ? waitErr : err
146
+ })
147
+ } else {
148
+ await raceAbort(sleep(RETRY_DELAY_MS * (attempt + 1)), signal)
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ /** 丢掉一个进行中的上传或还没被引用的 blob;失败不管(daemon 自己回收:上传 10 分钟、blob 24 小时)。 */
155
+ function discardQuietly(node: Node, blobId: string): void {
156
+ node.call('blob.discard', { blob_id: blobId }).catch(() => undefined)
157
+ }
158
+
159
+ /** @internal `Node.uploadImage` 的实现(排队由 `Node` 负责)。 */
160
+ export async function uploadImage(
161
+ node: Node,
162
+ bytes: Uint8Array,
163
+ options: UploadImageOptions,
164
+ ): Promise<AttachmentRef> {
165
+ const { signal, onProgress } = options
166
+ const timeoutMs = options.requestTimeoutMs ?? UPLOAD_REQUEST_TIMEOUT_MS
167
+ if (signal?.aborted) throw abortReason(signal)
168
+ const mime = options.mime ?? detectImageMime(bytes)
169
+ if (mime === undefined) {
170
+ throw new AnyconError(
171
+ 'unsupported_image',
172
+ `cannot tell the image type of ${options.name} from its first bytes; pass mime (only ${IMAGE_MIME_TYPES.join(', ')} are accepted)`,
173
+ )
174
+ }
175
+ const size = bytes.length
176
+ const sha256 = await sha256Hex(bytes)
177
+ if (signal?.aborted) throw abortReason(signal)
178
+
179
+ const beginReq = node.call('blob.put_begin', { name: options.name, mime, size, sha256 })
180
+ let begin: BlobPutBeginResult
181
+ try {
182
+ begin = await raceAbort(beginReq, signal)
183
+ } catch (err) {
184
+ // 等 put_begin 的时候被中止了:它迟早会答复,到时候把这个刚开的上传丢掉
185
+ if (signal?.aborted)
186
+ beginReq.then(
187
+ (b) => discardQuietly(node, b.blob_id),
188
+ () => undefined,
189
+ )
190
+ throw err
191
+ }
192
+
193
+ const blobId = begin.blob_id
194
+ try {
195
+ const chunkSize = begin.chunk_size
196
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0 || chunkSize > MAX_CHUNK_BYTES) {
197
+ throw new AnyconError(
198
+ 'protocol',
199
+ `blob.put_begin returned an unusable chunk_size (${String(chunkSize)})`,
200
+ )
201
+ }
202
+ const total = Math.ceil(size / chunkSize)
203
+ let next = 0
204
+ let sent = 0
205
+ let failed = false
206
+ let finalizing = false
207
+ onProgress?.(0, size)
208
+
209
+ // 两个 worker 各自取下一块;任何一块最终失败,整个上传立刻失败(另一个 worker 发完手上这块就停)
210
+ const worker = async (): Promise<void> => {
211
+ for (;;) {
212
+ if (failed || finalizing || signal?.aborted) return
213
+ const index = next++
214
+ if (index >= total) return
215
+ const start = index * chunkSize
216
+ const slice = bytes.subarray(start, Math.min(size, start + chunkSize))
217
+ try {
218
+ await withRetry(
219
+ node,
220
+ () =>
221
+ node.call(
222
+ 'blob.put_chunk',
223
+ { blob_id: blobId, index, data: bytesToBase64(slice) },
224
+ { timeoutMs },
225
+ ),
226
+ signal,
227
+ )
228
+ } catch (err) {
229
+ // `put_end` 已经接手了这个上传(重连后旧传输上的 put_end 和这里的重发重叠):不再发块,下面 put_end 拿它的结果
230
+ if (err instanceof AttachmentError && err.reason === 'finalizing') {
231
+ finalizing = true
232
+ return
233
+ }
234
+ failed = true
235
+ throw err
236
+ }
237
+ sent += slice.length
238
+ onProgress?.(sent, size)
239
+ }
240
+ }
241
+ await raceAbort(
242
+ Promise.all(Array.from({ length: Math.min(MAX_CHUNKS_IN_FLIGHT, total) }, worker)),
243
+ signal,
244
+ )
245
+ if (signal?.aborted) throw abortReason(signal)
246
+
247
+ const ref = await raceAbort(
248
+ withRetry(node, () => node.call('blob.put_end', { blob_id: blobId }, { timeoutMs }), signal),
249
+ signal,
250
+ )
251
+ // 传完的同时被中止了:没人会引用它,下面丢掉
252
+ if (signal?.aborted) throw abortReason(signal)
253
+ return ref
254
+ } catch (err) {
255
+ discardQuietly(node, blobId)
256
+ throw err
257
+ }
258
+ }
259
+
260
+ /** @internal `Node.downloadAttachment` 的实现。 */
261
+ export async function downloadAttachment(
262
+ node: Node,
263
+ blobId: string,
264
+ options: DownloadOptions = {},
265
+ ): Promise<DownloadedAttachment> {
266
+ const { signal } = options
267
+ const parts: Uint8Array[] = []
268
+ let ref: AttachmentRef | undefined
269
+ let offset = 0
270
+ for (;;) {
271
+ if (signal?.aborted) throw abortReason(signal)
272
+ const page = await raceAbort(
273
+ node.call('blob.get', { blob_id: blobId, offset, max_bytes: GET_PAGE_BYTES }),
274
+ signal,
275
+ )
276
+ ref ??= page.blob
277
+ const data = base64ToBytes(page.data)
278
+ parts.push(data)
279
+ offset += data.length
280
+ if (page.eof) break
281
+ if (data.length === 0) {
282
+ throw new AnyconError(
283
+ 'protocol',
284
+ `blob.get returned an empty page before the end of ${blobId}`,
285
+ )
286
+ }
287
+ if (offset > ref.bytes) {
288
+ throw new AnyconError(
289
+ 'protocol',
290
+ `blob.get returned more than ${ref.bytes} bytes for ${blobId}`,
291
+ )
292
+ }
293
+ }
294
+ const bytes = new Uint8Array(offset)
295
+ let at = 0
296
+ for (const part of parts) {
297
+ bytes.set(part, at)
298
+ at += part.length
299
+ }
300
+ return { ref, bytes }
301
+ }
package/src/client.ts ADDED
@@ -0,0 +1,351 @@
1
+ /**
2
+ * `Client`:一个 hub 连接(一台设备,单设备单连接)+ 到若干节点的端到端通道。
3
+ * `connect()` 是「一个 Client + 一个 Node」的快捷方式;同时连多个节点就用 `Client.open()` 再多次 `client.node()`。
4
+ */
5
+ import {
6
+ bytesOfHex,
7
+ loadCrypto,
8
+ type ClientInfo,
9
+ type Crypto,
10
+ type Keypair,
11
+ } from '@anycon/protocol'
12
+
13
+ import { defaultStorage } from './default-storage.js'
14
+ import { Emitter } from './emitter.js'
15
+ import { AnyconError, NodeRejected, PairingRequired, ProtocolMismatch } from './errors.js'
16
+ import { HubConnection, type BackoffOptions } from './hub.js'
17
+ import { NodeLink } from './link.js'
18
+ import { Node, type NodeOptions } from './node.js'
19
+ import type { PermissionPolicy } from './permissions.js'
20
+ import { detectPlatform } from './runtime.js'
21
+ import { StateStore, envCredentials, type SdkStorage, type StoredNode } from './storage.js'
22
+ import { SDK_VERSION } from './version.js'
23
+ import { toWsUrl, type WebSocketFactory } from './ws.js'
24
+
25
+ export interface ClientOptions {
26
+ /** 身份 / 节点存储。默认:Node 下 `~/.anycon/sdk/<hub-host>/<profile>/`,浏览器下 IndexedDB。 */
27
+ storage?: SdkStorage
28
+ /** 存储 profile,默认 `ANYCON_PROFILE` 或 `default`。 */
29
+ profile?: string
30
+ /** 覆盖自报的设备信息(`kind` 固定为 `sdk`)。 */
31
+ clientInfo?: Partial<Omit<ClientInfo, 'kind'>>
32
+ /** 默认的权限策略。 */
33
+ onPermission?: PermissionPolicy
34
+ /** SDK 代答 deny 前等多久(只对 SDK 自己在用的会话)。默认 10 分钟。 */
35
+ permissionTimeoutMs?: number
36
+ /** 掉线后自动重连,默认 true(指数退避 1s → 30s)。 */
37
+ reconnect?: boolean | BackoffOptions
38
+ /** RPC 请求默认超时。默认 30 秒。 */
39
+ requestTimeoutMs?: number
40
+ /** 等握手完成的上限。默认 20 秒。 */
41
+ connectTimeoutMs?: number
42
+ /** 单次握手等回复的时间。默认 5 秒;重试 `handshakeAttempts` 次。 */
43
+ handshakeTimeoutMs?: number
44
+ handshakeAttempts?: number
45
+ /**
46
+ * 保留最近发出的信封原文的字节上限(hub 退回 `backpressure` 时按原样重发它们)。默认 16 MiB,协议要求不低于
47
+ * 8 MiB。超过上限时 SDK 暂停发新的信封(把上限当作在途窗口)直到最老的一批过了保留期,不会逐出还在路上的;
48
+ * 调小只会让大消息发得更慢。主要给测试用。
49
+ */
50
+ resendBufferBytes?: number
51
+ /** 发出不满这么久的信封永不逐出(它们可能还在路上),毫秒。默认 10000。主要给测试用。 */
52
+ resendRetainMs?: number
53
+ /** 注入 Noise 实现(默认 wasm)。 */
54
+ crypto?: Crypto
55
+ /** 注入 WebSocket 构造(默认:浏览器原生 / Node 用 `ws`)。 */
56
+ webSocket?: WebSocketFactory
57
+ /**
58
+ * WebSocket 升级请求附带的 HTTP 头(仅 Node / Bun;浏览器忽略)。
59
+ * 用途:hub 前面的反向代理要求的头(`CF-Access-Client-Id` 等)。已配对的设备用 token 认证,不需要 cookie。
60
+ */
61
+ headers?: Record<string, string>
62
+ }
63
+
64
+ export interface ClientEvents {
65
+ /** hub 认证成功(含每次重连后)。 */
66
+ connected: []
67
+ /** hub 连接断开。 */
68
+ disconnected: [willReconnect: boolean]
69
+ /** 不会再恢复的错误(被顶掉、设备被吊销、token 失效)。 */
70
+ error: [Error]
71
+ }
72
+
73
+ export function buildClientInfo(overrides: ClientOptions['clientInfo'] = {}): ClientInfo {
74
+ return {
75
+ name: overrides.name ?? 'anycon-sdk',
76
+ kind: 'sdk',
77
+ platform: overrides.platform ?? detectPlatform(),
78
+ version: overrides.version ?? SDK_VERSION,
79
+ ...(overrides.origin !== undefined ? { origin: overrides.origin } : {}),
80
+ }
81
+ }
82
+
83
+ export class Client extends Emitter<ClientEvents> {
84
+ readonly hubUrl: string
85
+ readonly #hub: HubConnection
86
+ readonly #store: StateStore
87
+ readonly #crypto: Crypto
88
+ readonly #keypair: Keypair
89
+ readonly #options: ClientOptions
90
+ readonly #envNode: StoredNode | undefined
91
+ readonly #nodes = new Map<string, Node>()
92
+ readonly #links = new Map<string, NodeLink>()
93
+ readonly #onlinePeers = new Set<string>()
94
+ readonly #identityStored: boolean
95
+ #fatal: Error | undefined
96
+ #closed = false
97
+
98
+ private constructor(
99
+ hubUrl: string,
100
+ hub: HubConnection,
101
+ store: StateStore,
102
+ crypto: Crypto,
103
+ keypair: Keypair,
104
+ options: ClientOptions,
105
+ envNode: StoredNode | undefined,
106
+ identityStored: boolean,
107
+ ) {
108
+ super()
109
+ this.#identityStored = identityStored
110
+ this.hubUrl = hubUrl
111
+ this.#hub = hub
112
+ this.#store = store
113
+ this.#crypto = crypto
114
+ this.#keypair = keypair
115
+ this.#options = options
116
+ this.#envNode = envNode
117
+
118
+ hub.on('authed', (ok) => {
119
+ this.#onlinePeers.clear()
120
+ for (const id of ok.peers_online) this.#onlinePeers.add(id)
121
+ for (const link of this.#links.values()) link.onHubAuthed(ok.peers_online)
122
+ this.emit('connected')
123
+ })
124
+ hub.on('control', (ctrl) => {
125
+ if (ctrl.type === 'peer_online') this.#onlinePeers.add(ctrl.device)
126
+ else if (ctrl.type === 'peer_offline') this.#onlinePeers.delete(ctrl.device)
127
+ for (const link of this.#links.values()) link.onControl(ctrl)
128
+ })
129
+ hub.on('envelope', (env) => this.#links.get(env.from)?.onEnvelope(env))
130
+ hub.on('disconnected', ({ willReconnect }) => {
131
+ this.#onlinePeers.clear()
132
+ for (const link of this.#links.values()) link.onHubDown()
133
+ this.emit('disconnected', willReconnect)
134
+ })
135
+ hub.on('fatal', (err) => {
136
+ this.#fatal = err
137
+ if (err instanceof NodeRejected) void this.#forgetRevokedIdentity()
138
+ for (const link of this.#links.values()) link.onHubDown()
139
+ this.emit('error', err)
140
+ })
141
+ }
142
+
143
+ /**
144
+ * 读取本地身份,连接 hub 并认证。没有身份抛 `PairingRequired`;
145
+ * hub 不认 token 抛 `PairingRequired`,设备被吊销抛 `NodeRejected`,协议不兼容抛 `ProtocolMismatch`。
146
+ */
147
+ static async open(hubUrl: string, options: ClientOptions = {}): Promise<Client> {
148
+ const storage = options.storage ?? (await defaultStorage(hubUrl, options.profile))
149
+ const store = new StateStore(storage)
150
+ const env = envCredentials()
151
+ const stored = await store.getIdentity()
152
+ const secretKey = env.identity?.secretKey ?? stored?.secretKey
153
+ const deviceToken = env.identity?.deviceToken ?? stored?.deviceToken
154
+ if (!secretKey || !deviceToken) throw new PairingRequired()
155
+ const crypto = options.crypto ?? (await loadCrypto())
156
+ const keypair = crypto.keypairFromSecret(bytesOfHex(secretKey))
157
+ const deviceId = env.identity?.deviceId ?? stored?.deviceId
158
+ const hub = new HubConnection({
159
+ url: toWsUrl(hubUrl),
160
+ token: deviceToken,
161
+ ...(deviceId ? { deviceId } : {}),
162
+ client: buildClientInfo(options.clientInfo),
163
+ reconnect: options.reconnect ?? true,
164
+ ...(options.webSocket ? { webSocket: options.webSocket } : {}),
165
+ ...(options.headers ? { headers: options.headers } : {}),
166
+ })
167
+ const client = new Client(hubUrl, hub, store, crypto, keypair, options, env.node, !env.identity)
168
+ try {
169
+ await hub.start()
170
+ } catch (err) {
171
+ hub.close()
172
+ if (err instanceof NodeRejected) await client.#forgetRevokedIdentity()
173
+ throw err
174
+ }
175
+ return client
176
+ }
177
+
178
+ /** hub 分配的本设备 id。 */
179
+ get deviceId(): string {
180
+ return this.#hub.deviceId
181
+ }
182
+
183
+ /** hub 连接是否已认证。 */
184
+ get connected(): boolean {
185
+ return this.#hub.ready
186
+ }
187
+
188
+ /** 不会再恢复的错误;设置之后所有调用都会抛它。 */
189
+ get fatalError(): Error | undefined {
190
+ return this.#fatal
191
+ }
192
+
193
+ /** 已配对的节点(本地记录,不管在不在线)。 */
194
+ async pairedNodes(): Promise<StoredNode[]> {
195
+ const nodes = await this.#store.getNodes()
196
+ if (this.#envNode && !nodes.some((n) => n.id === this.#envNode?.id)) nodes.push(this.#envNode)
197
+ return nodes
198
+ }
199
+
200
+ /**
201
+ * 连接一个已配对的节点:`selector` 是节点名或 id 前缀;只配对了一个节点时可省略。
202
+ * 节点不在线时也返回(`node.online === false`,调用抛 `NodeOffline`,`waitOnline()` 等上线)。
203
+ * 握手被拒抛 `NodeRejected`。同一个节点重复调用返回同一个 `Node`。
204
+ */
205
+ async node(selector?: string, options: NodeOptions = {}): Promise<Node> {
206
+ if (this.#closed) throw new AnyconError('client_closed', 'the client has been closed')
207
+ if (this.#fatal) throw this.#fatal
208
+ const stored = selectNode(await this.pairedNodes(), selector)
209
+ const existing = this.#nodes.get(stored.id)
210
+ if (existing) return existing
211
+
212
+ const link = new NodeLink(this.#hub, this.#crypto, this.#keypair, stored, {
213
+ ...(this.#options.requestTimeoutMs !== undefined
214
+ ? { requestTimeoutMs: this.#options.requestTimeoutMs }
215
+ : {}),
216
+ ...(this.#options.handshakeTimeoutMs !== undefined
217
+ ? { handshakeTimeoutMs: this.#options.handshakeTimeoutMs }
218
+ : {}),
219
+ ...(this.#options.handshakeAttempts !== undefined
220
+ ? { handshakeAttempts: this.#options.handshakeAttempts }
221
+ : {}),
222
+ ...(this.#options.resendBufferBytes !== undefined
223
+ ? { resendBufferBytes: this.#options.resendBufferBytes }
224
+ : {}),
225
+ ...(this.#options.resendRetainMs !== undefined
226
+ ? { resendRetainMs: this.#options.resendRetainMs }
227
+ : {}),
228
+ })
229
+ const node = new Node(this, link, {
230
+ ...(this.#options.onPermission ? { onPermission: this.#options.onPermission } : {}),
231
+ ...(this.#options.permissionTimeoutMs !== undefined
232
+ ? { permissionTimeoutMs: this.#options.permissionTimeoutMs }
233
+ : {}),
234
+ ...options,
235
+ })
236
+ this.#links.set(stored.id, link)
237
+ this.#nodes.set(stored.id, node)
238
+
239
+ const settled = waitSettled(link, this.#options.connectTimeoutMs ?? 20_000)
240
+ link.onHubAuthed([...this.#onlinePeers])
241
+ try {
242
+ await settled
243
+ if (link.ready) await node.info().catch(rethrowProtocol)
244
+ } catch (err) {
245
+ this.#drop(stored.id)
246
+ throw err
247
+ }
248
+ return node
249
+ }
250
+
251
+ /** 设备被 hub 吊销(4004 / auth_fail revoked):token 已作废,清掉本地凭据,下次 connect 抛 PairingRequired。 */
252
+ async #forgetRevokedIdentity(): Promise<void> {
253
+ if (this.#identityStored) await this.#store.clearIdentity().catch(() => undefined)
254
+ }
255
+
256
+ /** @internal 补上节点名,下次可以用名字选节点。 */
257
+ async rememberNodeName(id: string, name: string): Promise<void> {
258
+ await this.#store.updateNode(id, { name }).catch(() => undefined)
259
+ }
260
+
261
+ /** @internal Node.close()。 */
262
+ async release(node: Node, closeClient: boolean): Promise<void> {
263
+ this.#drop(node.id)
264
+ if (closeClient) await this.close()
265
+ }
266
+
267
+ async close(): Promise<void> {
268
+ if (this.#closed) return
269
+ this.#closed = true
270
+ for (const id of Array.from(this.#links.keys())) this.#drop(id)
271
+ this.#hub.close()
272
+ }
273
+
274
+ #drop(id: string): void {
275
+ this.#nodes.get(id)?.markClosed()
276
+ this.#links.get(id)?.close()
277
+ this.#links.delete(id)
278
+ this.#nodes.delete(id)
279
+ }
280
+ }
281
+
282
+ /** 按节点名(精确)或 id 前缀选节点。 */
283
+ export function selectNode(nodes: readonly StoredNode[], selector?: string): StoredNode {
284
+ if (nodes.length === 0) {
285
+ throw new PairingRequired('no node is paired with this device yet: call pair() first')
286
+ }
287
+ if (selector === undefined) {
288
+ if (nodes.length === 1) return nodes[0]!
289
+ const names = nodes.map((n) => n.name ?? n.id.slice(0, 8)).join(', ')
290
+ throw new AnyconError(
291
+ 'node_required',
292
+ `several nodes are paired (${names}); pass { node } to choose one`,
293
+ )
294
+ }
295
+ const byName = nodes.filter((n) => n.name === selector)
296
+ const matches = byName.length > 0 ? byName : nodes.filter((n) => n.id.startsWith(selector))
297
+ if (matches.length === 1) return matches[0]!
298
+ if (matches.length > 1) {
299
+ throw new AnyconError(
300
+ 'node_ambiguous',
301
+ `"${selector}" matches ${matches.length} paired nodes; use a longer id prefix`,
302
+ )
303
+ }
304
+ const names = nodes.map((n) => n.name ?? n.id.slice(0, 8)).join(', ')
305
+ throw new AnyconError('node_not_found', `no paired node matches "${selector}" (paired: ${names})`)
306
+ }
307
+
308
+ function rethrowProtocol(err: unknown): void {
309
+ // info() 失败:协议不兼容要报出去;节点中途掉线之类忽略(connect 仍然成功,之后的调用自己会抛)。
310
+ if (err instanceof ProtocolMismatch) throw err
311
+ }
312
+
313
+ /** 等通道落定:ready 或节点不在线(peer_offline)都算,noise_failed 抛错。 */
314
+ function waitSettled(link: NodeLink, timeoutMs: number): Promise<void> {
315
+ return new Promise<void>((resolve, reject) => {
316
+ let timer: ReturnType<typeof setTimeout> | undefined
317
+ let off: (() => void) | undefined
318
+ const finish = (fn: () => void) => {
319
+ off?.()
320
+ if (timer !== undefined) clearTimeout(timer)
321
+ fn()
322
+ }
323
+ const check = (): boolean => {
324
+ switch (link.state) {
325
+ case 'ready':
326
+ case 'peer_offline':
327
+ finish(resolve)
328
+ return true
329
+ case 'noise_failed':
330
+ finish(() => reject(link.failure ?? new NodeRejected()))
331
+ return true
332
+ case 'closed':
333
+ finish(() => reject(new AnyconError('client_closed', 'the client has been closed')))
334
+ return true
335
+ default:
336
+ return false
337
+ }
338
+ }
339
+ off = link.on('state', () => {
340
+ check()
341
+ })
342
+ timer = setTimeout(
343
+ () =>
344
+ finish(() =>
345
+ reject(new NodeRejected('timed out waiting for the Noise handshake with the node')),
346
+ ),
347
+ timeoutMs,
348
+ )
349
+ check()
350
+ })
351
+ }
package/src/connect.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { Client, type ClientOptions } from './client.js'
2
+ import type { Node, NodeOptions } from './node.js'
3
+
4
+ export interface ConnectOptions extends ClientOptions {
5
+ /** 节点名或 id 前缀;只配对了一个节点时可省略。 */
6
+ node?: string
7
+ }
8
+
9
+ /**
10
+ * 连接 hub 并打开一个已配对的节点。返回的 `Node` 拥有底层连接:`node.close()` 会一并关闭。
11
+ * 一个进程要同时连多个节点时用 `Client.open()` + 多次 `client.node()`(hub 对单设备只允许一条连接)。
12
+ *
13
+ * - 没有本地身份 / token 失效 → `PairingRequired`
14
+ * - 设备被吊销、Noise 握手被拒 → `NodeRejected`
15
+ * - 节点不在线:照常返回,`node.online === false`,调用抛 `NodeOffline`,`node.waitOnline()` 等上线
16
+ */
17
+ export async function connect(hubUrl: string, options: ConnectOptions = {}): Promise<Node> {
18
+ const { node: selector, ...clientOptions } = options
19
+ const client = await Client.open(hubUrl, clientOptions)
20
+ try {
21
+ const nodeOptions: NodeOptions = {}
22
+ const node = await client.node(selector, nodeOptions)
23
+ node.markOwnsClient()
24
+ return node
25
+ } catch (err) {
26
+ await client.close()
27
+ throw err
28
+ }
29
+ }
@@ -0,0 +1,14 @@
1
+ import { defaultSdkDir, FileStorage, profileDir } from './storage-file.js'
2
+ import { IndexedDBStorage } from './storage-idb.js'
3
+ import { hubHostKey, MemoryStorage, resolveProfile, type SdkStorage } from './storage.js'
4
+ import { isNodeRuntime } from './runtime.js'
5
+
6
+ /** 按运行环境选默认存储:Node / Bun → 文件;浏览器 → IndexedDB;都没有 → 内存。 */
7
+ export async function defaultStorage(hubUrl: string, profile?: string): Promise<SdkStorage> {
8
+ const scope = `${hubHostKey(hubUrl)}/${resolveProfile(profile)}`
9
+ if (isNodeRuntime()) return new FileStorage(profileDir(await defaultSdkDir(), hubUrl, profile))
10
+ if (typeof (globalThis as { indexedDB?: unknown }).indexedDB !== 'undefined') {
11
+ return new IndexedDBStorage(scope)
12
+ }
13
+ return new MemoryStorage()
14
+ }