@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
package/src/node.ts ADDED
@@ -0,0 +1,652 @@
1
+ /**
2
+ * 一个节点(daemon)的客户端视图:`info()` / `agents` / `projects` / `sessions`,
3
+ * 以及 daemon → 客户端的通知分发(`session.event`、`permission.request`、`job.*` ……)。
4
+ */
5
+ import {
6
+ METHODS,
7
+ PROTOCOL_VERSION,
8
+ type AgentInfo,
9
+ type AttachmentRef,
10
+ type AgentListResult,
11
+ type JobDone,
12
+ type JobProgress,
13
+ type NodeInfo,
14
+ type PermissionRequest,
15
+ type PermissionResolved,
16
+ type Project,
17
+ type RequestMethodName,
18
+ type RequestMethods,
19
+ type RequestOptions,
20
+ type SessionChanged,
21
+ type SessionEvent,
22
+ type SessionListParams,
23
+ type SessionSettings,
24
+ type SessionSummary,
25
+ type SessionWorkspace,
26
+ type WorkspaceBranchesResult,
27
+ type WorkspaceBrowseResult,
28
+ type WorkspaceChanged,
29
+ type SearchHit,
30
+ type TrashEntry,
31
+ type WorktreeInfo,
32
+ } from '@anycon/protocol'
33
+
34
+ import {
35
+ downloadAttachment,
36
+ raceAbort,
37
+ uploadImage,
38
+ type DownloadOptions,
39
+ type DownloadedAttachment,
40
+ type UploadImageOptions,
41
+ } from './attachments.js'
42
+ import type { Client } from './client.js'
43
+ import { Emitter } from './emitter.js'
44
+ import {
45
+ AnyconError,
46
+ NodeOffline,
47
+ NodeRejected,
48
+ ProtocolMismatch,
49
+ RpcError,
50
+ mapRpcError,
51
+ } from './errors.js'
52
+ import type { LinkState, NodeLink } from './link.js'
53
+ import { decisionToParams, type PermissionPolicy } from './permissions.js'
54
+ import { Session, randomId } from './session.js'
55
+
56
+ export interface NodeEvents {
57
+ /** 与节点的端到端通道建立(含每次重连后)。 */
58
+ online: []
59
+ /** 通道断开(节点下线、hub 断线、重新握手开始)。 */
60
+ offline: []
61
+ state: [state: LinkState]
62
+ /**
63
+ * 非致命的通道问题:hub 丢了我们的信封(`dropped`:分片后仍超限 / 配对关系不对)。进行中的请求已经
64
+ * 失败,通道会重新握手;这里让调用方有机会记录。限速(`rate_limited`)和背压(`backpressure`)不走这里:
65
+ * hub 不丢信封,SDK 暂停、等一会儿再按序重发,请求照常完成。
66
+ */
67
+ error: [error: Error]
68
+ /** `node.close()` 或 client 关闭:进行中的事件流会因此失败。 */
69
+ closed: []
70
+ session_changed: [SessionChanged]
71
+ permission: [PermissionRequest]
72
+ permission_resolved: [PermissionResolved]
73
+ /**
74
+ * 权限策略没能答复这个请求:策略回调抛了异常,或它的决定无法执行(比如 `'allow'` 但请求里没有 `allow_once`)。
75
+ * 请求照常走超时 deny(`permissionTimeoutMs`);这里让调用方有机会记录 / 报警,而不是悄悄吞掉。
76
+ */
77
+ permission_error: [error: unknown, request: PermissionRequest]
78
+ agent_changed: [AgentListResult]
79
+ workspace_changed: [WorkspaceChanged]
80
+ }
81
+
82
+ export interface NodeOptions {
83
+ onPermission?: PermissionPolicy
84
+ /** SDK 代答 deny 前等多久。默认 10 分钟。 */
85
+ permissionTimeoutMs?: number
86
+ }
87
+
88
+ export interface CreateSessionParams {
89
+ agent: string
90
+ /** 项目名;省略 = scratch 会话。 */
91
+ project?: string
92
+ /** 值来自 `agents.list()`:model / thinking / mode / options / env ……不传的取节点默认。 */
93
+ settings?: SessionSettings
94
+ /** 只对这个会话生效的权限策略,覆盖 `connect()` 的。 */
95
+ onPermission?: PermissionPolicy
96
+ /**
97
+ * 在哪里工作(ADR-34)。不传 = 在项目目录本身工作(线路上缺省 `{ mode: 'local' }`;SDK 不替调用方读节点的
98
+ * `worktree.default`)。`{ mode: 'worktree', base?, branch? }` 让 daemon 新建 worktree 和分支,`create()` 返回时
99
+ * `session.worktree.state` 是 `creating`,建好之后才拉起 agent。项目不是 `worktree_ready` → `RpcError`
100
+ * (`invalid`,`data.reason = 'not_worktree_ready'`),分支已存在 → `exists`,`base` 解析不了 → `invalid`(`bad_base`)。
101
+ */
102
+ workspace?: SessionWorkspace
103
+ /**
104
+ * 创建后立即发送的第一条消息。SDK 为它生成 `message_id`(uuid v4);空串当作没有。
105
+ * `create()` 不替你收这个 turn 的事件:要看它,创建后马上 `session.events({ fromSeq: 0 })`
106
+ * (`events()` 会从历史补齐已经发生的),权限策略也要等会话有进行中的 `events()` / `send()` 才会代答。
107
+ */
108
+ prompt?: string
109
+ /**
110
+ * 第一条消息的附件(`node.uploadImage()` 的结果,原样放进来)。有附件时 `prompt` 可以为空,照样发第一条消息。
111
+ * daemon 的核对见 `Session.send` 的 `attachments`。
112
+ */
113
+ attachments?: AttachmentRef[]
114
+ /**
115
+ * 第一条消息的幂等键,默认随机 uuid。`create()` 超时后要重试时传同一个:daemon 按它返回第一次创建的会话,
116
+ * 不会再开第二个(附件已经绑定到那个会话也不会得到 `blob_in_use`)。没有 `prompt` 也没有 `attachments` 时忽略。
117
+ */
118
+ messageId?: string
119
+ }
120
+
121
+ /** 长任务(克隆)。 */
122
+ export interface Job {
123
+ readonly id: string
124
+ /** 进度流;任务结束(`job.done`)后迭代完毕。 */
125
+ progress(): AsyncIterable<JobProgress>
126
+ /** 等任务结束。`ok = false` 时抛 `AnyconError('job_failed')`。 */
127
+ wait(): Promise<JobDone>
128
+ }
129
+
130
+ interface JobRecord {
131
+ progress: JobProgress[]
132
+ done: JobDone | undefined
133
+ waiters: Set<() => void>
134
+ }
135
+
136
+ const PERMISSION_TIMEOUT_MS = 10 * 60_000
137
+
138
+ export class Node extends Emitter<NodeEvents> {
139
+ readonly id: string
140
+ readonly #client: Client
141
+ readonly #link: NodeLink
142
+ readonly #policy: PermissionPolicy | undefined
143
+ readonly #permissionTimeoutMs: number
144
+ readonly #sessions = new Map<string, Session>()
145
+ readonly #jobs = new Map<string, JobRecord>()
146
+ readonly #permSeen = new Set<string>()
147
+ readonly #permTimers = new Map<string, ReturnType<typeof setTimeout>>()
148
+ #name: string | undefined
149
+ /** 上传排队:每个节点同时只传一张(这张传完 / 失败之后才轮到下一张)。 */
150
+ #uploadTail: Promise<void> = Promise.resolve()
151
+ #info: NodeInfo | undefined
152
+ #agents: AgentInfo[] | undefined
153
+ #agentsEtag: string | undefined
154
+ #ownsClient = false
155
+
156
+ /** @internal 由 `Client.node()` 创建。 */
157
+ constructor(client: Client, link: NodeLink, options: NodeOptions = {}) {
158
+ super()
159
+ this.#client = client
160
+ this.#link = link
161
+ this.id = link.node.id
162
+ this.#name = link.node.name
163
+ this.#policy = options.onPermission
164
+ this.#permissionTimeoutMs = options.permissionTimeoutMs ?? PERMISSION_TIMEOUT_MS
165
+
166
+ link.on('ready', () => {
167
+ this.emit('online')
168
+ void this.#resyncSessions()
169
+ })
170
+ link.on('offline', () => this.emit('offline'))
171
+ link.on('state', (state) => this.emit('state', state))
172
+ link.on('error', (error) => this.emit('error', error))
173
+
174
+ const rpc = link.rpc
175
+ rpc.onNotification<SessionEvent>(METHODS.SESSION_EVENT, (se) => {
176
+ this.#sessions.get(se.session_id)?.dispatch(se)
177
+ })
178
+ rpc.onNotification<SessionChanged>(METHODS.SESSION_CHANGED, (c) => this.#onSessionChanged(c))
179
+ rpc.onNotification<PermissionRequest>(METHODS.PERMISSION_REQUEST, (req) => {
180
+ this.emit('permission', req)
181
+ this.observePermission(req)
182
+ })
183
+ rpc.onNotification<PermissionResolved>(METHODS.PERMISSION_RESOLVED, (r) => this.#onResolved(r))
184
+ rpc.onNotification<AgentListResult>(METHODS.AGENT_CHANGED, (r) => {
185
+ this.#agents = r.agents
186
+ this.#agentsEtag = r.etag
187
+ this.emit('agent_changed', r)
188
+ })
189
+ rpc.onNotification<WorkspaceChanged>(METHODS.WORKSPACE_CHANGED, (c) => {
190
+ this.emit('workspace_changed', c)
191
+ })
192
+ rpc.onNotification<JobProgress>(METHODS.JOB_PROGRESS, (p) => {
193
+ const rec = this.#job(p.job_id)
194
+ rec.progress.push(p)
195
+ this.#wake(rec)
196
+ })
197
+ rpc.onNotification<JobDone>(METHODS.JOB_DONE, (d) => {
198
+ const rec = this.#job(d.job_id)
199
+ rec.done = d
200
+ this.#wake(rec)
201
+ })
202
+ }
203
+
204
+ /** 节点显示名(配对时未知,首次 `info()` 后补上)。 */
205
+ get name(): string | undefined {
206
+ return this.#name
207
+ }
208
+
209
+ /** 端到端通道是否可用(节点在线且 Noise 握手完成)。 */
210
+ get online(): boolean {
211
+ return this.#link.state === 'ready'
212
+ }
213
+
214
+ get state(): LinkState {
215
+ return this.#link.state
216
+ }
217
+
218
+ /** 配置了 `onPermission`(`run()` 据此决定无策略时是否自动 deny)。 */
219
+ get hasPermissionPolicy(): boolean {
220
+ return this.#policy !== undefined
221
+ }
222
+
223
+ /** 等节点上线。超时抛 `NodeOffline`;握手被拒抛 `NodeRejected`。 */
224
+ waitOnline(timeoutMs = 30_000): Promise<void> {
225
+ return new Promise<void>((resolve, reject) => {
226
+ const check = (): boolean => {
227
+ const state = this.#link.state
228
+ if (state === 'ready') {
229
+ resolve()
230
+ return true
231
+ }
232
+ if (state === 'noise_failed') {
233
+ reject(this.#link.failure ?? new NodeRejected())
234
+ return true
235
+ }
236
+ if (state === 'closed') {
237
+ reject(new NodeOffline(this.#name ?? this.id, 'the client was closed'))
238
+ return true
239
+ }
240
+ return false
241
+ }
242
+ if (check()) return
243
+ const off = this.#link.on('state', () => {
244
+ if (check()) done()
245
+ })
246
+ const timer =
247
+ timeoutMs > 0
248
+ ? setTimeout(() => {
249
+ done()
250
+ reject(
251
+ new NodeOffline(this.#name ?? this.id, `node still offline after ${timeoutMs}ms`),
252
+ )
253
+ }, timeoutMs)
254
+ : undefined
255
+ const done = () => {
256
+ off()
257
+ if (timer !== undefined) clearTimeout(timer)
258
+ }
259
+ })
260
+ }
261
+
262
+ // ---------- RPC ----------
263
+
264
+ /** 类型化的 RPC 调用。错误按稳定码映射成 `AgentUnavailable` / `SettingsInvalid` / … */
265
+ async call<M extends RequestMethodName>(
266
+ method: M,
267
+ params: RequestMethods[M]['params'],
268
+ options?: RequestOptions,
269
+ ): Promise<RequestMethods[M]['result']> {
270
+ return this.rpc<RequestMethods[M]['result']>(method, params, options)
271
+ }
272
+
273
+ /** 未类型化的 RPC(调用 SDK 还不认识的方法)。 */
274
+ async rpc<T = unknown>(method: string, params?: unknown, options?: RequestOptions): Promise<T> {
275
+ const fatal = this.#client.fatalError
276
+ if (fatal) throw fatal
277
+ try {
278
+ return await this.#link.rpc.request<T>(method, params ?? {}, options)
279
+ } catch (err) {
280
+ throw mapRpcError(err, PROTOCOL_VERSION)
281
+ }
282
+ }
283
+
284
+ /** `node.info`。首次成功时检查协议版本、记下节点名。 */
285
+ async info(options: { refresh?: boolean } = {}): Promise<NodeInfo> {
286
+ if (this.#info && !options.refresh) return this.#info
287
+ const info = await this.call('node.info', {})
288
+ if (Math.abs(info.protocol_version - PROTOCOL_VERSION) > 1) {
289
+ throw new ProtocolMismatch(PROTOCOL_VERSION, info.protocol_version)
290
+ }
291
+ this.#info = info
292
+ if (info.name && info.name !== this.#name) {
293
+ this.#name = info.name
294
+ await this.#client.rememberNodeName(this.id, info.name)
295
+ }
296
+ return info
297
+ }
298
+
299
+ readonly agents = {
300
+ /** `agent.list`,带 etag 缓存;`refresh` 强制重探。 */
301
+ list: async (options: { refresh?: boolean } = {}): Promise<AgentInfo[]> => {
302
+ const useEtag =
303
+ !options.refresh && this.#agents !== undefined && this.#agentsEtag !== undefined
304
+ const result = await this.call('agent.list', {
305
+ ...(options.refresh ? { refresh: true } : {}),
306
+ ...(useEtag ? { if_none_match: this.#agentsEtag } : {}),
307
+ })
308
+ if (result.not_modified && this.#agents) return this.#agents
309
+ this.#agents = result.agents
310
+ this.#agentsEtag = result.etag
311
+ return result.agents
312
+ },
313
+ diagnose: (id: string) => this.call('agent.diagnose', { id }),
314
+ }
315
+
316
+ readonly projects = {
317
+ list: async (): Promise<Project[]> => (await this.call('workspace.list', {})).projects,
318
+ create: (name: string, options: { gitInit?: boolean } = {}) =>
319
+ this.call('workspace.create', { name, git_init: options.gitInit ?? false }),
320
+ /** 克隆是长任务:返回 `Job`,`job.progress()` 看进度,`job.wait()` 等结束。 */
321
+ clone: async (url: string, options: { name?: string } = {}): Promise<Job> => {
322
+ const started = await this.call('workspace.clone', {
323
+ url,
324
+ ...(options.name !== undefined ? { name: options.name } : {}),
325
+ })
326
+ return this.#jobHandle(started.job_id)
327
+ },
328
+ /**
329
+ * 关联本机已有目录为项目(`workspace.link`):不移动、不复制。`path` 是 daemon 所在机器上的绝对路径
330
+ * 或 `~/…`,必须在 daemon 的 `workspace.link_roots` 之内;`name` 缺省取目录名。
331
+ * 越界 → `forbidden`,重名或已关联 → `exists`。
332
+ */
333
+ link: (path: string, options: { name?: string } = {}): Promise<Project> =>
334
+ this.call('workspace.link', {
335
+ path,
336
+ ...(options.name !== undefined ? { name: options.name } : {}),
337
+ }),
338
+ /** 解除关联(`workspace.unlink`):只从项目列表去掉,不动目录。对根目录下的项目 → `invalid`,有运行中的会话 → `busy`。 */
339
+ unlink: (name: string) => this.call('workspace.unlink', { name }),
340
+ /**
341
+ * 列本机目录供选择(`workspace.browse`):只列 `link_roots` 之内的子目录。`path` 缺省 = `roots` 的第一项;
342
+ * `showHidden` 也列 `.` 开头的目录。`link_roots` 为空 → `forbidden`。
343
+ */
344
+ browse: (
345
+ options: { path?: string; showHidden?: boolean } = {},
346
+ ): Promise<WorkspaceBrowseResult> =>
347
+ this.call('workspace.browse', {
348
+ ...(options.path !== undefined ? { path: options.path } : {}),
349
+ ...(options.showHidden !== undefined ? { show_hidden: options.showHidden } : {}),
350
+ }),
351
+ /**
352
+ * `workspace.branches`:列项目的分支(给「基于哪个分支」下拉框用)。`default_base` 是新会话的默认 base,
353
+ * `local` / `remote` 按最近提交时间倒序(各最多 200 个,`truncated` 为 true 表示被截断)。项目目录不是 git 仓库 → 报错。
354
+ */
355
+ branches: (project: string): Promise<WorkspaceBranchesResult> =>
356
+ this.call('workspace.branches', { project }),
357
+ rename: (from: string, to: string) => this.call('workspace.rename', { from, to }),
358
+ trash: (name: string) => this.call('workspace.trash', { name }),
359
+ trashList: async (): Promise<TrashEntry[]> =>
360
+ (await this.call('workspace.trash_list', {})).entries,
361
+ restore: (id: string) => this.call('workspace.restore', { id }),
362
+ purge: (id: string) => this.call('workspace.purge', { id }),
363
+ }
364
+
365
+ readonly worktrees = {
366
+ /**
367
+ * `workspace.worktrees`:anycon 建的全部 worktree(含已保留的、会话已删除的),带状态、未提交文件数、
368
+ * 自己的提交数、磁盘占用。`project` 缺省 = 全部项目。
369
+ */
370
+ list: async (options: { project?: string } = {}): Promise<WorktreeInfo[]> =>
371
+ (
372
+ await this.call(
373
+ 'workspace.worktrees',
374
+ options.project !== undefined ? { project: options.project } : {},
375
+ )
376
+ ).worktrees,
377
+ /**
378
+ * `workspace.remove_worktree`:删掉一个已保留或没有会话的 worktree。所属会话还没归档 → `busy`;
379
+ * 有未提交改动而没 `force` → `invalid`(`data.reason = 'uncommitted_changes'`)。`deleteBranch` 同时删分支
380
+ * (`git branch -D`,没合并的提交会丢)。
381
+ */
382
+ remove: (id: string, options: { force?: boolean; deleteBranch?: boolean } = {}) =>
383
+ this.call('workspace.remove_worktree', {
384
+ id,
385
+ ...(options.force !== undefined ? { force: options.force } : {}),
386
+ ...(options.deleteBranch !== undefined ? { delete_branch: options.deleteBranch } : {}),
387
+ }),
388
+ }
389
+
390
+ readonly sessions = {
391
+ list: async (params: SessionListParams = {}): Promise<SessionSummary[]> =>
392
+ (await this.call('session.list', params)).sessions,
393
+ /** 拿到已有会话的句柄。 */
394
+ get: async (id: string): Promise<Session> =>
395
+ this.#handle(await this.call('session.get', { session_id: id })),
396
+ create: async (params: CreateSessionParams): Promise<Session> => {
397
+ const attachments = params.attachments ?? []
398
+ // 带 prompt 或附件时 daemon 发第一条消息,要求 message_id(幂等键);空 prompt 当作没有(daemon 也这样处理)。
399
+ const hasMessage = Boolean(params.prompt) || attachments.length > 0
400
+ const summary = await this.call('session.create', {
401
+ agent: params.agent,
402
+ ...(params.project !== undefined ? { project: params.project } : {}),
403
+ settings: params.settings ?? {},
404
+ ...(params.workspace !== undefined ? { workspace: params.workspace } : {}),
405
+ ...(params.prompt ? { prompt: params.prompt } : {}),
406
+ ...(attachments.length > 0 ? { attachments: [...attachments] } : {}),
407
+ ...(hasMessage ? { message_id: params.messageId || randomId() } : {}),
408
+ })
409
+ const session = this.#handle(summary)
410
+ if (params.onPermission) session.policy = params.onPermission
411
+ return session
412
+ },
413
+ search: async (
414
+ query: string,
415
+ options: { project?: string; limit?: number } = {},
416
+ ): Promise<SearchHit[]> => (await this.call('session.search', { query, ...options })).hits,
417
+ }
418
+
419
+ // ---------- 附件(ADR-35) ----------
420
+
421
+ /**
422
+ * 把一张图片传到节点(`blob.put_begin` → 512 KiB 一块、最多 2 块在途的 `blob.put_chunk` → `blob.put_end`),
423
+ * 返回 daemon 的记录(`AttachmentRef`,含宽高),原样放进 `session.send(text, { attachments })` /
424
+ * `sessions.create({ attachments })`。同一个节点上的上传排队、一张一张传。
425
+ *
426
+ * SDK 不缩放、不重编码:调用方自己把图控制在长边 ≤ 2000 px、单张 ≤ 约 1.5 MiB(daemon 每张默认上限 10 MiB)。
427
+ * 被拒绝时抛 `AttachmentError`(`reason`:`too_large` / `quota` / `disk_full` / `hash_mismatch` / `mime_mismatch` / …)
428
+ * 或 `RpcError`(`unsupported`:mime 不在白名单;`busy`:这台设备同时进行的上传太多)。没传完的上传会被 `blob.discard`。
429
+ * 没上传完就不要了用 `signal`;传完了但不发了用 `discardAttachment()`(不丢的话 daemon 24 小时后回收)。
430
+ */
431
+ async uploadImage(bytes: Uint8Array, options: UploadImageOptions): Promise<AttachmentRef> {
432
+ const prev = this.#uploadTail
433
+ let release!: () => void
434
+ this.#uploadTail = new Promise<void>((resolve) => (release = resolve))
435
+ try {
436
+ await raceAbort(prev, options.signal)
437
+ return await uploadImage(this, bytes, options)
438
+ } finally {
439
+ // 排队时被中止:等前一张传完再放行下一张,保证同时只有一张在传
440
+ void prev.then(release)
441
+ }
442
+ }
443
+
444
+ /**
445
+ * 下载一个附件(`blob.get` 按 512 KiB 分页拉)。任何已配对设备都能读任何 blob;不存在 / 文件不见了 →
446
+ * `RpcError`(`not_found`,文件不见了时是 `AttachmentError`,`reason = 'blob'`)。
447
+ */
448
+ downloadAttachment(
449
+ attachment: AttachmentRef | string,
450
+ options: DownloadOptions = {},
451
+ ): Promise<DownloadedAttachment> {
452
+ const blobId = typeof attachment === 'string' ? attachment : attachment.blob_id
453
+ return downloadAttachment(this, blobId, options)
454
+ }
455
+
456
+ /**
457
+ * 丢掉一个已经上传、但还没被消息引用的附件(`blob.discard`,幂等:不存在也成功)。已被消息引用 →
458
+ * `AttachmentError`(`invalid`,`reason = 'in_use'`):它随会话删除。
459
+ */
460
+ async discardAttachment(attachment: AttachmentRef | string): Promise<void> {
461
+ const blobId = typeof attachment === 'string' ? attachment : attachment.blob_id
462
+ await this.call('blob.discard', { blob_id: blobId })
463
+ }
464
+
465
+ readonly permissions = {
466
+ /** 未决的权限请求(重连后先拉一次)。 */
467
+ list: async (sessionId?: string): Promise<PermissionRequest[]> =>
468
+ (await this.call('permission.list', sessionId ? { session_id: sessionId } : {})).requests,
469
+ }
470
+
471
+ /** 关闭这个节点的视图。由 `connect()` 创建的 Node 会同时关闭底层 hub 连接。 */
472
+ async close(): Promise<void> {
473
+ await this.#client.release(this, this.#ownsClient)
474
+ }
475
+
476
+ /** @internal Client 丢弃这个 Node 时调用。 */
477
+ markClosed(): void {
478
+ for (const timer of this.#permTimers.values()) clearTimeout(timer)
479
+ this.#permTimers.clear()
480
+ this.emit('closed')
481
+ this.#sessions.clear()
482
+ }
483
+
484
+ /** @internal */
485
+ markOwnsClient(): void {
486
+ this.#ownsClient = true
487
+ }
488
+
489
+ /** @internal Session.delete 之后。 */
490
+ forgetSession(id: string): void {
491
+ this.#sessions.delete(id)
492
+ }
493
+
494
+ // ---------- 权限 ----------
495
+
496
+ /** @internal 来自 `permission.request` 通知或会话事件流里的 `permission` 事件。 */
497
+ observePermission(request: PermissionRequest): void {
498
+ if (this.#permSeen.has(request.request_id)) return
499
+ const session = this.#sessions.get(request.session_id)
500
+ // 只管自己正在用的会话:不替别的设备(比如用户在 Web 上开的会话)做决定。
501
+ if (!session?.active) return
502
+ this.#permSeen.add(request.request_id)
503
+ if (this.#permSeen.size > 2000) {
504
+ const oldest = this.#permSeen.values().next().value
505
+ if (oldest !== undefined) this.#permSeen.delete(oldest)
506
+ }
507
+ void this.#decide(request, session)
508
+ }
509
+
510
+ async #decide(request: PermissionRequest, session: Session): Promise<void> {
511
+ const policy = session.policy ?? this.#policy
512
+ if (policy) {
513
+ try {
514
+ const decision = await policy(request, { session, node: this })
515
+ const params = decisionToParams(request, decision)
516
+ if (params) {
517
+ await this.call('permission.respond', params)
518
+ return
519
+ }
520
+ // 策略给了决定却无法执行(比如 'allow' 但没有 allow_once):不悄悄升级,告诉调用方。
521
+ if (decision !== undefined && decision !== null) {
522
+ this.emit(
523
+ 'permission_error',
524
+ new AnyconError(
525
+ 'no_matching_option',
526
+ `the permission policy decided on request ${request.request_id}, but it has no matching option (an 'allow' needs an allow_once option; nothing is upgraded to allow_always)`,
527
+ ),
528
+ request,
529
+ )
530
+ }
531
+ } catch (err) {
532
+ // 策略出错:落到超时兜底,并告诉调用方。已被别的设备答复(already_resolved)不算错。
533
+ if (!(err instanceof RpcError && err.code === 'already_resolved')) {
534
+ this.emit('permission_error', err, request)
535
+ }
536
+ }
537
+ }
538
+ this.#armPermissionTimeout(request)
539
+ }
540
+
541
+ #armPermissionTimeout(request: PermissionRequest): void {
542
+ if (this.#permissionTimeoutMs <= 0) return
543
+ const timer = setTimeout(() => {
544
+ this.#permTimers.delete(request.request_id)
545
+ const params =
546
+ decisionToParams(request, { deny: 'timeout' }) ?? decisionToParams(request, 'deny')
547
+ if (params) void this.call('permission.respond', params).catch(() => undefined)
548
+ }, this.#permissionTimeoutMs)
549
+ ;(timer as { unref?: () => void }).unref?.()
550
+ this.#permTimers.set(request.request_id, timer)
551
+ }
552
+
553
+ #onResolved(resolved: PermissionResolved): void {
554
+ const timer = this.#permTimers.get(resolved.request_id)
555
+ if (timer !== undefined) clearTimeout(timer)
556
+ this.#permTimers.delete(resolved.request_id)
557
+ this.emit('permission_resolved', resolved)
558
+ }
559
+
560
+ // ---------- 内部 ----------
561
+
562
+ #handle(summary: SessionSummary): Session {
563
+ const existing = this.#sessions.get(summary.id)
564
+ if (existing) {
565
+ existing.updateSummary(summary)
566
+ return existing
567
+ }
568
+ const session = new Session(this, summary)
569
+ this.#sessions.set(summary.id, session)
570
+ return session
571
+ }
572
+
573
+ #onSessionChanged(change: SessionChanged): void {
574
+ this.emit('session_changed', change)
575
+ if (change.deleted) {
576
+ this.#sessions.delete(change.session_id)
577
+ return
578
+ }
579
+ const session = this.#sessions.get(change.session_id)
580
+ if (!session) return
581
+ session.updateSummary({
582
+ ...session.summary,
583
+ title: change.title,
584
+ status: change.status,
585
+ archived: change.archived ?? session.summary.archived ?? false,
586
+ pending_permissions: change.pending_permissions,
587
+ updated_at_ms: change.updated_at_ms,
588
+ last_seq: Math.max(change.last_seq, session.summary.last_seq),
589
+ // worktree 的状态变化(creating → active / kept / removed …);通知里没带就保持原值。
590
+ ...(change.worktree ? { worktree: change.worktree } : {}),
591
+ })
592
+ }
593
+
594
+ async #resyncSessions(): Promise<void> {
595
+ for (const session of Array.from(this.#sessions.values())) {
596
+ try {
597
+ await session.resync()
598
+ } catch {
599
+ // 补事件失败不影响连接;调用方下次 history() 会拿到。
600
+ }
601
+ }
602
+ }
603
+
604
+ #job(id: string): JobRecord {
605
+ let rec = this.#jobs.get(id)
606
+ if (!rec) {
607
+ rec = { progress: [], done: undefined, waiters: new Set() }
608
+ this.#jobs.set(id, rec)
609
+ if (this.#jobs.size > 200) {
610
+ const oldest = this.#jobs.keys().next().value
611
+ if (oldest !== undefined) this.#jobs.delete(oldest)
612
+ }
613
+ }
614
+ return rec
615
+ }
616
+
617
+ #wake(rec: JobRecord): void {
618
+ for (const w of Array.from(rec.waiters)) w()
619
+ }
620
+
621
+ #jobHandle(id: string): Job {
622
+ const rec = this.#job(id)
623
+ const waitForChange = () =>
624
+ new Promise<void>((resolve) => {
625
+ const wake = () => {
626
+ rec.waiters.delete(wake)
627
+ resolve()
628
+ }
629
+ rec.waiters.add(wake)
630
+ })
631
+ return {
632
+ id,
633
+ progress: () => ({
634
+ async *[Symbol.asyncIterator]() {
635
+ let at = 0
636
+ for (;;) {
637
+ while (at < rec.progress.length) yield rec.progress[at++]!
638
+ if (rec.done) return
639
+ await waitForChange()
640
+ }
641
+ },
642
+ }),
643
+ wait: async () => {
644
+ while (!rec.done) await waitForChange()
645
+ if (!rec.done.ok) {
646
+ throw new AnyconError('job_failed', rec.done.error ?? `job ${id} failed`)
647
+ }
648
+ return rec.done
649
+ },
650
+ }
651
+ }
652
+ }