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
@@ -0,0 +1,205 @@
1
+ import crypto from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import fsp from 'node:fs/promises'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ export const FILE_UPLOAD_REQUEST_TYPES = new Set([
8
+ 'file-upload-open', 'file-upload-chunk', 'file-upload-finish', 'file-upload-cancel',
9
+ ])
10
+ export const FILE_UPLOAD_DEFAULTS = Object.freeze({
11
+ fileUploadsEnabled: true,
12
+ fileUploadMaxBytes: 512 * 1024 * 1024,
13
+ fileUploadChunkBytes: 256 * 1024,
14
+ fileUploadMaxTransfers: 4,
15
+ fileUploadIdleMs: 2 * 60 * 1000,
16
+ fileUploadCommitTimeoutMs: 180_000,
17
+ })
18
+
19
+ function failure(code, message) { return Object.assign(new Error(message), { code }) }
20
+ function check(condition, code, message) { if (!condition) throw failure(code, message) }
21
+ function validName(name) {
22
+ return typeof name === 'string' && name.trim().length > 0 && name.length <= 255
23
+ && name !== '.' && name !== '..' && !/[\x00-\x1f\x7f/\\]/.test(name)
24
+ }
25
+
26
+ // Receive bounded chunks in a private spool, verify exact bytes, then use DSH's
27
+ // streaming attachment admission. Never interpret client names as host paths.
28
+ export function createFileUploadManager(api, configuration = {}) {
29
+ const options = { ...FILE_UPLOAD_DEFAULTS, ...configuration }
30
+ const payloadLimit = Math.max(0, Math.floor(((options.maxPayloadBytes ?? 144 * 1024 * 1024) - 4096) / 4) * 3)
31
+ const chunkBytes = Math.min(options.fileUploadChunkBytes, payloadLimit)
32
+ const transfers = new Map()
33
+ const completed = new Map()
34
+ const closedClients = new WeakSet()
35
+ let disposed = false
36
+
37
+ const cleanup = async transfer => {
38
+ if (transfer.handle) {
39
+ await transfer.handle.close().catch(() => {})
40
+ transfer.handle = undefined
41
+ }
42
+ if (transfer.directory) await fsp.rm(transfer.directory, { recursive: true, force: true })
43
+ }
44
+ const release = async transfer => {
45
+ try { await cleanup(transfer) } finally { transfers.delete(transfer.id) }
46
+ }
47
+ const stop = async transfer => {
48
+ transfer.abort.abort(failure('file-upload-cancelled', 'File upload cancelled'))
49
+ // Keep the slot reserved until its writes/Host commit have actually stopped.
50
+ await transfer.operation?.catch(() => {})
51
+ await release(transfer)
52
+ }
53
+ const assertActive = transfer => {
54
+ transfer.abort.signal.throwIfAborted()
55
+ check(!disposed && !closedClients.has(transfer.client), 'file-upload-cancelled', 'Upload connection closed')
56
+ }
57
+ const run = (transfer, task) => {
58
+ check(!transfer.operation, 'file-upload-busy', 'An upload operation is already in progress')
59
+ const operation = task()
60
+ transfer.operation = operation
61
+ return operation.finally(() => { if (transfer.operation === operation) transfer.operation = undefined })
62
+ }
63
+
64
+ const open = async (client, msg) => {
65
+ check(!disposed && !closedClients.has(client), 'file-upload-cancelled', 'Upload connection closed')
66
+ check(api.files?.available(), 'file-upload-unavailable', 'The official file upload service is unavailable')
67
+ check(typeof msg.sessionId === 'string' && msg.sessionId.trim(), 'bad-request', 'An existing sessionId is required')
68
+ check(msg.parentSessionId === undefined && msg.subagentMode === undefined, 'subagent/attachment-invalid', 'Subagent file uploads are unsupported')
69
+ check(validName(msg.name), 'bad-request', 'name must be a leaf filename of 1..255 characters without control characters')
70
+ check(Number.isSafeInteger(msg.size) && msg.size >= 0, 'bad-request', 'size must be a nonnegative safe integer')
71
+ check(msg.size <= options.fileUploadMaxBytes, 'file-too-large', 'File exceeds the configured upload limit')
72
+ check(typeof msg.sha256 === 'string' && /^[a-fA-F0-9]{64}$/.test(msg.sha256), 'bad-request', 'sha256 must contain 64 hexadecimal digits')
73
+ check(transfers.size < options.fileUploadMaxTransfers, 'file-upload-limit', 'Too many active uploads')
74
+ const transfer = {
75
+ id: crypto.randomUUID(), client, sessionId: msg.sessionId.trim(), name: msg.name,
76
+ size: msg.size, sha256: msg.sha256.toLowerCase(), offset: 0, hash: crypto.createHash('sha256'),
77
+ abort: new AbortController(), lastActiveAt: Date.now(),
78
+ }
79
+ transfers.set(transfer.id, transfer)
80
+ try {
81
+ return await run(transfer, async () => {
82
+ const sessions = await api.sessions.list({}, AbortSignal.any([
83
+ transfer.abort.signal, AbortSignal.timeout(options.fileUploadCommitTimeoutMs),
84
+ ]))
85
+ check(sessions.items?.some(item => item.sessionId === transfer.sessionId && item.origin !== 'subagent'),
86
+ 'session-not-found', 'No visible ordinary session exists with this ID')
87
+ assertActive(transfer)
88
+ transfer.directory = await fsp.mkdtemp(path.join(os.tmpdir(), 'dsh-mobile-upload-'))
89
+ transfer.path = path.join(transfer.directory, 'payload')
90
+ transfer.handle = await fsp.open(transfer.path, 'wx', 0o600)
91
+ assertActive(transfer)
92
+ return { kind: 'file-upload-opened', uploadId: transfer.id, sessionId: transfer.sessionId,
93
+ name: transfer.name, size: transfer.size, chunkBytes, maxBytes: options.fileUploadMaxBytes,
94
+ idleTimeoutMs: options.fileUploadIdleMs }
95
+ })
96
+ } catch (error) {
97
+ await release(transfer)
98
+ throw error
99
+ }
100
+ }
101
+
102
+ const receive = async (client, msg) => {
103
+ if (msg.type === 'file-upload-open') return open(client, msg)
104
+ check(typeof msg.uploadId === 'string' && msg.uploadId.length > 0, 'bad-request', 'uploadId is required')
105
+ const done = completed.get(msg.uploadId)
106
+ if (done?.client === client && msg.type === 'file-upload-finish') return done.frame
107
+ const transfer = transfers.get(msg.uploadId)
108
+ check(transfer?.client === client, 'file-upload-not-found', 'Upload is unknown or belongs to another connection')
109
+ if (msg.type === 'file-upload-cancel') {
110
+ await stop(transfer)
111
+ return { kind: 'file-upload-cancelled', uploadId: msg.uploadId, sessionId: transfer.sessionId }
112
+ }
113
+ assertActive(transfer)
114
+ return run(transfer, async () => {
115
+ transfer.lastActiveAt = Date.now()
116
+ if (msg.type === 'file-upload-chunk') {
117
+ check(Number.isSafeInteger(msg.offset) && msg.offset === transfer.offset,
118
+ 'file-upload-offset', 'offset must equal the next expected byte')
119
+ check(typeof msg.data === 'string' && msg.data.length > 0 && msg.data.length <= Math.ceil(chunkBytes / 3) * 4,
120
+ 'file-upload-invalid-data', 'Chunk must be nonempty canonical base64 within chunkBytes')
121
+ const bytes = Buffer.from(msg.data, 'base64')
122
+ check(bytes.length > 0 && bytes.length <= chunkBytes && bytes.toString('base64') === msg.data,
123
+ 'file-upload-invalid-data', 'Chunk must be nonempty canonical base64 within chunkBytes')
124
+ check(transfer.offset + bytes.length <= transfer.size, 'file-upload-size', 'Chunk exceeds declared size')
125
+ try {
126
+ let written = 0
127
+ while (written < bytes.length) {
128
+ assertActive(transfer)
129
+ const result = await transfer.handle.write(bytes, written, bytes.length - written, transfer.offset + written)
130
+ check(result.bytesWritten > 0, 'file-upload-write-failed', 'Upload write made no progress')
131
+ written += result.bytesWritten
132
+ }
133
+ } catch (error) {
134
+ transfer.abort.abort(error)
135
+ await release(transfer)
136
+ throw error
137
+ }
138
+ assertActive(transfer)
139
+ transfer.hash.update(bytes)
140
+ transfer.offset += bytes.length
141
+ return { kind: 'file-upload-chunk-accepted', uploadId: transfer.id, sessionId: transfer.sessionId, nextOffset: transfer.offset }
142
+ }
143
+ check(transfer.offset === transfer.size, 'file-upload-incomplete', 'Not all declared bytes have arrived')
144
+ try {
145
+ check(transfer.hash.digest('hex') === transfer.sha256, 'file-upload-checksum', 'SHA-256 does not match the uploaded bytes')
146
+ await transfer.handle.close()
147
+ transfer.handle = undefined
148
+ const signal = AbortSignal.any([transfer.abort.signal, AbortSignal.timeout(options.fileUploadCommitTimeoutMs)])
149
+ const result = await api.files.upload({ sessionId: transfer.sessionId, name: transfer.name,
150
+ data: fs.createReadStream(transfer.path, { highWaterMark: chunkBytes }) }, signal)
151
+ signal.throwIfAborted()
152
+ assertActive(transfer)
153
+ check(typeof result.receiptId === 'string' && result.receiptId.length > 0
154
+ && typeof result.file?.attachmentId === 'string' && result.file.attachmentId.length > 0
155
+ && typeof result.file.name === 'string' && result.file.bytes === transfer.size,
156
+ 'file-upload-invalid-response', 'Official upload result does not match the declared file')
157
+ const frame = { kind: 'file-upload-completed', uploadId: transfer.id, sessionId: transfer.sessionId,
158
+ receiptId: result.receiptId, file: { attachmentId: result.file.attachmentId, name: result.file.name, bytes: result.file.bytes },
159
+ sha256: transfer.sha256 }
160
+ completed.set(transfer.id, { client, frame, lastActiveAt: Date.now() })
161
+ if (completed.size > 128) completed.delete(completed.keys().next().value)
162
+ return frame
163
+ } finally {
164
+ await release(transfer)
165
+ }
166
+ })
167
+ }
168
+
169
+ return {
170
+ async handle(client, msg) {
171
+ const correlation = {
172
+ ...(typeof msg.requestId === 'string' ? { requestId: msg.requestId } : {}),
173
+ ...(typeof msg.sessionId === 'string' ? { sessionId: msg.sessionId } : {}),
174
+ ...(typeof msg.uploadId === 'string' ? { uploadId: msg.uploadId } : {}),
175
+ }
176
+ try {
177
+ check(options.fileUploadsEnabled, 'file-upload-disabled', 'File uploads are disabled')
178
+ check(typeof msg.requestId === 'string' && msg.requestId.trim().length > 0 && msg.requestId.length <= 128,
179
+ 'bad-request', 'requestId must contain 1..128 characters')
180
+ const frame = await receive(client, msg)
181
+ return { ...frame, requestId: msg.requestId }
182
+ } catch (error) {
183
+ return { kind: 'error', requestType: msg.type, ...correlation,
184
+ code: error.name === 'TimeoutError' ? 'file-upload-timeout'
185
+ : typeof error.code === 'string' ? error.code : 'file-upload-failed',
186
+ message: error.message || 'File upload failed' }
187
+ }
188
+ },
189
+ async closeClient(client) {
190
+ closedClients.add(client)
191
+ await Promise.all([...transfers.values()].filter(transfer => transfer.client === client).map(stop))
192
+ for (const [id, done] of completed) if (done.client === client) completed.delete(id)
193
+ },
194
+ async expire() {
195
+ const cutoff = Date.now() - options.fileUploadIdleMs
196
+ await Promise.all([...transfers.values()].filter(transfer => !transfer.operation && transfer.lastActiveAt < cutoff).map(stop))
197
+ for (const [id, done] of completed) if (done.lastActiveAt < cutoff) completed.delete(id)
198
+ },
199
+ async dispose() {
200
+ disposed = true
201
+ await Promise.all([...transfers.values()].map(stop))
202
+ completed.clear()
203
+ },
204
+ }
205
+ }
@@ -1,6 +1,6 @@
1
- // Echo only a strictly bounded, non-secret challenge on an unauthenticated
2
- // rejection. This does not authorize a device or expose management data.
3
- export function gatewayProbeHeader(value) {
4
- return typeof value === 'string' && /^[a-f0-9]{32}$/.test(value)
5
- ? `X-DSH-Gateway-Probe: ${value}\r\n` : ''
6
- }
1
+ // Echo only a strictly bounded, non-secret challenge on an unauthenticated
2
+ // rejection. This does not authorize a device or expose management data.
3
+ export function gatewayProbeHeader(value) {
4
+ return typeof value === 'string' && /^[a-f0-9]{32}$/.test(value)
5
+ ? `X-DSH-Gateway-Probe: ${value}\r\n` : ''
6
+ }
@@ -1,57 +1,57 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import crypto from 'node:crypto'
4
-
5
- export const GATEWAY_MODES = ['disabled', 'temporary', 'persistent']
6
-
7
- // A dedicated file keeps installation identity independent of device revocation.
8
- // A malformed file must fail startup rather than silently replace that identity.
9
- export function createGatewayState(file) {
10
- const validate = (value) => {
11
- if (!value || value.version !== 1 ||
12
- typeof value.gatewayId !== 'string' ||
13
- !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.gatewayId) ||
14
- (value.mode !== null && !GATEWAY_MODES.includes(value.mode))) {
15
- throw new Error('invalid gateway identity or mode')
16
- }
17
- return value
18
- }
19
- const read = () => validate(JSON.parse(fs.readFileSync(file, 'utf8')))
20
- const write = (value, initial = false) => {
21
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
22
- const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`
23
- try {
24
- fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
25
- if (initial) fs.linkSync(tmp, file) // Never overwrite a concurrently created identity.
26
- else fs.renameSync(tmp, file)
27
- } finally {
28
- fs.rmSync(tmp, { force: true })
29
- }
30
- }
31
- let state
32
- try {
33
- try {
34
- state = read()
35
- } catch (error) {
36
- if (error.code !== 'ENOENT') throw error
37
- state = { version: 1, gatewayId: crypto.randomUUID(), mode: null }
38
- try { write(state, true) } catch (cause) {
39
- if (cause.code !== 'EEXIST') throw cause
40
- state = read()
41
- }
42
- }
43
- fs.chmodSync(file, 0o600)
44
- } catch (error) {
45
- throw new Error(`failed to load gateway state ${file}: ${error.message}`, { cause: error })
46
- }
47
- return {
48
- get gatewayId() { return state.gatewayId },
49
- get mode() { return state.mode },
50
- setMode(mode) {
51
- if (!GATEWAY_MODES.includes(mode)) throw new TypeError('invalid gateway mode')
52
- const next = { ...state, mode }
53
- write(next)
54
- state = next
55
- },
56
- }
57
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+
5
+ export const GATEWAY_MODES = ['disabled', 'temporary', 'persistent']
6
+
7
+ // A dedicated file keeps installation identity independent of device revocation.
8
+ // A malformed file must fail startup rather than silently replace that identity.
9
+ export function createGatewayState(file) {
10
+ const validate = (value) => {
11
+ if (!value || value.version !== 1 ||
12
+ typeof value.gatewayId !== 'string' ||
13
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.gatewayId) ||
14
+ (value.mode !== null && !GATEWAY_MODES.includes(value.mode))) {
15
+ throw new Error('invalid gateway identity or mode')
16
+ }
17
+ return value
18
+ }
19
+ const read = () => validate(JSON.parse(fs.readFileSync(file, 'utf8')))
20
+ const write = (value, initial = false) => {
21
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
22
+ const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`
23
+ try {
24
+ fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
25
+ if (initial) fs.linkSync(tmp, file) // Never overwrite a concurrently created identity.
26
+ else fs.renameSync(tmp, file)
27
+ } finally {
28
+ fs.rmSync(tmp, { force: true })
29
+ }
30
+ }
31
+ let state
32
+ try {
33
+ try {
34
+ state = read()
35
+ } catch (error) {
36
+ if (error.code !== 'ENOENT') throw error
37
+ state = { version: 1, gatewayId: crypto.randomUUID(), mode: null }
38
+ try { write(state, true) } catch (cause) {
39
+ if (cause.code !== 'EEXIST') throw cause
40
+ state = read()
41
+ }
42
+ }
43
+ fs.chmodSync(file, 0o600)
44
+ } catch (error) {
45
+ throw new Error(`failed to load gateway state ${file}: ${error.message}`, { cause: error })
46
+ }
47
+ return {
48
+ get gatewayId() { return state.gatewayId },
49
+ get mode() { return state.mode },
50
+ setMode(mode) {
51
+ if (!GATEWAY_MODES.includes(mode)) throw new TypeError('invalid gateway mode')
52
+ const next = { ...state, mode }
53
+ write(next)
54
+ state = next
55
+ },
56
+ }
57
+ }
@@ -1,36 +1,36 @@
1
- import { spawn } from 'node:child_process'
2
- import { realpathSync } from 'node:fs'
3
- import { fileURLToPath } from 'node:url'
4
-
5
- export function webRestartAvailable(profile, runtime = process) {
6
- if (profile?.name !== 'web' || !runtime.argv?.[1]) return false
7
- try {
8
- return /[/\\]@deepseek-ai[/\\]dsh[/\\]lib[/\\]bin\.js$/.test(realpathSync(runtime.argv[1]))
9
- } catch {
10
- return false
11
- }
12
- }
13
-
14
- export async function prepareWebRestart(runtime = process, spawnChild = spawn) {
15
- const argv = runtime.argv.slice(1)
16
- // DSH Web opens a browser on every boot by default. This restart was
17
- // initiated from an existing tab, so keep that tab and suppress the handoff.
18
- const terminator = argv.indexOf('--')
19
- const flagEnd = terminator < 0 ? argv.length : terminator
20
- if (!argv.slice(0, flagEnd).includes('--no-open')) argv.splice(flagEnd, 0, '--no-open')
21
- const payload = Buffer.from(JSON.stringify({
22
- pid: runtime.pid,
23
- execPath: runtime.execPath,
24
- execArgv: runtime.execArgv,
25
- argv,
26
- cwd: runtime.cwd(),
27
- })).toString('base64url')
28
- const helper = spawnChild(runtime.execPath, [fileURLToPath(new URL('./web-restart.mjs', import.meta.url)), payload], {
29
- cwd: runtime.cwd(), env: runtime.env, detached: true, stdio: 'ignore',
30
- })
31
- await new Promise((resolve, reject) => {
32
- helper.once('spawn', resolve)
33
- helper.once('error', reject)
34
- })
35
- helper.unref()
36
- }
1
+ import { spawn } from 'node:child_process'
2
+ import { realpathSync } from 'node:fs'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ export function webRestartAvailable(profile, runtime = process) {
6
+ if (profile?.name !== 'web' || !runtime.argv?.[1]) return false
7
+ try {
8
+ return /[/\\]@deepseek-ai[/\\]dsh[/\\]lib[/\\]bin\.js$/.test(realpathSync(runtime.argv[1]))
9
+ } catch {
10
+ return false
11
+ }
12
+ }
13
+
14
+ export async function prepareWebRestart(runtime = process, spawnChild = spawn) {
15
+ const argv = runtime.argv.slice(1)
16
+ // DSH Web opens a browser on every boot by default. This restart was
17
+ // initiated from an existing tab, so keep that tab and suppress the handoff.
18
+ const terminator = argv.indexOf('--')
19
+ const flagEnd = terminator < 0 ? argv.length : terminator
20
+ if (!argv.slice(0, flagEnd).includes('--no-open')) argv.splice(flagEnd, 0, '--no-open')
21
+ const payload = Buffer.from(JSON.stringify({
22
+ pid: runtime.pid,
23
+ execPath: runtime.execPath,
24
+ execArgv: runtime.execArgv,
25
+ argv,
26
+ cwd: runtime.cwd(),
27
+ })).toString('base64url')
28
+ const helper = spawnChild(runtime.execPath, [fileURLToPath(new URL('./web-restart.mjs', import.meta.url)), payload], {
29
+ cwd: runtime.cwd(), env: runtime.env, detached: true, stdio: 'ignore',
30
+ })
31
+ await new Promise((resolve, reject) => {
32
+ helper.once('spawn', resolve)
33
+ helper.once('error', reject)
34
+ })
35
+ helper.unref()
36
+ }
@@ -0,0 +1,66 @@
1
+ // Short-lived LRU for immutable history pages (`beforeSeq` cut). The host has to
2
+ // re-read the session log for every page, so caching pages makes scrolling back
3
+ // through already-visited regions instant and lets a background prefetch warm
4
+ // the next pages before the client asks for them.
5
+
6
+ export function historyCacheKey(sessionId, msg) {
7
+ const before = msg && typeof msg.beforeSeq === 'number' ? msg.beforeSeq : 'tail'
8
+ // A child session's ID is only meaningful together with its durable parent
9
+ // address and lifecycle mode; never reuse a page across those targets.
10
+ return [sessionId, msg && msg.parentSessionId, msg && (msg.subagentMode ?? msg.mode), before,
11
+ msg && msg.maxMessages, msg && msg.maxBytes, msg && msg.view].join('|')
12
+ }
13
+
14
+ export function createHistoryCache(options = {}) {
15
+ const maxEntries = Number.isSafeInteger(options.maxEntries) && options.maxEntries > 0 ? options.maxEntries : 60
16
+ const maxBytes = Number.isSafeInteger(options.maxBytes) && options.maxBytes > 0 ? options.maxBytes : 64 * 1024 * 1024
17
+ const ttlMs = Number.isSafeInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : 5 * 60 * 1000
18
+ const entries = new Map()
19
+ let totalBytes = 0
20
+
21
+ function sizeOf(frame) {
22
+ const bytes = Number(frame && frame.bytes)
23
+ return Number.isFinite(bytes) && bytes > 0 ? Math.min(bytes, 4 * 1024 * 1024) : 64 * 1024
24
+ }
25
+
26
+ function drop(key) {
27
+ const entry = entries.get(key)
28
+ if (!entry) return
29
+ entries.delete(key)
30
+ totalBytes -= entry.size
31
+ }
32
+
33
+ function prune(now) {
34
+ for (const [key, entry] of entries) {
35
+ if (now - entry.at > ttlMs) drop(key)
36
+ }
37
+ while (entries.size > 0 && (entries.size > maxEntries || totalBytes > maxBytes)) {
38
+ const oldest = entries.keys().next().value
39
+ drop(oldest)
40
+ }
41
+ }
42
+
43
+ return {
44
+ get(key, now = Date.now()) {
45
+ const entry = entries.get(key)
46
+ if (!entry) return null
47
+ if (now - entry.at > ttlMs) { drop(key); return null }
48
+ // Refresh recency without changing insertion semantics too much.
49
+ entries.delete(key)
50
+ entries.set(key, entry)
51
+ return entry.frame
52
+ },
53
+ set(key, frame, now = Date.now()) {
54
+ if (!frame || frame.kind !== 'history') return
55
+ if (entries.has(key)) drop(key)
56
+ const size = sizeOf(frame)
57
+ entries.set(key, { frame, at: now, size })
58
+ totalBytes += size
59
+ prune(now)
60
+ },
61
+ has(key, now = Date.now()) { return this.get(key, now) !== null },
62
+ get size() { return entries.size },
63
+ get bytes() { return totalBytes },
64
+ clear() { entries.clear(); totalBytes = 0 },
65
+ }
66
+ }