dsh-miloco-bridge 0.1.1 → 0.1.3
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 +2 -2
- package/cordis.patch.yml +78 -2
- package/docs/ARCHITECTURE.md +11 -4
- package/docs/INSTALL.md +21 -10
- package/docs/TOOLS.md +1 -1
- package/docs/VERIFICATION.md +2 -2
- package/lib/client.js +65 -12
- package/lib/deploy.js +236 -38
- package/lib/github-release.js +162 -0
- package/lib/index.js +44 -2
- package/lib/settings-api.js +85 -1
- package/lib/tools-entry.js +40 -6
- package/lib/tools.js +62 -4
- package/package.json +1 -1
- package/skills/miloco-devices/SKILL.md +3 -2
package/lib/settings-api.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
|
|
23
23
|
import { access } from 'node:fs/promises'
|
|
24
24
|
import { dirname, join } from 'node:path'
|
|
25
|
+
import { fetchLatestRelease, inferDeployKind, isNewerRelease, normalizeReleaseVersion } from './github-release.js'
|
|
25
26
|
import { MilocoError, readMilocoConfig } from './miloco-client.js'
|
|
26
27
|
import { normalizePerceptionLevel, PERCEPTION_LEVELS } from './perception.js'
|
|
27
28
|
import { AGENT_MODES, describeMode, readSessions } from './state.js'
|
|
@@ -212,6 +213,8 @@ export function registerSettingsApi(options) {
|
|
|
212
213
|
const { ctx, config, client, overlay } = options
|
|
213
214
|
const log = options.logger ?? ctx.logger
|
|
214
215
|
const disposers = []
|
|
216
|
+
/** @type {null | {at: number, source: string, has_update: boolean, current: string, latest: string}} */
|
|
217
|
+
let lastUpgradeCheck = null
|
|
215
218
|
|
|
216
219
|
/**
|
|
217
220
|
* Register one exact route.
|
|
@@ -485,7 +488,7 @@ export function registerSettingsApi(options) {
|
|
|
485
488
|
: (config.deploy?.sourceDir || '')
|
|
486
489
|
|
|
487
490
|
try {
|
|
488
|
-
const [version,
|
|
491
|
+
const [version, backendUpgrade, upgradeStatus] = await Promise.all([
|
|
489
492
|
client.get('/api/admin/version', { signal: AbortSignal.timeout(8_000) }),
|
|
490
493
|
client.get('/api/admin/upgrade/check', {
|
|
491
494
|
query: { force: force ? 'true' : 'false' },
|
|
@@ -493,6 +496,55 @@ export function registerSettingsApi(options) {
|
|
|
493
496
|
}).catch(() => null),
|
|
494
497
|
client.get('/api/admin/upgrade/status', { signal: AbortSignal.timeout(8_000) }).catch(() => null),
|
|
495
498
|
])
|
|
499
|
+
let upgrade = backendUpgrade
|
|
500
|
+
if (!upgrade || upgrade.reachable === false) {
|
|
501
|
+
const current = String(upgrade?.current || version?.version || '')
|
|
502
|
+
const deployKind = upgrade?.deploy_kind || inferDeployKind(current)
|
|
503
|
+
try {
|
|
504
|
+
const latest = await fetchLatestRelease({
|
|
505
|
+
repo: config.deploy?.repo,
|
|
506
|
+
apiBase: config.deploy?.githubApi,
|
|
507
|
+
mirrors: config.deploy?.githubMirrors,
|
|
508
|
+
timeoutMs: 6_000,
|
|
509
|
+
})
|
|
510
|
+
upgrade = {
|
|
511
|
+
current,
|
|
512
|
+
latest: normalizeReleaseVersion(latest.tag),
|
|
513
|
+
has_update: Boolean(current) && deployKind === 'release'
|
|
514
|
+
&& isNewerRelease(current, latest.tag),
|
|
515
|
+
deploy_kind: deployKind,
|
|
516
|
+
release_url: latest.release_url || latest.html_url,
|
|
517
|
+
reachable: true,
|
|
518
|
+
source: latest.source,
|
|
519
|
+
mirror: latest.mirror || null,
|
|
520
|
+
checked_at: Math.floor(Date.now() / 1000),
|
|
521
|
+
}
|
|
522
|
+
} catch (fallbackError) {
|
|
523
|
+
const message = fallbackError instanceof Error ? fallbackError.message : String(fallbackError)
|
|
524
|
+
upgrade = {
|
|
525
|
+
...(upgrade ?? {}),
|
|
526
|
+
current,
|
|
527
|
+
latest: null,
|
|
528
|
+
has_update: false,
|
|
529
|
+
deploy_kind: deployKind,
|
|
530
|
+
release_url: null,
|
|
531
|
+
reachable: false,
|
|
532
|
+
source: 'none',
|
|
533
|
+
error: message,
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
} else {
|
|
537
|
+
upgrade = { ...upgrade, source: upgrade.source || 'backend' }
|
|
538
|
+
}
|
|
539
|
+
if (upgrade) {
|
|
540
|
+
lastUpgradeCheck = {
|
|
541
|
+
at: Date.now(),
|
|
542
|
+
source: upgrade.source || 'backend',
|
|
543
|
+
has_update: Boolean(upgrade.has_update),
|
|
544
|
+
current: String(upgrade.current || ''),
|
|
545
|
+
latest: String(upgrade.latest || ''),
|
|
546
|
+
}
|
|
547
|
+
}
|
|
496
548
|
sendJson(res, 200, {
|
|
497
549
|
ok: true,
|
|
498
550
|
reachable: true,
|
|
@@ -521,6 +573,24 @@ export function registerSettingsApi(options) {
|
|
|
521
573
|
}
|
|
522
574
|
const body = await mutateBody(req, res)
|
|
523
575
|
if (body === null) return
|
|
576
|
+
const recent = lastUpgradeCheck && Date.now() - lastUpgradeCheck.at < 10 * 60_000
|
|
577
|
+
const pluginUpgrade = recent
|
|
578
|
+
&& lastUpgradeCheck.source !== 'backend'
|
|
579
|
+
&& lastUpgradeCheck.has_update
|
|
580
|
+
&& typeof options.deploy?.startUpgrade === 'function'
|
|
581
|
+
if (pluginUpgrade) {
|
|
582
|
+
const proto = String(req.headers['x-forwarded-proto'] || 'http').split(',')[0].trim()
|
|
583
|
+
const origin = typeof req.headers.origin === 'string' && req.headers.origin
|
|
584
|
+
? req.headers.origin
|
|
585
|
+
: `${proto}://${req.headers.host ?? '127.0.0.1:3080'}`
|
|
586
|
+
const outcome = await options.deploy.startUpgrade({ origin })
|
|
587
|
+
if (!outcome.started) {
|
|
588
|
+
sendJson(res, 409, { ok: false, error: outcome.reason || '升级未启动', ...outcome })
|
|
589
|
+
return
|
|
590
|
+
}
|
|
591
|
+
sendJson(res, 200, { ok: true, source: 'plugin', ...outcome })
|
|
592
|
+
return
|
|
593
|
+
}
|
|
524
594
|
// Upstream only allows /upgrade/run for release deployments. It performs
|
|
525
595
|
// its own has_update check; surface its 400 reason verbatim.
|
|
526
596
|
try {
|
|
@@ -541,6 +611,20 @@ export function registerSettingsApi(options) {
|
|
|
541
611
|
sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
542
612
|
return
|
|
543
613
|
}
|
|
614
|
+
const pluginState = options.deploy?.upgradeState?.()
|
|
615
|
+
if (pluginState && pluginState.step !== 'idle') {
|
|
616
|
+
const phaseMap = {
|
|
617
|
+
'downloading-installer': 'downloading',
|
|
618
|
+
'starting-service': 'restarting',
|
|
619
|
+
wiring: 'installing',
|
|
620
|
+
}
|
|
621
|
+
sendJson(res, 200, {
|
|
622
|
+
ok: true,
|
|
623
|
+
source: 'plugin',
|
|
624
|
+
status: { ...pluginState, phase: phaseMap[pluginState.step] || pluginState.step },
|
|
625
|
+
})
|
|
626
|
+
return
|
|
627
|
+
}
|
|
544
628
|
try {
|
|
545
629
|
const status = await client.get('/api/admin/upgrade/status', {
|
|
546
630
|
signal: AbortSignal.timeout(8_000),
|
package/lib/tools-entry.js
CHANGED
|
@@ -83,6 +83,20 @@ export function normalizeConfig(raw) {
|
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Whether the context can still own new effects.
|
|
88
|
+
*
|
|
89
|
+
* Cordis clears `uid` on disposal and moves `state` to 5 on unload. A plugin
|
|
90
|
+
* whose async work outlives its scope must stop before calling `effect`.
|
|
91
|
+
*
|
|
92
|
+
* @param {any} ctx - Cordis context.
|
|
93
|
+
* @returns {boolean} True while the fiber is loadable.
|
|
94
|
+
*/
|
|
95
|
+
function fiberActive(ctx) {
|
|
96
|
+
const fiber = ctx?.fiber
|
|
97
|
+
return fiber === undefined || (fiber.uid !== null && fiber.state !== 5)
|
|
98
|
+
}
|
|
99
|
+
|
|
86
100
|
/**
|
|
87
101
|
* Read the session id from a tool execution.
|
|
88
102
|
* @param {any} exec - Tool execution context.
|
|
@@ -118,6 +132,9 @@ export async function apply(ctx, rawConfig) {
|
|
|
118
132
|
// Runtime mode: state file first (written by the Web tab), static config as
|
|
119
133
|
// fallback. The two halves live in different scopes, hence the shared file.
|
|
120
134
|
const persisted = await state.read().catch(() => ({}))
|
|
135
|
+
// The preset can be torn down while that read is pending (for example when a
|
|
136
|
+
// sibling row fails to load). Registering tools on a disposed context throws.
|
|
137
|
+
if (!fiberActive(ctx)) return
|
|
121
138
|
const persistedMode = typeof persisted.mode === 'string'
|
|
122
139
|
? persisted.mode
|
|
123
140
|
: (config.readOnly === false ? 'full' : 'readonly')
|
|
@@ -182,15 +199,32 @@ export async function apply(ctx, rawConfig) {
|
|
|
182
199
|
// ------------------------------------------------------------------ 技能
|
|
183
200
|
|
|
184
201
|
ctx.inject(['skills'], (host) => {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
202
|
+
/** @type {(() => void)[]} */
|
|
203
|
+
const skillDisposers = []
|
|
204
|
+
// Claim the cleanup effect before the async reads start: the scope may be
|
|
205
|
+
// disposed while a read is pending, and an effect registered afterwards
|
|
206
|
+
// throws INACTIVE_EFFECT inside a detached promise.
|
|
207
|
+
host.effect(() => () => {
|
|
208
|
+
for (const dispose of skillDisposers.splice(0)) {
|
|
209
|
+
try {
|
|
210
|
+
dispose()
|
|
211
|
+
} catch { /* 卸载期忽略 */ }
|
|
212
|
+
}
|
|
213
|
+
}, 'dsh-miloco-bridge: skills')
|
|
214
|
+
|
|
215
|
+
void registerSkills(host, host.logger).then((registered) => {
|
|
216
|
+
if (!fiberActive(host)) {
|
|
217
|
+
for (const dispose of registered) {
|
|
188
218
|
try {
|
|
189
219
|
dispose()
|
|
190
|
-
} catch { /*
|
|
220
|
+
} catch { /* 作用域已销毁 */ }
|
|
191
221
|
}
|
|
192
|
-
|
|
193
|
-
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
skillDisposers.push(...registered)
|
|
225
|
+
host.logger?.info?.(`dsh-miloco-bridge: 已注册 ${registered.length} 个技能`)
|
|
226
|
+
}).catch((error) => {
|
|
227
|
+
host.logger?.warn?.(`dsh-miloco-bridge: 注册技能失败:${error instanceof Error ? error.message : error}`)
|
|
194
228
|
})
|
|
195
229
|
})
|
|
196
230
|
|
package/lib/tools.js
CHANGED
|
@@ -23,6 +23,16 @@ import { MilocoError } from './miloco-client.js'
|
|
|
23
23
|
import { PERCEPTION_LEVELS } from './perception.js'
|
|
24
24
|
import { noteSession } from './state.js'
|
|
25
25
|
|
|
26
|
+
/** Extra device fields that callers may request explicitly. */
|
|
27
|
+
const DEVICE_LIST_EXTRA_FIELDS = [
|
|
28
|
+
'icon',
|
|
29
|
+
'local_ip',
|
|
30
|
+
'home_name',
|
|
31
|
+
'order_time',
|
|
32
|
+
'lan_online',
|
|
33
|
+
'sub_devices',
|
|
34
|
+
]
|
|
35
|
+
|
|
26
36
|
/**
|
|
27
37
|
* Serialise a canonical tool value as readable JSON text.
|
|
28
38
|
* @param {unknown} value - Value to serialise.
|
|
@@ -134,15 +144,63 @@ export function createMilocoTools(options) {
|
|
|
134
144
|
|
|
135
145
|
tools.push(defineMilocoTool({
|
|
136
146
|
name: 'miloco_device_list',
|
|
137
|
-
description: '
|
|
147
|
+
description: '列出米家设备。默认返回 did、名称、在线状态、房间、型号和 home_id;'
|
|
148
|
+
+ '可用 include 显式取回 icon/local_ip 等额外字段。默认最多 500 台,超过时用 offset 翻页。',
|
|
138
149
|
parameters: {
|
|
139
|
-
room: { type: 'string', description: '按房间名过滤(本地匹配 room_name
|
|
150
|
+
room: { type: 'string', description: '按房间名过滤(本地匹配 room_name)' },
|
|
151
|
+
name: { type: 'string', description: '按设备名过滤(本地子串匹配,忽略大小写)' },
|
|
152
|
+
online_only: { type: 'boolean', description: '只返回在线设备' },
|
|
153
|
+
limit: {
|
|
154
|
+
type: 'integer',
|
|
155
|
+
minimum: 1,
|
|
156
|
+
maximum: 500,
|
|
157
|
+
description: '最多返回多少台,默认 500',
|
|
158
|
+
},
|
|
159
|
+
offset: { type: 'integer', minimum: 0, description: '从第几台开始,默认 0' },
|
|
160
|
+
include: {
|
|
161
|
+
type: 'array',
|
|
162
|
+
items: { type: 'string', enum: DEVICE_LIST_EXTRA_FIELDS },
|
|
163
|
+
description: '额外字段:icon / local_ip / home_name / order_time / lan_online / sub_devices',
|
|
164
|
+
},
|
|
140
165
|
},
|
|
141
166
|
async run(args, exec) {
|
|
142
167
|
const devices = await call('GET', '/api/miot/device_list', { signal: exec?.signal })
|
|
168
|
+
const list = Array.isArray(devices) ? devices : []
|
|
143
169
|
const room = typeof args.room === 'string' ? args.room.trim().toLowerCase() : ''
|
|
144
|
-
|
|
145
|
-
|
|
170
|
+
const name = typeof args.name === 'string' ? args.name.trim().toLowerCase() : ''
|
|
171
|
+
const onlineOnly = args.online_only === true
|
|
172
|
+
const includes = Array.isArray(args.include)
|
|
173
|
+
? [...new Set(args.include.filter(field => typeof field === 'string'))]
|
|
174
|
+
: []
|
|
175
|
+
for (const field of includes) {
|
|
176
|
+
if (!DEVICE_LIST_EXTRA_FIELDS.includes(field)) throw new Error(`include 不支持字段:${field}`)
|
|
177
|
+
}
|
|
178
|
+
const limit = args.limit === undefined ? 500 : Number(args.limit)
|
|
179
|
+
const offset = args.offset === undefined ? 0 : Number(args.offset)
|
|
180
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 500) throw new Error('limit 必须是 1~500 的整数')
|
|
181
|
+
if (!Number.isInteger(offset) || offset < 0) throw new Error('offset 必须是非负整数')
|
|
182
|
+
const filtered = list.filter((device) => {
|
|
183
|
+
if (!device || typeof device !== 'object') return false
|
|
184
|
+
if (onlineOnly && device.online !== true) return false
|
|
185
|
+
if (room && !String(device.room_name ?? device.room ?? '').toLowerCase().includes(room)) return false
|
|
186
|
+
if (name && !String(device.name ?? '').toLowerCase().includes(name)) return false
|
|
187
|
+
return true
|
|
188
|
+
})
|
|
189
|
+
const page = filtered.slice(offset, offset + limit).map((device) => {
|
|
190
|
+
const row = {
|
|
191
|
+
did: device.did ?? '',
|
|
192
|
+
name: device.name ?? '',
|
|
193
|
+
online: device.online === true,
|
|
194
|
+
room_name: device.room_name ?? '',
|
|
195
|
+
model: device.model ?? '',
|
|
196
|
+
home_id: device.home_id ?? '',
|
|
197
|
+
}
|
|
198
|
+
for (const field of includes) {
|
|
199
|
+
if (Object.prototype.hasOwnProperty.call(device, field)) row[field] = device[field]
|
|
200
|
+
}
|
|
201
|
+
return row
|
|
202
|
+
})
|
|
203
|
+
return { total: filtered.length, returned: page.length, offset, limit, devices: page }
|
|
146
204
|
},
|
|
147
205
|
}))
|
|
148
206
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-miloco-bridge",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
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",
|
|
@@ -12,7 +12,7 @@ whenToUse: 用户说“开/关/调/查某台设备”“客厅多少度”“执
|
|
|
12
12
|
|
|
13
13
|
| 目的 | 工具 |
|
|
14
14
|
|---|---|
|
|
15
|
-
| 找设备 did | `miloco_device_list(room?)` |
|
|
15
|
+
| 找设备 did | `miloco_device_list(room?, online_only?, name?, include?)` |
|
|
16
16
|
| 读 SPEC / iid | `miloco_device_spec(did)` |
|
|
17
17
|
| 读当前属性 | `miloco_device_status(did, iid?)` |
|
|
18
18
|
| 控制设备(写) | `miloco_device_control(...)` |
|
|
@@ -21,7 +21,7 @@ whenToUse: 用户说“开/关/调/查某台设备”“客厅多少度”“执
|
|
|
21
21
|
|
|
22
22
|
## 查询流程
|
|
23
23
|
|
|
24
|
-
1. `miloco_device_list` 拿 did
|
|
24
|
+
1. `miloco_device_list` 拿 did(结果在 `devices` 数组里)。名字相同或跨房间时用 `name` / `room` / `online_only` 先缩小范围,不猜。
|
|
25
25
|
2. `miloco_device_status` 读状态。传 `iid` 读单项,不传读全部。
|
|
26
26
|
3. 回答里带上设备名、房间、关键数值和时间(若后端返回)。
|
|
27
27
|
|
|
@@ -42,6 +42,7 @@ whenToUse: 用户说“开/关/调/查某台设备”“客厅多少度”“执
|
|
|
42
42
|
- 门锁、燃气阀、摄像头开关、厨房电器等有物理风险的操作,先说明将要做什么并取得确认。
|
|
43
43
|
- 不要把“感知事件里的 did”当成控制目标:事件 did 通常是摄像头/传感器。
|
|
44
44
|
- 不确定设备是否存在时重新 `miloco_device_list` 或 `miloco_home_info(refresh=true)`,禁止编造 did。
|
|
45
|
+
- 需要 `icon`、`local_ip` 等默认裁剪字段时,用 `include=[...]` 显式请求,不要为了一个字段重拉全量原始对象。
|
|
45
46
|
|
|
46
47
|
## 场景
|
|
47
48
|
|