@oxmumu3/dsh-agent-twin 0.6.0 → 0.6.2
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 +16 -9
- package/client.js +503 -6
- package/examples/growth-bi-desk/README.md +2 -1
- package/examples/growth-bi-desk/mtn/growth-ska-graph.json +69 -0
- package/lib/channels.js +67 -9
- package/lib/fullblood-runner.js +33 -6
- package/lib/guest-server.js +614 -137
- package/lib/host.js +38 -3
- package/lib/mtn-provider.js +284 -0
- package/lib/official-connectors.js +5 -1
- package/lib/owner-notifier.js +123 -0
- package/lib/routes.js +53 -3
- package/lib/scanner.js +145 -14
- package/lib/service.js +48 -6
- package/lib/store.js +162 -16
- package/lib/twin-engine.js +956 -440
- package/package.json +3 -3
- package/shared/schema.js +63 -0
package/lib/scanner.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* zero-token mtime/size delta detector, and Scoped Workspace sandbox materializer.
|
|
4
4
|
*/
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
|
-
import { lstat, mkdir, open, readdir, rm, symlink } from 'node:fs/promises';
|
|
6
|
+
import { lstat, mkdir, open, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';
|
|
7
7
|
import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
8
8
|
import {
|
|
9
9
|
IGNORED_DIR_NAMES,
|
|
@@ -85,6 +85,88 @@ function summarizeExcerpt(content) {
|
|
|
85
85
|
return sanitizeSurfaceText(joined).slice(0, 260);
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Normalize per-capability intra-project path scopes (`scopePaths`).
|
|
90
|
+
* Rejects path traversal (`..`) and null bytes while preserving trailing `/` dir prefixes.
|
|
91
|
+
*/
|
|
92
|
+
export function normalizeScopePaths(raw) {
|
|
93
|
+
const items = Array.isArray(raw)
|
|
94
|
+
? raw
|
|
95
|
+
: typeof raw === 'string'
|
|
96
|
+
? raw.split(/[,;\n]/)
|
|
97
|
+
: [];
|
|
98
|
+
const seen = new Set();
|
|
99
|
+
const out = [];
|
|
100
|
+
for (const entry of items) {
|
|
101
|
+
let clean = String(entry || '')
|
|
102
|
+
.trim()
|
|
103
|
+
.replace(/\\/g, '/')
|
|
104
|
+
.replace(/^(?:\.\/)+/, '')
|
|
105
|
+
.replace(/^\/+/, '');
|
|
106
|
+
if (!clean || clean.includes('\0')) continue;
|
|
107
|
+
const segments = clean.split('/').filter(Boolean);
|
|
108
|
+
if (segments.includes('..') || segments.includes('.')) continue;
|
|
109
|
+
if (!seen.has(clean)) {
|
|
110
|
+
seen.add(clean);
|
|
111
|
+
out.push(clean);
|
|
112
|
+
if (out.length >= 32) break;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function globPatternToRegex(pattern) {
|
|
119
|
+
let re = '^';
|
|
120
|
+
let i = 0;
|
|
121
|
+
while (i < pattern.length) {
|
|
122
|
+
const ch = pattern[i];
|
|
123
|
+
if (ch === '*') {
|
|
124
|
+
if (pattern[i + 1] === '*') {
|
|
125
|
+
re += '.*';
|
|
126
|
+
i += 2;
|
|
127
|
+
if (pattern[i] === '/') {
|
|
128
|
+
re = `${re.slice(0, -2)}(?:.*/)?`;
|
|
129
|
+
i += 1;
|
|
130
|
+
}
|
|
131
|
+
} else {
|
|
132
|
+
re += '[^/]*';
|
|
133
|
+
i += 1;
|
|
134
|
+
}
|
|
135
|
+
} else if (ch === '?') {
|
|
136
|
+
re += '[^/]';
|
|
137
|
+
i += 1;
|
|
138
|
+
} else {
|
|
139
|
+
re += ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
140
|
+
i += 1;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return new RegExp(`${re}$`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Check whether a project-relative POSIX path matches any allowed `scopePaths` entry.
|
|
148
|
+
* Empty `scopePaths` allows all safe project files.
|
|
149
|
+
*/
|
|
150
|
+
export function matchesScopePaths(relPosixPath, scopePaths) {
|
|
151
|
+
const patterns = normalizeScopePaths(scopePaths);
|
|
152
|
+
if (patterns.length === 0) return true;
|
|
153
|
+
const rel = String(relPosixPath || '')
|
|
154
|
+
.replace(/\\/g, '/')
|
|
155
|
+
.replace(/^(?:\.\/)+/, '')
|
|
156
|
+
.replace(/^\/+/, '');
|
|
157
|
+
if (!rel) return false;
|
|
158
|
+
for (const pat of patterns) {
|
|
159
|
+
if (pat.endsWith('/')) {
|
|
160
|
+
if (rel.startsWith(pat)) return true;
|
|
161
|
+
} else if (pat.includes('*') || pat.includes('?')) {
|
|
162
|
+
if (globPatternToRegex(pat).test(rel)) return true;
|
|
163
|
+
} else if (rel === pat || rel.startsWith(`${pat}/`)) {
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
|
|
88
170
|
/**
|
|
89
171
|
* Walk a local directory in read-only bounded mode, separating high-signal docs,
|
|
90
172
|
* read-only tools, secret files, and write-capable scripts without storing secret values.
|
|
@@ -262,6 +344,7 @@ function buildCapabilities({ projectId, projectName, docs, readOnlyScripts }) {
|
|
|
262
344
|
projectName,
|
|
263
345
|
name: `${projectName} · 指标与业务口径解答`,
|
|
264
346
|
enabled: true,
|
|
347
|
+
scopePaths: [],
|
|
265
348
|
desc: docs.length > 0
|
|
266
349
|
? `依据已扫描的「${docTopics}」等 ${docs.length} 份项目文档,精确说明口径定义与统计边界。`
|
|
267
350
|
: `仅在「${projectName}」现有说明范围内提供只读解答,遇到未定义内容自动标注「待补口径」。`,
|
|
@@ -276,6 +359,7 @@ function buildCapabilities({ projectId, projectName, docs, readOnlyScripts }) {
|
|
|
276
359
|
projectName,
|
|
277
360
|
name: `${projectName} · 异常排查与规律总结`,
|
|
278
361
|
enabled: true,
|
|
362
|
+
scopePaths: [],
|
|
279
363
|
desc: '对照历史复盘与只读查询结构拆解波动原因,优先排除测试干扰后再输出归因判断。',
|
|
280
364
|
basis: `${docs.length} 份文档 · ${readOnlyScripts.length} 项只读逻辑`,
|
|
281
365
|
output: '逐条列出主因、已排除干扰项与建议'
|
|
@@ -288,6 +372,7 @@ function buildCapabilities({ projectId, projectName, docs, readOnlyScripts }) {
|
|
|
288
372
|
projectName,
|
|
289
373
|
name: `${projectName} · 方案复核与只读核验`,
|
|
290
374
|
enabled: true,
|
|
375
|
+
scopePaths: [],
|
|
291
376
|
desc: '按约定规则与拦截红线复核对外提问,自动挡回越权明细与修改写入请求。',
|
|
292
377
|
basis: '项目规范与只读红线边界',
|
|
293
378
|
output: '安全汇总结论,越权部分转负责人拍板'
|
|
@@ -298,14 +383,16 @@ function buildCapabilities({ projectId, projectName, docs, readOnlyScripts }) {
|
|
|
298
383
|
|
|
299
384
|
/**
|
|
300
385
|
* Materialize an isolated per-caller (or per-extraction) symlink sandbox containing ONLY
|
|
301
|
-
* owner-authorized project files
|
|
386
|
+
* owner-authorized project files (and optional per-capability `scopePaths`),
|
|
387
|
+
* excluding secrets, hidden agent/git dirs, and write scripts.
|
|
302
388
|
*/
|
|
303
389
|
export async function materializeScopedWorkspace({
|
|
304
390
|
rootDir,
|
|
305
391
|
scopeKey,
|
|
306
392
|
mountedProjects = [],
|
|
307
393
|
capabilities = [],
|
|
308
|
-
allowedCapIds = null
|
|
394
|
+
allowedCapIds = null,
|
|
395
|
+
reuseIfUnchanged = false
|
|
309
396
|
}) {
|
|
310
397
|
const sandboxesRoot = resolve(String(rootDir || ''), 'sandboxes');
|
|
311
398
|
const safeScope = slugifyCallerId(scopeKey || 'default');
|
|
@@ -314,20 +401,52 @@ export async function materializeScopedWorkspace({
|
|
|
314
401
|
throw new Error('Invalid sandbox scope key');
|
|
315
402
|
}
|
|
316
403
|
|
|
317
|
-
await rm(sandboxDir, { recursive: true, force: true });
|
|
318
|
-
await mkdir(sandboxDir, { recursive: true, mode: 0o700 });
|
|
319
|
-
|
|
320
404
|
const allowedSet = Array.isArray(allowedCapIds) ? new Set(allowedCapIds) : null;
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
.filter(c => c?.enabled && (!allowedSet || allowedSet.has(c.id)))
|
|
324
|
-
.map(c => c.projectId)
|
|
325
|
-
);
|
|
405
|
+
const authorizedCaps = (capabilities || []).filter(c => c?.enabled && (!allowedSet || allowedSet.has(c.id)));
|
|
406
|
+
const authorizedProjectIds = new Set(authorizedCaps.map(c => c.projectId));
|
|
326
407
|
|
|
327
408
|
const selectedProjects = (mountedProjects || []).filter(mp =>
|
|
328
409
|
mp?.rootPath && (authorizedProjectIds.size === 0 ? false : authorizedProjectIds.has(mp.id))
|
|
329
410
|
);
|
|
330
411
|
|
|
412
|
+
const digestPayload = {
|
|
413
|
+
projects: selectedProjects
|
|
414
|
+
.map(mp => ({
|
|
415
|
+
id: mp.id,
|
|
416
|
+
rootPath: resolve(String(mp.rootPath)),
|
|
417
|
+
lastCheckedAt: mp.lastCheckedAt || ''
|
|
418
|
+
}))
|
|
419
|
+
.sort((a, b) => a.id.localeCompare(b.id)),
|
|
420
|
+
caps: authorizedCaps
|
|
421
|
+
.map(c => ({
|
|
422
|
+
id: c.id,
|
|
423
|
+
projectId: c.projectId,
|
|
424
|
+
scopePaths: normalizeScopePaths(c.scopePaths)
|
|
425
|
+
}))
|
|
426
|
+
.sort((a, b) => a.id.localeCompare(b.id))
|
|
427
|
+
};
|
|
428
|
+
const manifestDigest = createHash('sha256').update(JSON.stringify(digestPayload)).digest('hex');
|
|
429
|
+
const manifestPath = resolve(sandboxesRoot, `.manifest-${safeScope}.json`);
|
|
430
|
+
|
|
431
|
+
if (reuseIfUnchanged) {
|
|
432
|
+
try {
|
|
433
|
+
const [sbStat, mfStat] = await Promise.all([lstat(sandboxDir), lstat(manifestPath)]);
|
|
434
|
+
if (!sbStat.isSymbolicLink() && sbStat.isDirectory() && !mfStat.isSymbolicLink() && mfStat.isFile()) {
|
|
435
|
+
const mfRaw = JSON.parse(await readFile(manifestPath, 'utf8'));
|
|
436
|
+
if (mfRaw?.digest === manifestDigest && Array.isArray(mfRaw.linkedProjects)) {
|
|
437
|
+
return { sandboxDir, linkedProjects: mfRaw.linkedProjects, reused: true };
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
} catch {
|
|
441
|
+
// Cache miss or stale directory — fall through to fresh materialization
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
await mkdir(sandboxesRoot, { recursive: true, mode: 0o700 });
|
|
446
|
+
await rm(manifestPath, { force: true }).catch(() => {});
|
|
447
|
+
await rm(sandboxDir, { recursive: true, force: true });
|
|
448
|
+
await mkdir(sandboxDir, { recursive: true, mode: 0o700 });
|
|
449
|
+
|
|
331
450
|
const linkedProjects = [];
|
|
332
451
|
|
|
333
452
|
for (const mp of selectedProjects) {
|
|
@@ -340,6 +459,11 @@ export async function materializeScopedWorkspace({
|
|
|
340
459
|
continue;
|
|
341
460
|
}
|
|
342
461
|
|
|
462
|
+
const projCaps = authorizedCaps.filter(c => c.projectId === mp.id);
|
|
463
|
+
const normalizedLists = projCaps.map(c => normalizeScopePaths(c.scopePaths));
|
|
464
|
+
const restrictByPaths = projCaps.length > 0 && normalizedLists.every(list => list.length > 0);
|
|
465
|
+
const unionPaths = restrictByPaths ? [...new Set(normalizedLists.flat())] : [];
|
|
466
|
+
|
|
343
467
|
const slug = slugifyCallerId(mp.projectName || basename(absProjectRoot) || mp.id);
|
|
344
468
|
const targetProjectDir = selectedProjects.length === 1 ? sandboxDir : join(sandboxDir, slug);
|
|
345
469
|
await mkdir(targetProjectDir, { recursive: true, mode: 0o700 });
|
|
@@ -373,12 +497,12 @@ export async function materializeScopedWorkspace({
|
|
|
373
497
|
if (ent.isDirectory()) {
|
|
374
498
|
if (IGNORED_DIR_NAMES.has(ent.name)) continue;
|
|
375
499
|
const nextDst = join(dstDir, ent.name);
|
|
376
|
-
await mkdir(nextDst, { recursive: true, mode: 0o700 });
|
|
377
500
|
await mirrorSafeEntries(srcFull, nextDst, depth + 1);
|
|
378
501
|
continue;
|
|
379
502
|
}
|
|
380
503
|
if (!st.isFile()) continue;
|
|
381
504
|
if (NOISE_FILE_RE.test(ent.name) || SECRET_FILE_RE.test(rel)) continue;
|
|
505
|
+
if (restrictByPaths && !matchesScopePaths(rel, unionPaths)) continue;
|
|
382
506
|
|
|
383
507
|
const ext = extname(ent.name).toLowerCase();
|
|
384
508
|
if (!DOC_EXTS.has(ext) && !SCRIPT_EXTS.has(ext)) continue;
|
|
@@ -394,16 +518,23 @@ export async function materializeScopedWorkspace({
|
|
|
394
518
|
const relFromRoot = relative(absProjectRoot, srcFull);
|
|
395
519
|
if (relFromRoot === '..' || relFromRoot.startsWith(`..${sep}`) || isAbsolute(relFromRoot)) continue;
|
|
396
520
|
|
|
521
|
+
await mkdir(dstDir, { recursive: true, mode: 0o700 });
|
|
397
522
|
await symlink(srcFull, join(dstDir, ent.name));
|
|
398
523
|
linkedCount += 1;
|
|
399
524
|
}
|
|
400
525
|
}
|
|
401
526
|
|
|
402
527
|
await mirrorSafeEntries(absProjectRoot, targetProjectDir, 0);
|
|
403
|
-
linkedProjects.push({ id: mp.id, name: mp.projectName, linkedCount, dir: targetProjectDir });
|
|
528
|
+
linkedProjects.push({ id: mp.id, name: mp.projectName, linkedCount, dir: targetProjectDir, scopedPaths: unionPaths });
|
|
404
529
|
}
|
|
405
530
|
|
|
406
|
-
|
|
531
|
+
await writeFile(
|
|
532
|
+
manifestPath,
|
|
533
|
+
`${JSON.stringify({ digest: manifestDigest, linkedProjects, updatedAt: new Date().toISOString() }, null, 2)}\n`,
|
|
534
|
+
{ encoding: 'utf8', mode: 0o600 }
|
|
535
|
+
).catch(() => {});
|
|
536
|
+
|
|
537
|
+
return { sandboxDir, linkedProjects, reused: false };
|
|
407
538
|
}
|
|
408
539
|
|
|
409
540
|
/**
|
package/lib/service.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Public Cordis service (`ctx.get('agentTwin')`, `agentTwin` v0.6.
|
|
2
|
+
* Public Cordis service (`ctx.get('agentTwin')`, `agentTwin` v0.6.1).
|
|
3
3
|
* Exposes AI 分身 lifecycle, Scoped Twin querying, inbound event injection,
|
|
4
|
-
*
|
|
4
|
+
* intra-project `scopePaths` controls, and MTN / SKA semantic graph hooks.
|
|
5
5
|
*/
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import {
|
|
@@ -11,8 +11,25 @@ import {
|
|
|
11
11
|
RULE_KINDS,
|
|
12
12
|
channelIdFromSelection,
|
|
13
13
|
channelSelectionLabel,
|
|
14
|
+
normalizePublicBaseUrl,
|
|
15
|
+
normalizePublicLobbyConfig,
|
|
14
16
|
sanitizeSurfaceText
|
|
15
17
|
} from '../shared/schema.js';
|
|
18
|
+
import { normalizeScopePaths } from './scanner.js';
|
|
19
|
+
|
|
20
|
+
export async function applyPublicLobbyPatch(store, patch = {}) {
|
|
21
|
+
const input = patch && typeof patch === 'object' ? { ...patch } : {};
|
|
22
|
+
if (input.publicBaseUrl !== undefined) {
|
|
23
|
+
input.publicBaseUrl = normalizePublicBaseUrl(input.publicBaseUrl);
|
|
24
|
+
}
|
|
25
|
+
await store.updateState(st => {
|
|
26
|
+
const validCaps = new Set((st.capabilities || []).map(c => c.id));
|
|
27
|
+
const nextCfg = normalizePublicLobbyConfig(input, st.publicLobby);
|
|
28
|
+
nextCfg.capIds = (nextCfg.capIds || []).filter(cid => validCaps.has(cid));
|
|
29
|
+
st.publicLobby = nextCfg;
|
|
30
|
+
}, { saveUndo: 'caps' });
|
|
31
|
+
return store.getState().publicLobby;
|
|
32
|
+
}
|
|
16
33
|
|
|
17
34
|
export function createTwinService(runtime) {
|
|
18
35
|
const {
|
|
@@ -22,6 +39,7 @@ export function createTwinService(runtime) {
|
|
|
22
39
|
officialConnectors,
|
|
23
40
|
guestServer,
|
|
24
41
|
fullBloodRunner,
|
|
42
|
+
mtnProvider = null,
|
|
25
43
|
registerKnowledgeProvider
|
|
26
44
|
} = runtime;
|
|
27
45
|
|
|
@@ -220,23 +238,47 @@ export function createTwinService(runtime) {
|
|
|
220
238
|
};
|
|
221
239
|
}
|
|
222
240
|
|
|
241
|
+
async function updateCapabilityScope(capId, scopePaths) {
|
|
242
|
+
const normalized = normalizeScopePaths(scopePaths);
|
|
243
|
+
await store.updateState(st => {
|
|
244
|
+
const cap = st.capabilities.find(c => c.id === capId);
|
|
245
|
+
if (!cap) throw new Error('未找到对应能力项');
|
|
246
|
+
cap.scopePaths = normalized;
|
|
247
|
+
}, { saveUndo: 'caps' });
|
|
248
|
+
return { ok: true, capId, scopePaths: normalized };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function configurePublicLobby(patch = {}) {
|
|
252
|
+
await applyPublicLobbyPatch(store, patch);
|
|
253
|
+
return getStatus();
|
|
254
|
+
}
|
|
255
|
+
|
|
223
256
|
return Object.freeze({
|
|
224
|
-
version: '0.6.
|
|
257
|
+
version: '0.6.2',
|
|
225
258
|
features: Object.freeze({
|
|
226
259
|
fullBloodDshAgent: true,
|
|
227
260
|
officialConnectors023: true,
|
|
228
261
|
weixinIlink: true,
|
|
229
262
|
toolViews: true,
|
|
230
|
-
knowledgeProviderHook: true
|
|
263
|
+
knowledgeProviderHook: true,
|
|
264
|
+
streamingProgress: true,
|
|
265
|
+
scopePathIsolation: true,
|
|
266
|
+
mtnSemanticGraph: true,
|
|
267
|
+
mobileOwnerApproval: true,
|
|
268
|
+
publicTryLobby: true
|
|
231
269
|
}),
|
|
232
270
|
getStatus,
|
|
233
271
|
publishWorkspace,
|
|
234
272
|
grantAccess,
|
|
235
273
|
listInbox,
|
|
236
274
|
resolveApproval,
|
|
275
|
+
updateCapabilityScope,
|
|
276
|
+
configurePublicLobby,
|
|
277
|
+
listMtnNodes: () => (mtnProvider ? mtnProvider.listNodes() : Promise.resolve([])),
|
|
278
|
+
upsertMtnNodes: nodes => (mtnProvider ? mtnProvider.upsertNodes(nodes) : Promise.reject(new Error('MTN provider unavailable'))),
|
|
237
279
|
submitInboundEvent: (channelId, event) => channelManager.handleExternalEvent(channelId, event),
|
|
238
|
-
queryScopedTwin: ({ personId, question, sandboxOnly = true }) =>
|
|
239
|
-
engine.handleInboundMessage({ personId, question, sandboxOnly }),
|
|
280
|
+
queryScopedTwin: ({ personId, question, sandboxOnly = true, onProgress = null }) =>
|
|
281
|
+
engine.handleInboundMessage({ personId, question, sandboxOnly, onProgress }),
|
|
240
282
|
probeOfficialConnectors: () =>
|
|
241
283
|
officialConnectors ? officialConnectors.probeAll() : Promise.resolve({}),
|
|
242
284
|
registerKnowledgeProvider: provider => registerKnowledgeProvider(provider)
|
package/lib/store.js
CHANGED
|
@@ -3,15 +3,18 @@
|
|
|
3
3
|
* per-caller isolated conversation directories, and non-destructive legacy import.
|
|
4
4
|
*/
|
|
5
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
-
import { chmod, lstat, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { chmod, lstat, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
|
|
7
7
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import QRCode from 'qrcode';
|
|
9
10
|
import {
|
|
10
11
|
DEFAULT_DAILY_TURN_CAP,
|
|
11
12
|
channelIdFromSelection,
|
|
12
13
|
createDefaultChannels,
|
|
14
|
+
createDefaultPublicLobby,
|
|
13
15
|
createDefaultRules,
|
|
14
16
|
maskSecretHint,
|
|
17
|
+
normalizePublicLobbyConfig,
|
|
15
18
|
redactSecrets,
|
|
16
19
|
sanitizeSurfaceText,
|
|
17
20
|
slugifyCallerId
|
|
@@ -127,6 +130,11 @@ export function createInitialState() {
|
|
|
127
130
|
onboardMode: 'initial',
|
|
128
131
|
dutyMode: 'shadow',
|
|
129
132
|
presenceAutoYield: true,
|
|
133
|
+
ackSlowTurns: true,
|
|
134
|
+
ownerNotify: {
|
|
135
|
+
feishu: true,
|
|
136
|
+
wechat: false
|
|
137
|
+
},
|
|
130
138
|
dailyTurnCap: DEFAULT_DAILY_TURN_CAP,
|
|
131
139
|
twinProfile: {
|
|
132
140
|
personaId: 'advisor',
|
|
@@ -144,6 +152,8 @@ export function createInitialState() {
|
|
|
144
152
|
approvals: [],
|
|
145
153
|
deliveries: [],
|
|
146
154
|
processedEventIds: [],
|
|
155
|
+
publicLobby: createDefaultPublicLobby(),
|
|
156
|
+
publicLobbyUsage: { date: todayKey(), count: 0 },
|
|
147
157
|
selfTestTurn: null,
|
|
148
158
|
extractionJob: null
|
|
149
159
|
};
|
|
@@ -157,6 +167,7 @@ export function createTwinStore(paths) {
|
|
|
157
167
|
const statePath = join(paths.rootDir, 'state.json');
|
|
158
168
|
const secretsPath = join(paths.rootDir, 'secrets.json');
|
|
159
169
|
const callersRoot = join(paths.rootDir, 'twins', 'main', 'callers');
|
|
170
|
+
const visitorsRoot = join(paths.rootDir, 'twins', 'main', 'visitors');
|
|
160
171
|
const projectsRoot = join(paths.rootDir, 'projects');
|
|
161
172
|
|
|
162
173
|
let state = null;
|
|
@@ -165,6 +176,9 @@ export function createTwinStore(paths) {
|
|
|
165
176
|
let capsUndoStack = [];
|
|
166
177
|
let writeChain = Promise.resolve();
|
|
167
178
|
let pairSeq = 10;
|
|
179
|
+
let lastVisitorPruneMs = 0;
|
|
180
|
+
let cachedTryQrKey = '';
|
|
181
|
+
let cachedTryQrSvg = '';
|
|
168
182
|
|
|
169
183
|
function enqueue(fn) {
|
|
170
184
|
const next = writeChain.then(fn, fn);
|
|
@@ -181,12 +195,24 @@ export function createTwinStore(paths) {
|
|
|
181
195
|
return resolved;
|
|
182
196
|
}
|
|
183
197
|
|
|
184
|
-
|
|
185
|
-
const
|
|
198
|
+
function safeVisitorDir(visitorId) {
|
|
199
|
+
const clean = String(visitorId || '').trim().toLowerCase();
|
|
200
|
+
if (!/^[a-f0-9]{16,32}$/.test(clean)) {
|
|
201
|
+
throw new Error('Invalid visitor identifier');
|
|
202
|
+
}
|
|
203
|
+
const resolved = resolve(visitorsRoot, clean);
|
|
204
|
+
if (!resolved.startsWith(`${resolve(visitorsRoot)}/`)) {
|
|
205
|
+
throw new Error('Invalid visitor directory');
|
|
206
|
+
}
|
|
207
|
+
return { clean, dir: resolved };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function readScopedThread(dir, idField, idVal) {
|
|
211
|
+
const file = join(dir, 'thread.json');
|
|
186
212
|
const data = await safeReadJson(file);
|
|
187
213
|
if (data && typeof data === 'object') {
|
|
188
214
|
return {
|
|
189
|
-
|
|
215
|
+
[idField]: idVal,
|
|
190
216
|
dshSessionId: typeof data.dshSessionId === 'string' ? data.dshSessionId : '',
|
|
191
217
|
lastPolicyDigest: typeof data.lastPolicyDigest === 'string' ? data.lastPolicyDigest : '',
|
|
192
218
|
turns: Array.isArray(data.turns) ? data.turns : [],
|
|
@@ -195,7 +221,7 @@ export function createTwinStore(paths) {
|
|
|
195
221
|
};
|
|
196
222
|
}
|
|
197
223
|
return {
|
|
198
|
-
|
|
224
|
+
[idField]: idVal,
|
|
199
225
|
dshSessionId: '',
|
|
200
226
|
lastPolicyDigest: '',
|
|
201
227
|
turns: [],
|
|
@@ -204,17 +230,15 @@ export function createTwinStore(paths) {
|
|
|
204
230
|
};
|
|
205
231
|
}
|
|
206
232
|
|
|
207
|
-
async function
|
|
208
|
-
const file = join(safeCallerDir(callerId), 'thread.json');
|
|
209
|
-
return atomicWriteJson(file, threadData, 0o600);
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async function appendCallerTurn(callerId, turn, opts = {}) {
|
|
233
|
+
async function appendScopedTurn(dir, idField, idVal, turn, opts = {}) {
|
|
213
234
|
return enqueue(async () => {
|
|
214
|
-
const thread = await
|
|
235
|
+
const thread = await readScopedThread(dir, idField, idVal);
|
|
215
236
|
const today = todayKey();
|
|
216
237
|
const currentCount = thread.dailyTurns?.date === today ? (thread.dailyTurns.count || 0) : 0;
|
|
217
238
|
thread.turns.push(turn);
|
|
239
|
+
if (opts.maxTurns && thread.turns.length > opts.maxTurns) {
|
|
240
|
+
thread.turns = thread.turns.slice(-opts.maxTurns);
|
|
241
|
+
}
|
|
218
242
|
if (typeof opts.dshSessionId === 'string' && opts.dshSessionId) {
|
|
219
243
|
thread.dshSessionId = opts.dshSessionId;
|
|
220
244
|
}
|
|
@@ -224,21 +248,97 @@ export function createTwinStore(paths) {
|
|
|
224
248
|
if (opts.countTurn !== false) {
|
|
225
249
|
thread.dailyTurns = { date: today, count: currentCount + 1 };
|
|
226
250
|
}
|
|
227
|
-
await
|
|
251
|
+
await atomicWriteJson(join(dir, 'thread.json'), thread, 0o600);
|
|
228
252
|
return thread;
|
|
229
253
|
});
|
|
230
254
|
}
|
|
231
255
|
|
|
232
|
-
async function
|
|
256
|
+
async function updateScopedMeta(dir, idField, idVal, patch = {}) {
|
|
233
257
|
return enqueue(async () => {
|
|
234
|
-
const thread = await
|
|
258
|
+
const thread = await readScopedThread(dir, idField, idVal);
|
|
235
259
|
if (typeof patch.dshSessionId === 'string') thread.dshSessionId = patch.dshSessionId;
|
|
236
260
|
if (typeof patch.lastPolicyDigest === 'string') thread.lastPolicyDigest = patch.lastPolicyDigest;
|
|
237
|
-
await
|
|
261
|
+
await atomicWriteJson(join(dir, 'thread.json'), thread, 0o600);
|
|
238
262
|
return thread;
|
|
239
263
|
});
|
|
240
264
|
}
|
|
241
265
|
|
|
266
|
+
async function readCallerThread(callerId) {
|
|
267
|
+
return readScopedThread(safeCallerDir(callerId), 'callerId', callerId);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function writeCallerThread(callerId, threadData) {
|
|
271
|
+
const file = join(safeCallerDir(callerId), 'thread.json');
|
|
272
|
+
return atomicWriteJson(file, threadData, 0o600);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async function appendCallerTurn(callerId, turn, opts = {}) {
|
|
276
|
+
return appendScopedTurn(safeCallerDir(callerId), 'callerId', callerId, turn, opts);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function updateCallerMeta(callerId, patch = {}) {
|
|
280
|
+
return updateScopedMeta(safeCallerDir(callerId), 'callerId', callerId, patch);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function pruneStaleVisitors() {
|
|
284
|
+
const now = Date.now();
|
|
285
|
+
if (now - lastVisitorPruneMs < 10 * 60 * 1000) return;
|
|
286
|
+
lastVisitorPruneMs = now;
|
|
287
|
+
try {
|
|
288
|
+
const entries = await readdir(visitorsRoot, { withFileTypes: true });
|
|
289
|
+
if (entries.length === 0) return;
|
|
290
|
+
const metaList = [];
|
|
291
|
+
const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;
|
|
292
|
+
for (const ent of entries) {
|
|
293
|
+
if (!ent.isDirectory()) continue;
|
|
294
|
+
const p = join(visitorsRoot, ent.name);
|
|
295
|
+
try {
|
|
296
|
+
const st = await stat(p);
|
|
297
|
+
if (now - st.mtimeMs > sevenDaysMs) {
|
|
298
|
+
await rm(p, { recursive: true, force: true });
|
|
299
|
+
} else {
|
|
300
|
+
metaList.push({ p, mtimeMs: st.mtimeMs });
|
|
301
|
+
}
|
|
302
|
+
} catch {
|
|
303
|
+
// ignore
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (metaList.length > 300) {
|
|
307
|
+
metaList.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
308
|
+
for (const item of metaList.slice(0, metaList.length - 300)) {
|
|
309
|
+
await rm(item.p, { recursive: true, force: true }).catch(() => {});
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
} catch {
|
|
313
|
+
// ignore pruning failures
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function readVisitorThread(visitorId) {
|
|
318
|
+
const { clean, dir } = safeVisitorDir(visitorId);
|
|
319
|
+
return readScopedThread(dir, 'visitorId', clean);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function appendVisitorTurn(visitorId, turn, opts = {}) {
|
|
323
|
+
const { clean, dir } = safeVisitorDir(visitorId);
|
|
324
|
+
const res = await appendScopedTurn(dir, 'visitorId', clean, turn, { ...opts, maxTurns: 40 });
|
|
325
|
+
void pruneStaleVisitors();
|
|
326
|
+
return res;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function updateVisitorMeta(visitorId, patch = {}) {
|
|
330
|
+
const { clean, dir } = safeVisitorDir(visitorId);
|
|
331
|
+
return updateScopedMeta(dir, 'visitorId', clean, patch);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function incrementPublicLobbyUsage() {
|
|
335
|
+
return updateState(st => {
|
|
336
|
+
const today = todayKey();
|
|
337
|
+
const prevCount = st.publicLobbyUsage?.date === today ? (st.publicLobbyUsage.count || 0) : 0;
|
|
338
|
+
st.publicLobbyUsage = { date: today, count: prevCount + 1 };
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
242
342
|
async function readProjectIndex(projectId) {
|
|
243
343
|
const clean = slugifyCallerId(projectId);
|
|
244
344
|
const file = join(projectsRoot, clean, 'index.json');
|
|
@@ -317,6 +417,7 @@ export function createTwinStore(paths) {
|
|
|
317
417
|
async function init() {
|
|
318
418
|
await ensureDir(paths.rootDir, 0o700);
|
|
319
419
|
await ensureDir(callersRoot, 0o700);
|
|
420
|
+
await ensureDir(visitorsRoot, 0o700);
|
|
320
421
|
await ensureDir(projectsRoot, 0o700);
|
|
321
422
|
|
|
322
423
|
const existingSecrets = await safeReadJson(secretsPath);
|
|
@@ -328,6 +429,11 @@ export function createTwinStore(paths) {
|
|
|
328
429
|
state = existingState;
|
|
329
430
|
// Ensure structural defaults if upgrading patch state
|
|
330
431
|
state.dailyTurnCap ||= DEFAULT_DAILY_TURN_CAP;
|
|
432
|
+
state.ackSlowTurns = state.ackSlowTurns !== false;
|
|
433
|
+
state.ownerNotify = {
|
|
434
|
+
feishu: state.ownerNotify?.feishu !== false,
|
|
435
|
+
wechat: Boolean(state.ownerNotify?.wechat)
|
|
436
|
+
};
|
|
331
437
|
state.channels ||= createDefaultChannels();
|
|
332
438
|
state.rules ||= createDefaultRules();
|
|
333
439
|
state.mountedProjects ||= [];
|
|
@@ -337,6 +443,10 @@ export function createTwinStore(paths) {
|
|
|
337
443
|
state.deliveries ||= [];
|
|
338
444
|
state.processedEventIds ||= [];
|
|
339
445
|
state.pendingDeltaByProject ||= {};
|
|
446
|
+
state.publicLobby = normalizePublicLobbyConfig(state.publicLobby);
|
|
447
|
+
if (!state.publicLobbyUsage || typeof state.publicLobbyUsage !== 'object' || !state.publicLobbyUsage.date) {
|
|
448
|
+
state.publicLobbyUsage = { date: todayKey(), count: 0 };
|
|
449
|
+
}
|
|
340
450
|
|
|
341
451
|
const beforeLen = state.mountedProjects.length;
|
|
342
452
|
state.mountedProjects = state.mountedProjects.filter(mp =>
|
|
@@ -528,6 +638,30 @@ export function createTwinStore(paths) {
|
|
|
528
638
|
deltaSpec: mp.deltaSpec || null
|
|
529
639
|
}));
|
|
530
640
|
|
|
641
|
+
const publicCfg = normalizePublicLobbyConfig(s.publicLobby);
|
|
642
|
+
const rawPublicBase = (publicCfg.publicBaseUrl || guestBaseUrl || '').replace(/\/+$/, '');
|
|
643
|
+
const tryUrl = rawPublicBase ? `${rawPublicBase}/try` : '';
|
|
644
|
+
let publicQrSvg = '';
|
|
645
|
+
if (tryUrl) {
|
|
646
|
+
if (cachedTryQrKey === tryUrl && cachedTryQrSvg) {
|
|
647
|
+
publicQrSvg = cachedTryQrSvg;
|
|
648
|
+
} else {
|
|
649
|
+
try {
|
|
650
|
+
publicQrSvg = await QRCode.toString(tryUrl, {
|
|
651
|
+
type: 'svg',
|
|
652
|
+
margin: 1,
|
|
653
|
+
width: 180,
|
|
654
|
+
color: { dark: '#1b2228', light: '#fffefb' }
|
|
655
|
+
});
|
|
656
|
+
cachedTryQrKey = tryUrl;
|
|
657
|
+
cachedTryQrSvg = publicQrSvg;
|
|
658
|
+
} catch {
|
|
659
|
+
publicQrSvg = '';
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
const todayGlobalUsed = s.publicLobbyUsage?.date === todayKey() ? (s.publicLobbyUsage.count || 0) : 0;
|
|
664
|
+
|
|
531
665
|
return {
|
|
532
666
|
revision: s.revision,
|
|
533
667
|
lifecycleStage: s.lifecycleStage,
|
|
@@ -535,8 +669,16 @@ export function createTwinStore(paths) {
|
|
|
535
669
|
onboardMode: s.onboardMode,
|
|
536
670
|
dutyMode: s.dutyMode,
|
|
537
671
|
presenceAutoYield: s.presenceAutoYield,
|
|
672
|
+
ackSlowTurns: s.ackSlowTurns !== false,
|
|
673
|
+
ownerNotify: s.ownerNotify || { feishu: true, wechat: false },
|
|
538
674
|
dailyTurnCap: s.dailyTurnCap,
|
|
539
675
|
twinProfile: s.twinProfile,
|
|
676
|
+
publicLobby: {
|
|
677
|
+
...publicCfg,
|
|
678
|
+
tryUrl,
|
|
679
|
+
qrSvg: publicQrSvg,
|
|
680
|
+
todayGlobalUsed
|
|
681
|
+
},
|
|
540
682
|
mountedProjects: sanitizedProjects,
|
|
541
683
|
capabilities: s.capabilities,
|
|
542
684
|
rules: s.rules,
|
|
@@ -570,6 +712,10 @@ export function createTwinStore(paths) {
|
|
|
570
712
|
writeCallerThread,
|
|
571
713
|
appendCallerTurn,
|
|
572
714
|
updateCallerMeta,
|
|
715
|
+
readVisitorThread,
|
|
716
|
+
appendVisitorTurn,
|
|
717
|
+
updateVisitorMeta,
|
|
718
|
+
incrementPublicLobbyUsage,
|
|
573
719
|
hasProcessedEvent,
|
|
574
720
|
recordProcessedEvent,
|
|
575
721
|
readProjectIndex,
|