dsh-plugin-weapp-gateway 0.8.23 → 0.8.34

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 (71) hide show
  1. package/LICENSE +21 -21
  2. package/PROTOCOL.md +1545 -1486
  3. package/README.md +503 -464
  4. package/THIRD-PARTY-NOTICES/dsh-cost-meter.txt +31 -31
  5. package/bin/setup-ip.mjs +474 -474
  6. package/cordis.patch.yml +50 -50
  7. package/docs/agent-team-app-integration.md +945 -0
  8. package/docs/blog-mobile-gateway.md +542 -542
  9. package/docs/dsh-0.1.5-rc.2-compatibility-audit.md +255 -255
  10. package/docs/dsh-0.1.6-alpha.1-compatibility-audit.md +122 -122
  11. package/docs/dsh-0.1.7-rc.1-compatibility-audit.md +52 -52
  12. package/docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md +109 -109
  13. package/docs/dsh-rc2-mobile-integration.md +155 -155
  14. package/docs/file-upload-app-integration.md +250 -0
  15. package/docs/multi-gateway-app-integration.md +141 -125
  16. package/docs/multi-gateway-phase1-acceptance.md +179 -179
  17. package/docs/multi-gateway-todo.md +137 -137
  18. package/docs/remote-gateway-refactor-plan.md +52 -52
  19. package/docs/runtime-architecture.architecture.json +264 -264
  20. package/docs/runtime-architecture.html +15001 -15001
  21. package/docs/runtime-architecture.visual-check.html +32 -32
  22. package/docs/runtime-architecture.visual-check.json +548 -548
  23. package/docs/session-agent-preset-app-integration.md +93 -93
  24. package/docs/turn-outline-app-integration.md +196 -0
  25. package/docs/typert-remote-gateway-feature-checklist.md +294 -294
  26. package/docs/voice-input-implementation.md +219 -219
  27. package/docs/workspace-changes-mobile-integration.md +32 -32
  28. package/helper/dsh_mobile_gateway_helper.py +227 -227
  29. package/lib/account-bridge.mjs +57 -57
  30. package/lib/client.js +1409 -1361
  31. package/lib/cloudflare-tunnel.mjs +314 -314
  32. package/lib/cloudflared-binary.mjs +135 -135
  33. package/lib/context-bridge.mjs +3338 -1715
  34. package/lib/cost-meter-bridge.mjs +794 -794
  35. package/lib/cost-meter-dashboard-bridge.mjs +1655 -1449
  36. package/lib/devices.js +273 -245
  37. package/lib/dsh-host-adapter.mjs +508 -426
  38. package/lib/file-upload.mjs +205 -0
  39. package/lib/gateway-probe.mjs +6 -6
  40. package/lib/gateway-state.mjs +57 -57
  41. package/lib/gateway-tools.mjs +36 -36
  42. package/lib/history-cache.mjs +66 -0
  43. package/lib/index.mjs +4390 -3803
  44. package/lib/plugin-management.mjs +251 -233
  45. package/lib/public-endpoint-check.mjs +61 -61
  46. package/lib/relay-connector.mjs +213 -181
  47. package/lib/relay-state.mjs +83 -76
  48. package/lib/session-follower.mjs +140 -136
  49. package/lib/session-resume-bridge.mjs +86 -0
  50. package/lib/session-target.mjs +29 -0
  51. package/lib/speech-input.mjs +192 -192
  52. package/lib/vendor/cost-meter/aliyun-balance.mjs +123 -123
  53. package/lib/vendor/cost-meter/coding-plans.mjs +1668 -1668
  54. package/lib/vendor/cost-meter/credentials-shim.mjs +8 -8
  55. package/lib/vendor/cost-meter/custom-balance.mjs +281 -281
  56. package/lib/vendor/cost-meter/factory-quota.mjs +69 -69
  57. package/lib/vendor/cost-meter/gateway-quota-adapters.mjs +1006 -1006
  58. package/lib/vendor/cost-meter/gateway-quotas.mjs +664 -664
  59. package/lib/vendor/cost-meter/home-paths-shim.mjs +13 -13
  60. package/lib/vendor/cost-meter/net.mjs +183 -183
  61. package/lib/vendor/cost-meter/opendesign.mjs +204 -204
  62. package/lib/vendor/cost-meter/tokenrhythm-balance.mjs +95 -95
  63. package/lib/vendor/cost-meter/workbuddy-accounts.mjs +44 -44
  64. package/lib/vendor/cost-meter/workbuddy-transport.mjs +38 -38
  65. package/lib/vendor/cost-meter/workbuddy.mjs +356 -356
  66. package/lib/web-restart.mjs +47 -47
  67. package/lib/wire-json.mjs +7 -7
  68. package/lib/workspace-changes-bridge.mjs +32 -32
  69. package/package.json +54 -54
  70. package/relay/agent-connector.js +588 -569
  71. package/relay/vendor/tweetnacl.js +2391 -2391
@@ -1,192 +1,192 @@
1
- // 移动连接只代理官方 speech Remote,不持有识别模型或写入会话历史。
2
- export const SPEECH_REQUEST_TYPES = new Set([
3
- 'speech-catalog', 'speech-subscribe', 'speech-unsubscribe', 'speech-configure',
4
- 'speech-prepare', 'speech-cancel-preparation', 'speech-transcribe', 'speech-cancel',
5
- ])
6
-
7
- const MAX_AUDIO_BYTES = 4 * 1024 * 1024
8
- const UNAVAILABLE_CODES = new Set(['gateway/invocation-unavailable', 'gateway/definition-unavailable', 'gateway/service-unavailable'])
9
-
10
- function failure(code, message) {
11
- return Object.assign(new Error(message), { code })
12
- }
13
-
14
- function identifier(value, name) {
15
- if (typeof value !== 'string' || !value.trim() || value.length > 128) {
16
- throw failure('bad-request', `${name} must be a nonempty string of at most 128 characters`)
17
- }
18
- return value.trim()
19
- }
20
-
21
- function errorFrame(msg, error) {
22
- return { kind: 'error', requestType: msg.type,
23
- ...(typeof msg.requestId === 'string' ? { requestId: msg.requestId } : {}),
24
- code: UNAVAILABLE_CODES.has(error?.code) ? 'speech/unavailable' : error?.code || 'speech/failed',
25
- message: UNAVAILABLE_CODES.has(error?.code)
26
- ? 'Enable the official voice input bundle in DSH plugin management' : error?.message || 'Speech operation failed' }
27
- }
28
-
29
- export function createSpeechInputManager(api, { maxPayloadBytes = 64 * 1024 * 1024,
30
- transcriptionTimeoutMs = 180_000 } = {}) {
31
- const clients = new Map()
32
- let activeTranscriptions = 0
33
- let disposed = false
34
- // 为 JSON 信封留出空间;实际限制还须服从官方插件的目录。
35
- const audioLimit = Math.min(MAX_AUDIO_BYTES, Math.max(0, Math.floor((maxPayloadBytes - 4096) / 4) * 3))
36
- const stateFor = client => {
37
- if (disposed) throw failure('speech/unavailable', 'Speech gateway has been disposed')
38
- let state = clients.get(client)
39
- if (!state) {
40
- state = { operations: new Map(), follow: null, closed: false }
41
- clients.set(client, state)
42
- }
43
- return state
44
- }
45
- const normalizeCatalog = value => {
46
- if (!value || !Array.isArray(value.providers) || !value.selection
47
- || !Number.isSafeInteger(value.maxAudioBytes) || value.maxAudioBytes < 46
48
- || !Number.isFinite(value.maxDurationSeconds) || value.maxDurationSeconds < 1) {
49
- throw failure('speech/invalid-response', 'Official speech catalog is invalid')
50
- }
51
- return { ...value, maxAudioBytes: Math.min(audioLimit, value.maxAudioBytes),
52
- maxDurationSeconds: value.maxDurationSeconds, available: true }
53
- }
54
- const stopFollow = state => {
55
- state.follow?.abort.abort()
56
- state.follow = null
57
- }
58
- const catalog = async signal => normalizeCatalog(await api.speech.catalog(signal))
59
-
60
- return {
61
- async handle(client, msg, send) {
62
- try {
63
- const requestId = identifier(msg.requestId, 'requestId')
64
- const state = stateFor(client)
65
- if (msg.type === 'speech-cancel') {
66
- const targetRequestId = identifier(msg.targetRequestId, 'targetRequestId')
67
- const task = state.operations.get(targetRequestId)
68
- if (!task || task.type !== 'speech-transcribe') throw failure('speech/request-not-found', 'Transcription is not active on this connection')
69
- task.abort.abort(failure('speech/cancelled', 'Transcription cancelled'))
70
- return { kind: 'speech-cancelled', requestId, targetRequestId }
71
- }
72
- if (msg.type === 'speech-unsubscribe') {
73
- stopFollow(state)
74
- return { kind: 'speech-unsubscribed', requestId }
75
- }
76
- if (state.operations.has(requestId) || state.follow?.requestId === requestId) {
77
- throw failure('speech/request-in-progress', 'requestId is already active on this connection')
78
- }
79
- if (state.operations.size >= 8) throw failure('speech/busy', 'Too many pending speech requests')
80
- if (msg.type === 'speech-subscribe') {
81
- stopFollow(state)
82
- const follow = { abort: new AbortController(), requestId }
83
- state.follow = follow
84
- // 先回执,再按订阅 requestId 推送完整快照。Host 的准备任务不属于此观察连接。
85
- queueMicrotask(async () => {
86
- try {
87
- const stream = await api.speech.follow(follow.abort.signal)
88
- for await (const snapshot of stream) {
89
- if (state.closed || state.follow !== follow || follow.abort.signal.aborted) break
90
- send({ kind: 'speech-state', requestId, ...normalizeCatalog(snapshot) })
91
- }
92
- if (!follow.abort.signal.aborted) throw failure('speech/stream-ended', 'Speech readiness stream ended; subscribe again')
93
- } catch (error) {
94
- if (!state.closed && state.follow === follow && !follow.abort.signal.aborted) send(errorFrame(msg, error))
95
- } finally {
96
- if (state.follow === follow) state.follow = null
97
- }
98
- })
99
- return { kind: 'speech-subscribed', requestId }
100
- }
101
- const abort = new AbortController()
102
- const task = { abort, type: msg.type }
103
- let timer
104
- let admitted = false
105
- state.operations.set(requestId, task)
106
- try {
107
- if (msg.type === 'speech-catalog') {
108
- try { return { kind: 'speech-catalog', requestId, ...await catalog(abort.signal) } }
109
- catch (error) {
110
- if (UNAVAILABLE_CODES.has(error?.code)) return { kind: 'speech-catalog', requestId,
111
- available: false, providers: [], code: 'speech/unavailable',
112
- message: 'Enable the official voice input bundle in DSH plugin management' }
113
- throw error
114
- }
115
- }
116
- if (msg.type === 'speech-transcribe') {
117
- if ([...state.operations.values()].some(value => value !== task && value.type === msg.type)
118
- || activeTranscriptions >= 4) throw failure('speech/busy', 'Too many active transcriptions')
119
- const encoded = msg.audioBase64
120
- if (typeof encoded !== 'string' || !encoded.length || encoded.length > Math.ceil(audioLimit / 3) * 4) {
121
- throw failure('speech/invalid-audio', 'Audio is empty or exceeds the gateway byte limit')
122
- }
123
- const audio = Buffer.from(encoded, 'base64')
124
- if (audio.length > audioLimit || audio.toString('base64') !== encoded) {
125
- throw failure('speech/invalid-audio', 'Audio must use canonical base64 within the gateway byte limit')
126
- }
127
- const request = { audioBase64: encoded,
128
- ...(msg.providerId === undefined ? {} : { providerId: identifier(msg.providerId, 'providerId') }),
129
- ...(msg.language === undefined ? {} : { language: identifier(msg.language, 'language') }) }
130
- activeTranscriptions++
131
- admitted = true
132
- timer = setTimeout(() => abort.abort(failure('speech/timeout', 'Transcription timed out')), transcriptionTimeoutMs)
133
- timer.unref?.()
134
- const limits = await catalog(abort.signal)
135
- abort.signal.throwIfAborted()
136
- if (audio.length > limits.maxAudioBytes) throw failure('speech/invalid-audio', 'Audio exceeds the official plugin byte limit')
137
- // 官方 Remote 负责 WAV、采样率、语言、模型就绪与录音时长校验。
138
- const result = await api.speech.transcribe(request, abort.signal)
139
- abort.signal.throwIfAborted()
140
- if (typeof result?.text !== 'string' || !Number.isFinite(result.audioSeconds) || result.audioSeconds < 0
141
- || !Number.isFinite(result.inferenceSeconds) || result.inferenceSeconds < 0) {
142
- throw failure('speech/invalid-response', 'Official speech transcript is invalid')
143
- }
144
- return { kind: 'speech-transcript', requestId, text: result.text,
145
- audioSeconds: result.audioSeconds, inferenceSeconds: result.inferenceSeconds }
146
- }
147
- if (msg.type === 'speech-configure') {
148
- const patch = {
149
- ...(msg.providerId === undefined ? {} : { providerId: identifier(msg.providerId, 'providerId') }),
150
- ...(msg.language === undefined ? {} : { language: identifier(msg.language, 'language') }),
151
- }
152
- if (!Object.keys(patch).length) throw failure('bad-request', 'Provide providerId or language')
153
- await api.speech.configure(patch, abort.signal)
154
- return { kind: 'speech-configured', requestId }
155
- }
156
- const providerId = identifier(msg.providerId, 'providerId')
157
- if (msg.type === 'speech-prepare') {
158
- const options = msg.downloadSource === undefined ? undefined : { downloadSource: msg.downloadSource }
159
- if (options && (typeof options.downloadSource !== 'string' || !options.downloadSource.trim() || options.downloadSource.length > 2048)) {
160
- throw failure('bad-request', 'downloadSource must be an advertised nonempty origin')
161
- }
162
- await api.speech.prepare(providerId, options, abort.signal)
163
- return { kind: 'speech-preparing', requestId, providerId }
164
- }
165
- if (msg.type === 'speech-cancel-preparation') {
166
- await api.speech.cancelPreparation(providerId, abort.signal)
167
- return { kind: 'speech-preparation-cancelled', requestId, providerId }
168
- }
169
- throw failure('bad-request', 'Unknown speech request')
170
- } catch (error) {
171
- throw abort.signal.aborted ? abort.signal.reason : error
172
- } finally {
173
- clearTimeout(timer)
174
- state.operations.delete(requestId)
175
- if (admitted) activeTranscriptions--
176
- }
177
- } catch (error) { return errorFrame(msg, error) }
178
- },
179
- closeClient(client) {
180
- const state = clients.get(client)
181
- if (!state) return
182
- state.closed = true
183
- stopFollow(state)
184
- for (const task of state.operations.values()) task.abort.abort(failure('speech/cancelled', 'Mobile connection closed'))
185
- clients.delete(client)
186
- },
187
- dispose() {
188
- disposed = true
189
- for (const client of clients.keys()) this.closeClient(client)
190
- },
191
- }
192
- }
1
+ // 移动连接只代理官方 speech Remote,不持有识别模型或写入会话历史。
2
+ export const SPEECH_REQUEST_TYPES = new Set([
3
+ 'speech-catalog', 'speech-subscribe', 'speech-unsubscribe', 'speech-configure',
4
+ 'speech-prepare', 'speech-cancel-preparation', 'speech-transcribe', 'speech-cancel',
5
+ ])
6
+
7
+ const MAX_AUDIO_BYTES = 4 * 1024 * 1024
8
+ const UNAVAILABLE_CODES = new Set(['gateway/invocation-unavailable', 'gateway/definition-unavailable', 'gateway/service-unavailable'])
9
+
10
+ function failure(code, message) {
11
+ return Object.assign(new Error(message), { code })
12
+ }
13
+
14
+ function identifier(value, name) {
15
+ if (typeof value !== 'string' || !value.trim() || value.length > 128) {
16
+ throw failure('bad-request', `${name} must be a nonempty string of at most 128 characters`)
17
+ }
18
+ return value.trim()
19
+ }
20
+
21
+ function errorFrame(msg, error) {
22
+ return { kind: 'error', requestType: msg.type,
23
+ ...(typeof msg.requestId === 'string' ? { requestId: msg.requestId } : {}),
24
+ code: UNAVAILABLE_CODES.has(error?.code) ? 'speech/unavailable' : error?.code || 'speech/failed',
25
+ message: UNAVAILABLE_CODES.has(error?.code)
26
+ ? 'Enable the official voice input bundle in DSH plugin management' : error?.message || 'Speech operation failed' }
27
+ }
28
+
29
+ export function createSpeechInputManager(api, { maxPayloadBytes = 64 * 1024 * 1024,
30
+ transcriptionTimeoutMs = 180_000 } = {}) {
31
+ const clients = new Map()
32
+ let activeTranscriptions = 0
33
+ let disposed = false
34
+ // 为 JSON 信封留出空间;实际限制还须服从官方插件的目录。
35
+ const audioLimit = Math.min(MAX_AUDIO_BYTES, Math.max(0, Math.floor((maxPayloadBytes - 4096) / 4) * 3))
36
+ const stateFor = client => {
37
+ if (disposed) throw failure('speech/unavailable', 'Speech gateway has been disposed')
38
+ let state = clients.get(client)
39
+ if (!state) {
40
+ state = { operations: new Map(), follow: null, closed: false }
41
+ clients.set(client, state)
42
+ }
43
+ return state
44
+ }
45
+ const normalizeCatalog = value => {
46
+ if (!value || !Array.isArray(value.providers) || !value.selection
47
+ || !Number.isSafeInteger(value.maxAudioBytes) || value.maxAudioBytes < 46
48
+ || !Number.isFinite(value.maxDurationSeconds) || value.maxDurationSeconds < 1) {
49
+ throw failure('speech/invalid-response', 'Official speech catalog is invalid')
50
+ }
51
+ return { ...value, maxAudioBytes: Math.min(audioLimit, value.maxAudioBytes),
52
+ maxDurationSeconds: value.maxDurationSeconds, available: true }
53
+ }
54
+ const stopFollow = state => {
55
+ state.follow?.abort.abort()
56
+ state.follow = null
57
+ }
58
+ const catalog = async signal => normalizeCatalog(await api.speech.catalog(signal))
59
+
60
+ return {
61
+ async handle(client, msg, send) {
62
+ try {
63
+ const requestId = identifier(msg.requestId, 'requestId')
64
+ const state = stateFor(client)
65
+ if (msg.type === 'speech-cancel') {
66
+ const targetRequestId = identifier(msg.targetRequestId, 'targetRequestId')
67
+ const task = state.operations.get(targetRequestId)
68
+ if (!task || task.type !== 'speech-transcribe') throw failure('speech/request-not-found', 'Transcription is not active on this connection')
69
+ task.abort.abort(failure('speech/cancelled', 'Transcription cancelled'))
70
+ return { kind: 'speech-cancelled', requestId, targetRequestId }
71
+ }
72
+ if (msg.type === 'speech-unsubscribe') {
73
+ stopFollow(state)
74
+ return { kind: 'speech-unsubscribed', requestId }
75
+ }
76
+ if (state.operations.has(requestId) || state.follow?.requestId === requestId) {
77
+ throw failure('speech/request-in-progress', 'requestId is already active on this connection')
78
+ }
79
+ if (state.operations.size >= 8) throw failure('speech/busy', 'Too many pending speech requests')
80
+ if (msg.type === 'speech-subscribe') {
81
+ stopFollow(state)
82
+ const follow = { abort: new AbortController(), requestId }
83
+ state.follow = follow
84
+ // 先回执,再按订阅 requestId 推送完整快照。Host 的准备任务不属于此观察连接。
85
+ queueMicrotask(async () => {
86
+ try {
87
+ const stream = await api.speech.follow(follow.abort.signal)
88
+ for await (const snapshot of stream) {
89
+ if (state.closed || state.follow !== follow || follow.abort.signal.aborted) break
90
+ send({ kind: 'speech-state', requestId, ...normalizeCatalog(snapshot) })
91
+ }
92
+ if (!follow.abort.signal.aborted) throw failure('speech/stream-ended', 'Speech readiness stream ended; subscribe again')
93
+ } catch (error) {
94
+ if (!state.closed && state.follow === follow && !follow.abort.signal.aborted) send(errorFrame(msg, error))
95
+ } finally {
96
+ if (state.follow === follow) state.follow = null
97
+ }
98
+ })
99
+ return { kind: 'speech-subscribed', requestId }
100
+ }
101
+ const abort = new AbortController()
102
+ const task = { abort, type: msg.type }
103
+ let timer
104
+ let admitted = false
105
+ state.operations.set(requestId, task)
106
+ try {
107
+ if (msg.type === 'speech-catalog') {
108
+ try { return { kind: 'speech-catalog', requestId, ...await catalog(abort.signal) } }
109
+ catch (error) {
110
+ if (UNAVAILABLE_CODES.has(error?.code)) return { kind: 'speech-catalog', requestId,
111
+ available: false, providers: [], code: 'speech/unavailable',
112
+ message: 'Enable the official voice input bundle in DSH plugin management' }
113
+ throw error
114
+ }
115
+ }
116
+ if (msg.type === 'speech-transcribe') {
117
+ if ([...state.operations.values()].some(value => value !== task && value.type === msg.type)
118
+ || activeTranscriptions >= 4) throw failure('speech/busy', 'Too many active transcriptions')
119
+ const encoded = msg.audioBase64
120
+ if (typeof encoded !== 'string' || !encoded.length || encoded.length > Math.ceil(audioLimit / 3) * 4) {
121
+ throw failure('speech/invalid-audio', 'Audio is empty or exceeds the gateway byte limit')
122
+ }
123
+ const audio = Buffer.from(encoded, 'base64')
124
+ if (audio.length > audioLimit || audio.toString('base64') !== encoded) {
125
+ throw failure('speech/invalid-audio', 'Audio must use canonical base64 within the gateway byte limit')
126
+ }
127
+ const request = { audioBase64: encoded,
128
+ ...(msg.providerId === undefined ? {} : { providerId: identifier(msg.providerId, 'providerId') }),
129
+ ...(msg.language === undefined ? {} : { language: identifier(msg.language, 'language') }) }
130
+ activeTranscriptions++
131
+ admitted = true
132
+ timer = setTimeout(() => abort.abort(failure('speech/timeout', 'Transcription timed out')), transcriptionTimeoutMs)
133
+ timer.unref?.()
134
+ const limits = await catalog(abort.signal)
135
+ abort.signal.throwIfAborted()
136
+ if (audio.length > limits.maxAudioBytes) throw failure('speech/invalid-audio', 'Audio exceeds the official plugin byte limit')
137
+ // 官方 Remote 负责 WAV、采样率、语言、模型就绪与录音时长校验。
138
+ const result = await api.speech.transcribe(request, abort.signal)
139
+ abort.signal.throwIfAborted()
140
+ if (typeof result?.text !== 'string' || !Number.isFinite(result.audioSeconds) || result.audioSeconds < 0
141
+ || !Number.isFinite(result.inferenceSeconds) || result.inferenceSeconds < 0) {
142
+ throw failure('speech/invalid-response', 'Official speech transcript is invalid')
143
+ }
144
+ return { kind: 'speech-transcript', requestId, text: result.text,
145
+ audioSeconds: result.audioSeconds, inferenceSeconds: result.inferenceSeconds }
146
+ }
147
+ if (msg.type === 'speech-configure') {
148
+ const patch = {
149
+ ...(msg.providerId === undefined ? {} : { providerId: identifier(msg.providerId, 'providerId') }),
150
+ ...(msg.language === undefined ? {} : { language: identifier(msg.language, 'language') }),
151
+ }
152
+ if (!Object.keys(patch).length) throw failure('bad-request', 'Provide providerId or language')
153
+ await api.speech.configure(patch, abort.signal)
154
+ return { kind: 'speech-configured', requestId }
155
+ }
156
+ const providerId = identifier(msg.providerId, 'providerId')
157
+ if (msg.type === 'speech-prepare') {
158
+ const options = msg.downloadSource === undefined ? undefined : { downloadSource: msg.downloadSource }
159
+ if (options && (typeof options.downloadSource !== 'string' || !options.downloadSource.trim() || options.downloadSource.length > 2048)) {
160
+ throw failure('bad-request', 'downloadSource must be an advertised nonempty origin')
161
+ }
162
+ await api.speech.prepare(providerId, options, abort.signal)
163
+ return { kind: 'speech-preparing', requestId, providerId }
164
+ }
165
+ if (msg.type === 'speech-cancel-preparation') {
166
+ await api.speech.cancelPreparation(providerId, abort.signal)
167
+ return { kind: 'speech-preparation-cancelled', requestId, providerId }
168
+ }
169
+ throw failure('bad-request', 'Unknown speech request')
170
+ } catch (error) {
171
+ throw abort.signal.aborted ? abort.signal.reason : error
172
+ } finally {
173
+ clearTimeout(timer)
174
+ state.operations.delete(requestId)
175
+ if (admitted) activeTranscriptions--
176
+ }
177
+ } catch (error) { return errorFrame(msg, error) }
178
+ },
179
+ closeClient(client) {
180
+ const state = clients.get(client)
181
+ if (!state) return
182
+ state.closed = true
183
+ stopFollow(state)
184
+ for (const task of state.operations.values()) task.abort.abort(failure('speech/cancelled', 'Mobile connection closed'))
185
+ clients.delete(client)
186
+ },
187
+ dispose() {
188
+ disposed = true
189
+ for (const client of clients.keys()) this.closeClient(client)
190
+ },
191
+ }
192
+ }
@@ -1,123 +1,123 @@
1
- /** 千问 / 阿里云资金账户可用金(issue #98)。凭据仅用于服务端 ACS3 签名。 */
2
- import { createHash, createHmac, randomUUID } from 'node:crypto'
3
- import { credentialRef } from './credentials-shim.mjs'
4
- import { fetchWithRetry } from './net.mjs'
5
-
6
- // API shape/endpoint: aliyun/alibabacloud-typescript-sdk, bssopenapi-20230930.
7
- // Signature: https://help.aliyun.com/zh/sdk/product-overview/v3-request-structure-and-signature
8
- export const ALIYUN_BALANCE_URL = 'https://business.aliyuncs.com/'
9
- export const ALIYUN_BALANCE_CREDENTIAL_VARS = [
10
- 'ALIBABA_CLOUD_ACCESS_KEY_ID',
11
- 'ALIBABA_CLOUD_ACCESS_KEY_SECRET',
12
- 'ALIBABA_CLOUD_SECURITY_TOKEN',
13
- ]
14
- const MAX_BYTES = 262144
15
- const hash = value => createHash('sha256').update(value).digest('hex')
16
-
17
- export function signAliyunBalanceRequest(accessKeyId, accessKeySecret, securityToken = '', { now = new Date(), nonce = randomUUID() } = {}) {
18
- const headers = {
19
- 'content-type': 'application/x-www-form-urlencoded',
20
- host: 'business.aliyuncs.com',
21
- 'x-acs-action': 'GetFundAccountAvailableAmount',
22
- 'x-acs-content-sha256': hash(''),
23
- 'x-acs-date': now.toISOString().replace(/\.\d{3}Z$/, 'Z'),
24
- 'x-acs-signature-nonce': nonce,
25
- 'x-acs-version': '2023-09-30',
26
- }
27
- if (securityToken) headers['x-acs-security-token'] = securityToken
28
- const keys = Object.keys(headers).sort()
29
- const signedHeaders = keys.join(';')
30
- const canonicalHeaders = keys.map(key => `${key}:${headers[key].trim()}\n`).join('')
31
- const canonical = ['POST', '/', '', canonicalHeaders, signedHeaders, hash('')].join('\n')
32
- const signature = createHmac('sha256', accessKeySecret).update(`ACS3-HMAC-SHA256\n${hash(canonical)}`).digest('hex')
33
- headers.Authorization = `ACS3-HMAC-SHA256 Credential=${accessKeyId},SignedHeaders=${signedHeaders},Signature=${signature}`
34
- headers.Accept = 'application/json'
35
- return { method: 'POST', headers, body: '', redirect: 'manual' }
36
- }
37
-
38
- const messages = {
39
- zh: {
40
- missing: '请配置阿里云 RAM AccessKey ID 和 AccessKey Secret(不是千问模型 API Key)',
41
- network: '阿里云余额网络请求失败,请稍后重试',
42
- redirect: '阿里云余额接口发生重定向,已拒绝转发凭据',
43
- permission: '阿里云余额鉴权失败,请检查 AccessKey、STS 有效期及 RAM 权限 bss:DescribeBillingAccount',
44
- http: '阿里云余额接口返回 HTTP {status}',
45
- payload: '阿里云余额响应无效或过大,请稍后重试',
46
- amount: '阿里云余额响应缺少有效的 AvailableAmount,未将其视为零余额',
47
- currency: '阿里云余额响应缺少受支持的币种(CNY / USD / EUR)',
48
- },
49
- en: {
50
- missing: 'Configure Alibaba Cloud RAM AccessKey ID and AccessKey Secret (not a Qianwen model API key)',
51
- network: 'Alibaba Cloud balance network request failed; please retry later',
52
- redirect: 'Alibaba Cloud balance redirect refused to protect credentials',
53
- permission: 'Alibaba Cloud balance authentication failed; check AccessKey, STS expiry and RAM permission bss:DescribeBillingAccount',
54
- http: 'Alibaba Cloud balance returned HTTP {status}',
55
- payload: 'Alibaba Cloud balance response is invalid or too large; please retry later',
56
- amount: 'Alibaba Cloud balance response has no valid AvailableAmount; it was not treated as zero',
57
- currency: 'Alibaba Cloud balance response has no supported currency (CNY / USD / EUR)',
58
- },
59
- }
60
- const failure = (locale, key, status = '') => new Error(messages[locale === 'en' ? 'en' : 'zh'][key].replace('{status}', String(status)))
61
-
62
- export function parseAliyunBalance(data, locale = 'zh') {
63
- const raw = data?.AvailableAmount
64
- const text = typeof raw === 'string' ? raw.trim() : ''
65
- const amount = typeof raw === 'number' ? raw : /^[+-]?\d+(\.\d+)?$/.test(text) ? Number(text) : NaN
66
- if (!Number.isFinite(amount)) throw failure(locale, 'amount')
67
- if (!['CNY', 'USD', 'EUR'].includes(data?.Currency)) throw failure(locale, 'currency')
68
- // AvailableAmount 是可用金,包含信控/未结清款等因素;不能把它当成现金余额或消费额。
69
- return { remaining: amount, unit: data.Currency, maxBudget: null, spend: null }
70
- }
71
-
72
- async function resolveCredential(ctx, name) {
73
- try {
74
- const hit = await ctx?.get?.('credentials')?.resolve(credentialRef(name))
75
- if (typeof hit?.value === 'string' && hit.value.trim()) return hit.value.trim()
76
- } catch { /* 与现有余额 adapter 一致,回落环境变量。 */ }
77
- return String(process.env[name] ?? '').trim()
78
- }
79
-
80
- async function readPayload(response, locale) {
81
- if (Number(response.headers.get('content-length')) > MAX_BYTES) {
82
- await response.body?.cancel().catch(() => {})
83
- throw failure(locale, 'payload')
84
- }
85
- try {
86
- const parts = []
87
- let bytes = 0
88
- for await (const part of response.body) {
89
- bytes += part.length
90
- if (bytes > MAX_BYTES) throw failure(locale, 'payload')
91
- parts.push(part)
92
- }
93
- return JSON.parse(Buffer.concat(parts).toString('utf8'))
94
- } catch { throw failure(locale, 'payload') }
95
- }
96
-
97
- export async function queryAliyunBalance(ctx, config, { fetchImpl = fetch, signal } = {}) {
98
- signal?.throwIfAborted()
99
- const locale = config?.locale
100
- const [ak, sk, token] = await Promise.all(ALIYUN_BALANCE_CREDENTIAL_VARS.map(name => resolveCredential(ctx, name)))
101
- if (!ak || !sk) throw Object.assign(failure(locale, 'missing'), { soft: true })
102
- let response
103
- try {
104
- // 每次网络重试重新生成时间戳与 nonce;URL、Action、body 均固定为只读账户查询。
105
- response = await fetchWithRetry(ALIYUN_BALANCE_URL, { signal }, {
106
- attempts: 2, timeoutMs: 15000,
107
- fetchImpl: (url, init) => fetchImpl(url, { ...signAliyunBalanceRequest(ak, sk, token), signal: init.signal }),
108
- })
109
- } catch {
110
- signal?.throwIfAborted()
111
- throw failure(locale, 'network')
112
- }
113
- if (!response.ok) {
114
- await response.body?.cancel().catch(() => {})
115
- if (response.status >= 300 && response.status < 400) throw failure(locale, 'redirect')
116
- if (response.status === 401 || response.status === 403) throw failure(locale, 'permission')
117
- throw failure(locale, 'http', response.status)
118
- }
119
- const data = await readPayload(response, locale)
120
- // 不把上游 Message/RequestId/账户身份下发浏览器;即使错误响应夹带余额也不能记作成功。
121
- if ((data?.Code && data.Code !== 'Success') || data?.Success === false) throw failure(locale, 'permission')
122
- return { label: config?.customBalance?.label || '千问 / 阿里云', ...parseAliyunBalance(data, locale) }
123
- }
1
+ /** 千问 / 阿里云资金账户可用金(issue #98)。凭据仅用于服务端 ACS3 签名。 */
2
+ import { createHash, createHmac, randomUUID } from 'node:crypto'
3
+ import { credentialRef } from './credentials-shim.mjs'
4
+ import { fetchWithRetry } from './net.mjs'
5
+
6
+ // API shape/endpoint: aliyun/alibabacloud-typescript-sdk, bssopenapi-20230930.
7
+ // Signature: https://help.aliyun.com/zh/sdk/product-overview/v3-request-structure-and-signature
8
+ export const ALIYUN_BALANCE_URL = 'https://business.aliyuncs.com/'
9
+ export const ALIYUN_BALANCE_CREDENTIAL_VARS = [
10
+ 'ALIBABA_CLOUD_ACCESS_KEY_ID',
11
+ 'ALIBABA_CLOUD_ACCESS_KEY_SECRET',
12
+ 'ALIBABA_CLOUD_SECURITY_TOKEN',
13
+ ]
14
+ const MAX_BYTES = 262144
15
+ const hash = value => createHash('sha256').update(value).digest('hex')
16
+
17
+ export function signAliyunBalanceRequest(accessKeyId, accessKeySecret, securityToken = '', { now = new Date(), nonce = randomUUID() } = {}) {
18
+ const headers = {
19
+ 'content-type': 'application/x-www-form-urlencoded',
20
+ host: 'business.aliyuncs.com',
21
+ 'x-acs-action': 'GetFundAccountAvailableAmount',
22
+ 'x-acs-content-sha256': hash(''),
23
+ 'x-acs-date': now.toISOString().replace(/\.\d{3}Z$/, 'Z'),
24
+ 'x-acs-signature-nonce': nonce,
25
+ 'x-acs-version': '2023-09-30',
26
+ }
27
+ if (securityToken) headers['x-acs-security-token'] = securityToken
28
+ const keys = Object.keys(headers).sort()
29
+ const signedHeaders = keys.join(';')
30
+ const canonicalHeaders = keys.map(key => `${key}:${headers[key].trim()}\n`).join('')
31
+ const canonical = ['POST', '/', '', canonicalHeaders, signedHeaders, hash('')].join('\n')
32
+ const signature = createHmac('sha256', accessKeySecret).update(`ACS3-HMAC-SHA256\n${hash(canonical)}`).digest('hex')
33
+ headers.Authorization = `ACS3-HMAC-SHA256 Credential=${accessKeyId},SignedHeaders=${signedHeaders},Signature=${signature}`
34
+ headers.Accept = 'application/json'
35
+ return { method: 'POST', headers, body: '', redirect: 'manual' }
36
+ }
37
+
38
+ const messages = {
39
+ zh: {
40
+ missing: '请配置阿里云 RAM AccessKey ID 和 AccessKey Secret(不是千问模型 API Key)',
41
+ network: '阿里云余额网络请求失败,请稍后重试',
42
+ redirect: '阿里云余额接口发生重定向,已拒绝转发凭据',
43
+ permission: '阿里云余额鉴权失败,请检查 AccessKey、STS 有效期及 RAM 权限 bss:DescribeBillingAccount',
44
+ http: '阿里云余额接口返回 HTTP {status}',
45
+ payload: '阿里云余额响应无效或过大,请稍后重试',
46
+ amount: '阿里云余额响应缺少有效的 AvailableAmount,未将其视为零余额',
47
+ currency: '阿里云余额响应缺少受支持的币种(CNY / USD / EUR)',
48
+ },
49
+ en: {
50
+ missing: 'Configure Alibaba Cloud RAM AccessKey ID and AccessKey Secret (not a Qianwen model API key)',
51
+ network: 'Alibaba Cloud balance network request failed; please retry later',
52
+ redirect: 'Alibaba Cloud balance redirect refused to protect credentials',
53
+ permission: 'Alibaba Cloud balance authentication failed; check AccessKey, STS expiry and RAM permission bss:DescribeBillingAccount',
54
+ http: 'Alibaba Cloud balance returned HTTP {status}',
55
+ payload: 'Alibaba Cloud balance response is invalid or too large; please retry later',
56
+ amount: 'Alibaba Cloud balance response has no valid AvailableAmount; it was not treated as zero',
57
+ currency: 'Alibaba Cloud balance response has no supported currency (CNY / USD / EUR)',
58
+ },
59
+ }
60
+ const failure = (locale, key, status = '') => new Error(messages[locale === 'en' ? 'en' : 'zh'][key].replace('{status}', String(status)))
61
+
62
+ export function parseAliyunBalance(data, locale = 'zh') {
63
+ const raw = data?.AvailableAmount
64
+ const text = typeof raw === 'string' ? raw.trim() : ''
65
+ const amount = typeof raw === 'number' ? raw : /^[+-]?\d+(\.\d+)?$/.test(text) ? Number(text) : NaN
66
+ if (!Number.isFinite(amount)) throw failure(locale, 'amount')
67
+ if (!['CNY', 'USD', 'EUR'].includes(data?.Currency)) throw failure(locale, 'currency')
68
+ // AvailableAmount 是可用金,包含信控/未结清款等因素;不能把它当成现金余额或消费额。
69
+ return { remaining: amount, unit: data.Currency, maxBudget: null, spend: null }
70
+ }
71
+
72
+ async function resolveCredential(ctx, name) {
73
+ try {
74
+ const hit = await ctx?.get?.('credentials')?.resolve(credentialRef(name))
75
+ if (typeof hit?.value === 'string' && hit.value.trim()) return hit.value.trim()
76
+ } catch { /* 与现有余额 adapter 一致,回落环境变量。 */ }
77
+ return String(process.env[name] ?? '').trim()
78
+ }
79
+
80
+ async function readPayload(response, locale) {
81
+ if (Number(response.headers.get('content-length')) > MAX_BYTES) {
82
+ await response.body?.cancel().catch(() => {})
83
+ throw failure(locale, 'payload')
84
+ }
85
+ try {
86
+ const parts = []
87
+ let bytes = 0
88
+ for await (const part of response.body) {
89
+ bytes += part.length
90
+ if (bytes > MAX_BYTES) throw failure(locale, 'payload')
91
+ parts.push(part)
92
+ }
93
+ return JSON.parse(Buffer.concat(parts).toString('utf8'))
94
+ } catch { throw failure(locale, 'payload') }
95
+ }
96
+
97
+ export async function queryAliyunBalance(ctx, config, { fetchImpl = fetch, signal } = {}) {
98
+ signal?.throwIfAborted()
99
+ const locale = config?.locale
100
+ const [ak, sk, token] = await Promise.all(ALIYUN_BALANCE_CREDENTIAL_VARS.map(name => resolveCredential(ctx, name)))
101
+ if (!ak || !sk) throw Object.assign(failure(locale, 'missing'), { soft: true })
102
+ let response
103
+ try {
104
+ // 每次网络重试重新生成时间戳与 nonce;URL、Action、body 均固定为只读账户查询。
105
+ response = await fetchWithRetry(ALIYUN_BALANCE_URL, { signal }, {
106
+ attempts: 2, timeoutMs: 15000,
107
+ fetchImpl: (url, init) => fetchImpl(url, { ...signAliyunBalanceRequest(ak, sk, token), signal: init.signal }),
108
+ })
109
+ } catch {
110
+ signal?.throwIfAborted()
111
+ throw failure(locale, 'network')
112
+ }
113
+ if (!response.ok) {
114
+ await response.body?.cancel().catch(() => {})
115
+ if (response.status >= 300 && response.status < 400) throw failure(locale, 'redirect')
116
+ if (response.status === 401 || response.status === 403) throw failure(locale, 'permission')
117
+ throw failure(locale, 'http', response.status)
118
+ }
119
+ const data = await readPayload(response, locale)
120
+ // 不把上游 Message/RequestId/账户身份下发浏览器;即使错误响应夹带余额也不能记作成功。
121
+ if ((data?.Code && data.Code !== 'Success') || data?.Success === false) throw failure(locale, 'permission')
122
+ return { label: config?.customBalance?.label || '千问 / 阿里云', ...parseAliyunBalance(data, locale) }
123
+ }