@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.
@@ -8,11 +8,14 @@
8
8
  import { randomUUID } from 'node:crypto';
9
9
  import {
10
10
  DEFAULT_DAILY_TURN_CAP,
11
+ DEFAULT_PUBLIC_GLOBAL_DAILY_LIMIT,
12
+ DEFAULT_PUBLIC_VISITOR_DAILY_LIMIT,
11
13
  PRESENCE_YIELD_MS,
12
14
  REDLINE_PATTERNS,
13
15
  TWIN_PERSONA_PRESETS,
14
16
  channelIdFromSelection,
15
17
  channelSelectionLabel,
18
+ normalizePublicLobbyConfig,
16
19
  redactSecrets,
17
20
  sanitizeSurfaceText
18
21
  } from '../shared/schema.js';
@@ -79,6 +82,11 @@ export function createTwinEngine({
79
82
  const pendingScans = new Map();
80
83
  const scopeQueues = new Map();
81
84
  const activeTurns = new Map();
85
+ const MAX_CONCURRENT_PUBLIC_TURNS = 3;
86
+ const MAX_PUBLIC_PENDING_APPROVALS = 10;
87
+ const PUBLIC_PUSH_COOLDOWN_MS = 10 * 60 * 1000;
88
+ let activePublicTurns = 0;
89
+ let lastPublicOwnerPushAt = 0;
82
90
  let extractTimer = null;
83
91
  let stepChain = Promise.resolve();
84
92
  let disposed = false;
@@ -89,13 +97,34 @@ export function createTwinEngine({
89
97
  shortCode: item.shortCode || makeApprovalShortCode(item.id)
90
98
  };
91
99
  await store.updateState(st => {
100
+ if (withCode.isPublicLobby) {
101
+ let keptPublic = 0;
102
+ st.approvals = st.approvals.filter(existing => {
103
+ if (!existing?.isPublicLobby) return true;
104
+ if (keptPublic < MAX_PUBLIC_PENDING_APPROVALS - 1) {
105
+ keptPublic += 1;
106
+ return true;
107
+ }
108
+ return false;
109
+ });
110
+ }
92
111
  st.approvals.unshift(withCode);
93
112
  if (setDeskOnCold && st.lifecycleStage === 'cold') st.scene = 'desk';
94
113
  });
114
+
95
115
  if (ownerNotifier && typeof ownerNotifier.notifyPendingApproval === 'function') {
96
- await ownerNotifier.notifyPendingApproval(withCode).catch(err =>
97
- logger?.warn?.('[agent-twin] ownerNotifier push warning:', err?.message)
98
- );
116
+ let allowPush = true;
117
+ if (withCode.isPublicLobby) {
118
+ const pubCfg = store.getState().publicLobby;
119
+ const now = Date.now();
120
+ allowPush = Boolean(pubCfg?.pushOwner) && (now - lastPublicOwnerPushAt >= PUBLIC_PUSH_COOLDOWN_MS);
121
+ if (allowPush) lastPublicOwnerPushAt = now;
122
+ }
123
+ if (allowPush) {
124
+ await ownerNotifier.notifyPendingApproval(withCode).catch(err =>
125
+ logger?.warn?.('[agent-twin] ownerNotifier push warning:', err?.message)
126
+ );
127
+ }
99
128
  }
100
129
  return withCode;
101
130
  }
@@ -547,344 +576,718 @@ export function createTwinEngine({
547
576
  return out;
548
577
  }
549
578
 
579
+ async function recordTurnDelivery({
580
+ person,
581
+ isPublicVisitor,
582
+ visitorId,
583
+ cleanQ,
584
+ replyText,
585
+ capLabel,
586
+ statusLabel,
587
+ statusTone = 'ok',
588
+ basisHint,
589
+ channelId,
590
+ trace,
591
+ approvalId = '',
592
+ shortCode = '',
593
+ dshSessionId = '',
594
+ policyDigest = '',
595
+ countTurn = true
596
+ }) {
597
+ const turn = {
598
+ id: `th-${randomUUID().slice(0, 8)}`,
599
+ time: nowTimeLabel(),
600
+ capLabel,
601
+ question: cleanQ,
602
+ reply: replyText,
603
+ statusLabel,
604
+ statusTone,
605
+ basisHint,
606
+ approvalId,
607
+ shortCode,
608
+ trace
609
+ };
610
+ if (isPublicVisitor && visitorId) {
611
+ await store.appendVisitorTurn(visitorId, turn, {
612
+ countTurn,
613
+ dshSessionId,
614
+ lastPolicyDigest: policyDigest
615
+ });
616
+ await store.incrementPublicLobbyUsage();
617
+ } else if (person) {
618
+ await store.appendCallerTurn(person.id, turn, {
619
+ countTurn,
620
+ dshSessionId,
621
+ lastPolicyDigest: policyDigest
622
+ });
623
+ }
624
+
625
+ await store.updateState(st => {
626
+ if (!isPublicVisitor && person) {
627
+ const target = st.people.find(p => p.id === person.id);
628
+ if (target) {
629
+ target.servedCount = (target.servedCount || 0) + 1;
630
+ target.lastActive = '刚刚';
631
+ }
632
+ }
633
+ st.deliveries.unshift({
634
+ id: `del-${randomUUID().slice(0, 8)}`,
635
+ personId: person?.id || '',
636
+ isPublicLobby: Boolean(isPublicVisitor),
637
+ time: nowTimeLabel(),
638
+ who: person?.name || '访客',
639
+ whoNote: person?.role || '公开扫码体验',
640
+ channel: channelSelectionLabel(channelId),
641
+ summary: replyText.slice(0, 52),
642
+ statusLabel,
643
+ statusTone,
644
+ trace
645
+ });
646
+ st.deliveries = st.deliveries.slice(0, 40);
647
+ });
648
+ return turn;
649
+ }
650
+
550
651
  /**
551
- * Core Scoped Twin Session runtime handler for BOTH external inbound requests
552
- * and owner self-test / caller preview sandboxes.
652
+ * Shared Scoped Twin execution kernel for private callers and fail-closed `/try` public visitors.
553
653
  */
554
- async function handleInboundMessage({
555
- personId,
556
- question,
654
+ function executeCoreTurn({
655
+ person = null,
656
+ twinProfile,
657
+ activeCaps,
658
+ cleanQ,
557
659
  channelId = 'ch-web',
558
- threadKey = '',
559
- isGroup = false,
560
- mentionsBot = true,
660
+ replyContext = {},
561
661
  isOwnerSelfTest = false,
562
662
  sandboxOnly = false,
563
- replyContext = {},
564
663
  forceDeterministic = false,
565
- onProgress = null
664
+ onProgress = null,
665
+ threadAdapter = null,
666
+ materializeScopeKey = 'selftest',
667
+ turnLockKey = 'selftest',
668
+ reuseSandbox = false,
669
+ isPublicVisitor = false,
670
+ visitorId = '',
671
+ dailyLimit = 0,
672
+ globalDailyLimit = 0
566
673
  }) {
567
- const s = store.getState();
568
- const secretVals = store.allSecretValues();
569
- const cleanQ = redactSecrets(sanitizeSurfaceText(String(question || '').trim()), secretVals);
570
- if (!cleanQ) throw new Error('提问内容不能为空');
674
+ return serializeScope(turnLockKey, async () => {
675
+ const s = store.getState();
676
+ const secretVals = store.allSecretValues();
677
+ const latestThread = threadAdapter && !sandboxOnly && !isOwnerSelfTest
678
+ ? await threadAdapter.readThread()
679
+ : null;
680
+ const currentTodayCount = latestThread?.dailyTurns?.date === todayKey()
681
+ ? (latestThread.dailyTurns.count || 0)
682
+ : 0;
683
+
684
+ if (dailyLimit > 0 && currentTodayCount >= dailyLimit) {
685
+ return isPublicVisitor
686
+ ? {
687
+ action: 'rate_limited',
688
+ limitReached: true,
689
+ remainingTurns: 0,
690
+ visitorDailyLimit: dailyLimit,
691
+ statusLabel: '你今日的体验次数已用完',
692
+ reply: `你今天在本公开大厅的 ${dailyLimit} 轮免费体验次数已用完(会话独立计数)。如果觉得效果不错,按下方「30 秒自建同款分身」提示在 DeepSeek Harness 中安装即可无限使用!`
693
+ }
694
+ : {
695
+ action: 'rate_limited',
696
+ statusLabel: '已达单日回复上限',
697
+ reply: '今天的分身自动化答疑已达到单日轮次上限,避免刷屏与过度消耗。如有紧急问题请直接联系项目负责人,本工具无任何付费升级限制。'
698
+ };
699
+ }
571
700
 
572
- if (!isOwnerSelfTest && s.dutyMode === 'off') {
573
- return {
574
- action: 'paused',
575
- statusLabel: '工作分身当前暂停对外值班',
576
- reply: '工作分身当前已暂停对外值班,暂时停止自动回复。工具内不设任何收费门槛,重要事项请直接联系项目负责人。'
577
- };
578
- }
701
+ if (isPublicVisitor && globalDailyLimit > 0) {
702
+ const globalToday = s.publicLobbyUsage?.date === todayKey() ? (s.publicLobbyUsage.count || 0) : 0;
703
+ if (globalToday >= globalDailyLimit) {
704
+ return {
705
+ action: 'rate_limited',
706
+ limitReached: true,
707
+ remainingTurns: 0,
708
+ visitorDailyLimit: dailyLimit,
709
+ statusLabel: '公开体验今日总接待已满',
710
+ reply: `本机公开大厅今日 ${globalDailyLimit} 轮免费接待总上限已满(防刷熔断),明日自动恢复;也可按底部教程 30 秒把自己的工作区部署为同款 AI 分身。`
711
+ };
712
+ }
713
+ }
579
714
 
580
- const person = personId ? s.people.find(p => p.id === personId) : null;
581
- let callerThread = null;
582
- if (person) {
583
- callerThread = await store.readCallerThread(person.id);
584
- }
715
+ const turnTrackId = randomUUID().slice(0, 8);
716
+ const visitorDailyLimit = dailyLimit || DEFAULT_PUBLIC_VISITOR_DAILY_LIMIT;
717
+ const remainingAfterTurn = isPublicVisitor
718
+ ? Math.max(0, visitorDailyLimit - (currentTodayCount + 1))
719
+ : undefined;
720
+
721
+ activeTurns.set(turnTrackId, {
722
+ id: turnTrackId,
723
+ callerId: person?.id || 'selftest',
724
+ personName: person?.name || '本机自测',
725
+ channelId,
726
+ question: cleanQ.slice(0, 64),
727
+ startedAt: Date.now(),
728
+ latestStep: null
729
+ });
585
730
 
586
- if (!isOwnerSelfTest && !sandboxOnly) {
587
- if (!person) {
588
- return { action: 'ignored', reason: 'unknown_caller' };
589
- }
590
- if (!person.enabled || isPersonExpired(person)) {
591
- return {
592
- action: 'paused',
593
- statusLabel: '当前访问权限已暂停',
594
- reply: `你好 ${person.name},当前的分身试用或服务权限已暂停。本工具不收取任何费用,如需恢复请直接联系负责人打开开关。`
595
- };
596
- }
597
- if (isGroup && !mentionsBot) {
598
- return { action: 'ignored', reason: 'group_not_mentioned' };
599
- }
600
- if (threadKey && isOwnerPresentRecently(channelId, threadKey)) {
601
- const yieldNotice = {
602
- id: `del-yield-${Date.now()}`,
603
- personId: person.id,
604
- time: nowTimeLabel(),
605
- who: person.name,
606
- whoNote: person.role,
607
- channel: channelSelectionLabel(channelId),
608
- summary: '检测到本人在原会话 15 分钟内发言,分身自动收声未抢答',
609
- statusLabel: '本人在场自动收声',
610
- statusTone: 'muted',
611
- trace: {
612
- intro: '15 分钟内检测到负责人在同一会话亲自回复过,触发本人在场收声保护。',
613
- steps: [{ title: '检测最近真人互动', detail: '保持现场沟通顺畅,不做重复插话。' }],
614
- techNote: '15 分钟计时窗口自动刷新。'
731
+ const emitProgress = step => {
732
+ if (!step) return;
733
+ const entry = activeTurns.get(turnTrackId);
734
+ if (entry) entry.latestStep = step;
735
+ if (typeof onProgress === 'function') {
736
+ try {
737
+ onProgress(step);
738
+ } catch {
739
+ // ignore streaming listener errors
615
740
  }
616
- };
617
- await store.updateState(st => {
618
- st.deliveries.unshift(yieldNotice);
619
- st.deliveries = st.deliveries.slice(0, 40);
741
+ }
742
+ };
743
+
744
+ try {
745
+ emitProgress({
746
+ phase: 'auth',
747
+ title: '核对身份与能力范围',
748
+ detail: person ? `${person.name} · 独立隔离会话` : '本机只读自测'
620
749
  });
621
- return { action: 'yielded', statusLabel: '本人在场自动收声', delivery: yieldNotice };
622
- }
623
750
 
624
- const capLimit = s.dailyTurnCap || DEFAULT_DAILY_TURN_CAP;
625
- const todayCount = callerThread?.dailyTurns?.date === todayKey() ? (callerThread.dailyTurns.count || 0) : 0;
626
- if (todayCount >= capLimit) {
627
- return {
628
- action: 'rate_limited',
629
- statusLabel: '已达单日回复上限',
630
- reply: '今天的分身自动化答疑已达到单日轮次上限,避免刷屏与过度消耗。如有紧急问题请直接联系项目负责人,本工具无任何付费升级限制。'
631
- };
632
- }
633
- }
751
+ const externalKnowledge = await queryExternalProviders(cleanQ, person, activeCaps);
752
+ if (externalKnowledge.length > 0) {
753
+ emitProgress({
754
+ phase: 'mtn',
755
+ title: '命中语义知识图谱',
756
+ detail: `${externalKnowledge.length} 条关联口径`
757
+ });
758
+ }
634
759
 
635
- const turnTrackId = randomUUID().slice(0, 8);
636
- activeTurns.set(turnTrackId, {
637
- id: turnTrackId,
638
- callerId: person?.id || 'selftest',
639
- personName: person?.name || '本机自测',
640
- channelId,
641
- question: cleanQ.slice(0, 64),
642
- startedAt: Date.now(),
643
- latestStep: null
644
- });
760
+ // Path A: Full-Blooded Native DSH Agent Session + Thin Harness
761
+ if (!forceDeterministic && fullBloodRunner?.isAvailable?.()) {
762
+ try {
763
+ const startedAt = Date.now();
764
+ const runMaterialize = () => materializeScopedWorkspace({
765
+ rootDir: store.paths.rootDir,
766
+ scopeKey: materializeScopeKey,
767
+ mountedProjects: s.mountedProjects,
768
+ capabilities: s.capabilities,
769
+ allowedCapIds: activeCaps,
770
+ reuseIfUnchanged: reuseSandbox
771
+ });
772
+ const mat = reuseSandbox
773
+ ? await serializeScope(`materialize-${materializeScopeKey}`, runMaterialize)
774
+ : await runMaterialize();
775
+
776
+ const digest = computePolicyDigest({
777
+ twinProfile,
778
+ rules: s.rules,
779
+ mode: person?.mode || 'direct',
780
+ note: person?.note || '',
781
+ activeCaps
782
+ });
783
+ const canReuseSession = Boolean(threadAdapter && !sandboxOnly && !isOwnerSelfTest && latestThread?.dshSessionId);
784
+ const includeFullPolicy = !canReuseSession || latestThread?.lastPolicyDigest !== digest;
785
+
786
+ const aiRes = await fullBloodRunner.runCallerTurn({
787
+ callerId: person?.id || 'selftest',
788
+ sessionId: canReuseSession ? latestThread.dshSessionId : '',
789
+ sandboxCwd: mat.sandboxDir,
790
+ twinProfile,
791
+ rules: s.rules,
792
+ person,
793
+ question: cleanQ,
794
+ externalKnowledge: externalKnowledge.map(k => k.snippet),
795
+ includeFullPolicy,
796
+ onProgress: emitProgress
797
+ });
645
798
 
646
- const emitProgress = step => {
647
- if (!step) return;
648
- const entry = activeTurns.get(turnTrackId);
649
- if (entry) entry.latestStep = step;
650
- if (typeof onProgress === 'function') {
651
- try {
652
- onProgress(step);
653
- } catch {
654
- // ignore streaming listener errors
655
- }
656
- }
657
- };
799
+ if (threadAdapter && (canReuseSession || (!sandboxOnly && !isOwnerSelfTest && aiRes.sessionId))) {
800
+ await threadAdapter.updateMeta({
801
+ dshSessionId: aiRes.sessionId || latestThread?.dshSessionId || '',
802
+ lastPolicyDigest: digest
803
+ });
804
+ }
658
805
 
659
- try {
660
- emitProgress({
661
- phase: 'auth',
662
- title: '核对身份与能力范围',
663
- detail: person ? `${person.name} · 独立隔离会话` : '本机只读自测'
664
- });
806
+ const linkedProjects = mat.linkedProjects;
807
+ const policyDigest = digest;
808
+
809
+ const durationSec = `${Math.max(0.2, (Date.now() - startedAt) / 1000).toFixed(1)} 秒`;
810
+ const cleanReply = redactSecrets(sanitizeSurfaceText(aiRes.reply), secretVals);
811
+ const steps = Array.isArray(aiRes.traceSteps) && aiRes.traceSteps.length > 0
812
+ ? aiRes.traceSteps
813
+ : [{ title: '只读核对授权沙箱', detail: linkedProjects.map(p => `${p.name}(${p.linkedCount}份)`).join('、') || '授权口径范围' }];
814
+
815
+ if (aiRes.decision === 'REDLINE') {
816
+ if (sandboxOnly) {
817
+ return {
818
+ action: 'redline_intercepted',
819
+ statusLabel: '待拍板 + 敏感拦截',
820
+ reply: cleanReply,
821
+ reason: aiRes.reason || '命中红线拦截'
822
+ };
823
+ }
824
+ const appItem = {
825
+ id: `app-red-${randomUUID().slice(0, 8)}`,
826
+ personId: person?.id || 'p-self',
827
+ personName: person?.name || '自测预演',
828
+ isPublicLobby: Boolean(isPublicVisitor),
829
+ visitorId: isPublicVisitor ? visitorId : '',
830
+ channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
831
+ tone: 'danger',
832
+ tag: '待拍板 + 敏感拦截',
833
+ headline: `${person?.name || '访客'} 触发红线拦截:${aiRes.reason || '涉敏或越界请求'}`,
834
+ gist: '满血分身核对规则后已自动拦截越权内容,并拟好安全替代回复等你确认。',
835
+ question: cleanQ,
836
+ draft: cleanReply,
837
+ primaryActionLabel: '批准发出安全回复',
838
+ allowRuleExtract: false,
839
+ basisHint: `规则与红线拦截(${aiRes.reason || '安全边界'})`,
840
+ replyContext,
841
+ trace: {
842
+ intro: `${person?.name || '访客'} 的消息经隔离分身语义审查命中工作台红线。`,
843
+ steps,
844
+ techNote: '隔离只读沙箱 + 模型外双层校验:敏感目录已物理剔除,拦截未外发。'
845
+ }
846
+ };
847
+ const savedRedline = await enqueueApproval(appItem, { setDeskOnCold: true });
848
+ const safeFallbackReply = isPublicVisitor
849
+ ? `这个问题涉及敏感边界或未公开事项,已实时拦截并生成待拍板卡片 #${savedRedline.shortCode}。你可以在下方体验常规问题,或点击底部用 30 秒把自己的工作区部署成同款分身。`
850
+ : '这个问题涉及敏感边界或需本人拍板事项,已转呈负责人确认,稍后答复你。';
851
+
852
+ if (isPublicVisitor) {
853
+ await recordTurnDelivery({
854
+ person,
855
+ isPublicVisitor: true,
856
+ visitorId,
857
+ cleanQ,
858
+ replyText: safeFallbackReply,
859
+ capLabel: '敏感红线拦截',
860
+ statusLabel: `已拦下 · #${savedRedline.shortCode}`,
861
+ statusTone: 'warn',
862
+ basisHint: appItem.basisHint,
863
+ channelId,
864
+ trace: appItem.trace,
865
+ approvalId: savedRedline.id,
866
+ shortCode: savedRedline.shortCode,
867
+ dshSessionId: aiRes.sessionId || '',
868
+ policyDigest
869
+ });
870
+ }
665
871
 
666
- const activeCaps = person ? person.caps : s.capabilities.filter(c => c.enabled).map(c => c.id);
667
- const externalKnowledge = await queryExternalProviders(cleanQ, person, activeCaps);
668
- if (externalKnowledge.length > 0) {
669
- emitProgress({
670
- phase: 'mtn',
671
- title: '命中语义知识图谱',
672
- detail: `${externalKnowledge.length} 条关联口径`
673
- });
674
- }
872
+ return {
873
+ action: 'pending_approval',
874
+ isPublicLobby: Boolean(isPublicVisitor),
875
+ approvalId: savedRedline.id,
876
+ shortCode: savedRedline.shortCode,
877
+ statusLabel: isPublicVisitor ? `已拦下 · 待拍板 #${savedRedline.shortCode}` : '已拦下并待本人拍板',
878
+ draft: cleanReply,
879
+ safeFallbackReply,
880
+ ...(isPublicVisitor ? { reply: safeFallbackReply, remainingTurns: remainingAfterTurn, visitorDailyLimit } : {})
881
+ };
882
+ }
675
883
 
676
- // Path A: Full-Blooded Native DSH Agent Session + Thin Harness (Mexico-style)
677
- if (!forceDeterministic && fullBloodRunner?.isAvailable?.()) {
678
- const scopeKey = person && !isOwnerSelfTest ? `caller-${person.id}` : 'selftest';
679
- try {
680
- const startedAt = Date.now();
681
- const { linkedProjects, policyDigest, aiRes } = await serializeScope(scopeKey, async () => {
682
- const latestThread = person && !sandboxOnly && !isOwnerSelfTest
683
- ? await store.readCallerThread(person.id)
684
- : callerThread;
685
- const mat = await materializeScopedWorkspace({
686
- rootDir: store.paths.rootDir,
687
- scopeKey,
688
- mountedProjects: s.mountedProjects,
689
- capabilities: s.capabilities,
690
- allowedCapIds: activeCaps
691
- });
884
+ if (aiRes.decision === 'GAP') {
885
+ if (sandboxOnly) {
886
+ return {
887
+ action: 'knowledge_gap',
888
+ statusLabel: '触发待补口径(沙箱预览)',
889
+ reply: cleanReply
890
+ };
891
+ }
892
+ if (isOwnerSelfTest) {
893
+ const selfRes = {
894
+ question: cleanQ,
895
+ answer: cleanReply,
896
+ basis: '隔离工作区实查(未命中明确口径 · 已标待补)',
897
+ duration: durationSec
898
+ };
899
+ await store.updateState(st => { st.selfTestTurn = selfRes; });
900
+ return { action: 'replied', ...selfRes, reply: selfRes.answer };
901
+ }
902
+ const gapItem = {
903
+ id: `app-gap-${randomUUID().slice(0, 8)}`,
904
+ personId: person.id,
905
+ personName: person.name,
906
+ isPublicLobby: Boolean(isPublicVisitor),
907
+ visitorId: isPublicVisitor ? visitorId : '',
908
+ channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
909
+ tone: 'amber',
910
+ tag: '待补口径',
911
+ headline: `${person.name} 问到授权资料外问题,待你补充口径`,
912
+ gist: cleanReply.slice(0, 64),
913
+ question: cleanQ,
914
+ draft: cleanReply,
915
+ primaryActionLabel: '补好并回复对方',
916
+ allowRuleExtract: true,
917
+ basisHint: aiRes.reason || '授权资料核查未覆盖',
918
+ replyContext,
919
+ trace: {
920
+ intro: `${person.name} 的问题超出当前已授权项目文档覆盖范围。`,
921
+ steps,
922
+ techNote: '宁可转交负责人补充口径,绝不编造数字或越权读取未授权目录。'
923
+ }
924
+ };
925
+ const savedGap = await enqueueApproval(gapItem);
926
+ const gapHoldingReply = isPublicVisitor
927
+ ? `这个问题暂未收录在当前公开体验工作区的授权资料中(已记入待补口径 #${savedGap.shortCode}),严禁编造答案。`
928
+ : '这个问题暂未在我当前掌握的公开口径文档中明确定义,我已转请负责人核实补充,确认后会第一时间给你答复。';
929
+ if (isPublicVisitor) {
930
+ await recordTurnDelivery({
931
+ person,
932
+ isPublicVisitor: true,
933
+ visitorId,
934
+ cleanQ,
935
+ replyText: gapHoldingReply,
936
+ capLabel: '待补口径边界',
937
+ statusLabel: `待补口径 · #${savedGap.shortCode}`,
938
+ statusTone: 'warn',
939
+ basisHint: gapItem.basisHint,
940
+ channelId,
941
+ trace: gapItem.trace,
942
+ approvalId: savedGap.id,
943
+ shortCode: savedGap.shortCode,
944
+ dshSessionId: aiRes.sessionId || '',
945
+ policyDigest
946
+ });
947
+ }
948
+ return {
949
+ action: 'knowledge_gap',
950
+ isPublicLobby: Boolean(isPublicVisitor),
951
+ approvalId: savedGap.id,
952
+ shortCode: savedGap.shortCode,
953
+ statusLabel: isPublicVisitor ? `待补口径 · #${savedGap.shortCode}` : '待补口径已转服务台',
954
+ reply: gapHoldingReply,
955
+ ...(isPublicVisitor ? { remainingTurns: remainingAfterTurn, visitorDailyLimit } : {})
956
+ };
957
+ }
692
958
 
693
- const digest = computePolicyDigest({
694
- twinProfile: s.twinProfile,
695
- rules: s.rules,
696
- mode: person?.mode || 'direct',
697
- note: person?.note || '',
698
- activeCaps
699
- });
700
- const canReuseSession = Boolean(person && !sandboxOnly && !isOwnerSelfTest && latestThread?.dshSessionId);
701
- const includeFullPolicy = !canReuseSession || latestThread?.lastPolicyDigest !== digest;
702
-
703
- const turnRes = await fullBloodRunner.runCallerTurn({
704
- callerId: person?.id || 'selftest',
705
- sessionId: canReuseSession ? latestThread.dshSessionId : '',
706
- sandboxCwd: mat.sandboxDir,
707
- twinProfile: s.twinProfile,
708
- rules: s.rules,
709
- person,
710
- question: cleanQ,
711
- externalKnowledge: externalKnowledge.map(k => k.snippet),
712
- includeFullPolicy,
713
- onProgress: emitProgress
714
- });
959
+ if (sandboxOnly) {
960
+ return {
961
+ action: 'replied',
962
+ statusLabel: '满血沙箱试答(未写入外部记录)',
963
+ reply: cleanReply,
964
+ basis: linkedProjects.map(p => p.name).join('、') || '授权只读工作区'
965
+ };
966
+ }
715
967
 
716
- if (canReuseSession || (person && !sandboxOnly && !isOwnerSelfTest && turnRes.sessionId)) {
717
- await store.updateCallerMeta(person.id, {
718
- dshSessionId: turnRes.sessionId || latestThread?.dshSessionId || '',
719
- lastPolicyDigest: digest
968
+ if (isOwnerSelfTest) {
969
+ const selfRes = {
970
+ question: cleanQ,
971
+ answer: cleanReply,
972
+ basis: `${linkedProjects.map(p => p.name).join('、') || '授权工作区'}(满血只读实查 · ${steps.length} 步)`,
973
+ duration: durationSec
974
+ };
975
+ await store.updateState(st => { st.selfTestTurn = selfRes; });
976
+ return { action: 'replied', ...selfRes, reply: cleanReply };
977
+ }
978
+
979
+ const trace = {
980
+ intro: `收到 ${person.name} 通过「${channelSelectionLabel(channelId)}」的提问,已在独立只读工作区完成满血核查。`,
981
+ steps,
982
+ techNote: isPublicVisitor
983
+ ? '公开体验会话按匿名 Cookie 隔离,与私有项目工作区物理分离。'
984
+ : '单人会话物理隔离与独立 DSH 会话上下文,不含他人历史或密钥文件。'
985
+ };
986
+
987
+ const shouldAutoReply = isPublicVisitor
988
+ ? true
989
+ : (s.dutyMode === 'live' && (person.mode === 'direct' || person.mode === 'summary'));
990
+ if (shouldAutoReply) {
991
+ const statusLabel = isPublicVisitor ? '满血只读解答完成' : '通道回执已送达';
992
+ const turn = await recordTurnDelivery({
993
+ person,
994
+ isPublicVisitor,
995
+ visitorId,
996
+ cleanQ,
997
+ replyText: cleanReply,
998
+ capLabel: linkedProjects[0]?.name || '只读核查',
999
+ statusLabel,
1000
+ statusTone: 'ok',
1001
+ basisHint: `已实查「${linkedProjects.map(p => p.name).join('、') || '授权工作区'}」`,
1002
+ channelId,
1003
+ trace,
1004
+ dshSessionId: aiRes.sessionId || latestThread?.dshSessionId || '',
1005
+ policyDigest
720
1006
  });
1007
+ return {
1008
+ action: 'replied',
1009
+ reply: cleanReply,
1010
+ statusLabel,
1011
+ turn,
1012
+ ...(isPublicVisitor ? { remainingTurns: remainingAfterTurn, visitorDailyLimit } : {})
1013
+ };
721
1014
  }
722
1015
 
723
- return { linkedProjects: mat.linkedProjects, policyDigest: digest, aiRes: turnRes };
724
- });
1016
+ const draftApproval = {
1017
+ id: `app-${randomUUID().slice(0, 8)}`,
1018
+ personId: person.id,
1019
+ personName: person.name,
1020
+ channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
1021
+ tone: 'amber',
1022
+ tag: '待过目草稿',
1023
+ headline: `${person.name} 提问:${cleanQ.slice(0, 26)}`,
1024
+ gist: cleanReply.slice(0, 56),
1025
+ question: cleanQ,
1026
+ draft: cleanReply,
1027
+ primaryActionLabel: '批准发出',
1028
+ allowRuleExtract: true,
1029
+ basisHint: `已实查「${linkedProjects.map(p => p.name).join('、') || '授权工作区'}」`,
1030
+ replyContext,
1031
+ trace
1032
+ };
1033
+ const savedDraft = await enqueueApproval(draftApproval);
1034
+ return {
1035
+ action: 'pending_approval',
1036
+ approvalId: savedDraft.id,
1037
+ shortCode: savedDraft.shortCode,
1038
+ statusLabel: '草稿待本人拍板',
1039
+ draft: cleanReply
1040
+ };
1041
+ } catch (err) {
1042
+ logger?.warn?.('[agent-twin] full-blood turn error, falling back to deterministic engine:', err?.message);
1043
+ }
1044
+ }
725
1045
 
726
- const durationSec = `${Math.max(0.2, (Date.now() - startedAt) / 1000).toFixed(1)} 秒`;
1046
+ // Path B: Deterministic Offline Fallback
1047
+ const violation = detectRedlineViolation(cleanQ, person);
727
1048
 
728
- const cleanReply = redactSecrets(sanitizeSurfaceText(aiRes.reply), secretVals);
729
- const steps = Array.isArray(aiRes.traceSteps) && aiRes.traceSteps.length > 0
730
- ? aiRes.traceSteps
731
- : [{ title: '只读核对授权沙箱', detail: linkedProjects.map(p => `${p.name}(${p.linkedCount}份)`).join('、') || '授权口径范围' }];
1049
+ if (violation) {
1050
+ const draft = violation.kind === 'write'
1051
+ ? '按只读安全红线,分身无权修改代码、写入数据库或执行变更脚本;我已将你的诉求转交给负责人本人评估处理。'
1052
+ : violation.kind === 'commitment'
1053
+ ? '具体排期、商务报价或未公开策略需要由负责人本人核定;已将你的诉求转入待办,确认后第一时间回复你。'
1054
+ : '按只读隐私红线,不能提供逐笔客户手机号或原始流水明细;如需分析波动结构,我可以先为你整理脱敏汇总占比趋势。';
732
1055
 
733
- if (aiRes.decision === 'REDLINE') {
734
1056
  if (sandboxOnly) {
735
1057
  return {
736
1058
  action: 'redline_intercepted',
737
- statusLabel: '待拍板 + 敏感拦截',
738
- reply: cleanReply,
739
- reason: aiRes.reason || '命中红线拦截'
1059
+ statusLabel: violation.label,
1060
+ reply: draft,
1061
+ reason: violation.reason
740
1062
  };
741
1063
  }
1064
+
742
1065
  const appItem = {
743
1066
  id: `app-red-${randomUUID().slice(0, 8)}`,
744
1067
  personId: person?.id || 'p-self',
745
1068
  personName: person?.name || '自测预演',
1069
+ isPublicLobby: Boolean(isPublicVisitor),
1070
+ visitorId: isPublicVisitor ? visitorId : '',
746
1071
  channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
747
1072
  tone: 'danger',
748
- tag: '待拍板 + 敏感拦截',
749
- headline: `${person?.name || '访客'} 触发红线拦截:${aiRes.reason || '涉敏或越界请求'}`,
750
- gist: '满血分身核对规则后已自动拦截越权内容,并拟好安全替代回复等你确认。',
1073
+ tag: violation.label,
1074
+ headline: `${person?.name || '访客'} 触发红线拦截:${violation.reason}`,
1075
+ gist: '已自动挡回越权明细或变更操作,并准备好安全替代回复等你确认。',
751
1076
  question: cleanQ,
752
- draft: cleanReply,
1077
+ draft,
753
1078
  primaryActionLabel: '批准发出安全回复',
754
1079
  allowRuleExtract: false,
755
- basisHint: `规则与红线拦截(${aiRes.reason || '安全边界'})`,
1080
+ basisHint: `红线规则触发(${violation.reason})`,
756
1081
  replyContext,
757
1082
  trace: {
758
- intro: `${person?.name || '访客'} 的消息经隔离分身语义审查命中工作台红线。`,
759
- steps,
760
- techNote: '隔离只读沙箱 + 模型外双层校验:敏感目录已物理剔除,拦截未外发。'
1083
+ intro: `${person?.name || '访客'} 的消息触发了工作台安全红线。`,
1084
+ steps: [
1085
+ { title: '边界校验命中红线', detail: violation.reason },
1086
+ { title: '生成脱敏替代答复', detail: '阻断原始字段或写操作,待本人审核发出。' }
1087
+ ],
1088
+ techNote: '红线规则先于任何资料检索执行,零越权泄露风险。'
761
1089
  }
762
1090
  };
763
- const savedRedline = await enqueueApproval(appItem, { setDeskOnCold: true });
1091
+
1092
+ const savedViolation = await enqueueApproval(appItem, { setDeskOnCold: true });
1093
+ const safeFallbackReply = isPublicVisitor
1094
+ ? `这个问题涉及敏感边界或未公开事项,已实时拦截并生成待拍板卡片 #${savedViolation.shortCode}。你可以在下方体验常规问题,或点击底部用 30 秒把自己的工作区部署成同款分身。`
1095
+ : '这个问题涉及敏感边界或需本人拍板事项,已转呈负责人确认,稍后答复你。';
1096
+
1097
+ if (isPublicVisitor) {
1098
+ await recordTurnDelivery({
1099
+ person,
1100
+ isPublicVisitor: true,
1101
+ visitorId,
1102
+ cleanQ,
1103
+ replyText: safeFallbackReply,
1104
+ capLabel: violation.label,
1105
+ statusLabel: `已拦下 · #${savedViolation.shortCode}`,
1106
+ statusTone: 'warn',
1107
+ basisHint: appItem.basisHint,
1108
+ channelId,
1109
+ trace: appItem.trace,
1110
+ approvalId: savedViolation.id,
1111
+ shortCode: savedViolation.shortCode
1112
+ });
1113
+ }
1114
+
764
1115
  return {
765
1116
  action: 'pending_approval',
766
- approvalId: savedRedline.id,
767
- shortCode: savedRedline.shortCode,
768
- statusLabel: '已拦下并待本人拍板',
769
- draft: cleanReply,
770
- safeFallbackReply: '这个问题涉及敏感边界或需本人拍板事项,已转呈负责人确认,稍后答复你。'
1117
+ isPublicLobby: Boolean(isPublicVisitor),
1118
+ approvalId: savedViolation.id,
1119
+ shortCode: savedViolation.shortCode,
1120
+ statusLabel: isPublicVisitor ? `已拦下 · 待拍板 #${savedViolation.shortCode}` : '已拦下并待本人拍板',
1121
+ draft,
1122
+ safeFallbackReply,
1123
+ ...(isPublicVisitor ? { reply: safeFallbackReply, remainingTurns: remainingAfterTurn, visitorDailyLimit } : {})
771
1124
  };
772
1125
  }
773
1126
 
774
- if (aiRes.decision === 'GAP') {
1127
+ const localMatches = await gatherAuthorizedSnippets(activeCaps, cleanQ);
1128
+ const matches = [...externalKnowledge, ...localMatches].sort((a, b) => b.score - a.score);
1129
+ const hasCustomKnowledge = matches.length > 0 && matches[0].score >= 2;
1130
+ const isExplicitGapPrompt = /(未公开|内部底价|定价策略|内幕|保密|还没写)/.test(cleanQ);
1131
+
1132
+ if (!hasCustomKnowledge || isExplicitGapPrompt) {
1133
+ const gapDraft = '感谢提问,这块暂未写入当前已授权的项目口径文档,我已向负责人提交待补口径说明,确认准确边界后会补充回复你。';
775
1134
  if (sandboxOnly) {
776
1135
  return {
777
1136
  action: 'knowledge_gap',
778
1137
  statusLabel: '触发待补口径(沙箱预览)',
779
- reply: cleanReply
1138
+ reply: '这个问题涉及尚未写入授权资料库的口径细节,我先记下并转负责人「待补口径」补充,确认后第一时间答复你。'
780
1139
  };
781
1140
  }
1141
+
782
1142
  if (isOwnerSelfTest) {
783
1143
  const selfRes = {
784
1144
  question: cleanQ,
785
- answer: cleanReply,
786
- basis: `隔离工作区实查(未命中明确口径 · 已标待补)`,
787
- duration: durationSec
1145
+ answer: '在当前授权的只读项目文档中未命中足够支撑(触发「待补口径」保护,未瞎编回答);若来自真实访客,会自动向你服务台发起口径补充卡片。',
1146
+ basis: '本地授权范围核查(未超出授权文件夹)',
1147
+ duration: '0.2 秒'
788
1148
  };
789
1149
  await store.updateState(st => { st.selfTestTurn = selfRes; });
790
1150
  return { action: 'replied', ...selfRes, reply: selfRes.answer };
791
1151
  }
1152
+
792
1153
  const gapItem = {
793
1154
  id: `app-gap-${randomUUID().slice(0, 8)}`,
794
1155
  personId: person.id,
795
1156
  personName: person.name,
1157
+ isPublicLobby: Boolean(isPublicVisitor),
1158
+ visitorId: isPublicVisitor ? visitorId : '',
796
1159
  channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
797
1160
  tone: 'amber',
798
1161
  tag: '待补口径',
799
1162
  headline: `${person.name} 问到授权资料外问题,待你补充口径`,
800
- gist: cleanReply.slice(0, 64),
1163
+ gist: '已先礼貌告知正在核实(严禁胡编),等你填补结论后可顺手记成长期规矩。',
801
1164
  question: cleanQ,
802
- draft: cleanReply,
1165
+ draft: gapDraft,
803
1166
  primaryActionLabel: '补好并回复对方',
804
1167
  allowRuleExtract: true,
805
- basisHint: aiRes.reason || '授权资料核查未覆盖',
1168
+ basisHint: '知识缺口拦截 · 未发现公开授权依据',
806
1169
  replyContext,
807
1170
  trace: {
808
- intro: `${person.name} 的问题超出当前已授权项目文档覆盖范围。`,
809
- steps,
810
- techNote: '宁可转交负责人补充口径,绝不编造数字或越权读取未授权目录。'
1171
+ intro: `${person.name} 的问题超出当前已提取能力文档覆盖范围。`,
1172
+ steps: [
1173
+ { title: '在授权文档索引中检索', detail: '未找到满足置信度的授权片段。' },
1174
+ { title: '拒绝幻觉编造并升级待补口径', detail: '保留人工补充口供,确认后可一键沉淀为长期规矩。' }
1175
+ ],
1176
+ techNote: '知识边界守卫拦截:宁可标待补口径,绝不编造数字或越权读取未授权目录。'
811
1177
  }
812
1178
  };
813
- const savedGap = await enqueueApproval(gapItem);
1179
+
1180
+ const savedGapB = await enqueueApproval(gapItem);
1181
+ const politeHoldingReply = isPublicVisitor
1182
+ ? `这个问题暂未收录在当前公开体验工作区的授权资料中(已记入待补口径 #${savedGapB.shortCode}),严禁编造答案。`
1183
+ : '这个问题暂未在我当前掌握的公开口径文档中明确定义,我已转请负责人核实补充,确认后会第一时间给你答复。';
1184
+
1185
+ if (isPublicVisitor) {
1186
+ await recordTurnDelivery({
1187
+ person,
1188
+ isPublicVisitor: true,
1189
+ visitorId,
1190
+ cleanQ,
1191
+ replyText: politeHoldingReply,
1192
+ capLabel: '待补口径边界',
1193
+ statusLabel: `待补口径 · #${savedGapB.shortCode}`,
1194
+ statusTone: 'warn',
1195
+ basisHint: gapItem.basisHint,
1196
+ channelId,
1197
+ trace: gapItem.trace,
1198
+ approvalId: savedGapB.id,
1199
+ shortCode: savedGapB.shortCode
1200
+ });
1201
+ }
1202
+
814
1203
  return {
815
1204
  action: 'knowledge_gap',
816
- approvalId: savedGap.id,
817
- shortCode: savedGap.shortCode,
818
- statusLabel: '待补口径已转服务台',
819
- reply: '这个问题暂未在我当前掌握的公开口径文档中明确定义,我已转请负责人核实补充,确认后会第一时间给你答复。'
1205
+ isPublicLobby: Boolean(isPublicVisitor),
1206
+ approvalId: savedGapB.id,
1207
+ shortCode: savedGapB.shortCode,
1208
+ statusLabel: isPublicVisitor ? `待补口径 · #${savedGapB.shortCode}` : '待补口径已转服务台',
1209
+ reply: politeHoldingReply,
1210
+ ...(isPublicVisitor ? { remainingTurns: remainingAfterTurn, visitorDailyLimit } : {})
820
1211
  };
821
1212
  }
822
1213
 
1214
+ emitProgress({
1215
+ phase: 'doc',
1216
+ title: '核对授权文档口径',
1217
+ detail: `${matches[0].projectName} · ${matches[0].snippet.title}`
1218
+ });
1219
+
1220
+ const top = matches[0];
1221
+ let generatedReply = `根据「${top.projectName} · ${top.snippet.title}」的只读口径说明:${top.snippet.summary}`;
1222
+ if (typeof llmResponder === 'function') {
1223
+ try {
1224
+ const custom = await llmResponder({ question: cleanQ, matches: matches.slice(0, 3), rules: s.rules, person });
1225
+ if (typeof custom === 'string' && custom.trim()) {
1226
+ generatedReply = redactSecrets(sanitizeSurfaceText(custom.trim()), secretVals);
1227
+ }
1228
+ } catch (err) {
1229
+ logger?.warn?.('[agent-twin] llmResponder fallback used:', err?.message);
1230
+ }
1231
+ }
1232
+
1233
+ if (person?.note) {
1234
+ generatedReply += `(注:按「${sanitizeSurfaceText(person.note)}」约定整理)`;
1235
+ }
1236
+
823
1237
  if (sandboxOnly) {
824
1238
  return {
825
1239
  action: 'replied',
826
- statusLabel: '满血沙箱试答(未写入外部记录)',
827
- reply: cleanReply,
828
- basis: linkedProjects.map(p => p.name).join('、') || '授权只读工作区'
1240
+ statusLabel: '沙箱试答(未写入外部记录)',
1241
+ reply: generatedReply,
1242
+ basis: `${top.projectName} · ${top.snippet.title}`
829
1243
  };
830
1244
  }
831
1245
 
832
1246
  if (isOwnerSelfTest) {
833
1247
  const selfRes = {
834
1248
  question: cleanQ,
835
- answer: cleanReply,
836
- basis: `${linkedProjects.map(p => p.name).join('、') || '授权工作区'}(满血只读实查 · ${steps.length} 步)`,
837
- duration: durationSec
1249
+ answer: generatedReply,
1250
+ basis: `${top.projectName} · ${top.snippet.title}(仅本地自测)`,
1251
+ duration: '0.4 秒'
838
1252
  };
839
1253
  await store.updateState(st => { st.selfTestTurn = selfRes; });
840
- return { action: 'replied', ...selfRes, reply: cleanReply };
1254
+ return { action: 'replied', ...selfRes, reply: generatedReply };
841
1255
  }
842
1256
 
843
1257
  const trace = {
844
- intro: `收到 ${person.name} 通过「${channelSelectionLabel(channelId)}」的提问,已在独立只读工作区完成满血核查。`,
845
- steps,
846
- techNote: '单人会话物理隔离与独立 DSH 会话上下文,不含他人历史或密钥文件。'
1258
+ intro: `收到 ${person.name} 通过「${channelSelectionLabel(channelId)}」的提问,已在独立沙箱内完成只读核对。`,
1259
+ steps: [
1260
+ { title: '核对白名单与能力范围', detail: `仅检索 ${person.name} 已获授权的 ${matches.length} 处片段。` },
1261
+ { title: '依据授权文档生成结论', detail: `引用「${top.projectName} · ${top.snippet.title}」,过滤私密字段。` }
1262
+ ],
1263
+ techNote: '单人会话物理隔离存档,不含其他访客历史或敏感文件路径。'
847
1264
  };
848
1265
 
849
- const shouldAutoReply = s.dutyMode === 'live' && (person.mode === 'direct' || person.mode === 'summary');
1266
+ const shouldAutoReply = isPublicVisitor
1267
+ ? true
1268
+ : (s.dutyMode === 'live' && (person.mode === 'direct' || person.mode === 'summary'));
850
1269
  if (shouldAutoReply) {
851
- const turn = {
852
- id: `th-${randomUUID().slice(0, 8)}`,
853
- time: nowTimeLabel(),
854
- capLabel: linkedProjects[0]?.name || '只读核查',
855
- question: cleanQ,
856
- reply: cleanReply,
857
- statusLabel: '通道回执已送达',
1270
+ const statusLabel = isPublicVisitor ? '只读口径解答完成' : '通道回执已送达';
1271
+ const turn = await recordTurnDelivery({
1272
+ person,
1273
+ isPublicVisitor,
1274
+ visitorId,
1275
+ cleanQ,
1276
+ replyText: generatedReply,
1277
+ capLabel: top.snippet.title,
1278
+ statusLabel,
858
1279
  statusTone: 'ok',
859
- basisHint: `已实查「${linkedProjects.map(p => p.name).join('、') || '授权工作区'}」`,
1280
+ basisHint: `已核对「${top.snippet.title}」`,
1281
+ channelId,
860
1282
  trace
861
- };
862
- await store.appendCallerTurn(person.id, turn, {
863
- countTurn: true,
864
- dshSessionId: aiRes.sessionId || callerThread?.dshSessionId || '',
865
- lastPolicyDigest: policyDigest
866
1283
  });
867
- await store.updateState(st => {
868
- const target = st.people.find(p => p.id === person.id);
869
- if (target) {
870
- target.servedCount = (target.servedCount || 0) + 1;
871
- target.lastActive = '刚刚';
872
- }
873
- st.deliveries.unshift({
874
- id: `del-${randomUUID().slice(0, 8)}`,
875
- personId: person.id,
876
- time: nowTimeLabel(),
877
- who: person.name,
878
- whoNote: person.role,
879
- channel: channelSelectionLabel(channelId),
880
- summary: cleanReply.slice(0, 52),
881
- statusLabel: '通道回执已送达',
882
- statusTone: 'ok',
883
- trace
884
- });
885
- st.deliveries = st.deliveries.slice(0, 40);
886
- });
887
- return { action: 'replied', reply: cleanReply, statusLabel: '通道回执已送达', turn };
1284
+ return {
1285
+ action: 'replied',
1286
+ reply: generatedReply,
1287
+ statusLabel,
1288
+ turn,
1289
+ ...(isPublicVisitor ? { remainingTurns: remainingAfterTurn, visitorDailyLimit } : {})
1290
+ };
888
1291
  }
889
1292
 
890
1293
  const draftApproval = {
@@ -895,262 +1298,223 @@ export function createTwinEngine({
895
1298
  tone: 'amber',
896
1299
  tag: '待过目草稿',
897
1300
  headline: `${person.name} 提问:${cleanQ.slice(0, 26)}`,
898
- gist: cleanReply.slice(0, 56),
1301
+ gist: generatedReply.slice(0, 56),
899
1302
  question: cleanQ,
900
- draft: cleanReply,
1303
+ draft: generatedReply,
901
1304
  primaryActionLabel: '批准发出',
902
1305
  allowRuleExtract: true,
903
- basisHint: `已实查「${linkedProjects.map(p => p.name).join('、') || '授权工作区'}」`,
1306
+ basisHint: `已核对「${top.snippet.title}」`,
904
1307
  replyContext,
905
1308
  trace
906
1309
  };
907
- const savedDraft = await enqueueApproval(draftApproval);
1310
+ const savedDraftB = await enqueueApproval(draftApproval);
908
1311
  return {
909
1312
  action: 'pending_approval',
910
- approvalId: savedDraft.id,
911
- shortCode: savedDraft.shortCode,
1313
+ approvalId: savedDraftB.id,
1314
+ shortCode: savedDraftB.shortCode,
912
1315
  statusLabel: '草稿待本人拍板',
913
- draft: cleanReply
1316
+ draft: generatedReply
914
1317
  };
915
- } catch (err) {
916
- logger?.warn?.('[agent-twin] full-blood turn error, falling back to deterministic engine:', err?.message);
917
- }
1318
+ } finally {
1319
+ activeTurns.delete(turnTrackId);
918
1320
  }
1321
+ });
1322
+ }
919
1323
 
920
- // Path B: Deterministic Offline Fallback (unit tests / offline environments)
921
- const violation = detectRedlineViolation(cleanQ, person);
922
-
923
- if (violation) {
924
- const draft = violation.kind === 'write'
925
- ? '按只读安全红线,分身无权修改代码、写入数据库或执行变更脚本;我已将你的诉求转交给负责人本人评估处理。'
926
- : violation.kind === 'commitment'
927
- ? '具体排期、商务报价或未公开策略需要由负责人本人核定;已将你的诉求转入待办,确认后第一时间回复你。'
928
- : '按只读隐私红线,不能提供逐笔客户手机号或原始流水明细;如需分析波动结构,我可以先为你整理脱敏汇总占比趋势。';
929
-
930
- if (sandboxOnly) {
931
- return {
932
- action: 'redline_intercepted',
933
- statusLabel: violation.label,
934
- reply: draft,
935
- reason: violation.reason
936
- };
937
- }
938
-
939
- const appItem = {
940
- id: `app-red-${randomUUID().slice(0, 8)}`,
941
- personId: person?.id || 'p-self',
942
- personName: person?.name || '自测预演',
943
- channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
944
- tone: 'danger',
945
- tag: violation.label,
946
- headline: `${person?.name || '访客'} 触发红线拦截:${violation.reason}`,
947
- gist: '已自动挡回越权明细或变更操作,并准备好安全替代回复等你确认。',
948
- question: cleanQ,
949
- draft,
950
- primaryActionLabel: '批准发出安全回复',
951
- allowRuleExtract: false,
952
- basisHint: `红线规则触发(${violation.reason})`,
953
- replyContext,
954
- trace: {
955
- intro: `${person?.name || '访客'} 的消息触发了工作台安全红线。`,
956
- steps: [
957
- { title: '边界校验命中红线', detail: violation.reason },
958
- { title: '生成脱敏替代答复', detail: '阻断原始字段或写操作,待本人审核发出。' }
959
- ],
960
- techNote: '红线规则先于任何资料检索执行,零越权泄露风险。'
961
- }
962
- };
963
-
964
- const savedViolation = await enqueueApproval(appItem, { setDeskOnCold: true });
1324
+ /**
1325
+ * Core Scoped Twin Session runtime handler for external named callers and self-tests.
1326
+ */
1327
+ async function handleInboundMessage({
1328
+ personId,
1329
+ question,
1330
+ channelId = 'ch-web',
1331
+ threadKey = '',
1332
+ isGroup = false,
1333
+ mentionsBot = true,
1334
+ isOwnerSelfTest = false,
1335
+ sandboxOnly = false,
1336
+ replyContext = {},
1337
+ forceDeterministic = false,
1338
+ onProgress = null
1339
+ }) {
1340
+ const s = store.getState();
1341
+ const secretVals = store.allSecretValues();
1342
+ const cleanQ = redactSecrets(sanitizeSurfaceText(String(question || '').trim()), secretVals);
1343
+ if (!cleanQ) throw new Error('提问内容不能为空');
965
1344
 
1345
+ if (!isOwnerSelfTest && s.dutyMode === 'off') {
966
1346
  return {
967
- action: 'pending_approval',
968
- approvalId: savedViolation.id,
969
- shortCode: savedViolation.shortCode,
970
- statusLabel: '已拦下并待本人拍板',
971
- draft,
972
- safeFallbackReply: '这个问题涉及敏感边界或需本人拍板事项,已转呈负责人确认,稍后答复你。'
1347
+ action: 'paused',
1348
+ statusLabel: '工作分身当前暂停对外值班',
1349
+ reply: '工作分身当前已暂停对外值班,暂时停止自动回复。工具内不设任何收费门槛,重要事项请直接联系项目负责人。'
973
1350
  };
974
1351
  }
975
1352
 
976
- const localMatches = await gatherAuthorizedSnippets(activeCaps, cleanQ);
977
- const matches = [...externalKnowledge, ...localMatches].sort((a, b) => b.score - a.score);
978
- const hasCustomKnowledge = matches.length > 0 && matches[0].score >= 2;
979
- const isExplicitGapPrompt = /(未公开|内部底价|定价策略|内幕|保密|还没写)/.test(cleanQ);
1353
+ const person = personId ? s.people.find(p => p.id === personId) : null;
980
1354
 
981
- if (!hasCustomKnowledge || isExplicitGapPrompt) {
982
- const gapDraft = '感谢提问,这块暂未写入当前已授权的项目口径文档,我已向负责人提交待补口径说明,确认准确边界后会补充回复你。';
983
- if (sandboxOnly) {
1355
+ if (!isOwnerSelfTest && !sandboxOnly) {
1356
+ if (!person) {
1357
+ return { action: 'ignored', reason: 'unknown_caller' };
1358
+ }
1359
+ if (!person.enabled || isPersonExpired(person)) {
984
1360
  return {
985
- action: 'knowledge_gap',
986
- statusLabel: '触发待补口径(沙箱预览)',
987
- reply: '这个问题涉及尚未写入授权资料库的口径细节,我先记下并转负责人「待补口径」补充,确认后第一时间答复你。'
1361
+ action: 'paused',
1362
+ statusLabel: '当前访问权限已暂停',
1363
+ reply: `你好 ${person.name},当前的分身试用或服务权限已暂停。本工具不收取任何费用,如需恢复请直接联系负责人打开开关。`
988
1364
  };
989
1365
  }
990
-
991
- if (isOwnerSelfTest) {
992
- const selfRes = {
993
- question: cleanQ,
994
- answer: '在当前授权的只读项目文档中未命中足够支撑(触发「待补口径」保护,未瞎编回答);若来自真实访客,会自动向你服务台发起口径补充卡片。',
995
- basis: '本地授权范围核查(未超出授权文件夹)',
996
- duration: '0.2 秒'
1366
+ if (isGroup && !mentionsBot) {
1367
+ return { action: 'ignored', reason: 'group_not_mentioned' };
1368
+ }
1369
+ if (threadKey && isOwnerPresentRecently(channelId, threadKey)) {
1370
+ const yieldNotice = {
1371
+ id: `del-yield-${Date.now()}`,
1372
+ personId: person.id,
1373
+ time: nowTimeLabel(),
1374
+ who: person.name,
1375
+ whoNote: person.role,
1376
+ channel: channelSelectionLabel(channelId),
1377
+ summary: '检测到本人在原会话 15 分钟内发言,分身自动收声未抢答',
1378
+ statusLabel: '本人在场自动收声',
1379
+ statusTone: 'muted',
1380
+ trace: {
1381
+ intro: '15 分钟内检测到负责人在同一会话亲自回复过,触发本人在场收声保护。',
1382
+ steps: [{ title: '检测最近真人互动', detail: '保持现场沟通顺畅,不做重复插话。' }],
1383
+ techNote: '15 分钟计时窗口自动刷新。'
1384
+ }
997
1385
  };
998
- await store.updateState(st => { st.selfTestTurn = selfRes; });
999
- return { action: 'replied', ...selfRes, reply: selfRes.answer };
1386
+ await store.updateState(st => {
1387
+ st.deliveries.unshift(yieldNotice);
1388
+ st.deliveries = st.deliveries.slice(0, 40);
1389
+ });
1390
+ return { action: 'yielded', statusLabel: '本人在场自动收声', delivery: yieldNotice };
1000
1391
  }
1001
-
1002
- const gapItem = {
1003
- id: `app-gap-${randomUUID().slice(0, 8)}`,
1004
- personId: person.id,
1005
- personName: person.name,
1006
- channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
1007
- tone: 'amber',
1008
- tag: '待补口径',
1009
- headline: `${person.name} 问到授权资料外问题,待你补充口径`,
1010
- gist: '已先礼貌告知正在核实(严禁胡编),等你填补结论后可顺手记成长期规矩。',
1011
- question: cleanQ,
1012
- draft: gapDraft,
1013
- primaryActionLabel: '补好并回复对方',
1014
- allowRuleExtract: true,
1015
- basisHint: '知识缺口拦截 · 未发现公开授权依据',
1016
- replyContext,
1017
- trace: {
1018
- intro: `${person.name} 的问题超出当前已提取能力文档覆盖范围。`,
1019
- steps: [
1020
- { title: '在授权文档索引中检索', detail: '未找到满足置信度的授权片段。' },
1021
- { title: '拒绝幻觉编造并升级待补口径', detail: '保留人工补充口供,确认后可一键沉淀为长期规矩。' }
1022
- ],
1023
- techNote: '知识边界守卫拦截:宁可标待补口径,绝不编造数字或越权读取未授权目录。'
1024
- }
1025
- };
1026
-
1027
- const politeHoldingReply = '这个问题暂未在我当前掌握的公开口径文档中明确定义,我已转请负责人核实补充,确认后会第一时间给你答复。';
1028
- const savedGapB = await enqueueApproval(gapItem);
1029
- return {
1030
- action: 'knowledge_gap',
1031
- approvalId: savedGapB.id,
1032
- shortCode: savedGapB.shortCode,
1033
- statusLabel: '待补口径已转服务台',
1034
- reply: politeHoldingReply
1035
- };
1036
1392
  }
1037
1393
 
1038
- emitProgress({
1039
- phase: 'doc',
1040
- title: '核对授权文档口径',
1041
- detail: `${matches[0].projectName} · ${matches[0].snippet.title}`
1394
+ const activeCaps = person ? person.caps : s.capabilities.filter(c => c.enabled).map(c => c.id);
1395
+ const scopeKey = person && !isOwnerSelfTest ? `caller-${person.id}` : 'selftest';
1396
+
1397
+ return executeCoreTurn({
1398
+ person,
1399
+ twinProfile: s.twinProfile,
1400
+ activeCaps,
1401
+ cleanQ,
1402
+ channelId,
1403
+ replyContext,
1404
+ isOwnerSelfTest,
1405
+ sandboxOnly,
1406
+ forceDeterministic,
1407
+ onProgress,
1408
+ threadAdapter: person
1409
+ ? {
1410
+ readThread: () => store.readCallerThread(person.id),
1411
+ updateMeta: patch => store.updateCallerMeta(person.id, patch)
1412
+ }
1413
+ : null,
1414
+ materializeScopeKey: scopeKey,
1415
+ turnLockKey: scopeKey,
1416
+ reuseSandbox: false,
1417
+ isPublicVisitor: false,
1418
+ dailyLimit: (!isOwnerSelfTest && !sandboxOnly) ? (s.dailyTurnCap || DEFAULT_DAILY_TURN_CAP) : 0
1042
1419
  });
1420
+ }
1043
1421
 
1044
- const top = matches[0];
1045
- let generatedReply = `根据「${top.projectName} · ${top.snippet.title}」的只读口径说明:${top.snippet.summary}`;
1046
- if (typeof llmResponder === 'function') {
1047
- try {
1048
- const custom = await llmResponder({ question: cleanQ, matches: matches.slice(0, 3), rules: s.rules, person });
1049
- if (typeof custom === 'string' && custom.trim()) {
1050
- generatedReply = redactSecrets(sanitizeSurfaceText(custom.trim()), secretVals);
1051
- }
1052
- } catch (err) {
1053
- logger?.warn?.('[agent-twin] llmResponder fallback used:', err?.message);
1054
- }
1055
- }
1422
+ /**
1423
+ * Fail-closed handler for anonymous visitors on the `/try` Public Scan-to-Try Lobby.
1424
+ */
1425
+ async function handlePublicVisitorMessage({
1426
+ visitorId,
1427
+ question,
1428
+ forceDeterministic = false,
1429
+ onProgress = null
1430
+ }) {
1431
+ const s = store.getState();
1432
+ const secretVals = store.allSecretValues();
1433
+ const cleanQ = redactSecrets(sanitizeSurfaceText(String(question || '').trim()), secretVals);
1434
+ if (!cleanQ) throw new Error('提问内容不能为空');
1056
1435
 
1057
- if (person?.note) {
1058
- generatedReply += `(注:按「${sanitizeSurfaceText(person.note)}」约定整理)`;
1436
+ if (s.dutyMode === 'off') {
1437
+ return {
1438
+ action: 'paused',
1439
+ statusLabel: '工作分身当前暂停对外值班',
1440
+ reply: '本分身当前处于暂停对外值班状态,欢迎随时按底部指引 30 秒在 DeepSeek Harness 自建自己的隔离 AI 分身。'
1441
+ };
1059
1442
  }
1060
1443
 
1061
- if (sandboxOnly) {
1444
+ const publicCfg = normalizePublicLobbyConfig(s.publicLobby);
1445
+ if (!publicCfg.enabled) {
1062
1446
  return {
1063
- action: 'replied',
1064
- statusLabel: '沙箱试答(未写入外部记录)',
1065
- reply: generatedReply,
1066
- basis: `${top.projectName} · ${top.snippet.title}`
1447
+ action: 'paused',
1448
+ statusLabel: '公开体验大厅未开启',
1449
+ reply: '工作区负责人尚未开启公开扫码体验大厅,请先在工作台「能力与通道 -> 公开扫码真体验大厅」开启并勾选允许对外展示的只读能力。'
1067
1450
  };
1068
1451
  }
1069
1452
 
1070
- if (isOwnerSelfTest) {
1071
- const selfRes = {
1072
- question: cleanQ,
1073
- answer: generatedReply,
1074
- basis: `${top.projectName} · ${top.snippet.title}(仅本地自测)`,
1075
- duration: '0.4 秒'
1453
+ // Fail-Closed: NEVER fall back to all enabled capabilities when capIds is empty
1454
+ const configuredCapSet = new Set(publicCfg.capIds || []);
1455
+ const allowedCaps = s.capabilities.filter(c => c.enabled && configuredCapSet.has(c.id));
1456
+ const allowedCapIds = allowedCaps.map(c => c.id);
1457
+ if (allowedCapIds.length === 0) {
1458
+ return {
1459
+ action: 'paused',
1460
+ statusLabel: '暂未勾选公开体验能力',
1461
+ reply: '为严守 Fail-Closed 安全默认,负责人尚未在工作台勾选任何可对外体验的只读能力项,当前拒绝访问任何工作区文件。'
1076
1462
  };
1077
- await store.updateState(st => { st.selfTestTurn = selfRes; });
1078
- return { action: 'replied', ...selfRes, reply: generatedReply };
1079
1463
  }
1080
1464
 
1081
- const trace = {
1082
- intro: `收到 ${person.name} 通过「${channelSelectionLabel(channelId)}」的提问,已在独立沙箱内完成只读核对。`,
1083
- steps: [
1084
- { title: '核对白名单与能力范围', detail: `仅检索 ${person.name} 已获授权的 ${matches.length} 处片段。` },
1085
- { title: '依据授权文档生成结论', detail: `引用「${top.projectName} · ${top.snippet.title}」,过滤私密字段。` }
1086
- ],
1087
- techNote: '单人会话物理隔离存档,不含其他访客历史或敏感文件路径。'
1088
- };
1089
-
1090
- const shouldAutoReply = s.dutyMode === 'live' && (person.mode === 'direct' || person.mode === 'summary');
1091
- if (shouldAutoReply) {
1092
- const turn = {
1093
- id: `th-${randomUUID().slice(0, 8)}`,
1094
- time: nowTimeLabel(),
1095
- capLabel: top.snippet.title,
1096
- question: cleanQ,
1097
- reply: generatedReply,
1098
- statusLabel: '通道回执已送达',
1099
- statusTone: 'ok',
1100
- basisHint: `已核对「${top.snippet.title}」`,
1101
- trace
1102
- };
1103
- await store.appendCallerTurn(person.id, turn, { countTurn: true });
1104
- await store.updateState(st => {
1105
- const target = st.people.find(p => p.id === person.id);
1106
- if (target) {
1107
- target.servedCount = (target.servedCount || 0) + 1;
1108
- target.lastActive = '刚刚';
1109
- }
1110
- st.deliveries.unshift({
1111
- id: `del-${randomUUID().slice(0, 8)}`,
1112
- personId: person.id,
1113
- time: nowTimeLabel(),
1114
- who: person.name,
1115
- whoNote: person.role,
1116
- channel: channelSelectionLabel(channelId),
1117
- summary: generatedReply.slice(0, 48),
1118
- statusLabel: '通道回执已送达',
1119
- statusTone: 'ok',
1120
- trace
1121
- });
1122
- st.deliveries = st.deliveries.slice(0, 40);
1123
- });
1124
- return { action: 'replied', reply: generatedReply, statusLabel: '通道回执已送达', turn };
1465
+ if (activePublicTurns >= MAX_CONCURRENT_PUBLIC_TURNS) {
1466
+ const busyErr = new Error('当前同时在线体验人数较多,请稍等 10 秒后再试。');
1467
+ busyErr.statusCode = 429;
1468
+ throw busyErr;
1125
1469
  }
1126
1470
 
1127
- const draftApproval = {
1128
- id: `app-${randomUUID().slice(0, 8)}`,
1129
- personId: person.id,
1130
- personName: person.name,
1131
- channel: `${channelSelectionLabel(channelId)} · ${nowTimeLabel()}`,
1132
- tone: 'amber',
1133
- tag: '待过目草稿',
1134
- headline: `${person.name} 提问:${cleanQ.slice(0, 26)}`,
1135
- gist: generatedReply.slice(0, 56),
1136
- question: cleanQ,
1137
- draft: generatedReply,
1138
- primaryActionLabel: '批准发出',
1139
- allowRuleExtract: true,
1140
- basisHint: `已核对「${top.snippet.title}」`,
1141
- replyContext,
1142
- trace
1471
+ const visitorDailyLimit = Math.max(1, publicCfg.visitorDailyLimit || DEFAULT_PUBLIC_VISITOR_DAILY_LIMIT);
1472
+ const globalDailyLimit = Math.max(1, publicCfg.globalDailyLimit || DEFAULT_PUBLIC_GLOBAL_DAILY_LIMIT);
1473
+ const allowedProjectNames = [...new Set(allowedCaps.map(c => c.projectName).filter(Boolean))].join('、') || '公开授权工作区';
1474
+ // Strict Persona Isolation: never inherit private workspace title/intro (e.g. unrelated client projects)
1475
+ const effectiveTwinProfile = {
1476
+ personaId: 'advisor',
1477
+ name: publicCfg.title || `${allowedProjectNames} · 公开体验分身`,
1478
+ intro: publicCfg.intro || `由本机 DeepSeek Harness 只读驱动,仅可查「${allowedProjectNames}」已勾选能力,私有项目物理隔离不可见。`
1143
1479
  };
1144
- const savedDraftB = await enqueueApproval(draftApproval);
1145
- return {
1146
- action: 'pending_approval',
1147
- approvalId: savedDraftB.id,
1148
- shortCode: savedDraftB.shortCode,
1149
- statusLabel: '草稿待本人拍板',
1150
- draft: generatedReply
1480
+ const shortTag = String(visitorId).slice(-4).toUpperCase();
1481
+ const virtualPerson = {
1482
+ id: `vis-${String(visitorId).slice(0, 12)}`,
1483
+ name: `扫码访客 #${shortTag}`,
1484
+ role: '公开扫码体验',
1485
+ channel: '公开扫码体验',
1486
+ mode: publicCfg.mode === 'direct' ? 'direct' : 'summary',
1487
+ caps: allowedCapIds,
1488
+ enabled: true,
1489
+ isPublicVisitor: true
1151
1490
  };
1491
+
1492
+ activePublicTurns += 1;
1493
+ try {
1494
+ return await executeCoreTurn({
1495
+ person: virtualPerson,
1496
+ twinProfile: effectiveTwinProfile,
1497
+ activeCaps: allowedCapIds,
1498
+ cleanQ,
1499
+ channelId: 'ch-public-try',
1500
+ isOwnerSelfTest: false,
1501
+ sandboxOnly: false,
1502
+ forceDeterministic,
1503
+ onProgress,
1504
+ threadAdapter: {
1505
+ readThread: () => store.readVisitorThread(visitorId),
1506
+ updateMeta: patch => store.updateVisitorMeta(visitorId, patch)
1507
+ },
1508
+ materializeScopeKey: 'public-lobby',
1509
+ turnLockKey: `visitor-${visitorId}`,
1510
+ reuseSandbox: true,
1511
+ isPublicVisitor: true,
1512
+ visitorId,
1513
+ dailyLimit: visitorDailyLimit,
1514
+ globalDailyLimit
1515
+ });
1152
1516
  } finally {
1153
- activeTurns.delete(turnTrackId);
1517
+ activePublicTurns = Math.max(0, activePublicTurns - 1);
1154
1518
  }
1155
1519
  }
1156
1520
 
@@ -1164,7 +1528,7 @@ export function createTwinEngine({
1164
1528
  );
1165
1529
 
1166
1530
  const person = s.people.find(p => p.id === item.personId);
1167
- let dispatchStatus = '已调用通道接口发出';
1531
+ let dispatchStatus = item.isPublicLobby ? '公开体验已审阅存档' : '已调用通道接口发出';
1168
1532
  if (person && typeof onDispatchOutbound === 'function') {
1169
1533
  try {
1170
1534
  const res = await onDispatchOutbound(person, finalReply, item.replyContext || {});
@@ -1174,18 +1538,22 @@ export function createTwinEngine({
1174
1538
  }
1175
1539
  }
1176
1540
 
1177
- if (person) {
1178
- await store.appendCallerTurn(person.id, {
1179
- id: `th-ap-${randomUUID().slice(0, 8)}`,
1180
- time: nowTimeLabel(),
1181
- capLabel: item.tag,
1182
- question: item.question,
1183
- reply: finalReply,
1184
- statusLabel: dispatchStatus,
1185
- statusTone: 'ok',
1186
- basisHint: item.basisHint || '经负责人审核发出',
1187
- trace: item.trace
1188
- }, { countTurn: true });
1541
+ const approvedTurn = {
1542
+ id: `th-ap-${randomUUID().slice(0, 8)}`,
1543
+ time: nowTimeLabel(),
1544
+ capLabel: item.tag,
1545
+ question: item.question,
1546
+ reply: finalReply,
1547
+ statusLabel: dispatchStatus,
1548
+ statusTone: 'ok',
1549
+ basisHint: item.basisHint || '经负责人审核发出',
1550
+ trace: item.trace
1551
+ };
1552
+
1553
+ if (item.isPublicLobby && item.visitorId) {
1554
+ await store.appendVisitorTurn(item.visitorId, approvedTurn, { countTurn: false });
1555
+ } else if (person) {
1556
+ await store.appendCallerTurn(person.id, approvedTurn, { countTurn: true });
1189
1557
  }
1190
1558
 
1191
1559
  await store.updateState(st => {
@@ -1346,6 +1714,7 @@ export function createTwinEngine({
1346
1714
  recheckProjectDelta,
1347
1715
  confirmDeltaUpgrade,
1348
1716
  handleInboundMessage,
1717
+ handlePublicVisitorMessage,
1349
1718
  approveDraft,
1350
1719
  executeOwnerCommand,
1351
1720
  resolveRemoteOwnerCommand,