@linxin666/dsh-remote-bridge 0.4.21 → 0.4.23

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/src/core/usage.ts CHANGED
@@ -85,6 +85,9 @@ const DEEPSEEK_BALANCE_URL = `${DEEPSEEK_API_ORIGIN}/user/balance`
85
85
  /** 官方余额适配认的 provider 路由 id,与 dsh-usage 的 deepseek adapter 同一份名单。 */
86
86
  const DEEPSEEK_ROUTES: ReadonlySet<string> = new Set(['deepseek', 'deepseek-official'])
87
87
 
88
+ /** 官方 App 托管账户的路由 id(走 `ctx.deepseekAccount.getBalance`)。 */
89
+ const DEEPSEEK_ACCOUNT_ROUTE = 'deepseek-account'
90
+
88
91
  /** pi-ai 凭据记录的 scope:一条记录以 `<scope>/<id>` 寻址。 */
89
92
  const PI_AI_CREDENTIAL_SCOPE = 'llm-pi-ai'
90
93
 
@@ -321,6 +324,45 @@ export interface SessionRouteFace {
321
324
  current(sessionId: string): Promise<{ readonly provider: string; readonly model: string } | undefined>
322
325
  }
323
326
 
327
+ /** 官方 DeepSeek 请求鉴权服务(`ctx.deepseekAuth`,DSH 0.2.3-alpha.2+)。 */
328
+ export interface DeepSeekAuthFace {
329
+ authorize(request: {
330
+ readonly consumer: string
331
+ readonly accepts: readonly ('account' | 'api-key')[]
332
+ readonly billing: 'auto' | 'account' | 'api-key'
333
+ readonly route?: string
334
+ readonly destination: { readonly path: string }
335
+ }, signal?: AbortSignal): Promise<{
336
+ readonly kind: 'account' | 'api-key'
337
+ readonly endpoint: string
338
+ readonly headers: Readonly<Record<string, string>>
339
+ } | undefined>
340
+ }
341
+
342
+ /** 官方 DeepSeek 账号钱包条目(`ctx.deepseekAccount`)。 */
343
+ export interface DeepSeekAccountWalletFace {
344
+ readonly currency: string
345
+ readonly balance: string
346
+ }
347
+
348
+ /** 官方 DeepSeek 账号余额服务(`ctx.deepseekAccount`)。 */
349
+ export interface DeepSeekAccountFace {
350
+ getState(): Promise<{ readonly status: 'signed-out' | 'credential-stored' }>
351
+ getBalance(client: {
352
+ readonly version: string
353
+ readonly locale: string
354
+ readonly timezoneOffsetSeconds: number
355
+ }): Promise<
356
+ | {
357
+ readonly status: 'ready'
358
+ readonly value: readonly DeepSeekAccountWalletFace[]
359
+ readonly bonusWallets: readonly DeepSeekAccountWalletFace[]
360
+ }
361
+ | { readonly status: 'failed' }
362
+ | null
363
+ >
364
+ }
365
+
324
366
  /** 本模块要读的宿主服务;每一个都可能不存在。 */
325
367
  export interface UsageFaces {
326
368
  /** 活会话的存储:`usage.session` 靠它区分「不存在」与「存在但没读数」。 */
@@ -333,6 +375,10 @@ export interface UsageFaces {
333
375
  readonly settings?: SettingsFace | undefined
334
376
  /** 会话此刻的路由:`modelContextWindow` 的来源。 */
335
377
  readonly route?: SessionRouteFace | undefined
378
+ /** 官方 DeepSeek 请求鉴权服务(优先于手工凭据解析)。 */
379
+ readonly deepseekAuth?: DeepSeekAuthFace | undefined
380
+ /** 官方 DeepSeek App 托管账户余额服务。 */
381
+ readonly deepseekAccount?: DeepSeekAccountFace | undefined
336
382
  }
337
383
 
338
384
  /** 上游探测用的 fetch 一角。 */
@@ -444,13 +490,20 @@ export class UsageService {
444
490
  * @returns 余额,或者为什么读不到。
445
491
  */
446
492
  async balance(provider: string): Promise<UsageBalanceAnswer> {
447
- if (!DEEPSEEK_ROUTES.has(provider)) return { provider, unsupported: 'not-deepseek-route' }
448
493
  const faces = this.#faces()
494
+ if (provider === DEEPSEEK_ACCOUNT_ROUTE) {
495
+ return await this.#accountBalance(provider, faces.deepseekAccount)
496
+ }
497
+ if (!DEEPSEEK_ROUTES.has(provider)) return { provider, unsupported: 'not-deepseek-route' }
449
498
  if (!officialRoute(provider, faces.settings)) return { provider, unsupported: 'not-deepseek-route' }
450
- const credential = await this.#credentialOf(provider, faces)
451
- if (credential === undefined) return { provider, unsupported: 'no-credential' }
499
+ const authorized = await this.#deepseekAuthOf(provider, faces)
500
+ const credential = authorized === undefined ? await this.#credentialOf(provider, faces) : undefined
501
+ if (authorized === undefined && credential === undefined) return { provider, unsupported: 'no-credential' }
502
+ const identity = authorized !== undefined
503
+ ? `${authorized.endpoint}\u0000${headerAuthFingerprint(authorized.headers)}`
504
+ : fingerprint(credential as string)
452
505
  // 缓存键带上凭据指纹:换一把 key 就是另一个账户,不能被上一把的读数冒充。
453
- const cacheKey = `${provider}\u0000${fingerprint(credential)}`
506
+ const cacheKey = `${provider}\u0000${identity}`
454
507
  const cached = this.#cache.get(cacheKey)
455
508
  if (cached !== undefined && this.#options.now() - cached.at < this.#ttl()) return cached.answer
456
509
  const running = this.#inFlight.get(cacheKey)
@@ -460,7 +513,9 @@ export class UsageService {
460
513
  this.#inFlight.delete(cacheKey)
461
514
  return answer
462
515
  }
463
- const probe = this.#probe(provider, credential)
516
+ const probe = (authorized !== undefined
517
+ ? this.#probeAuthorized(provider, authorized.endpoint, authorized.headers)
518
+ : this.#probe(provider, credential as string))
464
519
  .then(settle, (error: unknown) => settle({ provider, unsupported: 'probe-failed', reason: failureText(error) }))
465
520
  this.#inFlight.set(cacheKey, probe)
466
521
  return await probe
@@ -541,6 +596,67 @@ export class UsageService {
541
596
  return undefined
542
597
  }
543
598
 
599
+ /** 优先向官方 `ctx.deepseekAuth` 申请余额请求头,仅接受指向官方 origin 的 api-key 授权。 */
600
+ async #deepseekAuthOf(
601
+ provider: string,
602
+ faces: UsageFaces,
603
+ ): Promise<{ readonly endpoint: string; readonly headers: Record<string, string> } | undefined> {
604
+ const auth = faces.deepseekAuth
605
+ if (auth === undefined || typeof auth.authorize !== 'function') return undefined
606
+ try {
607
+ const authorization = await auth.authorize({
608
+ consumer: 'dsh-remote-bridge',
609
+ accepts: ['api-key'],
610
+ billing: 'api-key',
611
+ route: provider,
612
+ destination: { path: '/user/balance' },
613
+ }, AbortSignal.timeout(this.#timeout()))
614
+ if (authorization === undefined || authorization.kind !== 'api-key') return undefined
615
+ if (originOf(authorization.endpoint) !== DEEPSEEK_API_ORIGIN) return undefined
616
+ return { endpoint: authorization.endpoint, headers: { ...authorization.headers } }
617
+ } catch (error) {
618
+ this.#options.log(`deepseekAuth could not authorize route "${provider}": ${failureText(error)}`)
619
+ return undefined
620
+ }
621
+ }
622
+
623
+ /** 通过官方 `ctx.deepseekAccount` 查询 App 托管账户余额,带缓存与并发合并。 */
624
+ async #accountBalance(provider: string, account: DeepSeekAccountFace | undefined): Promise<UsageBalanceAnswer> {
625
+ if (account === undefined || typeof account.getState !== 'function' || typeof account.getBalance !== 'function') {
626
+ return { provider, unsupported: 'not-deepseek-route' }
627
+ }
628
+ const cacheKey = `${provider}\u0000account`
629
+ const cached = this.#cache.get(cacheKey)
630
+ if (cached !== undefined && this.#options.now() - cached.at < this.#ttl()) return cached.answer
631
+ const running = this.#inFlight.get(cacheKey)
632
+ if (running !== undefined) return await running
633
+ const settle = (answer: UsageBalanceAnswer): UsageBalanceAnswer => {
634
+ this.#remember(cacheKey, answer)
635
+ this.#inFlight.delete(cacheKey)
636
+ return answer
637
+ }
638
+ const probe = (async (): Promise<UsageBalanceAnswer> => {
639
+ try {
640
+ const state = await account.getState()
641
+ if (state.status !== 'credential-stored') return { provider, unsupported: 'no-credential' }
642
+ const offsetMin = new Date().getTimezoneOffset()
643
+ const outcome = await account.getBalance({
644
+ version: '0.2.3',
645
+ locale: 'zh-CN',
646
+ timezoneOffsetSeconds: offsetMin === 0 ? 0 : -offsetMin * 60,
647
+ })
648
+ if (outcome === null) return { provider, unsupported: 'no-credential' }
649
+ if (outcome.status === 'failed') return { provider, unsupported: 'probe-failed', reason: 'account balance query failed' }
650
+ const parsed = parseAccountWallets(outcome.value, outcome.bonusWallets)
651
+ return { provider, ...parsed, updatedAt: this.#options.now() }
652
+ } catch (error) {
653
+ return { provider, unsupported: 'probe-failed', reason: failureText(error) }
654
+ }
655
+ })().then(settle, (error: unknown) => settle({ provider, unsupported: 'probe-failed', reason: failureText(error) }))
656
+ this.#inFlight.set(cacheKey, probe)
657
+ return await probe
658
+ }
659
+
544
660
  /**
545
661
  * 对官方余额端点做一次探测。
546
662
  *
@@ -548,10 +664,18 @@ export class UsageService {
548
664
  * 「这次没读到」,任何一条都不会拿上一轮的旧值顶上。
549
665
  */
550
666
  async #probe(provider: string, credential: string): Promise<UsageBalanceAnswer> {
667
+ return await this.#probeAuthorized(provider, DEEPSEEK_BALANCE_URL, { authorization: `Bearer ${credential}` })
668
+ }
669
+
670
+ async #probeAuthorized(
671
+ provider: string,
672
+ endpoint: string,
673
+ headers: Record<string, string>,
674
+ ): Promise<UsageBalanceAnswer> {
551
675
  const call = this.#options.fetch ?? defaultFetch
552
676
  try {
553
- const response = await call(DEEPSEEK_BALANCE_URL, {
554
- headers: { authorization: `Bearer ${credential}` },
677
+ const response = await call(endpoint, {
678
+ headers,
555
679
  signal: AbortSignal.timeout(this.#timeout()),
556
680
  })
557
681
  if (!response.ok) return { provider, unsupported: 'probe-failed', reason: `HTTP ${response.status}` }
@@ -911,6 +1035,48 @@ function amount(value: unknown): number | undefined {
911
1035
  return Number.isFinite(parsed) ? parsed : undefined
912
1036
  }
913
1037
 
1038
+ /** 合并官方 `ctx.deepseekAccount.getBalance` 返回的充值与赠金钱包,优先 CNY,次选 USD。 */
1039
+ function parseAccountWallets(
1040
+ value: readonly DeepSeekAccountWalletFace[],
1041
+ bonusWallets: readonly DeepSeekAccountWalletFace[],
1042
+ ): ParsedBalance {
1043
+ const sum = (list: readonly DeepSeekAccountWalletFace[], target: string): { found: boolean; total: number } => {
1044
+ let found = false
1045
+ let total = 0
1046
+ for (const wallet of list) {
1047
+ if (wallet.currency.toUpperCase() !== target) continue
1048
+ const num = amount(wallet.balance)
1049
+ if (num === undefined) continue
1050
+ found = true
1051
+ total += num
1052
+ }
1053
+ return { found, total }
1054
+ }
1055
+ const cnyTopped = sum(value, 'CNY')
1056
+ const cnyBonus = sum(bonusWallets, 'CNY')
1057
+ if (cnyTopped.found || cnyBonus.found) {
1058
+ const toppedUp = Number(cnyTopped.total.toFixed(2))
1059
+ const granted = Number(cnyBonus.total.toFixed(2))
1060
+ return { currency: 'CNY', toppedUp, granted, total: Number((toppedUp + granted).toFixed(2)) }
1061
+ }
1062
+ const usdTopped = sum(value, 'USD')
1063
+ const usdBonus = sum(bonusWallets, 'USD')
1064
+ if (usdTopped.found || usdBonus.found) {
1065
+ const toppedUp = Number(usdTopped.total.toFixed(2))
1066
+ const granted = Number(usdBonus.total.toFixed(2))
1067
+ return { currency: 'USD', toppedUp, granted, total: Number((toppedUp + granted).toFixed(2)) }
1068
+ }
1069
+ return { currency: 'CNY', toppedUp: 0, granted: 0, total: 0 }
1070
+ }
1071
+
1072
+ /** 根据授权请求头计算凭据指纹,键名小写排序确保稳定。 */
1073
+ function headerAuthFingerprint(headers: Readonly<Record<string, string>>): string {
1074
+ const entries = Object.entries(headers)
1075
+ .map(([key, value]) => `${key.toLowerCase()}:${value}`)
1076
+ .sort()
1077
+ return fingerprint(entries.join('\n'))
1078
+ }
1079
+
914
1080
  /**
915
1081
  * 凭据的指纹(FNV-1a)。
916
1082
  *
package/src/core/wire.ts CHANGED
@@ -128,7 +128,7 @@ export const WIRE_TABLE: readonly WireRow[] = [
128
128
  { namespace: 'session', method: 'cancel', wire: 'request' },
129
129
  { namespace: 'session', method: 'attachment', wire: 'request' },
130
130
  { namespace: 'session', method: 'projections', wire: 'request' },
131
- { namespace: 'session', method: 'modelCatalog', wire: 'none' },
131
+ { namespace: 'models', method: 'catalog', wire: 'none' },
132
132
  { namespace: 'session', method: 'selectModel', wire: 'request' },
133
133
  { namespace: 'session', method: 'rename', wire: 'request' },
134
134
  { namespace: 'workspace', method: 'pinSession', wire: 'request' },
@@ -1,8 +1,8 @@
1
1
  // Generated by scripts/sync-shared.mjs from shared/host/dsh-home.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
2
  /**
3
- * DSH_HOME resolution shared by the plugin family's Host halves: the
4
- * environment override wins, the platform home fallback follows. Mirrors
5
- * what dsh-pet and dsh-liangshen each used to implement locally.
3
+ * DSH_HOME and DSH_AGENTS_HOME resolution shared by the plugin family's Host
4
+ * halves: environment overrides win (blank values treated as unset), then the
5
+ * platform home fallbacks follow — mirroring `@deepseek-ai/dsh-home-paths`.
6
6
  */
7
7
 
8
8
  import { homedir } from 'node:os'
@@ -18,6 +18,21 @@ export function expandHome(path: string, home: string = homedir()): string {
18
18
  return path
19
19
  }
20
20
 
21
+ function resolveUserRoot(
22
+ envValue: string | undefined,
23
+ defaultDirName: string,
24
+ home: string,
25
+ ): string {
26
+ const isPosix = home.startsWith('/')
27
+ const j = isPosix ? posixJoin : join
28
+ const isAbs = isPosix ? posixIsAbsolute : isAbsolute
29
+ if (envValue !== undefined && envValue.trim() !== '') {
30
+ const expanded = expandHome(envValue.trim(), home)
31
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded)
32
+ }
33
+ return j(home, defaultDirName)
34
+ }
35
+
21
36
  /**
22
37
  * Resolve the DSH home directory.
23
38
  * @param env - process environment to read DSH_HOME from.
@@ -25,18 +40,26 @@ export function expandHome(path: string, home: string = homedir()): string {
25
40
  * @returns the absolute DSH home path.
26
41
  */
27
42
  export function resolveDshHome(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
28
- const isPosix = home.startsWith('/')
29
- const j = isPosix ? posixJoin : join
30
- const isAbs = isPosix ? posixIsAbsolute : isAbsolute
31
- const raw = env.DSH_HOME
32
- if (raw !== undefined && raw.trim() !== '') {
33
- const expanded = expandHome(raw.trim(), home)
34
- return isAbs(expanded) ? expanded : j(process.cwd(), expanded)
35
- }
36
- return j(home, '.dsh')
43
+ return resolveUserRoot(env.DSH_HOME, '.dsh', home)
37
44
  }
38
45
 
39
46
  /** Resolve the DSH home directory from the live environment. */
40
47
  export function dshHome(): string {
41
48
  return resolveDshHome()
42
49
  }
50
+
51
+ /**
52
+ * Resolve the shared agent configuration root (`$DSH_AGENTS_HOME`, defaulting
53
+ * to `<home>/.agents`), matching `@deepseek-ai/dsh-home-paths`'s `resolveAgentsHome`.
54
+ * @param env - process environment to read DSH_AGENTS_HOME from.
55
+ * @param home - platform home directory fallback (test seam).
56
+ * @returns the absolute shared agents home path.
57
+ */
58
+ export function resolveAgentsHome(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
59
+ return resolveUserRoot(env.DSH_AGENTS_HOME, '.agents', home)
60
+ }
61
+
62
+ /** Resolve the shared agent configuration root from the live environment. */
63
+ export function agentsHome(): string {
64
+ return resolveAgentsHome()
65
+ }
@@ -140,17 +140,14 @@ export function makePairTokenHandler(deps: PairTokenRouteDeps): WebRoute['handle
140
140
  }
141
141
  }
142
142
 
143
- type AuthAwareWebRoute = WebRoute & { readonly auth?: 'anonymous' | 'required' | 'deny' }
144
-
145
143
  /** The route as the host web server takes it: one exact path, no trailing slash. */
146
144
  export function makePairTokenRoute(deps: PairTokenRouteDeps): WebRoute {
147
145
  // This endpoint runs its own strict loopback-and-Host trust fence (plus pair-token
148
146
  // semantics) without requiring a desktop browser session cookie.
149
- const route: AuthAwareWebRoute = {
147
+ return {
150
148
  kind: 'exact',
151
149
  path: PAIR_TOKEN_PATH,
152
150
  auth: 'anonymous',
153
151
  handler: makePairTokenHandler(deps),
154
152
  }
155
- return route
156
153
  }
@@ -138,6 +138,7 @@ function presentationOf(args: { html: string; title?: string; height?: number },
138
138
  export function createUiPresentTool(host: UiToolHost): ToolDefinition {
139
139
  return defineTool({
140
140
  name: 'ui_present',
141
+ environment: 'independent',
141
142
  description: UI_PRESENT_DESCRIPTION,
142
143
  parameters: {
143
144
  html: {
package/src/index.ts CHANGED
@@ -62,7 +62,15 @@ import { SessionMeta, type SessionStoreFace, type SessionTitleFace, type Workspa
62
62
  import { sessionQuietProbe, TURN_END_QUIET_REPORT_MS, TurnEndQuietGate } from './core/turn-end-quiet.ts'
63
63
  import { SessionPermissions, type ApprovalPolicyFace, type PermissionPresetsFace, type SandboxPolicyFace } from './core/session-permissions.ts'
64
64
  import { selectionOf, modelSelectionOf, type RelayTierFace } from './core/connection.ts'
65
- import { UsageService, type CredentialStoreFace, type SessionRosterFace, type SessionRouteFace, type SettingsFace } from './core/usage.ts'
65
+ import {
66
+ UsageService,
67
+ type CredentialStoreFace,
68
+ type DeepSeekAccountFace,
69
+ type DeepSeekAuthFace,
70
+ type SessionRosterFace,
71
+ type SessionRouteFace,
72
+ type SettingsFace,
73
+ } from './core/usage.ts'
66
74
  import { UsageStatsReader } from './core/usage-stats.ts'
67
75
  import { wireArgs, type GatewayPeer } from './core/wire.ts'
68
76
  import { dshHome } from './host/dsh-home.ts'
@@ -304,20 +312,20 @@ function sessionRoster(ctx: Context, peer: GatewayPeer, log: (message: string) =
304
312
  * @returns 路由 face。
305
313
  */
306
314
  function sessionRoute(ctx: Context, peer: GatewayPeer, log: (message: string) => void): SessionRouteFace {
307
- const invoke = async (method: string, args: Readonly<Record<string, unknown>>): Promise<unknown> => await ctx.typertGateway.invoke({
308
- namespace: 'session',
315
+ const invoke = async (namespace: string, method: string, args: Readonly<Record<string, unknown>>): Promise<unknown> => await ctx.typertGateway.invoke({
316
+ namespace,
309
317
  method,
310
- args: wireArgs('session', method, args),
318
+ args: wireArgs(namespace, method, args),
311
319
  peer,
312
320
  })
313
321
  return {
314
322
  current: async (sessionId: string) => {
315
323
  try {
316
- const folded = modelSelectionOf(await invoke('projections', { sessionId }))
324
+ const folded = modelSelectionOf(await invoke('session', 'projections', { sessionId }))
317
325
  const selected = folded.next ?? folded.lastUsed
318
326
  // 还没选过模型的会话在目录默认上——它下一步就会用那个,也正是
319
327
  // `session.models` 对同一条会话给出的答案。
320
- const fallback = selected === undefined ? selectionOf(catalogDefaultOf(await invoke('modelCatalog', {}))) : undefined
328
+ const fallback = selected === undefined ? selectionOf(catalogDefaultOf(await invoke('models', 'catalog', {}))) : undefined
321
329
  const answer = selected ?? fallback
322
330
  return answer === undefined ? undefined : { provider: answer.provider, model: answer.model }
323
331
  } catch (error) {
@@ -328,7 +336,7 @@ function sessionRoute(ctx: Context, peer: GatewayPeer, log: (message: string) =>
328
336
  }
329
337
  }
330
338
 
331
- /** `session/modelCatalog` 里的 `default` 一格。 */
339
+ /** `models/catalog` 里的 `default` 一格。 */
332
340
  function catalogDefaultOf(value: unknown): unknown {
333
341
  return typeof value === 'object' && value !== null ? (value as { default?: unknown }).default : undefined
334
342
  }
@@ -346,13 +354,23 @@ function catalogDefaultOf(value: unknown): unknown {
346
354
  * @param log - 读不到名册时的落点。
347
355
  * @returns 这些 face 此刻的样子。
348
356
  */
357
+ function optionalService<T>(ctx: Context, name: string): T | undefined {
358
+ try {
359
+ return (ctx.get(name as never, false) ?? ctx.get(name as never)) as T | undefined
360
+ } catch {
361
+ return undefined
362
+ }
363
+ }
364
+
349
365
  function usageFaces(ctx: Context, peer: GatewayPeer, log: (message: string) => void) {
350
366
  return {
351
- sessions: ctx.get('sessions') as SessionStoreFace | undefined,
367
+ sessions: optionalService<SessionStoreFace>(ctx, 'sessions'),
352
368
  roster: sessionRoster(ctx, peer, log),
353
- credentials: ctx.get('credentials') as CredentialStoreFace | undefined,
354
- settings: ctx.get('settings') as SettingsFace | undefined,
369
+ credentials: optionalService<CredentialStoreFace>(ctx, 'credentials'),
370
+ settings: optionalService<SettingsFace>(ctx, 'settings'),
355
371
  route: sessionRoute(ctx, peer, log),
372
+ deepseekAuth: optionalService<DeepSeekAuthFace>(ctx, 'deepseekAuth'),
373
+ deepseekAccount: optionalService<DeepSeekAccountFace>(ctx, 'deepseekAccount'),
356
374
  }
357
375
  }
358
376