@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.
Files changed (84) hide show
  1. package/README.md +5 -5
  2. package/build-info.json +18 -3
  3. package/desktop/main.mjs +6 -2
  4. package/dist/assets/{AboutDialog-fbm5CG09.js → AboutDialog-k7oUOua0.js} +2 -2
  5. package/dist/assets/AboutDialog-k7oUOua0.js.map +1 -0
  6. package/dist/assets/{BotAutomationsView-DPAAYyuy.js → BotAutomationsView-CUaMkVfT.js} +2 -2
  7. package/dist/assets/{BotAutomationsView-DPAAYyuy.js.map → BotAutomationsView-CUaMkVfT.js.map} +1 -1
  8. package/dist/assets/{BotPluginsDialog-MwGpwjgu.js → BotPluginsDialog-BqfqrWdq.js} +2 -2
  9. package/dist/assets/{BotPluginsDialog-MwGpwjgu.js.map → BotPluginsDialog-BqfqrWdq.js.map} +1 -1
  10. package/dist/assets/{BotSettingsDialog-DXtsSzi8.js → BotSettingsDialog-BfW0Jxhg.js} +4 -4
  11. package/dist/assets/{BotSettingsDialog-DXtsSzi8.js.map → BotSettingsDialog-BfW0Jxhg.js.map} +1 -1
  12. package/dist/assets/{ChatView-BNqHa6Ma.js → ChatView-CTWvNlNq.js} +2 -2
  13. package/dist/assets/{ChatView-BNqHa6Ma.js.map → ChatView-CTWvNlNq.js.map} +1 -1
  14. package/dist/assets/{ComputerPanel-B0QyKQkF.js → ComputerPanel-D_wWUzlj.js} +2 -2
  15. package/dist/assets/{ComputerPanel-B0QyKQkF.js.map → ComputerPanel-D_wWUzlj.js.map} +1 -1
  16. package/dist/assets/{ComputerViewerView-CaOkTXpc.js → ComputerViewerView-C2nS7MWX.js} +2 -2
  17. package/dist/assets/{ComputerViewerView-CaOkTXpc.js.map → ComputerViewerView-C2nS7MWX.js.map} +1 -1
  18. package/dist/assets/{ConversationsView-CYNc59hv.js → ConversationsView-D5KvMs7J.js} +2 -2
  19. package/dist/assets/{ConversationsView-CYNc59hv.js.map → ConversationsView-D5KvMs7J.js.map} +1 -1
  20. package/dist/assets/{FilesView-CluNyIk8.js → FilesView-xOEZGSrD.js} +2 -2
  21. package/dist/assets/{FilesView-CluNyIk8.js.map → FilesView-xOEZGSrD.js.map} +1 -1
  22. package/dist/assets/{FloatingResourceSearch-Bg5rUZMy.js → FloatingResourceSearch-D5XwWF0V.js} +2 -2
  23. package/dist/assets/{FloatingResourceSearch-Bg5rUZMy.js.map → FloatingResourceSearch-D5XwWF0V.js.map} +1 -1
  24. package/dist/assets/{HistoryView-DSbSDzsB.js → HistoryView-CnUN9Qik.js} +2 -2
  25. package/dist/assets/{HistoryView-DSbSDzsB.js.map → HistoryView-CnUN9Qik.js.map} +1 -1
  26. package/dist/assets/{KanbanView-D5AdRwqi.js → KanbanView-DXJCj1E6.js} +2 -2
  27. package/dist/assets/{KanbanView-D5AdRwqi.js.map → KanbanView-DXJCj1E6.js.map} +1 -1
  28. package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js → LocalVmSettingsPanel-8wF6wA3P.js} +2 -2
  29. package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js.map → LocalVmSettingsPanel-8wF6wA3P.js.map} +1 -1
  30. package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js → RunnerSettingsPanel-DDEMgUS9.js} +2 -2
  31. package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js.map → RunnerSettingsPanel-DDEMgUS9.js.map} +1 -1
  32. package/dist/assets/{StandaloneDialog-DdcL_wV2.js → StandaloneDialog-BN6RJ3uh.js} +2 -2
  33. package/dist/assets/{StandaloneDialog-DdcL_wV2.js.map → StandaloneDialog-BN6RJ3uh.js.map} +1 -1
  34. package/dist/assets/{UpdateCheckDialog-CJQezkXo.js → UpdateCheckDialog-CZ6NZSkP.js} +2 -2
  35. package/dist/assets/{UpdateCheckDialog-CJQezkXo.js.map → UpdateCheckDialog-CZ6NZSkP.js.map} +1 -1
  36. package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js → WorkspaceKnowledgePanel-BA7yVvWK.js} +2 -2
  37. package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js.map → WorkspaceKnowledgePanel-BA7yVvWK.js.map} +1 -1
  38. package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js → WorkspaceRoutinesPanel-DgCqaACO.js} +2 -2
  39. package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js.map → WorkspaceRoutinesPanel-DgCqaACO.js.map} +1 -1
  40. package/dist/assets/{WorkspaceShell-Bykfy3AR.js → WorkspaceShell-DQZKvx2p.js} +4 -4
  41. package/dist/assets/{WorkspaceShell-Bykfy3AR.js.map → WorkspaceShell-DQZKvx2p.js.map} +1 -1
  42. package/dist/assets/{WorkspaceView-Cco3Umfn.js → WorkspaceView-jMPyO8oT.js} +2 -2
  43. package/dist/assets/{WorkspaceView-Cco3Umfn.js.map → WorkspaceView-jMPyO8oT.js.map} +1 -1
  44. package/dist/assets/{docx-preview-C6qrP-g2.js → docx-preview-Ba7Ciq-i.js} +2 -2
  45. package/dist/assets/{docx-preview-C6qrP-g2.js.map → docx-preview-Ba7Ciq-i.js.map} +1 -1
  46. package/dist/assets/{index-CEqMqiJr.js → index-dvKMU4Xy.js} +3 -3
  47. package/dist/assets/{index-CEqMqiJr.js.map → index-dvKMU4Xy.js.map} +1 -1
  48. package/dist/assets/{pdf-G3DUsfMb.js → pdf-C3k8l1DI.js} +2 -2
  49. package/dist/assets/{pdf-G3DUsfMb.js.map → pdf-C3k8l1DI.js.map} +1 -1
  50. package/dist/assets/{sessionOwnership-DMfBRINe.js → sessionOwnership-HZsbONG-.js} +2 -2
  51. package/dist/assets/{sessionOwnership-DMfBRINe.js.map → sessionOwnership-HZsbONG-.js.map} +1 -1
  52. package/dist/assets/{viewModels-DfaKvI0x.js → viewModels-OLQqqyt3.js} +4 -4
  53. package/dist/assets/{viewModels-DfaKvI0x.js.map → viewModels-OLQqqyt3.js.map} +1 -1
  54. package/dist/index.html +1 -1
  55. package/dist-server/runner/agent.js +13 -2
  56. package/dist-server/runner/hermes-bots-bridge/README.md +4 -2
  57. package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +21 -2
  58. package/dist-server/runner/hermes-bots-bridge/plugin.yaml +1 -1
  59. package/dist-server/runner/worker/gateway.js +52 -22
  60. package/dist-server/runner/worker/profileSession.js +2 -12
  61. package/dist-server/server/chatTranscriptApi.js +2 -2
  62. package/dist-server/server/desktopEnvironments.js +2 -2
  63. package/dist-server/server/hermesRuntimeEnvironment.js +14 -0
  64. package/dist-server/server/openVikingMemoryProvider.js +29 -10
  65. package/dist-server/server/openVikingService.js +44 -14
  66. package/dist-server/server/realtimeApi.js +11 -2
  67. package/dist-server/server/realtimeBroker.js +1 -1
  68. package/dist-server/server/realtimeReceipts.js +39 -8
  69. package/dist-server/server/runnerHub.js +3 -3
  70. package/dist-server/server/sessionStop.js +19 -0
  71. package/dist-server/server/taskCoordinator.js +3 -1
  72. package/dist-server/server/workspaceAssets.js +54 -11
  73. package/dist-server/server/workspaceEnvironment.js +1 -0
  74. package/dist-server/server/workspaceMemorySynthesis.js +5 -1
  75. package/dist-server/server/workspacePrompt.js +5 -1
  76. package/dist-server/server/workspaceRoutes.js +25 -20
  77. package/dist-server/server/workspaceRuntime.js +71 -6
  78. package/dist-server/server/workspaceScheduler.js +5 -1
  79. package/dist-server/server/workspaceStore.js +21 -4
  80. package/dist-server/server/workspaceSync.js +4 -1
  81. package/dist-server/shared/botEnvironment.js +3 -3
  82. package/package.json +5 -4
  83. package/release.json +3 -3
  84. package/dist/assets/AboutDialog-fbm5CG09.js.map +0 -1
@@ -280,10 +280,10 @@ export class RunnerHub {
280
280
  return { rpc: async (method, params) => {
281
281
  if (closed)
282
282
  throw new Error('Runner gateway closed');
283
- const cleanup = ['session.interrupt', 'session.close'].includes(method);
283
+ const cleanup = ['session.interrupt', 'session.close', 'session.active_list'].includes(method);
284
284
  if (method === 'computer.transfer' && !this.online.get(record.id)?.features.includes('file-transfer-v1'))
285
285
  throw new HttpError(409, '请更新 Runner 以使用虚拟机文件传输', 'computer_transfer_upgrade_required');
286
- if (scope?.cleanupOnly && (!['session.resume', 'session.interrupt', 'session.close'].includes(method) || (method === 'session.resume' && params.session_id !== scope.sessionId)))
286
+ if (scope?.cleanupOnly && (!['session.resume', 'session.interrupt', 'session.close', 'session.active_list'].includes(method) || (method === 'session.resume' && params.session_id !== scope.sessionId)))
287
287
  throw new HttpError(403, '清理通道只能操作原绑定会话', 'runner_cleanup_forbidden');
288
288
  if (!cleanup && !valid())
289
289
  throw new HttpError(403, '本轮执行授权已失效', 'runner_command_not_admitted');
@@ -617,7 +617,7 @@ export class RunnerHub {
617
617
  let allowed = !!command && command.expiresAt > Date.now() && pending.valid() && this.networkCommandAllowed(record.id, command.kind, command.payload);
618
618
  if (command?.kind === 'gateway.rpc' || command?.kind === 'gateway.open') {
619
619
  const connection = this.connections.get(String(command.payload.connectionId));
620
- allowed &&= connection?.runnerId === record.id && (command.kind === 'gateway.rpc' && ['session.interrupt', 'session.close'].includes(String(command.payload.method)) || connection.valid());
620
+ allowed &&= connection?.runnerId === record.id && (command.kind === 'gateway.rpc' && ['session.interrupt', 'session.close', 'session.active_list'].includes(String(command.payload.method)) || connection.valid());
621
621
  }
622
622
  if (command?.kind === 'lease.create' || command?.kind === 'lease.bind') {
623
623
  const lease = this.leases.get(String(command.payload.leaseId));
@@ -0,0 +1,19 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { HttpError } from './errors.js';
3
+ /** Interrupt acknowledgement only requests cancellation; native tools may still be running. */
4
+ export async function waitForHermesSessionIdle(rpc, sessionId, profile, options = {}) {
5
+ const deadline = Date.now() + (options.timeoutMs ?? 20_000);
6
+ for (;;) {
7
+ options.signal?.throwIfAborted();
8
+ const state = await rpc('session.active_list', { profile, current_session_id: sessionId });
9
+ if (!Array.isArray(state?.sessions))
10
+ throw new HttpError(502, 'Hermes 停止状态无效,原执行仍需核对', 'session_stop_unconfirmed');
11
+ // Finalized sessions disappear from Hermes' live list.
12
+ const session = state.sessions.find((item) => item.id === sessionId);
13
+ if (!session || session.status === 'idle')
14
+ return;
15
+ if (Date.now() >= deadline)
16
+ throw new HttpError(409, 'Hermes 原任务尚未停止,请等待执行结束后重试', 'session_still_stopping');
17
+ await delay(options.pollMs ?? 100, undefined, { signal: options.signal });
18
+ }
19
+ }
@@ -274,6 +274,8 @@ export class WorkspaceTaskCoordinator {
274
274
  return this.store.command(owner, body.requestId, { actorId, operation: 'goal.resume', goalId: goal.id, origin }, () => {
275
275
  if (goal.status === 'cancelling')
276
276
  throw new HttpError(409, '旧执行尚未确认结束,请先核对状态', 'goal_still_running');
277
+ if (this.store.hasPendingCleanup(owner, { conversationTaskId: goal.id }))
278
+ throw new HttpError(409, '旧执行尚未确认结束,请先核对状态', 'goal_still_running');
277
279
  if (!['blocked', 'waiting', 'cancelled'].includes(goal.status))
278
280
  throw new HttpError(409, '只能恢复受阻、等待或已停止的目标', 'goal_not_resumable');
279
281
  if (this.store.list(owner, 'run').some(r => r.conversationId === goal.conversationId && r.conversationTaskId === goal.id && r.id !== source.id && !terminalRun(r.status)))
@@ -364,7 +366,7 @@ export class WorkspaceTaskCoordinator {
364
366
  helper.retiredAt ??= Date.now();
365
367
  this.store.put(owner, 'agent', helper.id, helper);
366
368
  }
367
- const works = this.store.list(owner, 'turn').filter(work => work.agentId === helper.id && !terminalRun(work.status));
369
+ const works = this.store.list(owner, 'turn').filter(work => work.agentId === helper.id && (!terminalRun(work.status) || work.cleanupPending));
368
370
  if (works.length) {
369
371
  for (const runId of new Set(works.map(work => work.runId)))
370
372
  void this.runtime.stop(owner, runId).catch(() => { });
@@ -2,10 +2,12 @@ import { randomUUID, createHash } from 'node:crypto';
2
2
  import { mkdirSync, writeFileSync } from 'node:fs';
3
3
  import { join, basename } from 'node:path';
4
4
  import { HttpError } from './errors.js';
5
+ import { authorizeFileRead } from './fileAccess.js';
5
6
  import { lookup } from 'mime-types';
6
7
  import { messageFileReferences } from '../shared/messageFiles.js';
7
8
  import { WorkspaceStore } from './workspaceStore.js';
8
9
  import { WorkspaceNodes } from './workspaceGateway.js';
10
+ const archiveKey = (nodeId, profile, messageId, path) => createHash('sha256').update(JSON.stringify([nodeId, profile, messageId, path])).digest('hex');
9
11
  export function publicFile(f) {
10
12
  const { path: _path, digest: _digest, messageFileSource: _source, ...result } = f;
11
13
  return result;
@@ -76,6 +78,42 @@ export class WorkspaceAssets {
76
78
  this.nodes = nodes;
77
79
  this.home = home;
78
80
  }
81
+ requireCapacity(owner, messageId, bytes) {
82
+ const count = Number(this.store.db.prepare("SELECT count(*) AS n FROM workspace_entities WHERE owner=? AND kind='file' AND json_extract(data,'$.messageId')=?").get(owner, messageId)?.n ?? 0);
83
+ if (bytes > 25 * 1024 * 1024 || count >= 8)
84
+ throw new HttpError(413, '每轮最多 8 个产物,每个不超过 25 MiB', 'artifact_limit');
85
+ const used = Number(this.store.db.prepare("SELECT coalesce(sum(json_extract(data,'$.size')),0) AS n FROM workspace_entities WHERE kind='file'").get()?.n ?? 0);
86
+ if (used + bytes > 2 * 1024 * 1024 * 1024)
87
+ throw new HttpError(413, '产物存储空间已达上限', 'artifact_quota');
88
+ }
89
+ /** Legacy archives lost nodeId, but their immutable archive key includes it.
90
+ * Restore only a unique authorized match; never assume a file came from local. */
91
+ recoverFileSource(owner, file) {
92
+ if (file.sourceNodeId || !file.sourcePath || !file.profile || !file.messageId)
93
+ return file;
94
+ const records = Number(this.store.db.prepare("SELECT count(*) AS n FROM workspace_entities WHERE owner=? AND kind='file' AND json_extract(data,'$.sourcePath')=? AND json_extract(data,'$.profile')=? AND json_extract(data,'$.messageId')=?").get(owner, file.sourcePath, file.profile, file.messageId)?.n ?? 0);
95
+ if (records !== 1)
96
+ return file;
97
+ const candidates = ['local', ...this.store.list(owner, 'node').map(node => node.id)];
98
+ let revokedMatch = false;
99
+ const matches = [...new Set(candidates)].filter(nodeId => {
100
+ if (!this.store.get(owner, 'archived-path', archiveKey(nodeId, file.profile, file.messageId, file.sourcePath)))
101
+ return false;
102
+ try {
103
+ this.nodes.requireSource(owner, { nodeId, profile: file.profile });
104
+ }
105
+ catch {
106
+ revokedMatch = true;
107
+ return false;
108
+ }
109
+ return true;
110
+ });
111
+ if (revokedMatch || matches.length !== 1)
112
+ return file;
113
+ const recovered = { ...file, sourceNodeId: matches[0] };
114
+ this.store.put(owner, 'file', file.id, recovered);
115
+ return recovered;
116
+ }
79
117
  publish(owner, message, agent, name, bytes) {
80
118
  const digest = createHash('sha256').update(bytes).digest('hex');
81
119
  name = basename(name).replace(/[\\/\u0000-\u001f\u007f]/g, '_').slice(0, 240) || 'artifact';
@@ -83,11 +121,7 @@ export class WorkspaceAssets {
83
121
  const existing = files.find(file => file.messageId === message.id && file.name === name && file.digest === digest);
84
122
  if (existing)
85
123
  return publicFile(existing);
86
- if (bytes.length > 25 * 1024 * 1024 || files.filter(file => file.messageId === message.id).length >= 8)
87
- throw new HttpError(413, '每轮最多 8 个产物,每个不超过 25 MiB', 'artifact_limit');
88
- const used = Number(this.store.db.prepare("SELECT coalesce(sum(json_extract(data,'$.size')),0) AS n FROM workspace_entities WHERE kind='file'").get()?.n ?? 0);
89
- if (used + bytes.length > 2 * 1024 * 1024 * 1024)
90
- throw new HttpError(413, '产物存储空间已达上限', 'artifact_quota');
124
+ this.requireCapacity(owner, message.id, bytes.length);
91
125
  const dir = join(this.home, 'workspace-files', owner);
92
126
  mkdirSync(dir, { recursive: true, mode: 0o700 });
93
127
  const path = join(dir, digest);
@@ -132,20 +166,28 @@ export class WorkspaceAssets {
132
166
  }
133
167
  }
134
168
  for (const path of [...paths].slice(0, 8)) {
135
- const key = createHash('sha256')
136
- .update(JSON.stringify([nodeId, profile, messageId, path]))
137
- .digest('hex');
169
+ const key = archiveKey(nodeId, profile, messageId, path);
138
170
  if (this.store.get(owner, 'archived-path', key) || this.pending.has(`${owner}:${key}`))
139
171
  continue;
140
172
  this.pending.add(`${owner}:${key}`);
141
173
  try {
142
- const response = await (remoteAgentId ? this.nodes.targetForAgent(owner, { nodeId, remoteAgentId }) : this.nodes.target(owner, nodeId))
143
- .session.request('/api/files/download', {
144
- search: new URLSearchParams({ profile, path }),
174
+ this.nodes.requireSource(owner, { nodeId, profile });
175
+ this.requireCapacity(owner, messageId, 0);
176
+ const target = remoteAgentId ? this.nodes.targetForAgent(owner, { nodeId, remoteAgentId }) : this.nodes.target(owner, nodeId);
177
+ const authorizedPath = await authorizeFileRead({ home: this.home }, target.session, path, profile);
178
+ this.nodes.requireSource(owner, { nodeId, profile });
179
+ const response = await target.session.request('/api/files/download', {
180
+ search: new URLSearchParams({ profile, path: authorizedPath }),
145
181
  maxResponseBytes: 25 * 1024 * 1024,
146
182
  });
147
183
  if (response.status !== 200 || this.stopped)
148
184
  continue;
185
+ // A download may outlive an assignment or directory-policy change.
186
+ this.nodes.requireSource(owner, { nodeId, profile });
187
+ if (await authorizeFileRead({ home: this.home }, target.session, path, profile) !== authorizedPath || this.stopped)
188
+ continue;
189
+ this.nodes.requireSource(owner, { nodeId, profile });
190
+ this.requireCapacity(owner, messageId, response.body.length);
149
191
  const dir = join(this.home, 'workspace-files', owner);
150
192
  mkdirSync(dir, { recursive: true, mode: 0o700 });
151
193
  const digest = createHash('sha256').update(response.body).digest('hex');
@@ -168,6 +210,7 @@ export class WorkspaceAssets {
168
210
  size: response.body.length,
169
211
  sender,
170
212
  profile,
213
+ sourceNodeId: nodeId,
171
214
  conversationId,
172
215
  messageId,
173
216
  createdAt: Date.now(),
@@ -14,6 +14,7 @@ export function buildWorkspaceEnvironment(input) {
14
14
  return {
15
15
  ...(input.execution ? { selection: input.execution } : {}),
16
16
  version: 1, capturedAt: desktop.capturedAt, execution: { nodeId: agent.nodeId, profile: agent.profile },
17
+ runtime: input.runtime ? structuredClone(input.runtime) : { connected: false },
17
18
  open: { computer: globals.scriptMachine, server: globals.serverComputer, vm: globals.vm, cloud: globals.cloud },
18
19
  desktop: { ...desktop, hosts },
19
20
  tools: {
@@ -39,6 +39,7 @@ export class WorkspaceMemorySynthesis {
39
39
  timer;
40
40
  active = false;
41
41
  closed = false;
42
+ lastOwner;
42
43
  infer;
43
44
  constructor(runtime) {
44
45
  this.runtime = runtime;
@@ -101,12 +102,15 @@ export class WorkspaceMemorySynthesis {
101
102
  return;
102
103
  this.active = true;
103
104
  try {
104
- for (const owner of this.runtime.store.owners()) {
105
+ const owners = this.runtime.store.owners();
106
+ const start = (owners.indexOf(this.lastOwner ?? '') + 1) % (owners.length || 1);
107
+ for (const owner of [...owners.slice(start), ...owners.slice(0, start)]) {
105
108
  if (this.closed || !this.runtime.userActive(owner) || owner.startsWith('_'))
106
109
  continue;
107
110
  const jobs = this.runtime.knowledge.jobs(owner).filter(j => ['pending', 'running'].includes(j.status) && j.nextAt <= Date.now()).sort((a, b) => a.createdAt - b.createdAt);
108
111
  // One inference per tick keeps background work behind conversation work.
109
112
  if (jobs[0]) {
113
+ this.lastOwner = owner;
110
114
  await this.run(owner, jobs[0]);
111
115
  break;
112
116
  }
@@ -12,9 +12,13 @@ function section(title, lines) {
12
12
  export function workspaceEnvironmentPrompt(env) {
13
13
  const open = [env.open.computer && '电脑', env.open.server && '服务器桌面', env.open.vm && '虚拟环境', env.open.cloud && '云虚拟机'].filter(Boolean);
14
14
  const desktop = env.tools.desktopView || env.tools.desktopFile;
15
+ const runtime = env.runtime.metadata;
15
16
  return section('本轮环境与设备', [
16
17
  env.selection ? `默认运行环境:${({ none: '不指定', server: '服务器本机', virtual: '虚拟环境' })[env.selection.mode]};配置版本 ${env.selection.revision}。这只决定未指定目标时的默认执行位置,不限制其他已开放且获授权的环境。用户明确指定目标时优先使用该目标;默认环境未开放或不可用时说明原因,不能因此获得额外权限。未指定默认环境时按任务和本轮可用能力选择,目标不明确时澄清。` : undefined,
17
- '模型会话运行在服务端 Hermes。Hermes 原生终端和文件工具操作它所在的服务器运行环境,不代表用户所说的「本机」;若运行在容器中,也不能假定其路径与服务器桌面共享。网页、浏览器、终端和文件能力以本轮实际工具目录为准。',
18
+ env.runtime.connected ? `服务端 Hermes 已连接(节点=${JSON.stringify(env.execution.nodeId)};Profile=${JSON.stringify(env.execution.profile)})。该状态来自本轮 Hermes 会话连接,与夭夭客户端是否打开、电脑桌面代理是否在线无关。` : '服务端 Hermes 连接状态尚未确认,不能根据客户端电脑清单判断。',
19
+ '模型会话运行在服务端 Hermes。操作服务端运行环境时优先使用本轮可用的 Hermes 原生终端、文件、桌面和浏览器工具;它们的实际执行目标遵循 Hermes 自身配置,不能假定所有工具都操作同一台物理机。网页、浏览器、终端和文件能力以本轮实际工具目录为准,首次操作时按工具说明和结果确认目标。',
20
+ runtime ? `Hermes 进程环境(由对应 Profile 的工具桥上报,不代表客户端电脑或工具后端):系统=${JSON.stringify(runtime.platform)};系统版本=${JSON.stringify(runtime.osRelease)};架构=${JSON.stringify(runtime.arch)}。原生能力的 Profile 工具目录(名称是数据,目录存在不保证后端连接就绪):${JSON.stringify(runtime.nativeTools)}。` : 'Hermes 原生能力与系统信息尚未由工具桥上报;这不表示工具被禁用,请按本轮实际工具目录发现和核实,不能因客户端未连接而报告服务器离线。',
21
+ '客户端电脑清单只描述 desktop_* 控制通道。服务器桌面代理离线不影响已连接的 Hermes 原生能力;desktop_* 的 host="server" 专指服务器桌面代理,不是 Hermes 原生工具的运行环境。服务器也打开客户端时,两种连接分别报告;未确认实际操作目标一致前,不因名称或 IP 相同而合并设备、路径或权限。Hermes 在容器中时,其路径不能当作宿主机路径;Hermes 环境也不自动代表用户所说的「本机」。',
18
22
  env.cwd ? `Hermes 本轮工作目录(已确认):${JSON.stringify(env.cwd)}。该路径仅属于 Hermes 运行环境。` : undefined,
19
23
  `全局开放的额外电脑环境:${open.join('、') || '无'}。开放不等于在线或已授权;具体操作仍需目标设备就绪。已开放且获授权的环境可按任务同时使用,工具以本轮实际目录为准。`,
20
24
  '先确定操作目标,再选择工具。用户明确点名的设备优先;「本机」只指本轮消息来源电脑,历史消息中的来源不适用于本轮。来源未知、名称重名或目标不明确时先澄清;目标离线、未开放或未授权时说明原因,不得切换其他机器代做。',
@@ -23,21 +23,22 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
23
23
  .prepare("SELECT rowid AS n FROM workspace_entities WHERE owner=? AND kind='file' AND id=?")
24
24
  .get(user, id)?.n ?? 0);
25
25
  const fileRecord = (user, id) => {
26
+ const authorize = (file) => {
27
+ file = assets.recoverFileSource(user, file);
28
+ if ((file.sourcePath || file.sourceNodeId) && (!file.sourceNodeId || !file.profile))
29
+ throw new HttpError(403, '归档文件来源无法确认,请重新交付文件', 'archived_file_source_unknown');
30
+ if (file.sourceNodeId && file.profile)
31
+ nodes.requireSource(user, { nodeId: file.sourceNodeId, profile: file.profile });
32
+ return file;
33
+ };
26
34
  if (/^\d+$/.test(id)) {
27
35
  const row = store.db
28
36
  .prepare("SELECT data FROM workspace_entities WHERE owner=? AND kind='file' AND rowid=?")
29
37
  .get(user, Number(id));
30
- if (row) {
31
- const file = JSON.parse(String(row.data));
32
- if (file.sourceNodeId && file.profile)
33
- nodes.requireSource(user, { nodeId: file.sourceNodeId, profile: file.profile });
34
- return file;
35
- }
38
+ if (row)
39
+ return authorize(JSON.parse(String(row.data)));
36
40
  }
37
- const file = store.require(user, 'file', id);
38
- if (file.sourceNodeId && file.profile)
39
- nodes.requireSource(user, { nodeId: file.sourceNodeId, profile: file.profile });
40
- return file;
41
+ return authorize(store.require(user, 'file', id));
41
42
  };
42
43
  router.get('/api/app/capabilities', (ctx) => {
43
44
  owner(ctx);
@@ -163,8 +164,7 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
163
164
  });
164
165
  router.delete('/api/app/agents/:id', async (ctx) => {
165
166
  const user = owner(ctx);
166
- await runtime.cleanupAgent(user, ctx.params.id);
167
- store.deleteAgent(user, ctx.params.id);
167
+ await runtime.deleteAgent(user, ctx.params.id);
168
168
  ctx.body = { ok: true };
169
169
  });
170
170
  router.get('/api/app/agents/:id/usage', (ctx) => {
@@ -198,15 +198,20 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
198
198
  const input = parse(z.object({ action: z.enum(['archive', 'restore', 'delete']), confirmationToken: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict(), body(ctx));
199
199
  if (input.action !== 'restore' && !input.confirmationToken)
200
200
  throw new HttpError(409, '请先确认聊天操作', 'lifecycle_confirmation_required');
201
- const user = owner(ctx), conversation = store.require(user, 'conversation', ctx.params.id);
202
- if (runtime.openViking?.enabled && input.action === 'delete' && conversation.kind === 'direct') {
203
- const agent = store.require(user, 'agent', conversation.memberIds[0]);
204
- store.changeConversationLifecycle(user, conversation.id, 'archive', input.confirmationToken);
205
- await runtime.cleanupAgent(user, agent.id);
206
- store.deleteAgent(user, agent.id);
201
+ const user = owner(ctx), conversation = store.get(user, 'conversation', ctx.params.id);
202
+ if (!conversation && input.action === 'delete') {
203
+ const deletion = store.list(user, 'agent-deletion').find(item => item.conversationIds.includes(ctx.params.id));
204
+ if (deletion)
205
+ await runtime.deleteAgent(user, deletion.id);
206
+ else
207
+ store.require(user, 'conversation', ctx.params.id);
208
+ }
209
+ else {
210
+ const current = conversation ?? store.require(user, 'conversation', ctx.params.id);
211
+ store.changeConversationLifecycle(user, current.id, input.action, input.confirmationToken);
212
+ if (input.action === 'delete' && current.kind === 'direct')
213
+ await runtime.cleanupAgent(user, current.memberIds[0]);
207
214
  }
208
- else
209
- store.changeConversationLifecycle(user, conversation.id, input.action, input.confirmationToken);
210
215
  runtime.wake();
211
216
  ctx.body = { ok: true };
212
217
  });
@@ -5,6 +5,7 @@ import { browserOwnedFile, browserVmFile } from './browserFiles.js';
5
5
  import {} from './desktopEnvironments.js';
6
6
  import {} from './grokCloud.js';
7
7
  import { VmToolSession } from './vmComputer.js';
8
+ import { waitForHermesSessionIdle } from './sessionStop.js';
8
9
  import { randomUUID } from 'node:crypto';
9
10
  import { setTimeout as delay } from 'node:timers/promises';
10
11
  import { readFileSync } from 'node:fs';
@@ -17,6 +18,7 @@ import {} from './workspaceAssets.js';
17
18
  import { UploadStore } from './uploads.js';
18
19
  import { buildWorkspacePrompt } from './workspacePrompt.js';
19
20
  import { buildWorkspaceEnvironment, workspaceEnvironmentTools } from './workspaceEnvironment.js';
21
+ import { parseHermesRuntimeMetadata } from './hermesRuntimeEnvironment.js';
20
22
  import { readHostTools } from './hostToolSettings.js';
21
23
  import { resolveBotModelSettings, applyBotModelSettings, botModelTarget, BotModelConfirmationError } from './botModelSettings.js';
22
24
  function globalComputers(home) {
@@ -82,7 +84,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
82
84
  operationJournal;
83
85
  assertCanSubmit = () => { };
84
86
  get idleForUpdate() {
85
- return this.live.size === 0 && this.executing.size === 0 && !this.store.db.prepare("SELECT 1 FROM workspace_entities WHERE kind IN ('run','turn') AND COALESCE(json_extract(data,'$.status'),'unknown') NOT IN ('complete','failed','interrupted') LIMIT 1").get();
87
+ return this.live.size === 0 && this.executing.size === 0 && !this.store.db.prepare("SELECT 1 FROM workspace_entities WHERE kind IN ('run','turn') AND (COALESCE(json_extract(data,'$.status'),'unknown') NOT IN ('complete','failed','interrupted') OR coalesce(json_extract(data,'$.cleanupPending'),0)=1) LIMIT 1").get();
86
88
  }
87
89
  desktopEnvironments;
88
90
  cloud;
@@ -90,6 +92,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
90
92
  computerAvailable;
91
93
  inspector;
92
94
  live = new Map();
95
+ memoryCleanup;
96
+ memoryCleanupRetries = new Map();
93
97
  teamTools;
94
98
  routineTools;
95
99
  tasks;
@@ -103,6 +107,9 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
103
107
  this.authorizationVersion = authorizationVersion;
104
108
  this.operationJournal = new ToolOperationJournal(store);
105
109
  this.openViking = openViking;
110
+ if (openViking)
111
+ openViking.onConfigurationChanged = () => { if (!this.closing)
112
+ this.wake(); };
106
113
  this.teamTools = new WorkspaceTeamTools(store, nodes, this);
107
114
  this.tasks = new WorkspaceTaskCoordinator(store, this);
108
115
  this.knowledge = new WorkspaceKnowledge(store.home, store, openViking);
@@ -120,10 +127,60 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
120
127
  return;
121
128
  await this.openViking.ensureUser(owner, { id, temporaryGoalId: undefined });
122
129
  }
130
+ maintenance() {
131
+ if (!this.openViking?.enabled)
132
+ return false;
133
+ const pending = new Map();
134
+ for (const owner of this.store.owners()) {
135
+ for (const item of this.store.list(owner, 'agent-deletion'))
136
+ if (item.memoryCleanupPending)
137
+ pending.set(`${owner}:${item.id}`, { owner, id: item.id });
138
+ for (const binding of this.store.list(owner, 'openviking-binding'))
139
+ if (binding.namespace === this.openViking.namespace && binding.status === 'removed' && binding.pendingRemoval)
140
+ pending.set(`${owner}:${binding.agentId}`, { owner, id: binding.agentId });
141
+ }
142
+ if (!this.memoryCleanup) {
143
+ const next = [...pending.entries()].find(([key]) => (this.memoryCleanupRetries.get(key)?.after ?? 0) <= Date.now());
144
+ if (next) {
145
+ const [key, { owner, id }] = next;
146
+ this.memoryCleanup = this.cleanupAgent(owner, id).then(() => { this.memoryCleanupRetries.delete(key); })
147
+ .catch(error => {
148
+ if (this.closing)
149
+ return;
150
+ const attempt = (this.memoryCleanupRetries.get(key)?.attempt ?? 0) + 1;
151
+ this.memoryCleanupRetries.set(key, { attempt, after: Date.now() + Math.min(30_000, 500 * 2 ** Math.min(attempt - 1, 6)) });
152
+ const deletion = this.store.get(owner, 'agent-deletion', id);
153
+ if (deletion) {
154
+ deletion.cleanupError = error instanceof Error ? error.message : '远端记忆清理失败';
155
+ this.store.put(owner, 'agent-deletion', id, deletion);
156
+ }
157
+ }).finally(() => { this.memoryCleanup = undefined; this.wake(); });
158
+ }
159
+ }
160
+ return pending.size > 0;
161
+ }
123
162
  async cleanupAgent(owner, id) {
124
- if (!this.openViking)
125
- return;
126
- await this.openViking.removeUser(owner, { id, temporaryGoalId: undefined });
163
+ await this.openViking?.removeUser(owner, { id, temporaryGoalId: undefined });
164
+ const deletion = this.store.get(owner, 'agent-deletion', id);
165
+ if (deletion) {
166
+ deletion.memoryCleanupPending = this.openViking?.binding(owner, id)?.pendingRemoval === true;
167
+ delete deletion.cleanupError;
168
+ this.store.put(owner, 'agent-deletion', id, deletion);
169
+ }
170
+ }
171
+ async deleteAgent(owner, id) {
172
+ // Commit all local validation/deletion before any destructive remote action.
173
+ // The durable tombstone also makes a repeated DELETE retry remote cleanup.
174
+ if (this.store.get(owner, 'agent', id))
175
+ this.store.deleteAgent(owner, id);
176
+ else if (!this.store.get(owner, 'agent-deletion', id))
177
+ this.store.require(owner, 'agent', id);
178
+ try {
179
+ await this.cleanupAgent(owner, id);
180
+ }
181
+ finally {
182
+ this.wake();
183
+ }
127
184
  }
128
185
  send(owner, conversationId, input) {
129
186
  return this.submit(owner, conversationId, input);
@@ -133,7 +190,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
133
190
  const response = await target.session.request('/api/plugins/yaoyao-bot-bridge/capabilities', { search: new URLSearchParams({ profile: agent.profile }) });
134
191
  const value = JSON.parse(response.body.toString());
135
192
  const tools = response.status === 200 && value.ready === true && value.native_tools === true && value.in_process === true;
136
- return { tools, memory: tools && value.memory_isolation === true, extraction: value.memory_extraction === true };
193
+ const runtime = response.status === 200 ? parseHermesRuntimeMetadata(value.runtime_environment, agent.profile) : undefined;
194
+ return { tools, memory: tools && value.memory_isolation === true, extraction: value.memory_extraction === true, ...(runtime ? { runtime } : {}) };
137
195
  }
138
196
  catch (error) {
139
197
  if (error instanceof HttpError && RESOURCE_WAIT_CODES.has(error.code ?? ''))
@@ -179,6 +237,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
179
237
  for (const id of source?.targetAgentId ? [source.targetAgentId] : c.memberIds)
180
238
  this.knowledge.requireProjectMember(owner, projectId, id);
181
239
  const conversationTask = this.store.resolveTask(owner, conversationId, body.taskId), conversationTaskId = conversationTask?.id;
240
+ if (this.store.hasPendingCleanup(owner, { conversationId, conversationTaskId }))
241
+ throw new HttpError(409, '原执行尚未确认停止,请等待停止完成后再发消息', 'conversation_stopping');
182
242
  if (conversationTaskId) {
183
243
  const alreadyActive = this.store.list(owner, 'run').some(run => run.conversationTaskId === conversationTaskId && !['complete', 'failed', 'interrupted'].includes(run.status));
184
244
  if (!alreadyActive && this.store.activeTaskCount(owner, conversationId) >= WORKSPACE_CONCURRENCY_LIMIT)
@@ -903,7 +963,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
903
963
  const globals = globalComputers(this.store.home);
904
964
  const desktopSnapshot = this.desktopEnvironments?.snapshot(owner, agent, root.deviceHost, { script: globals.scriptMachine, server: globals.serverComputer, maxMiB: globals.fileTransferMaxMiB })
905
965
  ?? { capturedAt: Date.now(), sourceHost: root.deviceHost, hosts: [] };
906
- const environment = buildWorkspaceEnvironment({ agent, globals, execution, serverDesktop: agent.nodeId === 'local' && isLocalAuthorizationTarget(target.url), desktop: desktopSnapshot, bridge: botCapabilities.tools, cloud: !!this.cloud?.selected(owner, agent), plugins: !!this.plugins?.selected(owner, agent), managedBrowser: this.managedBrowsers?.available(owner, agent) });
966
+ const environment = buildWorkspaceEnvironment({ agent, globals, execution, runtime: { connected: gateway.connected, ...(botCapabilities.runtime ? { metadata: botCapabilities.runtime } : {}) }, serverDesktop: agent.nodeId === 'local' && isLocalAuthorizationTarget(target.url), desktop: desktopSnapshot, bridge: botCapabilities.tools, cloud: !!this.cloud?.selected(owner, agent), plugins: !!this.plugins?.selected(owner, agent), managedBrowser: this.managedBrowsers?.available(owner, agent) });
907
967
  const { cloud, plugins, vm: dispatchedVm } = environment.tools;
908
968
  const desktop = environment.tools.desktopView || environment.tools.desktopFile;
909
969
  const desktopEpochs = Object.fromEntries(environment.desktop.hosts.map(host => [host.id, host.epoch ?? '']));
@@ -1231,6 +1291,9 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
1231
1291
  if (live?.taskId === work.id) {
1232
1292
  try {
1233
1293
  await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId });
1294
+ const binding = this.store.require(owner, 'binding', key);
1295
+ if (binding.execution !== 'computer')
1296
+ await waitForHermesSessionIdle((method, params) => live.gateway.rpc(method, params), live.runtimeId, binding.profile);
1234
1297
  }
1235
1298
  catch (error) {
1236
1299
  if (!live.gateway.connected)
@@ -1268,6 +1331,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
1268
1331
  const opened = await gateway.rpc('session.resume', { profile: binding.profile, session_id: binding.storedId, omit_messages: true, close_on_disconnect: false, ...(binding.execution === 'computer' ? { recoverOnly: true } : {}) });
1269
1332
  if (opened.running)
1270
1333
  await gateway.rpc('session.interrupt', { session_id: opened.session_id });
1334
+ if (binding.execution !== 'computer')
1335
+ await waitForHermesSessionIdle((method, params) => gateway.rpc(method, params), String(opened.session_id), binding.profile);
1271
1336
  }
1272
1337
  finally {
1273
1338
  gateway.close();
@@ -128,6 +128,8 @@ export class WorkspaceScheduler {
128
128
  this.updateRoot(owner, root.id);
129
129
  }
130
130
  start() { this.wake(); }
131
+ /** Maintenance uses the same bounded retry loop as durable turn cleanup. */
132
+ maintenance() { return false; }
131
133
  wake() {
132
134
  if (this.closing || this.wakePending)
133
135
  return;
@@ -304,6 +306,8 @@ export class WorkspaceScheduler {
304
306
  return;
305
307
  this.pumping = true;
306
308
  try {
309
+ if (this.maintenance())
310
+ this.retrySoon();
307
311
  let all = this.store.owners().flatMap(owner => this.pendingWorks(owner).map(work => ({ owner, work })));
308
312
  for (const { owner, work } of all) {
309
313
  if (terminal(work.status) && work.cleanupPending)
@@ -377,7 +381,7 @@ export class WorkspaceScheduler {
377
381
  this.wake();
378
382
  continue;
379
383
  }
380
- const occupied = all.map(entry => this.getWork(entry.owner, entry.work.id)).filter(t => (['running', 'waiting', 'uncertain'].includes(t.status) || this.executing.has(t.id)) && t.id !== work.id);
384
+ const occupied = all.map(entry => this.getWork(entry.owner, entry.work.id)).filter(t => (t.cleanupPending || ['running', 'waiting', 'uncertain'].includes(t.status) || this.executing.has(t.id)) && t.id !== work.id);
381
385
  // Only the conversation/task/Agent binding shares mutable session state.
382
386
  // Other sessions may run concurrently; computer leases and tool queues
383
387
  // continue to serialize access to their actual shared resources.
@@ -431,6 +431,8 @@ export class WorkspaceStore {
431
431
  if (origin?.createdByAgentId)
432
432
  this.require(owner, 'agent', origin.createdByAgentId);
433
433
  return this.atomic(() => {
434
+ if (this.get(owner, 'agent-deletion', allocatedId))
435
+ throw new HttpError(409, '已删除的 Bot 编号不能复用', 'agent_deleted');
434
436
  if (this.list(owner, 'agent').some((a) => a.name.toLocaleLowerCase() === body.name.toLocaleLowerCase()))
435
437
  throw new HttpError(409, '机器人名称已存在', 'duplicate_agent_name');
436
438
  const now = Date.now(), id = allocatedId;
@@ -543,8 +545,8 @@ export class WorkspaceStore {
543
545
  const hostPermissionChanged = patch.allowHostEnvironment !== undefined && patch.allowHostEnvironment !== (agent.allowHostEnvironment === true);
544
546
  const destinationChanged = desktopHostChanged || hostPermissionChanged || (patch.vmExecution !== undefined && patch.vmExecution !== (agent.vmExecution ?? 'worker')) || (patch.computer !== undefined && patch.computer !== agent.computer) || (patch.browserProfile !== undefined && patch.browserProfile !== (agent.browserProfile ?? 'persistent'));
545
547
  if (sourceChanged || destinationChanged) {
546
- if (this.list(owner, 'turn').some(work => work.agentId === id && ['queued', 'running', 'waiting', 'uncertain', 'cancelling'].includes(work.status)))
547
- throw new HttpError(409, '请先停止当前任务,再修改机器人来源或电脑', 'agent_execution_busy');
548
+ if (this.list(owner, 'turn').some(work => work.agentId === id && (work.cleanupPending || ['queued', 'running', 'waiting', 'uncertain', 'cancelling'].includes(work.status))))
549
+ throw new HttpError(409, '请先确认当前任务停止,再修改机器人来源或电脑', 'agent_execution_busy');
548
550
  if (this.list('_system', 'computer-control').some(grant => grant.owner === owner && grant.expiresAt > Date.now() && (grant.agentId === id || grant.environmentId === (agent.computerEnvironmentId ?? id))))
549
551
  throw new HttpError(409, '请先交还电脑控制权', 'agent_execution_busy');
550
552
  if (sourceChanged && agent.computerEnvironmentId) {
@@ -557,8 +559,8 @@ export class WorkspaceStore {
557
559
  throw new HttpError(409, '临时助手由所属任务管理,不能修改权限或恢复为持久成员', 'helper_task_bound');
558
560
  if (agent.computerEnvironmentId && patch.execution === 'profile' && (patch.envs?.vm ?? agent.envs?.vm) !== true)
559
561
  throw new HttpError(409, '请先解除电脑共享,再切换执行环境', 'shared_computer_active');
560
- if (patch.execution && patch.execution !== (agent.execution ?? 'profile') && this.list(owner, 'turn').some(work => work.agentId === id && ['running', 'waiting', 'uncertain'].includes(work.status)))
561
- throw new HttpError(409, '请先停止当前任务,再切换执行环境', 'agent_execution_busy');
562
+ if (patch.execution && patch.execution !== (agent.execution ?? 'profile') && this.list(owner, 'turn').some(work => work.agentId === id && (work.cleanupPending || ['running', 'waiting', 'uncertain'].includes(work.status))))
563
+ throw new HttpError(409, '请先确认当前任务停止,再切换执行环境', 'agent_execution_busy');
562
564
  if (agent.remoteAgentId && Object.keys(patch).some(key => key !== 'archived' && key !== 'approvalPolicy'))
563
565
  throw new HttpError(409, '引用机器人的配置由远端管理', 'remote_agent_read_only');
564
566
  if (patch.name &&
@@ -601,11 +603,17 @@ export class WorkspaceStore {
601
603
  };
602
604
  }
603
605
  requireConversationIdle(owner, id) {
606
+ if (this.hasPendingCleanup(owner, { conversationId: id }))
607
+ throw new HttpError(409, '聊天原执行尚未确认停止,请稍后重试', 'conversation_stopping');
604
608
  if (['run', 'turn'].some(kind => this.list(owner, kind).some(run => run.conversationId === id && !['complete', 'failed', 'interrupted', 'skipped'].includes(run.status))))
605
609
  throw new HttpError(409, '聊天仍有任务未结束,请停止任务后重试', 'conversation_running');
606
610
  if (this.list(owner, 'goal').some(goal => (goal.conversationId === id || goal.origin?.conversationId === id) && !['complete', 'blocked', 'cancelled'].includes(goal.status)))
607
611
  throw new HttpError(409, '聊天仍有关联任务未结束,请停止任务后重试', 'conversation_running');
608
612
  }
613
+ hasPendingCleanup(owner, scope) {
614
+ return this.list(owner, 'turn')
615
+ .some(work => work.cleanupPending && Object.entries(scope).every(([key, value]) => work[key] === value));
616
+ }
609
617
  changeConversationLifecycle(owner, id, action, confirmationToken) {
610
618
  this.atomic(() => {
611
619
  const conversation = this.require(owner, 'conversation', id);
@@ -627,6 +635,8 @@ export class WorkspaceStore {
627
635
  throw new HttpError(409, '此 Bot 仍是群聊成员,请确认退出群聊后再归档或删除', 'agent_in_group');
628
636
  if (agent?.temporaryGoalId)
629
637
  throw new HttpError(409, '临时助手由所属任务管理', 'helper_task_bound');
638
+ if (agent && this.hasPendingCleanup(owner, { agentId: agent.id }))
639
+ throw new HttpError(409, 'Bot 原执行尚未确认停止,请稍后重试', 'agent_stopping');
630
640
  if (agent && this.list(owner, 'turn').some(turn => turn.agentId === agent.id && !['complete', 'failed', 'interrupted', 'skipped'].includes(turn.status)))
631
641
  throw new HttpError(409, 'Bot 仍有任务未结束,请停止任务后重试', 'agent_running');
632
642
  for (const conversationId of [id, ...preview.groups.map(group => group.id)])
@@ -648,6 +658,8 @@ export class WorkspaceStore {
648
658
  });
649
659
  }
650
660
  detachAgentComputer(owner, agent) {
661
+ if (this.hasPendingCleanup(owner, { agentId: agent.id }))
662
+ throw new HttpError(409, 'Bot 原执行尚未确认停止,请稍后重试', 'agent_stopping');
651
663
  const environmentId = agent.computerEnvironmentId;
652
664
  if (!environmentId)
653
665
  return;
@@ -673,6 +685,8 @@ export class WorkspaceStore {
673
685
  throw new HttpError(409, '请先归档 Bot,再删除', 'agent_not_archived');
674
686
  if (agent.temporaryGoalId)
675
687
  throw new HttpError(409, '临时助手由所属任务管理', 'helper_task_bound');
688
+ if (this.hasPendingCleanup(owner, { agentId: id }))
689
+ throw new HttpError(409, 'Bot 原执行尚未确认停止,请稍后重试', 'agent_stopping');
676
690
  const conversations = this.list(owner, 'conversation');
677
691
  if (conversations.some(c => c.kind === 'group' && c.memberIds.includes(id)))
678
692
  throw new HttpError(409, '此 Bot 仍是群聊成员,请先从群聊移除或删除相关群聊', 'agent_in_group');
@@ -690,6 +704,7 @@ export class WorkspaceStore {
690
704
  this.put(owner, 'bot-mcp-plugin', plugin.id, { ...plugin, agentIds: plugin.agentIds.filter(agentId => agentId !== id), revision: plugin.revision + 1 });
691
705
  }
692
706
  this.remove(owner, 'agent', id);
707
+ this.put(owner, 'agent-deletion', id, { id, conversationIds: conversations.filter(c => c.kind === 'direct' && c.memberIds[0] === id).map(c => c.id), deletedAt: Date.now(), memoryCleanupPending: true });
693
708
  this.event(owner, 'agent.deleted', { id });
694
709
  });
695
710
  }
@@ -949,6 +964,8 @@ export class WorkspaceStore {
949
964
  deleteTask(owner, conversationId, taskId) {
950
965
  this.atomic(() => {
951
966
  const task = this.requireTask(owner, conversationId, taskId);
967
+ if (this.hasPendingCleanup(owner, { conversationTaskId: taskId }))
968
+ throw new HttpError(409, '任务原执行尚未确认停止,暂时无法移除', 'workspace_task_stopping');
952
969
  if (this.list(owner, 'run').some(run => run.conversationTaskId === taskId && !['complete', 'failed', 'interrupted'].includes(run.status)))
953
970
  throw new HttpError(409, '任务仍在运行,暂时无法移除', 'workspace_task_running');
954
971
  const messageIds = new Set(this.list(owner, 'message').filter(message => message.conversationTaskId === taskId).map(message => message.id));
@@ -21,6 +21,7 @@ export function workspaceDetail(store, runtime, owner, conversationId, taskId, l
21
21
  /** Durable replay followed by live updates. A slow reader reconnects from its last applied cursor. */
22
22
  export function streamWorkspace(ctx, store, auth) {
23
23
  const owner = auth.require(ctx).id, version = auth.pushAuthorizationVersion(owner);
24
+ const cookie = ctx.get('cookie');
24
25
  const patches = store.messagePatchesEnabled && ctx.query.format === 'patch-v1';
25
26
  const res = ctx.res;
26
27
  const raw = ctx.get('last-event-id') || String(ctx.query.after ?? '0');
@@ -30,8 +31,10 @@ export function streamWorkspace(ctx, store, auth) {
30
31
  const pending = new Map();
31
32
  const knownMessages = new Set();
32
33
  const valid = () => {
34
+ // Koa's localUser is a request snapshot; a long-lived stream must check the
35
+ // captured session itself so logout and expiry revoke this connection.
33
36
  try {
34
- return auth.require(ctx).id === owner && auth.isUserActive(owner) && auth.pushAuthorizationVersion(owner) === version;
37
+ return auth.currentFromCookieHeader(cookie)?.id === owner && auth.isUserActive(owner) && auth.pushAuthorizationVersion(owner) === version;
35
38
  }
36
39
  catch {
37
40
  return false;
@@ -13,8 +13,8 @@ export function deviceSourceText(snapshot) {
13
13
  }
14
14
  export function deviceInventoryText(snapshot) {
15
15
  if (!snapshot.hosts.length)
16
- return '当前没有已知的电脑连接;设备路径与能力未知。';
17
- return `本轮电脑清单(名称是数据;重名时使用 host 固定值;状态为采集时快照,调用时重新核对):\n${snapshot.hosts.map(host => {
16
+ return '当前没有已知的客户端电脑控制通道;不能据此判断服务端 Hermes 离线或原生工具不可用。';
17
+ return `本轮电脑清单(仅描述客户端电脑控制通道,不代表 Hermes 连接状态;名称是数据;重名时使用 host 固定值;状态为采集时快照,调用时重新核对):\n${snapshot.hosts.map(host => {
18
18
  const m = host.metadata;
19
19
  const details = m ? [
20
20
  m.osRelease && `系统版本=${JSON.stringify(m.osRelease)}`, m.arch && `架构=${JSON.stringify(m.arch)}`,
@@ -23,6 +23,6 @@ export function deviceInventoryText(snapshot) {
23
23
  m.shellScope && 'Shell范围=桌面用户的系统权限(不受文件工具根目录约束)', m.timezone && `时区=${JSON.stringify(m.timezone)}`,
24
24
  ].filter(Boolean).join(';') : '运行路径未上报或无文件与命令授权';
25
25
  const state = !host.online ? '离线' : !host.open ? '未开放' : '在线';
26
- return `${JSON.stringify(host.name)}(${host.kind === 'server' ? '服务器' : '电脑'}${host.source ? '·本机' : ''};host=${JSON.stringify(host.target)};${state};系统=${JSON.stringify(host.platform ?? '未知')};屏幕控制=${deviceCapabilityLabels[host.capabilities.view.status]};文件与命令=${deviceCapabilityLabels[host.capabilities.shell.status]})\n${details};文件传输协议=${host.transfer.protocol === 'chunked' ? '分块' : host.transfer.protocol === 'legacy' ? '旧版' : '未知'},读取上限=${host.transfer.readMaxMiB === null ? '未知' : host.transfer.readMaxMiB + ' MiB'},写入上限=${host.transfer.writeMaxMiB === null ? '未知' : host.transfer.writeMaxMiB + ' MiB'}`;
26
+ return `${JSON.stringify(host.name)}(${host.kind === 'server' ? '服务器桌面代理' : '客户端电脑'}${host.source ? '·本机' : ''};host=${JSON.stringify(host.target)};控制通道=${state};系统=${JSON.stringify(host.platform ?? '未知')};屏幕控制=${deviceCapabilityLabels[host.capabilities.view.status]};文件与命令=${deviceCapabilityLabels[host.capabilities.shell.status]})\n${details};文件传输协议=${host.transfer.protocol === 'chunked' ? '分块' : host.transfer.protocol === 'legacy' ? '旧版' : '未知'},读取上限=${host.transfer.readMaxMiB === null ? '未知' : host.transfer.readMaxMiB + ' MiB'},写入上限=${host.transfer.writeMaxMiB === null ? '未知' : host.transfer.writeMaxMiB + ' MiB'}`;
27
27
  }).join('\n')}`;
28
28
  }