dsh-remote-plugin 0.8.0-rc.8 → 0.8.0-rc.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.
- package/README.en.md +10 -5
- package/README.md +10 -5
- package/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +401 -165
- package/index.mjs +29 -16
- package/package.json +1 -1
- package/plugin-center.mjs +2 -2
- package/plugin-transaction.mjs +18 -2
- package/public/admin.html +1 -1
- package/public/admin.js +2 -1
- package/public/app.js +291 -97
- package/public/approval-records.js +229 -0
- package/public/build.json +2 -2
- package/public/desktop/desktop.css +52 -0
- package/public/desktop/desktop.html +39 -2
- package/public/desktop/desktop.js +192 -60
- package/public/doctor-entry.js +33 -4
- package/public/doctor.js +41 -13
- package/public/index.html +44 -9
- package/public/onboarding.css +36 -0
- package/public/onboarding.js +253 -0
- package/public/operations.js +1 -1
- package/public/permission-presets.js +159 -0
- package/public/plugin.html +1 -1
- package/public/plugin.js +5 -1
- package/public/skins/blue-fish/skin.css +12 -0
- package/public/styles.css +43 -1
- package/public/theme.js +5 -11
- package/public/turn-results.js +2 -0
- package/public/update.json +4 -4
- package/public/version.json +1 -1
- package/public/workflow.js +13 -4
package/gateway.cjs
CHANGED
|
@@ -590,7 +590,7 @@ const CRASH_LOG_FILE=process.env.DSH_REMOTE_CRASH_LOG_FILE || path.join(os.homed
|
|
|
590
590
|
const AUTO_RESTART=process.env.DSH_REMOTE_AUTO_RESTART!=='0'
|
|
591
591
|
const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash','lease-recovered','lease-conflict','lease-failed'])
|
|
592
592
|
const CRASH_COMPONENTS=new Set(['gateway','dsh','desktop'])
|
|
593
|
-
const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED','SUPERVISOR_ALREADY_RUNNING','SUPERVISOR_IDENTITY_UNAVAILABLE','SUPERVISOR_LEASE_STALE','SUPERVISOR_LEASE_INVALID'])
|
|
593
|
+
const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','EINVAL','ENAMETOOLONG','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED','SUPERVISOR_ALREADY_RUNNING','SUPERVISOR_IDENTITY_UNAVAILABLE','SUPERVISOR_ENDPOINT_TOO_LONG','SUPERVISOR_LEASE_STALE','SUPERVISOR_LEASE_INVALID'])
|
|
594
594
|
function safeCrashRecord(value) {
|
|
595
595
|
const row={at:Number.isFinite(value?.at)?value.at:Date.now(),component:CRASH_COMPONENTS.has(value?.component)?value.component:'gateway',kind:CRASH_KINDS.has(value?.kind)?value.kind:'fatal'}
|
|
596
596
|
if(Number.isInteger(value?.exitCode))row.exitCode=value.exitCode
|
|
@@ -774,32 +774,71 @@ async function legacyGatewaySupervisorAlive(owner, modifiedAt) {
|
|
|
774
774
|
return /(?:^|[\\/\s"'])gateway\.(?:js|cjs)(?:["'\s]|$)/i.test(command)
|
|
775
775
|
}
|
|
776
776
|
|
|
777
|
+
function supervisorSocketPath(tmpdir,key) {
|
|
778
|
+
return path.join(tmpdir,'dsh-remote-supervisor-'+key+'.sock')
|
|
779
|
+
}
|
|
780
|
+
function pickSupervisorEndpoint({tmpdir,key,fallback='/tmp'}) {
|
|
781
|
+
for(const directory of [tmpdir,fallback]){
|
|
782
|
+
const candidate=supervisorSocketPath(directory,key)
|
|
783
|
+
// Leave room for sun_path's terminator on macOS (104 bytes including NUL).
|
|
784
|
+
if(Buffer.byteLength(candidate)<=100)return candidate
|
|
785
|
+
}
|
|
786
|
+
throw fault('SUPERVISOR_ENDPOINT_TOO_LONG')
|
|
787
|
+
}
|
|
788
|
+
async function listenSupervisorEndpoint(endpoint,fileSocket) {
|
|
789
|
+
const lock=net.createServer(socket=>socket.destroy())
|
|
790
|
+
const listen=()=>new Promise((resolve,reject)=>{
|
|
791
|
+
const failed=error=>{lock.removeListener('listening',ready);reject(error)}
|
|
792
|
+
const ready=()=>{lock.removeListener('error',failed);resolve(lock)}
|
|
793
|
+
lock.once('error',failed);lock.once('listening',ready);lock.listen(endpoint)
|
|
794
|
+
})
|
|
795
|
+
try {
|
|
796
|
+
await listen().catch(async error=>{
|
|
797
|
+
if(!fileSocket||error.code!=='EADDRINUSE')throw error
|
|
798
|
+
let before
|
|
799
|
+
try{before=fs.statSync(endpoint)}catch(error){if(error.code!=='ENOENT')throw error}
|
|
800
|
+
if(before){
|
|
801
|
+
const unused=await new Promise(resolve=>{
|
|
802
|
+
const socket=net.connect(endpoint),done=value=>{socket.destroy();resolve(value)}
|
|
803
|
+
socket.once('connect',()=>done(false));socket.once('error',e=>done(e.code==='ECONNREFUSED'||e.code==='ENOENT'));socket.setTimeout(1000,()=>done(false))
|
|
804
|
+
})
|
|
805
|
+
if(!unused)throw error
|
|
806
|
+
let now
|
|
807
|
+
try{now=fs.statSync(endpoint)}catch(error){if(error.code!=='ENOENT')throw error}
|
|
808
|
+
if(now){if(now.ino!==before.ino||now.mtimeMs!==before.mtimeMs)throw error;fs.unlinkSync(endpoint)}
|
|
809
|
+
}
|
|
810
|
+
await listen()
|
|
811
|
+
})
|
|
812
|
+
if(fileSocket)fs.chmodSync(endpoint,0o600)
|
|
813
|
+
return lock
|
|
814
|
+
}catch(error){
|
|
815
|
+
if(lock.listening)lock.close()
|
|
816
|
+
if(fileSocket&&['EINVAL','ENAMETOOLONG'].includes(error.code))throw Object.assign(fault('SUPERVISOR_ENDPOINT_TOO_LONG'),{cause:error})
|
|
817
|
+
throw error
|
|
818
|
+
}
|
|
819
|
+
}
|
|
777
820
|
async function lockGatewaySupervisor(lease) {
|
|
778
|
-
// These kernel-owned endpoints disappear even on TerminateProcess/SIGKILL.
|
|
779
821
|
// Key by the real state directory + port, independent of package/cwd upgrades.
|
|
780
822
|
let identity=path.join(fs.realpathSync(path.dirname(lease)),path.basename(lease))
|
|
781
823
|
if(process.platform==='win32')identity=identity.toLowerCase()
|
|
782
824
|
const key=crypto.createHash('sha256').update(identity).digest('hex').slice(0,40)
|
|
783
825
|
const [major,minor]=process.versions.node.split('.').map(Number)
|
|
784
826
|
const abstract=process.platform==='linux'&&(major>20||(major===20&&minor>=8))
|
|
827
|
+
const fileSocket=process.platform!=='win32'&&!abstract,tmpdir=os.tmpdir()
|
|
828
|
+
// Keep Windows named pipes and Linux abstract names byte-for-byte compatible.
|
|
785
829
|
const endpoint=process.platform==='win32'?'\\\\.\\pipe\\dsh-remote-supervisor-'+key
|
|
786
|
-
:abstract?'\0dsh-remote-supervisor-'+key:
|
|
787
|
-
const
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
const socket=net.connect(endpoint),done=value=>{socket.destroy();resolve(value)}
|
|
799
|
-
socket.once('connect',()=>done(false));socket.once('error',e=>done(e.code==='ECONNREFUSED'||e.code==='ENOENT'));socket.setTimeout(1000,()=>done(false))
|
|
800
|
-
})
|
|
801
|
-
if(unused){const now=fs.statSync(endpoint);if(now.ino===before.ino&&now.mtimeMs===before.mtimeMs){fs.unlinkSync(endpoint);return listen()}}
|
|
802
|
-
}
|
|
830
|
+
:abstract?'\0dsh-remote-supervisor-'+key:pickSupervisorEndpoint({tmpdir,key:key.slice(0,16)})
|
|
831
|
+
const locks=[]
|
|
832
|
+
try {
|
|
833
|
+
locks.push(await listenSupervisorEndpoint(endpoint,fileSocket))
|
|
834
|
+
if(fileSocket){
|
|
835
|
+
const legacy=supervisorSocketPath(tmpdir,key),limit=process.platform==='linux'?107:103
|
|
836
|
+
// Also hold an old, usable endpoint: an older binary may start during upgrade.
|
|
837
|
+
if(legacy!==endpoint&&Buffer.byteLength(legacy)<=limit)locks.push(await listenSupervisorEndpoint(legacy,true))
|
|
838
|
+
}
|
|
839
|
+
return {verifyLease:fileSocket,close:()=>{for(const lock of locks)lock.close()}}
|
|
840
|
+
}catch(error){
|
|
841
|
+
for(const lock of locks)lock.close()
|
|
803
842
|
throw error
|
|
804
843
|
}
|
|
805
844
|
}
|
|
@@ -816,9 +855,10 @@ async function runGatewaySupervisor() {
|
|
|
816
855
|
const raw=fs.readFileSync(lease,'utf8');modifiedAt=fs.statSync(lease).mtimeMs
|
|
817
856
|
try{old=JSON.parse(raw);recovered='SUPERVISOR_LEASE_STALE'}catch{recovered='SUPERVISOR_LEASE_INVALID'}
|
|
818
857
|
}catch(error){if(error.code!=='ENOENT')throw error}
|
|
819
|
-
//
|
|
820
|
-
//
|
|
821
|
-
|
|
858
|
+
// File endpoints may move after shortening or TMPDIR fallback. Check even v2
|
|
859
|
+
// leases during that migration, using command + birth identity, never PID alone.
|
|
860
|
+
// Named pipes/abstract locks retain their names and remain authoritative for v2.
|
|
861
|
+
if((old?.version!==2||lock.verifyLease)&&await legacyGatewaySupervisorAlive(old,modifiedAt)){
|
|
822
862
|
throw Object.assign(Error('supervisor already running'),{code:'SUPERVISOR_ALREADY_RUNNING'})
|
|
823
863
|
}
|
|
824
864
|
const temporary=lease+'.'+nonce+'.tmp'
|
|
@@ -1082,7 +1122,7 @@ let fsWorkspaceRootsCache = { roots: [], reals: [], fetchedAt: 0 }
|
|
|
1082
1122
|
let fsWorkspaceRootsFetch = null
|
|
1083
1123
|
function fsRootReals() {
|
|
1084
1124
|
if (!FS_ROOT_REALS) {
|
|
1085
|
-
FS_ROOT_REALS = FS_ROOTS.map(r => { try { return fs.realpathSync(r) } catch { return null } }).filter(Boolean)
|
|
1125
|
+
FS_ROOT_REALS = FS_ROOTS.map(r => { try { return (fs.realpathSync.native || fs.realpathSync)(r) } catch { return null } }).filter(Boolean)
|
|
1086
1126
|
}
|
|
1087
1127
|
return FS_ROOT_REALS
|
|
1088
1128
|
}
|
|
@@ -1097,18 +1137,28 @@ function fsInsideReal(real) {
|
|
|
1097
1137
|
// 网关自身的状态与安装目录永远不出现在 /fs 通道里: 设备密钥同样能访问 /fs,
|
|
1098
1138
|
// 若允许读取就等同于把主令牌(以及其它设备密钥)直接交出去, 允许写入还能替换
|
|
1099
1139
|
// 正在对外提供的静态资源或网关文件。显式配置到其它位置的状态文件按精确路径保护。
|
|
1140
|
+
function fsCanonicalPath(value) {
|
|
1141
|
+
let current = path.resolve(value)
|
|
1142
|
+
const suffix = []
|
|
1143
|
+
while (true) {
|
|
1144
|
+
try { return path.join((fs.realpathSync.native || fs.realpathSync)(current), ...suffix) }
|
|
1145
|
+
catch (error) {
|
|
1146
|
+
const parent = path.dirname(current)
|
|
1147
|
+
if (!['ENOENT', 'ENOTDIR'].includes(error.code) || parent === current) return path.resolve(value)
|
|
1148
|
+
suffix.unshift(path.basename(current)); current = parent
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1100
1152
|
const FS_PROTECTED_DIRS = [...new Set([
|
|
1101
1153
|
path.resolve(path.join(FS_DEFAULT_ROOT, '.dsh-remote')),
|
|
1102
1154
|
path.resolve(ROOT),
|
|
1103
1155
|
path.resolve(DSH_CONTROL_DIR),
|
|
1104
|
-
])]
|
|
1156
|
+
].flatMap(value => [value, fsCanonicalPath(value)]))]
|
|
1105
1157
|
const FS_PROTECTED_FILES = [...new Set([TOKEN_FILE, DEVICE_KEYS_FILE, NOTES_FILE, WORKBENCH_FILE,
|
|
1106
|
-
HANDOFF_FILE, DSH_UPSTREAM_COOKIE_FILE, DSH_LAUNCH_FILE].filter(Boolean).
|
|
1158
|
+
HANDOFF_FILE, DSH_UPSTREAM_COOKIE_FILE, DSH_LAUNCH_FILE].filter(Boolean).flatMap(value => [path.resolve(String(value)), fsCanonicalPath(String(value))]))]
|
|
1107
1159
|
|
|
1108
1160
|
function fsSamePath(left, right) {
|
|
1109
|
-
|
|
1110
|
-
const b = path.resolve(String(right || ''))
|
|
1111
|
-
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
|
|
1161
|
+
return fsInsideRoot(left, right) && fsInsideRoot(right, left)
|
|
1112
1162
|
}
|
|
1113
1163
|
|
|
1114
1164
|
/** 路径是否命中受保护目录(目录内全部)或受保护文件(精确匹配)。realpath 结果同样适用。 */
|
|
@@ -1662,7 +1712,8 @@ function httpGetJson(url, cb) {
|
|
|
1662
1712
|
agent
|
|
1663
1713
|
}, (res) => {
|
|
1664
1714
|
let body = ''
|
|
1665
|
-
res.
|
|
1715
|
+
res.setEncoding('utf8')
|
|
1716
|
+
res.on('data', c => { body += c; if (Buffer.byteLength(body) > 512 * 1024) res.destroy() })
|
|
1666
1717
|
res.on('end', () => {
|
|
1667
1718
|
if (res.statusCode >= 400) return done(new Error('HTTP ' + res.statusCode))
|
|
1668
1719
|
try { done(null, JSON.parse(body)) } catch (e) { done(e) }
|
|
@@ -1703,7 +1754,8 @@ function httpGetJson(url, cb) {
|
|
|
1703
1754
|
headers: { host: u.host, 'user-agent': 'dsh-remote-gateway/' + VERSION, accept: 'application/json' }
|
|
1704
1755
|
}, (res) => {
|
|
1705
1756
|
let body = ''
|
|
1706
|
-
res.
|
|
1757
|
+
res.setEncoding('utf8')
|
|
1758
|
+
res.on('data', c => { body += c; if (Buffer.byteLength(body) > 512 * 1024) res.destroy() })
|
|
1707
1759
|
res.on('end', () => {
|
|
1708
1760
|
if (res.statusCode >= 400) return done(new Error('HTTP ' + res.statusCode))
|
|
1709
1761
|
try { done(null, JSON.parse(body)) } catch (e) { done(e) }
|
|
@@ -1784,8 +1836,8 @@ function readBody(req, maxBytes = 64 * 1024) {
|
|
|
1784
1836
|
size += chunk.length
|
|
1785
1837
|
if (size > maxBytes) {
|
|
1786
1838
|
settled = true
|
|
1787
|
-
|
|
1788
|
-
|
|
1839
|
+
chunks.length = 0
|
|
1840
|
+
reject(Object.assign(new Error('request body too large'), { status: 413, code: 'body-too-large' }))
|
|
1789
1841
|
return
|
|
1790
1842
|
}
|
|
1791
1843
|
chunks.push(chunk)
|
|
@@ -1800,6 +1852,19 @@ function readBody(req, maxBytes = 64 * 1024) {
|
|
|
1800
1852
|
settled = true
|
|
1801
1853
|
reject(err)
|
|
1802
1854
|
})
|
|
1855
|
+
req.once('aborted', () => {
|
|
1856
|
+
if (settled) return
|
|
1857
|
+
settled = true
|
|
1858
|
+
reject(Object.assign(new Error('request aborted'), { status: 400, code: 'request-aborted' }))
|
|
1859
|
+
})
|
|
1860
|
+
})
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
function withRequestBody(req, res, limit, callback) {
|
|
1864
|
+
void readBody(req, limit).then(callback).catch(error => {
|
|
1865
|
+
if (res.writableEnded || res.destroyed) return
|
|
1866
|
+
if (res.headersSent) return res.destroy()
|
|
1867
|
+
fsJson(res, error.status || 500, { error: error.status === 413 ? 'body-too-large' : 'bad-request' }, { connection: 'close' })
|
|
1803
1868
|
})
|
|
1804
1869
|
}
|
|
1805
1870
|
|
|
@@ -2715,6 +2780,8 @@ const modernState = {
|
|
|
2715
2780
|
workspaces: { items: [], archivedSessionIds: [] },
|
|
2716
2781
|
pendingEvents: new Map(),
|
|
2717
2782
|
assistantStreams: new Map(),
|
|
2783
|
+
sessionInterests: new Map(),
|
|
2784
|
+
followedSessions: new Set(),
|
|
2718
2785
|
}
|
|
2719
2786
|
|
|
2720
2787
|
async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID()) {
|
|
@@ -2776,8 +2843,9 @@ function updateModernSessions(items) {
|
|
|
2776
2843
|
if (!item?.sessionId) continue
|
|
2777
2844
|
modernState.sessions.set(item.sessionId, item)
|
|
2778
2845
|
const cursor = Number(item.projections?.asOfSeq)
|
|
2779
|
-
if (item.projections?.kind !== 'cached' && Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
|
|
2846
|
+
if (modernState.followedSessions?.has(item.sessionId) && item.projections?.kind !== 'cached' && Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
|
|
2780
2847
|
}
|
|
2848
|
+
eventCollectors.mux?.syncSessions?.()
|
|
2781
2849
|
}
|
|
2782
2850
|
|
|
2783
2851
|
function legacyEnvelope(rpcId, result) {
|
|
@@ -2820,6 +2888,28 @@ async function refreshModernSessions() {
|
|
|
2820
2888
|
return response
|
|
2821
2889
|
}
|
|
2822
2890
|
|
|
2891
|
+
// The permission catalog mixes configured presets, the live experimental `auto`
|
|
2892
|
+
// contribution and derived `custom`. Remote republishes only rows a client can
|
|
2893
|
+
// render, with bounded text; `custom` is display-only and never a switch target.
|
|
2894
|
+
function modernPermissionCatalog(value) {
|
|
2895
|
+
const option = item => {
|
|
2896
|
+
const row = item && typeof item === 'object' ? item : {}
|
|
2897
|
+
const name = typeof row.value === 'string' ? row.value.trim() : ''
|
|
2898
|
+
if (!/^[a-z][a-z0-9-]{0,63}$/.test(name)) return null
|
|
2899
|
+
const label = typeof row.name === 'string' && row.name.trim() ? row.name.trim().slice(0, 80) : name
|
|
2900
|
+
const description = typeof row.description === 'string' ? row.description.trim().slice(0, 400) : ''
|
|
2901
|
+
return { value: name, name: label, ...(description ? { description } : {}) }
|
|
2902
|
+
}
|
|
2903
|
+
const rows = (list, limit) => Array.isArray(list)
|
|
2904
|
+
? list.slice(0, limit).map(option).filter(row => row && row.value !== 'custom')
|
|
2905
|
+
: []
|
|
2906
|
+
return {
|
|
2907
|
+
options: rows(value?.options, 20),
|
|
2908
|
+
defaultOptions: rows(value?.defaultOptions, 20),
|
|
2909
|
+
defaultPreset: typeof value?.defaultPreset === 'string' ? value.defaultPreset.slice(0, 64) : '',
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2823
2913
|
async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
|
|
2824
2914
|
const migrationFailure = response => method === 'session.history' && /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(JSON.stringify(response.body?.result?.error || {}))
|
|
2825
2915
|
const migrationReply = () => legacyEnvelope(rpcId, modernError('The source session format cannot be migrated by DSH. Update DSH and open the original session there before retrying; Remote will not rewrite its log.', 'session/migration-required', { sessionId: payload.sessionId }))
|
|
@@ -2865,7 +2955,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2865
2955
|
if (summary?.formatStatus === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.sessionId }))
|
|
2866
2956
|
const isChild = !!payload.parentSessionId && typeof payload.subagentMode === 'string'
|
|
2867
2957
|
let throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
|
|
2868
|
-
if (isChild || summary?.projections?.kind === 'cached') {
|
|
2958
|
+
if (isChild || summary?.projections?.kind === 'cached' || !modernState.followedSessions?.has(payload.sessionId)) {
|
|
2869
2959
|
// Cached storage watermarks are not connected stream sequence numbers.
|
|
2870
2960
|
// Child logs also need a fresh durable cursor and Host address validation.
|
|
2871
2961
|
const projection = await callUpstreamRemote('session/projections', { request: { sessionId: payload.sessionId } }, rpcId)
|
|
@@ -2886,7 +2976,10 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2886
2976
|
...(payload.beforeSeq === undefined ? {} : { beforeSeq: payload.beforeSeq }),
|
|
2887
2977
|
...(payload.maxMessages === undefined ? {} : { maxMessages: payload.maxMessages }),
|
|
2888
2978
|
} }
|
|
2889
|
-
transform = value =>
|
|
2979
|
+
transform = value => {
|
|
2980
|
+
if (!isChild) requestModernSessionStream(payload.sessionId)
|
|
2981
|
+
return { ...legacyHistoryValue(value, summary), ...modernReasoningValue(payload.sessionId) }
|
|
2982
|
+
}
|
|
2890
2983
|
} else if (method === 'session.models') {
|
|
2891
2984
|
endpoint = 'session/modelCatalog'
|
|
2892
2985
|
args = {}
|
|
@@ -2904,6 +2997,10 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2904
2997
|
} else if (method === 'agentPresets.list') {
|
|
2905
2998
|
endpoint = 'agentPresets/list'
|
|
2906
2999
|
args = {}
|
|
3000
|
+
} else if (method === 'permissionPresets.catalog') {
|
|
3001
|
+
endpoint = 'permissionPresets/catalog'
|
|
3002
|
+
args = {}
|
|
3003
|
+
transform = modernPermissionCatalog
|
|
2907
3004
|
} else if (method.startsWith('session.')) {
|
|
2908
3005
|
const verb = method.slice('session.'.length)
|
|
2909
3006
|
if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
|
|
@@ -2979,14 +3076,21 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2979
3076
|
}
|
|
2980
3077
|
|
|
2981
3078
|
let response = await callUpstreamRemote(endpoint, args, rpcId)
|
|
2982
|
-
|
|
3079
|
+
let receiptStage = 'modern-request'
|
|
3080
|
+
if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (typeof response.body?.result?.ok !== 'boolean' && ![404,405,501].includes(response.status)))) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: response.status, receiptCategory: response.status >= 500 ? 'upstream-http' : 'invalid-response', receiptStage })
|
|
2983
3081
|
if (method === 'session.prompt' && imageAdmissionRejected(response.body)) {
|
|
3082
|
+
let bridged
|
|
2984
3083
|
try {
|
|
2985
|
-
|
|
2986
|
-
if (bridged) response = await callUpstreamRemote(endpoint, { ...args, request: bridged }, rpcId)
|
|
3084
|
+
bridged = await bridgeVisionPrompt(args.request)
|
|
2987
3085
|
} catch (error) {
|
|
2988
|
-
|
|
2989
|
-
|
|
3086
|
+
// The original image request was explicitly rejected and no replacement
|
|
3087
|
+
// prompt has been submitted. Preparation failure is a known rejection.
|
|
3088
|
+
return legacyEnvelope(rpcId, modernError(error.message, 'image-vision-failed', { reason: error.code }))
|
|
3089
|
+
}
|
|
3090
|
+
if (bridged) {
|
|
3091
|
+
receiptStage = 'vision-submit'
|
|
3092
|
+
try { response = await callUpstreamRemote(endpoint, { ...args, request: bridged }, rpcId) }
|
|
3093
|
+
catch (error) { if (error && typeof error === 'object') error.receiptStage = receiptStage; throw error }
|
|
2990
3094
|
}
|
|
2991
3095
|
}
|
|
2992
3096
|
if (method === 'subagent.list' && modernResponseNeedsLegacyFallback(response)) {
|
|
@@ -3016,7 +3120,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3016
3120
|
}))
|
|
3017
3121
|
return legacyEnvelope(rpcId, { ok: true, value: { entries, parentAvailable: !!modernState.sessions.get(payload.parentSessionId)?.agentAvailable } })
|
|
3018
3122
|
}
|
|
3019
|
-
if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (
|
|
3123
|
+
if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (typeof response.body?.result?.ok !== 'boolean' && ![404,405,501].includes(response.status)))) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: response.status, receiptCategory: response.status >= 500 ? 'upstream-http' : 'invalid-response', receiptStage })
|
|
3020
3124
|
if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
|
|
3021
3125
|
if (!response.body?.result?.ok) {
|
|
3022
3126
|
if (migrationFailure(response)) return migrationReply()
|
|
@@ -3347,30 +3451,79 @@ function legacyPush(kind, payload, rpcId = crypto.randomUUID()) {
|
|
|
3347
3451
|
pushEvent(kind, { rpcId, payload })
|
|
3348
3452
|
}
|
|
3349
3453
|
|
|
3350
|
-
function
|
|
3351
|
-
if (!sessionId ||
|
|
3352
|
-
//
|
|
3353
|
-
//
|
|
3354
|
-
|
|
3454
|
+
function requestModernSessionStream(sessionId) {
|
|
3455
|
+
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 500) return
|
|
3456
|
+
// Current clients refresh visible history every 15s. Keep bounded, expiring demand
|
|
3457
|
+
// without changing their protocol or opening history just because it was listed.
|
|
3458
|
+
const interests = modernState.sessionInterests
|
|
3459
|
+
interests.delete(sessionId)
|
|
3460
|
+
interests.set(sessionId, Date.now() + 90000)
|
|
3461
|
+
while (interests.size > 8) interests.delete(interests.keys().next().value)
|
|
3462
|
+
eventCollectors.mux?.syncSessions?.()
|
|
3463
|
+
}
|
|
3464
|
+
|
|
3465
|
+
function modernSessionStreamAvailable(sessionId) {
|
|
3355
3466
|
const summary = modernState.sessions.get(sessionId)
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3467
|
+
// DSH follow promotes a cold ordinary session to a writable Agent. Only observe
|
|
3468
|
+
// sessions already activated by the host/user; history itself stays a cold read.
|
|
3469
|
+
return !!summary && (summary.agentAvailable === true || summary.running === true)
|
|
3470
|
+
&& summary.origin !== 'subagent' && summary.formatStatus !== 'migration-required'
|
|
3471
|
+
&& (modernState.sessionFailures?.get(sessionId)?.until || 0) <= Date.now()
|
|
3472
|
+
}
|
|
3473
|
+
|
|
3474
|
+
function openModernSessionStream(ws, sessionId, streams = { session: 'session:' + sessionId, jobs: 'jobs:' + sessionId }) {
|
|
3475
|
+
if (ws.readyState !== 1 || !modernSessionStreamAvailable(sessionId)) return null
|
|
3476
|
+
try {
|
|
3477
|
+
ws.send(JSON.stringify({
|
|
3478
|
+
type: 'open', streamId: streams.session, endpoint: 'session/follow',
|
|
3479
|
+
payload: { args: { request: { address: { kind: 'session', sessionId }, assistantStream: true } } },
|
|
3480
|
+
}))
|
|
3481
|
+
ws.send(JSON.stringify({
|
|
3482
|
+
type: 'open', streamId: streams.jobs, endpoint: 'job/list',
|
|
3483
|
+
payload: { args: { request: { sessionId } } },
|
|
3484
|
+
}))
|
|
3485
|
+
return streams
|
|
3486
|
+
} catch {
|
|
3487
|
+
// A carrier closing during the history response must not fail the cold read.
|
|
3488
|
+
for (const streamId of Object.values(streams)) try { ws.send(JSON.stringify({ type: 'cancel', streamId })) } catch {}
|
|
3489
|
+
return null
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
|
|
3493
|
+
function forgetModernSessionStream(sessionId) {
|
|
3494
|
+
modernState.followedSessions.delete(sessionId)
|
|
3495
|
+
modernState.sessionCursors.delete(sessionId)
|
|
3496
|
+
modernState.assistantStreams.delete(sessionId)
|
|
3497
|
+
for (const prefix of ['session:', 'reasoning:', 'jobs:']) collectorReplay.mux.delete(prefix + sessionId)
|
|
3498
|
+
}
|
|
3499
|
+
|
|
3500
|
+
function syncModernSessionStreams(ws, opened) {
|
|
3501
|
+
const interests = modernState.sessionInterests, now = Date.now()
|
|
3502
|
+
for (const [sessionId, until] of interests) if (until <= now) interests.delete(sessionId)
|
|
3503
|
+
for (const [sessionId, streams] of opened) {
|
|
3504
|
+
if (interests.has(sessionId) && modernSessionStreamAvailable(sessionId)) continue
|
|
3505
|
+
if (ws?.readyState === 1) for (const streamId of Object.values(streams)) {
|
|
3506
|
+
try { ws.send(JSON.stringify({ type: 'cancel', streamId })) } catch {}
|
|
3507
|
+
}
|
|
3508
|
+
opened.delete(sessionId)
|
|
3509
|
+
forgetModernSessionStream(sessionId)
|
|
3510
|
+
}
|
|
3511
|
+
if (ws?.readyState !== 1) return
|
|
3512
|
+
for (const sessionId of interests.keys()) {
|
|
3513
|
+
if (opened.has(sessionId) || !modernSessionStreamAvailable(sessionId)) continue
|
|
3514
|
+
// Cancellation completes asynchronously at DSH. A fresh stream id allows a
|
|
3515
|
+
// quick revisit without colliding with a still-closing invocation or its frames.
|
|
3516
|
+
const key = crypto.randomUUID()
|
|
3517
|
+
const streams = openModernSessionStream(ws, sessionId, { session: 'session:' + key, jobs: 'jobs:' + key })
|
|
3518
|
+
if (streams) { opened.set(sessionId, streams); modernState.followedSessions.add(sessionId) }
|
|
3519
|
+
}
|
|
3367
3520
|
}
|
|
3368
3521
|
|
|
3369
|
-
function handleModernStreamFailure(ws, frame) {
|
|
3522
|
+
function handleModernStreamFailure(ws, frame, observedSessionId = '', streams) {
|
|
3370
3523
|
const text = String(frame.error?.message || '')
|
|
3371
3524
|
const streamId = String(frame.streamId || '')
|
|
3372
|
-
const sessionId = streamId.startsWith('session:') ? streamId.slice(8) : streamId.startsWith('jobs:') ? streamId.slice(5)
|
|
3373
|
-
: text.match(/failed to observe session ["']([^"']+)["']/i)?.[1]
|
|
3525
|
+
const sessionId = observedSessionId || (streamId.startsWith('session:') ? streamId.slice(8) : streamId.startsWith('jobs:') ? streamId.slice(5)
|
|
3526
|
+
: text.match(/failed to observe session ["']([^"']+)["']/i)?.[1])
|
|
3374
3527
|
if (!sessionId || !modernState.sessions.has(sessionId)) return false
|
|
3375
3528
|
const migration = /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(text + ' ' + frame.error?.code)
|
|
3376
3529
|
const error = { code: migration ? 'session/migration-required' : 'session/stream-unavailable', message: migration
|
|
@@ -3378,8 +3531,8 @@ function handleModernStreamFailure(ws, frame) {
|
|
|
3378
3531
|
modernState.sessionFailures ||= new Map()
|
|
3379
3532
|
if (modernState.sessionFailures.size >= 200) modernState.sessionFailures.delete(modernState.sessionFailures.keys().next().value)
|
|
3380
3533
|
modernState.sessionFailures.set(sessionId, { until: Date.now() + 60000, error })
|
|
3381
|
-
for (const id of new Set(['session:' + sessionId, 'jobs:' + sessionId, streamId])) if (id) {
|
|
3382
|
-
try { ws.send(JSON.stringify({ type: '
|
|
3534
|
+
for (const id of new Set(streams ? Object.values(streams) : ['session:' + sessionId, 'jobs:' + sessionId, streamId])) if (id) {
|
|
3535
|
+
try { ws.send(JSON.stringify({ type: 'cancel', streamId: id })) } catch {}
|
|
3383
3536
|
}
|
|
3384
3537
|
legacyPush('mux', { type: 'session/stream-error', sessionId, error })
|
|
3385
3538
|
return true
|
|
@@ -3578,7 +3731,7 @@ function applyModernRemoteEvent(ws, value) {
|
|
|
3578
3731
|
const summary = args[0]
|
|
3579
3732
|
if (summary?.sessionId) {
|
|
3580
3733
|
modernState.sessions.set(summary.sessionId, summary)
|
|
3581
|
-
|
|
3734
|
+
eventCollectors.mux?.syncSessions?.()
|
|
3582
3735
|
legacyPush('host', {
|
|
3583
3736
|
type: 'host/session-added', sessionId: summary.sessionId, blank: !!summary.blank,
|
|
3584
3737
|
...(summary.parentSessionId === undefined ? {} : { parentSessionId: summary.parentSessionId }),
|
|
@@ -3588,16 +3741,19 @@ function applyModernRemoteEvent(ws, value) {
|
|
|
3588
3741
|
}
|
|
3589
3742
|
} else if (value.event === 'api-session/removed') {
|
|
3590
3743
|
modernState.sessions.delete(args[0])
|
|
3744
|
+
modernState.sessionInterests.delete(args[0])
|
|
3591
3745
|
modernState.sessionCursors.delete(args[0])
|
|
3592
3746
|
modernState.assistantStreams.delete(args[0])
|
|
3593
3747
|
collectorReplay.mux.delete(`reasoning:${args[0]}`)
|
|
3594
3748
|
collectorReplay.mux.delete(`session:${args[0]}`)
|
|
3595
3749
|
collectorReplay.mux.delete(`queue:${args[0]}`)
|
|
3596
3750
|
collectorReplay.mux.delete(`jobs:${args[0]}`)
|
|
3597
|
-
|
|
3598
|
-
try { ws.send(JSON.stringify({ type: 'cancel', streamId: 'jobs:' + args[0] })) } catch {}
|
|
3751
|
+
eventCollectors.mux?.syncSessions?.()
|
|
3599
3752
|
legacyPush('host', { type: 'host/session-removed', sessionId: args[0] })
|
|
3600
3753
|
} else if (value.event === 'api-session/status') {
|
|
3754
|
+
const summary = modernState.sessions.get(args[0])
|
|
3755
|
+
if (summary) modernState.sessions.set(args[0], { ...summary, running: !!args[1] })
|
|
3756
|
+
eventCollectors.mux?.syncSessions?.()
|
|
3601
3757
|
legacyPush('host', { type: 'host/session-status', sessionId: args[0], running: !!args[1] })
|
|
3602
3758
|
} else if (value.event === 'api-session/activity') {
|
|
3603
3759
|
const sessionId = String(args[0] || '')
|
|
@@ -3619,6 +3775,10 @@ function startModernEventCollector() {
|
|
|
3619
3775
|
let retryTimer = null
|
|
3620
3776
|
let connectTimer = null
|
|
3621
3777
|
let attempt = 0
|
|
3778
|
+
const sessionStreams = new Map()
|
|
3779
|
+
const syncSessions = () => syncModernSessionStreams(ws, sessionStreams)
|
|
3780
|
+
const interestTimer = setInterval(syncSessions, 15000)
|
|
3781
|
+
interestTimer.unref?.()
|
|
3622
3782
|
const scheme = UPSTREAM.protocol === 'https:' ? 'wss' : 'ws'
|
|
3623
3783
|
const url = `${scheme}://${UPSTREAM_AUTHORITY}/api/remote.mux`
|
|
3624
3784
|
const setConnected = (connected, error = '') => {
|
|
@@ -3639,6 +3799,8 @@ function startModernEventCollector() {
|
|
|
3639
3799
|
}
|
|
3640
3800
|
const connect = () => {
|
|
3641
3801
|
if (stopped) return
|
|
3802
|
+
for (const sessionId of sessionStreams.keys()) forgetModernSessionStream(sessionId)
|
|
3803
|
+
sessionStreams.clear()
|
|
3642
3804
|
let current
|
|
3643
3805
|
try {
|
|
3644
3806
|
const headers = dshUpstreamHeaders()
|
|
@@ -3653,7 +3815,10 @@ function startModernEventCollector() {
|
|
|
3653
3815
|
const finish = (code = 0, reason = '', error = '') => {
|
|
3654
3816
|
if (finished) return
|
|
3655
3817
|
finished = true
|
|
3818
|
+
if (ws !== current) return
|
|
3656
3819
|
clearTimeout(connectTimer)
|
|
3820
|
+
for (const sessionId of sessionStreams.keys()) forgetModernSessionStream(sessionId)
|
|
3821
|
+
sessionStreams.clear()
|
|
3657
3822
|
modernState.eventClientId = ''
|
|
3658
3823
|
setConnected(false, error)
|
|
3659
3824
|
for (const state of Object.values(eventCollectorState)) {
|
|
@@ -3677,17 +3842,23 @@ function startModernEventCollector() {
|
|
|
3677
3842
|
current.send(JSON.stringify({ type: 'open', streamId: 'events', endpoint: '$events', payload: { args: {} } }))
|
|
3678
3843
|
current.send(JSON.stringify({ type: 'open', streamId: 'control', endpoint: 'session/control', payload: { args: {} } }))
|
|
3679
3844
|
current.send(JSON.stringify({ type: 'open', streamId: 'workspaces', endpoint: 'workspace/follow', payload: { args: {} } }))
|
|
3680
|
-
|
|
3845
|
+
syncSessions()
|
|
3681
3846
|
}
|
|
3682
3847
|
current.onmessage = ev => {
|
|
3848
|
+
if (finished || stopped || ws !== current) return
|
|
3683
3849
|
try {
|
|
3684
3850
|
const data = typeof ev.data === 'string' ? ev.data : Buffer.isBuffer(ev.data) ? ev.data.toString() : String(ev.data)
|
|
3685
3851
|
const frame = JSON.parse(data)
|
|
3852
|
+
const observed = [...sessionStreams].find(([, streams]) => streams.session === frame.streamId || streams.jobs === frame.streamId)
|
|
3853
|
+
if ((frame.streamId?.startsWith('session:') || frame.streamId?.startsWith('jobs:')) && !observed) return
|
|
3686
3854
|
if (frame.type === 'error') {
|
|
3687
3855
|
// Old generated-RPC Hosts may have no job namespace. This optional
|
|
3688
3856
|
// roster must not degrade the working session and approval streams.
|
|
3689
3857
|
if (frame.streamId?.startsWith('jobs:') && ['gateway/definition-unavailable', 'gateway/invocation-unavailable', 'gateway/service-unavailable', 'gateway/method-unavailable', 'method-unavailable', 'not-found'].includes(frame.error?.code)) return
|
|
3690
|
-
if (handleModernStreamFailure(current, frame))
|
|
3858
|
+
if (handleModernStreamFailure(current, frame, observed?.[0], observed?.[1])) {
|
|
3859
|
+
if (observed) { sessionStreams.delete(observed[0]); forgetModernSessionStream(observed[0]) }
|
|
3860
|
+
return
|
|
3861
|
+
}
|
|
3691
3862
|
const message = frame.error?.message || 'modern stream error'
|
|
3692
3863
|
for (const state of Object.values(eventCollectorState)) state.lastError = message
|
|
3693
3864
|
legacyPush('mux', { type: 'stream/error', error: frame.error || { message } })
|
|
@@ -3697,8 +3868,8 @@ function startModernEventCollector() {
|
|
|
3697
3868
|
if (frame.streamId === 'events') applyModernRemoteEvent(current, frame.value)
|
|
3698
3869
|
else if (frame.streamId === 'control') applyModernControlFrame(frame.value)
|
|
3699
3870
|
else if (frame.streamId === 'workspaces') applyModernWorkspaceFrame(frame.value)
|
|
3700
|
-
else if (frame.streamId.startsWith('jobs:')) applyModernJobFrame(
|
|
3701
|
-
else if (frame.streamId.startsWith('session:')) applyModernSessionFrame(
|
|
3871
|
+
else if (frame.streamId.startsWith('jobs:')) applyModernJobFrame(observed[0], frame.value)
|
|
3872
|
+
else if (frame.streamId.startsWith('session:')) applyModernSessionFrame(observed[0], frame.value)
|
|
3702
3873
|
} catch {}
|
|
3703
3874
|
}
|
|
3704
3875
|
current.onclose = ev => finish(ev?.code, ev?.reason)
|
|
@@ -3710,6 +3881,7 @@ function startModernEventCollector() {
|
|
|
3710
3881
|
connect()
|
|
3711
3882
|
return {
|
|
3712
3883
|
kind: 'modern',
|
|
3884
|
+
syncSessions,
|
|
3713
3885
|
reconnectNow() {
|
|
3714
3886
|
if (stopped || ws?.readyState === 0 || ws?.readyState === 1) return
|
|
3715
3887
|
clearTimeout(retryTimer)
|
|
@@ -3721,6 +3893,9 @@ function startModernEventCollector() {
|
|
|
3721
3893
|
stopped = true
|
|
3722
3894
|
clearTimeout(retryTimer)
|
|
3723
3895
|
clearTimeout(connectTimer)
|
|
3896
|
+
clearInterval(interestTimer)
|
|
3897
|
+
for (const sessionId of sessionStreams.keys()) forgetModernSessionStream(sessionId)
|
|
3898
|
+
sessionStreams.clear()
|
|
3724
3899
|
try { ws?.close() } catch {}
|
|
3725
3900
|
},
|
|
3726
3901
|
}
|
|
@@ -3804,12 +3979,11 @@ function serveStats(req, res, url) {
|
|
|
3804
3979
|
}
|
|
3805
3980
|
|
|
3806
3981
|
if (pathname === '/stats/ingest' && req.method === 'POST') {
|
|
3807
|
-
|
|
3808
|
-
req.on('data', c => { body += c; if (body.length > 256 * 1024) req.destroy() })
|
|
3809
|
-
req.on('end', () => {
|
|
3982
|
+
withRequestBody(req, res, 256 * 1024, body => {
|
|
3810
3983
|
let payload
|
|
3811
3984
|
try {
|
|
3812
3985
|
payload = JSON.parse(body || '{}')
|
|
3986
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('invalid object')
|
|
3813
3987
|
} catch {
|
|
3814
3988
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
3815
3989
|
res.end(JSON.stringify({ error: 'invalid json' }))
|
|
@@ -4138,12 +4312,11 @@ function serveFeedback(req, res, url) {
|
|
|
4138
4312
|
}
|
|
4139
4313
|
touchDevice(req)
|
|
4140
4314
|
|
|
4141
|
-
|
|
4142
|
-
req.on('data', c => { body += c; if (body.length > 16 * 1024) req.destroy() })
|
|
4143
|
-
req.on('end', async () => {
|
|
4315
|
+
withRequestBody(req, res, 16 * 1024, async body => {
|
|
4144
4316
|
let payload
|
|
4145
4317
|
try {
|
|
4146
4318
|
payload = JSON.parse(body || '{}')
|
|
4319
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('invalid object')
|
|
4147
4320
|
} catch {
|
|
4148
4321
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
4149
4322
|
res.end(JSON.stringify({ error: 'invalid json' }))
|
|
@@ -4248,6 +4421,7 @@ function serveStatic(req, res, url) {
|
|
|
4248
4421
|
let pathname
|
|
4249
4422
|
try {
|
|
4250
4423
|
pathname = decodeURIComponent(url.pathname)
|
|
4424
|
+
if (pathname.includes('\0')) throw new Error('invalid path')
|
|
4251
4425
|
} catch {
|
|
4252
4426
|
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
4253
4427
|
res.end('400 Bad Request')
|
|
@@ -4339,16 +4513,7 @@ async function serveAdminApi(req, res, url) {
|
|
|
4339
4513
|
if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST'); return reply(405, { error: 'method-not-allowed' }) }
|
|
4340
4514
|
try {
|
|
4341
4515
|
if (req.method === 'GET') return reply(200, { ok: true, ...await loginAutostart.status() })
|
|
4342
|
-
|
|
4343
|
-
await new Promise((resolve, reject) => {
|
|
4344
|
-
req.on('data', chunk => {
|
|
4345
|
-
if (Buffer.byteLength(body) + chunk.length > 1024) oversized = true
|
|
4346
|
-
if (!oversized) body += chunk
|
|
4347
|
-
})
|
|
4348
|
-
req.once('end', resolve)
|
|
4349
|
-
req.once('error', reject)
|
|
4350
|
-
})
|
|
4351
|
-
if (oversized) { res.setHeader('connection', 'close'); return reply(413, { error: 'body-too-large' }) }
|
|
4516
|
+
const body = await readBody(req, 1024)
|
|
4352
4517
|
let input
|
|
4353
4518
|
try { input = JSON.parse(body) } catch { return reply(400, { error: 'bad-request' }) }
|
|
4354
4519
|
if (!input || typeof input.enabled !== 'boolean' || Object.keys(input).some(key => key !== 'enabled')) return reply(400, { error: 'bad-request' })
|
|
@@ -4415,12 +4580,7 @@ async function serveAdminApi(req, res, url) {
|
|
|
4415
4580
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
4416
4581
|
return
|
|
4417
4582
|
}
|
|
4418
|
-
|
|
4419
|
-
req.on('data', chunk => {
|
|
4420
|
-
body += chunk
|
|
4421
|
-
if (body.length > 8192) req.destroy()
|
|
4422
|
-
})
|
|
4423
|
-
req.on('end', () => {
|
|
4583
|
+
withRequestBody(req, res, 8192, body => {
|
|
4424
4584
|
let payload = {}
|
|
4425
4585
|
try { payload = JSON.parse(body || '{}') } catch {
|
|
4426
4586
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
@@ -4431,6 +4591,9 @@ async function serveAdminApi(req, res, url) {
|
|
|
4431
4591
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
4432
4592
|
res.end(JSON.stringify(value))
|
|
4433
4593
|
}
|
|
4594
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload) || (payload.note !== undefined && typeof payload.note !== 'string')) {
|
|
4595
|
+
return send(400, { error: 'bad-request' })
|
|
4596
|
+
}
|
|
4434
4597
|
if (sub === '/device-keys/mode') {
|
|
4435
4598
|
if (typeof payload.enabled !== 'boolean') return send(400, { error: 'bad-request', detail: 'enabled 必须是布尔值' })
|
|
4436
4599
|
if (payload.enabled && deviceKeyState.keys.length === 0 && !createDeviceKey(payload.note || '我的设备')) {
|
|
@@ -4539,9 +4702,7 @@ async function serveAdminApi(req, res, url) {
|
|
|
4539
4702
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
4540
4703
|
return
|
|
4541
4704
|
}
|
|
4542
|
-
|
|
4543
|
-
req.on('data', c => { body += c; if (body.length > 4096) req.destroy() })
|
|
4544
|
-
req.on('end', () => {
|
|
4705
|
+
withRequestBody(req, res, 4096, body => {
|
|
4545
4706
|
try {
|
|
4546
4707
|
const { ip, name } = JSON.parse(body || '{}')
|
|
4547
4708
|
if (typeof ip !== 'string' || typeof name !== 'string') throw new Error('bad')
|
|
@@ -4564,9 +4725,7 @@ async function serveAdminApi(req, res, url) {
|
|
|
4564
4725
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
4565
4726
|
return
|
|
4566
4727
|
}
|
|
4567
|
-
|
|
4568
|
-
req.on('data', c => { body += c; if (body.length > 1024) req.destroy() })
|
|
4569
|
-
req.on('end', () => {
|
|
4728
|
+
withRequestBody(req, res, 1024, body => {
|
|
4570
4729
|
try {
|
|
4571
4730
|
const ip = JSON.parse(body || '{}').ip
|
|
4572
4731
|
const n = typeof ip === 'string' ? kickDevice(ip) : 0
|
|
@@ -4625,8 +4784,10 @@ function fsAuthorized(req, url, res) {
|
|
|
4625
4784
|
}
|
|
4626
4785
|
|
|
4627
4786
|
function fsInsideRootFor(pathApi, abs, root, caseInsensitive = false) {
|
|
4628
|
-
|
|
4629
|
-
|
|
4787
|
+
const normal = value => pathApi.sep === '\\'
|
|
4788
|
+
? String(value || '').replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '') : String(value || '')
|
|
4789
|
+
let candidate = pathApi.resolve(normal(abs))
|
|
4790
|
+
let boundary = pathApi.resolve(normal(root))
|
|
4630
4791
|
if (caseInsensitive) {
|
|
4631
4792
|
candidate = candidate.toLowerCase()
|
|
4632
4793
|
boundary = boundary.toLowerCase()
|
|
@@ -4681,7 +4842,7 @@ async function loadFsWorkspaceRoots(force = false) {
|
|
|
4681
4842
|
}
|
|
4682
4843
|
const items = Array.isArray(value?.items) ? value.items : []
|
|
4683
4844
|
const roots = [...new Set(items.map(fsWorkspacePath).filter(Boolean))]
|
|
4684
|
-
const reals = roots.map(root => { try { return fs.realpathSync(root) } catch { return null } }).filter(Boolean)
|
|
4845
|
+
const reals = roots.map(root => { try { return (fs.realpathSync.native || fs.realpathSync)(root) } catch { return null } }).filter(Boolean)
|
|
4685
4846
|
fsWorkspaceRootsCache = { roots, reals, fetchedAt: Date.now() }
|
|
4686
4847
|
} catch {
|
|
4687
4848
|
// DSH 重启期间保留上次成功的工作区根;缓存为空时仍仅允许显式 FS_ROOTS。
|
|
@@ -4717,7 +4878,7 @@ async function fsResolve(input) {
|
|
|
4717
4878
|
function fsRealChecked(abs) {
|
|
4718
4879
|
let real
|
|
4719
4880
|
try {
|
|
4720
|
-
real = fs.realpathSync(abs)
|
|
4881
|
+
real = (fs.realpathSync.native || fs.realpathSync)(abs)
|
|
4721
4882
|
} catch (err) {
|
|
4722
4883
|
return { error: err.code === 'ENOENT' ? 'not-found' : 'permission-denied' }
|
|
4723
4884
|
}
|
|
@@ -4793,14 +4954,16 @@ async function fsList(req, res, url) {
|
|
|
4793
4954
|
try {
|
|
4794
4955
|
// 符号链接指向允许根之外时直接不展示, 点进去/下载也必然被 realpath 复核拒绝
|
|
4795
4956
|
if (d.isSymbolicLink()) {
|
|
4796
|
-
const real = fs.realpathSync(full)
|
|
4957
|
+
const real = (fs.realpathSync.native || fs.realpathSync)(full)
|
|
4797
4958
|
if (!fsInsideReal(real) || fsProtectedPath(real)) continue
|
|
4798
4959
|
}
|
|
4799
4960
|
const info = fs.statSync(full)
|
|
4800
4961
|
if (!info.isFile() && !info.isDirectory()) continue
|
|
4801
4962
|
entries.push({
|
|
4802
4963
|
name: d.name,
|
|
4803
|
-
|
|
4964
|
+
// Keep entry addresses in the same namespace as the requested directory.
|
|
4965
|
+
// Native realpath may expand Windows short names or change their casing.
|
|
4966
|
+
path: path.join(resolved.abs, d.name),
|
|
4804
4967
|
type: info.isDirectory() ? 'dir' : 'file',
|
|
4805
4968
|
size: info.isDirectory() ? 0 : info.size,
|
|
4806
4969
|
mtimeMs: Math.round(info.mtimeMs)
|
|
@@ -4926,6 +5089,7 @@ function fsValidName(name) {
|
|
|
4926
5089
|
if (!name || name === '.' || name === '..') return false
|
|
4927
5090
|
if (name.includes('/') || name.includes('\\') || name.includes('\0')) return false
|
|
4928
5091
|
if (path.basename(name) !== name) return false
|
|
5092
|
+
if (Buffer.byteLength(name, 'utf8') > 255 || name.length > 255) return false
|
|
4929
5093
|
return true
|
|
4930
5094
|
}
|
|
4931
5095
|
|
|
@@ -5020,7 +5184,9 @@ function fsOpenUploadTarget(res, url, dirLex, dirReal, name) {
|
|
|
5020
5184
|
fsJson(res, 409, { error: 'conflict', detail: '文件已存在, 追加 overwrite=1 可覆盖' })
|
|
5021
5185
|
return null
|
|
5022
5186
|
}
|
|
5023
|
-
|
|
5187
|
+
let temporaryName = `.${name}.dsh-remote-part-${process.pid}-${crypto.randomBytes(4).toString('hex')}`
|
|
5188
|
+
if (Buffer.byteLength(temporaryName) > 255) temporaryName = `.dsh-remote-part-${crypto.randomBytes(16).toString('hex')}`
|
|
5189
|
+
const tmp = path.join(dirReal, temporaryName)
|
|
5024
5190
|
let stream
|
|
5025
5191
|
try {
|
|
5026
5192
|
stream = fs.createWriteStream(tmp, { flags: 'wx', mode: 0o600 })
|
|
@@ -5115,24 +5281,29 @@ function fsUploadRaw(req, res, url, dirLex, dirReal) {
|
|
|
5115
5281
|
/** 零依赖流式 multipart 解析: 只取第一个文件部分, 2GB 也不会整块进内存。 */
|
|
5116
5282
|
function fsUploadMultipart(req, res, url, dirLex, dirReal, boundary) {
|
|
5117
5283
|
const queryName = url.searchParams.get('name') || ''
|
|
5284
|
+
if (!boundary || boundary.length > 70 || /[^\x20-\x7e]/.test(boundary)) return fsJson(res, 400, { error: 'bad-multipart' })
|
|
5118
5285
|
const marker = Buffer.from('\r\n--' + boundary)
|
|
5286
|
+
const first = Buffer.from('--' + boundary + '\r\n')
|
|
5119
5287
|
let head = Buffer.alloc(0)
|
|
5120
5288
|
let tail = Buffer.alloc(0)
|
|
5121
|
-
let state = 'headers' // headers -> data -> done
|
|
5289
|
+
let state = 'headers' // headers -> data -> remainder/closed -> done
|
|
5122
5290
|
let pipe = null
|
|
5123
5291
|
|
|
5124
5292
|
const fail = (status, msg) => {
|
|
5293
|
+
if (state === 'failed' || state === 'done') return
|
|
5294
|
+
state = 'failed'
|
|
5125
5295
|
if (pipe) pipe.abort(status, msg)
|
|
5126
5296
|
else if (!res.headersSent) fsJson(res, status, { error: msg })
|
|
5127
5297
|
}
|
|
5128
5298
|
|
|
5129
|
-
const process = (buf) => {
|
|
5130
|
-
if (
|
|
5299
|
+
const process = (buf, final = false) => {
|
|
5300
|
+
if (['closed', 'failed', 'done'].includes(state)) return
|
|
5131
5301
|
if (state === 'headers') {
|
|
5132
5302
|
head = Buffer.concat([head, buf])
|
|
5133
5303
|
if (head.length > 64 * 1024) return fail(400, 'multipart-headers-too-large')
|
|
5134
5304
|
const idx = head.indexOf('\r\n\r\n')
|
|
5135
5305
|
if (idx === -1) return
|
|
5306
|
+
if (!head.subarray(0, first.length).equals(first)) return fail(400, 'bad-multipart')
|
|
5136
5307
|
const headerText = head.slice(0, idx).toString('utf8')
|
|
5137
5308
|
let partName = queryName
|
|
5138
5309
|
if (!partName) {
|
|
@@ -5148,29 +5319,49 @@ function fsUploadMultipart(req, res, url, dirLex, dirReal, boundary) {
|
|
|
5148
5319
|
if (rest.length) process(rest)
|
|
5149
5320
|
return
|
|
5150
5321
|
}
|
|
5151
|
-
// data
|
|
5322
|
+
// A boundary prefix inside file data is not a delimiter unless its suffix is valid.
|
|
5152
5323
|
buf = Buffer.concat([tail, buf])
|
|
5153
|
-
|
|
5154
|
-
|
|
5155
|
-
const
|
|
5156
|
-
if (
|
|
5157
|
-
|
|
5158
|
-
|
|
5324
|
+
let from = 0
|
|
5325
|
+
while (true) {
|
|
5326
|
+
const idx = buf.indexOf(marker, from)
|
|
5327
|
+
if (idx < 0) break
|
|
5328
|
+
const suffix = idx + marker.length
|
|
5329
|
+
if (buf.length < suffix + 2) {
|
|
5330
|
+
if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
|
|
5331
|
+
tail = buf.subarray(idx); return
|
|
5332
|
+
}
|
|
5333
|
+
const ending = buf.subarray(suffix, suffix + 2).toString('ascii')
|
|
5334
|
+
if (ending === '--') {
|
|
5335
|
+
const after = suffix + 2
|
|
5336
|
+
if (!final && buf.length < after + 2) {
|
|
5337
|
+
if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
|
|
5338
|
+
tail = buf.subarray(idx); return
|
|
5339
|
+
}
|
|
5340
|
+
if (buf.length === after || buf.subarray(after, after + 2).toString('ascii') === '\r\n') {
|
|
5341
|
+
if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
|
|
5342
|
+
tail = Buffer.alloc(0); state = 'closed'; return
|
|
5343
|
+
}
|
|
5344
|
+
} else if (ending === '\r\n') {
|
|
5345
|
+
if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
|
|
5346
|
+
state = 'remainder'
|
|
5347
|
+
buf = buf.subarray(suffix + 2); from = 0; continue
|
|
5348
|
+
}
|
|
5349
|
+
from = idx + 1
|
|
5159
5350
|
}
|
|
5160
|
-
|
|
5161
|
-
state
|
|
5162
|
-
|
|
5351
|
+
const keep = Math.min(buf.length, marker.length + 3)
|
|
5352
|
+
if (state === 'data' && buf.length > keep) pipe.write(buf.subarray(0, buf.length - keep))
|
|
5353
|
+
tail = buf.subarray(buf.length - keep)
|
|
5163
5354
|
}
|
|
5164
5355
|
|
|
5165
5356
|
req.on('aborted', () => { if (pipe) pipe.abort(400, 'client-aborted') })
|
|
5166
5357
|
req.on('error', () => { if (pipe) pipe.abort(400, 'client-aborted') })
|
|
5167
5358
|
req.on('data', (chunk) => process(chunk))
|
|
5168
5359
|
req.on('end', () => {
|
|
5360
|
+
if (state === 'failed' || state === 'done') return
|
|
5169
5361
|
if (state === 'headers') return fail(400, 'no-file-part')
|
|
5170
|
-
if (state
|
|
5171
|
-
|
|
5172
|
-
|
|
5173
|
-
}
|
|
5362
|
+
if (state !== 'closed') process(Buffer.alloc(0), true)
|
|
5363
|
+
if (state !== 'closed') return fail(400, 'bad-multipart')
|
|
5364
|
+
state = 'done'; pipe.end()
|
|
5174
5365
|
})
|
|
5175
5366
|
}
|
|
5176
5367
|
|
|
@@ -5183,7 +5374,9 @@ function fsUploadMultipart(req, res, url, dirLex, dirReal, boundary) {
|
|
|
5183
5374
|
*/
|
|
5184
5375
|
function fsPartPath(dirReal, name, session) {
|
|
5185
5376
|
const s = String(session || 'default').replace(/[^A-Za-z0-9._-]/g, '').slice(0, 64) || 'default'
|
|
5186
|
-
|
|
5377
|
+
let partName = `.${name}.dsh-remote-part-${s}`
|
|
5378
|
+
if (Buffer.byteLength(partName) > 255) partName = `.dsh-remote-part-${crypto.createHash('sha256').update(name).digest('hex').slice(0, 32)}-${s}`
|
|
5379
|
+
return path.join(dirReal, partName)
|
|
5187
5380
|
}
|
|
5188
5381
|
|
|
5189
5382
|
function fsTargetState(target) {
|
|
@@ -5633,20 +5826,7 @@ function serveHandoff(req, res, url) {
|
|
|
5633
5826
|
}
|
|
5634
5827
|
|
|
5635
5828
|
// PUT:读 JSON 体,字段白名单 + 截断,4KB 上限
|
|
5636
|
-
|
|
5637
|
-
let done = false
|
|
5638
|
-
req.on('data', chunk => {
|
|
5639
|
-
if (done) return
|
|
5640
|
-
body += chunk
|
|
5641
|
-
if (Buffer.byteLength(body) > 4096) {
|
|
5642
|
-
done = true
|
|
5643
|
-
fsJson(res, 413, { error: 'payload too large' })
|
|
5644
|
-
req.destroy()
|
|
5645
|
-
}
|
|
5646
|
-
})
|
|
5647
|
-
req.on('end', () => {
|
|
5648
|
-
if (done || res.headersSent) return
|
|
5649
|
-
done = true
|
|
5829
|
+
withRequestBody(req, res, 4096, body => {
|
|
5650
5830
|
let payload
|
|
5651
5831
|
try {
|
|
5652
5832
|
payload = JSON.parse(body || '{}')
|
|
@@ -5722,23 +5902,13 @@ function serveWorkbench(req, res, url) {
|
|
|
5722
5902
|
}
|
|
5723
5903
|
|
|
5724
5904
|
if (sub === '/bind' && req.method === 'POST') {
|
|
5725
|
-
let body = ''
|
|
5726
5905
|
let done = false
|
|
5727
5906
|
const fail = (status, payload) => {
|
|
5728
5907
|
if (done || res.headersSent) return
|
|
5729
5908
|
done = true
|
|
5730
5909
|
fsJson(res, status, payload)
|
|
5731
5910
|
}
|
|
5732
|
-
req
|
|
5733
|
-
if (done) return
|
|
5734
|
-
body += chunk
|
|
5735
|
-
if (Buffer.byteLength(body) > 4096) {
|
|
5736
|
-
req.destroy()
|
|
5737
|
-
fail(413, { error: 'too-large' })
|
|
5738
|
-
}
|
|
5739
|
-
})
|
|
5740
|
-
req.on('error', () => { if (!done) done = true })
|
|
5741
|
-
req.on('end', () => {
|
|
5911
|
+
withRequestBody(req, res, 4096, body => {
|
|
5742
5912
|
if (done) return
|
|
5743
5913
|
try {
|
|
5744
5914
|
const rawPath = JSON.parse(body || '{}')?.path
|
|
@@ -5773,7 +5943,7 @@ function serveWorkbench(req, res, url) {
|
|
|
5773
5943
|
|
|
5774
5944
|
// ---------- /api 代理 ----------
|
|
5775
5945
|
const ADAPTIVE_RPC_METHODS = new Set([
|
|
5776
|
-
'agentPresets.list',
|
|
5946
|
+
'agentPresets.list', 'permissionPresets.catalog',
|
|
5777
5947
|
'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
|
|
5778
5948
|
'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
|
|
5779
5949
|
'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
|
|
@@ -5815,10 +5985,10 @@ async function bridgeVisionPrompt(payload) {
|
|
|
5815
5985
|
redirect: 'error',
|
|
5816
5986
|
})
|
|
5817
5987
|
const configResponse = await pluginFetch('config')
|
|
5818
|
-
if (configResponse.status === 404) throw new Error('当前模型不支持图片,未找到兼容的 dsh-image-vision 插件;请安装并启用视觉辅助插件,或切换视觉模型。')
|
|
5988
|
+
if (configResponse.status === 404) throw Object.assign(new Error('当前模型不支持图片,未找到兼容的 dsh-image-vision 插件;请安装并启用视觉辅助插件,或切换视觉模型。'), { code: 'VISION_PLUGIN_MISSING' })
|
|
5819
5989
|
if (!configResponse.ok) throw new Error('无法检查视觉辅助插件状态,请稍后重试。')
|
|
5820
5990
|
const config = await configResponse.json()
|
|
5821
|
-
if (config?.config?.enabled !== true) throw new Error('当前模型不支持图片,视觉辅助插件尚未开启。请在 DSH 中启用插件后重试。')
|
|
5991
|
+
if (config?.config?.enabled !== true) throw Object.assign(new Error('当前模型不支持图片,视觉辅助插件尚未开启。请在 DSH 中启用插件后重试。'), { code: 'VISION_PLUGIN_DISABLED' })
|
|
5822
5992
|
const content = []
|
|
5823
5993
|
for (const part of payload.content) {
|
|
5824
5994
|
if (part?.type !== 'image') { content.push(part); continue }
|
|
@@ -5858,7 +6028,7 @@ async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
|
|
|
5858
6028
|
const bridged = await bridgeVisionPrompt(request.payload)
|
|
5859
6029
|
if (bridged) return forwardLegacyRpc(url, JSON.stringify({ ...request, payload: bridged }), false)
|
|
5860
6030
|
} catch (error) {
|
|
5861
|
-
return { ...result, status: 200, raw: JSON.stringify(legacyEnvelope(request.rpcId, modernError(error.message, 'image-vision-failed'))) }
|
|
6031
|
+
return { ...result, status: 200, raw: JSON.stringify(legacyEnvelope(request.rpcId, modernError(error.message, 'image-vision-failed', { reason: error.code }))) }
|
|
5862
6032
|
}
|
|
5863
6033
|
}
|
|
5864
6034
|
}
|
|
@@ -5910,12 +6080,36 @@ function loadOperation(key) {
|
|
|
5910
6080
|
}
|
|
5911
6081
|
function operationSnapshot(job) {
|
|
5912
6082
|
return { id: job.id, method: job.method, phase: job.phase, createdAt: job.createdAt,
|
|
5913
|
-
completedAt: job.completedAt || null, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }
|
|
6083
|
+
completedAt: job.completedAt || null, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}), ...(job.diagnostic ? { diagnostic: job.diagnostic } : {}) }
|
|
6084
|
+
}
|
|
6085
|
+
function operationFailureFacts(error, stage, createdAt) {
|
|
6086
|
+
const categories = ['upstream-http', 'invalid-response', 'network', 'timeout']
|
|
6087
|
+
const code = error?.cause?.code || error?.code
|
|
6088
|
+
const timeout = ['AbortError', 'TimeoutError'].includes(error?.name) || ['UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT'].includes(code)
|
|
6089
|
+
const network = ['ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'EHOSTUNREACH', 'ENETUNREACH', 'ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_SOCKET'].includes(code)
|
|
6090
|
+
const category = categories.includes(error?.receiptCategory) ? error.receiptCategory : timeout ? 'timeout' : network ? 'network' : 'upstream-uncertain'
|
|
6091
|
+
const stages = ['protocol-detection', 'modern-request', 'legacy-request', 'response-validation', 'vision-submit']
|
|
6092
|
+
const httpStatus = error?.httpStatus
|
|
6093
|
+
return { category, stage: stages.includes(error?.receiptStage) ? error.receiptStage : stage,
|
|
6094
|
+
...(Number.isInteger(httpStatus) && httpStatus >= 100 && httpStatus <= 599 ? { httpStatus } : {}),
|
|
6095
|
+
durationMs: Math.max(0, Date.now() - createdAt) }
|
|
5914
6096
|
}
|
|
5915
6097
|
function operationResult(body) {
|
|
6098
|
+
const guidance = {
|
|
6099
|
+
'image-vision-failed': '图片处理未完成,消息尚未提交。请检查视觉辅助插件或切换支持图片的模型。',
|
|
6100
|
+
'session/agent-busy': '当前会话正忙,请等待当前任务结束后再操作。',
|
|
6101
|
+
'session/not-found': '会话不存在,请刷新列表后重新打开。',
|
|
6102
|
+
'session/model-not-found': '所选模型不可用,请重新选择模型。',
|
|
6103
|
+
'session/attachment-invalid': '图片或附件未被主机接受,请检查文件及所选模型的支持情况。',
|
|
6104
|
+
}
|
|
6105
|
+
const visionGuidance = {
|
|
6106
|
+
VISION_PLUGIN_MISSING: '当前模型不支持图片,且未安装视觉辅助插件。请安装并启用 dsh-image-vision,或切换支持图片的模型。',
|
|
6107
|
+
VISION_PLUGIN_DISABLED: '当前模型不支持图片,视觉辅助插件尚未开启。请启用插件或切换支持图片的模型。',
|
|
6108
|
+
}
|
|
6109
|
+
const code = String(body.result.error?.code || 'operation-rejected').slice(0, 120)
|
|
5916
6110
|
if (body.result.ok !== true) return { result: { ok: false, error: {
|
|
5917
|
-
code
|
|
5918
|
-
message: '主机拒绝了操作,请核对会话和当前配置。'
|
|
6111
|
+
code,
|
|
6112
|
+
message: (code === 'image-vision-failed' && Object.hasOwn(visionGuidance, body.result.error?.details?.reason) && visionGuidance[body.result.error.details.reason]) || (Object.hasOwn(guidance, code) && guidance[code]) || '主机拒绝了操作,请核对会话和当前配置。'
|
|
5919
6113
|
} } }
|
|
5920
6114
|
const input = body.result.value || {}, value = {}
|
|
5921
6115
|
for (const key of ['accepted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'ref', 'selected', 'model', 'cleared']) {
|
|
@@ -5927,30 +6121,42 @@ function operationResult(body) {
|
|
|
5927
6121
|
async function executeOperation(key, job, payload) {
|
|
5928
6122
|
const request = { type: 'client-request', rpcId: job.id, method: job.method,
|
|
5929
6123
|
payload: job.method === 'session.prompt' ? { ...payload, requestId: job.id } : payload }
|
|
6124
|
+
let stage = 'protocol-detection'
|
|
6125
|
+
let responseStatus
|
|
5930
6126
|
try {
|
|
5931
6127
|
let body
|
|
5932
6128
|
const url = new URL('/api/' + job.method, UPSTREAM)
|
|
5933
6129
|
if (await detectUpstreamApiFlavor() === 'modern') {
|
|
6130
|
+
stage = 'modern-request'
|
|
5934
6131
|
body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
|
|
5935
6132
|
}
|
|
5936
6133
|
if (!body || body.__dshRemoteLegacyFallback) {
|
|
6134
|
+
stage = 'legacy-request'
|
|
5937
6135
|
const legacy = await forwardLegacyRpc(url, JSON.stringify(request))
|
|
6136
|
+
responseStatus = legacy.status
|
|
5938
6137
|
if ([404, 405, 501].includes(legacy.status)) {
|
|
5939
6138
|
body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
|
|
5940
6139
|
if (body?.__dshRemoteLegacyFallback) body = null
|
|
5941
|
-
} else if (legacy.status >= 500) throw new Error('upstream-uncertain')
|
|
6140
|
+
} else if (legacy.status >= 500) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'upstream-http' })
|
|
5942
6141
|
else {
|
|
5943
|
-
try { body = JSON.parse(legacy.raw) } catch { throw new Error('upstream-uncertain') }
|
|
6142
|
+
try { body = JSON.parse(legacy.raw) } catch { throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'invalid-response' }) }
|
|
5944
6143
|
}
|
|
5945
6144
|
}
|
|
5946
|
-
|
|
6145
|
+
stage = 'response-validation'
|
|
6146
|
+
if (typeof body?.result?.ok !== 'boolean' || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) throw Object.assign(new Error('upstream-uncertain'), { receiptCategory: 'invalid-response', httpStatus: responseStatus })
|
|
5947
6147
|
job.result = operationResult(body)
|
|
5948
6148
|
job.phase = body.result.ok === true ? 'complete' : 'rejected'
|
|
5949
|
-
} catch {
|
|
6149
|
+
} catch (error) {
|
|
5950
6150
|
job.phase = 'unknown'
|
|
5951
6151
|
job.error = 'result-unconfirmed'
|
|
6152
|
+
job.diagnostic = operationFailureFacts(error, stage, job.createdAt)
|
|
5952
6153
|
}
|
|
5953
6154
|
job.completedAt = Date.now()
|
|
6155
|
+
if (job.diagnostic) {
|
|
6156
|
+
const facts = { method: job.method, phase: job.phase, ...job.diagnostic }
|
|
6157
|
+
recordCompatibility('operation-result', facts)
|
|
6158
|
+
console.warn('[operation]', JSON.stringify(facts))
|
|
6159
|
+
}
|
|
5954
6160
|
try { saveOperation(key, job) } catch {
|
|
5955
6161
|
// The durable intent remains running and becomes unknown after restart.
|
|
5956
6162
|
// Do not return a success that could not be durably recorded.
|
|
@@ -6104,14 +6310,15 @@ async function proxyLegacyApi(req, res, url) {
|
|
|
6104
6310
|
return proxyLegacyRpcWithModernFallback(req, res, url)
|
|
6105
6311
|
}
|
|
6106
6312
|
const headers = {}
|
|
6313
|
+
const connectionHeaders = String(req.headers.connection || '').toLowerCase().split(',').map(value => value.trim())
|
|
6107
6314
|
for (const [k, v] of Object.entries(req.headers)) {
|
|
6108
6315
|
if (v === undefined) continue
|
|
6109
6316
|
const key = k.toLowerCase()
|
|
6110
6317
|
if (['host', 'authorization', 'cookie', 'connection', 'keep-alive', 'transfer-encoding', 'upgrade',
|
|
6111
|
-
'proxy-connection', 'accept-encoding', 'origin', 'referer',
|
|
6318
|
+
'proxy-connection', 'te', 'trailer', 'proxy-authenticate', 'proxy-authorization', 'accept-encoding', 'origin', 'referer',
|
|
6112
6319
|
'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-fetch-user',
|
|
6113
6320
|
'x-dsh-remote-client'].includes(key)) continue
|
|
6114
|
-
headers[k] = v
|
|
6321
|
+
if (!connectionHeaders.includes(key)) headers[k] = v
|
|
6115
6322
|
}
|
|
6116
6323
|
headers.host = UPSTREAM.host
|
|
6117
6324
|
Object.assign(headers, dshUpstreamHeaders())
|
|
@@ -6127,6 +6334,7 @@ async function proxyLegacyApi(req, res, url) {
|
|
|
6127
6334
|
headers
|
|
6128
6335
|
}, (upstreamRes) => {
|
|
6129
6336
|
const out = { ...upstreamRes.headers }
|
|
6337
|
+
for (const key of ['connection', 'keep-alive', 'transfer-encoding', 'te', 'trailer', 'upgrade', 'proxy-connection', 'proxy-authenticate', 'proxy-authorization', ...String(out.connection || '').toLowerCase().split(',').map(value => value.trim())]) delete out[key]
|
|
6130
6338
|
delete out['content-length']
|
|
6131
6339
|
cors(res)
|
|
6132
6340
|
res.writeHead(upstreamRes.statusCode || 502, out)
|
|
@@ -6337,7 +6545,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
6337
6545
|
try {
|
|
6338
6546
|
if (!res.headersSent) {
|
|
6339
6547
|
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
|
|
6340
|
-
res.end(JSON.stringify({ error: 'internal'
|
|
6548
|
+
res.end(JSON.stringify({ error: 'internal' }))
|
|
6341
6549
|
} else {
|
|
6342
6550
|
res.destroy()
|
|
6343
6551
|
}
|
|
@@ -6519,7 +6727,10 @@ function acceptCollectorClient(req, socket, head, kind, device) {
|
|
|
6519
6727
|
// Pong 8a03010203)。这里按 RFC6455 组帧:维护 per-socket 缓冲,帧头
|
|
6520
6728
|
// (含 126/127 扩展长度)与载荷凑齐才应答,整帧消费,控制帧间数据帧安全跳过。
|
|
6521
6729
|
let rx = Buffer.alloc(0)
|
|
6730
|
+
let closing = false
|
|
6731
|
+
let stopHeartbeat = () => {}
|
|
6522
6732
|
socket.on('data', (chunk) => {
|
|
6733
|
+
if (closing) return
|
|
6523
6734
|
rx = rx.length ? Buffer.concat([rx, chunk]) : chunk
|
|
6524
6735
|
while (true) {
|
|
6525
6736
|
let frame
|
|
@@ -6532,6 +6743,30 @@ function acceptCollectorClient(req, socket, head, kind, device) {
|
|
|
6532
6743
|
if (!frame) break
|
|
6533
6744
|
if (typeof frame === 'string') { rx = Buffer.alloc(0); break }
|
|
6534
6745
|
rx = rx.subarray(frame.total)
|
|
6746
|
+
if (frame.opcode === 0x8) {
|
|
6747
|
+
// Complete the peer's close handshake instead of retaining a CLOSING
|
|
6748
|
+
// client until its implementation timeout (and still broadcasting to it).
|
|
6749
|
+
let payload = frame.payload, errorCode = 0
|
|
6750
|
+
if (!frame.fin || payload.length > 125 || payload.length === 1) errorCode = 1002
|
|
6751
|
+
else if (payload.length >= 2) {
|
|
6752
|
+
const code = payload.readUInt16BE(0)
|
|
6753
|
+
if (!(code >= 1000 && code <= 1014 && ![1004, 1005, 1006].includes(code) || code >= 3000 && code <= 4999)) errorCode = 1002
|
|
6754
|
+
else try { new TextDecoder('utf-8', { fatal: true }).decode(payload.subarray(2)) } catch { errorCode = 1007 }
|
|
6755
|
+
}
|
|
6756
|
+
if (errorCode) { payload = Buffer.alloc(2); payload.writeUInt16BE(errorCode) }
|
|
6757
|
+
closing = true
|
|
6758
|
+
rx = Buffer.alloc(0)
|
|
6759
|
+
stopHeartbeat()
|
|
6760
|
+
collectorClients[kind].delete(socket)
|
|
6761
|
+
eventCollectorState[kind].clients = collectorClients[kind].size
|
|
6762
|
+
const reply = Buffer.alloc(2 + payload.length)
|
|
6763
|
+
reply[0] = 0x88; reply[1] = payload.length; payload.copy(reply, 2)
|
|
6764
|
+
const timer = setTimeout(() => socket.destroy(), 1000)
|
|
6765
|
+
timer.unref?.()
|
|
6766
|
+
socket.once('close', () => clearTimeout(timer))
|
|
6767
|
+
try { socket.end(reply) } catch { socket.destroy() }
|
|
6768
|
+
return
|
|
6769
|
+
}
|
|
6535
6770
|
if (frame.payload.length > 125) continue
|
|
6536
6771
|
if (frame.fin === false) continue
|
|
6537
6772
|
// 仅应答 Ping(RFC6455 §5.5 控制帧载荷上限 125);Pong(0xA)消费后丢弃,
|
|
@@ -6554,7 +6789,7 @@ function acceptCollectorClient(req, socket, head, kind, device) {
|
|
|
6554
6789
|
socket.write(frame)
|
|
6555
6790
|
} catch { break }
|
|
6556
6791
|
}
|
|
6557
|
-
|
|
6792
|
+
stopHeartbeat = startWsClientHeartbeat(socket, () => socket.destroy())
|
|
6558
6793
|
const release = () => {
|
|
6559
6794
|
stopHeartbeat()
|
|
6560
6795
|
collectorClients[kind].delete(socket)
|
|
@@ -6614,15 +6849,16 @@ server.on('upgrade', (req, socket, head) => {
|
|
|
6614
6849
|
socket.once('close', release)
|
|
6615
6850
|
|
|
6616
6851
|
const headers = {}
|
|
6852
|
+
const connectionHeaders = String(req.headers.connection || '').toLowerCase().split(',').map(value => value.trim())
|
|
6617
6853
|
for (const [k, v] of Object.entries(req.headers)) {
|
|
6618
6854
|
if (v === undefined) continue
|
|
6619
6855
|
const key = k.toLowerCase()
|
|
6620
|
-
if (['host', 'authorization', 'cookie', 'connection', 'upgrade', 'sec-websocket-key',
|
|
6856
|
+
if (['host', 'authorization', 'cookie', 'connection', 'keep-alive', 'transfer-encoding', 'upgrade', 'sec-websocket-key',
|
|
6621
6857
|
'sec-websocket-version', 'sec-websocket-extensions', 'sec-websocket-protocol',
|
|
6622
|
-
'proxy-connection', 'accept-encoding', 'origin', 'referer',
|
|
6858
|
+
'proxy-connection', 'te', 'trailer', 'proxy-authenticate', 'proxy-authorization', 'accept-encoding', 'origin', 'referer',
|
|
6623
6859
|
'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-fetch-user',
|
|
6624
6860
|
'x-dsh-remote-client'].includes(key)) continue
|
|
6625
|
-
headers[k] = v
|
|
6861
|
+
if (!connectionHeaders.includes(key)) headers[k] = v
|
|
6626
6862
|
}
|
|
6627
6863
|
headers.host = UPSTREAM.host
|
|
6628
6864
|
Object.assign(headers, dshUpstreamHeaders())
|