@syengup/fridaynext-hermes-channel 0.1.0-beta.2 → 0.1.0-beta.4
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/install-config.js +67 -0
- package/install-runtime.js +18 -9
- package/install.js +6 -4
- package/package.json +2 -1
- package/plugin/README.md +2 -2
- package/plugin/fridaynext_plugin/__init__.py +10 -0
- package/plugin/fridaynext_plugin/adapter.py +231 -12
- package/plugin/fridaynext_plugin/agent_management.py +158 -0
- package/plugin/fridaynext_plugin/canonical_control.py +12 -4
- package/plugin/fridaynext_plugin/compat_v0225.py +1247 -4
- package/plugin/fridaynext_plugin/continuations.py +271 -0
- package/plugin/fridaynext_plugin/device-tools-v1.json +302 -0
- package/plugin/fridaynext_plugin/device_tools.py +144 -0
- package/plugin/fridaynext_plugin/history.py +25 -3
- package/plugin/fridaynext_plugin/host.py +7 -4
- package/plugin/fridaynext_plugin/media_input.py +56 -9
- package/plugin/fridaynext_plugin/message_speech.py +143 -0
- package/plugin/fridaynext_plugin/multi_agent.py +221 -0
- package/plugin/fridaynext_plugin/reply_context.py +39 -0
- package/plugin/fridaynext_plugin/runtime_port.py +23 -1
- package/plugin/fridaynext_plugin/scheduled_tasks.py +229 -0
- package/plugin/fridaynext_plugin/settings.py +7 -3
- package/plugin/fridaynext_plugin/slash_commands.py +163 -0
- package/plugin/fridaynext_plugin/stream_bridge.py +83 -26
- package/plugin/fridaynext_plugin/stream_projection.py +30 -6
- package/plugin/fridaynext_plugin/subagents.py +228 -0
- package/plugin/plugin.yaml +11 -0
- package/plugin/runtime/dist/commands-routes.js +94 -0
- package/plugin/runtime/dist/device-tools-v1.json +302 -0
- package/plugin/runtime/dist/hosted-backend.js +293 -25
- package/plugin/runtime/dist/hosted-continuations.js +41 -0
- package/plugin/runtime/dist/hosted-device-tools.js +82 -0
- package/plugin/runtime/dist/hosted-media.js +54 -13
- package/plugin/runtime/dist/hosted-stream.js +124 -14
- package/plugin/runtime/dist/hosted-subagents.js +78 -0
- package/plugin/runtime/dist/platform-service.js +4 -0
- package/plugin/runtime/dist/plugin-control.js +10 -6
- package/plugin/runtime/dist/scheduled-routes.js +63 -0
- package/plugin/runtime/dist/service-host.js +40 -5
- package/plugin/runtime/dist/speech-routes.js +111 -0
- package/plugin/runtime/dist/tool-presentation.js +399 -0
- package/plugin/runtime/node_modules/.package-lock.json +6 -6
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/API.md +125 -5
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/README.md +21 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.d.ts +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.js +3 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.d.ts +136 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.js +105 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.d.ts +3 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.js +45 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.d.ts +10 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.js +2 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.d.ts +27 -2
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.js +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.d.ts +56 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.js +60 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/device-request/pending-store.js +3 -3
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.d.ts +5 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.js +5 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.d.ts +26 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.js +112 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.d.ts +4 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.js +30 -5
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.d.ts +18 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.js +187 -51
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.d.ts +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.js +52 -2
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.d.ts +13 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.js +73 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/service/channel-service.js +1 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.d.ts +47 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.js +184 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.d.ts +1 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.js +11 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/messages.js +12 -6
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.d.ts +13 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.js +336 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.d.ts +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.js +52 -10
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/session-settings.js +38 -6
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/sessions.js +8 -8
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/package.json +6 -7
- package/plugin/runtime/node_modules/tslib/README.md +3 -8
- package/plugin/runtime/node_modules/tslib/package.json +1 -1
- package/plugin/runtime/node_modules/tslib/tslib.d.ts +4 -2
- package/plugin/runtime/node_modules/tslib/tslib.es6.js +10 -1
- package/plugin/runtime/node_modules/tslib/tslib.es6.mjs +10 -1
- package/plugin/runtime/node_modules/tslib/tslib.js +10 -1
- package/plugin/runtime/package-lock.json +7 -7
- package/plugin/runtime/package.json +1 -1
- package/plugin/tools.py +3 -0
|
@@ -1,57 +1,237 @@
|
|
|
1
|
+
import * as Kit from "@syengup/fridaynext-channel-kit";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
1
4
|
import { RUNTIME_CAPABILITIES, ChannelError } from "@syengup/fridaynext-channel-kit";
|
|
2
5
|
import { HermesError, object } from "./service-errors.js";
|
|
6
|
+
import { presentHistory } from "./tool-presentation.js";
|
|
3
7
|
import { HostedStreamPublisher } from "./hosted-stream.js";
|
|
8
|
+
import { publishSubagent } from "./hosted-subagents.js";
|
|
9
|
+
import { publishContinuation } from "./hosted-continuations.js";
|
|
4
10
|
import { HostedSettings } from "./hosted-settings.js";
|
|
5
11
|
import { HostedRecoveryPort } from "./hosted-recovery.js";
|
|
12
|
+
import { HostedDeviceTools } from "./hosted-device-tools.js";
|
|
6
13
|
import { HostedMediaInput } from "./hosted-media.js";
|
|
7
14
|
import { HostedArtifacts } from "./hosted-artifacts.js";
|
|
8
15
|
import { HostedDeliveryObservations } from "./hosted-delivery-observations.js";
|
|
16
|
+
import { MAX_SPEECH_AUDIO_BASE64_LENGTH, MAX_SPEECH_TEXT_LENGTH, SPEECH_ERROR_CODES } from "./speech-routes.js";
|
|
17
|
+
const REPLY_FIELDS = ["version", "messageId", "text", "authorName", "isAssistant"];
|
|
18
|
+
function validReplyContext(value) {
|
|
19
|
+
const c = object(value);
|
|
20
|
+
return Object.keys(c).length === REPLY_FIELDS.length && REPLY_FIELDS.every(key => Object.hasOwn(c, key))
|
|
21
|
+
&& c.version === 1 && typeof c.messageId === "string" && !!c.messageId.trim() && c.messageId.length <= 1024
|
|
22
|
+
&& typeof c.text === "string" && !!c.text.trim() && c.text.length <= 500
|
|
23
|
+
&& typeof c.authorName === "string" && c.authorName.length <= 256 && typeof c.isAssistant === "boolean"
|
|
24
|
+
&& [c.messageId, c.text, c.authorName].every(text => Buffer.from(text, "utf8").toString("utf8") === text);
|
|
25
|
+
}
|
|
26
|
+
function replyPresentation(text, context) {
|
|
27
|
+
const escaped = new Set("\\`*_{}[]()#+-.!|>");
|
|
28
|
+
const author = Array.from(String(context.authorName).trim() || "User").map(c => escaped.has(c) ? "\\" + c : c).join("");
|
|
29
|
+
const quoted = String(context.text).trim();
|
|
30
|
+
return quoted.includes("\n") ? "> **" + author + ":**\n" + quoted.split("\n").map(line => "> " + line).join("\n") + "\n\n" + text
|
|
31
|
+
: "> **" + author + ":** " + quoted + "\n\n" + text;
|
|
32
|
+
}
|
|
33
|
+
function speechToken(value) {
|
|
34
|
+
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(value);
|
|
35
|
+
}
|
|
36
|
+
function speechBase64(value) {
|
|
37
|
+
return value.length % 4 === 0 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
|
|
38
|
+
}
|
|
39
|
+
function speechMime(value) {
|
|
40
|
+
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9.+-]{0,63}\/[A-Za-z0-9][A-Za-z0-9.+-]{0,63}$/.test(value);
|
|
41
|
+
}
|
|
9
42
|
export class HostedBackendAdapter {
|
|
10
43
|
rpc;
|
|
11
44
|
store;
|
|
12
45
|
facilities;
|
|
13
|
-
|
|
46
|
+
mediaEnvironment;
|
|
47
|
+
operations = { version: 1, ports: {
|
|
48
|
+
"commands.list": { execute: (context) => this.rpc.call("commands.list", {
|
|
49
|
+
serviceInstanceId: context.serviceInstanceId, agentId: context.agentId, sessionKey: context.sessionKey,
|
|
50
|
+
}) },
|
|
51
|
+
...Object.fromEntries(["schedule.list", "schedule.create", "schedule.update", "schedule.delete", "schedule.run", "schedule.runs", "inbox.list", "inbox.delete"].map(operation => [operation, {
|
|
52
|
+
execute: (context, input) => this.rpc.call("schedule.operation", {
|
|
53
|
+
serviceInstanceId: context.serviceInstanceId, operation, context, input, inspect: false,
|
|
54
|
+
}),
|
|
55
|
+
...(["schedule.create", "schedule.update", "schedule.delete", "schedule.run", "inbox.delete"].includes(operation) ? {
|
|
56
|
+
inspect: (context, input) => this.rpc.call("schedule.operation", {
|
|
57
|
+
serviceInstanceId: context.serviceInstanceId, operation, context, input, inspect: true,
|
|
58
|
+
}),
|
|
59
|
+
} : {}),
|
|
60
|
+
}])),
|
|
61
|
+
...Object.fromEntries(["agent.config", "agent.configure", "agent.identity", "agent.greeting", "agent.files", "agent.file", "agent.write-file", "agent.tools"].map(operation => [operation, {
|
|
62
|
+
execute: (context, input) => this.rpc.call("agent.operation", {
|
|
63
|
+
serviceInstanceId: context.serviceInstanceId, operation, context, input, inspect: false,
|
|
64
|
+
}),
|
|
65
|
+
...(["agent.configure", "agent.identity", "agent.write-file"].includes(operation) ? {
|
|
66
|
+
inspect: (context, input) => this.rpc.call("agent.operation", {
|
|
67
|
+
serviceInstanceId: context.serviceInstanceId, operation, context, input, inspect: true,
|
|
68
|
+
}),
|
|
69
|
+
} : {}),
|
|
70
|
+
}])),
|
|
71
|
+
"speech.config": { execute: () => this.speechConfig() },
|
|
72
|
+
"speech.speak": { execute: async (_context, input) => {
|
|
73
|
+
const text = input.text.trim();
|
|
74
|
+
if (!text)
|
|
75
|
+
throw new ChannelError(400, "TTS_INPUT_INVALID", "朗读正文为空");
|
|
76
|
+
if ([...text].length > MAX_SPEECH_TEXT_LENGTH)
|
|
77
|
+
throw new ChannelError(400, "TTS_INPUT_TOO_LONG", "朗读正文超过上限");
|
|
78
|
+
return this.speak(text);
|
|
79
|
+
} },
|
|
80
|
+
"talk.config": { execute: async () => ({ config: { talk: await this.speechConfig() } }) },
|
|
81
|
+
"talk.speak": { execute: async (_context, input) => {
|
|
82
|
+
const text = input.text.trim();
|
|
83
|
+
if (!text)
|
|
84
|
+
throw new ChannelError(400, "TTS_INPUT_INVALID", "播报正文为空");
|
|
85
|
+
// 超过宿主的合成上限时由 Native Talk 沿原路径完整播报,不截断答复。
|
|
86
|
+
if ([...text].length > MAX_SPEECH_TEXT_LENGTH) {
|
|
87
|
+
throw new ChannelError(503, "TTS_INPUT_TOO_LONG", "宿主语音合成无法处理这段长度的正文");
|
|
88
|
+
}
|
|
89
|
+
return this.speak(text);
|
|
90
|
+
} },
|
|
91
|
+
} };
|
|
92
|
+
descriptor = { id: "hermes", name: "Platform", version: "0.22.5", adapter: { id: "platform", version: "0.2.0-beta.1" }, eventFormats: ["canonical-v1"], capabilities: [...RUNTIME_CAPABILITIES, "tool.presentation-v1"] };
|
|
14
93
|
runChanged;
|
|
15
94
|
reportRunChangeError;
|
|
16
95
|
runChanges = new Map();
|
|
17
96
|
closed = false;
|
|
18
97
|
publisher;
|
|
19
98
|
recovery;
|
|
99
|
+
deviceTools;
|
|
100
|
+
bindDeviceRequests(devices) {
|
|
101
|
+
if (!this.store || this.deviceTools)
|
|
102
|
+
throw new HermesError("DEVICE_PORT_UNAVAILABLE");
|
|
103
|
+
this.deviceTools = new HostedDeviceTools(this.rpc, this.store);
|
|
104
|
+
this.deviceTools.bind(devices);
|
|
105
|
+
}
|
|
106
|
+
requestDevice(params, signal) {
|
|
107
|
+
if (typeof params.runId === "string")
|
|
108
|
+
this.publisher?.flush(params.runId);
|
|
109
|
+
if (!this.deviceTools)
|
|
110
|
+
throw new HermesError("DEVICE_PORT_UNAVAILABLE");
|
|
111
|
+
return this.deviceTools.request(params, signal);
|
|
112
|
+
}
|
|
20
113
|
runtimeInterface = {};
|
|
21
114
|
media;
|
|
22
115
|
artifacts;
|
|
23
116
|
delivery;
|
|
24
|
-
|
|
117
|
+
profileMedia = new Map();
|
|
118
|
+
constructor(rpc, store, facilities = {}, mediaEnvironment) {
|
|
25
119
|
this.rpc = rpc;
|
|
26
120
|
this.store = store;
|
|
27
121
|
this.facilities = facilities;
|
|
122
|
+
this.mediaEnvironment = mediaEnvironment;
|
|
28
123
|
if (store)
|
|
29
124
|
this.publisher = new HostedStreamPublisher(store);
|
|
30
125
|
this.recovery = new HostedRecoveryPort(rpc, store);
|
|
31
|
-
if (
|
|
32
|
-
this.media = new HostedMediaInput(
|
|
33
|
-
this.artifacts = new HostedArtifacts(store,
|
|
34
|
-
this.delivery = new HostedDeliveryObservations(store,
|
|
126
|
+
if (mediaEnvironment && store) {
|
|
127
|
+
this.media = new HostedMediaInput(mediaEnvironment, store.serverInstanceId);
|
|
128
|
+
this.artifacts = new HostedArtifacts(store, mediaEnvironment);
|
|
129
|
+
this.delivery = new HostedDeliveryObservations(store, mediaEnvironment);
|
|
35
130
|
}
|
|
36
131
|
}
|
|
132
|
+
async mediaFor(agentId) {
|
|
133
|
+
if (!this.store || !this.mediaEnvironment || !this.media || !this.artifacts || !this.delivery)
|
|
134
|
+
throw new HermesError("HOST_MEDIA_UNAVAILABLE");
|
|
135
|
+
if (agentId === "hermes")
|
|
136
|
+
return { input: this.media, artifacts: this.artifacts, delivery: this.delivery };
|
|
137
|
+
// 私有、已认证宿主端口确认原Agent的Profile与数据根;客户端路径不能参与选择。
|
|
138
|
+
const scope = await this.rpc.call("agent.scope", { serviceInstanceId: this.store.serverInstanceId, agentId });
|
|
139
|
+
if (scope.agentId !== agentId || typeof scope.profileRoot !== "string" || typeof scope.dataDir !== "string"
|
|
140
|
+
|| !path.isAbsolute(scope.profileRoot) || !path.isAbsolute(scope.dataDir)
|
|
141
|
+
|| fs.realpathSync(scope.profileRoot) !== scope.profileRoot || fs.realpathSync(scope.dataDir) !== scope.dataDir)
|
|
142
|
+
throw new HermesError("HOST_MEDIA_SCOPE_INVALID");
|
|
143
|
+
const key = JSON.stringify([scope.profileRoot, scope.dataDir]);
|
|
144
|
+
const cached = this.profileMedia.get(agentId);
|
|
145
|
+
if (cached?.key === key)
|
|
146
|
+
return cached;
|
|
147
|
+
cached?.delivery.close();
|
|
148
|
+
const environment = { ...this.mediaEnvironment, profileRoot: scope.profileRoot, dataDir: scope.dataDir };
|
|
149
|
+
const services = { key, input: new HostedMediaInput(environment, this.store.serverInstanceId),
|
|
150
|
+
artifacts: new HostedArtifacts(this.store, environment), delivery: new HostedDeliveryObservations(this.store, environment) };
|
|
151
|
+
this.profileMedia.set(agentId, services);
|
|
152
|
+
return services;
|
|
153
|
+
}
|
|
37
154
|
async describe() {
|
|
38
155
|
const reply = await this.rpc.call("describe", { serviceInstanceId: this.store?.serverInstanceId });
|
|
39
156
|
const d = object(reply.backend);
|
|
40
157
|
if (typeof d.id !== "string" || typeof d.name !== "string" || typeof d.version !== "string" || typeof object(d.adapter).id !== "string" || !Array.isArray(d.capabilities) || !RUNTIME_CAPABILITIES.every(c => d.capabilities.includes(c)))
|
|
41
158
|
throw new HermesError("HOST_DESCRIPTOR_INVALID");
|
|
42
|
-
this.descriptor = d;
|
|
159
|
+
this.descriptor = { ...d, capabilities: [...new Set([...d.capabilities, "tool.presentation-v1", ...(Reflect.get(Kit, "BACKEND_OPERATIONS_V1") === "backend.operations-v1" ? ["backend.operations-v1", ...(reply.agentManagement === true ? ["agent.config", "agent.files", "tools.catalog", "skills.catalog", "agents.greeting"] : []), ...(reply.scheduledTasks === true ? ["cron", "cron.catalog-v1", "inbox"] : []), ...(reply.slashCommands === true ? ["commands.catalog", "commands.execute-v1"] : [])] : [])])] };
|
|
160
|
+
if (this.descriptor.capabilities.includes("backend.operations-v1") && this.descriptor.capabilities.includes("tts")) {
|
|
161
|
+
this.descriptor.capabilities.push("talk");
|
|
162
|
+
}
|
|
163
|
+
this.descriptor.capabilities = [...new Set([...this.descriptor.capabilities.filter(c => !c.startsWith("device.")),
|
|
164
|
+
...(reply.deviceTools === true ? ["device.health", "device.calendar", "device.location"] : [])])];
|
|
43
165
|
this.runtimeInterface = object(reply.runtimeInterface);
|
|
44
166
|
}
|
|
167
|
+
slashCommand(context, input) {
|
|
168
|
+
return this.rpc.call("commands.execute", { serviceInstanceId: context.serviceInstanceId,
|
|
169
|
+
agentId: context.agentId, sessionKey: context.sessionKey, commandId: context.commandId, text: input.text }, 120000);
|
|
170
|
+
}
|
|
171
|
+
scheduledCatalog(operation, input) {
|
|
172
|
+
if (!["schedule.blueprints", "schedule.preview", "schedule.channels"].includes(operation)
|
|
173
|
+
|| !this.descriptor.capabilities.includes("cron.catalog-v1"))
|
|
174
|
+
throw new HermesError("SCHEDULE_UNAVAILABLE");
|
|
175
|
+
return this.rpc.call("schedule.operation", { serviceInstanceId: this.store?.serverInstanceId, operation,
|
|
176
|
+
context: { serviceInstanceId: this.store?.serverInstanceId }, input, inspect: false });
|
|
177
|
+
}
|
|
45
178
|
async resolveCommand(command) {
|
|
179
|
+
if (Object.hasOwn(command.sessionOptions ?? {}, "commandContext"))
|
|
180
|
+
throw new ChannelError(422, "COMMAND_CONTEXT_INVALID", "命令展示上下文必须由原生解析产生");
|
|
181
|
+
if (this.descriptor.capabilities.includes("commands.execute-v1") && command.text.trimStart().startsWith("/")) {
|
|
182
|
+
const prepared = await this.rpc.call("commands.prepare", {
|
|
183
|
+
serviceInstanceId: this.store?.serverInstanceId, agentId: command.agentId, sessionKey: command.sessionKey,
|
|
184
|
+
text: command.text, clientRequestId: command.clientRequestId,
|
|
185
|
+
});
|
|
186
|
+
if (prepared.allowed !== true || prepared.kind !== "run" || typeof prepared.message !== "string" || !prepared.message.trim()
|
|
187
|
+
|| prepared.display !== command.text)
|
|
188
|
+
throw new ChannelError(422, typeof prepared.reason === "string" ? prepared.reason : "SLASH_COMMAND_UNSUPPORTED", "当前命令不可作为对话执行");
|
|
189
|
+
command = { ...command, text: prepared.message, sessionOptions: { ...command.sessionOptions,
|
|
190
|
+
commandContext: { version: 1, text: command.text } } };
|
|
191
|
+
}
|
|
192
|
+
if (Object.hasOwn(command.sessionOptions ?? {}, "replyContext") && !validReplyContext(command.sessionOptions.replyContext)) {
|
|
193
|
+
throw new ChannelError(422, "REPLY_CONTEXT_INVALID", "引用上下文无效,请重新选择消息");
|
|
194
|
+
}
|
|
46
195
|
if (command.attachments.length && !this.media)
|
|
47
196
|
throw new ChannelError(400, "UNSUPPORTED_MEDIA", "当前插件尚未开放原生媒体输入");
|
|
48
197
|
const decision = await this.rpc.call("validate", { serviceInstanceId: this.store?.serverInstanceId, sessionKey: command.sessionKey, agentId: command.agentId, sessionOptions: command.sessionOptions, clientRequestId: command.clientRequestId, ...(command.attachments.length ? { attachmentCount: command.attachments.length } : {}) });
|
|
49
198
|
if (decision.allowed !== true)
|
|
50
199
|
throw new ChannelError([400, 403, 404, 409, 422, 503].includes(Number(decision.status)) ? Number(decision.status) : 409, typeof decision.reason === "string" ? decision.reason : "HOST_INPUT_REFUSED", "宿主当前不接受该会话的新输入,请检查迁移或插件状态");
|
|
51
|
-
return
|
|
200
|
+
return command.attachments.length ? (await this.mediaFor(command.agentId)).input.prepare(command, decision.mediaPolicy) : command;
|
|
201
|
+
}
|
|
202
|
+
async validateCommandReplay(command) {
|
|
203
|
+
if (command.attachments.length)
|
|
204
|
+
await (await this.mediaFor(command.agentId)).input.validateReplay(command);
|
|
52
205
|
}
|
|
53
206
|
async operation(method, run) {
|
|
54
|
-
|
|
207
|
+
if (run.origin === "observed" && run.sourceKind === "session" && run.runId.startsWith("continuation:")) {
|
|
208
|
+
if (method !== "inspect")
|
|
209
|
+
return { state: "unknown", reason: "CONTINUATION_READ_ONLY" };
|
|
210
|
+
const reply = await this.rpc.call("continuation.inspect", { serviceInstanceId: this.store?.serverInstanceId, runId: run.runId, agentId: run.agentId });
|
|
211
|
+
const inspection = object(reply.inspection);
|
|
212
|
+
if (!["running", "completed", "failed", "cancelled", "unknown"].includes(String(inspection.state)))
|
|
213
|
+
throw new HermesError("HOST_INSPECTION_INVALID");
|
|
214
|
+
return inspection;
|
|
215
|
+
}
|
|
216
|
+
if (run.origin === "observed" && run.sourceKind === "subagent") {
|
|
217
|
+
if (method !== "inspect")
|
|
218
|
+
return { state: "unknown", reason: "SUBAGENT_READ_ONLY" };
|
|
219
|
+
const reply = await this.rpc.call("subagent.inspect", { serviceInstanceId: this.store?.serverInstanceId, runId: run.runId, agentId: run.agentId });
|
|
220
|
+
const inspection = object(reply.inspection);
|
|
221
|
+
if (!["running", "completed", "failed", "cancelled", "unknown"].includes(String(inspection.state)))
|
|
222
|
+
throw new HermesError("HOST_INSPECTION_INVALID");
|
|
223
|
+
return inspection;
|
|
224
|
+
}
|
|
225
|
+
if (run.origin === "observed" && run.sourceKind === "cron") {
|
|
226
|
+
if (method !== "inspect")
|
|
227
|
+
return { state: "unknown", reason: "SCHEDULE_RUN_READ_ONLY" };
|
|
228
|
+
const reply = await this.rpc.call("schedule.inspect", { serviceInstanceId: this.store?.serverInstanceId, runId: run.runId, agentId: run.agentId });
|
|
229
|
+
const inspection = object(reply.inspection);
|
|
230
|
+
if (!["running", "completed", "failed", "unknown"].includes(String(inspection.state)))
|
|
231
|
+
throw new HermesError("HOST_INSPECTION_INVALID");
|
|
232
|
+
return inspection;
|
|
233
|
+
}
|
|
234
|
+
const media = method === "execute" && run.attachments.length ? await (await this.mediaFor(run.agentId)).input.execution(run) : undefined;
|
|
55
235
|
const response = await this.rpc.call(method, { serviceInstanceId: this.store?.serverInstanceId, run, ...(media ? { media } : {}) });
|
|
56
236
|
const inspection = object(response.inspection);
|
|
57
237
|
if (!["running", "completed", "failed", "cancelled", "unknown"].includes(String(inspection.state)))
|
|
@@ -107,26 +287,66 @@ export class HostedBackendAdapter {
|
|
|
107
287
|
return { accepted: true };
|
|
108
288
|
}
|
|
109
289
|
async publish(params) {
|
|
110
|
-
if (!this.store || params.serviceInstanceId !== this.store.serverInstanceId || typeof params.runId !== "string" || !this.store.run(params.runId) || !Array.isArray(params.updates))
|
|
290
|
+
if (this.closed || !this.store || params.serviceInstanceId !== this.store.serverInstanceId || typeof params.runId !== "string" || !this.store.run(params.runId) || !Array.isArray(params.updates))
|
|
111
291
|
throw new HermesError("HOST_PUBLISH_SCOPE_INVALID");
|
|
112
|
-
|
|
292
|
+
if (params.child !== undefined) {
|
|
293
|
+
this.publisher.flush(params.runId);
|
|
294
|
+
return publishSubagent(this.store, params.runId, params);
|
|
295
|
+
}
|
|
296
|
+
if (params.continuation !== undefined) {
|
|
297
|
+
this.publisher.flush(params.runId);
|
|
298
|
+
return publishContinuation(this.store, params.runId, params);
|
|
299
|
+
}
|
|
300
|
+
return this.publisher.publishBuffered(params.runId, params.updates, params.source);
|
|
301
|
+
}
|
|
302
|
+
flushRun(runId) { this.publisher?.flush(runId); }
|
|
303
|
+
async publishScheduled(params) {
|
|
304
|
+
const fields = ["serviceInstanceId", "runId", "sessionKey", "jobId", "executionId", "deviceId", "text"];
|
|
305
|
+
if (this.closed || !this.store || params.serviceInstanceId !== this.store.serverInstanceId
|
|
306
|
+
|| fields.some(k => typeof params[k] !== "string" || !params[k] || String(params[k]).length > (k === "text" ? 256 * 1024 : 1024))
|
|
307
|
+
|| !String(params.runId).startsWith("scheduled:") || !String(params.sessionKey).startsWith("scheduled:"))
|
|
308
|
+
throw new HermesError("SCHEDULE_DELIVERY_SCOPE_INVALID");
|
|
309
|
+
const agentId = typeof params.agentId === "string" && params.agentId ? params.agentId : "hermes";
|
|
310
|
+
const proof = await this.rpc.call("schedule.delivery-check", { ...Object.fromEntries(fields.map(k => [k, params[k]])), agentId });
|
|
311
|
+
if (this.closed || proof.allowed !== true)
|
|
312
|
+
throw new HermesError("SCHEDULE_DELIVERY_SCOPE_INVALID");
|
|
313
|
+
const runId = params.runId;
|
|
314
|
+
const run = this.store.observeRun({ runId, sessionKey: params.sessionKey, agentId, deviceIds: [params.deviceId], sourceKind: "cron",
|
|
315
|
+
...(typeof params.occurredAt === "number" ? { occurredAt: params.occurredAt } : {}) });
|
|
316
|
+
if (!run)
|
|
317
|
+
throw new HermesError("SCHEDULE_DELIVERY_SCOPE_INVALID");
|
|
318
|
+
const result = this.publisher.publish(runId, [{ kind: "text", id: "answer:" + runId, channel: "answer", operation: "replace", text: params.text }], { id: "scheduled:" + params.executionId, sequence: 1 });
|
|
319
|
+
if (this.runChanged && !["completed", "failed", "cancelled"].includes(run.phase))
|
|
320
|
+
this.notifyRunChanged({ serviceInstanceId: this.store.serverInstanceId, runId });
|
|
321
|
+
return result;
|
|
113
322
|
}
|
|
114
323
|
lookupControl(id) { return this.recovery.lookup(id); }
|
|
115
|
-
async registerMedia(params, signal) { if (!
|
|
116
|
-
throw new HermesError("
|
|
117
|
-
async observeMedia(params, signal) { if (!
|
|
118
|
-
throw new HermesError("
|
|
324
|
+
async registerMedia(params, signal) { const run = this.store?.run(String(object(params.source).runId)); if (!run)
|
|
325
|
+
throw new HermesError("HOST_MEDIA_SCOPE_INVALID"); return (await this.mediaFor(run.agentId)).artifacts.register(params, signal); }
|
|
326
|
+
async observeMedia(params, signal) { const run = this.store?.run(String(object(params.source).runId)); if (!run)
|
|
327
|
+
throw new HermesError("HOST_MEDIA_SCOPE_INVALID"); return (await this.mediaFor(run.agentId)).delivery.observe(params, signal); }
|
|
119
328
|
respondControl(id, response) { return this.recovery.respond(id, response); }
|
|
120
329
|
async historyMedia(row, sessionKey) {
|
|
121
|
-
const { _inputMedia, _outputMedia, ...publicRow } = row;
|
|
330
|
+
const { _inputMedia, _outputMedia, _replyContext, ...publicRow } = row;
|
|
122
331
|
row = publicRow;
|
|
123
|
-
if (!this.
|
|
332
|
+
if (!this.store || typeof row.id !== "string" || !row.id || typeof row.runId !== "string" || typeof row.clientRequestId !== "string")
|
|
124
333
|
return row;
|
|
334
|
+
const messageId = row.id;
|
|
125
335
|
const run = this.store.run(row.runId);
|
|
126
336
|
if (!run || run.sessionKey !== sessionKey || run.clientRequestId !== row.clientRequestId)
|
|
127
337
|
return row;
|
|
338
|
+
const reply = object(_replyContext), context = run.sessionOptions?.replyContext;
|
|
339
|
+
const replyExact = row.role === "user" && validReplyContext(context) && reply.version === 1
|
|
340
|
+
&& reply.messageId === row.id && reply.runId === run.runId && reply.clientRequestId === run.clientRequestId
|
|
341
|
+
&& reply.text === run.text && reply.rendered === row.text && row.content === row.text
|
|
342
|
+
&& REPLY_FIELDS.every(key => object(reply.context)[key] === context[key]);
|
|
343
|
+
const displayText = replyExact ? replyPresentation(run.text, context) : undefined;
|
|
344
|
+
if (displayText !== undefined)
|
|
345
|
+
row = { ...row, text: displayText, content: displayText };
|
|
346
|
+
if (!this.media || Array.isArray(row.images) && row.images.length)
|
|
347
|
+
return row;
|
|
128
348
|
if (row.role === "assistant") {
|
|
129
|
-
const images = this.artifacts
|
|
349
|
+
const images = (await this.mediaFor(run.agentId)).artifacts.historyImages(run.runId, messageId);
|
|
130
350
|
if (!images.length)
|
|
131
351
|
return row;
|
|
132
352
|
const proof = object(_outputMedia);
|
|
@@ -139,18 +359,18 @@ export class HostedBackendAdapter {
|
|
|
139
359
|
}
|
|
140
360
|
if (row.role !== "user")
|
|
141
361
|
return row;
|
|
142
|
-
const { images, sha256 } = await this.
|
|
362
|
+
const { images, sha256 } = await (await this.mediaFor(run.agentId)).input.historyImages(run);
|
|
143
363
|
if (!images.length)
|
|
144
364
|
return row;
|
|
145
365
|
const proof = object(_inputMedia);
|
|
146
366
|
const exact = proof.version === 1 && proof.messageId === row.id && proof.runId === run.runId && proof.clientRequestId === run.clientRequestId
|
|
147
|
-
&& proof.text === run.text && proof.rendered ===
|
|
367
|
+
&& proof.text === run.text && proof.rendered === publicRow.text && publicRow.content === publicRow.text && Array.isArray(proof.sha256)
|
|
148
368
|
&& proof.sha256.length === sha256.length && proof.sha256.every((digest, index) => digest === sha256[index]);
|
|
149
|
-
return { ...row, images, ...(exact ? { text: run.text, content: run.text } : {}) };
|
|
369
|
+
return { ...row, images, ...(exact ? { text: displayText ?? run.text, content: displayText ?? run.text } : {}) };
|
|
150
370
|
}
|
|
151
|
-
async snapshot(sessionKey, limit = 200) { const result = (await this.rpc.call("snapshot", { sessionKey, limit })).snapshot; return { ...result, transcript: await Promise.all(result.transcript.map(row => this.historyMedia(row, sessionKey))) }; }
|
|
152
|
-
async historyPage(query) { const page = (await this.rpc.call("history", { ...query })).page; return { ...page, messages: await Promise.all(page.messages.map(row => this.historyMedia(row, query.sessionKey))) }; }
|
|
153
|
-
async historyMessage(sessionKey, messageId) { const row = (await this.rpc.call("history.message", { sessionKey, messageId })).message; return row ? this.historyMedia(row, sessionKey) : null; }
|
|
371
|
+
async snapshot(sessionKey, limit = 200) { const result = (await this.rpc.call("snapshot", { sessionKey, limit })).snapshot; return { ...result, transcript: await Promise.all(presentHistory(result.transcript).map(row => this.historyMedia(row, sessionKey))) }; }
|
|
372
|
+
async historyPage(query) { const page = (await this.rpc.call("history", { ...query })).page; return { ...page, messages: await Promise.all(presentHistory(page.messages).map(row => this.historyMedia(row, query.sessionKey))) }; }
|
|
373
|
+
async historyMessage(sessionKey, messageId) { const row = (await this.rpc.call("history.message", { sessionKey, messageId })).message; return row ? this.historyMedia(presentHistory([row])[0], sessionKey) : null; }
|
|
154
374
|
async setSessionTitle(sessionKey, title) { return (await this.rpc.call("session.title", { sessionKey, title })); }
|
|
155
375
|
async setSessionPinned(sessionKey, pinned) { return (await this.rpc.call("session.pin", { sessionKey, pinned })); }
|
|
156
376
|
async listSessions() { return (await this.rpc.call("sessions", {})).sessions; }
|
|
@@ -164,5 +384,53 @@ export class HostedBackendAdapter {
|
|
|
164
384
|
async mutateAgentDefaults(agentId, change) { return new HostedSettings(this.rpc, this.store?.serverInstanceId).mutateDefaults(agentId, change); }
|
|
165
385
|
async inspectAgentDefaultsMutation(agentId, commandId) { return new HostedSettings(this.rpc, this.store?.serverInstanceId).inspectDefaults(agentId, commandId); }
|
|
166
386
|
async healthDetails() { return { hostMode: "platform-plugin", runtimeInterface: this.runtimeInterface, facilities: this.facilities, diagnostics: await new HostedSettings(this.rpc, this.store?.serverInstanceId).diagnostics() }; }
|
|
167
|
-
|
|
387
|
+
// 消息朗读只读宿主TTS配置并做本地合成;Node只保留受控字段,不转发host异常或音频路径。
|
|
388
|
+
async speechConfig() {
|
|
389
|
+
let reply;
|
|
390
|
+
try {
|
|
391
|
+
reply = await this.rpc.call("speech.config", { serviceInstanceId: this.store?.serverInstanceId }, 15000);
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
395
|
+
}
|
|
396
|
+
if (reply.error !== undefined)
|
|
397
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
398
|
+
const value = reply.maxTextLength;
|
|
399
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
|
|
400
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
401
|
+
return { maxTextLength: Math.min(value, MAX_SPEECH_TEXT_LENGTH) };
|
|
402
|
+
}
|
|
403
|
+
async speak(text) {
|
|
404
|
+
let reply;
|
|
405
|
+
try {
|
|
406
|
+
reply = await this.rpc.call("speech.speak", { serviceInstanceId: this.store?.serverInstanceId, text }, 110000);
|
|
407
|
+
}
|
|
408
|
+
catch {
|
|
409
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
410
|
+
}
|
|
411
|
+
if (reply.error !== undefined)
|
|
412
|
+
throw new HermesError(typeof reply.error === "string" && SPEECH_ERROR_CODES.has(reply.error) ? reply.error : "TTS_FAILED");
|
|
413
|
+
const { audioBase64, provider, outputFormat, mimeType } = reply;
|
|
414
|
+
if (typeof audioBase64 !== "string" || !audioBase64 || audioBase64.length > MAX_SPEECH_AUDIO_BASE64_LENGTH
|
|
415
|
+
|| !speechBase64(audioBase64) || !speechToken(provider) || !speechToken(outputFormat) || !speechMime(mimeType)) {
|
|
416
|
+
throw new HermesError("TTS_FAILED");
|
|
417
|
+
}
|
|
418
|
+
return { audioBase64, provider, outputFormat, mimeType };
|
|
419
|
+
}
|
|
420
|
+
async close() {
|
|
421
|
+
this.closed = true;
|
|
422
|
+
this.deviceTools?.close();
|
|
423
|
+
this.runChanged = undefined;
|
|
424
|
+
this.runChanges.clear();
|
|
425
|
+
try {
|
|
426
|
+
this.publisher?.close();
|
|
427
|
+
}
|
|
428
|
+
finally {
|
|
429
|
+
this.delivery?.close();
|
|
430
|
+
for (const services of this.profileMedia.values())
|
|
431
|
+
services.delivery.close();
|
|
432
|
+
this.profileMedia.clear();
|
|
433
|
+
this.rpc.close?.();
|
|
434
|
+
}
|
|
435
|
+
}
|
|
168
436
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { normalizedUpdate, persistedSourceSequences } from "./hosted-stream.js";
|
|
3
|
+
import { HermesError, object } from "./service-errors.js";
|
|
4
|
+
/** 后台正常父回复是同一母会话的新观察运行,不能改写已经结束的原答复。 */
|
|
5
|
+
export function publishContinuation(store, rootId, params) {
|
|
6
|
+
const root = store.run(rootId), item = object(params.continuation), source = object(params.source);
|
|
7
|
+
const invalid = () => { throw new HermesError("HOST_CONTINUATION_SCOPE_INVALID"); };
|
|
8
|
+
if (!root || root.parentRunId || root.sourceKind !== "session"
|
|
9
|
+
|| Object.keys(item).some(k => !["runId", "phase"].includes(k))
|
|
10
|
+
|| typeof item.runId !== "string" || !item.runId.startsWith("continuation:") || item.runId.length > 1024
|
|
11
|
+
|| !["running", "completed", "failed", "cancelled", "reconciling"].includes(String(item.phase))
|
|
12
|
+
|| Object.keys(source).some(k => !["id", "sequence"].includes(k))
|
|
13
|
+
|| typeof source.id !== "string" || !source.id || source.id.length > 256
|
|
14
|
+
|| !Number.isSafeInteger(source.sequence) || Number(source.sequence) < 1 || !Array.isArray(params.updates))
|
|
15
|
+
return invalid();
|
|
16
|
+
const existing = store.run(item.runId);
|
|
17
|
+
if (existing && (existing.origin !== "observed" || existing.sourceKind !== "session" || existing.parentRunId
|
|
18
|
+
|| existing.rootRunId !== rootId || existing.sessionKey !== root.sessionKey || existing.agentId !== root.agentId))
|
|
19
|
+
return invalid();
|
|
20
|
+
const updates = params.updates.map(normalizedUpdate);
|
|
21
|
+
if (updates.some(u => !["text", "tool", "activity", "session"].includes(String(u.kind))))
|
|
22
|
+
return invalid();
|
|
23
|
+
const events = store.eventsForRun(item.runId);
|
|
24
|
+
const positions = events.flatMap(e => persistedSourceSequences(e.payload, source.id));
|
|
25
|
+
if (!positions.includes(Number(source.sequence)) && positions.some(n => n > Number(source.sequence)))
|
|
26
|
+
throw new HermesError("HOST_SOURCE_OUT_OF_ORDER");
|
|
27
|
+
const run = store.observeRun({ runId: item.runId, sessionKey: root.sessionKey, agentId: root.agentId, sourceKind: "session", rootRunId: rootId,
|
|
28
|
+
deviceIds: root.deliveryDeviceIds ?? [root.deviceId] });
|
|
29
|
+
if (!run)
|
|
30
|
+
return invalid();
|
|
31
|
+
const phase = String(item.phase), terminal = ["completed", "failed", "cancelled"].includes(phase);
|
|
32
|
+
const result = store.appendRunEventWithOutcome(run.runId, terminal ? "run." + phase : "host.update", {
|
|
33
|
+
format: "canonical-v1", source, updates: [...updates, { kind: "run", phase, data: { traceComplete: false,
|
|
34
|
+
...(phase === "reconciling" ? { reason: "background_reply_owner_unknown" } : {}) } }]
|
|
35
|
+
}, { appendId: "continuation:" + createHash("sha256").update(JSON.stringify([run.runId, source])).digest("hex") });
|
|
36
|
+
if (result.outcome === "conflict")
|
|
37
|
+
throw new HermesError("HOST_SOURCE_CONFLICT");
|
|
38
|
+
if (result.outcome === "rejected")
|
|
39
|
+
throw new HermesError("HOST_DELIVERY_NOT_COMMITTED");
|
|
40
|
+
return { durable: true, duplicate: result.outcome === "replayed" };
|
|
41
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { object } from "./service-errors.js";
|
|
5
|
+
const contract = JSON.parse(fs.readFileSync(new URL("./device-tools-v1.json", import.meta.url), "utf8"));
|
|
6
|
+
const operations = new Set(Object.keys(contract.operations));
|
|
7
|
+
const failure = (code) => ({ ok: false, error: { code,
|
|
8
|
+
message: code === "DEVICE_RESULT_UNKNOWN" ? "设备操作结果未知,请先核实,不要自动再次写入" : "原手机请求当前不可用" } });
|
|
9
|
+
const terminal = (phase) => ["completed", "failed", "cancelled", "cancelPending"].includes(phase);
|
|
10
|
+
/** 仅适配宿主工具身份;等待、持久请求和结果收口均由同一Kit协调器拥有。 */
|
|
11
|
+
export class HostedDeviceTools {
|
|
12
|
+
rpc;
|
|
13
|
+
store;
|
|
14
|
+
devices;
|
|
15
|
+
closed = false;
|
|
16
|
+
calls = new Map();
|
|
17
|
+
constructor(rpc, store) {
|
|
18
|
+
this.rpc = rpc;
|
|
19
|
+
this.store = store;
|
|
20
|
+
}
|
|
21
|
+
bind(devices) {
|
|
22
|
+
if (this.devices)
|
|
23
|
+
throw new Error("DEVICE_PORT_ALREADY_BOUND");
|
|
24
|
+
this.devices = devices;
|
|
25
|
+
const respond = devices.respond.bind(devices);
|
|
26
|
+
// 精确registry版本在这里补充原设备归属,完成仍委托原协调器。
|
|
27
|
+
devices.respond = (id, body) => {
|
|
28
|
+
const request = this.store.deviceRequest(typeof body.tool === "string" ? body.tool : "", id);
|
|
29
|
+
if (!request || typeof body.deviceId !== "string" || body.deviceId.toUpperCase() !== request.deviceId)
|
|
30
|
+
return { status: 403, body: { code: "DEVICE_SCOPE_MISMATCH" } };
|
|
31
|
+
return respond(id, body);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
async request(params, signal) {
|
|
35
|
+
const source = object(params.source), args = object(params.arguments), operation = params.operation;
|
|
36
|
+
const fields = ["serviceInstanceId", "profileRoot", "runId", "sessionKey", "nativeId", "inputId", "admissionId", "toolCallId"];
|
|
37
|
+
if (this.closed || !this.devices || signal.aborted || params.version !== 1 || typeof operation !== "string"
|
|
38
|
+
|| !operations.has(operation) || typeof params.scopeToken !== "string" || params.scopeToken.length !== 64
|
|
39
|
+
|| fields.some(key => typeof source[key] !== "string" || !source[key] || String(source[key]).length > 4096)
|
|
40
|
+
|| !Number.isSafeInteger(source.generation) || Number(source.generation) < 1
|
|
41
|
+
|| !Number.isSafeInteger(source.authorityEpoch) || Number(source.authorityEpoch) < 1
|
|
42
|
+
|| source.serviceInstanceId !== this.store.serverInstanceId
|
|
43
|
+
|| Object.keys(args).some(key => !Object.hasOwn(contract.operations[operation].parameters.properties, key))
|
|
44
|
+
|| Buffer.byteLength(JSON.stringify(args)) > 128 * 1024)
|
|
45
|
+
return failure("DEVICE_SOURCE_UNAVAILABLE");
|
|
46
|
+
const runId = source.runId, run = this.store.run(runId);
|
|
47
|
+
if (!run || run.origin === "observed" || run.sessionKey !== source.sessionKey || terminal(run.phase))
|
|
48
|
+
return failure("DEVICE_SOURCE_UNAVAILABLE");
|
|
49
|
+
const check = async () => {
|
|
50
|
+
const reply = await this.rpc.call("device.check", { source, scopeToken: params.scopeToken,
|
|
51
|
+
runId, serviceInstanceId: this.store.serverInstanceId });
|
|
52
|
+
return !this.closed && !signal.aborted && reply.allowed === true && !terminal(this.store.run(runId)?.phase ?? "completed");
|
|
53
|
+
};
|
|
54
|
+
try {
|
|
55
|
+
if (!await check())
|
|
56
|
+
return failure("DEVICE_SOURCE_UNAVAILABLE");
|
|
57
|
+
const kind = operation.split("-")[0];
|
|
58
|
+
const requestId = "device:" + createHash("sha256").update(JSON.stringify(fields.map(key => source[key])
|
|
59
|
+
.concat([source.generation, source.authorityEpoch]))).digest("hex");
|
|
60
|
+
const payload = { ...args, kind: operation };
|
|
61
|
+
const active = this.calls.get(requestId);
|
|
62
|
+
if (active)
|
|
63
|
+
return isDeepStrictEqual(active.payload, payload) ? await active.promise : failure("DEVICE_IDENTITY_CONFLICT");
|
|
64
|
+
// worker重建后原调用已失去本地等待;保留原请求,不重新发到手机。
|
|
65
|
+
if (this.store.deviceRequest(kind, requestId))
|
|
66
|
+
return failure("DEVICE_RESULT_UNKNOWN");
|
|
67
|
+
if (!this.store.deviceListenerCount(run.deviceId))
|
|
68
|
+
return failure("DEVICE_OFFLINE");
|
|
69
|
+
const promise = this.devices.request(run, { kind, requestId, payload, timeoutMs: 60_000 })
|
|
70
|
+
.then(async (outcome) => await check() ? outcome : failure("DEVICE_RESULT_UNKNOWN"))
|
|
71
|
+
.catch(error => failure(error instanceof Error && error.message === "DEVICE_BUSY" ? "DEVICE_BUSY" : "DEVICE_RESULT_UNKNOWN"));
|
|
72
|
+
this.calls.set(requestId, { payload, promise });
|
|
73
|
+
if (this.calls.size > 256)
|
|
74
|
+
this.calls.delete(this.calls.keys().next().value);
|
|
75
|
+
return await promise;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return failure("DEVICE_RESULT_UNKNOWN");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
close() { this.closed = true; this.calls.clear(); }
|
|
82
|
+
}
|