pygmalion 0.1.15 → 0.2.1
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/LICENSE +21 -0
- package/README.md +141 -70
- package/THIRD_PARTY.md +9 -0
- package/docs/ARCHITECTURE.md +66 -108
- package/docs/DEPLOY.md +33 -137
- package/docs/DEVELOPMENT.md +67 -0
- package/docs/DEVICE.md +56 -47
- package/docs/EXTENSIONS.md +176 -0
- package/docs/PRESET.md +21 -63
- package/docs/UPGRADE-0.2.md +52 -0
- package/package.json +52 -33
- package/preset/pygmalion-director/cordis.patch.yml +234 -0
- package/preset/pygmalion-director/pygmalion-tools.js +43 -41
- package/scripts/start-local-test.mjs +45 -45
- package/skills/pygmalion-life-scripts/SKILL.md +12 -0
- package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
- package/skills/pygmalion-memory-archive/SKILL.md +24 -0
- package/skills/pygmalion-toy-control/SKILL.md +16 -0
- package/src/agent-life.js +608 -606
- package/src/archive-tools.js +9 -0
- package/src/bot-factory.js +129 -311
- package/src/bots.js +264 -275
- package/src/channel-qq.js +262 -0
- package/src/config.js +69 -68
- package/src/delivery-receipt.js +36 -0
- package/src/delivery-scope.js +20 -0
- package/src/devices/manager.mjs +80 -570
- package/src/devices/monsterparty-controller.mjs +393 -0
- package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -71
- package/src/devices/monsterparty.mjs +294 -294
- package/src/devices/pb.mjs +110 -110
- package/src/devices/registry.mjs +19 -0
- package/src/devices/script-helper.mjs +45 -0
- package/src/devices/scripts.mjs +109 -0
- package/src/devices/service.mjs +254 -0
- package/src/director-messages.js +35 -0
- package/src/dsh-runtime.js +17 -0
- package/src/extension-config.js +20 -0
- package/src/extensions.js +118 -0
- package/src/heartbeat.js +118 -97
- package/src/http-api.js +519 -509
- package/src/inbound.js +36 -207
- package/src/index.js +109 -37
- package/src/llm-provider.js +214 -171
- package/src/meme-worker.js +35 -39
- package/src/memebox.js +1 -1
- package/src/memory-recall.js +55 -0
- package/src/memory-write.js +136 -133
- package/src/peer-identity.js +26 -0
- package/src/persona.js +132 -69
- package/src/role-agent.js +155 -0
- package/src/role-runtime.js +65 -0
- package/src/roleplay-config.js +37 -0
- package/src/roleplay-format.js +37 -0
- package/src/roleplay-generation.js +46 -0
- package/src/roleplay-materials.js +113 -0
- package/src/roleplay-output.js +19 -0
- package/src/roleplay-parallel.js +239 -0
- package/src/roleplay-session.js +134 -0
- package/src/roleplay-worker.js +10 -0
- package/src/session-log.js +180 -172
- package/src/setup-agent.js +92 -100
- package/src/skills.js +97 -0
- package/src/slash-commands.js +155 -142
- package/src/speech-input.js +20 -0
- package/src/threads.js +2 -1
- package/src/tools.js +226 -254
- package/src/voice-defaults.js +13 -0
- package/src/voice-mimo.js +139 -125
- package/src/voice.js +200 -0
- package/src/wakeup.js +85 -66
- package/src/web-public/app.js +542 -382
- package/src/web-public/index.html +161 -158
- package/src/web-public/layout.css +7 -7
- package/src/web-public/style.css +12 -8
- package/src/web-server.js +161 -102
- package/src/worker-tools.js +18 -0
- package/templates/sample-life.mjs +59 -59
- package/templates/sample-toy.mjs +33 -33
- package/preset/pygmalion-director/agent.cordis.yml +0 -262
- package/preset/pygmalion-director/preset.yml +0 -3
- package/src/message-review.js +0 -276
package/src/devices/pb.mjs
CHANGED
|
@@ -1,110 +1,110 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MonsterParty WS protobuf 线格式编解码(移植自 toy-protocol/,协议已实测验证)。
|
|
3
|
-
* 仅依赖 node:buffer;encode 用于构造帧,decode 用于解析服务端回包。
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
/** 读 varint(用于解码)。返回 { value: bigint, next: 下一字节下标 }。 */
|
|
7
|
-
export function readVarint(buf, i) {
|
|
8
|
-
let result = 0n, shift = 0n;
|
|
9
|
-
while (i < buf.length) {
|
|
10
|
-
const b = buf[i++];
|
|
11
|
-
result |= BigInt(b & 0x7f) << shift;
|
|
12
|
-
if (!(b & 0x80)) return { value: result, next: i };
|
|
13
|
-
shift += 7n;
|
|
14
|
-
if (shift > 63n) throw new Error('varint too long');
|
|
15
|
-
}
|
|
16
|
-
throw new Error('truncated varint');
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/** 写 varint(用于编码)。返回写入后的下标。 */
|
|
20
|
-
export function writeVarint(buf, offset, value) {
|
|
21
|
-
let n = BigInt(value), i = offset;
|
|
22
|
-
for (;;) {
|
|
23
|
-
const byte = Number(n & 0x7fn);
|
|
24
|
-
n >>= 7n;
|
|
25
|
-
if (n === 0n) { buf[i++] = byte; break; }
|
|
26
|
-
buf[i++] = byte | 0x80;
|
|
27
|
-
}
|
|
28
|
-
return i;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* 把字段列表编码为一条 protobuf 消息。
|
|
33
|
-
* 字段格式 { num, wire, value }:wire 0=varint(value 数字)、2=bytes(value Buffer/字符串)、
|
|
34
|
-
* 5=fixed32、1=fixed64;value 可为嵌套 encodeFields 返回的 Buffer。
|
|
35
|
-
*/
|
|
36
|
-
export function encodeFields(fields) {
|
|
37
|
-
const chunks = [];
|
|
38
|
-
for (const f of fields) {
|
|
39
|
-
const tag = Buffer.alloc(10);
|
|
40
|
-
chunks.push(tag.subarray(0, writeVarint(tag, 0, (BigInt(f.num) << 3n) | BigInt(f.wire))));
|
|
41
|
-
if (f.wire === 0) {
|
|
42
|
-
const b = Buffer.alloc(10);
|
|
43
|
-
chunks.push(b.subarray(0, writeVarint(b, 0, BigInt(f.value))));
|
|
44
|
-
} else if (f.wire === 2) {
|
|
45
|
-
const bytes = typeof f.value === 'string' ? Buffer.from(f.value, 'utf8') : Buffer.from(f.value);
|
|
46
|
-
const lb = Buffer.alloc(10);
|
|
47
|
-
chunks.push(lb.subarray(0, writeVarint(lb, 0, BigInt(bytes.length))), bytes);
|
|
48
|
-
} else if (f.wire === 5) {
|
|
49
|
-
const b = Buffer.alloc(4);
|
|
50
|
-
b.writeUInt32LE(Number(f.value) >>> 0);
|
|
51
|
-
chunks.push(b);
|
|
52
|
-
} else if (f.wire === 1) {
|
|
53
|
-
const b = Buffer.alloc(8);
|
|
54
|
-
b.writeBigUInt64LE(BigInt(f.value));
|
|
55
|
-
chunks.push(b);
|
|
56
|
-
} else {
|
|
57
|
-
throw new Error(`不支持的线类型 ${f.wire}`);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
return Buffer.concat(chunks);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* 解码一条 protobuf 消息。每字段含 num/wire;wire0 附 varint、wire2 附 ascii/hex 与
|
|
65
|
-
* 可能的 nested(递归解码)。供解析服务端帧(tick 学习 / 错误识别)用。
|
|
66
|
-
*/
|
|
67
|
-
export function decodeFields(buf, depth = 0) {
|
|
68
|
-
const out = [];
|
|
69
|
-
let i = 0;
|
|
70
|
-
while (i < buf.length) {
|
|
71
|
-
try {
|
|
72
|
-
const { value: tag, next: n1 } = readVarint(buf, i);
|
|
73
|
-
const num = Number(tag >> 3n);
|
|
74
|
-
const wire = Number(tag & 7n);
|
|
75
|
-
if (num === 0) break; // 非法
|
|
76
|
-
let val;
|
|
77
|
-
switch (wire) {
|
|
78
|
-
case 0: { const v = readVarint(buf, n1); val = { varint: v.value, signed: BigInt.asIntN(64, v.value), next: v.next }; break; }
|
|
79
|
-
case 1: { val = { bytes: buf.subarray(n1, n1 + 8).toString('hex'), next: n1 + 8 }; break; }
|
|
80
|
-
case 2: {
|
|
81
|
-
const len = readVarint(buf, n1);
|
|
82
|
-
const L = Number(len.value);
|
|
83
|
-
const raw = buf.subarray(Number(len.next), Number(len.next) + L);
|
|
84
|
-
const next = Number(len.next) + L;
|
|
85
|
-
const ascii = [...raw].map((c) => (c >= 32 && c < 127) ? String.fromCharCode(c) : '.').join('');
|
|
86
|
-
const allPrintable = [...raw].every((c) => c >= 32 && c < 127);
|
|
87
|
-
let nested = null;
|
|
88
|
-
if (L >= 2 && !allPrintable) {
|
|
89
|
-
try {
|
|
90
|
-
const sub = decodeFields(raw, depth + 1);
|
|
91
|
-
const strict = sub.length >= 1 && sub.length <= 32
|
|
92
|
-
&& sub.every((f) => !f.error && f.num >= 1 && (f.wire === 0 || f.wire === 1 || f.wire === 2 || f.wire === 5));
|
|
93
|
-
if (strict) nested = sub;
|
|
94
|
-
} catch { /* 非消息 */ }
|
|
95
|
-
}
|
|
96
|
-
val = { len: L, hex: raw.toString('hex'), ascii, nested, next };
|
|
97
|
-
break;
|
|
98
|
-
}
|
|
99
|
-
case 5: { val = { bytes: buf.subarray(n1, n1 + 4).toString('hex'), next: n1 + 4 }; break; }
|
|
100
|
-
default: val = { wire, next: n1 };
|
|
101
|
-
}
|
|
102
|
-
out.push({ num, wire, ...val });
|
|
103
|
-
i = val.next;
|
|
104
|
-
} catch (e) {
|
|
105
|
-
out.push({ error: e.message, at: i });
|
|
106
|
-
break;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
return out;
|
|
110
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* MonsterParty WS protobuf 线格式编解码(移植自 toy-protocol/,协议已实测验证)。
|
|
3
|
+
* 仅依赖 node:buffer;encode 用于构造帧,decode 用于解析服务端回包。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** 读 varint(用于解码)。返回 { value: bigint, next: 下一字节下标 }。 */
|
|
7
|
+
export function readVarint(buf, i) {
|
|
8
|
+
let result = 0n, shift = 0n;
|
|
9
|
+
while (i < buf.length) {
|
|
10
|
+
const b = buf[i++];
|
|
11
|
+
result |= BigInt(b & 0x7f) << shift;
|
|
12
|
+
if (!(b & 0x80)) return { value: result, next: i };
|
|
13
|
+
shift += 7n;
|
|
14
|
+
if (shift > 63n) throw new Error('varint too long');
|
|
15
|
+
}
|
|
16
|
+
throw new Error('truncated varint');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 写 varint(用于编码)。返回写入后的下标。 */
|
|
20
|
+
export function writeVarint(buf, offset, value) {
|
|
21
|
+
let n = BigInt(value), i = offset;
|
|
22
|
+
for (;;) {
|
|
23
|
+
const byte = Number(n & 0x7fn);
|
|
24
|
+
n >>= 7n;
|
|
25
|
+
if (n === 0n) { buf[i++] = byte; break; }
|
|
26
|
+
buf[i++] = byte | 0x80;
|
|
27
|
+
}
|
|
28
|
+
return i;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 把字段列表编码为一条 protobuf 消息。
|
|
33
|
+
* 字段格式 { num, wire, value }:wire 0=varint(value 数字)、2=bytes(value Buffer/字符串)、
|
|
34
|
+
* 5=fixed32、1=fixed64;value 可为嵌套 encodeFields 返回的 Buffer。
|
|
35
|
+
*/
|
|
36
|
+
export function encodeFields(fields) {
|
|
37
|
+
const chunks = [];
|
|
38
|
+
for (const f of fields) {
|
|
39
|
+
const tag = Buffer.alloc(10);
|
|
40
|
+
chunks.push(tag.subarray(0, writeVarint(tag, 0, (BigInt(f.num) << 3n) | BigInt(f.wire))));
|
|
41
|
+
if (f.wire === 0) {
|
|
42
|
+
const b = Buffer.alloc(10);
|
|
43
|
+
chunks.push(b.subarray(0, writeVarint(b, 0, BigInt(f.value))));
|
|
44
|
+
} else if (f.wire === 2) {
|
|
45
|
+
const bytes = typeof f.value === 'string' ? Buffer.from(f.value, 'utf8') : Buffer.from(f.value);
|
|
46
|
+
const lb = Buffer.alloc(10);
|
|
47
|
+
chunks.push(lb.subarray(0, writeVarint(lb, 0, BigInt(bytes.length))), bytes);
|
|
48
|
+
} else if (f.wire === 5) {
|
|
49
|
+
const b = Buffer.alloc(4);
|
|
50
|
+
b.writeUInt32LE(Number(f.value) >>> 0);
|
|
51
|
+
chunks.push(b);
|
|
52
|
+
} else if (f.wire === 1) {
|
|
53
|
+
const b = Buffer.alloc(8);
|
|
54
|
+
b.writeBigUInt64LE(BigInt(f.value));
|
|
55
|
+
chunks.push(b);
|
|
56
|
+
} else {
|
|
57
|
+
throw new Error(`不支持的线类型 ${f.wire}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return Buffer.concat(chunks);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 解码一条 protobuf 消息。每字段含 num/wire;wire0 附 varint、wire2 附 ascii/hex 与
|
|
65
|
+
* 可能的 nested(递归解码)。供解析服务端帧(tick 学习 / 错误识别)用。
|
|
66
|
+
*/
|
|
67
|
+
export function decodeFields(buf, depth = 0) {
|
|
68
|
+
const out = [];
|
|
69
|
+
let i = 0;
|
|
70
|
+
while (i < buf.length) {
|
|
71
|
+
try {
|
|
72
|
+
const { value: tag, next: n1 } = readVarint(buf, i);
|
|
73
|
+
const num = Number(tag >> 3n);
|
|
74
|
+
const wire = Number(tag & 7n);
|
|
75
|
+
if (num === 0) break; // 非法
|
|
76
|
+
let val;
|
|
77
|
+
switch (wire) {
|
|
78
|
+
case 0: { const v = readVarint(buf, n1); val = { varint: v.value, signed: BigInt.asIntN(64, v.value), next: v.next }; break; }
|
|
79
|
+
case 1: { val = { bytes: buf.subarray(n1, n1 + 8).toString('hex'), next: n1 + 8 }; break; }
|
|
80
|
+
case 2: {
|
|
81
|
+
const len = readVarint(buf, n1);
|
|
82
|
+
const L = Number(len.value);
|
|
83
|
+
const raw = buf.subarray(Number(len.next), Number(len.next) + L);
|
|
84
|
+
const next = Number(len.next) + L;
|
|
85
|
+
const ascii = [...raw].map((c) => (c >= 32 && c < 127) ? String.fromCharCode(c) : '.').join('');
|
|
86
|
+
const allPrintable = [...raw].every((c) => c >= 32 && c < 127);
|
|
87
|
+
let nested = null;
|
|
88
|
+
if (L >= 2 && !allPrintable) {
|
|
89
|
+
try {
|
|
90
|
+
const sub = decodeFields(raw, depth + 1);
|
|
91
|
+
const strict = sub.length >= 1 && sub.length <= 32
|
|
92
|
+
&& sub.every((f) => !f.error && f.num >= 1 && (f.wire === 0 || f.wire === 1 || f.wire === 2 || f.wire === 5));
|
|
93
|
+
if (strict) nested = sub;
|
|
94
|
+
} catch { /* 非消息 */ }
|
|
95
|
+
}
|
|
96
|
+
val = { len: L, hex: raw.toString('hex'), ascii, nested, next };
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
case 5: { val = { bytes: buf.subarray(n1, n1 + 4).toString('hex'), next: n1 + 4 }; break; }
|
|
100
|
+
default: val = { wire, next: n1 };
|
|
101
|
+
}
|
|
102
|
+
out.push({ num, wire, ...val });
|
|
103
|
+
i = val.next;
|
|
104
|
+
} catch (e) {
|
|
105
|
+
out.push({ error: e.message, at: i });
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** 使用宿主公开的同一校验器,避免工具与脚本接受不同参数。 */
|
|
2
|
+
import { assertObjectJsonSchema, assertSupportedJsonSchema } from '@deepseek-ai/dsh-tools';
|
|
3
|
+
import { createExtensionRegistry } from '../extensions.js';
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { isAbsolute } from 'node:path';
|
|
6
|
+
|
|
7
|
+
export function createDeviceExtensionRegistry() {
|
|
8
|
+
return createExtensionRegistry({ assertDeviceDriver(descriptor) {
|
|
9
|
+
if (!isAbsolute(descriptor.skill.path)) throw new Error('设备 skill 必须使用本地绝对路径');
|
|
10
|
+
const content = readFileSync(descriptor.skill.path, 'utf8');
|
|
11
|
+
const name = /^---\r?\n[\s\S]*?^name:\s*([^\r\n]+)$/m.exec(content)?.[1]?.trim();
|
|
12
|
+
if (name !== descriptor.skill.name) throw new Error('设备 skill 文件名称与声明不一致');
|
|
13
|
+
if (['pygmalion-life-scripts', 'pygmalion-meme-maintenance', 'pygmalion-memory-archive'].includes(name)) throw new Error('设备 skill 与内置能力同名');
|
|
14
|
+
if (!Object.keys(descriptor.operations).length && typeof descriptor.subscribe !== 'function') throw new Error('设备须提供操作或事件订阅入口');
|
|
15
|
+
}, assertDeviceOperation(operation) {
|
|
16
|
+
assertObjectJsonSchema(operation.parameters);
|
|
17
|
+
assertSupportedJsonSchema(operation.output ?? {});
|
|
18
|
+
} });
|
|
19
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** 子进程只持有绑定到本次运行的 IPC 通道,不持有设备凭据或任意目标选择权。 */
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
const requests = new Map();
|
|
4
|
+
const events = new EventEmitter();
|
|
5
|
+
let sequence = 0;
|
|
6
|
+
const syncRef = () => {
|
|
7
|
+
if (requests.size || events.eventNames().length) process.channel?.ref();
|
|
8
|
+
else process.channel?.unref();
|
|
9
|
+
};
|
|
10
|
+
function request(type, operation, input) {
|
|
11
|
+
if (!process.connected) return Promise.reject(new Error('设备脚本控制通道已关闭'));
|
|
12
|
+
const id = ++sequence;
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
requests.set(id, { resolve, reject }); syncRef();
|
|
15
|
+
process.send({ id, type, operation, input }, error => {
|
|
16
|
+
if (!error) return;
|
|
17
|
+
requests.delete(id); syncRef(); reject(error);
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
process.on('message', message => {
|
|
22
|
+
if (message?.type === 'event') { events.emit(message.name, message.data); return; }
|
|
23
|
+
const pending = requests.get(message?.id);
|
|
24
|
+
if (!pending) return;
|
|
25
|
+
requests.delete(message.id); syncRef();
|
|
26
|
+
if (message.ok) pending.resolve(message.result); else pending.reject(new Error(message.error || '设备操作失败'));
|
|
27
|
+
});
|
|
28
|
+
process.on('disconnect', () => {
|
|
29
|
+
for (const pending of requests.values()) pending.reject(new Error('设备脚本控制通道已关闭'));
|
|
30
|
+
requests.clear(); events.removeAllListeners();
|
|
31
|
+
});
|
|
32
|
+
syncRef();
|
|
33
|
+
const operations = Object.freeze(Object.fromEntries(JSON.parse(process.env.PYG_DEVICE_OPERATIONS || '[]')
|
|
34
|
+
.map(name => [name, input => request('operation', name, input ?? {})])));
|
|
35
|
+
globalThis.device = Object.freeze({
|
|
36
|
+
operations,
|
|
37
|
+
sleep: ms => new Promise(resolve => setTimeout(resolve, Math.max(0, Number(ms) || 0))),
|
|
38
|
+
wake: input => request('wake', '', input ?? {}),
|
|
39
|
+
on(name, listener) { events.on(name, listener); syncRef(); return () => { events.off(name, listener); syncRef(); }; },
|
|
40
|
+
});
|
|
41
|
+
// 只有对应驱动声明的旧 SDK 别名才出现;其他设备没有 toy.* 等特定接口。
|
|
42
|
+
for (const alias of JSON.parse(process.env.PYG_DEVICE_ALIASES || '[]')) {
|
|
43
|
+
globalThis[alias.name] = Object.freeze(Object.fromEntries(Object.entries(alias.methods).map(([name, operation]) =>
|
|
44
|
+
[name, operation === '$sleep' ? device.sleep : operation === '$wake' ? device.wake : operations[operation]])));
|
|
45
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** 受监管的设备脚本运行器;设备操作经父进程的同一执行入口,不创建 HTTP 控制旁路。 */
|
|
2
|
+
import { fork } from 'node:child_process';
|
|
3
|
+
import { mkdir, realpath, open, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { join, resolve, relative, isAbsolute, basename, extname } from 'node:path';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
|
|
8
|
+
const helper = fileURLToPath(new URL('./script-helper.mjs', import.meta.url));
|
|
9
|
+
export function createDeviceScripts({ prepare, log }) {
|
|
10
|
+
const runs = new Map();
|
|
11
|
+
const writes = new Map();
|
|
12
|
+
const persist = (workspace, directory) => {
|
|
13
|
+
const key = join(workspace, directory);
|
|
14
|
+
const pending = (writes.get(key) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
15
|
+
await mkdir(key, { recursive: true });
|
|
16
|
+
await writeFile(join(key, '.running.json'), JSON.stringify([...runs.values()]
|
|
17
|
+
.filter(run => run.workspace === workspace && run.directory === directory)
|
|
18
|
+
.map(({ runId, roleId, deviceId, driverId, script, pid, startedAt }) => ({ runId, roleId, deviceId, driverId, script, pid, startedAt })), null, 2));
|
|
19
|
+
});
|
|
20
|
+
writes.set(key, pending);
|
|
21
|
+
void pending.catch(() => log?.warn?.('设备脚本监管记录保存失败'));
|
|
22
|
+
};
|
|
23
|
+
const list = () => [...runs.values()].map(({ child, binding, closed, ended, finish, ...run }) => run);
|
|
24
|
+
async function start({ roleId, deviceId, scriptPath, directory = 'device-scripts' }) {
|
|
25
|
+
let binding, output;
|
|
26
|
+
try {
|
|
27
|
+
if (!['toys', 'device-scripts'].includes(directory)) throw new Error('脚本目录无效');
|
|
28
|
+
binding = await prepare(roleId, deviceId, randomUUID());
|
|
29
|
+
const base = await realpath(join(binding.role.workspace, directory));
|
|
30
|
+
const script = await realpath(resolve(base, scriptPath));
|
|
31
|
+
const rel = relative(base, script);
|
|
32
|
+
if (rel.startsWith('..') || isAbsolute(rel) || !['.mjs', '.js', '.ts'].includes(extname(script))) throw new Error('只能运行指定目录内的 JavaScript/TypeScript 文件');
|
|
33
|
+
const startedAt = Date.now(), scriptName = basename(script), runId = binding.runId;
|
|
34
|
+
await mkdir(join(base, '.logs'), { recursive: true });
|
|
35
|
+
const logName = `${scriptName.replace(/\.[^.]+$/, '')}-${startedAt}.log`;
|
|
36
|
+
output = await open(join(base, '.logs', logName), 'a');
|
|
37
|
+
await binding.descriptor.scriptStart?.(binding.instance, { roleId, deviceId, runId, script });
|
|
38
|
+
const child = fork(script, [], { cwd: binding.role.workspace, windowsHide: true,
|
|
39
|
+
execArgv: ['--import', pathToFileURL(helper).href],
|
|
40
|
+
stdio: ['ignore', output.fd, output.fd, 'ipc'], env: { ...process.env,
|
|
41
|
+
PYG_WORKSPACE: binding.role.workspace, PYG_DEVICE_OPERATIONS: JSON.stringify(Object.keys(binding.descriptor.operations)),
|
|
42
|
+
PYG_DEVICE_ALIASES: JSON.stringify(binding.descriptor.scriptAliases ?? []) } });
|
|
43
|
+
let end;
|
|
44
|
+
const ended = new Promise(resolve => { end = resolve; });
|
|
45
|
+
const run = { runId, roleId, deviceId, driverId: binding.descriptor.id, workspace: binding.role.workspace,
|
|
46
|
+
directory, script, scriptName, logName, pid: child.pid, startedAt, child, binding, closed: false, ended };
|
|
47
|
+
let finished = false, unsubscribe;
|
|
48
|
+
const finish = async (reason, code) => {
|
|
49
|
+
if (finished) return; finished = true; run.closed = true;
|
|
50
|
+
binding.signal.removeEventListener('abort', onAbort);
|
|
51
|
+
try { await unsubscribe?.(); }
|
|
52
|
+
catch { log?.warn?.('设备事件订阅清理失败'); }
|
|
53
|
+
try { await output.close(); } catch { /* 子进程错误与 close 只关闭一次 */ }
|
|
54
|
+
try {
|
|
55
|
+
if (binding.descriptor.scriptEnd) await binding.descriptor.scriptEnd(binding.instance, { roleId, deviceId, runId, script, reason, code });
|
|
56
|
+
else if (reason !== 'disposed') await binding.wake({ type: 'script-ended', runId, script: scriptName, reason, code });
|
|
57
|
+
}
|
|
58
|
+
catch { log?.warn?.('设备脚本结束处理失败'); }
|
|
59
|
+
runs.delete(runId); binding.release(); persist(run.workspace, directory);
|
|
60
|
+
end();
|
|
61
|
+
};
|
|
62
|
+
const onAbort = () => { void stop(runId, roleId, 'disposed'); };
|
|
63
|
+
run.finish = finish; runs.set(runId, run); persist(run.workspace, directory);
|
|
64
|
+
child.on('error', () => { void finish('failed'); });
|
|
65
|
+
child.on('close', code => { void finish(run.reason ?? (code === 0 ? 'completed' : 'failed'), code); });
|
|
66
|
+
child.on('message', async message => {
|
|
67
|
+
if (!message || !Number.isInteger(message.id)) return;
|
|
68
|
+
try {
|
|
69
|
+
if (run.closed) throw new Error('设备脚本已停止');
|
|
70
|
+
const result = message.type === 'operation' ? await binding.invoke(message.operation, message.input)
|
|
71
|
+
: message.type === 'wake' ? await binding.wake(message.input) : (() => { throw new Error('未知脚本请求'); })();
|
|
72
|
+
if (child.connected) child.send({ id: message.id, ok: true, result: result ?? null });
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (child.connected) child.send({ id: message.id, ok: false, error: error.message });
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
binding.signal.addEventListener('abort', onAbort, { once: true });
|
|
78
|
+
if (binding.signal.aborted) onAbort();
|
|
79
|
+
if (binding.descriptor.subscribe) {
|
|
80
|
+
unsubscribe = await binding.descriptor.subscribe(binding.instance, (name, data) => {
|
|
81
|
+
if (!run.closed && child.connected) child.send({ type: 'event', name, data });
|
|
82
|
+
});
|
|
83
|
+
if (finished) await unsubscribe?.();
|
|
84
|
+
}
|
|
85
|
+
return { ok: true, runId, roleId, deviceId, pid: child.pid, startedAt, script };
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (binding && runs.has(binding.runId)) await stop(binding.runId, roleId, 'failed');
|
|
88
|
+
else { await output?.close().catch(() => {}); binding?.release(); }
|
|
89
|
+
return { ok: false, error: error.message, code: error.code ?? 'script-start-failed' };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function stop(runId, roleId, reason = 'stopped') {
|
|
93
|
+
const run = runs.get(runId);
|
|
94
|
+
if (!run || roleId && run.roleId !== roleId) return { ok: false, error: '脚本不存在或不属于当前角色' };
|
|
95
|
+
if (run.closed) { await run.ended; return { ok: true, stopped: runId }; }
|
|
96
|
+
run.closed = true; run.reason = reason;
|
|
97
|
+
run.binding.cancel();
|
|
98
|
+
if (run.child.connected) run.child.disconnect();
|
|
99
|
+
run.child.kill('SIGTERM');
|
|
100
|
+
let timer;
|
|
101
|
+
await Promise.race([run.ended, new Promise(resolve => { timer = setTimeout(resolve, 1000); })]); clearTimeout(timer);
|
|
102
|
+
if (runs.has(runId)) { run.child.kill('SIGKILL'); await run.finish(reason); }
|
|
103
|
+
return { ok: true, stopped: runId };
|
|
104
|
+
}
|
|
105
|
+
return { start, stop, list,
|
|
106
|
+
async stopRole(roleId) { await Promise.all(list().filter(run => run.roleId === roleId).map(run => stop(run.runId, roleId, 'disposed'))); },
|
|
107
|
+
async dispose() { await Promise.all(list().map(run => stop(run.runId, run.roleId, 'disposed'))); await Promise.allSettled(writes.values()); },
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/** 通用设备执行:授权、参数校验、资源串行、脚本租用与生命周期;无型号参数。 */
|
|
2
|
+
import { validateJsonSchemaValue } from '@deepseek-ai/dsh-tools';
|
|
3
|
+
import { createDeviceScripts } from './scripts.mjs';
|
|
4
|
+
import { deviceToolName } from '../extensions.js';
|
|
5
|
+
import { defaults, validate } from '../extension-config.js';
|
|
6
|
+
|
|
7
|
+
export function createDeviceService({ persona, extensions, log }) {
|
|
8
|
+
const instances = new Map(), queues = new Map(), leases = new Map(), wakes = new Map(), blocked = new Set();
|
|
9
|
+
const lifetime = new AbortController();
|
|
10
|
+
const generations = new Map();
|
|
11
|
+
const identity = ({ role, device, generation }) => JSON.stringify([generation, role.binding ?? {}, device.revision ?? 0, device.config ?? {}]);
|
|
12
|
+
const assertSame = (before, after) => {
|
|
13
|
+
if (before.key !== after.key || before.entry !== after.entry || identity(before) !== identity(after)) throw new Error('角色或设备配置已改变,本次操作已取消');
|
|
14
|
+
};
|
|
15
|
+
const wake = async (roleId, input) => wakes.get(roleId)?.(`[设备事件] ${JSON.stringify(input ?? {})}`, {})
|
|
16
|
+
?? { ok: false, error: '当前角色没有可用唤醒入口' };
|
|
17
|
+
async function authorize(roleId, deviceId) {
|
|
18
|
+
lifetime.signal.throwIfAborted();
|
|
19
|
+
if (blocked.has(roleId)) throw new Error('角色已停止');
|
|
20
|
+
const role = await persona.loadRole(roleId), device = await persona.loadDevice(deviceId);
|
|
21
|
+
if (!role || !device || device.owner !== role.persona?.owner || !role.persona?.devices?.includes(deviceId)) {
|
|
22
|
+
throw new Error('当前角色没有此设备的授权');
|
|
23
|
+
}
|
|
24
|
+
const entry = extensions.getDeviceDriver(device.kind);
|
|
25
|
+
if (!entry) throw new Error('设备驱动不可用,登记信息已保留');
|
|
26
|
+
entry.signal.throwIfAborted();
|
|
27
|
+
const key = `${device.owner}:${device.id}`;
|
|
28
|
+
return { role, device, entry, key, generation: generations.get(roleId) ?? 0 };
|
|
29
|
+
}
|
|
30
|
+
async function close(row) {
|
|
31
|
+
if (row.closing) return row.closing;
|
|
32
|
+
row.controller.abort(new Error('设备实例已释放'));
|
|
33
|
+
row.entry.signal.removeEventListener('abort', row.onUnload);
|
|
34
|
+
if (instances.get(row.key) === row) instances.delete(row.key);
|
|
35
|
+
row.closing = row.created.then(instance => row.entry.descriptor.dispose?.(instance)).catch(() => log?.warn?.('设备资源释放失败'));
|
|
36
|
+
return row.closing;
|
|
37
|
+
}
|
|
38
|
+
async function binding(context) {
|
|
39
|
+
const { role, device, entry, key } = context;
|
|
40
|
+
const signature = JSON.stringify([role.roleId, device.id, identity(context)]);
|
|
41
|
+
let row = instances.get(key);
|
|
42
|
+
if (row && (row.entry !== entry || row.signature !== signature)) { await close(row); row = undefined; }
|
|
43
|
+
if (!row) {
|
|
44
|
+
const controller = new AbortController();
|
|
45
|
+
const signal = AbortSignal.any([controller.signal, entry.signal, lifetime.signal]);
|
|
46
|
+
row = { key, signature, entry, controller, signal, roleId: role.roleId, deviceId: device.id };
|
|
47
|
+
row.onUnload = () => { void stopDeviceScripts(device.id, 'disposed').then(() => close(row)); };
|
|
48
|
+
row.created = Promise.resolve().then(() => entry.descriptor.create({ roleId: role.roleId, deviceId: device.id,
|
|
49
|
+
device, config: device.config ?? {}, signal, wake: input => wake(role.roleId, input) }));
|
|
50
|
+
instances.set(key, row);
|
|
51
|
+
entry.signal.addEventListener('abort', row.onUnload, { once: true });
|
|
52
|
+
row.created.catch(() => { entry.signal.removeEventListener('abort', row.onUnload); if (instances.get(key) === row) instances.delete(key); });
|
|
53
|
+
}
|
|
54
|
+
const instance = await row.created;
|
|
55
|
+
row.signal.throwIfAborted();
|
|
56
|
+
return { ...context, row, instance };
|
|
57
|
+
}
|
|
58
|
+
function enqueue(key, action) {
|
|
59
|
+
const pending = (queues.get(key) ?? Promise.resolve()).catch(() => {}).then(action);
|
|
60
|
+
queues.set(key, pending);
|
|
61
|
+
return pending.finally(() => { if (queues.get(key) === pending) queues.delete(key); });
|
|
62
|
+
}
|
|
63
|
+
async function invoke(roleId, deviceId, operationId, input = {}, { signal, runId } = {}) {
|
|
64
|
+
const initial = await authorize(roleId, deviceId);
|
|
65
|
+
return enqueue(initial.key, async () => {
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
const context = await authorize(roleId, deviceId);
|
|
68
|
+
assertSame(initial, context);
|
|
69
|
+
const lease = leases.get(context.key);
|
|
70
|
+
if (lease && lease !== runId) {
|
|
71
|
+
const error = new Error('设备脚本正在运行,请先显式终止脚本'); error.code = 'script-active'; throw error;
|
|
72
|
+
}
|
|
73
|
+
const operation = context.entry.descriptor.operations[operationId];
|
|
74
|
+
if (!operation) throw new Error('设备不支持此操作');
|
|
75
|
+
const violations = validateJsonSchemaValue(operation.parameters, input, 'input');
|
|
76
|
+
if (violations.length) throw new Error(violations.join(';'));
|
|
77
|
+
const current = await binding(context);
|
|
78
|
+
const combined = AbortSignal.any([current.row.signal, ...(signal ? [signal] : [])]);
|
|
79
|
+
combined.throwIfAborted();
|
|
80
|
+
const result = await operation.execute(current.instance, input, { roleId, deviceId, signal: combined,
|
|
81
|
+
fromScript: Boolean(runId), wake: data => wake(roleId, data) });
|
|
82
|
+
combined.throwIfAborted();
|
|
83
|
+
const latest = await authorize(roleId, deviceId);
|
|
84
|
+
assertSame(context, latest);
|
|
85
|
+
const invalid = validateJsonSchemaValue(operation.output ?? {}, result, 'result');
|
|
86
|
+
if (invalid.length) throw new Error('驱动返回了不符合声明的结果');
|
|
87
|
+
return result;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
const scripts = createDeviceScripts({ log, async prepare(roleId, deviceId, runId) {
|
|
91
|
+
const context = await authorize(roleId, deviceId);
|
|
92
|
+
if (leases.has(context.key)) { const error = new Error('设备已有运行脚本'); error.code = 'script-active'; throw error; }
|
|
93
|
+
leases.set(context.key, runId);
|
|
94
|
+
const controller = new AbortController();
|
|
95
|
+
const release = () => { controller.abort(new Error('设备脚本已结束')); if (leases.get(context.key) === runId) leases.delete(context.key); };
|
|
96
|
+
try {
|
|
97
|
+
const current = await enqueue(context.key, async () => {
|
|
98
|
+
const latest = await authorize(roleId, deviceId); assertSame(context, latest); return binding(latest);
|
|
99
|
+
});
|
|
100
|
+
return { ...current, descriptor: context.entry.descriptor, runId,
|
|
101
|
+
signal: AbortSignal.any([current.row.signal, controller.signal]), release,
|
|
102
|
+
cancel: () => controller.abort(new Error('设备脚本已停止')),
|
|
103
|
+
invoke: (operation, input) => invoke(roleId, deviceId, operation, input, { runId, signal: controller.signal }),
|
|
104
|
+
wake: async input => { controller.signal.throwIfAborted(); await authorize(roleId, deviceId); return wake(roleId, input); } };
|
|
105
|
+
} catch (error) { release(); throw error; }
|
|
106
|
+
} });
|
|
107
|
+
async function disposeRole(roleId) {
|
|
108
|
+
generations.set(roleId, (generations.get(roleId) ?? 0) + 1);
|
|
109
|
+
await scripts.stopRole(roleId);
|
|
110
|
+
await Promise.all([...instances.values()].filter(row => row.roleId === roleId).map(close));
|
|
111
|
+
}
|
|
112
|
+
async function stopDeviceScripts(deviceId, reason = 'stopped') {
|
|
113
|
+
for (const run of scripts.list().filter(run => run.deviceId === deviceId)) await scripts.stop(run.runId, run.roleId, reason);
|
|
114
|
+
}
|
|
115
|
+
async function skillDefinitions(role) {
|
|
116
|
+
const result = new Map();
|
|
117
|
+
for (const id of role?.persona?.devices ?? []) {
|
|
118
|
+
const device = await persona.loadDevice(id);
|
|
119
|
+
const entry = device?.owner === role.persona.owner && extensions.getDeviceDriver(device.kind);
|
|
120
|
+
if (entry) result.set(entry.descriptor.id, { ...entry.descriptor.skill, tools: entry.descriptor.legacyTools ?? [], driverId: entry.descriptor.id, entry });
|
|
121
|
+
}
|
|
122
|
+
return [...result.values()];
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
invoke, skillDefinitions, extensions, wake,
|
|
126
|
+
async updateDevice(owner, deviceId, patch) {
|
|
127
|
+
return enqueue(`config:${deviceId}`, async () => {
|
|
128
|
+
const device = await persona.loadDevice(deviceId);
|
|
129
|
+
if (!device || device.owner !== owner) throw new Error('设备不存在');
|
|
130
|
+
if (patch.revision !== undefined && patch.revision !== (device.revision ?? 0)) throw new Error('设备配置已更新,请重新加载');
|
|
131
|
+
const descriptor = extensions.getDeviceDriver(device.kind)?.descriptor;
|
|
132
|
+
if (!descriptor) throw new Error('设备驱动不可用,原登记信息已保留');
|
|
133
|
+
const values = { ...device.config };
|
|
134
|
+
const fields = new Map(descriptor.fields.map(field => [field.key, field]));
|
|
135
|
+
for (const [key, value] of Object.entries(patch.config ?? {})) {
|
|
136
|
+
const field = fields.get(key); if (!field) throw new Error('设备配置包含未声明字段');
|
|
137
|
+
if (field.type === 'secret' && value === '') continue;
|
|
138
|
+
if (value === null) delete values[key]; else values[key] = value;
|
|
139
|
+
}
|
|
140
|
+
const config = defaults(descriptor, values); validate(descriptor, config, true);
|
|
141
|
+
const alias = patch.alias === undefined ? device.alias : String(patch.alias).trim();
|
|
142
|
+
if (!alias) throw new Error('请填写设备别名');
|
|
143
|
+
const updated = { ...device, alias, config, revision: (device.revision ?? 0) + 1 };
|
|
144
|
+
await persona.saveDevice(updated);
|
|
145
|
+
await stopDeviceScripts(deviceId, 'disposed');
|
|
146
|
+
await Promise.all([...instances.values()].filter(row => row.deviceId === deviceId).map(close));
|
|
147
|
+
return this.publicDevice(updated);
|
|
148
|
+
});
|
|
149
|
+
},
|
|
150
|
+
async handleInput(roleId, text, { openid } = {}) {
|
|
151
|
+
const role = await persona.loadRole(roleId);
|
|
152
|
+
if (!role?.binding?.openid || role.binding.openid !== openid) return null;
|
|
153
|
+
const matches = [];
|
|
154
|
+
for (const id of role.persona.devices ?? []) {
|
|
155
|
+
const context = await authorize(roleId, id).catch(() => null);
|
|
156
|
+
if (!context?.entry.descriptor.matchInput || !context.entry.descriptor.acceptInput) continue;
|
|
157
|
+
const match = await context.entry.descriptor.matchInput(text);
|
|
158
|
+
if (match) matches.push({ context, match });
|
|
159
|
+
}
|
|
160
|
+
if (!matches.length) return null;
|
|
161
|
+
const { context, match } = matches[0];
|
|
162
|
+
if (matches.length > 1) return { ok: false, raw: match.raw, error: '多台设备均匹配此次输入,请先在管理页明确授权目标设备。' };
|
|
163
|
+
return enqueue(context.key, async () => {
|
|
164
|
+
const latest = await authorize(roleId, context.device.id); assertSame(context, latest);
|
|
165
|
+
const current = await binding(latest);
|
|
166
|
+
const result = await context.entry.descriptor.acceptInput(current.instance, match, { roleId, deviceId: context.device.id, openid, signal: current.row.signal });
|
|
167
|
+
current.row.signal.throwIfAborted();
|
|
168
|
+
assertSame(latest, await authorize(roleId, context.device.id));
|
|
169
|
+
return { ...result, raw: match.raw, alias: context.device.alias, skill: context.entry.descriptor.skill.name };
|
|
170
|
+
});
|
|
171
|
+
},
|
|
172
|
+
publicDevice(device) {
|
|
173
|
+
const descriptor = extensions.getDeviceDriver(device.kind)?.descriptor;
|
|
174
|
+
const config = {}, secrets = {};
|
|
175
|
+
for (const field of descriptor?.fields ?? []) {
|
|
176
|
+
if (field.type === 'secret') secrets[field.key] = Boolean(device.config?.[field.key]);
|
|
177
|
+
else if (device.config?.[field.key] !== undefined) config[field.key] = device.config[field.key];
|
|
178
|
+
}
|
|
179
|
+
return { ...device, config, secrets, available: Boolean(descriptor) };
|
|
180
|
+
},
|
|
181
|
+
deviceConfig(kind, values = {}) {
|
|
182
|
+
const descriptor = extensions.getDeviceDriver(kind)?.descriptor;
|
|
183
|
+
if (!descriptor) throw new Error('所选设备驱动不可用');
|
|
184
|
+
const known = new Set(descriptor.fields.map(field => field.key));
|
|
185
|
+
if (Object.keys(values).some(key => !known.has(key))) throw new Error('设备配置包含未声明字段');
|
|
186
|
+
const config = defaults(descriptor, values); validate(descriptor, config, true); return config;
|
|
187
|
+
},
|
|
188
|
+
listDrivers: () => extensions.listDeviceDrivers(),
|
|
189
|
+
async status(roleId) {
|
|
190
|
+
const role = await persona.loadRole(roleId), devices = [];
|
|
191
|
+
for (const id of role?.persona?.devices ?? []) {
|
|
192
|
+
const device = await persona.loadDevice(id);
|
|
193
|
+
if (!device || device.owner !== role.persona.owner) continue;
|
|
194
|
+
const entry = extensions.getDeviceDriver(device.kind);
|
|
195
|
+
const extra = entry?.descriptor.snapshot ? await entry.descriptor.snapshot({ roleId, deviceId: id }) : {};
|
|
196
|
+
devices.push({ ...extra, deviceId: id, alias: device.alias, kind: device.kind, available: Boolean(entry),
|
|
197
|
+
operations: Object.keys(entry?.descriptor.operations ?? {}) });
|
|
198
|
+
}
|
|
199
|
+
return { ok: Boolean(role), devices };
|
|
200
|
+
},
|
|
201
|
+
async document(device) {
|
|
202
|
+
const descriptor = extensions.getDeviceDriver(device.kind)?.descriptor;
|
|
203
|
+
const identity = `设备标识:${device.id}\n驱动:${device.kind}\n`;
|
|
204
|
+
return identity + (await descriptor?.document?.(device) ?? `# 设备:${device.alias}\n\n${descriptor ? `使用前加载 ${descriptor.skill.name} skill。` : '驱动不可用,登记信息保留。'}`);
|
|
205
|
+
},
|
|
206
|
+
registerRole(roleId, callback) { blocked.delete(roleId); wakes.set(roleId, callback); },
|
|
207
|
+
unregisterRole(roleId) { blocked.add(roleId); wakes.delete(roleId); void disposeRole(roleId); },
|
|
208
|
+
disposeRole,
|
|
209
|
+
runDeviceScript: args => scripts.start(args),
|
|
210
|
+
stopScript: (runId, roleId, reason) => scripts.stop(runId, roleId, reason),
|
|
211
|
+
listScriptRuns: scripts.list,
|
|
212
|
+
stopDeviceScripts,
|
|
213
|
+
async disposeAll() {
|
|
214
|
+
lifetime.abort(new Error('设备服务已停止'));
|
|
215
|
+
await scripts.dispose(); await Promise.all([...instances.values()].map(close)); wakes.clear();
|
|
216
|
+
},
|
|
217
|
+
registerTools(scope, driverId, resolveContext) {
|
|
218
|
+
const entry = extensions.getDeviceDriver(driverId);
|
|
219
|
+
if (!entry) throw new Error('设备驱动不可用');
|
|
220
|
+
const releases = [];
|
|
221
|
+
releases.push(scope.tools.register({ name: deviceToolName(driverId, 'run_script'),
|
|
222
|
+
description: '运行或显式终止此驱动的设备脚本;脚本位于角色工作区 device-scripts/,全局 device.operations 提供驱动操作。',
|
|
223
|
+
parameters: { type: 'object', additionalProperties: false, required: ['deviceId'], properties: {
|
|
224
|
+
deviceId: { type: 'string' }, script: { type: 'string' }, stop: { type: 'string' } } },
|
|
225
|
+
output: { schema: {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
|
|
226
|
+
async execute(args, exec) {
|
|
227
|
+
entry.signal.throwIfAborted(); const context = await resolveContext(exec);
|
|
228
|
+
const authorized = await authorize(context.roleId, args.deviceId);
|
|
229
|
+
if (authorized.entry !== entry) throw new Error('设备与当前驱动不匹配');
|
|
230
|
+
if (args.stop) {
|
|
231
|
+
const run = scripts.list().find(run => run.runId === args.stop && run.deviceId === args.deviceId);
|
|
232
|
+
if (!run) throw new Error('设备脚本不存在');
|
|
233
|
+
return scripts.stop(args.stop, context.roleId);
|
|
234
|
+
}
|
|
235
|
+
if (!args.script) throw new Error('请指定 script 或 stop');
|
|
236
|
+
return scripts.start({ roleId: context.roleId, deviceId: args.deviceId, scriptPath: args.script });
|
|
237
|
+
} }));
|
|
238
|
+
for (const [id, operation] of Object.entries(entry.descriptor.operations)) {
|
|
239
|
+
releases.push(scope.tools.register({ name: deviceToolName(driverId, id), description: operation.description,
|
|
240
|
+
parameters: { type: 'object', additionalProperties: false, required: ['deviceId', 'input'],
|
|
241
|
+
properties: { deviceId: { type: 'string' }, input: operation.parameters } },
|
|
242
|
+
output: { schema: operation.output ?? {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
|
|
243
|
+
async execute(args, exec) {
|
|
244
|
+
entry.signal.throwIfAborted();
|
|
245
|
+
const context = await resolveContext(exec);
|
|
246
|
+
const device = await persona.loadDevice(args.deviceId);
|
|
247
|
+
if (device?.kind !== driverId) throw new Error('设备与当前驱动不匹配');
|
|
248
|
+
return invoke(context.roleId, args.deviceId, id, args.input, { signal: exec.signal });
|
|
249
|
+
} }));
|
|
250
|
+
}
|
|
251
|
+
return async () => { for (const release of releases) await release(); };
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|