@lsamien/yaoyao 0.4.77 → 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.
- package/README.md +7 -5
- package/THIRD_PARTY_NOTICES.md +8 -0
- package/bin/hermes-yaoyao.mjs +15 -2
- package/build-info.json +20 -3
- package/desktop/main.mjs +6 -2
- package/dist/assets/{AboutDialog-k7oUOua0.js → AboutDialog-jvhTP8-J.js} +2 -2
- package/dist/assets/AboutDialog-jvhTP8-J.js.map +1 -0
- package/dist/assets/BotAutomationsView-ktoci79V.js +2 -0
- package/dist/assets/{BotAutomationsView-CUaMkVfT.js.map → BotAutomationsView-ktoci79V.js.map} +1 -1
- package/dist/assets/{BotPluginsDialog-BqfqrWdq.js → BotPluginsDialog-H85RI-7P.js} +2 -2
- package/dist/assets/{BotPluginsDialog-BqfqrWdq.js.map → BotPluginsDialog-H85RI-7P.js.map} +1 -1
- package/dist/assets/{BotSettingsDialog-BfW0Jxhg.js → BotSettingsDialog-Ci_DZL4m.js} +5 -5
- package/dist/assets/{BotSettingsDialog-BfW0Jxhg.js.map → BotSettingsDialog-Ci_DZL4m.js.map} +1 -1
- package/dist/assets/ChatView-6cdLMsuy.js +2 -0
- package/dist/assets/ChatView-6cdLMsuy.js.map +1 -0
- package/dist/assets/ChatView-C_7_7olu.css +1 -0
- package/dist/assets/{ComputerPanel-D_wWUzlj.js → ComputerPanel-Dbwgx5n8.js} +2 -2
- package/dist/assets/{ComputerPanel-D_wWUzlj.js.map → ComputerPanel-Dbwgx5n8.js.map} +1 -1
- package/dist/assets/{ComputerViewerView-C2nS7MWX.js → ComputerViewerView-csnhRedK.js} +2 -2
- package/dist/assets/{ComputerViewerView-C2nS7MWX.js.map → ComputerViewerView-csnhRedK.js.map} +1 -1
- package/dist/assets/ConversationsView-CEO2SVGT.js +6 -0
- package/dist/assets/ConversationsView-CEO2SVGT.js.map +1 -0
- package/dist/assets/{ConversationsView-C_VZl5g2.css → ConversationsView-CHLGKsJt.css} +1 -1
- package/dist/assets/FilesView-t5jA-H2-.js +2 -0
- package/dist/assets/{FilesView-xOEZGSrD.js.map → FilesView-t5jA-H2-.js.map} +1 -1
- package/dist/assets/FloatingResourceSearch-3GOuDkuO.css +1 -0
- package/dist/assets/FloatingResourceSearch-BAYymuJV.js +9 -0
- package/dist/assets/FloatingResourceSearch-BAYymuJV.js.map +1 -0
- package/dist/assets/HistoryView-BqMSV9iC.js +2 -0
- package/dist/assets/HistoryView-BqMSV9iC.js.map +1 -0
- package/dist/assets/HistoryView-DlVfSP_p.css +1 -0
- package/dist/assets/KanbanView-CWwrwH9S.js +2 -0
- package/dist/assets/{KanbanView-DXJCj1E6.js.map → KanbanView-CWwrwH9S.js.map} +1 -1
- package/dist/assets/{LocalVmSettingsPanel-8wF6wA3P.js → LocalVmSettingsPanel-BXvZwFQP.js} +2 -2
- package/dist/assets/{LocalVmSettingsPanel-8wF6wA3P.js.map → LocalVmSettingsPanel-BXvZwFQP.js.map} +1 -1
- package/dist/assets/{RunnerSettingsPanel-DDEMgUS9.js → RunnerSettingsPanel-KkpIkkob.js} +2 -2
- package/dist/assets/{RunnerSettingsPanel-DDEMgUS9.js.map → RunnerSettingsPanel-KkpIkkob.js.map} +1 -1
- package/dist/assets/{StandaloneDialog-BN6RJ3uh.js → StandaloneDialog-D4BQqjpB.js} +2 -2
- package/dist/assets/{StandaloneDialog-BN6RJ3uh.js.map → StandaloneDialog-D4BQqjpB.js.map} +1 -1
- package/dist/assets/{UpdateCheckDialog-CZ6NZSkP.js → UpdateCheckDialog-Ct0bT6xU.js} +2 -2
- package/dist/assets/{UpdateCheckDialog-CZ6NZSkP.js.map → UpdateCheckDialog-Ct0bT6xU.js.map} +1 -1
- package/dist/assets/{WorkspaceKnowledgePanel-BA7yVvWK.js → WorkspaceKnowledgePanel-WBcPB49x.js} +2 -2
- package/dist/assets/{WorkspaceKnowledgePanel-BA7yVvWK.js.map → WorkspaceKnowledgePanel-WBcPB49x.js.map} +1 -1
- package/dist/assets/{WorkspaceRoutinesPanel-DgCqaACO.js → WorkspaceRoutinesPanel-JubUwGsV.js} +2 -2
- package/dist/assets/{WorkspaceRoutinesPanel-DgCqaACO.js.map → WorkspaceRoutinesPanel-JubUwGsV.js.map} +1 -1
- package/dist/assets/WorkspaceShell-0m4gg6AW.css +1 -0
- package/dist/assets/WorkspaceShell-Do2VAwIz.js +44 -0
- package/dist/assets/WorkspaceShell-Do2VAwIz.js.map +1 -0
- package/dist/assets/{WorkspaceView-jMPyO8oT.js → WorkspaceView-DTanioWW.js} +2 -2
- package/dist/assets/{WorkspaceView-jMPyO8oT.js.map → WorkspaceView-DTanioWW.js.map} +1 -1
- package/dist/assets/{docx-preview-Ba7Ciq-i.js → docx-preview-B1SjJgD_.js} +2 -2
- package/dist/assets/{docx-preview-Ba7Ciq-i.js.map → docx-preview-B1SjJgD_.js.map} +1 -1
- package/dist/assets/index-CWamgtSb.js +17 -0
- package/dist/assets/index-CWamgtSb.js.map +1 -0
- package/dist/assets/{pdf-C3k8l1DI.js → pdf-DVDddcFC.js} +2 -2
- package/dist/assets/{pdf-C3k8l1DI.js.map → pdf-DVDddcFC.js.map} +1 -1
- package/dist/assets/sessionOwnership-0hdKcwOs.js +4 -0
- package/dist/assets/sessionOwnership-0hdKcwOs.js.map +1 -0
- package/dist/assets/{sessionOwnership-BTz0Fyp5.css → sessionOwnership-CfO8CfmZ.css} +1 -1
- package/dist/assets/{viewModels-OLQqqyt3.js → viewModels-DKBqaDRg.js} +12 -12
- package/dist/assets/{viewModels-OLQqqyt3.js.map → viewModels-DKBqaDRg.js.map} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/runner/agent.js +2 -2
- package/dist-server/server/app.js +15 -1
- package/dist-server/server/chatTranscriptStore.js +16 -0
- package/dist-server/server/config.js +3 -0
- package/dist-server/server/credentialVault/broker.js +272 -0
- package/dist-server/server/credentialVault/coordinator.js +297 -0
- package/dist-server/server/credentialVault/executor.js +1 -0
- package/dist-server/server/credentialVault/fixtureWebsiteExecutor.js +51 -0
- package/dist-server/server/credentialVault/index.js +49 -0
- package/dist-server/server/credentialVault/isolation.js +37 -0
- package/dist-server/server/credentialVault/privateFiles.js +17 -0
- package/dist-server/server/credentialVault/protectedExecutor.js +21 -0
- package/dist-server/server/credentialVault/schema.js +45 -0
- package/dist-server/server/credentialVault/sshExecutor.js +135 -0
- package/dist-server/server/credentialVault/store.js +308 -0
- package/dist-server/server/credentialVault/transport.js +127 -0
- package/dist-server/server/credentialVault/websiteExecutor.js +102 -0
- package/dist-server/server/localAuth.js +5 -0
- package/dist-server/server/openVikingSessionSync.js +148 -37
- package/dist-server/server/pushCoordinator.js +7 -4
- package/dist-server/server/routes.js +18 -0
- package/dist-server/server/runnerHub.js +14 -1
- package/dist-server/server/subaccountAccess.js +12 -0
- package/dist-server/server/unreadCenter.js +61 -0
- package/dist-server/server/uploads.js +4 -1
- package/dist-server/server/workspaceAssets.js +2 -1
- package/dist-server/server/workspaceRoutes.js +1 -1
- package/dist-server/server/workspaceRuntime.js +18 -2
- package/dist-server/server/workspaceStore.js +104 -43
- package/dist-server/shared/credentialVault.js +2 -0
- package/dist-server/shared/unread.js +6 -0
- package/dist-server/shared/uploadNames.js +14 -0
- package/licenses/libsodium.js/LICENSE +16 -0
- package/licenses/ssh2/LICENSE +19 -0
- package/package.json +4 -2
- package/release.json +3 -3
- package/dist/assets/AboutDialog-k7oUOua0.js.map +0 -1
- package/dist/assets/BotAutomationsView-CUaMkVfT.js +0 -2
- package/dist/assets/ChatView-CTWvNlNq.js +0 -2
- package/dist/assets/ChatView-CTWvNlNq.js.map +0 -1
- package/dist/assets/ChatView-Dx8YlcPr.css +0 -1
- package/dist/assets/ConversationsView-D5KvMs7J.js +0 -6
- package/dist/assets/ConversationsView-D5KvMs7J.js.map +0 -1
- package/dist/assets/FilesView-xOEZGSrD.js +0 -2
- package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +0 -1
- package/dist/assets/FloatingResourceSearch-D5XwWF0V.js +0 -9
- package/dist/assets/FloatingResourceSearch-D5XwWF0V.js.map +0 -1
- package/dist/assets/HistoryView-CnUN9Qik.js +0 -2
- package/dist/assets/HistoryView-CnUN9Qik.js.map +0 -1
- package/dist/assets/HistoryView-DvuCAjlo.css +0 -1
- package/dist/assets/KanbanView-DXJCj1E6.js +0 -2
- package/dist/assets/WorkspaceShell-7wn8iTne.css +0 -1
- package/dist/assets/WorkspaceShell-DQZKvx2p.js +0 -44
- package/dist/assets/WorkspaceShell-DQZKvx2p.js.map +0 -1
- package/dist/assets/index-dvKMU4Xy.js +0 -17
- package/dist/assets/index-dvKMU4Xy.js.map +0 -1
- package/dist/assets/sessionOwnership-HZsbONG-.js +0 -6
- package/dist/assets/sessionOwnership-HZsbONG-.js.map +0 -1
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { chromium } from 'playwright';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
/** Standard HTML POST form only. One private browser/context per lease; no
|
|
4
|
+
* persistent profile, public CDP port, fill/JS API, screenshots or page output. */
|
|
5
|
+
export class WebsiteFormExecutor {
|
|
6
|
+
home;
|
|
7
|
+
gate;
|
|
8
|
+
testCA;
|
|
9
|
+
constructor(home, gate, testCA) {
|
|
10
|
+
this.home = home;
|
|
11
|
+
this.gate = gate;
|
|
12
|
+
this.testCA = testCA;
|
|
13
|
+
}
|
|
14
|
+
async execute(entry, input, signal) {
|
|
15
|
+
this.gate.assert();
|
|
16
|
+
signal.throwIfAborted();
|
|
17
|
+
const plan = entry.usage;
|
|
18
|
+
if (entry.target.kind !== 'website' || input.target.kind !== 'website' || input.operation !== 'website.login' || entry.target.origin !== input.target.origin || plan?.kind !== 'website.form')
|
|
19
|
+
return { status: 'manual_takeover_required', reason: 'usage_policy_required', submitted: false };
|
|
20
|
+
// Test-only custom CA is not a TLS bypass: Chromium explicitly trusts this
|
|
21
|
+
// certificate's SPKI. It is restricted to loopback and never set by CLI.
|
|
22
|
+
const base = new URL(entry.target.origin);
|
|
23
|
+
if (this.testCA && base.hostname !== '127.0.0.1')
|
|
24
|
+
throw new Error('fixture CA is loopback only');
|
|
25
|
+
let browser, context, page, unsafe = false, submitted = false;
|
|
26
|
+
const abort = () => { void context?.close().catch(() => { }); void browser?.close().catch(() => { }); };
|
|
27
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
28
|
+
try {
|
|
29
|
+
const args = ['--force-webrtc-ip-handling-policy=disable_non_proxied_udp', '--disable-background-networking'];
|
|
30
|
+
if (this.testCA) {
|
|
31
|
+
const { X509Certificate, createHash } = await import('node:crypto');
|
|
32
|
+
args.push('--ignore-certificate-errors-spki-list=' + createHash('sha256').update(new X509Certificate(this.testCA).publicKey.export({ type: 'spki', format: 'der' })).digest('base64'));
|
|
33
|
+
}
|
|
34
|
+
browser = await chromium.launch({ headless: true, chromiumSandbox: true, timeout: 10000, args, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: resolve(this.home), TMPDIR: resolve(this.home), LANG: 'en_US.UTF-8' } });
|
|
35
|
+
signal.throwIfAborted();
|
|
36
|
+
this.gate.assert();
|
|
37
|
+
context = await browser.newContext({ acceptDownloads: false, serviceWorkers: 'block', permissions: [] });
|
|
38
|
+
context.setDefaultTimeout(5000);
|
|
39
|
+
context.setDefaultNavigationTimeout(5000);
|
|
40
|
+
await context.routeWebSocket('**/*', route => route.close());
|
|
41
|
+
page = await context.newPage();
|
|
42
|
+
context.on('page', other => { if (other !== page) {
|
|
43
|
+
unsafe = true;
|
|
44
|
+
void other.close().catch(() => { });
|
|
45
|
+
} });
|
|
46
|
+
page.on('dialog', dialog => { unsafe = true; void dialog.dismiss().catch(() => { }); });
|
|
47
|
+
page.on('frameattached', () => { unsafe = true; });
|
|
48
|
+
await context.route('**/*', async (route) => {
|
|
49
|
+
const request = route.request(), url = new URL(request.url());
|
|
50
|
+
const main = request.isNavigationRequest() && request.frame() === page.mainFrame();
|
|
51
|
+
const approvedNavigation = main && [plan.loginPath, plan.submitPath, plan.successPath, ...(plan.logoutPath ? [plan.logoutPath] : [])].includes(url.pathname) && !url.search && !url.hash;
|
|
52
|
+
const resource = !request.isNavigationRequest() && request.method() === 'GET' && ['script', 'stylesheet', 'image', 'font'].includes(request.resourceType());
|
|
53
|
+
const allowed = url.origin === base.origin && (approvedNavigation || resource) && (!request.redirectedFrom() || request.method() === 'GET' && url.pathname === plan.successPath)
|
|
54
|
+
&& (request.method() === 'GET' || main && request.method() === 'POST' && url.pathname === plan.submitPath) && !signal.aborted;
|
|
55
|
+
if (!allowed) {
|
|
56
|
+
unsafe = true;
|
|
57
|
+
await route.abort();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
await route.continue();
|
|
61
|
+
});
|
|
62
|
+
await page.goto(new URL(plan.loginPath, base).href, { waitUntil: 'domcontentloaded' });
|
|
63
|
+
const form = page.locator(`form[id="${plan.formId}"]`), user = form.locator(`input[name="${plan.usernameName}"]`), password = form.locator(`input[name="${plan.passwordName}"]`), submit = form.locator('button[type="submit"],input[type="submit"]');
|
|
64
|
+
if (unsafe || page.frames().length !== 1 || await form.count() !== 1 || await user.count() !== 1 || await password.count() !== 1 || await submit.count() !== 1 || plan.usernameName === plan.passwordName)
|
|
65
|
+
return { status: 'manual_takeover_required', reason: 'unsupported_form_flow', submitted: false };
|
|
66
|
+
const metadata = await form.evaluate(el => { const f = el; return { method: f.method, action: f.action, enctype: f.enctype }; });
|
|
67
|
+
const action = new URL(metadata.action);
|
|
68
|
+
if (metadata.method.toLowerCase() !== 'post' || metadata.enctype !== 'application/x-www-form-urlencoded' || action.origin !== base.origin || action.pathname !== plan.submitPath || action.search || action.hash || await password.getAttribute('type') !== 'password')
|
|
69
|
+
return { status: 'manual_takeover_required', reason: 'unsupported_form_flow', submitted: false };
|
|
70
|
+
this.gate.assert();
|
|
71
|
+
signal.throwIfAborted();
|
|
72
|
+
await user.fill(entry.username);
|
|
73
|
+
await password.fill(entry.secret);
|
|
74
|
+
if (unsafe)
|
|
75
|
+
return { status: 'manual_takeover_required', reason: 'unsupported_form_flow', submitted: false };
|
|
76
|
+
submitted = true;
|
|
77
|
+
await Promise.all([page.waitForURL(url => url.origin === base.origin && url.pathname === plan.successPath && !url.search && !url.hash, { waitUntil: 'domcontentloaded' }), submit.click()]);
|
|
78
|
+
signal.throwIfAborted();
|
|
79
|
+
this.gate.assert();
|
|
80
|
+
if (unsafe || page.frames().length !== 1 || await page.locator(plan.successSelector).count() !== 1 || !await page.locator(plan.successSelector).isVisible())
|
|
81
|
+
return { status: 'manual_takeover_required', reason: 'unsupported_form_flow', submitted: true };
|
|
82
|
+
if (plan.logoutPath) {
|
|
83
|
+
const response = await page.goto(new URL(plan.logoutPath, base).href, { waitUntil: 'domcontentloaded' });
|
|
84
|
+
if (!response || response.status() >= 300 || unsafe)
|
|
85
|
+
return { status: 'manual_takeover_required', reason: 'unsupported_form_flow', submitted: true };
|
|
86
|
+
}
|
|
87
|
+
// The authenticated context is destroyed below. Cookies/DOM/network output
|
|
88
|
+
// are never handed to generic tools or included in the model receipt.
|
|
89
|
+
return { status: 'complete', operation: 'website.login' };
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
signal.throwIfAborted();
|
|
93
|
+
return { status: 'manual_takeover_required', reason: 'unsupported_form_flow', submitted };
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
signal.removeEventListener('abort', abort);
|
|
97
|
+
await context?.clearCookies().catch(() => { });
|
|
98
|
+
await context?.close().catch(() => { });
|
|
99
|
+
await browser?.close().catch(() => { });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -154,6 +154,11 @@ export class LocalAuthStore {
|
|
|
154
154
|
return injected;
|
|
155
155
|
return this.currentFromCookieHeader(ctx.get('cookie'));
|
|
156
156
|
}
|
|
157
|
+
/** Opaque vault binding; callers must separately validate the session. */
|
|
158
|
+
sessionBinding(cookieHeader) {
|
|
159
|
+
const token = parse(cookieHeader ?? '')[SESSION_COOKIE];
|
|
160
|
+
return token ? createHash('sha256').update('yaoyao-vault-session-v1\0').update(token).digest('hex') : undefined;
|
|
161
|
+
}
|
|
157
162
|
/** Resolve the same authenticated user for non-Koa transports such as WS Upgrade. */
|
|
158
163
|
currentFromCookieHeader(cookieHeader) {
|
|
159
164
|
const token = parse(cookieHeader ?? '')[SESSION_COOKIE];
|
|
@@ -1,10 +1,41 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { OpenVikingError } from '@openviking/sdk';
|
|
3
3
|
import { visibleMessageText } from '../shared/messageFiles.js';
|
|
4
4
|
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
5
5
|
const missing = (error) => error instanceof OpenVikingError && (error.statusCode === 404 || ['NOT_FOUND', 'ENOENT'].includes(error.code));
|
|
6
6
|
class Paused extends Error {
|
|
7
7
|
}
|
|
8
|
+
const conflictMessage = 'OpenViking 会话记录与本地顺序不一致,已停止追加,请核对会话';
|
|
9
|
+
class TranscriptConflict extends Error {
|
|
10
|
+
constructor(reason) {
|
|
11
|
+
super(`${conflictMessage}(${reason})。请备份并核对本地与远端会话后重试;仍有冲突时需人工恢复。`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function transcript(raw) {
|
|
15
|
+
try {
|
|
16
|
+
return raw.split('\n').filter(line => line.trim()).map(line => {
|
|
17
|
+
const row = JSON.parse(line);
|
|
18
|
+
if (!row || typeof row.role !== 'string' || typeof row.created_at !== 'string')
|
|
19
|
+
throw new Error();
|
|
20
|
+
let content;
|
|
21
|
+
if (Array.isArray(row.parts)) {
|
|
22
|
+
// A transcript mirror contains text only. Do not hide foreign parts when comparing.
|
|
23
|
+
if (row.parts.some((part) => !part || part.type !== 'text' || typeof part.text !== 'string'))
|
|
24
|
+
throw new Error();
|
|
25
|
+
content = row.parts.map((part) => part.text).join('');
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
if (typeof row.content !== 'string')
|
|
29
|
+
throw new Error();
|
|
30
|
+
content = row.content;
|
|
31
|
+
}
|
|
32
|
+
return { role: row.role, content, createdAt: new Date(row.created_at).toISOString() };
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new TranscriptConflict('远端记录格式无法安全核对');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
8
39
|
/** A durable transcript mirror. Memory synthesis remains owned by WorkspaceMemorySynthesis. */
|
|
9
40
|
export class OpenVikingSessionSync {
|
|
10
41
|
store;
|
|
@@ -22,6 +53,8 @@ export class OpenVikingSessionSync {
|
|
|
22
53
|
CREATE TABLE IF NOT EXISTS openviking_sync_state(namespace TEXT PRIMARY KEY, scan_row INTEGER NOT NULL DEFAULT 0, scanned INTEGER NOT NULL DEFAULT 0, event_seq INTEGER NOT NULL);
|
|
23
54
|
CREATE TABLE IF NOT EXISTS openviking_sync_jobs(id TEXT PRIMARY KEY, namespace TEXT NOT NULL, owner TEXT NOT NULL, agent TEXT NOT NULL, conversation TEXT NOT NULL, task TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, synced_messages INTEGER NOT NULL DEFAULT 0, next_at INTEGER NOT NULL DEFAULT 0, error TEXT, updated_at INTEGER NOT NULL);
|
|
24
55
|
CREATE INDEX IF NOT EXISTS openviking_sync_pending ON openviking_sync_jobs(namespace,status,next_at);
|
|
56
|
+
CREATE TABLE IF NOT EXISTS openviking_sync_appends(session TEXT PRIMARY KEY, expected INTEGER NOT NULL, fingerprint TEXT NOT NULL);
|
|
57
|
+
CREATE TABLE IF NOT EXISTS openviking_sync_locks(session TEXT PRIMARY KEY, token TEXT NOT NULL, pid INTEGER NOT NULL);
|
|
25
58
|
CREATE TABLE IF NOT EXISTS openviking_sync_messages(session TEXT NOT NULL, message TEXT NOT NULL, seq INTEGER NOT NULL, ready INTEGER NOT NULL, payload TEXT NOT NULL, fingerprint TEXT NOT NULL, PRIMARY KEY(session,message));
|
|
26
59
|
`);
|
|
27
60
|
}
|
|
@@ -146,6 +179,47 @@ export class OpenVikingSessionSync {
|
|
|
146
179
|
return !!this.store.get(job.owner, 'agent', job.agent) && !!this.store.get(job.owner, 'conversation', job.conversation)
|
|
147
180
|
&& (!job.task || !!this.store.get(job.owner, 'conversation-task', job.task));
|
|
148
181
|
}
|
|
182
|
+
claim(session) {
|
|
183
|
+
return this.store.atomic(() => {
|
|
184
|
+
const lock = this.store.db.prepare('SELECT pid FROM openviking_sync_locks WHERE session=?').get(session);
|
|
185
|
+
if (lock) {
|
|
186
|
+
// Never steal a lock from a live writer, even if a remote request is slow.
|
|
187
|
+
// After a process crash, reconcile the remote prefix before writing again.
|
|
188
|
+
try {
|
|
189
|
+
process.kill(Number(lock.pid), 0);
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
if (error.code !== 'ESRCH')
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
this.store.db.prepare('DELETE FROM openviking_sync_locks WHERE session=?').run(session);
|
|
197
|
+
}
|
|
198
|
+
const token = randomUUID();
|
|
199
|
+
this.store.db.prepare('INSERT INTO openviking_sync_locks VALUES(?,?,?)').run(session, token, process.pid);
|
|
200
|
+
return token;
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
projection(job) {
|
|
204
|
+
const rows = this.store.db.prepare('SELECT * FROM openviking_sync_messages WHERE session=? ORDER BY seq,message').all(job.id);
|
|
205
|
+
const desired = [];
|
|
206
|
+
for (const row of rows) {
|
|
207
|
+
if (!row.ready)
|
|
208
|
+
return { desired, unfinished: true };
|
|
209
|
+
if (row.payload)
|
|
210
|
+
desired.push(JSON.parse(String(row.payload)));
|
|
211
|
+
}
|
|
212
|
+
return { desired, unfinished: false };
|
|
213
|
+
}
|
|
214
|
+
verify(remote, desired, acknowledged) {
|
|
215
|
+
if (remote.length < acknowledged)
|
|
216
|
+
throw new TranscriptConflict('远端记录少于已确认的同步记录');
|
|
217
|
+
for (let i = 0; i < remote.length; i++) {
|
|
218
|
+
const local = desired[i], actual = remote[i];
|
|
219
|
+
if (!local || actual.role !== local.role || actual.content !== local.content || actual.createdAt !== local.createdAt)
|
|
220
|
+
throw new TranscriptConflict(`第 ${i + 1} 条记录内容或顺序不同`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
149
223
|
async sync(job) {
|
|
150
224
|
const check = () => this.current(job.namespace);
|
|
151
225
|
check();
|
|
@@ -170,6 +244,7 @@ export class OpenVikingSessionSync {
|
|
|
170
244
|
check();
|
|
171
245
|
this.store.db.prepare("UPDATE openviking_sync_jobs SET status='deleted',error=NULL WHERE id=?").run(job.id);
|
|
172
246
|
this.store.db.prepare('DELETE FROM openviking_sync_messages WHERE session=?').run(job.id);
|
|
247
|
+
this.store.db.prepare('DELETE FROM openviking_sync_appends WHERE session=?').run(job.id);
|
|
173
248
|
return;
|
|
174
249
|
}
|
|
175
250
|
const agent = this.store.require(job.owner, 'agent', job.agent);
|
|
@@ -185,6 +260,8 @@ export class OpenVikingSessionSync {
|
|
|
185
260
|
catch (error) {
|
|
186
261
|
if (!missing(error))
|
|
187
262
|
throw error;
|
|
263
|
+
if (job.synced_messages > 0)
|
|
264
|
+
throw new TranscriptConflict('已确认同步的远端会话缺失');
|
|
188
265
|
check();
|
|
189
266
|
if (!this.exists(job))
|
|
190
267
|
return;
|
|
@@ -198,46 +275,66 @@ export class OpenVikingSessionSync {
|
|
|
198
275
|
check();
|
|
199
276
|
}
|
|
200
277
|
const uri = typeof info.uri === 'string' ? info.uri : `viking://session/${job.id}`;
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
catch (error) {
|
|
206
|
-
if (!missing(error) || Number(info.message_count ?? 0) > 0)
|
|
207
|
-
throw error;
|
|
208
|
-
}
|
|
209
|
-
check();
|
|
210
|
-
const remote = raw.split('\n').filter(line => line.trim()).map(line => {
|
|
211
|
-
const row = JSON.parse(line);
|
|
212
|
-
return { role: row.role, content: Array.isArray(row.parts) ? row.parts.filter((part) => part.type === 'text').map((part) => part.text).join('') : row.content ?? '', createdAt: new Date(row.created_at).toISOString() };
|
|
213
|
-
});
|
|
214
|
-
const rows = this.store.db.prepare('SELECT * FROM openviking_sync_messages WHERE session=? ORDER BY seq,message').all(job.id);
|
|
215
|
-
const desired = [];
|
|
216
|
-
let unfinished = false;
|
|
217
|
-
for (const row of rows) {
|
|
218
|
-
if (!row.ready) {
|
|
219
|
-
unfinished = true;
|
|
220
|
-
break;
|
|
278
|
+
const readRemote = async (minimum) => {
|
|
279
|
+
let raw = '';
|
|
280
|
+
try {
|
|
281
|
+
raw = await client.read(`${uri}/messages.jsonl`);
|
|
221
282
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
229
|
-
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (!missing(error) || minimum > 0 || Number(info.message_count ?? 0) > 0)
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
check();
|
|
288
|
+
return transcript(raw);
|
|
289
|
+
};
|
|
290
|
+
const acknowledged = Number(this.store.db.prepare('SELECT synced_messages FROM openviking_sync_jobs WHERE id=?').get(job.id)?.synced_messages ?? 0);
|
|
291
|
+
let remote = await readRemote(acknowledged);
|
|
292
|
+
// Network awaits let other clients revise/finish messages. Drain durable events
|
|
293
|
+
// before comparing so we never append using a stale local projection.
|
|
294
|
+
if (!this.discover(job.namespace) || !this.exists(job))
|
|
230
295
|
return;
|
|
296
|
+
let { desired, unfinished } = this.projection(job);
|
|
297
|
+
this.verify(remote, desired, acknowledged);
|
|
298
|
+
const intent = this.store.db.prepare('SELECT expected,fingerprint FROM openviking_sync_appends WHERE session=?').get(job.id);
|
|
299
|
+
if (intent) {
|
|
300
|
+
// A timed-out/crashed writer may still be executing at the remote service.
|
|
301
|
+
// A short prefix cannot prove it stopped. Never replay an uncertain suffix.
|
|
302
|
+
const expected = Number(intent.expected);
|
|
303
|
+
if (remote.length < expected || hash(JSON.stringify(remote.slice(0, expected))) !== intent.fingerprint)
|
|
304
|
+
throw new TranscriptConflict('上次追加结果尚未确认,请先确认原写入已结束');
|
|
305
|
+
this.store.db.prepare('DELETE FROM openviking_sync_appends WHERE session=?').run(job.id);
|
|
306
|
+
}
|
|
307
|
+
const verified = remote.length;
|
|
308
|
+
this.store.db.prepare('UPDATE openviking_sync_jobs SET synced_messages=? WHERE id=?').run(verified, job.id);
|
|
231
309
|
const batch = desired.slice(remote.length, remote.length + 100);
|
|
232
310
|
if (batch.length) {
|
|
233
|
-
|
|
311
|
+
this.store.db.prepare('INSERT INTO openviking_sync_appends VALUES(?,?,?)')
|
|
312
|
+
.run(job.id, verified + batch.length, hash(JSON.stringify(desired.slice(0, verified + batch.length))));
|
|
313
|
+
try {
|
|
314
|
+
await client.batchAddMessages(job.id, batch);
|
|
315
|
+
this.store.db.prepare('DELETE FROM openviking_sync_appends WHERE session=?').run(job.id);
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
// An application HTTP error completed the request; a timeout, broken
|
|
319
|
+
// connection or gateway timeout leaves the write result uncertain.
|
|
320
|
+
if (error instanceof OpenVikingError && error.statusCode && ![408, 502, 503, 504].includes(error.statusCode))
|
|
321
|
+
this.store.db.prepare('DELETE FROM openviking_sync_appends WHERE session=?').run(job.id);
|
|
322
|
+
throw error;
|
|
323
|
+
}
|
|
234
324
|
check();
|
|
325
|
+
// A successful HTTP response is not proof that the whole batch was stored.
|
|
326
|
+
// Partial failures and lost responses resume from this verified prefix.
|
|
327
|
+
remote = await readRemote(Math.max(verified, 1));
|
|
328
|
+
if (!this.discover(job.namespace) || !this.exists(job))
|
|
329
|
+
return;
|
|
330
|
+
({ desired, unfinished } = this.projection(job));
|
|
331
|
+
this.verify(remote, desired, verified);
|
|
332
|
+
if (remote.length === verified)
|
|
333
|
+
throw new Error('OpenViking 尚未确认新增记录,请稍后重试');
|
|
235
334
|
}
|
|
236
|
-
|
|
237
|
-
return;
|
|
238
|
-
const complete = !unfinished && remote.length + batch.length === desired.length;
|
|
335
|
+
const complete = !unfinished && remote.length === desired.length;
|
|
239
336
|
this.store.db.prepare('UPDATE openviking_sync_jobs SET status=?,synced_messages=?,attempts=0,next_at=?,error=NULL,updated_at=? WHERE id=?')
|
|
240
|
-
.run(complete ? 'complete' : 'pending', remote.length
|
|
337
|
+
.run(complete ? 'complete' : 'pending', remote.length, unfinished && !batch.length ? Date.now() + 5000 : 0, Date.now(), job.id);
|
|
241
338
|
}
|
|
242
339
|
async tick() {
|
|
243
340
|
if (this.active || this.closed)
|
|
@@ -253,6 +350,10 @@ export class OpenVikingSessionSync {
|
|
|
253
350
|
// consuming durable events, including databases whose events were pruned.
|
|
254
351
|
if (this.scanningNamespace !== namespace) {
|
|
255
352
|
this.store.db.prepare('UPDATE openviking_sync_state SET scan_row=0,scanned=0 WHERE namespace=?').run(namespace);
|
|
353
|
+
// Recheck legacy order failures once on startup. A genuine divergence
|
|
354
|
+
// still fails closed; no remote records are replaced or reordered.
|
|
355
|
+
this.store.db.prepare("UPDATE openviking_sync_jobs SET status='pending',attempts=0,next_at=0 WHERE namespace=? AND status='failed' AND error=?")
|
|
356
|
+
.run(namespace, conflictMessage);
|
|
256
357
|
this.scanningNamespace = namespace;
|
|
257
358
|
}
|
|
258
359
|
if (!this.discover(namespace))
|
|
@@ -261,17 +362,27 @@ export class OpenVikingSessionSync {
|
|
|
261
362
|
this.store.db.prepare("UPDATE openviking_sync_jobs SET status='pending',next_at=0 WHERE namespace=? AND status='complete' AND (NOT EXISTS(SELECT 1 FROM workspace_entities e WHERE e.owner=openviking_sync_jobs.owner AND e.kind='agent' AND e.id=openviking_sync_jobs.agent) OR NOT EXISTS(SELECT 1 FROM workspace_entities e WHERE e.owner=openviking_sync_jobs.owner AND e.kind='conversation' AND e.id=openviking_sync_jobs.conversation) OR (task!='' AND NOT EXISTS(SELECT 1 FROM workspace_entities e WHERE e.owner=openviking_sync_jobs.owner AND e.kind='conversation-task' AND e.id=openviking_sync_jobs.task)))").run(namespace);
|
|
262
363
|
const jobs = this.store.db.prepare("SELECT * FROM openviking_sync_jobs WHERE namespace=? AND status='pending' AND next_at<=? ORDER BY updated_at LIMIT 4").all(namespace, Date.now());
|
|
263
364
|
for (const job of jobs) {
|
|
365
|
+
const token = this.claim(job.id);
|
|
366
|
+
if (!token)
|
|
367
|
+
continue;
|
|
368
|
+
let currentJob = job;
|
|
264
369
|
try {
|
|
265
|
-
|
|
370
|
+
currentJob = this.store.db.prepare('SELECT * FROM openviking_sync_jobs WHERE id=?').get(job.id);
|
|
371
|
+
if (currentJob.status !== 'pending' || currentJob.next_at > Date.now())
|
|
372
|
+
continue;
|
|
373
|
+
await this.sync(currentJob);
|
|
266
374
|
}
|
|
267
375
|
catch (error) {
|
|
268
376
|
if (error instanceof Paused || this.closed)
|
|
269
377
|
break;
|
|
270
|
-
const attempts =
|
|
378
|
+
const attempts = currentJob.attempts + 1;
|
|
271
379
|
// Remote errors can contain request details; expose only a short error message.
|
|
272
380
|
const message = error instanceof Error ? error.message.slice(0, 400) : 'OpenViking 会话同步失败';
|
|
273
381
|
this.store.db.prepare('UPDATE openviking_sync_jobs SET status=?,attempts=?,next_at=?,error=?,updated_at=? WHERE id=?')
|
|
274
|
-
.run(attempts >= 3 ? 'failed' : 'pending', attempts, Date.now() + 2000 * 2 ** attempts, message, Date.now(), job.id);
|
|
382
|
+
.run(error instanceof TranscriptConflict || attempts >= 3 ? 'failed' : 'pending', attempts, Date.now() + 2000 * 2 ** attempts, message, Date.now(), job.id);
|
|
383
|
+
}
|
|
384
|
+
finally {
|
|
385
|
+
this.store.db.prepare('DELETE FROM openviking_sync_locks WHERE session=? AND token=?').run(job.id, token);
|
|
275
386
|
}
|
|
276
387
|
}
|
|
277
388
|
}
|
|
@@ -647,6 +647,8 @@ export class PushCoordinator {
|
|
|
647
647
|
return state.installations.length !== before;
|
|
648
648
|
});
|
|
649
649
|
}
|
|
650
|
+
unreadCounter;
|
|
651
|
+
setUnreadCounter(counter) { this.unreadCounter = counter; }
|
|
650
652
|
resetBadge(userIdValue, installationIdValue, clientAccountIdValue) {
|
|
651
653
|
const userId = requiredIdentifier(userIdValue, 'userId');
|
|
652
654
|
const installationId = requiredIdentifier(installationIdValue, 'installationId');
|
|
@@ -655,9 +657,10 @@ export class PushCoordinator {
|
|
|
655
657
|
const installation = state.installations.find(item => item.userId === userId
|
|
656
658
|
&& item.installationId === installationId
|
|
657
659
|
&& item.clientAccountId === clientAccountId);
|
|
660
|
+
const count = this.unreadCounter?.(userId) ?? 0;
|
|
658
661
|
if (installation)
|
|
659
|
-
installation.badge =
|
|
660
|
-
return
|
|
662
|
+
installation.badge = count;
|
|
663
|
+
return count;
|
|
661
664
|
});
|
|
662
665
|
}
|
|
663
666
|
listGroupSubscriptions(userIdValue) {
|
|
@@ -1006,7 +1009,7 @@ export class PushCoordinator {
|
|
|
1006
1009
|
throw new Error('Push outbox limit reached');
|
|
1007
1010
|
state.processedEvents[key] = now;
|
|
1008
1011
|
for (const target of targets) {
|
|
1009
|
-
target.badge
|
|
1012
|
+
target.badge = this.unreadCounter ? this.unreadCounter(userId) : target.badge + 1;
|
|
1010
1013
|
state.outbox.push({
|
|
1011
1014
|
id: randomUUID(),
|
|
1012
1015
|
eventId,
|
|
@@ -1146,7 +1149,7 @@ export class PushCoordinator {
|
|
|
1146
1149
|
aps: {
|
|
1147
1150
|
alert: { title: item.title, body: item.body },
|
|
1148
1151
|
sound: 'default',
|
|
1149
|
-
badge: installation.badge,
|
|
1152
|
+
badge: this.unreadCounter ? this.unreadCounter(item.userId) : installation.badge,
|
|
1150
1153
|
...(item.threadId ? { 'thread-id': item.threadId } : {}),
|
|
1151
1154
|
},
|
|
1152
1155
|
version: 1,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { acknowledgeUnread, unreadSnapshot } from './unreadCenter.js';
|
|
2
|
+
import { z } from 'zod';
|
|
1
3
|
import { RegistrationLimiter } from './subaccountAccess.js';
|
|
2
4
|
import { readServerIdentity, updateServerIdentity } from './serverIdentity.js';
|
|
3
5
|
import { authorizeFileRead, fileAccessWorkingDirectory, readFileAccess, saveFileAccess } from './fileAccess.js';
|
|
@@ -1924,6 +1926,22 @@ export function createApiRouter(dependencies) {
|
|
|
1924
1926
|
const owner = dependencies.auth.require(ctx).id;
|
|
1925
1927
|
ctx.body = { session_ids: dependencies.chatCache.store.pins(owner, String(ctx.query.profile ?? '')) };
|
|
1926
1928
|
});
|
|
1929
|
+
const unreadInput = z.object({ items: z.array(z.object({ mode: z.enum(['bot', 'chat']), id: z.string().min(1).max(256), profile: z.string().max(256).optional(), messages: z.array(z.object({ id: z.string().min(1).max(512), seq: z.number().int().nonnegative(), version: z.number().int().nonnegative().optional(), taskId: z.string().max(256).optional() }).strict()).max(20000) }).strict()).max(1000) }).strict();
|
|
1930
|
+
router.get('/api/app/unread', ctx => {
|
|
1931
|
+
const owner = dependencies.auth.require(ctx).id;
|
|
1932
|
+
ctx.set('Cache-Control', 'no-store');
|
|
1933
|
+
ctx.body = unreadSnapshot(dependencies.workspace, dependencies.chatCache.store, owner, (node, profile) => dependencies.auth.canUseSource(owner, node, profile));
|
|
1934
|
+
});
|
|
1935
|
+
router.post('/api/app/unread/read', ctx => {
|
|
1936
|
+
const owner = dependencies.auth.require(ctx).id, input = unreadInput.safeParse(body(ctx));
|
|
1937
|
+
if (!input.success)
|
|
1938
|
+
throw new HttpError(400, '未读快照格式无效', 'invalid_unread_snapshot');
|
|
1939
|
+
acknowledgeUnread(dependencies.workspace, dependencies.chatCache.store, owner, input.data.items, (node, profile) => dependencies.auth.canUseSource(owner, node, profile));
|
|
1940
|
+
for (const item of input.data.items)
|
|
1941
|
+
if (item.mode === 'chat')
|
|
1942
|
+
dependencies.onChatListChanged?.(owner, item.profile ?? 'default', item.id);
|
|
1943
|
+
ctx.body = unreadSnapshot(dependencies.workspace, dependencies.chatCache.store, owner, (node, profile) => dependencies.auth.canUseSource(owner, node, profile));
|
|
1944
|
+
});
|
|
1927
1945
|
router.get('/api/app/sessions/unread', ctx => {
|
|
1928
1946
|
const owner = dependencies.auth.require(ctx).id;
|
|
1929
1947
|
ctx.body = dependencies.chatCache.store.unread(owner, String(ctx.query.profile ?? ''));
|
|
@@ -125,6 +125,19 @@ export class RunnerHub {
|
|
|
125
125
|
return result;
|
|
126
126
|
}
|
|
127
127
|
records() { return this.store.list('_system', 'runner'); }
|
|
128
|
+
credentialBinding(owner, agent) {
|
|
129
|
+
if (agent.archived || !this.auth.canUseSource(owner, agent.nodeId, agent.profile))
|
|
130
|
+
throw new HttpError(403, 'Bot 凭据授权已结束', 'vault_agent_forbidden');
|
|
131
|
+
const record = this.records().find(r => r.enabled && r.sourceNodeId === agent.nodeId && (r.sourceOwner === '_system' || r.sourceOwner === owner));
|
|
132
|
+
const online = record && this.online.get(record.id);
|
|
133
|
+
if (!record || !online || Date.now() - online.seen >= 35000)
|
|
134
|
+
throw new HttpError(503, '执行节点离线,请等待节点连接', 'vault_runner_offline');
|
|
135
|
+
if (!record.allowedProfiles.includes(agent.profile))
|
|
136
|
+
throw new HttpError(403, '执行节点未授权当前 Profile', 'vault_agent_forbidden');
|
|
137
|
+
if (!online.features.includes('credential-ref-v1'))
|
|
138
|
+
throw new HttpError(409, '请更新 Runner,旧节点不支持凭据引用授权', 'vault_runner_upgrade_required');
|
|
139
|
+
return { runnerId: record.id, runnerInstance: online.instance, runnerEpoch: online.epoch };
|
|
140
|
+
}
|
|
128
141
|
enroll(owner, value) {
|
|
129
142
|
const body = parse(input, value);
|
|
130
143
|
body.allowedProfiles = this.auth.validateAssignedProfiles(body.allowedProfiles);
|
|
@@ -456,7 +469,7 @@ export class RunnerHub {
|
|
|
456
469
|
const state = this.online.get(record.id) ?? { instance, seen: Date.now(), features: [], epoch: `${this.epoch}:${randomUUID()}` };
|
|
457
470
|
state.seen = Date.now();
|
|
458
471
|
if (ctx.get('x-runner-features'))
|
|
459
|
-
state.features = ctx.get('x-runner-features').split(',').filter(value => ['execution-context-v1', 'vm-egress-v1', 'workspace-memory-bind-v1', 'hermes-computer-v2', 'profile-computer-v1', 'host-computer-tools-v1', 'file-transfer-v1', 'idle-stop-policy-v1', 'computer-worker-v1', 'artifact-chunks-v1', 'helper-retirement-v1', 'computer-control-v1', 'shared-computer-v1', 'local-vm-v1', 'image-options-v1', 'image-ready-v1', 'compose-desktops-v1', 'managed-browser-v1', 'managed-browser-setup-v1', 'managed-browser-disabled-v1', 'managed-browser-retention-v1'].includes(value));
|
|
472
|
+
state.features = ctx.get('x-runner-features').split(',').filter(value => ['execution-context-v1', 'vm-egress-v1', 'workspace-memory-bind-v1', 'hermes-computer-v2', 'profile-computer-v1', 'host-computer-tools-v1', 'file-transfer-v1', 'idle-stop-policy-v1', 'computer-worker-v1', 'artifact-chunks-v1', 'helper-retirement-v1', 'computer-control-v1', 'shared-computer-v1', 'local-vm-v1', 'image-options-v1', 'image-ready-v1', 'compose-desktops-v1', 'managed-browser-v1', 'managed-browser-setup-v1', 'managed-browser-disabled-v1', 'managed-browser-retention-v1', 'credential-ref-v1'].includes(value));
|
|
460
473
|
this.online.set(record.id, state);
|
|
461
474
|
ctx.set('Cache-Control', 'no-store');
|
|
462
475
|
if (match[2] === 'poll') {
|
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
/** Owner-scoped Bot endpoints. Keep native and administrative surfaces denied. */
|
|
2
2
|
export function isWorkspaceAccountPath(method, path) {
|
|
3
3
|
const read = method === 'GET' || method === 'HEAD';
|
|
4
|
+
if (read && path === '/api/app/unread')
|
|
5
|
+
return true;
|
|
6
|
+
if (method === 'POST' && path === '/api/app/unread/read')
|
|
7
|
+
return true;
|
|
8
|
+
if (read && path === '/api/app/vault')
|
|
9
|
+
return true;
|
|
10
|
+
if (method === 'POST' && /^\/api\/app\/vault\/(initialize|unlock|lock|rotate|backup|restore|entries|leases)$/.test(path))
|
|
11
|
+
return true;
|
|
12
|
+
if (['PUT', 'DELETE'].includes(method) && /^\/api\/app\/vault\/entries\/[0-9a-f-]{36}$/.test(path))
|
|
13
|
+
return true;
|
|
14
|
+
if (method === 'DELETE' && /^\/api\/app\/vault\/leases\/[0-9a-f-]{36}$/.test(path))
|
|
15
|
+
return true;
|
|
4
16
|
if (read && /^\/api\/app\/workspace\/(snapshot|projects|memories|memory-export|memory-jobs|collaboration)$/.test(path))
|
|
5
17
|
return true;
|
|
6
18
|
if (read && /^\/api\/app\/workspace\/memories\/[^/]+\/revisions$/.test(path))
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { emptyUnread } from '../shared/unread.js';
|
|
2
|
+
import { notificationPlainText } from './notificationText.js';
|
|
3
|
+
function messageTime(value) {
|
|
4
|
+
const numeric = Number(value);
|
|
5
|
+
if (Number.isFinite(numeric))
|
|
6
|
+
return numeric > 0 && numeric < 100_000_000_000 ? numeric * 1000 : numeric;
|
|
7
|
+
const parsed = typeof value === 'string' ? Date.parse(value) : NaN;
|
|
8
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
9
|
+
}
|
|
10
|
+
export function unreadSnapshot(workspace, cache, owner, allowed = () => true) {
|
|
11
|
+
const result = emptyUnread();
|
|
12
|
+
for (const c of workspace.list(owner, 'conversation')) {
|
|
13
|
+
if (c.archived || !c.memberIds.every(id => { const a = workspace.get(owner, 'agent', id); return !a || allowed(a.nodeId, a.profile); }))
|
|
14
|
+
continue;
|
|
15
|
+
const messages = workspace.chatUnreadMessages(owner, c.id);
|
|
16
|
+
if (!messages.length)
|
|
17
|
+
continue;
|
|
18
|
+
result.conversations.push({ mode: 'bot', id: c.id, name: c.name, preview: notificationPlainText(messages.at(-1).content, { maximum: 160, fallback: messages.at(-1).attachments[0]?.name ?? '附件' }), count: messages.length,
|
|
19
|
+
updatedAt: messages.at(-1).createdAt, messages: messages.map(m => ({ id: m.id, seq: m.seq, version: m.chatUnreadVersion, taskId: m.conversationTaskId })) });
|
|
20
|
+
}
|
|
21
|
+
for (const row of cache.unread(owner, '').sessions) {
|
|
22
|
+
if (!allowed('local', row.profile))
|
|
23
|
+
continue;
|
|
24
|
+
const stored = cache.db.prepare('SELECT s.data,l.archived FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE s.owner=? AND s.profile=? AND s.session_id=?').get(owner, row.profile, row.session_id);
|
|
25
|
+
if (!stored || stored.archived === 1)
|
|
26
|
+
continue;
|
|
27
|
+
const summary = JSON.parse(String(stored.data));
|
|
28
|
+
if (summary.archived || summary.source === 'yaoyao_workspace')
|
|
29
|
+
continue;
|
|
30
|
+
const messages = cache.transcripts.unreadMessages(owner, row.profile, row.session_id);
|
|
31
|
+
if (!messages.length)
|
|
32
|
+
continue;
|
|
33
|
+
const last = messages.at(-1);
|
|
34
|
+
result.conversations.push({ mode: 'chat', id: row.session_id, profile: row.profile, name: summary.title || summary.name || '未命名聊天', preview: notificationPlainText(typeof last.content === 'string' ? last.content : '', { maximum: 160, fallback: '附件' }), count: messages.length,
|
|
35
|
+
updatedAt: messageTime(last.timestamp ?? last.created_at ?? last.createdAt ?? summary.updated_at ?? 0), messages: messages.map(m => ({ id: m.id, seq: m.seq })) });
|
|
36
|
+
}
|
|
37
|
+
result.conversations.sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));
|
|
38
|
+
for (const row of result.conversations)
|
|
39
|
+
result[row.mode] += row.count;
|
|
40
|
+
result.total = result.bot + result.chat;
|
|
41
|
+
return result;
|
|
42
|
+
}
|
|
43
|
+
/** Only IDs in the user's click/render snapshot are acknowledged; later completions survive. */
|
|
44
|
+
export function acknowledgeUnread(workspace, cache, owner, items, allowed = () => true) {
|
|
45
|
+
for (const item of items) {
|
|
46
|
+
if (item.mode === 'bot') {
|
|
47
|
+
const c = workspace.require(owner, 'conversation', item.id);
|
|
48
|
+
if (!c.memberIds.every(id => { const a = workspace.get(owner, 'agent', id); return !a || allowed(a.nodeId, a.profile); }))
|
|
49
|
+
continue;
|
|
50
|
+
workspace.markChatMessagesRead(owner, c.id, item.messages);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
const profile = item.profile ?? 'default';
|
|
54
|
+
if (!allowed('local', profile))
|
|
55
|
+
continue;
|
|
56
|
+
cache.requireOwned(owner, profile, item.id);
|
|
57
|
+
cache.transcripts.seed(owner, profile, item.id);
|
|
58
|
+
cache.transcripts.markMessagesRead(owner, profile, item.id, item.messages.map(m => m.id));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -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,
|
|
@@ -5,12 +5,13 @@ import { HttpError } from './errors.js';
|
|
|
5
5
|
import { authorizeFileRead } from './fileAccess.js';
|
|
6
6
|
import { lookup } from 'mime-types';
|
|
7
7
|
import { messageFileReferences } from '../shared/messageFiles.js';
|
|
8
|
+
import { normalizeUploadName } from '../shared/uploadNames.js';
|
|
8
9
|
import { WorkspaceStore } from './workspaceStore.js';
|
|
9
10
|
import { WorkspaceNodes } from './workspaceGateway.js';
|
|
10
11
|
const archiveKey = (nodeId, profile, messageId, path) => createHash('sha256').update(JSON.stringify([nodeId, profile, messageId, path])).digest('hex');
|
|
11
12
|
export function publicFile(f) {
|
|
12
13
|
const { path: _path, digest: _digest, messageFileSource: _source, ...result } = f;
|
|
13
|
-
return result;
|
|
14
|
+
return result.sender === 'user' ? { ...result, name: normalizeUploadName(result.name) } : result;
|
|
14
15
|
}
|
|
15
16
|
export function libraryFile(f, id, conversation) {
|
|
16
17
|
const path = `/api/app/files/${f.id}/download`;
|
|
@@ -477,7 +477,7 @@ export function workspaceRouter(store, runtime, nodes, assets, uploads, auth, pu
|
|
|
477
477
|
const activeContent = /(?:html|svg|javascript|ecmascript|xml)/i.test(file.mimeType) ||
|
|
478
478
|
/\.(?:html?|svg|js|mjs|xml|xhtml)$/i.test(file.name);
|
|
479
479
|
ctx.type = activeContent ? 'application/octet-stream' : file.mimeType;
|
|
480
|
-
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)}`);
|
|
481
481
|
ctx.set('Accept-Ranges', 'bytes');
|
|
482
482
|
ctx.set('Cache-Control', 'private, no-store');
|
|
483
483
|
if (size === 0) {
|