@lsamien/yaoyao 0.4.76 → 0.4.77
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 +5 -5
- package/build-info.json +18 -3
- package/desktop/main.mjs +6 -2
- package/dist/assets/{AboutDialog-fbm5CG09.js → AboutDialog-k7oUOua0.js} +2 -2
- package/dist/assets/AboutDialog-k7oUOua0.js.map +1 -0
- package/dist/assets/{BotAutomationsView-DPAAYyuy.js → BotAutomationsView-CUaMkVfT.js} +2 -2
- package/dist/assets/{BotAutomationsView-DPAAYyuy.js.map → BotAutomationsView-CUaMkVfT.js.map} +1 -1
- package/dist/assets/{BotPluginsDialog-MwGpwjgu.js → BotPluginsDialog-BqfqrWdq.js} +2 -2
- package/dist/assets/{BotPluginsDialog-MwGpwjgu.js.map → BotPluginsDialog-BqfqrWdq.js.map} +1 -1
- package/dist/assets/{BotSettingsDialog-DXtsSzi8.js → BotSettingsDialog-BfW0Jxhg.js} +4 -4
- package/dist/assets/{BotSettingsDialog-DXtsSzi8.js.map → BotSettingsDialog-BfW0Jxhg.js.map} +1 -1
- package/dist/assets/{ChatView-BNqHa6Ma.js → ChatView-CTWvNlNq.js} +2 -2
- package/dist/assets/{ChatView-BNqHa6Ma.js.map → ChatView-CTWvNlNq.js.map} +1 -1
- package/dist/assets/{ComputerPanel-B0QyKQkF.js → ComputerPanel-D_wWUzlj.js} +2 -2
- package/dist/assets/{ComputerPanel-B0QyKQkF.js.map → ComputerPanel-D_wWUzlj.js.map} +1 -1
- package/dist/assets/{ComputerViewerView-CaOkTXpc.js → ComputerViewerView-C2nS7MWX.js} +2 -2
- package/dist/assets/{ComputerViewerView-CaOkTXpc.js.map → ComputerViewerView-C2nS7MWX.js.map} +1 -1
- package/dist/assets/{ConversationsView-CYNc59hv.js → ConversationsView-D5KvMs7J.js} +2 -2
- package/dist/assets/{ConversationsView-CYNc59hv.js.map → ConversationsView-D5KvMs7J.js.map} +1 -1
- package/dist/assets/{FilesView-CluNyIk8.js → FilesView-xOEZGSrD.js} +2 -2
- package/dist/assets/{FilesView-CluNyIk8.js.map → FilesView-xOEZGSrD.js.map} +1 -1
- package/dist/assets/{FloatingResourceSearch-Bg5rUZMy.js → FloatingResourceSearch-D5XwWF0V.js} +2 -2
- package/dist/assets/{FloatingResourceSearch-Bg5rUZMy.js.map → FloatingResourceSearch-D5XwWF0V.js.map} +1 -1
- package/dist/assets/{HistoryView-DSbSDzsB.js → HistoryView-CnUN9Qik.js} +2 -2
- package/dist/assets/{HistoryView-DSbSDzsB.js.map → HistoryView-CnUN9Qik.js.map} +1 -1
- package/dist/assets/{KanbanView-D5AdRwqi.js → KanbanView-DXJCj1E6.js} +2 -2
- package/dist/assets/{KanbanView-D5AdRwqi.js.map → KanbanView-DXJCj1E6.js.map} +1 -1
- package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js → LocalVmSettingsPanel-8wF6wA3P.js} +2 -2
- package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js.map → LocalVmSettingsPanel-8wF6wA3P.js.map} +1 -1
- package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js → RunnerSettingsPanel-DDEMgUS9.js} +2 -2
- package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js.map → RunnerSettingsPanel-DDEMgUS9.js.map} +1 -1
- package/dist/assets/{StandaloneDialog-DdcL_wV2.js → StandaloneDialog-BN6RJ3uh.js} +2 -2
- package/dist/assets/{StandaloneDialog-DdcL_wV2.js.map → StandaloneDialog-BN6RJ3uh.js.map} +1 -1
- package/dist/assets/{UpdateCheckDialog-CJQezkXo.js → UpdateCheckDialog-CZ6NZSkP.js} +2 -2
- package/dist/assets/{UpdateCheckDialog-CJQezkXo.js.map → UpdateCheckDialog-CZ6NZSkP.js.map} +1 -1
- package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js → WorkspaceKnowledgePanel-BA7yVvWK.js} +2 -2
- package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js.map → WorkspaceKnowledgePanel-BA7yVvWK.js.map} +1 -1
- package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js → WorkspaceRoutinesPanel-DgCqaACO.js} +2 -2
- package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js.map → WorkspaceRoutinesPanel-DgCqaACO.js.map} +1 -1
- package/dist/assets/{WorkspaceShell-Bykfy3AR.js → WorkspaceShell-DQZKvx2p.js} +4 -4
- package/dist/assets/{WorkspaceShell-Bykfy3AR.js.map → WorkspaceShell-DQZKvx2p.js.map} +1 -1
- package/dist/assets/{WorkspaceView-Cco3Umfn.js → WorkspaceView-jMPyO8oT.js} +2 -2
- package/dist/assets/{WorkspaceView-Cco3Umfn.js.map → WorkspaceView-jMPyO8oT.js.map} +1 -1
- package/dist/assets/{docx-preview-C6qrP-g2.js → docx-preview-Ba7Ciq-i.js} +2 -2
- package/dist/assets/{docx-preview-C6qrP-g2.js.map → docx-preview-Ba7Ciq-i.js.map} +1 -1
- package/dist/assets/{index-CEqMqiJr.js → index-dvKMU4Xy.js} +3 -3
- package/dist/assets/{index-CEqMqiJr.js.map → index-dvKMU4Xy.js.map} +1 -1
- package/dist/assets/{pdf-G3DUsfMb.js → pdf-C3k8l1DI.js} +2 -2
- package/dist/assets/{pdf-G3DUsfMb.js.map → pdf-C3k8l1DI.js.map} +1 -1
- package/dist/assets/{sessionOwnership-DMfBRINe.js → sessionOwnership-HZsbONG-.js} +2 -2
- package/dist/assets/{sessionOwnership-DMfBRINe.js.map → sessionOwnership-HZsbONG-.js.map} +1 -1
- package/dist/assets/{viewModels-DfaKvI0x.js → viewModels-OLQqqyt3.js} +4 -4
- package/dist/assets/{viewModels-DfaKvI0x.js.map → viewModels-OLQqqyt3.js.map} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/runner/agent.js +13 -2
- package/dist-server/runner/hermes-bots-bridge/README.md +4 -2
- package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +21 -2
- package/dist-server/runner/hermes-bots-bridge/plugin.yaml +1 -1
- package/dist-server/runner/worker/gateway.js +52 -22
- package/dist-server/runner/worker/profileSession.js +2 -12
- package/dist-server/server/chatTranscriptApi.js +2 -2
- package/dist-server/server/desktopEnvironments.js +2 -2
- package/dist-server/server/hermesRuntimeEnvironment.js +14 -0
- package/dist-server/server/openVikingMemoryProvider.js +29 -10
- package/dist-server/server/openVikingService.js +44 -14
- package/dist-server/server/realtimeApi.js +11 -2
- package/dist-server/server/realtimeBroker.js +1 -1
- package/dist-server/server/realtimeReceipts.js +39 -8
- package/dist-server/server/runnerHub.js +3 -3
- package/dist-server/server/sessionStop.js +19 -0
- package/dist-server/server/taskCoordinator.js +3 -1
- package/dist-server/server/workspaceAssets.js +54 -11
- package/dist-server/server/workspaceEnvironment.js +1 -0
- package/dist-server/server/workspaceMemorySynthesis.js +5 -1
- package/dist-server/server/workspacePrompt.js +5 -1
- package/dist-server/server/workspaceRoutes.js +25 -20
- package/dist-server/server/workspaceRuntime.js +71 -6
- package/dist-server/server/workspaceScheduler.js +5 -1
- package/dist-server/server/workspaceStore.js +21 -4
- package/dist-server/server/workspaceSync.js +4 -1
- package/dist-server/shared/botEnvironment.js +3 -3
- package/package.json +5 -4
- package/release.json +3 -3
- package/dist/assets/AboutDialog-fbm5CG09.js.map +0 -1
package/dist/index.html
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
<link rel="apple-touch-icon" sizes="180x180" href="/icons/apple-touch-icon.png" />
|
|
10
10
|
<link rel="manifest" href="/manifest.webmanifest" />
|
|
11
11
|
<title>夭夭</title>
|
|
12
|
-
<script type="module" crossorigin src="/assets/index-
|
|
12
|
+
<script type="module" crossorigin src="/assets/index-dvKMU4Xy.js"></script>
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/_plugin-vue_export-helper-CscYwSBt.js">
|
|
14
14
|
<link rel="stylesheet" crossorigin href="/assets/index-g5POnMkp.css">
|
|
15
15
|
</head>
|
|
@@ -18,7 +18,7 @@ import { assertRunnerHermes } from './config.js';
|
|
|
18
18
|
import { RunnerBrowser } from './managedBrowser.js';
|
|
19
19
|
import { BrowserRuntimeError } from './browser/types.js';
|
|
20
20
|
import { LoopbackTransport, isLocalAuthorizationTarget } from '../server/loopbackAuthorization.js';
|
|
21
|
-
const commands = new Set(['session.create', 'session.resume', 'session.close', 'session.usage', 'session.interrupt', 'session.cwd.set', 'prompt.submit', 'session.steer', 'image.attach_bytes', 'file.attach', 'approval.respond', 'clarify.respond']);
|
|
21
|
+
const commands = new Set(['session.create', 'session.resume', 'session.close', 'session.usage', 'session.interrupt', 'session.active_list', 'session.cwd.set', 'prompt.submit', 'session.steer', 'image.attach_bytes', 'file.attach', 'approval.respond', 'clarify.respond']);
|
|
22
22
|
export class RunnerAgent {
|
|
23
23
|
config;
|
|
24
24
|
fetchImpl;
|
|
@@ -376,8 +376,19 @@ export class RunnerAgent {
|
|
|
376
376
|
const computerCommand = method === 'computer.invoke' || method === 'computer.transfer' || method === 'computer.complete';
|
|
377
377
|
if (!connection || (!commands.has(method) && !(computerCommand && connection.gateway instanceof ComputerGateway)) || !params || typeof params !== 'object')
|
|
378
378
|
throw new HttpError(403, '执行通道或命令无效', 'runner_command_forbidden');
|
|
379
|
-
if (connection.cleanupOnly && !['session.resume', 'session.interrupt', 'session.close'].includes(method))
|
|
379
|
+
if (connection.cleanupOnly && !['session.resume', 'session.interrupt', 'session.close', 'session.active_list'].includes(method))
|
|
380
380
|
throw new HttpError(403, '清理通道不允许执行新工作', 'runner_cleanup_forbidden');
|
|
381
|
+
if (method === 'session.active_list') {
|
|
382
|
+
const id = String(params.current_session_id ?? ''), profile = connection.sessions.get(id);
|
|
383
|
+
if (!profile || params.profile !== profile || Object.keys(params).some(key => !['profile', 'current_session_id'].includes(key)))
|
|
384
|
+
throw new HttpError(403, '停止状态查询不属于这个通道', 'runner_session_forbidden');
|
|
385
|
+
if (connection.gateway instanceof ComputerGateway)
|
|
386
|
+
throw new HttpError(409, '电脑通道使用独立停止确认', 'computer_method_unavailable');
|
|
387
|
+
const state = await connection.gateway.rpc(method, { profile, current_session_id: id });
|
|
388
|
+
if (!Array.isArray(state?.sessions))
|
|
389
|
+
throw new HttpError(502, 'Hermes 停止状态无效', 'session_stop_unconfirmed');
|
|
390
|
+
return { sessions: state.sessions.filter((item) => item.id === id).map((item) => ({ id: item.id, status: item.status })) };
|
|
391
|
+
}
|
|
381
392
|
if (method === 'session.create' || method === 'session.resume') {
|
|
382
393
|
if (!connection.cleanupOnly)
|
|
383
394
|
this.requireProfile(params.profile);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 夭夭 Bot 的 Hermes 工具桥
|
|
2
2
|
|
|
3
|
-
这是运行在 Hermes 内的用户插件,版本 1.
|
|
3
|
+
这是运行在 Hermes 内的用户插件,版本 1.3.1。它连接 Yaoyao 每轮授权的电脑、团队和应用工具。随附安装器还提供有备份的 Hermes Profile 模型兼容修复。
|
|
4
4
|
|
|
5
5
|
## Hermes 托管虚拟机会话
|
|
6
6
|
|
|
@@ -44,7 +44,7 @@ Runner 包内可直接运行同目录的 `install-hermes-bridge.py`。安装器
|
|
|
44
44
|
|
|
45
45
|
前缀:`/api/plugins/yaoyao-bot-bridge`。
|
|
46
46
|
|
|
47
|
-
- `GET /capabilities?profile=...`:检查对应 Profile 及托管能力。
|
|
47
|
+
- `GET /capabilities?profile=...`:检查对应 Profile 及托管能力。1.3.1 起可选的 `runtime_environment` 返回版本 1 的 Hermes 进程系统信息及对应 Profile 的原生终端、文件、桌面和浏览器工具名称;按完整目录采集,包含延迟发现的工具,不执行工具或探测其后端。进程系统信息不代表 SSH、容器或桌面工具的实际目标,不返回配置、凭据或客户端路径。
|
|
48
48
|
- `GET /model-options?profile=...`:读取 Profile 的模型目录、默认值、思考能力与速度能力;只返回公开配置,不返回凭据。
|
|
49
49
|
- `POST /model-settings/resolve`:接收 `profile` 与 `settings`,通过 Hermes 原生解析器校验完整组合,返回版本 1 的有效配置和模型确认提示;不写 Profile 配置。
|
|
50
50
|
- 模型目录与配置解析均使用 Hermes 原生配置作用域,同时绑定 Profile 目录和凭据;多 Profile Dashboard 不会因缺少凭据作用域而报错,也不会借用其他 Profile 的环境变量。默认 Profile 保留 Hermes 自身的启动凭据规则。
|
|
@@ -99,4 +99,6 @@ CLI 增加 `--check` 可只读检查默认及命名 Profile;`--enable` 明确
|
|
|
99
99
|
|
|
100
100
|
1.3.0 增加 Bot 个人资料的模型设置协议(`model_settings_version: 1`)。模型与 Provider 成对选择,思考等级和 `normal / fast / auto / cold` 速度可分别继承。Web 服务在每轮提交前解析配置,并通过原生 `config.set` 按模型、思考、速度的顺序应用到当前 Bot 会话;保存资料不修改 Profile 默认值,也不打断正在运行的回复。恢复中的原轮次只继续追踪,不重新设置或提交。模型目录未声明具体等级时返回 `reasoningKnown: false`;快速能力同时检查模型和 Provider 路由。
|
|
101
101
|
|
|
102
|
+
1.3.1 增加上述 Hermes 环境快照。Bot 的服务端连接状态取自本轮 Hermes 会话,客户端电脑清单仅表示 `desktop_*` 控制通道。服务器未打开客户端或客户端退出时,Hermes 原生能力不因此被标记离线;非回环地址也不会隐藏 Hermes 运行环境。旧工具桥没有快照时保持聊天与原生工具兼容,系统与目录信息显示未知。更新工具桥后需要重启 Hermes 才能加载新快照协议。
|
|
103
|
+
|
|
102
104
|
发布时先更新工具桥与 Web 服务,在空闲时重启 Hermes Dashboard,再发布 Web/桌面端、iOS 和 Android 客户端。旧桥不能编辑新增设置,会明确提示升级;未设置 `modelSettings` 的旧 Bot 继续按原有继承路径运行。原生会话配置回执不兼容、模型无效或应用失败会停止本轮,不使用旧配置继续运行。
|
|
@@ -13,6 +13,7 @@ import json
|
|
|
13
13
|
import math
|
|
14
14
|
import mimetypes
|
|
15
15
|
import os
|
|
16
|
+
import platform
|
|
16
17
|
import re
|
|
17
18
|
import sys
|
|
18
19
|
import threading
|
|
@@ -28,7 +29,7 @@ from pathlib import Path
|
|
|
28
29
|
from typing import Any
|
|
29
30
|
|
|
30
31
|
VERSION = 1
|
|
31
|
-
PLUGIN_VERSION = "1.3.
|
|
32
|
+
PLUGIN_VERSION = "1.3.1"
|
|
32
33
|
def _plugin_fingerprint():
|
|
33
34
|
root = Path(__file__).parent
|
|
34
35
|
digest = hashlib.sha256()
|
|
@@ -351,6 +352,23 @@ def _transport_identity(transport) -> tuple[str, str]:
|
|
|
351
352
|
return "local-session-token", "dashboard"
|
|
352
353
|
|
|
353
354
|
|
|
355
|
+
def _runtime_environment(profile: str, definitions: list) -> dict:
|
|
356
|
+
# Only directory facts: never execute tools, probe desktops, or expose config
|
|
357
|
+
# credentials. Process metadata does not identify an SSH/container/UI backend.
|
|
358
|
+
names = {tool.get("function", {}).get("name") for tool in definitions if isinstance(tool, dict)}
|
|
359
|
+
names = {name for name in names if isinstance(name, str) and re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", name)}
|
|
360
|
+
return {
|
|
361
|
+
"version": 1, "profile": profile, "platform": sys.platform,
|
|
362
|
+
"osRelease": platform.release(), "arch": platform.machine(),
|
|
363
|
+
"nativeTools": {
|
|
364
|
+
"terminal": sorted(names & {"terminal", "process", "process_manage", "execute_code", "code_execution"}),
|
|
365
|
+
"files": sorted(names & {"read_file", "write_file", "patch", "search_files"}),
|
|
366
|
+
"desktop": sorted(names & {"computer_use", "desktop_project"}),
|
|
367
|
+
"browser": sorted(name for name in names if name.startswith("browser_")),
|
|
368
|
+
},
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
|
|
354
372
|
def capabilities(profile: str = "default") -> dict:
|
|
355
373
|
in_process = False
|
|
356
374
|
try:
|
|
@@ -386,7 +404,8 @@ def capabilities(profile: str = "default") -> dict:
|
|
|
386
404
|
return {"version": VERSION, "ready": True, "in_process": True, "profile": profile, "native_tools": True,
|
|
387
405
|
"computer_runtime_version": 2, "execution_policy_version": 1, "plugin_version": PLUGIN_VERSION, "plugin_fingerprint": PLUGIN_FINGERPRINT,
|
|
388
406
|
"memory_isolation": True, "memory_isolation_transport": "bridge-bind-v1", "memory_extraction": True,
|
|
389
|
-
"isolated_context_files": True, "skill_learning": True, "model_settings_version": 1, "file_transfer_version": 1
|
|
407
|
+
"isolated_context_files": True, "skill_learning": True, "model_settings_version": 1, "file_transfer_version": 1,
|
|
408
|
+
"runtime_environment": _runtime_environment(profile, definitions)}
|
|
390
409
|
finally:
|
|
391
410
|
reset_hermes_home_override(context)
|
|
392
411
|
except Exception as exc:
|
|
@@ -131,7 +131,12 @@ export class ComputerRuntime {
|
|
|
131
131
|
if (!gateways.size)
|
|
132
132
|
this.gateways.delete(gateway.meta.environmentId);
|
|
133
133
|
} }
|
|
134
|
-
activeGateways(environmentId) {
|
|
134
|
+
activeGateways(environmentId) {
|
|
135
|
+
if (this.stopPending(environmentId))
|
|
136
|
+
throw new HttpError(409, '原电脑执行尚未确认停止,不能接管或复用', 'computer_stopping');
|
|
137
|
+
return [...(this.gateways.get(environmentId) ?? [])].filter(gateway => gateway.active || gateway.paused);
|
|
138
|
+
}
|
|
139
|
+
stopPending(environmentId) { return this.db.prepare('SELECT value FROM computer_sessions').all().some(row => { const session = JSON.parse(row.value); return session.environmentId === environmentId && session.stopPending === true; }); }
|
|
135
140
|
/** One guest proxy per environment, shared by every holder; the guest
|
|
136
141
|
* reserves port 3128, so concurrent holders must never start their own. */
|
|
137
142
|
acquireProxy(spec, authorize) {
|
|
@@ -380,7 +385,10 @@ export class ComputerGateway {
|
|
|
380
385
|
return { status: 'interrupted' };
|
|
381
386
|
}
|
|
382
387
|
if ((method === 'session.interrupt' || method === 'session.close') && params.session_id === this.recoverySession?.id) {
|
|
388
|
+
await this.profileSession?.stop();
|
|
383
389
|
await this.runtime.pool.stopHolder(this.meta.ownerKey, this.meta.environmentId, this.workId);
|
|
390
|
+
this.recoverySession.stopPending = false;
|
|
391
|
+
this.runtime.save(this.recoverySession);
|
|
384
392
|
return { status: 'interrupted' };
|
|
385
393
|
}
|
|
386
394
|
this.guard();
|
|
@@ -391,6 +399,8 @@ export class ComputerGateway {
|
|
|
391
399
|
if (method === 'session.resume' && params.recoverOnly === true) {
|
|
392
400
|
const session = this.runtime.session(String(params.session_id), this.meta, String(params.profile));
|
|
393
401
|
this.recoverySession = session;
|
|
402
|
+
session.stopPending = true;
|
|
403
|
+
this.runtime.save(session);
|
|
394
404
|
if (session.profileSessionId) {
|
|
395
405
|
await this.openProfile(session, params);
|
|
396
406
|
await this.profileSession.stop();
|
|
@@ -398,8 +408,12 @@ export class ComputerGateway {
|
|
|
398
408
|
const resource = this.runtime.pool.status(this.meta.ownerKey).find(item => item.environmentId === this.meta.environmentId);
|
|
399
409
|
if (resource?.holderIds.includes(this.workId))
|
|
400
410
|
await this.runtime.pool.stopHolder(this.meta.ownerKey, this.meta.environmentId, this.workId);
|
|
411
|
+
session.stopPending = false;
|
|
412
|
+
this.runtime.save(session);
|
|
401
413
|
return { session_id: session.id, stored_session_id: session.id, running: false, info: { profile_name: session.profile } };
|
|
402
414
|
}
|
|
415
|
+
if (this.runtime.stopPending(this.meta.environmentId))
|
|
416
|
+
throw new HttpError(409, '原电脑执行尚未确认停止,不能复用', 'computer_stopping');
|
|
403
417
|
const profile = String(params.profile), resolved = this.hermesManaged ? { cwd: this.runtime.pool.definition(this.meta.ownerKey, this.meta.environmentId)?.cwd ?? COMPUTER_WORKSPACE, configuredCwd: '.' } : await (this.meta.profileSession ? this.runtime.resolveWorkspace(profile, this.controller.signal) : this.runtime.resolve(profile, this.controller.signal));
|
|
404
418
|
if (this.meta.hostAccess) {
|
|
405
419
|
const configured = String(resolved.configuredCwd ?? '.');
|
|
@@ -646,8 +660,12 @@ export class ComputerGateway {
|
|
|
646
660
|
throw new HttpError(409, '请先在应用设置的本地虚拟机页面完成准备', 'computer_image_required');
|
|
647
661
|
await this.runtime.pool.configure(this.spec(live.session), () => this.guard());
|
|
648
662
|
await this.authorized();
|
|
649
|
-
|
|
650
|
-
|
|
663
|
+
// Tool cancellation must not discard the reservation before native Hermes
|
|
664
|
+
// termination is confirmed. Only this existing holder may renew for cleanup.
|
|
665
|
+
const leaseController = new AbortController();
|
|
666
|
+
live.leaseController = leaseController;
|
|
667
|
+
const lease = await this.runtime.pool.acquire(this.spec(live.session), this.workId, () => { if (live.session.stopPending && !live.releasing)
|
|
668
|
+
return; this.guard(); }, leaseController.signal);
|
|
651
669
|
if (this.closed) {
|
|
652
670
|
await this.runtime.pool.release(lease);
|
|
653
671
|
throw new Error('电脑通道已关闭');
|
|
@@ -665,7 +683,8 @@ export class ComputerGateway {
|
|
|
665
683
|
}
|
|
666
684
|
}
|
|
667
685
|
this.timer = setInterval(() => { if (this.checking || !this.live?.lease)
|
|
668
|
-
return; this.checking = true; void
|
|
686
|
+
return; this.checking = true; void Promise.resolve().then(async () => { if (!this.live.session.stopPending)
|
|
687
|
+
await this.authorized(); this.runtime.pool.renew(this.live.lease); }).catch(async () => { await this.interrupt().catch(() => { }); if (!this.closed)
|
|
669
688
|
this.onDisconnect(); }).finally(() => { this.checking = false; }); }, 5000);
|
|
670
689
|
this.timer.unref();
|
|
671
690
|
return lease;
|
|
@@ -921,6 +940,7 @@ export class ComputerGateway {
|
|
|
921
940
|
* records pending tool calls so the model can resume coherently. The pool
|
|
922
941
|
* lease stays — the human acquires a holder of the same shared desktop. */
|
|
923
942
|
async takeControl(controlId, authorize) {
|
|
943
|
+
this.guard();
|
|
924
944
|
const live = this.live;
|
|
925
945
|
if (!live || !this.active)
|
|
926
946
|
throw new HttpError(409, '机器人已不在执行,请重新打开电脑', 'computer_not_active');
|
|
@@ -978,32 +998,42 @@ export class ComputerGateway {
|
|
|
978
998
|
if (live.stopping)
|
|
979
999
|
return live.stopping;
|
|
980
1000
|
live.stopping = (async () => {
|
|
1001
|
+
live.session.stopPending = true;
|
|
1002
|
+
this.runtime.save(live.session);
|
|
981
1003
|
live.controller.abort();
|
|
982
|
-
|
|
1004
|
+
await this.profileSession?.stop();
|
|
1005
|
+
await this.profileSession?.close();
|
|
1006
|
+
await live.worker?.close();
|
|
983
1007
|
try {
|
|
984
|
-
await this.
|
|
1008
|
+
await this.release(live);
|
|
985
1009
|
}
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
try {
|
|
990
|
-
await this.release(live);
|
|
991
|
-
}
|
|
992
|
-
catch (error) {
|
|
993
|
-
if (error.code !== 'computer_lease_stale')
|
|
994
|
-
throw error;
|
|
995
|
-
}
|
|
996
|
-
live.running = false;
|
|
1010
|
+
catch (error) {
|
|
1011
|
+
if (error.code !== 'computer_lease_stale')
|
|
1012
|
+
throw error;
|
|
997
1013
|
}
|
|
998
|
-
|
|
1014
|
+
live.running = false;
|
|
1015
|
+
live.session.stopPending = false;
|
|
1016
|
+
this.runtime.save(live.session);
|
|
1017
|
+
if (this.closed)
|
|
1018
|
+
this.runtime.detachGateway(this);
|
|
1019
|
+
})().finally(() => { live.stopping = undefined; });
|
|
999
1020
|
return live.stopping;
|
|
1000
1021
|
}
|
|
1001
1022
|
async stopControl() { await this.interrupt(); this.event('message.complete', { text: '电脑控制已结束,本轮已停止', status: 'interrupted' }); }
|
|
1002
|
-
async close() {
|
|
1023
|
+
async close() {
|
|
1024
|
+
this.closed = true;
|
|
1025
|
+
this.controller.abort();
|
|
1026
|
+
this.team = undefined;
|
|
1003
1027
|
if (this.live?.running || this.live && !this.live.releasing)
|
|
1004
1028
|
await this.interrupt();
|
|
1005
|
-
|
|
1006
|
-
|
|
1029
|
+
if (this.recoverySession?.stopPending) {
|
|
1030
|
+
await this.profileSession?.stop();
|
|
1031
|
+
await this.runtime.pool.stopHolder(this.meta.ownerKey, this.meta.environmentId, this.workId);
|
|
1032
|
+
this.recoverySession.stopPending = false;
|
|
1033
|
+
this.runtime.save(this.recoverySession);
|
|
1034
|
+
}
|
|
1007
1035
|
await this.profileSession?.close();
|
|
1008
|
-
|
|
1036
|
+
clearInterval(this.timer);
|
|
1037
|
+
this.runtime.detachGateway(this);
|
|
1038
|
+
}
|
|
1009
1039
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { waitForHermesSessionIdle } from '../../server/sessionStop.js';
|
|
2
2
|
import { HttpError } from '../../server/errors.js';
|
|
3
3
|
import { WorkspaceGateway } from '../../server/workspaceGateway.js';
|
|
4
4
|
import { createWorkspaceToolLease, requireTeamToolBridge } from '../../server/workspaceToolLease.js';
|
|
@@ -121,17 +121,7 @@ export class ProfileComputerSession {
|
|
|
121
121
|
if (!this.runtimeId || this.closed)
|
|
122
122
|
return;
|
|
123
123
|
await this.rpc('session.interrupt');
|
|
124
|
-
|
|
125
|
-
const deadline = Date.now() + 20000;
|
|
126
|
-
for (;;) {
|
|
127
|
-
const state = await this.rpc('session.active_list');
|
|
128
|
-
const session = state.sessions?.find((item) => item.id === this.runtimeId);
|
|
129
|
-
if (session?.status === 'idle')
|
|
130
|
-
return;
|
|
131
|
-
if (Date.now() >= deadline)
|
|
132
|
-
throw new HttpError(409, '本机任务尚未停止,暂不能交出电脑控制权', 'computer_profile_stopping');
|
|
133
|
-
await delay(100, undefined, { signal: this.controller.signal });
|
|
134
|
-
}
|
|
124
|
+
await waitForHermesSessionIdle((method, params) => this.rpc(method, params), this.runtimeId, this.profile, { signal: this.controller.signal });
|
|
135
125
|
}
|
|
136
126
|
async close() {
|
|
137
127
|
if (this.closed)
|
|
@@ -36,7 +36,7 @@ export function chatTranscriptRouter(cache, auth) {
|
|
|
36
36
|
}
|
|
37
37
|
});
|
|
38
38
|
router.get('/api/app/chat/sessions/:id/events', ctx => {
|
|
39
|
-
const { owner, profile, id } = scope(ctx), version = auth.pushAuthorizationVersion(owner);
|
|
39
|
+
const { owner, profile, id } = scope(ctx), version = auth.pushAuthorizationVersion(owner), cookie = ctx.get('cookie');
|
|
40
40
|
const raw = ctx.get('last-event-id') || String(ctx.query.after ?? ''), parts = raw.split(':');
|
|
41
41
|
let cursor = Number(parts.at(-1)), closed = false, lastFlush = 0, ready = false;
|
|
42
42
|
transcripts.seed(owner, profile, id);
|
|
@@ -45,7 +45,7 @@ export function chatTranscriptRouter(cache, auth) {
|
|
|
45
45
|
throw new HttpError(409, '聊天事件需要重新同步', 'transcript_reset');
|
|
46
46
|
const res = ctx.res;
|
|
47
47
|
let timer, heartbeat, off = () => { };
|
|
48
|
-
const valid = () => !store.isClosed && auth.isUserActive(owner) && auth.pushAuthorizationVersion(owner) === version && auth.
|
|
48
|
+
const valid = () => !store.isClosed && auth.isUserActive(owner) && auth.pushAuthorizationVersion(owner) === version && auth.currentFromCookieHeader(cookie)?.id === owner && store.ownsSession(owner, profile, id) && auth.canUseSource(owner, 'local', profile);
|
|
49
49
|
const close = () => { if (closed)
|
|
50
50
|
return; closed = true; clearTimeout(timer); clearInterval(heartbeat); off(); if (!res.writableEnded)
|
|
51
51
|
res.end(); };
|
|
@@ -48,11 +48,11 @@ export const DESKTOP_ENVIRONMENT_TOOLS = [
|
|
|
48
48
|
{ id: 'desktop_shell', name: 'desktop_shell', description: '在这台电脑的用户主目录执行一条 shell 命令,返回 stdout、stderr 与退出码。长任务会超时终止;不要用它代替文件工具读写大文件。可用 host 指定目标电脑。', inputSchema: { type: 'object', properties: { command: { type: 'string' }, cwd: { type: 'string' }, timeoutMs: { type: 'integer' }, host: { type: 'string' } }, required: ['command'], additionalProperties: false } },
|
|
49
49
|
];
|
|
50
50
|
export const DESKTOP_FILE_TOOL_IDS = new Set(['desktop_file_list', 'desktop_file_read', 'desktop_file_write', 'desktop_file_copy', 'desktop_shell']);
|
|
51
|
-
export const DESKTOP_FILE_TRANSFER_RULES = '电脑间传文件用 desktop_file_copy,一次指定 sourceHost、sourcePath、targetHost、targetPath
|
|
51
|
+
export const DESKTOP_FILE_TRANSFER_RULES = '电脑间传文件用 desktop_file_copy,一次指定 sourceHost、sourcePath、targetHost、targetPath;服务器桌面代理用 server,当前 Bot 的虚拟机用 vm,设备名用设置里的名字,「本机」只指本轮消息来源电脑。例:把 mac1 桌面的 a.txt 放到 mac2 桌面,调用 {sourceHost:"mac1",sourcePath:"Desktop/a.txt",targetHost:"mac2",targetPath:"Desktop/a.txt"}。这是复制,保留原文件;只有用户明确要求覆盖时才传 overwrite:true。无需先截图,不要读取 base64 给模型、上传聊天附件或假设不同电脑共享文件路径。最大 25 MiB;工具返回已校验的成功结果后才报告完成。';
|
|
52
52
|
/** Macs connected to the server as computers. */
|
|
53
53
|
export const DESKTOP_ENVIRONMENT_RULES = '操作连接服务器的电脑时,使用本轮提供的 desktop_* 工具,并用 host 指定电脑名称或编号。Hermes 原生终端和文件工具不能代替该电脑上的操作。';
|
|
54
54
|
/** Yaoyao host Mac — same look-then-act pattern as the cloud computer. */
|
|
55
|
-
export const SERVER_COMPUTER_RULES = '
|
|
55
|
+
export const SERVER_COMPUTER_RULES = '操作客户端提供的服务器桌面代理时,使用本轮提供的 desktop_* 工具并明确指定 host="server"。处理 Hermes 原生工具实际控制的运行环境时,优先使用对应原生工具;处理服务器桌面代理用户主目录内的文件时,使用已授权的 desktop_file_* 或 desktop_shell,不假定两者共享路径或能力。';
|
|
56
56
|
/** The loopback native transport is admitted only by serviceInstance's
|
|
57
57
|
* private capability; remote hosts are admitted by DesktopHostHub's bearer
|
|
58
58
|
* pairing. Browser/desktop authority never crosses into the renderer. */
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const text = z.string().min(1).max(256).refine(value => !/[\u0000-\u001f]/.test(value));
|
|
3
|
+
const tools = z.array(z.string().regex(/^[A-Za-z0-9_.:-]{1,128}$/)).max(256);
|
|
4
|
+
const metadata = z.object({
|
|
5
|
+
version: z.literal(1), profile: text, platform: text, osRelease: text, arch: text,
|
|
6
|
+
nativeTools: z.object({ terminal: tools, files: tools, desktop: tools, browser: tools }),
|
|
7
|
+
});
|
|
8
|
+
/** Optional protocol extension: old or incompatible bridges leave facts unknown. */
|
|
9
|
+
export function parseHermesRuntimeMetadata(value, profile) {
|
|
10
|
+
const parsed = metadata.safeParse(value);
|
|
11
|
+
if (!parsed.success || parsed.data.profile !== profile)
|
|
12
|
+
return undefined;
|
|
13
|
+
return parsed.data;
|
|
14
|
+
}
|
|
@@ -7,6 +7,7 @@ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
|
|
|
7
7
|
const isUuid = (value) => /^[0-9a-f]{32}$/.test(value);
|
|
8
8
|
const memoryId = (requestId) => requestId.replaceAll('-', '');
|
|
9
9
|
const MEMORY_TAG = 'yaoyao_memory=true';
|
|
10
|
+
const MEMORY_READ_CONCURRENCY = 8;
|
|
10
11
|
const activeUri = (scope, id) => `viking://~/memories/yaoyao/${scope.scope}/${id}.json`;
|
|
11
12
|
const revisionsUri = (scope, id, revision) => `viking://resources/yaoyao/${scope.scope}/${id}/revisions/${revision}.json`;
|
|
12
13
|
const tombstoneUri = (scope, fingerprint) => `viking://resources/yaoyao/${scope.scope}/tombstones/${fingerprint}.json`;
|
|
@@ -98,18 +99,36 @@ export class OpenVikingMemoryProvider {
|
|
|
98
99
|
const client = this.service.userClient(owner, scope.agentId);
|
|
99
100
|
const directory = `viking://~/memories/yaoyao/${scope.scope}`;
|
|
100
101
|
const entries = await notFoundAsUndefined(() => client.list(directory, { recursive: true })) ?? [];
|
|
101
|
-
const
|
|
102
|
-
for (const entry of entries) {
|
|
102
|
+
const ids = entries.flatMap(entry => {
|
|
103
103
|
const name = uriName(entry);
|
|
104
104
|
const match = /([0-9a-f]{32})\.json$/.exec(name ?? '');
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
105
|
+
return match ? [match[1]] : [];
|
|
106
|
+
});
|
|
107
|
+
const records = new Array(ids.length);
|
|
108
|
+
let next = 0, failed = false;
|
|
109
|
+
// Preserve directory order and per-record scope checks without N serial round trips.
|
|
110
|
+
const reads = await Promise.allSettled(Array.from({ length: Math.min(ids.length, MEMORY_READ_CONCURRENCY) }, async () => {
|
|
111
|
+
while (!failed) {
|
|
112
|
+
const index = next++;
|
|
113
|
+
if (index >= ids.length)
|
|
114
|
+
return;
|
|
115
|
+
let record;
|
|
116
|
+
try {
|
|
117
|
+
record = await this.readRecord(owner, scope, ids[index]);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
failed = true;
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
if (record && record.memory.scope === scope.scope && record.memory.agentId === scope.agentId
|
|
124
|
+
&& record.memory.projectId === scope.projectId)
|
|
125
|
+
records[index] = record.memory;
|
|
126
|
+
}
|
|
127
|
+
}));
|
|
128
|
+
const failure = reads.find(read => read.status === 'rejected');
|
|
129
|
+
if (failure?.status === 'rejected')
|
|
130
|
+
throw failure.reason;
|
|
131
|
+
return records.filter((memory) => memory !== undefined);
|
|
113
132
|
}
|
|
114
133
|
async list(owner, scopes) {
|
|
115
134
|
const result = [];
|
|
@@ -22,6 +22,8 @@ export class OpenVikingService {
|
|
|
22
22
|
#clients = new Map();
|
|
23
23
|
#adminClients = new Map();
|
|
24
24
|
#registrations = new Map();
|
|
25
|
+
#removals = new Map();
|
|
26
|
+
onConfigurationChanged = () => { };
|
|
25
27
|
#configuration;
|
|
26
28
|
#clientFactory;
|
|
27
29
|
constructor(store, configurationManager, clientFactory) {
|
|
@@ -37,11 +39,14 @@ export class OpenVikingService {
|
|
|
37
39
|
}
|
|
38
40
|
configure(config) {
|
|
39
41
|
const signature = config ? `${config.url}\0${config.accountId}\0${config.adminKey}` : '';
|
|
40
|
-
|
|
42
|
+
const changed = signature !== this.#signature;
|
|
43
|
+
if (changed) {
|
|
41
44
|
this.#clients.clear();
|
|
42
45
|
this.#adminClients.clear();
|
|
43
46
|
}
|
|
44
47
|
this.#configuration = config;
|
|
48
|
+
if (changed)
|
|
49
|
+
this.onConfigurationChanged();
|
|
45
50
|
}
|
|
46
51
|
get #signature() { return this.#configuration ? `${this.#configuration.url}\0${this.#configuration.accountId}\0${this.#configuration.adminKey}` : ''; }
|
|
47
52
|
binding(owner, agentId) {
|
|
@@ -83,6 +88,8 @@ export class OpenVikingService {
|
|
|
83
88
|
return client;
|
|
84
89
|
}
|
|
85
90
|
userClient(owner, agentId) {
|
|
91
|
+
if (this.store.get(owner, 'agent-deletion', agentId))
|
|
92
|
+
throw new HttpError(410, 'Bot 已删除,记忆用户不可使用', 'openviking_user_removed');
|
|
86
93
|
const config = this.#configuration;
|
|
87
94
|
if (!config)
|
|
88
95
|
throw new HttpError(409, 'OpenViking 记忆服务未启用', 'openviking_disabled');
|
|
@@ -100,6 +107,8 @@ export class OpenVikingService {
|
|
|
100
107
|
}
|
|
101
108
|
async ensureUser(owner, agent) {
|
|
102
109
|
const key = `${this.namespace}:${owner}:${agent.id}`;
|
|
110
|
+
if (this.#removals.has(key) || this.store.get(owner, 'agent-deletion', agent.id) || this.binding(owner, agent.id)?.status === 'removed')
|
|
111
|
+
throw new HttpError(410, 'Bot 已删除或正在移除记忆用户,不能重新注册', 'openviking_user_removed');
|
|
103
112
|
const existing = this.#registrations.get(key);
|
|
104
113
|
if (existing)
|
|
105
114
|
return existing;
|
|
@@ -151,22 +160,43 @@ export class OpenVikingService {
|
|
|
151
160
|
}
|
|
152
161
|
}
|
|
153
162
|
async removeUser(owner, agent) {
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
163
|
+
const namespace = this.namespace, key = `${namespace}:${owner}:${agent.id}`;
|
|
164
|
+
const existing = this.#removals.get(key);
|
|
165
|
+
if (existing)
|
|
166
|
+
return existing;
|
|
167
|
+
const registrations = [...this.#registrations.entries()].filter(([registrationKey]) => registrationKey.endsWith(`:${owner}:${agent.id}`)).map(([, registration]) => registration);
|
|
168
|
+
const config = this.#configuration, admin = config ? this.adminClient() : undefined;
|
|
169
|
+
const pending = Promise.resolve().then(async () => {
|
|
170
|
+
// Registration can already have reached the remote server. Finish it before
|
|
171
|
+
// removal so its late receipt cannot recreate the deleted user's binding.
|
|
172
|
+
await Promise.allSettled(registrations);
|
|
173
|
+
// Keep the deletion attached to the configuration captured at admission.
|
|
174
|
+
const legacy = this.store.get(owner, 'openviking-binding', agent.id);
|
|
175
|
+
const binding = config
|
|
176
|
+
? this.store.get(owner, 'openviking-binding', `${namespace}:${agent.id}`) ?? (legacy && (!legacy.namespace || legacy.namespace === namespace) ? legacy : undefined)
|
|
177
|
+
: legacy;
|
|
178
|
+
if (binding?.status === 'removed' && !binding.pendingRemoval)
|
|
179
|
+
return;
|
|
180
|
+
const removed = { ...(binding ?? { provider: 'openviking', owner, agentId: agent.id, userId: openVikingUserId(agent.id), encryptedUserKey: '', namespace }), status: 'removed', pendingRemoval: true, updatedAt: Date.now() };
|
|
181
|
+
this.saveBinding(removed);
|
|
182
|
+
if (!config || !admin)
|
|
183
|
+
return; // Keep a durable pending removal while disabled.
|
|
184
|
+
try {
|
|
185
|
+
await admin.adminRemoveUser(config.accountId, removed.userId);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
if (!(error instanceof OpenVikingError) || !(error.statusCode === 404 || error.code === 'NOT_FOUND'))
|
|
189
|
+
mapError(error, 'user 删除');
|
|
190
|
+
}
|
|
191
|
+
this.saveBinding({ ...removed, pendingRemoval: false, updatedAt: Date.now() });
|
|
192
|
+
});
|
|
193
|
+
this.#removals.set(key, pending);
|
|
162
194
|
try {
|
|
163
|
-
await
|
|
195
|
+
await pending;
|
|
164
196
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
mapError(error, 'user 删除');
|
|
197
|
+
finally {
|
|
198
|
+
this.#removals.delete(key);
|
|
168
199
|
}
|
|
169
|
-
this.saveBinding({ ...binding, status: 'removed', pendingRemoval: false, updatedAt: Date.now() });
|
|
170
200
|
}
|
|
171
201
|
}
|
|
172
202
|
function encryptUserKey(home, value) {
|
|
@@ -235,9 +235,18 @@ export class RealtimeAPI {
|
|
|
235
235
|
ctx.body = { id: c.id, brokerEpoch: this.broker.epoch };
|
|
236
236
|
return;
|
|
237
237
|
}
|
|
238
|
-
const receipt = /^\/commands\/([
|
|
238
|
+
const receipt = /^\/commands\/([^/]+)$/.exec(path);
|
|
239
239
|
if (receipt && ctx.method === 'GET') {
|
|
240
|
-
|
|
240
|
+
let id;
|
|
241
|
+
try {
|
|
242
|
+
id = decodeURIComponent(receipt[1]);
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
throw new HttpError(400, 'Invalid request ID', 'invalid_request_id');
|
|
246
|
+
}
|
|
247
|
+
if (!/^[A-Za-z0-9:_-]{1,200}$/.test(id))
|
|
248
|
+
throw new HttpError(400, 'Invalid request ID', 'invalid_request_id');
|
|
249
|
+
ctx.body = this.broker.receipt(principal, id);
|
|
241
250
|
return;
|
|
242
251
|
}
|
|
243
252
|
const channel = /^\/channels\/([0-9a-f-]{36})(?:\/(commands|events))?$/.exec(path);
|
|
@@ -147,7 +147,7 @@ export class RealtimeBroker {
|
|
|
147
147
|
return this.commands.get(key) ?? Promise.resolve(this.completed.get(key)?.receipt ?? existing);
|
|
148
148
|
const work = this.perform(c, frame, requestId).then(response => {
|
|
149
149
|
const state = response.error ? 'rejected' : 'confirmed';
|
|
150
|
-
this.receipts.finish(c.principal.key, requestId, state, response);
|
|
150
|
+
this.receipts.finish(c.principal.key, requestId, state, response, frame);
|
|
151
151
|
return { requestId, state, response };
|
|
152
152
|
}, (error) => {
|
|
153
153
|
if (error instanceof HttpError) {
|
|
@@ -17,12 +17,16 @@ export class RealtimeReceipts {
|
|
|
17
17
|
state TEXT NOT NULL, response TEXT, updated INTEGER NOT NULL,
|
|
18
18
|
PRIMARY KEY(owner,id));
|
|
19
19
|
CREATE INDEX IF NOT EXISTS receipt_retention ON receipts(state,updated);
|
|
20
|
+
CREATE TABLE IF NOT EXISTS receipt_tombstones (
|
|
21
|
+
owner TEXT NOT NULL, id TEXT NOT NULL, fingerprint TEXT NOT NULL,
|
|
22
|
+
PRIMARY KEY(owner,id));
|
|
20
23
|
UPDATE receipts SET state='unknown' WHERE state='pending';`);
|
|
21
24
|
}
|
|
22
25
|
lookup(owner, id) {
|
|
23
26
|
const row = this.db.prepare('SELECT state,response FROM receipts WHERE owner=? AND id=?').get(owner, id);
|
|
24
27
|
if (!row)
|
|
25
|
-
return
|
|
28
|
+
return this.db.prepare('SELECT 1 FROM receipt_tombstones WHERE owner=? AND id=?').get(owner, id)
|
|
29
|
+
? { requestId: id, state: 'unknown' } : undefined;
|
|
26
30
|
return { requestId: id, state: row.state,
|
|
27
31
|
...(row.response ? { response: JSON.parse(String(row.response)) } : {}) };
|
|
28
32
|
}
|
|
@@ -30,27 +34,54 @@ export class RealtimeReceipts {
|
|
|
30
34
|
if (!/^[A-Za-z0-9:_-]{1,200}$/.test(id))
|
|
31
35
|
throw new HttpError(400, 'Invalid request ID', 'invalid_request_id');
|
|
32
36
|
const fingerprint = createHash('sha256').update(frame).digest('hex');
|
|
33
|
-
const row = this.db.prepare(
|
|
37
|
+
const row = this.db.prepare(`SELECT fingerprint FROM receipts WHERE owner=? AND id=?
|
|
38
|
+
UNION ALL SELECT fingerprint FROM receipt_tombstones WHERE owner=? AND id=?`).get(owner, id, owner, id);
|
|
34
39
|
if (row) {
|
|
35
40
|
if (row.fingerprint !== fingerprint)
|
|
36
41
|
throw new HttpError(409, 'Request ID payload conflict', 'idempotency_conflict');
|
|
37
42
|
return this.lookup(owner, id);
|
|
38
43
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
44
|
+
// Retire results, never admission identities. Old clients may retry years later.
|
|
45
|
+
// A compact fingerprint tombstone prevents those retries from executing again.
|
|
46
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
47
|
+
try {
|
|
48
|
+
const cutoff = Date.now() - 86_400_000;
|
|
49
|
+
this.db.prepare(`INSERT OR IGNORE INTO receipt_tombstones
|
|
50
|
+
SELECT owner,id,fingerprint FROM receipts WHERE updated<? AND state IN ('confirmed','rejected')`).run(cutoff);
|
|
51
|
+
this.db.prepare("DELETE FROM receipts WHERE updated<? AND state IN ('confirmed','rejected')").run(cutoff);
|
|
52
|
+
if (Number(this.db.prepare('SELECT count(*) AS n FROM receipts').get().n) >= 100_000) {
|
|
53
|
+
throw new HttpError(429, 'Command receipt capacity reached', 'receipt_capacity');
|
|
54
|
+
}
|
|
55
|
+
this.db.prepare('INSERT INTO receipts VALUES(?,?,?,?,NULL,?)').run(owner, id, fingerprint, 'pending', Date.now());
|
|
56
|
+
this.db.exec('COMMIT');
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
this.db.exec('ROLLBACK');
|
|
60
|
+
throw error;
|
|
42
61
|
}
|
|
43
|
-
this.db.prepare('INSERT INTO receipts VALUES(?,?,?,?,NULL,?)').run(owner, id, fingerprint, 'pending', Date.now());
|
|
44
62
|
return undefined;
|
|
45
63
|
}
|
|
46
|
-
finish(owner, id, state, response) {
|
|
47
|
-
// Persist
|
|
64
|
+
finish(owner, id, state, response, command) {
|
|
65
|
+
// Persist bounded recovery metadata, never command bodies, attachment bytes or history.
|
|
48
66
|
const result = response?.result;
|
|
49
67
|
const safe = {};
|
|
50
68
|
for (const key of ['status', 'session_id', 'stored_session_id', 'session_key', 'queued', 'running', 'ok']) {
|
|
51
69
|
if (result && ['string', 'number', 'boolean'].includes(typeof result[key]))
|
|
52
70
|
safe[key] = result[key];
|
|
53
71
|
}
|
|
72
|
+
const strings = command?.method === 'config.set' && ['model', 'reasoning', 'fast'].includes(String(command.params?.key))
|
|
73
|
+
? ['value', 'confirm_message', 'warning']
|
|
74
|
+
: ['file.attach', 'image.attach_bytes', 'pdf.attach'].includes(String(command?.method))
|
|
75
|
+
? ['path', 'image_path', 'ref_path', 'ref_text'] : [];
|
|
76
|
+
for (const key of strings) {
|
|
77
|
+
if (typeof result?.[key] === 'string' && result[key].length <= 4096)
|
|
78
|
+
safe[key] = result[key];
|
|
79
|
+
}
|
|
80
|
+
if (command?.method === 'config.set')
|
|
81
|
+
for (const key of ['deferred', 'confirm_required']) {
|
|
82
|
+
if (typeof result?.[key] === 'boolean')
|
|
83
|
+
safe[key] = result[key];
|
|
84
|
+
}
|
|
54
85
|
const saved = response?.error ? { error: { message: 'Upstream rejected command' } }
|
|
55
86
|
: response ? { result: safe } : undefined;
|
|
56
87
|
this.db.prepare('UPDATE receipts SET state=?,response=?,updated=? WHERE owner=? AND id=?')
|