dsh-miloco-bridge 0.1.4 → 0.1.6
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.md +28 -11
- package/cordis.patch.yml +13 -2
- package/docs/ARCHITECTURE.md +96 -17
- package/docs/INSTALL.md +29 -13
- package/docs/TOOLS.md +1 -1
- package/docs/VERIFICATION.md +50 -18
- package/docs/images/miloco-overview.png +0 -0
- package/docs/images/miloco-settings.png +0 -0
- package/docs/images/miloco-setup.png +0 -0
- package/lib/client.js +1386 -54
- package/lib/home.js +319 -0
- package/lib/index.js +57 -1
- package/lib/miloco-client.js +13 -5
- package/lib/overlay.js +53 -7
- package/lib/paths.js +18 -0
- package/lib/push.js +328 -48
- package/lib/settings-api.js +435 -7
- package/lib/state.js +62 -2
- package/lib/tools-entry.js +3 -1
- package/lib/tools.js +37 -7
- package/package.json +7 -2
package/lib/settings-api.js
CHANGED
|
@@ -6,8 +6,13 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Routes:
|
|
8
8
|
* GET /dsh-miloco-bridge/api/status mode, connection, overview, sessions
|
|
9
|
+
* GET /dsh-miloco-bridge/api/home household workspace snapshot
|
|
10
|
+
* POST /dsh-miloco-bridge/api/home move the household directory
|
|
11
|
+
* GET /dsh-miloco-bridge/api/home/overview household dashboard aggregate
|
|
12
|
+
* POST /dsh-miloco-bridge/api/miot/bind start the MiOT account binding (oauth url)
|
|
13
|
+
* POST /dsh-miloco-bridge/api/miot/authorize finish the MiOT account binding (code + state)
|
|
9
14
|
* GET /dsh-miloco-bridge/api/sessions live DSH conversations
|
|
10
|
-
* POST /dsh-miloco-bridge/api/target push destination (session + model)
|
|
15
|
+
* POST /dsh-miloco-bridge/api/target push destination (mode + session + model)
|
|
11
16
|
* POST /dsh-miloco-bridge/api/mode readonly / full
|
|
12
17
|
* GET /dsh-miloco-bridge/api/deploy deployment state + log
|
|
13
18
|
* POST /dsh-miloco-bridge/api/deploy start one-click deployment
|
|
@@ -20,12 +25,15 @@
|
|
|
20
25
|
* @module dsh-miloco-bridge/settings-api
|
|
21
26
|
*/
|
|
22
27
|
|
|
23
|
-
import { access } from 'node:fs/promises'
|
|
24
|
-
import { dirname, join } from 'node:path'
|
|
28
|
+
import { access, mkdir } from 'node:fs/promises'
|
|
29
|
+
import { dirname, isAbsolute, join } from 'node:path'
|
|
25
30
|
import { fetchLatestRelease, inferDeployKind, isNewerRelease, normalizeReleaseVersion } from './github-release.js'
|
|
26
31
|
import { MilocoError, readMilocoConfig } from './miloco-client.js'
|
|
32
|
+
import { normalizePushTargetMode } from './overlay.js'
|
|
33
|
+
import { resolveMilocoHomeDir } from './paths.js'
|
|
27
34
|
import { normalizePerceptionLevel, PERCEPTION_LEVELS } from './perception.js'
|
|
28
|
-
import {
|
|
35
|
+
import { ARCHIVE_SESSION_ID } from './push.js'
|
|
36
|
+
import { AGENT_MODES, describeMode, readPushLog, readSessions } from './state.js'
|
|
29
37
|
|
|
30
38
|
/** Prefix shared by every settings route. */
|
|
31
39
|
export const SETTINGS_PREFIX = '/dsh-miloco-bridge/api'
|
|
@@ -102,9 +110,15 @@ export function publicOverlay(overlay) {
|
|
|
102
110
|
baseUrl: overlay?.connection?.baseUrl ?? '',
|
|
103
111
|
tokenSet: Boolean(overlay?.connection?.token),
|
|
104
112
|
},
|
|
113
|
+
workspace: {
|
|
114
|
+
enabled: overlay?.workspace?.enabled !== false,
|
|
115
|
+
},
|
|
105
116
|
push: {
|
|
106
117
|
tokenSet: Boolean(overlay?.push?.token),
|
|
107
|
-
target: {
|
|
118
|
+
target: {
|
|
119
|
+
mode: overlay?.push?.target?.mode ?? '',
|
|
120
|
+
sessionId: overlay?.push?.target?.sessionId ?? '',
|
|
121
|
+
},
|
|
108
122
|
model: {
|
|
109
123
|
provider: overlay?.push?.model?.provider ?? '',
|
|
110
124
|
model: overlay?.push?.model?.model ?? '',
|
|
@@ -147,6 +161,148 @@ async function readCatalog(ctx) {
|
|
|
147
161
|
}
|
|
148
162
|
}
|
|
149
163
|
|
|
164
|
+
/**
|
|
165
|
+
* Decode the payload the Xiaomi callback page hands out.
|
|
166
|
+
*
|
|
167
|
+
* The callback page shows one base64 blob that encodes `{"code":…,"state":…}`.
|
|
168
|
+
* Miloco's own web UI decodes it in the browser; the plugin accepts the same
|
|
169
|
+
* blob (plain JSON is accepted too) so the household page can finish the
|
|
170
|
+
* binding without asking the user to split two values by hand.
|
|
171
|
+
*
|
|
172
|
+
* The authorization code is a one-time credential: it is never logged and
|
|
173
|
+
* never echoed back to the browser.
|
|
174
|
+
*
|
|
175
|
+
* @param {string} raw - The pasted payload.
|
|
176
|
+
* @returns {{code: string, state: string} | null} The decoded pair, or null.
|
|
177
|
+
*/
|
|
178
|
+
export function decodeAuthPayload(raw) {
|
|
179
|
+
const text = String(raw ?? '').trim()
|
|
180
|
+
if (!text) return null
|
|
181
|
+
const candidates = [text]
|
|
182
|
+
const normalized = text.replace(/-/g, '+').replace(/_/g, '/')
|
|
183
|
+
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
|
|
184
|
+
if (padded !== text) candidates.push(padded)
|
|
185
|
+
for (const candidate of candidates) {
|
|
186
|
+
try {
|
|
187
|
+
const parsed = JSON.parse(Buffer.from(candidate, 'base64').toString('utf8'))
|
|
188
|
+
if (parsed && typeof parsed.code === 'string' && typeof parsed.state === 'string') {
|
|
189
|
+
return { code: parsed.code.trim(), state: parsed.state.trim() }
|
|
190
|
+
}
|
|
191
|
+
} catch { /* not this shape; try the next one */ }
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
const parsed = JSON.parse(text)
|
|
195
|
+
if (parsed && typeof parsed.code === 'string' && typeof parsed.state === 'string') {
|
|
196
|
+
return { code: parsed.code.trim(), state: parsed.state.trim() }
|
|
197
|
+
}
|
|
198
|
+
} catch { /* not JSON either */ }
|
|
199
|
+
return null
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Group device rows by room for the household overview.
|
|
204
|
+
* @param {any[]} rows - Raw `/api/miot/device_list` rows.
|
|
205
|
+
* @returns {{name: string, total: number, online: number, devices: any[]}[]} Room groups.
|
|
206
|
+
*/
|
|
207
|
+
function groupDevices(rows) {
|
|
208
|
+
const rooms = new Map()
|
|
209
|
+
for (const row of rows) {
|
|
210
|
+
if (!row || typeof row !== 'object') continue
|
|
211
|
+
const name = String(row.room_name ?? row.room ?? '').trim() || '未分组'
|
|
212
|
+
const room = rooms.get(name) ?? { name, total: 0, online: 0, devices: [] }
|
|
213
|
+
room.total += 1
|
|
214
|
+
if (row.online === true) room.online += 1
|
|
215
|
+
room.devices.push({
|
|
216
|
+
did: String(row.did ?? ''),
|
|
217
|
+
name: String(row.name ?? ''),
|
|
218
|
+
online: row.online === true,
|
|
219
|
+
model: String(row.model ?? ''),
|
|
220
|
+
})
|
|
221
|
+
rooms.set(name, room)
|
|
222
|
+
}
|
|
223
|
+
return [...rooms.values()]
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Read one `键:值` line out of a Miloco event text block.
|
|
228
|
+
* @param {string} text - Raw event text.
|
|
229
|
+
* @param {string[]} labels - Accepted labels, first match wins.
|
|
230
|
+
* @returns {string} The trimmed value, or ''.
|
|
231
|
+
*/
|
|
232
|
+
function readEventField(text, labels) {
|
|
233
|
+
for (const label of labels) {
|
|
234
|
+
const match = new RegExp(`^\\s*${label}\\s*[::]\\s*(.+)$`, 'm').exec(text)
|
|
235
|
+
if (match) return match[1].trim()
|
|
236
|
+
}
|
|
237
|
+
return ''
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Return the first value that carries text.
|
|
242
|
+
* @param {...any} values - Candidate values.
|
|
243
|
+
* @returns {string} The first non-empty trimmed string, or ''.
|
|
244
|
+
*/
|
|
245
|
+
function firstText(...values) {
|
|
246
|
+
for (const value of values) {
|
|
247
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
248
|
+
if (text) return text
|
|
249
|
+
}
|
|
250
|
+
return ''
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Normalise `/api/events` rows for the household overview.
|
|
255
|
+
*
|
|
256
|
+
* The backend unwraps to `{ events: [...] }`, and a perception row carries all
|
|
257
|
+
* of its meaning inside a free-text block (`来源:…`, `检测到:…`,
|
|
258
|
+
* `事件优先级:…`) rather than in structured fields. Older or non-perception
|
|
259
|
+
* rows may still use `type` / `source`, so both shapes are accepted.
|
|
260
|
+
*
|
|
261
|
+
* @param {any} payload - Unwrapped `/api/events` payload (array or `{events}`).
|
|
262
|
+
* @returns {{kind: string, source: string, summary: string, priority: string, timestamp: number}[]} Rows, newest first.
|
|
263
|
+
*/
|
|
264
|
+
export function normalizeEvents(payload) {
|
|
265
|
+
const rows = Array.isArray(payload)
|
|
266
|
+
? payload
|
|
267
|
+
: Array.isArray(payload?.events) ? payload.events : []
|
|
268
|
+
const items = []
|
|
269
|
+
for (const row of rows) {
|
|
270
|
+
if (!row || typeof row !== 'object') continue
|
|
271
|
+
const text = typeof row.text === 'string' ? row.text : ''
|
|
272
|
+
const perception = text.includes('[感知引擎]')
|
|
273
|
+
const rawPriority = firstText(
|
|
274
|
+
row.urgency, row.priority, readEventField(text, ['事件优先级', '优先级']),
|
|
275
|
+
).toLowerCase()
|
|
276
|
+
const rawStamp = row.timestamp ?? row.ts ?? row.created_at ?? row.time
|
|
277
|
+
const fallbackLine = text
|
|
278
|
+
.split('\n')
|
|
279
|
+
.map(line => line.trim())
|
|
280
|
+
.find(line => line && !line.startsWith('[')) ?? ''
|
|
281
|
+
items.push({
|
|
282
|
+
kind: firstText(row.type, row.event_type) || (perception ? '感知事件' : '事件'),
|
|
283
|
+
source: firstText(
|
|
284
|
+
row.source,
|
|
285
|
+
row.device_name,
|
|
286
|
+
row.did,
|
|
287
|
+
readEventField(text, ['来源']),
|
|
288
|
+
Array.isArray(row.device_ids) && row.device_ids.length ? String(row.device_ids[0]) : '',
|
|
289
|
+
) || '—',
|
|
290
|
+
summary: firstText(
|
|
291
|
+
row.summary,
|
|
292
|
+
readEventField(text, ['检测到', '画面描述', '建议']),
|
|
293
|
+
fallbackLine,
|
|
294
|
+
),
|
|
295
|
+
priority: ['high', 'medium', 'low'].includes(rawPriority) ? rawPriority : '',
|
|
296
|
+
timestamp: Number.isFinite(rawStamp)
|
|
297
|
+
? (rawStamp < 1e12 ? rawStamp * 1000 : rawStamp)
|
|
298
|
+
: (typeof rawStamp === 'string' ? Date.parse(rawStamp) : NaN),
|
|
299
|
+
})
|
|
300
|
+
}
|
|
301
|
+
return items
|
|
302
|
+
.sort((a, b) => (Number.isFinite(b.timestamp) ? b.timestamp : 0) - (Number.isFinite(a.timestamp) ? a.timestamp : 0))
|
|
303
|
+
.slice(0, 10)
|
|
304
|
+
}
|
|
305
|
+
|
|
150
306
|
/**
|
|
151
307
|
* List DSH conversations for the target dropdown.
|
|
152
308
|
*
|
|
@@ -206,7 +362,7 @@ async function listSessions(ctx, state) {
|
|
|
206
362
|
/**
|
|
207
363
|
* Register the settings routes on the host web server.
|
|
208
364
|
*
|
|
209
|
-
* @param {{ctx: any, config: any, client: any, overlay: any, state?: any, deploy?: any, writeConfig?: any, logger?: any}} options - Service options.
|
|
365
|
+
* @param {{ctx: any, config: any, client: any, overlay: any, state?: any, deploy?: any, writeConfig?: any, home?: any, logger?: any}} options - Service options.
|
|
210
366
|
* @returns {() => void} A disposer removing every route.
|
|
211
367
|
*/
|
|
212
368
|
export function registerSettingsApi(options) {
|
|
@@ -365,6 +521,10 @@ export function registerSettingsApi(options) {
|
|
|
365
521
|
push: {
|
|
366
522
|
enabled: config.push.enabled,
|
|
367
523
|
path: config.push.path,
|
|
524
|
+
target: {
|
|
525
|
+
// Effective mode: runtime overlay first, static config second.
|
|
526
|
+
mode: current.push.target.mode || config.push?.target?.mode || 'archive',
|
|
527
|
+
},
|
|
368
528
|
tokenSet: Boolean(effectivePushToken),
|
|
369
529
|
waitForResult: config.push.waitForResult,
|
|
370
530
|
perception: {
|
|
@@ -390,6 +550,267 @@ export function registerSettingsApi(options) {
|
|
|
390
550
|
})
|
|
391
551
|
})
|
|
392
552
|
|
|
553
|
+
route(`${SETTINGS_PREFIX}/home`, async (req, res) => {
|
|
554
|
+
const homeService = options.home
|
|
555
|
+
if (!homeService) {
|
|
556
|
+
sendJson(res, 503, { ok: false, error: '家庭助手工作区不可用' })
|
|
557
|
+
return
|
|
558
|
+
}
|
|
559
|
+
if (req.method === 'GET') {
|
|
560
|
+
// `ensure()` is idempotent: it creates the directory and registers the
|
|
561
|
+
// host workspace once, so the id is present even on the first request.
|
|
562
|
+
const state = await homeService.ensure()
|
|
563
|
+
sendJson(res, 200, { ok: true, ...state, archiveSessionId: ARCHIVE_SESSION_ID })
|
|
564
|
+
return
|
|
565
|
+
}
|
|
566
|
+
if (req.method !== 'POST') {
|
|
567
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
568
|
+
return
|
|
569
|
+
}
|
|
570
|
+
const body = await mutateBody(req, res)
|
|
571
|
+
if (body === null) return
|
|
572
|
+
const raw = typeof body.dir === 'string' ? body.dir.trim() : ''
|
|
573
|
+
const hasEnabled = typeof body.enabled === 'boolean'
|
|
574
|
+
if (!raw && !hasEnabled) {
|
|
575
|
+
sendJson(res, 400, { ok: false, error: '目录不能为空' })
|
|
576
|
+
return
|
|
577
|
+
}
|
|
578
|
+
if (raw) {
|
|
579
|
+
const target = resolveMilocoHomeDir(raw)
|
|
580
|
+
if (!isAbsolute(target)) {
|
|
581
|
+
sendJson(res, 400, { ok: false, error: '目录必须是绝对路径' })
|
|
582
|
+
return
|
|
583
|
+
}
|
|
584
|
+
// Create before writing the overlay: a directory that cannot be created
|
|
585
|
+
// must leave the configured household workspace untouched.
|
|
586
|
+
try {
|
|
587
|
+
await mkdir(target, { recursive: true })
|
|
588
|
+
} catch (error) {
|
|
589
|
+
sendJson(res, 500, { ok: false, error: `创建目录失败:${error instanceof Error ? error.message : error}` })
|
|
590
|
+
return
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
const previousPath = homeService.dir
|
|
594
|
+
try {
|
|
595
|
+
if (raw) await homeService.setDir(raw)
|
|
596
|
+
if (hasEnabled) await homeService.setEnabled(body.enabled)
|
|
597
|
+
const state = await homeService.ensure()
|
|
598
|
+
sendJson(res, 200, { ok: true, ...state, previousPath, archiveSessionId: ARCHIVE_SESSION_ID })
|
|
599
|
+
} catch (error) {
|
|
600
|
+
sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
601
|
+
}
|
|
602
|
+
})
|
|
603
|
+
|
|
604
|
+
route(`${SETTINGS_PREFIX}/home/overview`, async (req, res) => {
|
|
605
|
+
if (req.method !== 'GET') {
|
|
606
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
607
|
+
return
|
|
608
|
+
}
|
|
609
|
+
if (!options.home) {
|
|
610
|
+
sendJson(res, 503, { ok: false, error: '家庭助手工作区不可用' })
|
|
611
|
+
return
|
|
612
|
+
}
|
|
613
|
+
// Every backend section fails on its own: one unreachable endpoint must
|
|
614
|
+
// not blank the whole dashboard.
|
|
615
|
+
const homeState = await options.home.ensure()
|
|
616
|
+
const short = AbortSignal.timeout(8_000)
|
|
617
|
+
const attempt = promise => promise
|
|
618
|
+
.then(data => ({ ok: true, data }))
|
|
619
|
+
.catch(error => ({ ok: false, error: error instanceof Error ? error.message : String(error) }))
|
|
620
|
+
const [status, version, devices, events, user, login, engine, cameras, rules, tasks, usage] = await Promise.all([
|
|
621
|
+
attempt(client.get('/api/admin/status', { signal: short })),
|
|
622
|
+
attempt(client.get('/api/admin/version', { signal: short })),
|
|
623
|
+
attempt(client.get('/api/miot/device_list', { signal: short })),
|
|
624
|
+
attempt(client.get('/api/events', { query: { limit: 10 }, signal: short })),
|
|
625
|
+
attempt(client.get('/api/miot/user_info', { signal: short })),
|
|
626
|
+
attempt(client.get('/api/miot/login_status', { signal: short })),
|
|
627
|
+
attempt(client.get('/api/perception/engine/status', { signal: short })),
|
|
628
|
+
attempt(client.get('/api/miot/camera_list', { signal: short })),
|
|
629
|
+
attempt(client.get('/api/rules', { signal: short })),
|
|
630
|
+
attempt(client.get('/api/tasks', { signal: short })),
|
|
631
|
+
attempt(client.get('/api/admin/token-usage', { query: { limit: 500 }, signal: short })),
|
|
632
|
+
])
|
|
633
|
+
const rows = devices.ok && Array.isArray(devices.data) ? devices.data : []
|
|
634
|
+
const rooms = groupDevices(rows)
|
|
635
|
+
const online = rows.filter(device => device && device.online === true).length
|
|
636
|
+
// Token usage is a sum over the recorded events, not a single counter.
|
|
637
|
+
const usageRows = usage.ok && Array.isArray(usage.data?.events) ? usage.data.events : []
|
|
638
|
+
const sumField = field => usageRows.reduce(
|
|
639
|
+
(sum, row) => sum + (Number(row?.[field] ?? 0) || 0),
|
|
640
|
+
0,
|
|
641
|
+
)
|
|
642
|
+
const tokenInput = sumField('input_tokens')
|
|
643
|
+
const tokenOutput = sumField('output_tokens')
|
|
644
|
+
const tokenTotal = tokenInput + tokenOutput
|
|
645
|
+
+ sumField('cache_tokens')
|
|
646
|
+
+ sumField('video_tokens')
|
|
647
|
+
+ sumField('audio_tokens')
|
|
648
|
+
const current = await overlay.current()
|
|
649
|
+
let archiveExists = false
|
|
650
|
+
try {
|
|
651
|
+
const resolved = await ctx.sessionController.resolveAgent(ARCHIVE_SESSION_ID)
|
|
652
|
+
archiveExists = Boolean(resolved && typeof resolved === 'object' && resolved.agent)
|
|
653
|
+
} catch { /* treat as absent */ }
|
|
654
|
+
// The setup block tells the household page whether the plugin is wired up
|
|
655
|
+
// at all. An unconfigured installation must not render the same dense
|
|
656
|
+
// dashboard as a working one: the page switches to its own centred
|
|
657
|
+
// onboarding view instead.
|
|
658
|
+
const endpoint = await client.endpoint()
|
|
659
|
+
const accountBound = Boolean(user.ok && user.data?.uid)
|
|
660
|
+
const pushTokenSet = Boolean(
|
|
661
|
+
String(current.push.token ?? '') || String(config.push?.token ?? ''),
|
|
662
|
+
)
|
|
663
|
+
sendJson(res, 200, {
|
|
664
|
+
ok: true,
|
|
665
|
+
setup: {
|
|
666
|
+
connection: {
|
|
667
|
+
baseUrl: endpoint.baseUrl,
|
|
668
|
+
source: endpoint.source,
|
|
669
|
+
tokenSet: Boolean(endpoint.token),
|
|
670
|
+
// Miloco answered `/api/admin/status`: the bridge can talk to it.
|
|
671
|
+
reachable: status.ok,
|
|
672
|
+
},
|
|
673
|
+
account: {
|
|
674
|
+
bound: accountBound,
|
|
675
|
+
uid: user.ok ? (user.data?.uid ?? null) : null,
|
|
676
|
+
nickname: user.ok ? (user.data?.nickname ?? '') : '',
|
|
677
|
+
loggedIn: Boolean(login.ok && login.data?.is_logged_in),
|
|
678
|
+
},
|
|
679
|
+
accountBound,
|
|
680
|
+
pushTokenSet,
|
|
681
|
+
// Ready = the household page can show real data. A reachable backend
|
|
682
|
+
// without a bound account still shows the onboarding page: the
|
|
683
|
+
// dashboard would be empty without a household.
|
|
684
|
+
ready: status.ok && accountBound,
|
|
685
|
+
// Miloco's own web UI: the recommended place to bind the account.
|
|
686
|
+
milocoUrl: endpoint.baseUrl,
|
|
687
|
+
...(status.ok ? {} : { error: status.error }),
|
|
688
|
+
},
|
|
689
|
+
home: {
|
|
690
|
+
...homeState,
|
|
691
|
+
archive: { sessionId: ARCHIVE_SESSION_ID, exists: archiveExists },
|
|
692
|
+
},
|
|
693
|
+
status: {
|
|
694
|
+
ok: status.ok,
|
|
695
|
+
reachable: status.ok,
|
|
696
|
+
account: user.ok && user.data?.nickname
|
|
697
|
+
? { nickname: user.data.nickname, uid: user.data.uid ?? null }
|
|
698
|
+
: null,
|
|
699
|
+
accountBound: Boolean(user.ok && user.data?.uid),
|
|
700
|
+
perceptionRunning: Boolean(engine.ok && engine.data?.running),
|
|
701
|
+
...(status.ok ? {} : { error: status.error }),
|
|
702
|
+
},
|
|
703
|
+
version: {
|
|
704
|
+
ok: version.ok,
|
|
705
|
+
current: version.ok ? String(version.data?.version ?? '') : '',
|
|
706
|
+
latest: lastUpgradeCheck?.latest ?? '',
|
|
707
|
+
hasUpdate: Boolean(lastUpgradeCheck?.has_update),
|
|
708
|
+
...(version.ok ? {} : { error: version.error }),
|
|
709
|
+
},
|
|
710
|
+
devices: {
|
|
711
|
+
ok: devices.ok,
|
|
712
|
+
total: rows.length,
|
|
713
|
+
online,
|
|
714
|
+
rooms,
|
|
715
|
+
...(devices.ok ? {} : { error: devices.error }),
|
|
716
|
+
},
|
|
717
|
+
overview: {
|
|
718
|
+
account: user.ok && user.data?.nickname
|
|
719
|
+
? { nickname: user.data.nickname, uid: user.data.uid ?? null }
|
|
720
|
+
: null,
|
|
721
|
+
accountBound: Boolean(user.ok && user.data?.uid),
|
|
722
|
+
deviceCount: devices.ok ? rows.length : null,
|
|
723
|
+
cameraCount: cameras.ok && Array.isArray(cameras.data) ? cameras.data.length : null,
|
|
724
|
+
ruleCount: rules.ok && Array.isArray(rules.data) ? rules.data.length : null,
|
|
725
|
+
taskCount: tasks.ok && Array.isArray(tasks.data) ? tasks.data.length : null,
|
|
726
|
+
perceptionRunning: Boolean(engine.ok && engine.data?.running),
|
|
727
|
+
perceptionSources: engine.ok && Array.isArray(engine.data?.active_sources)
|
|
728
|
+
? engine.data.active_sources.length
|
|
729
|
+
: null,
|
|
730
|
+
tokenEvents: usage.ok
|
|
731
|
+
? (Number.isFinite(usage.data?.total) ? usage.data.total : usageRows.length)
|
|
732
|
+
: null,
|
|
733
|
+
tokenInput: tokenInput || null,
|
|
734
|
+
tokenOutput: tokenOutput || null,
|
|
735
|
+
tokenTotal: tokenTotal || null,
|
|
736
|
+
},
|
|
737
|
+
events: {
|
|
738
|
+
ok: events.ok,
|
|
739
|
+
items: events.ok ? normalizeEvents(events.data) : [],
|
|
740
|
+
...(events.ok ? {} : { error: events.error }),
|
|
741
|
+
},
|
|
742
|
+
pushes: {
|
|
743
|
+
ok: true,
|
|
744
|
+
items: options.state ? await readPushLog(options.state) : [],
|
|
745
|
+
},
|
|
746
|
+
push: {
|
|
747
|
+
path: String(config.push?.path ?? '/miloco/webhook'),
|
|
748
|
+
tokenSet: Boolean(String(current.push.token ?? '') || String(config.push?.token ?? '')),
|
|
749
|
+
},
|
|
750
|
+
})
|
|
751
|
+
})
|
|
752
|
+
|
|
753
|
+
route(`${SETTINGS_PREFIX}/miot/bind`, async (req, res) => {
|
|
754
|
+
if (req.method !== 'POST') {
|
|
755
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
756
|
+
return
|
|
757
|
+
}
|
|
758
|
+
const body = await mutateBody(req, res)
|
|
759
|
+
if (body === null) return
|
|
760
|
+
try {
|
|
761
|
+
// Miloco answers with the Xiaomi OAuth URL; the user opens it, approves,
|
|
762
|
+
// and comes back with the payload the callback page shows.
|
|
763
|
+
const result = await client.post('/api/miot/bind')
|
|
764
|
+
const oauthUrl = String(result?.oauth_url ?? result?.oauthUrl ?? '').trim()
|
|
765
|
+
if (!oauthUrl) {
|
|
766
|
+
sendJson(res, 502, { ok: false, error: 'Miloco 没有返回授权链接' })
|
|
767
|
+
return
|
|
768
|
+
}
|
|
769
|
+
let state = ''
|
|
770
|
+
try {
|
|
771
|
+
state = new URL(oauthUrl).searchParams.get('state') ?? ''
|
|
772
|
+
} catch { /* the URL is not parseable; the user pastes the whole payload anyway */ }
|
|
773
|
+
sendJson(res, 200, { ok: true, oauthUrl, state })
|
|
774
|
+
} catch (error) {
|
|
775
|
+
sendJson(res, 502, {
|
|
776
|
+
ok: false,
|
|
777
|
+
error: error instanceof Error ? error.message : String(error),
|
|
778
|
+
})
|
|
779
|
+
}
|
|
780
|
+
})
|
|
781
|
+
|
|
782
|
+
route(`${SETTINGS_PREFIX}/miot/authorize`, async (req, res) => {
|
|
783
|
+
if (req.method !== 'POST') {
|
|
784
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
785
|
+
return
|
|
786
|
+
}
|
|
787
|
+
const body = await mutateBody(req, res)
|
|
788
|
+
if (body === null) return
|
|
789
|
+
const payload = decodeAuthPayload(body.payload ?? body.code ?? '')
|
|
790
|
+
if (!payload) {
|
|
791
|
+
sendJson(res, 400, { ok: false, error: '看不懂这段授权内容,请粘贴小米回调页给出的整段内容' })
|
|
792
|
+
return
|
|
793
|
+
}
|
|
794
|
+
try {
|
|
795
|
+
// The authorization code is a one-time credential: it is forwarded to
|
|
796
|
+
// Miloco and never logged or echoed back.
|
|
797
|
+
const result = await client.post('/api/miot/authorize', {
|
|
798
|
+
code: payload.code,
|
|
799
|
+
state: payload.state,
|
|
800
|
+
})
|
|
801
|
+
sendJson(res, 200, {
|
|
802
|
+
ok: true,
|
|
803
|
+
accountChanged: Boolean(result?.account_changed),
|
|
804
|
+
scopePreserved: Boolean(result?.scope_preserved),
|
|
805
|
+
})
|
|
806
|
+
} catch (error) {
|
|
807
|
+
sendJson(res, 502, {
|
|
808
|
+
ok: false,
|
|
809
|
+
error: error instanceof Error ? error.message : String(error),
|
|
810
|
+
})
|
|
811
|
+
}
|
|
812
|
+
})
|
|
813
|
+
|
|
393
814
|
route(`${SETTINGS_PREFIX}/sessions`, async (req, res) => {
|
|
394
815
|
if (req.method !== 'GET') {
|
|
395
816
|
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
@@ -423,6 +844,9 @@ export function registerSettingsApi(options) {
|
|
|
423
844
|
const perceptionLevel = typeof body.perceptionLevel === 'string'
|
|
424
845
|
? body.perceptionLevel.trim()
|
|
425
846
|
: current.push.perception.minLevel
|
|
847
|
+
const mode = body.mode === undefined
|
|
848
|
+
? (current.push.target.mode || '')
|
|
849
|
+
: normalizePushTargetMode(body.mode)
|
|
426
850
|
|
|
427
851
|
if (Boolean(provider) !== Boolean(model)) {
|
|
428
852
|
sendJson(res, 400, { ok: false, error: 'provider 与 model 必须同时选择,或都留空(跟随对话)' })
|
|
@@ -435,12 +859,16 @@ export function registerSettingsApi(options) {
|
|
|
435
859
|
})
|
|
436
860
|
return
|
|
437
861
|
}
|
|
862
|
+
if (body.mode !== undefined && !mode) {
|
|
863
|
+
sendJson(res, 400, { ok: false, error: 'mode 只能是 archive / session' })
|
|
864
|
+
return
|
|
865
|
+
}
|
|
438
866
|
|
|
439
867
|
await overlay.write({
|
|
440
868
|
connection: current.connection,
|
|
441
869
|
push: {
|
|
442
870
|
token: current.push.token,
|
|
443
|
-
target: { sessionId },
|
|
871
|
+
target: { mode, sessionId },
|
|
444
872
|
model: { provider, model, reasoningEffort },
|
|
445
873
|
perception: { minLevel: perceptionLevel },
|
|
446
874
|
},
|
package/lib/state.js
CHANGED
|
@@ -8,9 +8,11 @@
|
|
|
8
8
|
*
|
|
9
9
|
* - `mode` — readonly / full, read by the tool half at activation;
|
|
10
10
|
* - `lastSession` — the DSH session that last touched a Miloco tool. This is
|
|
11
|
-
* the default destination for an inbound push when no session is configured
|
|
11
|
+
* the default destination for an inbound push when no session is configured;
|
|
12
|
+
* - `pushLog` — the most recent outbound pushes, metadata only.
|
|
12
13
|
*
|
|
13
|
-
* Only session ids and timestamps are stored; no
|
|
14
|
+
* Only session ids, titles, summaries and timestamps are stored; no
|
|
15
|
+
* conversation content.
|
|
14
16
|
*
|
|
15
17
|
* @module dsh-miloco-bridge/state
|
|
16
18
|
*/
|
|
@@ -185,3 +187,61 @@ export async function clearSessions(store, sessionIds = []) {
|
|
|
185
187
|
...(keepLast ? {} : { lastSession: '', lastSessionAt: 0 }),
|
|
186
188
|
})
|
|
187
189
|
}
|
|
190
|
+
|
|
191
|
+
/** Maximum remembered push log entries. */
|
|
192
|
+
export const MAX_PUSH_LOG = 20
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Normalise a stored push log.
|
|
196
|
+
* @param {any} value - Raw `pushLog` value.
|
|
197
|
+
* @returns {{at: number, title: string, summary: string, sessionId: string, status: string, runId: string}[]} Entries, newest first.
|
|
198
|
+
*/
|
|
199
|
+
export function normalizePushLog(value) {
|
|
200
|
+
if (!Array.isArray(value)) return []
|
|
201
|
+
const rows = []
|
|
202
|
+
for (const item of value) {
|
|
203
|
+
if (!item || typeof item !== 'object') continue
|
|
204
|
+
rows.push({
|
|
205
|
+
at: Number.isFinite(item.at) ? item.at : 0,
|
|
206
|
+
title: typeof item.title === 'string' ? item.title : '',
|
|
207
|
+
summary: typeof item.summary === 'string' ? item.summary : '',
|
|
208
|
+
sessionId: typeof item.sessionId === 'string' ? item.sessionId : '',
|
|
209
|
+
status: typeof item.status === 'string' ? item.status : '',
|
|
210
|
+
runId: typeof item.runId === 'string' ? item.runId : '',
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
return rows.slice(0, MAX_PUSH_LOG)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Prepend one delivery record to the push log.
|
|
218
|
+
* @param {{file: string, read: () => Promise<any>, write: (patch: any) => Promise<any>}} store - The state store.
|
|
219
|
+
* @param {{at?: number, title?: string, summary?: string, sessionId?: string, status?: string, runId?: string}} entry - Delivery metadata.
|
|
220
|
+
* @returns {Promise<any[]>} The persisted log.
|
|
221
|
+
*/
|
|
222
|
+
export async function notePush(store, entry) {
|
|
223
|
+
const current = await store.read()
|
|
224
|
+
const log = normalizePushLog(current.pushLog)
|
|
225
|
+
if (entry && typeof entry === 'object') {
|
|
226
|
+
log.unshift({
|
|
227
|
+
at: Number.isFinite(entry.at) ? entry.at : Date.now(),
|
|
228
|
+
title: typeof entry.title === 'string' ? entry.title : '',
|
|
229
|
+
summary: typeof entry.summary === 'string' ? entry.summary : '',
|
|
230
|
+
sessionId: typeof entry.sessionId === 'string' ? entry.sessionId : '',
|
|
231
|
+
status: typeof entry.status === 'string' ? entry.status : '',
|
|
232
|
+
runId: typeof entry.runId === 'string' ? entry.runId : '',
|
|
233
|
+
})
|
|
234
|
+
}
|
|
235
|
+
const next = log.slice(0, MAX_PUSH_LOG)
|
|
236
|
+
await store.write({ pushLog: next })
|
|
237
|
+
return next
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Read the recent push log.
|
|
242
|
+
* @param {{file: string, read: () => Promise<any>}} store - The state store.
|
|
243
|
+
* @returns {Promise<any[]>} Entries, newest first.
|
|
244
|
+
*/
|
|
245
|
+
export async function readPushLog(store) {
|
|
246
|
+
return normalizePushLog((await store.read()).pushLog)
|
|
247
|
+
}
|
package/lib/tools-entry.js
CHANGED
|
@@ -22,7 +22,7 @@ import { createMilocoClient, resolveMilocoHome } from './miloco-client.js'
|
|
|
22
22
|
import { createMilocoTools } from './tools.js'
|
|
23
23
|
import { registerSkills } from './skills.js'
|
|
24
24
|
import { createDeliverTool } from './deliver-tool.js'
|
|
25
|
-
import { createOverlay, DEFAULT_OVERLAY_FILE } from './overlay.js'
|
|
25
|
+
import { createOverlay, DEFAULT_OVERLAY_FILE, normalizePushTargetMode } from './overlay.js'
|
|
26
26
|
import { normalizePerceptionLevel } from './perception.js'
|
|
27
27
|
import { DEFAULT_PUSH_PATH } from './push.js'
|
|
28
28
|
import { createStateStore, DEFAULT_STATE_FILE, noteSession, describeMode } from './state.js'
|
|
@@ -69,6 +69,7 @@ export function normalizeConfig(raw) {
|
|
|
69
69
|
token: typeof pushRaw.token === 'string' ? pushRaw.token : '',
|
|
70
70
|
waitForResult: pushRaw.waitForResult !== false,
|
|
71
71
|
target: {
|
|
72
|
+
mode: normalizePushTargetMode(targetRaw.mode) || 'archive',
|
|
72
73
|
sessionId: typeof targetRaw.sessionId === 'string' ? targetRaw.sessionId.trim() : '',
|
|
73
74
|
},
|
|
74
75
|
model: {
|
|
@@ -179,6 +180,7 @@ export async function apply(ctx, rawConfig) {
|
|
|
179
180
|
catalog,
|
|
180
181
|
state,
|
|
181
182
|
sessionIdOf,
|
|
183
|
+
pushMode: config.push.target.mode,
|
|
182
184
|
})
|
|
183
185
|
|
|
184
186
|
const disposers = tools.map(tool => ctx.tools.register(tool))
|