@lsamien/yaoyao 0.4.76 → 0.4.78

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 (141) hide show
  1. package/README.md +7 -5
  2. package/THIRD_PARTY_NOTICES.md +8 -0
  3. package/bin/hermes-yaoyao.mjs +15 -2
  4. package/build-info.json +35 -3
  5. package/desktop/main.mjs +12 -4
  6. package/dist/assets/{AboutDialog-fbm5CG09.js → AboutDialog-jvhTP8-J.js} +2 -2
  7. package/dist/assets/AboutDialog-jvhTP8-J.js.map +1 -0
  8. package/dist/assets/BotAutomationsView-ktoci79V.js +2 -0
  9. package/dist/assets/{BotAutomationsView-DPAAYyuy.js.map → BotAutomationsView-ktoci79V.js.map} +1 -1
  10. package/dist/assets/{BotPluginsDialog-MwGpwjgu.js → BotPluginsDialog-H85RI-7P.js} +2 -2
  11. package/dist/assets/{BotPluginsDialog-MwGpwjgu.js.map → BotPluginsDialog-H85RI-7P.js.map} +1 -1
  12. package/dist/assets/{BotSettingsDialog-DXtsSzi8.js → BotSettingsDialog-Ci_DZL4m.js} +5 -5
  13. package/dist/assets/{BotSettingsDialog-DXtsSzi8.js.map → BotSettingsDialog-Ci_DZL4m.js.map} +1 -1
  14. package/dist/assets/ChatView-6cdLMsuy.js +2 -0
  15. package/dist/assets/ChatView-6cdLMsuy.js.map +1 -0
  16. package/dist/assets/ChatView-C_7_7olu.css +1 -0
  17. package/dist/assets/{ComputerPanel-B0QyKQkF.js → ComputerPanel-Dbwgx5n8.js} +2 -2
  18. package/dist/assets/{ComputerPanel-B0QyKQkF.js.map → ComputerPanel-Dbwgx5n8.js.map} +1 -1
  19. package/dist/assets/{ComputerViewerView-CaOkTXpc.js → ComputerViewerView-csnhRedK.js} +2 -2
  20. package/dist/assets/{ComputerViewerView-CaOkTXpc.js.map → ComputerViewerView-csnhRedK.js.map} +1 -1
  21. package/dist/assets/ConversationsView-CEO2SVGT.js +6 -0
  22. package/dist/assets/ConversationsView-CEO2SVGT.js.map +1 -0
  23. package/dist/assets/{ConversationsView-C_VZl5g2.css → ConversationsView-CHLGKsJt.css} +1 -1
  24. package/dist/assets/FilesView-t5jA-H2-.js +2 -0
  25. package/dist/assets/{FilesView-CluNyIk8.js.map → FilesView-t5jA-H2-.js.map} +1 -1
  26. package/dist/assets/FloatingResourceSearch-3GOuDkuO.css +1 -0
  27. package/dist/assets/FloatingResourceSearch-BAYymuJV.js +9 -0
  28. package/dist/assets/FloatingResourceSearch-BAYymuJV.js.map +1 -0
  29. package/dist/assets/HistoryView-BqMSV9iC.js +2 -0
  30. package/dist/assets/HistoryView-BqMSV9iC.js.map +1 -0
  31. package/dist/assets/HistoryView-DlVfSP_p.css +1 -0
  32. package/dist/assets/KanbanView-CWwrwH9S.js +2 -0
  33. package/dist/assets/{KanbanView-D5AdRwqi.js.map → KanbanView-CWwrwH9S.js.map} +1 -1
  34. package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js → LocalVmSettingsPanel-BXvZwFQP.js} +2 -2
  35. package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js.map → LocalVmSettingsPanel-BXvZwFQP.js.map} +1 -1
  36. package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js → RunnerSettingsPanel-KkpIkkob.js} +2 -2
  37. package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js.map → RunnerSettingsPanel-KkpIkkob.js.map} +1 -1
  38. package/dist/assets/{StandaloneDialog-DdcL_wV2.js → StandaloneDialog-D4BQqjpB.js} +2 -2
  39. package/dist/assets/{StandaloneDialog-DdcL_wV2.js.map → StandaloneDialog-D4BQqjpB.js.map} +1 -1
  40. package/dist/assets/{UpdateCheckDialog-CJQezkXo.js → UpdateCheckDialog-Ct0bT6xU.js} +2 -2
  41. package/dist/assets/{UpdateCheckDialog-CJQezkXo.js.map → UpdateCheckDialog-Ct0bT6xU.js.map} +1 -1
  42. package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js → WorkspaceKnowledgePanel-WBcPB49x.js} +2 -2
  43. package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js.map → WorkspaceKnowledgePanel-WBcPB49x.js.map} +1 -1
  44. package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js → WorkspaceRoutinesPanel-JubUwGsV.js} +2 -2
  45. package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js.map → WorkspaceRoutinesPanel-JubUwGsV.js.map} +1 -1
  46. package/dist/assets/WorkspaceShell-0m4gg6AW.css +1 -0
  47. package/dist/assets/WorkspaceShell-Do2VAwIz.js +44 -0
  48. package/dist/assets/WorkspaceShell-Do2VAwIz.js.map +1 -0
  49. package/dist/assets/{WorkspaceView-Cco3Umfn.js → WorkspaceView-DTanioWW.js} +2 -2
  50. package/dist/assets/{WorkspaceView-Cco3Umfn.js.map → WorkspaceView-DTanioWW.js.map} +1 -1
  51. package/dist/assets/{docx-preview-C6qrP-g2.js → docx-preview-B1SjJgD_.js} +2 -2
  52. package/dist/assets/{docx-preview-C6qrP-g2.js.map → docx-preview-B1SjJgD_.js.map} +1 -1
  53. package/dist/assets/index-CWamgtSb.js +17 -0
  54. package/dist/assets/index-CWamgtSb.js.map +1 -0
  55. package/dist/assets/{pdf-G3DUsfMb.js → pdf-DVDddcFC.js} +2 -2
  56. package/dist/assets/{pdf-G3DUsfMb.js.map → pdf-DVDddcFC.js.map} +1 -1
  57. package/dist/assets/sessionOwnership-0hdKcwOs.js +4 -0
  58. package/dist/assets/sessionOwnership-0hdKcwOs.js.map +1 -0
  59. package/dist/assets/{sessionOwnership-BTz0Fyp5.css → sessionOwnership-CfO8CfmZ.css} +1 -1
  60. package/dist/assets/{viewModels-DfaKvI0x.js → viewModels-DKBqaDRg.js} +12 -12
  61. package/dist/assets/{viewModels-DfaKvI0x.js.map → viewModels-DKBqaDRg.js.map} +1 -1
  62. package/dist/index.html +1 -1
  63. package/dist-server/runner/agent.js +15 -4
  64. package/dist-server/runner/hermes-bots-bridge/README.md +4 -2
  65. package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +21 -2
  66. package/dist-server/runner/hermes-bots-bridge/plugin.yaml +1 -1
  67. package/dist-server/runner/worker/gateway.js +52 -22
  68. package/dist-server/runner/worker/profileSession.js +2 -12
  69. package/dist-server/server/app.js +15 -1
  70. package/dist-server/server/chatTranscriptApi.js +2 -2
  71. package/dist-server/server/chatTranscriptStore.js +16 -0
  72. package/dist-server/server/config.js +3 -0
  73. package/dist-server/server/credentialVault/broker.js +272 -0
  74. package/dist-server/server/credentialVault/coordinator.js +297 -0
  75. package/dist-server/server/credentialVault/executor.js +1 -0
  76. package/dist-server/server/credentialVault/fixtureWebsiteExecutor.js +51 -0
  77. package/dist-server/server/credentialVault/index.js +49 -0
  78. package/dist-server/server/credentialVault/isolation.js +37 -0
  79. package/dist-server/server/credentialVault/privateFiles.js +17 -0
  80. package/dist-server/server/credentialVault/protectedExecutor.js +21 -0
  81. package/dist-server/server/credentialVault/schema.js +45 -0
  82. package/dist-server/server/credentialVault/sshExecutor.js +135 -0
  83. package/dist-server/server/credentialVault/store.js +308 -0
  84. package/dist-server/server/credentialVault/transport.js +127 -0
  85. package/dist-server/server/credentialVault/websiteExecutor.js +102 -0
  86. package/dist-server/server/desktopEnvironments.js +2 -2
  87. package/dist-server/server/hermesRuntimeEnvironment.js +14 -0
  88. package/dist-server/server/localAuth.js +5 -0
  89. package/dist-server/server/openVikingMemoryProvider.js +29 -10
  90. package/dist-server/server/openVikingService.js +44 -14
  91. package/dist-server/server/openVikingSessionSync.js +148 -37
  92. package/dist-server/server/pushCoordinator.js +7 -4
  93. package/dist-server/server/realtimeApi.js +11 -2
  94. package/dist-server/server/realtimeBroker.js +1 -1
  95. package/dist-server/server/realtimeReceipts.js +39 -8
  96. package/dist-server/server/routes.js +18 -0
  97. package/dist-server/server/runnerHub.js +17 -4
  98. package/dist-server/server/sessionStop.js +19 -0
  99. package/dist-server/server/subaccountAccess.js +12 -0
  100. package/dist-server/server/taskCoordinator.js +3 -1
  101. package/dist-server/server/unreadCenter.js +61 -0
  102. package/dist-server/server/uploads.js +4 -1
  103. package/dist-server/server/workspaceAssets.js +56 -12
  104. package/dist-server/server/workspaceEnvironment.js +1 -0
  105. package/dist-server/server/workspaceMemorySynthesis.js +5 -1
  106. package/dist-server/server/workspacePrompt.js +5 -1
  107. package/dist-server/server/workspaceRoutes.js +26 -21
  108. package/dist-server/server/workspaceRuntime.js +89 -8
  109. package/dist-server/server/workspaceScheduler.js +5 -1
  110. package/dist-server/server/workspaceStore.js +125 -47
  111. package/dist-server/server/workspaceSync.js +4 -1
  112. package/dist-server/shared/botEnvironment.js +3 -3
  113. package/dist-server/shared/credentialVault.js +2 -0
  114. package/dist-server/shared/unread.js +6 -0
  115. package/dist-server/shared/uploadNames.js +14 -0
  116. package/licenses/libsodium.js/LICENSE +16 -0
  117. package/licenses/ssh2/LICENSE +19 -0
  118. package/package.json +8 -5
  119. package/release.json +3 -3
  120. package/dist/assets/AboutDialog-fbm5CG09.js.map +0 -1
  121. package/dist/assets/BotAutomationsView-DPAAYyuy.js +0 -2
  122. package/dist/assets/ChatView-BNqHa6Ma.js +0 -2
  123. package/dist/assets/ChatView-BNqHa6Ma.js.map +0 -1
  124. package/dist/assets/ChatView-Dx8YlcPr.css +0 -1
  125. package/dist/assets/ConversationsView-CYNc59hv.js +0 -6
  126. package/dist/assets/ConversationsView-CYNc59hv.js.map +0 -1
  127. package/dist/assets/FilesView-CluNyIk8.js +0 -2
  128. package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +0 -1
  129. package/dist/assets/FloatingResourceSearch-Bg5rUZMy.js +0 -9
  130. package/dist/assets/FloatingResourceSearch-Bg5rUZMy.js.map +0 -1
  131. package/dist/assets/HistoryView-DSbSDzsB.js +0 -2
  132. package/dist/assets/HistoryView-DSbSDzsB.js.map +0 -1
  133. package/dist/assets/HistoryView-DvuCAjlo.css +0 -1
  134. package/dist/assets/KanbanView-D5AdRwqi.js +0 -2
  135. package/dist/assets/WorkspaceShell-7wn8iTne.css +0 -1
  136. package/dist/assets/WorkspaceShell-Bykfy3AR.js +0 -44
  137. package/dist/assets/WorkspaceShell-Bykfy3AR.js.map +0 -1
  138. package/dist/assets/index-CEqMqiJr.js +0 -17
  139. package/dist/assets/index-CEqMqiJr.js.map +0 -1
  140. package/dist/assets/sessionOwnership-DMfBRINe.js +0 -6
  141. package/dist/assets/sessionOwnership-DMfBRINe.js.map +0 -1
@@ -5,6 +5,7 @@ import { basename, extname, join, resolve, sep } from 'node:path';
5
5
  import { DatabaseSync } from 'node:sqlite';
6
6
  import Busboy from 'busboy';
7
7
  import { HttpError } from './errors.js';
8
+ import { normalizeUploadName } from '../shared/uploadNames.js';
8
9
  export const MAX_UPLOAD_FILE_BYTES = 25 * 1_024 * 1_024;
9
10
  export const MAX_UPLOAD_REQUEST_BYTES = 50 * 1_024 * 1_024;
10
11
  export const MAX_UPLOAD_FILES = 8;
@@ -117,7 +118,7 @@ export class UploadStore {
117
118
  return {
118
119
  id: row.id,
119
120
  accountKey: row.account_key,
120
- name: row.name,
121
+ name: normalizeUploadName(row.name),
121
122
  mimeType: row.mime_type,
122
123
  size: Number(row.size),
123
124
  path: row.path,
@@ -179,6 +180,8 @@ export async function receiveGroupUploads(request, store, accountKey) {
179
180
  }
180
181
  const busboy = Busboy({
181
182
  headers: request.headers,
183
+ // Browser FormData sends ordinary filename parameters as UTF-8 bytes.
184
+ defParamCharset: 'utf8',
182
185
  limits: {
183
186
  files: MAX_UPLOAD_FILES,
184
187
  fileSize: MAX_UPLOAD_FILE_BYTES,
@@ -2,13 +2,16 @@ 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';
8
+ import { normalizeUploadName } from '../shared/uploadNames.js';
7
9
  import { WorkspaceStore } from './workspaceStore.js';
8
10
  import { WorkspaceNodes } from './workspaceGateway.js';
11
+ const archiveKey = (nodeId, profile, messageId, path) => createHash('sha256').update(JSON.stringify([nodeId, profile, messageId, path])).digest('hex');
9
12
  export function publicFile(f) {
10
13
  const { path: _path, digest: _digest, messageFileSource: _source, ...result } = f;
11
- return result;
14
+ return result.sender === 'user' ? { ...result, name: normalizeUploadName(result.name) } : result;
12
15
  }
13
16
  export function libraryFile(f, id, conversation) {
14
17
  const path = `/api/app/files/${f.id}/download`;
@@ -76,6 +79,42 @@ export class WorkspaceAssets {
76
79
  this.nodes = nodes;
77
80
  this.home = home;
78
81
  }
82
+ requireCapacity(owner, messageId, bytes) {
83
+ 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);
84
+ if (bytes > 25 * 1024 * 1024 || count >= 8)
85
+ throw new HttpError(413, '每轮最多 8 个产物,每个不超过 25 MiB', 'artifact_limit');
86
+ 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);
87
+ if (used + bytes > 2 * 1024 * 1024 * 1024)
88
+ throw new HttpError(413, '产物存储空间已达上限', 'artifact_quota');
89
+ }
90
+ /** Legacy archives lost nodeId, but their immutable archive key includes it.
91
+ * Restore only a unique authorized match; never assume a file came from local. */
92
+ recoverFileSource(owner, file) {
93
+ if (file.sourceNodeId || !file.sourcePath || !file.profile || !file.messageId)
94
+ return file;
95
+ 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);
96
+ if (records !== 1)
97
+ return file;
98
+ const candidates = ['local', ...this.store.list(owner, 'node').map(node => node.id)];
99
+ let revokedMatch = false;
100
+ const matches = [...new Set(candidates)].filter(nodeId => {
101
+ if (!this.store.get(owner, 'archived-path', archiveKey(nodeId, file.profile, file.messageId, file.sourcePath)))
102
+ return false;
103
+ try {
104
+ this.nodes.requireSource(owner, { nodeId, profile: file.profile });
105
+ }
106
+ catch {
107
+ revokedMatch = true;
108
+ return false;
109
+ }
110
+ return true;
111
+ });
112
+ if (revokedMatch || matches.length !== 1)
113
+ return file;
114
+ const recovered = { ...file, sourceNodeId: matches[0] };
115
+ this.store.put(owner, 'file', file.id, recovered);
116
+ return recovered;
117
+ }
79
118
  publish(owner, message, agent, name, bytes) {
80
119
  const digest = createHash('sha256').update(bytes).digest('hex');
81
120
  name = basename(name).replace(/[\\/\u0000-\u001f\u007f]/g, '_').slice(0, 240) || 'artifact';
@@ -83,11 +122,7 @@ export class WorkspaceAssets {
83
122
  const existing = files.find(file => file.messageId === message.id && file.name === name && file.digest === digest);
84
123
  if (existing)
85
124
  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');
125
+ this.requireCapacity(owner, message.id, bytes.length);
91
126
  const dir = join(this.home, 'workspace-files', owner);
92
127
  mkdirSync(dir, { recursive: true, mode: 0o700 });
93
128
  const path = join(dir, digest);
@@ -132,20 +167,28 @@ export class WorkspaceAssets {
132
167
  }
133
168
  }
134
169
  for (const path of [...paths].slice(0, 8)) {
135
- const key = createHash('sha256')
136
- .update(JSON.stringify([nodeId, profile, messageId, path]))
137
- .digest('hex');
170
+ const key = archiveKey(nodeId, profile, messageId, path);
138
171
  if (this.store.get(owner, 'archived-path', key) || this.pending.has(`${owner}:${key}`))
139
172
  continue;
140
173
  this.pending.add(`${owner}:${key}`);
141
174
  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 }),
175
+ this.nodes.requireSource(owner, { nodeId, profile });
176
+ this.requireCapacity(owner, messageId, 0);
177
+ const target = remoteAgentId ? this.nodes.targetForAgent(owner, { nodeId, remoteAgentId }) : this.nodes.target(owner, nodeId);
178
+ const authorizedPath = await authorizeFileRead({ home: this.home }, target.session, path, profile);
179
+ this.nodes.requireSource(owner, { nodeId, profile });
180
+ const response = await target.session.request('/api/files/download', {
181
+ search: new URLSearchParams({ profile, path: authorizedPath }),
145
182
  maxResponseBytes: 25 * 1024 * 1024,
146
183
  });
147
184
  if (response.status !== 200 || this.stopped)
148
185
  continue;
186
+ // A download may outlive an assignment or directory-policy change.
187
+ this.nodes.requireSource(owner, { nodeId, profile });
188
+ if (await authorizeFileRead({ home: this.home }, target.session, path, profile) !== authorizedPath || this.stopped)
189
+ continue;
190
+ this.nodes.requireSource(owner, { nodeId, profile });
191
+ this.requireCapacity(owner, messageId, response.body.length);
149
192
  const dir = join(this.home, 'workspace-files', owner);
150
193
  mkdirSync(dir, { recursive: true, mode: 0o700 });
151
194
  const digest = createHash('sha256').update(response.body).digest('hex');
@@ -168,6 +211,7 @@ export class WorkspaceAssets {
168
211
  size: response.body.length,
169
212
  sender,
170
213
  profile,
214
+ sourceNodeId: nodeId,
171
215
  conversationId,
172
216
  messageId,
173
217
  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
  });
@@ -472,7 +477,7 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
472
477
  const activeContent = /(?:html|svg|javascript|ecmascript|xml)/i.test(file.mimeType) ||
473
478
  /\.(?:html?|svg|js|mjs|xml|xhtml)$/i.test(file.name);
474
479
  ctx.type = activeContent ? 'application/octet-stream' : file.mimeType;
475
- ctx.set('Content-Disposition', `${action === 'preview' && !activeContent ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(file.name)}`);
480
+ ctx.set('Content-Disposition', `${action === 'preview' && !activeContent ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(publicFile(file).name)}`);
476
481
  ctx.set('Accept-Ranges', 'bytes');
477
482
  ctx.set('Cache-Control', 'private, no-store');
478
483
  if (size === 0) {
@@ -1,3 +1,4 @@
1
+ import { CREDENTIAL_TOOLS } from './credentialVault/coordinator.js';
1
2
  import { isLocalAuthorizationTarget } from './loopbackAuthorization.js';
2
3
  import {} from './managedBrowsers.js';
3
4
  import { ToolOperationJournal } from './toolOperationJournal.js';
@@ -5,6 +6,7 @@ import { browserOwnedFile, browserVmFile } from './browserFiles.js';
5
6
  import {} from './desktopEnvironments.js';
6
7
  import {} from './grokCloud.js';
7
8
  import { VmToolSession } from './vmComputer.js';
9
+ import { waitForHermesSessionIdle } from './sessionStop.js';
8
10
  import { randomUUID } from 'node:crypto';
9
11
  import { setTimeout as delay } from 'node:timers/promises';
10
12
  import { readFileSync } from 'node:fs';
@@ -17,6 +19,7 @@ import {} from './workspaceAssets.js';
17
19
  import { UploadStore } from './uploads.js';
18
20
  import { buildWorkspacePrompt } from './workspacePrompt.js';
19
21
  import { buildWorkspaceEnvironment, workspaceEnvironmentTools } from './workspaceEnvironment.js';
22
+ import { parseHermesRuntimeMetadata } from './hermesRuntimeEnvironment.js';
20
23
  import { readHostTools } from './hostToolSettings.js';
21
24
  import { resolveBotModelSettings, applyBotModelSettings, botModelTarget, BotModelConfirmationError } from './botModelSettings.js';
22
25
  function globalComputers(home) {
@@ -77,12 +80,13 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
77
80
  executionTurns = new Map();
78
81
  activeExecutionTurns() { return [...this.executionTurns.values()]; }
79
82
  executionSettings;
83
+ credentialVault;
80
84
  plugins;
81
85
  managedBrowsers;
82
86
  operationJournal;
83
87
  assertCanSubmit = () => { };
84
88
  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();
89
+ 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
90
  }
87
91
  desktopEnvironments;
88
92
  cloud;
@@ -90,6 +94,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
90
94
  computerAvailable;
91
95
  inspector;
92
96
  live = new Map();
97
+ memoryCleanup;
98
+ memoryCleanupRetries = new Map();
93
99
  teamTools;
94
100
  routineTools;
95
101
  tasks;
@@ -103,6 +109,9 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
103
109
  this.authorizationVersion = authorizationVersion;
104
110
  this.operationJournal = new ToolOperationJournal(store);
105
111
  this.openViking = openViking;
112
+ if (openViking)
113
+ openViking.onConfigurationChanged = () => { if (!this.closing)
114
+ this.wake(); };
106
115
  this.teamTools = new WorkspaceTeamTools(store, nodes, this);
107
116
  this.tasks = new WorkspaceTaskCoordinator(store, this);
108
117
  this.knowledge = new WorkspaceKnowledge(store.home, store, openViking);
@@ -120,10 +129,60 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
120
129
  return;
121
130
  await this.openViking.ensureUser(owner, { id, temporaryGoalId: undefined });
122
131
  }
132
+ maintenance() {
133
+ if (!this.openViking?.enabled)
134
+ return false;
135
+ const pending = new Map();
136
+ for (const owner of this.store.owners()) {
137
+ for (const item of this.store.list(owner, 'agent-deletion'))
138
+ if (item.memoryCleanupPending)
139
+ pending.set(`${owner}:${item.id}`, { owner, id: item.id });
140
+ for (const binding of this.store.list(owner, 'openviking-binding'))
141
+ if (binding.namespace === this.openViking.namespace && binding.status === 'removed' && binding.pendingRemoval)
142
+ pending.set(`${owner}:${binding.agentId}`, { owner, id: binding.agentId });
143
+ }
144
+ if (!this.memoryCleanup) {
145
+ const next = [...pending.entries()].find(([key]) => (this.memoryCleanupRetries.get(key)?.after ?? 0) <= Date.now());
146
+ if (next) {
147
+ const [key, { owner, id }] = next;
148
+ this.memoryCleanup = this.cleanupAgent(owner, id).then(() => { this.memoryCleanupRetries.delete(key); })
149
+ .catch(error => {
150
+ if (this.closing)
151
+ return;
152
+ const attempt = (this.memoryCleanupRetries.get(key)?.attempt ?? 0) + 1;
153
+ this.memoryCleanupRetries.set(key, { attempt, after: Date.now() + Math.min(30_000, 500 * 2 ** Math.min(attempt - 1, 6)) });
154
+ const deletion = this.store.get(owner, 'agent-deletion', id);
155
+ if (deletion) {
156
+ deletion.cleanupError = error instanceof Error ? error.message : '远端记忆清理失败';
157
+ this.store.put(owner, 'agent-deletion', id, deletion);
158
+ }
159
+ }).finally(() => { this.memoryCleanup = undefined; this.wake(); });
160
+ }
161
+ }
162
+ return pending.size > 0;
163
+ }
123
164
  async cleanupAgent(owner, id) {
124
- if (!this.openViking)
125
- return;
126
- await this.openViking.removeUser(owner, { id, temporaryGoalId: undefined });
165
+ await this.openViking?.removeUser(owner, { id, temporaryGoalId: undefined });
166
+ const deletion = this.store.get(owner, 'agent-deletion', id);
167
+ if (deletion) {
168
+ deletion.memoryCleanupPending = this.openViking?.binding(owner, id)?.pendingRemoval === true;
169
+ delete deletion.cleanupError;
170
+ this.store.put(owner, 'agent-deletion', id, deletion);
171
+ }
172
+ }
173
+ async deleteAgent(owner, id) {
174
+ // Commit all local validation/deletion before any destructive remote action.
175
+ // The durable tombstone also makes a repeated DELETE retry remote cleanup.
176
+ if (this.store.get(owner, 'agent', id))
177
+ this.store.deleteAgent(owner, id);
178
+ else if (!this.store.get(owner, 'agent-deletion', id))
179
+ this.store.require(owner, 'agent', id);
180
+ try {
181
+ await this.cleanupAgent(owner, id);
182
+ }
183
+ finally {
184
+ this.wake();
185
+ }
127
186
  }
128
187
  send(owner, conversationId, input) {
129
188
  return this.submit(owner, conversationId, input);
@@ -133,7 +192,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
133
192
  const response = await target.session.request('/api/plugins/yaoyao-bot-bridge/capabilities', { search: new URLSearchParams({ profile: agent.profile }) });
134
193
  const value = JSON.parse(response.body.toString());
135
194
  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 };
195
+ const runtime = response.status === 200 ? parseHermesRuntimeMetadata(value.runtime_environment, agent.profile) : undefined;
196
+ return { tools, memory: tools && value.memory_isolation === true, extraction: value.memory_extraction === true, ...(runtime ? { runtime } : {}) };
137
197
  }
138
198
  catch (error) {
139
199
  if (error instanceof HttpError && RESOURCE_WAIT_CODES.has(error.code ?? ''))
@@ -179,6 +239,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
179
239
  for (const id of source?.targetAgentId ? [source.targetAgentId] : c.memberIds)
180
240
  this.knowledge.requireProjectMember(owner, projectId, id);
181
241
  const conversationTask = this.store.resolveTask(owner, conversationId, body.taskId), conversationTaskId = conversationTask?.id;
242
+ if (this.store.hasPendingCleanup(owner, { conversationId, conversationTaskId }))
243
+ throw new HttpError(409, '原执行尚未确认停止,请等待停止完成后再发消息', 'conversation_stopping');
182
244
  if (conversationTaskId) {
183
245
  const alreadyActive = this.store.list(owner, 'run').some(run => run.conversationTaskId === conversationTaskId && !['complete', 'failed', 'interrupted'].includes(run.status));
184
246
  if (!alreadyActive && this.store.activeTaskCount(owner, conversationId) >= WORKSPACE_CONCURRENCY_LIMIT)
@@ -376,6 +438,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
376
438
  let reconnecting;
377
439
  const toolController = new AbortController();
378
440
  let toolLease;
441
+ let credentialTurn;
379
442
  let pluginLease;
380
443
  let resolveTurn, rejectTurn;
381
444
  const completion = new Promise((resolve, reject) => {
@@ -397,6 +460,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
397
460
  catch { /* Missing/revoked work must not retain a browser. */ }
398
461
  void browserTurn?.close({ retain: retainBrowser }).catch(() => { });
399
462
  toolController.abort();
463
+ credentialTurn?.close();
400
464
  void toolLease?.dispose();
401
465
  void pluginLease?.dispose();
402
466
  clearTimeout(flushTimer);
@@ -903,7 +967,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
903
967
  const globals = globalComputers(this.store.home);
904
968
  const desktopSnapshot = this.desktopEnvironments?.snapshot(owner, agent, root.deviceHost, { script: globals.scriptMachine, server: globals.serverComputer, maxMiB: globals.fileTransferMaxMiB })
905
969
  ?? { 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) });
970
+ 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
971
  const { cloud, plugins, vm: dispatchedVm } = environment.tools;
908
972
  const desktop = environment.tools.desktopView || environment.tools.desktopFile;
909
973
  const desktopEpochs = Object.fromEntries(environment.desktop.hosts.map(host => [host.id, host.epoch ?? '']));
@@ -937,7 +1001,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
937
1001
  }
938
1002
  return name === '__file_transfer' ? vmHolder.session.transfer(args) : vmHolder.session.call(name, args, callId);
939
1003
  };
940
- if (team || cloud || desktop || plugins || knowledge || routines || dispatchedVm || environment.tools.managedBrowser || (execution && botCapabilities.tools)) {
1004
+ if (team || cloud || desktop || plugins || knowledge || routines || dispatchedVm || environment.tools.managedBrowser || (execution && botCapabilities.tools) || (this.credentialVault?.client.configured && botCapabilities.tools)) {
941
1005
  if (team) {
942
1006
  const granted = this.getWork(owner, run.id);
943
1007
  granted.teamManagementRevision = agent.revision;
@@ -977,9 +1041,21 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
977
1041
  // the preferred target. Each dispatched environment checks its grants.
978
1042
  ...(execution ? { computerPolicy: { mode: 'profile', hostAccess: true } } : {}),
979
1043
  session: () => ({ runtimeId, storedId: binding.storedId }), assertActive,
980
- catalog: () => [...(team ? this.teamTools.catalog(owner, run.id) : []), ...(routines ? this.routineTools.catalog(owner, run.id) : []), ...(knowledge ? this.knowledgeTools.catalog(owner, run.id, botCapabilities.memory) : []), ...environmentCatalog, ...(systemTurn?.catalog() ?? []), ...(pluginLease?.catalog() ?? [])],
1044
+ catalog: () => [...(this.credentialVault?.client.configured && botCapabilities.tools ? CREDENTIAL_TOOLS : []), ...(team ? this.teamTools.catalog(owner, run.id) : []), ...(routines ? this.routineTools.catalog(owner, run.id) : []), ...(knowledge ? this.knowledgeTools.catalog(owner, run.id, botCapabilities.memory) : []), ...environmentCatalog, ...(systemTurn?.catalog() ?? []), ...(pluginLease?.catalog() ?? [])],
981
1045
  call: async (toolId, args, callId) => {
982
1046
  assertActive();
1047
+ if (toolId.startsWith('credential_') && this.credentialVault?.client.configured && botCapabilities.tools) {
1048
+ credentialTurn ??= this.credentialVault.openTurn(owner, agent.id, run.id, toolController.signal, assertActive, value => {
1049
+ if (settled || toolController.signal.aborted)
1050
+ return;
1051
+ const work = this.getWork(owner, run.id);
1052
+ if (!['running', 'waiting'].includes(work.status))
1053
+ return;
1054
+ work.status = value ? 'waiting' : 'running';
1055
+ this.saveWork(owner, work);
1056
+ });
1057
+ return credentialTurn.call(toolId, args);
1058
+ }
983
1059
  if (toolId === 'yaoyao_service_request' && systemTurn)
984
1060
  return systemTurn.call(args, toolController.signal);
985
1061
  if (this.routineTools?.handles(toolId))
@@ -1231,6 +1307,9 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
1231
1307
  if (live?.taskId === work.id) {
1232
1308
  try {
1233
1309
  await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId });
1310
+ const binding = this.store.require(owner, 'binding', key);
1311
+ if (binding.execution !== 'computer')
1312
+ await waitForHermesSessionIdle((method, params) => live.gateway.rpc(method, params), live.runtimeId, binding.profile);
1234
1313
  }
1235
1314
  catch (error) {
1236
1315
  if (!live.gateway.connected)
@@ -1268,6 +1347,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
1268
1347
  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
1348
  if (opened.running)
1270
1349
  await gateway.rpc('session.interrupt', { session_id: opened.session_id });
1350
+ if (binding.execution !== 'computer')
1351
+ await waitForHermesSessionIdle((method, params) => gateway.rpc(method, params), String(opened.session_id), binding.profile);
1271
1352
  }
1272
1353
  finally {
1273
1354
  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.