nova-personal-agent-server 0.4.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +674 -201
- package/README.md +10 -0
- package/bin/nova-space-host.mjs +4 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
- package/node_modules/@nova-personal-agent/relay/package.json +1 -0
- package/package.json +11 -4
- package/runtime/dist/src/cascaded-text-provider.js +8 -3
- package/runtime/dist/src/composition/assembly.js +133 -35
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
- package/runtime/dist/src/composition/production-composition.js +57 -21
- package/runtime/dist/src/composition/realtime-assembly.js +160 -52
- package/runtime/dist/src/composition/soul-context.js +22 -0
- package/runtime/dist/src/config/capability-registry.js +48 -3
- package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
- package/runtime/dist/src/config/config.js +541 -128
- package/runtime/dist/src/config/credential-rotation.js +26 -0
- package/runtime/dist/src/config/data-root.js +764 -0
- package/runtime/dist/src/config/diagnostics.js +3 -1
- package/runtime/dist/src/config/environment-contract.js +190 -188
- package/runtime/dist/src/config/model-routes.js +140 -0
- package/runtime/dist/src/config/voice-credentials.js +55 -0
- package/runtime/dist/src/connectors/composio/index.js +9 -0
- package/runtime/dist/src/connectors/feishu/index.js +258 -44
- package/runtime/dist/src/connectors/macos/mail.js +7 -3
- package/runtime/dist/src/connectors/macos/reader.js +3 -1
- package/runtime/dist/src/conversation-voice-provider.js +5 -2
- package/runtime/dist/src/core/causal-runtime.js +38 -3
- package/runtime/dist/src/core/context-view.js +7 -0
- package/runtime/dist/src/core/guards.js +32 -0
- package/runtime/dist/src/core/runtime.js +3 -0
- package/runtime/dist/src/core/schedule-tools.js +2 -2
- package/runtime/dist/src/core/source-processing-instructions.js +2 -2
- package/runtime/dist/src/core/source-processing-tools.js +3 -1
- package/runtime/dist/src/core/tool-schema.js +42 -7
- package/runtime/dist/src/desktop/desktop-camera.js +3 -5
- package/runtime/dist/src/desktop/desktop-control.js +41 -8
- package/runtime/dist/src/desktop/desktop-session.js +90 -19
- package/runtime/dist/src/desktop/desktop-wire.js +5 -7
- package/runtime/dist/src/desktop/startup-error.js +18 -16
- package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
- package/runtime/dist/src/desktop-entry.js +6 -2
- package/runtime/dist/src/desktop.js +5 -1
- package/runtime/dist/src/device/attempt.js +65 -0
- package/runtime/dist/src/device/authority.js +159 -0
- package/runtime/dist/src/device/gateway.js +87 -0
- package/runtime/dist/src/device/ledger.js +91 -0
- package/runtime/dist/src/device/ownership.js +92 -0
- package/runtime/dist/src/device/port.js +2 -0
- package/runtime/dist/src/device/schedule-ownership.js +103 -0
- package/runtime/dist/src/executors/acp/transport.js +2 -0
- package/runtime/dist/src/executors/browser.js +4 -3
- package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
- package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
- package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
- package/runtime/dist/src/executors/codex/common.js +1 -1
- package/runtime/dist/src/executors/codex/contract.js +12 -16
- package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
- package/runtime/dist/src/executors/codex/factory.js +54 -32
- package/runtime/dist/src/executors/codex/host-config.js +69 -20
- package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
- package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
- package/runtime/dist/src/executors/codex/process-owner.js +4 -6
- package/runtime/dist/src/executors/codex/production-host.js +33 -34
- package/runtime/dist/src/executors/codex/protocol.js +9 -14
- package/runtime/dist/src/executors/codex/session-title.js +6 -8
- package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
- package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
- package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
- package/runtime/dist/src/executors/coding/intake.js +12 -7
- package/runtime/dist/src/executors/computer-backend.js +18 -10
- package/runtime/dist/src/executors/computer-config.js +32 -0
- package/runtime/dist/src/executors/computer-device.js +68 -16
- package/runtime/dist/src/executors/computer-worker.js +18 -6
- package/runtime/dist/src/executors/computer.js +29 -56
- package/runtime/dist/src/executors/device-lock.js +14 -5
- package/runtime/dist/src/executors/gui-execution.js +2 -0
- package/runtime/dist/src/executors/index.js +0 -1
- package/runtime/dist/src/executors/mobile.js +9 -8
- package/runtime/dist/src/executors/native-process.js +4 -0
- package/runtime/dist/src/executors/search.js +3 -5
- package/runtime/dist/src/executors/task-resources.js +21 -0
- package/runtime/dist/src/executors/watcher.js +2 -4
- package/runtime/dist/src/experience/host.js +179 -0
- package/runtime/dist/src/index.js +2 -0
- package/runtime/dist/src/knowledge/assembly.js +3 -4
- package/runtime/dist/src/knowledge/embeddings.js +50 -34
- package/runtime/dist/src/knowledge/service.js +1 -0
- package/runtime/dist/src/knowledge/store-client.js +1 -6
- package/runtime/dist/src/knowledge/store-worker.js +1 -3
- package/runtime/dist/src/mem0/resource.js +25 -0
- package/runtime/dist/src/mem0/store-worker.js +234 -21
- package/runtime/dist/src/memory/consumer.js +31 -0
- package/runtime/dist/src/memory/engine-worker.js +210 -0
- package/runtime/dist/src/memory/entry.js +8 -1
- package/runtime/dist/src/memory/explicit-memory.js +20 -0
- package/runtime/dist/src/memory/factory.js +30 -15
- package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
- package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
- package/runtime/dist/src/memory/prerecall-port.js +27 -0
- package/runtime/dist/src/memory/prerecall.js +1 -1
- package/runtime/dist/src/memory/production-engine.js +151 -0
- package/runtime/dist/src/memory/provenance.js +1 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
- package/runtime/dist/src/memory/retrieval.js +107 -22
- package/runtime/dist/src/memory/sensitivity.js +6 -2
- package/runtime/dist/src/memory/source-retrieval.js +11 -0
- package/runtime/dist/src/memory/tool-capabilities.js +46 -0
- package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
- package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
- package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
- package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
- package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
- package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
- package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
- package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
- package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
- package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
- package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
- package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
- package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
- package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
- package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
- package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
- package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
- package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
- package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
- package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
- package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
- package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
- package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
- package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
- package/runtime/dist/src/memory-ledger/store-client.js +235 -37
- package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
- package/runtime/dist/src/memory-ledger/store.js +91 -1
- package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
- package/runtime/dist/src/memory-substrate/diary.js +27 -0
- package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
- package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
- package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
- package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
- package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
- package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
- package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
- package/runtime/dist/src/memory-substrate/migration.js +2 -0
- package/runtime/dist/src/memory-substrate/purge.js +12 -2
- package/runtime/dist/src/memory-substrate/resource.js +514 -129
- package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
- package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
- package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
- package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
- package/runtime/dist/src/memory-substrate/source-state.js +8 -0
- package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
- package/runtime/dist/src/memory-substrate/store.js +125 -23
- package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
- package/runtime/dist/src/model/goal-writer.js +80 -0
- package/runtime/dist/src/model/jev-client.js +24 -13
- package/runtime/dist/src/model/model-adapters.js +2 -3
- package/runtime/dist/src/model/model-catalog.js +80 -0
- package/runtime/dist/src/model/model-gateway.js +47 -18
- package/runtime/dist/src/model/model-purpose.js +3 -4
- package/runtime/dist/src/model/personal-writer.js +536 -44
- package/runtime/dist/src/model/proactivity.js +50 -6
- package/runtime/dist/src/model/responses-model-gateway.js +59 -0
- package/runtime/dist/src/model/task-verifier.js +3 -3
- package/runtime/dist/src/model/timeline-anchors.js +77 -0
- package/runtime/dist/src/model/timeline-perspective.js +13 -0
- package/runtime/dist/src/model/timeline-selection.js +182 -0
- package/runtime/dist/src/model/understanding-writer.js +27 -0
- package/runtime/dist/src/model/vision-capability.js +3 -1
- package/runtime/dist/src/model/workbench-writer.js +96 -0
- package/runtime/dist/src/news/feeds.js +6 -10
- package/runtime/dist/src/news/interests.js +23 -0
- package/runtime/dist/src/news/service.js +87 -31
- package/runtime/dist/src/news/sources.json +116 -0
- package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
- package/runtime/dist/src/notifications/content.js +41 -0
- package/runtime/dist/src/notifications/contracts.js +4 -2
- package/runtime/dist/src/notifications/feed.js +6 -2
- package/runtime/dist/src/notifications/service.js +27 -14
- package/runtime/dist/src/notifications/store.js +3 -1
- package/runtime/dist/src/personal-agent/app-context.js +39 -4
- package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
- package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
- package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
- package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
- package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
- package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
- package/runtime/dist/src/personal-agent/contracts.js +24 -4
- package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
- package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
- package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
- package/runtime/dist/src/personal-agent/conversations.js +71 -15
- package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
- package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
- package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
- package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2379 -223
- package/runtime/dist/src/personal-agent/identity-context.js +33 -0
- package/runtime/dist/src/personal-agent/life.js +129 -11
- package/runtime/dist/src/personal-agent/local-shell.js +181 -0
- package/runtime/dist/src/personal-agent/local-tools.js +234 -0
- package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
- package/runtime/dist/src/personal-agent/project-digests.js +7 -3
- package/runtime/dist/src/personal-agent/project-history.js +36 -0
- package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
- package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
- package/runtime/dist/src/personal-agent/sources.js +9 -1
- package/runtime/dist/src/personal-agent/store.js +124 -14
- package/runtime/dist/src/personal-agent/task-loop.js +3 -0
- package/runtime/dist/src/personal-agent/tasks.js +16 -4
- package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
- package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
- package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
- package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
- package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
- package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
- package/runtime/dist/src/personal-agent/understanding.js +7 -22
- package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
- package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
- package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
- package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
- package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
- package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
- package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
- package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
- package/runtime/dist/src/projects/project-native-resource.js +10 -8
- package/runtime/dist/src/projects/project-store.js +36 -4
- package/runtime/dist/src/realtime/bridge.js +77 -8
- package/runtime/dist/src/realtime/capabilities.js +19 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
- package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
- package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
- package/runtime/dist/src/realtime/evidence.js +1 -1
- package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
- package/runtime/dist/src/realtime/gemini.js +14 -3
- package/runtime/dist/src/realtime/host-delivery.js +37 -4
- package/runtime/dist/src/realtime/protocol.js +18 -3
- package/runtime/dist/src/realtime/provider-projection.js +4 -1
- package/runtime/dist/src/realtime/provider-session.js +73 -16
- package/runtime/dist/src/realtime/qwen-transport.js +35 -4
- package/runtime/dist/src/realtime/qwen.js +144 -9
- package/runtime/dist/src/realtime/service-state.js +0 -1
- package/runtime/dist/src/realtime/service.js +93 -7
- package/runtime/dist/src/realtime/session.js +39 -32
- package/runtime/dist/src/realtime/sglang-native.js +214 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
- package/runtime/dist/src/realtime/telemetry.js +6 -3
- package/runtime/dist/src/realtime/tool-continuations.js +84 -7
- package/runtime/dist/src/realtime/transport.js +17 -0
- package/runtime/dist/src/realtime/usage.js +33 -17
- package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
- package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
- package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
- package/runtime/dist/src/server/aoq-chat-server.js +1 -1
- package/runtime/dist/src/server/client-server.js +21 -0
- package/runtime/dist/src/server-entry.js +3 -0
- package/runtime/dist/src/space-host/admin-socket.js +115 -0
- package/runtime/dist/src/space-host/audio-owner.js +44 -0
- package/runtime/dist/src/space-host/cli.js +195 -0
- package/runtime/dist/src/space-host/config.js +247 -0
- package/runtime/dist/src/space-host/context-input.js +12 -0
- package/runtime/dist/src/space-host/contracts.js +10 -0
- package/runtime/dist/src/space-host/host-admin.js +114 -0
- package/runtime/dist/src/space-host/key-delivery.js +28 -0
- package/runtime/dist/src/space-host/mobile-tools.js +9 -0
- package/runtime/dist/src/space-host/model-settings.js +213 -0
- package/runtime/dist/src/space-host/projection.js +37 -0
- package/runtime/dist/src/space-host/push.js +137 -0
- package/runtime/dist/src/space-host/relay-transport.js +55 -0
- package/runtime/dist/src/space-host/service.js +841 -0
- package/runtime/dist/src/space-host/voice-crypto.js +240 -0
- package/runtime/dist/src/space-host/voice.js +600 -0
- package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
- package/runtime/dist/src/storage/private-database.js +7 -10
- package/runtime/dist/src/text/unicode-normalize.js +5 -1
- package/runtime/dist/src/understanding/candidates.js +8 -10
- package/runtime/dist/src/understanding/fixture.js +1 -1
- package/runtime/dist/src/understanding/pipeline.js +4 -4
- package/runtime/dist/src/usage/context.js +23 -0
- package/runtime/dist/src/usage/index.js +4 -0
- package/runtime/dist/src/usage/ledger-worker.js +90 -0
- package/runtime/dist/src/usage/ledger.js +74 -0
- package/runtime/dist/src/usage/model-call.js +63 -0
- package/runtime/dist/src/usage/pricing.js +68 -0
- package/runtime/dist/src/usage/summary.js +69 -0
- package/runtime/dist/src/voicemem/store-client.js +104 -21
- package/runtime/dist/src/voicemem/store-worker.js +5 -8
- package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
- package/src/command.mjs +8 -1
- package/runtime/dist/src/executors/autoglm.js +0 -376
|
@@ -1,30 +1,164 @@
|
|
|
1
|
+
import { lifeEvidenceMatches } from './life.js';
|
|
2
|
+
import { withUsageContext } from '../usage/context.js';
|
|
3
|
+
import { inspectProject, inspectProjectDiff } from './project-history.js';
|
|
4
|
+
import { basename, relative } from 'node:path';
|
|
5
|
+
import { emptyUnderstanding, understandingSourceTags } from './understanding-products.js';
|
|
1
6
|
import { canonicalJson } from '../text/canonical-json.js';
|
|
2
7
|
import { sourceAgentArguments } from '../core/source-processing-tools.js';
|
|
3
8
|
import { profileSourceInput } from '../memory-substrate/profile-source-input.js';
|
|
4
9
|
import { createHash } from 'node:crypto';
|
|
5
10
|
import { z } from 'zod';
|
|
6
11
|
import { processingRefSchema } from '../memory-substrate/source-processing.js';
|
|
7
|
-
const batchResult = z.object({ batch: z.custom(), valid: z.boolean() });
|
|
8
|
-
const originalSchema = z.object({ items: z.array(processingRefSchema.and(z.object({ text: z.string(), version: z.string(), source_kind: z.string(), observed_at: z.string(), locator: z.string(), source_metadata: z.record(z.string(), z.unknown()).nullable() }))) });
|
|
12
|
+
const batchResult = z.object({ batch: z.custom(), valid: z.boolean(), observed: z.boolean().optional(), published: z.boolean().optional() });
|
|
13
|
+
const originalSchema = z.object({ items: z.array(processingRefSchema.and(z.object({ source_key: z.string(), text: z.string(), version: z.string(), source_kind: z.string(), observed_at: z.string(), locator: z.string(), source_metadata: z.record(z.string(), z.unknown()).nullable() }))) });
|
|
9
14
|
/** Uses the existing ScheduleRun/Task ledgers and scheduler wake; owns no timer. */
|
|
10
15
|
export class SourceProcessingAgent {
|
|
11
16
|
host;
|
|
12
17
|
constructor(host) {
|
|
13
18
|
this.host = host;
|
|
14
19
|
}
|
|
20
|
+
#products = emptyUnderstanding();
|
|
21
|
+
#history = [];
|
|
22
|
+
#refreshPending = false;
|
|
23
|
+
#revision = 0;
|
|
24
|
+
#error = false;
|
|
25
|
+
#lastGitCheck = 0;
|
|
26
|
+
#gitOffset = 0;
|
|
27
|
+
get enabled() { return !!this.host.options.memory()?.sourceProcessing; }
|
|
28
|
+
#source(item) { const anchor = item.anchor, ref = anchor && item.refs.find(ref => ref.entry_id === anchor.entry_id); return anchor?.quote && ref ? { candidate_id: item.id, refs: [{ ...ref, version: String(ref.version), quote: anchor.quote }] } : undefined; }
|
|
29
|
+
#captured(item) {
|
|
30
|
+
const life = this.host.life.snapshot(), rows = item.kind === 'goal' ? life.goals : item.kind === 'idea' ? life.ideas : life.todos, source = this.#source(item);
|
|
31
|
+
return rows.find(row => row.source_suggestion_id === item.id || (!item.todo_id && source && lifeEvidenceMatches(source.refs, [...(row.workbench_source?.refs ?? []), ...(row.suggestion_source?.refs ?? [])])));
|
|
32
|
+
}
|
|
33
|
+
#account() { const feishu = this.host.snapshot().feishu; return typeof feishu === 'object' && feishu !== null && 'account_id' in feishu ? feishu.account_id : undefined; }
|
|
34
|
+
snapshot() { const products = structuredClone(this.#products); products.suggestions = products.suggestions.filter(item => item.kind !== 'action' && !this.#captured(item)); return products; }
|
|
35
|
+
#presentationAccount;
|
|
36
|
+
setPresentationAccount(account) { if (account !== this.#presentationAccount) {
|
|
37
|
+
this.#products = emptyUnderstanding();
|
|
38
|
+
this.#history = [];
|
|
39
|
+
this.#refreshPending = false;
|
|
40
|
+
this.#error = false;
|
|
41
|
+
this.#revision++;
|
|
42
|
+
this.#presentationAccount = account;
|
|
43
|
+
} }
|
|
44
|
+
async reload() {
|
|
45
|
+
if (!this.enabled)
|
|
46
|
+
return;
|
|
47
|
+
const account = this.#account();
|
|
48
|
+
const revision = ++this.#revision;
|
|
49
|
+
try {
|
|
50
|
+
const snapshot = await this.operation({ action: 'products', presentation: true, ...(typeof account === 'string' ? { account_scope: account } : {}) });
|
|
51
|
+
const current = this.#account();
|
|
52
|
+
if (revision !== this.#revision || current !== account)
|
|
53
|
+
return;
|
|
54
|
+
const { history, refresh_pending, ...products } = snapshot;
|
|
55
|
+
this.#products = products;
|
|
56
|
+
this.#history = Array.isArray(history) ? history : [];
|
|
57
|
+
this.#refreshPending = refresh_pending === true;
|
|
58
|
+
this.#presentationAccount = typeof account === 'string' ? account : undefined;
|
|
59
|
+
this.#error = false;
|
|
60
|
+
if (products.news_cleanup_pending)
|
|
61
|
+
try {
|
|
62
|
+
await this.host.news.clearSeededInterests();
|
|
63
|
+
await this.operation({ action: 'confirm_cleanup' });
|
|
64
|
+
this.#products.news_cleanup_pending = false;
|
|
65
|
+
}
|
|
66
|
+
catch { /* Durable marker survives a failed write; retry on the next wake. */ }
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
const current = this.#account();
|
|
70
|
+
if (revision !== this.#revision)
|
|
71
|
+
return;
|
|
72
|
+
const sameAccount = (typeof current === 'string' ? current : undefined) === this.#presentationAccount, retained = sameAccount ? this.#products.last_success : null;
|
|
73
|
+
this.#products = { ...emptyUnderstanding(), last_success: retained ?? null };
|
|
74
|
+
this.#history = sameAccount ? this.#history : [];
|
|
75
|
+
this.#refreshPending = false;
|
|
76
|
+
this.#error = true;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Read-only published versions, newest first; compact enough for every state projection. */
|
|
80
|
+
#historyView() { return this.#history.map(item => ({ generated_at: item.generated_at, generation_version: item.generation_version, about: item.draft.about?.text.slice(0, 240) ?? null, work: item.draft.work.map(work => work.title).slice(0, 6), interests: item.draft.interests.map(interest => interest.text).slice(0, 8), unavailable_sources: item.unavailable_sources })); }
|
|
81
|
+
profileSnapshot() {
|
|
82
|
+
const active = this.host.schedules.activeRuns().filter(run => run.processing), terminal = this.host.schedules.terminalRuns().filter(run => run.processing), runs = [...active, ...terminal].sort((a, b) => b.claimed_at.localeCompare(a.claimed_at)), latest = terminal.sort((a, b) => b.claimed_at.localeCompare(a.claimed_at))[0];
|
|
83
|
+
// A queued refresh is an accepted request that has not started a run yet; last_attempt_at comes from the run ledger.
|
|
84
|
+
const status = active.length ? 'working' : this.#error || latest?.terminal_summary?.outcome === 'failed' ? 'failed' : this.#products.profile_pending ? 'working' : this.#refreshPending ? 'queued' : this.#products.draft ? 'ready' : 'idle';
|
|
85
|
+
return { status, draft: this.#products.draft, last_success: this.#products.last_success, history: this.#historyView(), last_attempt_at: runs[0]?.claimed_at ?? null, last_success_at: this.#products.generated_at ?? this.#history[0]?.generated_at ?? null, needs_update: this.#products.profile_needs_update === true, sources: this.#products.sources, processing: runs.slice(0, 5).map(run => ({ started_at: run.claimed_at, status: run.terminal_summary?.outcome ?? 'running', model_calls: run.processing?.model_calls ?? 0, tool_calls: run.processing?.calls.length ?? 0 })) };
|
|
86
|
+
}
|
|
87
|
+
/** Full read-only publication history for an explicit client request. */
|
|
88
|
+
async profileHistory(limit = 10) { if (!this.enabled)
|
|
89
|
+
return { items: [] }; const account = this.#account(); return await this.operation({ action: 'profile.history', limit, ...(typeof account === 'string' ? { account_scope: account } : {}) }); }
|
|
90
|
+
contextSnapshot() {
|
|
91
|
+
const p = this.snapshot(), status = this.profileSnapshot().status;
|
|
92
|
+
const cards = p.suggestions.filter(item => item.kind === 'goal' || item.kind === 'idea').map(item => ({ id: item.id, candidate_id: item.id, tab: item.kind === 'goal' ? 'goals' : 'ideas', title: item.title, body: item.body, why: null, next: null, refs: item.refs.map(ref => ({ ...ref, label: p.sources.find(source => source.id === ref.entry_id)?.label ?? '来源' })), sources: understandingSourceTags(item.refs, p.sources) }));
|
|
93
|
+
return { status, candidate_count: cards.length, recap: { text: null, projects: p.projects.filter(item => item.relation === 'participating' && item.status === 'current').map(item => ({ name: item.name, line: item.summary })) }, empty_reason: cards.length ? null : 'no_eligible_sources', empty_reasons: { ideas: 'no_eligible_sources', goals: 'no_eligible_sources' }, cards };
|
|
94
|
+
}
|
|
95
|
+
async adopt(id) {
|
|
96
|
+
await this.host.life.refresh();
|
|
97
|
+
const receipt = this.host.life.receipt('understanding-adopt:' + id);
|
|
98
|
+
if (receipt)
|
|
99
|
+
return receipt;
|
|
100
|
+
const life = this.host.life.snapshot(), prior = [...life.todos, ...life.ideas, ...life.goals].find(todo => todo.source_suggestion_id === id);
|
|
101
|
+
if (prior)
|
|
102
|
+
return { id: prior.id, version: prior.version };
|
|
103
|
+
await this.reload();
|
|
104
|
+
const item = this.#products.suggestions.find(item => item.id === id);
|
|
105
|
+
if (!item || item.kind === 'action')
|
|
106
|
+
throw Error('card_not_found');
|
|
107
|
+
const captured = this.#captured(item);
|
|
108
|
+
if (captured) {
|
|
109
|
+
await this.operation({ action: 'dismiss', id });
|
|
110
|
+
await this.reload();
|
|
111
|
+
return { id: captured.id, version: captured.version };
|
|
112
|
+
}
|
|
113
|
+
const sources = understandingSourceTags(item.refs, this.#products.sources), source = this.#source(item);
|
|
114
|
+
const guard = () => { if (!this.#products.suggestions.some(current => current.id === id && canonicalJson(current) === canonicalJson(item)))
|
|
115
|
+
throw Error('candidate_stale_source'); };
|
|
116
|
+
const result = await this.host.life.mutate({ op: 'from_suggestion', ...(source ? { source } : {}), suggestion_id: id, title: item.title, note: item.body, kind: item.kind === 'goal' ? 'goal' : item.kind === 'idea' ? 'idea' : 'todo', due: item.due, sources, provenance_refs: item.refs.map(ref => ref.entry_id), todo_id: item.todo_id }, 'understanding-adopt:' + id, guard);
|
|
117
|
+
await this.operation({ action: 'dismiss', id });
|
|
118
|
+
await this.reload();
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
async refresh() { await this.refreshProjectState(true); await this.operation({ action: 'refresh' }); await this.host.scheduledTaskTick(); await this.reload(); this.host.connectionChanged(); }
|
|
122
|
+
async projects(refs) {
|
|
123
|
+
const roots = this.host.sourceProjectRoots(refs.map(ref => ref.evidence_id)), groups = new Map();
|
|
124
|
+
for (const root of [...new Set(roots.map(row => row.root))].slice(0, 8)) {
|
|
125
|
+
const project = await inspectProject(root), existing = groups.get(project.id), evidence_ids = roots.filter(row => row.root === root).map(row => row.evidence_id);
|
|
126
|
+
groups.set(project.id, existing ? { ...existing, evidence_ids: [...new Set([...existing.evidence_ids, ...evidence_ids])], commits: [...new Map([...existing.commits, ...project.commits].map(c => [c.id, c])).values()].slice(0, 30), unmerged: [...new Map([...existing.unmerged, ...project.unmerged].map(c => [c.id, c])).values()].slice(0, 30) } : { ...project, evidence_ids });
|
|
127
|
+
}
|
|
128
|
+
return [...groups.values()];
|
|
129
|
+
}
|
|
15
130
|
async operation(request) { const memory = this.host.options.memory(); if (!memory?.sourceProcessing)
|
|
16
131
|
throw Error('source_processing_unavailable'); return memory.sourceProcessing(request); }
|
|
132
|
+
async refreshProjectState(force = false) {
|
|
133
|
+
if (!force && this.host.sourceProcessingNow() - this.#lastGitCheck < 60000)
|
|
134
|
+
return;
|
|
135
|
+
this.#lastGitCheck = this.host.sourceProcessingNow();
|
|
136
|
+
const rows = this.host.sourceProjectRoots(), roots = [...new Set(rows.map(row => row.root))];
|
|
137
|
+
if (this.#gitOffset >= roots.length)
|
|
138
|
+
this.#gitOffset = 0;
|
|
139
|
+
for (const root of roots.slice(this.#gitOffset, this.#gitOffset + 8)) {
|
|
140
|
+
const project = await inspectProject(root), fingerprint = createHash('sha256').update(canonicalJson(project)).digest('hex'), ids = rows.filter(row => row.root === root).map(row => row.evidence_id);
|
|
141
|
+
for (let n = 0; n < ids.length; n += 512)
|
|
142
|
+
await this.operation({ action: 'project_state', ids: ids.slice(n, n + 512), fingerprint });
|
|
143
|
+
}
|
|
144
|
+
this.#gitOffset += 8;
|
|
145
|
+
}
|
|
17
146
|
async tick() {
|
|
18
147
|
const memory = this.host.options.memory();
|
|
19
148
|
if (!memory?.sourceProcessing || !memory.sourceProcessingConsumer)
|
|
20
149
|
return;
|
|
150
|
+
if (!this.host.sourceProcessingForegroundBusy())
|
|
151
|
+
await this.refreshProjectState();
|
|
152
|
+
await this.reload();
|
|
21
153
|
const schedule = await this.host.schedules.ensureSourceProcessing(this.host.options.userScope);
|
|
22
154
|
for (const run of this.host.schedules.activeRuns().filter(run => run.processing)) {
|
|
23
155
|
if (!run.task_id)
|
|
24
156
|
continue;
|
|
25
157
|
const task = this.host.tasks.get(run.task_id);
|
|
26
|
-
//
|
|
27
|
-
|
|
158
|
+
// A lost built-in reply can be cancelled: its only effects are fenced, idempotent derived writes.
|
|
159
|
+
// Live deliveries and any unknown external execution still require normal recovery.
|
|
160
|
+
const lostReply = task.waiting_reason === 'task_delivery_uncertain' && !!task.pending_delivery && this.host.tasks.needsReconcile(task.id) && !task.work_ids.length && !this.host.tasks.pendingEffect(task.id) && !this.host.tasks.inputReceipts(task.id).some(receipt => receipt.status === 'unknown');
|
|
161
|
+
if (task.phase === 'waiting' && (lostReply || !task.pending_delivery && !this.host.tasks.hasUnresolvedExecution(task.id) && !this.host.tasks.pendingEffect(task.id))) {
|
|
28
162
|
const fence = { task_id: task.id, goal_revision: task.goal_revision, control_revision: task.control_revision };
|
|
29
163
|
await this.host.cancelTask('processing-failed:' + run.run_id, fence, { kind: 'nova' });
|
|
30
164
|
}
|
|
@@ -72,7 +206,8 @@ export class SourceProcessingAgent {
|
|
|
72
206
|
return false;
|
|
73
207
|
}
|
|
74
208
|
}
|
|
75
|
-
|
|
209
|
+
// Foreground activity gates admission, but does not revoke an already authorized batch.
|
|
210
|
+
async validate(grant) { return this.valid(this.host.schedules.getRun(grant.run_id), grant.consumer); }
|
|
76
211
|
async call(grant, callId, value) {
|
|
77
212
|
this.host.scheduledAuthority.assert(grant, grant.fence);
|
|
78
213
|
if (!await this.validate(grant))
|
|
@@ -90,6 +225,27 @@ export class SourceProcessingAgent {
|
|
|
90
225
|
throw error;
|
|
91
226
|
}
|
|
92
227
|
const owner = { batch_id: run.processing.batch_id, task_id: grant.task_id, run_id: grant.run_id };
|
|
228
|
+
if (args.action === 'projects' || args.action === 'project_diff') {
|
|
229
|
+
await this.operation({ action: 'evidence', refs: args.refs, ...owner });
|
|
230
|
+
const projects = await this.projects(args.refs);
|
|
231
|
+
this.host.scheduledAuthority.assert(grant, grant.fence);
|
|
232
|
+
if (!await this.validate(grant))
|
|
233
|
+
throw Error('processing_context_unavailable');
|
|
234
|
+
if (args.action === 'projects')
|
|
235
|
+
return { projects };
|
|
236
|
+
const project = projects.find(p => p.id === args.project_id);
|
|
237
|
+
if (!project)
|
|
238
|
+
throw Error('project_not_authorized');
|
|
239
|
+
const roots = this.host.sourceProjectRoots(project.evidence_ids);
|
|
240
|
+
const root = roots[0]?.root;
|
|
241
|
+
if (!root)
|
|
242
|
+
throw Error('project_not_authorized');
|
|
243
|
+
const result = await inspectProjectDiff(root, args.commit, roots.filter(r => r.root === root).map(r => relative(root, r.file)));
|
|
244
|
+
this.host.scheduledAuthority.assert(grant, grant.fence);
|
|
245
|
+
if (!await this.validate(grant))
|
|
246
|
+
throw Error('processing_context_unavailable');
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
93
249
|
if (args.action === 'read')
|
|
94
250
|
return this.operation({ action: 'read', batch_id: owner.batch_id });
|
|
95
251
|
if (args.action === 'topics')
|
|
@@ -99,20 +255,84 @@ export class SourceProcessingAgent {
|
|
|
99
255
|
if (args.action === 'evidence')
|
|
100
256
|
return this.operation({ ...args, ...owner });
|
|
101
257
|
if (args.action === 'compose') {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
258
|
+
return withUsageContext({ feature: 'profile', runId: grant.run_id, taskId: grant.fence.task_id, trigger: 'scheduled' }, async () => {
|
|
259
|
+
const memory = this.host.options.memory(), generate = memory?.sourceProcessingProfile?.bind(memory);
|
|
260
|
+
if (!generate)
|
|
261
|
+
throw Error('profile_generation_unavailable');
|
|
262
|
+
const batch = memory?.sourceProcessingObserve ? batchResult.parse(await this.operation({ action: 'batch', batch_id: owner.batch_id })).batch : undefined;
|
|
263
|
+
const processingRefs = batch?.items ?? args.refs;
|
|
264
|
+
const original = originalSchema.parse(await this.operation({ action: 'evidence', refs: processingRefs, ...owner }));
|
|
265
|
+
const previous = await this.operation({ action: 'profile', batch_id: owner.batch_id });
|
|
266
|
+
const inputs = (items) => items.map(item => item.source_kind === 'conversation' || item.source_kind === 'user_correction' ? { id: item.evidence_id, version: item.version, content: item.text, origin: item.source_kind === 'user_correction' ? 'stated' : 'inferred', observed_at: item.observed_at, source: { project: 'Conversation', document: item.locator } } : item.source_kind === 'file' ? { id: item.evidence_id, version: item.version, content: item.text, origin: 'inferred', source: { project: '资料', document: item.locator } } : profileSourceInput({ id: item.evidence_id, hash: item.version, raw_text: item.text, observed_at: item.observed_at, source_kind: item.source_kind, source_id: item.locator, source_metadata: item.source_metadata }, 4000));
|
|
267
|
+
const entries = inputs(original.items);
|
|
268
|
+
const signal = AbortSignal.any([this.host.scheduledAuthority.signal(grant), AbortSignal.timeout(600000)]), authorize = async () => { this.host.scheduledAuthority.assert(grant, grant.fence); if (!await this.validate(grant))
|
|
269
|
+
throw Error('processing_context_unavailable'); };
|
|
270
|
+
const projects = await this.projects(processingRefs), projectStamp = canonicalJson(projects), todoContext = await memory?.sourceProcessingTodoContext?.();
|
|
271
|
+
const authorizeWithProjects = async () => { await authorize(); await todoContext?.authorize(); if (canonicalJson(await this.projects(processingRefs)) !== projectStamp)
|
|
272
|
+
throw Error('project_context_changed'); };
|
|
273
|
+
for (const entry of entries) {
|
|
274
|
+
const project = projects.find(p => p.evidence_ids.includes(entry.id));
|
|
275
|
+
if (project && entry.source) {
|
|
276
|
+
entry.source.project = project.name;
|
|
277
|
+
entry.source.document = basename(entry.source.document);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
await this.reload();
|
|
281
|
+
const modelCall = async (maxTokens) => { await this.host.schedules.reserveSourceProcessingModelCall(grant.run_id, maxTokens); };
|
|
282
|
+
original.items.forEach((item, index) => { entries[index].identity_key = item.source_key; });
|
|
283
|
+
const identities = (await this.operation({ action: 'identities', ...owner, refs: processingRefs })).items;
|
|
284
|
+
const previousProducts = await this.operation({ action: 'products', include_dismissed: true });
|
|
285
|
+
const products = !batch?.profile_only && memory?.sourceProcessingProducts ? await memory.sourceProcessingProducts(entries, { projects, identities: identities ?? [], previous: previousProducts, corrections: this.#products.corrections, timezone: this.host.snapshot().settings.timezone ?? 'UTC', todos: todoContext?.todos ?? [] }, signal, authorizeWithProjects, modelCall) : undefined;
|
|
286
|
+
let profileEntries = entries, observations, profileContextKey, profileRefs = processingRefs, deferProfile = false, unchangedProfile = false;
|
|
287
|
+
if (memory?.sourceProcessingObserve) {
|
|
288
|
+
if (!batch?.profile_only) {
|
|
289
|
+
const observed = await memory.sourceProcessingObserve(entries, signal, authorizeWithProjects, modelCall);
|
|
290
|
+
const indexed = observed.map(item => ({ ...item, refs: [...new Map(item.refs.flatMap(ref => processingRefs.filter(original => original.evidence_id === ref.entry_id)).map(ref => [canonicalJson(ref), ref])).values()] }));
|
|
291
|
+
await authorizeWithProjects();
|
|
292
|
+
await this.operation({ action: 'observe', ...owner, refs: processingRefs, observations: indexed });
|
|
293
|
+
}
|
|
294
|
+
const context = await this.operation({ action: 'profile_context', ...owner });
|
|
295
|
+
const grouped = new Map();
|
|
296
|
+
for (const entry of inputs(context.items)) {
|
|
297
|
+
const existing = grouped.get(entry.id);
|
|
298
|
+
grouped.set(entry.id, existing ? { ...existing, content: existing.content + '\n\n' + entry.content } : entry);
|
|
299
|
+
}
|
|
300
|
+
profileEntries = [...grouped.values()];
|
|
301
|
+
profileRefs = [...new Map([...processingRefs, ...context.refs].map(ref => [canonicalJson(ref), ref])).values()];
|
|
302
|
+
profileContextKey = context.key;
|
|
303
|
+
deferProfile = !context.ready;
|
|
304
|
+
unchangedProfile = context.unchanged;
|
|
305
|
+
// Rehydrate current original slices; cached observations are never used as factual text.
|
|
306
|
+
observations = context.observations.map(item => ({ ...item, refs: item.refs.map(ref => ({ entry_id: ref.evidence_id, version: context.items.find(original => original.evidence_id === ref.evidence_id).version })) }));
|
|
307
|
+
}
|
|
308
|
+
// Read-only continuity: the current card's prose (already pruned to live evidence) shapes voice only, never facts.
|
|
309
|
+
// Archived prose is a fallback only when every cited source is still available, so a deleted version cannot be resurrected.
|
|
310
|
+
// Continuity stays off unless the previous prose looks healthy (several paragraphs and interests), so a thin paraphrase-style version cannot lock itself in.
|
|
311
|
+
const healthy = (prior) => prior.interests.length > 0 && (prior.about?.text.split(/\n{2,}/u).filter(part => part.trim()).length ?? 0) >= 2;
|
|
312
|
+
const continuityOf = (prior, generatedAt) => prior && healthy(prior) ? { generated_at: generatedAt, about: prior.about?.text ?? null, work: prior.work.map(item => ({ title: item.title, text: item.text })), interests: prior.interests.map(item => item.text) } : undefined;
|
|
313
|
+
let continuity = continuityOf(previous.draft, previousProducts.generated_at);
|
|
314
|
+
if (!continuity && !deferProfile && !unchangedProfile)
|
|
315
|
+
try {
|
|
316
|
+
const account = this.#account(), history = await this.operation({ action: 'profile.history', limit: 3, ...(typeof account === 'string' ? { account_scope: account } : {}) });
|
|
317
|
+
const archived = history.items.find(item => item.unavailable_sources === 0);
|
|
318
|
+
continuity = archived ? continuityOf(archived.draft, archived.generated_at) : undefined;
|
|
319
|
+
}
|
|
320
|
+
catch { /* An unreadable archive only removes continuity; generation continues from current evidence. */ }
|
|
321
|
+
// Reuse still commits product/revision updates; publish deduplicates archived prose by draft hash.
|
|
322
|
+
const draft = deferProfile || unchangedProfile ? (previous.draft ?? { about: null, work: [], interests: [] }) : await generate(profileEntries, signal, authorizeWithProjects, modelCall, observations, continuity);
|
|
323
|
+
await authorizeWithProjects();
|
|
324
|
+
this.host.scheduledAuthority.assert(grant, grant.fence);
|
|
325
|
+
if (!await this.validate(grant))
|
|
326
|
+
throw Error('processing_context_unavailable');
|
|
327
|
+
const result = await this.operation({ action: 'publish', ...owner, expected_revision: previous.revision, draft, refs: profileRefs, product_refs: processingRefs, ...(profileContextKey ? { profile_context_key: profileContextKey, ...(deferProfile ? { defer_profile: true } : {}) } : {}), ...(products ? { products } : {}) });
|
|
328
|
+
await this.reload();
|
|
329
|
+
this.host.understandingProductsChanged();
|
|
330
|
+
return result;
|
|
331
|
+
});
|
|
114
332
|
}
|
|
115
333
|
const current = batchResult.parse(await this.operation({ action: 'batch', batch_id: owner.batch_id }));
|
|
334
|
+
if (this.host.options.memory()?.sourceProcessingObserve && !current.published)
|
|
335
|
+
throw Error('Call compose for the current batch before finish; a successful durable publication is required');
|
|
116
336
|
const available = new Set(current.batch.items.map(ref => canonicalJson(ref)));
|
|
117
337
|
if (args.topics.some(topic => topic.refs.some(ref => !available.has(canonicalJson(ref)))))
|
|
118
338
|
throw Error('finish topic refs must exactly match current batch read refs; historical refs are for compose only');
|
|
@@ -128,6 +348,8 @@ export class SourceProcessingAgent {
|
|
|
128
348
|
const data = batchResult.parse(await this.operation({ action: 'batch', batch_id: run.processing.batch_id }));
|
|
129
349
|
if (!data.valid)
|
|
130
350
|
return { kind: 'wait', reason: 'processing_context_unavailable', evidence_refs: [] };
|
|
351
|
+
if (this.host.options.memory()?.sourceProcessingObserve && !data.published && run.processing.calls.some(call => call.startsWith('compose:')))
|
|
352
|
+
return { kind: 'wait', reason: 'processing_incomplete', evidence_refs: [] };
|
|
131
353
|
const refs = this.host.tasks.evidence(task.id).filter(row => row.kind === 'context' && row.content.includes(run.processing.batch_id)).map(row => row.ref);
|
|
132
354
|
if (data.batch.status === 'completed' && refs.length)
|
|
133
355
|
return { kind: 'complete', evidence_refs: refs, criteria: task.acceptance.map((_, index) => ({ index, evidence_refs: refs })) };
|
|
@@ -14,7 +14,8 @@ import { preparePrivateDatabasePath } from '../storage/private-database.js';
|
|
|
14
14
|
import { SensitivePathPolicy } from '../memory/sensitivity.js';
|
|
15
15
|
import { readKnowledgeFile, KnowledgeDocumentFailure } from '../knowledge/documents.js';
|
|
16
16
|
export const SOURCE_EXCLUDES = ['.git', '.worktrees', '.codex', '.claude', 'node_modules', 'dist', 'build', 'target', '.cache', '__pycache__', '.venv', 'venv', 'Library', 'Browser', 'Chrome', 'Chromium', 'Firefox', 'Safari'];
|
|
17
|
-
|
|
17
|
+
// Compatibility: `.nova-audio-agent` is the retired data root (a link to `.nova-personal-agent` once migrated).
|
|
18
|
+
const COMPUTER_EXCLUDES = ['Applications', 'opt', 'System', 'Windows', 'Program Files', 'Program Files (x86)', '$RECYCLE.BIN', 'System Volume Information', 'private', 'dev', 'proc', 'sys', 'bin', 'sbin', 'usr', 'etc', 'var', '.Trash', '.Trashes', '.npm', '.cargo', '.rustup', '.local', '.nova-personal-agent', '.nova-audio-agent'];
|
|
18
19
|
const policy = new SensitivePathPolicy();
|
|
19
20
|
const pathSchema = z.string().min(1).max(4096).refine(value => isAbsolute(value) && !value.includes('\0'));
|
|
20
21
|
const idSchema = z.string().uuid();
|
|
@@ -325,10 +326,17 @@ export class LocalDirectorySources {
|
|
|
325
326
|
}
|
|
326
327
|
return null;
|
|
327
328
|
}
|
|
329
|
+
canReadContext(id, version, consumer) {
|
|
330
|
+
return this.contextEntries().some(entry => entry.id === id && entry.version === version && entry.kind === 'file' && this.#records.some(record => record.view.id === entry.source_id && record.processing_consent?.conversation_providers?.includes(consumer)));
|
|
331
|
+
}
|
|
328
332
|
contextEntries() {
|
|
329
333
|
const expected = this.#options.processingGrant?.(true, 1, 0);
|
|
330
334
|
return this.#records.filter(r => !r.deleting && ['connected', 'error'].includes(r.view.state) && !!r.processing_consent?.extraction_provider && r.processing_consent.extraction_provider === expected?.extraction_provider && r.processing_consent.embedding_provider === expected?.embedding_provider).flatMap(record => record.files.filter(f => f.valid && f.excerpt && (record.view.scope !== 'computer' || !isComputerExcludedPath(record.view, f.path))).map(file => { const root = file.unit ?? computerUnit(record.view.path, file.path), activity = this.#activity?.peek(root), gitMs = activity?.lastGitCommitMs; return { last_commit_ms: gitMs ?? null, own_commits: activity?.ownCommits ?? 0, kind: 'file', id: 'source:' + file.id, version: file.fingerprint, content: file.excerpt, source_id: record.view.id, file_id: file.id, root, rel_path: record.view.scope === 'computer' ? relative(record.view.path, file.path) : join(basename(record.view.path), relative(record.view.path, file.path)), role: /\.(?:md|markdown|txt|pdf|docx)$/iu.test(file.path) ? 'document' : /\.(?:json|yaml|yml|csv)$/iu.test(file.path) ? 'config' : 'code', mtime_ms: file.mtime, hidden_prefix_depth: hiddenPrefixDepth(record.view, file.path), priority: record.view.priority_dirs.some(dir => within(dir, file.path)) ? 3 : record.view.scope === 'directory' ? 2 : this.#workspacePath && within(this.#workspacePath, file.path) ? 1 : gitMs !== null && gitMs !== undefined && Date.now() - gitMs < 30 * 86_400_000 ? 1 : 0 }; }));
|
|
331
335
|
}
|
|
336
|
+
projectRoots(ids = []) {
|
|
337
|
+
const allowed = new Map(this.contextEntries().filter(entry => entry.kind === 'file').map(entry => [entry.file_id, entry.root]));
|
|
338
|
+
return this.#records.flatMap(record => record.files.flatMap(file => { const root = allowed.get(file.id); return root ? (file.evidence_ids ?? []).filter(id => !ids.length || ids.includes(id)).map(evidence_id => ({ evidence_id, root, file: file.path })) : []; }));
|
|
339
|
+
}
|
|
332
340
|
evidenceSnapshot() {
|
|
333
341
|
const fingerprints = new Set();
|
|
334
342
|
return interleave(this.#records.filter(record => !record.deleting).map(record => balanced(record.files.filter(file => file.valid && (record.view.scope !== 'computer' || !isComputerExcludedPath(record.view, file.path))), record.view.path).map(file => ({
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { notificationSchema } from '../notifications/contracts.js';
|
|
2
|
-
import { conversationsStateSchema, initialConversations } from './conversations.js';
|
|
2
|
+
import { conversationSchema, conversationsStateSchema, initialConversations } from './conversations.js';
|
|
3
3
|
import { Worker } from 'node:worker_threads';
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
import { constants } from 'node:fs';
|
|
@@ -7,11 +7,94 @@ import { open, rename, unlink } from 'node:fs/promises';
|
|
|
7
7
|
import { dirname } from 'node:path';
|
|
8
8
|
import { randomUUID } from 'node:crypto';
|
|
9
9
|
import { preparePrivateDatabasePath } from '../storage/private-database.js';
|
|
10
|
-
import { feedItemSchema, personalSettingsSchema } from './contracts.js';
|
|
11
|
-
export const initialState = () => ({ notification_task_baseline: [], notification_intents: {}, notification_fingerprints: {}, notifications_initialized: false, conversations: initialConversations(), user_scope: null, revision: 0, feed: [], dedupe: [], brief_runs: {}, settings: { discovery_enabled: true, discovery_interval_minutes: 30 }, receipts: {} });
|
|
10
|
+
import { feedItemSchema, goalProgressSchema, personalSettingsSchema } from './contracts.js';
|
|
11
|
+
export const initialState = () => ({ schema_version: STATE_SCHEMA_VERSION, notification_task_baseline: [], notification_intents: {}, notification_fingerprints: {}, notifications_initialized: false, conversations: initialConversations(), user_scope: null, revision: 0, feed: [], dedupe: [], brief_runs: {}, goal_progress: [], goal_proposal_rejections: [], goal_proposer: { last_run_date: null, consumed_through: null, last_outcome: null }, goal_checkins: { runs: {}, last_at: {} }, settings: { discovery_enabled: true, discovery_interval_minutes: 30, proactive_daily_cap: 5, news_rank_fallback: true }, receipts: {} });
|
|
12
12
|
// ponytail: bounded JSON ledger; move to the existing Worker if 10000 retained matters are needed.
|
|
13
13
|
const MAX_STORE_BYTES = 16 * 1024 * 1024;
|
|
14
|
-
|
|
14
|
+
/** Root state is versioned so a newer build can refuse to read a file it would silently rewrite. */
|
|
15
|
+
export const STATE_SCHEMA_VERSION = 1;
|
|
16
|
+
export class PersonalStoreError extends Error {
|
|
17
|
+
code;
|
|
18
|
+
constructor(code) {
|
|
19
|
+
super(code);
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.name = 'PersonalStoreError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const WINDOWS_RENAME_RETRY_DELAYS_MS = [25, 50, 75, 100, 125, 150, 175, 200];
|
|
25
|
+
/** Windows can briefly deny replacing a file while another process closes its handle. */
|
|
26
|
+
export async function renamePersonalStoreFile(source, destination, renameFn = rename, platform = process.platform) {
|
|
27
|
+
for (let attempt = 0;; attempt++) {
|
|
28
|
+
try {
|
|
29
|
+
await renameFn(source, destination);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
const code = error.code;
|
|
34
|
+
const delay = WINDOWS_RENAME_RETRY_DELAYS_MS[attempt];
|
|
35
|
+
if (platform !== 'win32' || (code !== 'EPERM' && code !== 'EBUSY') || delay === undefined)
|
|
36
|
+
throw error;
|
|
37
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const stateSchema = z.object({ schema_version: z.number().int().nonnegative().default(STATE_SCHEMA_VERSION), notification_task_baseline: z.array(z.string()).default([]), notification_intents: z.record(z.string(), notificationSchema).default({}), notification_fingerprints: z.record(z.string(), z.string()).default({}), notifications_initialized: z.boolean().default(false), conversations: conversationsStateSchema.default(initialConversations), user_scope: z.string().max(512).nullable(), revision: z.number().int().nonnegative(), feed: z.array(feedItemSchema).max(10000), dedupe: z.array(z.string().max(128)).max(20000), brief_runs: z.record(z.string().max(128), z.object({ status: z.enum(['processing', 'success', 'failed', 'empty']), attempts: z.number().int().min(1).max(3), last_attempt_at: z.iso.datetime() })).default({}), goal_progress: z.array(goalProgressSchema).max(200).refine(rows => new Set(rows.map(r => r.goal_id)).size === rows.length).default([]), goal_proposal_rejections: z.array(z.object({ topic_key: z.string().max(64), title: z.string().max(80), rejected_at: z.iso.datetime(), until: z.iso.datetime() }).strict()).max(200).default([]), goal_proposer: z.object({ last_run_date: z.string().date().nullable(), consumed_through: z.iso.datetime().nullable(), last_outcome: z.enum(['processing', 'success', 'empty', 'failed']).nullable() }).strict().default({ last_run_date: null, consumed_through: null, last_outcome: null }), goal_checkins: z.object({ runs: z.record(z.string().date(), z.object({ status: z.enum(['processing', 'success', 'failed', 'empty', 'invalidated', 'delivered']), attempts: z.number().int().min(0).max(3), last_attempt_at: z.iso.datetime(), feed_id: z.string().max(128).nullable() }).strict()).refine(r => Object.keys(r).length <= 31), last_at: z.record(z.string().max(512), z.iso.datetime()).refine(r => Object.keys(r).length <= 200) }).strict().default({ runs: {}, last_at: {} }), settings: personalSettingsSchema, receipts: z.record(z.string().max(128), z.object({ payload: z.string().max(16384), result: z.unknown() })).refine(r => Object.keys(r).length <= 256) }).strict();
|
|
42
|
+
const storedStateSchema = stateSchema.extend({ schema_version: z.number().int().nonnegative().default(0), conversations: z.object({ ...conversationsStateSchema.shape, items: z.array(z.union([conversationSchema, conversationSchema.extend({ kind: z.literal('proactive') })])).min(1).max(192) }).strict().default(initialConversations) });
|
|
43
|
+
function parseStoredState(value) {
|
|
44
|
+
const state = storedStateSchema.parse(value), conversations = state.conversations;
|
|
45
|
+
if (state.schema_version > STATE_SCHEMA_VERSION)
|
|
46
|
+
throw new PersonalStoreError('state_version_unsupported');
|
|
47
|
+
const legacy = conversations.items.filter(item => item.kind === 'proactive');
|
|
48
|
+
for (const item of legacy) {
|
|
49
|
+
// Keep historical messages as ordinary topics; deleting the old navigation must not delete history.
|
|
50
|
+
const retained = item.messages.length > 0 || item.feed_ids.length > 0;
|
|
51
|
+
const id = retained ? `history:${item.id}` : 'chat:main';
|
|
52
|
+
if (retained && conversations.items.some(other => other.id === id))
|
|
53
|
+
throw Error('legacy_conversation_id_collision');
|
|
54
|
+
if (conversations.selected_id === item.id)
|
|
55
|
+
conversations.selected_id = 'chat:main';
|
|
56
|
+
if (conversations.voice_id === item.id)
|
|
57
|
+
conversations.voice_id = 'chat:main';
|
|
58
|
+
for (const owners of [conversations.work_owners, conversations.approval_owners])
|
|
59
|
+
for (const key of Object.keys(owners))
|
|
60
|
+
if (owners[key] === item.id)
|
|
61
|
+
owners[key] = id;
|
|
62
|
+
for (const other of conversations.items)
|
|
63
|
+
if (other.build?.source_conversation_id === item.id)
|
|
64
|
+
other.build.source_conversation_id = id;
|
|
65
|
+
if (retained)
|
|
66
|
+
conversations.items = conversations.items.map(other => other === item ? { ...item, id, kind: 'topic', messages: item.messages.map(message => ({ ...message, conversation_id: id })) } : other);
|
|
67
|
+
else
|
|
68
|
+
conversations.items = conversations.items.filter(other => other !== item);
|
|
69
|
+
}
|
|
70
|
+
state.schema_version = STATE_SCHEMA_VERSION;
|
|
71
|
+
return stateSchema.parse(state);
|
|
72
|
+
}
|
|
73
|
+
function parseStateText(text) {
|
|
74
|
+
let value;
|
|
75
|
+
try {
|
|
76
|
+
value = JSON.parse(text);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
throw new PersonalStoreError('state_corrupt');
|
|
80
|
+
}
|
|
81
|
+
// Check the version before the strict schema: a newer file may contain keys this build does not
|
|
82
|
+
// know yet, and it must fail closed as "unsupported" instead of being quarantined as corrupt.
|
|
83
|
+
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
84
|
+
const version = value.schema_version;
|
|
85
|
+
if (typeof version === 'number' && Number.isInteger(version) && version > STATE_SCHEMA_VERSION)
|
|
86
|
+
throw new PersonalStoreError('state_version_unsupported');
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
return parseStoredState(value);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error instanceof PersonalStoreError)
|
|
93
|
+
throw error;
|
|
94
|
+
// A readable file can belong to another schema; never quarantine it as damaged bytes.
|
|
95
|
+
throw new PersonalStoreError('state_schema_incompatible');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
15
98
|
export class PersonalStore {
|
|
16
99
|
path;
|
|
17
100
|
constructor(path) {
|
|
@@ -19,14 +102,22 @@ export class PersonalStore {
|
|
|
19
102
|
}
|
|
20
103
|
async ensureScheduleBackup() {
|
|
21
104
|
const path = this.path + '.before-schedules.json';
|
|
105
|
+
// An empty backup (a truncating reset) is treated as missing and recreated below; any other invalid backup still fails.
|
|
106
|
+
let empty = false;
|
|
22
107
|
try {
|
|
23
108
|
const saved = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
24
109
|
try {
|
|
25
110
|
const info = await saved.stat();
|
|
26
|
-
if (info.size > MAX_STORE_BYTES
|
|
111
|
+
if (info.size > MAX_STORE_BYTES)
|
|
112
|
+
throw new PersonalStoreError('personal_store_capacity');
|
|
113
|
+
if (process.platform !== 'win32' && (info.mode & 0o777) !== 0o600)
|
|
27
114
|
throw Error('invalid_schedule_backup');
|
|
28
|
-
|
|
29
|
-
|
|
115
|
+
if (info.size === 0 && info.isFile())
|
|
116
|
+
empty = true;
|
|
117
|
+
else {
|
|
118
|
+
parseStateText(await saved.readFile('utf8'));
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
30
121
|
}
|
|
31
122
|
finally {
|
|
32
123
|
await saved.close();
|
|
@@ -36,11 +127,13 @@ export class PersonalStore {
|
|
|
36
127
|
if (error.code !== 'ENOENT')
|
|
37
128
|
throw error;
|
|
38
129
|
}
|
|
130
|
+
if (empty)
|
|
131
|
+
await unlink(path);
|
|
39
132
|
const original = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
40
133
|
let text;
|
|
41
134
|
try {
|
|
42
135
|
if ((await original.stat()).size > MAX_STORE_BYTES)
|
|
43
|
-
throw
|
|
136
|
+
throw new PersonalStoreError('personal_store_capacity');
|
|
44
137
|
text = await original.readFile('utf8');
|
|
45
138
|
}
|
|
46
139
|
finally {
|
|
@@ -48,7 +141,7 @@ export class PersonalStore {
|
|
|
48
141
|
}
|
|
49
142
|
if (!text)
|
|
50
143
|
text = JSON.stringify(initialState());
|
|
51
|
-
|
|
144
|
+
parseStateText(text);
|
|
52
145
|
const backup = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
53
146
|
try {
|
|
54
147
|
await backup.writeFile(text);
|
|
@@ -71,18 +164,35 @@ export class PersonalStore {
|
|
|
71
164
|
const file = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
72
165
|
try {
|
|
73
166
|
if ((await file.stat()).size > MAX_STORE_BYTES)
|
|
74
|
-
throw
|
|
167
|
+
throw new PersonalStoreError('personal_store_capacity');
|
|
75
168
|
const text = await file.readFile('utf8');
|
|
76
|
-
return text === '' ? initialState() :
|
|
169
|
+
return text === '' ? initialState() : parseStateText(text);
|
|
77
170
|
}
|
|
78
171
|
finally {
|
|
79
172
|
await file.close();
|
|
80
173
|
}
|
|
81
174
|
}
|
|
175
|
+
/** Preserve an unreadable state (and its schedule backup) under a timestamped name. */
|
|
176
|
+
async quarantine(code) {
|
|
177
|
+
const stamp = new Date().toISOString().replace(/[:.]/gu, '-');
|
|
178
|
+
const to = `${this.path}.${code}-${stamp}`;
|
|
179
|
+
await renamePersonalStoreFile(this.path, to);
|
|
180
|
+
const backup = this.path + '.before-schedules.json';
|
|
181
|
+
// The primary file is already safe. A backup that cannot be moved must not turn a
|
|
182
|
+
// recoverable corrupt state into a failed startup.
|
|
183
|
+
await renamePersonalStoreFile(backup, `${backup}.${code}-${stamp}`).catch(() => { });
|
|
184
|
+
return { from: this.path, to };
|
|
185
|
+
}
|
|
82
186
|
async write(state) {
|
|
83
|
-
|
|
187
|
+
let text;
|
|
188
|
+
try {
|
|
189
|
+
text = JSON.stringify(stateSchema.parse(state));
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
throw new PersonalStoreError('state_write_failed');
|
|
193
|
+
}
|
|
84
194
|
if (Buffer.byteLength(text) > MAX_STORE_BYTES)
|
|
85
|
-
throw
|
|
195
|
+
throw new PersonalStoreError('personal_store_capacity');
|
|
86
196
|
preparePrivateDatabasePath(this.path);
|
|
87
197
|
const tmp = this.path + '.' + randomUUID() + '.tmp';
|
|
88
198
|
const file = await open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
@@ -98,7 +208,7 @@ export class PersonalStore {
|
|
|
98
208
|
await file.close();
|
|
99
209
|
}
|
|
100
210
|
try {
|
|
101
|
-
await
|
|
211
|
+
await renamePersonalStoreFile(tmp, this.path);
|
|
102
212
|
// Node cannot fsync directories on Windows; the file was synced before rename.
|
|
103
213
|
if (process.platform !== 'win32') {
|
|
104
214
|
const directory = await open(dirname(this.path), constants.O_RDONLY);
|
|
@@ -80,6 +80,9 @@ export class TaskLoop {
|
|
|
80
80
|
catch { /* durable projection remains pending; execution is never retried */ }
|
|
81
81
|
return;
|
|
82
82
|
}
|
|
83
|
+
// A plan delegation refused before executor admission is retried only by the Plan UI.
|
|
84
|
+
if (task.approved_plan && task.waiting_reason === 'plan_delegation_refused')
|
|
85
|
+
return;
|
|
83
86
|
if (task.pending_delivery || this.ports.ready?.(task) === false)
|
|
84
87
|
return;
|
|
85
88
|
if (task.phase === 'cancelled' || task.controller.kind !== 'nova' || this.tasks.activeWork(task.id).length)
|