@lsamien/yaoyao 0.4.79 → 0.4.81
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 +9 -7
- package/THIRD_PARTY_NOTICES.md +4 -0
- package/bin/hermes-yaoyao-updater.mjs +97 -1
- package/bin/lib/npm-release.d.mts +10 -0
- package/bin/lib/npm-release.mjs +93 -0
- package/build-info.json +22 -3
- package/desktop/main.mjs +28 -26
- package/dist/assets/{AboutDialog-CrajAC--.js → AboutDialog-g6pYSCjs.js} +2 -2
- package/dist/assets/{AboutDialog-CrajAC--.js.map → AboutDialog-g6pYSCjs.js.map} +1 -1
- package/dist/assets/{BotAutomationsView-DTOoFSEl.js → BotAutomationsView-D1qf-5yf.js} +2 -2
- package/dist/assets/{BotAutomationsView-DTOoFSEl.js.map → BotAutomationsView-D1qf-5yf.js.map} +1 -1
- package/dist/assets/BotPluginsDialog-B0iR4Jy2.css +1 -0
- package/dist/assets/BotPluginsDialog-BOSzPlLZ.js +2 -0
- package/dist/assets/BotPluginsDialog-BOSzPlLZ.js.map +1 -0
- package/dist/assets/{BotSettingsDialog-ChffrjSM.js → BotSettingsDialog-Ba-380qV.js} +4 -4
- package/dist/assets/{BotSettingsDialog-ChffrjSM.js.map → BotSettingsDialog-Ba-380qV.js.map} +1 -1
- package/dist/assets/ChatView-ClK12dmT.css +1 -0
- package/dist/assets/ChatView-DHyj3yzu.js +2 -0
- package/dist/assets/ChatView-DHyj3yzu.js.map +1 -0
- package/dist/assets/{ComputerPanel-bNkvZAiT.js → ComputerPanel-D1hglwwV.js} +2 -2
- package/dist/assets/{ComputerPanel-bNkvZAiT.js.map → ComputerPanel-D1hglwwV.js.map} +1 -1
- package/dist/assets/{ComputerViewerView-DCTvbHr-.js → ComputerViewerView-BDL1eNKT.js} +2 -2
- package/dist/assets/{ComputerViewerView-DCTvbHr-.js.map → ComputerViewerView-BDL1eNKT.js.map} +1 -1
- package/dist/assets/{ConversationsView-BnysxvX_.js → ConversationsView-BaWBEaBU.js} +5 -5
- package/dist/assets/{ConversationsView-BnysxvX_.js.map → ConversationsView-BaWBEaBU.js.map} +1 -1
- package/dist/assets/{ConversationsView-CbArO1v2.css → ConversationsView-CdPjaDik.css} +1 -1
- package/dist/assets/{FilesView-D7tA6Nu1.js → FilesView-AjaCIyCs.js} +2 -2
- package/dist/assets/{FilesView-D7tA6Nu1.js.map → FilesView-AjaCIyCs.js.map} +1 -1
- package/dist/assets/FloatingResourceSearch-CeLuyNWO.js +9 -0
- package/dist/assets/{FloatingResourceSearch-c6l1JuAA.js.map → FloatingResourceSearch-CeLuyNWO.js.map} +1 -1
- package/dist/assets/{FloatingResourceSearch-3GOuDkuO.css → FloatingResourceSearch-CqauCQAf.css} +1 -1
- package/dist/assets/{HistoryView-Cnsriop4.js → HistoryView-C96yRoyB.js} +2 -2
- package/dist/assets/{HistoryView-Cnsriop4.js.map → HistoryView-C96yRoyB.js.map} +1 -1
- package/dist/assets/{KanbanView-CXm05b62.js → KanbanView-CVbjfqiX.js} +2 -2
- package/dist/assets/{KanbanView-CXm05b62.js.map → KanbanView-CVbjfqiX.js.map} +1 -1
- package/dist/assets/{LocalVmSettingsPanel-HgNC1SCF.js → LocalVmSettingsPanel-DcDIRVsO.js} +2 -2
- package/dist/assets/{LocalVmSettingsPanel-HgNC1SCF.js.map → LocalVmSettingsPanel-DcDIRVsO.js.map} +1 -1
- package/dist/assets/{RunnerSettingsPanel-CLKZvWua.js → RunnerSettingsPanel-XYeXVx5y.js} +2 -2
- package/dist/assets/{RunnerSettingsPanel-CLKZvWua.js.map → RunnerSettingsPanel-XYeXVx5y.js.map} +1 -1
- package/dist/assets/{StandaloneDialog-DODllzh1.js → StandaloneDialog-C6HIM_jc.js} +2 -2
- package/dist/assets/{StandaloneDialog-DODllzh1.js.map → StandaloneDialog-C6HIM_jc.js.map} +1 -1
- package/dist/assets/{UpdateCheckDialog-DHcAuryL.js → UpdateCheckDialog-Dv1d1s42.js} +2 -2
- package/dist/assets/{UpdateCheckDialog-DHcAuryL.js.map → UpdateCheckDialog-Dv1d1s42.js.map} +1 -1
- package/dist/assets/{WorkspaceKnowledgePanel-BrE8xSi2.js → WorkspaceKnowledgePanel-Dnauu0Hw.js} +2 -2
- package/dist/assets/{WorkspaceKnowledgePanel-BrE8xSi2.js.map → WorkspaceKnowledgePanel-Dnauu0Hw.js.map} +1 -1
- package/dist/assets/{WorkspaceRoutinesPanel-CpDVEwHx.js → WorkspaceRoutinesPanel-WNI3qP4D.js} +2 -2
- package/dist/assets/{WorkspaceRoutinesPanel-CpDVEwHx.js.map → WorkspaceRoutinesPanel-WNI3qP4D.js.map} +1 -1
- package/dist/assets/WorkspaceShell-BT92dIOL.css +1 -0
- package/dist/assets/WorkspaceShell-Bl2QMnvN.js +44 -0
- package/dist/assets/WorkspaceShell-Bl2QMnvN.js.map +1 -0
- package/dist/assets/{WorkspaceView-CBWFRLki.js → WorkspaceView-Dhdw4Kml.js} +2 -2
- package/dist/assets/{WorkspaceView-CBWFRLki.js.map → WorkspaceView-Dhdw4Kml.js.map} +1 -1
- package/dist/assets/{docx-preview-CG4CK2Qm.js → docx-preview-BNRkFvPc.js} +2 -2
- package/dist/assets/{docx-preview-CG4CK2Qm.js.map → docx-preview-BNRkFvPc.js.map} +1 -1
- package/dist/assets/{index-BRP9NWum.js → index-DU4OTLup.js} +3 -3
- package/dist/assets/{index-BRP9NWum.js.map → index-DU4OTLup.js.map} +1 -1
- package/dist/assets/{pdf-CFWXmhVF.js → pdf-C6_9GF5Z.js} +2 -2
- package/dist/assets/{pdf-CFWXmhVF.js.map → pdf-C6_9GF5Z.js.map} +1 -1
- package/dist/assets/{sessionOwnership-B2YxdBdf.js → sessionOwnership-D9vGe33s.js} +2 -2
- package/dist/assets/{sessionOwnership-B2YxdBdf.js.map → sessionOwnership-D9vGe33s.js.map} +1 -1
- package/dist/assets/{viewModels-CYJ8m5Uf.js → viewModels-BLN4GfVX.js} +5 -5
- package/dist/assets/viewModels-BLN4GfVX.js.map +1 -0
- package/dist/index.html +1 -1
- package/dist/provider-logos/airtable.svg +13 -0
- package/dist/provider-logos/discord.svg +15 -0
- package/dist/provider-logos/github.svg +10 -0
- package/dist/provider-logos/gmail.svg +1 -0
- package/dist/provider-logos/googlecalendar.svg +148 -0
- package/dist/provider-logos/googledrive.svg +25 -0
- package/dist/provider-logos/linear.svg +5 -0
- package/dist/provider-logos/notion.svg +11 -0
- package/dist/provider-logos/outlook.svg +76 -0
- package/dist/provider-logos/slack.svg +22 -0
- package/dist/provider-logos/trello.svg +19 -0
- package/dist/provider-logos/twitter.svg +128 -0
- package/dist-server/server/app.js +4 -2
- package/dist-server/server/botPlugins/connectedApps.js +3 -2
- package/dist-server/server/chatCache.js +3 -2
- package/dist-server/server/chatPresentation.js +32 -0
- package/dist-server/server/chatTranscriptApi.js +2 -1
- package/dist-server/server/config.js +2 -0
- package/dist-server/server/credentialVault/adapterExecutor.js +23 -0
- package/dist-server/server/credentialVault/botAccess.js +161 -0
- package/dist-server/server/credentialVault/broker.js +61 -6
- package/dist-server/server/credentialVault/coordinator.js +109 -14
- package/dist-server/server/credentialVault/localClient.js +191 -0
- package/dist-server/server/credentialVault/localExecutor.js +15 -0
- package/dist-server/server/credentialVault/protectedExecutor.js +3 -19
- package/dist-server/server/credentialVault/schema.js +11 -4
- package/dist-server/server/credentialVault/sshExecutor.js +111 -15
- package/dist-server/server/credentialVault/store.js +11 -5
- package/dist-server/server/credentialVault/transport.js +5 -1
- package/dist-server/server/dashboardCommand.js +62 -0
- package/dist-server/server/dashboardController.js +117 -25
- package/dist-server/server/jsonCompression.js +29 -0
- package/dist-server/server/routes.js +19 -1
- package/dist-server/server/runnerHub.js +12 -1
- package/dist-server/server/security.js +2 -1
- package/dist-server/server/updateManager.js +42 -10
- package/dist-server/server/workspaceRoutes.js +30 -4
- package/dist-server/server/workspaceSync.js +22 -4
- package/dist-server/shared/botProviderLogos.js +61 -0
- package/dist-server/shared/desktopUpdate.js +1 -0
- package/package.json +1 -1
- package/release.json +3 -3
- package/dist/assets/BotPluginsDialog-Ckiwmito.js +0 -2
- package/dist/assets/BotPluginsDialog-Ckiwmito.js.map +0 -1
- package/dist/assets/BotPluginsDialog-Db5dTqvg.css +0 -1
- package/dist/assets/ChatView-C_7_7olu.css +0 -1
- package/dist/assets/ChatView-znZF8RZE.js +0 -2
- package/dist/assets/ChatView-znZF8RZE.js.map +0 -1
- package/dist/assets/FloatingResourceSearch-c6l1JuAA.js +0 -9
- package/dist/assets/WorkspaceShell-Dhm3r61t.js +0 -44
- package/dist/assets/WorkspaceShell-Dhm3r61t.js.map +0 -1
- package/dist/assets/WorkspaceShell-Dk003lIq.css +0 -1
- package/dist/assets/viewModels-CYJ8m5Uf.js.map +0 -1
|
@@ -1,19 +1,34 @@
|
|
|
1
|
-
import { execFile } from 'node:child_process';
|
|
2
|
-
import { basename } from 'node:path';
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
3
2
|
import { promisify } from 'node:util';
|
|
3
|
+
import { isAbsolute } from 'node:path';
|
|
4
|
+
import { dashboardCommandIndex, standaloneDashboardCommand } from './dashboardCommand.js';
|
|
5
|
+
import { LoopbackTransport } from './loopbackAuthorization.js';
|
|
4
6
|
const execFileAsync = promisify(execFile);
|
|
5
7
|
const labels = ['com.samien.hermes.dashboard.local', 'ai.hermes.dashboard'];
|
|
6
8
|
const localOrigin = 'http://127.0.0.1:9119';
|
|
7
9
|
async function healthy(origin) {
|
|
10
|
+
const transport = new LoopbackTransport();
|
|
8
11
|
try {
|
|
9
|
-
const response = await fetch(`${origin}/api/health
|
|
12
|
+
const response = await transport.fetch(new URL(`${origin}/api/health`), { signal: AbortSignal.timeout(1000) });
|
|
10
13
|
await response.body?.cancel();
|
|
11
14
|
return response.ok;
|
|
12
15
|
}
|
|
13
16
|
catch {
|
|
14
17
|
return false;
|
|
15
18
|
}
|
|
19
|
+
finally {
|
|
20
|
+
transport.close();
|
|
21
|
+
}
|
|
16
22
|
}
|
|
23
|
+
const launch = (command, args, cwd) => new Promise((resolve, reject) => {
|
|
24
|
+
const env = { ...process.env };
|
|
25
|
+
for (const key of Object.keys(env))
|
|
26
|
+
if (key.startsWith('HERMES_YAOYAO_') || key.startsWith('ELECTRON_'))
|
|
27
|
+
delete env[key];
|
|
28
|
+
const child = spawn(command, args, { cwd, env, detached: true, stdio: 'ignore' });
|
|
29
|
+
child.once('error', reject);
|
|
30
|
+
child.once('spawn', () => { child.unref(); child.pid ? resolve(child.pid) : reject(new Error('Hermes Dashboard 启动失败。')); });
|
|
31
|
+
});
|
|
17
32
|
/** Runs only in the Yaoyao server. No browser, desktop IPC or client-supplied target is used. */
|
|
18
33
|
export class ServerDashboardController {
|
|
19
34
|
upstream;
|
|
@@ -24,6 +39,8 @@ export class ServerDashboardController {
|
|
|
24
39
|
healthy;
|
|
25
40
|
timeout;
|
|
26
41
|
interval;
|
|
42
|
+
launch;
|
|
43
|
+
launchedPid;
|
|
27
44
|
service;
|
|
28
45
|
restarting = false;
|
|
29
46
|
stopped = false;
|
|
@@ -34,8 +51,9 @@ export class ServerDashboardController {
|
|
|
34
51
|
this.uid = options.uid ?? process.getuid?.();
|
|
35
52
|
this.run = options.run ?? (async (command, args) => (await execFileAsync(command, args, { timeout: 3000, maxBuffer: 256 * 1024 })).stdout);
|
|
36
53
|
this.healthy = options.healthy ?? healthy;
|
|
37
|
-
this.timeout = options.readyTimeoutMs ??
|
|
54
|
+
this.timeout = options.readyTimeoutMs ?? 30000;
|
|
38
55
|
this.interval = options.pollIntervalMs ?? 250;
|
|
56
|
+
this.launch = options.launch ?? launch;
|
|
39
57
|
}
|
|
40
58
|
get canRestart() {
|
|
41
59
|
return !this.stopped && this.upstream.origin === localOrigin && (!!this.owned?.canRestart || !!this.service);
|
|
@@ -45,7 +63,7 @@ export class ServerDashboardController {
|
|
|
45
63
|
return '此 Hermes 不在夭夭服务端可管理的本机地址,请在 Hermes 所在节点重启。';
|
|
46
64
|
if (this.platform !== 'darwin')
|
|
47
65
|
return '夭夭服务端尚未支持此系统的外部 Dashboard 服务管理,请在 Hermes 所在节点重启。';
|
|
48
|
-
return '
|
|
66
|
+
return '夭夭服务端未识别到当前账号可管理的 9119 Hermes Dashboard 进程;请确认由本机 Hermes 命令启动且与夭夭使用同一系统账号。';
|
|
49
67
|
}
|
|
50
68
|
async refresh() {
|
|
51
69
|
if (this.restarting || this.stopped)
|
|
@@ -58,25 +76,94 @@ export class ServerDashboardController {
|
|
|
58
76
|
async discover() {
|
|
59
77
|
if (this.stopped || this.upstream.origin !== localOrigin || this.platform !== 'darwin' || this.uid === undefined)
|
|
60
78
|
return;
|
|
79
|
+
const pids = await this.listeners().catch(() => []);
|
|
80
|
+
if (pids.length !== 1)
|
|
81
|
+
return;
|
|
82
|
+
const pid = pids[0];
|
|
61
83
|
for (const label of labels) {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
84
|
+
const service = await this.launchAgent(label, pid);
|
|
85
|
+
if (service)
|
|
86
|
+
return service;
|
|
87
|
+
}
|
|
88
|
+
// Custom labels are common in manual installs. The listener PID, rather than
|
|
89
|
+
// a label alone, identifies the only candidate we may inspect and restart.
|
|
90
|
+
let jobs;
|
|
91
|
+
try {
|
|
92
|
+
const listing = await this.run('/bin/launchctl', ['list']);
|
|
93
|
+
jobs = [...listing.matchAll(/^\s*(\d+)\s+-?\d+\s+(\S+)\s*$/gm)].map(m => ({ pid: Number(m[1]), label: m[2] }));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const job = jobs.find(job => job.pid === pid);
|
|
99
|
+
if (job)
|
|
100
|
+
return this.launchAgent(job.label, pid);
|
|
101
|
+
const process = await this.process(pid);
|
|
102
|
+
if (!process || process.uid !== this.uid || this.uid === 0 || (pid !== this.launchedPid && jobs.some(job => job.pid === process.parent)))
|
|
103
|
+
return;
|
|
104
|
+
const invocation = standaloneDashboardCommand(process.command);
|
|
105
|
+
if (!invocation)
|
|
106
|
+
return;
|
|
107
|
+
if (process.parent !== 1 && pid !== this.launchedPid) {
|
|
108
|
+
const parent = await this.process(process.parent);
|
|
109
|
+
if (!parent || parent.uid !== this.uid || !/^(?:\S*\/)?-?(?:zsh|bash|sh|fish)(?:\s|$)/.test(parent.command))
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
// Module entry points can depend on the original working directory.
|
|
113
|
+
try {
|
|
114
|
+
const detail = await this.run('/usr/sbin/lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn']);
|
|
115
|
+
const paths = detail.split('\n').filter(line => line.startsWith('n')).map(line => line.slice(1));
|
|
116
|
+
const cwd = paths[0];
|
|
117
|
+
if (paths.length === 1 && cwd && isAbsolute(cwd) && !/[\r\0]/.test(cwd))
|
|
118
|
+
return { kind: 'standalone', pid, cwd, ...invocation };
|
|
119
|
+
}
|
|
120
|
+
catch { /* Do not stop a process we cannot reliably relaunch. */ }
|
|
121
|
+
}
|
|
122
|
+
async listeners() {
|
|
123
|
+
try {
|
|
124
|
+
const listeners = await this.run('/usr/sbin/lsof', ['-nP', '-a', '-iTCP:9119', '-sTCP:LISTEN', '-Fp']);
|
|
125
|
+
return [...new Set([...listeners.matchAll(/^p(\d+)$/gm)].map(match => Number(match[1])))];
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (error.code === 1)
|
|
129
|
+
return [];
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async launchAgent(label, listener) {
|
|
134
|
+
if (!/^[A-Za-z0-9_.-]+$/.test(label))
|
|
135
|
+
return;
|
|
136
|
+
const target = `gui/${this.uid}/${label}`;
|
|
137
|
+
try {
|
|
138
|
+
const detail = await this.run('/bin/launchctl', ['print', target]);
|
|
139
|
+
const pid = Number(detail.match(/^\s*pid = (\d+)\s*$/m)?.[1]);
|
|
140
|
+
const args = detail.match(/^\s*arguments = \{\n([\s\S]*?)^\s*\}/m)?.[1]?.trim().split('\n').map(line => line.trim()) ?? [];
|
|
141
|
+
if (pid === listener && dashboardCommandIndex(args) !== undefined)
|
|
142
|
+
return { kind: 'launchagent', target, pid };
|
|
143
|
+
}
|
|
144
|
+
catch { /* Missing job or unknown command: fail closed. */ }
|
|
145
|
+
}
|
|
146
|
+
async process(pid) {
|
|
147
|
+
try {
|
|
148
|
+
const detail = await this.run('/bin/ps', ['-p', String(pid), '-o', 'uid=', '-o', 'ppid=', '-o', 'command=']);
|
|
149
|
+
const match = /^\s*(\d+)\s+(\d+)\s+([^\r\n]+)\s*$/.exec(detail);
|
|
150
|
+
if (match)
|
|
151
|
+
return { uid: Number(match[1]), parent: Number(match[2]), command: match[3].trim() };
|
|
152
|
+
}
|
|
153
|
+
catch { /* Process has exited or is unreadable. */ }
|
|
154
|
+
}
|
|
155
|
+
async restartStandalone(service) {
|
|
156
|
+
// discover() has just checked the owner, executable and sole listener.
|
|
157
|
+
await this.run('/bin/kill', ['-TERM', String(service.pid)]);
|
|
158
|
+
const deadline = Date.now() + this.timeout;
|
|
159
|
+
while (!this.stopped && await this.process(service.pid)) {
|
|
160
|
+
if (Date.now() >= deadline)
|
|
161
|
+
throw new Error('Hermes Dashboard 未能停止,请在所在节点检查。');
|
|
162
|
+
await new Promise(resolve => setTimeout(resolve, this.interval));
|
|
79
163
|
}
|
|
164
|
+
if (this.stopped || (await this.listeners()).length)
|
|
165
|
+
throw new Error('9119 已被其他进程占用,未启动新的 Dashboard。');
|
|
166
|
+
this.launchedPid = await this.launch(service.command, service.args, service.cwd);
|
|
80
167
|
}
|
|
81
168
|
async restart() {
|
|
82
169
|
if (this.restarting)
|
|
@@ -97,13 +184,18 @@ export class ServerDashboardController {
|
|
|
97
184
|
previous = await this.discover();
|
|
98
185
|
if (!previous || this.stopped)
|
|
99
186
|
throw new Error(this.unavailableReason);
|
|
100
|
-
|
|
187
|
+
if (previous.kind === 'launchagent')
|
|
188
|
+
await this.run('/bin/launchctl', ['kickstart', '-k', previous.target]);
|
|
189
|
+
else
|
|
190
|
+
await this.restartStandalone(previous);
|
|
101
191
|
}
|
|
102
192
|
const deadline = Date.now() + this.timeout;
|
|
103
193
|
while (!this.stopped && Date.now() < deadline) {
|
|
104
194
|
const replacement = owned ? undefined : await this.discover();
|
|
105
|
-
const replaced = owned ? this.owned?.canRestart
|
|
106
|
-
|
|
195
|
+
const replaced = owned ? this.owned?.canRestart : replacement && previous && replacement.pid !== previous.pid
|
|
196
|
+
&& (replacement.kind === 'launchagent' && previous.kind === 'launchagent' ? replacement.target === previous.target
|
|
197
|
+
: replacement.kind === 'standalone' && previous.kind === 'standalone' && replacement.pid === this.launchedPid
|
|
198
|
+
&& replacement.command === previous.command && replacement.cwd === previous.cwd && JSON.stringify(replacement.args) === JSON.stringify(previous.args));
|
|
107
199
|
if (replaced && await this.healthy(this.upstream.origin) && !this.stopped) {
|
|
108
200
|
this.service = replacement;
|
|
109
201
|
return;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { gzip } from 'node:zlib';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
const compress = promisify(gzip);
|
|
4
|
+
/** Compress completed API documents only; SSE must flush each event unchanged. */
|
|
5
|
+
export const jsonCompression = async (ctx, next) => {
|
|
6
|
+
await next();
|
|
7
|
+
if (!ctx.path.startsWith('/api/') || ctx.method === 'HEAD' || ctx.status !== 200
|
|
8
|
+
|| ctx.respond === false || ctx.res.headersSent || !ctx.response.is('application/json')
|
|
9
|
+
|| ctx.response.get('Content-Encoding') || ctx.body == null)
|
|
10
|
+
return;
|
|
11
|
+
const value = ctx.body;
|
|
12
|
+
if (!Buffer.isBuffer(value) && typeof value !== 'string' && typeof value !== 'object')
|
|
13
|
+
return;
|
|
14
|
+
if (typeof value === 'object' && !Buffer.isBuffer(value) && 'pipe' in value)
|
|
15
|
+
return;
|
|
16
|
+
const body = Buffer.isBuffer(value) ? value : Buffer.from(typeof value === 'string' ? value : JSON.stringify(value));
|
|
17
|
+
if (body.length < 1024)
|
|
18
|
+
return;
|
|
19
|
+
ctx.vary('Accept-Encoding');
|
|
20
|
+
if (ctx.acceptsEncodings('gzip', 'identity') !== 'gzip')
|
|
21
|
+
return;
|
|
22
|
+
const compressed = await compress(body);
|
|
23
|
+
if (compressed.length >= body.length)
|
|
24
|
+
return;
|
|
25
|
+
ctx.set('Content-Encoding', 'gzip');
|
|
26
|
+
ctx.remove('Content-Length');
|
|
27
|
+
ctx.body = compressed;
|
|
28
|
+
ctx.type = 'application/json';
|
|
29
|
+
};
|
|
@@ -147,7 +147,7 @@ function requireLocalSystemUpdate(ctx, dependencies) {
|
|
|
147
147
|
}
|
|
148
148
|
function updateFailure(error) {
|
|
149
149
|
const message = error instanceof Error ? error.message : String(error);
|
|
150
|
-
if (
|
|
150
|
+
if (/最新版本|目标版本|正在执行|可回滚|不支持|没有可生效|已准备更新/.test(message)) {
|
|
151
151
|
return new HttpError(409, message, 'system_update_conflict');
|
|
152
152
|
}
|
|
153
153
|
return new HttpError(502, `无法访问系统发布源:${message}`, 'system_update_source_failed');
|
|
@@ -270,6 +270,9 @@ function isMissingSessionResponse(response) {
|
|
|
270
270
|
if (payload.code === 'session_not_found')
|
|
271
271
|
return true;
|
|
272
272
|
const detail = payload.detail;
|
|
273
|
+
// Hermes also uses this detail for a stored session absent from its history.
|
|
274
|
+
if (typeof detail === 'string' && /^not found[.!]?$/i.test(detail.trim()))
|
|
275
|
+
return true;
|
|
273
276
|
const message = [payload.error, payload.message, detail,
|
|
274
277
|
detail && typeof detail === 'object' && 'message' in detail ? detail.message : undefined]
|
|
275
278
|
.find(value => typeof value === 'string');
|
|
@@ -1886,6 +1889,19 @@ export function createApiRouter(dependencies) {
|
|
|
1886
1889
|
throw updateFailure(error);
|
|
1887
1890
|
}
|
|
1888
1891
|
});
|
|
1892
|
+
router.post('/api/app/system/update/activate', (ctx) => {
|
|
1893
|
+
dependencies.auth.requireAdmin(ctx);
|
|
1894
|
+
requireLocalSystemUpdate(ctx, dependencies);
|
|
1895
|
+
const jobID = body(ctx).jobID;
|
|
1896
|
+
if (typeof jobID !== 'string' || !/^[0-9a-f-]{36}$/.test(jobID))
|
|
1897
|
+
throw new HttpError(400, 'jobID 无效', 'invalid_request');
|
|
1898
|
+
try {
|
|
1899
|
+
json(ctx, 202, dependencies.updates.startActivation(jobID));
|
|
1900
|
+
}
|
|
1901
|
+
catch (error) {
|
|
1902
|
+
throw updateFailure(error);
|
|
1903
|
+
}
|
|
1904
|
+
});
|
|
1889
1905
|
router.get('/api/app/system/update/jobs/:jobID', async (ctx) => {
|
|
1890
1906
|
dependencies.auth.requireAdmin(ctx);
|
|
1891
1907
|
const job = dependencies.updates.job(ctx.params.jobID);
|
|
@@ -2069,6 +2085,7 @@ export function createApiRouter(dependencies) {
|
|
|
2069
2085
|
if (isMissingSessionResponse(existing)) {
|
|
2070
2086
|
// Only this account's cached copy remains; no upstream mutation is needed.
|
|
2071
2087
|
dependencies.chatCache?.store.deleteSession(owner, profile, id);
|
|
2088
|
+
dependencies.onChatListChanged?.(owner, profile, id);
|
|
2072
2089
|
ctx.body = { ok: true };
|
|
2073
2090
|
return;
|
|
2074
2091
|
}
|
|
@@ -2077,6 +2094,7 @@ export function createApiRouter(dependencies) {
|
|
|
2077
2094
|
const alreadyMissing = isMissingSessionResponse(response);
|
|
2078
2095
|
if ((response.status >= 200 && response.status < 300) || alreadyMissing) {
|
|
2079
2096
|
dependencies.chatCache?.store.deleteSession(owner, profile, id);
|
|
2097
|
+
dependencies.onChatListChanged?.(owner, profile, id);
|
|
2080
2098
|
}
|
|
2081
2099
|
if (alreadyMissing) {
|
|
2082
2100
|
ctx.body = { ok: true };
|
|
@@ -64,6 +64,7 @@ export class RunnerHub {
|
|
|
64
64
|
browserAllowed = () => false;
|
|
65
65
|
controlAllowed = () => false;
|
|
66
66
|
epoch = randomUUID();
|
|
67
|
+
credentialServerId = randomUUID();
|
|
67
68
|
online = new Map();
|
|
68
69
|
retired = new Map();
|
|
69
70
|
pending = new Map();
|
|
@@ -125,11 +126,21 @@ export class RunnerHub {
|
|
|
125
126
|
return result;
|
|
126
127
|
}
|
|
127
128
|
records() { return this.store.list('_system', 'runner'); }
|
|
128
|
-
credentialBinding(owner, agent) {
|
|
129
|
+
credentialBinding(owner, agent, location = 'node') {
|
|
129
130
|
if (agent.archived || !this.auth.canUseSource(owner, agent.nodeId, agent.profile))
|
|
130
131
|
throw new HttpError(403, 'Bot 凭据授权已结束', 'vault_agent_forbidden');
|
|
131
132
|
const record = this.records().find(r => r.enabled && r.sourceNodeId === agent.nodeId && (r.sourceOwner === '_system' || r.sourceOwner === owner));
|
|
132
133
|
const online = record && this.online.get(record.id);
|
|
134
|
+
if (location === 'server') {
|
|
135
|
+
if (record && (!online || Date.now() - online.seen >= 35000))
|
|
136
|
+
throw new HttpError(503, 'Bot 所在节点离线,请等待节点连接', 'vault_runner_offline');
|
|
137
|
+
if (record && !record.allowedProfiles.includes(agent.profile))
|
|
138
|
+
throw new HttpError(403, '执行节点未授权当前 Profile', 'vault_agent_forbidden');
|
|
139
|
+
// No Runner is needed for direct Hermes tasks. Existing Runner reconnects
|
|
140
|
+
// still change the binding, even though secrets remain in this server.
|
|
141
|
+
return { runnerId: this.credentialServerId, runnerInstance: this.epoch,
|
|
142
|
+
runnerEpoch: hash(JSON.stringify([agent.nodeId, agent.profile, record?.id, online?.instance, online?.epoch])) };
|
|
143
|
+
}
|
|
133
144
|
if (!record || !online || Date.now() - online.seen >= 35000)
|
|
134
145
|
throw new HttpError(503, '执行节点离线,请等待节点连接', 'vault_runner_offline');
|
|
135
146
|
if (!record.allowedProfiles.includes(agent.profile))
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { parse, serialize } from 'cookie';
|
|
3
3
|
import { isLoopbackHost, isPrivateHost } from './config.js';
|
|
4
|
+
import { BOT_LOGO_ORIGINS } from '../shared/botProviderLogos.js';
|
|
4
5
|
export const CSRF_COOKIE = 'hermes_yaoyao_csrf';
|
|
5
6
|
function splitHostPort(value) {
|
|
6
7
|
const trimmed = value.trim().toLowerCase();
|
|
@@ -179,7 +180,7 @@ export function applySecurityHeaders(ctx, tls, allowedHosts = new Set()) {
|
|
|
179
180
|
"object-src 'none'",
|
|
180
181
|
"script-src 'self'",
|
|
181
182
|
"style-src 'self' 'unsafe-inline'",
|
|
182
|
-
|
|
183
|
+
`img-src 'self' data: blob: ${BOT_LOGO_ORIGINS.join(' ')}`,
|
|
183
184
|
"media-src 'self' blob:",
|
|
184
185
|
`connect-src 'self' ${socketOrigin} ${proxySocketOrigins.join(' ')}`.trim(),
|
|
185
186
|
].join('; '));
|
|
@@ -8,6 +8,7 @@ import { join, resolve } from 'node:path';
|
|
|
8
8
|
import { spawn } from 'node:child_process';
|
|
9
9
|
import { DEFAULT_YAOYAO_RELEASE_SOURCE } from './config.js';
|
|
10
10
|
import { normalizeReleaseSource } from '../../bin/lib/release-source.mjs';
|
|
11
|
+
import { inspectNpmRelease, isNpmInstallation, NPM_RELEASE_SOURCE, verifyPreparedNpmArchive } from '../../bin/lib/npm-release.mjs';
|
|
11
12
|
import { githubReleasePage, inspectGitHubRelease } from './githubReleases.js';
|
|
12
13
|
import { compareReleaseVersions, parseReleaseManifest, readReleaseManifest, } from './releases.js';
|
|
13
14
|
function run(command, args, timeout = 30_000) {
|
|
@@ -127,7 +128,7 @@ function publicJob(job) {
|
|
|
127
128
|
return value;
|
|
128
129
|
}
|
|
129
130
|
function terminal(state) {
|
|
130
|
-
return ['succeeded', 'failed', 'rolled_back'].includes(state);
|
|
131
|
+
return ['prepared', 'succeeded', 'failed', 'rolled_back'].includes(state);
|
|
131
132
|
}
|
|
132
133
|
export class SystemUpdateManager {
|
|
133
134
|
config;
|
|
@@ -148,8 +149,13 @@ export class SystemUpdateManager {
|
|
|
148
149
|
this.updaterPath = resolve(options.updaterPath ?? join(this.projectRoot, 'bin', 'hermes-yaoyao-updater.mjs'));
|
|
149
150
|
this.updateHome = join(config.home, 'updates');
|
|
150
151
|
this.releaseRoot = resolve(config.releaseRoot ?? join(homedir(), '.local', 'share', 'hermes-yaoyao'));
|
|
151
|
-
|
|
152
|
-
this.
|
|
152
|
+
const source = normalizeReleaseSource(config.releaseSource ?? DEFAULT_YAOYAO_RELEASE_SOURCE);
|
|
153
|
+
this.releaseSource = source === DEFAULT_YAOYAO_RELEASE_SOURCE && isNpmInstallation(this.projectRoot) ? NPM_RELEASE_SOURCE : source;
|
|
154
|
+
this.inspectRemote = options.inspectRemote ?? (this.releaseSource === NPM_RELEASE_SOURCE
|
|
155
|
+
? async () => {
|
|
156
|
+
const npm = await inspectNpmRelease(this.projectRoot);
|
|
157
|
+
return { npm, manifest: { schemaVersion: 1, releaseVersion: npm.version, webVersion: npm.version, gitTag: `v${npm.version}` } };
|
|
158
|
+
} : inspectGitRemote);
|
|
153
159
|
this.platform = options.platform ?? process.platform;
|
|
154
160
|
this.desktopOwned = options.desktopOwned ?? process.env.HERMES_YAOYAO_DESKTOP === '1';
|
|
155
161
|
this.launchUpdater = options.launchUpdater ?? ((jobPath) => {
|
|
@@ -197,14 +203,15 @@ export class SystemUpdateManager {
|
|
|
197
203
|
return {
|
|
198
204
|
current,
|
|
199
205
|
releaseSource: this.releaseSource,
|
|
200
|
-
releasePageUrl: githubReleasePage(this.releaseSource),
|
|
206
|
+
releasePageUrl: this.releaseSource === NPM_RELEASE_SOURCE ? 'https://www.npmjs.com/package/@lsamien/yaoyao' : githubReleasePage(this.releaseSource),
|
|
201
207
|
build: readBuildIdentity(this.projectRoot),
|
|
202
|
-
installationMode: this.desktopOwned ? 'desktop' : this.projectRoot.startsWith(`${this.releaseRoot}/`) ? 'release' : 'source',
|
|
208
|
+
installationMode: this.desktopOwned ? 'desktop' : this.releaseSource === NPM_RELEASE_SOURCE ? 'npm' : this.projectRoot.startsWith(`${this.releaseRoot}/`) ? 'release' : 'source',
|
|
209
|
+
updateMethod: this.releaseSource === NPM_RELEASE_SOURCE ? 'npm' : 'git',
|
|
203
210
|
latest,
|
|
204
211
|
updateAvailable: Boolean(latest && compareReleaseVersions(latest.releaseVersion, current.releaseVersion) > 0),
|
|
205
212
|
supported: !this.desktopOwned && this.platform === 'darwin',
|
|
206
213
|
unsupportedReason: this.desktopOwned ? 'App 内置服务随 App 一起更新,请使用夭夭菜单中的 App 更新与回退。' : this.platform === 'darwin' ? undefined : '容器和非 macOS 环境请通过替换部署镜像升级',
|
|
207
|
-
canRollback: !this.desktopOwned && existsSync(join(this.updateHome, 'last-success.json')),
|
|
214
|
+
canRollback: !this.desktopOwned && this.releaseSource !== NPM_RELEASE_SOURCE && existsSync(join(this.updateHome, 'last-success.json')),
|
|
208
215
|
job: job?.state === 'succeeded' && job.target && (job.target.webVersion !== current.webVersion || job.target.releaseVersion !== current.releaseVersion) ? undefined : publicJob(job),
|
|
209
216
|
};
|
|
210
217
|
}
|
|
@@ -213,7 +220,7 @@ export class SystemUpdateManager {
|
|
|
213
220
|
if (this.desktopOwned)
|
|
214
221
|
return this.status();
|
|
215
222
|
const latest = await this.inspectRemote(this.releaseSource, current);
|
|
216
|
-
return { ...this.status(latest?.manifest), releasePageUrl: latest
|
|
223
|
+
return { ...this.status(latest?.manifest), ...(latest?.releasePageUrl ? { releasePageUrl: latest.releasePageUrl } : {}) };
|
|
217
224
|
}
|
|
218
225
|
acquire(jobID) {
|
|
219
226
|
mkdirSync(this.updateHome, { recursive: true, mode: 0o700 });
|
|
@@ -277,7 +284,7 @@ export class SystemUpdateManager {
|
|
|
277
284
|
closeSync(descriptor);
|
|
278
285
|
}
|
|
279
286
|
}
|
|
280
|
-
createJob(operation, target, targetCommit) {
|
|
287
|
+
createJob(operation, target, targetCommit, npm, prepared) {
|
|
281
288
|
const id = randomUUID();
|
|
282
289
|
this.acquire(id);
|
|
283
290
|
const now = new Date().toISOString();
|
|
@@ -285,7 +292,7 @@ export class SystemUpdateManager {
|
|
|
285
292
|
id,
|
|
286
293
|
operation,
|
|
287
294
|
state: 'queued',
|
|
288
|
-
message: operation === 'update' ? '升级任务已排队' : '回滚任务已排队',
|
|
295
|
+
message: prepared ? '服务器重启任务已排队' : operation === 'update' ? '升级任务已排队' : '回滚任务已排队',
|
|
289
296
|
createdAt: now,
|
|
290
297
|
updatedAt: now,
|
|
291
298
|
target,
|
|
@@ -297,6 +304,8 @@ export class SystemUpdateManager {
|
|
|
297
304
|
previousServiceRoot: this.projectRoot,
|
|
298
305
|
target,
|
|
299
306
|
targetCommit,
|
|
307
|
+
npm,
|
|
308
|
+
prepared,
|
|
300
309
|
},
|
|
301
310
|
};
|
|
302
311
|
const jobPath = join(this.updateHome, `${id}.json`);
|
|
@@ -326,11 +335,34 @@ export class SystemUpdateManager {
|
|
|
326
335
|
}
|
|
327
336
|
if (targetVersion !== latest.manifest.releaseVersion)
|
|
328
337
|
throw new Error('目标版本不是当前发布源的最新版本');
|
|
329
|
-
|
|
338
|
+
if (this.releaseSource === NPM_RELEASE_SOURCE && !latest.npm)
|
|
339
|
+
throw new Error('npm 发布信息不完整');
|
|
340
|
+
return publicJob(this.createJob('update', latest.manifest, latest.commit, latest.npm));
|
|
341
|
+
}
|
|
342
|
+
startActivation(jobID) {
|
|
343
|
+
if (this.desktopOwned || this.platform !== 'darwin')
|
|
344
|
+
throw new Error('当前环境不支持服务器重启更新');
|
|
345
|
+
const job = this.latestJob();
|
|
346
|
+
if (!job || job.id !== jobID || job.state !== 'prepared' || !job.plan.prepared || !job.plan.npm || !job.target)
|
|
347
|
+
throw new Error('没有可生效的已准备更新,请重新检查更新');
|
|
348
|
+
if (compareReleaseVersions(job.target.releaseVersion, this.currentManifest().releaseVersion) <= 0)
|
|
349
|
+
throw new Error('已准备更新不是比当前服务更新的版本');
|
|
350
|
+
const prepared = job.plan.prepared;
|
|
351
|
+
try {
|
|
352
|
+
verifyPreparedNpmArchive(this.config.home, prepared, job.plan.npm);
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
const error = '已准备更新的文件已改变或不可用,请重新下载';
|
|
356
|
+
writeFileSync(join(this.updateHome, `${job.id}.json`), JSON.stringify({ ...job, state: 'failed', message: error, error, updatedAt: new Date().toISOString() }), { mode: 0o600 });
|
|
357
|
+
throw new Error(error);
|
|
358
|
+
}
|
|
359
|
+
return publicJob(this.createJob('update', job.target, undefined, job.plan.npm, prepared));
|
|
330
360
|
}
|
|
331
361
|
startRollback() {
|
|
332
362
|
if (this.desktopOwned)
|
|
333
363
|
throw new Error('App 内置服务随 App 一起更新或回退');
|
|
364
|
+
if (this.releaseSource === NPM_RELEASE_SOURCE)
|
|
365
|
+
throw new Error('npm 覆盖更新不保留旧版本,不支持回滚');
|
|
334
366
|
if (this.platform !== 'darwin')
|
|
335
367
|
throw new Error('当前环境不支持服务内回滚');
|
|
336
368
|
if (!existsSync(join(this.updateHome, 'last-success.json')))
|
|
@@ -2,6 +2,7 @@ import { WORKSPACE_PATCH_CAPABILITY } from '../shared/workspaceMessagePatch.js';
|
|
|
2
2
|
import { KNOWLEDGE_FEATURES } from './workspaceKnowledge.js';
|
|
3
3
|
import { workspaceKnowledgeRouter } from './workspaceKnowledgeRoutes.js';
|
|
4
4
|
import { workspaceDetail, streamWorkspace } from './workspaceSync.js';
|
|
5
|
+
import { workspaceMessageForClient } from './chatPresentation.js';
|
|
5
6
|
import { readServerIdentity } from './serverIdentity.js';
|
|
6
7
|
import { randomUUID } from 'node:crypto';
|
|
7
8
|
import Router from '@koa/router';
|
|
@@ -296,7 +297,27 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
|
|
|
296
297
|
ctx.body = { ok: true };
|
|
297
298
|
});
|
|
298
299
|
router.get('/api/app/conversations/:id', (ctx) => {
|
|
299
|
-
ctx.body = workspaceDetail(store, runtime, owner(ctx), ctx.params.id, typeof ctx.query.taskId === 'string' ? ctx.query.taskId : undefined, Math.max(1, Math.min(100, number(ctx.query.limit, 100))));
|
|
300
|
+
ctx.body = workspaceDetail(store, runtime, owner(ctx), ctx.params.id, typeof ctx.query.taskId === 'string' ? ctx.query.taskId : undefined, Math.max(1, Math.min(100, number(ctx.query.limit, 100))), ctx.query.toolDetails === 'lazy');
|
|
301
|
+
});
|
|
302
|
+
router.get('/api/app/conversations/:id/messages/:messageId/tools/:index', ctx => {
|
|
303
|
+
const user = owner(ctx);
|
|
304
|
+
const conversation = store.require(user, 'conversation', ctx.params.id);
|
|
305
|
+
for (const id of conversation.memberIds) {
|
|
306
|
+
const agent = store.get(user, 'agent', id);
|
|
307
|
+
if (agent && !auth.canUseSource(user, agent.nodeId, agent.profile))
|
|
308
|
+
throw new HttpError(403, '没有此机器人的权限', 'agent_source_forbidden');
|
|
309
|
+
}
|
|
310
|
+
const message = store.require(user, 'message', ctx.params.messageId);
|
|
311
|
+
if (message.conversationId !== conversation.id || message.visible === false)
|
|
312
|
+
throw new HttpError(404, '工具记录不存在', 'tool_not_found');
|
|
313
|
+
const index = number(ctx.params.index, -1);
|
|
314
|
+
const tool = typeof ctx.query.toolId === 'string'
|
|
315
|
+
? message.tools.find(tool => String(tool.id) === ctx.query.toolId)
|
|
316
|
+
: message.tools[index];
|
|
317
|
+
if (!tool)
|
|
318
|
+
throw new HttpError(404, '工具记录不存在', 'tool_not_found');
|
|
319
|
+
ctx.set('Cache-Control', 'no-store');
|
|
320
|
+
ctx.body = { input: tool.arguments ?? tool.args ?? tool.input, output: tool.error ?? tool.result ?? tool.output, revision: message.revision };
|
|
300
321
|
});
|
|
301
322
|
router.patch('/api/app/conversations/:id', async (ctx) => {
|
|
302
323
|
const user = owner(ctx), input = body(ctx);
|
|
@@ -316,7 +337,7 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
|
|
|
316
337
|
router.get('/api/app/conversations/:id/messages', (ctx) => {
|
|
317
338
|
const user = owner(ctx), taskId = typeof ctx.query.taskId === 'string' ? ctx.query.taskId : undefined, task = store.resolveTask(user, ctx.params.id, taskId);
|
|
318
339
|
ctx.body = {
|
|
319
|
-
messages: store.messages(user, ctx.params.id, number(ctx.query.before, Number.MAX_SAFE_INTEGER), Math.min(200, number(ctx.query.limit, 100)), false, task?.id),
|
|
340
|
+
messages: store.messages(user, ctx.params.id, number(ctx.query.before, Number.MAX_SAFE_INTEGER), Math.min(200, number(ctx.query.limit, 100)), false, task?.id).map(message => ctx.query.toolDetails === 'lazy' ? workspaceMessageForClient(message) : message),
|
|
320
341
|
cursor: store.cursor(user),
|
|
321
342
|
};
|
|
322
343
|
});
|
|
@@ -368,10 +389,15 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
|
|
|
368
389
|
const user = owner(ctx);
|
|
369
390
|
const conversations = store.list(user, 'conversation')
|
|
370
391
|
.map(c => store.conversationSummary(user, c)).sort(compareWorkspaceConversations);
|
|
371
|
-
const
|
|
392
|
+
const partialDetails = ctx.query.details === 'selected';
|
|
393
|
+
const taskId = partialDetails && typeof ctx.query.taskId === 'string' ? ctx.query.taskId : undefined;
|
|
394
|
+
// A stale task link must still load the list; the detail route handles its fallback.
|
|
395
|
+
const details = conversations.filter(c => !c.archived && (!partialDetails || c.id === ctx.query.conversationId)
|
|
396
|
+
&& (!taskId || store.get(user, 'conversation-task', taskId)?.conversationId === c.id))
|
|
397
|
+
.map(c => workspaceDetail(store, runtime, user, c.id, taskId, 50, ctx.query.toolDetails === 'lazy'));
|
|
372
398
|
ctx.set('Cache-Control', 'no-store');
|
|
373
399
|
ctx.body = { projects: runtime.knowledge.projects(user), agents: store.list(user, 'agent').map(a => store.agentSummary(a)),
|
|
374
|
-
conversations, details, cursor: store.cursor(user), serverIdentity: readServerIdentity(store) };
|
|
400
|
+
conversations, details, partialDetails, cursor: store.cursor(user), serverIdentity: readServerIdentity(store) };
|
|
375
401
|
});
|
|
376
402
|
router.get('/api/app/events/stream', ctx => streamWorkspace(ctx, store, auth));
|
|
377
403
|
router.get('/api/app/events', (ctx) => {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readServerIdentity } from './serverIdentity.js';
|
|
2
|
+
import { workspaceMessageForClient, workspaceEventForClient } from './chatPresentation.js';
|
|
2
3
|
/** Bot transcripts are a local projection. Snapshot and cursor are read in the same synchronous turn. */
|
|
3
|
-
export function workspaceDetail(store, runtime, owner, conversationId, taskId, limit = 50) {
|
|
4
|
+
export function workspaceDetail(store, runtime, owner, conversationId, taskId, limit = 50, lazyTools = false) {
|
|
4
5
|
const conversation = store.require(owner, 'conversation', conversationId);
|
|
5
6
|
const task = store.resolveTask(owner, conversationId, taskId);
|
|
6
7
|
const activeRunId = task?.activeRunId ?? (conversation.kind === 'direct' ? conversation.activeRunId : undefined);
|
|
@@ -9,7 +10,7 @@ export function workspaceDetail(store, runtime, owner, conversationId, taskId, l
|
|
|
9
10
|
conversation: store.conversationSummary(owner, conversation), task: task ?? null,
|
|
10
11
|
tasks: conversation.kind === 'group' ? store.tasks(owner, conversationId) : [],
|
|
11
12
|
assignments: task ? runtime.tasks.assignments(owner, task.id) : [],
|
|
12
|
-
messages: page.slice(-limit), hasOlder: page.length > limit,
|
|
13
|
+
messages: page.slice(-limit).map(message => lazyTools ? workspaceMessageForClient(message) : message), hasOlder: page.length > limit,
|
|
13
14
|
hiddenMessageIds: store.hiddenMessageIds(owner, conversationId, task?.id),
|
|
14
15
|
run: activeRunId ? store.require(owner, 'run', activeRunId) : null,
|
|
15
16
|
interactions: store.list(owner, 'interaction')
|
|
@@ -23,6 +24,7 @@ export function streamWorkspace(ctx, store, auth) {
|
|
|
23
24
|
const owner = auth.require(ctx).id, version = auth.pushAuthorizationVersion(owner);
|
|
24
25
|
const cookie = ctx.get('cookie');
|
|
25
26
|
const patches = store.messagePatchesEnabled && ctx.query.format === 'patch-v1';
|
|
27
|
+
const lazyTools = ctx.query.toolDetails === 'lazy';
|
|
26
28
|
const res = ctx.res;
|
|
27
29
|
const raw = ctx.get('last-event-id') || String(ctx.query.after ?? '0');
|
|
28
30
|
let cursor = /^\d+$/.test(raw) ? Number(raw) : 0;
|
|
@@ -66,7 +68,7 @@ export function streamWorkspace(ctx, store, auth) {
|
|
|
66
68
|
const emit = (event) => {
|
|
67
69
|
if (event.seq <= cursor)
|
|
68
70
|
return;
|
|
69
|
-
write(`id: ${event.seq}\nevent: workspace\ndata: ${JSON.stringify(event)}\n\n`);
|
|
71
|
+
write(`id: ${event.seq}\nevent: workspace\ndata: ${JSON.stringify(lazyTools ? workspaceEventForClient(event) : event)}\n\n`);
|
|
70
72
|
cursor = event.seq;
|
|
71
73
|
if (event.type.startsWith('message.'))
|
|
72
74
|
lastTextAt = Date.now();
|
|
@@ -86,7 +88,23 @@ export function streamWorkspace(ctx, store, auth) {
|
|
|
86
88
|
if (patches) {
|
|
87
89
|
// A new live subscription may not have this background task in its snapshot.
|
|
88
90
|
// The first live update is a full committed baseline; replay stays revision-checked.
|
|
89
|
-
|
|
91
|
+
let baseline = wire;
|
|
92
|
+
if (wire.type === 'message.patch' && id && !knownMessages.has(id)) {
|
|
93
|
+
if (event.type === 'message.changed')
|
|
94
|
+
baseline = event;
|
|
95
|
+
else if (lazyTools) {
|
|
96
|
+
// Partial snapshots do not include background messages. A replayed
|
|
97
|
+
// first patch also needs a baseline, scoped to this authenticated owner.
|
|
98
|
+
const message = store.get(owner, 'message', id);
|
|
99
|
+
if (!message) {
|
|
100
|
+
write('event: reset\ndata: {}\n\n');
|
|
101
|
+
close();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
baseline = { ...event, type: 'message.changed', data: store.messageForDisplay(owner, message) };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
emit(baseline);
|
|
90
108
|
if (id && event.type.startsWith('message.')) {
|
|
91
109
|
knownMessages.delete(id);
|
|
92
110
|
knownMessages.add(id);
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Bundled logos keep the built-in directory usable without a third-party request. */
|
|
2
|
+
const providers = {
|
|
3
|
+
gmail: { hosts: ['gmail.com'] },
|
|
4
|
+
googledrive: { hosts: ['drive.google.com'] },
|
|
5
|
+
googlecalendar: { hosts: ['calendar.google.com'] },
|
|
6
|
+
github: { hosts: ['github.com', 'githubcopilot.com'] },
|
|
7
|
+
notion: { hosts: ['notion.so', 'notion.com'] },
|
|
8
|
+
slack: { hosts: ['slack.com'] },
|
|
9
|
+
linear: { hosts: ['linear.app'] },
|
|
10
|
+
discord: { hosts: ['discord.com'] },
|
|
11
|
+
outlook: { hosts: ['outlook.com', 'outlook.office.com'] },
|
|
12
|
+
trello: { hosts: ['trello.com'] },
|
|
13
|
+
airtable: { hosts: ['airtable.com'] },
|
|
14
|
+
twitter: { hosts: ['twitter.com', 'x.com'] },
|
|
15
|
+
};
|
|
16
|
+
const aliases = { gdrive: 'googledrive', x: 'twitter', microsoftoutlook: 'outlook' };
|
|
17
|
+
export const BOT_LOGO_ORIGINS = ['https://logos.composio.dev', 'https://assets.composio.dev'];
|
|
18
|
+
export function bundledProviderLogo(slug) {
|
|
19
|
+
const key = slug.toLowerCase().replace(/[\s_-]/g, '');
|
|
20
|
+
const provider = aliases[key] ?? key;
|
|
21
|
+
return Object.hasOwn(providers, provider) ? `/provider-logos/${provider}.svg` : undefined;
|
|
22
|
+
}
|
|
23
|
+
/** Match the image CSP; never forward credentials or arbitrary image origins. */
|
|
24
|
+
export function safeProviderLogo(value) {
|
|
25
|
+
if (typeof value !== 'string' || value.length > 2048)
|
|
26
|
+
return undefined;
|
|
27
|
+
if (Object.keys(providers).some(slug => value === bundledProviderLogo(slug)))
|
|
28
|
+
return value;
|
|
29
|
+
try {
|
|
30
|
+
const url = new URL(value);
|
|
31
|
+
if (url.username || url.password || !BOT_LOGO_ORIGINS.some(origin => url.origin === origin))
|
|
32
|
+
return undefined;
|
|
33
|
+
return url.href;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export function mcpProviderLogo(plugin) {
|
|
40
|
+
if (plugin.transport === 'http' && plugin.url) {
|
|
41
|
+
try {
|
|
42
|
+
const host = new URL(plugin.url).hostname.toLowerCase();
|
|
43
|
+
const provider = Object.entries(providers).find(([, { hosts }]) => hosts.some(domain => host === domain || host.endsWith(`.${domain}`)));
|
|
44
|
+
if (provider)
|
|
45
|
+
return bundledProviderLogo(provider[0]);
|
|
46
|
+
}
|
|
47
|
+
catch { /* Older invalid definitions still get a readable placeholder. */ }
|
|
48
|
+
}
|
|
49
|
+
if (plugin.transport === 'stdio') {
|
|
50
|
+
for (const arg of [plugin.command ?? '', ...(plugin.args ?? [])]) {
|
|
51
|
+
const packageName = arg.toLowerCase().replace(/^--package=/, '').replace(/@[^/@]+$/, '');
|
|
52
|
+
if (packageName === '@notionhq/notion-mcp-server')
|
|
53
|
+
return bundledProviderLogo('notion');
|
|
54
|
+
const slug = /^@modelcontextprotocol\/server-([a-z-]+)$/.exec(packageName)?.[1];
|
|
55
|
+
const logo = slug && bundledProviderLogo(slug);
|
|
56
|
+
if (logo)
|
|
57
|
+
return logo;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return bundledProviderLogo(plugin.name.replace(/\s*(?:mcp(?:\s*(?:server|服务))?|server|服务)$/i, '').trim());
|
|
61
|
+
}
|