@anycon/sdk 0.3.0 → 0.4.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anycon/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Anycon TypeScript SDK (client side): pairing, connecting to nodes, sessions, and permissions. Works in Node and the browser.",
5
5
  "homepage": "https://github.com/anycon-ai/anycon/tree/main/packages/sdk#readme",
6
6
  "bugs": {
@@ -41,21 +41,21 @@
41
41
  "scripts": {
42
42
  "build": "bun run --cwd ../protocol build && tsc -p tsconfig.build.json",
43
43
  "typecheck": "tsc --noEmit -p tsconfig.json",
44
- "test": "bun test",
44
+ "test": "bun test --timeout 60000",
45
45
  "test:node": "node --import tsx --conditions source --test \"tests/**/*.test.ts\"",
46
46
  "lint": "oxlint -c ../../.oxlintrc.json src tests",
47
47
  "fmt": "oxfmt --config ../../.oxfmtrc.json src tests",
48
48
  "prepack": "rm -rf dist && bun run build"
49
49
  },
50
50
  "dependencies": {
51
- "@anycon/protocol": "0.3.0",
52
- "ws": "^8.22.1"
51
+ "@anycon/protocol": "0.4.1",
52
+ "ws": "^8.23.0"
53
53
  },
54
54
  "devDependencies": {
55
- "@types/bun": "^1.4.4",
56
- "@types/node": "^26.6.6",
55
+ "@types/bun": "^1.4.5",
56
+ "@types/node": "^26.6.8",
57
57
  "@types/ws": "^8.18.1",
58
- "fake-indexeddb": "^6.2.7",
58
+ "fake-indexeddb": "^6.2.8",
59
59
  "tsx": "^4.23.15",
60
60
  "typescript": "~5.9.3"
61
61
  },
package/src/index.ts CHANGED
@@ -118,6 +118,9 @@ export type {
118
118
  AttachmentRef,
119
119
  BrowseEntry,
120
120
  ClearableSetting,
121
+ ExtractRun,
122
+ RuleExtractDone,
123
+ RuleExtractResult,
121
124
  DiffAgainst,
122
125
  DiffFile,
123
126
  DiffFileStatus,
@@ -127,6 +130,7 @@ export type {
127
130
  ModelInfo,
128
131
  ModeInfo,
129
132
  NodeInfo,
133
+ NodeTwinLinkCodeResult,
130
134
  PairFailReason,
131
135
  PermissionOption,
132
136
  PermissionRequest,
@@ -145,6 +149,38 @@ export type {
145
149
  SessionWorkspace,
146
150
  SessionWorktree,
147
151
  SyncOutcome,
152
+ TodoHandler,
153
+ TwinAction,
154
+ TwinAnswerParams,
155
+ TwinChanged,
156
+ TwinDecision,
157
+ TwinDecisionOutcome,
158
+ TwinDryRunResult,
159
+ TwinGetParams,
160
+ TwinGetResult,
161
+ TwinLink,
162
+ TwinLinkParams,
163
+ TwinLinksResult,
164
+ TwinPeerAgent,
165
+ TwinPeerStatus,
166
+ TwinQuestion,
167
+ TwinQuestionNotice,
168
+ TwinQuestionStatus,
169
+ TwinQuestionsParams,
170
+ TwinQuestionsResult,
171
+ TwinRun,
172
+ TwinRunResult,
173
+ TwinRunsParams,
174
+ TwinRunsResult,
175
+ TwinStatsParams,
176
+ TwinStatsResult,
177
+ TwinScope,
178
+ TwinSetParams,
179
+ TwinSkipReason,
180
+ TwinState,
181
+ TwinToday,
182
+ TwinTrigger,
183
+ TwinUnlinkParams,
148
184
  TurnDoneReason,
149
185
  Usage,
150
186
  WorkspaceBranchesResult,
package/src/node.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  type JobDone,
12
12
  type JobProgress,
13
13
  type NodeInfo,
14
+ type NodeTwinLinkCodeResult,
14
15
  type PermissionRequest,
15
16
  type PermissionResolved,
16
17
  type Project,
@@ -23,6 +24,59 @@ import {
23
24
  type SessionSettings,
24
25
  type SessionSummary,
25
26
  type SessionWorkspace,
27
+ type Rule,
28
+ type RuleAddParams,
29
+ type RuleChanged,
30
+ type RuleExtractDone,
31
+ type RuleExtractResult,
32
+ type ExtractRun,
33
+ type RuleListParams,
34
+ type RuleListResult,
35
+ type RulePreviewParams,
36
+ type RulePreviewResult,
37
+ type RuleUpdateParams,
38
+ type TwinAnswerParams,
39
+ type TwinChanged,
40
+ type TwinDryRunResult,
41
+ type TwinGetParams,
42
+ type TwinGetResult,
43
+ type TwinLink,
44
+ type TwinLinkParams,
45
+ type TwinLinksResult,
46
+ type TwinPeerStatus,
47
+ type TwinQuestion,
48
+ type TwinQuestionNotice,
49
+ type TwinQuestionsParams,
50
+ type TwinQuestionsResult,
51
+ type TwinRunsParams,
52
+ type TwinRunsResult,
53
+ type TwinStatsParams,
54
+ type TwinStatsResult,
55
+ type TwinSetParams,
56
+ type TwinUnlinkParams,
57
+ type Todo,
58
+ type TodoAddParams,
59
+ type TodoChanged,
60
+ type TodoDispatchParams,
61
+ type TodoDispatchPreviewParams,
62
+ type TodoDispatchPreviewResult,
63
+ type TodoDispatchResult,
64
+ type TodoEventNotice,
65
+ type TodoHistoryParams,
66
+ type TodoHistoryResult,
67
+ type TodoListParams,
68
+ type TodoListResult,
69
+ type TodoRepeatPreviewParams,
70
+ type TodoRepeatPreviewResult,
71
+ type TodoUpdateParams,
72
+ type RepeatStateChanged,
73
+ type RepeatStateClearResult,
74
+ type RepeatStateDeleteResult,
75
+ type RepeatStateGetResult,
76
+ type RepeatStateListParams,
77
+ type RepeatStateListResult,
78
+ type RepeatStateSetResult,
79
+ type RepeatStateUnseenResult,
26
80
  type WorkspaceBranchesResult,
27
81
  type WorkspaceBrowseResult,
28
82
  type WorkspaceChanged,
@@ -80,6 +134,22 @@ export interface NodeEvents {
80
134
  permission_error: [error: unknown, request: PermissionRequest]
81
135
  agent_changed: [AgentListResult]
82
136
  workspace_changed: [WorkspaceChanged]
137
+ /** 清单有项被新建、修改或删除(`todo.changed`,发给所有在线客户端,包括发起的那一个)。 */
138
+ todo_changed: [TodoChanged]
139
+ /** 清单项的「经过」多了一条(`todo.event`,docs/spec/daemon.md § 22;发给所有在线客户端)。`text` 是 agent 写的,按不可信内容渲染。 */
140
+ todo_event: [TodoEventNotice]
141
+ /**
142
+ * 一个周期项(模板)的跨次状态被写、删或清空(`todo.state_changed`,docs/spec/daemon.md § 26.11):只有模板 id 和条数,
143
+ * 不带键和值;要看内容用 `node.todos.stateList`。
144
+ */
145
+ todo_state_changed: [RepeatStateChanged]
146
+ /** 规则有一条被新建、修改或删除(`rule.changed`,docs/spec/daemon.md § 23;发给所有在线客户端,包括发起的那一个)。`last_injected_ms` 和 `last_referenced_ms` 的变化不通知;daemon 标过期、人恢复时通知。 */
147
+ rule_changed: [RuleChanged]
148
+ /** 一次提炼结束,按 run.id 对应发起的调用;所有在线客户端都会收到。 */
149
+ rule_extract_done: [RuleExtractDone]
150
+ // Twin 状态和问题变化,包含别的设备的回答和作废。
151
+ twin_changed: [TwinChanged]
152
+ twin_question: [TwinQuestionNotice]
83
153
  }
84
154
 
85
155
  export interface NodeOptions {
@@ -192,6 +262,27 @@ export class Node extends Emitter<NodeEvents> {
192
262
  rpc.onNotification<WorkspaceChanged>(METHODS.WORKSPACE_CHANGED, (c) => {
193
263
  this.emit('workspace_changed', c)
194
264
  })
265
+ rpc.onNotification<TodoChanged>(METHODS.TODO_CHANGED, (c) => {
266
+ this.emit('todo_changed', c)
267
+ })
268
+ rpc.onNotification<TodoEventNotice>(METHODS.TODO_EVENT, (e) => {
269
+ this.emit('todo_event', e)
270
+ })
271
+ rpc.onNotification<RepeatStateChanged>(METHODS.TODO_STATE_CHANGED, (c) => {
272
+ this.emit('todo_state_changed', c)
273
+ })
274
+ rpc.onNotification<RuleChanged>(METHODS.RULE_CHANGED, (c) => {
275
+ this.emit('rule_changed', c)
276
+ })
277
+ rpc.onNotification<RuleExtractDone>(METHODS.RULE_EXTRACT_DONE, (done) => {
278
+ this.emit('rule_extract_done', done)
279
+ })
280
+ rpc.onNotification<TwinChanged>(METHODS.TWIN_CHANGED, (change) =>
281
+ this.emit('twin_changed', change),
282
+ )
283
+ rpc.onNotification<TwinQuestionNotice>(METHODS.TWIN_QUESTION, (notice) =>
284
+ this.emit('twin_question', notice),
285
+ )
195
286
  rpc.onNotification<JobProgress>(METHODS.JOB_PROGRESS, (p) => {
196
287
  const rec = this.#job(p.job_id)
197
288
  rec.progress.push(p)
@@ -498,6 +589,187 @@ export class Node extends Emitter<NodeEvents> {
498
589
  await this.call('blob.discard', { blob_id: blobId })
499
590
  }
500
591
 
592
+ /**
593
+ * 节点上的清单(`todo.*`,节点 `capabilities.todo` 为 true 才有;旧节点 → `RpcError`,`unsupported`)。薄封装:不做离线缓存,
594
+ * 也不重放;节点离线时这些调用和别的请求一样失败。
595
+ */
596
+ readonly todos = {
597
+ /**
598
+ * `todo.list`:缺省只给没关闭的项,按 `(updated_ms, id)` 从新到旧;一页最多 `limit`(缺省 200、上限 1000)项,
599
+ * 并受 1 MiB 的字节预算限制,所以可能更少。`has_more` 时用最后一项的 `{ updated_ms, id }` 作为 `before` 取下一页,
600
+ * 翻页期间被改过的项可能出现两次(按 `id` 去重)或被跳过(`todo_changed` 会补上)。
601
+ */
602
+ list: (params: TodoListParams = {}): Promise<TodoListResult> => this.call('todo.list', params),
603
+ /** `todo.get`:读一项(只读,不审计、不通知)。项不存在 → `RpcError`(`not_found`),`id` 不是小写 UUID → `invalid`(`data.field = 'id'`)。 */
604
+ get: (id: string): Promise<Todo> => this.call('todo.get', { id }),
605
+ /**
606
+ * `todo.add`。`id` 缺省时 SDK 生成一个 UUID(小写带连字符;自己给的 id 必须是这个写法,daemon 不做规范化,别的写法 → `invalid`,`data.field = 'id'`);超时后要重试就传同一个:`id` 已经存在时 daemon 原样返回已有的那一项,
607
+ * 不会出现第二项。标题为空 / 超长、正文超长、`id` 不是 UUID、清单已满 → `RpcError`(`invalid`,见 `data.field` /
608
+ * `data.reason`:`too_many` / `too_many_unreviewed`)。`source` 由 daemon 填;`agent: true` 表示这是 agent 加的。
609
+ */
610
+ add: (params: Omit<TodoAddParams, 'id'> & { id?: string }): Promise<Todo> =>
611
+ this.call('todo.add', { ...params, id: params.id ?? randomId() }),
612
+ /** `todo.update`:只带要改的字段;`clear` 列出要清空的可选字段(`project` / `due_ms` / `repeat`)。`repeat` 是周期规则(docs/spec/daemon.md § 26.9,节点 `capabilities.todo_repeat` 为 true 才有;只由人设置,自报 `mcp` 或 `agent: true` → `forbidden`)。项不存在 → `RpcError`(`not_found`)。 */
613
+ update: (params: TodoUpdateParams): Promise<Todo> => this.call('todo.update', params),
614
+ /**
615
+ * `todo.delete`:物理删除。项不存在 → `RpcError`(`not_found`)。给了 `ifUpdatedMs`,而这一项现在的 `updated_ms` 不是它:
616
+ * 什么都不删,`RpcError`(`invalid`,`reason = 'changed'`,`updatedMs` 是现在的值)。同一项的 `updated_ms` 每次修改都严格递增,
617
+ * 所以「读到之后没被改过」可以用它来判断。
618
+ */
619
+ delete: async (id: string, opts: { ifUpdatedMs?: number } = {}): Promise<void> => {
620
+ await this.call('todo.delete', {
621
+ id,
622
+ ...(opts.ifUpdatedMs !== undefined ? { if_updated_ms: opts.ifUpdatedMs } : {}),
623
+ })
624
+ },
625
+ /**
626
+ * `todo.dispatch`(docs/spec/daemon.md § 22):从一项开一个会话,关联、记「经过」、算 `activity`,全部由 daemon 做,不要自己拼
627
+ * `session.create`。成功得到更新后的项(`state: 'working'`、`sessions` 多一个)和会话。第一条消息由 daemon 生成,调用方不能另给。
628
+ * `no_push` 缺省 `true`(「不 push、不开 PR」):所选 agent 没有声明这个选项而它为 `true` → `RpcError`(`unsupported`,
629
+ * `data.reason = 'no_push'`),要派给这样的 agent 必须明确传 `false`。别的错误:项已关闭 → `invalid`(`data.reason = 'closed'`);
630
+ * 没有项目 → `invalid`(`data.field = 'project'`);`message_id` 缺省时 SDK 生成一个:超时后重试传同一个,daemon 返回第一次的结果、不开第二个会话;已派发 20 次 → `invalid`(`data.reason = 'too_many_sessions'`);
631
+ * 项目不存在 / 项不存在 → `not_found`;自报了 `mcp` 的本机连接 → `forbidden`;会话建不起来时这一项原样不变。
632
+ * `workspace` 缺省时能开 worktree 的项目用新的 worktree,否则在项目目录里(没有隔离)。
633
+ */
634
+ dispatch: (
635
+ params: Omit<TodoDispatchParams, 'message_id'> & { message_id?: string },
636
+ ): Promise<TodoDispatchResult> =>
637
+ this.call('todo.dispatch', { ...params, message_id: params.message_id ?? randomId() }),
638
+ /**
639
+ * `todo.dispatch_preview`:此刻 `dispatch` 会发出的第一条消息,一字不差(不开会话、不审计、不发推送通知;唯一的副作用是先把排着的结果记进「经过」,和 `dispatch` 之前的那一步一样)。
640
+ * `no_push` 缺省 `true`。项不存在 → `not_found`,已关闭 → `invalid`(`data.reason = 'closed'`),自报了 `mcp` 的本机连接 → `forbidden`。
641
+ */
642
+ dispatchPreview: (params: TodoDispatchPreviewParams): Promise<TodoDispatchPreviewResult> =>
643
+ this.call('todo.dispatch_preview', params),
644
+ /**
645
+ * `todo.repeat_now`(docs/spec/daemon.md § 26.9):现在执行一次周期项,得到新复制出的一项;不动周期项的下一次时间。节点 `capabilities.todo_repeat_interval` 为 true 才有。
646
+ * 项不存在 → `not_found`;不是周期项 / 已关闭 / 未收下 / 上一份还没关闭 → `invalid`(`data.reason` = `not_template` / `closed` / `unreviewed` / `previous_open`,最后一种带 `data.todo_id`);
647
+ * 清单满了 → `invalid`(`data.reason = 'too_many'`);自报了 `mcp` 的本机连接 → `forbidden`。
648
+ */
649
+ repeatNow: (id: string): Promise<Todo> => this.call('todo.repeat_now', { id }),
650
+ /**
651
+ * `todo.repeat_preview`(docs/spec/daemon.md § 26.11):周期项(模板)复制出来的下一项交给 Twin 时会发出的第一条消息,`segments`
652
+ * 按来源分段(`title` / `body` 是人写的,其余是 daemon 加的);和真正派发同一个组装函数。`keep_state` / `state_hint_off` 给了就代替
653
+ * 模板上存着的值(还没保存的开关);`no_push` 缺省 `true`。`state_usage_text` 是用模板 id 写的「抄进正文」版本。
654
+ * 节点 `capabilities.todo_repeat_state` 为 true 才有。不是周期项 → `invalid`(`data.reason = 'not_template'`);自报了 `mcp` 的连接 → `forbidden`。
655
+ */
656
+ repeatPreview: (params: TodoRepeatPreviewParams): Promise<TodoRepeatPreviewResult> =>
657
+ this.call('todo.repeat_preview', params),
658
+ /**
659
+ * 周期项的跨次状态(`todo.state_*`,docs/spec/daemon.md § 26.11;节点 `capabilities.todo_repeat_state` 为 true 才有)。`id` 是模板或它复制出来的
660
+ * 某一项,两者读写模板的同一份。键:非空、≤ 200 字节、不含控制字符;值:≤ 1 KiB。错误:不是周期项也不是它的复制 → `invalid`
661
+ * (`data.reason = 'not_repeating'`);模板已删除 → `'template_gone'`;模板没开 `keep_state` → `'state_off'`;`origin_session`
662
+ * 不是这个模板的某次复制派出的会话 → `forbidden`(`'origin_session'`)。键和值是用户内容,按不可信内容显示。
663
+ */
664
+ stateGet: (id: string, key: string): Promise<RepeatStateGetResult> =>
665
+ this.call('todo.state_get', { id, key }),
666
+ /** `todo.state_set`:写一个键(已有就覆盖);满 2 000 条时淘汰最久没被写过的(`evicted`)。`value` 缺省空串。 */
667
+ stateSet: (id: string, key: string, value = ''): Promise<RepeatStateSetResult> =>
668
+ this.call('todo.state_set', { id, key, value }),
669
+ /** `todo.state_delete`:删一个键;没存着时 `deleted = false`,不是错误。 */
670
+ stateDelete: (id: string, key: string): Promise<RepeatStateDeleteResult> =>
671
+ this.call('todo.state_delete', { id, key }),
672
+ /** `todo.state_list`:按键从小到大翻页(`after` 填上一页最后一条的 `key`;`limit` 缺省 200、上限 1000),`prefix` 过滤;`total` 是总条数,`matched` 是匹配前缀的条数。 */
673
+ stateList: (params: RepeatStateListParams): Promise<RepeatStateListResult> =>
674
+ this.call('todo.state_list', params),
675
+ /** `todo.state_unseen`:给一组键(≤ 2 000 个),返回其中没存着的(按给的顺序、去重)。 */
676
+ stateUnseen: (id: string, keys: string[]): Promise<RepeatStateUnseenResult> =>
677
+ this.call('todo.state_unseen', { id, keys }),
678
+ /** `todo.state_clear`:清空这个模板的全部状态(开关关着时也能清)。只由人调用:自报 `mcp` 的连接 → `forbidden`。 */
679
+ stateClear: (id: string): Promise<RepeatStateClearResult> =>
680
+ this.call('todo.state_clear', { id }),
681
+ /** `todo.history`:这一项的「经过」,按 `seq` 从新到旧;`has_more` 时用最后一条的 `seq` 作为 `before_seq` 取下一页(`limit` 缺省 50、上限 200)。 */
682
+ history: (params: TodoHistoryParams): Promise<TodoHistoryResult> =>
683
+ this.call('todo.history', params),
684
+ }
685
+
686
+ /**
687
+ * 节点上的决策档案(`rule.*`,docs/spec/daemon.md § 23;节点 `capabilities.rules` 为 true 才有,旧节点 → `RpcError`,`unsupported`):
688
+ * 用户自己的做法,生效的规则注入派发出去的会话的系统提示。规则只影响 agent 怎么判断,不影响任何权限。薄封装:不做离线缓存,也不重放。
689
+ * 规则的文字是用户内容,经过 `rule.add` 进来的、agent 写的文字会进之后每个会话的系统提示:生效之前要人确认。
690
+ */
691
+ readonly rules = {
692
+ /** 提炼会话里新的决策点;points 为 0 时没有 run,否则按 run.id 等 rule_extract_done。 */
693
+ extract: (sessionId: string): Promise<RuleExtractResult> =>
694
+ this.call('rule.extract', { session_id: sessionId }),
695
+ /** 最近的提炼记录与今天所有判断位置合计的调用次数;省略 limit 时为 20。 */
696
+ extractRuns: async (
697
+ options: { sessionId?: string; limit?: number } = {},
698
+ ): Promise<{ runs: ExtractRun[]; usedToday: number; dailyCalls: number }> => {
699
+ const result = await this.call('rule.extract_runs', {
700
+ ...(options.sessionId !== undefined ? { session_id: options.sessionId } : {}),
701
+ ...(options.limit !== undefined ? { limit: options.limit } : {}),
702
+ })
703
+ return { runs: result.runs, usedToday: result.used_today, dailyCalls: result.daily_calls }
704
+ },
705
+ /**
706
+ * `rule.list`:全部规则(总数上限 300,不翻页),按创建时间从早到晚;`status` / `project` 过滤(`project` 不含全节点规则)。
707
+ * `budget` 是注入的字数预算(只算生效的规则,不随过滤条件变):一个这个项目的会话拿到的规则文字是 `node_bytes + projects[项目]`,上限 `cap`。
708
+ */
709
+ list: (params: RuleListParams = {}): Promise<RuleListResult> => this.call('rule.list', params),
710
+ /**
711
+ * `rule.add`。`id` 缺省时 SDK 生成一个 UUID(小写带连字符);超时后要重试就传同一个:`id` 已经存在时 daemon 原样返回已有的那一条。
712
+ * `sync` 缺省 `node`;`group` 仅允许非待确认的全节点规则。SDK 只写当前节点,不负责跨节点同步。
713
+ * `status` 缺省 `active`;`agent: true`(调用方自报是 agent)或来自自报了 `mcp` 的本机连接时,状态强制为 `pending`、来源强制为 `agent`。
714
+ * 文字为空 / 超过 600 个码点 / 含换行以外的控制字符、总数已满 300(`reason = 'too_many'`)、
715
+ * 生效后会超出注入的字数上限(`reason = 'over_budget'`,`bytes` 和 `cap` 是这次改动之后的字节数和上限)→ `RpcError`(`invalid`)。
716
+ */
717
+ add: (params: Omit<RuleAddParams, 'id'> & { id?: string }): Promise<Rule> =>
718
+ this.call('rule.add', { ...params, id: params.id ?? randomId() }),
719
+ /**
720
+ * `rule.update`:只带要改的字段;`clear` 列出要清空的可选字段(`project`)。没有任何字段真的变了就是空操作。
721
+ * `if_updated_ms` 给了而和现在的不同 → `RpcError`(`invalid`,`reason = 'changed'`,`updatedMs` 是现在的值)。
722
+ * 变成生效、或者改了生效的规则的文字 / 项目而超出字数上限 → `over_budget`。规则不存在 → `not_found`;
723
+ * 自报了 `mcp` 的本机连接 → `forbidden`。
724
+ * `stale: false` 恢复一条过期的规则(`Rule.stale`:生效的规则 60 天没被用到,daemon 标上它;过期的不注入、不计字数预算),
725
+ * 和变成生效一样过字数检查,超出 → `over_budget`;`stale: true` → `invalid`(`field = 'stale'`),过期只由 daemon 标。
726
+ */
727
+ update: (params: RuleUpdateParams): Promise<Rule> => this.call('rule.update', params),
728
+ /** `rule.delete`:物理删除;`ifUpdatedMs` 的语义同 `update`。规则不存在 → `not_found`;自报了 `mcp` 的本机连接 → `forbidden`。 */
729
+ delete: async (id: string, opts: { ifUpdatedMs?: number } = {}): Promise<void> => {
730
+ await this.call('rule.delete', {
731
+ id,
732
+ ...(opts.ifUpdatedMs !== undefined ? { if_updated_ms: opts.ifUpdatedMs } : {}),
733
+ })
734
+ },
735
+ /** `rule.preview`:现在开一个这个项目的会话(缺省:不属于任何项目的会话)会注入的那段文字、用到的规则和它的字节数。只读。 */
736
+ preview: (params: RulePreviewParams = {}): Promise<RulePreviewResult> =>
737
+ this.call('rule.preview', params),
738
+ }
739
+
740
+ // Twin 的薄封装:需要 capabilities.twin,不缓存、不重放;问题和理由是模型写的纯文字。
741
+ readonly twin = {
742
+ // `requester` 缺省是本机 Twin;给一台 Twin 设备的 id,读被使用的节点给这条连接的范围。
743
+ get: (params: TwinGetParams = {}): Promise<TwinGetResult> => this.call('twin.get', params),
744
+ set: (params: TwinSetParams): Promise<TwinGetResult> => this.call('twin.set', params),
745
+ wake: async (): Promise<void> => {
746
+ await this.call('twin.wake', {})
747
+ },
748
+ // 判断后端最长可跑十五分钟;调用方仍可通过标准 RPC 选项收紧时限或取消。
749
+ dryRun: (options: RequestOptions = {}): Promise<TwinDryRunResult> =>
750
+ this.call('twin.dry_run', {}, { timeoutMs: 16 * 60_000, ...options }),
751
+ runs: (params: TwinRunsParams = {}): Promise<TwinRunsResult> => this.call('twin.runs', params),
752
+ // 最近几个本地日的统计(只读、只统计本机 Twin);`days` 1..=90,缺省 7。节点 `capabilities.twin_stats` 为 true 才有,旧节点回 `unsupported`。
753
+ stats: (params: TwinStatsParams = {}): Promise<TwinStatsResult> =>
754
+ this.call('twin.stats', params),
755
+ questions: (params: TwinQuestionsParams = {}): Promise<TwinQuestionsResult> =>
756
+ this.call('twin.questions', params),
757
+ answer: (params: TwinAnswerParams): Promise<TwinQuestion> => this.call('twin.answer', params),
758
+ // Twin 连接(ADR-56)。`link` 的 `code` 是被使用的节点发的短码:只经内存从 `twinLinkCode()` 的结果交给这里,
759
+ // SDK 不缓存、不写日志。`link` / `unlink` 在使用别的节点的那一端调用;`peerStatus` 在被使用的节点上由 Twin 设备调用。
760
+ link: (params: TwinLinkParams): Promise<TwinLink> => this.call('twin.link', params),
761
+ links: (): Promise<TwinLinksResult> => this.call('twin.links', {}),
762
+ unlink: async (params: TwinUnlinkParams): Promise<void> => {
763
+ await this.call('twin.unlink', params)
764
+ },
765
+ peerStatus: (): Promise<TwinPeerStatus> => this.call('twin.peer_status', {}),
766
+ }
767
+
768
+ /** `node.twin_link_code`:在被使用的节点上开一次只接受 Twin 设备的短码配对(10 分钟);短码是秘密,只交给 `twin.link`。 */
769
+ twinLinkCode(): Promise<NodeTwinLinkCodeResult> {
770
+ return this.call('node.twin_link_code', {})
771
+ }
772
+
501
773
  readonly permissions = {
502
774
  /** 未决的权限请求(重连后先拉一次)。 */
503
775
  list: async (sessionId?: string): Promise<PermissionRequest[]> =>
package/src/session.ts CHANGED
@@ -31,7 +31,7 @@ import type {
31
31
  } from '@anycon/protocol'
32
32
 
33
33
  import { AsyncQueue } from './async-queue.js'
34
- import { AnyconError, NodeOffline } from './errors.js'
34
+ import { AnyconError, ConnectionError, NodeOffline } from './errors.js'
35
35
  import type { Node } from './node.js'
36
36
  import type { PermissionPolicy } from './permissions.js'
37
37
 
@@ -139,6 +139,46 @@ export interface ArchiveOptions {
139
139
  worktree?: WorktreeDisposal
140
140
  }
141
141
 
142
+ /**
143
+ * 补历史期间扣住实时事件的闸门(`events({ fromSeq })` 和重连后的 `Session.resync()` 共用)。
144
+ * 补历史时,实时事件到达的时机不受控:它们可能比还没补完的历史更新。如果直接放行,消费者先看到较新的 seq,
145
+ * 随后补来的较旧事件会被「seq 不大于已见过的最大值」的去重丢掉。所以补历史期间 `live()` 只扣住,
146
+ * 补完(`release()`)之后按 seq 接在历史后面;`emit` 负责去重和保序。
147
+ */
148
+ class ReplayGate {
149
+ readonly #emit: (se: SessionEvent) => void
150
+ readonly #held: SessionEvent[] = []
151
+ #replaying: boolean
152
+
153
+ constructor(emit: (se: SessionEvent) => void, replaying: boolean) {
154
+ this.#emit = emit
155
+ this.#replaying = replaying
156
+ }
157
+
158
+ get replaying(): boolean {
159
+ return this.#replaying
160
+ }
161
+
162
+ /** 实时事件:补历史期间扣住,之后直接放行。 */
163
+ live(se: SessionEvent): void {
164
+ if (this.#replaying) this.#held.push(se)
165
+ else this.#emit(se)
166
+ }
167
+
168
+ /** 补历史没有补完而放弃:扣住的实时事件丢掉(不放出),之后的实时事件直接放行。 */
169
+ discard(): void {
170
+ this.#replaying = false
171
+ this.#held.length = 0
172
+ }
173
+
174
+ /** 补历史结束:按 seq 放出扣住的实时事件,之后的实时事件直接放行。 */
175
+ release(): void {
176
+ this.#replaying = false
177
+ for (const se of this.#held.toSorted((a, b) => a.seq - b.seq)) this.#emit(se)
178
+ this.#held.length = 0
179
+ }
180
+ }
181
+
142
182
  /** `session.delete` 的选项。 */
143
183
  export interface DeleteOptions extends ArchiveOptions {
144
184
  /** 同时删掉 worktree 的分支(`git branch -D`),分支上没合并的提交会丢。只有 worktree 也被删掉时才生效。 */
@@ -176,6 +216,9 @@ export class Session {
176
216
  readonly #subs = new Set<Subscriber>()
177
217
  #watched = false
178
218
  #watchChain: Promise<unknown> = Promise.resolve()
219
+ #resyncChain: Promise<unknown> = Promise.resolve()
220
+ /** `resync()` 补历史期间的闸门;有它时 `dispatch` 的实时事件先扣住。 */
221
+ #resyncGate: ReplayGate | undefined
179
222
 
180
223
  /** @internal 由 `Node` 创建。 */
181
224
  constructor(node: Node, summary: SessionSummary) {
@@ -329,17 +372,13 @@ export class Session {
329
372
  const onAbort = () => queue.fail(options.signal?.reason ?? new Error('aborted'))
330
373
  // 已经推给消费者的最大 seq;补历史和实时事件会重叠,按它去重、保序。
331
374
  let high = options.fromSeq ?? 0
332
- let replaying = options.fromSeq !== undefined
333
- const held: SessionEvent[] = []
334
375
  const emit = (se: SessionEvent) => {
335
376
  if (se.seq <= high) return
336
377
  high = se.seq
337
378
  queue.push(this.#toStream(se))
338
379
  }
339
- const live = (se: SessionEvent) => {
340
- if (replaying) held.push(se)
341
- else emit(se)
342
- }
380
+ const gate = new ReplayGate(emit, options.fromSeq !== undefined)
381
+ const live = (se: SessionEvent) => gate.live(se)
343
382
  release = this.#subscribe(live)
344
383
  options.signal?.addEventListener('abort', onAbort, { once: true })
345
384
  queue.onDispose(this.#guardQueue(queue, 0))
@@ -347,9 +386,7 @@ export class Session {
347
386
  await this.#ensureWatching()
348
387
  if (options.fromSeq !== undefined) {
349
388
  await this.#replay(emit, options.fromSeq)
350
- replaying = false
351
- for (const se of held.toSorted((a, b) => a.seq - b.seq)) emit(se)
352
- held.length = 0
389
+ gate.release()
353
390
  }
354
391
  })().catch((err: unknown) => queue.fail(err))
355
392
  return queue
@@ -483,8 +520,13 @@ export class Session {
483
520
 
484
521
  // ---------- 内部:事件分发 ----------
485
522
 
486
- /** @internal Node 收到 `session.event` 时调用。按 seq 去重。 */
523
+ /** @internal Node 收到 `session.event` 时调用。按 seq 去重;`resync()` 补历史期间先扣住。 */
487
524
  dispatch(se: SessionEvent): void {
525
+ if (this.#resyncGate) this.#resyncGate.live(se)
526
+ else this.#deliver(se)
527
+ }
528
+
529
+ #deliver(se: SessionEvent): void {
488
530
  if (se.seq <= this.#lastSeq) return
489
531
  this.#lastSeq = se.seq
490
532
  for (const sub of Array.from(this.#subs)) {
@@ -502,20 +544,46 @@ export class Session {
502
544
  }
503
545
  }
504
546
 
505
- /** @internal 重新握手后:重新 watch 并补齐错过的事件。 */
506
- async resync(): Promise<void> {
547
+ /**
548
+ * @internal 重新握手 / 重连之后:重新 watch 并补齐错过的事件。
549
+ *
550
+ * 补历史(`session.history`,分页)期间到达的实时事件先扣住(和 `events({ fromSeq })` 同一个闸门),补完之后
551
+ * 按 seq 接在历史后面,所以订阅者看到的 seq 严格递增、每个只有一次,不会因为较新的实时事件先到而丢掉较旧的历史事件。
552
+ * `since` 在重新 watch 之前取,补的是「断线前最后一次看到的 seq」之后的全部。
553
+ * 补历史没补完(`watch` 或 `history` 抛错)时,看通道还在不在:
554
+ * - 通道没了(节点不在线,或错误是 `ConnectionError` / `NodeOffline`;最常见的原因是补历史期间又断了一次):
555
+ * 扣住的实时事件**丢掉**,`lastSeq` 停在已经交付的地方。daemon 持久化事件,下一次 `ready` 的 `resync()`
556
+ * 从这里补,补回的历史把丢掉的实时事件也带上,仍然按序、每个一次。如果放出它们,`lastSeq` 会越过还没补到的历史,
557
+ * 那段历史永远补不回来;
558
+ * - 通道还在、是别的原因失败(比如 `history` 答 `internal`):扣住的实时事件照样按序放出(不丢、不乱序、不重复),
559
+ * 没补上的历史留下一个空档,调用方之后用 `history({ afterSeq })` 取回。
560
+ * 错误向上抛(`Node` 吞掉它)。丢掉的 `permission` 事件会随下一次补历史重新交付并交给权限策略(`permission.request`
561
+ * 通知不经过会话的事件分发,`Node` 直接处理,不受影响)。同一个会话的多次 `resync()` 排队执行。
562
+ */
563
+ resync(): Promise<void> {
564
+ const run = this.#resyncChain.then(() => this.#resyncOnce())
565
+ this.#resyncChain = run.catch(() => undefined)
566
+ return run
567
+ }
568
+
569
+ async #resyncOnce(): Promise<void> {
507
570
  if (this.#subs.size === 0) return
508
- this.#watched = false
509
- await this.#ensureWatching()
510
571
  const since = this.#lastSeq
511
- let after = since
512
- for (let guard = 0; guard < 50; guard++) {
513
- const page = await this.history({ afterSeq: after, limit: 1000 })
514
- for (const se of page.events) this.dispatch(se)
515
- const last = page.events.at(-1)
516
- if (!page.has_more || !last || last.seq <= after) break
517
- after = last.seq
572
+ const gate = new ReplayGate((se) => this.#deliver(se), true)
573
+ this.#resyncGate = gate
574
+ try {
575
+ this.#watched = false
576
+ await this.#ensureWatching()
577
+ await this.#replay((se) => this.#deliver(se), since)
578
+ } catch (err) {
579
+ this.#resyncGate = undefined
580
+ if (!this.node.online || err instanceof ConnectionError || err instanceof NodeOffline) {
581
+ gate.discard()
582
+ } else gate.release()
583
+ throw err
518
584
  }
585
+ this.#resyncGate = undefined
586
+ gate.release()
519
587
  }
520
588
 
521
589
  #subscribe(sub: Subscriber): () => void {
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** SDK 版本。与 package.json 一致(`tests/version.test.ts` 守着)。 */
2
- export const SDK_VERSION = '0.3.0'
2
+ export const SDK_VERSION = '0.4.1'