@xopcai/xopc 0.0.125 → 0.0.127
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -102
- package/README.zh-CN.md +51 -98
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/feishu/src/schema/config-schema.d.ts +6 -6
- package/dist/extensions/feishu/src/workflow-progress.js +1 -1
- package/dist/extensions/telegram/src/adapters/streaming-adapter.js +1 -1
- package/dist/extensions/telegram/src/config-schema.d.ts +8 -8
- package/dist/extensions/telegram/src/inbound-processor.js +1 -1
- package/dist/extensions/telegram/src/plugin.js +1 -1
- package/dist/extensions/telegram/src/routing-integration.js +2 -2
- package/dist/extensions/telegram/src/workflow-progress.js +1 -1
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/extensions/weixin/src/api/api.js +1 -1
- package/dist/extensions/weixin/src/config-schema.d.ts +3 -3
- package/dist/extensions/weixin/src/plugin.js +1 -1
- package/dist/extensions/weixin/src/workflow-progress.js +1 -1
- package/dist/gateway/static/root/assets/{agent-avatar-dicebear-BKDKICZV.js → agent-avatar-dicebear-CgGgO4OV.js} +1 -1
- package/dist/gateway/static/root/assets/agents-k59l7NMb.js +2 -0
- package/dist/gateway/static/root/assets/{app-management-settings-panel-DI4BqHKW.js → app-management-settings-panel-DeQsTsyy.js} +1 -1
- package/dist/gateway/static/root/assets/{appearance-settings-6_ie3NQ4.js → appearance-settings-BnHQW7Hv.js} +1 -1
- package/dist/gateway/static/root/assets/apps-page-BG9b4abG.js +1 -0
- package/dist/gateway/static/root/assets/{archive-plugin-kUHEJ1HK.js → archive-plugin-5NXT7Zqv.js} +1 -1
- package/dist/gateway/static/root/assets/{attachment-load-Dm-9prpU.js → attachment-load-DghwhYe0.js} +1 -1
- package/dist/gateway/static/root/assets/{automation-suggestion-card-OTxQTPnC.js → automation-suggestion-card-DYmESgwl.js} +1 -1
- package/dist/gateway/static/root/assets/automations-page-De8mVutL.js +4 -0
- package/dist/gateway/static/root/assets/{binary-plugins-DllA_jQ0.js → binary-plugins-DSbPKdWX.js} +1 -1
- package/dist/gateway/static/root/assets/{block-editor-Cm6CWNj1.js → block-editor-CoZ-_np-.js} +28 -28
- package/dist/gateway/static/root/assets/browser-settings-page-C_ZRa4LF.js +8 -0
- package/dist/gateway/static/root/assets/{capability-presets-api-VJ89b6I2.js → capability-presets-api-hny224j-.js} +1 -1
- package/dist/gateway/static/root/assets/{capability-presets-settings-panel-BaPj8wC2.js → capability-presets-settings-panel-Drc0qLsw.js} +1 -1
- package/dist/gateway/static/root/assets/{channel-recipient-api-B5PwBEUx.js → channel-recipient-api-DAlOHxKJ.js} +1 -1
- package/dist/gateway/static/root/assets/channels-settings-CA20zBV9.js +1 -0
- package/dist/gateway/static/root/assets/connectors-page-qMyMB5te.js +2 -0
- package/dist/gateway/static/root/assets/desktop-pet-XG6Vb_fZ.js +1 -0
- package/dist/gateway/static/root/assets/desktop-pet-settings-npJ0Oh5p.js +1 -0
- package/dist/gateway/static/root/assets/desktop-pet-sprite-DqZ6fbIj.js +1 -0
- package/dist/gateway/static/root/assets/directory-picker-path-field-BR2ItBuf.js +1 -0
- package/dist/gateway/static/root/assets/dreaming-settings-CkUZ997f.js +3 -0
- package/dist/gateway/static/root/assets/{extension-debug-page-BaM0FpW7.js → extension-debug-page-Tl0f1rNv.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-page-DuZWVOGA.js → extension-page-Ck7QuwE3.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-settings-page-DarVtbmJ.js → extension-settings-page-3RMhQtZ3.js} +1 -1
- package/dist/gateway/static/root/assets/{fetch-NFKfkqrd.js → fetch-pg2ErdAk.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-config-api-CFEm9rgy.js → gateway-config-api-DbG97ia2.js} +1 -1
- package/dist/gateway/static/root/assets/gateway-settings-B8cyqKk-.js +1 -0
- package/dist/gateway/static/root/assets/{gateway-startup-retry-Dtwh_yGg.js → gateway-startup-retry-Yh8h3hkj.js} +1 -1
- package/dist/gateway/static/root/assets/{goal-create-dialog-BKP7ylcG.js → goal-create-dialog-DmeW7Zz3.js} +1 -1
- package/dist/gateway/static/root/assets/goal-detail-page-DrTyGbVD.js +1 -0
- package/dist/gateway/static/root/assets/{goals-config-api-DTWZNA_Y.js → goals-config-api-CxCWGIBB.js} +1 -1
- package/dist/gateway/static/root/assets/goals-page-DV1bJhIh.js +2 -0
- package/dist/gateway/static/root/assets/{goals-settings-Bhct0ZT-.js → goals-settings-9DrfOkP5.js} +1 -1
- package/dist/gateway/static/root/assets/{heartbeat-settings-C-UxSU4a.js → heartbeat-settings-KaDpZrv0.js} +1 -1
- package/dist/gateway/static/root/assets/index-C2F0Clvm.js +256 -0
- package/dist/gateway/static/root/assets/index-COQSX5d_.css +1 -0
- package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-DCjy2y4d.js → keyboard-shortcuts-settings-CfQrt_Rb.js} +1 -1
- package/dist/gateway/static/root/assets/logs-page-C9dpiNTF.js +2 -0
- package/dist/gateway/static/root/assets/{markdown-split-BaqxP-GQ.js → markdown-split-BwiMdCf_.js} +1 -1
- package/dist/gateway/static/root/assets/{media-plugins-DQ_EXloK.js → media-plugins-DhoizyZv.js} +1 -1
- package/dist/gateway/static/root/assets/messages-DmnbiNxU.js +3 -0
- package/dist/gateway/static/root/assets/models-hub-panel-zdCdmBmH.js +2 -0
- package/dist/gateway/static/root/assets/notes-page-MpGeFfPt.js +1 -0
- package/dist/gateway/static/root/assets/notes-workbench-DYCM3yd2.js +2 -0
- package/dist/gateway/static/root/assets/{page-tabs-EIZhLppK.js → page-tabs-DDC2t4Z8.js} +1 -1
- package/dist/gateway/static/root/assets/{preview-open-alternatives-r_uB4Epr.js → preview-open-alternatives-BTmk-XDM.js} +1 -1
- package/dist/gateway/static/root/assets/project-detail-page-Cu0ElRnS.js +1 -0
- package/dist/gateway/static/root/assets/projects-page-DakNaUjZ.js +1 -0
- package/dist/gateway/static/root/assets/remote-access-hub-DYKjt7L9.js +1 -0
- package/dist/gateway/static/root/assets/{save-bar-controls-B132Uf-2.js → save-bar-controls-DqU-yKIh.js} +1 -1
- package/dist/gateway/static/root/assets/{schedule-field-B5qshALm.js → schedule-field-CUttkoSB.js} +1 -1
- package/dist/gateway/static/root/assets/{schema-form-CvLmkdS9.js → schema-form-CVSQA9nI.js} +1 -1
- package/dist/gateway/static/root/assets/sessions-page-CcGHDsz1.js +1 -0
- package/dist/gateway/static/root/assets/settings-advanced-gate-CuFdeKNu.js +1 -0
- package/dist/gateway/static/root/assets/{settings-collapsible-section-pRlvqsAf.js → settings-collapsible-section-CK7ogS-P.js} +1 -1
- package/dist/gateway/static/root/assets/settings-form-section-Bugp38Fa.js +1 -0
- package/dist/gateway/static/root/assets/settings-page-0AJoUvxi.js +1 -0
- package/dist/gateway/static/root/assets/settings-page-layout-DBRWwdhh.js +1 -0
- package/dist/gateway/static/root/assets/setup-status-panel-D6a_hEk7.js +1 -0
- package/dist/gateway/static/root/assets/{share-preview-page-v6-IOp8t.js → share-preview-page-BtsuETKF.js} +1 -1
- package/dist/gateway/static/root/assets/shares-settings-CcEFT7S9.js +1 -0
- package/dist/gateway/static/root/assets/skill-reload-api-BcN_RuTD.js +1 -0
- package/dist/gateway/static/root/assets/skills-page-BbRZZZA5.js +2 -0
- package/dist/gateway/static/root/assets/{system-settings-panel-HUU2FFjM.js → system-settings-panel-DJ6YuLqR.js} +1 -1
- package/dist/gateway/static/root/assets/{typed-models-lib-AH160QHh.js → typed-models-lib-B0T7N8Km.js} +1 -1
- package/dist/gateway/static/root/assets/{use-channel-catalog-BXzDmjCQ.js → use-channel-catalog-C6vrxdzZ.js} +1 -1
- package/dist/gateway/static/root/assets/{user-profile-settings-panel-DxwnQvQ3.js → user-profile-settings-panel-DZ0nKMgj.js} +1 -1
- package/dist/gateway/static/root/assets/{utils-i5POEtqd.js → utils-CehXcWAY.js} +1 -1
- package/dist/gateway/static/root/assets/voice-api-key-field-2QKflCx8.js +1 -0
- package/dist/gateway/static/root/assets/work-item-detail-page-DfJnuWq1.js +1 -0
- package/dist/gateway/static/root/assets/{workflow-run-setup-panel-ClVVMgN-.js → workflow-run-setup-panel-c4jeaohQ.js} +2 -2
- package/dist/gateway/static/root/assets/{workflow-start-dialog-Dv4ZA1T0.js → workflow-start-dialog-ENRHjoqa.js} +1 -1
- package/dist/gateway/static/root/assets/workflows-page-BJwwFTm_.js +18 -0
- package/dist/gateway/static/root/index.html +5 -5
- package/dist/package.js +1 -1
- package/dist/src/activity/context.d.ts +11 -0
- package/dist/src/activity/context.js +36 -0
- package/dist/src/activity/context.js.map +1 -0
- package/dist/src/activity/emitter.d.ts +6 -0
- package/dist/src/activity/emitter.js +43 -0
- package/dist/src/activity/emitter.js.map +1 -0
- package/dist/src/activity/index.d.ts +3 -0
- package/dist/src/activity/index.js +3 -0
- package/dist/src/activity/service.d.ts +12 -0
- package/dist/src/activity/service.js +59 -0
- package/dist/src/activity/service.js.map +1 -0
- package/dist/src/activity/types.d.ts +109 -0
- package/dist/src/activity/types.js +1 -0
- package/dist/src/agent/agent-instance-gateway.d.ts +5 -0
- package/dist/src/agent/agent-manager.d.ts +21 -0
- package/dist/src/agent/agent-manager.js +118 -6
- package/dist/src/agent/agent-manager.js.map +1 -1
- package/dist/src/agent/capabilities/definitions.d.ts +153 -0
- package/dist/src/agent/capabilities/definitions.js +156 -0
- package/dist/src/agent/capabilities/definitions.js.map +1 -0
- package/dist/src/agent/capabilities/index.d.ts +2 -0
- package/dist/src/agent/capabilities/index.js +3 -0
- package/dist/src/agent/capabilities/registry.d.ts +10 -0
- package/dist/src/agent/capabilities/registry.js +51 -0
- package/dist/src/agent/capabilities/registry.js.map +1 -0
- package/dist/src/agent/context/project-context.js +2 -2
- package/dist/src/agent/context/workspace-seed.js +2 -2
- package/dist/src/agent/embedded/run-for-session.js +1 -1
- package/dist/src/agent/goals/post-turn.js +2 -2
- package/dist/src/agent/ipc/bus.js +1 -1
- package/dist/src/agent/mcp/bundle-mcp-materialize.js +1 -1
- package/dist/src/agent/mcp/bundle-mcp-runtime.js +1 -1
- package/dist/src/agent/mcp/mcp-transport-config.js +1 -1
- package/dist/src/agent/mcp/mcp-transport.js +1 -1
- package/dist/src/agent/memory/plugin-discovery.js +1 -1
- package/dist/src/agent/models/manager.js +1 -1
- package/dist/src/agent/orchestration/agent-orchestrator.js +1 -1
- package/dist/src/agent/service/process-direct-one-shot.js +5 -3
- package/dist/src/agent/service/process-direct-one-shot.js.map +1 -1
- package/dist/src/agent/service/process-direct-streaming.js +4 -3
- package/dist/src/agent/service/process-direct-streaming.js.map +1 -1
- package/dist/src/agent/service.d.ts +2 -0
- package/dist/src/agent/service.js +9 -3
- package/dist/src/agent/service.js.map +1 -1
- package/dist/src/agent/service.types.d.ts +7 -0
- package/dist/src/agent/session/session-inspector.js +1 -1
- package/dist/src/agent/skills/hub-pull.js +1 -1
- package/dist/src/agent/skills/parse-skill-metadata.js +9 -1
- package/dist/src/agent/skills/parse-skill-metadata.js.map +1 -1
- package/dist/src/agent/skills/skill-manager.d.ts +4 -0
- package/dist/src/agent/skills/skill-manager.js +17 -0
- package/dist/src/agent/skills/skill-manager.js.map +1 -1
- package/dist/src/agent/skills/types.d.ts +5 -0
- package/dist/src/agent/tool-manuals/index.js +15 -6
- package/dist/src/agent/tool-manuals/index.js.map +1 -1
- package/dist/src/agent/tool-manuals/xopc-use.d.ts +1 -0
- package/dist/src/agent/tool-manuals/xopc-use.js +204 -0
- package/dist/src/agent/tool-manuals/xopc-use.js.map +1 -0
- package/dist/src/agent/tools/desktop-pet-tool.d.ts +24 -0
- package/dist/src/agent/tools/desktop-pet-tool.js +90 -0
- package/dist/src/agent/tools/desktop-pet-tool.js.map +1 -0
- package/dist/src/agent/tools/factory.d.ts +9 -0
- package/dist/src/agent/tools/factory.js +26 -0
- package/dist/src/agent/tools/factory.js.map +1 -1
- package/dist/src/agent/tools/goal-tool.js +2 -2
- package/dist/src/agent/tools/index.d.ts +2 -0
- package/dist/src/agent/tools/index.js +3 -1
- package/dist/src/agent/tools/workflow-tool.js +1 -1
- package/dist/src/agent/tools/xopc-use-tool.d.ts +34 -0
- package/dist/src/agent/tools/xopc-use-tool.js +636 -0
- package/dist/src/agent/tools/xopc-use-tool.js.map +1 -0
- package/dist/src/agent-manifest/schema.d.ts +27 -27
- package/dist/src/automations/api/routes.js +1 -1
- package/dist/src/automations/domain/validation.d.ts +55 -55
- package/dist/src/automations/draft/automation-draft-service.js +1 -1
- package/dist/src/automations/draft/automation-draft-validator.d.ts +25 -25
- package/dist/src/automations/service/action-executor.js +2 -2
- package/dist/src/browser/cdp-local-launcher.js +1 -1
- package/dist/src/browser/providers/browser-ext-install.js +3 -3
- package/dist/src/browser/providers/cloakbrowser.js +2 -2
- package/dist/src/browser/providers/playwright-doctor.js +1 -1
- package/dist/src/browser/stealth.js +1 -1
- package/dist/src/chat-commands/agent-edit.js +1 -1
- package/dist/src/chat-commands/builtins/config.js +1 -1
- package/dist/src/chat-commands/builtins/goal.js +2 -2
- package/dist/src/chat-commands/context.js +1 -1
- package/dist/src/cli/commands/agent.js +3 -3
- package/dist/src/cli/commands/doctor/checks/database-schema.js +2 -2
- package/dist/src/cli/commands/doctor/checks/session-integrity.js +1 -1
- package/dist/src/cli/commands/extension-marketplace.js +1 -1
- package/dist/src/cli/commands/extension-pack.js +1 -1
- package/dist/src/cli/commands/gateway/lifecycle.js +1 -1
- package/dist/src/cli/commands/goal.js +3 -3
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/commands/models.js +1 -1
- package/dist/src/cli/commands/onboard.js +1 -1
- package/dist/src/cli/commands/profile.js +1 -1
- package/dist/src/cli/commands/project.js +4 -4
- package/dist/src/cli/commands/tunnel.js +1 -1
- package/dist/src/cli/commands/update.js +1 -1
- package/dist/src/cli/extension-cli-register.js +1 -1
- package/dist/src/config/agent-profile.js +1 -1
- package/dist/src/config/gateway-bind.js +1 -1
- package/dist/src/config/index.js +2 -2
- package/dist/src/config/loader.js +1 -1
- package/dist/src/config/models-json.d.ts +14 -14
- package/dist/src/config/models-json.js +1 -1
- package/dist/src/config/schema.d.ts +60 -60
- package/dist/src/daemon/launchd.js +1 -1
- package/dist/src/daemon/systemd.js +1 -1
- package/dist/src/extensions/discover-extensions.js +1 -1
- package/dist/src/extensions/loader.js +2 -2
- package/dist/src/gateway/agent-builtin-tools.d.ts +1 -1
- package/dist/src/gateway/agent-builtin-tools.js +1 -0
- package/dist/src/gateway/agent-builtin-tools.js.map +1 -1
- package/dist/src/gateway/agents-admin.js +1 -1
- package/dist/src/gateway/hono/lib/config-payload.d.ts +14 -14
- package/dist/src/gateway/hono/lib/static-ui.js +1 -1
- package/dist/src/gateway/hono/middleware/log-context.js +8 -1
- package/dist/src/gateway/hono/middleware/log-context.js.map +1 -1
- package/dist/src/gateway/hono/routes/activity.d.ts +14 -0
- package/dist/src/gateway/hono/routes/activity.js +72 -0
- package/dist/src/gateway/hono/routes/activity.js.map +1 -0
- package/dist/src/gateway/hono/routes/commands-skills.js +7 -0
- package/dist/src/gateway/hono/routes/commands-skills.js.map +1 -1
- package/dist/src/gateway/hono/routes/goals.js +1 -1
- package/dist/src/gateway/hono/routes/index.js +2 -0
- package/dist/src/gateway/hono/routes/index.js.map +1 -1
- package/dist/src/gateway/hono/routes/lazy-bundles.js +2 -1
- package/dist/src/gateway/hono/routes/lazy-bundles.js.map +1 -1
- package/dist/src/gateway/hono/routes/memory.js +2 -2
- package/dist/src/gateway/hono/routes/projects.js +93 -15
- package/dist/src/gateway/hono/routes/projects.js.map +1 -1
- package/dist/src/gateway/hono/routes/sessions.js +101 -2
- package/dist/src/gateway/hono/routes/sessions.js.map +1 -1
- package/dist/src/gateway/hono/routes/workflows.js +2 -2
- package/dist/src/gateway/lock.js +1 -1
- package/dist/src/gateway/ports.js +1 -1
- package/dist/src/gateway/run-loop.js +1 -1
- package/dist/src/gateway/service/run-gateway-agent.js +6 -2
- package/dist/src/gateway/service/run-gateway-agent.js.map +1 -1
- package/dist/src/gateway/service/sessions-api.d.ts +10 -0
- package/dist/src/gateway/service/sessions-api.js +31 -0
- package/dist/src/gateway/service/sessions-api.js.map +1 -1
- package/dist/src/gateway/service.js +12 -9
- package/dist/src/gateway/service.js.map +1 -1
- package/dist/src/goals/goal-store.js +1 -1
- package/dist/src/goals/goal-store.js.map +1 -1
- package/dist/src/goals/goal-workflow-judge.js +1 -1
- package/dist/src/infra/ports.js +1 -1
- package/dist/src/infra/ssh-tunnel.js +1 -1
- package/dist/src/infra/update-check.js +1 -1
- package/dist/src/infra/update-restart.js +1 -1
- package/dist/src/migrations/runner.js +1 -1
- package/dist/src/notes/service.js +65 -6
- package/dist/src/notes/service.js.map +1 -1
- package/dist/src/notes/store.js +1 -1
- package/dist/src/pets/factory.d.ts +25 -0
- package/dist/src/pets/factory.js +327 -0
- package/dist/src/pets/factory.js.map +1 -0
- package/dist/src/pets/manifest.d.ts +2 -0
- package/dist/src/pets/manifest.js +16 -0
- package/dist/src/pets/manifest.js.map +1 -0
- package/dist/src/pets/validator.d.ts +12 -0
- package/dist/src/pets/validator.js +175 -0
- package/dist/src/pets/validator.js.map +1 -0
- package/dist/src/projects/project-service.d.ts +4 -1
- package/dist/src/projects/project-service.js +65 -2
- package/dist/src/projects/project-service.js.map +1 -1
- package/dist/src/projects/project-store.d.ts +3 -1
- package/dist/src/projects/project-store.js +56 -6
- package/dist/src/projects/project-store.js.map +1 -1
- package/dist/src/projects/types.d.ts +12 -0
- package/dist/src/projects/workspace.js +1 -1
- package/dist/src/routing/agent-session-key.js +1 -1
- package/dist/src/routing/resolve-route.js +1 -1
- package/dist/src/routing/resolve-tui-session-key.js +1 -1
- package/dist/src/session/client-history.d.ts +3 -0
- package/dist/src/session/client-history.js +24 -9
- package/dist/src/session/client-history.js.map +1 -1
- package/dist/src/session/init-session-turn.js +1 -1
- package/dist/src/session/resolve-session.js +1 -1
- package/dist/src/session/session-title.js +24 -4
- package/dist/src/session/session-title.js.map +1 -1
- package/dist/src/session/store.js +1 -1
- package/dist/src/session/types.d.ts +4 -0
- package/dist/src/session/types.js.map +1 -1
- package/dist/src/storage/sqlite/activity-repository.d.ts +8 -0
- package/dist/src/storage/sqlite/activity-repository.js +208 -0
- package/dist/src/storage/sqlite/activity-repository.js.map +1 -0
- package/dist/src/storage/sqlite/connection.js +1 -1
- package/dist/src/storage/sqlite/index.d.ts +1 -0
- package/dist/src/storage/sqlite/index.js +2 -1
- package/dist/src/storage/sqlite/migrations/024_activity_events.sql +62 -0
- package/dist/src/storage/sqlite/migrations/025_project_pinned_at.sql +5 -0
- package/dist/src/storage/sqlite/migrations/runner.d.ts +1 -1
- package/dist/src/storage/sqlite/migrations/runner.js +3 -3
- package/dist/src/storage/sqlite/migrations/runner.js.map +1 -1
- package/dist/src/storage/sqlite/migrations/runner.ts +1 -1
- package/dist/src/storage/sqlite/row-mappers.js +1 -1
- package/dist/src/storage/sqlite/schema.js +1 -1
- package/dist/src/storage/sqlite/schema.sql +63 -0
- package/dist/src/storage/sqlite/session-repository.js +11 -0
- package/dist/src/storage/sqlite/session-repository.js.map +1 -1
- package/dist/src/tui/backends/embedded-backend.d.ts +13 -0
- package/dist/src/tui/backends/embedded-backend.js +76 -7
- package/dist/src/tui/backends/embedded-backend.js.map +1 -1
- package/dist/src/tui/backends/gateway-sse-backend.d.ts +13 -0
- package/dist/src/tui/backends/gateway-sse-backend.js +53 -0
- package/dist/src/tui/backends/gateway-sse-backend.js.map +1 -1
- package/dist/src/tui/chat-history.js +16 -3
- package/dist/src/tui/chat-history.js.map +1 -1
- package/dist/src/tui/clipboard-image.js +1 -1
- package/dist/src/tui/components/chat-log.d.ts +23 -3
- package/dist/src/tui/components/chat-log.js +68 -9
- package/dist/src/tui/components/chat-log.js.map +1 -1
- package/dist/src/tui/components/tui-bottom-bar.js +9 -5
- package/dist/src/tui/components/tui-bottom-bar.js.map +1 -1
- package/dist/src/tui/tui-backend.d.ts +16 -0
- package/dist/src/tui/tui-command-formatters.js +2 -2
- package/dist/src/tui/tui-commands.d.ts +9 -0
- package/dist/src/tui/tui-commands.js +95 -6
- package/dist/src/tui/tui-commands.js.map +1 -1
- package/dist/src/tui/tui-picker-overlay.d.ts +1 -0
- package/dist/src/tui/tui-picker-overlay.js +36 -1
- package/dist/src/tui/tui-picker-overlay.js.map +1 -1
- package/dist/src/tui/tui-picker-services.d.ts +13 -0
- package/dist/src/tui/tui-run-state.js +11 -0
- package/dist/src/tui/tui-run-state.js.map +1 -1
- package/dist/src/tui/tui-run-status-format.d.ts +3 -0
- package/dist/src/tui/tui-run-status-format.js +33 -0
- package/dist/src/tui/tui-run-status-format.js.map +1 -0
- package/dist/src/tui/tui-session-actions.d.ts +5 -0
- package/dist/src/tui/tui-session-actions.js +24 -0
- package/dist/src/tui/tui-session-actions.js.map +1 -1
- package/dist/src/tui/tui-timeline-picker.d.ts +19 -0
- package/dist/src/tui/tui-timeline-picker.js +81 -0
- package/dist/src/tui/tui-timeline-picker.js.map +1 -0
- package/dist/src/tui/tui-timeline.d.ts +15 -0
- package/dist/src/tui/tui-timeline.js +65 -0
- package/dist/src/tui/tui-timeline.js.map +1 -0
- package/dist/src/tui/tui-types.d.ts +1 -0
- package/dist/src/tui/tui-types.js +1 -0
- package/dist/src/tui/tui-types.js.map +1 -1
- package/dist/src/tui/tui.js +31 -25
- package/dist/src/tui/tui.js.map +1 -1
- package/dist/src/utils/index.js +1 -1
- package/dist/src/utils/logger/index.js +1 -1
- package/dist/src/utils/logger/stats.d.ts +3 -3
- package/dist/src/utils/logger.js +1 -1
- package/dist/src/work-items/agent-context.d.ts +5 -1
- package/dist/src/work-items/agent-context.js +39 -3
- package/dist/src/work-items/agent-context.js.map +1 -1
- package/dist/src/work-items/work-item-service.d.ts +2 -0
- package/dist/src/work-items/work-item-service.js +97 -0
- package/dist/src/work-items/work-item-service.js.map +1 -1
- package/dist/src/workflows/draft/workflow-draft-service.js +1 -1
- package/dist/src/workflows/service/workflow-session-bridge.js +1 -1
- package/package.json +5 -5
- package/skills/creative/hatch-pet/SKILL.md +63 -0
- package/dist/gateway/static/root/assets/agents-BnTB7-c5.js +0 -2
- package/dist/gateway/static/root/assets/apps-page-B6bG65SW.js +0 -1
- package/dist/gateway/static/root/assets/automations-page-1lVbo0dS.js +0 -1
- package/dist/gateway/static/root/assets/browser-settings-page-CzDBlOK0.js +0 -8
- package/dist/gateway/static/root/assets/channels-settings-Df4m7p1k.js +0 -1
- package/dist/gateway/static/root/assets/connectors-page-BMTphmHS.js +0 -2
- package/dist/gateway/static/root/assets/directory-picker-path-field-DySMzOF6.js +0 -1
- package/dist/gateway/static/root/assets/dist-By6Rh2ee.js +0 -1
- package/dist/gateway/static/root/assets/dreaming-settings-D_AjSnV_.js +0 -3
- package/dist/gateway/static/root/assets/gateway-settings-BMk2S5td.js +0 -1
- package/dist/gateway/static/root/assets/goal-detail-page-C2cTxf71.js +0 -1
- package/dist/gateway/static/root/assets/goals-page-CTmA3hWK.js +0 -2
- package/dist/gateway/static/root/assets/index-BNHDd2j1.css +0 -1
- package/dist/gateway/static/root/assets/index-BPXLPMuY.js +0 -193
- package/dist/gateway/static/root/assets/logs-page-CGc3_CQU.js +0 -2
- package/dist/gateway/static/root/assets/messages-CjuIJcZl.js +0 -3
- package/dist/gateway/static/root/assets/models-hub-panel-Drz4UQMb.js +0 -2
- package/dist/gateway/static/root/assets/notes-page-CY1ylng1.js +0 -1
- package/dist/gateway/static/root/assets/notes-workbench-X7IaD--t.js +0 -2
- package/dist/gateway/static/root/assets/project-detail-page-DE5adRBE.js +0 -1
- package/dist/gateway/static/root/assets/projects-page-CuOb1k6F.js +0 -1
- package/dist/gateway/static/root/assets/remote-access-hub-BOxNrUVA.js +0 -1
- package/dist/gateway/static/root/assets/sessions-page-CY0IQcGW.js +0 -1
- package/dist/gateway/static/root/assets/settings-advanced-gate-D4NBNVCB.js +0 -1
- package/dist/gateway/static/root/assets/settings-form-section-BBYUDLVd.js +0 -1
- package/dist/gateway/static/root/assets/settings-page-DaO7zYZM.js +0 -1
- package/dist/gateway/static/root/assets/settings-page-layout-D8g9PAek.js +0 -1
- package/dist/gateway/static/root/assets/setup-status-panel-Bks0CLLT.js +0 -1
- package/dist/gateway/static/root/assets/shares-settings-CEZsKm9r.js +0 -1
- package/dist/gateway/static/root/assets/skill-reload-api-oTkHbb9W.js +0 -1
- package/dist/gateway/static/root/assets/skills-page-DigsbZ6K.js +0 -2
- package/dist/gateway/static/root/assets/voice-api-key-field-CEJklEgb.js +0 -1
- package/dist/gateway/static/root/assets/work-item-detail-page-CD6FL_Rs.js +0 -1
- package/dist/gateway/static/root/assets/workflows-page-OLQiUpoW.js +0 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-store.js","names":[],"sources":["../../../src/goals/goal-store.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { getSqliteDatabase, runSqliteWriteTransaction } from '../storage/sqlite/transaction.js';\nimport type {\n CreateGoalInput,\n Goal,\n GoalChecklistAddedBy,\n GoalChecklistItem,\n GoalChecklistStatus,\n GoalContextAttachment,\n GoalContextMessage,\n GoalEvent,\n GoalEvidence,\n GoalListQuery,\n GoalPriority,\n GoalRun,\n GoalRunStatus,\n GoalRunVerdict,\n GoalSource,\n GoalStatus,\n} from './types.js';\n\ntype GoalRow = {\n goal_id: string;\n title: string;\n description: string | null;\n status: string;\n agent_id: string;\n priority: string;\n deadline_at: number | null;\n created_at: number;\n updated_at: number;\n completed_at: number | null;\n archived_at: number | null;\n active_session_key: string | null;\n current_run_id: string | null;\n next_action: string | null;\n blocked_reason: string | null;\n judge_model_ref: string | null;\n max_turns: number;\n turns_used: number;\n ui_locale: string | null;\n source: string;\n project_id: string | null;\n};\n\ntype ChecklistRow = {\n item_id: string;\n goal_id: string;\n text: string;\n status: string;\n added_by: string;\n added_at: number;\n completed_at: number | null;\n evidence_summary: string | null;\n sort_order: number;\n};\n\ntype GoalRunRow = {\n run_id: string;\n goal_id: string;\n session_key: string;\n source: string;\n status: string;\n started_at: number;\n finished_at: number | null;\n verdict: string | null;\n reason: string | null;\n next_action: string | null;\n assistant_preview: string | null;\n checklist_done: number | null;\n checklist_total: number | null;\n confidence: number | null;\n missing_evidence_json: string | null;\n user_question: string | null;\n completed_checklist_item_ids_json: string | null;\n};\n\ntype EventRow = {\n event_id: string;\n goal_id: string;\n run_id: string | null;\n kind: string;\n message: string;\n data_json: string | null;\n created_at: number;\n};\n\ntype EvidenceRow = {\n evidence_id: string;\n goal_id: string;\n run_id: string | null;\n kind: GoalEvidence['kind'];\n title: string;\n summary: string | null;\n uri: string | null;\n data_json: string | null;\n created_at: number;\n};\n\ntype GoalContextRow = {\n goal_id: string;\n text: string;\n attachments_json: string;\n created_at: number;\n updated_at: number;\n};\n\nfunction goalFromRow(row: GoalRow): Goal {\n return {\n id: row.goal_id,\n title: row.title,\n description: row.description ?? undefined,\n status: row.status as GoalStatus,\n agentId: row.agent_id,\n priority: row.priority as GoalPriority,\n deadlineAt: row.deadline_at ?? undefined,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n completedAt: row.completed_at ?? undefined,\n archivedAt: row.archived_at ?? undefined,\n activeSessionKey: row.active_session_key ?? undefined,\n currentRunId: row.current_run_id ?? undefined,\n nextAction: row.next_action ?? undefined,\n blockedReason: row.blocked_reason ?? undefined,\n judgeModelRef: row.judge_model_ref ?? undefined,\n maxTurns: row.max_turns,\n turnsUsed: row.turns_used,\n uiLocale: row.ui_locale === 'en' || row.ui_locale === 'zh' ? row.ui_locale : undefined,\n source: row.source as GoalSource,\n projectId: row.project_id ?? undefined,\n };\n}\n\nfunction checklistFromRow(row: ChecklistRow): GoalChecklistItem {\n return {\n id: row.item_id,\n goalId: row.goal_id,\n text: row.text,\n status: row.status as GoalChecklistStatus,\n addedBy: row.added_by as GoalChecklistAddedBy,\n addedAt: row.added_at,\n completedAt: row.completed_at ?? undefined,\n evidenceSummary: row.evidence_summary ?? undefined,\n sortOrder: row.sort_order,\n };\n}\n\nfunction runFromRow(row: GoalRunRow): GoalRun {\n return {\n id: row.run_id,\n goalId: row.goal_id,\n sessionKey: row.session_key,\n source: row.source as GoalSource,\n status: row.status as GoalRunStatus,\n startedAt: row.started_at,\n finishedAt: row.finished_at ?? undefined,\n verdict: row.verdict ? (row.verdict as GoalRunVerdict) : undefined,\n reason: row.reason ?? undefined,\n nextAction: row.next_action ?? undefined,\n assistantPreview: row.assistant_preview ?? undefined,\n checklistProgress:\n row.checklist_done != null && row.checklist_total != null\n ? { done: row.checklist_done, total: row.checklist_total }\n : undefined,\n confidence: row.confidence ?? undefined,\n missingEvidence: parseJsonStringArray(row.missing_evidence_json),\n userQuestion: row.user_question ?? undefined,\n completedChecklistItemIds: parseJsonStringArray(row.completed_checklist_item_ids_json),\n };\n}\n\nfunction parseJsonField(raw: string | null): unknown {\n if (!raw) return undefined;\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return undefined;\n }\n}\n\nfunction parseJsonStringArray(raw: string | null): string[] | undefined {\n const value = parseJsonField(raw);\n if (!Array.isArray(value)) return undefined;\n const rows = value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0);\n return rows.length ? rows : undefined;\n}\n\nfunction parseGoalContextAttachments(raw: string): GoalContextAttachment[] {\n const parsed = parseJsonField(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((item): item is GoalContextAttachment => {\n if (!item || typeof item !== 'object') return false;\n const ref = item as Partial<GoalContextAttachment>;\n return (\n typeof ref.id === 'string' &&\n (ref.bucket === 'inbound' || ref.bucket === 'tts' || ref.bucket === 'outbound') &&\n typeof ref.type === 'string' &&\n typeof ref.mimeType === 'string' &&\n typeof ref.name === 'string' &&\n typeof ref.size === 'number' &&\n typeof ref.uri === 'string' &&\n typeof ref.path === 'string'\n );\n });\n}\n\nfunction goalContextFromRow(row: GoalContextRow): GoalContextMessage {\n return {\n goalId: row.goal_id,\n text: row.text,\n attachments: parseGoalContextAttachments(row.attachments_json),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction eventFromRow(row: EventRow): GoalEvent {\n return {\n id: row.event_id,\n goalId: row.goal_id,\n runId: row.run_id ?? undefined,\n kind: row.kind,\n message: row.message,\n data: parseJsonField(row.data_json),\n createdAt: row.created_at,\n };\n}\n\nfunction evidenceFromRow(row: EvidenceRow): GoalEvidence {\n return {\n id: row.evidence_id,\n goalId: row.goal_id,\n runId: row.run_id ?? undefined,\n kind: row.kind,\n title: row.title,\n summary: row.summary ?? undefined,\n uri: row.uri ?? undefined,\n data: parseJsonField(row.data_json),\n createdAt: row.created_at,\n };\n}\n\nfunction clampLimit(n: number | undefined, fallback: number): number {\n return Math.min(500, Math.max(1, Math.floor(n ?? fallback)));\n}\n\nfunction insertGoalEvent(db: ReturnType<typeof getSqliteDatabase>, input: {\n goalId: string;\n runId?: string;\n kind: string;\n message: string;\n data?: unknown;\n createdAt?: number;\n}): GoalEvent {\n const event: GoalEvent = {\n id: randomUUID(),\n goalId: input.goalId,\n runId: input.runId,\n kind: input.kind,\n message: input.message,\n data: input.data,\n createdAt: input.createdAt ?? Date.now(),\n };\n db.prepare(\n `INSERT INTO goal_events (event_id, goal_id, run_id, kind, message, data_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n event.id,\n event.goalId,\n event.runId ?? null,\n event.kind,\n event.message,\n event.data === undefined ? null : JSON.stringify(event.data),\n event.createdAt,\n );\n return event;\n}\n\nexport class GoalStore {\n create(input: CreateGoalInput): Goal {\n const now = Date.now();\n const goal: Goal = {\n id: randomUUID(),\n title: input.title.trim(),\n description: input.description?.trim() || undefined,\n status: 'active',\n agentId: input.agentId,\n priority: input.priority ?? 'normal',\n deadlineAt: input.deadlineAt,\n createdAt: now,\n updatedAt: now,\n activeSessionKey: input.sessionKey,\n judgeModelRef: input.judgeModelRef?.trim() || undefined,\n maxTurns: Math.max(1, Math.min(500, Math.floor(input.maxTurns))),\n turnsUsed: 0,\n uiLocale: input.uiLocale,\n source: input.source ?? 'chat',\n projectId: input.projectId?.trim() || undefined,\n };\n\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `INSERT INTO goals (\n goal_id, title, description, status, agent_id, priority, deadline_at,\n created_at, updated_at, active_session_key, judge_model_ref,\n max_turns, turns_used, ui_locale, source, project_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n goal.id,\n goal.title,\n goal.description ?? null,\n goal.status,\n goal.agentId,\n goal.priority,\n goal.deadlineAt ?? null,\n goal.createdAt,\n goal.updatedAt,\n goal.activeSessionKey ?? null,\n goal.judgeModelRef ?? null,\n goal.maxTurns,\n goal.turnsUsed,\n goal.uiLocale ?? null,\n goal.source,\n goal.projectId ?? null,\n );\n if (goal.activeSessionKey) {\n db.prepare(\n `INSERT OR REPLACE INTO goal_session_links (goal_id, session_key, linked_at)\n VALUES (?, ?, ?)`,\n ).run(goal.id, goal.activeSessionKey, now);\n }\n insertGoalEvent(db, { goalId: goal.id, kind: 'created', message: 'Goal created', createdAt: now });\n });\n\n return goal;\n }\n\n get(goalId: string): Goal | null {\n const row = getSqliteDatabase()\n .prepare(`SELECT * FROM goals WHERE goal_id = ?`)\n .get(goalId) as GoalRow | undefined;\n return row ? goalFromRow(row) : null;\n }\n\n setContextMessage(input: {\n goalId: string;\n text: string;\n attachments?: GoalContextAttachment[];\n }): GoalContextMessage {\n return runSqliteWriteTransaction((db) => {\n const now = Date.now();\n const existing = db\n .prepare(`SELECT created_at FROM goal_context_messages WHERE goal_id = ?`)\n .get(input.goalId) as { created_at: number } | undefined;\n db.prepare(\n `INSERT INTO goal_context_messages (goal_id, text, attachments_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(goal_id) DO UPDATE SET\n text = excluded.text,\n attachments_json = excluded.attachments_json,\n updated_at = excluded.updated_at`,\n ).run(\n input.goalId,\n input.text.trim(),\n JSON.stringify(input.attachments ?? []),\n existing?.created_at ?? now,\n now,\n );\n insertGoalEvent(db, {\n goalId: input.goalId,\n kind: 'context_updated',\n message: input.text.trim() || `${input.attachments?.length ?? 0} attachment(s)`,\n data: { attachmentCount: input.attachments?.length ?? 0 },\n createdAt: now,\n });\n const row = db\n .prepare(`SELECT * FROM goal_context_messages WHERE goal_id = ?`)\n .get(input.goalId) as GoalContextRow;\n return goalContextFromRow(row);\n });\n }\n\n getContextMessage(goalId: string): GoalContextMessage | null {\n const row = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_context_messages WHERE goal_id = ?`)\n .get(goalId) as GoalContextRow | undefined;\n return row ? goalContextFromRow(row) : null;\n }\n\n getActiveForSession(sessionKey: string): Goal | null {\n const row = getSqliteDatabase()\n .prepare(\n `SELECT * FROM goals\n WHERE active_session_key = ?\n AND status IN ('active', 'paused', 'blocked', 'needs_input', 'done')\n ORDER BY updated_at DESC\n LIMIT 1`,\n )\n .get(sessionKey) as GoalRow | undefined;\n return row ? goalFromRow(row) : null;\n }\n\n list(query: GoalListQuery = {}): Goal[] {\n const conditions: string[] = [];\n const params: Array<string | number> = [];\n if (query.status) {\n const statuses = Array.isArray(query.status) ? query.status : [query.status];\n conditions.push(`status IN (${statuses.map(() => '?').join(', ')})`);\n params.push(...statuses);\n }\n if (query.agentId) {\n conditions.push(`agent_id = ?`);\n params.push(query.agentId);\n }\n if (query.sessionKey) {\n conditions.push(`goal_id IN (SELECT goal_id FROM goal_session_links WHERE session_key = ?)`);\n params.push(query.sessionKey);\n }\n if (query.projectId) {\n conditions.push(`project_id = ?`);\n params.push(query.projectId);\n }\n const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';\n const limit = clampLimit(query.limit, 50);\n const offset = Math.max(0, Math.floor(query.offset ?? 0));\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goals ${where} ORDER BY updated_at DESC LIMIT ? OFFSET ?`)\n .all(...params, limit, offset) as GoalRow[];\n return rows.map(goalFromRow);\n }\n\n update(goalId: string, patch: Partial<Pick<\n Goal,\n | 'title'\n | 'description'\n | 'status'\n | 'priority'\n | 'deadlineAt'\n | 'completedAt'\n | 'archivedAt'\n | 'activeSessionKey'\n | 'currentRunId'\n | 'nextAction'\n | 'blockedReason'\n | 'judgeModelRef'\n | 'maxTurns'\n | 'turnsUsed'\n | 'uiLocale'\n | 'projectId'\n >>): Goal | null {\n const before = this.get(goalId);\n if (!before) return null;\n const next = { ...before, ...patch, updatedAt: Date.now() };\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `UPDATE goals SET\n title = ?, description = ?, status = ?, priority = ?, deadline_at = ?,\n updated_at = ?, completed_at = ?, archived_at = ?, active_session_key = ?,\n current_run_id = ?, next_action = ?, blocked_reason = ?, judge_model_ref = ?,\n max_turns = ?, turns_used = ?, ui_locale = ?, project_id = ?\n WHERE goal_id = ?`,\n ).run(\n next.title,\n next.description ?? null,\n next.status,\n next.priority,\n next.deadlineAt ?? null,\n next.updatedAt,\n next.completedAt ?? null,\n next.archivedAt ?? null,\n next.activeSessionKey ?? null,\n next.currentRunId ?? null,\n next.nextAction ?? null,\n next.blockedReason ?? null,\n next.judgeModelRef ?? null,\n next.maxTurns,\n next.turnsUsed,\n next.uiLocale ?? null,\n next.projectId ?? null,\n goalId,\n );\n if (next.activeSessionKey) {\n db.prepare(\n `INSERT OR REPLACE INTO goal_session_links (goal_id, session_key, linked_at)\n VALUES (?, ?, ?)`,\n ).run(goalId, next.activeSessionKey, next.updatedAt);\n }\n });\n return this.get(goalId);\n }\n\n listChecklist(goalId: string): GoalChecklistItem[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_checklist_items WHERE goal_id = ? ORDER BY sort_order ASC, added_at ASC`)\n .all(goalId) as ChecklistRow[];\n return rows.map(checklistFromRow);\n }\n\n addChecklistItem(input: {\n goalId: string;\n text: string;\n addedBy: GoalChecklistAddedBy;\n status?: GoalChecklistStatus;\n }): GoalChecklistItem {\n return runSqliteWriteTransaction((db) => {\n const maxRow = db\n .prepare(`SELECT COALESCE(MAX(sort_order), 0) AS max_sort FROM goal_checklist_items WHERE goal_id = ?`)\n .get(input.goalId) as { max_sort: number };\n const now = Date.now();\n const item: GoalChecklistItem = {\n id: randomUUID(),\n goalId: input.goalId,\n text: input.text.trim(),\n status: input.status ?? 'pending',\n addedBy: input.addedBy,\n addedAt: now,\n sortOrder: maxRow.max_sort + 1,\n };\n db.prepare(\n `INSERT INTO goal_checklist_items (\n item_id, goal_id, text, status, added_by, added_at, sort_order\n ) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n ).run(item.id, item.goalId, item.text, item.status, item.addedBy, item.addedAt, item.sortOrder);\n insertGoalEvent(db, {\n goalId: input.goalId,\n kind: 'checklist_added',\n message: item.text,\n data: { itemId: item.id, addedBy: item.addedBy },\n createdAt: now,\n });\n return item;\n });\n }\n\n updateChecklistItem(\n itemId: string,\n patch: Partial<Pick<GoalChecklistItem, 'text' | 'status' | 'evidenceSummary'>>,\n ): GoalChecklistItem | null {\n return runSqliteWriteTransaction((db) => {\n const row = db\n .prepare(`SELECT * FROM goal_checklist_items WHERE item_id = ?`)\n .get(itemId) as ChecklistRow | undefined;\n if (!row) return null;\n const before = checklistFromRow(row);\n const status = patch.status ?? before.status;\n const completedAt =\n status === 'completed' || status === 'impossible'\n ? (before.completedAt ?? Date.now())\n : null;\n db.prepare(\n `UPDATE goal_checklist_items SET text = ?, status = ?, completed_at = ?, evidence_summary = ?\n WHERE item_id = ?`,\n ).run(\n patch.text?.trim() || before.text,\n status,\n completedAt,\n patch.evidenceSummary ?? before.evidenceSummary ?? null,\n itemId,\n );\n insertGoalEvent(db, {\n goalId: before.goalId,\n kind: 'checklist_updated',\n message: patch.text?.trim() || before.text,\n data: { itemId, status },\n });\n const next = db\n .prepare(`SELECT * FROM goal_checklist_items WHERE item_id = ?`)\n .get(itemId) as ChecklistRow;\n return checklistFromRow(next);\n });\n }\n\n removeChecklistItem(itemId: string): boolean {\n return runSqliteWriteTransaction((db) => {\n const row = db\n .prepare(`SELECT goal_id, text FROM goal_checklist_items WHERE item_id = ?`)\n .get(itemId) as { goal_id: string; text: string } | undefined;\n if (!row) return false;\n db.prepare(`DELETE FROM goal_checklist_items WHERE item_id = ?`).run(itemId);\n insertGoalEvent(db, {\n goalId: row.goal_id,\n kind: 'checklist_removed',\n message: row.text,\n data: { itemId },\n });\n return true;\n });\n }\n\n clearChecklist(goalId: string): void {\n runSqliteWriteTransaction((db) => {\n db.prepare(`DELETE FROM goal_checklist_items WHERE goal_id = ?`).run(goalId);\n insertGoalEvent(db, { goalId, kind: 'checklist_cleared', message: 'Checklist cleared' });\n });\n }\n\n replaceChecklist(goalId: string, items: Array<{\n text: string;\n status: GoalChecklistStatus;\n addedBy: GoalChecklistAddedBy;\n addedAt?: number;\n completedAt?: number;\n evidenceSummary?: string;\n }>): GoalChecklistItem[] {\n return runSqliteWriteTransaction((db) => {\n db.prepare(`DELETE FROM goal_checklist_items WHERE goal_id = ?`).run(goalId);\n const now = Date.now();\n const next: GoalChecklistItem[] = [];\n for (let i = 0; i < items.length; i++) {\n const raw = items[i]!;\n const item: GoalChecklistItem = {\n id: randomUUID(),\n goalId,\n text: raw.text.trim(),\n status: raw.status,\n addedBy: raw.addedBy,\n addedAt: raw.addedAt ?? now,\n completedAt: raw.completedAt,\n evidenceSummary: raw.evidenceSummary,\n sortOrder: i + 1,\n };\n if (!item.text) continue;\n db.prepare(\n `INSERT INTO goal_checklist_items (\n item_id, goal_id, text, status, added_by, added_at, completed_at, evidence_summary, sort_order\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n item.id,\n item.goalId,\n item.text,\n item.status,\n item.addedBy,\n item.addedAt,\n item.completedAt ?? null,\n item.evidenceSummary ?? null,\n item.sortOrder,\n );\n next.push(item);\n }\n insertGoalEvent(db, {\n goalId,\n kind: 'checklist_replaced',\n message: `Checklist replaced (${next.length} items)`,\n });\n return next;\n });\n }\n\n appendRun(run: Omit<GoalRun, 'id' | 'startedAt'> & { id?: string; startedAt?: number }): GoalRun {\n const record: GoalRun = {\n id: run.id ?? randomUUID(),\n goalId: run.goalId,\n sessionKey: run.sessionKey,\n source: run.source,\n status: run.status,\n startedAt: run.startedAt ?? Date.now(),\n finishedAt: run.finishedAt,\n verdict: run.verdict,\n reason: run.reason,\n nextAction: run.nextAction,\n assistantPreview: run.assistantPreview,\n checklistProgress: run.checklistProgress,\n };\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `INSERT INTO goal_runs (\n run_id, goal_id, session_key, source, status, started_at, finished_at,\n verdict, reason, next_action, assistant_preview, checklist_done, checklist_total,\n confidence, missing_evidence_json, user_question, completed_checklist_item_ids_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n record.id,\n record.goalId,\n record.sessionKey,\n record.source,\n record.status,\n record.startedAt,\n record.finishedAt ?? null,\n record.verdict ?? null,\n record.reason ?? null,\n record.nextAction ?? null,\n record.assistantPreview ?? null,\n record.checklistProgress?.done ?? null,\n record.checklistProgress?.total ?? null,\n record.confidence ?? null,\n record.missingEvidence ? JSON.stringify(record.missingEvidence) : null,\n record.userQuestion ?? null,\n record.completedChecklistItemIds ? JSON.stringify(record.completedChecklistItemIds) : null,\n );\n db.prepare(`UPDATE goals SET current_run_id = ?, updated_at = ? WHERE goal_id = ?`).run(\n record.id,\n record.finishedAt ?? record.startedAt,\n record.goalId,\n );\n insertGoalEvent(db, {\n goalId: record.goalId,\n runId: record.id,\n kind: 'run_recorded',\n message: record.reason ?? record.status,\n data: {\n verdict: record.verdict,\n status: record.status,\n confidence: record.confidence,\n missingEvidence: record.missingEvidence,\n userQuestion: record.userQuestion,\n completedChecklistItemIds: record.completedChecklistItemIds,\n },\n createdAt: record.finishedAt ?? record.startedAt,\n });\n });\n return record;\n }\n\n listRuns(goalId: string, limit?: number): GoalRun[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_runs WHERE goal_id = ? ORDER BY started_at DESC LIMIT ?`)\n .all(goalId, clampLimit(limit, 50)) as GoalRunRow[];\n return rows.map(runFromRow);\n }\n\n listRunsForSession(sessionKey: string, limit?: number): GoalRun[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_runs WHERE session_key = ? ORDER BY started_at DESC LIMIT ?`)\n .all(sessionKey, clampLimit(limit, 50)) as GoalRunRow[];\n return rows.map(runFromRow);\n }\n\n listEvents(goalId: string, limit?: number): GoalEvent[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_events WHERE goal_id = ? ORDER BY created_at DESC LIMIT ?`)\n .all(goalId, clampLimit(limit, 100)) as EventRow[];\n return rows.map(eventFromRow);\n }\n\n addEvidence(input: Omit<GoalEvidence, 'id' | 'createdAt'> & { id?: string; createdAt?: number }): GoalEvidence {\n const evidence: GoalEvidence = {\n id: input.id ?? randomUUID(),\n goalId: input.goalId,\n runId: input.runId,\n kind: input.kind,\n title: input.title,\n summary: input.summary,\n uri: input.uri,\n data: input.data,\n createdAt: input.createdAt ?? Date.now(),\n };\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `INSERT INTO goal_evidence (\n evidence_id, goal_id, run_id, kind, title, summary, uri, data_json, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n evidence.id,\n evidence.goalId,\n evidence.runId ?? null,\n evidence.kind,\n evidence.title,\n evidence.summary ?? null,\n evidence.uri ?? null,\n evidence.data === undefined ? null : JSON.stringify(evidence.data),\n evidence.createdAt,\n );\n insertGoalEvent(db, {\n goalId: evidence.goalId,\n runId: evidence.runId,\n kind: 'evidence_added',\n message: evidence.title,\n data: { evidenceId: evidence.id, kind: evidence.kind },\n createdAt: evidence.createdAt,\n });\n });\n return evidence;\n }\n\n listEvidence(goalId: string, limit?: number): GoalEvidence[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_evidence WHERE goal_id = ? ORDER BY created_at DESC LIMIT ?`)\n .all(goalId, clampLimit(limit, 100)) as EvidenceRow[];\n return rows.map(evidenceFromRow);\n }\n}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SAAS,OACT,SAAS,WAAW,MACpB,SAAS,OAAO,MAChB,SAAS,SAAS,KAAA,IAAY,OAAO,KAAK,UAAU,SAAS,KAAK,EAClE,SAAS,UACV;AACD,mBAAgB,IAAI;IAClB,QAAQ,SAAS;IACjB,OAAO,SAAS;IAChB,MAAM;IACN,SAAS,SAAS;IAClB,MAAM;KAAE,YAAY,SAAS;KAAI,MAAM,SAAS;KAAM;IACtD,WAAW,SAAS;IACrB,CAAC;IACF;AACF,SAAO;;CAGT,aAAa,QAAgB,OAAgC;AAI3D,SAHa,mBAAmB,CAC7B,QAAQ,iFAAiF,CACzF,IAAI,QAAQ,WAAW,OAAO,IAAI,CAC1B,CAAC,IAAI,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"goal-store.js","names":[],"sources":["../../../src/goals/goal-store.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { getSqliteDatabase, runSqliteWriteTransaction } from '../storage/sqlite/transaction.js';\nimport type {\n CreateGoalInput,\n Goal,\n GoalChecklistAddedBy,\n GoalChecklistItem,\n GoalChecklistStatus,\n GoalContextAttachment,\n GoalContextMessage,\n GoalEvent,\n GoalEvidence,\n GoalListQuery,\n GoalPriority,\n GoalRun,\n GoalRunStatus,\n GoalRunVerdict,\n GoalSource,\n GoalStatus,\n} from './types.js';\n\ntype GoalRow = {\n goal_id: string;\n title: string;\n description: string | null;\n status: string;\n agent_id: string;\n priority: string;\n deadline_at: number | null;\n created_at: number;\n updated_at: number;\n completed_at: number | null;\n archived_at: number | null;\n active_session_key: string | null;\n current_run_id: string | null;\n next_action: string | null;\n blocked_reason: string | null;\n judge_model_ref: string | null;\n max_turns: number;\n turns_used: number;\n ui_locale: string | null;\n source: string;\n project_id: string | null;\n};\n\ntype ChecklistRow = {\n item_id: string;\n goal_id: string;\n text: string;\n status: string;\n added_by: string;\n added_at: number;\n completed_at: number | null;\n evidence_summary: string | null;\n sort_order: number;\n};\n\ntype GoalRunRow = {\n run_id: string;\n goal_id: string;\n session_key: string;\n source: string;\n status: string;\n started_at: number;\n finished_at: number | null;\n verdict: string | null;\n reason: string | null;\n next_action: string | null;\n assistant_preview: string | null;\n checklist_done: number | null;\n checklist_total: number | null;\n confidence: number | null;\n missing_evidence_json: string | null;\n user_question: string | null;\n completed_checklist_item_ids_json: string | null;\n};\n\ntype EventRow = {\n event_id: string;\n goal_id: string;\n run_id: string | null;\n kind: string;\n message: string;\n data_json: string | null;\n created_at: number;\n};\n\ntype EvidenceRow = {\n evidence_id: string;\n goal_id: string;\n run_id: string | null;\n kind: GoalEvidence['kind'];\n title: string;\n summary: string | null;\n uri: string | null;\n data_json: string | null;\n created_at: number;\n};\n\ntype GoalContextRow = {\n goal_id: string;\n text: string;\n attachments_json: string;\n created_at: number;\n updated_at: number;\n};\n\nfunction goalFromRow(row: GoalRow): Goal {\n return {\n id: row.goal_id,\n title: row.title,\n description: row.description ?? undefined,\n status: row.status as GoalStatus,\n agentId: row.agent_id,\n priority: row.priority as GoalPriority,\n deadlineAt: row.deadline_at ?? undefined,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n completedAt: row.completed_at ?? undefined,\n archivedAt: row.archived_at ?? undefined,\n activeSessionKey: row.active_session_key ?? undefined,\n currentRunId: row.current_run_id ?? undefined,\n nextAction: row.next_action ?? undefined,\n blockedReason: row.blocked_reason ?? undefined,\n judgeModelRef: row.judge_model_ref ?? undefined,\n maxTurns: row.max_turns,\n turnsUsed: row.turns_used,\n uiLocale: row.ui_locale === 'en' || row.ui_locale === 'zh' ? row.ui_locale : undefined,\n source: row.source as GoalSource,\n projectId: row.project_id ?? undefined,\n };\n}\n\nfunction checklistFromRow(row: ChecklistRow): GoalChecklistItem {\n return {\n id: row.item_id,\n goalId: row.goal_id,\n text: row.text,\n status: row.status as GoalChecklistStatus,\n addedBy: row.added_by as GoalChecklistAddedBy,\n addedAt: row.added_at,\n completedAt: row.completed_at ?? undefined,\n evidenceSummary: row.evidence_summary ?? undefined,\n sortOrder: row.sort_order,\n };\n}\n\nfunction runFromRow(row: GoalRunRow): GoalRun {\n return {\n id: row.run_id,\n goalId: row.goal_id,\n sessionKey: row.session_key,\n source: row.source as GoalSource,\n status: row.status as GoalRunStatus,\n startedAt: row.started_at,\n finishedAt: row.finished_at ?? undefined,\n verdict: row.verdict ? (row.verdict as GoalRunVerdict) : undefined,\n reason: row.reason ?? undefined,\n nextAction: row.next_action ?? undefined,\n assistantPreview: row.assistant_preview ?? undefined,\n checklistProgress:\n row.checklist_done != null && row.checklist_total != null\n ? { done: row.checklist_done, total: row.checklist_total }\n : undefined,\n confidence: row.confidence ?? undefined,\n missingEvidence: parseJsonStringArray(row.missing_evidence_json),\n userQuestion: row.user_question ?? undefined,\n completedChecklistItemIds: parseJsonStringArray(row.completed_checklist_item_ids_json),\n };\n}\n\nfunction parseJsonField(raw: string | null): unknown {\n if (!raw) return undefined;\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return undefined;\n }\n}\n\nfunction parseJsonStringArray(raw: string | null): string[] | undefined {\n const value = parseJsonField(raw);\n if (!Array.isArray(value)) return undefined;\n const rows = value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0);\n return rows.length ? rows : undefined;\n}\n\nfunction parseGoalContextAttachments(raw: string): GoalContextAttachment[] {\n const parsed = parseJsonField(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((item): item is GoalContextAttachment => {\n if (!item || typeof item !== 'object') return false;\n const ref = item as Partial<GoalContextAttachment>;\n return (\n typeof ref.id === 'string' &&\n (ref.bucket === 'inbound' || ref.bucket === 'tts' || ref.bucket === 'outbound' || ref.bucket === 'work-item') &&\n typeof ref.type === 'string' &&\n typeof ref.mimeType === 'string' &&\n typeof ref.name === 'string' &&\n typeof ref.size === 'number' &&\n typeof ref.uri === 'string' &&\n typeof ref.path === 'string'\n );\n });\n}\n\nfunction goalContextFromRow(row: GoalContextRow): GoalContextMessage {\n return {\n goalId: row.goal_id,\n text: row.text,\n attachments: parseGoalContextAttachments(row.attachments_json),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction eventFromRow(row: EventRow): GoalEvent {\n return {\n id: row.event_id,\n goalId: row.goal_id,\n runId: row.run_id ?? undefined,\n kind: row.kind,\n message: row.message,\n data: parseJsonField(row.data_json),\n createdAt: row.created_at,\n };\n}\n\nfunction evidenceFromRow(row: EvidenceRow): GoalEvidence {\n return {\n id: row.evidence_id,\n goalId: row.goal_id,\n runId: row.run_id ?? undefined,\n kind: row.kind,\n title: row.title,\n summary: row.summary ?? undefined,\n uri: row.uri ?? undefined,\n data: parseJsonField(row.data_json),\n createdAt: row.created_at,\n };\n}\n\nfunction clampLimit(n: number | undefined, fallback: number): number {\n return Math.min(500, Math.max(1, Math.floor(n ?? fallback)));\n}\n\nfunction insertGoalEvent(db: ReturnType<typeof getSqliteDatabase>, input: {\n goalId: string;\n runId?: string;\n kind: string;\n message: string;\n data?: unknown;\n createdAt?: number;\n}): GoalEvent {\n const event: GoalEvent = {\n id: randomUUID(),\n goalId: input.goalId,\n runId: input.runId,\n kind: input.kind,\n message: input.message,\n data: input.data,\n createdAt: input.createdAt ?? Date.now(),\n };\n db.prepare(\n `INSERT INTO goal_events (event_id, goal_id, run_id, kind, message, data_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n event.id,\n event.goalId,\n event.runId ?? null,\n event.kind,\n event.message,\n event.data === undefined ? null : JSON.stringify(event.data),\n event.createdAt,\n );\n return event;\n}\n\nexport class GoalStore {\n create(input: CreateGoalInput): Goal {\n const now = Date.now();\n const goal: Goal = {\n id: randomUUID(),\n title: input.title.trim(),\n description: input.description?.trim() || undefined,\n status: 'active',\n agentId: input.agentId,\n priority: input.priority ?? 'normal',\n deadlineAt: input.deadlineAt,\n createdAt: now,\n updatedAt: now,\n activeSessionKey: input.sessionKey,\n judgeModelRef: input.judgeModelRef?.trim() || undefined,\n maxTurns: Math.max(1, Math.min(500, Math.floor(input.maxTurns))),\n turnsUsed: 0,\n uiLocale: input.uiLocale,\n source: input.source ?? 'chat',\n projectId: input.projectId?.trim() || undefined,\n };\n\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `INSERT INTO goals (\n goal_id, title, description, status, agent_id, priority, deadline_at,\n created_at, updated_at, active_session_key, judge_model_ref,\n max_turns, turns_used, ui_locale, source, project_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n goal.id,\n goal.title,\n goal.description ?? null,\n goal.status,\n goal.agentId,\n goal.priority,\n goal.deadlineAt ?? null,\n goal.createdAt,\n goal.updatedAt,\n goal.activeSessionKey ?? null,\n goal.judgeModelRef ?? null,\n goal.maxTurns,\n goal.turnsUsed,\n goal.uiLocale ?? null,\n goal.source,\n goal.projectId ?? null,\n );\n if (goal.activeSessionKey) {\n db.prepare(\n `INSERT OR REPLACE INTO goal_session_links (goal_id, session_key, linked_at)\n VALUES (?, ?, ?)`,\n ).run(goal.id, goal.activeSessionKey, now);\n }\n insertGoalEvent(db, { goalId: goal.id, kind: 'created', message: 'Goal created', createdAt: now });\n });\n\n return goal;\n }\n\n get(goalId: string): Goal | null {\n const row = getSqliteDatabase()\n .prepare(`SELECT * FROM goals WHERE goal_id = ?`)\n .get(goalId) as GoalRow | undefined;\n return row ? goalFromRow(row) : null;\n }\n\n setContextMessage(input: {\n goalId: string;\n text: string;\n attachments?: GoalContextAttachment[];\n }): GoalContextMessage {\n return runSqliteWriteTransaction((db) => {\n const now = Date.now();\n const existing = db\n .prepare(`SELECT created_at FROM goal_context_messages WHERE goal_id = ?`)\n .get(input.goalId) as { created_at: number } | undefined;\n db.prepare(\n `INSERT INTO goal_context_messages (goal_id, text, attachments_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(goal_id) DO UPDATE SET\n text = excluded.text,\n attachments_json = excluded.attachments_json,\n updated_at = excluded.updated_at`,\n ).run(\n input.goalId,\n input.text.trim(),\n JSON.stringify(input.attachments ?? []),\n existing?.created_at ?? now,\n now,\n );\n insertGoalEvent(db, {\n goalId: input.goalId,\n kind: 'context_updated',\n message: input.text.trim() || `${input.attachments?.length ?? 0} attachment(s)`,\n data: { attachmentCount: input.attachments?.length ?? 0 },\n createdAt: now,\n });\n const row = db\n .prepare(`SELECT * FROM goal_context_messages WHERE goal_id = ?`)\n .get(input.goalId) as GoalContextRow;\n return goalContextFromRow(row);\n });\n }\n\n getContextMessage(goalId: string): GoalContextMessage | null {\n const row = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_context_messages WHERE goal_id = ?`)\n .get(goalId) as GoalContextRow | undefined;\n return row ? goalContextFromRow(row) : null;\n }\n\n getActiveForSession(sessionKey: string): Goal | null {\n const row = getSqliteDatabase()\n .prepare(\n `SELECT * FROM goals\n WHERE active_session_key = ?\n AND status IN ('active', 'paused', 'blocked', 'needs_input', 'done')\n ORDER BY updated_at DESC\n LIMIT 1`,\n )\n .get(sessionKey) as GoalRow | undefined;\n return row ? goalFromRow(row) : null;\n }\n\n list(query: GoalListQuery = {}): Goal[] {\n const conditions: string[] = [];\n const params: Array<string | number> = [];\n if (query.status) {\n const statuses = Array.isArray(query.status) ? query.status : [query.status];\n conditions.push(`status IN (${statuses.map(() => '?').join(', ')})`);\n params.push(...statuses);\n }\n if (query.agentId) {\n conditions.push(`agent_id = ?`);\n params.push(query.agentId);\n }\n if (query.sessionKey) {\n conditions.push(`goal_id IN (SELECT goal_id FROM goal_session_links WHERE session_key = ?)`);\n params.push(query.sessionKey);\n }\n if (query.projectId) {\n conditions.push(`project_id = ?`);\n params.push(query.projectId);\n }\n const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';\n const limit = clampLimit(query.limit, 50);\n const offset = Math.max(0, Math.floor(query.offset ?? 0));\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goals ${where} ORDER BY updated_at DESC LIMIT ? OFFSET ?`)\n .all(...params, limit, offset) as GoalRow[];\n return rows.map(goalFromRow);\n }\n\n update(goalId: string, patch: Partial<Pick<\n Goal,\n | 'title'\n | 'description'\n | 'status'\n | 'priority'\n | 'deadlineAt'\n | 'completedAt'\n | 'archivedAt'\n | 'activeSessionKey'\n | 'currentRunId'\n | 'nextAction'\n | 'blockedReason'\n | 'judgeModelRef'\n | 'maxTurns'\n | 'turnsUsed'\n | 'uiLocale'\n | 'projectId'\n >>): Goal | null {\n const before = this.get(goalId);\n if (!before) return null;\n const next = { ...before, ...patch, updatedAt: Date.now() };\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `UPDATE goals SET\n title = ?, description = ?, status = ?, priority = ?, deadline_at = ?,\n updated_at = ?, completed_at = ?, archived_at = ?, active_session_key = ?,\n current_run_id = ?, next_action = ?, blocked_reason = ?, judge_model_ref = ?,\n max_turns = ?, turns_used = ?, ui_locale = ?, project_id = ?\n WHERE goal_id = ?`,\n ).run(\n next.title,\n next.description ?? null,\n next.status,\n next.priority,\n next.deadlineAt ?? null,\n next.updatedAt,\n next.completedAt ?? null,\n next.archivedAt ?? null,\n next.activeSessionKey ?? null,\n next.currentRunId ?? null,\n next.nextAction ?? null,\n next.blockedReason ?? null,\n next.judgeModelRef ?? null,\n next.maxTurns,\n next.turnsUsed,\n next.uiLocale ?? null,\n next.projectId ?? null,\n goalId,\n );\n if (next.activeSessionKey) {\n db.prepare(\n `INSERT OR REPLACE INTO goal_session_links (goal_id, session_key, linked_at)\n VALUES (?, ?, ?)`,\n ).run(goalId, next.activeSessionKey, next.updatedAt);\n }\n });\n return this.get(goalId);\n }\n\n listChecklist(goalId: string): GoalChecklistItem[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_checklist_items WHERE goal_id = ? ORDER BY sort_order ASC, added_at ASC`)\n .all(goalId) as ChecklistRow[];\n return rows.map(checklistFromRow);\n }\n\n addChecklistItem(input: {\n goalId: string;\n text: string;\n addedBy: GoalChecklistAddedBy;\n status?: GoalChecklistStatus;\n }): GoalChecklistItem {\n return runSqliteWriteTransaction((db) => {\n const maxRow = db\n .prepare(`SELECT COALESCE(MAX(sort_order), 0) AS max_sort FROM goal_checklist_items WHERE goal_id = ?`)\n .get(input.goalId) as { max_sort: number };\n const now = Date.now();\n const item: GoalChecklistItem = {\n id: randomUUID(),\n goalId: input.goalId,\n text: input.text.trim(),\n status: input.status ?? 'pending',\n addedBy: input.addedBy,\n addedAt: now,\n sortOrder: maxRow.max_sort + 1,\n };\n db.prepare(\n `INSERT INTO goal_checklist_items (\n item_id, goal_id, text, status, added_by, added_at, sort_order\n ) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n ).run(item.id, item.goalId, item.text, item.status, item.addedBy, item.addedAt, item.sortOrder);\n insertGoalEvent(db, {\n goalId: input.goalId,\n kind: 'checklist_added',\n message: item.text,\n data: { itemId: item.id, addedBy: item.addedBy },\n createdAt: now,\n });\n return item;\n });\n }\n\n updateChecklistItem(\n itemId: string,\n patch: Partial<Pick<GoalChecklistItem, 'text' | 'status' | 'evidenceSummary'>>,\n ): GoalChecklistItem | null {\n return runSqliteWriteTransaction((db) => {\n const row = db\n .prepare(`SELECT * FROM goal_checklist_items WHERE item_id = ?`)\n .get(itemId) as ChecklistRow | undefined;\n if (!row) return null;\n const before = checklistFromRow(row);\n const status = patch.status ?? before.status;\n const completedAt =\n status === 'completed' || status === 'impossible'\n ? (before.completedAt ?? Date.now())\n : null;\n db.prepare(\n `UPDATE goal_checklist_items SET text = ?, status = ?, completed_at = ?, evidence_summary = ?\n WHERE item_id = ?`,\n ).run(\n patch.text?.trim() || before.text,\n status,\n completedAt,\n patch.evidenceSummary ?? before.evidenceSummary ?? null,\n itemId,\n );\n insertGoalEvent(db, {\n goalId: before.goalId,\n kind: 'checklist_updated',\n message: patch.text?.trim() || before.text,\n data: { itemId, status },\n });\n const next = db\n .prepare(`SELECT * FROM goal_checklist_items WHERE item_id = ?`)\n .get(itemId) as ChecklistRow;\n return checklistFromRow(next);\n });\n }\n\n removeChecklistItem(itemId: string): boolean {\n return runSqliteWriteTransaction((db) => {\n const row = db\n .prepare(`SELECT goal_id, text FROM goal_checklist_items WHERE item_id = ?`)\n .get(itemId) as { goal_id: string; text: string } | undefined;\n if (!row) return false;\n db.prepare(`DELETE FROM goal_checklist_items WHERE item_id = ?`).run(itemId);\n insertGoalEvent(db, {\n goalId: row.goal_id,\n kind: 'checklist_removed',\n message: row.text,\n data: { itemId },\n });\n return true;\n });\n }\n\n clearChecklist(goalId: string): void {\n runSqliteWriteTransaction((db) => {\n db.prepare(`DELETE FROM goal_checklist_items WHERE goal_id = ?`).run(goalId);\n insertGoalEvent(db, { goalId, kind: 'checklist_cleared', message: 'Checklist cleared' });\n });\n }\n\n replaceChecklist(goalId: string, items: Array<{\n text: string;\n status: GoalChecklistStatus;\n addedBy: GoalChecklistAddedBy;\n addedAt?: number;\n completedAt?: number;\n evidenceSummary?: string;\n }>): GoalChecklistItem[] {\n return runSqliteWriteTransaction((db) => {\n db.prepare(`DELETE FROM goal_checklist_items WHERE goal_id = ?`).run(goalId);\n const now = Date.now();\n const next: GoalChecklistItem[] = [];\n for (let i = 0; i < items.length; i++) {\n const raw = items[i]!;\n const item: GoalChecklistItem = {\n id: randomUUID(),\n goalId,\n text: raw.text.trim(),\n status: raw.status,\n addedBy: raw.addedBy,\n addedAt: raw.addedAt ?? now,\n completedAt: raw.completedAt,\n evidenceSummary: raw.evidenceSummary,\n sortOrder: i + 1,\n };\n if (!item.text) continue;\n db.prepare(\n `INSERT INTO goal_checklist_items (\n item_id, goal_id, text, status, added_by, added_at, completed_at, evidence_summary, sort_order\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n item.id,\n item.goalId,\n item.text,\n item.status,\n item.addedBy,\n item.addedAt,\n item.completedAt ?? null,\n item.evidenceSummary ?? null,\n item.sortOrder,\n );\n next.push(item);\n }\n insertGoalEvent(db, {\n goalId,\n kind: 'checklist_replaced',\n message: `Checklist replaced (${next.length} items)`,\n });\n return next;\n });\n }\n\n appendRun(run: Omit<GoalRun, 'id' | 'startedAt'> & { id?: string; startedAt?: number }): GoalRun {\n const record: GoalRun = {\n id: run.id ?? randomUUID(),\n goalId: run.goalId,\n sessionKey: run.sessionKey,\n source: run.source,\n status: run.status,\n startedAt: run.startedAt ?? Date.now(),\n finishedAt: run.finishedAt,\n verdict: run.verdict,\n reason: run.reason,\n nextAction: run.nextAction,\n assistantPreview: run.assistantPreview,\n checklistProgress: run.checklistProgress,\n };\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `INSERT INTO goal_runs (\n run_id, goal_id, session_key, source, status, started_at, finished_at,\n verdict, reason, next_action, assistant_preview, checklist_done, checklist_total,\n confidence, missing_evidence_json, user_question, completed_checklist_item_ids_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n record.id,\n record.goalId,\n record.sessionKey,\n record.source,\n record.status,\n record.startedAt,\n record.finishedAt ?? null,\n record.verdict ?? null,\n record.reason ?? null,\n record.nextAction ?? null,\n record.assistantPreview ?? null,\n record.checklistProgress?.done ?? null,\n record.checklistProgress?.total ?? null,\n record.confidence ?? null,\n record.missingEvidence ? JSON.stringify(record.missingEvidence) : null,\n record.userQuestion ?? null,\n record.completedChecklistItemIds ? JSON.stringify(record.completedChecklistItemIds) : null,\n );\n db.prepare(`UPDATE goals SET current_run_id = ?, updated_at = ? WHERE goal_id = ?`).run(\n record.id,\n record.finishedAt ?? record.startedAt,\n record.goalId,\n );\n insertGoalEvent(db, {\n goalId: record.goalId,\n runId: record.id,\n kind: 'run_recorded',\n message: record.reason ?? record.status,\n data: {\n verdict: record.verdict,\n status: record.status,\n confidence: record.confidence,\n missingEvidence: record.missingEvidence,\n userQuestion: record.userQuestion,\n completedChecklistItemIds: record.completedChecklistItemIds,\n },\n createdAt: record.finishedAt ?? record.startedAt,\n });\n });\n return record;\n }\n\n listRuns(goalId: string, limit?: number): GoalRun[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_runs WHERE goal_id = ? ORDER BY started_at DESC LIMIT ?`)\n .all(goalId, clampLimit(limit, 50)) as GoalRunRow[];\n return rows.map(runFromRow);\n }\n\n listRunsForSession(sessionKey: string, limit?: number): GoalRun[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_runs WHERE session_key = ? ORDER BY started_at DESC LIMIT ?`)\n .all(sessionKey, clampLimit(limit, 50)) as GoalRunRow[];\n return rows.map(runFromRow);\n }\n\n listEvents(goalId: string, limit?: number): GoalEvent[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_events WHERE goal_id = ? ORDER BY created_at DESC LIMIT ?`)\n .all(goalId, clampLimit(limit, 100)) as EventRow[];\n return rows.map(eventFromRow);\n }\n\n addEvidence(input: Omit<GoalEvidence, 'id' | 'createdAt'> & { id?: string; createdAt?: number }): GoalEvidence {\n const evidence: GoalEvidence = {\n id: input.id ?? randomUUID(),\n goalId: input.goalId,\n runId: input.runId,\n kind: input.kind,\n title: input.title,\n summary: input.summary,\n uri: input.uri,\n data: input.data,\n createdAt: input.createdAt ?? Date.now(),\n };\n runSqliteWriteTransaction((db) => {\n db.prepare(\n `INSERT INTO goal_evidence (\n evidence_id, goal_id, run_id, kind, title, summary, uri, data_json, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n evidence.id,\n evidence.goalId,\n evidence.runId ?? null,\n evidence.kind,\n evidence.title,\n evidence.summary ?? null,\n evidence.uri ?? null,\n evidence.data === undefined ? null : JSON.stringify(evidence.data),\n evidence.createdAt,\n );\n insertGoalEvent(db, {\n goalId: evidence.goalId,\n runId: evidence.runId,\n kind: 'evidence_added',\n message: evidence.title,\n data: { evidenceId: evidence.id, kind: evidence.kind },\n createdAt: evidence.createdAt,\n });\n });\n return evidence;\n }\n\n listEvidence(goalId: string, limit?: number): GoalEvidence[] {\n const rows = getSqliteDatabase()\n .prepare(`SELECT * FROM goal_evidence WHERE goal_id = ? ORDER BY created_at DESC LIMIT ?`)\n .all(goalId, clampLimit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8CAGD,CAAC,IACA,SAAS,IACT,SAAS,QACT,SAAS,SAAS,MAClB,SAAS,MACT,SAAS,OACT,SAAS,WAAW,MACpB,SAAS,OAAO,MAChB,SAAS,SAAS,KAAA,IAAY,OAAO,KAAK,UAAU,SAAS,KAAK,EAClE,SAAS,UACV;AACD,mBAAgB,IAAI;IAClB,QAAQ,SAAS;IACjB,OAAO,SAAS;IAChB,MAAM;IACN,SAAS,SAAS;IAClB,MAAM;KAAE,YAAY,SAAS;KAAI,MAAM,SAAS;KAAM;IACtD,WAAW,SAAS;IACrB,CAAC;IACF;AACF,SAAO;;CAGT,aAAa,QAAgB,OAAgC;AAI3D,SAHa,mBAAmB,CAC7B,QAAQ,iFAAiF,CACzF,IAAI,QAAQ,WAAW,OAAO,IAAI,CAC1B,CAAC,IAAI,gBAAgB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { getAgentDefaultModelRef, init_schema } from "../config/schema.js";
|
|
2
1
|
import { createLogger } from "../utils/logger/index.js";
|
|
3
2
|
import { init_logger } from "../utils/logger.js";
|
|
3
|
+
import { getAgentDefaultModelRef, init_schema } from "../config/schema.js";
|
|
4
4
|
import { GoalService } from "./goal-service.js";
|
|
5
5
|
import { renderWorkflowText } from "../agent/workflow/snapshot.js";
|
|
6
6
|
import { resolveGoalUiLocale } from "../agent/goals/goal-locale.js";
|
package/dist/src/infra/ports.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { PACKAGE_VERSION, init_package_version } from "../package-version.js";
|
|
2
2
|
import { channelToNpmTag } from "./update-channels.js";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
-
import { access, readFile } from "node:fs/promises";
|
|
5
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { access, readFile } from "node:fs/promises";
|
|
6
6
|
//#region src/infra/update-check.ts
|
|
7
7
|
init_package_version();
|
|
8
8
|
const REGISTRY_BASE = "https://registry.npmjs.org";
|
|
@@ -2,8 +2,8 @@ import { createLogger } from "../utils/logger/index.js";
|
|
|
2
2
|
import { init_logger } from "../utils/logger.js";
|
|
3
3
|
import { init_paths, resolveConfigPath } from "../config/paths.js";
|
|
4
4
|
import { init_loader, loadConfig } from "../config/loader.js";
|
|
5
|
-
import { resolveGatewayService } from "../daemon/service.js";
|
|
6
5
|
import { isRestartEnabled } from "../config/commands.flags.js";
|
|
6
|
+
import { resolveGatewayService } from "../daemon/service.js";
|
|
7
7
|
import { authorizeGatewaySigusr1Restart, writeGatewayRestartIntentSync } from "./restart.js";
|
|
8
8
|
import { findVerifiedGatewayListenerPidsOnPortSync, signalVerifiedGatewayPidSync } from "./gateway-processes.js";
|
|
9
9
|
//#region src/infra/update-restart.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ConfigSchema, init_schema } from "../config/schema.js";
|
|
2
1
|
import { createLogger } from "../utils/logger/index.js";
|
|
3
2
|
import { init_logger } from "../utils/logger.js";
|
|
3
|
+
import { ConfigSchema, init_schema } from "../config/schema.js";
|
|
4
4
|
import { listRegisteredMigrations } from "./registry.js";
|
|
5
5
|
import { defaultCapabilityPresetMigration } from "./config/default-capability-preset.js";
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { createLogger } from "../utils/logger/index.js";
|
|
2
2
|
import { init_logger } from "../utils/logger.js";
|
|
3
|
-
import { getDefaultModelSync, init_providers, resolveModel } from "../providers/index.js";
|
|
4
|
-
import { publishAutomationProductEvent } from "../automations/product-events.js";
|
|
5
3
|
import { buildNoteAttachmentRef } from "./attachment-ref.js";
|
|
6
4
|
import { parseNoteMarkdown } from "./note-markdown.js";
|
|
5
|
+
import { changedFieldsFromPatch, emitActivity, previewText, systemActivityActor, systemActivitySource } from "../activity/emitter.js";
|
|
6
|
+
import { getDefaultModelSync, init_providers, resolveModel } from "../providers/index.js";
|
|
7
|
+
import { publishAutomationProductEvent } from "../automations/product-events.js";
|
|
7
8
|
import { NotesStore } from "./store.js";
|
|
8
9
|
import { partitionAttachmentsByReference } from "./note-attachment-sync.js";
|
|
9
10
|
import { buildNoteAgentContextArtifact, getCachedNoteAgentContextArtifact } from "./agent-context.js";
|
|
@@ -163,6 +164,24 @@ var NotesService = class {
|
|
|
163
164
|
localVersion: 1
|
|
164
165
|
};
|
|
165
166
|
await this.store.addNote(note);
|
|
167
|
+
emitActivity({
|
|
168
|
+
type: "note.created",
|
|
169
|
+
primaryObject: {
|
|
170
|
+
kind: "note",
|
|
171
|
+
id: note.id,
|
|
172
|
+
title: note.title
|
|
173
|
+
},
|
|
174
|
+
actor: systemActivityActor(),
|
|
175
|
+
source: systemActivitySource(),
|
|
176
|
+
payload: {
|
|
177
|
+
title: note.title,
|
|
178
|
+
kind: note.kind,
|
|
179
|
+
tags: note.tags,
|
|
180
|
+
contentPreview: previewText(note.markdown),
|
|
181
|
+
contentLength: note.markdown.length
|
|
182
|
+
},
|
|
183
|
+
nowMs: note.createdAt
|
|
184
|
+
});
|
|
166
185
|
log.debug({
|
|
167
186
|
id: note.id,
|
|
168
187
|
kind: note.kind
|
|
@@ -191,6 +210,24 @@ var NotesService = class {
|
|
|
191
210
|
localVersion: 1
|
|
192
211
|
};
|
|
193
212
|
await this.store.addNote(note);
|
|
213
|
+
emitActivity({
|
|
214
|
+
type: "note.created",
|
|
215
|
+
primaryObject: {
|
|
216
|
+
kind: "note",
|
|
217
|
+
id: note.id,
|
|
218
|
+
title: note.title
|
|
219
|
+
},
|
|
220
|
+
actor: systemActivityActor(),
|
|
221
|
+
source: systemActivitySource(),
|
|
222
|
+
payload: {
|
|
223
|
+
title: note.title,
|
|
224
|
+
kind: note.kind,
|
|
225
|
+
tags: note.tags,
|
|
226
|
+
contentPreview: previewText(note.markdown),
|
|
227
|
+
contentLength: note.markdown.length
|
|
228
|
+
},
|
|
229
|
+
nowMs: note.createdAt
|
|
230
|
+
});
|
|
194
231
|
publishNoteEvent("note.created", note);
|
|
195
232
|
log.debug({
|
|
196
233
|
id: note.id,
|
|
@@ -214,10 +251,32 @@ var NotesService = class {
|
|
|
214
251
|
}
|
|
215
252
|
const updatedRaw = await this.store.updateNote(id, normalizedPatch);
|
|
216
253
|
const updated = updatedRaw ? await this.reconcileAttachments(updatedRaw) : null;
|
|
217
|
-
if (updated)
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
254
|
+
if (updated) {
|
|
255
|
+
const changes = changedFieldsFromPatch(patch);
|
|
256
|
+
emitActivity({
|
|
257
|
+
type: existing.status !== updated.status ? "note.status_changed" : "note.updated",
|
|
258
|
+
primaryObject: {
|
|
259
|
+
kind: "note",
|
|
260
|
+
id: updated.id,
|
|
261
|
+
title: updated.title
|
|
262
|
+
},
|
|
263
|
+
actor: systemActivityActor(),
|
|
264
|
+
source: systemActivitySource(),
|
|
265
|
+
payload: {
|
|
266
|
+
changes,
|
|
267
|
+
contentTouched,
|
|
268
|
+
...existing.status !== updated.status ? {
|
|
269
|
+
from: existing.status,
|
|
270
|
+
to: updated.status
|
|
271
|
+
} : {}
|
|
272
|
+
},
|
|
273
|
+
nowMs: updated.updatedAt
|
|
274
|
+
});
|
|
275
|
+
publishNoteEvent("note.updated", updated, {
|
|
276
|
+
contentTouched,
|
|
277
|
+
trigger
|
|
278
|
+
});
|
|
279
|
+
}
|
|
221
280
|
return updated;
|
|
222
281
|
}
|
|
223
282
|
async reconcileAttachments(note) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","names":[],"sources":["../../../src/notes/service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { complete, type UserMessage } from '@earendil-works/pi-ai/compat';\n\nimport { publishAutomationProductEvent } from '../automations/product-events.js';\nimport type { Config } from '../config/schema.js';\nimport { getDefaultModelSync, resolveModel } from '../providers/index.js';\nimport { createLogger } from '../utils/logger.js';\nimport { buildNoteAttachmentRef } from './attachment-ref.js';\nimport { partitionAttachmentsByReference } from './note-attachment-sync.js';\nimport { parseNoteMarkdown } from './note-markdown.js';\nimport { buildNoteAgentContextArtifact, getCachedNoteAgentContextArtifact } from './agent-context.js';\nimport { NotesStore } from './store.js';\nimport type {\n CaptureSource,\n CreateNoteParams,\n Note,\n NoteAiPatch,\n NoteAttachment,\n NoteCatalysisAction,\n NoteCatalysisMeta,\n NoteCatalysisReport,\n NoteIndexEntry,\n NoteKind,\n NoteSnapshot,\n NoteSnapshotEntry,\n NotesListQuery,\n SnapshotTrigger,\n} from './types.js';\n\nconst log = createLogger('NotesService');\nconst MAX_SNAPSHOTS_PER_NOTE = 50;\nconst SNAPSHOT_THROTTLE_MS = 60_000;\n\nfunction inferKind(markdown?: string, hasAttachments?: boolean, attachments?: NoteAttachment[]): NoteKind {\n if (hasAttachments && attachments?.length && attachments.every((item) => item.type === 'audio')) return 'voice';\n if (hasAttachments) return 'media';\n if (!markdown) return 'thought';\n const lower = markdown.toLowerCase();\n if (/^(todo|task|remind|buy|call|email|meet|finish|submit|send)\\b/i.test(lower) || /\\b(明天|今天|记得|别忘|待办|提醒)\\b/.test(markdown)) return 'todo';\n if (/^https?:\\/\\//.test(markdown.trim())) return 'bookmark';\n return 'thought';\n}\n\nfunction deriveDefaultTitle(markdown?: string): string | undefined {\n const normalized = parseNoteMarkdown(markdown ?? '').plainText.trim().replace(/\\s+/g, ' ');\n return normalized ? Array.from(normalized).slice(0, 10).join('') : undefined;\n}\n\nfunction splitMeaningfulLines(markdown?: string): string[] {\n return parseNoteMarkdown(markdown ?? '').plainText.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n}\n\nfunction summarizeIdea(markdown?: string): string {\n const lines = splitMeaningfulLines(markdown);\n return lines.slice(0, 3).join(';').slice(0, 140);\n}\n\nfunction publishNoteEvent(\n type: 'note.created' | 'note.updated',\n note: Note,\n extra?: Record<string, unknown>,\n): void {\n publishAutomationProductEvent({\n type,\n source: 'notes',\n payload: {\n noteId: note.id,\n kind: note.kind,\n status: note.status,\n title: note.title,\n capturedVia: note.capturedVia,\n tagCount: note.tags?.length ?? 0,\n hasAttachments: Boolean(note.attachments?.length),\n ...extra,\n },\n });\n}\n\nfunction inferCatalysisStage(note: Note): NonNullable<NoteCatalysisMeta['stage']> {\n const text = `${note.title ?? ''}\\n${note.markdown}`;\n if (/上线|发布|launch|ship/i.test(text)) return 'shipped';\n if (/验证|访谈|用户|测试|validate/i.test(text)) return 'validating';\n if (/开发|实现|构建|build|mvp/i.test(text)) return 'developing';\n if (/想法|机会|问题|idea|seed/i.test(text)) return 'seed';\n return 'incubating';\n}\n\nfunction buildCatalysisReport(note: Note): NoteCatalysisReport {\n const summary = summarizeIdea(note.markdown || note.title);\n const title = note.title?.trim() || summary.slice(0, 28) || '未命名想法';\n const actions: NoteCatalysisAction[] = [\n { kind: 'research', text: `验证「${title}」的真实需求和目标用户` },\n { kind: 'task', text: `拆解「${title}」的最小可行下一步` },\n { kind: 'chat', text: `继续和 AI 讨论「${title}」的方案` },\n ];\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title,\n valueHypothesis: summary || '这条笔记可能包含一个待澄清的想法。',\n targetUsers: ['待确认的核心用户'],\n keyQuestions: ['用户为什么现在需要它?', '最小可验证版本是什么?', '如何判断它值得继续投入?'],\n mvpPath: ['定义目标用户', '写出最小场景', '完成一次验证'],\n risks: ['需求不够明确', '执行路径过大'],\n nextActions: actions,\n confidence: summary ? 0.58 : 0.35,\n };\n}\n\nfunction normalizeAiCatalysisReport(note: Note, data: Record<string, unknown>): NoteCatalysisReport {\n const fallback = buildCatalysisReport(note);\n const stringArray = (value: unknown, fallbackValue: string[]) => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string').slice(0, 12) : fallbackValue;\n const actions = Array.isArray(data.nextActions)\n ? data.nextActions.map((item): NoteCatalysisAction | null => {\n if (!item || typeof item !== 'object') return null;\n const row = item as { kind?: unknown; text?: unknown };\n const kind = row.kind === 'task' || row.kind === 'workflow' || row.kind === 'research' || row.kind === 'share' || row.kind === 'chat' ? row.kind : 'task';\n return typeof row.text === 'string' && row.text.trim() ? { kind, text: row.text.trim() } : null;\n }).filter((item): item is NoteCatalysisAction => Boolean(item)).slice(0, 12)\n : fallback.nextActions;\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : fallback.title,\n valueHypothesis: typeof data.valueHypothesis === 'string' && data.valueHypothesis.trim() ? data.valueHypothesis.trim() : fallback.valueHypothesis,\n targetUsers: stringArray(data.targetUsers, fallback.targetUsers),\n keyQuestions: stringArray(data.keyQuestions, fallback.keyQuestions),\n mvpPath: stringArray(data.mvpPath, fallback.mvpPath),\n risks: stringArray(data.risks, fallback.risks),\n nextActions: actions,\n confidence: typeof data.confidence === 'number' ? Math.max(0, Math.min(1, data.confidence)) : fallback.confidence,\n };\n}\n\nfunction buildCatalysisPrompt(note: Note): string {\n const title = note.title?.trim() || '未命名笔记';\n const markdown = note.markdown.trim() || '(无正文)';\n return `请把下面的 Markdown 笔记催化成可执行的想法报告,输出 JSON:\\n{\\n \"title\": string,\\n \"valueHypothesis\": string,\\n \"targetUsers\": string[],\\n \"keyQuestions\": string[],\\n \"mvpPath\": string[],\\n \"risks\": string[],\\n \"nextActions\": [{\"text\": string, \"kind\": \"task\"|\"workflow\"|\"research\"|\"share\"|\"chat\"}],\\n \"confidence\": number\\n}\\n\\n标题:${title}\\n\\nMarkdown:\\n${markdown}`;\n}\n\nasync function buildAiCatalysisReport(note: Note, config?: Config): Promise<NoteCatalysisReport> {\n const modelRef = getDefaultModelSync(config);\n if (!modelRef) {\n throw new Error('No global default model configured');\n }\n const resolved = resolveModel(modelRef);\n const messages: UserMessage[] = [{ role: 'user', content: buildCatalysisPrompt(note), timestamp: Date.now() }];\n const response = await complete(resolved, { messages }, { temperature: 0.2 });\n let responseText = '';\n if (Array.isArray(response.content)) {\n for (const part of response.content) {\n if (part && typeof part === 'object' && (part as { type?: string }).type === 'text') {\n responseText += String((part as { text?: string }).text || '');\n }\n }\n }\n const raw = responseText.trim().replace(/^```json\\s*/i, '').replace(/```$/i, '').trim();\n return normalizeAiCatalysisReport(note, JSON.parse(raw) as Record<string, unknown>);\n}\n\nexport class NotesService {\n private lastSnapshotAt = new Map<string, number>();\n\n constructor(private readonly store = new NotesStore()) {}\n\n async initialize(): Promise<void> {\n await this.store.initialize();\n }\n\n async quickCapture(markdown: string, source: CaptureSource): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const note: Note = {\n id,\n title: deriveDefaultTitle(markdown),\n kind: inferKind(markdown),\n status: 'inbox',\n markdown,\n createdAt: now,\n updatedAt: now,\n capturedVia: source,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n log.debug({ id: note.id, kind: note.kind }, 'Quick capture');\n return note;\n }\n\n async createNote(params: CreateNoteParams): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const markdown = params.markdown ?? '';\n const note: Note = {\n id,\n title: params.title ?? deriveDefaultTitle(markdown),\n kind: params.kind ?? inferKind(markdown),\n status: 'inbox',\n markdown,\n attachments: [],\n createdAt: now,\n updatedAt: now,\n capturedVia: params.capturedVia,\n tags: params.tags,\n pinned: params.pinned,\n groupId: params.groupId,\n taskMeta: params.taskMeta,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n publishNoteEvent('note.created', note);\n log.debug({ id: note.id, kind: note.kind }, 'Note created');\n return note;\n }\n\n async getNote(id: string): Promise<Note | null> {\n return this.store.getNote(id);\n }\n\n async updateNote(id: string, patch: Partial<Note>, trigger: SnapshotTrigger = 'edit'): Promise<Note | null> {\n const existing = await this.store.getNote(id);\n if (!existing) return null;\n const contentTouched = patch.markdown !== undefined || patch.title !== undefined;\n if (contentTouched) await this.maybeSaveSnapshot(existing, trigger);\n\n const normalizedPatch: Partial<Note> = { ...patch };\n if (patch.markdown !== undefined) {\n normalizedPatch.kind = patch.kind ?? inferKind(patch.markdown, Boolean(existing.attachments?.length), existing.attachments);\n }\n if (contentTouched || patch.attachments) {\n normalizedPatch.remoteVersion = (existing.remoteVersion ?? 1) + 1;\n normalizedPatch.localVersion = patch.localVersion ?? (existing.localVersion ?? 1) + 1;\n }\n\n const updatedRaw = await this.store.updateNote(id, normalizedPatch);\n const updated = updatedRaw ? await this.reconcileAttachments(updatedRaw) : null;\n if (updated) {\n publishNoteEvent('note.updated', updated, {\n contentTouched,\n trigger,\n });\n }\n return updated;\n }\n\n private async reconcileAttachments(note: Note): Promise<Note> {\n const { kept, removed } = partitionAttachmentsByReference(note);\n if (removed.length === 0) return note;\n for (const attachment of removed) await this.store.deleteAttachmentFile(note.id, attachment.relativePath);\n log.debug({ noteId: note.id, removedIds: removed.map((attachment) => attachment.id) }, 'Pruned orphan note attachments');\n const hasAttachments = kept.length > 0;\n const updated = await this.store.updateNote(note.id, { attachments: kept, kind: inferKind(note.markdown, hasAttachments, kept) });\n return updated ?? { ...note, attachments: kept };\n }\n\n async syncNote(id: string, patch: Partial<Note>, baseRemoteVersion?: number): Promise<{ note: Note | null; conflict: boolean }> {\n const existing = await this.store.getNote(id);\n if (!existing) return { note: null, conflict: false };\n if (baseRemoteVersion !== undefined && existing.remoteVersion !== undefined && baseRemoteVersion < existing.remoteVersion) {\n return { note: existing, conflict: true };\n }\n const updated = await this.updateNote(id, patch, 'sync');\n return { note: updated, conflict: false };\n }\n\n async createAiEditPatch(id: string, instruction: string, markdownOverride?: string): Promise<{ message: string; patch: NoteAiPatch } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const source = markdownOverride ?? note.markdown;\n const parsed = parseNoteMarkdown(source, id);\n const wantsTodos = /待办|todo|task|行动|提醒/i.test(instruction);\n const wantsSummary = /摘要|总结|summary|压缩/i.test(instruction);\n let generated = '';\n if (wantsTodos) {\n const lines = source.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n generated = (lines.length ? lines : [parsed.plainText]).slice(0, 12).map((line) => `- [ ] ${line.replace(/^[-*\\d.\\s\\[\\]x]+/i, '').trim()}`).join('\\n');\n } else if (wantsSummary) {\n generated = `> [!SUMMARY]\\n> ${parsed.plainText.slice(0, 220)}`;\n } else {\n generated = `${source.trimEnd()}\\n\\n## AI 整理\\n\\n${instruction.trim()}`;\n }\n return {\n message: 'AI edit patch generated',\n patch: {\n id: randomUUID(),\n summary: instruction,\n operations: [{ type: 'replaceRange', from: 0, to: source.length, markdown: generated || source }],\n },\n };\n }\n\n async catalyzeNote(id: string, config?: Config): Promise<{ note: Note; report: NoteCatalysisReport } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n let report: NoteCatalysisReport;\n try {\n report = await buildAiCatalysisReport(note, config);\n } catch (err) {\n log.warn({ err, noteId: id }, 'AI note catalysis failed; using local fallback report');\n report = buildCatalysisReport(note);\n }\n const updated = await this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: 'catalyzed',\n stage: inferCatalysisStage(note),\n lastCatalyzedAt: Date.now(),\n confidence: report.confidence,\n report,\n ...note.aiDeep?.catalysis,\n },\n },\n ai: { ...note.ai, intent: note.ai?.intent ?? 'idea', summary: note.ai?.summary ?? report.valueHypothesis },\n status: note.status === 'inbox' ? 'processed' : note.status,\n }, 'ai_edit');\n return updated ? { note: updated, report } : null;\n }\n\n async recordCatalysisFeedback(id: string, feedback: 'helpful' | 'not_helpful' | 'neutral'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return this.updateNote(id, { aiDeep: { ...note.aiDeep, processedAt: Date.now(), catalysis: { status: note.aiDeep?.catalysis?.status ?? 'catalyzed', ...note.aiDeep?.catalysis, feedback } } });\n }\n\n async linkNoteThread(id: string, sessionKey: string): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const existingKeys = note.aiDeep?.catalysis?.linkedSessionKeys ?? [];\n return this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: note.aiDeep?.catalysis?.status ?? 'none',\n ...note.aiDeep?.catalysis,\n sourceSessionKey: note.aiDeep?.catalysis?.sourceSessionKey ?? sessionKey,\n linkedSessionKeys: Array.from(new Set([...existingKeys, sessionKey])),\n },\n },\n }, 'sync');\n }\n\n async listNoteThreads(id: string): Promise<string[] | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return Array.from(new Set([note.aiDeep?.catalysis?.sourceSessionKey, ...(note.aiDeep?.catalysis?.linkedSessionKeys ?? [])].filter((key): key is string => Boolean(key))));\n }\n\n async getAgentContextStatus(id: string, config?: Config, force = false): Promise<{ noteUpdatedAt: number; artifact: import('./agent-context.js').NoteAgentContextArtifact | null; stale: boolean } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const cached = getCachedNoteAgentContextArtifact(id);\n if (!force && cached && cached.noteUpdatedAt === note.updatedAt) {\n return { noteUpdatedAt: note.updatedAt, artifact: cached, stale: false };\n }\n const artifact = await buildNoteAgentContextArtifact({ note, notesService: this, config, force });\n return { noteUpdatedAt: note.updatedAt, artifact, stale: false };\n }\n\n async appendTextToNote(id: string, content: string, heading = 'AI 讨论沉淀'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const trimmed = content.trim();\n if (!trimmed) return note;\n const current = note.markdown.trimEnd();\n const nextMarkdown = `${current}${current ? '\\n\\n' : ''}## ${heading}\\n\\n${trimmed}\\n`;\n return this.updateNote(id, { markdown: nextMarkdown }, 'ai_edit');\n }\n\n async deleteNote(id: string): Promise<boolean> {\n const removed = await this.store.deleteNote(id);\n if (removed) await this.store.deleteAllSnapshots(id);\n return removed;\n }\n\n async listNotes(query: NotesListQuery = {}): Promise<{ items: NoteIndexEntry[]; total: number; limit: number; offset: number; hasMore: boolean }> {\n return this.store.listNotes(query);\n }\n\n async addAttachment(noteId: string, file: { name: string; buffer: Buffer; mimeType: string; duration?: number }): Promise<NoteAttachment | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const { relativePath, size } = await this.store.saveAttachment(noteId, file.name, file.buffer);\n const attachment: NoteAttachment = {\n id: randomUUID(),\n type: file.mimeType.startsWith('image/') ? 'image' : file.mimeType.startsWith('audio/') ? 'audio' : file.mimeType.startsWith('video/') ? 'video' : 'file',\n mimeType: file.mimeType,\n fileName: file.name,\n size,\n relativePath,\n duration: file.duration,\n };\n const attachments = [...(note.attachments || []), attachment];\n const kind = note.kind === 'thought' && attachment.type === 'audio' ? 'voice' : note.kind === 'thought' ? 'media' : note.kind;\n await this.store.updateNote(noteId, { attachments, kind });\n return attachment;\n }\n\n async getAttachmentPath(noteId: string, attachmentId: string): Promise<{ filePath: string; mimeType: string; fileName: string } | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const attachment = note.attachments?.find((a) => a.id === attachmentId);\n if (!attachment) return null;\n return { filePath: this.store.resolveAttachmentPath(noteId, attachment.relativePath), mimeType: attachment.mimeType, fileName: attachment.fileName };\n }\n\n async listNoteHistory(noteId: string): Promise<NoteSnapshotEntry[]> { return this.store.listSnapshots(noteId); }\n async getNoteSnapshot(noteId: string, timestamp: number): Promise<NoteSnapshot | null> { return this.store.getSnapshot(noteId, timestamp); }\n\n async restoreNoteSnapshot(noteId: string, timestamp: number): Promise<Note | null> {\n const snapshot = await this.store.getSnapshot(noteId, timestamp);\n const existing = await this.store.getNote(noteId);\n if (!snapshot || !existing) return null;\n await this.maybeSaveSnapshot(existing, 'restore');\n this.lastSnapshotAt.set(noteId, Date.now());\n await this.store.pruneSnapshots(noteId, MAX_SNAPSHOTS_PER_NOTE);\n return this.store.updateNote(noteId, { title: snapshot.title, markdown: snapshot.markdown, tags: snapshot.tags, kind: snapshot.kind, status: snapshot.status });\n }\n\n async flush(): Promise<void> { await this.store.flush(); }\n async moveToGroup(noteId: string, groupId: string | null): Promise<Note | null> { return this.updateNote(noteId, { groupId: groupId ?? undefined }); }\n\n async createTask(title: string, source: CaptureSource, opts: { dueAt?: number; priority?: 'high' | 'medium' | 'low'; sourceSessionKey?: string; sourceNoteId?: string; groupId?: string } = {}): Promise<Note> {\n return this.createNote({\n title,\n markdown: `- [ ] ${title}`,\n kind: 'task',\n capturedVia: source,\n groupId: opts.groupId,\n taskMeta: { done: false, dueAt: opts.dueAt, priority: opts.priority, sourceSessionKey: opts.sourceSessionKey, sourceNoteId: opts.sourceNoteId },\n });\n }\n\n async toggleTaskDone(noteId: string): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n const done = !note.taskMeta?.done;\n const markdown = note.markdown.replace(/^- \\[[ xX]\\]/m, `- [${done ? 'x' : ' '}]`);\n return this.updateNote(noteId, { markdown, taskMeta: { ...note.taskMeta, done } });\n }\n\n async updateTaskMeta(noteId: string, patch: Partial<import('./types.js').NoteTaskMeta>): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n return this.updateNote(noteId, { taskMeta: { ...note.taskMeta, done: note.taskMeta?.done ?? false, ...patch } });\n }\n\n async recordOpen(noteId: string): Promise<Note | null> {\n return this.updateNote(noteId, { lastOpenedAt: Date.now() } as Partial<Note>);\n }\n\n private async maybeSaveSnapshot(note: Note, trigger: SnapshotTrigger): Promise<void> {\n if (trigger !== 'edit') {\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n return;\n }\n const last = this.lastSnapshotAt.get(note.id) ?? 0;\n if (Date.now() - last < SNAPSHOT_THROTTLE_MS) return;\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n }\n}\n\nexport { buildNoteAttachmentRef };\n"],"mappings":";;;;;;;;;;;;gBAM0E;aACxB;AAuBlD,MAAM,MAAM,aAAa,eAAe;AACxC,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAE7B,SAAS,UAAU,UAAmB,gBAA0B,aAA0C;AACxG,KAAI,kBAAkB,aAAa,UAAU,YAAY,OAAO,SAAS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F,SAAO,KAAK,WAAW,QAAQ;GAAE;GAAU,UAAU;IAAE,GAAG,KAAK;IAAU;IAAM;GAAE,CAAC;;CAGpF,MAAM,eAAe,QAAgB,OAAyE;EAC5G,MAAM,OAAO,MAAM,KAAK,MAAM,QAAQ,OAAO;AAC7C,MAAI,CAAC,QAAQ,KAAK,SAAS,OAAQ,QAAO;AAC1C,SAAO,KAAK,WAAW,QAAQ,EAAE,UAAU;GAAE,GAAG,KAAK;GAAU,MAAM,KAAK,UAAU,QAAQ;GAAO,GAAG;GAAO,EAAE,CAAC;;CAGlH,MAAM,WAAW,QAAsC;AACrD,SAAO,KAAK,WAAW,QAAQ,EAAE,cAAc,KAAK,KAAK,EAAE,CAAkB;;CAG/E,MAAc,kBAAkB,MAAY,SAAyC;AACnF,MAAI,YAAY,QAAQ;AACtB,SAAM,KAAK,MAAM,aAAa,MAAM,QAAQ;AAC5C,QAAK,eAAe,IAAI,KAAK,IAAI,KAAK,KAAK,CAAC;AAC5C,SAAM,KAAK,MAAM,eAAe,KAAK,IAAI,uBAAuB;AAChE;;EAEF,MAAM,OAAO,KAAK,eAAe,IAAI,KAAK,GAAG,IAAI;AACjD,MAAI,KAAK,KAAK,GAAG,OAAO,qBAAsB;AAC9C,QAAM,KAAK,MAAM,aAAa,MAAM,QAAQ;AAC5C,OAAK,eAAe,IAAI,KAAK,IAAI,KAAK,KAAK,CAAC;AAC5C,QAAM,KAAK,MAAM,eAAe,KAAK,IAAI,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"service.js","names":[],"sources":["../../../src/notes/service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { complete, type UserMessage } from '@earendil-works/pi-ai/compat';\n\nimport { changedFieldsFromPatch, emitActivity, previewText, systemActivityActor, systemActivitySource } from '../activity/emitter.js';\nimport { publishAutomationProductEvent } from '../automations/product-events.js';\nimport type { Config } from '../config/schema.js';\nimport { getDefaultModelSync, resolveModel } from '../providers/index.js';\nimport { createLogger } from '../utils/logger.js';\nimport { buildNoteAttachmentRef } from './attachment-ref.js';\nimport { partitionAttachmentsByReference } from './note-attachment-sync.js';\nimport { parseNoteMarkdown } from './note-markdown.js';\nimport { buildNoteAgentContextArtifact, getCachedNoteAgentContextArtifact } from './agent-context.js';\nimport { NotesStore } from './store.js';\nimport type {\n CaptureSource,\n CreateNoteParams,\n Note,\n NoteAiPatch,\n NoteAttachment,\n NoteCatalysisAction,\n NoteCatalysisMeta,\n NoteCatalysisReport,\n NoteIndexEntry,\n NoteKind,\n NoteSnapshot,\n NoteSnapshotEntry,\n NotesListQuery,\n SnapshotTrigger,\n} from './types.js';\n\nconst log = createLogger('NotesService');\nconst MAX_SNAPSHOTS_PER_NOTE = 50;\nconst SNAPSHOT_THROTTLE_MS = 60_000;\n\nfunction inferKind(markdown?: string, hasAttachments?: boolean, attachments?: NoteAttachment[]): NoteKind {\n if (hasAttachments && attachments?.length && attachments.every((item) => item.type === 'audio')) return 'voice';\n if (hasAttachments) return 'media';\n if (!markdown) return 'thought';\n const lower = markdown.toLowerCase();\n if (/^(todo|task|remind|buy|call|email|meet|finish|submit|send)\\b/i.test(lower) || /\\b(明天|今天|记得|别忘|待办|提醒)\\b/.test(markdown)) return 'todo';\n if (/^https?:\\/\\//.test(markdown.trim())) return 'bookmark';\n return 'thought';\n}\n\nfunction deriveDefaultTitle(markdown?: string): string | undefined {\n const normalized = parseNoteMarkdown(markdown ?? '').plainText.trim().replace(/\\s+/g, ' ');\n return normalized ? Array.from(normalized).slice(0, 10).join('') : undefined;\n}\n\nfunction splitMeaningfulLines(markdown?: string): string[] {\n return parseNoteMarkdown(markdown ?? '').plainText.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n}\n\nfunction summarizeIdea(markdown?: string): string {\n const lines = splitMeaningfulLines(markdown);\n return lines.slice(0, 3).join(';').slice(0, 140);\n}\n\nfunction publishNoteEvent(\n type: 'note.created' | 'note.updated',\n note: Note,\n extra?: Record<string, unknown>,\n): void {\n publishAutomationProductEvent({\n type,\n source: 'notes',\n payload: {\n noteId: note.id,\n kind: note.kind,\n status: note.status,\n title: note.title,\n capturedVia: note.capturedVia,\n tagCount: note.tags?.length ?? 0,\n hasAttachments: Boolean(note.attachments?.length),\n ...extra,\n },\n });\n}\n\nfunction inferCatalysisStage(note: Note): NonNullable<NoteCatalysisMeta['stage']> {\n const text = `${note.title ?? ''}\\n${note.markdown}`;\n if (/上线|发布|launch|ship/i.test(text)) return 'shipped';\n if (/验证|访谈|用户|测试|validate/i.test(text)) return 'validating';\n if (/开发|实现|构建|build|mvp/i.test(text)) return 'developing';\n if (/想法|机会|问题|idea|seed/i.test(text)) return 'seed';\n return 'incubating';\n}\n\nfunction buildCatalysisReport(note: Note): NoteCatalysisReport {\n const summary = summarizeIdea(note.markdown || note.title);\n const title = note.title?.trim() || summary.slice(0, 28) || '未命名想法';\n const actions: NoteCatalysisAction[] = [\n { kind: 'research', text: `验证「${title}」的真实需求和目标用户` },\n { kind: 'task', text: `拆解「${title}」的最小可行下一步` },\n { kind: 'chat', text: `继续和 AI 讨论「${title}」的方案` },\n ];\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title,\n valueHypothesis: summary || '这条笔记可能包含一个待澄清的想法。',\n targetUsers: ['待确认的核心用户'],\n keyQuestions: ['用户为什么现在需要它?', '最小可验证版本是什么?', '如何判断它值得继续投入?'],\n mvpPath: ['定义目标用户', '写出最小场景', '完成一次验证'],\n risks: ['需求不够明确', '执行路径过大'],\n nextActions: actions,\n confidence: summary ? 0.58 : 0.35,\n };\n}\n\nfunction normalizeAiCatalysisReport(note: Note, data: Record<string, unknown>): NoteCatalysisReport {\n const fallback = buildCatalysisReport(note);\n const stringArray = (value: unknown, fallbackValue: string[]) => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string').slice(0, 12) : fallbackValue;\n const actions = Array.isArray(data.nextActions)\n ? data.nextActions.map((item): NoteCatalysisAction | null => {\n if (!item || typeof item !== 'object') return null;\n const row = item as { kind?: unknown; text?: unknown };\n const kind = row.kind === 'task' || row.kind === 'workflow' || row.kind === 'research' || row.kind === 'share' || row.kind === 'chat' ? row.kind : 'task';\n return typeof row.text === 'string' && row.text.trim() ? { kind, text: row.text.trim() } : null;\n }).filter((item): item is NoteCatalysisAction => Boolean(item)).slice(0, 12)\n : fallback.nextActions;\n return {\n originalNoteId: note.id,\n generatedAt: Date.now(),\n title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : fallback.title,\n valueHypothesis: typeof data.valueHypothesis === 'string' && data.valueHypothesis.trim() ? data.valueHypothesis.trim() : fallback.valueHypothesis,\n targetUsers: stringArray(data.targetUsers, fallback.targetUsers),\n keyQuestions: stringArray(data.keyQuestions, fallback.keyQuestions),\n mvpPath: stringArray(data.mvpPath, fallback.mvpPath),\n risks: stringArray(data.risks, fallback.risks),\n nextActions: actions,\n confidence: typeof data.confidence === 'number' ? Math.max(0, Math.min(1, data.confidence)) : fallback.confidence,\n };\n}\n\nfunction buildCatalysisPrompt(note: Note): string {\n const title = note.title?.trim() || '未命名笔记';\n const markdown = note.markdown.trim() || '(无正文)';\n return `请把下面的 Markdown 笔记催化成可执行的想法报告,输出 JSON:\\n{\\n \"title\": string,\\n \"valueHypothesis\": string,\\n \"targetUsers\": string[],\\n \"keyQuestions\": string[],\\n \"mvpPath\": string[],\\n \"risks\": string[],\\n \"nextActions\": [{\"text\": string, \"kind\": \"task\"|\"workflow\"|\"research\"|\"share\"|\"chat\"}],\\n \"confidence\": number\\n}\\n\\n标题:${title}\\n\\nMarkdown:\\n${markdown}`;\n}\n\nasync function buildAiCatalysisReport(note: Note, config?: Config): Promise<NoteCatalysisReport> {\n const modelRef = getDefaultModelSync(config);\n if (!modelRef) {\n throw new Error('No global default model configured');\n }\n const resolved = resolveModel(modelRef);\n const messages: UserMessage[] = [{ role: 'user', content: buildCatalysisPrompt(note), timestamp: Date.now() }];\n const response = await complete(resolved, { messages }, { temperature: 0.2 });\n let responseText = '';\n if (Array.isArray(response.content)) {\n for (const part of response.content) {\n if (part && typeof part === 'object' && (part as { type?: string }).type === 'text') {\n responseText += String((part as { text?: string }).text || '');\n }\n }\n }\n const raw = responseText.trim().replace(/^```json\\s*/i, '').replace(/```$/i, '').trim();\n return normalizeAiCatalysisReport(note, JSON.parse(raw) as Record<string, unknown>);\n}\n\nexport class NotesService {\n private lastSnapshotAt = new Map<string, number>();\n\n constructor(private readonly store = new NotesStore()) {}\n\n async initialize(): Promise<void> {\n await this.store.initialize();\n }\n\n async quickCapture(markdown: string, source: CaptureSource): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const note: Note = {\n id,\n title: deriveDefaultTitle(markdown),\n kind: inferKind(markdown),\n status: 'inbox',\n markdown,\n createdAt: now,\n updatedAt: now,\n capturedVia: source,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n emitActivity({\n type: 'note.created',\n primaryObject: { kind: 'note', id: note.id, title: note.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n title: note.title,\n kind: note.kind,\n tags: note.tags,\n contentPreview: previewText(note.markdown),\n contentLength: note.markdown.length,\n },\n nowMs: note.createdAt,\n });\n log.debug({ id: note.id, kind: note.kind }, 'Quick capture');\n return note;\n }\n\n async createNote(params: CreateNoteParams): Promise<Note> {\n const id = randomUUID();\n const now = Date.now();\n const markdown = params.markdown ?? '';\n const note: Note = {\n id,\n title: params.title ?? deriveDefaultTitle(markdown),\n kind: params.kind ?? inferKind(markdown),\n status: 'inbox',\n markdown,\n attachments: [],\n createdAt: now,\n updatedAt: now,\n capturedVia: params.capturedVia,\n tags: params.tags,\n pinned: params.pinned,\n groupId: params.groupId,\n taskMeta: params.taskMeta,\n remoteVersion: 1,\n localVersion: 1,\n };\n await this.store.addNote(note);\n emitActivity({\n type: 'note.created',\n primaryObject: { kind: 'note', id: note.id, title: note.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n title: note.title,\n kind: note.kind,\n tags: note.tags,\n contentPreview: previewText(note.markdown),\n contentLength: note.markdown.length,\n },\n nowMs: note.createdAt,\n });\n publishNoteEvent('note.created', note);\n log.debug({ id: note.id, kind: note.kind }, 'Note created');\n return note;\n }\n\n async getNote(id: string): Promise<Note | null> {\n return this.store.getNote(id);\n }\n\n async updateNote(id: string, patch: Partial<Note>, trigger: SnapshotTrigger = 'edit'): Promise<Note | null> {\n const existing = await this.store.getNote(id);\n if (!existing) return null;\n const contentTouched = patch.markdown !== undefined || patch.title !== undefined;\n if (contentTouched) await this.maybeSaveSnapshot(existing, trigger);\n\n const normalizedPatch: Partial<Note> = { ...patch };\n if (patch.markdown !== undefined) {\n normalizedPatch.kind = patch.kind ?? inferKind(patch.markdown, Boolean(existing.attachments?.length), existing.attachments);\n }\n if (contentTouched || patch.attachments) {\n normalizedPatch.remoteVersion = (existing.remoteVersion ?? 1) + 1;\n normalizedPatch.localVersion = patch.localVersion ?? (existing.localVersion ?? 1) + 1;\n }\n\n const updatedRaw = await this.store.updateNote(id, normalizedPatch);\n const updated = updatedRaw ? await this.reconcileAttachments(updatedRaw) : null;\n if (updated) {\n const changes = changedFieldsFromPatch(patch as Record<string, unknown>);\n emitActivity({\n type: existing.status !== updated.status ? 'note.status_changed' : 'note.updated',\n primaryObject: { kind: 'note', id: updated.id, title: updated.title },\n actor: systemActivityActor(),\n source: systemActivitySource(),\n payload: {\n changes,\n contentTouched,\n ...(existing.status !== updated.status ? { from: existing.status, to: updated.status } : {}),\n },\n nowMs: updated.updatedAt,\n });\n publishNoteEvent('note.updated', updated, {\n contentTouched,\n trigger,\n });\n }\n return updated;\n }\n\n private async reconcileAttachments(note: Note): Promise<Note> {\n const { kept, removed } = partitionAttachmentsByReference(note);\n if (removed.length === 0) return note;\n for (const attachment of removed) await this.store.deleteAttachmentFile(note.id, attachment.relativePath);\n log.debug({ noteId: note.id, removedIds: removed.map((attachment) => attachment.id) }, 'Pruned orphan note attachments');\n const hasAttachments = kept.length > 0;\n const updated = await this.store.updateNote(note.id, { attachments: kept, kind: inferKind(note.markdown, hasAttachments, kept) });\n return updated ?? { ...note, attachments: kept };\n }\n\n async syncNote(id: string, patch: Partial<Note>, baseRemoteVersion?: number): Promise<{ note: Note | null; conflict: boolean }> {\n const existing = await this.store.getNote(id);\n if (!existing) return { note: null, conflict: false };\n if (baseRemoteVersion !== undefined && existing.remoteVersion !== undefined && baseRemoteVersion < existing.remoteVersion) {\n return { note: existing, conflict: true };\n }\n const updated = await this.updateNote(id, patch, 'sync');\n return { note: updated, conflict: false };\n }\n\n async createAiEditPatch(id: string, instruction: string, markdownOverride?: string): Promise<{ message: string; patch: NoteAiPatch } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const source = markdownOverride ?? note.markdown;\n const parsed = parseNoteMarkdown(source, id);\n const wantsTodos = /待办|todo|task|行动|提醒/i.test(instruction);\n const wantsSummary = /摘要|总结|summary|压缩/i.test(instruction);\n let generated = '';\n if (wantsTodos) {\n const lines = source.split(/\\n|。|;|;/).map((line) => line.trim()).filter(Boolean);\n generated = (lines.length ? lines : [parsed.plainText]).slice(0, 12).map((line) => `- [ ] ${line.replace(/^[-*\\d.\\s\\[\\]x]+/i, '').trim()}`).join('\\n');\n } else if (wantsSummary) {\n generated = `> [!SUMMARY]\\n> ${parsed.plainText.slice(0, 220)}`;\n } else {\n generated = `${source.trimEnd()}\\n\\n## AI 整理\\n\\n${instruction.trim()}`;\n }\n return {\n message: 'AI edit patch generated',\n patch: {\n id: randomUUID(),\n summary: instruction,\n operations: [{ type: 'replaceRange', from: 0, to: source.length, markdown: generated || source }],\n },\n };\n }\n\n async catalyzeNote(id: string, config?: Config): Promise<{ note: Note; report: NoteCatalysisReport } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n let report: NoteCatalysisReport;\n try {\n report = await buildAiCatalysisReport(note, config);\n } catch (err) {\n log.warn({ err, noteId: id }, 'AI note catalysis failed; using local fallback report');\n report = buildCatalysisReport(note);\n }\n const updated = await this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: 'catalyzed',\n stage: inferCatalysisStage(note),\n lastCatalyzedAt: Date.now(),\n confidence: report.confidence,\n report,\n ...note.aiDeep?.catalysis,\n },\n },\n ai: { ...note.ai, intent: note.ai?.intent ?? 'idea', summary: note.ai?.summary ?? report.valueHypothesis },\n status: note.status === 'inbox' ? 'processed' : note.status,\n }, 'ai_edit');\n return updated ? { note: updated, report } : null;\n }\n\n async recordCatalysisFeedback(id: string, feedback: 'helpful' | 'not_helpful' | 'neutral'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return this.updateNote(id, { aiDeep: { ...note.aiDeep, processedAt: Date.now(), catalysis: { status: note.aiDeep?.catalysis?.status ?? 'catalyzed', ...note.aiDeep?.catalysis, feedback } } });\n }\n\n async linkNoteThread(id: string, sessionKey: string): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const existingKeys = note.aiDeep?.catalysis?.linkedSessionKeys ?? [];\n return this.updateNote(id, {\n aiDeep: {\n ...note.aiDeep,\n processedAt: Date.now(),\n catalysis: {\n status: note.aiDeep?.catalysis?.status ?? 'none',\n ...note.aiDeep?.catalysis,\n sourceSessionKey: note.aiDeep?.catalysis?.sourceSessionKey ?? sessionKey,\n linkedSessionKeys: Array.from(new Set([...existingKeys, sessionKey])),\n },\n },\n }, 'sync');\n }\n\n async listNoteThreads(id: string): Promise<string[] | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n return Array.from(new Set([note.aiDeep?.catalysis?.sourceSessionKey, ...(note.aiDeep?.catalysis?.linkedSessionKeys ?? [])].filter((key): key is string => Boolean(key))));\n }\n\n async getAgentContextStatus(id: string, config?: Config, force = false): Promise<{ noteUpdatedAt: number; artifact: import('./agent-context.js').NoteAgentContextArtifact | null; stale: boolean } | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const cached = getCachedNoteAgentContextArtifact(id);\n if (!force && cached && cached.noteUpdatedAt === note.updatedAt) {\n return { noteUpdatedAt: note.updatedAt, artifact: cached, stale: false };\n }\n const artifact = await buildNoteAgentContextArtifact({ note, notesService: this, config, force });\n return { noteUpdatedAt: note.updatedAt, artifact, stale: false };\n }\n\n async appendTextToNote(id: string, content: string, heading = 'AI 讨论沉淀'): Promise<Note | null> {\n const note = await this.store.getNote(id);\n if (!note) return null;\n const trimmed = content.trim();\n if (!trimmed) return note;\n const current = note.markdown.trimEnd();\n const nextMarkdown = `${current}${current ? '\\n\\n' : ''}## ${heading}\\n\\n${trimmed}\\n`;\n return this.updateNote(id, { markdown: nextMarkdown }, 'ai_edit');\n }\n\n async deleteNote(id: string): Promise<boolean> {\n const removed = await this.store.deleteNote(id);\n if (removed) await this.store.deleteAllSnapshots(id);\n return removed;\n }\n\n async listNotes(query: NotesListQuery = {}): Promise<{ items: NoteIndexEntry[]; total: number; limit: number; offset: number; hasMore: boolean }> {\n return this.store.listNotes(query);\n }\n\n async addAttachment(noteId: string, file: { name: string; buffer: Buffer; mimeType: string; duration?: number }): Promise<NoteAttachment | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const { relativePath, size } = await this.store.saveAttachment(noteId, file.name, file.buffer);\n const attachment: NoteAttachment = {\n id: randomUUID(),\n type: file.mimeType.startsWith('image/') ? 'image' : file.mimeType.startsWith('audio/') ? 'audio' : file.mimeType.startsWith('video/') ? 'video' : 'file',\n mimeType: file.mimeType,\n fileName: file.name,\n size,\n relativePath,\n duration: file.duration,\n };\n const attachments = [...(note.attachments || []), attachment];\n const kind = note.kind === 'thought' && attachment.type === 'audio' ? 'voice' : note.kind === 'thought' ? 'media' : note.kind;\n await this.store.updateNote(noteId, { attachments, kind });\n return attachment;\n }\n\n async getAttachmentPath(noteId: string, attachmentId: string): Promise<{ filePath: string; mimeType: string; fileName: string } | null> {\n const note = await this.store.getNote(noteId);\n if (!note) return null;\n const attachment = note.attachments?.find((a) => a.id === attachmentId);\n if (!attachment) return null;\n return { filePath: this.store.resolveAttachmentPath(noteId, attachment.relativePath), mimeType: attachment.mimeType, fileName: attachment.fileName };\n }\n\n async listNoteHistory(noteId: string): Promise<NoteSnapshotEntry[]> { return this.store.listSnapshots(noteId); }\n async getNoteSnapshot(noteId: string, timestamp: number): Promise<NoteSnapshot | null> { return this.store.getSnapshot(noteId, timestamp); }\n\n async restoreNoteSnapshot(noteId: string, timestamp: number): Promise<Note | null> {\n const snapshot = await this.store.getSnapshot(noteId, timestamp);\n const existing = await this.store.getNote(noteId);\n if (!snapshot || !existing) return null;\n await this.maybeSaveSnapshot(existing, 'restore');\n this.lastSnapshotAt.set(noteId, Date.now());\n await this.store.pruneSnapshots(noteId, MAX_SNAPSHOTS_PER_NOTE);\n return this.store.updateNote(noteId, { title: snapshot.title, markdown: snapshot.markdown, tags: snapshot.tags, kind: snapshot.kind, status: snapshot.status });\n }\n\n async flush(): Promise<void> { await this.store.flush(); }\n async moveToGroup(noteId: string, groupId: string | null): Promise<Note | null> { return this.updateNote(noteId, { groupId: groupId ?? undefined }); }\n\n async createTask(title: string, source: CaptureSource, opts: { dueAt?: number; priority?: 'high' | 'medium' | 'low'; sourceSessionKey?: string; sourceNoteId?: string; groupId?: string } = {}): Promise<Note> {\n return this.createNote({\n title,\n markdown: `- [ ] ${title}`,\n kind: 'task',\n capturedVia: source,\n groupId: opts.groupId,\n taskMeta: { done: false, dueAt: opts.dueAt, priority: opts.priority, sourceSessionKey: opts.sourceSessionKey, sourceNoteId: opts.sourceNoteId },\n });\n }\n\n async toggleTaskDone(noteId: string): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n const done = !note.taskMeta?.done;\n const markdown = note.markdown.replace(/^- \\[[ xX]\\]/m, `- [${done ? 'x' : ' '}]`);\n return this.updateNote(noteId, { markdown, taskMeta: { ...note.taskMeta, done } });\n }\n\n async updateTaskMeta(noteId: string, patch: Partial<import('./types.js').NoteTaskMeta>): Promise<Note | null> {\n const note = await this.store.getNote(noteId);\n if (!note || note.kind !== 'task') return null;\n return this.updateNote(noteId, { taskMeta: { ...note.taskMeta, done: note.taskMeta?.done ?? false, ...patch } });\n }\n\n async recordOpen(noteId: string): Promise<Note | null> {\n return this.updateNote(noteId, { lastOpenedAt: Date.now() } as Partial<Note>);\n }\n\n private async maybeSaveSnapshot(note: Note, trigger: SnapshotTrigger): Promise<void> {\n if (trigger !== 'edit') {\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n return;\n }\n const last = this.lastSnapshotAt.get(note.id) ?? 0;\n if (Date.now() - last < SNAPSHOT_THROTTLE_MS) return;\n await this.store.saveSnapshot(note, trigger);\n this.lastSnapshotAt.set(note.id, Date.now());\n await this.store.pruneSnapshots(note.id, MAX_SNAPSHOTS_PER_NOTE);\n }\n}\n\nexport { buildNoteAttachmentRef };\n"],"mappings":";;;;;;;;;;;;;gBAO0E;aACxB;AAuBlD,MAAM,MAAM,aAAa,eAAe;AACxC,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAE7B,SAAS,UAAU,UAAmB,gBAA0B,aAA0C;AACxG,KAAI,kBAAkB,aAAa,UAAU,YAAY,OAAO,SAAS,KAAK,SAAS,QAAQ,CAAE,QAAO;AACxG,KAAI,eAAgB,QAAO;AAC3B,KAAI,CAAC,SAAU,QAAO;CACtB,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,gEAAgE,KAAK,MAAM,IAAI,0BAA0B,KAAK,SAAS,CAAE,QAAO;AACpI,KAAI,eAAe,KAAK,SAAS,MAAM,CAAC,CAAE,QAAO;AACjD,QAAO;;AAGT,SAAS,mBAAmB,UAAuC;CACjE,MAAM,aAAa,kBAAkB,YAAY,GAAG,CAAC,UAAU,MAAM,CAAC,QAAQ,QAAQ,IAAI;AAC1F,QAAO,aAAa,MAAM,KAAK,WAAW,CAAC,MAAM,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,KAAA;;AAGrE,SAAS,qBAAqB,UAA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AAK,MAAM,aAAa,MAAM,QAAQ;AAC5C,OAAK,eAAe,IAAI,KAAK,IAAI,KAAK,KAAK,CAAC;AAC5C,QAAM,KAAK,MAAM,eAAe,KAAK,IAAI,uBAAuB"}
|
package/dist/src/notes/store.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createLogger } from "../utils/logger/index.js";
|
|
2
2
|
import { init_logger } from "../utils/logger.js";
|
|
3
|
-
import { init_write_file_atomic, writeTextAtomic } from "../infra/write-file-atomic.js";
|
|
4
3
|
import { requireXopcDatabase } from "../storage/sqlite/connection.js";
|
|
5
4
|
import { buildNoteIndexMeta } from "./note-index-meta.js";
|
|
6
5
|
import { deleteNoteRecord, getNoteRecord, listNoteRecords, upsertNoteRecord } from "../storage/sqlite/notes-repository.js";
|
|
7
6
|
import { deleteNoteAgentContextRecord } from "../storage/sqlite/note-agent-context-repository.js";
|
|
8
7
|
import "../storage/sqlite/index.js";
|
|
8
|
+
import { init_write_file_atomic, writeTextAtomic } from "../infra/write-file-atomic.js";
|
|
9
9
|
import { resolveNoteHistoryDir, resolveNoteMediaDir } from "./paths.js";
|
|
10
10
|
import { join } from "node:path";
|
|
11
11
|
import { randomUUID } from "node:crypto";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type DesktopPetPackageAction } from './manifest.js';
|
|
2
|
+
export { DESKTOP_PET_ACTIONS, type DesktopPetPackageAction } from './manifest.js';
|
|
3
|
+
export type CreateDesktopPetPackageInput = {
|
|
4
|
+
id?: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
prompt: string;
|
|
7
|
+
description?: string;
|
|
8
|
+
targetDir?: string;
|
|
9
|
+
overwrite?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export type CreateDesktopPetPackageResult = {
|
|
12
|
+
id: string;
|
|
13
|
+
name: string;
|
|
14
|
+
description: string;
|
|
15
|
+
dir: string;
|
|
16
|
+
manifestPath: string;
|
|
17
|
+
thumbnailPath: string;
|
|
18
|
+
spritesheetPath: string;
|
|
19
|
+
sourcePrompt: string;
|
|
20
|
+
};
|
|
21
|
+
export declare function resolveDesktopPetsDir(): string;
|
|
22
|
+
export declare function desktopPetActionFrameCount(action: DesktopPetPackageAction): number;
|
|
23
|
+
export declare function desktopPetActionFps(action: DesktopPetPackageAction): number;
|
|
24
|
+
export declare function desktopPetActionLoops(action: DesktopPetPackageAction): boolean;
|
|
25
|
+
export declare function createDesktopPetPackage(input: CreateDesktopPetPackageInput): Promise<CreateDesktopPetPackageResult>;
|