@linxin666/dsh-remote-bridge 0.4.7 → 0.4.9

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 (78) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +93 -26
  3. package/README.zh.md +91 -26
  4. package/icon.svg +3 -0
  5. package/lib/client.js +274 -253
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +8891 -2433
  8. package/lib/types/client/PairEntry.d.ts +2 -2
  9. package/lib/types/client/PairPanel.d.ts +10 -2
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/locales.d.ts +10 -14
  12. package/lib/types/client/semantic.d.ts +9 -5
  13. package/lib/types/core/approvals.d.ts +24 -0
  14. package/lib/types/core/commands.d.ts +59 -0
  15. package/lib/types/core/connection.d.ts +124 -5
  16. package/lib/types/core/delta.d.ts +101 -0
  17. package/lib/types/core/devices.d.ts +98 -2
  18. package/lib/types/core/dsh-frames.d.ts +155 -4
  19. package/lib/types/core/envelope.d.ts +34 -0
  20. package/lib/types/core/extension.d.ts +144 -0
  21. package/lib/types/core/hub.d.ts +96 -20
  22. package/lib/types/core/jobs.d.ts +204 -0
  23. package/lib/types/core/liveactivity.d.ts +324 -0
  24. package/lib/types/core/protocol.d.ts +491 -2
  25. package/lib/types/core/push.d.ts +178 -0
  26. package/lib/types/core/questions.d.ts +109 -9
  27. package/lib/types/core/session-meta.d.ts +55 -1
  28. package/lib/types/core/squads.d.ts +130 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/core/wire.d.ts +1 -1
  32. package/lib/types/core/ws-frames.d.ts +11 -0
  33. package/lib/types/host/apns.d.ts +151 -0
  34. package/lib/types/host/squads-ledger.d.ts +39 -0
  35. package/lib/types/host/squads.d.ts +77 -0
  36. package/lib/types/host/usage-stats.d.ts +75 -0
  37. package/lib/types/host/watchers.d.ts +88 -0
  38. package/lib/types/host/websocket.d.ts +8 -1
  39. package/lib/types/index.d.ts +34 -3
  40. package/lib/types/mount-once.d.ts +55 -0
  41. package/locale/en.json +6 -0
  42. package/locale/ru.json +6 -0
  43. package/locale/zh.json +6 -0
  44. package/package.json +20 -14
  45. package/src/client/PairEntry.tsx +58 -31
  46. package/src/client/PairPanel.tsx +181 -97
  47. package/src/client/icons.tsx +17 -60
  48. package/src/client/locales.ts +15 -23
  49. package/src/client/panel.module.css +239 -186
  50. package/src/client/semantic.ts +10 -6
  51. package/src/core/approvals.ts +32 -1
  52. package/src/core/commands.ts +95 -0
  53. package/src/core/connection.ts +1483 -31
  54. package/src/core/delta.ts +204 -0
  55. package/src/core/devices.ts +221 -3
  56. package/src/core/dsh-frames.ts +365 -8
  57. package/src/core/envelope.ts +46 -0
  58. package/src/core/extension.ts +197 -0
  59. package/src/core/hub.ts +441 -49
  60. package/src/core/jobs.ts +372 -0
  61. package/src/core/liveactivity.ts +833 -0
  62. package/src/core/protocol.ts +556 -2
  63. package/src/core/push.ts +354 -0
  64. package/src/core/questions.ts +264 -17
  65. package/src/core/session-meta.ts +73 -1
  66. package/src/core/squads.ts +345 -0
  67. package/src/core/usage-stats.ts +424 -0
  68. package/src/core/usage.ts +937 -0
  69. package/src/core/wire.ts +13 -1
  70. package/src/core/ws-frames.ts +14 -0
  71. package/src/host/apns.ts +320 -0
  72. package/src/host/squads-ledger.ts +105 -0
  73. package/src/host/squads.ts +206 -0
  74. package/src/host/usage-stats.ts +155 -0
  75. package/src/host/watchers.ts +272 -0
  76. package/src/host/websocket.ts +37 -3
  77. package/src/index.ts +310 -9
  78. package/src/mount-once.ts +142 -0
@@ -0,0 +1,160 @@
1
+ /**
2
+ * `usage.stats` 的应答:宿主自己那份按天记的 token 台账的聚合。
3
+ *
4
+ * 这一半与 `usage.ts` 的两半有一个根本区别:那两半读的是本进程自己的事实,这一半
5
+ * 读的是另一个插件(`dsh-usage`)挂在这个宿主上的 HTTP 路由。所以它的缺席方式也
6
+ * 不同——宿主根本没挂那个插件是一件关于这台 Mac 的事实(`no-usage-plugin`),
7
+ * 不是错误;而路由取不到、形状不符、超时才是 `probe-failed`。
8
+ *
9
+ * 两条铁律贯穿本模块:
10
+ *
11
+ * - 永不编 0。五个桶在一行里恒在,但那说的是「这一行读到过」:一次没读到的聚合
12
+ * 回 `probe-failed` 并带上短原因,绝不拿上一轮的值冒充这一轮。日历上某一天宿主
13
+ * 台账里没有条目,是那一天确实没有用量——宿主自己的 `/day` 路由对这种日子答的
14
+ * 也是全 0,所以按 0 收是转述,不是编造。
15
+ * - 宿主侧 30 秒一次。同一份聚合数据在一个窗口内最多读一次,并发调用合并成一次:
16
+ * 台账是这台 Mac 的事实,一部手机重复问不该让宿主多读一遍。
17
+ *
18
+ * 读的是两条路由(都在那个插件的 `/api/dsh-usage` 前缀下):`GET /overview` 一次
19
+ * 给出今天、最近 30 个有记录的日子的台账、以及观测花费;`GET /day?date=YYYY-MM-DD`
20
+ * 补一天。所以一次聚合是 1 + K 次本机回环读,K 只在请求的窗口比 `/overview` 自带的
21
+ * 那一截更深、或本月台账被那一截截断时才不为 0。
22
+ * @module dsh-remote-bridge/core/usage-stats
23
+ */
24
+ /** 省略 `days` 时回多少天。 */
25
+ export declare const STATS_DAYS_DEFAULT = 14;
26
+ /** 一次最多回多少天:再往上按这个数收。 */
27
+ export declare const STATS_DAYS_MAX = 60;
28
+ /** 同一份聚合数据在这个窗口内最多读一次(本桥这一侧)。 */
29
+ export declare const STATS_CACHE_TTL_MS = 30000;
30
+ /** 最多记住几个不同窗口的聚合;一次开屏通常只问一个。 */
31
+ export declare const STATS_CACHE_LIMIT = 8;
32
+ /** 一次读数里的一行:五个互不重叠的 token 桶,未用即真实的 0。 */
33
+ export interface UsageBuckets {
34
+ /** 未命中缓存的输入 token。 */
35
+ readonly input: number;
36
+ /** 输出 token(含推理)。 */
37
+ readonly output: number;
38
+ /** 命中缓存的输入 token。 */
39
+ readonly cacheRead: number;
40
+ /** 写入缓存的 token。 */
41
+ readonly cacheWrite: number;
42
+ /** 推理 token,provider 报过才有。 */
43
+ readonly reasoning: number;
44
+ }
45
+ /** 按天的一行:日期键 `YYYY-MM-DD` 加上五个桶。 */
46
+ export interface UsageDayBucket extends UsageBuckets {
47
+ /** 本地日期键 `YYYY-MM-DD`。 */
48
+ readonly day: string;
49
+ }
50
+ /** 观测到的真实花费:官方账户余额的下降累计,CNY 口径。 */
51
+ export interface UsageObservedSpend {
52
+ /** 累计花费,元。 */
53
+ readonly cny: number;
54
+ /** 这次累计起点的那次余额观测时刻(epoch ms)。 */
55
+ readonly since: number;
56
+ }
57
+ /** `usage.stats` 读得到时回的那一份。 */
58
+ export interface UsageStatsView {
59
+ /** 宿主拼这份聚合的时刻(epoch ms),不是本桥答话的时刻。 */
60
+ readonly updatedAt: number;
61
+ /** 宿主本地的今天。 */
62
+ readonly today: UsageBuckets;
63
+ /** 宿主本地的本月,从 1 号到今天的累计。 */
64
+ readonly month: UsageBuckets;
65
+ /** 请求的窗口内按日期升序的一天一行,最多 `days` 条。 */
66
+ readonly days: UsageDayBucket[];
67
+ /** 宿主有观测花费时才有这个键。 */
68
+ readonly observedSpend?: UsageObservedSpend;
69
+ }
70
+ /** 读不到时回的那一份:为什么读不到,不是错误码。 */
71
+ export interface UsageStatsUnsupported {
72
+ /**
73
+ * `no-usage-plugin` —— 这台宿主没挂 `dsh-usage`(关于这台 Mac 的事实);
74
+ * `probe-failed` —— 路由取不到、形状不符或超时。
75
+ */
76
+ readonly unsupported: 'no-usage-plugin' | 'probe-failed';
77
+ /** 短原因,只给 `probe-failed`。 */
78
+ readonly reason?: string;
79
+ }
80
+ /** `usage.stats` 的应答体。 */
81
+ export type UsageStatsAnswer = UsageStatsView | UsageStatsUnsupported;
82
+ /**
83
+ * 一次宿主路由读数的结果。
84
+ *
85
+ * `missing` 单独一格,是因为「路由不存在」与「路由答了错」在协议里是两个答案:
86
+ * 前者说明那台宿主没挂插件,后者说明这次没读到。
87
+ */
88
+ export type UsageStatsOutcome = {
89
+ readonly kind: 'answer';
90
+ readonly body: unknown;
91
+ } | {
92
+ readonly kind: 'missing';
93
+ } | {
94
+ readonly kind: 'failed';
95
+ readonly reason: string;
96
+ };
97
+ /** 宿主那两条路由,按本模块需要的那一格给出来。 */
98
+ export interface UsageStatsTransport {
99
+ /** `GET /api/dsh-usage/overview`。 */
100
+ overview(): Promise<UsageStatsOutcome>;
101
+ /**
102
+ * `GET /api/dsh-usage/day?date=<day>`。
103
+ * @param day - 本地日期键 `YYYY-MM-DD`。
104
+ */
105
+ day(day: string): Promise<UsageStatsOutcome>;
106
+ }
107
+ /** 构造 {@link UsageStatsReader} 的全部输入。 */
108
+ export interface UsageStatsReaderOptions {
109
+ /** 每次读数都重新解析一次;晚挂载的宿主路由因此也能被读到。 */
110
+ readonly transport: () => UsageStatsTransport | undefined;
111
+ /** 缓存窗口读的时钟。 */
112
+ readonly now: () => number;
113
+ /** 读不到时的落点。 */
114
+ readonly log: (message: string) => void;
115
+ /** 缓存窗口;默认 {@link STATS_CACHE_TTL_MS}。 */
116
+ readonly ttlMs?: number;
117
+ }
118
+ /**
119
+ * `usage.stats` 背后的读服务,一个宿主一份、所有连接共享。
120
+ *
121
+ * 缓存与合并都按窗口值分开放:两个客户端问 14 天和问 30 天是两份不同的聚合,但
122
+ * 它们各自的窗口内都不会让宿主多读一遍。
123
+ */
124
+ export declare class UsageStatsReader {
125
+ #private;
126
+ /**
127
+ * @param options - 宿主路由的解析函数、时钟与日志。
128
+ */
129
+ constructor(options: UsageStatsReaderOptions);
130
+ /**
131
+ * 一个窗口的用量聚合。
132
+ *
133
+ * 窗口值先收进 `[1, 60]`:省下的天数与超出的天数都不是客户端能定的,而「问 1000
134
+ * 天」不该让本桥去翻 1000 个日历。
135
+ * @param days - 要多少天。
136
+ * @returns 读到的那一份,或者为什么读不到。
137
+ */
138
+ stats(days: number): Promise<UsageStatsAnswer>;
139
+ }
140
+ /**
141
+ * 把客户端给的天数收成合法的窗口。
142
+ * @param days - 客户端给的天数。
143
+ * @returns 一个 `[1, 60]` 间的整数;不是有限数时回默认的 14 天。
144
+ */
145
+ export declare function clampStatsDays(days: number): number;
146
+ /**
147
+ * 一个日期键加减天数。
148
+ *
149
+ * 走 UTC 是为了不让夏令时把「加一天」算成 23 或 25 小时:这里加的是日历天。
150
+ * @param day - 日期键 `YYYY-MM-DD`。
151
+ * @param delta - 加减多少天,负数向前。
152
+ * @returns 新的日期键。
153
+ */
154
+ export declare function shiftDay(day: string, delta: number): string;
155
+ /**
156
+ * `YYYY-MM-DD` 是不是一个真实存在的日子。
157
+ * @param value - 待判定的文本。
158
+ * @returns 格式对且日子存在时为 true。
159
+ */
160
+ export declare function isDayKey(value: string): boolean;
@@ -0,0 +1,294 @@
1
+ /**
2
+ * `usage.v1` 的两个读数:一条会话下一次请求由什么组成,以及某个 provider
3
+ * 路由背后账户的余额;外加 `usage.stats.v1` 那一份宿主台账的聚合(见
4
+ * `usage-stats.ts`,本模块只把它的读数转发出去)。
5
+ *
6
+ * 前两半都是「本进程自己的事实」,所以谁都不去打断会话,也不落盘:
7
+ *
8
+ * - 会话那一半折的是宿主经 `session/event` 广播给本进程的事件。上下文窗口
9
+ * 只有宿主真正广播过才有(最近一次 `request/context` 的 `contextWindow`),
10
+ * 组成由本桥按文本长度折算,因此 `composition` 恒带 `estimated: true`:它是
11
+ * 估算,永不冒充宿主读数。
12
+ * - 余额那一半只在路由确实指向官方 origin、且凭据确实拿得到时才发一次上游
13
+ * 请求。同一 provider + 凭据在 {@link BALANCE_CACHE_TTL_MS} 内最多一次,
14
+ * 并发调用合并成一次;401、超时与形状不符都回 `probe-failed`,绝不把上一
15
+ * 次的旧值当成新值发出去。
16
+ *
17
+ * 宿主服务一律走结构化 face:一个服务没挂载就少一档读数,而不是让整条方法
18
+ * 失败(`session-meta.ts` 与 `wire.ts` 都是同一套理由)。
19
+ *
20
+ * 会话那一半还有第三档读数:宿主从未广播过 `request/context` 窗口时,去问那条
21
+ * 路由的模型目录(`GET {baseURL}/models`),把模型自己声明的窗口填进
22
+ * `modelContextWindow`。两个键永不混用——`contextWindow` 恒为宿主实测,
23
+ * `modelContextWindow` 恒为模型声明,客户端据此能分辨该相信谁;宿主广播过窗口时
24
+ * 这一档根本不出现。
25
+ * @module dsh-remote-bridge/core/usage
26
+ */
27
+ import type { SessionStoreFace } from './session-meta.ts';
28
+ import { type UsageStatsAnswer, type UsageStatsReader } from './usage-stats.ts';
29
+ /** `usage.v1` 背后的两个方法:能力门按这一张表判定。 */
30
+ export declare const USAGE_METHODS: ReadonlySet<string>;
31
+ /** 折算分母:一份 token 约合四个 UTF-8 字节。 */
32
+ export declare const BYTES_PER_TOKEN = 4;
33
+ /** 会话折叠最多记住多少条会话,超出时丢最早的一条。 */
34
+ export declare const USAGE_SESSIONS_MAX = 512;
35
+ /**
36
+ * 宿主名册在本进程里的缓存窗口。
37
+ *
38
+ * 名册只在「活会话存储没有、事件折叠也没有」时才读,但一次开屏可能连着问几条,
39
+ * 所以同一个窗口内的多次存在性判定共用一次读取;窗口取得很短,是因为名册本身
40
+ * 会随新建会话变化。
41
+ */
42
+ export declare const ROSTER_CACHE_TTL_MS = 5000;
43
+ /** 同一个 provider + 凭据在这个窗口内最多打一次上游。 */
44
+ export declare const BALANCE_CACHE_TTL_MS = 60000;
45
+ /** 一次上游探测的超时;超时与 401 一样是 `probe-failed`。 */
46
+ export declare const BALANCE_PROBE_TIMEOUT_MS = 10000;
47
+ /** 余额缓存最多记住多少个 provider + 凭据组合。 */
48
+ export declare const BALANCE_CACHE_LIMIT = 64;
49
+ /**
50
+ * 一条路由的模型目录在这个窗口内最多读一次。
51
+ *
52
+ * 目录里的窗口是模型自己声明的静态事实,不会因为一次请求而变化,所以这一档比
53
+ * 余额那一档长得多:10 分钟既跟得上用户改配置,也不会让每次 `usage.session`
54
+ * 都打一次上游。
55
+ */
56
+ export declare const MODEL_WINDOW_CACHE_TTL_MS = 600000;
57
+ /** 一次模型目录探测的超时;超时与 404 一样是「这次没读到」。 */
58
+ export declare const MODEL_WINDOW_PROBE_TIMEOUT_MS = 5000;
59
+ /** 模型目录缓存最多记住多少条路由。 */
60
+ export declare const MODEL_WINDOW_CACHE_LIMIT = 32;
61
+ /**
62
+ * 官方 DeepSeek 的 API origin。
63
+ *
64
+ * 余额端点是按 origin 记账的:只有确实发往这里的路由才查得到官方账户的钱。
65
+ */
66
+ export declare const DEEPSEEK_API_ORIGIN = "https://api.deepseek.com";
67
+ /** 一条会话事件里本模块读到的字段;结构化读取,不导入 SDK 的事件类型。 */
68
+ export interface UsageEventLike {
69
+ readonly type: string;
70
+ readonly data?: unknown;
71
+ }
72
+ /** 一条会话下一次请求的组成估算,单位 token,三格各自向下取整。 */
73
+ export interface UsageComposition {
74
+ /** system 消息文本折算出来的分量。 */
75
+ readonly system: number;
76
+ /** 最近一次 `request/header` 的 tools schema 原文折算出来的分量。 */
77
+ readonly tools: number;
78
+ /** 会话里已观察到的消息文本折算出来的分量。 */
79
+ readonly messages: number;
80
+ /** 恒为 true:这是本桥的估算,宿主从未广播过这个数字。 */
81
+ readonly estimated: true;
82
+ }
83
+ /** `usage.session` 的应答体;两项都取不到时是空对象。 */
84
+ export interface UsageSessionAnswer {
85
+ /** 宿主广播过的上下文窗口;没广播过就没有这个键。 */
86
+ readonly contextWindow?: number;
87
+ /**
88
+ * 会话当前路由的模型目录声明的窗口;宿主广播过 `contextWindow` 时永不出现,
89
+ * 目录也取不到时同样不出现。
90
+ *
91
+ * 它与 {@link contextWindow} 是两个来源:那个是宿主实测,这个是模型声明。两者
92
+ * 不得混用,所以这个键的存在本身就说明「宿主没有实测值」。
93
+ */
94
+ readonly modelContextWindow?: number;
95
+ /** 组成估算;一项都没观察到时没有这个键。 */
96
+ readonly composition?: UsageComposition;
97
+ }
98
+ /** `usage.balance` 支持不到的情况。 */
99
+ export type UsageUnsupported = 'no-credential' | 'not-deepseek-route' | 'probe-failed';
100
+ /** `usage.balance` 的应答体:要么是一次成功读数的四个金额,要么是为什么读不到。 */
101
+ export type UsageBalanceAnswer = {
102
+ readonly provider: string;
103
+ readonly currency: string;
104
+ readonly total: number;
105
+ readonly toppedUp: number;
106
+ readonly granted: number;
107
+ readonly updatedAt: number;
108
+ } | {
109
+ readonly provider: string;
110
+ readonly unsupported: UsageUnsupported;
111
+ readonly reason?: string;
112
+ };
113
+ /**
114
+ * 会话事件的折叠:一条会话最近一次广播过的上下文窗口,以及它的组成原文长度。
115
+ *
116
+ * 只在事件里出现过的会话才有记录,所以「宿主没广播过」与「值恰好是 0」是
117
+ * 两件不同的事,应答里也就不会把没观察到的分量当成读数发出去。
118
+ */
119
+ export declare class UsageTracker {
120
+ #private;
121
+ /**
122
+ * @param limit - 最多记住多少条会话;默认 {@link USAGE_SESSIONS_MAX}。
123
+ */
124
+ constructor(limit?: number);
125
+ /**
126
+ * 折进一条会话事件。
127
+ *
128
+ * 只认四类会改变读数的原文:`request/context` 的窗口、`request/header` 的
129
+ * tools schema、`system/message` 的 system 文本,以及 `user/message`、
130
+ * `assistant/message` 与 `tool/result` 的消息文本。其余事件一概不落记录,
131
+ * 所以一条只跑工具事件的会话不会凭空长出一条组成。
132
+ * @param sessionId - 事件所属会话。
133
+ * @param event - 宿主广播的事件。
134
+ */
135
+ record(sessionId: string, event: UsageEventLike): void;
136
+ /**
137
+ * 本进程是否观察过这条会话。
138
+ * @param sessionId - 会话 id。
139
+ * @returns 观察到过任何一条相关事件时为 true。
140
+ */
141
+ known(sessionId: string): boolean;
142
+ /**
143
+ * 一条会话的读数,两项都取不到时是空对象。
144
+ *
145
+ * 空对象而不是 0:一个还没广播过窗口、也没观察到任何原文的会话,本桥对
146
+ * 它的组成一无所知,编一个 0 会把「不知道」说成「没有内容」。
147
+ * @param sessionId - 会话 id。
148
+ * @returns 应答体,字段按观察到的部分给出。
149
+ */
150
+ answer(sessionId: string): UsageSessionAnswer;
151
+ }
152
+ /** 凭据服务的一角:pi-ai 记录与外部引用。 */
153
+ export interface CredentialStoreFace {
154
+ readRecord(key: string): Promise<{
155
+ readonly kind?: string;
156
+ readonly key?: string;
157
+ } | undefined>;
158
+ resolve(ref: string): Promise<{
159
+ readonly value?: string;
160
+ } | undefined>;
161
+ }
162
+ /** 设置服务的一角:按命名空间读一段解析后的配置。 */
163
+ export interface SettingsFace {
164
+ get?(ns: string): unknown;
165
+ describe?(options?: unknown): readonly {
166
+ readonly ns?: string;
167
+ readonly value?: unknown;
168
+ }[];
169
+ }
170
+ /**
171
+ * 宿主自己的会话名册。
172
+ *
173
+ * 这是 `session.list` 服务的同一个来源,也就是手机名册的来源:它名下既有活的
174
+ * 会话,也有本进程没观察过、甚至当前不 live 的会话。活会话存储答不了这一问
175
+ * 的一半(`ctx.sessions.list()` 只列已进入存储的会话),所以名册单独一格。
176
+ */
177
+ export interface SessionRosterFace {
178
+ /**
179
+ * 名册里的会话 id。
180
+ * @returns id 列表;读不到时回 undefined,调用方据此退回「不知道名册」。
181
+ */
182
+ ids(): Promise<readonly string[] | undefined>;
183
+ }
184
+ /** 一条会话此刻的路由:下一步要用哪个 provider 的哪个模型。 */
185
+ export interface SessionRouteFace {
186
+ /**
187
+ * 一条会话当前的路由。
188
+ *
189
+ * 与 `session.models` 的 `current` 同一个折叠:下一步的选择、其次是用过的
190
+ * 那个、最后才是目录默认——三者都不是本模块能自己推的,所以只转发。
191
+ * @param sessionId - 会话 id。
192
+ * @returns provider 与模型 id,或者 undefined 表示这条路由读不到。
193
+ */
194
+ current(sessionId: string): Promise<{
195
+ readonly provider: string;
196
+ readonly model: string;
197
+ } | undefined>;
198
+ }
199
+ /** 本模块要读的宿主服务;每一个都可能不存在。 */
200
+ export interface UsageFaces {
201
+ /** 活会话的存储:`usage.session` 靠它区分「不存在」与「存在但没读数」。 */
202
+ readonly sessions?: SessionStoreFace | undefined;
203
+ /** 宿主自己的会话名册:本进程没观察过的会话靠它证明自己存在。 */
204
+ readonly roster?: SessionRosterFace | undefined;
205
+ /** 凭据服务:余额探测的密钥来源。 */
206
+ readonly credentials?: CredentialStoreFace | undefined;
207
+ /** 设置服务:路由的 `apiKeyEnv` 与 `baseURL` 来源。 */
208
+ readonly settings?: SettingsFace | undefined;
209
+ /** 会话此刻的路由:`modelContextWindow` 的来源。 */
210
+ readonly route?: SessionRouteFace | undefined;
211
+ }
212
+ /** 上游探测用的 fetch 一角。 */
213
+ export type FetchFace = (url: string, init?: {
214
+ readonly headers?: Record<string, string>;
215
+ readonly signal?: AbortSignal;
216
+ }) => Promise<{
217
+ readonly ok: boolean;
218
+ readonly status: number;
219
+ json(): Promise<unknown>;
220
+ }>;
221
+ /** 构造 {@link UsageService} 的全部输入。 */
222
+ export interface UsageServiceOptions {
223
+ /** 每读一次宿主服务都重新解析一次,晚挂载的服务因此也能被读到。 */
224
+ readonly faces: () => UsageFaces;
225
+ /** 缓存窗口与 `updatedAt` 读的时钟。 */
226
+ readonly now: () => number;
227
+ /** 读不到宿主服务时的落点。 */
228
+ readonly log: (message: string) => void;
229
+ /** 上游探测;默认用本进程的 `fetch`。 */
230
+ readonly fetch?: FetchFace;
231
+ /** 余额缓存窗口;默认 {@link BALANCE_CACHE_TTL_MS}。 */
232
+ readonly ttlMs?: number;
233
+ /** 一次探测的超时;默认 {@link BALANCE_PROBE_TIMEOUT_MS}。 */
234
+ readonly timeoutMs?: number;
235
+ /** 模型目录探测的超时;默认 {@link MODEL_WINDOW_PROBE_TIMEOUT_MS}。 */
236
+ readonly modelTimeoutMs?: number;
237
+ /** 宿主台账的聚合;没有它时 `usage.stats` 答 `probe-failed`。 */
238
+ readonly stats?: UsageStatsReader;
239
+ }
240
+ /**
241
+ * `usage.v1` 的两条方法背后的读服务,一个宿主一份、所有连接共享。
242
+ *
243
+ * 会话读数是宿主的事实而不是某个设备的事实,余额是账户的事实,所以两半都
244
+ * 挂在宿主侧:一部手机重复问、两台手机同时问,都不该让上游多收一个请求。
245
+ */
246
+ export declare class UsageService {
247
+ #private;
248
+ /**
249
+ * @param options - 宿主服务的解析函数、时钟与上游探测。
250
+ */
251
+ constructor(options: UsageServiceOptions);
252
+ /**
253
+ * 折进一条宿主广播的会话事件。
254
+ *
255
+ * 没广播过的事件不会出现在任何应答里:本模块不读会话日志,也不回填历史,
256
+ * 所以一条在桥挂载前就结束的会话只有活会话存储能证明它存在。
257
+ * @param sessionId - 事件所属会话。
258
+ * @param event - 事件本身。
259
+ */
260
+ record(sessionId: string, event: UsageEventLike): void;
261
+ /**
262
+ * 一条会话的上下文窗口与组成估算。
263
+ *
264
+ * 「不存在」与「存在但两项都取不到」是两个答案,而「存在」有三个证人:活会话
265
+ * 存储里有它、本进程观察过它的事件、或者宿主名册里有它。前两个是同步的,因此
266
+ * 只有两个都答不上来时才会去问名册——名册才是那条「本进程没观察过、当前也不
267
+ * live」的会话唯一的证据,把它说成不存在会变成一次假的失败。
268
+ *
269
+ * 名册也读不到时,证人只剩前两个:这时回 undefined 就是协议的
270
+ * `unknown-session`,与加名册之前逐字一样。
271
+ * @param sessionId - 会话 id。
272
+ * @returns 应答体,或者 undefined 表示这条会话不存在。
273
+ */
274
+ session(sessionId: string): Promise<UsageSessionAnswer | undefined>;
275
+ /**
276
+ * 宿主自己那份按天记的 token 台账的聚合。
277
+ *
278
+ * 缓存、合并与「读到/没读到」的区分都在 `usage-stats.ts`:那是对另一个插件的
279
+ * HTTP 路由的读数,与本节两半的「本进程自己的事实」不是同一类东西,因此单独
280
+ * 一格。本方法只转发。
281
+ * @param days - 要多少天;省略按 {@link STATS_DAYS_DEFAULT}。
282
+ * @returns 台账聚合,或者为什么读不到。
283
+ */
284
+ stats(days?: number): Promise<UsageStatsAnswer>;
285
+ /**
286
+ * 一条 provider 路由背后账户的余额,DeepSeek 官方口径。
287
+ *
288
+ * 判定的顺序就是省下上游请求的顺序:不是官方路由的 id 不查,指向别的
289
+ * origin 的路由不查,拿不到凭据不查;只有三关都过了才谈得上缓存与探测。
290
+ * @param provider - 客户端给的 provider 路由 id。
291
+ * @returns 余额,或者为什么读不到。
292
+ */
293
+ balance(provider: string): Promise<UsageBalanceAnswer>;
294
+ }
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * - `session/list` is the only endpoint whose single parameter is named
11
11
  * `_request` (the underscore is part of the wire name);
12
- * - three endpoints take NO parameters at all and must be called with `{}`;
12
+ * - four endpoints take NO parameters at all and must be called with `{}`;
13
13
  * - every other endpoint names its single parameter `request`.
14
14
  * @module dsh-remote-bridge/core/wire
15
15
  */
@@ -22,6 +22,15 @@ export declare const CLOSE_PROTOCOL_ERROR = 1002;
22
22
  export declare const CLOSE_UNSUPPORTED_DATA = 1003;
23
23
  /** Close code for a message past the size this bridge will carry. */
24
24
  export declare const CLOSE_TOO_LARGE = 1009;
25
+ /**
26
+ * Close code for a peer that stopped answering: a liveness ping went out and no
27
+ * frame at all came back before its deadline.
28
+ *
29
+ * It is an application-range code (4000-4999), so a client can tell a peer that
30
+ * went silent from a protocol fault, from a frame this bridge will not carry,
31
+ * and from the ordinary 1001 teardown of a bridge that is unloading.
32
+ */
33
+ export declare const CLOSE_LIVENESS_TIMEOUT = 4000;
25
34
  /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
26
35
  export declare function webSocketAccept(secWebSocketKey: string): string;
27
36
  /** One decoded frame header plus its payload. */
@@ -57,5 +66,7 @@ export declare function parseClientFrame(buffer: Buffer, maxBytes: number): Fram
57
66
  export declare function encodeServerFrame(opcode: number, payload: Buffer, fin?: boolean): Buffer;
58
67
  /** Encode one text message. */
59
68
  export declare function encodeTextFrame(text: string): Buffer;
69
+ /** Encode one binary message: already-encoded payload bytes, never a text frame. */
70
+ export declare function encodeBinaryFrame(payload: Buffer): Buffer;
60
71
  /** Encode one close frame with a code and a short reason. */
61
72
  export declare function encodeCloseFrame(code: number, reason: string): Buffer;
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The APNs client this bridge sends notifications through.
3
+ *
4
+ * Written against `node:http2` and `node:crypto` and nothing else: the provider
5
+ * API is one POST per notification behind an ES256 JWT, which is small enough
6
+ * that a dependency would cost more than it saves, and this package's whole
7
+ * install surface is one browser library.
8
+ *
9
+ * Two facts about the credential shape everything here:
10
+ *
11
+ * - the signing key is an Apple `.p8` on this machine, named by an environment
12
+ * variable. It never enters this repository, the roster file, a log line or a
13
+ * wire frame; only the JWT derived from it leaves the process.
14
+ * - a bridge with no key is a bridge with the channel OFF. {@link apnsConfigFromEnv}
15
+ * answers undefined, no sender is constructed, and every notification path is
16
+ * a no-op — the existing protocol runs byte for byte as it did before (§28).
17
+ * @module dsh-remote-bridge/host/apns
18
+ */
19
+ import { type KeyObject } from 'node:crypto';
20
+ import { type ClientHttp2Session } from 'node:http2';
21
+ import type { LiveActivityAddress, LiveActivityNotification, LiveActivitySender } from '../core/liveactivity.ts';
22
+ import type { PushAddress, PushNotification, PushSendResult, PushSender } from '../core/push.ts';
23
+ /** Production APNs authority. */
24
+ export declare const APNS_PRODUCTION_AUTHORITY = "api.push.apple.com";
25
+ /** Development APNs authority; a build signed for development must use it. */
26
+ export declare const APNS_SANDBOX_AUTHORITY = "api.sandbox.push.apple.com";
27
+ /** Path prefix of one device delivery. */
28
+ export declare const APNS_DEVICE_PATH = "/3/device/";
29
+ /**
30
+ * The topic suffix a Live Activity push needs.
31
+ *
32
+ * A Live Activity is addressed under the app bundle's own topic with this
33
+ * suffix appended (§29); the bare bundle is the alert channel's topic, and
34
+ * sending a card there is delivered as an alert the App cannot decode.
35
+ */
36
+ export declare const APNS_LIVE_ACTIVITY_TOPIC_SUFFIX = ".push-type.liveactivity";
37
+ /**
38
+ * How long one signed provider token is reused.
39
+ *
40
+ * Apple rejects a token older than an hour and throttles a provider that mints
41
+ * one per request, so the token is refreshed well inside that window.
42
+ */
43
+ export declare const APNS_TOKEN_TTL_MS: number;
44
+ /** How long one delivery may take before it is abandoned. */
45
+ export declare const APNS_TIMEOUT_MS = 10000;
46
+ /** Environment variables this bridge reads its credential from. */
47
+ export declare const APNS_ENV: {
48
+ readonly keyFile: "DSH_REMOTE_BRIDGE_APNS_KEY_FILE";
49
+ readonly keyId: "DSH_REMOTE_BRIDGE_APNS_KEY_ID";
50
+ readonly teamId: "DSH_REMOTE_BRIDGE_APNS_TEAM_ID";
51
+ };
52
+ /** The credential this bridge signs with. */
53
+ export interface ApnsConfig {
54
+ /** Absolute path of the `.p8` private key. */
55
+ readonly keyFile: string;
56
+ /** The key id Apple issued for that file. */
57
+ readonly keyId: string;
58
+ /** The Apple Developer team id, which is the token's `iss`. */
59
+ readonly teamId: string;
60
+ }
61
+ /**
62
+ * Read the APNs credential from the environment.
63
+ * @param env - the environment to read; defaults to this process's.
64
+ * @returns the credential, or undefined when any part of it is missing — which
65
+ * is how the channel stays off by default.
66
+ */
67
+ export declare function apnsConfigFromEnv(env?: NodeJS.ProcessEnv): ApnsConfig | undefined;
68
+ /** @returns the base64url text of one buffer, without padding. */
69
+ export declare function base64Url(value: Buffer | string): string;
70
+ /**
71
+ * Sign one APNs provider token.
72
+ *
73
+ * Header and claims are exactly what Apple accepts and nothing more: `alg`,
74
+ * `kid` and `iss`, `iat`. APNs rejects a token carrying any other claim, so
75
+ * this is not a place to add a convenient `exp` beside it.
76
+ * @param input - the key, its id, the team id, and the issue time.
77
+ * @returns the compact JWT.
78
+ */
79
+ export declare function es256Jwt(input: {
80
+ readonly key: KeyObject;
81
+ readonly keyId: string;
82
+ readonly teamId: string;
83
+ readonly issuedAt?: number;
84
+ }): string;
85
+ /** What one delivery's HTTP/2 request looks like. */
86
+ export interface ApnsRequestSpec {
87
+ readonly authority: string;
88
+ readonly path: string;
89
+ readonly headers: Readonly<Record<string, string>>;
90
+ }
91
+ /**
92
+ * The request one notification becomes.
93
+ *
94
+ * `apns-topic` is the registration's own bundle id and `apns-push-type` is
95
+ * always `alert`: this channel only ever sends a user-visible notification, and
96
+ * a body typed as anything else would be dropped by the system for having an
97
+ * alert payload.
98
+ * @param target - the device being notified.
99
+ * @param jwt - the provider token.
100
+ * @returns the authority, path and headers of the POST.
101
+ */
102
+ export declare function apnsRequestSpec(target: PushAddress, jwt: string): ApnsRequestSpec;
103
+ /**
104
+ * The topic one Live Activity push is addressed under.
105
+ * @param bundle - the app bundle the device registered with.
106
+ * @returns the bundle plus the Live Activity suffix, appended once.
107
+ */
108
+ export declare function liveActivityTopicOf(bundle: string): string;
109
+ /**
110
+ * The request one Live Activity push becomes.
111
+ *
112
+ * Three headers differ from the alert request beside it, and each of them is a
113
+ * rule rather than a preference: the push type is `liveactivity`, the topic is
114
+ * the app bundle's Live Activity topic, and the expiration is `0` — a card
115
+ * update that could not be delivered now must never be delivered later, because
116
+ * it would overwrite the present with the past (§29).
117
+ * @param target - the card being pushed to.
118
+ * @param jwt - the provider token.
119
+ * @returns the authority, path and headers of the POST.
120
+ */
121
+ export declare function liveActivityRequestSpec(target: LiveActivityAddress, jwt: string): ApnsRequestSpec;
122
+ export interface ApnsSenderOptions {
123
+ readonly config: ApnsConfig;
124
+ readonly log?: (message: string) => void;
125
+ /** Clock the token lifetime is measured against; the wall clock by default. */
126
+ readonly now?: () => number;
127
+ readonly timeoutMs?: number;
128
+ /** The HTTP/2 dial, injectable so the failure paths need no network. */
129
+ readonly connect?: (authority: string) => ClientHttp2Session;
130
+ }
131
+ /**
132
+ * The APNs delivery half of the push channel.
133
+ *
134
+ * Every method resolves: a delivery that failed is a {@link PushSendResult} with
135
+ * `ok: false`, never a rejection, because both callers sit on frame paths that
136
+ * must not learn about APNs at all.
137
+ */
138
+ export declare class ApnsSender implements PushSender, LiveActivitySender {
139
+ #private;
140
+ constructor(options: ApnsSenderOptions);
141
+ /** Deliver one notification, or report why it did not arrive. */
142
+ send(target: PushAddress, notification: PushNotification): Promise<PushSendResult>;
143
+ /**
144
+ * Deliver one Live Activity push, or report why it did not arrive.
145
+ *
146
+ * The same provider token, the same transport and the same "resolve, never
147
+ * reject" rule as {@link send}; only the request's headers and the body differ,
148
+ * and both are built outside this class so the contract stays assertable.
149
+ */
150
+ sendLiveActivity(target: LiveActivityAddress, notification: LiveActivityNotification): Promise<PushSendResult>;
151
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The read-only ledger fallback of the squads channel.
3
+ *
4
+ * `dsh-agents` is the only writer of this document, and this bridge reads the
5
+ * same bytes under the same rules: a document of an unknown generation, a
6
+ * revision that is not a whole number, or a team/run set this build cannot read
7
+ * is refused rather than repaired. Nothing here writes, locks, creates or
8
+ * quarantines anything — a Host whose loopback route cannot answer still shows
9
+ * the user's own definitions, and never edits them from behind the plugin's back.
10
+ *
11
+ * The rows themselves are mapped by `core/squads.ts`, exactly as a loopback
12
+ * answer is: the two paths meet in one mapping, so a fallback body cannot drift
13
+ * from a served one.
14
+ * @module dsh-remote-bridge/host/squads-ledger
15
+ */
16
+ /** Ledger file name inside the plugin's own directory. */
17
+ export declare const SQUAD_LEDGER_FILE = "ledger.json";
18
+ /** Owner lock beside it; it is what carries the owning pid. */
19
+ export declare const SQUAD_LEDGER_LOCK_FILE = "ledger.json.lock";
20
+ /** The one ledger generation this build reads. */
21
+ export declare const SQUAD_LEDGER_SCHEMA_VERSION = 1;
22
+ /** One state document read off the ledger, in the plugin's own key names. */
23
+ export interface SquadLedgerDocument {
24
+ teams: readonly unknown[];
25
+ runs: readonly unknown[];
26
+ host: {
27
+ ownerPid?: number;
28
+ };
29
+ }
30
+ /**
31
+ * Read the ledger document without touching it.
32
+ * @param directory - the plugin-owned directory (`$DSH_HOME/dsh-agents`).
33
+ * @returns the definitions and runs as stored, plus the owning pid when the lock
34
+ * names one.
35
+ * @throws {SquadRefusal} `squads-unavailable` when there is no readable ledger, or
36
+ * the plugin's own `ledger-corrupt` when the bytes are not the document this
37
+ * build reads.
38
+ */
39
+ export declare function readSquadLedger(directory: string): Promise<SquadLedgerDocument>;