@oxmumu3/dsh-agent-twin 0.6.1 → 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/lib/host.js CHANGED
@@ -123,8 +123,10 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
123
123
  guestServer = createGuestServer({
124
124
  host: overrides.guestHost || '127.0.0.1',
125
125
  port: overrides.guestPort ?? readConfigPort(config),
126
+ publicBurstLimit: overrides.publicBurstLimit,
126
127
  getState: () => store.getState(),
127
128
  readCallerThread: callerId => store.readCallerThread(callerId),
129
+ readVisitorThread: visitorId => store.readVisitorThread(visitorId),
128
130
  allSecretValues: () => store.allSecretValues(),
129
131
  onGuestAsk: async (person, question, opts = {}) => {
130
132
  return engine.handleInboundMessage({
@@ -135,6 +137,13 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
135
137
  onProgress: opts.onProgress
136
138
  });
137
139
  },
140
+ onPublicAsk: async (visitorId, question, opts = {}) => {
141
+ return engine.handlePublicVisitorMessage({
142
+ visitorId,
143
+ question,
144
+ onProgress: opts.onProgress
145
+ });
146
+ },
138
147
  logger
139
148
  });
140
149
  await guestServer.start();
@@ -214,6 +214,7 @@ export function createMtnKnowledgeProvider({ store, logger = console }) {
214
214
 
215
215
  const authorizedNodes = allNodes.filter(node => {
216
216
  if (node.projectId && !authorizedProjectIds.has(node.projectId)) return false;
217
+ if (!node.projectId && person?.isPublicVisitor) return false;
217
218
  if (!node.projectId && activeSet && activeSet.size === 0) return false;
218
219
  if (node.capIds.length > 0 && activeSet && !node.capIds.some(cid => activeSet.has(cid))) return false;
219
220
  return true;
package/lib/routes.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  sanitizeSurfaceText
18
18
  } from '../shared/schema.js';
19
19
  import { normalizeScopePaths, scanProjectDirectory } from './scanner.js';
20
+ import { applyPublicLobbyPatch } from './service.js';
20
21
 
21
22
  const MAX_BODY_BYTES = 65536;
22
23
  const CANDIDATE_SCAN_TTL_MS = 30_000;
@@ -742,6 +743,12 @@ export function registerTwinRoutes({
742
743
  result = { deleted: body.ruleId };
743
744
  break;
744
745
  }
746
+ case 'configure_public_lobby': {
747
+ result = {
748
+ publicLobby: await applyPublicLobbyPatch(store, body.publicLobby || body)
749
+ };
750
+ break;
751
+ }
745
752
  default:
746
753
  return jsonResponse({ ok: false, error: `未知操作:${action}` }, 400);
747
754
  }
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,
@@ -391,7 +391,8 @@ export async function materializeScopedWorkspace({
391
391
  scopeKey,
392
392
  mountedProjects = [],
393
393
  capabilities = [],
394
- allowedCapIds = null
394
+ allowedCapIds = null,
395
+ reuseIfUnchanged = false
395
396
  }) {
396
397
  const sandboxesRoot = resolve(String(rootDir || ''), 'sandboxes');
397
398
  const safeScope = slugifyCallerId(scopeKey || 'default');
@@ -400,9 +401,6 @@ export async function materializeScopedWorkspace({
400
401
  throw new Error('Invalid sandbox scope key');
401
402
  }
402
403
 
403
- await rm(sandboxDir, { recursive: true, force: true });
404
- await mkdir(sandboxDir, { recursive: true, mode: 0o700 });
405
-
406
404
  const allowedSet = Array.isArray(allowedCapIds) ? new Set(allowedCapIds) : null;
407
405
  const authorizedCaps = (capabilities || []).filter(c => c?.enabled && (!allowedSet || allowedSet.has(c.id)));
408
406
  const authorizedProjectIds = new Set(authorizedCaps.map(c => c.projectId));
@@ -411,6 +409,44 @@ export async function materializeScopedWorkspace({
411
409
  mp?.rootPath && (authorizedProjectIds.size === 0 ? false : authorizedProjectIds.has(mp.id))
412
410
  );
413
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
+
414
450
  const linkedProjects = [];
415
451
 
416
452
  for (const mp of selectedProjects) {
@@ -492,7 +528,13 @@ export async function materializeScopedWorkspace({
492
528
  linkedProjects.push({ id: mp.id, name: mp.projectName, linkedCount, dir: targetProjectDir, scopedPaths: unionPaths });
493
529
  }
494
530
 
495
- return { sandboxDir, linkedProjects };
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 };
496
538
  }
497
539
 
498
540
  /**
package/lib/service.js CHANGED
@@ -11,10 +11,26 @@ import {
11
11
  RULE_KINDS,
12
12
  channelIdFromSelection,
13
13
  channelSelectionLabel,
14
+ normalizePublicBaseUrl,
15
+ normalizePublicLobbyConfig,
14
16
  sanitizeSurfaceText
15
17
  } from '../shared/schema.js';
16
18
  import { normalizeScopePaths } from './scanner.js';
17
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
+ }
33
+
18
34
  export function createTwinService(runtime) {
19
35
  const {
20
36
  store,
@@ -232,8 +248,13 @@ export function createTwinService(runtime) {
232
248
  return { ok: true, capId, scopePaths: normalized };
233
249
  }
234
250
 
251
+ async function configurePublicLobby(patch = {}) {
252
+ await applyPublicLobbyPatch(store, patch);
253
+ return getStatus();
254
+ }
255
+
235
256
  return Object.freeze({
236
- version: '0.6.1',
257
+ version: '0.6.2',
237
258
  features: Object.freeze({
238
259
  fullBloodDshAgent: true,
239
260
  officialConnectors023: true,
@@ -243,7 +264,8 @@ export function createTwinService(runtime) {
243
264
  streamingProgress: true,
244
265
  scopePathIsolation: true,
245
266
  mtnSemanticGraph: true,
246
- mobileOwnerApproval: true
267
+ mobileOwnerApproval: true,
268
+ publicTryLobby: true
247
269
  }),
248
270
  getStatus,
249
271
  publishWorkspace,
@@ -251,6 +273,7 @@ export function createTwinService(runtime) {
251
273
  listInbox,
252
274
  resolveApproval,
253
275
  updateCapabilityScope,
276
+ configurePublicLobby,
254
277
  listMtnNodes: () => (mtnProvider ? mtnProvider.listNodes() : Promise.resolve([])),
255
278
  upsertMtnNodes: nodes => (mtnProvider ? mtnProvider.upsertNodes(nodes) : Promise.reject(new Error('MTN provider unavailable'))),
256
279
  submitInboundEvent: (channelId, event) => channelManager.handleExternalEvent(channelId, event),
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
@@ -149,6 +152,8 @@ export function createInitialState() {
149
152
  approvals: [],
150
153
  deliveries: [],
151
154
  processedEventIds: [],
155
+ publicLobby: createDefaultPublicLobby(),
156
+ publicLobbyUsage: { date: todayKey(), count: 0 },
152
157
  selfTestTurn: null,
153
158
  extractionJob: null
154
159
  };
@@ -162,6 +167,7 @@ export function createTwinStore(paths) {
162
167
  const statePath = join(paths.rootDir, 'state.json');
163
168
  const secretsPath = join(paths.rootDir, 'secrets.json');
164
169
  const callersRoot = join(paths.rootDir, 'twins', 'main', 'callers');
170
+ const visitorsRoot = join(paths.rootDir, 'twins', 'main', 'visitors');
165
171
  const projectsRoot = join(paths.rootDir, 'projects');
166
172
 
167
173
  let state = null;
@@ -170,6 +176,9 @@ export function createTwinStore(paths) {
170
176
  let capsUndoStack = [];
171
177
  let writeChain = Promise.resolve();
172
178
  let pairSeq = 10;
179
+ let lastVisitorPruneMs = 0;
180
+ let cachedTryQrKey = '';
181
+ let cachedTryQrSvg = '';
173
182
 
174
183
  function enqueue(fn) {
175
184
  const next = writeChain.then(fn, fn);
@@ -186,12 +195,24 @@ export function createTwinStore(paths) {
186
195
  return resolved;
187
196
  }
188
197
 
189
- async function readCallerThread(callerId) {
190
- const file = join(safeCallerDir(callerId), 'thread.json');
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');
191
212
  const data = await safeReadJson(file);
192
213
  if (data && typeof data === 'object') {
193
214
  return {
194
- callerId,
215
+ [idField]: idVal,
195
216
  dshSessionId: typeof data.dshSessionId === 'string' ? data.dshSessionId : '',
196
217
  lastPolicyDigest: typeof data.lastPolicyDigest === 'string' ? data.lastPolicyDigest : '',
197
218
  turns: Array.isArray(data.turns) ? data.turns : [],
@@ -200,7 +221,7 @@ export function createTwinStore(paths) {
200
221
  };
201
222
  }
202
223
  return {
203
- callerId,
224
+ [idField]: idVal,
204
225
  dshSessionId: '',
205
226
  lastPolicyDigest: '',
206
227
  turns: [],
@@ -209,17 +230,15 @@ export function createTwinStore(paths) {
209
230
  };
210
231
  }
211
232
 
212
- async function writeCallerThread(callerId, threadData) {
213
- const file = join(safeCallerDir(callerId), 'thread.json');
214
- return atomicWriteJson(file, threadData, 0o600);
215
- }
216
-
217
- async function appendCallerTurn(callerId, turn, opts = {}) {
233
+ async function appendScopedTurn(dir, idField, idVal, turn, opts = {}) {
218
234
  return enqueue(async () => {
219
- const thread = await readCallerThread(callerId);
235
+ const thread = await readScopedThread(dir, idField, idVal);
220
236
  const today = todayKey();
221
237
  const currentCount = thread.dailyTurns?.date === today ? (thread.dailyTurns.count || 0) : 0;
222
238
  thread.turns.push(turn);
239
+ if (opts.maxTurns && thread.turns.length > opts.maxTurns) {
240
+ thread.turns = thread.turns.slice(-opts.maxTurns);
241
+ }
223
242
  if (typeof opts.dshSessionId === 'string' && opts.dshSessionId) {
224
243
  thread.dshSessionId = opts.dshSessionId;
225
244
  }
@@ -229,21 +248,97 @@ export function createTwinStore(paths) {
229
248
  if (opts.countTurn !== false) {
230
249
  thread.dailyTurns = { date: today, count: currentCount + 1 };
231
250
  }
232
- await writeCallerThread(callerId, thread);
251
+ await atomicWriteJson(join(dir, 'thread.json'), thread, 0o600);
233
252
  return thread;
234
253
  });
235
254
  }
236
255
 
237
- async function updateCallerMeta(callerId, patch = {}) {
256
+ async function updateScopedMeta(dir, idField, idVal, patch = {}) {
238
257
  return enqueue(async () => {
239
- const thread = await readCallerThread(callerId);
258
+ const thread = await readScopedThread(dir, idField, idVal);
240
259
  if (typeof patch.dshSessionId === 'string') thread.dshSessionId = patch.dshSessionId;
241
260
  if (typeof patch.lastPolicyDigest === 'string') thread.lastPolicyDigest = patch.lastPolicyDigest;
242
- await writeCallerThread(callerId, thread);
261
+ await atomicWriteJson(join(dir, 'thread.json'), thread, 0o600);
243
262
  return thread;
244
263
  });
245
264
  }
246
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
+
247
342
  async function readProjectIndex(projectId) {
248
343
  const clean = slugifyCallerId(projectId);
249
344
  const file = join(projectsRoot, clean, 'index.json');
@@ -322,6 +417,7 @@ export function createTwinStore(paths) {
322
417
  async function init() {
323
418
  await ensureDir(paths.rootDir, 0o700);
324
419
  await ensureDir(callersRoot, 0o700);
420
+ await ensureDir(visitorsRoot, 0o700);
325
421
  await ensureDir(projectsRoot, 0o700);
326
422
 
327
423
  const existingSecrets = await safeReadJson(secretsPath);
@@ -347,6 +443,10 @@ export function createTwinStore(paths) {
347
443
  state.deliveries ||= [];
348
444
  state.processedEventIds ||= [];
349
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
+ }
350
450
 
351
451
  const beforeLen = state.mountedProjects.length;
352
452
  state.mountedProjects = state.mountedProjects.filter(mp =>
@@ -538,6 +638,30 @@ export function createTwinStore(paths) {
538
638
  deltaSpec: mp.deltaSpec || null
539
639
  }));
540
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
+
541
665
  return {
542
666
  revision: s.revision,
543
667
  lifecycleStage: s.lifecycleStage,
@@ -549,6 +673,12 @@ export function createTwinStore(paths) {
549
673
  ownerNotify: s.ownerNotify || { feishu: true, wechat: false },
550
674
  dailyTurnCap: s.dailyTurnCap,
551
675
  twinProfile: s.twinProfile,
676
+ publicLobby: {
677
+ ...publicCfg,
678
+ tryUrl,
679
+ qrSvg: publicQrSvg,
680
+ todayGlobalUsed
681
+ },
552
682
  mountedProjects: sanitizedProjects,
553
683
  capabilities: s.capabilities,
554
684
  rules: s.rules,
@@ -582,6 +712,10 @@ export function createTwinStore(paths) {
582
712
  writeCallerThread,
583
713
  appendCallerTurn,
584
714
  updateCallerMeta,
715
+ readVisitorThread,
716
+ appendVisitorTurn,
717
+ updateVisitorMeta,
718
+ incrementPublicLobbyUsage,
585
719
  hasProcessedEvent,
586
720
  recordProcessedEvent,
587
721
  readProjectIndex,