dsh-dafeiyu-life 2.8.2 → 2.8.3-dev.14
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/AGENTS.md +14 -2
- package/CHANGELOG.md +515 -0
- package/README.md +6 -2
- package/client.js +333 -84
- package/docs/ROADMAP.md +10 -4
- package/docs/architecture/2.8.2-current-architecture.md +2 -0
- package/docs/architecture/2.8.3-dev2-storage-and-memory.md +42 -0
- package/docs/architecture/2.8.3-dev3-cross-platform-installer-audit.md +44 -0
- package/docs/architecture/2.8.3-dev3-preview-read-auto-recovery.md +31 -0
- package/docs/architecture/2.8.3-dev3-storage-domains.md +163 -0
- package/docs/architecture/2.8.3-video-perception-memory-roadmap.md +20 -1
- package/docs/architecture/README.md +13 -1
- package/docs/architecture/diagrams/life-candidates-current.mmd +40 -0
- package/docs/architecture/diagrams/life-receipt-memory-current.mmd +50 -1
- package/docs/architecture/diagrams/life-system-current.mmd +46 -0
- package/docs/architecture/diagrams/life-universal-episodes-current.mmd +37 -0
- package/docs/architecture/future-layered-memory-progressive-recall-proposal.md +2 -2
- package/docs/architecture/life-system-current-view.md +173 -1
- package/docs/architecture/life-system-current.md +34 -0
- package/index.js +922 -219
- package/lib/account-binding.mjs +13 -2
- package/lib/asr.py +16 -3
- package/lib/autonomous-planner.mjs +155 -32
- package/lib/backup-directory.mjs +13 -6
- package/lib/backup-rotation.mjs +74 -0
- package/lib/cold-state-snapshot.mjs +9 -0
- package/lib/conversation-life-feedback.mjs +2 -1
- package/lib/data-backup.mjs +77 -20
- package/lib/embedding-memory-index.mjs +96 -12
- package/lib/embedding-runtime-manager.mjs +8 -4
- package/lib/emotion-recall.mjs +2 -1
- package/lib/emotional-state.mjs +2 -1
- package/lib/interaction-batch.mjs +10 -4
- package/lib/life-continuation.mjs +4 -0
- package/lib/life-decision-trace.mjs +4 -1
- package/lib/life-experience-continuity.mjs +2 -1
- package/lib/life-interests.mjs +14 -4
- package/lib/life-management-events.mjs +1 -1
- package/lib/life-memory-associations.mjs +72 -0
- package/lib/life-memory-coordinator.mjs +5 -2
- package/lib/life-memory-details.mjs +178 -0
- package/lib/life-memory-gateway.mjs +443 -43
- package/lib/life-reflection.mjs +90 -15
- package/lib/life-video-gallery.mjs +159 -0
- package/lib/life-willingness.mjs +15 -3
- package/lib/local-vision-model-manager.mjs +4 -1
- package/lib/long-term-memory.mjs +38 -9
- package/lib/main-session-bridge.mjs +47 -8
- package/lib/management-console.html +760 -108
- package/lib/management-console.js +1147 -182
- package/lib/management-host-auth.mjs +77 -0
- package/lib/mcp.mjs +9 -4
- package/lib/memory-neural-projection.mjs +59 -5
- package/lib/memory-retriever.mjs +200 -21
- package/lib/migration-wait.html +13 -0
- package/lib/migration-wait.js +35 -0
- package/lib/owner-dm-agent.mjs +7 -1
- package/lib/owner-video-debug-local-vision.mjs +136 -0
- package/lib/owner-video-revisit.mjs +30 -0
- package/lib/preview_vision.py +513 -80
- package/lib/private-conversation-experiences.mjs +2 -1
- package/lib/read-action-execution-gate.mjs +44 -5
- package/lib/recent-comments.mjs +14 -4
- package/lib/social-context-assembler.mjs +23 -6
- package/lib/state.mjs +6 -13
- package/lib/storage-archive-inventory.mjs +50 -0
- package/lib/storage-cleanup-queue.mjs +154 -0
- package/lib/storage-external-life-retired.mjs +130 -0
- package/lib/storage-large-data-v2.mjs +215 -0
- package/lib/storage-layout.mjs +629 -0
- package/lib/storage-life-cleanup-queue.mjs +129 -0
- package/lib/storage-life-retained.mjs +161 -0
- package/lib/storage-life-return-evidence.mjs +40 -0
- package/lib/storage-life-runtime-check.mjs +184 -0
- package/lib/storage-location.mjs +154 -0
- package/lib/storage-maintenance.mjs +112 -0
- package/lib/storage-migration-maintenance-state.mjs +31 -0
- package/lib/storage-migration-maintenance.mjs +85 -0
- package/lib/storage-migration-queue.mjs +199 -0
- package/lib/storage-model-runtime-check.mjs +110 -0
- package/lib/storage-platform.mjs +23 -0
- package/lib/storage-python-cache-check.mjs +55 -0
- package/lib/storage-vision-cache-access.mjs +44 -0
- package/lib/storage-vision-runtime-check.mjs +160 -0
- package/lib/system-health-projection.mjs +20 -3
- package/lib/video-cache-retention.mjs +75 -0
- package/lib/video-dependencies.mjs +5 -2
- package/lib/video-evidence-bundle.mjs +13 -13
- package/lib/video-experience.mjs +65 -0
- package/lib/video-memory-observation-groups.mjs +88 -0
- package/lib/video-moment-followup.mjs +1 -1
- package/lib/video-visual-attempt-diagnostics.mjs +3 -2
- package/lib/video-visual-failure.mjs +14 -1
- package/lib/vision-environment-repair.mjs +49 -8
- package/lib/vision-production-status.mjs +7 -1
- package/lib/vision-python-runtime.mjs +15 -5
- package/lib/vision_dsh.py +12 -7
- package/lib/whisper-model-cache.mjs +5 -1
- package/package.json +4 -1
- package/scripts/check-vision-cache-access.mjs +22 -0
- package/scripts/migrate-bili-duty-after-exit.mjs +10 -0
- package/scripts/resolve-bili-duty-storage.mjs +13 -0
- package/tools/repair-dsh-python-runtime.ps1 +9 -3
- package/tools/repair-dsh-vision-python.ps1 +9 -3
- package/tools//345/257/274/345/207/272B/347/253/231/346/227/245/345/277/227.bat +19 -1
- package/vendor/bilibili-mcp/mcp_server.py +82 -20
- package/vendor/bilibili-mcp/read_action_gate.py +118 -37
package/index.js
CHANGED
|
@@ -58,13 +58,35 @@ import {mcpIntegrity,repairReviewedMcp} from './lib/mcp-reviewed-repair.mjs'
|
|
|
58
58
|
import { createBackup, validateBackup, validateRestoreIdentity, restoreBackupFiles, createLifeMemoryBackup, inspectLifeMemoryBackup, restoreLifeMemoryBackup } from './lib/data-backup.mjs'
|
|
59
59
|
import { readJsonRequest } from './lib/http-json-body.mjs'
|
|
60
60
|
import { requireBackupDirectory, saveBackupJson } from './lib/backup-directory.mjs'
|
|
61
|
+
import {listBackupFiles,inspectBackupInDirectory,hasTodaysAutomatic,saveAutomaticBackup,pruneAutomaticBackups} from './lib/backup-rotation.mjs'
|
|
62
|
+
import {pruneVideoCaches,VIDEO_CACHE_RETENTION} from './lib/video-cache-retention.mjs'
|
|
63
|
+
import {addLifeVideoGallery,listLifeVideoGallery,readLifeVideoGalleryImage,pruneLifeVideoGallery,LIFE_GALLERY_RETENTION_HOURS} from './lib/life-video-gallery.mjs'
|
|
64
|
+
import {planOwnerGalleryRevisit} from './lib/owner-video-revisit.mjs'
|
|
61
65
|
import { appendFileSync, existsSync, mkdirSync, readdirSync, lstatSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
62
66
|
import { join, dirname } from 'node:path'
|
|
67
|
+
import { homedir } from 'node:os'
|
|
63
68
|
import { createRequire } from 'node:module'
|
|
64
69
|
import { fileURLToPath } from 'node:url'
|
|
65
70
|
import { McpClient } from './lib/mcp.mjs'
|
|
66
71
|
import { verifyRecent, appendVerifyToReport } from './lib/verify.mjs'
|
|
67
72
|
import { stateDirOf, readJson, writeJson, ensureHomeFiles, ensureCharter, charterPath, dayKey } from './lib/state.mjs'
|
|
73
|
+
import {originalStateDir,storageLocationStatus,inspectStorageTarget,storageCategories} from './lib/storage-location.mjs'
|
|
74
|
+
import {storageDataPath,storageDomainRoot,storagePythonRuntimeRoot,storageLayoutStatus,inspectDomainMigration,inspectDomainReturnHome,storageDomainsUsage,storageMigrationGroups} from './lib/storage-layout.mjs'
|
|
75
|
+
import {largeDataStatus,inspectLargeDataMigration} from './lib/storage-large-data-v2.mjs'
|
|
76
|
+
import {inspectRetainedModelCopies} from './lib/storage-maintenance.mjs'
|
|
77
|
+
import {verifyRelocatedModelRuntime} from './lib/storage-model-runtime-check.mjs'
|
|
78
|
+
import {verifyPythonCachePaths} from './lib/storage-python-cache-check.mjs'
|
|
79
|
+
import {verifyRelocatedLifeMemory} from './lib/storage-life-runtime-check.mjs'
|
|
80
|
+
import {inspectRetainedLifeCopies} from './lib/storage-life-retained.mjs'
|
|
81
|
+
import {queueLifeCleanup,queueExternalLifeCleanup,readLifeCleanupJob} from './lib/storage-life-cleanup-queue.mjs'
|
|
82
|
+
import {inspectExternalLifeCopy} from './lib/storage-external-life-retired.mjs'
|
|
83
|
+
import {queueModelCleanup,readCleanupJob} from './lib/storage-cleanup-queue.mjs'
|
|
84
|
+
import {queueDomainMigration,readMigrationJob,assertMigrationStartupSafe} from './lib/storage-migration-queue.mjs'
|
|
85
|
+
import {registerMigrationMaintenance} from './lib/storage-migration-maintenance.mjs'
|
|
86
|
+
import {managementOwnerStatus,managementAuthError,explicitManagementIntent,managementPath,managementBrowserUrl,managementBrowserLanding} from './lib/management-host-auth.mjs'
|
|
87
|
+
import {storageTargetSuggestions} from './lib/storage-platform.mjs'
|
|
88
|
+
import {storageArchiveInventory} from './lib/storage-archive-inventory.mjs'
|
|
89
|
+
import {readLifeReturnEvidence} from './lib/storage-life-return-evidence.mjs'
|
|
68
90
|
import { VIDEO_PICK_POLICY } from './lib/video-pick-policy.mjs'
|
|
69
91
|
import {effectiveVideoCharter} from './lib/video-charter.mjs'
|
|
70
92
|
import { loginStart, loginPoll, renderQrPng } from './lib/login.mjs'
|
|
@@ -111,7 +133,7 @@ import {observedVideoFromRead,verifiedVideoObservation,unifiedLegacySocialChoice
|
|
|
111
133
|
import { validateOwnerRosterUpdate } from './lib/owner-identity.mjs'
|
|
112
134
|
import { formatLocalLogTimestamp } from './lib/log-time.mjs'
|
|
113
135
|
import { collectLocalLifeEvents } from './lib/local-life-source.mjs'
|
|
114
|
-
import {buildVideoExplorationEvent} from './lib/video-experience.mjs'
|
|
136
|
+
import {buildVideoExplorationEvent,buildFreshVideoDetails} from './lib/video-experience.mjs'
|
|
115
137
|
import {synthesizeFocusVisualMemory} from './lib/video-memory-synthesis.mjs'
|
|
116
138
|
import {hasNewFocusFrameSample} from './lib/video-exploration-budget.mjs'
|
|
117
139
|
import {verifyEpisodeVideoVisual} from './lib/life-episode-video-visual.mjs'
|
|
@@ -146,6 +168,7 @@ import { createSocialIntentEngine } from './lib/social-intentions.mjs'
|
|
|
146
168
|
import { createEmotionalState } from './lib/emotional-state.mjs'
|
|
147
169
|
import {visionDecision} from './lib/video-vision-policy.mjs'
|
|
148
170
|
import {beginVideoObservationRead} from './lib/video-observation-read.mjs'
|
|
171
|
+
import {ownerDebugLocalVision,ownerDebugTimeoutMessage,ownerDebugOllamaSummary} from './lib/owner-video-debug-local-vision.mjs'
|
|
149
172
|
import { createConversationLifeFeedback } from './lib/conversation-life-feedback.mjs'
|
|
150
173
|
import { createDualContextAgency, classifyBiliOwnerRequest, agencyDeclineMessage } from './lib/dual-context-agency.mjs'
|
|
151
174
|
import { createSocialCognition } from './lib/social-cognition.mjs'
|
|
@@ -191,7 +214,7 @@ import { fetchBiliCover } from './lib/bili-cover-proxy.mjs'
|
|
|
191
214
|
import {createDmPollCursor} from './lib/dm-poll-cursor.mjs'
|
|
192
215
|
import {createDmDetailQueue} from './lib/dm-detail-queue.mjs'
|
|
193
216
|
import {createDmDetailSingleflight} from './lib/dm-detail-singleflight.mjs'
|
|
194
|
-
import {selectVisionPython,probeVisionPython,visionPythonCandidates,ensureVisionTempDir,visionTempPath,visionPythonTempEnv} from './lib/vision-python-runtime.mjs'
|
|
217
|
+
import {selectVisionPython,probeVisionPython,visionPythonCandidates,ensureVisionTempDir,visionTempPath,visionPythonTempEnv,productionVisionPython} from './lib/vision-python-runtime.mjs'
|
|
195
218
|
import {createVisionEnvironmentRepair,probeVisionPythonAsync} from './lib/vision-environment-repair.mjs'
|
|
196
219
|
import {dmContinuationPrompt,parseDmContinuationReply} from './lib/dm-progressive-expression.mjs'
|
|
197
220
|
import { listCommentMemes, getCommentMemePreview } from './lib/comment-meme-library.mjs'
|
|
@@ -217,10 +240,10 @@ import {callScopedDshVision} from './lib/scoped-dsh-vision-read.mjs'
|
|
|
217
240
|
import { mergeWatchedRows } from './lib/watched.mjs'
|
|
218
241
|
import { createMainSessionBridge } from './lib/main-session-bridge.mjs'
|
|
219
242
|
import { createLongTermMemory } from './lib/long-term-memory.mjs'
|
|
220
|
-
import { createMemoryRetriever } from './lib/memory-retriever.mjs'
|
|
243
|
+
import { createMemoryRetriever,publicVisualAssociationContext } from './lib/memory-retriever.mjs'
|
|
221
244
|
import {createEmbeddingRuntimeManager} from './lib/embedding-runtime-manager.mjs'
|
|
222
245
|
import {createLocalVisionModelManager,getLocalVisionModel,getLocalVisionTestImage} from './lib/local-vision-model-manager.mjs'
|
|
223
|
-
import {createEmbeddingMemoryIndex} from './lib/embedding-memory-index.mjs'
|
|
246
|
+
import {createEmbeddingMemoryIndex,visualParentIndexRows} from './lib/embedding-memory-index.mjs'
|
|
224
247
|
import {verifiedLifeActionEvent} from './lib/life-action-memory.mjs'
|
|
225
248
|
import {verifiedShareMemoryEvents} from './lib/confirmed-video-share.mjs'
|
|
226
249
|
import { createLifeReflection } from './lib/life-reflection.mjs'
|
|
@@ -231,8 +254,9 @@ import {createLifeManagementEvents} from './lib/life-management-events.mjs'
|
|
|
231
254
|
import {describeIncomingBiliImage,verifiedBiliImageUrl} from './lib/incoming-image-vision.mjs'
|
|
232
255
|
import {favoriteStyleFromPersona,publicFavoriteTopics} from './lib/favorite-style.mjs'
|
|
233
256
|
import { createLifeMemoryGateway, relationshipMemoryHalfLifeDays } from './lib/life-memory-gateway.mjs'
|
|
257
|
+
import {interestNeuralEvidence} from './lib/life-interests.mjs'
|
|
234
258
|
import { memoryGardenSnapshot } from './lib/memory-garden-view.mjs'
|
|
235
|
-
import { memoryNeuralProjection, neuralProjectionKey } from './lib/memory-neural-projection.mjs'
|
|
259
|
+
import { memoryNeuralProjection, neuralProjectionKey, createNeuralActivationTracker, projectNeuralActivation } from './lib/memory-neural-projection.mjs'
|
|
236
260
|
import { systemHealthSnapshot } from './lib/system-health-projection.mjs'
|
|
237
261
|
import {readProductionVisionStatus} from './lib/vision-production-status.mjs'
|
|
238
262
|
import {planVideoMomentFollowup} from './lib/video-moment-followup.mjs'
|
|
@@ -245,7 +269,7 @@ import { interestMemoryRows, selectionInterests, listLifeInterests, scopedIntere
|
|
|
245
269
|
import { readModelTaskUsage, recordModelTask, MODEL_TASKS } from './lib/model-task-usage.mjs'
|
|
246
270
|
|
|
247
271
|
export const name = 'dafeiyu-life'
|
|
248
|
-
export const inject = ['webServer', 'tools', 'settings', 'agents', 'sessionTitle', 'systemPrompt']
|
|
272
|
+
export const inject = ['webServer', 'connection', 'tools', 'settings', 'agents', 'sessionTitle', 'systemPrompt']
|
|
249
273
|
|
|
250
274
|
/**
|
|
251
275
|
* 🔴 每个字段都要 `.extra('volatile', true)`:DSH 的 settings.update() 只认 volatile 字段
|
|
@@ -435,6 +459,7 @@ export const Config = !z ? undefined : z.object({
|
|
|
435
459
|
commentReplyHotCount: z.natural().default(12).extra('volatile', true),
|
|
436
460
|
/** 用户自己选择的数据备份目录;不使用系统 Temp。 */
|
|
437
461
|
backupDirectory: z.string().default('').extra('volatile', true),
|
|
462
|
+
backupAutoEnabled: z.boolean().default(true).extra('volatile', true),
|
|
438
463
|
commentAllowGeneralTop: z.boolean().default(false).extra('volatile', true),
|
|
439
464
|
commentReplyPerPoll: z.natural().default(12).extra('volatile', true),
|
|
440
465
|
commentReplyPerDay: z.natural().default(1000).extra('volatile', true),
|
|
@@ -603,6 +628,21 @@ export function apply(ctx, config) {
|
|
|
603
628
|
return myVer
|
|
604
629
|
}
|
|
605
630
|
const stateDir = stateDirOf(ctx)
|
|
631
|
+
// Migration maintenance is a deliberately read-only activation. No Life,
|
|
632
|
+
// Python, MCP, cache initialization or authoritative data write may follow
|
|
633
|
+
// until the detached worker has safely settled and DSH restarts once more.
|
|
634
|
+
if(registerMigrationMaintenance(ctx,{root:stateDir,pluginDir}))return
|
|
635
|
+
assertMigrationStartupSafe(stateDir)
|
|
636
|
+
// Verify every configured storage domain before any write/identity creation.
|
|
637
|
+
const storageLayout = storageLayoutStatus(stateDir)
|
|
638
|
+
const storagePyEnv = (extra={})=>pyEnv({
|
|
639
|
+
...extra,
|
|
640
|
+
// The published partition is authoritative. A stale inherited or DSH CLI
|
|
641
|
+
// environment must never quietly move a child back to the old C cache.
|
|
642
|
+
HF_HOME:storageDataPath(stateDir,'.hf-cache'),
|
|
643
|
+
DSH_WHISPER_LIBRARY_HOME:largeDataStatus(stateDir).whisperHome||'',
|
|
644
|
+
DSH_MEDIA_CACHE_HOME:storageDomainRoot(stateDir,'media'),
|
|
645
|
+
})
|
|
606
646
|
// Determine whether this is an upgrade BEFORE allocating the vision TEMP folder.
|
|
607
647
|
// Otherwise the folder itself makes a pristine installation look like a legacy one,
|
|
608
648
|
// silently applying old defaults and changing first-start permissions/experience.
|
|
@@ -610,7 +650,7 @@ export function apply(ctx, config) {
|
|
|
610
650
|
// Pre-create the vision-only TEMP at host startup, before DSH/MCP sandboxing.
|
|
611
651
|
// Entering the models page remains read-only and never installs dependencies.
|
|
612
652
|
try{ensureVisionTempDir(stateDir,{create:true})}catch{/* health/repair will report unavailable */}
|
|
613
|
-
const visionEnv=extra=>visionPythonTempEnv({home:stateDir,env:
|
|
653
|
+
const visionEnv=extra=>visionPythonTempEnv({home:stateDir,env:storagePyEnv(extra),create:false})
|
|
614
654
|
// Character identity is stable; B站 UID is a replaceable, verified transport identity.
|
|
615
655
|
const accountBinding = createAccountBinding({dataDir:stateDir})
|
|
616
656
|
const accountRuntimeDir = accountBinding.runtimeDir()
|
|
@@ -698,16 +738,17 @@ export function apply(ctx, config) {
|
|
|
698
738
|
}})
|
|
699
739
|
const firstStart=createFirstStart({stateDir,credentialPath:join(stateDir,'bili_credential.json'),headlessSync})
|
|
700
740
|
/**
|
|
701
|
-
*
|
|
702
|
-
*
|
|
703
|
-
*
|
|
704
|
-
* ⇒ 把 uv 的缓存 / 工具 / 解释器目录**全部钉在插件家里**(那儿一定可写)✓ ——
|
|
705
|
-
* 跟 `HF_HOME` 那次是同一类:"环境差异由插件自己消掉,别让用户碰"。
|
|
741
|
+
* uv/pip 下载缓存默认固定在插件数据目录,允许用户安全迁移缓存;
|
|
742
|
+
* uv 工具环境和下载的 Python 解释器只有在用户明确选择高级重建时才切换,
|
|
743
|
+
* 普通缓存迁移不会改变任何现有虚拟环境的绝对路径。
|
|
706
744
|
*/
|
|
707
|
-
const uvEnv = (extra = {}) =>
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
745
|
+
const uvEnv = (extra = {}) => storagePyEnv({
|
|
746
|
+
// uv/pip download caches may move independently without changing any live interpreter.
|
|
747
|
+
PIP_CACHE_DIR: storageDataPath(stateDir,'pip-cache'),
|
|
748
|
+
UV_CACHE_DIR: storageDataPath(stateDir,'uv-cache'),
|
|
749
|
+
// Tool environments and downloaded Python interpreters move only in explicit rebuild mode.
|
|
750
|
+
UV_TOOL_DIR: storageDataPath(stateDir,'uv-tools'),
|
|
751
|
+
UV_PYTHON_INSTALL_DIR: storageDataPath(stateDir,'uv-python'),
|
|
711
752
|
...extra,
|
|
712
753
|
})
|
|
713
754
|
|
|
@@ -733,7 +774,7 @@ export function apply(ctx, config) {
|
|
|
733
774
|
// ⇒ 原判据**只查了 bilibili_api**(0.1.2 修"假就绪"时留下的口子)⇒ 缺 `mcp` / `qrcode` 也照样说就绪 ✗
|
|
734
775
|
// ⇒ 三个都得有:bilibili_api(查数据)· mcp(跑那一轮的 MCP 服务器)· qrcode(画登录二维码)
|
|
735
776
|
const VENV_DEPS = ['bilibili_api', 'mcp', 'qrcode']
|
|
736
|
-
const missingVenvDeps = () => VENV_DEPS.filter((n) => !hasPkg(
|
|
777
|
+
const missingVenvDeps = () => VENV_DEPS.filter((n) => !hasPkg(storageDataPath(stateDir,'.venv'), n))
|
|
737
778
|
const venvReadyNow = () => existsSync(venvPython()) && missingVenvDeps().length === 0
|
|
738
779
|
const asrReadyNow = () => existsSync(asrPython()) && hasPkg(asrDir, 'faster_whisper')
|
|
739
780
|
const cfgFile = join(stateDir, 'config.json')
|
|
@@ -833,7 +874,7 @@ function reportMeta() {
|
|
|
833
874
|
dmWhitelist: '', dmStrangerOnce: false, dmStrangerAutonomyEnabled: false, dmP6Enabled: true, dmP6MaxBubbles: 3, naturalThoughtOwnerMinutes:2, naturalThoughtIntimateMinutes:5, naturalThoughtFamiliarMinutes:10, naturalThoughtStrangerMinutes:30, naturalThoughtChancePercent:25, dmStrangerMaxReplies: 1, dmStrangerFirstFixed: false,
|
|
834
875
|
dmApprovalEnabled: false, dmApprovalPhrase: '白饭🍚',
|
|
835
876
|
pluginDefaultModelProvider: '', pluginDefaultModelId: '', videoModelProvider: '', videoModelId: '', videoReasoningEffort: '', behaviorDecisionModelProvider: '', behaviorDecisionModelId: '', behaviorDecisionReasoningEffort: '', interactionModelProvider: '', interactionModelId: '', interactionReasoningEffort: '', interactionContextMode: 'compact', memeRulesModelProvider:'', memeRulesModelId:'', memeRulesReasoningEffort:'', memeRulesPrompt:'',
|
|
836
|
-
commentWatchReplies: false, commentWatchTop: false, commentAtEnabled: true, socialRhythmCrossChannelMinutes: 30, socialRhythmDailyPerPerson: 0, friendAtFeedbackEnabled:false, strangerInspirationEnabled:false, socialInvitationEnabled:false, socialInvitationAutoInspectEnabled:false, ownerCommentAgentEnabled:false, ownerCommentLikeEnabled:false, ownerCommentDraftEnabled:false, ownerCommentPublishEnabled:false, ownerCommentSocialPublishEnabled:false, ownerCommentNaturalAckEnabled:false, commentAtMode:'whitelist', commentAtWhitelist:'', commentTopCount: 5, commentTopVideoCount: 3, commentReplyHotCount: 12, backupDirectory: '',
|
|
877
|
+
commentWatchReplies: false, commentWatchTop: false, commentAtEnabled: true, socialRhythmCrossChannelMinutes: 30, socialRhythmDailyPerPerson: 0, friendAtFeedbackEnabled:false, strangerInspirationEnabled:false, socialInvitationEnabled:false, socialInvitationAutoInspectEnabled:false, ownerCommentAgentEnabled:false, ownerCommentLikeEnabled:false, ownerCommentDraftEnabled:false, ownerCommentPublishEnabled:false, ownerCommentSocialPublishEnabled:false, ownerCommentNaturalAckEnabled:false, commentAtMode:'whitelist', commentAtWhitelist:'', commentTopCount: 5, commentTopVideoCount: 3, commentReplyHotCount: 12, backupDirectory: '', backupAutoEnabled: true,
|
|
837
878
|
commentAllowGeneralTop: false, commentReplyPerPoll: 12, commentReplyPerDay: 1000, commentOwnTopPerUser: 5, commentOwnNestedPerUser: 3,
|
|
838
879
|
mainSessionBridgeEnabled: false, ownerSpontaneousChatEnabled:true, ownerContactPreset:'natural', ownerContactStartHour:9,ownerContactEndHour:22,ownerContactCooldownMinutes:240,ownerContactDailyLimit:2,ownerContactSilenceMinutes:45,mainSessionSilenceFollowupEnabled:true,mainSessionShortPauseEnabled:true,mainSessionShortPauseSeconds:90,ownerDmSilenceFollowupEnabled:true, mainSessionId: '', mainSessionAutoSync: true, mainSessionSyncMinutes: 60, mainSessionDailyBatches: 4, mainSessionBatchSize: 8, mainSessionIncludeComments: true,
|
|
839
880
|
mainSessionMemoryEnabled: true, mainSessionMemoryAutoBili: true, mainSessionMemorySemanticEnabled: false, mainSessionMemoryEmbeddingEnabled: false, mainSessionMemoryModelProvider: '', mainSessionMemoryModelId: '', mainSessionMemoryReasoningEffort: '', mainSessionMemoryCandidates: RECOMMENDED_EXPERIENCE_GROUPS.retrieval.mainSessionMemoryCandidates, mainSessionMemorySearchDailyLimit: RECOMMENDED_EXPERIENCE_GROUPS.retrieval.mainSessionMemorySearchDailyLimit, socialOutreachEnabled:true, socialLifeIntentEnabled:true, lifeProactiveFriendDmEnabled:false, lifeNaturalDmOutreachEnabled:false, lifePublicInteractionEnabled:false, socialVideoRecommendationsAuthorizedV2:true, emotionSystemEnabled:true, socialAutoSend:true, socialOutreachDailyLimit:0, ownerTodoAutoReviewEnabled:false, ownerTodoReviewMinutes:60, ownerTodoCompletionFollowupEnabled:false, socialTodoCompletionFollowupEnabled:false, ownerTodoFollowupCooldownMinutes:60, ownerTodoFollowupDailyLimit:12, ownerTodoFollowupMinIntervalMinutes:5, ownerTodoFollowupPollMinutes:2, ownerTodoFollowupQuietEnabled:true, ownerTodoFollowupQuietStartHour:22, ownerTodoFollowupQuietEndHour:9, autonomousPlannerEnabled:true, emotionRecallEnabled:false, emotionRecallMainEnabled:false, emotionRecallDmEnabled:false, emotionRecallUnlimited:false, emotionRecallDailyLimit:1, emotionRecallCooldownHours:24, emotionRecallStartHour:9, emotionRecallEndHour:22, ownerDmAgentEnabled:true, ownerDmAgentReadMainContext:false, ownerDmAgentSyncMain:false, ownerDmAgentContextTurns:6, ownerDmAgentContextChars:1500, ownerDmAgentModelProvider:'', ownerDmAgentModelId:'', ownerDmAgentReasoningEffort:'', ownerDmReadCommandsEnabled:true, ownerDmActionsEnabled:true, ownerDmLikeEnabled:true, ownerDmCollectEnabled:true, ownerDmFollowEnabled:true, ownerDmCommentDraftEnabled:true, ownerDmCommentPublishEnabled:true, ownerDmDynamicDraftEnabled:true, ownerDmDynamicPublishEnabled:true, ownerDmFriendMessageEnabled:true, emotionRecallCandidateLimit:12, emotionRecallHistoryLimit:300, emotionRecallRecentDays:3, emotionRecallMinAgeDays:2, emotionRecallEmotionMinIntensity:30, emotionRecallEmotionMaxAgeHours:12, autonomousPlannerMinutes:180, autonomousPlannerDailyLimit:4, autonomousPlannerStartHour:9, autonomousPlannerEndHour:23, mainSessionReflectionAuto: true, mainSessionReflectionModelProvider: '', mainSessionReflectionModelId: '', mainSessionReflectionReasoningEffort: '', mainSessionReflectionMinCandidates: RECOMMENDED_EXPERIENCE_GROUPS.reflection.mainSessionReflectionMinCandidates, mainSessionReflectionBatchSize: RECOMMENDED_EXPERIENCE_GROUPS.reflection.mainSessionReflectionBatchSize, mainSessionReflectionIntervalHours: RECOMMENDED_EXPERIENCE_GROUPS.reflection.mainSessionReflectionIntervalHours, mainSessionReflectionDailyBatches: RECOMMENDED_EXPERIENCE_GROUPS.reflection.mainSessionReflectionDailyBatches, mainSessionMemoryHalfLifeDays: RECOMMENDED_EXPERIENCE_GROUPS.recall.mainSessionMemoryHalfLifeDays, socialMemoryHalfLifeNewDays:1.3, socialMemoryHalfLifeKnownDays:3, socialMemoryHalfLifeFamiliarDays:10, socialMemoryHalfLifeFriendDays:24, socialMemoryHalfLifeWhitelistDays:30, socialMemoryHalfLifeOwnerDays:50, mainSessionMemoryThreshold: RECOMMENDED_EXPERIENCE_GROUPS.recall.mainSessionMemoryThreshold, mainSessionMemoryMaxItems: RECOMMENDED_EXPERIENCE_GROUPS.recall.mainSessionMemoryMaxItems, mainSessionMemoryMaxChars: RECOMMENDED_EXPERIENCE_GROUPS.recall.mainSessionMemoryMaxChars, mainSessionMemoryDailyQuota: RECOMMENDED_EXPERIENCE_GROUPS.recall.mainSessionMemoryDailyQuota, mainSessionMemoryConsolidationEnabled:true, mainSessionMemoryFactsMax: RECOMMENDED_EXPERIENCE_GROUPS.recall.mainSessionMemoryFactsMax,
|
|
@@ -911,6 +952,7 @@ function reportMeta() {
|
|
|
911
952
|
p.peakIntervalMinutes = Number.isFinite(n) && n >= 1 ? Math.min(720, n) : DEFAULT_PEAK_INTERVAL_MINUTES
|
|
912
953
|
}
|
|
913
954
|
if ('backupDirectory' in p) p.backupDirectory = String(p.backupDirectory || '').trim().slice(0,420)
|
|
955
|
+
if ('backupAutoEnabled' in p) p.backupAutoEnabled = p.backupAutoEnabled===true
|
|
914
956
|
if ('mainSessionBridgeEnabled' in p) p.mainSessionBridgeEnabled = p.mainSessionBridgeEnabled === true
|
|
915
957
|
if ('ownerSpontaneousChatEnabled' in p) p.ownerSpontaneousChatEnabled = p.ownerSpontaneousChatEnabled === true
|
|
916
958
|
for(const key of ['mainSessionSilenceFollowupEnabled','mainSessionShortPauseEnabled','ownerDmSilenceFollowupEnabled'])if(key in p)p[key]=p[key]===true
|
|
@@ -1582,6 +1624,8 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
1582
1624
|
let memoryRetriever = null
|
|
1583
1625
|
let lifeReflection = null
|
|
1584
1626
|
let lifeMemoryCoordinator = null
|
|
1627
|
+
const admittedOwnerFocusProofs=new WeakSet()
|
|
1628
|
+
let ownerGalleryFocusJob=null,ownerGalleryFocusBusy=false
|
|
1585
1629
|
let privateConversationExperiences = null
|
|
1586
1630
|
let socialInteractionCoordinator = null
|
|
1587
1631
|
let socialContextAssembler = null
|
|
@@ -1862,6 +1906,19 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
1862
1906
|
// through an isolated, read-only MCP with an ephemeral host instead.
|
|
1863
1907
|
const scopedDshVision=toolName==='bili_preview_vision'&&cfg.visionEnabled===true&&
|
|
1864
1908
|
resolvedVisionMode()==='independent_dsh'
|
|
1909
|
+
// The local Ollama video tool runs INSIDE the primary MCP (cfg.pythonPath).
|
|
1910
|
+
// Fail before fetching B站 frames when that actual interpreter cannot write
|
|
1911
|
+
// the published external cache. A healthy unrelated vision venv is not proof.
|
|
1912
|
+
if(toolName==='bili_preview_vision'&&cfg.visionEnabled===true&&
|
|
1913
|
+
resolvedVisionMode()==='independent_local'&&process.platform==='win32'&&
|
|
1914
|
+
storageLayout.domains.media.configured){
|
|
1915
|
+
let check
|
|
1916
|
+
try{check=await probeVisionPythonAsync(cfg.pythonPath||'',{home:stateDir,env:visionEnv(),requiresMcp:true,timeoutMs:5000})}
|
|
1917
|
+
catch{check={ok:false,reason:'vision_temp_unavailable'}}
|
|
1918
|
+
if(!check.ok)throw Error('视频实际 MCP Python 未通过外迁目录读写/依赖检查('+
|
|
1919
|
+
String(check.reason||'runtime_execution_failed')+' / '+String(check.stage||'unknown')+
|
|
1920
|
+
');已阻止本轮取帧,等待可信宿主运行时修复')
|
|
1921
|
+
}
|
|
1865
1922
|
const client=scopedDshVision?null:await ensureMcp()
|
|
1866
1923
|
if(scopedDshVision&&!assertSecureMcp())throw Error('DSH 视频识图 Python MCP 安全版本校验失败')
|
|
1867
1924
|
if(toolName!=='bili_check_credential')accountBinding.assertReady()
|
|
@@ -1884,6 +1941,44 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
1884
1941
|
} finally {release()}
|
|
1885
1942
|
}
|
|
1886
1943
|
|
|
1944
|
+
// Owner-only Debug uses an isolated one-shot Python MCP for local Ollama.
|
|
1945
|
+
// A timed-out Debug may stop only its own worker, never the shared Life/MCP.
|
|
1946
|
+
// The existing Python platform read budget and reservation remain mandatory.
|
|
1947
|
+
const callOwnerVideoDebugVision=async (args,{onStage,onDiagnostic}={})=>{
|
|
1948
|
+
if(resolvedVisionMode()!=='independent_local')return call('bili_preview_vision',args)
|
|
1949
|
+
const release=accountBinding.enterPlatformOperation()
|
|
1950
|
+
const originalAccount=trustedLifeAccountTag()
|
|
1951
|
+
try{
|
|
1952
|
+
accountBinding.assertReady()
|
|
1953
|
+
if(!originalAccount||!firstStart.isReady()||!hasCredential())throw Error('视频调试账号未核验')
|
|
1954
|
+
refreshCfg()
|
|
1955
|
+
if(cfg.masterEnabled!==true||cfg.visionEnabled!==true||resolvedVisionMode()!=='independent_local')
|
|
1956
|
+
throw Error('视频调试的本地视觉路由已改变')
|
|
1957
|
+
const startedAt=Date.now()
|
|
1958
|
+
onStage?.('worker-starting')
|
|
1959
|
+
const source=await ensureMcp() // verified production executable and environment
|
|
1960
|
+
// Leave time for owned-process cleanup and the 8m page watchdog.
|
|
1961
|
+
const remainingMs=450_000-(Date.now()-startedAt)
|
|
1962
|
+
if(remainingMs<1000)throw Error('视频 Debug 启动阶段已超过安全等待上限,未启动本次独立识图')
|
|
1963
|
+
let result
|
|
1964
|
+
try{result=await ownerDebugLocalVision(source,args,{onStage,onDiagnostic,timeoutMs:Math.min(420_000,Math.floor(remainingMs))})}
|
|
1965
|
+
catch(error){
|
|
1966
|
+
// A JSON-RPC timeout is not a completed visual receipt. The one-shot
|
|
1967
|
+
// worker's finally has already requested its process shutdown.
|
|
1968
|
+
if(error?.code==='owner_debug_worker_deadline'||/MCP .*超时/.test(String(error?.message||''))){
|
|
1969
|
+
const failure=Error('本地视频 Debug 超过 7 分钟总时限(含 Python 启动与识图),已终止本次专用工作进程的等待;没有取得完整视觉回执。')
|
|
1970
|
+
failure.code='owner_debug_visual_timeout'
|
|
1971
|
+
failure.phase=error?.phase||'unknown'
|
|
1972
|
+
throw failure
|
|
1973
|
+
}
|
|
1974
|
+
throw error
|
|
1975
|
+
}
|
|
1976
|
+
if(originalAccount!==trustedLifeAccountTag()||accountBinding.status().blocked)
|
|
1977
|
+
throw Error('视频调试期间账号已切换,拒绝使用旧账号视觉结果')
|
|
1978
|
+
return result
|
|
1979
|
+
}finally{release()}
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1887
1982
|
const hasCredential = () => existsSync(join(stateDir, 'bili_credential.json'))
|
|
1888
1983
|
|
|
1889
1984
|
/* ─────────────── 工具 ─────────────── */
|
|
@@ -2011,28 +2106,65 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2011
2106
|
const row=recentVideoFocusCues.get(videoDebugAccount()+':'+bvid)
|
|
2012
2107
|
return row&&row.expiresAt>Date.now()?row.observations:[]
|
|
2013
2108
|
}
|
|
2014
|
-
const videoDebugExpiry=
|
|
2109
|
+
const videoDebugExpiry=VIDEO_CACHE_RETENTION.capture
|
|
2015
2110
|
const videoDebugAccount=()=>String(accountBinding.accountUid()||'')
|
|
2016
2111
|
const safeVideoDebugCapture=(value,bvid)=>{
|
|
2017
2112
|
if(!value||value.bvid!==bvid||!(/^[a-f0-9]{32}$/).test(String(value.id||''))||
|
|
2018
|
-
!['storyboard','focus'].includes(value.kind)||!Array.isArray(value.images)
|
|
2113
|
+
!['storyboard','focus'].includes(value.kind)||!Array.isArray(value.images)||
|
|
2114
|
+
!Number.isSafeInteger(value.createdAt)||value.createdAt>Date.now()+60_000||Date.now()-value.createdAt>=videoDebugExpiry)return null
|
|
2019
2115
|
const images=value.images.slice(0,value.kind==='focus'?13:12).filter(x=>
|
|
2020
2116
|
x?.kind===value.kind&&/^(?:storyboard|focus)-\d{2}\.jpg$/.test(String(x.file||''))&&
|
|
2021
|
-
Array.isArray(x.times)&&x.times.length<=12&&x.times.every(t=>Number.isFinite(t)&&t>=0&&t<=
|
|
2022
|
-
.map(x=>
|
|
2117
|
+
Array.isArray(x.times)&&x.times.length<=12&&x.times.every(t=>Number.isFinite(t)&&t>=0&&t<=14400))
|
|
2118
|
+
.map(x=>{
|
|
2119
|
+
const cols=Number(x.gridCols),rows=Number(x.gridRows)
|
|
2120
|
+
const grid=Number.isSafeInteger(cols)&&Number.isSafeInteger(rows)&&cols>=1&&cols<=4&&rows>=1&&rows<=4&&
|
|
2121
|
+
cols*rows>=x.times.length?{gridCols:cols,gridRows:rows}:{}
|
|
2122
|
+
return {kind:x.kind,file:x.file,times:x.times,resolution:String(x.resolution||'').slice(0,45),...grid}
|
|
2123
|
+
})
|
|
2023
2124
|
if(!images.length)return null
|
|
2024
|
-
//
|
|
2025
|
-
// stale captures on the next observation after a process restart.
|
|
2026
|
-
const purge=setTimeout(()=>{try{rmSync(join(stateDir,'vision-perception-captures',value.id),
|
|
2027
|
-
{recursive:true,force:true})}catch{}},videoDebugExpiry)
|
|
2028
|
-
purge.unref?.()
|
|
2125
|
+
// Physical expiry is handled by the startup/periodic cache sweeper.
|
|
2029
2126
|
return {id:value.id,kind:value.kind,createdAt:Number(value.createdAt)||0,images}
|
|
2030
2127
|
}
|
|
2128
|
+
// Called only with fresh platform/model receipts inside verified read paths.
|
|
2129
|
+
// Exact event identity; no time/BV heuristic and no permanent archive fallback.
|
|
2130
|
+
const persistFreshVideoDetail=({event,bvid,info,visual,account})=>{
|
|
2131
|
+
if(!lifeMemory||!event||event.accountTag!==account||account!==trustedLifeAccountTag()||
|
|
2132
|
+
accountBinding.status().blocked||cfg.masterEnabled!==true||cfg.visionEnabled!==true||!hasCredential())
|
|
2133
|
+
return {ok:false,reason:'account-or-permission-changed'}
|
|
2134
|
+
const memoryId='e-'+createHash('sha256').update(event.key).digest('hex').slice(0,18)
|
|
2135
|
+
const sourceRef='observation:'+createHash('sha256').update(event.key).digest('hex').slice(0,32)
|
|
2136
|
+
const fragments=buildFreshVideoDetails({bvid,info,visual,event,sourceRef})
|
|
2137
|
+
if(!fragments.length)return {ok:false,reason:'no-fresh-detail-evidence'}
|
|
2138
|
+
const ownerSession=event.experience?.source==='main-session'
|
|
2139
|
+
const proof=Object.freeze({memoryId,accountTag:account,bvid,sourceRef,fragmentCount:fragments.length,
|
|
2140
|
+
visibility:ownerSession?'private-session':'public-event',at:Date.now()})
|
|
2141
|
+
admittedOwnerFocusProofs.add(proof)
|
|
2142
|
+
try{return {...lifeMemory.attachMemoryDetails({memoryId,accountTag:account,fragments,sourceProof:proof,ownerSession}),memoryId}}
|
|
2143
|
+
finally{admittedOwnerFocusProofs.delete(proof)}
|
|
2144
|
+
}
|
|
2031
2145
|
const executeWatchVideo = async(args={},internal={}) => {
|
|
2032
2146
|
const dryRun=args.__debugDryRun===true
|
|
2033
2147
|
const initialAccount=videoDebugAccount()
|
|
2034
2148
|
const initialLifeAccountTag=trustedLifeAccountTag()
|
|
2035
|
-
const
|
|
2149
|
+
const activeDebugJob=dryRun?videoDebugJob:null
|
|
2150
|
+
const stage=(label,step)=>{if(activeDebugJob&&videoDebugJob===activeDebugJob&&activeDebugJob.status==='running'){
|
|
2151
|
+
activeDebugJob.stage=label;if(Number.isInteger(step))activeDebugJob.step=step
|
|
2152
|
+
activeDebugJob.updatedAt=Date.now();saveVideoDebugSummary(stateDir,activeDebugJob,initialAccount)}}
|
|
2153
|
+
const onVisualDiagnostic=diagnostic=>{
|
|
2154
|
+
if(!activeDebugJob||videoDebugJob!==activeDebugJob||activeDebugJob.status!=='running'||
|
|
2155
|
+
videoDebugAccount()!==initialAccount)return
|
|
2156
|
+
activeDebugJob.visualDiagnostic={...activeDebugJob.visualDiagnostic,
|
|
2157
|
+
phase:activeDebugJob.visualDiagnostic?.phase||'model-running',at:Date.now(),ollama:diagnostic}
|
|
2158
|
+
activeDebugJob.updatedAt=Date.now()
|
|
2159
|
+
saveVideoDebugSummary(stateDir,activeDebugJob,initialAccount)
|
|
2160
|
+
}
|
|
2161
|
+
const onVisualStage=phase=>{
|
|
2162
|
+
if(!activeDebugJob||videoDebugJob!==activeDebugJob||activeDebugJob.status!=='running'||
|
|
2163
|
+
videoDebugAccount()!==initialAccount)return
|
|
2164
|
+
activeDebugJob.visualDiagnostic={...activeDebugJob.visualDiagnostic,phase,at:Date.now()}
|
|
2165
|
+
activeDebugJob.updatedAt=Date.now()
|
|
2166
|
+
saveVideoDebugSummary(stateDir,activeDebugJob,initialAccount)
|
|
2167
|
+
}
|
|
2036
2168
|
refreshCfg()
|
|
2037
2169
|
if(cfg.masterEnabled!==true&&!dryRun)return {ok:false,blocked:true,error:'大肥鱼总开关已关闭'}
|
|
2038
2170
|
if(!hasCredential())return {ok:false,loggedIn:false,error:'B站尚未登录,请先扫码登录'}
|
|
@@ -2072,7 +2204,7 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2072
2204
|
willInvokeVision&&earlyVisionPlan.depth!=='skim'
|
|
2073
2205
|
const samplerDepth=fullGlobalPreview?'deep':earlyVisionPlan.depth
|
|
2074
2206
|
const visualPromise=willInvokeVision?beginVideoObservationRead(()=>
|
|
2075
|
-
call('bili_preview_vision',{bvid,
|
|
2207
|
+
(dryRun?args=>callOwnerVideoDebugVision(args,{onStage:onVisualStage,onDiagnostic:onVisualDiagnostic}):args=>call('bili_preview_vision',args))({bvid,
|
|
2076
2208
|
perception_source:lifeGlobalOverview?'preview':'adaptive',view_depth:samplerDepth,
|
|
2077
2209
|
// Only the localhost owner Debug endpoint may choose a different
|
|
2078
2210
|
// source; real Life and main-Session reads retain their existing gates.
|
|
@@ -2082,9 +2214,11 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2082
2214
|
focus_start_seconds:args.focus_start_seconds,focus_end_seconds:args.focus_end_seconds,
|
|
2083
2215
|
network_budget_bytes:args.network_budget_bytes,frame_budget_limit:args.frame_budget_limit
|
|
2084
2216
|
}:{}),
|
|
2085
|
-
...(dryRun?{capture_for_debug:true}:{})}),elapsed=>{
|
|
2217
|
+
...(dryRun?{capture_for_debug:true}:internal.lifeChoiceVerified===true&&args.record_session===false?{capture_for_gallery:true}:{})}),elapsed=>{
|
|
2086
2218
|
visionFinishedAt=Date.now();visualReadMs=elapsed
|
|
2087
|
-
}).catch(e=>({ok:false
|
|
2219
|
+
}).catch(e=>({ok:false,...(dryRun&&e?.code==='owner_debug_visual_timeout'?{
|
|
2220
|
+
status:'vision_unavailable',errorCode:'owner_debug_visual_timeout'}:{}),
|
|
2221
|
+
error:String(e?.message||e).slice(0,180)}))
|
|
2088
2222
|
:Promise.resolve(null)
|
|
2089
2223
|
stage(willInvokeVision?'字幕/Whisper 与已获授权的视觉读取并行中':'读取字幕/检查本地 Whisper 转写条件',2)
|
|
2090
2224
|
const speechStartedAt=Date.now()
|
|
@@ -2224,7 +2358,9 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2224
2358
|
// A successful, verifiable exploration is a B站 life experience even when
|
|
2225
2359
|
// record_session=false. This is NOT a main-Session watch receipt.
|
|
2226
2360
|
// No raw third-party comments, private text or model guesses are saved.
|
|
2227
|
-
|
|
2361
|
+
let memoryWrite={status:dryRun?'not-recorded-debug':parseMaybeJson(vision)?.status==='cached'?'not-recorded-cached':'not-recorded'}
|
|
2362
|
+
if(!dryRun&&(!isLifeEpisodeFocus||focusIsVerifiedAndNovel)&&
|
|
2363
|
+
!(args.record_session===false&&parseMaybeJson(vision)?.status==='cached'))try{
|
|
2228
2364
|
const normalized=x=>{if(typeof x!=='string')return x;try{return JSON.parse(x)}catch{return {text:x}}}
|
|
2229
2365
|
const event=buildVideoExplorationEvent({bvid,info:normalized(info),
|
|
2230
2366
|
subtitle:normalized(subtitle),comments:normalized(comments),
|
|
@@ -2233,9 +2369,16 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2233
2369
|
accountTag:initialLifeAccountTag,focusReview,integratedVisualNotes,
|
|
2234
2370
|
purpose:args.explorationPurpose||(args.record_session===false?'self-exploration':'main-session'),operationId:randomUUID(),
|
|
2235
2371
|
autonomousSelected:internal.lifeChoiceVerified===true&&args.record_session===false})
|
|
2236
|
-
if(event){const synced=await lifeMemoryCoordinator?.recordEvents([event],{reflect:true});if(!synced)throw Error('人生记忆协调器尚未就绪');
|
|
2372
|
+
if(event&&(!initialLifeAccountTag||initialLifeAccountTag===trustedLifeAccountTag())){const synced=await lifeMemoryCoordinator?.recordEvents([event],{reflect:true});if(!synced)throw Error('人生记忆协调器尚未就绪');memoryWrite={status:synced.skipped==='cached-visual'?'not-recorded-cached':synced.ok===false?'coordination-pending':'recorded',detailStatus:'not-recorded'}
|
|
2373
|
+
if(synced.ok===false)log('视频经历已进入待补偿队列:'+String(synced.lastError||synced.reason||'unknown').slice(0,100))
|
|
2374
|
+
if((args.record_session!==false||internal.lifeChoiceVerified===true)&&normalized(vision)?.status==='analyzed'){
|
|
2375
|
+
const detail=persistFreshVideoDetail({event,bvid,info:normalized(info),visual:normalized(vision),account:initialLifeAccountTag})
|
|
2376
|
+
memoryWrite={...memoryWrite,detailStatus:detail.ok?'recorded':'not-recorded',...(detail.ok?{memoryId:detail.memoryId}:{detailReason:detail.reason||'write-failed'})}
|
|
2377
|
+
log('Life 深层观察附件:'+(detail.ok?'已写入 '+detail.memoryId:String(detail.reason||'write-failed')))
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2237
2380
|
else log('视频探索没有可验证的标题/资料,不生成生活观看经历:'+bvid)
|
|
2238
|
-
}catch(e){log('视频探索经历写入失败(不影响只读查看):'+String(e?.message||e).slice(0,120))}
|
|
2381
|
+
}catch(e){memoryWrite={status:'write-failed'};log('视频探索经历写入失败(不影响只读查看):'+String(e?.message||e).slice(0,120))}
|
|
2239
2382
|
// Evidence provenance is read-only; it never grants a video write action.
|
|
2240
2383
|
stage('校验画面来源、整合多模态证据与 Life 输入',5)
|
|
2241
2384
|
const assemblyStartedAt=Date.now()
|
|
@@ -2271,7 +2414,7 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2271
2414
|
try{await call('bili_ledger_mark',{bvid,title:String(info?.title||bvid),up:String(info?.author||''),status:'主 Session 指定观看'})}catch(e){log('主 Session 指定观看判重记账失败:'+String(e?.message||e).slice(0,100))}
|
|
2272
2415
|
try{await call('bili_session_watch_mark',{bvid,title:String(info?.title||bvid),up:String(info?.author||'')})}catch(e){log('主 Session 指定观看经历记账失败:'+String(e?.message||e).slice(0,100))}
|
|
2273
2416
|
}
|
|
2274
|
-
const lifePayload={ok:true,action:'watch',bvid,viewDepth:visionPlan.depth,visionDecision:visionPlan.reason,info,videoEvidence,perceptionTimeline,perceptionHandoff,subtitle:subtitle||{message:'未取得字幕'},comments:comments||{message:'未读取评论'},danmaku:danmaku||{message:'未读取弹幕'},visual:vision||{status:cfg.visionEnabled?'视觉模式未提供独立文本结果':'未启用可供主 Session 使用的独立视觉识别'},
|
|
2417
|
+
const lifePayload={ok:true,action:'watch',bvid,memoryWrite,viewDepth:visionPlan.depth,visionDecision:visionPlan.reason,info,videoEvidence,perceptionTimeline,perceptionHandoff,subtitle:subtitle||{message:'未取得字幕'},comments:comments||{message:'未读取评论'},danmaku:danmaku||{message:'未读取弹幕'},visual:vision||{status:cfg.visionEnabled?'视觉模式未提供独立文本结果':'未启用可供主 Session 使用的独立视觉识别'},
|
|
2275
2418
|
focusReviewStatus:focusReviewStatus||'not-needed',
|
|
2276
2419
|
...(focusPlan?.status==='ready' ? {focusReviewSuggestion:{
|
|
2277
2420
|
kind:'life-choice-only',at_seconds:Math.round((focusPlan.startSeconds+focusPlan.endSeconds)*50)/100,
|
|
@@ -2280,6 +2423,10 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2280
2423
|
notice:'此为已核验视频采样候选,未执行额外观看;只有 Life 重新选择且通过既有只读门禁后才能复查。'}} : {}),
|
|
2281
2424
|
speechAttempt,
|
|
2282
2425
|
phaseDiagnostics:{schema:'life-video-phase-diagnostics/v1',metadataMs,
|
|
2426
|
+
visualRequestedDepth:visionPlan.depth,
|
|
2427
|
+
visualSamplerDepth:willInvokeVision?samplerDepth:'not-invoked',
|
|
2428
|
+
visualSource:willInvokeVision?(dryRun?debugPerceptionSource:(lifeGlobalOverview?'preview':'adaptive')):'not-invoked',
|
|
2429
|
+
globalOverviewMode:fullGlobalPreview?'full-global':'ordinary',
|
|
2283
2430
|
speechMs:speechReadMs,visualMs:visualReadMs,
|
|
2284
2431
|
subtitleToolMs,asrToolMs,
|
|
2285
2432
|
...(asrMcpTimings?{asrMcpTimings}:{}),
|
|
@@ -2314,6 +2461,24 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2314
2461
|
const retire=setTimeout(()=>{if(lastLifeVideoDebug===record)lastLifeVideoDebug=null},videoDebugExpiry)
|
|
2315
2462
|
retire.unref?.()
|
|
2316
2463
|
}
|
|
2464
|
+
// dev.4: genuine Life observation JPEG copies are display-only, scoped to
|
|
2465
|
+
// the verified current account and automatically expire within 24h.
|
|
2466
|
+
// A gallery entry is never treated as a durable or recallable memory.
|
|
2467
|
+
if(!dryRun&&internal.lifeChoiceVerified===true&&args.record_session===false&&debugImages.length&&
|
|
2468
|
+
initialLifeAccountTag&&initialLifeAccountTag===trustedLifeAccountTag()&&
|
|
2469
|
+
initialAccount===videoDebugAccount()){
|
|
2470
|
+
try{
|
|
2471
|
+
const proof=verifyEpisodeVideoVisual({result:lifePayload,bvid,depth:visionPlan.depth})
|
|
2472
|
+
if(proof||focusIsVerifiedAndNovel){
|
|
2473
|
+
const result=addLifeVideoGallery(stateDir,{account:initialLifeAccountTag,bvid,
|
|
2474
|
+
captures:debugImages,verified:true,phase:args.explorationPurpose?.includes('focus')?'focus':'global',
|
|
2475
|
+
groupId:String(internal.lifeGalleryGroupId||''),
|
|
2476
|
+
note:String(perceptionHandoff?.video?.modelDescription||'').slice(0,380),
|
|
2477
|
+
analysis:parseMaybeJson(vision)?.description,boardReceipts:parseMaybeJson(vision)?.visionBoardReceipts,memoryWrite})
|
|
2478
|
+
if(result.ok!==true)log('Life 视觉回放图片未保存:'+String(result.reason||'unknown'))
|
|
2479
|
+
}
|
|
2480
|
+
}catch(error){log('Life 视觉回放图片异常:'+String(error.message||error).slice(0,100))}
|
|
2481
|
+
}
|
|
2317
2482
|
if(dryRun&&videoDebugJob?.account===initialAccount)videoDebugJob.images=debugImages
|
|
2318
2483
|
stage('Life 输入已生成(调试试运行:未记账、未写记忆)',6)
|
|
2319
2484
|
return lifePayload
|
|
@@ -2338,12 +2503,13 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2338
2503
|
if(cfg.masterEnabled!==true||!hasCredential())return {ok:false,reason:'video-unavailable'}
|
|
2339
2504
|
const bvid=String(args.bvid||'').trim()
|
|
2340
2505
|
if(!validBv(bvid))return {ok:false,reason:'invalid-bv'}
|
|
2506
|
+
const visualGroupId=randomUUID().replaceAll('-','')
|
|
2341
2507
|
const overview=await runLifeChosenVideoRead({willingness:lifeWillingness,getAccountTag:trustedLifeAccountTag,
|
|
2342
2508
|
bvid,mode:'new',read:async({viewDepth,account})=>{
|
|
2343
2509
|
if(account!==trustedLifeAccountTag())return {ok:false,reason:'account-changed'}
|
|
2344
2510
|
const read=()=>executeWatchVideo({bvid,include_comments:true,include_danmaku:true,
|
|
2345
2511
|
record_session:false,view_depth:viewDepth,explorationPurpose:'life-voluntary-new-video'},
|
|
2346
|
-
{lifeChoiceVerified:true})
|
|
2512
|
+
{lifeChoiceVerified:true,lifeGalleryGroupId:visualGroupId})
|
|
2347
2513
|
if(!['standard','deep'].includes(viewDepth))return read()
|
|
2348
2514
|
return withLifeVideoVisualLease(stateDir,{accountTag:account,bvid},async()=>{
|
|
2349
2515
|
if(account!==trustedLifeAccountTag())return {ok:false,reason:'account-changed'}
|
|
@@ -2378,22 +2544,34 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2378
2544
|
try{visual=parseMaybeJson(await call('bili_preview_vision',{
|
|
2379
2545
|
bvid,perception_source:'adaptive',view_depth:'deep',
|
|
2380
2546
|
focus_start_seconds:plan.startSeconds,focus_end_seconds:plan.endSeconds,
|
|
2381
|
-
network_budget_bytes:networkBudgetBytes,frame_budget_limit:frameBudgetLimit
|
|
2547
|
+
network_budget_bytes:networkBudgetBytes,frame_budget_limit:frameBudgetLimit,
|
|
2548
|
+
capture_for_gallery:true}))}
|
|
2382
2549
|
catch{return {ok:false,reason:'focus-read-failed'}}
|
|
2383
2550
|
finally{stop()}
|
|
2384
2551
|
if(account!==trustedLifeAccountTag())return {ok:false,reason:'account-changed'}
|
|
2552
|
+
const focusCapture=safeVideoDebugCapture(visual?.debugCapture,bvid)
|
|
2553
|
+
if(visual&&typeof visual==='object')delete visual.debugCapture
|
|
2385
2554
|
const focusedEvidence=buildVideoEvidenceBundle({bvid,info:overview.info,visual})
|
|
2386
2555
|
const review=verifyVideoFocusReview({bvid,
|
|
2387
2556
|
plan:{...plan,status:'ready',networkBudgetBytes},result:visual,evidence:focusedEvidence})
|
|
2388
2557
|
if(!review)return {ok:false,reason:'focused-evidence-not-verified'}
|
|
2558
|
+
let memoryWrite={status:visual?.status==='cached'?'not-recorded-cached':'not-recorded'}
|
|
2389
2559
|
try{
|
|
2390
2560
|
const event=buildVideoExplorationEvent({bvid,info:overview.info,visual,
|
|
2391
2561
|
source:'bili-life',purpose:'life-voluntary-focus-read',
|
|
2392
|
-
operationId:randomUUID(),autonomousSelected:true})
|
|
2393
|
-
if(event){event.experience.focusWindow={startMs:review.startMs,endMs:review.endMs,
|
|
2562
|
+
operationId:randomUUID(),autonomousSelected:true,accountTag:account})
|
|
2563
|
+
if(event&&visual?.status==='analyzed'&&account===trustedLifeAccountTag()){event.experience.focusWindow={startMs:review.startMs,endMs:review.endMs,
|
|
2394
2564
|
frames:review.frameTimesMs.length,source:review.source}
|
|
2395
|
-
await lifeMemoryCoordinator?.recordEvents([event],{reflect:true})
|
|
2396
|
-
|
|
2565
|
+
const stored=await lifeMemoryCoordinator?.recordEvents([event],{reflect:true})
|
|
2566
|
+
memoryWrite={status:stored?.ok===true?'recorded':'coordination-pending'}
|
|
2567
|
+
const detail=persistFreshVideoDetail({event,bvid,info:overview.info,visual,account})
|
|
2568
|
+
memoryWrite={...memoryWrite,detailStatus:detail.ok?'recorded':'not-recorded',detailReason:detail.reason||''}
|
|
2569
|
+
log('Life 批量局部深层附件:'+(detail.ok?'已写入 '+detail.memoryId:String(detail.reason||'write-failed')))}
|
|
2570
|
+
}catch{memoryWrite={status:'write-failed'};log('Life 真实局部复查记忆待补偿;不影响只读视觉回执')}
|
|
2571
|
+
if(focusCapture&&account===trustedLifeAccountTag()&&!accountBinding.status().blocked)try{
|
|
2572
|
+
addLifeVideoGallery(stateDir,{account,bvid,captures:[focusCapture],verified:true,groupId:visualGroupId,
|
|
2573
|
+
phase:'focus',note:String(review.description||'').slice(0,380),analysis:visual?.description,boardReceipts:visual?.visionBoardReceipts,memoryWrite})
|
|
2574
|
+
}catch(e){log('Life 局部图片展示副本保存失败:'+String(e?.message||e).slice(0,100))}
|
|
2397
2575
|
return {ok:true,review}
|
|
2398
2576
|
}})
|
|
2399
2577
|
return {...overview,postOverviewFocus,
|
|
@@ -2444,7 +2622,7 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2444
2622
|
job.stage='Life 已自主选中局部,正在逐段解码与识图(已完成 '+focusedVisuals.length+' 段)'
|
|
2445
2623
|
job.updatedAt=Date.now()
|
|
2446
2624
|
let visual
|
|
2447
|
-
try{visual=parseMaybeJson(await
|
|
2625
|
+
try{visual=parseMaybeJson(await callOwnerVideoDebugVision({
|
|
2448
2626
|
bvid,perception_source:'adaptive',view_depth:'deep',
|
|
2449
2627
|
focus_start_seconds:plan.startSeconds,focus_end_seconds:plan.endSeconds,
|
|
2450
2628
|
network_budget_bytes:networkBudgetBytes,frame_budget_limit:frameBudgetLimit,
|
|
@@ -2503,9 +2681,12 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2503
2681
|
return {ok:false,reason:'vision-not-enabled',error:'尚未启用独立视觉识别'}
|
|
2504
2682
|
const bvid=String(args.bvid||'').trim()
|
|
2505
2683
|
if(!validBv(bvid))return {ok:false,reason:'invalid-bv'}
|
|
2684
|
+
const requestedAccount=trustedLifeAccountTag()
|
|
2685
|
+
if(!requestedAccount||accountBinding.status().blocked)return {ok:false,reason:'video-account-not-ready'}
|
|
2506
2686
|
let info
|
|
2507
2687
|
try{info=parseMaybeJson(await call('bili_video_info',{bvid}))}
|
|
2508
2688
|
catch{return {ok:false,reason:'video-metadata-unavailable'}}
|
|
2689
|
+
if(requestedAccount!==trustedLifeAccountTag()||accountBinding.status().blocked)return {ok:false,reason:'account-changed'}
|
|
2509
2690
|
const durationSeconds=Number(info?.duration)
|
|
2510
2691
|
const plan=planVideoMomentFollowup({bvid,atSeconds:args.at_seconds,
|
|
2511
2692
|
afterSeconds:args.after_seconds,description:args.event_cue,
|
|
@@ -2513,39 +2694,65 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
2513
2694
|
if(!plan.ok)return {ok:false,...plan}
|
|
2514
2695
|
return runLifeChosenVideoRead({willingness:lifeWillingness,getAccountTag:trustedLifeAccountTag,
|
|
2515
2696
|
bvid,mode:'revisit',read:async({account})=>{
|
|
2516
|
-
if(account!==trustedLifeAccountTag())return {ok:false,reason:'account-changed'}
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2697
|
+
if(account!==requestedAccount||account!==trustedLifeAccountTag())return {ok:false,reason:'account-changed'}
|
|
2698
|
+
return withLifeVideoVisualLease(stateDir,{accountTag:account,bvid},async()=>{
|
|
2699
|
+
refreshCfg()
|
|
2700
|
+
if(account!==trustedLifeAccountTag()||accountBinding.status().blocked||cfg.masterEnabled!==true||cfg.visionEnabled!==true||!hasCredential()||!['independent_dsh','independent_local'].includes(resolvedVisionMode()))return {ok:false,reason:'video-read-no-longer-authorized'}
|
|
2701
|
+
const budget=Number(cfg.visionFrames)>=48?100*1048576:Number(cfg.visionFrames)>=24?50*1048576:24*1048576
|
|
2702
|
+
let visual
|
|
2703
|
+
const stopVideoObserve=liveLifeActivity.start('video-observe',account,{maxAgeMs:8*60_000,bvid})
|
|
2704
|
+
try{visual=parseMaybeJson(await call('bili_preview_vision',{bvid,perception_source:'adaptive',
|
|
2705
|
+
view_depth:'deep',focus_start_seconds:plan.startSeconds,focus_end_seconds:plan.endSeconds,
|
|
2706
|
+
network_budget_bytes:budget,capture_for_gallery:true}))}
|
|
2707
|
+
catch(e){return {ok:false,reason:'focus-read-failed',error:String(e?.message||e).slice(0,160)}}
|
|
2708
|
+
finally{stopVideoObserve()}
|
|
2709
|
+
refreshCfg()
|
|
2710
|
+
if(account!==trustedLifeAccountTag()||accountBinding.status().blocked||cfg.masterEnabled!==true||cfg.visionEnabled!==true||!hasCredential()||!['independent_dsh','independent_local'].includes(resolvedVisionMode()))return {ok:false,reason:'video-read-no-longer-authorized'}
|
|
2711
|
+
const focusCapture=safeVideoDebugCapture(visual?.debugCapture,bvid)
|
|
2712
|
+
if(visual&&typeof visual==='object')delete visual.debugCapture
|
|
2713
|
+
const evidence=buildVideoEvidenceBundle({bvid,info,visual})
|
|
2714
|
+
const confirmed=verifyVideoFocusReview({bvid,plan:{...plan,networkBudgetBytes:budget},result:visual,evidence})
|
|
2715
|
+
if(!confirmed)return {ok:false,reason:'focus-receipt-unverified',
|
|
2716
|
+
error:String(visual?.error||visual?.status||'未取得可信复查结果').slice(0,130)}
|
|
2717
|
+
if(visual.status==='cached')return {ok:true,bvid,source:'decoded-public-video-focus',status:'reused-cached-window',review:confirmed,experienceState:'not-recorded-cached',noExternalActions:true}
|
|
2718
|
+
// Store bounded model observations under the exact new episode. Raw
|
|
2719
|
+
// answers and image bytes are not permanent memory; do not guess a
|
|
2720
|
+
// link to a historical episode simply from the same BV.
|
|
2721
|
+
let memoryState='not-recorded',deepMemory={status:'not-recorded'}
|
|
2722
|
+
try{
|
|
2723
|
+
const event=buildVideoExplorationEvent({bvid,info,visual,source:'bili-life',
|
|
2724
|
+
purpose:'life-voluntary-focus-read',operationId:randomUUID(),autonomousSelected:true,accountTag:account})
|
|
2725
|
+
if(event){
|
|
2726
|
+
event.note='自主补看一个已核实的公开视频时间窗口'
|
|
2727
|
+
event.experience.focusWindow={startMs:confirmed.startMs,endMs:confirmed.endMs,
|
|
2728
|
+
frames:confirmed.frameTimesMs.length,source:'decoded-public-video-focus'}
|
|
2729
|
+
const stored=await lifeMemoryCoordinator?.recordEvents([event],{reflect:true})
|
|
2730
|
+
memoryState=stored?.ok===true?'recorded': 'pending-retry'
|
|
2731
|
+
refreshCfg()
|
|
2732
|
+
// Use the exact newly persisted event identity, never a nearby BV match.
|
|
2733
|
+
if(stored?.ok===true&&account===trustedLifeAccountTag()&&!accountBinding.status().blocked&&cfg.masterEnabled===true&&cfg.visionEnabled===true&&hasCredential()&&lifeMemory){
|
|
2734
|
+
const memoryId='e-'+createHash('sha256').update(event.key).digest('hex').slice(0,18)
|
|
2735
|
+
const sourceRef='focus:'+randomUUID().replaceAll('-','')
|
|
2736
|
+
const verifiedFragments=buildFreshVideoDetails({bvid,info,visual,event,sourceRef})
|
|
2737
|
+
const proof=Object.freeze({memoryId,accountTag:account,bvid,sourceRef,fragmentCount:verifiedFragments.length,at:Date.now()})
|
|
2738
|
+
admittedOwnerFocusProofs.add(proof)
|
|
2739
|
+
try{
|
|
2740
|
+
const result=lifeMemory.recordVerifiedFocusRevision({memoryId,accountTag:account,bvid,review:confirmed,sourceProof:proof,sourceRef,verifiedFragments})
|
|
2741
|
+
deepMemory=result.ok?{status:'updated',memoryId,shallowVersion:result.shallowVersion,deepFragments:result.deepFragments}:
|
|
2742
|
+
{status:result.detailPersisted?'partial':'not-updated',reason:result.reason}
|
|
2743
|
+
}finally{admittedOwnerFocusProofs.delete(proof)}
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
}catch(e){log('Life 补看证据记账暂不可用:'+String(e?.message||e).slice(0,90))}
|
|
2747
|
+
if(focusCapture&&account===trustedLifeAccountTag()&&!accountBinding.status().blocked)try{
|
|
2748
|
+
addLifeVideoGallery(stateDir,{account,bvid,captures:[focusCapture],verified:true,
|
|
2749
|
+
phase:'focus',note:String(confirmed.description||'').slice(0,380),analysis:visual?.description,boardReceipts:visual?.visionBoardReceipts,memoryWrite:{status:memoryState,detailStatus:deepMemory.status,detailReason:deepMemory.reason}})
|
|
2750
|
+
}catch(e){log('Life 指定时刻回放图片保存失败:'+String(e?.message||e).slice(0,100))}
|
|
2751
|
+
return {ok:true,bvid,source:'decoded-public-video-focus',status:'observed-new-window',
|
|
2752
|
+
anchorSeconds:plan.anchorSeconds,origin:plan.origin,review:confirmed,experienceState:memoryState,deepMemory,
|
|
2753
|
+
limits:['sampled-window-only','not-full-video-playback','no-audio-perception',
|
|
2754
|
+
'new-observation-does-not-prove-prior-knowledge'],noExternalActions:true}
|
|
2755
|
+
})
|
|
2549
2756
|
}})
|
|
2550
2757
|
}
|
|
2551
2758
|
})
|
|
@@ -3519,7 +3726,7 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
3519
3726
|
let visionPythonCache=null
|
|
3520
3727
|
const selectHealthyVisionPython=({fresh=false}={})=>{
|
|
3521
3728
|
if(process.platform!=='win32')return {ok:true,path:cfg.pythonPath||'python',source:'configured',reason:'healthy'}
|
|
3522
|
-
const key=JSON.stringify([cfg.pythonPath,cfg.visionPythonPath,process.env.BILI_DUTY_VISION_PYTHON])
|
|
3729
|
+
const key=JSON.stringify([cfg.pythonPath,cfg.visionPythonPath,process.env.BILI_DUTY_VISION_PYTHON,storageDomainRoot(stateDir,'media')])
|
|
3523
3730
|
if(!fresh&&visionPythonCache?.key===key&&Date.now()-visionPythonCache.at<120000)return visionPythonCache.result
|
|
3524
3731
|
// The user-selected vision interpreter is the first candidate. Do not let
|
|
3525
3732
|
// an unhealthy main .venv mask a missing MCP package in the chosen Conda Python.
|
|
@@ -3535,9 +3742,10 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
3535
3742
|
// Explicit one-click repair from the management UI; never runs installers
|
|
3536
3743
|
// on boot, never modifies the main .venv or sends Bilibili requests.
|
|
3537
3744
|
const visionEnvironmentRepair=createVisionEnvironmentRepair({
|
|
3538
|
-
home:stateDir,workdir:process.cwd(),
|
|
3745
|
+
home:stateDir,workdir:process.cwd(),runtimeRoot:storagePythonRuntimeRoot(stateDir),
|
|
3539
3746
|
requirementsFile:join(pluginDir,'vendor','bilibili-mcp','requirements.txt'),
|
|
3540
|
-
|
|
3747
|
+
// Repair and real video MCP must probe the same published modelData cache.
|
|
3748
|
+
env:storagePyEnv({BILI_DUTY_HOME:stateDir}),
|
|
3541
3749
|
configured:()=>cfg.pythonPath||'',preferred:()=>cfg.visionPythonPath||'',
|
|
3542
3750
|
persist:async path=>{
|
|
3543
3751
|
const saved=await persistCfg({visionPythonPath:path})
|
|
@@ -3560,16 +3768,21 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
3560
3768
|
let environment
|
|
3561
3769
|
try{environment=visionEnv()}
|
|
3562
3770
|
catch{return {status:'unhealthy',reason:'vision_temp_unavailable',checked:0}}
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
|
|
3771
|
+
// Ollama executes in cfg.pythonPath inside the primary MCP. A healthy
|
|
3772
|
+
// independent vision candidate must not make this production route green.
|
|
3773
|
+
const candidates=resolvedVisionMode()==='independent_local'
|
|
3774
|
+
?[cfg.pythonPath||'']
|
|
3775
|
+
:visionPythonCandidates({preferred:cfg.visionPythonPath||'',configured:cfg.pythonPath||'',
|
|
3776
|
+
home:stateDir,workdir:process.cwd(),env:environment,platform:'win32'}).slice(0,4)
|
|
3777
|
+
let reason='missing_runtime',stage='',checked=0
|
|
3566
3778
|
for(const python of candidates){
|
|
3567
3779
|
const check=await probeVisionPythonAsync(python,{home:stateDir,env:environment,requiresMcp:true,timeoutMs:3000})
|
|
3568
3780
|
checked++
|
|
3569
3781
|
if(check.ok)return {status:'healthy',reason:'healthy',checked}
|
|
3570
3782
|
reason=check.reason||reason
|
|
3783
|
+
stage=check.stage||''
|
|
3571
3784
|
}
|
|
3572
|
-
return {status:'unhealthy',reason,checked}
|
|
3785
|
+
return {status:'unhealthy',reason,stage,checked}
|
|
3573
3786
|
})().catch(()=>({status:'unhealthy',reason:'runtime_execution_failed',checked:0}))
|
|
3574
3787
|
visualHealthCheck={at:Date.now(),promise}
|
|
3575
3788
|
return promise
|
|
@@ -3644,6 +3857,9 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
3644
3857
|
' BILI_MCP_TOOLS: '+yq(isSelftest?'bili_vision_selftest':'bili_preview_vision'),
|
|
3645
3858
|
...(isSelftest?[' BILI_VISION_SELFTEST_ALLOWED: '+yq('1'), ' BILI_VISION_TEST_ASSET: '+yq(posix(join(pluginDir,'lib','assets','local-vision-selftest-dafeiyu.png')))]:[' BILI_VISION_CHILD: '+yq('1')]),
|
|
3646
3859
|
' BILI_DUTY_HOME: '+yq(posix(stateDir)),
|
|
3860
|
+
' HF_HOME: '+yq(posix(storageDataPath(stateDir,'.hf-cache'))),
|
|
3861
|
+
' DSH_WHISPER_LIBRARY_HOME: '+yq(posix(largeDataStatus(stateDir).whisperHome||'')),
|
|
3862
|
+
' DSH_MEDIA_CACHE_HOME: '+yq(posix(storageDomainRoot(stateDir,'media'))),
|
|
3647
3863
|
' TEMP: '+yq(posix(visionTempPath(stateDir))),
|
|
3648
3864
|
' TMP: '+yq(posix(visionTempPath(stateDir))),
|
|
3649
3865
|
' TMPDIR: '+yq(posix(visionTempPath(stateDir))),
|
|
@@ -3711,7 +3927,7 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
3711
3927
|
if(process.platform!=='win32')return null
|
|
3712
3928
|
return startProductionVisionHostExecutor({
|
|
3713
3929
|
home:stateDir,exe:dsh.command,cli:dsh.args[1],baseOverlay:overlay,
|
|
3714
|
-
workdir:process.cwd(),env:
|
|
3930
|
+
workdir:process.cwd(),env:visionEnv({...dsh.env,BILI_DUTY_HOME:stateDir}),
|
|
3715
3931
|
visualInstruction:visionObservationFocus(cfg.visionPrompt),
|
|
3716
3932
|
allowRequest:()=>trustedLifeAccountTag()===account&&!accountBinding.status().blocked&&
|
|
3717
3933
|
cfg.visionEnabled===true&&resolvedVisionMode()==='independent_dsh',
|
|
@@ -3942,6 +4158,9 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
3942
4158
|
' BILI_COMMENT_DAILY_LIMIT: ' + yq(cfg.commentDailyLimit),
|
|
3943
4159
|
' BILI_DUTY_AUTO_COMMENT_REVIEW: ' + yq(cfg.autoComment && Number(cfg.commentPerRound)>0 && Number(cfg.commentDailyLimit)>0 && lifeVideoActionBridge?.status().ready===true ? '1':'0'),
|
|
3944
4160
|
' BILI_DUTY_HOME: ' + yq(posix(stateDir)),
|
|
4161
|
+
' HF_HOME: ' + yq(posix(storageDataPath(stateDir,'.hf-cache'))),
|
|
4162
|
+
' DSH_WHISPER_LIBRARY_HOME: ' + yq(posix(largeDataStatus(stateDir).whisperHome||'')),
|
|
4163
|
+
' DSH_MEDIA_CACHE_HOME: ' + yq(posix(storageDomainRoot(stateDir,'media'))),
|
|
3945
4164
|
' BILI_SHARED_READ_MINUTE_LIMIT: ' + yq(cfg.biliReadMinuteLimit),
|
|
3946
4165
|
' BILI_SHARED_READ_HOUR_LIMIT: ' + yq(cfg.biliReadHourLimit),
|
|
3947
4166
|
...(cfg.visionEnabled ? [
|
|
@@ -4314,7 +4533,7 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
4314
4533
|
if(!expectedAccount||accountBinding.status().blocked)throw Error('视觉启动时账号未通过验证')
|
|
4315
4534
|
productionVisionExecutor=await startProductionVisionHostExecutor({
|
|
4316
4535
|
home:stateDir,exe:route.command,cli:route.args[1],baseOverlay:baseVisionOverlay,
|
|
4317
|
-
workdir:process.cwd(),env:
|
|
4536
|
+
workdir:process.cwd(),env:visionEnv({...route.env,BILI_DUTY_HOME:stateDir}),
|
|
4318
4537
|
visualInstruction:visionObservationFocus(cfg.visionPrompt),
|
|
4319
4538
|
allowRequest:()=>trustedLifeAccountTag()===expectedAccount&&!accountBinding.status().blocked,
|
|
4320
4539
|
})
|
|
@@ -4790,7 +5009,12 @@ logger:{warn:m=>log('统一待办回访:'+m)}})
|
|
|
4790
5009
|
if(String(uid)!==String(cfg.dmOwnerUid||'')||cfg.ownerDmAgentEnabled!==true||!trustedLifeAccountTag()||accountBinding.status()?.blocked)
|
|
4791
5010
|
return {ok:false,reason:'account-not-verified',items:[]}
|
|
4792
5011
|
if(action==='public_comments')return recallOwnerPublicComments({uid,query,beforeAt})
|
|
4793
|
-
if(action==='memory_search')
|
|
5012
|
+
if(action==='memory_search'){
|
|
5013
|
+
const scope=trustedLifeAccountTag(),retriever=memoryRetriever
|
|
5014
|
+
if(!retriever)return {ok:false,reason:'memory-not-ready',items:[]}
|
|
5015
|
+
const isCurrent=()=>scope===trustedLifeAccountTag()&&!accountBinding.status().blocked&&String(uid)===String(cfg.dmOwnerUid||'')&&cfg.ownerDmAgentEnabled===true
|
|
5016
|
+
return retriever.ownerContextualSearch(query,{accountTag:scope,isCurrent,history,limit:6,beforeAt})
|
|
5017
|
+
}
|
|
4794
5018
|
if(action==='memory_detail'){
|
|
4795
5019
|
const item=memoryRetriever?.ownerDetail(id)
|
|
4796
5020
|
return {ok:true,items:item?[item]:[]}
|
|
@@ -5223,7 +5447,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
5223
5447
|
dataDir: stateDir,
|
|
5224
5448
|
isEnabled: () => {refreshCfg();return cfg.memeMemoryEnabled===true},
|
|
5225
5449
|
readEntries: () => readReplyMemeSnapshot({python:cfg.pythonPath||'python',
|
|
5226
|
-
script:join(pluginDir,'lib','meme-memory-admin.py'),dataDir:stateDir,env:
|
|
5450
|
+
script:join(pluginDir,'lib','meme-memory-admin.py'),dataDir:stateDir,env:storagePyEnv()}),
|
|
5227
5451
|
logger:{warn:(msg)=>log('互动梗检索:'+msg),info:(msg)=>log('互动梗检索:'+msg)},
|
|
5228
5452
|
})
|
|
5229
5453
|
const buildInteractionPersona=(batch=[])=>{
|
|
@@ -5391,7 +5615,8 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
5391
5615
|
}))
|
|
5392
5616
|
},
|
|
5393
5617
|
onEmotion:({mood,intensity,source})=>{try{return emotionalState.update({mood,intensity,source})}catch(e){log('情绪状态更新失败:'+String(e?.message||e).slice(0,100))}},
|
|
5394
|
-
onEmotionContext:({at,source,incoming,generated})=>{try{emotionalState.attachContext({at,source,incoming,generated})}catch(e){log('情绪来源片段记录失败:'+String(e?.message||e).slice(0,100))}
|
|
5618
|
+
onEmotionContext:({at,source,incoming,generated,observation})=>{try{emotionalState.attachContext({at,source,incoming,generated})}catch(e){log('情绪来源片段记录失败:'+String(e?.message||e).slice(0,100))}
|
|
5619
|
+
if(observation&&!accountBinding.status().blocked)try{lifeMemory?.recordEpisodeEmotion(observation)}catch(e){log('经历情绪证据保存失败:'+String(e?.message||e).slice(0,100))}},
|
|
5395
5620
|
invoke:prompt=>invokeInteractionPrompt(prompt,24000),
|
|
5396
5621
|
getPersona:batch=>buildInteractionPersona(batch),
|
|
5397
5622
|
logger:{warn:m=>log('互动 AI:'+m)},
|
|
@@ -5862,7 +6087,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
5862
6087
|
logger:{warn:(msg)=>log('评论上下文:'+msg)},
|
|
5863
6088
|
})
|
|
5864
6089
|
socialContextAssembler=createSocialContextAssembler({
|
|
5865
|
-
policy:socialPolicyGate,memoryRetriever,
|
|
6090
|
+
policy:socialPolicyGate,memoryRetriever,getMemoryRetriever:()=>memoryRetriever,getAccountTag:()=>accountBinding.status().blocked?'':trustedLifeAccountTag(),
|
|
5866
6091
|
getMeme:async(item)=>(await interactionMemeLookup.forBatch([item]))?.[0]||'',
|
|
5867
6092
|
getPersona:batch=>buildInteractionPersona(batch),
|
|
5868
6093
|
getIdentity:uid=>replyIdentityContext(uid),
|
|
@@ -6290,11 +6515,12 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6290
6515
|
const owner=routedSocialOwner('comment')
|
|
6291
6516
|
if(!owner.ok)throw Error('评论决策所有权检查失败:'+owner.reason)
|
|
6292
6517
|
return runLifeSocialOperation({channel:'comment',expectedScope:owner.scope,phase:'decision',requester:owner.owner,expectedGeneration:owner.generation},async()=>{
|
|
6518
|
+
const emotionAccountTag=trustedLifeAccountTag()
|
|
6293
6519
|
const visualReq=await addIncomingPictureObservation(req)
|
|
6294
6520
|
const commentEpisodeContext=lifeSubagentHandoff({agent:'comment',episodes:universalLifeEpisodes,
|
|
6295
6521
|
sourceRef:'comment-thread:'+String(req.bvid||'')+':'+String(req.uid||''),
|
|
6296
6522
|
linkedPublicBvid:String(req.bvid||'')});
|
|
6297
|
-
const generated=await interactionBatcher.generate({...visualReq,lifeCommentMessages:true,lifeEpisodeContext:commentEpisodeContext,
|
|
6523
|
+
const generated=await interactionBatcher.generate({...visualReq,lifeCommentMessages:true,lifeEpisodeContext:commentEpisodeContext,emotionAccountTag,
|
|
6298
6524
|
verifiedCommentSource:/^BV[0-9A-Za-z]{10}$/.test(String(req.bvid||''))&&/^[1-9]\d{0,18}$/.test(String(req.uid||''))&&/^[1-9]\d{0,19}$/.test(String(req.rpid||'')),
|
|
6299
6525
|
identityContext:'',incomingRpid:req.rpid,
|
|
6300
6526
|
p6MaxBubbles:1, // public comment/@ always one message
|
|
@@ -6520,8 +6746,8 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6520
6746
|
})
|
|
6521
6747
|
|
|
6522
6748
|
const venvPython = () => process.platform === 'win32'
|
|
6523
|
-
?
|
|
6524
|
-
:
|
|
6749
|
+
? storageDataPath(stateDir, '.venv', 'Scripts', 'python.exe')
|
|
6750
|
+
: storageDataPath(stateDir, '.venv', 'bin', 'python')
|
|
6525
6751
|
|
|
6526
6752
|
/**
|
|
6527
6753
|
* 建 venv + 装依赖 —— ⭐ **起完就返回,不等它装完**。
|
|
@@ -6577,14 +6803,14 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6577
6803
|
})
|
|
6578
6804
|
|
|
6579
6805
|
// ───────── 本地转写(ASR):**独立环境**,别把主 venv 撑成 1GB ─────────
|
|
6580
|
-
const asrDir =
|
|
6806
|
+
const asrDir = storageDataPath(stateDir,'.venv-asr')
|
|
6581
6807
|
const asrLogFile = join(stateDir, 'asr-install.log')
|
|
6582
6808
|
const asrPython = () => join(asrDir, process.platform === 'win32' ? 'Scripts' : 'bin',
|
|
6583
6809
|
process.platform === 'win32' ? 'python.exe' : 'python')
|
|
6584
6810
|
const appendAsr = (s) => { try { appendFileSync(asrLogFile, String(s)) } catch { /* 日志写不了也不能炸 */ } }
|
|
6585
6811
|
// ⭐ 转写的临时目录必须由**宿主**预先建好:值班那一轮跑在沙箱里,
|
|
6586
6812
|
// 而沙箱只允许写"该子进程启动前就已存在"的目录(2026-10-14 那一轮自己挖出来的规则)
|
|
6587
|
-
const asrTmp =
|
|
6813
|
+
const asrTmp = storageDataPath(stateDir,'tmp','asr')
|
|
6588
6814
|
try { mkdirSync(asrTmp, { recursive: true }) } catch { /* 建不了也别拦着插件加载 */ }
|
|
6589
6815
|
|
|
6590
6816
|
// ⭐ 判重表也由**宿主**预先建好(两个原因):
|
|
@@ -6626,7 +6852,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6626
6852
|
try {
|
|
6627
6853
|
const py = String(cfg.pythonPath || 'python')
|
|
6628
6854
|
const child = spawn(py, [join(stateDir, 'favops.py'), ...args], {
|
|
6629
|
-
cwd: stateDir, env:
|
|
6855
|
+
cwd: stateDir, env: storagePyEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
|
|
6630
6856
|
})
|
|
6631
6857
|
let outTxt = '', errTxt = ''
|
|
6632
6858
|
const timer = setTimeout(() => { try { child.kill() } catch { /* 已退出 */ } resolve({ ok: false, error: 'favops 超时(30 秒)' }) }, 30_000)
|
|
@@ -6756,7 +6982,13 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6756
6982
|
const event=preparePrivateLifeEvent({source:'owner-session',role:'owner',eventId,text,at,validated:true,accountTag:trustedLifeAccountTag()})
|
|
6757
6983
|
if(event){const result=await lifeMemoryCoordinator?.recordEvents([event],{reflect:true});if(result?.ok===false)log('主人主 Session 经历待补偿:'+String(result.lastError||result.reason||''))}
|
|
6758
6984
|
},
|
|
6759
|
-
getExperienceRecall: (query,limit) => lifeMemory?.recall({query,domain:'main-session',maxItems:limit,maxChars:3000}).map(x=>({kind:x.kind,time:x.at,summary:x.summary}))||[],
|
|
6985
|
+
getExperienceRecall: (query,limit) => lifeMemory?.recall({query,domain:'main-session',maxItems:limit,maxChars:3000}).map(x=>({kind:x.kind,time:x.at,bvid:x.bvid,summary:x.summary}))||[],
|
|
6986
|
+
getVideoAssociationRecall:async query=>{
|
|
6987
|
+
const scope=trustedLifeAccountTag();if(!scope||accountBinding.status().blocked||!memoryRetriever)return []
|
|
6988
|
+
const rows=await memoryRetriever.contextualVisualRecall({accountTag:scope,queries:[query],limit:2,associate:false,recentFallback:false})
|
|
6989
|
+
return scope===trustedLifeAccountTag()&&!accountBinding.status().blocked&&memoryRetriever.validateContextualVisualRecall({accountTag:scope,rows})?publicVisualAssociationContext(rows):[]
|
|
6990
|
+
},
|
|
6991
|
+
getVideoDetailRecall:({bvid,memoryId,startMs,endMs,firstObservation,order,maxBytes,cursor})=>lifeMemory?.recallVideoDetails({bvid,memoryId,startMs,endMs,firstObservation,order,maxBytes,cursor,accountTag:trustedLifeAccountTag(),ownerSession:true})||{ok:false,reason:'memory-not-ready'},
|
|
6760
6992
|
getTodoEngine: () => ownerTodos,
|
|
6761
6993
|
runTodo: (id) => runOwnerTodoWithFollowup(id),
|
|
6762
6994
|
logger: {warn:(m)=>log('⚠️ '+m),info:(m)=>log(m)},
|
|
@@ -6768,9 +7000,30 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6768
7000
|
const index=relationshipIndex()
|
|
6769
7001
|
if(!index)throw Error('relationship-index-unavailable')
|
|
6770
7002
|
return index.get(uid,relationshipOptions())
|
|
6771
|
-
},getAccountTag:trustedLifeAccountTag,
|
|
7003
|
+
},getAccountTag:trustedLifeAccountTag,admitMemoryDetails:({episode,fragments,sourceProof})=>{
|
|
7004
|
+
if(!sourceProof||typeof sourceProof!=='object'||!admittedOwnerFocusProofs.has(sourceProof)||
|
|
7005
|
+
!Array.isArray(fragments)||fragments.length!==(sourceProof.fragmentCount||1)||fragments.length<1||fragments.length>48||
|
|
7006
|
+
episode?.id!==sourceProof.memoryId||episode?.accountTag!==sourceProof.accountTag||
|
|
7007
|
+
episode?.visibility!==(sourceProof.visibility||'public-event')||
|
|
7008
|
+
episode?.bvid!==sourceProof.bvid||fragments.some(f=>f?.sourceRef!==sourceProof.sourceRef)||
|
|
7009
|
+
sourceProof.accountTag!==trustedLifeAccountTag()||
|
|
7010
|
+
!Number.isFinite(sourceProof.at)||Date.now()-sourceProof.at>60_000||
|
|
7011
|
+
accountBinding.status().blocked)return false
|
|
7012
|
+
admittedOwnerFocusProofs.delete(sourceProof)
|
|
7013
|
+
return true
|
|
7014
|
+
},onEpisodesRemoved:ids=>{void Promise.resolve(embeddingIndex?.removeVisualParents?.(ids,{includeEpisode:true})).catch(error=>log('遗忘向量清理失败:'+String(error?.message||error).slice(0,140)))},onDetailsInvalidated:ids=>{void Promise.resolve(embeddingIndex?.removeVisualParents?.(ids)).catch(error=>log('深层向量清理失败:'+String(error?.message||error).slice(0,140)))},
|
|
7015
|
+
onDetailsChanged:id=>{
|
|
7016
|
+
if(cfg.mainSessionMemoryEmbeddingEnabled!==true||!embeddingIndex)return
|
|
7017
|
+
const state=embeddingIndex.status();if(!state.ready&&!['syncing','indexing'].includes(state.phase))return
|
|
7018
|
+
const scope=trustedLifeAccountTag(),row=lifeMemory?.visualDetailCandidates({accountTag:scope,ids:[id]})[0]
|
|
7019
|
+
if(row)void embeddingIndex.replaceVisualParent(id,visualParentIndexRows(row)).then(result=>{
|
|
7020
|
+
if(!result.ok)log('深层向量增量更新失败:'+String(result.error||'未知错误').slice(0,140))
|
|
7021
|
+
if(scope!==trustedLifeAccountTag()||!lifeMemory?.visualDetailCandidates({accountTag:scope,ids:[id]})[0])return embeddingIndex.removeVisualParents([id])
|
|
7022
|
+
}).catch(error=>log('深层向量增量更新失败:'+String(error?.message||error).slice(0,140)))
|
|
7023
|
+
},logger:{warn:m=>log('人生记忆:'+m)}})
|
|
6772
7024
|
ctx.effect(()=>()=>lifeMemory?.close(),'bili-duty: 只读内存 FTS 关闭')
|
|
6773
|
-
embeddingRuntime=createEmbeddingRuntimeManager({dataDir:stateDir,
|
|
7025
|
+
embeddingRuntime=createEmbeddingRuntimeManager({dataDir:stateDir,rootDir:storageDataPath(stateDir,'embedding-runtime'),
|
|
7026
|
+
modelDir:largeDataStatus(stateDir).embeddingModelDir||undefined,logger:{warn:m=>log('本地语义运行时:'+m)}})
|
|
6774
7027
|
embeddingIndex=createEmbeddingMemoryIndex({dataDir:stateDir,provider:embeddingRuntime,logger:{warn:m=>log('本地语义索引:'+m)}})
|
|
6775
7028
|
ctx.effect(()=>()=>embeddingRuntime?.stop(),'bili-duty: 本地 Embedding Runtime 关闭')
|
|
6776
7029
|
personalityEvolution=createPersonalityEvolution({dataDir:stateDir,memoryGateway:lifeMemory,logger:{warn:m=>log('人格成长:'+m)}})
|
|
@@ -6783,12 +7036,22 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6783
7036
|
invokeModel:(prompt,maxChars)=>invokeMemoryPrompt(prompt,maxChars),
|
|
6784
7037
|
getEpisodes:(query,options)=>lifeMemory?.recall({query,domain:options?.domain||'main-session',role:options?.role||'owner',actorUid:options?.actorUid||'',excludeEventKey:options?.excludeEventKey||'',kinds:options?.kinds||null,maxItems:options?.maxItems||6,maxChars:options?.maxChars||800})||[],
|
|
6785
7038
|
getEpisodeCandidates:(options)=>lifeMemory?.semanticCandidates(options)||[],
|
|
7039
|
+
getVisualExperiences:options=>lifeMemory?.recentVisualExperienceContext(options)||[],
|
|
7040
|
+
getVisualDetailCandidates:options=>lifeMemory?.visualDetailCandidates(options)||[],
|
|
7041
|
+
getAssociations:options=>lifeMemory?.associationCandidates(options)||[],
|
|
7042
|
+
validateAssociationPath:options=>lifeMemory?.validateAssociationPath(options)===true,
|
|
7043
|
+
groupVideoEpisodes:rows=>lifeMemory?.videoRecallGroups(rows)||rows,
|
|
6786
7044
|
getPrivateInsights:(opts)=>lifeMemory?.privateInsights(opts)||[],
|
|
6787
7045
|
getPrivateInsightCandidates:(opts)=>lifeMemory?.privateInsightCandidates(opts)||[],
|
|
6788
7046
|
semanticSearch:(query,candidates,options)=>embeddingIndex?.search(query,candidates,options)||{ready:false,reason:'index-not-ready',items:[]},
|
|
6789
7047
|
getDailyUsage:()=>{const usage=readModelTaskUsage(stateDir);return {day:usage.day,used:usage.tasks.memory.today}},
|
|
6790
7048
|
logger:{warn:m=>log('⚠️ '+m)},
|
|
6791
7049
|
})
|
|
7050
|
+
const neuralActivationTracker=createNeuralActivationTracker({
|
|
7051
|
+
getAccountTag:()=>accountBinding.status().blocked?'':trustedLifeAccountTag(),
|
|
7052
|
+
validateRecall:opts=>memoryRetriever?.validateContextualVisualRecall(opts)===true,
|
|
7053
|
+
validatePath:opts=>lifeMemory?.validateAssociationPath(opts)===true,
|
|
7054
|
+
})
|
|
6792
7055
|
longTermMemory.start()
|
|
6793
7056
|
ctx.effect(() => () => longTermMemory.stop(), 'bili-duty: 内置长期记忆')
|
|
6794
7057
|
// Optional local semantic recall is strictly opt-in. Startup never downloads
|
|
@@ -6809,6 +7072,13 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6809
7072
|
dataDir: stateDir,
|
|
6810
7073
|
getConfig: () => cfg,
|
|
6811
7074
|
memoryGateway:lifeMemory,
|
|
7075
|
+
rankAssociationHistory:(seeds,history)=>{
|
|
7076
|
+
if(cfg.mainSessionMemoryEmbeddingEnabled!==true||embeddingIndex?.status()?.ready!==true)return {ready:false,items:[],indexed:0}
|
|
7077
|
+
// Same summary normalization as Gateway.semanticCandidates / embeddingCorpus.
|
|
7078
|
+
// The reflection path supplies exclusively revalidated current-account public episodes.
|
|
7079
|
+
const rows=values=>values.map(e=>({id:'episode:'+e.id,text:String(e.text??'').replace(/[\u0000-\u001f\u007f]+/g,' ').replace(/\s+/g,' ').trim().slice(0,330)}))
|
|
7080
|
+
return embeddingIndex.rankRelatedEpisodesWithQuery(rows(seeds),rows(history),{limit:12,minScore:.30})
|
|
7081
|
+
},
|
|
6812
7082
|
getAccountTag:trustedLifeAccountTag,
|
|
6813
7083
|
getPublicEpisodeContext:()=>lifeSubagentHandoff({agent:'reflection',episodes:universalLifeEpisodes}),
|
|
6814
7084
|
getPersonalityEnabled:()=>{try{return personalityEvolution?.status().enabled===true}catch{return false}},
|
|
@@ -6937,7 +7207,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6937
7207
|
enabled:()=>{refreshCfg();return cfg.masterEnabled===true&&firstStart.isReady()&&!accountBinding.status().blocked},
|
|
6938
7208
|
beginTrace:params=>lifeDecisionTrace.begin(params),
|
|
6939
7209
|
onActionState:event=>{lifeActionRecords.update(event)},
|
|
6940
|
-
getContext:({scene,uid,evidence})=>{
|
|
7210
|
+
getContext:async({scene,uid,evidence,sourceKey,kind})=>{
|
|
6941
7211
|
// Optional world projections cannot suppress an entire voluntary Life turn.
|
|
6942
7212
|
// Only an unbuildable base identity remains fail-closed; degraded categories
|
|
6943
7213
|
// are recorded without private text, UIDs, or underlying file paths.
|
|
@@ -6950,9 +7220,24 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6950
7220
|
if(topic&&cfg.mainSessionMemoryEnabled&&lifeMemory)
|
|
6951
7221
|
publicMemory=lifeMemory.recall({query:topic,domain:'bili-explore',kinds:['watch'],maxItems:2,maxChars:360,reinforce:false})||[]
|
|
6952
7222
|
}catch{degradedStages.push('public-memory');log('Life 上下文:可回忆视频线索暂不可用')}
|
|
6953
|
-
let world={}
|
|
7223
|
+
let world={},validateRecall=null
|
|
6954
7224
|
try{world=projectLifeWorldEvidence({interests,episodes:publicMemory})}
|
|
6955
7225
|
catch{degradedStages.push('public-memory');log('Life 上下文:公开记忆摘要暂不可用,使用基本人格继续')}
|
|
7226
|
+
// Original top-level comment only: sourceKey came from the checked
|
|
7227
|
+
// video action bridge. The agent's observation is an untrusted cue, not
|
|
7228
|
+
// a grant or a receipt. Do not query private or same-video memories.
|
|
7229
|
+
if(scene==='comment'&&kind==='video_comment')try{
|
|
7230
|
+
const target=/^video-comment:[a-f0-9]{24}:(BV[0-9A-Za-z]{10})$/.exec(String(sourceKey||''))?.[1]
|
|
7231
|
+
const scope=trustedLifeAccountTag()
|
|
7232
|
+
if(target&&scope&&cfg.mainSessionMemoryEnabled&&memoryRetriever){
|
|
7233
|
+
const cue=String(evidence?.publicVideoComment?.evidence||'').slice(0,540)
|
|
7234
|
+
const rows=await memoryRetriever.contextualVisualRecall({accountTag:scope,queries:[cue],limit:2,associate:true,excludeBvids:[target],recentFallback:false})
|
|
7235
|
+
if(scope===trustedLifeAccountTag()&&!accountBinding.status().blocked&&rows.length){
|
|
7236
|
+
validateRecall=()=>scope===trustedLifeAccountTag()&&!accountBinding.status().blocked&&memoryRetriever.validateContextualVisualRecall({accountTag:scope,rows})
|
|
7237
|
+
world={...world,optionalPastVideoAssociations:publicVisualAssociationContext(rows,target)}
|
|
7238
|
+
}
|
|
7239
|
+
}
|
|
7240
|
+
}catch{degradedStages.push('public-memory');log('Life 上下文:公开视频联想暂不可用')}
|
|
6956
7241
|
try{
|
|
6957
7242
|
const own=lifeMemory?.publicSocialEvidence(3)||[]
|
|
6958
7243
|
world.recentConfirmedPublicSpeech=own.filter(row=>typeof row.ownText==='string')
|
|
@@ -6990,7 +7275,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
6990
7275
|
catch{throw Error('life-base-identity-unavailable')}
|
|
6991
7276
|
}
|
|
6992
7277
|
if(!voice.trim())throw Error('life-base-identity-unavailable')
|
|
6993
|
-
return {voice,world,experience,degradedStages}
|
|
7278
|
+
return {voice,world,experience,degradedStages,validateRecall}
|
|
6994
7279
|
},
|
|
6995
7280
|
invokeModel:(prompt,maxChars)=>invokeInteractionPrompt(prompt,maxChars,{modelRoute:'behaviorDecision'}),
|
|
6996
7281
|
// Completion notifications are non-executing, account-bound and de-duped
|
|
@@ -7098,7 +7383,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
7098
7383
|
let child
|
|
7099
7384
|
try{child=spawn(cfg.pythonPath||'python',[join(pluginDir,'lib','video-action-verify.py'),
|
|
7100
7385
|
join(stateDir,'bili_credential.json'),kind,target,uid,...(kind==='video_comment'?[receiptId]:[])],{
|
|
7101
|
-
cwd:stateDir,env:
|
|
7386
|
+
cwd:stateDir,env:storagePyEnv(),shell:false,windowsHide:true,
|
|
7102
7387
|
stdio:[kind==='video_comment'?'pipe':'ignore','pipe','pipe']})}
|
|
7103
7388
|
catch{return resolve(false)}
|
|
7104
7389
|
let out='',done=false
|
|
@@ -7284,7 +7569,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
7284
7569
|
let result
|
|
7285
7570
|
try{
|
|
7286
7571
|
child=spawn(cfg.pythonPath||'python',[join(pluginDir,'lib','life-shared-dynamic-write.py')],{
|
|
7287
|
-
cwd:stateDir,windowsHide:true,shell:false,stdio:['pipe','pipe','ignore'],env:
|
|
7572
|
+
cwd:stateDir,windowsHide:true,shell:false,stdio:['pipe','pipe','ignore'],env:storagePyEnv({
|
|
7288
7573
|
BILI_DUTY_HOME:stateDir,BILI_MCP_TOOLS:tool,BILI_LIFE_SHARED_DYNAMIC_RUNNER:'1',
|
|
7289
7574
|
BILI_LIFE_SHARED_DYNAMIC_ACTION_ENABLED:'1',BILI_LIFE_EXPECT_UID:uid,
|
|
7290
7575
|
BILI_LIFE_PUBLIC_INTERACTION_ENABLED:cfg.lifePublicInteractionEnabled?'1':'0',
|
|
@@ -7342,7 +7627,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
7342
7627
|
if(!permitted[action]||cfg.masterEnabled!==true)return resolve({ok:false,status:'unavailable',attempted:false})
|
|
7343
7628
|
let child
|
|
7344
7629
|
try{child=spawn(cfg.pythonPath||'python',[join(pluginDir,'lib','life-continuation-write.py')],{
|
|
7345
|
-
cwd:stateDir,windowsHide:true,shell:false,stdio:['pipe','pipe','ignore'],env:
|
|
7630
|
+
cwd:stateDir,windowsHide:true,shell:false,stdio:['pipe','pipe','ignore'],env:storagePyEnv({
|
|
7346
7631
|
BILI_DUTY_HOME:stateDir,BILI_MCP_TOOLS:tool,BILI_LIFE_CONTINUATION_RUNNER:'1',
|
|
7347
7632
|
BILI_LIFE_EXPECT_UID:accountUid,BILI_JS_MCP_ADAPTER:'0',BILI_DUTY_TOP_LEVEL_ONLY:'1',
|
|
7348
7633
|
BILI_SYNC_DYNAMIC:'0',BILI_MENTION_MODE:'off',BILI_DM_TARGET_UID:'0',
|
|
@@ -7519,7 +7804,15 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
7519
7804
|
// The planner can prioritize a real ongoing episode without granting any
|
|
7520
7805
|
// additional tool. Model calls still use the existing daily Life budget.
|
|
7521
7806
|
getLifeEpisodeContext:()=>universalLifeEpisodes.list({limit:3}),
|
|
7522
|
-
getRecentLifeVideoMemory:opts=>
|
|
7807
|
+
getRecentLifeVideoMemory:async opts=>{
|
|
7808
|
+
const rows=await (memoryRetriever?.contextualVisualRecall({...opts,associate:true})||[])
|
|
7809
|
+
// Observe only the public autonomous planner return, not private/owner
|
|
7810
|
+
// recall or a model's inner thoughts. A diagnostic failure never alters recall.
|
|
7811
|
+
if(neuralActivationTracker.record({accountTag:opts?.accountTag,rows}))lifeManagementEvents.publish('memory-recall')
|
|
7812
|
+
return rows
|
|
7813
|
+
},
|
|
7814
|
+
validateLifeVideoMemory:opts=>memoryRetriever?.validateContextualVisualRecall(opts)===true,
|
|
7815
|
+
getLifeVideoDetailRecall:opts=>lifeMemory?.recallVideoDetails(opts)||{ok:false,reason:'memory-unavailable'},
|
|
7523
7816
|
// Video is not a mandatory Episode first step. For early, *optional*
|
|
7524
7817
|
// reconsideration, match the SAME original source for an existing active
|
|
7525
7818
|
// verified Episode against CURRENTLY executable public intentions,
|
|
@@ -7662,7 +7955,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
7662
7955
|
['independent_dsh','independent_local'].includes(resolvedVisionMode())&&
|
|
7663
7956
|
lifeOpportunityAccountReady()&&!accountBinding.status().blocked},
|
|
7664
7957
|
withLifeVisualObservationLease:(target,run)=>withLifeVideoVisualLease(stateDir,target,run),
|
|
7665
|
-
executeLifeVideoObservation:async({bvid,viewDepth,accountTag,focusWindow,globalVisualNotes,previousVerifiedFocusWindows,networkBudgetBytes,frameBudgetLimit})=>{
|
|
7958
|
+
executeLifeVideoObservation:async({bvid,viewDepth,accountTag,focusWindow,globalVisualNotes,previousVerifiedFocusWindows,networkBudgetBytes,frameBudgetLimit,galleryGroupId})=>{
|
|
7666
7959
|
refreshCfg()
|
|
7667
7960
|
if(cfg.masterEnabled!==true||cfg.lifeAgentMode!=='active'||cfg.visionEnabled!==true||
|
|
7668
7961
|
!['independent_dsh','independent_local'].includes(resolvedVisionMode())||
|
|
@@ -7678,7 +7971,7 @@ ${persona ? '你在这个场景下的角色人格与表达方式(真实性和
|
|
|
7678
7971
|
{lifeChoiceVerified:true,
|
|
7679
7972
|
lifeGlobalNotes:focusWindow?globalVisualNotes:undefined,
|
|
7680
7973
|
previousVerifiedFocusWindows:focusWindow?previousVerifiedFocusWindows:undefined,
|
|
7681
|
-
lifeFocusAccountTag:accountTag})).catch(()=>({ok:false,reason:'life-vision-resource-unavailable'}))
|
|
7974
|
+
lifeFocusAccountTag:accountTag,lifeGalleryGroupId:galleryGroupId})).catch(()=>({ok:false,reason:'life-vision-resource-unavailable'}))
|
|
7682
7975
|
},
|
|
7683
7976
|
recordLifeVideoVisual:(id,proof,tag)=>lifeOpportunities.recordVideoVisual(id,proof,tag),
|
|
7684
7977
|
hasVerifiedLifeVideoVisual:(bvid,tag)=>lifeOpportunities.hasVerifiedVideoVisual(bvid,tag),
|
|
@@ -7816,6 +8109,12 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
7816
8109
|
mainSessionBridge = createMainSessionBridge({
|
|
7817
8110
|
dataDir: stateDir,
|
|
7818
8111
|
agents: ctx.agents,
|
|
8112
|
+
getWorkspaceRegistry:()=>ctx.get('workspaceRegistry'),
|
|
8113
|
+
bindSession:async(id,expectedId)=>{
|
|
8114
|
+
refreshCfg()
|
|
8115
|
+
if(String(cfg.mainSessionId||'').replace(/^session-/,'')!==expectedId)throw Error('主 Session 已改变')
|
|
8116
|
+
await persistCfg({mainSessionId:id})
|
|
8117
|
+
},
|
|
7819
8118
|
getAccountTag: trustedLifeAccountTag,
|
|
7820
8119
|
titleOf: (agent) => {
|
|
7821
8120
|
try { const row=ctx.sessionTitle?.get?.(agent?.session); return typeof row==='string'?row:String(row?.title||'') } catch { return '' }
|
|
@@ -7878,7 +8177,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
7878
8177
|
let child
|
|
7879
8178
|
try{child=spawn(cfg.pythonPath||'python',[join(pluginDir,'lib','daily-dynamic-verify.py'),
|
|
7880
8179
|
join(stateDir,'bili_credential.json'),dynamicId,String(identity.activeUid)],{
|
|
7881
|
-
cwd:stateDir,env:
|
|
8180
|
+
cwd:stateDir,env:storagePyEnv(),shell:false,windowsHide:true,stdio:['pipe','pipe','pipe']})}
|
|
7882
8181
|
catch{return resolve({verified:false})}
|
|
7883
8182
|
let out='',done=false
|
|
7884
8183
|
const finish=v=>{if(done)return;done=true;clearTimeout(timeout);resolve(v)}
|
|
@@ -7911,7 +8210,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
7911
8210
|
const script=join(pluginDir,'lib','daily-dynamic-publish.py')
|
|
7912
8211
|
const cred=join(stateDir,'bili_credential.json')
|
|
7913
8212
|
const child=spawn(cfg.pythonPath||'python',[script,stateDir,cred,String(limit),'1'],{
|
|
7914
|
-
cwd:stateDir,env:
|
|
8213
|
+
cwd:stateDir,env:storagePyEnv(),shell:false,windowsHide:true,stdio:['pipe','pipe','pipe']})
|
|
7915
8214
|
let out='',err='';const timeout=setTimeout(()=>{try{child.kill()}catch{}},20_000);timeout.unref?.()
|
|
7916
8215
|
child.stdout.on('data',b=>{out=(out+String(b)).slice(0,4000)})
|
|
7917
8216
|
child.stderr.on('data',b=>{err=(err+String(b)).slice(-500)})
|
|
@@ -7927,7 +8226,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
7927
8226
|
const memeLearningScript=(mode,payload)=>new Promise((resolve,reject)=>{
|
|
7928
8227
|
const script=join(pluginDir,'lib','meme-learning-admin.py')
|
|
7929
8228
|
const child=spawn(cfg.pythonPath||'python',[script,stateDir,mode],{
|
|
7930
|
-
cwd:stateDir,env:
|
|
8229
|
+
cwd:stateDir,env:storagePyEnv(),shell:false,windowsHide:true,stdio:['pipe','pipe','pipe']})
|
|
7931
8230
|
// Preserve the full bounded JSON response. Truncating at 25,000 characters
|
|
7932
8231
|
// corrupted valid meme-learning lists and caused JSON.parse position 25000.
|
|
7933
8232
|
const chunks=[];let total=0,overflow=false,settled=false,err=''
|
|
@@ -8128,7 +8427,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8128
8427
|
// ⭐ 顺手把模型也下好(不然第一次跑那一轮会卡在下载上 ✗);模型走 HuggingFace 国内镜像
|
|
8129
8428
|
const model = String(cfg.asrModel || 'small')
|
|
8130
8429
|
// 模型缓存必须放进插件家:默认的 ~/.cache 在本机拒绝写入(2026-10-14 实测 WinError 5)
|
|
8131
|
-
const hfHome =
|
|
8430
|
+
const hfHome = storageDataPath(stateDir,'.hf-cache')
|
|
8132
8431
|
try { mkdirSync(hfHome, { recursive: true }) } catch { /* 建不了后面会给报错 */ }
|
|
8133
8432
|
setAsrProgress('download-start',{model,currentBytes:null,totalBytes:null})
|
|
8134
8433
|
appendAsr(`下 Whisper 模型「${model}」(缓存在 ${hfHome},源 ${hf};真实文件下载进度显示在下方)…\n`)
|
|
@@ -8179,8 +8478,8 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8179
8478
|
const restoreIfFailed=()=>{
|
|
8180
8479
|
if(!repairBackup.path||repairBackup.done)return
|
|
8181
8480
|
try{
|
|
8182
|
-
const current=
|
|
8183
|
-
if(existsSync(current))renameSync(current,
|
|
8481
|
+
const current=storageDataPath(stateDir,'.venv')
|
|
8482
|
+
if(existsSync(current))renameSync(current,storageDataPath(stateDir,'.venv') + '.failed-'+Date.now())
|
|
8184
8483
|
renameSync(repairBackup.path,current)
|
|
8185
8484
|
appendInstall('已恢复原有 Python 虚拟环境;未清理历史凭据或依赖。\n')
|
|
8186
8485
|
repairBackup.done=true
|
|
@@ -8199,13 +8498,13 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8199
8498
|
// 而 venv 一旦建好就不再重建 ⇒ 每次装依赖都在 brotli/pyyaml 上编译失败,用户只能自己删目录 ✗
|
|
8200
8499
|
// ⇒ 点「装主依赖」时先看现役环境是哪个版本,太高就改名换个新的(不删,留着回滚)✓
|
|
8201
8500
|
try {
|
|
8202
|
-
const pyv = readFileSync(
|
|
8501
|
+
const pyv = readFileSync(storageDataPath(stateDir, '.venv', 'pyvenv.cfg'), 'utf8')
|
|
8203
8502
|
const mv = /version\s*=\s*(\d+)\.(\d+)/.exec(pyv)
|
|
8204
8503
|
if (mv && existsSync(venvPy) && Number(mv[2]) >= 14) {
|
|
8205
8504
|
const tagV = mv[1] + '.' + mv[2]
|
|
8206
|
-
const bad =
|
|
8505
|
+
const bad = storageDataPath(stateDir,'.venv') + '.bad-' + tagV + '-' + Date.now()
|
|
8207
8506
|
appendInstall('当前环境是 Python ' + tagV + '(太高,brotli / pyyaml 没有现成的包)⇒ 改名重建 3.12\n')
|
|
8208
|
-
try { renameSync(
|
|
8507
|
+
try { renameSync(storageDataPath(stateDir,'.venv'), bad) } catch (e2) { appendInstall('改名没成功:' + String(e2?.message ?? e2) + '\n') }
|
|
8209
8508
|
}
|
|
8210
8509
|
} catch { /* 没有 pyvenv.cfg 就算了 */ }
|
|
8211
8510
|
// A Python installed by uv can be blocked by a per-executable Windows
|
|
@@ -8214,15 +8513,15 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8214
8513
|
const currentHealth=process.platform!=='win32'
|
|
8215
8514
|
?{ok:existsSync(venvPy),reason:'platform_not_checked'}
|
|
8216
8515
|
:existsSync(venvPy)
|
|
8217
|
-
?probeVisionPython(venvPy,{home:stateDir,env:
|
|
8516
|
+
?probeVisionPython(venvPy,{home:stateDir,env:storagePyEnv(),requiresMcp:false})
|
|
8218
8517
|
:{ok:false,reason:'missing_runtime'}
|
|
8219
8518
|
const explicitlyRequested=String(process.env.BILI_DUTY_VENV_PYTHON||'').trim()
|
|
8220
8519
|
const baseChoice=process.platform==='win32'&&(!currentHealth.ok||!existsSync(venvPy))
|
|
8221
8520
|
?selectVisionPython({preferred:explicitlyRequested||cfg.visionPythonPath,configured:cfg.visionPythonPath,
|
|
8222
|
-
home:stateDir,workdir:process.cwd(),env:
|
|
8521
|
+
home:stateDir,workdir:process.cwd(),env:storagePyEnv(),requiresMcp:false})
|
|
8223
8522
|
:null
|
|
8224
8523
|
if(explicitlyRequested && !currentHealth.ok && !probeVisionPython(explicitlyRequested,
|
|
8225
|
-
{home:stateDir,env:
|
|
8524
|
+
{home:stateDir,env:storagePyEnv(),requiresMcp:false}).ok){
|
|
8226
8525
|
appendInstall('指定的 BILI_DUTY_VENV_PYTHON 没有通过普通权限写入检查,拒绝创建环境。\n')
|
|
8227
8526
|
installOutcome='failed';installFailureHint='指定 Python 不健康;未修改现有环境';return
|
|
8228
8527
|
}
|
|
@@ -8231,8 +8530,8 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8231
8530
|
installOutcome='failed';installFailureHint='Python 运行时没有文件写入权限;原环境已保留';return
|
|
8232
8531
|
}
|
|
8233
8532
|
if(existsSync(venvPy)&&!currentHealth.ok){
|
|
8234
|
-
const backup=
|
|
8235
|
-
try{renameSync(
|
|
8533
|
+
const backup=storageDataPath(stateDir,'.venv') + '.unhealthy-'+Date.now()
|
|
8534
|
+
try{renameSync(storageDataPath(stateDir,'.venv'),backup);repairBackup.path=backup}
|
|
8236
8535
|
catch{appendInstall('旧虚拟环境正在占用或不可重命名;请完整退出 DSH 后再修复,旧环境未删除。\n');
|
|
8237
8536
|
installOutcome='failed';installFailureHint='现有虚拟环境不可安全备份';return}
|
|
8238
8537
|
appendInstall('已将不可写的旧虚拟环境保留为独立备份,不修改其权限。\n')
|
|
@@ -8241,16 +8540,16 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8241
8540
|
// uv's --python selects an interpreter. It does NOT grant admin
|
|
8242
8541
|
// rights or bypass Windows per-program access control.
|
|
8243
8542
|
const spec=baseChoice?.ok?baseChoice.path:String(explicitlyRequested||'3.12')
|
|
8244
|
-
const venvArgs=['venv','--seed','--python',spec,
|
|
8543
|
+
const venvArgs=['venv','--seed','--python',spec,storageDataPath(stateDir,'.venv')]
|
|
8245
8544
|
const createCode=uvCmd?await spawnLogged(uvCmd,venvArgs)
|
|
8246
|
-
:baseChoice?.ok?await spawnLogged(baseChoice.path,['-m','venv',
|
|
8545
|
+
:baseChoice?.ok?await spawnLogged(baseChoice.path,['-m','venv',storageDataPath(stateDir,'.venv')]):1
|
|
8247
8546
|
if(createCode!==0||!existsSync(venvPy)){
|
|
8248
8547
|
appendInstall('建 venv 失败,拒绝使用尚未验证的解释器。\n');restoreIfFailed()
|
|
8249
8548
|
installOutcome='failed';installFailureHint='Python 环境创建失败';return
|
|
8250
8549
|
}
|
|
8251
8550
|
}
|
|
8252
8551
|
const afterCreation=process.platform==='win32'
|
|
8253
|
-
?probeVisionPython(venvPy,{home:stateDir,env:
|
|
8552
|
+
?probeVisionPython(venvPy,{home:stateDir,env:storagePyEnv(),requiresMcp:false})
|
|
8254
8553
|
:{ok:existsSync(venvPy),reason:'platform_not_checked'}
|
|
8255
8554
|
if(!afterCreation.ok){
|
|
8256
8555
|
appendInstall('新建的 Python 在普通权限下仍无法写入:'+afterCreation.reason+';拒绝把它标记为就绪。\n')
|
|
@@ -8267,7 +8566,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8267
8566
|
if (code !== 0) code = await spawnLogged(venvPy, ['-m', 'pip', 'install', '-i', m, '-r', reqFile])
|
|
8268
8567
|
}
|
|
8269
8568
|
const installedHealthy=code===0 && (process.platform!=='win32'||
|
|
8270
|
-
probeVisionPython(venvPy,{home:stateDir,env:
|
|
8569
|
+
probeVisionPython(venvPy,{home:stateDir,env:storagePyEnv(),requiresMcp:true}).ok)
|
|
8271
8570
|
if (installedHealthy) {
|
|
8272
8571
|
// ⚠️ 光写 config.json 不够:DSH 原生设置里那份旧值("python")会在 loadCfg 时压回来
|
|
8273
8572
|
// (已由 loadCfg 的 HOST_WINS_EXCLUDED 解决 ✓);这里再把宿主的同步结果说清楚,
|
|
@@ -8345,7 +8644,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8345
8644
|
activityFeed:activityFeed.list({limit:8}),
|
|
8346
8645
|
venvReady: venvReadyNow(),
|
|
8347
8646
|
visionPythonRuntime:(()=>{const r=visionPythonCache?.result;return {status:r?.ok?'healthy':r?'unhealthy':'unchecked',
|
|
8348
|
-
source:r?.source||'none',reason:r?.reason||'not_run'}})(),
|
|
8647
|
+
source:r?.source||'none',reason:r?.reason||'not_run',stage:r?.stage||''}})(),
|
|
8349
8648
|
version: myVersion(),
|
|
8350
8649
|
// 2026-10-22:缺哪个 Python 包装不上,得能一眼看出来(出不了二维码 =09 缺 qrcode)
|
|
8351
8650
|
missingDeps: (() => { try { return missingVenvDeps() } catch { return [] } })(),
|
|
@@ -8389,6 +8688,67 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8389
8688
|
}
|
|
8390
8689
|
}
|
|
8391
8690
|
|
|
8691
|
+
// dev.4: one portable business snapshot per local day; never includes credentials or private-memory-only archives.
|
|
8692
|
+
// An unsuccessful snapshot never advances the day or removes older backups.
|
|
8693
|
+
// SQLite snapshot is made in memory, not in Windows / Python temp directories.
|
|
8694
|
+
const py = existsSync(venvPython()) ? venvPython() : String(cfg.pythonPath || 'python')
|
|
8695
|
+
const sqliteHelper = join(pluginDir, 'lib', 'data-backup-sqlite.py')
|
|
8696
|
+
const runSqlite = (op, data) => new Promise((resolve, reject) => {
|
|
8697
|
+
const child = spawn(py, [sqliteHelper, op, stateDir], {windowsHide:true, stdio:['pipe','pipe','pipe']})
|
|
8698
|
+
let stdout='',stderr='',settled=false
|
|
8699
|
+
const fail=e=>{if(!settled){settled=true;reject(e)}}
|
|
8700
|
+
child.on('error', e=>fail(Error('无法启动 SQLite 备份工具:'+String(e?.message||e))))
|
|
8701
|
+
child.stdin.on('error', e=>fail(Error('向 SQLite 备份工具写数据失败:'+String(e?.message||e))))
|
|
8702
|
+
child.stdout.on('data', chunk => {stdout+=chunk.toString();if(stdout.length>45_000_000){child.kill();fail(Error('SQLite 备份数据过大'))}})
|
|
8703
|
+
child.stderr.on('data', chunk => {stderr+=chunk.toString().slice(0,800)})
|
|
8704
|
+
child.on('close', code => {if(settled)return;settled=true;try{const result=JSON.parse(stdout||'{}');if(code!==0||!result.ok)throw Error(result.error||stderr||'SQLite 工具异常');resolve(result)}catch(e){reject(e)}})
|
|
8705
|
+
try{child.stdin.end(data ? JSON.stringify(data):'')}catch(e){fail(e)}
|
|
8706
|
+
})
|
|
8707
|
+
const snapshotBusinessBackup = async () => {
|
|
8708
|
+
refreshCfg()
|
|
8709
|
+
const socialPending=socialInteractionCoordinator?.status().pending||0
|
|
8710
|
+
if(socialPending)throw Error('仍有 '+socialPending+' 条社交事件等待补偿;为避免备份恢复产生跨系统数据不一致,请先修复同步错误再备份或恢复')
|
|
8711
|
+
const lifePending=lifeMemoryCoordinator?.status()?.pending||0
|
|
8712
|
+
if(lifePending)throw Error('仍有 '+lifePending+' 条人生事件等待补偿;请先修复同步后备份或恢复')
|
|
8713
|
+
const sqlite = (await runSqlite('export')).sqlite
|
|
8714
|
+
// All effective settings, including relationships, prompts and quotas.
|
|
8715
|
+
const effective = Object.fromEntries(Object.keys(DEFAULTS).map(k => [k, cfg[k]]))
|
|
8716
|
+
return createBackup({root:stateDir,config:effective,sqlite,version:myVersion()})
|
|
8717
|
+
}
|
|
8718
|
+
|
|
8719
|
+
let autoBackupBusy=false
|
|
8720
|
+
let autoBackupState={lastAttemptAt:'',lastError:'',lastSuccessAt:''}
|
|
8721
|
+
const runDailyBackup=async()=>{
|
|
8722
|
+
if(autoBackupBusy)return
|
|
8723
|
+
refreshCfg()
|
|
8724
|
+
if(cfg.backupAutoEnabled!==true||!cfg.backupDirectory||!firstStart.isReady())return
|
|
8725
|
+
autoBackupBusy=true
|
|
8726
|
+
try{
|
|
8727
|
+
const dir=requireBackupDirectory(cfg.backupDirectory)
|
|
8728
|
+
if(hasTodaysAutomatic(dir)){pruneAutomaticBackups(dir);return}
|
|
8729
|
+
autoBackupState.lastAttemptAt=new Date().toISOString()
|
|
8730
|
+
const backup=await snapshotBusinessBackup()
|
|
8731
|
+
const result=saveAutomaticBackup(dir,backup)
|
|
8732
|
+
if(result.created){autoBackupState.lastSuccessAt=new Date().toISOString();autoBackupState.lastError='';log('每日自动业务备份完成,保留最近5天:'+result.filePath)}
|
|
8733
|
+
}catch(error){autoBackupState.lastError=String(error?.message||error).slice(0,180);log('每日自动备份暂未完成:'+autoBackupState.lastError)}
|
|
8734
|
+
finally{autoBackupBusy=false}
|
|
8735
|
+
}
|
|
8736
|
+
const runVideoCacheCleanup=()=>{
|
|
8737
|
+
for(const [key,row] of recentVideoFocusCues)if(row.expiresAt<=Date.now())recentVideoFocusCues.delete(key)
|
|
8738
|
+
const result=pruneVideoCaches(stateDir)
|
|
8739
|
+
if(result.failed||result.skipped)log('音视频缓存清理:已删除 '+result.removed+' 项,待重试 '+result.failed+' 项,安全跳过 '+result.skipped+' 项')
|
|
8740
|
+
}
|
|
8741
|
+
const videoCacheTimer=setInterval(runVideoCacheCleanup,VIDEO_CACHE_RETENTION.interval)
|
|
8742
|
+
videoCacheTimer.unref?.()
|
|
8743
|
+
const videoCacheStart=setTimeout(runVideoCacheCleanup,30_000)
|
|
8744
|
+
videoCacheStart.unref?.()
|
|
8745
|
+
ctx.effect(()=>()=>{clearTimeout(videoCacheStart);clearInterval(videoCacheTimer)},'bili-duty: 音视频缓存清理任务关闭')
|
|
8746
|
+
const dailyBackupTimer=setInterval(()=>{void runDailyBackup()},15*60_000)
|
|
8747
|
+
dailyBackupTimer.unref?.()
|
|
8748
|
+
const dailyBackupStart=setTimeout(()=>{void runDailyBackup()},90_000)
|
|
8749
|
+
dailyBackupStart.unref?.()
|
|
8750
|
+
ctx.effect(()=>()=>{clearTimeout(dailyBackupStart);clearInterval(dailyBackupTimer)},'bili-duty: 每日业务备份任务关闭')
|
|
8751
|
+
let storageModelVerification=null,storageModelVerificationBusy=false,storageLifeVerification=null,storageExternalLifeVerification=null
|
|
8392
8752
|
const handle = async (req, res, url) => {
|
|
8393
8753
|
refreshCfg()
|
|
8394
8754
|
const path = url.pathname
|
|
@@ -8396,7 +8756,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8396
8756
|
// unlock business APIs merely because the user can load the settings UI.
|
|
8397
8757
|
const setupAccess = (req.method==='GET' && path==='/api/bili-duty/activity-feed') || path==='/api/bili-duty/status' || (req.method==='GET'&&path==='/api/bili-duty/life-agent/scheduler-snapshot') || path==='/api/bili-duty/config' || path==='/api/bili-duty/onboarding/status' ||
|
|
8398
8758
|
path.startsWith('/api/bili-duty/onboarding/') || path.startsWith('/api/bili-duty/headless-model/') ||
|
|
8399
|
-
path.startsWith('/api/bili-duty/login/') || path.startsWith('/api/bili-duty/account/') || (req.method==='GET' && path==='/api/bili-duty/main-session') || path==='/api/bili-duty/manage' || path==='/api/bili-duty/manage.js' || path==='/api/bili-duty/life-character.png' || (req.method==='GET' && path==='/api/bili-duty/embedding/status') ||
|
|
8759
|
+
path.startsWith('/api/bili-duty/login/') || path.startsWith('/api/bili-duty/account/') || (req.method==='GET' && path==='/api/bili-duty/main-session') || (req.method==='GET' && path==='/api/bili-duty/main-session/sessions') || (req.method==='POST' && path==='/api/bili-duty/main-session/bind') || path==='/api/bili-duty/manage' || path==='/api/bili-duty/manage.js' || path==='/api/bili-duty/life-character.png' || (req.method==='GET' && path==='/api/bili-duty/embedding/status') ||
|
|
8400
8760
|
path==='/api/bili-duty/dsh-vision/repair' || path==='/api/bili-duty/install' || path==='/api/bili-duty/install/status' || path==='/api/bili-duty/install-asr' || path==='/api/bili-duty/video-dependencies/ffmpeg/install' || path==='/api/bili-duty/local-vision/ensure' || path==='/api/bili-duty/open' ||
|
|
8401
8761
|
path==='/api/bili-duty/diagnose' || path==='/api/bili-duty/selfcheck' || path==='/api/bili-duty/check' || path==='/api/bili-duty/mcp-integrity' || (req.method==='GET'&&['/api/bili-duty/video-dependencies/status','/api/bili-duty/video-dependencies/whisper/status'].includes(path)) || (req.method==='POST'&&path==='/api/bili-duty/video-dependencies/whisper/delete') || (req.method==='POST'&&path==='/api/bili-duty/video-dependencies/paths') || (req.method==='POST'&&path==='/api/bili-duty/video-dependencies/ffmpeg/test')
|
|
8402
8762
|
if(!firstStart.isReady() && !setupAccess)return sendJson(res,423,{ok:false,blocked:true,error:firstStart.message()})
|
|
@@ -8442,7 +8802,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8442
8802
|
if (req.method === 'GET' && path === '/api/bili-duty/manage') {
|
|
8443
8803
|
const body=readFileSync(join(pluginDir,'lib','management-console.html'),'utf8')
|
|
8444
8804
|
res.writeHead(200,{'content-type':'text/html; charset=utf-8','cache-control':'no-store',
|
|
8445
|
-
'x-dafeiyu-management':'1','x-content-type-options':'nosniff','content-security-policy':"default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"})
|
|
8805
|
+
'x-dafeiyu-management':'1','referrer-policy':'no-referrer','x-content-type-options':'nosniff','content-security-policy':"default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"})
|
|
8446
8806
|
return res.end(body)
|
|
8447
8807
|
}
|
|
8448
8808
|
// Bundled character art for management UI. Constant filename; no user path input.
|
|
@@ -8461,7 +8821,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8461
8821
|
if(req.method === 'POST') {
|
|
8462
8822
|
const host=String(req.headers.host||'')
|
|
8463
8823
|
const origin=String(req.headers.origin||'')
|
|
8464
|
-
if(!
|
|
8824
|
+
if(!explicitManagementIntent(req)||
|
|
8465
8825
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
8466
8826
|
return sendJson(res,403,{ok:false,error:'只能由电脑本机管理中心同源确认 MCP 安全修复'})
|
|
8467
8827
|
try {
|
|
@@ -8488,8 +8848,86 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8488
8848
|
'cache-control':'no-store','x-content-type-options':'nosniff'})
|
|
8489
8849
|
return res.end(body)
|
|
8490
8850
|
}
|
|
8851
|
+
// Storage V2: only one explicitly scheduled large-model migration; no V1
|
|
8852
|
+
// partition migration, return-home, stale-copy cleanup or legacy API.
|
|
8853
|
+
if ((req.method==='GET'&&path==='/api/bili-duty/storage/location')||
|
|
8854
|
+
(req.method==='POST'&&['/api/bili-duty/storage/check',
|
|
8855
|
+
'/api/bili-duty/storage/verify-model-runtime',
|
|
8856
|
+
'/api/bili-duty/storage/review-model-vision',
|
|
8857
|
+
'/api/bili-duty/storage/schedule-migration'].includes(path))) {
|
|
8858
|
+
const peer=String(req.socket?.remoteAddress||'')
|
|
8859
|
+
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
8860
|
+
if(!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(peer)||
|
|
8861
|
+
(req.method==='POST'&&path!=='/api/bili-duty/storage/check'&&!explicitManagementIntent(req))||
|
|
8862
|
+
origin&&(!host||![`http://${host}`,`https://${host}`].includes(origin))||
|
|
8863
|
+
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
8864
|
+
return sendJson(res,403,{ok:false,error:'仅允许电脑本机同源管理中心操作存储'})
|
|
8865
|
+
try{
|
|
8866
|
+
if(req.method==='GET')return sendJson(res,200,{ok:true,
|
|
8867
|
+
currentDir:stateDir,usage:storageCategories(stateDir),
|
|
8868
|
+
largeDataV2:largeDataStatus(stateDir),migrationJob:readMigrationJob(stateDir),
|
|
8869
|
+
platform:process.platform})
|
|
8870
|
+
const body=await readBody(req,2048)
|
|
8871
|
+
if(path==='/api/bili-duty/storage/check'){
|
|
8872
|
+
if(body?.domain!=='large'||body?.returnHome===true)throw Error('仅支持 V2 大型数据统一迁移')
|
|
8873
|
+
const result=inspectLargeDataMigration({root:stateDir,target:body.target})
|
|
8874
|
+
return sendJson(res,200,{...result,offlineMigrationOnly:true})
|
|
8875
|
+
}
|
|
8876
|
+
if(path==='/api/bili-duty/storage/schedule-migration'){
|
|
8877
|
+
if(body?.domain!=='large'||body?.returnHome===true)throw Error('旧版分区迁移与回迁已移除,只支持大型数据统一迁移')
|
|
8878
|
+
if(body?.confirm!=='SCHEDULE_STOPPED_MIGRATION')throw Error('请明确确认退出 DSH 后执行迁移')
|
|
8879
|
+
return sendJson(res,200,queueDomainMigration({root:stateDir,domain:'large',
|
|
8880
|
+
target:body.target,workerScript:join(pluginDir,'scripts','migrate-bili-duty-after-exit.mjs'),parentPid:process.pid}))
|
|
8881
|
+
}
|
|
8882
|
+
if(path==='/api/bili-duty/storage/verify-model-runtime'){
|
|
8883
|
+
if(['waiting','running'].includes(readMigrationJob(stateDir).status))
|
|
8884
|
+
throw Error('离线迁移尚未结束,暂停模型实测')
|
|
8885
|
+
if(storageModelVerificationBusy)throw Error('模型运行实测已经在进行,请勿重复启动')
|
|
8886
|
+
storageModelVerificationBusy=true;storageModelVerification=null
|
|
8887
|
+
try{
|
|
8888
|
+
const configBefore=JSON.stringify([cfg.asrModel,cfg.asrModelPath,cfg.visionEnabled,cfg.visionMode,cfg.visionLocalModel])
|
|
8889
|
+
const selectedVisionRuntime=selectHealthyVisionPython({fresh:true})
|
|
8890
|
+
const result=await verifyRelocatedModelRuntime({root:stateDir,asrPython:asrPython(),
|
|
8891
|
+
visionPython:productionVisionPython({mode:resolvedVisionMode(),mainPython:cfg.pythonPath,
|
|
8892
|
+
selectedVisionPython:selectedVisionRuntime.ok?selectedVisionRuntime.path:''}),
|
|
8893
|
+
visionPythonEnv:visionEnv({BILI_DUTY_HOME:stateDir}),
|
|
8894
|
+
asrModel:cfg.asrModel||'small',asrModelPath:cfg.asrModelPath||'',embeddingRuntime,
|
|
8895
|
+
visionEnabled:cfg.visionEnabled===true,visionMode:resolvedVisionMode(),
|
|
8896
|
+
visionDshReview:dshVisionReview,visionLocalModels:localVisionModels,
|
|
8897
|
+
visionLocalModel:cfg.visionLocalModel||'',visionThinking:cfg.visionLocalThinking||'off'})
|
|
8898
|
+
if(configBefore!==JSON.stringify([cfg.asrModel,cfg.asrModelPath,cfg.visionEnabled,cfg.visionMode,cfg.visionLocalModel]))
|
|
8899
|
+
throw Error('实测期间模型配置改变,结果作废,请重新验证')
|
|
8900
|
+
const ticket=randomUUID()
|
|
8901
|
+
storageModelVerification={ticket,at:Date.now(),target:result.target,ready:false,
|
|
8902
|
+
checks:result.checks,configKey:configBefore}
|
|
8903
|
+
const vision=result.checks.vision
|
|
8904
|
+
const evidence=vision.pendingReview?(vision.mode==='independent_dsh'?dshVisionReview.status():
|
|
8905
|
+
localVisionModels.reviewEvidence(vision.model)):null
|
|
8906
|
+
return sendJson(res,200,{...result,ticket,cleanupEligible:false,
|
|
8907
|
+
review:vision.pendingReview?{reviewId:vision.reviewId,answer:String(evidence?.answer||''),mode:vision.mode}:null})
|
|
8908
|
+
}finally{storageModelVerificationBusy=false}
|
|
8909
|
+
}
|
|
8910
|
+
if(path==='/api/bili-duty/storage/review-model-vision'){
|
|
8911
|
+
if(!storageModelVerification||body?.ticket!==storageModelVerification.ticket||
|
|
8912
|
+
Date.now()-storageModelVerification.at>10*60_000||
|
|
8913
|
+
JSON.stringify([cfg.asrModel,cfg.asrModelPath,cfg.visionEnabled,cfg.visionMode,cfg.visionLocalModel])!==storageModelVerification.configKey)
|
|
8914
|
+
throw Error('实测凭据已过期或配置已变化,请重新验证')
|
|
8915
|
+
const vision=storageModelVerification.checks.vision
|
|
8916
|
+
if(!vision.pendingReview||body?.accepted!==true&&body?.accepted!==false)
|
|
8917
|
+
throw Error('没有待确认的真实图片识别结果')
|
|
8918
|
+
const reply=vision.mode==='independent_dsh'
|
|
8919
|
+
?dshVisionReview.review({reviewId:vision.reviewId,accepted:body.accepted})
|
|
8920
|
+
:await localVisionModels.review(vision.model,{reviewId:vision.reviewId,accepted:body.accepted})
|
|
8921
|
+
vision.ok=reply.verified===true;vision.pendingReview=false
|
|
8922
|
+
vision.reason=vision.ok?'本人已确认图片识别正确':'图片识别未被认可'
|
|
8923
|
+
const ready=Object.values(storageModelVerification.checks).every(x=>x.ok===true)
|
|
8924
|
+
storageModelVerification.ready=ready
|
|
8925
|
+
return sendJson(res,200,{ok:true,ready,cleanupEligible:false,checks:storageModelVerification.checks})
|
|
8926
|
+
}
|
|
8927
|
+
}catch(error){return sendJson(res,400,{ok:false,error:String(error?.message||error).slice(0,180)})}
|
|
8928
|
+
}
|
|
8491
8929
|
// v2.4.69: user-configured backup directory and SQLite memory snapshots; never use OS Temp.
|
|
8492
|
-
if (req.method === 'POST' && ['/api/bili-duty/data-backup/location', '/api/bili-duty/data-backup/export', '/api/bili-duty/data-backup/inspect', '/api/bili-duty/data-backup/restore'].includes(path)) {
|
|
8930
|
+
if (req.method === 'POST' && ['/api/bili-duty/data-backup/location', '/api/bili-duty/data-backup/export', '/api/bili-duty/data-backup/inspect', '/api/bili-duty/data-backup/restore','/api/bili-duty/data-backup/list','/api/bili-duty/data-backup/preview','/api/bili-duty/data-backup/auto'].includes(path)) {
|
|
8493
8931
|
const origin = String(req.headers.origin || '')
|
|
8494
8932
|
const host = String(req.headers.host || '')
|
|
8495
8933
|
if (origin && (!host || ![ `http://${host}`, `https://${host}` ].includes(origin)))
|
|
@@ -8497,6 +8935,11 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8497
8935
|
if (String(req.headers['sec-fetch-site'] || '').toLowerCase() === 'cross-site')
|
|
8498
8936
|
return sendJson(res, 403, {ok:false,error:'拒绝来自其他网站的备份请求'})
|
|
8499
8937
|
const action = path.split('/').pop()
|
|
8938
|
+
// Backup browsing returns memory texts and file inventory; the local
|
|
8939
|
+
// desktop session is the only authorized reader of these new endpoints.
|
|
8940
|
+
if(['preview','list','auto'].includes(action)&&
|
|
8941
|
+
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(String(req.socket?.remoteAddress||'')))
|
|
8942
|
+
return sendJson(res,403,{ok:false,error:'备份内容仅允许本机管理中心查看'})
|
|
8500
8943
|
try {
|
|
8501
8944
|
if (action === 'location') {
|
|
8502
8945
|
const body = await readBody(req, 12_000)
|
|
@@ -8505,40 +8948,32 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8505
8948
|
const {host} = await persistCfg({backupDirectory:folder})
|
|
8506
8949
|
return sendJson(res, 200, {ok:true,directory:folder,hostSynced:host.ok})
|
|
8507
8950
|
}
|
|
8508
|
-
|
|
8509
|
-
|
|
8510
|
-
|
|
8511
|
-
|
|
8512
|
-
|
|
8513
|
-
|
|
8514
|
-
|
|
8515
|
-
|
|
8516
|
-
child.stdin.on('error', e=>fail(Error('向 SQLite 备份工具写数据失败:'+String(e?.message||e))))
|
|
8517
|
-
child.stdout.on('data', chunk => {stdout+=chunk.toString();if(stdout.length>45_000_000){child.kill();fail(Error('SQLite 备份数据过大'))}})
|
|
8518
|
-
child.stderr.on('data', chunk => {stderr+=chunk.toString().slice(0,800)})
|
|
8519
|
-
child.on('close', code => {if(settled)return;settled=true;try{const result=JSON.parse(stdout||'{}');if(code!==0||!result.ok)throw Error(result.error||stderr||'SQLite 工具异常');resolve(result)}catch(e){reject(e)}})
|
|
8520
|
-
try{child.stdin.end(data ? JSON.stringify(data):'')}catch(e){fail(e)}
|
|
8521
|
-
})
|
|
8522
|
-
const snapshot = async () => {
|
|
8951
|
+
if (action === 'auto') {
|
|
8952
|
+
const body=await readBody(req,1024)
|
|
8953
|
+
if(typeof body?.enabled!=='boolean')throw Error('自动备份开关必须明确选择')
|
|
8954
|
+
const result=await persistCfg({backupAutoEnabled:body.enabled})
|
|
8955
|
+
if(body.enabled)void runDailyBackup()
|
|
8956
|
+
return sendJson(res,200,{ok:true,enabled:body.enabled,hostSynced:result.host.ok})
|
|
8957
|
+
}
|
|
8958
|
+
if (action === 'list') {
|
|
8523
8959
|
refreshCfg()
|
|
8524
|
-
const
|
|
8525
|
-
|
|
8526
|
-
|
|
8527
|
-
|
|
8528
|
-
const
|
|
8529
|
-
|
|
8530
|
-
|
|
8531
|
-
return createBackup({root:stateDir,config:effective,sqlite,version:myVersion()})
|
|
8960
|
+
const dir=requireBackupDirectory(cfg.backupDirectory)
|
|
8961
|
+
return sendJson(res,200,{ok:true,directory:dir,autoEnabled:cfg.backupAutoEnabled!==false,files:listBackupFiles(dir),lastAttempt: autoBackupState.lastAttemptAt,lastSuccess:autoBackupState.lastSuccessAt,lastError:autoBackupState.lastError,retentionDays:5})
|
|
8962
|
+
}
|
|
8963
|
+
if (action === 'preview') {
|
|
8964
|
+
const body=await readBody(req,2048)
|
|
8965
|
+
refreshCfg()
|
|
8966
|
+
return sendJson(res,200,{ok:true,...inspectBackupInDirectory(requireBackupDirectory(cfg.backupDirectory),body?.name)})
|
|
8532
8967
|
}
|
|
8533
8968
|
if (action === 'export') {
|
|
8534
8969
|
refreshCfg()
|
|
8535
8970
|
const folder = requireBackupDirectory(cfg.backupDirectory)
|
|
8536
|
-
const backup = await
|
|
8971
|
+
const backup = await snapshotBusinessBackup()
|
|
8537
8972
|
const filePath = saveBackupJson(folder, backup)
|
|
8538
8973
|
log('用户数据已备份到:'+filePath)
|
|
8539
8974
|
return sendJson(res, 200, {ok:true,filePath,summary:validateBackup(backup)})
|
|
8540
8975
|
}
|
|
8541
|
-
const body = await readBackupBody(req,
|
|
8976
|
+
const body = await readBackupBody(req, 320_000_000)
|
|
8542
8977
|
const data = body?.backup
|
|
8543
8978
|
const summary = validateBackup(data)
|
|
8544
8979
|
if (action === 'restore') validateRestoreIdentity(stateDir,data)
|
|
@@ -8555,7 +8990,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8555
8990
|
// User-chosen destination: no system Temp fallback, never overwrite prior snapshots.
|
|
8556
8991
|
refreshCfg()
|
|
8557
8992
|
const folder = requireBackupDirectory(cfg.backupDirectory)
|
|
8558
|
-
const safeguard = await
|
|
8993
|
+
const safeguard = await snapshotBusinessBackup()
|
|
8559
8994
|
const safeguardPath = saveBackupJson(folder, safeguard, 'pre-restore')
|
|
8560
8995
|
const backupName = safeguardPath.split(/[\\/]/).at(-1)
|
|
8561
8996
|
// Full restore is a three-part operation. Keep the verified pre-restore
|
|
@@ -8578,7 +9013,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8578
9013
|
// Remove files introduced solely by the failed restore. Never
|
|
8579
9014
|
// follow symlinks; leave other unrelated files untouched.
|
|
8580
9015
|
for(const name of Object.keys(data.files))if(!Object.hasOwn(safeguard.files,name)){
|
|
8581
|
-
const file=
|
|
9016
|
+
const file=storageDataPath(stateDir,...name.split('/'))
|
|
8582
9017
|
if(existsSync(file)&&lstatSync(file).isFile()&&!lstatSync(file).isSymbolicLink())rmSync(file)
|
|
8583
9018
|
}
|
|
8584
9019
|
}catch(e){rollbackErrors.push('文件:'+String(e?.message||e).slice(0,100))}
|
|
@@ -8658,7 +9093,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8658
9093
|
: String(id)
|
|
8659
9094
|
const commandArgs = [py, stateDir, operation, mutation ? data : keyword]
|
|
8660
9095
|
const result = await new Promise(resolve => {
|
|
8661
|
-
const child = spawn(cfg.pythonPath || 'python',commandArgs,{cwd:stateDir,shell:false,windowsHide:true,env:
|
|
9096
|
+
const child = spawn(cfg.pythonPath || 'python',commandArgs,{cwd:stateDir,shell:false,windowsHide:true,env:storagePyEnv(),stdio:['ignore','pipe','pipe']})
|
|
8662
9097
|
// Keep a bounded *complete* JSON document, never the trailing bytes of a
|
|
8663
9098
|
// larger JSON stream. The old slice(-22000) made a healthy meme library
|
|
8664
9099
|
// unreadable as soon as enough entries/sources were returned.
|
|
@@ -8685,6 +9120,164 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8685
9120
|
// The helper binds results to the CURRENT login (HMAC; no UID or cookie returned).
|
|
8686
9121
|
return sendJson(res,200,readVideoDiscussionDiagnostics({stateDir,credential:dmCred(stateDir)}))
|
|
8687
9122
|
}
|
|
9123
|
+
// dev.6: explicit owner-only, read-only video revisit. The selected gallery
|
|
9124
|
+
// record is a time anchor, not permission to assert a visual conclusion.
|
|
9125
|
+
if(path==='/api/bili-duty/life-video-gallery/focus'||
|
|
9126
|
+
path==='/api/bili-duty/life-video-gallery/focus/status'){
|
|
9127
|
+
const peer=String(req.socket?.remoteAddress||'')
|
|
9128
|
+
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
9129
|
+
if(!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(peer)||
|
|
9130
|
+
origin&&(!host||![`http://${host}`,`https://${host}`].includes(origin))||
|
|
9131
|
+
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
9132
|
+
return sendJson(res,403,{ok:false,reason:'local-same-origin-required'})
|
|
9133
|
+
const account=trustedLifeAccountTag()
|
|
9134
|
+
if(!hasCredential()||!account||accountBinding.status().blocked)
|
|
9135
|
+
return sendJson(res,401,{ok:false,reason:'account-not-verified'})
|
|
9136
|
+
if(req.method==='GET'&&path.endsWith('/status')){
|
|
9137
|
+
const job=ownerGalleryFocusJob
|
|
9138
|
+
return sendJson(res,200,{ok:true,job:job?.account===account?{
|
|
9139
|
+
id:job.id,bvid:job.bvid,status:job.status,stage:job.stage||'unknown',reason:job.reason||'',
|
|
9140
|
+
anchorSeconds:job.anchorSeconds,memory:job.memory||null,
|
|
9141
|
+
updatedAt:job.updatedAt}:null})
|
|
9142
|
+
}
|
|
9143
|
+
if(req.method!=='POST'||path.endsWith('/status'))return sendJson(res,405,{ok:false,reason:'method-not-allowed'})
|
|
9144
|
+
if(ownerGalleryFocusBusy)return sendJson(res,409,{ok:false,reason:'focus-already-running',error:'当前已有视频补看正在进行'})
|
|
9145
|
+
refreshCfg()
|
|
9146
|
+
if(cfg.masterEnabled!==true||cfg.visionEnabled!==true||
|
|
9147
|
+
!['independent_dsh','independent_local'].includes(resolvedVisionMode()))
|
|
9148
|
+
return sendJson(res,409,{ok:false,reason:'vision-not-enabled'})
|
|
9149
|
+
const body=await readBody(req,1600)
|
|
9150
|
+
if(body?.confirm!=='OWNER_READ_ONLY_REVISIT'||
|
|
9151
|
+
!/^[a-f0-9]{32}$/.test(String(body.galleryId||''))||
|
|
9152
|
+
!validBv(String(body.bvid||'')))return sendJson(res,400,{ok:false,reason:'invalid-owner-confirmation'})
|
|
9153
|
+
let gallery
|
|
9154
|
+
try{gallery=listLifeVideoGallery(stateDir,account).find(row=>row.id===body.galleryId&&row.bvid===body.bvid)}
|
|
9155
|
+
catch{return sendJson(res,409,{ok:false,reason:'gallery-unavailable'})}
|
|
9156
|
+
if(!gallery)return sendJson(res,404,{ok:false,reason:'gallery-not-found-or-expired'})
|
|
9157
|
+
const bvid=gallery.bvid
|
|
9158
|
+
let info
|
|
9159
|
+
try{info=parseMaybeJson(await call('bili_video_info',{bvid}))}
|
|
9160
|
+
catch(error){log('主人补看预检失败:video-metadata-unavailable '+String(error?.code||'').slice(0,45));return sendJson(res,409,{ok:false,reason:'video-metadata-unavailable'})}
|
|
9161
|
+
if(account!==trustedLifeAccountTag()||accountBinding.status().blocked)
|
|
9162
|
+
return sendJson(res,409,{ok:false,reason:'account-changed'})
|
|
9163
|
+
const durationSeconds=Number(info?.duration)
|
|
9164
|
+
const plan=planOwnerGalleryRevisit({row:gallery,account,bvid,mode:body.mode,
|
|
9165
|
+
atSeconds:body.atSeconds,imageFile:body.imageFile,durationSeconds})
|
|
9166
|
+
if(!plan.ok){log('主人补看拒绝:'+String(plan.reason||'invalid-plan').slice(0,70));return sendJson(res,400,{ok:false,reason:plan.reason})}
|
|
9167
|
+
const id=randomUUID().replaceAll('-',''),startedAt=Date.now()
|
|
9168
|
+
const job={id,account,bvid,galleryId:gallery.id,anchorSeconds:plan.anchorSeconds,
|
|
9169
|
+
status:'running',stage:'queued',updatedAt:startedAt,reason:'',memory:null}
|
|
9170
|
+
ownerGalleryFocusJob=job;ownerGalleryFocusBusy=true
|
|
9171
|
+
// Keep the worker's identity fixed across asynchronous network / model calls.
|
|
9172
|
+
const scope=()=>ownerGalleryFocusJob===job&&account===trustedLifeAccountTag()&&
|
|
9173
|
+
!accountBinding.status().blocked&&cfg.visionEnabled===true&&hasCredential()
|
|
9174
|
+
Promise.resolve().then(async()=>{
|
|
9175
|
+
if(!scope())return {ok:false,reason:'account-changed'}
|
|
9176
|
+
return withLifeVideoVisualLease(stateDir,{accountTag:account,bvid},async()=>{
|
|
9177
|
+
if(!scope())return {ok:false,reason:'account-changed'}
|
|
9178
|
+
job.stage='video-read';job.updatedAt=Date.now()
|
|
9179
|
+
const budget=Number(cfg.visionFrames)>=48?100*1048576:
|
|
9180
|
+
Number(cfg.visionFrames)>=24?50*1048576:24*1048576
|
|
9181
|
+
const stop=liveLifeActivity.start('video-observe',account,{maxAgeMs:8*60_000,bvid})
|
|
9182
|
+
let visual
|
|
9183
|
+
try{visual=parseMaybeJson(await call('bili_preview_vision',{
|
|
9184
|
+
bvid,perception_source:'adaptive',view_depth:'deep',
|
|
9185
|
+
focus_start_seconds:plan.startSeconds,focus_end_seconds:plan.endSeconds,
|
|
9186
|
+
network_budget_bytes:budget,frame_budget_limit:Math.min(12,Math.max(4,Number(cfg.visionFrames)||12)),
|
|
9187
|
+
capture_for_gallery:true}))}
|
|
9188
|
+
catch(error){log('主人补看视觉读取失败:'+String(error?.code||error?.message||'unknown').slice(0,120));return {ok:false,reason:'focus-tool-failed'}}
|
|
9189
|
+
finally{stop()}
|
|
9190
|
+
if(!scope())return {ok:false,reason:'account-changed'}
|
|
9191
|
+
job.stage='verification';job.updatedAt=Date.now()
|
|
9192
|
+
const capture=safeVideoDebugCapture(visual?.debugCapture,bvid)
|
|
9193
|
+
if(visual&&typeof visual==='object')delete visual.debugCapture
|
|
9194
|
+
const evidence=buildVideoEvidenceBundle({bvid,info,visual})
|
|
9195
|
+
const review=verifyVideoFocusReview({bvid,plan:{...plan,networkBudgetBytes:budget},
|
|
9196
|
+
result:visual,evidence})
|
|
9197
|
+
if(!review)return {ok:false,reason:diagnoseVideoFocusReceipt({bvid,
|
|
9198
|
+
plan:{...plan,networkBudgetBytes:budget},result:visual,evidence}).code}
|
|
9199
|
+
if(!scope())return {ok:false,reason:'account-changed'}
|
|
9200
|
+
job.stage='memory-write';job.updatedAt=Date.now()
|
|
9201
|
+
let gallerySaved=false
|
|
9202
|
+
let memory={status:'not-linked',reason:'no-fresh-detail-evidence'},memoryState='not-recorded'
|
|
9203
|
+
try{if(visual?.status==='analyzed'&&lifeMemory&&scope()){
|
|
9204
|
+
// This is a NEW verified read. Preserve its own lifetime and bind
|
|
9205
|
+
// the attachment to the exact new episode, even for legacy galleries.
|
|
9206
|
+
// BV aggregation is a read projection, not a guessed parent match.
|
|
9207
|
+
const event=buildVideoExplorationEvent({bvid,info,visual,source:'bili-life',
|
|
9208
|
+
purpose:'owner-manual-revisit',operationId:id,accountTag:account})
|
|
9209
|
+
if(event){
|
|
9210
|
+
event.experience.focusWindow={startMs:review.startMs,endMs:review.endMs,
|
|
9211
|
+
frames:review.frameTimesMs.length,source:review.source}
|
|
9212
|
+
const stored=await lifeMemoryCoordinator?.recordEvents([event],{reflect:true})
|
|
9213
|
+
memoryState=stored?.ok===true?'recorded':'coordination-pending'
|
|
9214
|
+
if(scope()){
|
|
9215
|
+
const memoryId='e-'+createHash('sha256').update(event.key).digest('hex').slice(0,18)
|
|
9216
|
+
const sourceRef='focus:'+id
|
|
9217
|
+
const verifiedFragments=buildFreshVideoDetails({bvid,info,visual,event,sourceRef})
|
|
9218
|
+
const proof=Object.freeze({memoryId,accountTag:account,bvid,sourceRef,fragmentCount:verifiedFragments.length,at:Date.now()})
|
|
9219
|
+
admittedOwnerFocusProofs.add(proof)
|
|
9220
|
+
try{
|
|
9221
|
+
const result=lifeMemory.recordVerifiedFocusRevision({memoryId,accountTag:account,
|
|
9222
|
+
bvid,review,sourceProof:proof,sourceRef,verifiedFragments})
|
|
9223
|
+
memory=result.ok?{status:'updated',memoryId,shallowVersion:result.shallowVersion,
|
|
9224
|
+
deepFragments:result.deepFragments}:result.detailPersisted?
|
|
9225
|
+
{status:'partial',reason:result.reason,deepPersisted:true}:{status:'not-updated',reason:result.reason}
|
|
9226
|
+
}finally{admittedOwnerFocusProofs.delete(proof)}
|
|
9227
|
+
}
|
|
9228
|
+
}
|
|
9229
|
+
}else if(visual?.status==='cached'){memoryState='not-recorded-cached';memory={status:'not-updated',reason:'cached-no-new-evidence'}}
|
|
9230
|
+
}catch(error){memoryState='write-failed';memory={status:'not-updated',reason:'memory-write-exception'};log('主人补看记忆保存失败:'+String(error?.message||error).slice(0,100))}
|
|
9231
|
+
if(capture&&scope()){const saved=addLifeVideoGallery(stateDir,{account,bvid,captures:[capture],
|
|
9232
|
+
verified:true,phase:'focus',groupId:gallery.groupId||gallery.id,
|
|
9233
|
+
note:String(review.description||'').slice(0,360),analysis:visual?.description,boardReceipts:visual?.visionBoardReceipts,memoryWrite:{status:memoryState,detailStatus:memory.status,detailReason:memory.reason}})
|
|
9234
|
+
gallerySaved=saved.ok===true}
|
|
9235
|
+
return {ok:true,review,mem:memory,gallerySaved}
|
|
9236
|
+
})
|
|
9237
|
+
}).then(outcome=>{
|
|
9238
|
+
if(!scope()){
|
|
9239
|
+
if(ownerGalleryFocusJob===job){job.status='failed';job.reason='account-changed';job.updatedAt=Date.now()}
|
|
9240
|
+
return
|
|
9241
|
+
}
|
|
9242
|
+
job.status=outcome?.ok===true?'verified':'failed';job.stage='finished'
|
|
9243
|
+
job.reason=outcome?.ok===true?(outcome.gallerySaved?'verified-new-focus':'verified-images-unavailable'):
|
|
9244
|
+
String(outcome?.reason||'focus-unverified').slice(0,90)
|
|
9245
|
+
job.memory=outcome?.mem||null;job.updatedAt=Date.now()
|
|
9246
|
+
}).catch(error=>{
|
|
9247
|
+
if(ownerGalleryFocusJob!==job)return
|
|
9248
|
+
job.status='failed';job.stage='finished';job.reason='focus-execution-failed';job.updatedAt=Date.now()
|
|
9249
|
+
log('主人视频补看执行失败:'+String(error?.message||error).slice(0,120))
|
|
9250
|
+
}).finally(()=>{ownerGalleryFocusBusy=false})
|
|
9251
|
+
return sendJson(res,202,{ok:true,id,status:'running',bvid,
|
|
9252
|
+
anchorSeconds:plan.anchorSeconds,notice:'只读视频补看已受理;仅真实新观察核验成功才写入本次经历及深层附件'})
|
|
9253
|
+
}
|
|
9254
|
+
// dev.4: current-account 12-hour Life image gallery; not the Debug endpoint,
|
|
9255
|
+
// never serves arbitrary paths, old accounts or expired files.
|
|
9256
|
+
if(req.method==='GET'&&(path==='/api/bili-duty/life-video-gallery'||
|
|
9257
|
+
path.startsWith('/api/bili-duty/life-video-gallery/image/'))){
|
|
9258
|
+
const peer=String(req.socket?.remoteAddress||'')
|
|
9259
|
+
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
9260
|
+
if(!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(peer)||
|
|
9261
|
+
origin&&(!host||![`http://${host}`,`https://${host}`].includes(origin))||
|
|
9262
|
+
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
9263
|
+
return sendJson(res,403,{ok:false,error:'视觉回放仅限本机同源管理中心'})
|
|
9264
|
+
const account=trustedLifeAccountTag()
|
|
9265
|
+
if(!hasCredential()||!account||accountBinding.status().blocked)
|
|
9266
|
+
return sendJson(res,401,{ok:false,error:'当前 B站账号尚未完成可信核验'})
|
|
9267
|
+
try{
|
|
9268
|
+
if(path==='/api/bili-duty/life-video-gallery'){
|
|
9269
|
+
pruneLifeVideoGallery(stateDir,account)
|
|
9270
|
+
return sendJson(res,200,{ok:true,retentionHours:LIFE_GALLERY_RETENTION_HOURS,rows:listLifeVideoGallery(stateDir,account)})
|
|
9271
|
+
}
|
|
9272
|
+
const match=/^\/api\/bili-duty\/life-video-gallery\/image\/([a-f0-9]{32})\/((?:storyboard|focus)-\d{2}\.jpg)$/.exec(path)
|
|
9273
|
+
if(!match)return sendJson(res,404,{ok:false,error:'图片不存在'})
|
|
9274
|
+
const bytes=readLifeVideoGalleryImage(stateDir,account,match[1],match[2])
|
|
9275
|
+
if(!bytes)return sendJson(res,404,{ok:false,error:'图片不存在或已过期'})
|
|
9276
|
+
res.writeHead(200,{'Content-Type':'image/jpeg','Content-Length':bytes.length,
|
|
9277
|
+
'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'})
|
|
9278
|
+
return res.end(bytes)
|
|
9279
|
+
}catch(error){return sendJson(res,409,{ok:false,error:String(error?.message||error).slice(0,150)})}
|
|
9280
|
+
}
|
|
8688
9281
|
if (path === '/api/bili-duty/video-perception-debug' || path === '/api/bili-duty/video-perception-debug/run' ||
|
|
8689
9282
|
path === '/api/bili-duty/video-perception-debug/focus' ||
|
|
8690
9283
|
path.startsWith('/api/bili-duty/video-perception-debug/image/')) {
|
|
@@ -8710,7 +9303,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8710
9303
|
const root=join(stateDir,'vision-perception-captures'),folder=join(root,id),target=join(folder,file)
|
|
8711
9304
|
try{
|
|
8712
9305
|
if(lstatSync(root).isSymbolicLink()||lstatSync(folder).isSymbolicLink()||lstatSync(target).isSymbolicLink())throw Error('unsafe')
|
|
8713
|
-
if(now-statSync(folder).mtimeMs
|
|
9306
|
+
if(now-statSync(folder).mtimeMs>=videoDebugExpiry||statSync(target).size>600000)throw Error('expired')
|
|
8714
9307
|
const contents=readFileSync(target)
|
|
8715
9308
|
if(contents.length<4||contents[0]!==0xff||contents[1]!==0xd8)throw Error('invalid')
|
|
8716
9309
|
res.writeHead(200,{'Content-Type':'image/jpeg','Content-Length':contents.length,
|
|
@@ -8724,11 +9317,13 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8724
9317
|
return sendJson(res,200,{ok:true,job:current&&{id:current.id,status:current.status,stage:current.stage,step:current.step,updatedAt:current.updatedAt,at:current.at,
|
|
8725
9318
|
sourceMode:current.sourceMode,viewDepth:current.viewDepth,
|
|
8726
9319
|
...(current.visionFailure?{visionFailure:current.visionFailure}:{}),
|
|
9320
|
+
...(current.visualDiagnostic?{visualDiagnostic:current.visualDiagnostic}:{}),
|
|
8727
9321
|
...(current.ownerFocus?{ownerFocus:current.ownerFocus}:{}),
|
|
8728
9322
|
...(current.status==='done'&¤t.twoStage?{twoStage:current.twoStage}:{}),
|
|
8729
9323
|
...(current.status==='done'?{lifeInput:current.payload,images:current.images||[],visionOutcome:current.visionOutcome||'no_model_answer'}:{}),...(current.status==='error'?{error:current.error}:{})},
|
|
8730
9324
|
lastLife:last&&{at:last.at,lifeInput:last.payload,images:last.images||[]},
|
|
8731
|
-
lastSummary:previous,visionRoute:{mode:resolvedVisionMode(),enabled:cfg.visionEnabled===true
|
|
9325
|
+
lastSummary:previous,visionRoute:{mode:resolvedVisionMode(),enabled:cfg.visionEnabled===true,
|
|
9326
|
+
localModel:resolvedVisionMode()==='independent_local'?cfg.visionLocalModel||'':null},
|
|
8732
9327
|
retention:'volatile-30m',source:'actual-bili-watch-video-return'})
|
|
8733
9328
|
}
|
|
8734
9329
|
const checkVideoDebugOllama=async()=>{
|
|
@@ -8770,7 +9365,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8770
9365
|
saveVideoDebugSummary(stateDir,job,account)
|
|
8771
9366
|
const watchdog=setTimeout(()=>{
|
|
8772
9367
|
if(videoDebugJob===job&&job.status==='running'){
|
|
8773
|
-
job.status='error';job.error='局部视频验收超过8
|
|
9368
|
+
job.status='error';job.error='局部视频验收超过8分钟,未取得完成回执;程序会自动收尾本轮受限任务,未核验的 B站读取不重放';
|
|
8774
9369
|
job.stage=job.error;job.updatedAt=Date.now();saveVideoDebugSummary(stateDir,job,account)
|
|
8775
9370
|
}
|
|
8776
9371
|
},8*60_000);watchdog.unref?.()
|
|
@@ -8780,11 +9375,15 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8780
9375
|
Promise.resolve().then(async()=>{
|
|
8781
9376
|
if(!safeScope())return {ok:false,reason:'account-or-job-changed'}
|
|
8782
9377
|
let visual
|
|
8783
|
-
try{visual=parseMaybeJson(await
|
|
9378
|
+
try{visual=parseMaybeJson(await callOwnerVideoDebugVision({
|
|
8784
9379
|
bvid,perception_source:'adaptive',view_depth:'deep',
|
|
8785
9380
|
focus_start_seconds:plan.startSeconds,focus_end_seconds:plan.endSeconds,
|
|
8786
9381
|
network_budget_bytes:networkBudgetBytes,frame_budget_limit:frameBudgetLimit,
|
|
8787
|
-
capture_for_debug:true}
|
|
9382
|
+
capture_for_debug:true},{onStage:phase=>{
|
|
9383
|
+
if(videoDebugJob!==job||job.status!=='running')return
|
|
9384
|
+
job.visualDiagnostic={...job.visualDiagnostic,phase,at:Date.now()};job.updatedAt=Date.now()
|
|
9385
|
+
saveVideoDebugSummary(stateDir,job,account)
|
|
9386
|
+
}}))}
|
|
8788
9387
|
catch{return {ok:false,reason:'focus-tool-failed'}}
|
|
8789
9388
|
if(!safeScope())return {ok:false,reason:'account-or-job-changed'}
|
|
8790
9389
|
const captured=safeVideoDebugCapture(visual?.debugCapture,bvid)
|
|
@@ -8849,7 +9448,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8849
9448
|
saveVideoDebugSummary(stateDir,job,account)
|
|
8850
9449
|
const watchdog=setTimeout(()=>{
|
|
8851
9450
|
if(videoDebugJob===job&&job.status==='running'){
|
|
8852
|
-
job.status='error';job.stage='视频感知处理超出 8 分钟';job.error=
|
|
9451
|
+
job.status='error';job.stage='视频感知处理超出 8 分钟';job.error=ownerDebugTimeoutMessage(job);job.updatedAt=Date.now()
|
|
8853
9452
|
saveVideoDebugSummary(stateDir,job,account)
|
|
8854
9453
|
}
|
|
8855
9454
|
},8*60_000);watchdog.unref?.()
|
|
@@ -8878,8 +9477,12 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8878
9477
|
if(videoDebugJob!==job||job.status!=='running')return
|
|
8879
9478
|
if(videoDebugAccount()!==job.account){job.status='error';job.stage='账号已切换';job.error='账号变化,已丢弃本轮诊断结果'}
|
|
8880
9479
|
else {
|
|
8881
|
-
|
|
8882
|
-
|
|
9480
|
+
// Page timeout and backend visual timeout are distinct. Never
|
|
9481
|
+
// turn a real MCP timeout into a misleading 'Debug completed'.
|
|
9482
|
+
const visualTimedOut=result?.visual?.errorCode==='owner_debug_visual_timeout'
|
|
9483
|
+
job.status=result?.ok===true&&!visualTimedOut?'done':'error'
|
|
9484
|
+
job.stage=visualTimedOut?'本地 Ollama 视觉读取超时':
|
|
9485
|
+
job.status==='done'?'完成,只读 Life 输入已生成':'只读感知失败'
|
|
8883
9486
|
if(job.status==='done'){
|
|
8884
9487
|
job.payload=result
|
|
8885
9488
|
job.visionFailure=explainVideoVisionFailure(result?.visual)
|
|
@@ -8890,7 +9493,17 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8890
9493
|
?'全局分镜已验证;请在下面选择一个真实采样时刻,再开始局部识图'
|
|
8891
9494
|
:job.visionFailure?.message||'全局分镜未通过证据验证,无法进入主人局部专项'
|
|
8892
9495
|
else if(job.visionFailure)job.stage=job.visionFailure.message
|
|
8893
|
-
}else
|
|
9496
|
+
}else{
|
|
9497
|
+
job.error=String(result?.visual?.error||result?.error||'视频感知未完成').slice(0,240)
|
|
9498
|
+
if(visualTimedOut){
|
|
9499
|
+
const phase=job.visualDiagnostic?.phase
|
|
9500
|
+
job.error+=' '+ownerDebugOllamaSummary(job.visualDiagnostic?.ollama)+' 最后确认阶段:'+({
|
|
9501
|
+
'worker-starting':'Python 进程启动','tool-started':'工具已启动',
|
|
9502
|
+
'reservation-waiting':'等待只读预约','frames-reading':'视频取帧',
|
|
9503
|
+
'frames-settled':'取帧已结算','model-running':'Ollama 推理',
|
|
9504
|
+
'tool-finished':'工具已返回'}[phase]||'无底层阶段回执')+';具体根因尚未确认。'
|
|
9505
|
+
}
|
|
9506
|
+
}
|
|
8894
9507
|
}
|
|
8895
9508
|
job.updatedAt=Date.now();saveVideoDebugSummary(stateDir,job,account)
|
|
8896
9509
|
}).catch(error=>{if(videoDebugJob===job&&job.status==='running'){job.status='error';job.stage='执行失败';
|
|
@@ -8966,7 +9579,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8966
9579
|
// URLs or account/private media data are persisted or returned.
|
|
8967
9580
|
const result = await new Promise(resolve => {
|
|
8968
9581
|
const child = spawn(cfg.pythonPath || 'python', [join(pluginDir,'lib','video_traffic.py'),'--home',stateDir,'--summary'], {
|
|
8969
|
-
cwd:stateDir,shell:false,windowsHide:true,env:
|
|
9582
|
+
cwd:stateDir,shell:false,windowsHide:true,env:storagePyEnv(),stdio:['ignore','pipe','pipe']
|
|
8970
9583
|
})
|
|
8971
9584
|
let output='',finished=false
|
|
8972
9585
|
const complete=data=>{if(finished)return;finished=true;clearTimeout(timer);resolve(data)}
|
|
@@ -8983,7 +9596,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
8983
9596
|
const getQuota = () => new Promise((resolve) => {
|
|
8984
9597
|
const child = spawn(cfg.pythonPath || 'python', [script, stateDir], {
|
|
8985
9598
|
cwd: stateDir, shell: false, windowsHide: true,
|
|
8986
|
-
env:
|
|
9599
|
+
env: storagePyEnv(), stdio: ['ignore', 'pipe', 'pipe'],
|
|
8987
9600
|
})
|
|
8988
9601
|
let out = '', done = false
|
|
8989
9602
|
const finish = (r) => { if (done) return; done = true; clearTimeout(timer); resolve(r) }
|
|
@@ -9097,7 +9710,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9097
9710
|
const py=existsSync(venvPython())?venvPython():String(cfg.pythonPath||'python')
|
|
9098
9711
|
const script=join(pluginDir,'lib','comment-meme-rule-preview.py')
|
|
9099
9712
|
const result=await new Promise(resolve=>{
|
|
9100
|
-
const child=spawn(py,[script,stateDir,query],{cwd:stateDir,shell:false,windowsHide:true,env:
|
|
9713
|
+
const child=spawn(py,[script,stateDir,query],{cwd:stateDir,shell:false,windowsHide:true,env:storagePyEnv(),stdio:['pipe','pipe','pipe']})
|
|
9101
9714
|
child.stdin.on('error',()=>{})
|
|
9102
9715
|
child.stdin.end(previewRules?JSON.stringify(previewRules):'')
|
|
9103
9716
|
let output='',finished=false
|
|
@@ -9134,7 +9747,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9134
9747
|
const py=existsSync(venvPython())?venvPython():String(cfg.pythonPath||'python')
|
|
9135
9748
|
const helper=join(pluginDir,'lib','sticker-archive.py')
|
|
9136
9749
|
const result=await new Promise(resolve=>{
|
|
9137
|
-
const child=spawn(py,[helper,stateDir,'export'],{cwd:stateDir,shell:false,windowsHide:true,env:
|
|
9750
|
+
const child=spawn(py,[helper,stateDir,'export'],{cwd:stateDir,shell:false,windowsHide:true,env:storagePyEnv(),stdio:['ignore','pipe','pipe']})
|
|
9138
9751
|
const chunks=[];let bytes=0,err='',done=false
|
|
9139
9752
|
const finish=v=>{if(done)return;done=true;clearTimeout(timer);resolve(v)}
|
|
9140
9753
|
const timer=setTimeout(()=>{try{child.kill()}catch{};finish({ok:false,error:'表情包 ZIP 导出超时'})},90000)
|
|
@@ -9159,7 +9772,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9159
9772
|
const py=existsSync(venvPython())?venvPython():String(cfg.pythonPath||'python')
|
|
9160
9773
|
const helper=join(pluginDir,'lib','sticker-archive.py')
|
|
9161
9774
|
const result=await new Promise(resolve=>{
|
|
9162
|
-
const child=spawn(py,[helper,stateDir,'import'],{cwd:stateDir,shell:false,windowsHide:true,env:
|
|
9775
|
+
const child=spawn(py,[helper,stateDir,'import'],{cwd:stateDir,shell:false,windowsHide:true,env:storagePyEnv(),stdio:['pipe','pipe','pipe']})
|
|
9163
9776
|
let out='',err='',done=false
|
|
9164
9777
|
const finish=v=>{if(done)return;done=true;clearTimeout(timer);resolve(v)}
|
|
9165
9778
|
const timer=setTimeout(()=>{try{child.kill()}catch{};finish({ok:false,error:'表情包 ZIP 导入超时'})},120000)
|
|
@@ -9182,7 +9795,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9182
9795
|
const py=join(pluginDir,'lib','sticker-admin.py')
|
|
9183
9796
|
const result=await new Promise(resolve=>{
|
|
9184
9797
|
const child=spawn(cfg.pythonPath||'python',[py,stateDir,operation],
|
|
9185
|
-
{cwd:stateDir,shell:false,windowsHide:true,env:
|
|
9798
|
+
{cwd:stateDir,shell:false,windowsHide:true,env:storagePyEnv(),stdio:['pipe','pipe','pipe']})
|
|
9186
9799
|
let out='',done=false
|
|
9187
9800
|
const finish=(value)=>{if(done)return;done=true;clearTimeout(timer);resolve(value)}
|
|
9188
9801
|
const timer=setTimeout(()=>{try{child.kill()}catch{};finish({ok:false,error:'表情包操作超时'})},20000)
|
|
@@ -9444,6 +10057,9 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9444
10057
|
catch(e){return sendJson(res,500,{ok:false,error:'只读动作执行诊断不可用:'+String(e?.message||e).slice(0,100)})}
|
|
9445
10058
|
}
|
|
9446
10059
|
if(req.method==='POST'&&path==='/api/bili-duty/read-action-executions/acknowledge'){
|
|
10060
|
+
// Developer emergency tool only. Never expose an ordinary-user release
|
|
10061
|
+
// path or accept a browser unlock without explicit host startup opt-in.
|
|
10062
|
+
if(process.env.DSH_DEV_READ_ACTION_UNLOCK!=='1')return sendJson(res,403,{ok:false,error:'仅限开发者临时维护;普通视频读取由系统自动恢复'})
|
|
9447
10063
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
9448
10064
|
if(origin&&(!host||![`http://${host}`,`https://${host}`].includes(origin)))return sendJson(res,403,{ok:false,error:'仅允许管理中心同源复核'})
|
|
9449
10065
|
if(String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')return sendJson(res,403,{ok:false,error:'拒绝跨站复核'})
|
|
@@ -9639,7 +10255,18 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9639
10255
|
}
|
|
9640
10256
|
// 大肥鱼主 Session:只看当前 DSH 里活着的会话,不扫描磁盘上的 sessions 目录。
|
|
9641
10257
|
if (req.method === 'GET' && path === '/api/bili-duty/main-session') {
|
|
9642
|
-
|
|
10258
|
+
// Reuse the established status URL for the light directory projection.
|
|
10259
|
+
// Older running plugin instances ignore the query and return legacy status.
|
|
10260
|
+
return sendJson(res,200,url.searchParams.get('directory')==='1'?mainSessionBridge.sessionDirectory({strict:true}):mainSessionBridge.status())
|
|
10261
|
+
}
|
|
10262
|
+
if (req.method === 'GET' && path === '/api/bili-duty/main-session/sessions') {
|
|
10263
|
+
return sendJson(res,200,mainSessionBridge.sessionDirectory({strict:true}))
|
|
10264
|
+
}
|
|
10265
|
+
if (req.method === 'POST' && path === '/api/bili-duty/main-session/bind') {
|
|
10266
|
+
const body=await readBody(req)
|
|
10267
|
+
if(body?.confirm!=='BIND_EXISTING_MAIN_SESSION')return sendJson(res,400,{ok:false,error:'请明确确认绑定已有主 Session'})
|
|
10268
|
+
const result=await mainSessionBridge.bindExistingSession({sessionId:body.sessionId,expectedId:body.expectedId})
|
|
10269
|
+
return sendJson(res,result.ok?200:409,result)
|
|
9643
10270
|
}
|
|
9644
10271
|
if (req.method === 'GET' && path === '/api/bili-duty/life-memory/status') {
|
|
9645
10272
|
return sendJson(res,200,lifeMemory?.status()||{ok:false,error:'记忆网关尚未就绪'})
|
|
@@ -9730,6 +10357,64 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9730
10357
|
}catch(e){return sendJson(res,400,{ok:false,error:String(e?.message||e).slice(0,300)})}
|
|
9731
10358
|
}
|
|
9732
10359
|
|
|
10360
|
+
// dev.6 read-only, on-demand deep memory for a SELECTED neural node.
|
|
10361
|
+
// Opaque node IDs are re-derived from currently recallable clear episodes.
|
|
10362
|
+
// No archive lookup, no cross-account read, no fuzzy similarity join.
|
|
10363
|
+
if(req.method==='GET'&&path==='/api/bili-duty/main-session/memory/neural/activation'){
|
|
10364
|
+
const peer=String(req.socket?.remoteAddress||''),origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
10365
|
+
if(!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(peer)||origin&&(!host||![`http://${host}`,`https://${host}`].includes(origin))||String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
10366
|
+
return sendJson(res,403,{ok:false,reason:'owner-local-only'})
|
|
10367
|
+
res.setHeader?.('Cache-Control','private, no-store')
|
|
10368
|
+
const scope=trustedLifeAccountTag()
|
|
10369
|
+
if(!scope||accountBinding.status().blocked||!lifeMemory||cfg.mainSessionMemoryEnabled!==true)return sendJson(res,200,{ok:true,activation:null})
|
|
10370
|
+
try{
|
|
10371
|
+
const receipt=neuralActivationTracker.read(scope)
|
|
10372
|
+
if(!receipt)return sendJson(res,200,{ok:true,activation:null})
|
|
10373
|
+
const episodes=lifeMemory.videoRecallGroups(lifeMemory.semanticCandidates({query:'',domain:'main-session',kinds:['watch','comment','social'],limit:3200})||[])
|
|
10374
|
+
const steps=lifeMemory.associationActivationSteps({accountTag:scope,receipt,episodeRows:episodes})
|
|
10375
|
+
const activation=projectNeuralActivation(receipt,steps,episodes)
|
|
10376
|
+
if(scope!==trustedLifeAccountTag()||accountBinding.status().blocked)return sendJson(res,409,{ok:false,reason:'account-changed'})
|
|
10377
|
+
return sendJson(res,200,{ok:true,activation,reason:activation?'':'path-not-in-current-projection'})
|
|
10378
|
+
}catch{return sendJson(res,200,{ok:true,activation:null,reason:'activation-unavailable'})}
|
|
10379
|
+
}
|
|
10380
|
+
if(req.method==='GET'&&path==='/api/bili-duty/main-session/memory/neural/deep'){
|
|
10381
|
+
const peer=String(req.socket?.remoteAddress||'')
|
|
10382
|
+
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
10383
|
+
if(!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(peer)||
|
|
10384
|
+
origin&&(!host||![`http://${host}`,`https://${host}`].includes(origin))||
|
|
10385
|
+
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
10386
|
+
return sendJson(res,403,{ok:false,reason:'owner-local-only'})
|
|
10387
|
+
res.setHeader?.('Cache-Control','private, no-store')
|
|
10388
|
+
const nodeId=String(url.searchParams.get('node')||'')
|
|
10389
|
+
if(!/^[a-f0-9]{16}$/.test(nodeId))return sendJson(res,400,{ok:false,reason:'invalid-memory-node'})
|
|
10390
|
+
const account=trustedLifeAccountTag()
|
|
10391
|
+
if(!hasCredential()||!/^[a-f0-9]{16}$/.test(String(account||''))||accountBinding.status().blocked||!lifeMemory)
|
|
10392
|
+
return sendJson(res,401,{ok:false,reason:'account-not-verified'})
|
|
10393
|
+
// Same current-fading-memory projection as the neural map. Limit is
|
|
10394
|
+
// bounded and no unbounded search or external retrieval is performed.
|
|
10395
|
+
const candidates=lifeMemory.videoRecallGroups(lifeMemory.semanticCandidates({query:'',domain:'main-session',
|
|
10396
|
+
kinds:['watch'],limit:3200})||[])
|
|
10397
|
+
const matches=candidates.filter(m=>m.stage==='clear'&&m.kind==='watch'&&validBv(String(m.bvid||''))&&
|
|
10398
|
+
neuralProjectionKey({...m,gardenKind:'experience',gardenEvidence:'fading-life-episode'})===nodeId)
|
|
10399
|
+
if(matches.length!==1)return sendJson(res,404,{ok:false,reason:'memory-unavailable'})
|
|
10400
|
+
// semanticCandidates exposes intentionally redacted public fields;
|
|
10401
|
+
// ONLY the Gateway can re-prove current account, scope and clear ownership.
|
|
10402
|
+
const trace=lifeMemory.videoEvidenceTrace({accountTag:account,memoryId:matches[0].id,limit:1,ownerSession:true})
|
|
10403
|
+
if(trace.length!==1||trace[0].bvid!==matches[0].bvid||!['public-event','private-session'].includes(trace[0].visibility))
|
|
10404
|
+
return sendJson(res,404,{ok:false,reason:'memory-unavailable'})
|
|
10405
|
+
if(account!==trustedLifeAccountTag()||accountBinding.status().blocked)
|
|
10406
|
+
return sendJson(res,409,{ok:false,reason:'account-changed'})
|
|
10407
|
+
const sourceMemoryId=String(url.searchParams.get('source')||'')
|
|
10408
|
+
const expanded=lifeMemory.inspectVideoDetails({bvid:matches[0].bvid,accountTag:account,visibility:trace[0].visibility,sourceMemoryId})
|
|
10409
|
+
if(expanded?.ok!==true)return sendJson(res,200,{ok:true,available:false,fragments:[],reason:expanded?.reason||'no-detail'})
|
|
10410
|
+
if(!sourceMemoryId)return sendJson(res,200,{ok:true,available:expanded.totalFragments>0,sources:expanded.sources,totalFragments:expanded.totalFragments})
|
|
10411
|
+
const fragments=(expanded.fragments||[]).map(item=>({
|
|
10412
|
+
type:item.type,content:item.content,certainty:item.certainty,observedAt:item.observedAt,
|
|
10413
|
+
observationSource:item.observationSource,observationRangeMs:item.observationRangeMs,
|
|
10414
|
+
...(Array.isArray(item.timeAnchorMs)?{timeAnchorMs:item.timeAnchorMs}:{}),uncertainties:item.uncertainties||[]}))
|
|
10415
|
+
return sendJson(res,200,{ok:true,available:true,fragments,totalFragments:expanded.totalFragments,truncated:expanded.truncated,
|
|
10416
|
+
certainty:'recorded-sampled-evidence-not-independent-semantic-proof'})
|
|
10417
|
+
}
|
|
9733
10418
|
if (req.method === 'GET' && (path === '/api/bili-duty/main-session/memory/garden' || path === '/api/bili-duty/main-session/memory/neural')) {
|
|
9734
10419
|
// Owner's read-only management view. It is never injected into social
|
|
9735
10420
|
// prompts, cannot revive archived events and must not create contacts.
|
|
@@ -9761,11 +10446,11 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9761
10446
|
}
|
|
9762
10447
|
}catch(e){peopleError='关系观察索引暂不可用:'+String(e?.message||e).slice(0,90)}
|
|
9763
10448
|
const sharedGardenArgs={interests:interestMemoryRows(stateDir),people,
|
|
9764
|
-
query:neuralView?'':q,kind:neuralView?'':kind,limit,peopleError}
|
|
10449
|
+
query:neuralView?'':q,kind:neuralView?'':kind,limit:neuralView?10000:limit,peopleError}
|
|
9765
10450
|
// Preserve the original bounded garden contract while the neural graph
|
|
9766
10451
|
// explicitly opts in to its separate, high-density read-only view.
|
|
9767
10452
|
const result=neuralView
|
|
9768
|
-
?memoryGardenSnapshot({memories:longTermMemory.listForVisualization(
|
|
10453
|
+
?memoryGardenSnapshot({memories:longTermMemory.listForVisualization(10000),...sharedGardenArgs})
|
|
9769
10454
|
:memoryGardenSnapshot({memories:longTermMemory.list('',300),...sharedGardenArgs})
|
|
9770
10455
|
if(neuralView){
|
|
9771
10456
|
// The graph is a bounded view of the CURRENT fading copy. `recall()`
|
|
@@ -9776,8 +10461,10 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9776
10461
|
// when that episode is older than the normal graph node cap. The
|
|
9777
10462
|
// Gateway still enforces account and forgetting scope; never read archives.
|
|
9778
10463
|
const exactVideoQuery=/^BV[0-9A-Za-z]{10}$/.test(q)?q:''
|
|
9779
|
-
const
|
|
9780
|
-
|
|
10464
|
+
const graphAccount=trustedLifeAccountTag()
|
|
10465
|
+
const rawEpisodes=lifeMemory?.semanticCandidates({query:exactVideoQuery,domain:'main-session',
|
|
10466
|
+
kinds:['watch','comment','social'],limit:3200})||[]
|
|
10467
|
+
const episodes=lifeMemory?.videoRecallGroups(rawEpisodes)||rawEpisodes
|
|
9781
10468
|
const allRows=[...result.rows,...episodes.map(m=>({...m,gardenKind:'experience',gardenEvidence:'fading-life-episode'}))]
|
|
9782
10469
|
const pre=memoryNeuralProjection({gardenRows:result.rows,episodes,query:q,kind,limit,showAll:true})
|
|
9783
10470
|
const allowedIds=new Set(pre.nodes.map(m=>m.id))
|
|
@@ -9786,7 +10473,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9786
10473
|
// index intentionally uses privacy-filtered wording, not the
|
|
9787
10474
|
// display label; hashing the display text made ALL those vectors
|
|
9788
10475
|
// appear missing even when the local model was ready.
|
|
9789
|
-
const indexedText=new Map(memoryRetriever.embeddingCorpus().map(row=>[row.id,row.text]))
|
|
10476
|
+
const indexedText=new Map(memoryRetriever.embeddingCorpus({includeVisualDetails:false}).map(row=>[row.id,row.text]))
|
|
9790
10477
|
const foodIntent=/(?:喜欢吃|爱吃|想吃|吃什么|吃的|美食|食物|口味|零食|水果|饭菜|好吃)/i.test(q)
|
|
9791
10478
|
const foodTopic=/(?:美食|食物|饮食|口味|零食|水果|蔬菜|饭|菜|甜点|饮料|肉|蛋|鱼|米|面|早餐|午餐|晚餐|小吃|烹饪|做饭)/i
|
|
9792
10479
|
const corpus=allRows.filter(m=>{
|
|
@@ -9821,7 +10508,9 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9821
10508
|
}else semanticWarning='向量查询没有可用索引,本次只使用关键词命中。'
|
|
9822
10509
|
}catch(error){semanticWarning='向量查询暂不可用,本次退回关键词命中。'}
|
|
9823
10510
|
}
|
|
9824
|
-
|
|
10511
|
+
if(graphAccount!==trustedLifeAccountTag()||(graphAccount&&accountBinding.status().blocked))return sendJson(res,409,{ok:false,error:'账号状态已改变,重新读取神经回忆场'})
|
|
10512
|
+
const verifiedGraph=lifeMemory?.neuralEvidenceSnapshot({accountTag:graphAccount,gardenRows:result.rows,interestEvidence:interestNeuralEvidence(stateDir,graphAccount),episodeRows:episodes})||{links:[],emotions:[]}
|
|
10513
|
+
const projection=memoryNeuralProjection({gardenRows:result.rows,episodes,query:q,kind,limit,showAll:true,semanticMatchIds:semanticMatches,semanticScores,verifiedGraph})
|
|
9825
10514
|
const layout=cfg.mainSessionMemoryEmbeddingEnabled===true?embeddingIndex?.projectPoints(corpus,{query:semanticReady?q:''}):null
|
|
9826
10515
|
const positions=layout?.coordinates||{}
|
|
9827
10516
|
return sendJson(res,200,{...projection,
|
|
@@ -9840,10 +10529,10 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9840
10529
|
if(req.method==='GET'&&path==='/api/bili-duty/dsh-vision/runtime-health')
|
|
9841
10530
|
return sendJson(res,200,{ok:true,...await checkVisualHealthOnEntry()})
|
|
9842
10531
|
if(req.method==='GET'&&path==='/api/bili-duty/dsh-vision/status')
|
|
9843
|
-
return sendJson(res,200,{ok:true,...dshVisionReview.status(),pythonRuntime:(()=>{const r=visionPythonCache?.result;return {status:r?.ok?'healthy':r?'unhealthy':'unchecked',source:r?.source||'none',reason:r?.reason||'not_run'}})(),visionRepair:visionEnvironmentRepair.status(),imageUrl:'/api/bili-duty/local-vision/selftest-image'})
|
|
10532
|
+
return sendJson(res,200,{ok:true,...dshVisionReview.status(),pythonRuntime:(()=>{const r=visionPythonCache?.result;return {status:r?.ok?'healthy':r?'unhealthy':'unchecked',source:r?.source||'none',reason:r?.reason||'not_run',stage:r?.stage||''}})(),visionRepair:visionEnvironmentRepair.status(),imageUrl:'/api/bili-duty/local-vision/selftest-image'})
|
|
9844
10533
|
if(req.method==='POST'&&path==='/api/bili-duty/dsh-vision/repair'){
|
|
9845
10534
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||''),ip=String(req.socket?.remoteAddress||'')
|
|
9846
|
-
if(!
|
|
10535
|
+
if(!explicitManagementIntent(req)||
|
|
9847
10536
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
9848
10537
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
9849
10538
|
return sendJson(res,403,{ok:false,error:'仅允许本机管理中心明确发起视觉环境修复'})
|
|
@@ -9851,7 +10540,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9851
10540
|
}
|
|
9852
10541
|
if(req.method==='POST'&&['/api/bili-duty/dsh-vision/verify','/api/bili-duty/dsh-vision/review'].includes(path)){
|
|
9853
10542
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
9854
|
-
if(!
|
|
10543
|
+
if(!explicitManagementIntent(req)||String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
9855
10544
|
return sendJson(res,403,{ok:false,error:'DSH 图片验收仅允许管理中心同源操作'})
|
|
9856
10545
|
try{
|
|
9857
10546
|
if(path.endsWith('/verify'))return sendJson(res,200,await dshVisionReview.verify())
|
|
@@ -9868,7 +10557,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9868
10557
|
if(req.method==='POST'&&path==='/api/bili-duty/local-vision/ensure'){
|
|
9869
10558
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
9870
10559
|
const ip=String(req.socket?.remoteAddress||'')
|
|
9871
|
-
if(!
|
|
10560
|
+
if(!explicitManagementIntent(req)||
|
|
9872
10561
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
9873
10562
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
9874
10563
|
return sendJson(res,403,{ok:false,error:'仅允许在本机 DSH 管理中心恢复 Ollama'})
|
|
@@ -9888,7 +10577,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9888
10577
|
return sendJson(res,200,{ok:true,whisper:whisperStatus()})
|
|
9889
10578
|
if(req.method==='POST'&&path==='/api/bili-duty/video-dependencies/whisper/delete'){
|
|
9890
10579
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||''),ip=String(req.socket?.remoteAddress||'')
|
|
9891
|
-
if(!
|
|
10580
|
+
if(!explicitManagementIntent(req)||
|
|
9892
10581
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
9893
10582
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
9894
10583
|
return sendJson(res,403,{ok:false,error:'仅允许从本机 DSH 管理中心删除插件自有 Whisper 模型'})
|
|
@@ -9914,7 +10603,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9914
10603
|
}
|
|
9915
10604
|
if(req.method==='POST'&&['/api/bili-duty/video-dependencies/ffmpeg/install','/api/bili-duty/video-dependencies/ffmpeg/test'].includes(path)){
|
|
9916
10605
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||''),ip=String(req.socket?.remoteAddress||'')
|
|
9917
|
-
if(!
|
|
10606
|
+
if(!explicitManagementIntent(req)||
|
|
9918
10607
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
9919
10608
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
9920
10609
|
return sendJson(res,403,{ok:false,error:'仅允许从本机 DSH 管理中心安装或验证 FFmpeg'})
|
|
@@ -9927,7 +10616,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9927
10616
|
}
|
|
9928
10617
|
if(req.method==='POST'&&path==='/api/bili-duty/video-dependencies/paths'){
|
|
9929
10618
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||''),ip=String(req.socket?.remoteAddress||'')
|
|
9930
|
-
if(!
|
|
10619
|
+
if(!explicitManagementIntent(req)||
|
|
9931
10620
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
9932
10621
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
9933
10622
|
return sendJson(res,403,{ok:false,error:'仅允许本机 DSH 管理中心选择已安装程序或模型目录'})
|
|
@@ -9961,7 +10650,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
9961
10650
|
}
|
|
9962
10651
|
if(req.method==='POST'&&['/api/bili-duty/local-vision/install','/api/bili-duty/local-vision/cancel','/api/bili-duty/local-vision/select','/api/bili-duty/local-vision/verify','/api/bili-duty/local-vision/review','/api/bili-duty/local-vision/delete'].includes(path)){
|
|
9963
10652
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
9964
|
-
if(!
|
|
10653
|
+
if(!explicitManagementIntent(req)||String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
9965
10654
|
return sendJson(res,403,{ok:false,error:'本地视觉模型管理仅允许电脑端同源操作'})
|
|
9966
10655
|
try{
|
|
9967
10656
|
const data=await readBody(req,1024)
|
|
@@ -10008,7 +10697,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10008
10697
|
}
|
|
10009
10698
|
if (req.method === 'POST' && ['/api/bili-duty/embedding/install','/api/bili-duty/embedding/disable','/api/bili-duty/embedding/rebuild','/api/bili-duty/embedding/cancel','/api/bili-duty/embedding/delete','/api/bili-duty/embedding/import-model'].includes(path)) {
|
|
10010
10699
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||'')
|
|
10011
|
-
if(!
|
|
10700
|
+
if(!explicitManagementIntent(req)||String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site')
|
|
10012
10701
|
return sendJson(res,403,{ok:false,error:'本地语义模型管理只允许电脑端管理中心同源操作'})
|
|
10013
10702
|
try{
|
|
10014
10703
|
if(path.endsWith('/install')){
|
|
@@ -10359,18 +11048,20 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10359
11048
|
return sendJson(res,200,{ok:true,localVerified:result.localVerified,host:result.host})
|
|
10360
11049
|
}
|
|
10361
11050
|
if(path.endsWith('/bili/verify')){
|
|
10362
|
-
const
|
|
10363
|
-
const
|
|
10364
|
-
|
|
10365
|
-
const
|
|
10366
|
-
|
|
10367
|
-
|
|
10368
|
-
|
|
11051
|
+
const bound=accountBinding.assertReady()
|
|
11052
|
+
const scope=trustedLifeAccountTag()
|
|
11053
|
+
if(!scope)throw Error('Life 账号尚未核验,请先确认账号并完成重启与授权复核')
|
|
11054
|
+
const result=await accountBinding.verifyCurrent()
|
|
11055
|
+
const current=accountBinding.assertReady()
|
|
11056
|
+
if(current.activeUid!==bound.activeUid||current.generation!==bound.generation||trustedLifeAccountTag()!==scope)
|
|
11057
|
+
throw Error('核验期间账号已变化,请重新验证')
|
|
10369
11058
|
const updated=firstStart.verifyBili();syncPauseState(true)
|
|
10370
11059
|
return sendJson(res,200,{...updated,username:String(result.username||'').slice(0,80)})
|
|
10371
11060
|
}
|
|
10372
11061
|
if(path.endsWith('/complete')){
|
|
10373
11062
|
const body=await readBody(req)
|
|
11063
|
+
accountBinding.assertReady()
|
|
11064
|
+
if(!trustedLifeAccountTag())throw Error('Life 账号尚未核验,请先完成账号确认')
|
|
10374
11065
|
const updated=firstStart.complete(Array.isArray(body?.skipped)?body.skipped:[]);syncPauseState(true)
|
|
10375
11066
|
return sendJson(res,200,updated)
|
|
10376
11067
|
}
|
|
@@ -10531,9 +11222,12 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10531
11222
|
vision:{configured:cfg.visionEnabled===true&&(resolvedVisionMode()==='independent_local'
|
|
10532
11223
|
?Boolean(getLocalVisionModel(cfg.visionLocalModel))
|
|
10533
11224
|
:Boolean(cfg.visionModelId||cfg.pluginDefaultModelId)),
|
|
10534
|
-
|
|
11225
|
+
mode:resolvedVisionMode(),
|
|
11226
|
+
backendModel:resolvedVisionMode()==='independent_local'?getLocalVisionModel(cfg.visionLocalModel)?.ollama||'':'',
|
|
11227
|
+
model:resolvedVisionMode()==='independent_local'?getLocalVisionModel(cfg.visionLocalModel)?.name||'未选择本地视觉模型':
|
|
10535
11228
|
String(cfg.visionModelId||cfg.pluginDefaultModelId||'DSH 视觉模型'),
|
|
10536
|
-
|
|
11229
|
+
...((attempt)=>attempt?{at:attempt.at,ok:attempt.ok,status:attempt.status,lastAttempt:attempt}:{})(
|
|
11230
|
+
readProductionVisionStatus(stateDir)||lastLifeVisionActivity)},
|
|
10537
11231
|
schedulerExpected:cfg.masterEnabled===true&&(cfg.dmWatch===true||cfg.commentWatchReplies===true||cfg.commentAtEnabled===true),
|
|
10538
11232
|
lifeExpected:cfg.masterEnabled===true&&cfg.autonomousPlannerEnabled===true&&cfg.lifeAgentMode==='active',
|
|
10539
11233
|
now:Date.now()}))}
|
|
@@ -10814,7 +11508,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10814
11508
|
// This must not clear seen IDs or force any platform send.
|
|
10815
11509
|
if(req.method==='POST'&&(path==='/api/bili-duty/dm-contact-check'||path==='/api/bili-duty/dm-contact-reconsider')){
|
|
10816
11510
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||''),ip=String(req.socket?.remoteAddress||'')
|
|
10817
|
-
if(!
|
|
11511
|
+
if(!explicitManagementIntent(req)||
|
|
10818
11512
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
10819
11513
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
10820
11514
|
return sendJson(res,403,{ok:false,error:'仅可在本机管理中心检查指定联系人'})
|
|
@@ -10881,7 +11575,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10881
11575
|
// 建 venv + 装依赖(**不等它**:几分钟的活,进度写 install.log)
|
|
10882
11576
|
if (req.method === 'POST' && path === '/api/bili-duty/install') {
|
|
10883
11577
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||''),ip=String(req.socket?.remoteAddress||'');
|
|
10884
|
-
if(!
|
|
11578
|
+
if(!explicitManagementIntent(req)||
|
|
10885
11579
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
10886
11580
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
10887
11581
|
return sendJson(res,403,{ok:false,error:'仅允许在本机管理中心明确操作 B站主依赖安装'});
|
|
@@ -10892,7 +11586,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10892
11586
|
if (req.method === 'POST' && path === '/api/bili-duty/install-asr') {
|
|
10893
11587
|
// Initial setup permits optional downloads only on the local management origin.
|
|
10894
11588
|
const origin=String(req.headers.origin||''),host=String(req.headers.host||''),ip=String(req.socket?.remoteAddress||'');
|
|
10895
|
-
if(!
|
|
11589
|
+
if(!explicitManagementIntent(req)||
|
|
10896
11590
|
String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site'||
|
|
10897
11591
|
!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(ip))
|
|
10898
11592
|
return sendJson(res,403,{ok:false,error:'仅允许从本机 DSH 管理中心安装 Whisper'});
|
|
@@ -10947,6 +11641,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10947
11641
|
offset: url.searchParams.get('offset'),
|
|
10948
11642
|
day: url.searchParams.get('day'),
|
|
10949
11643
|
kind: url.searchParams.get('kind'),
|
|
11644
|
+
search: url.searchParams.get('search'),
|
|
10950
11645
|
recipientMetadataDir: accountRuntimeDir,
|
|
10951
11646
|
}))
|
|
10952
11647
|
}
|
|
@@ -10966,22 +11661,20 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
10966
11661
|
const body = await readBody(req)
|
|
10967
11662
|
const what = String(body?.what || 'out')
|
|
10968
11663
|
if(!firstStart.isReady() && what!=='manage')return sendJson(res,423,{ok:false,blocked:true,error:firstStart.message()})
|
|
10969
|
-
//
|
|
10970
|
-
//
|
|
10971
|
-
if (what === 'manage'
|
|
10972
|
-
|
|
10973
|
-
if
|
|
10974
|
-
|
|
10975
|
-
|
|
10976
|
-
|
|
10977
|
-
const tab=String(body?.tab||'');u = `http://${host}/api/bili-duty/manage${['firststart','models','home','life'].includes(tab)?'?tab='+encodeURIComponent(tab):''}`;
|
|
10978
|
-
if(tab==='firststart'&&body?.anchor==='fs-deps-card')u+='#fs-deps-card'
|
|
10979
|
-
// 安卓客户端可以仅获取地址并由 WebView 导航,避免尝试在宿主系统弹窗。
|
|
10980
|
-
if (body?.resolveOnly === true) return sendJson(res, 200, { ok: true, url: u })
|
|
10981
|
-
} else {
|
|
10982
|
-
u = String(body?.u || '')
|
|
10983
|
-
if (!/^https?:\/\//i.test(u)) return sendJson(res, 200, { ok: false, error: '只接受 http(s) 链接' })
|
|
11664
|
+
// Only an authenticated, explicit owner operation can request the clean launcher URL.
|
|
11665
|
+
// The external browser establishes its own session with the official DSH login page.
|
|
11666
|
+
if (what === 'manage') {
|
|
11667
|
+
const path=managementPath(body?.tab,body?.anchor)
|
|
11668
|
+
if(body?.external===true){
|
|
11669
|
+
if(!explicitManagementIntent(req))return sendJson(res,403,{ok:false,error:'需要明确的主人操作'})
|
|
11670
|
+
try{return sendJson(res,200,{ok:true,path,openIn:'external-browser',url:managementBrowserUrl(ctx.webServer,body?.tab,body?.anchor)})}
|
|
11671
|
+
catch{return sendJson(res,503,{ok:false,error:'宿主未提供可信本机浏览器地址,请在 DSH 内打开'})}
|
|
10984
11672
|
}
|
|
11673
|
+
return sendJson(res,200,{ok:true,path,openIn:'current-dsh'})
|
|
11674
|
+
}
|
|
11675
|
+
if (what === 'url') {
|
|
11676
|
+
const u = String(body?.u || '')
|
|
11677
|
+
if (!/^https?:\/\//i.test(u)) return sendJson(res, 200, { ok: false, error: '只接受 http(s) 链接' })
|
|
10985
11678
|
if (process.platform !== 'win32') {
|
|
10986
11679
|
const opener = process.platform === 'darwin' ? 'open' : 'xdg-open'
|
|
10987
11680
|
const child = spawn(opener, [u], { detached: true, stdio: 'ignore' })
|
|
@@ -11140,7 +11833,7 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
11140
11833
|
'headless profile:headless(无人值守安全固定值;旧 headlessProfile 配置仅保留兼容)',
|
|
11141
11834
|
'pythonPath:' + cfg.pythonPath,
|
|
11142
11835
|
'venv 就绪:' + (venvReadyNow() ? '是' : '否') + (missingVenvDeps().length ? '(缺:' + missingVenvDeps().join(' / ') + ')' : ''),
|
|
11143
|
-
'转写环境:' + (existsSync(
|
|
11836
|
+
'转写环境:' + (existsSync(storageDataPath(stateDir,'.venv-asr')) ? '在' : '没装'),
|
|
11144
11837
|
'B站 登录:' + (hasCredential() ? '有凭证' : '没有凭证'),
|
|
11145
11838
|
'报告投递:旧视频清单私信已退役;本地日报继续保存,Life 自主分享独立控制',
|
|
11146
11839
|
'跑一轮原创评论:' + (cfg.autoComment ? '开' : '关') + ' · 后台评论回复:' + (cfg.commentWatchReplies ? '开' : '关'),
|
|
@@ -11293,26 +11986,36 @@ logger:{warn:m=>log('社交意图:'+m)}
|
|
|
11293
11986
|
try {
|
|
11294
11987
|
const host = String(req.headers.host || '')
|
|
11295
11988
|
if (String(req.headers['sec-fetch-site']||'').toLowerCase()==='cross-site') return false
|
|
11296
|
-
if (!host) return
|
|
11989
|
+
if (!host) return false // Host 缺失不能证明本机或主人身份
|
|
11297
11990
|
if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host)) return false
|
|
11298
11991
|
const pick = String(req.headers.origin || req.headers.referer || '')
|
|
11299
|
-
if (!pick) return true //
|
|
11992
|
+
if (!pick) return true // Desktop 转发可能移除来源头;仍必须通过宿主 owner 鉴权
|
|
11300
11993
|
try {
|
|
11301
11994
|
const u = new URL(pick)
|
|
11302
11995
|
return u.host.toLowerCase() === host.toLowerCase()
|
|
11303
11996
|
} catch { return false }
|
|
11304
11997
|
} catch { return false }
|
|
11305
11998
|
}
|
|
11999
|
+
// A public, exact, static login guide only. No business handler, data,
|
|
12000
|
+
// credential issuance, or owner exemption is reachable through this path.
|
|
12001
|
+
ctx.effect(() => ctx.webServer.register({kind:'exact',path:'/api/bili-duty/browser',auth:'anonymous',
|
|
12002
|
+
handler:(req,res)=>{
|
|
12003
|
+
if(!sameOriginOk(req))return sendJson(res,403,{ok:false,error:'只接受本机同源请求'})
|
|
12004
|
+
return managementBrowserLanding(req,res)
|
|
12005
|
+
}}), 'bili-duty: browser login guide')
|
|
11306
12006
|
ctx.effect(() => ctx.webServer.register({
|
|
11307
12007
|
kind: 'prefix',
|
|
11308
12008
|
path: '/api/bili-duty',
|
|
12009
|
+
auth: 'required',
|
|
11309
12010
|
// ⭐ 2026-10-23 安全加固(审计点名"未鉴权的控制接口"):**只接受本机同源请求** ——
|
|
11310
12011
|
// 别的网页在你浏览器里也能打到 127.0.0.1,所以要比对 Host 与本机、Origin/Referer 与同源 ✓
|
|
11311
|
-
handler: async (req, res) => {
|
|
12012
|
+
handler: async (req, res, peer) => {
|
|
11312
12013
|
if (!sameOriginOk(req)) {
|
|
11313
12014
|
try { sendJson(res, 403, { ok: false, error: '只接受本机同源请求' }) } catch { /* 忽略 */ }
|
|
11314
12015
|
return
|
|
11315
12016
|
}
|
|
12017
|
+
const status = await managementOwnerStatus(ctx, req, peer)
|
|
12018
|
+
if (status !== 200) return sendJson(res, status, managementAuthError(status))
|
|
11316
12019
|
try { await handle(req, res, new URL(req.url, 'http://127.0.0.1')) } catch (e) {
|
|
11317
12020
|
sendJson(res, 500, { ok: false, error: e?.message ?? String(e) })
|
|
11318
12021
|
}
|