dsh-miloco-bridge 0.1.4 → 0.1.5
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 +17 -11
- package/cordis.patch.yml +13 -2
- package/docs/ARCHITECTURE.md +74 -17
- package/docs/INSTALL.md +23 -13
- package/docs/TOOLS.md +1 -1
- package/docs/VERIFICATION.md +30 -16
- package/docs/images/miloco-overview.png +0 -0
- package/docs/images/miloco-settings.png +0 -0
- package/lib/client.js +979 -54
- package/lib/home.js +319 -0
- package/lib/index.js +57 -1
- package/lib/overlay.js +53 -7
- package/lib/paths.js +18 -0
- package/lib/push.js +328 -48
- package/lib/settings-api.js +300 -7
- package/lib/state.js +62 -2
- package/lib/tools-entry.js +3 -1
- package/lib/tools.js +24 -5
- package/package.json +7 -2
package/lib/settings-api.js
CHANGED
|
@@ -6,8 +6,11 @@
|
|
|
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
|
|
9
12
|
* GET /dsh-miloco-bridge/api/sessions live DSH conversations
|
|
10
|
-
* POST /dsh-miloco-bridge/api/target push destination (session + model)
|
|
13
|
+
* POST /dsh-miloco-bridge/api/target push destination (mode + session + model)
|
|
11
14
|
* POST /dsh-miloco-bridge/api/mode readonly / full
|
|
12
15
|
* GET /dsh-miloco-bridge/api/deploy deployment state + log
|
|
13
16
|
* POST /dsh-miloco-bridge/api/deploy start one-click deployment
|
|
@@ -20,12 +23,15 @@
|
|
|
20
23
|
* @module dsh-miloco-bridge/settings-api
|
|
21
24
|
*/
|
|
22
25
|
|
|
23
|
-
import { access } from 'node:fs/promises'
|
|
24
|
-
import { dirname, join } from 'node:path'
|
|
26
|
+
import { access, mkdir } from 'node:fs/promises'
|
|
27
|
+
import { dirname, isAbsolute, join } from 'node:path'
|
|
25
28
|
import { fetchLatestRelease, inferDeployKind, isNewerRelease, normalizeReleaseVersion } from './github-release.js'
|
|
26
29
|
import { MilocoError, readMilocoConfig } from './miloco-client.js'
|
|
30
|
+
import { normalizePushTargetMode } from './overlay.js'
|
|
31
|
+
import { resolveMilocoHomeDir } from './paths.js'
|
|
27
32
|
import { normalizePerceptionLevel, PERCEPTION_LEVELS } from './perception.js'
|
|
28
|
-
import {
|
|
33
|
+
import { ARCHIVE_SESSION_ID } from './push.js'
|
|
34
|
+
import { AGENT_MODES, describeMode, readPushLog, readSessions } from './state.js'
|
|
29
35
|
|
|
30
36
|
/** Prefix shared by every settings route. */
|
|
31
37
|
export const SETTINGS_PREFIX = '/dsh-miloco-bridge/api'
|
|
@@ -102,9 +108,15 @@ export function publicOverlay(overlay) {
|
|
|
102
108
|
baseUrl: overlay?.connection?.baseUrl ?? '',
|
|
103
109
|
tokenSet: Boolean(overlay?.connection?.token),
|
|
104
110
|
},
|
|
111
|
+
workspace: {
|
|
112
|
+
enabled: overlay?.workspace?.enabled !== false,
|
|
113
|
+
},
|
|
105
114
|
push: {
|
|
106
115
|
tokenSet: Boolean(overlay?.push?.token),
|
|
107
|
-
target: {
|
|
116
|
+
target: {
|
|
117
|
+
mode: overlay?.push?.target?.mode ?? '',
|
|
118
|
+
sessionId: overlay?.push?.target?.sessionId ?? '',
|
|
119
|
+
},
|
|
108
120
|
model: {
|
|
109
121
|
provider: overlay?.push?.model?.provider ?? '',
|
|
110
122
|
model: overlay?.push?.model?.model ?? '',
|
|
@@ -147,6 +159,110 @@ async function readCatalog(ctx) {
|
|
|
147
159
|
}
|
|
148
160
|
}
|
|
149
161
|
|
|
162
|
+
/**
|
|
163
|
+
* Group device rows by room for the household overview.
|
|
164
|
+
* @param {any[]} rows - Raw `/api/miot/device_list` rows.
|
|
165
|
+
* @returns {{name: string, total: number, online: number, devices: any[]}[]} Room groups.
|
|
166
|
+
*/
|
|
167
|
+
function groupDevices(rows) {
|
|
168
|
+
const rooms = new Map()
|
|
169
|
+
for (const row of rows) {
|
|
170
|
+
if (!row || typeof row !== 'object') continue
|
|
171
|
+
const name = String(row.room_name ?? row.room ?? '').trim() || '未分组'
|
|
172
|
+
const room = rooms.get(name) ?? { name, total: 0, online: 0, devices: [] }
|
|
173
|
+
room.total += 1
|
|
174
|
+
if (row.online === true) room.online += 1
|
|
175
|
+
room.devices.push({
|
|
176
|
+
did: String(row.did ?? ''),
|
|
177
|
+
name: String(row.name ?? ''),
|
|
178
|
+
online: row.online === true,
|
|
179
|
+
model: String(row.model ?? ''),
|
|
180
|
+
})
|
|
181
|
+
rooms.set(name, room)
|
|
182
|
+
}
|
|
183
|
+
return [...rooms.values()]
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Read one `键:值` line out of a Miloco event text block.
|
|
188
|
+
* @param {string} text - Raw event text.
|
|
189
|
+
* @param {string[]} labels - Accepted labels, first match wins.
|
|
190
|
+
* @returns {string} The trimmed value, or ''.
|
|
191
|
+
*/
|
|
192
|
+
function readEventField(text, labels) {
|
|
193
|
+
for (const label of labels) {
|
|
194
|
+
const match = new RegExp(`^\\s*${label}\\s*[::]\\s*(.+)$`, 'm').exec(text)
|
|
195
|
+
if (match) return match[1].trim()
|
|
196
|
+
}
|
|
197
|
+
return ''
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Return the first value that carries text.
|
|
202
|
+
* @param {...any} values - Candidate values.
|
|
203
|
+
* @returns {string} The first non-empty trimmed string, or ''.
|
|
204
|
+
*/
|
|
205
|
+
function firstText(...values) {
|
|
206
|
+
for (const value of values) {
|
|
207
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
208
|
+
if (text) return text
|
|
209
|
+
}
|
|
210
|
+
return ''
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Normalise `/api/events` rows for the household overview.
|
|
215
|
+
*
|
|
216
|
+
* The backend unwraps to `{ events: [...] }`, and a perception row carries all
|
|
217
|
+
* of its meaning inside a free-text block (`来源:…`, `检测到:…`,
|
|
218
|
+
* `事件优先级:…`) rather than in structured fields. Older or non-perception
|
|
219
|
+
* rows may still use `type` / `source`, so both shapes are accepted.
|
|
220
|
+
*
|
|
221
|
+
* @param {any} payload - Unwrapped `/api/events` payload (array or `{events}`).
|
|
222
|
+
* @returns {{kind: string, source: string, summary: string, priority: string, timestamp: number}[]} Rows, newest first.
|
|
223
|
+
*/
|
|
224
|
+
export function normalizeEvents(payload) {
|
|
225
|
+
const rows = Array.isArray(payload)
|
|
226
|
+
? payload
|
|
227
|
+
: Array.isArray(payload?.events) ? payload.events : []
|
|
228
|
+
const items = []
|
|
229
|
+
for (const row of rows) {
|
|
230
|
+
if (!row || typeof row !== 'object') continue
|
|
231
|
+
const text = typeof row.text === 'string' ? row.text : ''
|
|
232
|
+
const perception = text.includes('[感知引擎]')
|
|
233
|
+
const rawPriority = firstText(
|
|
234
|
+
row.urgency, row.priority, readEventField(text, ['事件优先级', '优先级']),
|
|
235
|
+
).toLowerCase()
|
|
236
|
+
const rawStamp = row.timestamp ?? row.ts ?? row.created_at ?? row.time
|
|
237
|
+
const fallbackLine = text
|
|
238
|
+
.split('\n')
|
|
239
|
+
.map(line => line.trim())
|
|
240
|
+
.find(line => line && !line.startsWith('[')) ?? ''
|
|
241
|
+
items.push({
|
|
242
|
+
kind: firstText(row.type, row.event_type) || (perception ? '感知事件' : '事件'),
|
|
243
|
+
source: firstText(
|
|
244
|
+
row.source,
|
|
245
|
+
row.device_name,
|
|
246
|
+
row.did,
|
|
247
|
+
readEventField(text, ['来源']),
|
|
248
|
+
Array.isArray(row.device_ids) && row.device_ids.length ? String(row.device_ids[0]) : '',
|
|
249
|
+
) || '—',
|
|
250
|
+
summary: firstText(
|
|
251
|
+
row.summary,
|
|
252
|
+
readEventField(text, ['检测到', '画面描述', '建议']),
|
|
253
|
+
fallbackLine,
|
|
254
|
+
),
|
|
255
|
+
priority: ['high', 'medium', 'low'].includes(rawPriority) ? rawPriority : '',
|
|
256
|
+
timestamp: Number.isFinite(rawStamp)
|
|
257
|
+
? (rawStamp < 1e12 ? rawStamp * 1000 : rawStamp)
|
|
258
|
+
: (typeof rawStamp === 'string' ? Date.parse(rawStamp) : NaN),
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
return items
|
|
262
|
+
.sort((a, b) => (Number.isFinite(b.timestamp) ? b.timestamp : 0) - (Number.isFinite(a.timestamp) ? a.timestamp : 0))
|
|
263
|
+
.slice(0, 10)
|
|
264
|
+
}
|
|
265
|
+
|
|
150
266
|
/**
|
|
151
267
|
* List DSH conversations for the target dropdown.
|
|
152
268
|
*
|
|
@@ -206,7 +322,7 @@ async function listSessions(ctx, state) {
|
|
|
206
322
|
/**
|
|
207
323
|
* Register the settings routes on the host web server.
|
|
208
324
|
*
|
|
209
|
-
* @param {{ctx: any, config: any, client: any, overlay: any, state?: any, deploy?: any, writeConfig?: any, logger?: any}} options - Service options.
|
|
325
|
+
* @param {{ctx: any, config: any, client: any, overlay: any, state?: any, deploy?: any, writeConfig?: any, home?: any, logger?: any}} options - Service options.
|
|
210
326
|
* @returns {() => void} A disposer removing every route.
|
|
211
327
|
*/
|
|
212
328
|
export function registerSettingsApi(options) {
|
|
@@ -365,6 +481,10 @@ export function registerSettingsApi(options) {
|
|
|
365
481
|
push: {
|
|
366
482
|
enabled: config.push.enabled,
|
|
367
483
|
path: config.push.path,
|
|
484
|
+
target: {
|
|
485
|
+
// Effective mode: runtime overlay first, static config second.
|
|
486
|
+
mode: current.push.target.mode || config.push?.target?.mode || 'archive',
|
|
487
|
+
},
|
|
368
488
|
tokenSet: Boolean(effectivePushToken),
|
|
369
489
|
waitForResult: config.push.waitForResult,
|
|
370
490
|
perception: {
|
|
@@ -390,6 +510,172 @@ export function registerSettingsApi(options) {
|
|
|
390
510
|
})
|
|
391
511
|
})
|
|
392
512
|
|
|
513
|
+
route(`${SETTINGS_PREFIX}/home`, async (req, res) => {
|
|
514
|
+
const homeService = options.home
|
|
515
|
+
if (!homeService) {
|
|
516
|
+
sendJson(res, 503, { ok: false, error: '家庭助手工作区不可用' })
|
|
517
|
+
return
|
|
518
|
+
}
|
|
519
|
+
if (req.method === 'GET') {
|
|
520
|
+
// `ensure()` is idempotent: it creates the directory and registers the
|
|
521
|
+
// host workspace once, so the id is present even on the first request.
|
|
522
|
+
const state = await homeService.ensure()
|
|
523
|
+
sendJson(res, 200, { ok: true, ...state, archiveSessionId: ARCHIVE_SESSION_ID })
|
|
524
|
+
return
|
|
525
|
+
}
|
|
526
|
+
if (req.method !== 'POST') {
|
|
527
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
528
|
+
return
|
|
529
|
+
}
|
|
530
|
+
const body = await mutateBody(req, res)
|
|
531
|
+
if (body === null) return
|
|
532
|
+
const raw = typeof body.dir === 'string' ? body.dir.trim() : ''
|
|
533
|
+
const hasEnabled = typeof body.enabled === 'boolean'
|
|
534
|
+
if (!raw && !hasEnabled) {
|
|
535
|
+
sendJson(res, 400, { ok: false, error: '目录不能为空' })
|
|
536
|
+
return
|
|
537
|
+
}
|
|
538
|
+
if (raw) {
|
|
539
|
+
const target = resolveMilocoHomeDir(raw)
|
|
540
|
+
if (!isAbsolute(target)) {
|
|
541
|
+
sendJson(res, 400, { ok: false, error: '目录必须是绝对路径' })
|
|
542
|
+
return
|
|
543
|
+
}
|
|
544
|
+
// Create before writing the overlay: a directory that cannot be created
|
|
545
|
+
// must leave the configured household workspace untouched.
|
|
546
|
+
try {
|
|
547
|
+
await mkdir(target, { recursive: true })
|
|
548
|
+
} catch (error) {
|
|
549
|
+
sendJson(res, 500, { ok: false, error: `创建目录失败:${error instanceof Error ? error.message : error}` })
|
|
550
|
+
return
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const previousPath = homeService.dir
|
|
554
|
+
try {
|
|
555
|
+
if (raw) await homeService.setDir(raw)
|
|
556
|
+
if (hasEnabled) await homeService.setEnabled(body.enabled)
|
|
557
|
+
const state = await homeService.ensure()
|
|
558
|
+
sendJson(res, 200, { ok: true, ...state, previousPath, archiveSessionId: ARCHIVE_SESSION_ID })
|
|
559
|
+
} catch (error) {
|
|
560
|
+
sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
561
|
+
}
|
|
562
|
+
})
|
|
563
|
+
|
|
564
|
+
route(`${SETTINGS_PREFIX}/home/overview`, async (req, res) => {
|
|
565
|
+
if (req.method !== 'GET') {
|
|
566
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
567
|
+
return
|
|
568
|
+
}
|
|
569
|
+
if (!options.home) {
|
|
570
|
+
sendJson(res, 503, { ok: false, error: '家庭助手工作区不可用' })
|
|
571
|
+
return
|
|
572
|
+
}
|
|
573
|
+
// Every backend section fails on its own: one unreachable endpoint must
|
|
574
|
+
// not blank the whole dashboard.
|
|
575
|
+
const homeState = await options.home.ensure()
|
|
576
|
+
const short = AbortSignal.timeout(8_000)
|
|
577
|
+
const attempt = promise => promise
|
|
578
|
+
.then(data => ({ ok: true, data }))
|
|
579
|
+
.catch(error => ({ ok: false, error: error instanceof Error ? error.message : String(error) }))
|
|
580
|
+
const [status, version, devices, events, user, engine, cameras, rules, tasks, usage] = await Promise.all([
|
|
581
|
+
attempt(client.get('/api/admin/status', { signal: short })),
|
|
582
|
+
attempt(client.get('/api/admin/version', { signal: short })),
|
|
583
|
+
attempt(client.get('/api/miot/device_list', { signal: short })),
|
|
584
|
+
attempt(client.get('/api/events', { query: { limit: 10 }, signal: short })),
|
|
585
|
+
attempt(client.get('/api/miot/user_info', { signal: short })),
|
|
586
|
+
attempt(client.get('/api/perception/engine/status', { signal: short })),
|
|
587
|
+
attempt(client.get('/api/miot/camera_list', { signal: short })),
|
|
588
|
+
attempt(client.get('/api/rules', { signal: short })),
|
|
589
|
+
attempt(client.get('/api/tasks', { signal: short })),
|
|
590
|
+
attempt(client.get('/api/admin/token-usage', { query: { limit: 500 }, signal: short })),
|
|
591
|
+
])
|
|
592
|
+
const rows = devices.ok && Array.isArray(devices.data) ? devices.data : []
|
|
593
|
+
const rooms = groupDevices(rows)
|
|
594
|
+
const online = rows.filter(device => device && device.online === true).length
|
|
595
|
+
// Token usage is a sum over the recorded events, not a single counter.
|
|
596
|
+
const usageRows = usage.ok && Array.isArray(usage.data?.events) ? usage.data.events : []
|
|
597
|
+
const sumField = field => usageRows.reduce(
|
|
598
|
+
(sum, row) => sum + (Number(row?.[field] ?? 0) || 0),
|
|
599
|
+
0,
|
|
600
|
+
)
|
|
601
|
+
const tokenInput = sumField('input_tokens')
|
|
602
|
+
const tokenOutput = sumField('output_tokens')
|
|
603
|
+
const tokenTotal = tokenInput + tokenOutput
|
|
604
|
+
+ sumField('cache_tokens')
|
|
605
|
+
+ sumField('video_tokens')
|
|
606
|
+
+ sumField('audio_tokens')
|
|
607
|
+
const current = await overlay.current()
|
|
608
|
+
let archiveExists = false
|
|
609
|
+
try {
|
|
610
|
+
const resolved = await ctx.sessionController.resolveAgent(ARCHIVE_SESSION_ID)
|
|
611
|
+
archiveExists = Boolean(resolved && typeof resolved === 'object' && resolved.agent)
|
|
612
|
+
} catch { /* treat as absent */ }
|
|
613
|
+
sendJson(res, 200, {
|
|
614
|
+
ok: true,
|
|
615
|
+
home: {
|
|
616
|
+
...homeState,
|
|
617
|
+
archive: { sessionId: ARCHIVE_SESSION_ID, exists: archiveExists },
|
|
618
|
+
},
|
|
619
|
+
status: {
|
|
620
|
+
ok: status.ok,
|
|
621
|
+
reachable: status.ok,
|
|
622
|
+
account: user.ok && user.data?.nickname
|
|
623
|
+
? { nickname: user.data.nickname, uid: user.data.uid ?? null }
|
|
624
|
+
: null,
|
|
625
|
+
accountBound: Boolean(user.ok && user.data?.uid),
|
|
626
|
+
perceptionRunning: Boolean(engine.ok && engine.data?.running),
|
|
627
|
+
...(status.ok ? {} : { error: status.error }),
|
|
628
|
+
},
|
|
629
|
+
version: {
|
|
630
|
+
ok: version.ok,
|
|
631
|
+
current: version.ok ? String(version.data?.version ?? '') : '',
|
|
632
|
+
latest: lastUpgradeCheck?.latest ?? '',
|
|
633
|
+
hasUpdate: Boolean(lastUpgradeCheck?.has_update),
|
|
634
|
+
...(version.ok ? {} : { error: version.error }),
|
|
635
|
+
},
|
|
636
|
+
devices: {
|
|
637
|
+
ok: devices.ok,
|
|
638
|
+
total: rows.length,
|
|
639
|
+
online,
|
|
640
|
+
rooms,
|
|
641
|
+
...(devices.ok ? {} : { error: devices.error }),
|
|
642
|
+
},
|
|
643
|
+
overview: {
|
|
644
|
+
account: user.ok && user.data?.nickname
|
|
645
|
+
? { nickname: user.data.nickname, uid: user.data.uid ?? null }
|
|
646
|
+
: null,
|
|
647
|
+
accountBound: Boolean(user.ok && user.data?.uid),
|
|
648
|
+
deviceCount: devices.ok ? rows.length : null,
|
|
649
|
+
cameraCount: cameras.ok && Array.isArray(cameras.data) ? cameras.data.length : null,
|
|
650
|
+
ruleCount: rules.ok && Array.isArray(rules.data) ? rules.data.length : null,
|
|
651
|
+
taskCount: tasks.ok && Array.isArray(tasks.data) ? tasks.data.length : null,
|
|
652
|
+
perceptionRunning: Boolean(engine.ok && engine.data?.running),
|
|
653
|
+
perceptionSources: engine.ok && Array.isArray(engine.data?.active_sources)
|
|
654
|
+
? engine.data.active_sources.length
|
|
655
|
+
: null,
|
|
656
|
+
tokenEvents: usage.ok
|
|
657
|
+
? (Number.isFinite(usage.data?.total) ? usage.data.total : usageRows.length)
|
|
658
|
+
: null,
|
|
659
|
+
tokenInput: tokenInput || null,
|
|
660
|
+
tokenOutput: tokenOutput || null,
|
|
661
|
+
tokenTotal: tokenTotal || null,
|
|
662
|
+
},
|
|
663
|
+
events: {
|
|
664
|
+
ok: events.ok,
|
|
665
|
+
items: events.ok ? normalizeEvents(events.data) : [],
|
|
666
|
+
...(events.ok ? {} : { error: events.error }),
|
|
667
|
+
},
|
|
668
|
+
pushes: {
|
|
669
|
+
ok: true,
|
|
670
|
+
items: options.state ? await readPushLog(options.state) : [],
|
|
671
|
+
},
|
|
672
|
+
push: {
|
|
673
|
+
path: String(config.push?.path ?? '/miloco/webhook'),
|
|
674
|
+
tokenSet: Boolean(String(current.push.token ?? '') || String(config.push?.token ?? '')),
|
|
675
|
+
},
|
|
676
|
+
})
|
|
677
|
+
})
|
|
678
|
+
|
|
393
679
|
route(`${SETTINGS_PREFIX}/sessions`, async (req, res) => {
|
|
394
680
|
if (req.method !== 'GET') {
|
|
395
681
|
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
@@ -423,6 +709,9 @@ export function registerSettingsApi(options) {
|
|
|
423
709
|
const perceptionLevel = typeof body.perceptionLevel === 'string'
|
|
424
710
|
? body.perceptionLevel.trim()
|
|
425
711
|
: current.push.perception.minLevel
|
|
712
|
+
const mode = body.mode === undefined
|
|
713
|
+
? (current.push.target.mode || '')
|
|
714
|
+
: normalizePushTargetMode(body.mode)
|
|
426
715
|
|
|
427
716
|
if (Boolean(provider) !== Boolean(model)) {
|
|
428
717
|
sendJson(res, 400, { ok: false, error: 'provider 与 model 必须同时选择,或都留空(跟随对话)' })
|
|
@@ -435,12 +724,16 @@ export function registerSettingsApi(options) {
|
|
|
435
724
|
})
|
|
436
725
|
return
|
|
437
726
|
}
|
|
727
|
+
if (body.mode !== undefined && !mode) {
|
|
728
|
+
sendJson(res, 400, { ok: false, error: 'mode 只能是 archive / session' })
|
|
729
|
+
return
|
|
730
|
+
}
|
|
438
731
|
|
|
439
732
|
await overlay.write({
|
|
440
733
|
connection: current.connection,
|
|
441
734
|
push: {
|
|
442
735
|
token: current.push.token,
|
|
443
|
-
target: { sessionId },
|
|
736
|
+
target: { mode, sessionId },
|
|
444
737
|
model: { provider, model, reasoningEffort },
|
|
445
738
|
perception: { minLevel: perceptionLevel },
|
|
446
739
|
},
|
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))
|
package/lib/tools.js
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
22
|
import { MilocoError } from './miloco-client.js'
|
|
23
|
+
import { normalizePushTargetMode } from './overlay.js'
|
|
23
24
|
import { PERCEPTION_LEVELS } from './perception.js'
|
|
24
25
|
import { noteSession } from './state.js'
|
|
25
26
|
|
|
@@ -1369,10 +1370,16 @@ export function createMilocoTools(options) {
|
|
|
1369
1370
|
|
|
1370
1371
|
writeTools.push(defineMilocoTool({
|
|
1371
1372
|
name: 'miloco_push_target_set',
|
|
1372
|
-
description: '修改 Miloco 主动推送的投递目标。
|
|
1373
|
+
description: '修改 Miloco 主动推送的投递目标。mode=archive(默认)投到专用归档会话,'
|
|
1374
|
+
+ '会忽略 sessionId;mode=session 投到指定会话,sessionId 留空 = 上一次触发 miloco 的会话。'
|
|
1373
1375
|
+ 'provider+model 留空 = 跟随那个对话自己选的模型;perceptionLevel 控制感知事件的最低优先级。',
|
|
1374
1376
|
parameters: {
|
|
1375
|
-
|
|
1377
|
+
mode: {
|
|
1378
|
+
type: 'string',
|
|
1379
|
+
enum: ['archive', 'session'],
|
|
1380
|
+
description: '投递方式:archive = 归档会话(默认);session = 指定会话。省略时按 sessionId 推断',
|
|
1381
|
+
},
|
|
1382
|
+
sessionId: { type: 'string', description: '目标对话的会话 id;仅 session 模式生效,留空 = 上一次触发 miloco 的会话' },
|
|
1376
1383
|
provider: { type: 'string', description: '模型供应商 id;留空 = 跟随该对话自己选的模型' },
|
|
1377
1384
|
model: { type: 'string', description: '模型 id;留空 = 跟随该对话自己选的模型' },
|
|
1378
1385
|
reasoningEffort: { type: 'string', description: '推理强度(可选)' },
|
|
@@ -1384,6 +1391,19 @@ export function createMilocoTools(options) {
|
|
|
1384
1391
|
async run(args) {
|
|
1385
1392
|
if (!options.overlay) throw new Error('插件未启用覆盖文件,无法修改推送目标')
|
|
1386
1393
|
const current = await options.overlay.current()
|
|
1394
|
+
const sessionArg = typeof args.sessionId === 'string' ? args.sessionId.trim() : ''
|
|
1395
|
+
let mode
|
|
1396
|
+
if (typeof args.mode === 'string') {
|
|
1397
|
+
mode = normalizePushTargetMode(args.mode)
|
|
1398
|
+
if (!mode) throw new Error('mode 只能是 archive / session')
|
|
1399
|
+
} else if (sessionArg) {
|
|
1400
|
+
mode = 'session'
|
|
1401
|
+
} else {
|
|
1402
|
+
mode = current.push.target.mode || options.pushMode || 'archive'
|
|
1403
|
+
}
|
|
1404
|
+
if (mode === 'archive' && sessionArg) {
|
|
1405
|
+
throw new Error('archive 模式会忽略 sessionId;要指定会话请同时传 mode=session')
|
|
1406
|
+
}
|
|
1387
1407
|
const provider = typeof args.provider === 'string' ? args.provider.trim() : current.push.model.provider
|
|
1388
1408
|
const model = typeof args.model === 'string' ? args.model.trim() : current.push.model.model
|
|
1389
1409
|
if (Boolean(provider) !== Boolean(model)) {
|
|
@@ -1400,9 +1420,8 @@ export function createMilocoTools(options) {
|
|
|
1400
1420
|
push: {
|
|
1401
1421
|
token: current.push.token,
|
|
1402
1422
|
target: {
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
: current.push.target.sessionId,
|
|
1423
|
+
mode,
|
|
1424
|
+
sessionId: sessionArg || current.push.target.sessionId,
|
|
1406
1425
|
},
|
|
1407
1426
|
model: {
|
|
1408
1427
|
provider,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-miloco-bridge",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "Unofficial DSH bridge for Xiaomi Miloco: an isolated Agent preset for Miloco tools, native tools/skills, Web settings, perception-priority filtering, and Miloco -> DSH push.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -30,7 +30,12 @@
|
|
|
30
30
|
"lib",
|
|
31
31
|
"skills",
|
|
32
32
|
"adapter",
|
|
33
|
-
"docs",
|
|
33
|
+
"docs/ARCHITECTURE.md",
|
|
34
|
+
"docs/INSTALL.md",
|
|
35
|
+
"docs/SKILL-REWRITES.md",
|
|
36
|
+
"docs/TOOLS.md",
|
|
37
|
+
"docs/VERIFICATION.md",
|
|
38
|
+
"docs/images",
|
|
34
39
|
"scripts",
|
|
35
40
|
"install.sh",
|
|
36
41
|
"cordis.patch.yml",
|