@inneranimalmedia/agentsam-sdk 2.6.17 → 2.6.18
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/AGENTSAM.md +19 -0
- package/README.md +15 -0
- package/apps/agentsam-copro-studio/agentsam.app.json +125 -0
- package/apps/cad-creator/agentsam.app.json +230 -0
- package/apps/cad-creator/shared/cad/package.json +1 -1
- package/apps/cad-creator/shared/cad/src/index.ts +1 -0
- package/apps/cad-creator/shared/cad/src/lighting.test.ts +32 -0
- package/apps/cad-creator/shared/cad/src/lighting.ts +79 -0
- package/apps/cad-creator/shared/cad/src/types.ts +106 -4
- package/apps/design-canvas/agentsam.app.json +144 -0
- package/apps/ecommerce-cms-agentsam/agentsam.app.json +658 -0
- package/apps/local-studio/agentsam.app.json +271 -0
- package/apps/samsketch/agentsam.app.json +136 -0
- package/contracts/source-types.v2.json +86 -1
- package/docs/CAPABILITIES.md +56 -0
- package/docs/PRODUCT_LIFECYCLE.md +2 -0
- package/docs/REPOSITORY_KNOWLEDGE.md +24 -0
- package/docs/adr/ADR-0010-widget-contributions-registry-persistence.md +60 -0
- package/docs/architecture/ACP_D1_HOSTING.md +67 -0
- package/docs/architecture/AGENTSAM-PRODUCT-CATALOG-RELEASES-20261028.md +3 -1
- package/docs/architecture/AGENTSAM_APPLICATION_CONTRACT.md +6 -2
- package/docs/architecture/AGENTSAM_APPLICATION_INVENTORY.md +135 -0
- package/docs/architecture/AGENTSAM_DISTRIBUTION_OWNERSHIP.md +1 -1
- package/docs/architecture/AGENTSAM_GO_RUNTIME.md +1 -1
- package/docs/architecture/APP_PRODUCT_DATA_MODEL.md +121 -0
- package/docs/architecture/BRAND_WORKSPACE_V1.md +71 -0
- package/docs/architecture/CANONICAL_CAD_FORMAT_SPINE.md +79 -0
- package/docs/architecture/ECOMMERCE_THEME_START_FLOW.md +31 -0
- package/docs/architecture/LIVE_AST_AND_CREATIVE_RESOURCE_GRAPH.md +129 -0
- package/docs/architecture/PRIMETECH_SCENE_V2_READINESS.md +89 -0
- package/docs/architecture/PYTHON_CAD_SERVICE_TRANSPORT.md +116 -0
- package/docs/architecture/SCHEMA_AUTHORITIES.md +83 -0
- package/docs/architecture/app-module-plugin-classification.md +71 -0
- package/docs/architecture/primetech/BARNDOMINIUM_BIM_BUILDOUT_RUNBOOK_20261123.md +139 -0
- package/docs/architecture/primetech/BARNDOMINIUM_SPACE_DELIVERY_20261123.md +58 -0
- package/docs/architecture/primetech/CAPABILITY_AND_ACCEPTANCE_MATRIX.md +176 -0
- package/docs/architecture/primetech/IMPLEMENTATION_WAVES.md +203 -0
- package/docs/architecture/primetech/PORTABLE_EDITOR_CONTRACTS.md +192 -0
- package/docs/architecture/primetech/README.md +65 -0
- package/docs/architecture/universal-registry-recovery.md +62 -0
- package/docs/audits/2026-11-22-sdk-d1-registry-parity.md +116 -0
- package/docs/brand/BRAND_CAPABILITY_INVENTORY.md +160 -0
- package/docs/cad/FORMAT_SUPPORT.md +46 -0
- package/docs/cad/LIB_CAD_REMASTER_AUDIT.md +49 -0
- package/docs/engineering/CMS_DATA_AUTHORITY_2026-11-03.md +4 -2
- package/docs/generated/SDK_CAPABILITY_INVENTORY.md +10 -10
- package/docs/intake/product-capabilities.proposed.ts +6 -6
- package/docs/operations/CLOUDFLARE-QUEUE-OBSERVABILITY.md +1 -1
- package/docs/product/AGENTSAM_PRODUCT_EXPERIENCE_STANDARD.md +1 -1
- package/docs/reference/AGENTSAM-CLI-WORKFLOWS.md +1 -1
- package/docs/reference/AGENTSAM-REGISTRY.generated.md +25 -16
- package/docs/sam/opencv-media.md +63 -0
- package/docs/standards/DESKTOP_WEB_PARITY_ACCEPTANCE.md +42 -0
- package/migrations/d1/0001_agentsam_plugin_runtime.sql +0 -2
- package/migrations/d1/0028_drop_unused_tool_handler_families.sql +4 -0
- package/migrations/d1/0029_agentsam_tools_account_plugin_key_unique.sql +26 -0
- package/migrations/d1/0030_cad_engine_plugins_contract_agnostic.sql +21 -0
- package/migrations/d1/0031_ops_trail_single_tool_call_source.sql +13 -0
- package/migrations/d1/0033_service_registry_model_discovery.sql +50 -0
- package/migrations/d1/20261123_skill_package_staging.sql +64 -0
- package/migrations/d1/20261123_universal_registry_stage.sql +58 -0
- package/migrations/d1/20261126_agentsam_tool_legacy_metadata_compact.sql +6 -0
- package/migrations/d1/20261126_agentsam_tools_archive_legacy_metadata.sql +20 -0
- package/migrations/d1/20261126_agentsam_tools_normalize_intent_tags.sql +49 -0
- package/migrations/d1/20261126_agentsam_tools_normalize_policy_health.sql +89 -0
- package/migrations/d1/20261126_agentsam_tools_remove_legacy_scope_keys.sql +29 -0
- package/migrations/d1/20261126_agentsam_tools_runtime_view_compat.sql +65 -0
- package/migrations/d1/generated/20261123_portable_cli_seed.sql +97 -0
- package/migrations/d1/generated/20261123_source_skill_seed.sql +3881 -0
- package/migrations/runtime/0012_agent_run_event_sequence.sql +27 -0
- package/package.json +57 -17
- package/packages/agentsam-3d-viewer/README.md +5 -0
- package/packages/agentsam-3d-viewer/package.json +1 -1
- package/packages/agentsam-3d-viewer/src/atmosphere.js +90 -0
- package/packages/agentsam-3d-viewer/src/gltf-loader.js +42 -0
- package/packages/agentsam-3d-viewer/src/index.d.ts +53 -1
- package/packages/agentsam-3d-viewer/src/index.js +18 -3
- package/packages/agentsam-3d-viewer/src/pbr-materials.js +330 -0
- package/packages/agentsam-3d-viewer/src/procedural-material.js +96 -0
- package/packages/agentsam-3d-viewer/src/procedural-textures.js +334 -0
- package/packages/agentsam-3d-viewer/src/renderer-capabilities.js +12 -0
- package/packages/agentsam-3d-viewer/src/stroke-geometry.js +4 -0
- package/packages/agentsam-3d-viewer/src/studio-finishes.js +67 -0
- package/packages/agentsam-3d-viewer/test/atmosphere.test.mjs +17 -0
- package/packages/agentsam-3d-viewer/test/gltf-loader.test.mjs +49 -0
- package/packages/agentsam-3d-viewer/test/pbr-mined-presets.test.mjs +44 -0
- package/packages/agentsam-3d-viewer/test/procedural-material.test.mjs +56 -0
- package/packages/agentsam-3d-viewer/test/renderer-capabilities.test.mjs +18 -0
- package/packages/agentsam-3d-viewer/test/studio-shared.test.mjs +23 -0
- package/packages/agentsam-architectural-intelligence/package.json +1 -1
- package/packages/agentsam-brand/package.json +3 -2
- package/packages/agentsam-brand/src/core/capabilities.js +108 -48
- package/packages/agentsam-brand/src/extract.js +6 -1
- package/packages/agentsam-brand/src/index.js +1 -0
- package/packages/agentsam-brand/src/public.js +15 -1
- package/packages/agentsam-brand/src/scan.js +47 -0
- package/packages/agentsam-brand/src/workspace.d.ts +19 -0
- package/packages/agentsam-brand/src/workspace.js +166 -0
- package/packages/agentsam-cms/README.md +11 -0
- package/packages/agentsam-cms/package.json +4 -3
- package/packages/agentsam-cms/src/contracts.js +16 -0
- package/packages/agentsam-cms/src/studio-bridge-protocol.js +113 -0
- package/packages/agentsam-cms/test/standalone.test.mjs +7 -3
- package/packages/agentsam-cms/test/studio-bridge-protocol.test.mjs +26 -0
- package/packages/agentsam-communications/package.json +3 -2
- package/packages/agentsam-communications/src/samspeaks-runtime.js +126 -0
- package/packages/agentsam-contracts/README.md +67 -0
- package/packages/agentsam-contracts/agentsam.package.json +46 -12
- package/packages/agentsam-contracts/dist/agent.d.ts +6 -3
- package/packages/agentsam-contracts/dist/agent.js +20 -0
- package/packages/agentsam-contracts/dist/bim-model.d.ts +95 -0
- package/packages/agentsam-contracts/dist/bim-model.js +57 -0
- package/packages/agentsam-contracts/dist/cad-source-formats.d.ts +55 -0
- package/packages/agentsam-contracts/dist/cad-source-formats.js +9617 -0
- package/packages/agentsam-contracts/dist/design-workspace.d.ts +13 -1
- package/packages/agentsam-contracts/dist/index.d.ts +6 -0
- package/packages/agentsam-contracts/dist/index.js +17836 -349
- package/packages/agentsam-contracts/dist/json-schema.d.ts +8 -0
- package/packages/agentsam-contracts/dist/json-schema.js +7787 -0
- package/packages/agentsam-contracts/dist/operations.d.ts +6 -1
- package/packages/agentsam-contracts/dist/operations.js +7795 -5
- package/packages/agentsam-contracts/dist/resource-ref.d.ts +21 -0
- package/packages/agentsam-contracts/dist/resource-ref.js +23 -0
- package/packages/agentsam-contracts/dist/run.d.ts +91 -3
- package/packages/agentsam-contracts/dist/run.js +28 -0
- package/packages/agentsam-contracts/dist/scene-document.d.ts +32 -0
- package/packages/agentsam-contracts/dist/scene-document.js +30 -0
- package/packages/agentsam-contracts/dist/scene-format.d.ts +44 -0
- package/packages/agentsam-contracts/dist/scene-format.js +35 -0
- package/packages/agentsam-contracts/dist/source-types-registry.d.ts +9 -0
- package/packages/agentsam-contracts/dist/source-types-registry.js +9512 -0
- package/packages/agentsam-contracts/dist/tools.d.ts +2 -1
- package/packages/agentsam-contracts/dist/tools.js +7794 -9
- package/packages/agentsam-contracts/dist/widgets.d.ts +2 -0
- package/packages/agentsam-contracts/package.json +42 -3
- package/packages/agentsam-contracts/schemas/activity.v1.schema.json +142 -0
- package/packages/agentsam-contracts/schemas/bim-model.v1.schema.json +76 -0
- package/packages/agentsam-contracts/schemas/resource-ref.v1.schema.json +18 -0
- package/packages/agentsam-contracts/schemas/run-receipt.v1.schema.json +411 -0
- package/packages/agentsam-contracts/schemas/run-start.v1.schema.json +40 -0
- package/packages/agentsam-contracts/schemas/run.v1.schema.json +243 -0
- package/packages/agentsam-contracts/schemas/sam-operation.v1.schema.json +8 -0
- package/packages/agentsam-contracts/schemas/scene-document.v2.schema.json +212 -0
- package/packages/agentsam-contracts/schemas/scene-format.v1.schema.json +173 -0
- package/packages/agentsam-contracts/schemas/source-types.v2.json +86 -1
- package/packages/agentsam-contracts/scripts/build.mjs +2 -1
- package/packages/agentsam-contracts/src/agent.ts +10 -18
- package/packages/agentsam-contracts/src/bim-model.ts +143 -0
- package/packages/agentsam-contracts/src/cad-source-formats.ts +195 -0
- package/packages/agentsam-contracts/src/design-workspace.ts +9 -0
- package/packages/agentsam-contracts/src/index.ts +6 -0
- package/packages/agentsam-contracts/src/json-schema.ts +37 -0
- package/packages/agentsam-contracts/src/operations.ts +12 -1
- package/packages/agentsam-contracts/src/resource-ref.ts +36 -0
- package/packages/agentsam-contracts/src/run.ts +93 -16
- package/packages/agentsam-contracts/src/scene-document.ts +58 -0
- package/packages/agentsam-contracts/src/scene-format.ts +91 -0
- package/packages/agentsam-contracts/src/source-types-registry.ts +65 -0
- package/packages/agentsam-contracts/src/tools.ts +4 -1
- package/packages/agentsam-contracts/src/widgets.ts +2 -0
- package/packages/agentsam-contracts/test/bim-model.test.mjs +66 -0
- package/packages/agentsam-contracts/test/cad-source-formats.test.mjs +103 -0
- package/packages/agentsam-contracts/test/contracts.test.mjs +23 -1
- package/packages/agentsam-contracts/test/resource-ref.test.mjs +29 -0
- package/packages/agentsam-contracts/test/run-contract.test.mjs +44 -0
- package/packages/agentsam-contracts/test/scene-document.test.mjs +30 -0
- package/packages/agentsam-contracts/test/scene-format.test.mjs +40 -0
- package/packages/agentsam-contracts/test/source-types.test.mjs +29 -0
- package/packages/agentsam-desktop-shell/scripts/app-discovery.mjs +36 -25
- package/packages/agentsam-errors/package.json +1 -1
- package/packages/agentsam-goalguru/agentsam.app.json +97 -0
- package/packages/agentsam-goap/package.json +2 -2
- package/packages/agentsam-hooks/package.json +1 -1
- package/packages/agentsam-knowledge/package.json +1 -1
- package/packages/agentsam-merch/package.json +1 -1
- package/packages/agentsam-nav/dist/Surfaces.d.ts +14 -4
- package/packages/agentsam-nav/dist/browser.global.js +16 -16
- package/packages/agentsam-nav/dist/browser.js +65 -22
- package/packages/agentsam-nav/dist/contracts.d.ts +2 -0
- package/packages/agentsam-nav/dist/index.d.ts +1 -1
- package/packages/agentsam-nav/dist/index.js +62 -21
- package/packages/agentsam-nav/dist/shell.css +149 -4
- package/packages/agentsam-nav/dist/theme.css +149 -4
- package/packages/agentsam-nav/dist/useAdminApps.d.ts +21 -2
- package/packages/agentsam-nav/package.json +1 -1
- package/packages/agentsam-occt/dist/native-provider.d.mts +1 -1
- package/packages/agentsam-occt/dist/native-provider.mjs +1 -1
- package/packages/agentsam-occt/package.json +1 -1
- package/packages/agentsam-occt/src/native-provider.mjs +1 -1
- package/packages/agentsam-queue-control/package.json +1 -1
- package/packages/agentsam-queue-control/src/adapters/sqlite.js +8 -6
- package/packages/agentsam-repository/package.json +1 -1
- package/packages/agentsam-vault/package.json +5 -1
- package/packages/agentsam-vault/src/crypto/aes-gcm.d.ts +25 -0
- package/packages/agentsam-vault/src/crypto/aes-gcm.js +149 -0
- package/packages/agentsam-vault/src/crypto/classify.d.ts +22 -0
- package/packages/agentsam-vault/src/crypto/classify.js +83 -0
- package/packages/agentsam-vault/src/crypto/oauth-envelope.d.ts +7 -0
- package/packages/agentsam-vault/src/index.js +10 -0
- package/packages/agentsam-vault/src/providers/registry.js +8 -0
- package/packages/agentsam-workbench/README.md +27 -3
- package/packages/agentsam-workbench/package.json +26 -4
- package/packages/agentsam-workbench/src/agent/AskAgentSamPill.tsx +17 -0
- package/packages/agentsam-workbench/src/agent/MiniAgentSam.tsx +144 -20
- package/packages/agentsam-workbench/src/agent/contextual-composer.css +7 -0
- package/packages/agentsam-workbench/src/agent/index.ts +1 -0
- package/packages/agentsam-workbench/src/agent/mini-agentsam.css +54 -0
- package/packages/agentsam-workbench/src/design/DesignWorkspaceFrame.tsx +277 -82
- package/packages/agentsam-workbench/src/design/design-workspace.css +173 -109
- package/packages/agentsam-workbench/src/index.ts +1 -0
- package/packages/agentsam-workbench/src/shell/InspectorPicker.tsx +38 -0
- package/packages/agentsam-workbench/src/shell/ResizableStage.tsx +26 -5
- package/packages/agentsam-workbench/src/shell/SidePanel.tsx +3 -3
- package/packages/agentsam-workbench/src/shell/StudioCommands.tsx +32 -0
- package/packages/agentsam-workbench/src/shell/appearance.d.mts +28 -0
- package/packages/agentsam-workbench/src/shell/appearance.mjs +279 -0
- package/packages/agentsam-workbench/src/shell/index.ts +2 -0
- package/packages/agentsam-workbench/src/shell/inspector-picker.css +48 -0
- package/packages/agentsam-workbench/src/shell/studio-icons.ts +104 -0
- package/packages/agentsam-workbench/src/shell/studio-panels.ts +21 -0
- package/packages/agentsam-workbench/src/widgets/registry.ts +4 -4
- package/packages/agentsam-workbench/src/workflows/WorkflowStudio.tsx +936 -0
- package/packages/agentsam-workbench/src/workflows/index.ts +5 -0
- package/packages/agentsam-workbench/src/workflows/model.ts +207 -0
- package/packages/agentsam-workbench/src/workflows/types.ts +206 -0
- package/packages/agentsam-workbench/src/workflows/workflow-studio.css +290 -0
- package/packages/catalog/generated/packages.json +157 -45
- package/packages/connectors/cfoa/package.json +7 -2
- package/packages/connectors/cfoa/src/PERMISSION_REGISTRY.md +45 -0
- package/packages/connectors/cfoa/src/api-client.js +4 -0
- package/packages/connectors/cfoa/src/capabilities.js +123 -285
- package/packages/connectors/cfoa/src/families/media.js +16 -12
- package/packages/connectors/cfoa/src/index.js +31 -37
- package/packages/connectors/cfoa/src/oauth-persist.js +18 -2
- package/packages/connectors/cfoa/src/permission-options.js +147 -1038
- package/packages/connectors/cfoa/src/routes.js +92 -35
- package/packages/connectors/cfoa/src/scope-catalog.js +16 -351
- package/packages/connectors/cfoa/src/scope-registry.js +248 -0
- package/packages/connectors/cfoa/test/scope-registry.test.mjs +168 -0
- package/packages/connectors/cfoa/tests/capabilities.test.mjs +86 -45
- package/packages/connectors/cfoa/tests/connector.test.mjs +143 -0
- package/packages/connectors/cfoa/tests/media-discovery.test.mjs +34 -10
- package/packages/identity/.agentsam/features/oauth-login-portal/agentsam.feature.json +1 -1
- package/packages/identity/agentsam.package.json +4 -4
- package/packages/identity/migrations/apply-portable.js +11 -4
- package/packages/identity/migrations/sqlite/007_identity_session_revoke_reason.sql +3 -0
- package/packages/identity/migrations/sqlite/008_identity_accounts.sql +41 -0
- package/packages/identity/migrations/sqlite/009_identity_scope.sql +30 -0
- package/packages/identity/package.json +11 -6
- package/packages/identity/schema/agentsam.identity/manifest.json +21 -4
- package/packages/identity/src/adapters/account-security-store.js +7 -0
- package/packages/identity/src/adapters/column-support.js +39 -0
- package/packages/identity/src/adapters/iam-compat/index.js +19 -4
- package/packages/identity/src/adapters/portable-d1/index.js +3 -1
- package/packages/identity/src/adapters/portable-store.js +80 -51
- package/packages/identity/src/app/verify-app.js +27 -0
- package/packages/identity/src/contracts/identity-store.js +2 -2
- package/packages/identity/src/core/password-gate.js +116 -0
- package/packages/identity/src/frontend/auth-portal/pages/login.html +1 -1
- package/packages/identity/src/frontend/auth-portal/pages/reset.html +1 -1
- package/packages/identity/src/frontend/auth-portal/pages/signup.html +1 -1
- package/packages/identity/src/frontend/auth-portal/shared/company-branding.js +18 -7
- package/packages/identity/src/frontend/auth-portal/shared/default-auth-logo.svg +4 -0
- package/packages/identity/src/frontend/auth-portal/store-access.js +97 -0
- package/packages/identity/src/migrations/0005_session_audit_columns.sql +6 -0
- package/packages/identity/src/migrations/README.md +2 -0
- package/packages/identity/src/oauth/native-handoff.js +2 -2
- package/packages/identity/src/server/identity-service.js +1 -1
- package/packages/identity/src/server/worker-router.js +16 -5
- package/packages/identity/tests/identity-portal-e2e.test.mjs +166 -0
- package/packages/identity/tests/lane1-identity-store-parity.test.mjs +17 -6
- package/packages/identity/tests/password-gate.test.mjs +66 -0
- package/packages/identity/tests/portable-identity-scope.test.mjs +59 -0
- package/packages/identity/tests/session-audit.test.mjs +135 -0
- package/packages/identity/tests/worker-portal-assets.test.mjs +47 -0
- package/packages/primetech-procedures/README.md +46 -5
- package/packages/primetech-procedures/agentsam.package.json +6 -6
- package/packages/primetech-procedures/package.json +14 -3
- package/packages/primetech-procedures/procedures/arch.assembly.calculate/procedure.json +83 -0
- package/packages/primetech-procedures/procedures/media.asset.preflight/procedure.json +85 -0
- package/packages/primetech-procedures/procedures/media.image.optimize-asset/procedure.json +102 -0
- package/packages/primetech-procedures/procedures/repo.asset.inventory/__pycache__/run.cpython-314.pyc +0 -0
- package/packages/primetech-procedures/procedures/repo.git.status/procedure.json +58 -0
- package/packages/primetech-procedures/procedures/repo.git.status/run.sh +10 -0
- package/packages/primetech-procedures/src/index.js +140 -41
- package/packages/primetech-procedures/test/__pycache__/test_inventory.cpython-314.pyc +0 -0
- package/packages/primetech-procedures/test/runtime-kinds.test.mjs +210 -0
- package/packages/theme-scenes/package.json +1 -1
- package/packages/work-graph/package.json +1 -1
- package/protocol/README.md +18 -0
- package/protocol/capabilities/capability-manifest.schema.json +111 -19
- package/protocol/capabilities/manifest.json +12 -1
- package/protocol/contracts/source-types.v2.json +86 -1
- package/protocol/product-releases/README.md +15 -12
- package/protocol/registry/universal-catalog.v1.json +2820 -0
- package/protocol/sam/activity.v1.schema.json +111 -17
- package/protocol/sam/operation.schema.json +8 -0
- package/protocol/sam/run-receipt.v1.schema.json +411 -0
- package/protocol/sam/run-start.v1.schema.json +40 -0
- package/protocol/sam/run.v1.schema.json +243 -0
- package/protocol/theme-refinery/d1-reconciliation.md +66 -32
- package/protocol/theme-refinery/product-metadata.schema.json +1 -1
- package/python/README.md +81 -8
- package/python/agentsam_sdk/cad/__init__.py +26 -3
- package/python/agentsam_sdk/cad/adapters/__init__.py +6 -0
- package/python/agentsam_sdk/cad/adapters/freecad.py +200 -0
- package/python/agentsam_sdk/cad/building.py +42 -0
- package/python/agentsam_sdk/cad/jobs.py +174 -0
- package/python/agentsam_sdk/cad/native.py +68 -9
- package/python/agentsam_sdk/cad/service.py +570 -0
- package/python/agentsam_sdk/cli.py +31 -0
- package/python/agentsam_sdk/client.py +49 -16
- package/python/agentsam_sdk/data/d1_bloat.py +0 -1
- package/python/agentsam_sdk/media/__init__.py +8 -0
- package/python/agentsam_sdk/media/opencv.py +188 -0
- package/python/agentsam_sdk/procedures/client.py +1 -1
- package/python/agentsam_sdk/registry_cli.py +88 -0
- package/python/agentsam_sdk/runtime/native.py +1 -1
- package/python/agentsam_sdk/terminal_art.py +5 -6
- package/python/pyproject.toml +3 -0
- package/python/tests/fixtures/freecad_host_cases.json +30 -0
- package/python/tests/test_bridge_policy.py +40 -0
- package/python/tests/test_cad_building_client.py +47 -0
- package/python/tests/test_cad_jobs_client.py +102 -0
- package/python/tests/test_cad_native.py +104 -1
- package/python/tests/test_cad_service_client.py +288 -0
- package/python/tests/test_opencv_media.py +79 -0
- package/python/tests/test_procedure_client.py +6 -0
- package/python/tests/test_public_client.py +13 -0
- package/services/cad/blender/adapter.py +49 -0
- package/services/cad/ifc/__pycache__/adapter.cpython-311.pyc +0 -0
- package/services/cad/ifc/adapter.py +836 -0
- package/services/cad/server.py +435 -132
- package/skills/README.md +1 -1
- package/skills/agentsam-app-fundamentals/agentsam.skill.json +20 -0
- package/skills/agentsam-arch-bim/SKILL.md +166 -6
- package/skills/agentsam-arch-bim/agentsam.skill.json +2 -2
- package/skills/agentsam-cad/SKILL.md +122 -36
- package/skills/agentsam-cad/agentsam.skill.json +20 -0
- package/skills/agentsam-cad/evals/README.md +56 -0
- package/skills/agentsam-cad/references/engines-and-lanes.md +70 -0
- package/skills/agentsam-cad/references/projects-and-operations.md +112 -0
- package/skills/agentsam-cad/references/proof-and-triage.md +89 -0
- package/skills/agentsam-cad/references/python-service-and-jobs.md +102 -0
- package/skills/agentsam-cad/references/scene-geometry-bim.md +113 -0
- package/skills/agentsam-canvas-creation/agentsam.skill.json +20 -0
- package/skills/agentsam-cloudflare-workers/agentsam.skill.json +20 -0
- package/skills/agentsam-cms-ready-creation/agentsam.skill.json +20 -0
- package/skills/agentsam-codebaseindex/agentsam.skill.json +20 -0
- package/skills/agentsam-jr-dev/agentsam.skill.json +20 -0
- package/skills/agentsam-plan-and-goap/agentsam.skill.json +20 -0
- package/skills/agentsam-progression-guard/agentsam.skill.json +20 -0
- package/skills/agentsam-repo-recon/agentsam.skill.json +20 -0
- package/skills/agentsam-sam-operations/SKILL.md +76 -36
- package/skills/agentsam-sam-operations/agentsam.skill.json +20 -0
- package/skills/agentsam-sdk-orientation/agentsam.skill.json +20 -0
- package/skills/catalog.json +21 -6
- package/src/acp/agent-executor.js +38 -2
- package/src/acp/client.js +128 -39
- package/src/acp/dependencies.js +159 -19
- package/src/acp/http.js +14 -0
- package/src/acp/index.js +3 -0
- package/src/acp/runs.js +5 -3
- package/src/agent/capability-adapter.js +21 -23
- package/src/cli/command-catalog.js +4 -4
- package/src/cli/desktop-launch.js +2 -2
- package/src/cli/update-check.js +131 -0
- package/src/cli.js +6 -5
- package/src/commands/account-auth.js +36 -26
- package/src/commands/app-inventory.js +343 -0
- package/src/commands/app.js +162 -27
- package/src/commands/ast.js +80 -0
- package/src/commands/cad.js +2 -0
- package/src/commands/cheat-sheet.js +1 -1
- package/src/commands/cloudflare-login.js +170 -65
- package/src/commands/cloudflare-status.js +38 -0
- package/src/commands/cloudflare.js +54 -42
- package/src/commands/codebaseindex.js +34 -13
- package/src/commands/db.js +2 -2
- package/src/commands/go.js +1 -1
- package/src/commands/interactive.js +5 -0
- package/src/commands/knowledge.js +4 -2
- package/src/commands/mcp.js +5 -2
- package/src/commands/preferences.js +48 -6
- package/src/commands/product.js +4 -4
- package/src/commands/run.js +3 -4
- package/src/commands/shell.js +32 -10
- package/src/go/contract.js +1 -1
- package/src/go/official-registry.js +41 -36
- package/src/go/product-catalog.test.mjs +52 -0
- package/src/go/receipts.js +19 -6
- package/src/indexing/index.js +10 -0
- package/src/indexing/live-ast.js +200 -0
- package/src/indexing/live-cad-graph.js +107 -0
- package/src/indexing/live-resource-graph.js +95 -0
- package/src/knowledge/config.js +5 -4
- package/src/knowledge/store-discovery.js +22 -5
- package/src/knowledge/stores/d1.js +141 -0
- package/src/lib/auth.js +7 -4
- package/src/lib/cad/bim-bridge.d.ts +6 -0
- package/src/lib/cad/bim-bridge.js +96 -0
- package/src/lib/cad/d1-project-store.js +1 -1
- package/src/lib/cad/delivery-profiles.d.ts +1 -1
- package/src/lib/cad/delivery-profiles.js +82 -6
- package/src/lib/cad/format-policy.d.ts +11 -0
- package/src/lib/cad/format-policy.js +14 -0
- package/src/lib/cad/freecad-host.d.ts +19 -0
- package/src/lib/cad/freecad-host.js +171 -0
- package/src/lib/cad/freecad.js +38 -65
- package/src/lib/cad/ifc-cli.js +82 -0
- package/src/lib/cad/ifc.js +152 -0
- package/src/lib/cad/index.js +3 -0
- package/src/lib/cad/production-operations.js +2 -0
- package/src/lib/cad/project-runtime.js +2 -2
- package/src/lib/cad/project-v2.js +13 -25
- package/src/lib/cad-docker.js +35 -17
- package/src/lib/whoami-capabilities.js +8 -14
- package/src/mcp/cloudflare-bundles.js +39 -41
- package/src/models/inventory-core.d.ts +32 -1
- package/src/models/inventory-core.js +118 -36
- package/src/plugins/cloudflare.js +3 -3
- package/src/plugins/completeful.js +2 -4
- package/src/plugins/contracts.js +2 -3
- package/src/plugins/creative.js +2 -2
- package/src/plugins/registry.js +52 -33
- package/src/plugins/runtime.js +64 -13
- package/src/registry/generated/inventory.json +289 -66
- package/src/registry/universal-reconcile.js +120 -0
- package/src/registry/universal-source.js +253 -0
- package/src/sam/adapters/opencv-video.js +206 -0
- package/src/sam/adapters/workspace-media.js +15 -2
- package/src/sam/bridge/policy.mjs +50 -0
- package/src/sam/bridge/stdio.mjs +61 -38
- package/src/sam/operations/architectural-knowledge.js +1 -0
- package/src/sam/operations/artifact-render.js +2 -1
- package/src/sam/operations/cad-bim-ifc.js +89 -0
- package/src/sam/operations/decision-evaluate.js +1 -0
- package/src/sam/operations/planning-goap.js +1 -0
- package/src/sam/operations/repository-inspect.js +1 -0
- package/src/sam/operations/robotics.js +1 -1
- package/src/sam/packs/core.js +2 -0
- package/src/sam/packs/evidence/endpoint.js +39 -0
- package/src/sam/packs/evidence/media.js +3 -2
- package/src/sam/packs/evidence/store-hosted.js +5 -3
- package/src/sam/shell-host.js +26 -8
- package/src/skills/catalog.js +12 -1
- package/src/skills/registry.js +16 -17
- package/src/ui/boot.js +12 -14
- package/src/ui/brand/agentsam-mark.generated.js +49 -0
- package/src/ui/cli/prompt-box.js +151 -0
- package/src/ui/home-screen.js +49 -0
- package/apps/README.md +0 -67
- package/apps/cad-creator/README.md +0 -743
- package/packages/agentsam-brand/LICENSE +0 -110
- package/packages/agentsam-desktop-shell/LICENSE +0 -110
- package/packages/agentsam-desktop-shell/README.md +0 -73
- package/packages/agentsam-ide/LICENSE +0 -110
- package/packages/agentsam-ide/README.md +0 -147
- package/packages/agentsam-nav/LICENSE +0 -110
- package/packages/agentsam-vault/LICENSE +0 -110
- package/packages/agentsam-workbench/LICENSE +0 -110
- package/src/ui/art/geaux_boot.json +0 -25
- package/src/ui/companion-art.js +0 -40
- /package/{apps/cad-creator → packages/primetech-procedures}/LICENSE +0 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live, index-free structural inspection of an authorized local source tree.
|
|
3
|
+
*
|
|
4
|
+
* This is deliberately separate from knowledge/index generations: a caller
|
|
5
|
+
* may use it immediately after "agentsam init ." or on a read-only checkout.
|
|
6
|
+
* JS/TS symbols use the bundled TypeScript parser. Other grammars can be
|
|
7
|
+
* queried through an explicitly installed ast-grep ("sg") binary.
|
|
8
|
+
* Never silently substitute grep/embeddings for a structural parse.
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { spawnSync } from 'node:child_process';
|
|
13
|
+
import { parseSource, readSource } from '../knowledge/source.js';
|
|
14
|
+
|
|
15
|
+
const JS_TS = /\.(?:[cm]?js|jsx|[cm]?ts|tsx)$/i;
|
|
16
|
+
const OMIT = new Set(['.git', '.agentsam', 'node_modules', 'dist', 'build', 'target', 'coverage', '.next', '.venv', '__pycache__', '.wrangler']);
|
|
17
|
+
const MAX_FILES = 2000;
|
|
18
|
+
const MAX_RESULTS = 200;
|
|
19
|
+
|
|
20
|
+
function limitNumber(value, fallback, ceiling) {
|
|
21
|
+
const n = Number(value);
|
|
22
|
+
return Number.isInteger(n) && n > 0 ? Math.min(n, ceiling) : fallback;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function sourceRoot(root) {
|
|
26
|
+
const absolute = fs.realpathSync(path.resolve(root || process.cwd()));
|
|
27
|
+
if (!fs.statSync(absolute).isDirectory()) throw new Error('AST root must be a directory');
|
|
28
|
+
return absolute;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function scopedPath(root, input = '.') {
|
|
32
|
+
const rel = String(input || '.').replaceAll('\\', '/').trim() || '.';
|
|
33
|
+
if (path.isAbsolute(rel) || rel.startsWith('~') || rel.split('/').includes('..')) {
|
|
34
|
+
throw new Error('AST path must be relative to the authorized root');
|
|
35
|
+
}
|
|
36
|
+
const resolved = path.resolve(root, rel);
|
|
37
|
+
if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new Error('AST path outside workspace');
|
|
38
|
+
if (fs.existsSync(resolved)) {
|
|
39
|
+
const real = fs.realpathSync(resolved);
|
|
40
|
+
if (real !== root && !real.startsWith(root + path.sep)) throw new Error('AST path outside workspace');
|
|
41
|
+
}
|
|
42
|
+
return resolved;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** List JS/TS sources deterministically, bounded, without following symlinks. */
|
|
46
|
+
export function listLiveAstFiles(root, options = {}) {
|
|
47
|
+
const base = sourceRoot(root);
|
|
48
|
+
const start = scopedPath(base, options.path || '.');
|
|
49
|
+
const maxFiles = limitNumber(options.maxFiles, 500, MAX_FILES);
|
|
50
|
+
const maxDepth = limitNumber(options.maxDepth, 20, 64);
|
|
51
|
+
const files = [];
|
|
52
|
+
let limited = false;
|
|
53
|
+
let visitedEntries = 0;
|
|
54
|
+
const maxEntries = limitNumber(options.maxEntries, 12000, 50000);
|
|
55
|
+
function descend(absolute, depth) {
|
|
56
|
+
if (files.length >= maxFiles || visitedEntries >= maxEntries) { limited = true; return; }
|
|
57
|
+
visitedEntries++;
|
|
58
|
+
let st;
|
|
59
|
+
try { st = fs.lstatSync(absolute); } catch { return; }
|
|
60
|
+
if (st.isSymbolicLink()) return;
|
|
61
|
+
if (st.isFile()) {
|
|
62
|
+
if (JS_TS.test(absolute)) files.push(path.relative(base, absolute).split(path.sep).join('/'));
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (!st.isDirectory() || depth > maxDepth) return;
|
|
66
|
+
const entries = fs.readdirSync(absolute, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
67
|
+
for (const entry of entries) {
|
|
68
|
+
if (files.length >= maxFiles || visitedEntries >= maxEntries) { limited = true; return; }
|
|
69
|
+
if (OMIT.has(entry.name) || entry.name.startsWith('.env')) continue;
|
|
70
|
+
if (entry.isSymbolicLink()) continue;
|
|
71
|
+
descend(path.join(absolute, entry.name), depth + 1);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
descend(start, 0);
|
|
75
|
+
return { root: base, files, limited, visited_entries: visitedEntries };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Immediate JS/TS symbol and call/import-edge lookup, no index or network. */
|
|
79
|
+
export function searchLiveAst(root, query, options = {}) {
|
|
80
|
+
const q = String(query || '').trim();
|
|
81
|
+
if (!q) throw new Error('AST symbol query is required');
|
|
82
|
+
const fileSet = listLiveAstFiles(root, options);
|
|
83
|
+
const limit = limitNumber(options.limit, 30, MAX_RESULTS);
|
|
84
|
+
const matches = [];
|
|
85
|
+
const parseErrors = [];
|
|
86
|
+
const edges = [];
|
|
87
|
+
let parsedFiles = 0;
|
|
88
|
+
for (const file of fileSet.files) {
|
|
89
|
+
const source = readSource(fileSet.root, file);
|
|
90
|
+
if (!source) continue;
|
|
91
|
+
let parsed;
|
|
92
|
+
try { parsed = parseSource(file, source.content); }
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (parseErrors.length < 12) parseErrors.push({ path: file, error: String(error.message || error) });
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
parsedFiles++;
|
|
98
|
+
const lines = source.content.split('\n');
|
|
99
|
+
for (const symbol of parsed.symbols) {
|
|
100
|
+
if (!symbol.name.toLowerCase().includes(q.toLowerCase())) continue;
|
|
101
|
+
matches.push({
|
|
102
|
+
path: file, name: symbol.name, kind: symbol.kind,
|
|
103
|
+
start_line: symbol.start_line, end_line: symbol.end_line,
|
|
104
|
+
source: 'local_working_tree', parser: parsed.parser,
|
|
105
|
+
snippet: lines.slice(Math.max(0, symbol.start_line - 1), Math.min(lines.length, symbol.start_line + 7)).join('\n').slice(0, 1200),
|
|
106
|
+
});
|
|
107
|
+
for (const edge of parsed.edges) {
|
|
108
|
+
if (edge.source === symbol.name && edges.length < MAX_RESULTS) {
|
|
109
|
+
edges.push({ from: symbol.name, from_path: file, to: edge.target, type: edge.kind, resolved: false });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (matches.length >= limit) break;
|
|
113
|
+
}
|
|
114
|
+
if (matches.length >= limit) break;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
ok: true, route: 'live_ast', index_required: false, query: q,
|
|
118
|
+
root: fileSet.root, matches, edges: options.edges === true ? edges : [],
|
|
119
|
+
scanned_files: parsedFiles, candidate_files: fileSet.files.length, visited_entries: fileSet.visited_entries,
|
|
120
|
+
truncated: fileSet.limited || matches.length >= limit,
|
|
121
|
+
errors: parseErrors,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Use a real ast-grep grammar for other code languages when the binary exists. */
|
|
126
|
+
export function matchLiveAst(root, pattern, options = {}) {
|
|
127
|
+
const base = sourceRoot(root);
|
|
128
|
+
const p = String(pattern || '').trim();
|
|
129
|
+
const language = String(options.language || '').trim();
|
|
130
|
+
if (!p) throw new Error('AST pattern is required');
|
|
131
|
+
if (!language || !/^[A-Za-z][A-Za-z0-9_-]*$/.test(language)) {
|
|
132
|
+
throw new Error('AST language is required (e.g. ts, python, rust, go)');
|
|
133
|
+
}
|
|
134
|
+
const scope = scopedPath(base, options.path || '.');
|
|
135
|
+
if (!fs.existsSync(scope)) throw new Error('AST path does not exist');
|
|
136
|
+
const requestedBinary = String(options.binary || 'sg');
|
|
137
|
+
if (!/^(?:sg|ast-grep)$/.test(requestedBinary)) throw new Error('AST binary must be sg or ast-grep');
|
|
138
|
+
// On Linux, /usr/bin/sg is often the shadow-utils group command, not ast-grep.
|
|
139
|
+
// Never interpret that unrelated program's empty stdout as no AST matches.
|
|
140
|
+
const isAstGrep = (candidate) => {
|
|
141
|
+
const result = spawnSync(candidate, ['--version'], {
|
|
142
|
+
cwd: base, encoding: 'utf8', timeout: 3000, shell: false,
|
|
143
|
+
});
|
|
144
|
+
return !result.error && result.status === 0 &&
|
|
145
|
+
/\bast-grep\s+\d/i.test(String(result.stdout || '') + String(result.stderr || ''));
|
|
146
|
+
};
|
|
147
|
+
const binary = isAstGrep(requestedBinary)
|
|
148
|
+
? requestedBinary
|
|
149
|
+
: requestedBinary === 'sg' && isAstGrep('ast-grep') ? 'ast-grep' : null;
|
|
150
|
+
if (!binary) throw new Error('ast-grep unavailable: install sg/ast-grep for this language; no lexical fallback performed');
|
|
151
|
+
const args = ['run', '--pattern', p, '--lang', language, '--json=compact', scope];
|
|
152
|
+
const run = spawnSync(binary, args, {
|
|
153
|
+
cwd: base, encoding: 'utf8', timeout: 30000, maxBuffer: 8 * 1024 * 1024, shell: false,
|
|
154
|
+
});
|
|
155
|
+
if (run.error) {
|
|
156
|
+
if (run.error.code === 'ENOENT') throw new Error('ast-grep unavailable: install sg/ast-grep for this language; no lexical fallback performed');
|
|
157
|
+
throw run.error;
|
|
158
|
+
}
|
|
159
|
+
if (![0, 1].includes(run.status)) throw new Error('ast-grep failed: ' + String(run.stderr || '').slice(0, 1000));
|
|
160
|
+
let raw;
|
|
161
|
+
try { raw = JSON.parse(run.stdout || '[]'); }
|
|
162
|
+
catch { throw new Error('ast-grep did not produce valid JSON'); }
|
|
163
|
+
if (!Array.isArray(raw)) throw new Error('ast-grep response must be an array');
|
|
164
|
+
const limit = limitNumber(options.limit, 30, MAX_RESULTS);
|
|
165
|
+
return {
|
|
166
|
+
ok: true, route: 'live_ast_grep', index_required: false,
|
|
167
|
+
pattern: p, language, root: base, truncated: raw.length > limit,
|
|
168
|
+
matches: raw.slice(0, limit).map((hit) => ({
|
|
169
|
+
path: path.relative(base, String(hit.file || '')).split(path.sep).join('/'),
|
|
170
|
+
start_line: Number(hit.range?.start?.line ?? 0) + 1,
|
|
171
|
+
end_line: Number(hit.range?.end?.line ?? 0) + 1,
|
|
172
|
+
kind: hit.language || language,
|
|
173
|
+
text: String(hit.text || hit.lines || '').slice(0, 1200),
|
|
174
|
+
captures: Object.fromEntries(Object.entries(hit.metaVariables?.single || {}).map(([key, val]) => [key, String(val?.text || '').slice(0, 200)])),
|
|
175
|
+
source: 'local_working_tree',
|
|
176
|
+
})),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Existing SDK RepositoryKnowledgeProvider adapter, without a persistence dependency. */
|
|
181
|
+
export function createLiveAstRepositoryProvider(root, defaults = {}) {
|
|
182
|
+
const absolute = sourceRoot(root);
|
|
183
|
+
const find = (input = {}) => searchLiveAst(absolute, input.query || input.name || input.symbol, { ...defaults, ...input });
|
|
184
|
+
return Object.freeze({
|
|
185
|
+
status: async () => ({
|
|
186
|
+
ok: true, provider: 'agentsam-live-ast', root: absolute,
|
|
187
|
+
index_required: false, semantic: false, structure: 'typescript-compiler',
|
|
188
|
+
additional_grammars: 'optional-ast-grep', persistence: 'none',
|
|
189
|
+
}),
|
|
190
|
+
refresh: async () => ({ ok: true, action: 'not_required', index_required: false }),
|
|
191
|
+
findSymbol: async (input) => find(input),
|
|
192
|
+
graph: async (input) => find({ ...input, edges: true }),
|
|
193
|
+
retrieve: async (input) => find(input),
|
|
194
|
+
snapshot: async () => ({
|
|
195
|
+
ok: true, source: 'live_working_tree', root: absolute,
|
|
196
|
+
durable: false, index_required: false,
|
|
197
|
+
note: 'Live results are not an immutable snapshot or a persisted graph generation.',
|
|
198
|
+
}),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live CAD project graph. Consumes canonical, independently editable
|
|
3
|
+
* cad.project.v1 and cad.project.v2 documents without changing them.
|
|
4
|
+
* Syntax/data inspection only: not an OCCT/BRep/IFC geometry evaluator.
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { readSource } from '../knowledge/source.js';
|
|
9
|
+
import { CAD_PROJECT_V2, validateCadProjectV2 } from '../lib/cad/project-v2.js';
|
|
10
|
+
import { validateProject } from '../lib/cad/editable-project-contract.js';
|
|
11
|
+
|
|
12
|
+
const V1_GROUPS = ['walls', 'rooms', 'doors', 'windows', 'furniture', 'annotations', 'parametricObjects'];
|
|
13
|
+
const V2_GROUPS = ['assets', 'views', 'sheets', 'scenes', 'productions', 'outputs', 'packages', 'receipts', 'revisions'];
|
|
14
|
+
|
|
15
|
+
function jsonPointerSegment(value) {
|
|
16
|
+
return String(value).replaceAll('~', '~0').replaceAll('/', '~1');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function inspectLiveCadProject(root, file, options = {}) {
|
|
20
|
+
const base = fs.realpathSync(path.resolve(root || process.cwd()));
|
|
21
|
+
if (!fs.statSync(base).isDirectory()) throw new Error('CAD root must be a directory');
|
|
22
|
+
const rel = String(file || '').replaceAll('\\', '/');
|
|
23
|
+
if (!rel || path.isAbsolute(rel) || rel.split('/').includes('..') || !/\.json$/i.test(rel)) {
|
|
24
|
+
throw new Error('A workspace-relative JSON CAD project is required');
|
|
25
|
+
}
|
|
26
|
+
const source = readSource(base, rel);
|
|
27
|
+
if (!source) throw new Error('CAD project source unavailable, symlinked, invalid, or exceeds the live-read limit');
|
|
28
|
+
let decoded;
|
|
29
|
+
try { decoded = JSON.parse(source.content); } catch (error) { throw new Error('Invalid CAD JSON: ' + error.message); }
|
|
30
|
+
const wrapped = Boolean(decoded && typeof decoded === 'object' && decoded.project && typeof decoded.project === 'object');
|
|
31
|
+
const project = wrapped ? decoded.project : decoded;
|
|
32
|
+
const prefix = wrapped ? '/project' : '';
|
|
33
|
+
const isV2 = project?.schema === CAD_PROJECT_V2;
|
|
34
|
+
const validation = isV2 ? validateCadProjectV2(project) : validateProject(project);
|
|
35
|
+
const maxNodes = Number.isInteger(options.maxNodes) && options.maxNodes > 0 ? Math.min(options.maxNodes, 3000) : 500;
|
|
36
|
+
const nodes = [];
|
|
37
|
+
const edges = [];
|
|
38
|
+
const byIdentity = new Map();
|
|
39
|
+
let totalObjects = 0;
|
|
40
|
+
|
|
41
|
+
function add(items, group, pointerPrefix, parent = null) {
|
|
42
|
+
if (!Array.isArray(items)) return;
|
|
43
|
+
totalObjects += items.length;
|
|
44
|
+
for (const [index, item] of items.entries()) {
|
|
45
|
+
if (nodes.length >= maxNodes) break;
|
|
46
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) continue;
|
|
47
|
+
const pointer = pointerPrefix + '/' + index;
|
|
48
|
+
const stableId = typeof item.id === 'string' ? item.id : null;
|
|
49
|
+
const node = {
|
|
50
|
+
id: pointer,
|
|
51
|
+
kind: String(item.kind || group.replace(/s$/, '')),
|
|
52
|
+
group,
|
|
53
|
+
name: String(item.name || stableId || group + '[' + index + ']'),
|
|
54
|
+
stable_id: stableId,
|
|
55
|
+
parent,
|
|
56
|
+
locator: { path: rel, json_pointer: pointer, source_hash: source.hash },
|
|
57
|
+
fields: Object.keys(item),
|
|
58
|
+
...(item.parameters && typeof item.parameters === 'object' ? { parameters: item.parameters } : {}),
|
|
59
|
+
};
|
|
60
|
+
nodes.push(node);
|
|
61
|
+
if (stableId) byIdentity.set(stableId, node);
|
|
62
|
+
if (parent) edges.push({ from: parent, to: pointer, type: 'contains', resolved: true });
|
|
63
|
+
if (!isV2 && group === 'walls' && Array.isArray(item.assembly?.layers)) {
|
|
64
|
+
add(item.assembly.layers, 'wall_assembly_layers', pointer + '/assembly/layers', pointer);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (isV2) {
|
|
70
|
+
add(project.geometry?.entities, 'geometry_entities', prefix + '/geometry/entities');
|
|
71
|
+
add(project.geometry?.constraints, 'geometry_constraints', prefix + '/geometry/constraints');
|
|
72
|
+
for (const group of V2_GROUPS) add(project[group], group, prefix + '/' + jsonPointerSegment(group));
|
|
73
|
+
for (const relation of project.geometry?.relationships || []) {
|
|
74
|
+
const from = byIdentity.get(relation?.from);
|
|
75
|
+
const to = byIdentity.get(relation?.to);
|
|
76
|
+
edges.push({
|
|
77
|
+
from: from?.id || null, to: to?.id || null,
|
|
78
|
+
type: String(relation?.kind || 'geometry_relationship'),
|
|
79
|
+
relation_id: relation?.id || null,
|
|
80
|
+
resolved: Boolean(from && to),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
for (const group of V1_GROUPS) add(project[group], group, prefix + '/' + jsonPointerSegment(group));
|
|
85
|
+
for (const group of ['doors', 'windows']) {
|
|
86
|
+
for (const item of project[group] || []) {
|
|
87
|
+
const from = byIdentity.get(item?.id);
|
|
88
|
+
const to = byIdentity.get(item?.wallId);
|
|
89
|
+
if (from) edges.push({
|
|
90
|
+
from: from.id, to: to?.id || null,
|
|
91
|
+
type: 'opening_of_wall', resolved: Boolean(to),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
ok: true, route: 'live_cad_project_graph', index_required: false,
|
|
98
|
+
schema: isV2 ? CAD_PROJECT_V2 : 'cad.project.v1',
|
|
99
|
+
project_id: project?.id || null, project_name: project?.name || null,
|
|
100
|
+
domain: project?.domain || 'architecture.building',
|
|
101
|
+
units: isV2 ? project?.coordinateSystem?.unit : 'in',
|
|
102
|
+
source_hash: source.hash, path: rel,
|
|
103
|
+
valid: validation.valid, validation_errors: validation.errors,
|
|
104
|
+
nodes, edges, total_objects: totalObjects, truncated: totalObjects > nodes.length,
|
|
105
|
+
note: 'Read-only schema inspection. Native OCCT geometry, IFC relations and FreeCAD document objects require separate format adapters.',
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only glTF 2.0 resource graph from a local source document.
|
|
3
|
+
* Materials, meshes, cameras, nodes, and scenes remain independent objects,
|
|
4
|
+
* addressed by JSON Pointer and protected by a source-content hash.
|
|
5
|
+
*
|
|
6
|
+
* This is NOT a BIM/IFC/OCCT parser. Other creative formats need their own
|
|
7
|
+
* schema-aware adapters, never a generic text-chunk substitute.
|
|
8
|
+
*/
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { readSource } from '../knowledge/source.js';
|
|
12
|
+
|
|
13
|
+
const GROUPS = ['scenes', 'nodes', 'meshes', 'materials', 'textures', 'images', 'samplers', 'cameras', 'skins', 'animations'];
|
|
14
|
+
|
|
15
|
+
export function inspectLiveGltf(root, file, options = {}) {
|
|
16
|
+
const base = fs.realpathSync(path.resolve(root || process.cwd()));
|
|
17
|
+
if (!fs.statSync(base).isDirectory()) throw new Error('Root must be a directory');
|
|
18
|
+
const rel = String(file || '').replaceAll('\\', '/');
|
|
19
|
+
if (!rel || path.isAbsolute(rel) || rel.split('/').includes('..') || !/\.gltf$/i.test(rel)) {
|
|
20
|
+
throw new Error('A workspace-relative .gltf file is required');
|
|
21
|
+
}
|
|
22
|
+
const abs = path.resolve(base, rel);
|
|
23
|
+
if (!abs.startsWith(base + path.sep)) throw new Error('Path outside authorized root');
|
|
24
|
+
const source = readSource(base, rel);
|
|
25
|
+
if (!source) throw new Error('glTF source unavailable, non-text, symlinked, or over the 2 MiB live-read limit');
|
|
26
|
+
let gltf;
|
|
27
|
+
try { gltf = JSON.parse(source.content); } catch (error) { throw new Error('Invalid glTF JSON: ' + error.message); }
|
|
28
|
+
if (!/^2\./.test(String(gltf?.asset?.version || ''))) throw new Error('This adapter requires glTF 2.x');
|
|
29
|
+
const maxNodes = Number.isInteger(options.maxNodes) && options.maxNodes > 0 ? Math.min(options.maxNodes, 2000) : 500;
|
|
30
|
+
const nodes = [];
|
|
31
|
+
const edges = [];
|
|
32
|
+
const diagnostics = [];
|
|
33
|
+
const total = GROUPS.reduce((sum, key) => sum + (Array.isArray(gltf[key]) ? gltf[key].length : 0), 0);
|
|
34
|
+
function pointer(group, index) { return '/' + group + '/' + index; }
|
|
35
|
+
function link(from, targetGroup, targetIndex, type) {
|
|
36
|
+
if (!Number.isInteger(targetIndex)) return;
|
|
37
|
+
const to = pointer(targetGroup, targetIndex);
|
|
38
|
+
const valid = Array.isArray(gltf[targetGroup]) && targetIndex >= 0 && targetIndex < gltf[targetGroup].length;
|
|
39
|
+
edges.push({ from, to, type, resolved: valid });
|
|
40
|
+
if (!valid && diagnostics.length < 50) diagnostics.push({ code: 'broken_gltf_reference', from, to, type });
|
|
41
|
+
}
|
|
42
|
+
for (const group of GROUPS) {
|
|
43
|
+
const values = Array.isArray(gltf[group]) ? gltf[group] : [];
|
|
44
|
+
for (let index = 0; index < values.length && nodes.length < maxNodes; index++) {
|
|
45
|
+
const data = values[index];
|
|
46
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) continue;
|
|
47
|
+
const id = pointer(group, index);
|
|
48
|
+
nodes.push({
|
|
49
|
+
id,
|
|
50
|
+
kind: group === 'meshes' ? 'mesh' : group.slice(0, -1),
|
|
51
|
+
name: typeof data.name === 'string' ? data.name : group + '[' + index + ']',
|
|
52
|
+
persistent_id: data.extras?.agentsam_id || data.extras?.uuid || null,
|
|
53
|
+
locator: { path: rel, json_pointer: id, source_hash: source.hash },
|
|
54
|
+
properties: Object.keys(data),
|
|
55
|
+
...(group === 'nodes' ? { transform: {
|
|
56
|
+
translation: data.translation || null, rotation: data.rotation || null,
|
|
57
|
+
scale: data.scale || null, matrix: data.matrix || null,
|
|
58
|
+
}} : {}),
|
|
59
|
+
...(group === 'materials' ? { pbr: data.pbrMetallicRoughness || null } : {}),
|
|
60
|
+
});
|
|
61
|
+
if (group === 'scenes') for (const n of data.nodes || []) link(id, 'nodes', n, 'contains');
|
|
62
|
+
if (group === 'nodes') {
|
|
63
|
+
for (const n of data.children || []) link(id, 'nodes', n, 'child');
|
|
64
|
+
link(id, 'meshes', data.mesh, 'mesh');
|
|
65
|
+
link(id, 'cameras', data.camera, 'camera');
|
|
66
|
+
link(id, 'skins', data.skin, 'skin');
|
|
67
|
+
}
|
|
68
|
+
if (group === 'meshes') for (const prim of data.primitives || []) link(id, 'materials', prim.material, 'material');
|
|
69
|
+
if (group === 'materials') {
|
|
70
|
+
link(id, 'textures', data.pbrMetallicRoughness?.baseColorTexture?.index, 'base_color_texture');
|
|
71
|
+
link(id, 'textures', data.pbrMetallicRoughness?.metallicRoughnessTexture?.index, 'metallic_roughness_texture');
|
|
72
|
+
link(id, 'textures', data.normalTexture?.index, 'normal_texture');
|
|
73
|
+
link(id, 'textures', data.occlusionTexture?.index, 'occlusion_texture');
|
|
74
|
+
link(id, 'textures', data.emissiveTexture?.index, 'emissive_texture');
|
|
75
|
+
}
|
|
76
|
+
if (group === 'textures') {
|
|
77
|
+
link(id, 'images', data.source, 'image');
|
|
78
|
+
link(id, 'samplers', data.sampler, 'sampler');
|
|
79
|
+
}
|
|
80
|
+
if (group === 'skins') for (const n of data.joints || []) link(id, 'nodes', n, 'joint');
|
|
81
|
+
if (group === 'animations') {
|
|
82
|
+
for (const channel of data.channels || []) link(id, 'nodes', channel.target?.node, 'animation_target');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (nodes.length >= maxNodes) break;
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
ok: true, route: 'live_resource_graph', format: 'gltf2', index_required: false,
|
|
89
|
+
root: base, path: rel, source_hash: source.hash,
|
|
90
|
+
root_scene: Number.isInteger(gltf.scene) ? pointer('scenes', gltf.scene) : null,
|
|
91
|
+
nodes, edges, diagnostics, total_objects: total,
|
|
92
|
+
truncated: nodes.length < total,
|
|
93
|
+
caveat: 'Object paths identify elements in this source revision. Array reordering can change JSON Pointers; use persistent_id when authored.',
|
|
94
|
+
};
|
|
95
|
+
}
|
package/src/knowledge/config.js
CHANGED
|
@@ -35,7 +35,7 @@ export function validateConfig(input) {
|
|
|
35
35
|
allowed(c.scope, ['name', 'include', 'exclude'], 'scope');
|
|
36
36
|
allowed(c.chunking, ['max_chars'], 'chunking');
|
|
37
37
|
allowed(c.embedding, ['provider', 'model', 'revision', 'dimensions', 'parameters'], 'embedding');
|
|
38
|
-
allowed(c.storage, ['driver', 'connection_env'], 'storage');
|
|
38
|
+
allowed(c.storage, ['driver', 'connection_env', 'database', 'binding', 'config', 'environment'], 'storage');
|
|
39
39
|
if (c.lane != null) allowed(c.lane, ['id', 'backend', 'resource', 'binding', 'index', 'metric'], 'lane');
|
|
40
40
|
if (![1, 2].includes(c.version)) throw new Error('Unsupported knowledge configuration version.');
|
|
41
41
|
if (typeof c.repository_id !== 'string' || !c.repository_id.trim()) throw new Error('repository_id is required.');
|
|
@@ -49,7 +49,8 @@ export function validateConfig(input) {
|
|
|
49
49
|
const disabledEmbedding = e?.provider === 'none' && e?.model === 'none' && e?.dimensions === 0;
|
|
50
50
|
if (!e || ['provider', 'model', 'revision'].some(k => typeof e[k] !== 'string' || !e[k].trim()) || !Number.isInteger(e.dimensions) || (!disabledEmbedding && (e.dimensions < 1 || e.dimensions > 3072))) throw new Error('Embedding provider, model, revision and dimensions (1..3072, or explicit none/0) are required.');
|
|
51
51
|
if (!e.parameters || typeof e.parameters !== 'object' || Array.isArray(e.parameters)) throw new Error('Embedding parameters must be an object.');
|
|
52
|
-
if (!['sqlite', 'postgres'].includes(c.storage?.driver)) throw new Error('storage.driver must be sqlite or postgres.');
|
|
52
|
+
if (!['sqlite', 'd1', 'postgres'].includes(c.storage?.driver)) throw new Error('storage.driver must be sqlite, d1 or postgres.');
|
|
53
|
+
if (c.storage.driver === 'd1' && (typeof c.storage.database !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(c.storage.database))) throw new Error('D1 storage requires the database name from this project\'s wrangler config.');
|
|
53
54
|
if (c.storage.driver === 'postgres' && !/^[A-Z_][A-Z0-9_]*$/.test(c.storage.connection_env || '')) throw new Error('Postgres requires a connection_env name, never a connection string in config.');
|
|
54
55
|
if (c.lane) {
|
|
55
56
|
if (typeof c.lane.id !== 'string' || !c.lane.id.trim() || !['local_exact', 'postgres_pgvector', 'supabase_pgvector', 'cloudflare_vectorize'].includes(c.lane.backend)) throw new Error('Knowledge lane requires an explicit supported backend.');
|
|
@@ -62,8 +63,8 @@ export function defaultConfig({ include = ['.'], exclude = [], scope = 'default'
|
|
|
62
63
|
return validateConfig({ version: 2, repository_id: String(repositoryId || '').trim() || randomUUID(), project_key: String(repositoryId || '').trim() || undefined,
|
|
63
64
|
scope: { name: scope, include, exclude }, chunking: { max_chars: 4000 },
|
|
64
65
|
embedding: { provider: 'gemini', model: 'gemini-embedding-2', revision: '1', dimensions, parameters: { task: 'code retrieval' } },
|
|
65
|
-
storage:
|
|
66
|
-
lane: { id: `${scope}-default`, backend:
|
|
66
|
+
storage: { driver: 'sqlite' },
|
|
67
|
+
lane: { id: `${scope}-default`, backend: 'local_exact', resource: null, binding: null, index: null, metric: 'cosine' } });
|
|
67
68
|
}
|
|
68
69
|
export function readConfig(root) { return validateConfig(JSON.parse(fs.readFileSync(path.join(root, CONFIG_PATH), 'utf8'))); }
|
|
69
70
|
export function initRepository(root, options = {}) {
|
|
@@ -14,7 +14,8 @@ export async function discoverProjectStores(cwd, env = process.env) {
|
|
|
14
14
|
{ id: 'runtime:sqlite', driver: 'sqlite', role: 'runtime', path: runtimeDatabasePath(root), selected: true },
|
|
15
15
|
{ id: 'knowledge:sqlite', driver: 'sqlite', role: 'knowledge', path: path.join(root, '.agentsam/knowledge/index.sqlite'), selected: !config || config.storage.driver === 'sqlite', selectable: true },
|
|
16
16
|
];
|
|
17
|
-
|
|
17
|
+
// Postgres is opt-in: only a connection_env the project explicitly configured is considered.
|
|
18
|
+
const envNames = new Set([config?.storage?.connection_env].filter(Boolean));
|
|
18
19
|
for (const name of envNames) {
|
|
19
20
|
if (!Object.hasOwn(env, name) && name !== config?.storage?.connection_env) continue;
|
|
20
21
|
candidates.push({ id: `knowledge:postgres:${name}`, driver: 'postgres', role: 'knowledge', connection_env: name, configured: Boolean(env[name]), selected: config?.storage?.driver === 'postgres' && config.storage.connection_env === name, selectable: true });
|
|
@@ -62,9 +63,20 @@ export async function discoverProjectStores(cwd, env = process.env) {
|
|
|
62
63
|
return { root, candidates, warnings, knowledge_config: CONFIG_PATH };
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
export function
|
|
66
|
+
export async function resolveD1Storage(cwd, selector) {
|
|
67
|
+
const found = (await discoverProjectStores(cwd)).candidates.filter((c) => c.driver === 'd1' && c.role === 'application' && c.name);
|
|
68
|
+
const pick = selector ? found.filter((c) => c.binding === selector || c.name === selector) : found;
|
|
69
|
+
if (pick.length !== 1) {
|
|
70
|
+
const names = found.map((c) => `${c.binding} (${c.name})`).join(', ');
|
|
71
|
+
throw new Error(pick.length ? `d1_binding_ambiguous: choose one of ${names}; e.g. /db select knowledge d1 <binding>` : `d1_binding_not_found: ${found.length ? `declared bindings: ${names}` : 'no D1 database is declared in this project\'s wrangler config'}`);
|
|
72
|
+
}
|
|
73
|
+
const [d1] = pick;
|
|
74
|
+
return { driver: 'd1', database: d1.name, binding: d1.binding, config: d1.source, ...(d1.environment ? { environment: d1.environment } : {}) };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function selectKnowledgeStore(cwd, driver, selector) {
|
|
66
78
|
const root = findCliProjectRoot(cwd);
|
|
67
|
-
if (!['sqlite', 'postgres'].includes(driver)) throw new Error('knowledge_store_adapter_unavailable: choose sqlite or postgres
|
|
79
|
+
if (!['sqlite', 'd1', 'postgres'].includes(driver)) throw new Error('knowledge_store_adapter_unavailable: choose sqlite, d1 or postgres');
|
|
68
80
|
const filename = path.join(root, CONFIG_PATH);
|
|
69
81
|
let config;
|
|
70
82
|
if (fs.existsSync(filename)) config = readConfig(root);
|
|
@@ -73,11 +85,16 @@ export function selectKnowledgeStore(cwd, driver, connectionEnv) {
|
|
|
73
85
|
if (!repositoryId) throw new Error('repository_identity_required: run agentsam init . --yes first');
|
|
74
86
|
config = defaultConfig({ repositoryId });
|
|
75
87
|
}
|
|
76
|
-
|
|
88
|
+
if (driver === 'd1') {
|
|
89
|
+
config.storage = await resolveD1Storage(cwd, selector);
|
|
90
|
+
} else if (driver === 'postgres') {
|
|
91
|
+
if (!selector) throw new Error('postgres_connection_env_required: Postgres is opt-in; name the environment variable that holds your connection string, e.g. agentsam db storage postgres MY_DATABASE_URL');
|
|
92
|
+
config.storage = { driver, connection_env: selector };
|
|
93
|
+
} else config.storage = { driver };
|
|
77
94
|
config = validateConfig(config);
|
|
78
95
|
fs.mkdirSync(path.dirname(filename), { recursive: true, mode: 0o700 });
|
|
79
96
|
const temp = `${filename}.${process.pid}.tmp`;
|
|
80
97
|
fs.writeFileSync(temp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
|
|
81
98
|
fs.renameSync(temp, filename);
|
|
82
|
-
return { storage: config.storage, config: CONFIG_PATH, next: driver === '
|
|
99
|
+
return { storage: config.storage, config: CONFIG_PATH, next: driver === 'postgres' ? 'agentsam index setup-store' : 'agentsam index run', note: 'Selection saved. Existing data remains in its original store; no migration or connection probe ran.' };
|
|
83
100
|
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare D1 knowledge store. Talks to the project's own D1 database through
|
|
3
|
+
* the user's existing Wrangler login (no env vars, no secrets, no connection URL).
|
|
4
|
+
*
|
|
5
|
+
* D1 caps statements (~100 KB) and rows (~2 MB), so every JSON payload is stored
|
|
6
|
+
* ASCII-escaped and split into small parts in `knowledge_blobs`. Publishing is a
|
|
7
|
+
* single compare-and-swap on `knowledge_active`, so concurrent runs cannot clobber
|
|
8
|
+
* each other.
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { execFile } from 'node:child_process';
|
|
14
|
+
import { promisify } from 'node:util';
|
|
15
|
+
|
|
16
|
+
const exec = promisify(execFile);
|
|
17
|
+
const PART_CHARS = 40_000;
|
|
18
|
+
const SCHEMA = `
|
|
19
|
+
CREATE TABLE IF NOT EXISTS knowledge_blobs (owner TEXT NOT NULL, seq INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY (owner, seq));
|
|
20
|
+
CREATE TABLE IF NOT EXISTS knowledge_cache (key TEXT PRIMARY KEY);
|
|
21
|
+
CREATE TABLE IF NOT EXISTS knowledge_generations (id TEXT PRIMARY KEY, scope TEXT NOT NULL, created_at TEXT NOT NULL, summary TEXT NOT NULL);
|
|
22
|
+
CREATE INDEX IF NOT EXISTS knowledge_history ON knowledge_generations(scope, created_at);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS knowledge_active (scope TEXT PRIMARY KEY, id TEXT NOT NULL REFERENCES knowledge_generations(id));
|
|
24
|
+
CREATE TABLE IF NOT EXISTS knowledge_observations (id TEXT PRIMARY KEY, namespace TEXT NOT NULL, created_at TEXT NOT NULL);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS knowledge_obs_ns ON knowledge_observations(namespace, created_at);`;
|
|
26
|
+
|
|
27
|
+
export const d1KnowledgeSchema = SCHEMA;
|
|
28
|
+
const lit = (value) => `'${String(value).replace(/'/g, "''")}'`;
|
|
29
|
+
const asciiJson = (value) => JSON.stringify(value).replace(/[\u007f-]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
30
|
+
const blobStatements = (owner, value) => {
|
|
31
|
+
const text = asciiJson(value);
|
|
32
|
+
const out = [];
|
|
33
|
+
for (let i = 0, seq = 0; i < text.length || seq === 0; i += PART_CHARS, seq++) {
|
|
34
|
+
out.push(`INSERT OR REPLACE INTO knowledge_blobs VALUES (${lit(owner)}, ${seq}, ${lit(text.slice(i, i + PART_CHARS))});`);
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
};
|
|
38
|
+
const summarize = (g) => ({
|
|
39
|
+
files: g.files?.length || 0, chunks: g.chunks?.length || 0,
|
|
40
|
+
provider: g.config?.embedding?.provider || 'none', model: g.config?.embedding?.model || null,
|
|
41
|
+
embedded: Boolean(g.profile_id), source_scope: g.config?.scope || null,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {{ root: string, storage: { database: string, config?: string, environment?: string|null } }} target
|
|
46
|
+
* @param {{ readOnly?: boolean, wrangler?: string, runner?: Function }} [options]
|
|
47
|
+
*/
|
|
48
|
+
export async function openD1Store(target, { readOnly = false, wrangler, runner = exec } = {}) {
|
|
49
|
+
const { root, storage } = target;
|
|
50
|
+
if (!storage?.database) throw new Error('d1_store_requires_database: run `agentsam index storage d1` to pick this project\'s D1 binding');
|
|
51
|
+
const bin = wrangler || (fs.existsSync(path.join(root, 'node_modules/.bin/wrangler')) ? path.join(root, 'node_modules/.bin/wrangler') : 'wrangler');
|
|
52
|
+
const base = ['d1', 'execute', storage.database, '--remote', '--json'];
|
|
53
|
+
if (storage.config) base.push('--config', path.resolve(root, storage.config));
|
|
54
|
+
if (storage.environment) base.push('--env', storage.environment);
|
|
55
|
+
|
|
56
|
+
async function run(sql, { file = false } = {}) {
|
|
57
|
+
let tmp = null;
|
|
58
|
+
const args = [...base];
|
|
59
|
+
if (file) {
|
|
60
|
+
tmp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'agentsam-d1-')), 'q.sql');
|
|
61
|
+
fs.writeFileSync(tmp, sql, { mode: 0o600 });
|
|
62
|
+
args.push('--file', tmp);
|
|
63
|
+
} else args.push('--command', sql);
|
|
64
|
+
try {
|
|
65
|
+
const { stdout } = await runner(bin, args, { cwd: root, timeout: 120_000, maxBuffer: 32 * 1024 * 1024, encoding: 'utf8' });
|
|
66
|
+
const parsed = JSON.parse(stdout);
|
|
67
|
+
const blocks = Array.isArray(parsed) ? parsed : [parsed];
|
|
68
|
+
if (blocks.some((b) => b?.success === false)) throw new Error('d1_query_failed');
|
|
69
|
+
return blocks;
|
|
70
|
+
} catch (error) {
|
|
71
|
+
throw new Error(`d1_store_failed:${String(error?.code || error?.message || 'command_failed').slice(0, 80)}`);
|
|
72
|
+
} finally { if (tmp) fs.rmSync(path.dirname(tmp), { recursive: true, force: true }); }
|
|
73
|
+
}
|
|
74
|
+
const rows = async (sql) => (await run(sql)).flatMap((b) => b.results || []);
|
|
75
|
+
const blob = async (owner) => {
|
|
76
|
+
const parts = await rows(`SELECT body FROM knowledge_blobs WHERE owner=${lit(owner)} ORDER BY seq`);
|
|
77
|
+
return parts.length ? JSON.parse(parts.map((p) => p.body).join('')) : null;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const exists = await rows(`SELECT name FROM sqlite_schema WHERE type='table' AND name='knowledge_generations'`);
|
|
81
|
+
if (!exists.length) {
|
|
82
|
+
if (readOnly) return null;
|
|
83
|
+
await run(SCHEMA, { file: true });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
async active(scope) {
|
|
88
|
+
const [row] = await rows(`SELECT id FROM knowledge_active WHERE scope=${lit(scope)}`);
|
|
89
|
+
return row ? blob(`gen:${row.id}`) : null;
|
|
90
|
+
},
|
|
91
|
+
async scopeStatus(scope) {
|
|
92
|
+
const [active] = await rows(`SELECT id FROM knowledge_active WHERE scope=${lit(scope)}`);
|
|
93
|
+
const [total] = await rows('SELECT COUNT(*) AS n FROM knowledge_generations');
|
|
94
|
+
return { active_id: active?.id || null, existing_generations: Number(total?.n || 0) };
|
|
95
|
+
},
|
|
96
|
+
async getGeneration(scope, id) {
|
|
97
|
+
const [row] = await rows(`SELECT id FROM knowledge_generations WHERE scope=${lit(scope)} AND id=${lit(id)}`);
|
|
98
|
+
return row ? blob(`gen:${id}`) : null;
|
|
99
|
+
},
|
|
100
|
+
async cacheGet(key) {
|
|
101
|
+
const [row] = await rows(`SELECT key FROM knowledge_cache WHERE key=${lit(key)}`);
|
|
102
|
+
return row ? blob(`cache:${key}`) : null;
|
|
103
|
+
},
|
|
104
|
+
async cachePut(key, value) {
|
|
105
|
+
await run([...blobStatements(`cache:${key}`, value), `INSERT OR IGNORE INTO knowledge_cache VALUES (${lit(key)});`].join('\n'), { file: true });
|
|
106
|
+
},
|
|
107
|
+
async publish(generation, expectedId) {
|
|
108
|
+
const summary = asciiJson(summarize(generation));
|
|
109
|
+
await run([
|
|
110
|
+
...blobStatements(`gen:${generation.id}`, generation),
|
|
111
|
+
`INSERT OR IGNORE INTO knowledge_generations VALUES (${lit(generation.id)}, ${lit(generation.scope_key)}, ${lit(generation.created_at)}, ${lit(summary)});`,
|
|
112
|
+
].join('\n'), { file: true });
|
|
113
|
+
// Compare-and-swap: only flips the pointer if nobody published since we read it.
|
|
114
|
+
const guard = expectedId ? `WHERE knowledge_active.id = ${lit(expectedId)}` : 'WHERE 0';
|
|
115
|
+
const swap = await run(`INSERT INTO knowledge_active VALUES (${lit(generation.scope_key)}, ${lit(generation.id)}) ON CONFLICT(scope) DO UPDATE SET id=excluded.id ${guard}`);
|
|
116
|
+
const changes = swap.reduce((n, b) => n + Number(b.meta?.changes || 0), 0);
|
|
117
|
+
if (!changes) throw new Error('Index changed concurrently; rerun to publish against the current generation.');
|
|
118
|
+
},
|
|
119
|
+
async history(scope) {
|
|
120
|
+
const list = await rows(`SELECT id FROM knowledge_generations WHERE scope=${lit(scope)} ORDER BY created_at, id`);
|
|
121
|
+
const out = [];
|
|
122
|
+
for (const row of list) out.push(await blob(`gen:${row.id}`));
|
|
123
|
+
return out;
|
|
124
|
+
},
|
|
125
|
+
async historicalSummaries() {
|
|
126
|
+
const list = await rows('SELECT g.id, g.scope, g.created_at, g.summary, (a.id IS NOT NULL) AS active FROM knowledge_generations g LEFT JOIN knowledge_active a ON a.scope=g.scope AND a.id=g.id ORDER BY g.created_at DESC');
|
|
127
|
+
return list.map((r) => ({ scope_key: r.scope, generation_id: r.id, created_at: r.created_at, ...JSON.parse(r.summary), active: Boolean(r.active) }));
|
|
128
|
+
},
|
|
129
|
+
async observe(namespace, observation) {
|
|
130
|
+
await run([...blobStatements(`obs:${observation.id}`, observation),
|
|
131
|
+
`INSERT INTO knowledge_observations VALUES (${lit(observation.id)}, ${lit(namespace)}, ${lit(observation.created_at)});`].join('\n'), { file: true });
|
|
132
|
+
},
|
|
133
|
+
async observations(namespace) {
|
|
134
|
+
const list = await rows(`SELECT id FROM knowledge_observations WHERE namespace=${lit(namespace)} ORDER BY created_at, id`);
|
|
135
|
+
const out = [];
|
|
136
|
+
for (const row of list) out.push(await blob(`obs:${row.id}`));
|
|
137
|
+
return out;
|
|
138
|
+
},
|
|
139
|
+
async close() {},
|
|
140
|
+
};
|
|
141
|
+
}
|